Legal Information

DirectX 9.0 Programmer's Reference

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1995-2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Visual C++, Visual Studio, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

BLUETOOTH is a trademark owned by Bluetooth SIG, Inc. and licensed to Microsoft Corporation.

Roland GS Sound Set/Microsoft (R) 1996 Roland Corporation U.S.

Roland is a registered trademark of the Roland Corporation.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Note Manufacturers of telecommunications devices implementing this API must ensure compliance with section 255 of the telecommunications act of 1996.

Copyright Warning

Special Note and Warning The Roland GS Sound Set/Microsoft, the "Sample Set", incorporates the SoundCanvas Sound Set. Roland Corporation U.S. owns the Sample Set and all copyrights pertaining thereto and has licensed the Sample Set for use solely on Microsoft Operating Systems Products and Microsoft Application Products.

Roland reserves all rights to the Sample Set not expressly granted by Roland Corporation U.S. or by Microsoft under the terms of Microsoft's End User License Agreement.

The Sample Set may only be redistributed with your software application as an integral component of a Microsoft Operating System Product and under the terms of Microsoft's End User License Agreement. All other uses of the Sample Set require a separate written license from Roland Corporation U.S.

The Sample Set may not be used, copied or redistributed in hardware ROM or similar technology of any device without prior express written permission from an authorized representative of Roland Corporation U.S. The Sample Set may not be redistributed with any Musical Instrument. A "Musical Instrument" is any device that is capable of generating musical sounds without being directly connected to a computer with a licensed Microsoft Operating System. You may not modify the Sample Set under any circumstances.

© 2002 Microsoft Corporation. All rights reserved.


Introducing DirectX 9.0

Microsoft® DirectX® is a set of low-level application programming interfaces (APIs) for creating games and other high-performance multimedia applications. It includes support for two-dimensional (2-D) and three-dimensional (3-D) graphics, sound effects and music, input devices, and networked applications such as multiplayer games.

This document provides introductory information about DirectX 9.0. Information is divided into the following sections.

  • DirectX 9.0 Components
  • What's New in DirectX 9.0
  • Security Considerations: Microsoft DirectX 9.0
  • Using the DirectX SDK

© 2002 Microsoft Corporation. All rights reserved.


DirectX 9.0 Components

Microsoft® DirectX® 9.0 is made up of the following components.

  • DirectX Graphics combines the Microsoft DirectDraw® and Microsoft Direct3D® components of previous DirectX versions into a single application programming interface (API) that you can use for all graphics programming. The component includes the Direct3D extensions (D3DX) utility library, which simplifies many graphics programming tasks.
  • Microsoft DirectInput® provides support for a variety of input devices, including full support for force-feedback technology.
  • Microsoft DirectPlay® provides support for multiplayer networked games.
  • Microsoft DirectSound® can be used in the development of high-performance audio applications that play and capture waveform audio.
  • Microsoft DirectMusic® provides a complete solution for both musical and non-musical soundtracks based on waveforms, MIDI sounds, or dynamic content authored in DirectMusic Producer.
  • Microsoft DirectShow® provides for high-quality capture and playback of multimedia streams.
  • DirectSetup is a simple API that provides one-call installation of the DirectX components.
  • DirectX Media Objects provide support for writing and using data-streaming objects, including video and audio encoders, decoders, and effects.

© 2002 Microsoft Corporation. All rights reserved.


What's New in DirectX 9.0

Microsoft® DirectX® 9.0 is a major release primarily for graphics. It includes new tools, new features for graphics and Microsoft DirectShow®, and enhancements for Microsoft DirectInput® and Microsoft DirectPlay®.

  • New Tools
  • New Features in DirectX Graphics
  • New Features in DirectShow
  • New Features in DirectInput
  • New Features in DirectPlay
  • New Features in DirectSound
  • New Features in DirectMusic

New Tools

  • AppWizard. This tool provides an application wizard for creating a DirectX application with any combination of DirectX components. This tool is installed during the software development kit (SDK) install and can be accessed within Microsoft Visual Studio® when creating a new application. For more information, see AppWizard.
  • Error Lookup Tool. Use this tool to take the hexadecimal error codes and look up a text-based error message. This tool is installed as part of the SDK install and can be accessed from Start, Programs, Microsoft DirectX 9.0 SDK, DirectX Utilities, DirectX Error Lookup.

New Features in DirectX Graphics

  • Vertex and pixel shaders now referred to by objects created by Component Object Model (COM) interfaces IDirect3DVShader9 and IDirect3DPShader9.
  • Vertex streams now created with a declaration.
  • Changes to vertex shaders and vertex stream declaration binding.
  • Added a limited form of flow control to version 2.0 vertex shaders.
  • Added a scissor test.
  • Added line antialiasing.
  • Added support for sphere map texture generation mode.
  • Added support for displacement maps.
  • Improved device enumeration support.

For more information, see What's New in DirectX Graphics or see each of the components.

New Features in DirectShow

  • Video Mixing Renderer Filter 9 (VMR-9). This new, redistributable rendering filter is similar in concept and design to the VMR that is available for Microsoft Windows® XP. The VMR-9 is more powerful than the original VMR (now called "VMR-7") because it is fully compatible with the DirectX 9.0 graphics capabilities and it offers improved support for deinterlacing and ProcAmp control (brightness, contrast, hue, and saturation).
  • New deinterlacing support in DirectX Video Acceleration.
  • New deinterlacing support in the digital video (DV) decoder filter.
  • New encoder application programming interface (API) specification: The Encoder API defines a standard, format-neutral way in which software or hardware encoders can communicate with applications and device drivers.
  • IGetCapabilitiesKey Interface is a new interface that filters can implement to enable applications to query for the filter's capabilities.
  • Enhancements to the GraphEdit utility.
  • The digital video disc (DVD) Graph Builder enables applications to use the VMR-9 through the IDvdGraphBuilder::RenderDvdVideoVolume method. The DVD Navigator now supports playback of audio during fast forward; users can now watch a movie at speeds higher than 1x without raising the pitch of the audio track, if the decoder supports this feature.
  • A new utility program called Profile Enumerator that displays information about Microsoft Windows Media™ system profiles installed on your computer. This program is located in (SDK root)\bin\DXUtils.
  • AVStream driver development and runtime support on all platforms prior to Windows XP has been improved for close functional parity with Windows XP.
  • New samples.

For more information, see What's New in DirectShow.

New Features in DirectInput

Version 9.0 primarily includes compatibility improvements for DirectInput. There are no API changes.

Note For important information about using IDirectInput8::ConfigureDevices within a Microsoft Direct3D® 9.0 environment, see the IDirectInput8::ConfigureDevices Remarks section.

New Features in DirectPlay

Version 9.0 features include the new interfaces IDirectPlay8ThreadPool and IDP8SimControl, a new service provider for network simulation, and functionality for Windows Powered Pocket PC 2002. For more information, see What's New in DirectPlay.

New Features in DirectSound

The Microsoft DirectSound® API has not been significantly revised for DirectX 9.0. However, many performance enhancements have been implemented. In addition, the following changes have been made.

  • The maximum frequency of sound buffers has been increased from 100 kHz to 200 kHz, where supported by the operating system. (These higher frequencies are not supported by DirectShow.)
  • Frequency and effects controls (DSBCAPS_CTRLFREQUENCY and DSBCAPS_CRTLFX) can now be combined on buffers. Combining these flags makes it possible to have Doppler shift on buffers with effects.
  • Audio formats described by the WAVEFORMATEXTENSIBLE structure are fully supported throughout DirectSound.
  • The standard effect DMOs can process audio data in WAVE_FORMAT_IEEE_FLOAT format.
  • The standard effects support parameter curves (when hosted outside of DirectSound) without having to call IMediaObjectInPlace::Process on them repeatedly in very small increments.

New Features in DirectMusic

The Microsoft DirectMusic® API has not been significantly revised for DirectX 9.0. However, many performance enhancements have been made. The most significant of these is a new low-latency DirectSound sink, which enables DirectMusic to attain much quicker response when using audiopaths that play through the software synthesizer. A large library of DirectMusic styles has been added to the SDK, along with an application for auditioning them. In addition, two new tools have been made available in the \bin\DXUtils\AppWizard folder of the SDK installation:

  • DMToolWizard.awx is a wizard for creating DirectMusic tools.
  • AEDMOWiz.awx is a wizard for creating effect DMOs.

© 2002 Microsoft Corporation. All rights reserved.


Security Considerations: Microsoft DirectX 9.0

This topic provides information about security considerations related to Microsoft® DirectX® 9.0. This topic does not provide all you need to know about security issues. Instead, use it as a starting point and reference for this technology area.

For general security topics, such as avoiding buffer overruns and running with special privileges, see Security Best Practices World Wide Web link, which also contains some DirectX-specific topics.

DirectPlay Security

For Microsoft DirectPlay®, also be aware of the following:

Secure Communications

DirectPlay does not provide secure communications. DirectPlay does support Internet Protocol Security (IPSec) for IPv4 or IPv6 for encrypting the entire packet. Applications can encrypt packets before passing them to DirectPlay. However, neither the DirectPlay headers nor internal traffic will be encrypted. See your network administrator for more information.

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectX SDK

This section contains information about developing with the Microsoft® DirectX® 9.0 software development kit (SDK).
  • Using the DirectX 9.0 Documentation
  • DirectX Tools
  • Programming DirectX with C/C++
  • DirectX and Windows XP
  • Further Information

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectX 9.0 Documentation

The following conventions are used in the syntax of methods, functions, and other application programming interface (API) elements, as well as typographic conventions used in explanatory material and sample code.

Convention | Meaning
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(x,y) requires you to substitute values for the x and y parameters.
monospace
Used for code examples, syntax spacing, and user input.
[] Encloses optional parameters.
... Specifies that the preceding item may be repeated or represents an omitted portion of text or sample.
.

.

. 		Represents an omitted portion of a sample application.

Printing Help Files

To print the software development kit (SDK) Help files, open the Help files, and then select File, and Print, which opens the Print Topics dialog box.

Print Topics dialog box

Choose either Print the selected topic or Print the selected heading and all subtopics and click OK.

To print C++ graphics files, for example, the Help files can be opened from Start, Programs, Microsoft DirectX 9.0 SDK, DirectX SDK Help, DirectX Documentation for C++ or by double-clicking on the Help file installed during the SDK install at C:\DXSDK\doc\DirectX9\.

If the pages are being cut off on the right side when printing, decrease the font size so that the text does not exceed the right page margin. You can do this by clicking the Font button one or more times to choose a smaller font size before opening the Print Topics dialog box.

Location of the Font button

Searching the Help Files

To begin a search, click the Search tab. Type in the word or phrase you are looking for. To do partial word searches, use the * wildcard. For example, a search for "DPNERR*" returns all of Microsoft® DirectPlay® error codes that begin with DPNERR.

© 2002 Microsoft Corporation. All rights reserved.


DirectX Tools

The following tools can be useful in developing and troubleshooting Microsoft® DirectX® applications.

  • DirectX Caps Viewer
  • DirectX Control Panel Application
  • DirectX Diagnostic Tool
  • Kill Help Utility
  • DirectX Diagnostic C/C++ Reference

© 2002 Microsoft Corporation. All rights reserved.


DirectX Caps Viewer

The Microsoft® DirectX® Caps Viewer tool shows information for the following components of DirectX.

  • Microsoft DirectMusic® capabilities (for DirectMusic ports).
  • Microsoft DirectInput® devices and their capabilities.
  • Microsoft DirectPlay® connections (server provider information).
  • Microsoft DirectSound® capture devices and capabilities.
  • Microsoft Direct3D® devices and capabilities.

The DirectX Caps Viewer screen shot below shows the general Microsoft DirectDraw® capabilities of the primary display adapter. Screen shot of DirectX Caps Viewer

Developers should use this tool to verify the capabilities of their development and test computers, making sure that DirectX applications correctly test for current computer capabilities and react accordingly. It is suggested that applications be designed with fallback strategies if the required features are not available.

Path

Executable: (SDK root)\Bin\DXUtils\DXCapsViewer.exe

User's Guide

Select items in the tree view on the left. Information about the selected item appears in the pane on the right.

© 2002 Microsoft Corporation. All rights reserved.


DirectX Control Panel Application

You can use the Microsoft® DirectX® Control Panel utility, which is installed with the software development kit (SDK), to examine and modify the properties of DirectX components. This utility contains tabs for each DirectX component. Using this utility you can:

  • Obtain version information for DirectX components.
  • Change the debug output level and debug settings to aid in troubleshooting during the development process.
  • View specific driver and hardware support information for DirectX components.
  • Toggle between debug and retail versions of the run times for Microsoft Direct3D®, Microsoft DirectMusic®, and Microsoft DirectInput®.

© 2002 Microsoft Corporation. All rights reserved.


DirectX Diagnostic Tool

The Microsoft® DirectX® Diagnostic Tool gathers information about the system and the DirectX components installed on it, as well as providing a number of tests to ensure that components are working properly. Because this tool is installed with DirectX, it can be used to help users track down problems.

Path

Executable: %windir%\system32\Dxdiag.exe

User's Guide

To display the DirectX Diagnostic Tool Help file, click the Help button.

© 2002 Microsoft Corporation. All rights reserved.


Kill Help Utility

Kill Help is a utility for developers who are working on Microsoft® Windows® 98 or Windows Millennium Edition (Windows Me). When a Microsoft DirectX® application crashes, the Ddhelp.exe process sometimes remains active. When this happens, it prevents other Microsoft DirectDraw® or Microsoft Direct3D® applications from working until Ddhelp.exe is terminated or the computer is rebooted. This utility will terminate the ddhelp process and spare developers from having to reboot their computer.

Path

Executable: (SDK root)\Bin\DXUtils\KillHelp.exe

User's Guide

Run this application to terminate Ddhelp.exe. If the ddhelp process is not active, then nothing happens.

© 2002 Microsoft Corporation. All rights reserved.


DirectX Diagnostic C/C++ Reference

The Microsoft® DirectX® Diagnostic Tool exposes a Component Object Model (COM) interface to allow developers to programmatically query the information gathered by the tool. For examples of how to use these methods, see the samples located at (SDK root)\Samples\C++\Misc\DXDiagReport\ and (SDK root)\Samples\C++\Misc\DXDiagOutput\.

  • Interfaces
  • Structures

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains references for methods of the interfaces exposed by the Microsoft® DirectX® Diagnostic Tool.

  • IDxDiagContainer
  • IDxDiagProvider

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer Interface

Applications use the methods of the IDxDiagContainer interface to query objects and properties exposed by the Microsoft® DirectX® Diagnostic Tool.

IDxDiagContainer Members

EnumChildContainerNames | Enumerates the name of the IDxDiagContainer object at the specified index.
EnumPropNames | Enumerates the name of the property at the specified index.
GetChildContainer | Retrieves a pointer to the child container specified.
GetNumberOfChildContainers | Returns the number of IDxDiagContainer objects in this container.
GetNumberOfProps | Retrieves the number of properties in this container.
GetProp | Retrieves an instance of the property specified.

Interface Information

Inherits from | IUnknown
Header | dxdiag.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::EnumChildContainerNames Method

Enumerates the name of the IDxDiagContainer object at the specified index.

Syntax

HRESULT EnumChildContainerNames(

    DWORD dwIndex,
    LPWSTR pwszContainer,
    DWORD cchContainer
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which child container name to retrieve. If this is outside of the allowable range, E_INVALIDARG is returned.
pwszContainer
[out] Address of a string buffer that receives the unique name of the child container. This should be at least 256 elements. If the buffer is too small, it will return DXDIAG_E_INSUFFICIENT_BUFFER.
cchContainer
[in] Specifies the size of the pwszContainer buffer in characters.

Return Value

Returns S_OK if successful. Otherwise, returns one of the following values.

E_INVALIDARG | An invalid argument was passed to the returning function.
DXDIAG_E_INSUFFICIENT_BUFFER | The buffer is too small.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*   pDxDiagContainer;
IDxDiagContainer*   pChildContainer;
DWORD   dwChildCount;
DWORD   dwChildIndex;
LPWSTR   wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::EnumPropNames Method

Enumerates the name of the property at the specified index.

Syntax

HRESULT EnumPropNames(

    DWORD dwIndex,
    LPWSTR pwszPropName,
    DWORD cchPropName
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which property name to retrieve. If this is outside the allowable range, then E_INVALIDARG is returned.
pwszPropName
[out] Receives the unique name of the property. It should be at least 256 elements. If the buffer is too small it will return DXDIAG_E_INSUFFICIENT_BUFFER.
cchPropName
[in] Specifies the size of the pwszPropName buffer in characters.

Return Value

If unsuccessful, returns one of the following values.

E_INVALIDARG | An invalid argument was passed to the returning function.
DXDIAG_E_INSUFFICIENT_BUFFER | The buffer is too small.

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::GetChildContainer Method

Retrieves a pointer to the child container specified.

Syntax

HRESULT GetChildContainer(

    LPCWSTR pwszContainer,
    IDxDiagContainer **ppInstance
);

Parameters

pwszContainer
[in] Specifies the NULL-terminated name of the container.
ppInstance
[out] Receives an instance of the child IDxDiagContainer specified by pwszContainer.

Return Value

If unsuccessful, returns one of the following values.

E_INVALIDARG | An invalid argument was passed to the returning function.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*	pDxDiagContainer;
IDxDiagContainer*	pChildContainer;
DWORD 	dwChildCount;
DWORD	dwChildIndex;
LPWSTR	wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::GetNumberOfChildContainers Method

Returns the number of IDxDiagContainer objects in this container.

Syntax

HRESULT GetNumberOfChildContainers(

    DWORD *pdwCount
);

Parameters

pdwCount
[out] Receives the number of IDxDiagContainer objects in the container.

Return Value

Returns S_OK if successful. Otherwise, returns the following value.

E_INVALIDARG An invalid argument was passed to the returning function.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*	pDxDiagContainer;
IDxDiagContainer*	pChildContainer;
DWORD 	dwChildCount;
DWORD	dwChildIndex;
LPWSTR	wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::GetNumberOfProps Method

Retrieves the number of properties in this container.

Syntax

HRESULT GetNumberOfProps(

    DWORD *pdwCount
);

Parameters

pdwCount
[out] Receives the number of properties in this container.

Return Value

Returns S_OK if successful. Otherwise, returns the following value.

E_INVALIDARG An invalid argument was passed to the returning function.

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagContainer::GetProp Method

Retrieves an instance of the property specified.

Syntax

HRESULT GetProp(

    LPCWSTR pwszPropName,
    VARIANT *pvarProp
);

Parameters

pwszPropName
[in] Specifies the NULL-terminated name of the property.
pvarProp
Receives an instance of the property specified in pwszPropName. Check the method's return value and call VariantClear only if the method succeeds.

Return Value

Returns S_OK if successful. Otherwise, returns the following value or one of the error codes for VariantCopy.

E_INVALIDARG An invalid argument was passed to the returning function.

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagProvider Interface

Applications use the methods of the IDxDiagProvider interface to create the root IDxDiagContainer object.

IDxDiagProvider Members

GetRootContainer | Creates and initializes an IDxDiagContainer object to be the root container.
Initialize | Initializes an IDxDiagProvider object.

Interface Information

Inherits from | IUnknown
Header | dxdiag.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagProvider::GetRootContainer Method

Creates and initializes an IDxDiagContainer object to be the root container.

Syntax

HRESULT GetRootContainer(

    IDxDiagContainer **ppInstance
);

Parameters

ppInstance
[in, out] Receives an instance of IDxDiagContainer.

Return Value

If unsuccessful, returns one of the following values.

E_CO_UNINITIALIZED | The requested object has not been initialized.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.
E_INVALIDARG | An invalid argument was passed to the returning function.
E_NOINTERFACE | No object interface is available.

© 2002 Microsoft Corporation. All rights reserved.


IDxDiagProvider::Initialize Method

Initializes an IDxDiagProvider object.

Syntax

HRESULT Initialize(

    DXDIAG_INIT_PARAMS *pParams
);

Parameters

pParams
[in] DXDIAG_INIT_PARAMS that specifies the initialization parameters.

Return Value

Returns S_OK if successful. Otherwise, returns one of the following values.

E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.
E_INVALIDARG | An invalid argument was passed to the returning function.
E_OUTOFMEMORY | Could not allocate enough memory to complete the operation.

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains structure exposed by the Microsoft® DirectX® Diagnostic Tool.

Structures

  • DXDIAG_INIT_PARAMS

© 2002 Microsoft Corporation. All rights reserved.


DXDIAG_INIT_PARAMS Structure

Used by IDxDiagProvider::Initialize to initialize the IDxDiagProvider object.

Syntax

typedef struct _DXDIAG_INIT_PARAMS {
    DWORD dwSize;
    DWORD dwDxDiagHeaderVersion;
    BOOL bAllowWHQLChecks;
    VOID *pReserved;
} DXDIAG_INIT_PARAMS;

Members

dwSize
Specifies the size of the structure.
dwDxDiagHeaderVersion
Identifies if header is built against correct version. This value must be DXDIAG_DX9_SDK_VERSION.
bAllowWHQLChecks
Specifies whether the Microsoft® DirectX® Diagnostic Tool is allowed to verify if the drivers are digitally signed by Microsoft Windows® Hardware Quality Labs (WHQL). When doing this, the DirectX Diagnostic Tool can connect to the Internet to download new WHQL certificates.
TRUE
Allow verification.
FALSE
Do not allow verification.
pReserved
Reserved. Must be NULL.

Structure Information

Header | dxdiag.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Programming DirectX with C/C++

Most Microsoft® DirectX® application development with C/C++ involves conventional programming techniques. However, there are several aspects of DirectX programming that may be unfamiliar to some developers. This section provides a brief overview of several specialized topics, along with some guidelines for compiling and debugging DirectX applications.

  • AppWizard
  • Using COM
  • Using Callback Functions
  • Version Checking
  • Compiling DirectX Samples and Other DirectX Applications
  • Debugging DirectX Applications
  • The DirectX 9.0 Error Handling Utility Library

© 2002 Microsoft Corporation. All rights reserved.


AppWizard

The Microsoft® DirectX® AppWizard creates a small C++ template application that can integrate the common DirectX components: Microsoft Direct3D®, Microsoft DirectInput®, Microsoft DirectMusic®, Microsoft DirectSound®, and Microsoft DirectPlay®. It provides basic functionality that is easy to build on and demonstrates the use of each component.

Along with the template, AppWizard includes the same C++ classes found in the DirectX software development kit (SDK) common directory. These C++ classes perform minimal wrapping of DirectX to get you up and running quickly. All the DirectX SDK samples make use of these classes. For example, the Direct3D samples use D3dapp.*, the DirectMusic samples use Dmutil.*, the DirectSound samples use Dsutil.*, and the DirectPlay samples use Netconnect.*.

The AppWizard target audience is amateur C++ game developers, 3-D hobbyists, and audio hobbyists (who do not need 3-D).

Running AppWizard

AppWizard is launched from Microsoft Visual Studio® 6.0 when you create a new project. It is one of the project types available when you choose File, New, and then the Projects tab, as shown in the following example.

Projects tab in the New box

When you enter a project name and click OK, the wizard presents a series of dialog boxes to allow you to configure the DirectX services that the application will need. The number of dialog boxes generated by the wizard depend on which DirectX technologies you select (Direct3D, DirectInput, and DirectPlay each generate their own dialog boxes). The files included in the project depend on the DirectX technologies selected, as well as the Microsoft Windows® technologies selected—Microsoft Win32®, Microsoft Foundation Classes (MFC), and Windows Graphics Device Interface (GDI). You select these technologies on the first page of the wizard, which is shown in the following example.

The wizard has three steps: Step 1 is the opening page, step 2 is the Direct3D page, and step 3 is the DirectInput page. The DirectMusic and DirectSound options do not generate additional pages but the DirectPlay Peer-to-Peer option will generate an additional page.

The wizard uses one of four base templates, based on the options you select.

  • For an application that is not MFC-based and uses Direct3D, choose Single document window and Direct3D. This is the standard case and is similar to the application used in the Dolphin VS Sample.
  • For an application that is MFC-based and uses Direct3D, choose MFC dialog based and Direct3D. The application will be similar to the MFC Fog Sample.
  • For a Microsoft® Windows® application that uses GDI but not MFC, choose Single document window. This application can use CreateWindow and basic GameLoop during idle time.
  • For an application that uses GDI and is MFC-based, choose MFC dialog based. The application will be similar to the MFC AppWizard dialog template.

The Direct3D, DirectInput, and DirectPlay check boxes each add another page to the wizard. These pages are described in the following sections.

Direct3D Page

The following Direct3D page is shown immediately after the first page if you selected the Direct3D check box in step 1.

The Direct3D page is step 2 because step 1 was the first page of the wizard.

The Direct3D exclusive options are:

  1. Blank. No Direct3D object is created.
  2. Triangle. Creates a simple object with two back-to-back triangles.
  3. Teapot. Creates a complex object using D3DXCreateTeapot.

If Direct3D fonts is checked, the project includes D3dfont.cpp and D3dfont.h. Otherwise, the project uses D3DXCreateFont to display 3-D fonts.

If 3D meshes is checked, the project includes D3dfile.cpp and D3dfile.h.

DirectInput Page

The following DirectInput page is shown immediately after the Direct3D page if you selected the DirectInput check box in step 1.

The DirectInput page is step 3. The options on this page are:

  • DirectInput action mapping. Uses Tutorial 5: Using Action Mapping to gather input data.
  • DirectInput keyboard device. Uses a simple DirectInput Devices to gather input data.

If you checked DirectInput in step 1, the project will include Diutil.cpp and Diutil.cpp files. The DirectX SDK sample, (SDK root)\Samples\bin\Donut3D.exe, uses these class files.

The application will use either Action Mapper or a keyboard device object to record key state. If neither is checked, DirectInput will use WM_KEYDOWN messages to record key state.

DirectMusic and DirectSound Check Boxes

These check boxes appear on page 1 of the wizard. They do no add pages to the wizard.

If DirectMusic is checked, the project will include Dmutil.cpp and Dmutil.h. The DirectMusic samples use these files.

If DirectSound is checked, the project will include Dsutil.cpp and Dsutil.h. The DirectSound samples use these files to load and play sounds.

If both DirectMusic and DirectSound are checked, DirectMusic is used to load and play the sounds, but Dsutil.* is still included in the project.

If either DirectMusic or DirectSound is checked, Bounce.wav is included in the project. Pressing the A key will play the sound.

If neither DirectMusic nor DirectSound is checked, Bounce.wav is not included and the A key is not recorded, nor is the Help string displayed.

DirectPlay Page

The following DirectPlay page is shown immediately after the DirectInput page if you selected the DirectPlay Peer-to-Peer check box in step 1.

The DirectPlay page is step 4, assuming that step 1 was the first page of the wizard, step 2 was the Direct3D page, and step 3 was the DirectInput page.

If DirectVoice is checked, the project will include Netvoice.cpp and Netvoice.h. The DirectPlay Voice samples use these files.

The project will integrate the NetConnect DirectPlay connection dialog boxes into the application. When the NetConnect dialog boxes finish, an active DirectPlay connection or failure results. If successful, the arrow key state is passed between all players using DirectPlay.

If DirectInput Action Mapper is used, DirectPlay sends the axis data across the network; otherwise it sends the state of the four arrow keys.

© 2002 Microsoft Corporation. All rights reserved.


Using COM

The Component Object Model (COM) is an object-oriented programming model used by numerous applications. Because the bulk of the Microsoft® DirectX® run time is in the form of COM-compliant objects, all DirectX developers need to have at least a basic understanding of COM principles and programming techniques. However, although COM has a reputation for being difficult and complex, the COM programming required by most DirectX applications is straightforward.

There are two distinct types of COM programming.

  • Using existing COM objects. This is not much more difficult than using C++ objects.
  • Implementing your own COM objects. This can be a complicated and demanding task. Much of COM's reputation for complexity comes from this type of COM programming.

Most DirectX applications need to use only the COM objects provided by DirectX. They do not need to implement their own COM objects. In other words, most DirectX developers will need to concern themselves only with the first, and easiest, type of COM programming.

This section provides a brief introduction to using the COM objects provided by DirectX. It is primarily intended for novice COM programmers. For a more detailed discussion of how to use COM objects, or for information about how to implement your own COM objects, see Further Information.

  • What is a COM Object?
  • Creating a COM Object
  • Using COM Interfaces
  • Managing a COM Object's Lifetime
  • Using C to Access COM Objects
  • Using Macros to Call DirectX COM Methods
  • DirectX COM Documentation Conventions
  • Using ATL with DirectX 9.0 COM Interfaces
  • IUnknown

© 2002 Microsoft Corporation. All rights reserved.


What is a COM Object?

Component Object Model (COM) objects are basically black boxes that can be used by applications to perform one or more tasks. They are most commonly implemented as a dynamic-link library (DLL). Like a conventional DLL, COM objects expose methods that your application can call to perform any of the supported tasks. Applications interact with COM objects in somewhat the same way they do with C++ objects. However, there are some distinct differences.

  • COM objects enforce stricter encapsulation than C++ objects. You cannot just create the object and call any public method. A COM object's public methods are grouped into one or more interfaces. To use a method, you must create the object and obtain the appropriate interface from the object. An interface typically contains a related set of methods that provide access to a particular feature of the object. For example, the IDirect3DCubeTexture9 interface contains methods that enable you to manipulate cube texture resources. Any methods that are not part of an interface are not accessible.
  • COM objects are not created in the same way as C++ objects. There are several ways to create a COM object, but all involve COM-specific techniques. The Microsoft® DirectX® API includes a variety of helper functions and methods that simplify creating most of the DirectX objects.
  • You must use COM-specific techniques to control the lifetime of the object.
  • COM objects do not need to be explicitly loaded. COM objects are typically contained in a DLL. However, you do not need to explicitly load the DLL or link to a static library in order to use a COM object. Each COM object has a unique registered identifier that is used to create the object. COM automatically loads the correct DLL.
  • COM is a binary specification. COM objects can be written in and accessed from a variety of languages. You don't need to know anything about the object's source code. For example, Microsoft Visual Basic® applications routinely use COM objects that were written in C++.

This document contains the following sections.

  • Objects and Interfaces
  • GUIDs
  • HRESULT Values
  • The Address of a Pointer

Objects and Interfaces

It is important to understand the distinction between objects and interfaces. In casual usage, an object may sometimes be referred to by the name of its principle interface. However, strictly speaking, the two terms are not interchangeable.

  • An object may expose any number of interfaces. For example, while all objects must expose the IUnknown interface, they normally expose at least one additional interface, and they might expose many. In order to use a particular method, you must not only create the object, you must also obtain the correct interface.
  • More than one object might expose the same interface. An interface is a group of methods that perform a specified set of operations. The interface definition specifies only the syntax of the methods and their general functionality. Any COM object that needs to support a particular set of operations can do so by exposing a suitable interface. Some interfaces are highly specialized and are exposed only by a single object. Others are useful in a variety of circumstances and are exposed by many objects. The extreme case is the IUnknown interface, which must be exposed by all COM objects.
Note If an object exposes an interface, it must support every method in the interface definition. In other words, you can call any method and be confident that it exists. However, the details of how a particular method is implemented may vary from object to object. For example, different objects may use different algorithms to arrive at the final result. There is also no guarantee that a method will be supported in a nontrivial way. Sometimes an object exposes a commonly-used interface, but needs to support only a subset of the methods. You will still be able to call the remaining methods successfully, but they will return E_NOTIMPL. You should refer to the documentation to see how an interface is implemented by any particular object.

The COM standard requires that an interface definition must not change once it has been published. You cannot, for example, add a new method to an existing interface. You must instead create a new interface. While there are no restrictions on what methods must be in that interface, a common practice is to have the next-generation interface include all the of the old interface's methods, plus any new methods.

It is not unusual for an interface to have several generations. Typically, all generations perform essentially the same overall task, but they will be different in detail. Often, an object will expose every generation of interface. Doing so allows older applications to continue using the object's older interfaces, while newer applications can take advantage of the features of the newer interfaces. Typically, a family of interfaces will all have the same name, plus an integer indicating the generation. For example, if the original interface were named IMyInterface, the next two generations would be called IMyInterface2 and IMyInterface3. DirectX typically labels successive generations of interfaces with the DirectX version number.

GUIDs

Globally unique identifiers (GUIDs) are a key part of the COM programming model. At its most basic, a GUID is a 128-bit structure. However, GUIDs are created in such as way as to guarantee that no two GUIDs are the same. COM uses GUIDs extensively for two primary purposes:

  • To uniquely identify a particular COM object. A GUID that is assigned to a COM object is called a class identifier (CLSID). You use a CLSID when you want to create an instance of the associated COM object.
  • To uniquely identify a particular COM interface. The GUID that is associated with a particular COM interface is called an interface identifier (IID). You use an IID when you request a particular interface from an object. An interface's IID will be the same, regardless of which object exposes the interface.
Note For convenience, documentation normally refers to objects and interfaces by a descriptive name such as IDirect3D9. In the context of the documentation, there is rarely any danger of confusion. However, strictly speaking, there is no guarantee that another object or interface does not have the same descriptive name. The only unambiguous way to refer to a particular object or interface is by its GUID.

Although GUIDs are structures, they are often expressed as an equivalent string. The general format of the string form of a GUID is 32 hexadecimal integers in the format 8-4-4-4-12. That is, "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}," where each x corresponds to a hexadecimal integer. For example, the string form of the IID for the IDirect3D9 interface is:

{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}

Because the actual GUID is somewhat clumsy to use and easy to mistype, an equivalent name is usually provided as well. You can use this name instead of the actual structure when you call functions such as CoCreateInstance. The customary naming convention is to prepend either IID_ or CLSID_ to the descriptive name of the interface or object, respectively. For example, the name of the IDirect3D9 interface's IID is IID_IDirect3D9.

HRESULT Values

All COM methods return a 32-bit integer called an HRESULT. With most methods, the HRESULT is essentially a structure that contains two primary pieces of information:

  • Whether the method succeeded or failed.
  • More detailed information about the outcome of the operation supported by the method.

Some methods return HRESULT values only from the standard set defined in Winerror.h. However, methods are free to return custom HRESULT values with more specialized information. These values are normally documented on the method's reference page.

Note The list of HRESULT values that you find on a method's reference page is often only a subset of the possible values that may be returned. The list typically covers only those values that are specific to the method and those standard values that have some method-specific meaning. You should assume that a method may return a variety of standard HRESULT values, even if they are not explicitly documented.

While HRESULT values are often used to return error information, you should not think of them as error codes. The fact that the bit that indicates success or failure is stored separately from the bits that contain the detailed information allows HRESULT values to have any number of success and failure codes. By convention, success codes are given names with an S_ prefix, and failure codes with an E_ prefix. For example, the two most commonly used codes are S_OK and E_FAIL, which indicate simple success or failure, respectively.

The fact that COM methods may return a variety of success or failure codes means that you have to be careful how you test the HRESULT value. For example, consider a hypothetical method with documented return values of S_OK if successful and E_FAIL if not. However, remember that the method may also return other failure or success codes. The following code fragment illustrates the danger of using a simple test. The hr value is the HRESULT that was returned by the method.

if(hr == E_FAIL)
{
    //Handle the failure
}

else
{
    //Handle the success
}

As long as the method returns only E_FAIL to indicate failure, this test will work properly. However, the method might also return an error value such as E_NOTIMPL or E_INVALIDARG. That value would be interpreted as a success, perhaps causing your application to fail.

If you need detailed information about the outcome of the method call, you will need to test each relevant HRESULT value. However, you may be interested only in whether the method succeeded or failed. A robust way to test whether an HRESULT value indicates success or failure is to pass the value to the one of the following macros, defined in Winerror.h.

  • The SUCCEEDED macro returns TRUE for a success code and FALSE for a failure code.
  • The FAILED macro returns TRUE for a failure code and FALSE for a success code.

You can fix the preceding code fragment by using the FAILED macro.

if(FAILED(hr))
{
   //Handle the failure
}

else
{
   //Handle the success
}

This code fragment properly treats E_NOTIMPL and E_INVALIDARG as failures.

Although most COM methods return structured HRESULT values, a small number use the HRESULT to return a simple integer. Implicitly, these methods are always successful. If you pass an HRESULT of this sort to the SUCCEEDED macro, the macro will always return TRUE. A commonly used example is the IUnknown::Release method. This method decrements an object's reference count by one and returns the current reference count. See Managing the Object's Lifetime for a discussion of reference counting.

The Address of a Pointer

If you view a few COM method reference pages, you will probably run across something like the following:

HRESULT CreateDevice(..., IDirect3DDevice9 **ppReturnedDeviceInterface);

While a normal pointer is quite familiar to any C/C++ developer, COM often uses an additional level of indirection. This second level of indirection is indicated by a "**" following the type declaration, and the variable name typically has a "pp" prefix. For the example given above, ppReturnedDeviceInterface parameter is typically referred to as the address of a pointer to an IDirect3DDevice9 interface.

Unlike C++, you do not access a COM object's methods directly. Instead, you must obtain a pointer to an interface that exposes the method. To invoke the method, you use essentially the same syntax that you would to invoke a pointer to a C++ method. For example, to invoke the IMyInterface::DoSomething method, you would use the following syntax.

IMyInterface *pMyIface;
...
pMyIface->DoSomething(...);

The need for a second level of indirection comes from the fact that you do not create interface pointers directly. You must call one of variety of methods, such as the CreateDevice method shown above. To use such a method to obtain an interface pointer, you declare a variable as a pointer to the desired interface, and pass the address of that variable to the method. In other words, you pass the method the address of a pointer. When the method returns, the variable will point to the requested interface, and you can use that pointer to call any of the interface's methods. For more information about how to use interface pointers, see Using COM Interfaces.

© 2002 Microsoft Corporation. All rights reserved.


Creating a COM Object

There are several ways to create Component Object Model (COM) objects. The two most common ones used in Microsoft® DirectX® programming are:

  • Directly, by passing the object's class identifier (CLSID) to the CoCreateInstance function. The function will create an instance of the object, and it will return a pointer to an interface that you specify.
  • Indirectly, by calling a DirectX method or function that creates the object for you. The method creates the object and returns an interface on the object. When you create an object this way, you usually cannot specify which interface should be returned.

Before you create any objects, COM must be initialized by calling the CoInitialize function. If you are creating objects indirectly, the object creation method will handle this task. If you need to create an object with CoCreateInstance, you must call CoInitialize explicitly. When you are finished, COM must be uninitialized by calling CoUninitialize If you make a call to CoInitialize you must match it with a call to CoUninitialize. Typically, applications that need to explicitly initialize COM do so in their startup routine, and they uninitialize COM in their cleanup routine.

To create a new instance of a COM object with CoCreateInstance, you must have the object's CLSID. If this CLSID is publicly available, you will find it in the reference documentation or the appropriate header file. If the CLSID is not publicly available, you cannot create the object directly.

The CoCreateInstance function has five parameters. For the COM objects you will be using with DirectX, you can normally set the parameters as follows

  • rclsid. Set this parameter to the CLSID of the object you want to create.
  • pUnkOuter. Set this parameter to NULL. It is used only if you are aggregating objects. See Further Information for a discussion of aggregation.
  • dwClsContext. Set this parameter to CLSCTX_INPROC_SERVER. This setting indicates that the object is implemented as a dynamic-link library (DLL) and will run as part of your application's process.
  • riid. Set this parameter to the interface identifier (IID) of the interface that you would like to have returned. The function will create the object, and it will return the requested interface pointer in the ppv parameter.
  • ppv. Set this parameter to the address of a pointer that will be set to the interface specified by riid when the function returns. This variable should be declared as a pointer to the requested interface, and the reference to the pointer in the parameter list should be cast as (LPVOID *).

For example, the following code fragment creates a new instance of the Microsoft DirectPlay® peer object, and returns a pointer to the object's IDirectPlay8Peer interface in the g_pDP variable. If an error occurs, a message box is displayed, and the application terminates.

IDirectPlay8Peer*  g_pDP = NULL;
...
CoInitialize( NULL );
...
hr = CoCreateInstance( CLSID_DirectPlay8, NULL, CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8Peer, (LPVOID*) &g_pDP );

if( FAILED( hr ) )
  {
    MessageBox( NULL, TEXT("Failed Creating IDirectPlay8Peer. "),
                  TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
    return FALSE;
  }
...

Creating an object indirectly is usually much simpler. You pass the object creation method the address of an interface pointer. The method then creates the object and returns an interface pointer. When you create an object indirectly, you typically cannot choose which interface the method will return. However, you can often specify a variety of things about how the object should be created. For example, the following code fragment calls the IDirect3D9::CreateDevice method discussed earlier to create a device object to represent a display adapter. It returns a pointer to the object's IDirect3DDevice9 interface. The first four parameters provide a variety of information needed to create the object, and the fifth parameter receives the interface pointer. See the reference documentation for details.

IDirect3DDevice9 *g_pd3dDevice = NULL;
...
if( FAILED( g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
                                 3DDEVTYPE_HAL,
                                 hWnd,
                                 D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                 &d3dpp,
                                 &g_pd3dDevice )))

  return E_FAIL;

© 2002 Microsoft Corporation. All rights reserved.


Using COM Interfaces

When a Component Object Model (COM) object is created, the creation method returns an interface pointer. You can then use that pointer to access any of the interface's methods. The syntax is identical to that used with a pointer to a C++ method. The following code fragment extends the example given in the previous section. After creating the IDirectPlay8Peer object, the example uses the IDirectPlay8Peer interface pointer returned by CoCreateInstance to initialize the object by calling the IDirectPlay8Peer::Initialize method. Error correction code is omitted for clarity.

IDirectPlay8Peer*  g_pDP = NULL;
...
CoInitialize( NULL );
...
hr = CoCreateInstance( CLSID_DirectPlay8Peer, NULL,CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8Peer, (LPVOID*) &g_pDP );

hr = g_pDP->Initialize( NULL, DirectPlayMessageHandler, 0 );

Requesting Additional Interfaces

In many cases, the interface pointer that you receive from the creation method may be the only one that you need. In fact, it is relatively common for an object to export only one interface other than IUnknown. However, many objects export multiple interfaces, and you may need pointers to several of them. If you need more interfaces than the one returned by the creation method, there is no need to create a new object. Instead, request another interface pointer by using the object's IUnknown::QueryInterface method.

If you create your object with CoCreateInstance, you can request an IUnknown interface pointer, and then call IUnknown::QueryInterface to request every interface you need. However, this approach is inconvenient if you need only a single interface, and it doesn't work at all if you use an object creation method that does not allow you to specify which interface pointer should be returned. In practice, you usually don't need to obtain an explicit IUnknown pointer because all COM interfaces extend the IUnknown interface.

Extending an interface is similar to inheriting from a C++ class. The child interface exposes all of the parent interface's methods, plus one or more of its own. In fact, you will often see "inherits from" used instead of "extends". What you need to remember is that the inheritance is internal to the object. Your application cannot inherit from or extend an object's interface. However, you can use the child interface to call any of the child's or the parent's methods.

Because all interfaces are children of IUnknown you can use any of the interface pointers you already have for the object to call QueryInterface. When you do so, you must provide the interface identifier (IID) of the interface you are requesting and the address of a pointer that will contain the interface pointer when the method returns. For example, the following code fragment calls IDirectSound9::CreateSoundBuffer to create a primary buffer object. This object exposes several interfaces. The CreateSoundBuffer method returns an IDirectSoundBuffer9 interface. The subsequent code then uses the IDirectSoundBuffer9 interface to call QueryInterface to request an IDirectSound3DListener9 interface.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener;
...
if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr = pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                           (LPVOID *)&pDSListener)))
  return hr;

© 2002 Microsoft Corporation. All rights reserved.


Managing a COM Object's Lifetime

When an object is created, the system allocates the necessary memory resources. When an object is no longer needed, it should be destroyed. The system can use that memory for other purposes. With C++ objects, you can control the object's lifetime directly with the new and delete operators. Component Object Model (COM) does not enable you to create or destroy objects directly. The reason for this practice is that the same object may be used by more than one application. If one of those applications were to destroy the object, the other applications would probably fail. Instead COM uses a system of reference counting, to control an object's lifetime.

An object's reference count is the number of times one of its interfaces has been requested. Each time an interface is requested, the reference count is incremented. An application releasesan interface when that interface is no longer needed, decrementing the reference count. As long as the reference count is greater than zero, the object remains in memory. When the reference count reaches zero, the object destroys itself. You don't need to know anything about the reference count of an object. As long as you obtain and release an object's interfaces properly, the object will have the appropriate lifetime.

Important Properly handling reference counting is a crucial part of COM programming. Failure to do so can easily create a memory leak. One of the most common mistakes that COM programmers make is failing to release an interface. When this happens, the reference count will never reach zero, and the object will remain in memory indefinitely.

Incrementing and Decrementing the Reference Count

Whenever you obtain a new interface pointer, the reference count must be incremented by a call to IUnknown::AddRef. However, your application does not usually need to call this method. If you obtain an interface pointer by calling an object creation method or by calling IUnknown::QueryInterface, the object will automatically increment the reference count. However, if you create an interface pointer in some other way, such as copying an existing pointer, you must explicitly call IUnknown::AddRef. Otherwise, when you release the original interface pointer, the object may be destroyed even though you may still need to use the copy of the pointer.

You must release all interface pointers, regardless of whether you or the object incremented the reference count. When you no longer need an interface pointer, call IUnknown::Release to decrement the reference count. A common practice is to initialize all interface pointers to NULL, and set them back to NULL when they are released. That convention allows you to test all interface pointers in your cleanup code. Those that are non-NULL are still active and must be released before you terminate the application.

The following code fragment extends the sample discussed in Using COM Interfaces to illustrate how to handle reference counting.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener = NULL;
IDirectSound3DListener9* pDSListener2 = NULL;
...
//Create the object and obtain an additional interface.
//The object increments the reference count.

if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr=pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                        (LPVOID *)&pDSListener)))
  return hr;

//Make a copy of the IDirectSound3DListener9 interface pointer.
//Call AddRef to increment the reference count and to ensure that
//the object is not destroyed prematurely

pDSListener2 = pDSListener;
pDSListener2->AddRef();
...
//Cleanup code. Check to see if the pointers are still active.
//If they are, call Release to release the interface.

if(pDSBPrimary != NULL)
{
  pDSBPrimary->Release();
  pDSBPrimary = NULL;
}

if(pDSListener != NULL)
{
  pDSListener->Release();
  pDSListener = NULL;
}

if(pDSListener2 != NULL)
{
  pDSListener2->Release();
  pDSListener2 = NULL;
}

© 2002 Microsoft Corporation. All rights reserved.


Using C to Access COM Objects

Although C++ is the most commonly used language for Component Object Model (COM) programming, you can also access COM objects using C. Doing so is relatively straightforward, but requires a somewhat more complex syntax.

  • All methods have an additional parameter added to the beginning of the parameter list. This parameter must be set to the interface pointer.
  • You must explicitly reference the object's vtable.

Every COM object has a vtable that contains a list of pointers to the methods that the object exposes. An interface pointer points to the appropriate location in the vtable, which in turn contains a pointer to the particular method you are calling. The vtable is not mentioned elsewhere in this documentation because with C++, the vtable is essentially invisible. However, if you want to call COM methods with C, you must include an additional level of indirection that explicitly references the vtable.

The following code fragment illustrates how to call the IDirectPlay8Peer::Initialize method with the C++ calling convention.

g_pDP->Initialize( NULL, DirectPlayMessageHandler, 0 );

To make the same method call from C, use the following syntax. The conventional name for the vtable pointer is lpVtbl.

g_pDP->lpVtbl->Initialize(g_pDP,NULL, DirectPlayMessageHandler, 0);

Some components have macros defined in their header files that resolve to the correct calling convention. See Using Macros to Call DirectX COM Methods for details.

© 2002 Microsoft Corporation. All rights reserved.


Using Macros to Call DirectX COM Methods

Many of the Microsoft® DirectX® Component Object Model (COM) interfaces have macros defined for each method that simplify using the methods in your application. You can find definitions of these macros in the same header file as the interface declaration. The macros are designed to be used by both C and C++ applications. To use the C++ macros, you must define _cplusplus. Otherwise, the C macros will be used. The macro syntax is the same for both languages, but the header files include separate sets of macro definitions that expand to the appropriate calling convention.

For example, the following code fragment from the d3d.h header file shows the definitions of the C and C++ macros for the IDirect3D9::GetAdapterIdentifier method.

...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->lpVtbl->GetAdapterIdentifier(p,a,b,c)
...
#else
...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->GetAdapterIdentifier(a,b,c)
...
#endif

To use one of these macros, you must first obtain a pointer to the associated interface. The first parameter of the macro must be set to that pointer. The remaining parameters map to the method's parameters. The macro's return value is the HRESULT value that is returned by the method. The following code fragment uses a macro to call the IDirect3D9::GetAdapterIdentifier method. pD3D is a pointer to an IDirect3D9 interface.

hr = IDirect3D9_GetAdapterIdentifier(pD3D,
                                     Adapter,
                                     dwFlags,
                                     pIdentifier);

© 2002 Microsoft Corporation. All rights reserved.


DirectX COM Documentation Conventions

By convention, Component Object Model (COM) methods and interfaces are referred to in the documentation by their equivalent C++ class names. The Initialize method of the IDirectPlay8Peer interface is thus referred to as IDirectPlay8Peer::Initialize. The primary reason for this convention is that different interfaces may export a method with the same name but with entirely different functionality and syntax. For example, many interfaces have an Init or Initialize method, but the functionality and parameters may be quite different. Using the C++ class name is a convenient way to uniquely identify the method.

The text and sample code generally uses C++ conventions for calling COM methods. See Using C to Access COM Objects, for a discussion of how to convert a C++ method call to its C equivalent.

© 2002 Microsoft Corporation. All rights reserved.


Using ATL with DirectX 9.0 COM Interfaces

To use the Active Template Library (ATL) with Microsoft® DirectX® 9.0, you must redefine the interfaces for ATL compatibility. This will allow you to properly use the CComQIPtr class to obtain a pointer to an interface.

If you do not redefine the interfaces for ATL, you will get the following error message.

C:\Program Files\Microsoft Visual Studio\VC98\ATL\INCLUDE\atlbase.h(566) :
  error C2787: 'IDirectXFileData' : no GUID has been associated with this object

The following code sample shows how to define the IDirectXFileData interface.

// Explicit declaration
struct __declspec(uuid("{3D82AB44-62DA-11CF-AB39-0020AF71E433}")) IDirectXFileData;

// Macro method
#define RT_IID(iid_, name_) struct __declspec(uuid(iid_)) name_
RT_IID("{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}", IDirectXFileData);

After redefining the interface, you must use the Attach method to attach the interface to the interface pointer returned by ::Direct3DCreate9. If you do not, the IDirect3D9 interface will not be properly released by the smart pointer class.

The CComPtr class internally calls IUnknown::AddRef on the interface pointer when the object is created and when an interface is assigned to the CComPtr class. To avoid leaking the interface pointer, do not call IUnknown::AddRef on the interface returned from ::Direct3DCreate9.

The following code properly releases the interface without doing IUnknown::AddRef.

CComPtr<IDirect3D9> d3d;
d3d.Attach(::Direct3DCreate9(D3D_SDK_VERSION));

Use the previous code. Do not use the following code, which calls IUnknown::AddRef followed by IUnknown::Release and does not release the reference added by ::Direct3DCreate9.

CComPtr<IDirect3D9> d3d = ::Direct3DCreate9(D3D_SDK_VERSION);

Note that this is the only place in Microsoft Direct3D® where you will have to use the Attach method in this manner.

For more information about the CComPTR and CComQIPtr classes, see their definitions in the Atlbase.h header file.

© 2002 Microsoft Corporation. All rights reserved.


IUnknown Interface

All Component Object Model (COM) objects support an interface called IUnknown. This interface provides Microsoft® DirectX® with control of the object's lifetime and the ability to retrieve other interfaces implemented by the object. IUnknown has three methods.

IUnknown Members

AddRef

Increases the interface's reference count by 1.

QueryInterface

Determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

Release Decreases the reference count of the interface by 1.

Remarks

The IUnknown::AddRef and IUnknown::Release methods maintain an object's reference count. For example, if you create a Microsoft Direct3D® object, the object's reference count is set to 1. Every time a function returns a pointer to an interface for that object, the function must call IUnknown::AddRef through that pointer to increment the reference count. Match each IUnknown::AddRef call with a call to IUnknown::Release. Before the pointer can be destroyed, you must call IUnknown::Release through that pointer. After an object's reference count reaches 0, the object is destroyed, and all interfaces to it become invalid.

The IUnknown::QueryInterface method determines whether an object supports a specific interface. If an object supports an interface, IUnknown::QueryInterface returns a pointer to that interface. You then can use the methods of that interface to communicate with the object. If IUnknown::QueryInterface successfully returns a pointer to an interface, it implicitly calls IUnknown::AddRef to increment the reference count, so your application must call IUnknown::Release to decrement the reference count before destroying the pointer to the interface.

Note The reference pages for IUnknown are included with this documentation as a convenience for users of the stand-alone DirectX Help file. Refer to the Microsoft Platform Software Development Kit (SDK) documentation for the most complete and up-to-date information about this interface.

Interface Information

Inherits from | None
Header | unknwn.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IUnknown::AddRef Method

Increases the interface's reference count by 1.

Syntax

ULONG AddRef(VOID);

Return Value

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

When the interface is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the IUnknown::AddRef method, the interface's reference count is increased by 1. Use the IUnknown::Release method to decrease the interface's reference count by 1.

© 2002 Microsoft Corporation. All rights reserved.


IUnknown::QueryInterface Method

Determines whether the object supports a particular Component Object Model (COM) interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

Syntax

HRESULT QueryInterface(

    REFIID riid,
    LPVOID *ppvObj
);

Parameters

riid
Reference identifier of the interface being requested.
ppvObj
Address of a pointer to fill with the interface pointer if the query succeeds.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be E_NOINTERFACE or E_POINTER. Some components also have their own definitions of these error values in their header files. In Microsoft® DirectInput®, for example, DIERR_NOINTERFACE is equivalent to E_NOINTERFACE.

Remarks

If the application does not need to use the interface retrieved by a call to this method, it must call the IUnknown::Release method for that interface to free it. The IUnknown::QueryInterface method enables Microsoft and third parties to extend objects without interfering with functionality.

© 2002 Microsoft Corporation. All rights reserved.


IUnknown::Release Method

Decreases the reference count of the interface by 1.

Syntax

ULONG Release(VOID);

Return Value

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

The object that exports the interface deallocates itself when its total reference count reaches 0. Use the IUnknown::AddRef method to increase the interface's reference count by 1.

Applications must call this method to release only those interfaces that were explicitly created in a previous call to IUnknown::AddRef, IUnknown::QueryInterface, or a creation function such as Direct3DCreate9.

© 2002 Microsoft Corporation. All rights reserved.


Using Callback Functions

A callback function is essentially an event handler that is implemented by an application and called by the system. Microsoft® Windows® applications typically implement multiple callback functions, each one designed for a particular set of events. When an event occurs, the system notifies the application by calling the appropriate callback function. The callback function also usually has a parameter list that the system can use to pass the application more detailed information about the event. The most common example of a callback function is the window procedure. This function is used by the system to pass Windows messages to the applications that owns the window.

Microsoft DirectX® uses callback functions for a variety of purposes. For example, your system supports multiple devices. Microsoft DirectInput® represents each device by a device object, that contains the details of the device's capabilities. Your application will typically need to enumerate the available devices and to examine the device objects in order to handle user input properly. To do this enumeration, you must implement a DIEnumDeviceObjectsCallback callback function.

You start the enumeration process by calling IDirectInputDevice8::EnumObjects and passing the method a pointer to your DIEnumDeviceObjectsCallback callback function. The system will call this function once for each device, and it will pass in a DIDEVICEOBJECTINSTANCE structure containing information about the device's capabilities. After your callback function has processed the information, it can return DIENUM_CONTINUE to request the next device object, or DIENUM_STOP to stop the enumeration.

DirectX uses a number of other callback functions for a variety of purposes. For details, see the documentation for the particular DirectX component.

Implementing a Callback Function

Because callback functions have different purposes and usage, they are documented in the appropriate Reference section in much the same way as a regular function. However, a callback function reference is essentially a template that describes how to implement the function, not a normal application programming interface (API) reference. The callback function reference provides the following information:

  • How the function is used
  • The function's syntax
  • An explanation of the information that will be contained by each parameter
  • An explanation of the possible return values

You should declare the function as a CALLBACK or WINAPI type. Either type is acceptable. You can use any function name. The name used in the documentation is just a convenient label for a particular callback function.

Implement the function according to the description in the reference. The implementation details will depend on the particular function and the requirements of your application. See the sample code for some examples of how to implement various callback functions.

Pass a pointer to the function to the appropriate DirectX component. The DirectX component can then use the function pointer to call the function. The way in which you pass this pointer varies from function to function, so you should see the particular function's reference for details.

The following code fragment is borrowed from the DirectInput Joystick sample. It sketches out the essential elements of a DIEnumDeviceObjectsCallback implementation that is used to enumerate the axes of a joystick.

// The function declaration
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext );
...
// Pass the function pointer to DirectInput by calling the
// IDirectInputDevice9::EnumObjects method

if ( FAILED( hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                            (VOID*)hDlg,
                                            DIDFT_AXIS )));

...

// The function implementation
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext )
{
// Process the information passed in through the two parameters
// Return DIENUM_CONTINUE to request the next device object
// Return DIENUM_STOP to stop the enumeration
}

© 2002 Microsoft Corporation. All rights reserved.


Version Checking

Applications sometimes need to know which version of Microsoft® DirectX® is currently available on the system. For example, if an older version of DirectX is on the system, your application may need to scale itself to the capabilities of that version or install the most recent version.

DirectX 9.0 supports the following operating systems. The table includes which version of DirectX shipped with each operating system.

Operating System | DirectX Version
Microsoft Windows® 98 Gold | DirectX 5.2
Windows 98 SE | DirectX 6.1a
Windows 2000 | DirectX 7.0
Windows Millennium Edition (Windows Me) | DirectX 7.1
Windows XP | DirectX 8.1

There is no direct way to obtain the DirectX version number. However, each version has a characteristic set of objects and interfaces. Because any version of DirectX supports all previous versions, this set of interfaces and objects will be supported by the version in which they are introduced and all subsequent versions. Thus, the preferred way to determine whether your desired version is available is to test for its characteristic objects or interfaces. As long as those are present, your application will work normally even though you might be using a more recent version of DirectX.

For example, suppose you need DirectX 6.1 support. The Microsoft DirectMusic® object (CLSID_DirectMusic) was introduced in DirectX 6.1. You can test for the presence of the DirectMusic object by attempting to create it with CoCreateInstance. If you are successful, you have version 6.1 or later, and you will be able to use all the DirectX 6.1 capabilities.

Rather than provide a detailed list here of each version's characteristic interfaces and objects, you should refer to the DirectX software development kits (SDKs) sample section. One of the samples is a function, GetDXVersion, that includes tests for all DirectX versions. GetDXVersion returns an integer that corresponds to the DirectX version that is present on the system. As long as this integer is greater than or equal to your desired version number, your application will run normally. You can find the sample code under your SDK root folder at \Samples\Multimedia\DXMisc\GetDXVer.

Checking the Operating System Version

In addition to determining the DirectX version, applications may also need to know what operating system they are running on, and perhaps which Service Pack has been installed. The preferred way to check the operating system version is to use the Windows function, GetVersionEx. This function returns an OSVERSIONINFO structure that contains a variety of information including:

  • Whether the system is Microsoft Windows NT®-based or Windows 95 or later
  • The major and minor version numbers
  • The service pack number, for Windows NT-based systems

The general procedure is to determine the earliest version of the operating system that your application is compliant with. If that version or later is installed, you can safely install and run your application.

Note The operating system information returned by GetVersionEx should not be used to test for the presence or version number of DirectX. In particular, the fact that a system is Windows NT-based does not necessarily mean that DirectX is absent. The Windows 2000 operating system, for example, includes DirectX 7.0 or later. New versions of Windows NT-based operating systems can also be expected to include a version of DirectX. Use the procedures described in the previous section to determine whether DirectX is present and, if so, the version number.

The following sample function illustrates how to use GetVersionEx to test the operating system version. If the installed version is identical to or more recent than the version specified in the parameter list, the function returns TRUE. You can then safely install and run your application. Otherwise the function returns FALSE, indicating that your application will not run properly, if at all.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

BOOL bIsWindowsVersionOK(DWORD dwWin9xMajor,
                         DWORD dwWin9xMinor,
                         DWORD dwWinNTMajor,
                         DWORD dwWinNTMinor,
                         WORD wWinNTSPMajor )

{
    OSVERSIONINFO           osvi;

    // Initialize the OSVERSIONINFO structure.

    ZeroMemory( &osvi, sizeof( osvi ) );
    osvi.dwOSVersionInfoSize = sizeof( osvi );

    GetVersionEx( &osvi );  // Assume this function succeeds.

    // Split code paths for NT and Windows 9x
    if( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
    {
        // Check the major version.
        if( osvi.dwMajorVersion > dwWin9xMajor )
            return TRUE;

        else if( osvi.dwMajorVersion == dwWin9xMajor )
        {
            // Check the minor version.
            if( osvi.dwMinorVersion >= dwWin9xMinor )
                return TRUE;
        }
    }

    else if( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT )
    {
        // Check the major version.
        if( osvi.dwMajorVersion > dwWinNTMajor )
            return TRUE;

        else if( osvi.dwMajorVersion == dwWinNTMajor )
        {
            // Check the minor version.
            if( osvi.dwMinorVersion > dwWinNTMinor )
                return TRUE;

            else if( osvi.dwMinorVersion == dwWinNTMinor )
            {
                // Check the service pack.

                DWORD dwServicePack = 0;

                if( osvi.szCSDVersion )
                {
                    _stscanf(osvi.szCSDVersion,
                             _T("Service Pack %d"),
                             &dwServicePack );
                }
                return ( dwServicePack >= wWinNTSPMajor );
            }
        }
    }
    return FALSE;
}

© 2002 Microsoft Corporation. All rights reserved.


Compiling DirectX Samples and Other DirectX Applications

This section provides information about considerations specific to compiling Microsoft® DirectX® applications. DirectX 9.0 supports only Microsoft Visual C++® 6.0 and later.

  • Preparing for Compilation
  • Component Version Constants
  • Linking with GUIDs

Preparing for Compilation

The samples included in this software development kit (SDK) use Microsoft Visual Studio® project files (.dsp files) that describe the appropriate source files, project resources, and linker settings for each sample. However, you might need to make additional preparations to ensure that the samples compile and link properly, or you might need to prepare settings for a new project. The information provided here applies to the DirectX samples and the DirectX applications that you create.

After opening a project file in Visual Studio, verify some settings before compiling the application. The settings will depend on whether you are using Visual C++ 6.0 or Visual Studio .NET.

Note The following discussion uses the default installation paths, C:\DXSDK\Include and C:\DXSDK\Lib, to describe header and library file locations. Your installation paths might differ.

Using Visual Studio 6.0

Include Search Paths

Be sure that the search path for header files is correct and that the directory for DirectX header files is the first path that the compiler searches. To check the include path, from the Tools menu, choose Options and then select the Directories tab. The following dialog box will appear.

The topmost path indicates the folder that contains the latest DirectX header files. The default path is C:\DXSDK\Include. If the path is not present, add it to the list and move it to the top of the search list by using the toolbar controls within the Directories tab.

Linker Search Paths

Check the search paths and search order that the linker uses to search for link libraries. The link search paths are also listed on the Directories tab. From the Tools menu, choose Options and then select the Directories tab. When the dialog box appears, choose the Library Files option in the Show directories for list box. The topmost path should be the folder that contains the latest DirectX link libraries. The default path is C:\DXSDK\Lib.

Project Link Libraries

If you are using the provided sample project files, you do not need to verify these settings. They are specified with the project files. For new applications, on the Project menu, click Settings. The following dialog box appears.

Project Settings box

You should verify that the application is linked to the appropriate standard DirectX link libraries.

Using Visual Studio .NET

Include Search Paths

Be sure that the search path for header files is correct and that the directory for DirectX header files is the first path that the compiler searches. To check the include path, from the Tools menu, choose Options, then open the Projects folder and select VC++ Directories. The following window will appear.

The topmost path indicates the folder that contains the latest DirectX header files. The default path is C:\DXSDK\Include. If the path is not present, add it to the list and move it to the top of the search list by using the up and down arrow buttons within the window.

Linker Search Paths

Check the search paths and search order that the linker uses to search for link libraries. The link search paths are also listed in the window displaying the VC++ Directories information. From the Tools menu, choose Options, then open the Projects folder and select VC++ Directories. When the window appears, choose the Library Files option in the Show directories for list box. The topmost path should be the folder that contains the latest DirectX link libraries. The default path is C:\DXSDK\Lib.

Project Link Libraries

If you are using the provided sample project files, you do not need to verify these settings. They are specified with the project files. For new applications, on the Project menu, click Properties. Open the Linker folder and select Input. The following dialog box appears.

Project Settings box

You should verify that libraries listed in the Application Dependencies are the appropriate standard DirectX link libraries.

Component Version Constants

For backward compatibility with earlier versions of DirectX, some DirectX components include variable application programming interface (API) element definitions in their header files. Affected elements are typically capability structures or flag sets that are version specific. Parts of some header files are surrounded by preprocessor conditionals that cause the preprocessor to filter out unneeded definitions. The value of the defined constant identifies a specific version of the component. If no value is defined, the headers set a value that identifies the DirectX version for which the header file was written. An example from the Microsoft Direct3D® header file, D3D9.h, is shown here.

#ifndef DIRECT3D_VERSION
#define DIRECT3D_VERSION         0x0900
#endif  //DIRECT3D_VERSION

You can define other values for these constants to use newer versions of the header files with older versions of the components. For example, to use the latest headers to compile against the DirectX 7.0 version of Direct3D, define DIRECT3D_VERSION to be 0x0700.

Linking with GUIDs

Direct3D uses globally unique identifiers (GUIDs) to identify parts of the interface. When you use the IUnknown::QueryInterface method to determine whether an object supports an interface, you identify the interface you're interested in by using its GUID.

To use GUIDs in a DirectX 9.0 application, include a link to the Dxguid.lib library and remove "#define INITGUID" from all your header files and source files. This is a change from previous versions, where GUIDs were linked by defining INITGUID prior to all other include and define statements. In the older versions, INITGUID needed to be defined in only one of your source modules.

Note that you use GUIDs differently depending on whether your application is written in C or C++. In C, you pass a pointer to the GUID (&IID_IDirect3D, for example), but in C++, you pass a reference to it (IID_IDirect3D).

© 2002 Microsoft Corporation. All rights reserved.


Debugging DirectX Applications

This section covers the following topics pertaining to debugging C and C++ applications.

  • Debug vs. Retail DLLs
  • Removing or Adding Debug DLLs
  • Other Resources

Debug vs. Retail DLLs

The Microsoft® DirectX® software development kit (SDK) installation program provides the option of installing either debug or retail builds of the DirectX dynamic-link libraries (DLLs).

When you develop software in C++, it is best to install the debug versions of the DLLs. This option installs both debug and retail DLLs on your system (the retail version installs only the retail DLLs). The debug DLLs have additional code that validates internal data structures and outputs debug error messages, using the OutputDebugString function while your program is executing. When an error occurs, the debug output gives you a more detailed description of the problem. The debug DLLs run more slowly than the retail DLLs but are much more useful for debugging an application. Be sure to ship the retail version with your application.

If you have the debug SDK installed, you can use the DirectX Control Panel utility to switch between the debug and retail builds of most components. To enable this feature, select the Debug option when you install the SDK.

To see the debug messages, configure your system so that debug output appears in a window or on a remote computer. A development environment such as Microsoft Visual Studio® .NET enables you to do this. Consult the environment documentation for setup instructions.

To ensure that the debugger can find the relevant symbolic information when using debug builds, locate the symbol files as follows:

Operating system | Debugger | .pdb file location | .dbg file location
Microsoft Windows® 98 | Microsoft Visual C++® | Same directory as binary | Same directory as binary
Windows 2000 | Visual Studio .NET | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Microsoft Windows NT®, Windows 2000 | Visual C++ | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Windows NT, Windows 2000 | NTSD/KD | %SystemRoot%\Symbols\<binary extension>\ | %SystemRoot%\Symbols\<binary extension>\
Windows XP | Visual Studio .NET | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\

Note When debugging with the Visual C++ development system on Windows NT or Windows 2000, do not use the Splitsym development tool. Splitsym copies private symbolic information from the <binary>.dbg file into the symbol directory under the binary extension—for example, %SystemRoot%\Symbols\Dll\—and deletes the original file from the binary directory. Visual C++ relies on finding a private symbolic information (<binary>.dbg) file in the same directory as the binary. Therefore, for debug builds, you must copy the private symbolic information and not delete it. This is an issue only when using Visual C++ with Windows NT or Windows 2000. Consult Visual C++ documentation and Windows 2000 Driver Development Kit (DDK) documentation for more debugging information.

Removing or Adding Debug DLLs

If you installed the retail runtime and would like to change to the debug runtime, run Dxpsetup.exe, which is located in the (DXSDK)\SDKDev\WindowsXP folder.

If you have the debug runtime and would like to revert to the retail runtime, run Undxxpdebug.exe, which is located in the Windows System folder. You can also run this by selecting Run from the Start menu and typing undxxpdebug in the box.

Note If you are using Windows 98, Windows Millennium Edition (Windows Me) or Windows 2000, you will need to uninstall the DirectX SDK in order to remove the debug version of the runtime.

Other Resources

To find C++ memory corruption problems, consider using a memory corruption/leak tool like Compuware's BoundsChecker World Wide Web link.

Microsoft maintains a database of "knowledge base" articles on MSDN®. Go to msdn.microsoft.com World Wide Web link and search for Knowledge Base Articles. Then search for the topic you need.

The AppVerifier tool monitors an application for things like heap corruption, locks usage, invalid handles, and thread stack size checking. To find the tool, search for Testing Applications with AppVerifier on the MSDN Library World Wide Web link.

© 2002 Microsoft Corporation. All rights reserved.


The DirectX 9.0 Error Handling Utility Library

The Microsoft® DirectX® 9.0 software development kit (SDK) includes a pair of utility functions and several macros designed to simplify the task of debugging your application. These functions are contained in the Dxerr9.lib library. The function and macro declarations are in Dxerr9.h.

  • DirectX 9.0 Error Handling Functions
  • DirectX 9.0 Error Handling Macros

© 2002 Microsoft Corporation. All rights reserved.


DirectX 9.0 Error Handling Functions

The following functions are included in the Microsoft® DirectX® error handling utility library, Dxerr9.lib.

Functions

  • DXGetErrorDescription9
  • DXGetErrorString9
  • DXTrace

© 2002 Microsoft Corporation. All rights reserved.


DXGetErrorDescription9 Function

Returns a string that describes a Microsoft® DirectX® HRESULT value.

Syntax

TCHAR *DXGetErrorDescription9(

    HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from Microsoft Direct3D®, Microsoft DirectPlay®, Microsoft DirectMusic®, Microsoft DirectSound®, Microsoft DirectInput®, and Microsoft DirectShow®.

Return Value

Returns a pointer to a character string that describes the HRESULT code.

Remarks

This function supports Microsoft Win32® Winerror.h error codes.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DXGetErrorString9 Function

Returns the name associated with an error code. This method is designed to handle error codes from all the Microsoft® DirectX® components and Microsoft Win32® functions.

Syntax

TCHAR *DXGetErrorString9(

    HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from Microsoft Direct3D®, Microsoft DirectPlay®, Microsoft DirectMusic®, Microsoft DirectSound®, Microsoft DirectInput®, and Microsoft DirectShow®.

Return Value

If successful, this function returns a pointer to a string that contains the name of the error code. If Unicode is set, DXGetErrorString9 will return a Unicode string. Otherwise, it will return an ANSI string.

Remarks

This function is designed to retrieve the text equivalent of a DirectX error message from a Direct3D, Direct3D extensions (D3DX), DirectPlay, DirectInput, DirectMusic, or DirectSound method. For example, if you set hr to 0x88760686, DXGetErrorString9 returns D3DERR_DEVICELOST.

If an error code maps to more than one text string, DXGetErrorString9 returns a generic string. For example, there are several DirectX error codes, such as DIERR_OUTOFMEMORY, that indicate that you are out of memory, and all map to the same value. If you set hr to any of these codes, DXGetErrorString9 will return E_OUTOFMEMORY.

This method handles all DirectX components including: Direct3D, DirectInput, DirectSound, DirectMusic, DirectShow, DirectPlay, and standard Win32 errors.

This function supports Unicode and ANSI strings.

This function supports Win32 Winerror.h error codes.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DXTrace Function

Displays a message box, and passes the error code to DXGetErrorString9.

Syntax

HRESULT DXTrace(

    CHAR *strFile,
    DWORD dwline,
    HRESULT hr,
    CHAR *strMsg,
    BOOL bPopMsgBox
);

Parameters

strFile
[in] Pointer to the name of the current file. You can set this parameter easily with the __FILE__ macro.
dwline
[in] Line number. You can set this parameter easily with the __LINE__ macro.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.
strMsg
[in] Pointer to an optional message that will be displayed along with the file name, line number, and HRESULT.
bPopMsgBox
[in] Specifies whether a message box should be displayed. If bPopMsgBox is set to TRUE, a message box will be displayed containing the values of the first four parameters. If bPopMsgBox is set to FALSE, the message box is not displayed.

Return Value

Returns the HRESULT that was assigned to hr.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DirectX 9.0 Error Handling Macros

The following macros simplify using the DXTrace function.

Functions

  • DXTRACE_ERR
  • DXTRACE_ERR_MSGBOX
  • DXTRACE_MSG

© 2002 Microsoft Corporation. All rights reserved.


DXTRACE_ERR Macro

Passes error information to the debugger.

Syntax

HRESULT DXTRACE_ERR(

    char *str,
    HRESULT hr
);

Parameters

str
[in] Pointer to a string to be passed to the debugger.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.

Return Value

Returns the HRESULT that was assigned to hr.

Remarks

The string and error name is accompanied by the file name and line number. The macro declaration is:

DXTRACE_ERR(str,hr) DXTrace(__FILE__,(DWORD)__LINE__,hr,str, FALSE)

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DXTRACE_ERR_MSGBOX Macro

Displays a message box with error information.

Syntax

HRESULT DXTRACE_ERR_MSGBOX(

    char *str,
    HRESULT hr
);

Parameters

str
[in] Pointer to a string to be displayed in the message box.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.

Return Value

Returns the HRESULT that was assigned to hr.

Remarks

The string and error name is accompanied by the file name and line number. The macro declaration is:

DXTRACE_ERR_MSGBOX(str,hr) DXTrace(__FILE__,(DWORD)__LINE__,hr,str,TRUE)

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DXTRACE_MSG Macro

Passes a string to the debugger.

Syntax

HRESULT DXTRACE_MSG(

    CHAR *str
);

Parameters

str
[in] Pointer to a string that will be passed to the debugger.

Return Value

Returns zero if successful, or a nonzero value if not.

Remarks

The string is accompanied by the file name and line number. The macro declaration is:

DXTRACE_MSG(str) DXTrace( __FILE__, (DWORD)__LINE__, 0, str, FALSE)

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DirectX and Windows XP

This topic contains tips for using Microsoft® DirectX® on Microsoft Windows® XP.

  • Handling Multiple Users
  • Fast User Switching
  • File Storage
  • Registry Storage

Handling Multiple Users

Windows XP allows multiple users to be logged on to one computer at the same time. If your application cannot run multiple instances simultaneously, you should check to see if another instance is running before starting a new instance. You cannot use FindWindow across desktop sessions. FindWindow only works within the current session.

To see if an instance of the application is already running, use a global mutex. If an instance is running, you can use FindWindow to see if the instance is in the current session and restore the window. Otherwise, notify users that they cannot use the application.

Fast User Switching

Fast User Switching allows users to switch between sessions. Users do not have to terminate their applications or log out for another user to start a session. Instead, they use Fast User Switching, which enables another user to log on and work on the computer.

DirectX applications should be prepared to handle this situation. Windows will send out a WM_WTSSESSION_CHANGE message when a user session changes. In order to receive this message, your application must register its window handle by calling WTSRegisterSessionNotification.

Note Microsoft DirectDraw® and Microsoft Direct3D® applications that set the window to full screen by default will not allow Fast User Switching.

File Storage

There are two types of users on Windows XP: administrators and limited users. Administrators have read/write access to all of the hard drive. Limited users are restricted to a few areas of the hard drive where they can write data.

The only areas of the hard drive that limited users have write access to, and therefore the only place DirectX applications should store information for limited users, are the following (default) directories:

CSIDL value | Folder
CSIDL_COMMON_DOCUMENTS | C:\Documents and Settings\All Users\Documents
CSIDL_PERSONAL | C:\Documents and Settings\<username>\MyDocuments
CSIDL_COMMON_APPDATA | C:\Documents and Settings\All Users\Application Data
CSIDL_LOCAL_APPDATA | C:\Documents and Settings\<username>\Application Data

Because installation should be to the Program Files directory (CSIDL_PROGRAM_FILES) by default, only an administrator can install an application. If a limited user is trying to install an application, an informational message box should be displayed telling the user that they need administrator privileges to install.

All of these locations should be determined by passing the appropriate CSIDL to the SHGetFolderPath function, rather than being hard-coded.

Data files generated by an application should be stored with limited users in mind. Use the following table to determine where to store the data.

Data available for: | CSIDL value | Can user load, view, and alter data? | Example
All users | CSIDL_COMMON_APPDATA | NO | System configuration
Current user | CSIDL_LOCAL_APPDATA | NO | Keyboard bindings
All users | CSIDL_COMMON_DOCUMENTS | YES | Shared saved files
Current user | CSIDL_PERSONAL | YES | Private saved files

Note If the user is meant to load, view, and alter data, ensure that there is a file association and icon representative to the application.

Registry Storage

To correctly store data in the registry, use the following guidelines.

  • Require administrator privileges for installation.
  • Be sure that each registry key item is less than 64 KB of data.
  • Registry data can exist in HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.

    HKEY_LOCAL_MACHINE

    • Only administrators have access, so do not store information that limited users will need to access in HKEY_LOCAL_MACHINE.
    • If you have data that few users must access, place it in HKEY_LOCAL_MACHINE.
    • Store computer configuration data in HKEY_LOCAL_MACHINE.

    HKEY_CURRENT_USER

    • Both administrators and limited users have access.
    • Any data that the "limited users" will need to access should be in HKEY_CURRENT_USER.
    • Store user configuration data in HKEY_CURRENT_USER.
    • When the game is first started, check the registry keys in HKEY_CURRENT_USER and make sure the default values exist.

© 2002 Microsoft Corporation. All rights reserved.


Further Information

For the latest about Microsoft® DirectX®, see the DirectX World Wide Web link Web site. This site contains DirectX downloads, the latest DirectX documentation, the "Driving DirectX" column, links to the DirectX newsgroups and more.

You can find more information about the graphics and multimedia concepts and terms discussed throughout the DirectX documentation, as well as information about Microsoft Windows® programming in general, in the following sources.

  • Bargen, Bradley, and Peter Donnelly. Inside DirectX. Microsoft Press®, 1998.
  • Begault, Durand R. 3-D Sound for Virtual Reality and Multimedia. Academic Press, 1994.
  • Blinn, James. Jim Blinn's Corner: A Trip Down the Graphics Pipeline. Morgan Kaufmann, 1996.
  • Dodge, Charles, and Thomas A. Jerse. Computer Music: Synthesis, Composition, and Performance. Second ed. Schirmer Books, 1997.
  • Engel, Wolfgang F. Direct3D ShaderX: Vertex and Pixel Tips and Tricks. Wordware Publishing, 2002.
  • Engel, Wolfgang F., et al., Beginning Direct3D Game Programming, Premier Press, 2001.
  • Foley, James D. Computer Graphics: Principles and Practice. Second ed. Addison-Wesley, 1991.
  • Hearn, Donald, and M. Pauline Baker. Computer Graphics. Prentice-Hall, 1986.
  • Kientzle, Tim. A Programmer's Guide to Sound. Addison-Wesley Developers Press, 1998.
  • Kovach, Peter J. Inside Direct3D. Microsoft Press, 2000.
  • Petzold, Charles. Programming Windows 98. Fifth ed. Microsoft Press, 1998.
  • Thompson, Nigel. 3D Graphics Programming for Windows 95. Microsoft Press, 1996.
  • Walsh, Peter. The Zen of Direct3D Game Programming. Premier Press, 2002.
  • Watt, Alan H., and Mark Watt. Advanced Animation and Rendering Techniques: Theory and Practice. Addison-Wesley, 1992.

Additional sources for the concepts and terms associated with Component Object Model (COM) can be found in the following sources:

  • Brockschmidt, Kraig. Inside OLE 2. Second ed. Microsoft Press, 1995.
  • Rogerson, Dale E. Inside COM. Microsoft Press, 1997.

© 2002 Microsoft Corporation. All rights reserved.


DirectX Graphics

This section provides information about using the Microsoft® DirectX® Graphics application programming interfaces (APIs).

As with other components of DirectX, DirectX Graphics can be used with C and C++.

Roadmap

Discover the features of DirectX 9.0 in four ways.

  • What's New in DirectX Graphics

    This section highlights new features and functionality of this component in DirectX 9.0. If you have used Microsoft Direct3D® or Microsoft DirectDraw® before, read this section first because much has changed since DirectX 8.0.

  • Converting to DirectX 9.0

    This section introduces new features and will help you port an application to DirectX 9.0.

  • Programming Guide

    This section contains architecture descriptions, functional block diagrams, descriptions of the building blocks in the pipeline, code snippets, and sample applications.

  • Reference

    This section contains the reference pages for the Direct3D API. This includes the syntax for the API methods, functions, instructions, and data structures. It includes an explanation of how the API method works and often includes code snippets.

© 2002 Microsoft Corporation. All rights reserved.


What's New in DirectX Graphics

This section describes Microsoft® DirectX® graphics features that are new in DirectX 9.0. See what's new in all of DirectX at What's New in DirectX 9.0.

Programming Guide

The programming guide has been reorganized into the following sections to help you find a topic.

  • Converting to DirectX 9.0 - This page contains hints for converting applications to DirectX 9.0. See Converting to DirectX 9.0.
  • Getting Started - Fundamental topics for getting started with Microsoft Direct3D®.

    Added a new page about DirectX 9.0 style vertex declarations. See Vertex Declaration.

  • Fixed Function - Covers the functionality of the fixed function pipeline.

    Textures section - Added automatic generation of mipmaps. See Automatic Generation of Mipmaps.

  • Programmable Pipeline - Many new features have been added to the shader models.

    Vertex and pixel shaders are no longer referred to with handles; they are objects. There is also a new section detailing the decoupling of vertex shaders and vertex declarations. See Component Object Model (COM) interfaces IDirect3DVertexShader9 and IDirect3DPixelShader9.

    Shaders and vertex stream declarations are no longer bound together at creation time. Vertex stream declarations are now expressed as an array of D3DVERTEXELEMENT9 elements. For more information, see Mapping Vertex Declarations and IDirect3DDevice9::SetFVF.

    Version 2 vertex shaders (vs_2_0) adds a limited form of flow control (loop...endloop, if...else...endif, and subroutines). Other features include more registers, constant setting methods (IDirect3DDevice9::SetVertexShaderConstantB, IDirect3DDevice9::SetVertexShaderConstantF, and IDirect3DDevice9::SetVertexShaderConstantI), new macro-ops for power, cross product, sign, absolute value, and linear interpolation. See Vertex Shader 2_0.

    Version 2 pixel shaders (ps_2_0) decoupled texture data and sampling by creating sampler registers in addition to the texture registers. Increased the instruction count and number of registers. Added float data types. Texture address and arithmetic instructions can now be intermixed. Eliminated all modifiers except negate. New macros and instructions include sincos (sine and cosine), normalization, cross product, power, linear interpolation, projected texture load, and biased level of detail (LOD) texture load. See Pixel Shader 2_0.

    Software shaders have been implemented to facilitate shader development without hardware support. The following software versions have been added: vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw.

    Extended shader versions take existing shader versions and extend their functionality if certain caps are set by the hardware. Extended functionality includes features like dynamic flow control, static flow control nesting, gradient instructions, and arbitrary swizzle. For more information, see Vertex Shader 2_0 Extended and Pixel Shader 2_0 Extended.

    Version 3 shaders further enhance the functionality of the extended shader versions without requiring caps to be set. Vertex shaders also add new support for vertex texturing, and control over how often vertex shader registers can be set during render calls. For more information, see Vertex Shader 3_0 and Pixel Shader 3_0.

  • Advanced Topics - Lots of new tools and techniques.
    • Adaptive tessellation can be applied to high-order primitives including N-patches, rectangle patches, and triangle patches based on the depth value of the control vertex in eye space. See Adaptive Tessellation.
    • Asynchronous notifications - There are a number of interesting asynchronous queries that could be made on driver status. This new functionality uses new interfaces to add asynchronous query capability. See Asynchronous Notification and IDirect3DQuery9.
    • Direct3D extensions (D3DX) - Added new functionality to the D3DX library to support new features, things like mesh functions, antialiased line drawing, pixel and vertex shaders, effects, math, and texturing functions. See Other Direct3D Extentions (D3DX).
    • Displacement mapping - Added support for displacement maps using several single-channel signed formats. See Displacement Mapping.
    • Gamma correction - Applications can indicate whether a texture is gamma 2.2 corrected (sRGB) or not so that the pipeline can perform gamma-correct blending. See Gamma.
    • Line drawing - A new interface was added for drawing antialiased lines. See Direct3D Extentions (D3DX) Line Drawing or ID3DXLine.
    • Multielement textures - This features allows applications to write out multiple elements of a texture simultaneously from a pixel shader. See Multielement Texture.
    • Multiple render targets - Support for a single render target has been extended to support multiple render targets. See Multiple Render Target.
    • Multihead - Multihead video cards use a common frame buffer and independent digital-to-analog converters (DACs) to offer more usable multiple-monitor support. See Multihead.
    • Surface locking behavior - A new locking flag, D3DLOCK_DONOTWAIT, allows an application to gain back CPU cycles if the driver cannot lock the surface immediately. See D3DLOCK.
    • Scissor test - The pipeline supports a scissor test, implemented with IDirect3DDevice9::SetScissorRect, IDirect3DDevice9::GetScissorRect, and a new render state, D3DRS_SCISSORTESTENABLE.
    • Tessellation - Tessellator support has been extended to adaptively tessellate and look up per-vertex displacement values from a displacement map. See Tessellation.
    • Two-sided stencil support - New support is available for adding shadows due to occluding geometry using shadow volumes. See Two-Sided Stencil.
  • Tutorials, Samples, Tools, and Tips - All the samples and other helpful tips and tools are gathered here. See Tutorials, Samples, Tools, and Tips.

Reference

Many new pages have been added to the reference section including:

  • Effects - ID3DXEffectCompiler, ID3DXBaseEffect, ID3DXEffect, ID3DXFragmentLinker, and ID3DXInclude. ID3DXSkinMesh was renamed ID3DXSkinInfo.

    Effects framework. A new interface, ID3DXEffectCompiler, allows the user to compile an effect from a function or from a vertex shader. The function can be written using the High-Level Shader Language.

  • High-Level Language Reference - A high-level shader language exists for creating effects from vertex shaders. This gives developers the ability to create effects from a C-like language. For more information, see High-Level Shader Language.
  • Shader Debugger - An extension to Microsoft Visual Studio® exists to support debugging some types of vertex shaders. For more information, see Shader Debugger.

Other Features

Other new features include the following:

  • Dirty Regions. IDirect3DDevice9::Present now supports a dirty region by means of the fourth parameter, a pointer to a region.
  • 2-D Support. Added support for a color-converting blit between most types of D3DPOOL_DEFAULT surfaces while using IDirect3DDevice9::StretchRect, and a color fill operation for D3DPOOL_DEFAULT surfaces while using IDirect3DDevice9::ColorFill.
  • Microsoft Windows® Graphics Device Interface (GDI) Interoperability. Two new methods have been added to get access to device contexts: IDirect3DSurface9::GetDC and IDirect3DSurface9::ReleaseDC.
  • DrawIndexedPrimitive. IDirect3DDevice9::DrawIndexedPrimitive has been changed to allow batching multiple primitives in the same index buffer without requiring multiple calls to IDirect3DDevice9::SetIndices.
  • Texgen Mode. The new texgen mode is to support the OpenGL-style sphere map texgen. Requires a new render state: D3DVTXPCAPS_TEXGEN_SPHEREMAP. See D3DVTXPCAPS.
  • ProcessVertices Behavior Change. This change enables multipass vertex processing and software pre-tessellation shaders. It enables IDirect3DDevice9::ProcessVertices to bypass the clipper and hence not compute the screen coordinates.
  • Mesh Copy and Update Methods. ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before. ID3DXBaseMesh::UpdateSemantics provides a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to re-label a 3-D texture coordinate as a binormal or tangent, or vice versa.
  • 32-Bit Texture Formats. Two new 32-bit texture formats were added: D3DFMT_A8B8G8R8, D3DFMT_X8B8G8R8. See D3DFORMAT.
  • Multisampling. A new multisampling control was added to give users control over performance versus quality. See SetDialogBoxMode, SetSampler, GetSamplerState, and D3DSAMPLERSTATE
  • CreateImageSurface. Removed as a result of adding D3DPOOL_SCRATCH.
  • Enumeration. IDirect3D9::EnumAdapterModes now takes a D3DFORMAT to support an expanding set of display modes.
  • Sample Framework. The sample framework now includes a dialog box for supporting user selection of processing type, device type, etc. The sample framework has improved the enumeration of device caps also. See Sample Framework.
  • Windowed Back Buffers. They can now be of a different format than the display. Added display modes with 10 bits per color channel. Added direct support for multihead adapters.
  • CopyRects. This has been replaced by IDirect3DDevice9::UpdateSurface.
  • State Blocks. These are no longer referred to with handles. They are now objects. See IDirect3DStateBlock9.

© 2002 Microsoft Corporation. All rights reserved.


Converting to DirectX 9.0

The following features were changed in Microsoft® DirectX® 9.0. If you are using these features, see the changes listed below to help you port your application to DirectX 9.0.

  • BaseVertexIndex Changes
  • CreateImageSurface Changes
  • D3DENUM_NO_WHQL_LEVEL Changes
  • EnumAdapterModes Changes
  • Get/SetStreamSource Changes
  • Handles
  • Multisampling Quality Changes
  • ResourceManagerDiscardBytes Changes
  • SetSoftwareVertexProcessing Changes
  • Texture Sampler Changes
  • Vertex Declaration Changes
  • Vsync, Intervals, and SwapEffects Changes

BaseVertexIndex Changes

In DirectX 8.x, SetIndices required a pointer to the index buffer and a BaseVertexIndex for the starting position in the vertex buffer. An application batching different objects into the vertex buffer had to switch the index buffer (or make a call to SetIndices) before calling DrawIndexedPrimitive.

In DirectX 9.0, the starting position in the vertex buffer, BaseVertexIndex, has been moved to IDirect3DDevice9::DrawIndexedPrimitive.

    HRESULT IDirect3DDevice9::DrawIndexedPrimitive(
        D3DPRIMITIVETYPE PrimType,
        INT BaseVertexIndex,
        UINT minIndex,
        UINT NumVertices,
        UINT startIndex,
        UINT primCount );

    HRESULT SetIndices(
        IDirect3DIndexBuffer9* pIndexData );

CreateImageSurface Changes

CreateImageSurface was renamed IDirect3DDevice9::CreateOffscreenPlainSurface. An additional parameter, D3DPOOL, was added.

HRESULT CreateOffscreenPlainSurface(
    UINT    Width,
    UINT    Height,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DSurface9** pReturnedSurfaceInterface);

D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the former CreateImageSurface.

D3DPOOL_DEFAULT is the appropriate pool for use with IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DENUM_NO_WHQL_LEVEL Changes

Applications now have to explicitly ask for the Microsoft Windows® Hardware Qualification Level, because the response takes relatively long (a few seconds). D3DENUM_NO_WHQL_LEVEL has been removed and D3DENUM_WHQL_LEVEL has been added. For more information, see the WHQLLevel member of D3DADAPTER_IDENTIFIER9.

EnumAdapterModes Changes

The IDirect3D9::EnumAdapterModes now takes a D3DFORMAT.

HRESULT IDirect3D9::EnumAdapterModes(
       UINT Adapter,
       D3DFORMAT Format,
       UINT Mode,
       D3DDISPLAYMODE *pMode);

The additional format parameter supports an expanding set of display modes. To protect applications from enumerating formats that were not invented when the application shipped, the application must tell Microsoft Direct3D® the format for which display modes should be enumerated. The resulting array of display modes will differ only by width, height, and refresh rate.

The application specifies a pixel format and the enumeration is restricted to those display modes that exactly match the format. Allowed formats are D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_A2B10G10R10, D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, and D3DFMT_R5G6B5.

Enumeration is equivalent for alpha and nonalpha versions of the same format. The returned FORMAT member of D3DDISPLAYMODE will always be filled with the same format supplied by the application.

This method treats 565 and 555 as equivalent, and returns the correct version in the Format. The difference comes into play only when the application locks the back buffer, and there is an explicit flag that the application must set in order to accomplish this.

Get/SetStreamSource Changes

One parameter has been added to the IDirect3DDevice9::GetStreamSource and IDirect3DDevice9::SetStreamSource methods. The offset parameter is the number of bytes between the beginning of the stream and the beginning of the vertex data. It is measured in bytes. This enables the pipeline to support stream offsets. To find out if the device supports stream offsets, see the D3DDEVCAPS2_STREAMOFFSET constant in D3DDEVCAPS2.

HRESULT GetStreamSource(
    UINT StreamNumber,
    IDirect3DVertexBuffer9 **ppStreamData,
    UINT *pOffsetInBytes,
    UINT *pStride
);

Handles

Another parameter, a handle, has been added to several methods. They are currently unused and should be set to NULL. The methods affected include:

    CreateTexture
    CreateVolumeTexture
    CreateCubeTexture
    CreateVertexBuffer
    CreateIndexBuffer
    CreateRenderTarget
    CreateDepthStencilSurface
    CreateOffscreenPlainSurface

Multisampling Quality Changes

Previously, there was only the D3DMULTISAMPLE_TYPE enumeration. DirectX 9.0 retains this enumeration and adds the idea of a quality level for each element of the enumeration. The quality level indicates a tradeoff between visual quality and performance by indicating the number of maskable samples (in the sense of D3DRS_MULTISAMPLEMASK).

An application should choose how many maskable samples it requires, and then consult the pQualityLevels value returned by IDirect3D9::CheckDeviceMultiSampleType. If nonzero, this value indicates the number of quality levels the application can pass to the various creation functions (CreateRenderTarget, etc.) through the new MultiSampleQuality argument.

Drivers expose all their multisample schemes as quality levels at D3DMULTISAMPLE_ONE, so if your application doesn't need to mask samples, you can enumerate all available multisampling schemes through this one type. The D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE caps bit has been retired. This bit used to mean that the multisampling method did not support write masks, and could not be toggled on and off between BeginScene and EndScene. Such nonmaskable methods are now exposed through D3DMULTISAMPLE_ONE.

A new caps bit, D3DPRASTERCAPS_MULTISAMPLE_TOGGLABLE, indicates that a device is capable of toggling multisampling on and off altogether, in between BeginScene and EndScene (using the D3DRS_MULTISAMPLEANTIALIAS render state). Any device that doesn't set this flag cannot disable or enable multisampling inside BeginScene/EndScene.

HRESULT CheckDeviceMultiSampleType(
       UINT Adapter,
       D3DDEVTYPE DeviceType,
       D3DFORMAT SurfaceFormat,
       BOOL Windowed,
       D3DMULTISAMPLE_TYPE MultiSampleType,
       DWORD * pQualityLevels);

There is a different maximum for each number of maskable samples (for example, D3DMULTISAMPLE_4_SAMPLES might have three levels of quality, while _2_SAMPLES might have only one). The number of quality levels is capped to at most eight levels of quality for each number of maskable samples (the driver is not allowed to express more). The quality ranges from zero to (*pQualityLevels-1).

IDirect3DDevice9::CreateRenderTarget and IDirect3DDevice9::CreateDepthStencilSurface were also extended to return the quality level. The quality level of paired methods must match, as well as the multisample type in DirectX 8.x.

ResourceManagerDiscardBytes Changes

ResourceManagerDiscardBytes has been replaced by IDirect3DDevice9::EvictManagedResources. It can evict all resources, both Direct3D and driver resources.

The resource manager is now consulted when a resource (whether managed or nonmanaged) fails creation because there is insufficient video memory. The manager will automatically be asked to free enough resources for the creation to succeed. In DirectX 8.0, this was not an automated process.

SetSoftwareVertexProcessing Changes

An application can create a mixed-mode device to use software and hardware vertex processing.

To switch between the two vertex processing modes in DirectX 8.x, call IDirect3DDevice8::SetRenderState with D3DRS_SOFTWAREVP. This has been replaced with IDirect3DDevice9::SetSoftwareVertexProcessing to ease problems caused by state blocks. This new method is not recorded by state blocks.

Texture Sampler Changes

In DirectX 9.0, there is support for up to 16 texture surfaces in one pass, using the pixel shader 2.0 model, yet the number of texture coordinates remains limited to 8. Some texture stage state is associated with surfaces, some with coordinate sets, some with vertex processing, and some with pixel processing. To manage these differences at compile time, the texture stage state application programming interface (API) is being broken into two. IDirect3DDevice9::SetTextureStageState will still be used for texture coordinate state such as wrap modes, and texture coordinate generation. In addition, IDirect3DDevice9::SetSamplerState will now be used for filtering, tiling, clamping, MIPLOD, etc. This will work for up to 16 samplers.

SetTextureStageState Changes

SetTextureStageState now sets the following states.

  • Fixed function vertex processing state - These states control the manipulation of texture coordinates - D3DTSS_TEXTURETRANSFORMFLAGS, D3DTSS_TEXCOORDINDEX. Up to eight of each can be set (because eight texture coordinates are always supported).
  • Fixed function pixel shader state (the legacy TextureStageState) - D3DTSS_COLOROP, D3DTSS_ALPHAOP, D3DTSS_COLORARG0, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG0, D3DTSS_ALPHAARG1, D3DTSS_ALPHAARG2, D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT11, D3DTSS_BUMPENVLSCALE, D3DTSS_BUMPENVLOFFSET, D3DTSS_RESULTARG. Up to MaxTextureBlendStages of these can be set.

D3DTSS_TEXCOORDINDEX, which is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.

The number of texture samplers available to the application is determined by the pixel shader version.

  • Fixed function pixel shader - MaxTextureBlendStages/MaxSimultaneousTextures Texture samplers.
  • ps_1_1 to ps_1_3 (4 texture samplers).
  • ps_1_4 (6 texture samplers).
  • ps_2_0 (16 texture samplers).
  • Devices that support displacement mapping in DirectX 9.0 will support an additional sampler (D3DDMAPSAMPLER), which samples the displacement maps in the tessellator unit.

SetSamplerState Changes

SetSamplerState sets the sampler state (including the one used in the tessellator unit to sample displacement maps). These have been renamed with a D3DSAMP_ prefix to enable compile time error detection when porting from DirectX 8.x. The states include D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, D3DSAMP_ADDRESSW, D3DSAMP_BORDERCOLOR, D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, D3DSAMP_MIPFILTER, D3DSAMP_MIPMAPLODBIAS, D3DSAMP_MAXMIPLEVEL, and D3DSAMP_MAXANISOTROPY.

Vertex Declaration Changes

Vertex declarations are now decoupled from vertex shader creation. Vertex declarations now use a Component Object Model (COM) interface.

For DirectX 8.x, vertex declarations are tied to vertex shaders.

  • For the fixed function pipeline, call SetVertexShader with the flexible vertex format (FVF) code of the vertex buffer.
  • For vertex shaders, call SetVertexShader with a handle to a previously create vertex shader. The shader includes a vertex declaration.

For DirectX 9.0, vertex declarations are decoupled from vertex shaders and they can be used with either the fixed function pipeline or with shaders.

  • For the fixed function pipeline, there is no need to call SetVertexShader. If however, you want to switch to the fixed function pipeline and have previously used a vertex shader, call SetVertexShader(NULL). When this is done, you will still need to call SetFVF to declare the FVF code.
  • When using vertex shaders, call SetVertexShader with the vertex shader object. Additionally, call SetFVF to set up a vertex declaration. This uses the information implicit in the FVF. SetVertexDeclaration can be called in place of SetFVF because it supports vertex declarations that cannot be expressed with an FVF.

Vsync, Intervals, and SwapEffects Changes

Several changes were made to give the user more control over monitor refresh rate, presentation rate, and front buffer vs back buffer drawing.

  • Removed one swap effect, D3DSWAPEFFECT_COPY_VSYNC, and one presentation rate, D3DPRESENT_RATE_UNLIMITED.
  • Renamed D3DPRESENT_PARAMETERS.FullScreen_PresentationInterval to PresentationIntervals.
  • Added the D3DPRESENT_INTERVAL_IMMEDIATE member of D3DPRESENT_PARAMETERS, which means that the presentation is not synchronized with the vertical sync.
  • As in DirectX 8.x, the D3DPRESENT_INTERVAL_DEFAULT member of D3DPRESENT_PARAMETERS is defined as zero and is equivalent to the D3DPRESENT_INTERVAL_ONE member of D3DPRESENT_PARAMETERS. the D3DPRESENT_INTERVAL_DEFAULT member of D3DPRESENT_PARAMETERS is a convenience for using memset to initialize D3DPRESENT_PARAMETERS to zero.

Windowed Mode

  • the D3DPRESENT_INTERVAL_DEFAULT member of D3DPRESENT_PARAMETERS or the D3DPRESENT_INTERVAL_ONE member of D3DPRESENT_PARAMETERS are nearly equivalent (see "Timer resolution" below). They perform similarly to COPY_VSYNC in that there is only one present per frame, and they prevent tearing with beam-following. In contrast, the D3DPRESENT_INTERVAL_IMMEDIATE member of D3DPRESENT_PARAMETERS will attempt to provide an unlimited presentation rate.
  • Windowed mode allows the D3DPRESENT_INTERVAL_DEFAULT, D3DPRESENT_INTERVAL_ONE, or the D3DPRESENT_INTERVAL_IMMEDIATE member of D3DPRESENT_PARAMETERS.

Full-Screen Mode

  • To promote usage similarity between windowed and full-screen mode, the D3DPRESENT_INTERVAL_IMMEDIATE member of D3DPRESENT_PARAMETERS will be supported regardless of the refresh rate or swap effect.

Timer resolution - the D3DPRESENT_INTERVAL_DEFAULT member of D3DPRESENT_PARAMETERS uses the default system timer resolution whereas the D3DPRESENT_INTERVAL_ONE member of D3DPRESENT_PARAMETERS calls timeBeginPeriod(1) to enhance system timer resolution. This improves the quality of vertical sync, but consumes slightly more processing time. Both parameters attempt to synchronize vertically.

© 2002 Microsoft Corporation. All rights reserved.


Programming Guide

This guide contains a description of the graphics pipeline implemented by Microsoft® Direct3D®. It is a guide for developers who are implementing three-dimensional (3-D) graphics functionality into their applications. The guide contains architecture descriptions, functional block diagrams, and descriptions of the building blocks in the pipeline, as well as code snippets and sample applications. The information is divided into the following sections.

  • Getting Started with Direct3D - This section contains both an overview of the pipeline and tutorials that can help you get a simple graphics application running in a few minutes.
  • Fixed Function Pipeline - This section explains how to use the fixed function pipeline. Included here are the basic functional steps in the graphics pipeline: converting geometry, adding lighting, and rendering output.
  • Programmable Pipeline - This section covers the new programmable extensions to the pipeline. Included here are details about using vertex shaders for manipulating object geometry, pixel shaders for controlling pixel shading, and effects and effect files for building applications that can run on a variety of hardware platforms.
  • Advanced Topics - This section contains examples of different types of special effects you can implement. Topics such as environment and bump mapping, antialiasing, vertex blending, and tweening show how to apply leading-edge special effects to your application.
  • Tutorials, Samples, Tools, and Tips - This section contains tutorials, sample applications, tools, and tips for using Microsoft DirectX® graphics.

For more information about specific application programming interface (API) methods, see the Reference pages.

© 2002 Microsoft Corporation. All rights reserved.


Getting Started with Direct3D

This section provides a brief introduction to the three-dimensional (3-D) graphics functionality in the Microsoft® Direct3D® application programming interface (API). Here you will find an overview of the graphics pipeline and tutorials to help you get basic Direct3D functionality up and running quickly.

  • Direct3D Architecture
  • 3-D Coordinate Systems and Geometry
  • Direct3D Object
  • Devices
  • Resources
  • States
  • Vertex Declaration
  • Vertex Formats
  • Object Geometry
  • Rendering

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Architecture

This section contains general information about the relationship between the Microsoft® Direct3D® component and the rest of Microsoft DirectX®, the operating system, and the system hardware. The following topics are discussed.

  • Architectural Overview for Direct3D
  • Hardware Abstraction Layer
  • System Integration
  • Programmable Vertex Shader Architecture
  • Programmable Pixel Shader Architecture

© 2002 Microsoft Corporation. All rights reserved.


Architectural Overview for Direct3D

This is an illustration of the graphics pipeline. The functionality in each of the blocks is introduced below and contains links to more information.

Graphics pipeline diagram

For more information about the architecture of the programmable sections of the Microsoft® Direct3D®, see Programmable Vertex Shader Architecture and Programmable Pixel Shader Architecture.

© 2002 Microsoft Corporation. All rights reserved.


Hardware Abstraction Layer

Microsoft® Direct3D® provides device independence through the hardware abstraction layer (HAL). The HAL is a device-specific interface, provided by the device manufacturer, that Direct3D uses to work directly with the display hardware. Applications never interact with the HAL. Rather, with the infrastructure that the HAL provides, Direct3D exposes a consistent set of interfaces and methods that an application uses to display graphics. The device manufacturer implements the HAL using 32-bit code with Microsoft Windows® XP, Microsoft Windows NT®, and Windows 2000. Windows 98 and Windows Millennium Edition (Windows Me) use a combination of 16-bit and 32-bit code. The HAL can be part of the display driver or a separate dynamic-link library (DLL) that communicates with the display driver through a private interface that the driver's creator defines.

The Direct3D HAL is implemented by the chip manufacturer, board producer, or OEM. The HAL implements only device-dependent code and performs no emulation. If a function is not performed by the hardware, the HAL does not report it as a hardware capability. Additionally, the HAL does not validate parameters; Direct3D does this before the HAL is invoked.

In Microsoft DirectX® 9.0, the HAL can have three different vertex processing modes: software vertex processing, hardware vertex processing, and mixed vertex processing on the same device. The pure device mode is a variant of the HAL device. The pure device type supports hardware vertex processing only, and allows only a small subset of the device state to be queried by the application. In addition, the pure device is available only on adapters that have a minimum level of capabilities.

© 2002 Microsoft Corporation. All rights reserved.


System Integration

The following diagram shows the relationships between Microsoft® Direct3D®, the Microsoft Windows® Graphics Device Interface (GDI), the hardware abstraction layer (HAL), and the hardware.

As the preceding diagram shows, Direct3D applications exist alongside GDI applications and both have access to the graphics hardware through the device driver for the graphics card. Unlike GDI, Direct3D can take advantage of hardware features when a HAL device is selected. HAL devices provide hardware acceleration based on the feature set supported by the graphics card. You are provided with a Direct3D method to determine at run time if a device is capable of the task.

For more information about devices supported by Direct3D, see Device Types.

© 2002 Microsoft Corporation. All rights reserved.


Programmable Vertex Shader Architecture

For information about vertex shader registers see Registers - vs_1_1.

For information about the vertex shader reference section, see the Vertex Shader 1_1.

© 2002 Microsoft Corporation. All rights reserved.


Programmable Pixel Shader Architecture

For information about pixel shader registers see Registers - ps_1_X.

For information about the pixel shader reference section, see the Pixel Shader 1_X.

© 2002 Microsoft Corporation. All rights reserved.


3-D Coordinate Systems and Geometry

Programming Microsoft® Direct3D® applications requires a working familiarity with 3-D geometric principles. This section introduces the most important geometric concepts for creating 3-D scenes. The following topics are covered.

  • 3-D Coordinate Systems
  • 3-D Primitives
  • Face and Vertex Normal Vectors
  • Triangle Rasterization Rules
  • Rectangles
  • Triangle Interpolants
  • Vectors, Vertices, and Quaternions

These topics provide high-level descriptions of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.

© 2002 Microsoft Corporation. All rights reserved.


3-D Coordinate Systems

Typically 3-D graphics applications use two types of Cartesian coordinate systems: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right, and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction that the positive z-axis points for that coordinate system. The following illustration shows these two coordinate systems.

Two coordinate systems

Microsoft® Direct3D® uses a left-handed coordinate system. If you are porting an application that is based on a right-handed coordinate system, you must make two changes to the data passed to Direct3D.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Use the view matrix to scale world space by -1 in the z-direction. To do this, flip the sign of the _31, _32, _33, and _34 member of the D3DMATRIX structure that you use for your view matrix.

To obtain what amounts to a right-handed world, use the D3DXMatrixPerspectiveRH and D3DXMatrixOrthoRH functions to define the projection transform. However, be careful to use the corresponding D3DXMatrixLookAtRH function, reverse the backface-culling order, and lay out the cube maps accordingly.

Although left-handed and right-handed coordinates are the most common systems, there is a variety of other coordinate systems used in 3-D software. For example, it is not unusual for 3-D modeling applications to use a coordinate system in which the y-axis points toward or away from the viewer, and the z-axis points up. In this case, right-handedness is defined as any positive axis (x, y, or z) pointing toward the viewer. Left-handedness is defined as any positive axis (x, y, or z) pointing away from the viewer. If you are porting a left-handed modeling application where the z-axis points up, you must do a rotation on all the vertex data in addition to the previous steps.

The essential operations performed on objects defined in a 3-D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see 3-D Transformations.

When you combine these operations, the results are not commutative - the order in which you multiply matrices is important.

© 2002 Microsoft Corporation. All rights reserved.


3-D Primitives

A 3-D primitive is a collection of vertices that form a single 3-D entity. The simplest primitive is a collection of points in a 3-D coordinate system, which is called a point list.

Often, 3-D primitives are polygons. A polygon is a closed 3-D figure delineated by at least three vertices. The simplest polygon is a triangle. Microsoft® Direct3D® uses triangles to compose most of its polygons because all three vertices in a triangle are guaranteed to be coplanar. Rendering nonplanar vertices is inefficient. You can combine triangles to form large, complex polygons and meshes.

The following illustration shows a cube. Two triangles form each face of the cube. The entire set of triangles forms one cubic primitive. You can apply textures and materials to the surfaces of primitives to make them appear to be a single solid form. For details, see Materials and Textures.

You can also use triangles to create primitives whose surfaces appear to be smooth curves. The following illustration shows how a sphere can be simulated with triangles. After a material is applied, the sphere looks curved when it is rendered. This is especially true if you use Gouraud shading. For details, see Gouraud Shading.

© 2002 Microsoft Corporation. All rights reserved.


Face and Vertex Normal Vectors

Each face in a mesh has a perpendicular normal vector. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Microsoft® Direct3D®, only the front of a face is visible. A front face is one in which vertices are defined in clockwise order.

Any face that is not a front face is a back face. Direct3D does not always render back faces; therefore, back faces are said to be culled. You can change the culling mode to render back faces if you want. See Culling State for more information.

Direct3D uses the vertex normals for Gouraud shading, lighting, and texturing effects.

When applying Gouraud shading to a polygon, Direct3D uses the vertex normals to calculate the angle between the light source and the surface. It calculates the color and intensity values for the vertices and interpolates them for every point across all the primitive's surfaces. Direct3D calculates the light intensity value by using the angle. The greater the angle, the less light is shining on the surface.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration. A flat surface composed of two triangles is defined.

It is more likely, however, that your object is made up of triangle strips and the triangles are not coplanar. One simple way to achieve smooth shading across all the triangles in the strip is to first calculate the surface normal vector for each polygonal face with which the vertex is associated. The vertex normal can be set to make an equal angle with each surface normal. However, this method might not be efficient enough for complex primitives.

This method is illustrated by the following figure, which shows two surfaces, S1 and S2 seen edge-on from above. The normal vectors for S1 and S2 are shown in blue. The vertex normal vector is shown in red. The angle that the vertex normal vector makes with the surface normal of S1 is the same as the angle between the vertex normal and the surface normal of S2. When these two surfaces are lit and shaded with Gouraud shading, the result is a smoothly shaded, smoothly rounded edge between them.

If the vertex normal leans toward one of the faces with which it is associated, it causes the light intensity to increase or decrease for points on that surface, depending on the angle it makes with the light source. An example is shown in the following figure. Again, these surfaces are seen edge-on. The vertex normal leans toward S1, causing it to have a smaller angle with the light source than if the vertex normal had equal angles with the surface normals.

You can use Gouraud shading to display some objects in a 3-D scene with sharp edges. To do so, duplicate the vertex normal vectors at any intersection of faces where a sharp edge is required, as shown in the following illustration.

If you use the DrawPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Because a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

Another alternative is to change to flat shading when rendering objects with sharp edges. This is computationally the most efficient method, but it may result in objects in the scene that are not rendered as realistically as the objects that are Gouraud-shaded.

© 2002 Microsoft Corporation. All rights reserved.


Rasterization Rules

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Microsoft® Direct3D® applies triangle rasterization rules to decide which pixels apply to a given triangle.

  • Triangle Rasterization Rules
  • Point and Line Rules
  • Point Sprite Rules

Triangle Rasterization Rules

Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in Microsoft Windows® Graphics Device Interface (GDI) and OpenGL. In Direct3D, the center of the pixel is the decisive point. If the center is inside a triangle, the pixel is part of the triangle. Pixel centers are at integer coordinates.

This description of triangle-rasterization rules used by Direct3D does not necessarily apply to all available hardware. Your testing may uncover minor variations in the implementation of these rules.

The following illustration shows a rectangle whose upper-left corner is at (0, 0) and whose lower-right corner is at (5, 5). This rectangle fills 25 pixels, just as you would expect. The width of the rectangle is defined as right minus left. The height is defined as bottom minus top.

Numbered square divided into six rows and columns

In the top-left filling convention, top refers to the vertical location of horizontal spans, and left refers to the horizontal location of pixels within a span. An edge cannot be a top edge unless it is horizontal. In general, most triangles have only left and right edges.

Numbered square containing two triangles

The top-left filling convention determines the action taken by Direct3D when a triangle passes through the center of a pixel. The following illustration shows two triangles, one at (0, 0), (5, 0), and (5, 5), and the other at (0, 5), (0, 0), and (5, 5). The first triangle in this case gets 15 pixels (shown in black), whereas the second gets only 10 pixels (shown in gray) because the shared edge is the left edge of the first triangle.

Numbered square containing diagonal line

If you define a rectangle with its upper-left corner at (0.5, 0.5) and its lower-right corner at (2.5, 4.5), the center point of this rectangle is at (1.5, 2.5). When the Direct3D rasterizer tessellates this rectangle, the center of each pixel is unambiguously inside each of the four triangles, and the top-left filling convention is not needed. The following illustration shows this. The pixels in the rectangle are labeled according to the triangle in which Direct3D includes them.

Numbered square containing rectangle divided into four triangles

If you move the rectangle in the previous example so that its upper-left corner is at (1.0, 1.0), its lower-right corner at (3.0, 5.0), and its center point at (2.0, 3.0), Direct3D applies the top-left filling convention. Most pixels in this rectangle straddle the border between two or more triangles, as the next illustration shows.

Numbered square containing rectangle divided into four triangles

For both rectangles, the same pixels are affected.

Numbered square containing rectangle divided into four triangles

Point and Line Rules

Points are rendered the same as point sprites, which are both rendered as screen-aligned quadrilaterals and thus adhere to the same rules as polygon rendering.

Non-antialiased line rendering rules are exactly the same as those for GDI.

For information about antialiased line rendering, see ID3DXLine.

Point Sprite Rules

Point sprites and patch primitives are rasterized as if the primitives were first tessellated into triangles and the resulting triangles rasterized. For more information, see Point Sprites.

© 2002 Microsoft Corporation. All rights reserved.


Rectangles

Throughout Microsoft® Direct3D® and Microsoft Windows® programming, objects on the screen are referred to in terms of bounding rectangles. The sides of a bounding rectangle are always parallel to the sides of the screen, so the rectangle can be described by two points, the upper-left corner and lower-right corner. Most applications use the RECT structure to carry information about a bounding rectangle to use when blitting to the screen or performing hit detection.

In C++, the RECT structure has the following definition.

typedef struct tagRECT {
    LONG    left;    // This is the upper-left corner x-coordinate.
    LONG    top;     // The upper-left corner y-coordinate.
    LONG    right;   // The lower-right corner x-coordinate.
    LONG    bottom;  // The lower-right corner y-coordinate.
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's upper-left corner. Similarly, the right and bottom members make up the coordinates of the lower-right corner. The following diagram illustrates how you can visualize these values.

In the interest of efficiency, consistency, and ease of use, all Direct3D presentation functions work with rectangles.

© 2002 Microsoft Corporation. All rights reserved.


Triangle Interpolants

During rendering, the pipeline interpolates vertex data across each triangle. Vertex data can be a broad variety of data and can include (but is not limited to): diffuse color, specular color, diffuse alpha (triangle opacity), specular alpha, and a fog factor (taken from specular alpha for fixed function vertex pipeline and from fog register for programmable vertex pipeline). The vertex data is defined by the Vertex Declaration.

For some vertex data, the interpolation is dependent on the current shading mode, as shown in the following table.

Shading mode | Description
Flat | Only the fog factor is interpolated in flat shade mode. For all other interpolants, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.

The diffuse color and specular color are treated differently, depending on the color model. In the RGB color model, the system uses the red, green, and blue color components in the interpolation.

The alpha component of a color is treated as a separate interpolant because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

Use the ShadeCaps member of the D3DCAPS9 structure to determine what forms of interpolation the current device driver supports.

© 2002 Microsoft Corporation. All rights reserved.


Vectors, Vertices, and Quaternions

Throughout Microsoft® Direct3D®, vertices describe position and orientation. Each vertex in a primitive is described by a vector that gives its position, color, texture coordinates, and a normal vector that gives its orientation.

Quaternions add a fourth element to the [ x, y, z] values that define a three-component-vector. Quaternions are an alternative to the matrix methods that are typically used for 3-D rotations. A quaternion represents an axis in 3-D space and a rotation around that axis. For example, a quaternion might represent a (1,1,2) axis and a rotation of 1 radian. Quaternions carry valuable information, but their true power comes from the two operations that you can perform on them: composition and interpolation.

Performing composition on quaternions is similar to combining them. The composition of two quaternions is notated as follows:

The composition of two quaternions applied to a geometry means "rotate the geometry around axis2 by rotation2, then rotate it around axis1 by rotation1." In this case, Q represents a rotation around a single axis that is the result of applying q2, then q1 to the geometry.

Using quaternion interpolation, an application can calculate a smooth and reasonable path from one axis and orientation to another. Therefore, interpolation between q1 and q2 provides a simple way to animate from one orientation to another.

When you use composition and interpolation together, they provide you with a simple way to manipulate a geometry in a manner that appears complex. For example, imagine that you have a geometry that you want to rotate to a given orientation. You know that you want to rotate it r2 degrees around axis2, then rotate it r1 degrees around axis1, but you don't know the final quaternion. By using composition, you could combine the two rotations on the geometry to get a single quaternion that is the result. Then, you could interpolate from the original to the composed quaternion to achieve a smooth transition from one to the other.

The Direct3D extensions (D3DX) utility library includes functions that help you work with quaternions. For example, the D3DXQuaternionRotationAxis function adds a rotation value to a vector that defines an axis of rotation, and returns the result in a quaternion defined by a D3DXQUATERNION structure. Additionally, the D3DXQuaternionMultiply function composes quaternions and the D3DXQuaternionSlerp performs spherical linear interpolation between two quaternions.

Direct3D applications can use the following functions to simplify the task of working with quaternions.

  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionToAxisAngle

Direct3D applications can use the following functions to simplify the task of working with three-component-vectors.

  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformCoord
  • D3DXVec3TransformNormal
  • D3DXVec3Unproject

Many additional functions that simplify tasks using two- and four-component-vectors are included among the Math Functions supplied by the D3DX utility library.

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Object

Microsoft® Direct3D® is implemented through Component Object Model (COM) objects and interfaces. Applications written in C++ access these interfaces and objects directly, whereas Microsoft Visual Basic® applications interact with a layer of code—visible as the Microsoft DirectX® for Visual Basic Classes—that marshals data from a Visual Basic application to the DirectX run time.

The Direct3D object is the first object that your application creates and the last object that your application releases. Functions for enumerating and retrieving capabilities of a Direct3D device are accessible through the Direct3D object. This enables applications to select devices without creating them.

When a Direct3D application written in C++ starts, it must obtain a pointer to an IDirect3D9 interface to access Direct3D functionality.

The following code example shows how to use the Direct3DCreate9 function to retrieve a pointer to the Direct3D interface.

LPDIRECT3D9 g_pD3D = NULL;

    if( NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
        return E_FAIL;

To navigate from the Direct3DDevice object to the Direct3D object that created the device, use the IDirect3DDevice9::GetDirect3D method.

© 2002 Microsoft Corporation. All rights reserved.


Devices

A Microsoft® Direct3D® device is the rendering component of Direct3D. It encapsulates and stores the rendering state. In addition, a Direct3D device performs transformations and lighting operations and rasterizes an image to a surface.

  • Device Types
  • Creating a Device
  • Selecting a Device
  • Lost Devices
  • Determining Hardware Support
  • Processing Vertex Data
  • Device-Supported Primitive Types

Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D device architecture

Direct3D currently supports two main types of Direct3D devices: a hardware abstraction layer (HAL) device with hardware-accelerated rasterization and shading with both hardware and software vertex processing; and a reference device.

You can think of these devices as two separate drivers. Software and reference devices are represented by software drivers, and the HAL device is represented by a hardware driver. The most common way to take advantage of these devices is to use the HAL device for shipping applications, and the reference device for feature testing. These are provided by third parties to emulate particular devices—for example, developmental hardware that has not yet been released.

The Direct3D device that an application creates must correspond to the capabilities of the hardware on which the application is running. Direct3D provides rendering capabilities, either by accessing 3-D hardware that is installed in the computer or by emulating the capabilities of 3-D hardware in software. Therefore, Direct3D provides devices for both hardware access and software emulation.

Hardware-accelerated devices give much better performance than software devices. The HAL device type is available on all Direct3D supported graphic adapters. In most cases, applications target computers that have hardware acceleration and rely on software emulation to accommodate lower-end computers.

With the exception of the reference device, software devices do not always support the same features as a hardware device. Applications should always query for device capabilities to determine which features are supported.

Because the behavior of the software and reference devices provided with Microsoft DirectX® 9.0 is identical to that of the HAL device, application code authored to work with the HAL device will work with the software or reference devices without modifications. Note that while the provided software or reference device behavior is identical to that of the HAL device, the device capabilities do vary, and a particular software device may implement a much smaller set of capabilities.

Behaviors

Direct3D enables you to specify the behavior of a device, as well the device's type. The IDirect3D9::CreateDevice method enables a combination of one or more of the behavior flags to control the global behaviors of the Direct3D device. These behaviors specify what is and is not maintained in the run-time portion of Direct3D, and the device types specify which driver to use. Although some combinations of device behaviors are not valid, it is possible to use all device behaviors with all device types. For example, it is valid to specify D3DDEVTYPE_SW on a device created with D3DCREATE_PUREDEVICE.

© 2002 Microsoft Corporation. All rights reserved.


Device Types

HAL Device

The primary device type is the HAL device, which supports hardware accelerated rasterization and both hardware and software vertex processing. If the computer on which your application is running is equipped with a display adapter that supports Microsoft® Direct3D®, your application should use it for 3-D operations. Direct3D HAL devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access 3-D cards directly. They call Direct3D functions and methods. Direct3D accesses the hardware through the HAL. If the computer that your application is running on supports the HAL, it will gain the best performance by using a HAL device.

To create a HAL device from C++, call the IDirect3D9::CreateDevice method, and pass the D3DDEVTYPE_HAL constant as the device type.

Note Hardware devices cannot render to 8-bit render-target surfaces.

Reference Device

Direct3D supports an additional device type called a reference device or reference rasterizer. Unlike a software device, the reference rasterizer supports every Direct3D feature. Because these features are implemented for accuracy, rather than speed, and are implemented in software, the results are not very fast. The reference rasterizer does make use of special CPU instructions whenever it can, but it is not intended for retail applications. Use the reference rasterizer only for feature testing or demonstration purposes.

To create a reference device from C++, call the IDirect3D9::CreateDevice method, and pass the D3DDEVTYPE_REF constant as the device type.

© 2002 Microsoft Corporation. All rights reserved.


Creating a Device

Note All rendering devices created by a given Microsoft® Direct3D® object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D object, because they share the same hardware, extreme performance penalties will be incurred.

To create a Direct3D device in a C++ application, your application must first create a Direct3D object, as explained in Direct3D Object.

First, initialize values for the D3DPRESENT_PARAMETERS structure that is used to create the Direct3D device. The following code example specifies a windowed application where the back buffer is flipped to the front buffer on VSYNC only.

LPDIRECT3DDEVICE9 pDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

Next, create the Direct3D device. The following IDirect3D9::CreateDevice call specifies the default adapter, a hardware abstraction layer (HAL) device, and software vertex processing.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &d3dDevice ) ) )
    return E_FAIL;

Note that a call to create, release, or reset the device should happen only on the same thread as the window procedure of the focus window.

After creating the device, set its state.

© 2002 Microsoft Corporation. All rights reserved.


Selecting a Device

Applications can query hardware to detect the supported Microsoft® Direct3D® device types. This section contains information about the primary tasks involved in enumerating display adapters and selecting Direct3D devices.

An application must perform a series of tasks to select an appropriate Direct3D device. Note that the following steps are intended for a full-screen application. In most cases, a windowed application can skip most of these steps.

  1. Initially, the application must enumerate the display adapters on the system. An adapter is a physical piece of hardware. Note that the graphics card might contain more than a single adapter, as is the case with a dual-head display. Applications that are not concerned with multimonitor support can disregard this step, and pass D3DADAPTER_DEFAULT to the IDirect3D9::EnumAdapterModes method in step 2.
  2. For each adapter, the application enumerates the supported display modes by calling IDirect3D9::EnumAdapterModes.
  3. If required, the application checks for the presence of hardware acceleration in each enumerated display mode by calling IDirect3D9::CheckDeviceType, as shown in the following code example. Note that this is only one of the possible uses for IDirect3D9::CheckDeviceType; for details, see Determining Hardware Support.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

Params.BackBufferFormat = D3DFMT_X1R5G5B5;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter,
                                  Device.m_DevType,
                                  Params.BackBufferFormat, Params.BackBufferFormat,
                                  FALSE)))
        return E_FAIL;
  4. The application checks for the desired level of functionality for the device on this adapter by calling the IDirect3D9::GetDeviceCaps method. This method filters out those devices that do not support the required functionality. The device capability returned by IDirect3D9::GetDeviceCaps is guaranteed to be constant for a device across all display modes verified by IDirect3D9::CheckDeviceType.
  5. Devices can always render to surfaces of the format of an enumerated display mode that is supported by the device. If the application is required to render to a surface of a different format, it can call IDirect3D9::CheckDeviceFormat. If the device can render to the format, then it is guaranteed that all capabilities returned by IDirect3D9::GetDeviceCaps are applicable.
  6. Lastly, the application can determine if multisampling techniques, such as full-scene antialiasing, are supported for a render format by using the IDirect3D9::CheckDeviceMultiSampleType method.

After completing the above steps, the application should have a list of display modes in which it can operate. The final step is to verify that enough device-accessible memory is available to accommodate the required number of buffers and antialiasing. This test is necessary because the memory consumption for the mode and multisample combination is impossible to predict without verifying it. Moreover, some display adapter architectures might not have a constant amount of device-accessible memory. This means that an application should be able to report out-of-video-memory failures when going into full-screen mode. Typically, an application should remove full-screen mode from the list of modes it offers to a user, or it should attempt to consume less memory by reducing the number of back buffers or using a less complex multisampling technique.

A windowed application performs a similar set of tasks.

  1. It determines the desktop rectangle covered by the client area of the window.
  2. It enumerates adapters, looking for the adapter whose monitor covers the client area. If the client area is owned by more than one adapter, then the application can choose to drive each adapter independently, or to drive a single adapter and have Direct3D transfer pixels from one device to another at presentation. The application can also disregard the above two steps and use the D3DADAPTER_DEFAULT adapter. Note that this might result in slower operation when the window is placed on a secondary monitor.
  3. The application should call IDirect3D9::CheckDeviceType to determine if the device can support rendering to a back buffer of the specified format while in desktop mode. IDirect3D9::GetAdapterDisplayMode can be used to determine the desktop display format, as shown in the following code example.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

// Use the current display mode.
D3DDISPLAYMODE mode;

if(FAILED(m_pD3D->GetAdapterDisplayMode(Device.m_uAdapter , &mode)))
        return E_FAIL;

Params.BackBufferFormat = mode.Format;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter, Device.m_DevType,
Params.BackBufferFormat, Params.BackBufferFormat, FALSE)))
       return E_FAIL;

© 2002 Microsoft Corporation. All rights reserved.


Lost Devices

A Microsoft® Direct3D® device can be in either an operational state or a lost state. The operational state is the normal state of the device, the device runs and presents all rendering as expected. The device makes a transition to the lost state when an event, such as the loss of keyboard focus in a full-screen application, causes rendering to become impossible. The lost state is characterized by the silent failure of all rendering operations, which means that the rendering methods can return success codes even though the rendering operations fail. In this situation, the error code D3DERR_DEVICELOST is returned by IDirect3DDevice9::Present.

By design, the full set of scenarios that can cause a device to become lost is not specified. Some typical examples include loss of focus, such as when the user presses ALT+TAB or when a system dialog is initialized. Devices can also be lost due to a power management event, or when another application assumes full-screen operation. In addition, any failure from IDirect3DDevice9::Reset puts the device into a lost state.

All methods that derive from IUnknown are guaranteed to work after a device is lost. After device loss, each function generally has three options.

  • Fail with D3DERR_DEVICELOST - This means that the application needs to recognize that the device was lost, so that the application identifies that something isn't happening as expected.
  • Silently fail, returning S_OK or any other return codes - If a function silently fails, the application generally can't distinguish between the result of "success" and a "silent failure."
  • The function returns a return code.

Responding to a Lost Device

A lost device must re-create resources (including video memory resources) after it has been reset. If a device is lost, the application queries the device to see if it can be restored to the operational state. If not, the application waits until the device can be restored.

If the device can be restored, the application prepares the device by destroying all video-memory resources and any swap chains. Then, the application calls the IDirect3DDevice9::Reset method. Reset is the only method that has an effect when a device is lost, and is the only method by which an application can change the device from a lost to an operational state. IDirect3DDevice9::Reset will fail unless the application releases all resources that are allocated in D3DPOOL_DEFAULT, including those created by the IDirect3DDevice9::CreateRenderTarget and IDirect3DDevice9::CreateDepthStencilSurface methods.

For the most part, the high-frequency calls of Direct3D do not return any information about whether the device has been lost. The application can continue to call rendering methods, such as IDirect3DDevice9::DrawPrimitive, without receiving notification of a lost device. Internally, these operations are discarded until the device is reset to the operational state.

The application can determine what to do on encountering a lost device by querying the return value of the IDirect3DDevice9::TestCooperativeLevel method.

Locking Operations

Internally, Direct3D does enough work to ensure that a lock operation will succeed after a device is lost. However, it is not guaranteed that the video-memory resource's data will be accurate during the lock operation. It is guaranteed that no error code will be returned. This allows applications to be written without concern for device loss during a lock operation.

Resources

Resources can consume video memory. Because a lost device is disconnected from the video memory owned by the adapter, it is not possible to guarantee allocation of video memory when the device is lost. As a result, all resource creation methods are implemented to succeed by returning D3D_OK, but do in fact allocate only dummy system memory. Because any video-memory resource must be destroyed before the device is resized, there is no issue of over-allocating video memory. These dummy surfaces allow lock and copy operations to appear to function normally until the application calls IDirect3DDevice9::Present and discovers that the device has been lost.

All video memory must be released before a device can be reset from a lost state to an operational state. This means that the application should release any swap chains created with IDirect3DDevice9::CreateAdditionalSwapChain and any resources placed in the D3DPOOL_DEFAULT memory class. The application need not release resources in the D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory classes. Other state data is automatically destroyed by the transition to an operational state.

You are encouraged to develop applications with a single code path to respond to device loss. This code path is likely to be similar, if not identical, to the code path taken to initialize the device at startup.

Retrieved Data

Direct3D allows applications to validate texture and render states against single pass rendering by the hardware using IDirect3DDevice9::ValidateDevice. This method, which is typically invoked during initialization of the application, will return D3DERR_DEVICELOST if the device has been lost.

Direct3D also allows applications to copy generated or previously written images from video-memory resources to nonvolatile system-memory resources. Because the source images of such transfers might be lost at any time, Direct3D allows such copy operations to fail when the device is lost.

Regarding asynchronous queries, IDirect3DQuery9::GetData returns D3DERR_DEVICELOST if the FLUSH flag is specified, in order to indicate to the application that IDirect3DQuery9::GetData will never return S_OK.

The copy operation, IDirect3DDevice9::GetFrontBufferData, can fail with D3DERR_DEVICELOST since there is no primary surface when the device is lost. IDirect3DDevice9::CreateAdditionalSwapChain can also fail with D3DERR_DEVICELOST because a back buffer can't be created when the device is lost.Note that these cases are the only instance of D3DERR_DEVICELOST outside of the IDirect3DDevice9::Present, IDirect3DDevice9::TestCooperativeLevel, and IDirect3DDevice9::Reset methods.

Programmable Shaders

In Microsoft DirectX® 9.0, Vertex Shader 1_1 and Pixel Shader 1_X don't need to be re-created after Reset. They will be remembered. In previous versions of DirectX, a lost device required shaders to be re-created.

© 2002 Microsoft Corporation. All rights reserved.


Determining Hardware Support

Microsoft® Direct3D® provides the following functions to determine hardware support.

  • IDirect3D9::CheckDeviceFormat

    Used to verify whether a surface format can be used as a texture, whether a surface format can be used as a texture and a render target, or whether a surface format can be used as a depth-stencil buffer. In addition, this method is used to verify depth buffer format support and depth-stencil buffer format support.

  • IDirect3D9::CheckDeviceType

    Used to verify a device's ability to perform hardware acceleration, a device's ability to build a swap chain for presentation, or a device's ability to render to the current display format.

  • IDirect3D9::CheckDepthStencilMatch

    Used to verify whether a depth-stencil buffer format is compatible with a render-target format. Note that before calling this method, the application should call IDirect3D9::CheckDeviceFormat on both the depth-stencil and render target formats.

© 2002 Microsoft Corporation. All rights reserved.


Processing Vertex Data

The IDirect3DDevice9 interface supports vertex processing in both software and hardware. In general, the device capabilities for software and hardware vertex processing are not identical. Hardware capabilities are variable, depending on the display adapter and driver, while software capabilities are fixed.

The following flags control vertex processing behavior for the hardware abstraction layer (HAL) and reference devices.

  • D3DCREATE_SOFTWARE_VERTEXPROCESSING
  • D3DCREATE_HARDWARE_VERTEXPROCESSING
  • D3DCREATE_MIXED_VERTEXPROCESSING

Specify one of the vertex processing behavior flags when calling IDirect3D9::CreateDevice. The mixed-mode flag enables the device to perform both software and hardware vertex processing. Only one vertex processing flag may be set for a device at any one time. Note that the D3DCREATE_HARDWARE_VERTEXPROCESSING flag is required to be set when creating a pure device (D3DCREATE_PUREDEVICE).

To avoid dual vertex processing capabilities on a single device, only the hardware vertex processing capabilities can be queried at run time. Software vertex processing capabilities are fixed and cannot be queried at run time.

You can consult the VertexProcessingCaps member of the D3DCAPS9 structure to determine the hardware vertex processing capabilities of the device. For software vertex processing the following capabilities are supported.

  • the D3DVTXPCAPS_DIRECTIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_LOCALVIEWER member of D3DVTXPCAPS
  • the D3DVTXPCAPS_MATERIALSOURCE7 member of D3DVTXPCAPS
  • the D3DVTXPCAPS_POSITIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TEXGEN member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TWEENING member of D3DVTXPCAPS

In addition, the following table lists the values that are set for members of the D3DCAPS9 structure for a device in software vertex processing mode.

Member | Software vertex processing capabilities
MaxActiveLights | Unlimited
MaxUserClipPlanes | 6
MaxVertexBlendMatrices | 4
MaxStreams | 16
MaxVertexIndex | 0xFFFFFFFF

Software vertex processing provides a guaranteed set of vertex processing capabilities, including an unbounded number of lights and full support for programmable vertex shaders. You can toggle between software and hardware vertex processing at any time when using the HAL Device, the only device type that supports both hardware and software vertex processing. The only requirement is that vertex buffers used for software vertex processing must be allocated in system memory.

Note The performance of hardware vertex processing is comparable to that of software vertex processing. For this reason, it's a good idea to provide, within a single device type, both hardware- and software-emulation functionality for vertex processing. This is not the case for rasterization, for which host processors are much slower than specialized graphics hardware. Thus both hardware- and software-emulated rasterization is not provided within a single device type. Software vertex processing is the only instance of functionality duplicated between the run time and the hardware (driver) within a single device. Thus all other device capabilities represent potentially variable functionality provided by the driver.

© 2002 Microsoft Corporation. All rights reserved.


Device-Supported Primitive Types

Microsoft® Direct3D®devices can create and manipulate the following types of primitives.

  • Point Lists
  • Line Lists
  • Line Strips
  • Triangle Lists
  • Triangle Strips
  • Triangle Fans

You can render primitive types from a C++ application with any of the rendering methods of the IDirect3DDevice9 interface.

© 2002 Microsoft Corporation. All rights reserved.


Point Lists

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3-D scenes for star fields, or dotted lines on the surface of a polygon.

The following illustration depicts a rendered point list.

Your application can apply materials and textures to a point list. The colors in the material or texture appear only at the points drawn, and not anywhere between the points.

The following code shows how to create vertices for this point list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this point list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_POINTLIST, 0, 6 );

© 2002 Microsoft Corporation. All rights reserved.


Line Lists

A line list is a list of isolated, straight line segments. Line lists are useful for such tasks as adding sleet or heavy rain to a 3-D scene. Applications create a line list by filling an array of vertices, and the number of vertices in a line list must be an even number greater than or equal to two.

The following illustration shows a rendered line list.

You can apply materials and textures to a line list. The colors in the material or texture appear only along the lines drawn, not at any point in between the lines.

The following code shows how to create vertices for this line list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 3 );

© 2002 Microsoft Corporation. All rights reserved.


Line Strips

A line strip is a primitive that is composed of connected line segments. Your application can use line strips for creating polygons that are not closed. A closed polygon is a polygon whose last vertex is connected to its first vertex by a line segment. If your application makes polygons based on line strips, the vertices are not guaranteed to be coplanar.

The following illustration depicts a rendered line strip.

The following code shows how to create vertices for this line strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINESTRIP, 0, 5 );

© 2002 Microsoft Corporation. All rights reserved.


Triangle Lists

A triangle list is a list of isolated triangles. They might or might not be near each other. A triangle list must have at least three vertices. The total number of vertices must be divisible by three.

Use triangle lists to create an object that is composed of disjoint pieces. For instance, one way to create a force-field wall in a 3-D game is to specify a large list of small, unconnected triangles. Then apply a material and texture that appears to emit light to the triangle list. Each triangle in the wall appears to glow. The scene behind the wall becomes partially visible through the gaps between the triangles, as a player might expect when looking at a force field.

Triangle lists are also useful for creating primitives that have sharp edges and are shaded with Gouraud shading. See Face and Vertex Normal Vectors.

The following illustration depicts a rendered triangle list.

Rendered triangle list

The following code shows how to create vertices for this triangle list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}

};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 2 );

© 2002 Microsoft Corporation. All rights reserved.


Triangle Strips

A triangle strip is a series of connected triangles. Because the triangles are connected, the application does not need to repeatedly specify all three vertices for each triangle. For example, you need only seven vertices to define the following triangle strip.

The system uses vertices v1, v2, and v3 to draw the first triangle, v2, v4, and v3 to draw the second triangle, v3, v4, and v5 to draw the third, v4, v6, and v5 to draw the fourth, and so on. Notice that the vertices of the second and fourth triangles are out of order; this is required to make sure that all the triangles are drawn in a clockwise orientation.

Most objects in 3-D scenes are composed of triangle strips. This is because triangle strips can be used to specify complex objects in a way that makes efficient use of memory and processing time.

The following illustration depicts a rendered triangle strip.

Rendered triangle strip

The following code shows how to create vertices for this triangle strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 4);

© 2002 Microsoft Corporation. All rights reserved.


Triangle Fans

A triangle fan is similar to a triangle strip, except that all the triangles share one vertex. This is shown in the following illustration.

The system uses vertices v2, v3, and v1 to draw the first triangle, v3, v4, and v1 to draw the second triangle, v4, v5, and v1 to draw the third triangle, and so on. When flat shading is enabled, the system shades the triangle with the color from its first vertex.

This illustration depicts a rendered triangle fan.

Rendered triangle fan

The following code shows how to create vertices for this triangle fan.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    { 0.0, 0.0, 0.0},
    {-5.0, 5.0, 0.0},
    {-3.0,  7.0, 0.0},
    { 0.0, 10.0, 0.0},
    { 3.0,  7.0, 0.0},
    { 5.0,  5.0, 0.0},
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle fan.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 4 );

© 2002 Microsoft Corporation. All rights reserved.


Resources

Resources are the textures and buffers that are used to render a scene. Applications need to create, load, copy, and use resources. This section gives a brief introduction to resources and the steps and methods used by applications when working with resources. For more information about specific resource types, see Textures, Vertex Buffers, and Index Buffers.

All resources, including the geometry resources IDirect3DIndexBuffer9 and IDirect3DVertexBuffer9, inherit from the IDirect3DResource9 interface. The texture resources, IDirect3DCubeTexture9, IDirect3DTexture9, and IDirect3DVolumeTexture9, also inherit from the IDirect3DBaseTexture9 interface.

Additional information is divided into the following topics.

  • Resource Properties
  • Manipulating Resources
  • Locking Resources
  • Resource Relationships
  • Managing Resources
  • Application-Managed Resources and Allocation Strategies

© 2002 Microsoft Corporation. All rights reserved.


Resource Properties

All resources share the following properties.

  • Usage. The way a resource is used, for example, as a texture or a render target.
  • Format. The format of the data, for example, the pixel format of a 2-D surface.
  • Pool. The type of memory where the resource is allocated.
  • Type. The type of resource, for example, a vertex buffer or render target.

Resource uses are enforced. An application that will use a resource in a certain operation must specify that operation at resource-creation time. For a list of the usage constants defined for resources, see D3DUSAGE.

The D3DUSAGE_RTPATCHES, D3DUSAGE_NPATCHES, and D3DUSAGE_POINTS constants indicate to the driver that the data in these buffers is likely to be used for triangular or grid patches, N-patches, or point sprites, respectively. These flags are provided in case the hardware cannot perform these operations without host processing. Therefore, the driver will want to allocate these surfaces in system memory so that the CPU can access them. If the driver can perform these operations entirely in hardware, it can allocate these surfaces in video or accelerated graphics port (AGP) memory to avoid a host copy and improve performance at least twofold. Note that the information provided by these flags is not absolutely required. A driver can detect that such operations are being performed on the data, and it will move the buffer back to system memory for subsequent frames.

For details about the usage flags and how they relate to specific resources, see the reference pages on the individual resource creation methods.

For information about the surface format of resources, see the D3DFORMAT enumerated type.

The class of memory that holds a resource's buffers is called a pool. Pool values are defined by the D3DPOOL enumerated type. A pool cannot be mixed for different objects contained in a single resource—that is, mip levels in a mipmap—and, when a pool is chosen for a resource, the pool cannot be changed.

The resources types are set implicitly at run time when the application calls a resource creation method such as IDirect3DDevice9::CreateCubeTexture. Resource types are defined by the D3DRESOURCETYPE enumerated type. Applications can query these types at run time; however, it is expected that most scenarios will not require run-time type checking.

© 2002 Microsoft Corporation. All rights reserved.


Manipulating Resources

Your application manipulates resources in order to render a scene. First, the application creates texture resources by using the following methods.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

The texture objects returned by the texture creation methods are containers for surfaces or volumes; these containers are generically known as buffers. The buffers owned by the resource inherit the usages, format, and pool of the resource but have their own type. For more information, see Resource Properties.

The application gains access to the contained surfaces, for the purpose of loading artwork, by calling the following methods. For details, see Locking Resources.

  • IDirect3DCubeTexture9::LockRect
  • IDirect3DTexture9::LockRect
  • IDirect3DVolumeTexture9::LockBox

The lock methods take arguments denoting the contained surface—for example, the mipmap sub-level or cube face of the texture—and return pointers to the pixels. The typical application never uses a surface object directly.

In addition, the application creates geometry-oriented resources by using the following methods.

  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateVertexBuffer

Your application locks and fills the buffer resources by calling the following methods.

  • IDirect3DIndexBuffer9::Lock
  • IDirect3DVertexBuffer9::Lock

If your application is allowing the Microsoft® Direct3D® run time to manage these resources, then the resource creation process ends here. Otherwise, the application manages the promotion of system memory resources to device-accessible resources, where the hardware accelerator can use them, by calling the IDirect3DDevice9::UpdateTexture method.

To present images rendered from resources, the application also needs color and depth-stencil buffers. For typical applications, the color buffer is owned by the device's swap chain, which is a collection of back buffer surfaces, and is implicitly created with the device. Depth-stencil surfaces can be implicitly created, or explicitly created by using the IDirect3DDevice9::CreateDepthStencilSurface method. The application associates a device and its depth and color buffer with a call to IDirect3DDevice9::SetRenderTarget.

For details on presenting the final image, see Presenting a Scene.

© 2002 Microsoft Corporation. All rights reserved.


Locking Resources

Locking a resource means granting CPU access to its storage. The following locking methods are defined for resources.

  • D3DLOCK_DISCARD
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_NO_DIRTY_UPDATE

For details on locking flags and how they relate to specific resources, see the reference pages on the individual resource locking methods. Application developers should note that the D3DLOCK_DISCARD, D3DLOCK_READONLY, and D3DLOCK_NOOVERWRITE flags are only hints. The run time does not check that applications are following the functionality specified by these flags. An application that specifies D3DLOCK_READONLY but then writes to the resource should expect undefined results. In general, working against locking flags, including the locking usage flags, is not guaranteed to work in later releases and may incur a significant performance penalty.

A lock operation is followed by an unlock operation. For example, after locking a texture, the application subsequently relinquishes direct access to locked textures by unlocking them. In addition to granting processor access, any other operations involving that resource are serialized for the duration of a lock. Only a single lock for a resource is allowed, even for non-overlapping regions, and no accelerator operations on a surface can be ongoing while a lock operation is outstanding on that surface.

Each resource interface has methods for locking the contained buffers. Each texture resource can also lock a sub-portion of that resource. Two-dimensional resources (surfaces) allow the locking of sub-rectangles, and volume resources allow the locking of sub-volumes or boxes. Each lock method returns a structure that contains a pointer to the storage backing the resource and values representing the distances between rows or planes of data, depending on the resource type. For details, see the method lists for the resource interfaces. The returned pointer always points to the top-left byte in the locked sub-regions.

When working with index and vertex buffers, you can make multiple lock calls; however, you must ensure that the number of lock calls matches the number of unlock calls.

The Microsoft® DirectX® Transform set of compressed texture formats, which store pixels in encoded 4x4 blocks, can only be locked on 4x4 boundaries.

© 2002 Microsoft Corporation. All rights reserved.


Resource Relationships

The following diagram illustrates the operations that are syntactically possible on specific resources and their contents. For more information about how to use resources, see Manipulating Resources.

Arrows running from left to right indicate that the target types are created by the given methods, while arrows running from right to left indicate that those resource types can be passed as arguments to the given methods.

© 2002 Microsoft Corporation. All rights reserved.


Managing Resources

Resource management is the process where resources are promoted from system-memory storage to device-accessible storage and discarded from device-accessible storage. The Microsoft® Direct3D® run time has its own management algorithm based on a least-recently-used priority technique. Direct3D switches to a most-recently-used priority technique when it detects that more resources than can coexist in device-accessible memory are used in a single frame—between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls.

Use the D3DPOOL_MANAGED flag at creation time to specify a managed resource. Managed resources persist through transitions between the lost and operational states of the device. The device can be restored with a call to IDirect3DDevice9::Reset, and such resources continue to function normally without being reloaded with artwork. However, if the device must be destroyed and re-created, all resources created using D3DPOOL_MANAGED must be re-created.

Use the D3DPOOL_DEFAULT flag at creation time to specify that a resource be placed in the default pool. Resources in the default pool do not persist through transitions between the lost and operational states of the device. These resources must be released before calling Reset and must then be re-created.

For more information about the lost state of a device, see Lost Devices.

Note that resource management is not supported for all types and usages. For example, objects created with the D3DUSAGE_RENDERTARGET flag are not supported. In addition, resource management is not recommended for objects whose contents are changing with high frequency. For example, a managed vertex buffer that changes every frame can significantly degrade performance for some hardware. However, this is not a problem for texture resources.

© 2002 Microsoft Corporation. All rights reserved.


Application-Managed Resources and Allocation Strategies

Managed vertex-buffer or index-buffer resources cannot be declared dynamic by specifying D3DUSAGE_DYNAMIC at creation time. This would require an additional copy for every modification to the vertex buffer contents. Dynamic vertex buffers are intended for rendering dynamic geometry and data pulled in from binary space partitioned trees or other visibility data structures. This can be accomplished by pre-allocating buffers of the desired format. These resources are then parceled out to support application needs by a resource manager within the application. The total number of dynamic vertex buffers is small because an application will use simultaneously only a few different vertex strides and because a different vertex buffer is required only for unique strides. When managing dynamic resources in this way, ensure that high-frequency demands on the resources do not significantly decrease the application's performance.

When using resources managed by both Microsoft® Direct3D® and applications, allocate application-managed resources in D3DPOOL_DEFAULT memory prior to creating Direct3D-managed resources. This enables the memory manager to maintain an accurate count of available memory.

© 2002 Microsoft Corporation. All rights reserved.


States

A Microsoft® Direct3D® device is a state computer. Applications set up the state of the lighting, rendering, and transformation modules and then pass data through them during rendering.

This section describes all the different kinds of states used by the graphics pipeline.

  • Render States
  • Sampler States
  • Texture Stage States
  • State Blocks

© 2002 Microsoft Corporation. All rights reserved.


Render States

Device render states control the behavior of the Microsoft® Direct3D® device's rasterization module. They do this by altering the attributes of the rendering state, what type of shading is used, fog attributes, and other rasterizer operations.

Applications written in C++ control the characteristics of the rendering state by invoking the IDirect3DDevice9::SetRenderState method. The D3DRENDERSTATETYPE enumerated type specifies all possible rendering states. Your application passes a value from the D3DRENDERSTATETYPE enumeration as the first parameter to the IDirect3DDevice9::SetRenderState method.

Fixed function vertex processing is controlled by the IDirect3DDevice9::SetRenderState method and the following device render states. Most of these controls do not have any effect when using programmed vertex shaders.

  • D3DRS_SPECULARENABLE
  • D3DRS_FOGSTART
  • D3DRS_FOGEND
  • D3DRS_FOGDENSITY
  • D3DRS_RANGEFOGENABLE
  • D3DRS_LIGHTING
  • D3DRS_AMBIENT
  • D3DRS_FOGVERTEXMODE
  • D3DRS_COLORVERTEX
  • D3DRS_LOCALVIEWER
  • D3DRS_NORMALIZENORMALS
  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
  • D3DRS_VERTEXBLEND

In addition, the fixed-function vertex processing pipeline uses the following methods to set transforms, materials, and lights.

  • IDirect3DDevice9::SetTransform
  • IDirect3DDevice9::SetMaterial
  • IDirect3DDevice9::SetLight
  • IDirect3DDevice9::LightEnable
Note D3DRS_SPECULARENABLE controls the addition of specular color in the pixel pipeline. D3DRS_FOGSTART, D3DRS_FOGEND, and D3DRS_FOGDENSITY control the start, end, and density of pixel fog density computation.

Additional information is contained in the following topics.

Overviews

  • Alpha Blending State
  • Alpha Testing State
  • Ambient Lighting State
  • Antialiasing State
  • Culling State
  • Depth Buffering State
  • Fog State
  • Lighting State
  • Outline and Fill State
  • Per-Vertex Color State
  • Primitive Clipping State
  • Shading State
  • Stencil Buffer State
  • Texture Wrapping State

© 2002 Microsoft Corporation. All rights reserved.


Sampler States

Sampler states control sampling related topics such as filtering, tiling, and addressing.

Sampling States

SetSamplerState sets the sampler state (including the one used in the tessellator unit to sample displacement maps). These have been renamed with a D3DSAMP_ prefix to enable compile time error detection when porting from Microsoft® DirectX® 8.x. The states include:

  • D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, D3DSAMP_ADDRESSW
  • D3DSAMP_BORDERCOLOR
  • D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, D3DSAMP_MIPFILTER
  • D3DSAMP_MIPMAPLODBIAS
  • D3DSAMP_MAXMIPLEVEL
  • D3DSAMP_MAXANISOTROPY

In DirectX 9.0, there is support for up to 16 texture surfaces in one pass, using the pixel shader 2.0 model, yet the number of texture coordinates remains limited to 8. Some texture stage state is associated with surfaces, some with coordinate sets, some with vertex processing, and some with pixel processing. IDirect3DDevice9::SetSamplerState specifies texture filtering, tiling, clamping, MIPLOD, etc. This will work for up to 16 samplers.

Applications written in C++ control the characteristics of the texture-related sampling states by invoking the IDirect3DDevice9::SetSamplerState method. The D3DSAMPLERSTATETYPE enumerated type specifies the sampling states.

Related Topics

  • Texture Stage States

© 2002 Microsoft Corporation. All rights reserved.


Texture Stage States

Texture stage states control texture coordinate generation and texture coordinate state such as wrapping modes.

Applications written in C++ control the characteristics of the texture-related render states by invoking the IDirect3DDevice9::SetTextureStageState method. The D3DTEXTURESTAGESTATETYPE enumerated type specifies all the possible texture-related rendering states. Your application passes a value from the D3DTEXTURESTAGESTATETYPE enumeration as the first parameter to the IDirect3DDevice9::SetTextureStageState method.

Applications set the texture for a stage by calling the IDirect3DDevice9::SetTexture method.

SetTextureStageState

SetTextureStageState now sets the following states.

  • Fixed function vertex processing state. These states control the manipulation of texture coordinates: D3DTSS_TEXTURETRANSFORMFLAGS and D3DTSS_TEXCOORDINDEX. Up to eight of each can be set (because eight texture coordinates are always supported).
  • Fixed function pixel shader state (the legacy TextureStageState). D3DTSS_COLOROP, D3DTSS_ALPHAOP, D3DTSS_COLORARG0, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG0, D3DTSS_ALPHAARG1, D3DTSS_ALPHAARG2, D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT11, D3DTSS_BUMPENVLSCALE, D3DTSS_BUMPENVLOFFSET, and D3DTSS_RESULTARG. Up to MaxTextureBlendStages of these can be set.

D3DTSS_TEXCOORDINDEX is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.

The number of texture samplers available to the application is determined by the pixel shader version.

  • Fixed function pixel shader: MaxTextureBlendStages/MaxSimultaneousTextures texture samplers.
  • ps_1_1 to ps_1_3: 4 texture samplers.
  • ps_1_4: 6 texture samplers.
  • ps_2_0: 16 texture samplers.
  • Devices that support displacement mapping in Microsoft® DirectX® 9.0 will support an additional sampler (D3DDMAPSAMPLER), which samples the displacement maps in the tessellator unit.

For more information about texture blending, see Texture Blending.

© 2002 Microsoft Corporation. All rights reserved.


State Blocks

A state block is a group of device states, render states, lighting and material parameters, transformation states, texture stage states, and current texture information. The state block is a snapshot of the device's current state, or it is explicitly recorded. The snapshot can be applied to a device in a single call. Device-state blocks can be optimized by the rendering device to accelerate the common sequences of state changes that your application requires, or they can just make applying device states easier.

In C++, you receive a state-block handle when you finish recording a state block by calling the IDirect3DDevice9::EndStateBlock method, and when you capture a predefined set of device state data by calling the IDirect3DDevice9::CreateStateBlock method.

Additional information is contained in the following topics.

Overviews

  • Creating Predefined State Blocks
  • Recording State Blocks

© 2002 Microsoft Corporation. All rights reserved.


Creating Predefined State Blocks

The IDirect3DDevice9::CreateStateBlock method creates a new state block that contains the entire set of device states or only those device states related to vertex or pixel processing. The method takes two parameters. The first parameter identifies the type of state information to capture in the new state block, and the second parameter is the address of a variable that will receive a valid state-block handle if the call succeeds.

The first parameter is a D3DSTATEBLOCKTYPE, which includes allows you to choose between:

  • Save all pixel and vertex state.
  • Save only pixel state.
  • Save only vertex state.

For a complete listing of the states saved, see D3DSTATEBLOCKTYPE.

Be sure to check the error code from the IDirect3DDevice9::CreateStateBlock method. If the method fails, it is likely the display mode has changed. Your application should recover from this type of failure by recreating its surfaces, and then recreating the state block.

© 2002 Microsoft Corporation. All rights reserved.


Recording State Blocks

The IDirect3DDevice9 interface provides IDirect3DDevice9::BeginStateBlock to record device states in a state block as your application calls for them. This method causes the system to start recording device state changes in a state block, rather than applying them to the device. A list of the states that can be recorded is in IDirect3DDevice9::BeginStateBlock.

When you're done recording the state block, notify the system to stop recording by calling the IDirect3DDevice9::EndStateBlock method. This method places the handle of the state block in the variable whose address you pass in the pToken parameter. Your application uses this handle to apply the state block to the device as needed, to capture new state data into the block, and to delete the state block when it is no longer required.

It is important to check the error code from the IDirect3DDevice9::EndStateBlock method. If the method fails, it is likely because the display mode has changed. Design your application to recover from this type of failure by recreating its surfaces and recording the state block again.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Declaration

Conceptually, the vertex declaration is a way of programming the vertex direct memory access (DMA) and the tessellator engine of the graphics pipe. It expresses the data layout and the tessellator operations concisely. To address the complexity and extensibility of declarations in Microsoft® DirectX® 8.x, a new format for expressing vertex streams has been introduced.

Vertex shaders and vertex declarations are no longer bound together at CreateVertexShader time. The shader validation has been divided into two parts. One runs at the vertex shader creation time and the other runs at the DrawPrimitive time. Vertex shaders and vertex declarations are represented by objects.

Decls are no longer expressed as streams of DWORDs. They are expressed as an array of D3DVERTEXELEMENT9 structures. Each element of the array describes one vertex element.

Additionally, to address application programming interface (API) usability issues, there will be a separate SetFVF call that is equivalent to the SetVertexDeclaration call. This is a convenience function; when this call is made, it will clobber the currently set declaration and vice versa. If the driver is pre-DirectX 8.0 (NumStreams is set to 0), SetVertexDeclaration might fail for declarations that cannot be converted to flexible vertex format (FVF) with an error. SetFVF can be used with both the fixed function, as well as the programmable vertex pipeline. Internally, FVF is converted to a vertex shader declaration using the Mapping FVF to DirectX 9.0 Decl. DCL commands in vertex shader functions should be written with this in mind. Because of this conversion, all further discussion will be about vertex declarations only.

D3DVERTEXELEMENT9 Structure

The following are the fields in the D3DVERTEXELEMENT9 structure and their explanations.

  • Stream - Stream number this field is to be read from.
  • Offset - Offset, in bytes, that this field is being read from.
  • Type - Type of the input data and how the data is transformed when fed into the vertex shader registers. That is, float1,float2,short2n, etc. Type of the output is determined by the method. Some methods have an implied type.
  • Method - Any one predefined operations that would be performed by a tessellator (or any procedural geometry routine) on the input specified.
    • D3DDECLMETHOD_DEFAULT: When a tessellator is used, this element is interpolated, else copied into the vertex processor's input register. The input type for this operation can be anything. The output type for this operation is the same as the input.
    • D3DDECLMETHOD_PARTIALU: Computes the tangent at a point on the rectangular patch (R-patch) in the u-direction. The input type for this operation can be D3DDECLTYPE_FLOAT[43], D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, D3DDECLTYPE_SHORT4. The output type for this operation is always D3DDECLTYPE_FLOAT3.
    • D3DDECLMETHOD_PARTIALV: Computes the tangent at a point on the R-patch in the v-direction. The input type for this operation can be D3DDECLTYPE_FLOAT[43], D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, D3DDECLTYPE_SHORT4. The output type for this operation is always D3DDECLTYPE_FLOAT3.
    • D3DDECLMETHOD_CROSSUV: Computes the normal at a point on rect/tri patches (RT-patches) by taking a cross product of the two tangents. The input type for this operation can be D3DDECLTYPE_FLOAT[43], D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, or D3DDECLTYPE_SHORT4. The output type for this operation is always D3DDECLTYPE_FLOAT3.
    • D3DDECLMETHOD_UV: Copy out the U, V values at a point on an R-patch. Generates a 2-D float. The input type for this operation must be set to D3DDECLTYPE_UNUSED. The output data type is always D3DDECLTYPE_FLOAT2. The input stream and offset are also unused (but must be set to 0).
    • D3DDECLMETHOD_LOOKUP: Look up a displacement map. The input type can be D3DDECLTYPE_FLOAT[234]. Only the .x and .y components are used for the texture map lookup. The output type for this operation is always D3DDECLTYPE_FLOAT4. It can be used only if the device supports displacement mapping. This method can be used only with D3DDECLUSAGE_SAMPLE.
    • D3DDECLMETHOD_LOOKUPPRESAMPLED: Look up a pre-sampled displacement map. The input type, stream index, and stream offset are all unused (Type must be set to D3DDECLTYPE_UNUSED, and stream and offset must be set to 0). The output type for this operation is always D3DDECLTYPE_FLOAT4. It can be used only if the device supports displacement mapping. This method can be used only with D3DDECLUSAGE_SAMPLE.
  • Semantic type - The element's usage, for example, is it a Normal? This is useful for N-patches and to enable greater interoperability between various data layouts and vertex shaders. TEXCOORDS semantic can be used for user defined fields (which don't have an existing semantic defined by Microsoft Direct3D®). The semantics are generally a binding mechanism between vertex declarations and vertex shaders. However, in some cases, they have a special interpretation. For example, an element that has NORMAL or POSITION semantic is used by the N-patch tessellator to set up tesselation.

    The following are the allowed.

    Semantics, usage index | Special interpretations
    (D3DDECLUSAGE_POSITION, 0 ) | Untransformed position in the fixed function vertex shader and the N-patch tessellator.
    (D3DDECLUSAGE_POSITION, 1) | Untransformed position in the fixed function vertex shader for skinning.
    (D3DDECLUSAGE_BLENDWEIGHT, 0) | Blend weights in the fixed function vertex shader.
    (D3DDECLUSAGE_BLENDINDICES, 0) | Matrix indices for the fixed function vertex-shader-indexed paletted skinning.
    (D3DDECLUSAGE_NORMAL, 0) | Vertex normal in the fixed function vertex shader and the N-patch tessellator.
    (D3DDECLUSAGE_NORMAL, 1) | Vertex normal in the fixed function vertex shader for skinning.
    (D3DDECLUSAGE_PSIZE, 0) | Point-size attribute that is used by the setup engine of the rasterizer to expand a point into a quad for the point-sprite functionality.
    (D3DDECLUSAGE_TEXCOORD, n) | Texture coordinates in fixed function vertex shader and pre-3_0 pixel shader. These can be used to pass user defined data.
    (D3DDECLUSAGE_TANGENT, n) | Tangent. It has no special interpretation.
    (D3DDECLUSAGE_BINORMAL, n) | Binormal. It has no special interpretation.
    (D3DDECLUSAGE_TESSFACTOR, 0) | Tessellation factor that is used in the tessellation unit to control the rate of tessellation.
    (D3DDECLUSAGE_POSITIONT, 0) | Post-transformed position. When a declaration containing this is set, it bypasses the vertex processing.
    (D3DDECLUSAGE_COLOR, 0) | Diffuse color in the fixed function vertex shader and pre-3_0 pixel shader.
    (D3DDECLUSAGE_COLOR, 1) | Specular color in the fixed function vertex shader and pre-3_0 pixel shader.
    (D3DDECLUSAGE_FOG, 0) | Fog blend value, that is used post pixel shader when a pre-3_0 pixel shader is set.
    (D3DDECLUSAGE_DEPTH, n) | Depth. It has no special interpretation.
    (D3DDECLUSAGE_SAMPLE, n) | Displacement value looked up. It can be used only with D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.

A special value for the vertex element is considered the end of vertex shader declaration. This value is #define D3DDECL_END() {0xFF,0,0,0,0,0}.

UsageIndex is used in conjunction with Usage to specify the semantic of a vertex element. Instead of using D3DVSDE_POSITION2 as in DirectX 8.x, now user can specify D3DDECLUSAGE_POSITION as Usage and UsageIndex = 1.

A Decl specifies the input to the tessellator engine (or directly the vertex processing engine in case the tessellator is not used) as well as its output. The type field in the vertex element specifies the type of the input data to the decl. The output type is implied by the method.

There is a preamble in the vertex shader that has the form of {semantic, semantic index, register number}. The runtime matches up the declaration's semantic with the shader's semantic information, thus pairing up an input register with byte offset into a stream.

Mapping FVF to DirectX 9.0 Decl

FVF | Data type | Usage | Usage index
D3DFVF_XYZ | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZRHW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0
D3DFVF_XYZW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_UBYTE4 | D3DVSDT_FLOAT3 D3DVSDT_FLOAT4 D3DVSDT_UBYTE4 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_D3DCOLOR | D3DVSDT_FLOAT3 D3DVSDT_FLOAT4 D3DVSDT_D3DCOLOR | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT4 D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOATn | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_UBYTE4 | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT(n-1) D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_D3DCOLOR | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT(n-1) D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_NORMAL | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0
D3DFVF_PSIZE | D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0
D3DFVF_DIFFUSE | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0
D3DFVF_SPECULAR | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1
D3DFVF_TEXCOORDSIZEm(n) | D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n

Vertex Declarations with D3DDECLUSAGE_POSITIONT

Presence of a vertex element with (D3DUSAGE_POSITIONT, 0) is used to indicate to the device that the vertex data coming in has already been through vertex processing (like an FVF with D3DFVF_XYZRHW bit set). At Draw time, if the currently set declaration has an element with the (D3DUSAGE_POSITIONT, 0) semantic, the entire vertex processing is skipped (just as if an FVF with D3DFVF_XYZRHW bit has been set).

There are some restrictions on vertex declarations with (D3DDECLUSAGE_POSITIONT, 0):

  • Only stream zero can be used is such declarations.
  • Vertex elements must be sorted by increasing stream offset.
  • Stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • Only D3DDECLMETHOD_DEFAULT method can be used.
  • Other vertex elements cannot have (D3DDECLUSAGE_POSITION, 0) semantic.

In addition, there are some restrictions on such declaration, related to the device driver version. These restrictions are in effect because Direct3D sends such declarations directly to the driver without doing any conversion.

Pre-DirectX 9.0 Drivers

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are not allowed. This means that if there is a vertex element with (D3DDECLUSAGE_TEXCOORD, n) then there also should be a vertex element with (D3DDECLUSAGE_TEXCOORD, n-1).

DirectX 9.0 Drivers without Pixel Shader Version 3 Support

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are allowed.

DirectX 9.0 Drivers with Pixel Shader Version 3 Support

More general declarations are allowed.

  • Vertex elements can be in arbitrary order and can have any data types.
  • Multiple vertex elements can share the same stream offset and be of a different type in the same time when if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by device.

Vertex Declarations without D3DDECLUSAGE_POSITIONT

Runtime validates the creation of declarations. Following are the general rules for what declarations are legal.

  • All vertex elements for a stream must be consecutive and sorted by offset.
  • Stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • If the D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set then the vertex elements can:
    • Multiple vertex elements can share the same offset in a stream.
    • They can all be of different types which can be of different sizes.
    • They can overlap arbitrarily. For example, one element can start at a location of a stream that is, at the same time, in the middle of another element.
    • Vertex element are allowed to have stream offset in any order.
  • Number of vertex elements cannot be greater than 64.
  • UsageIndex should be in the range [0-15].
  • Declaration, used with the DrawPrimitive API, should not have vertex elements other than D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.
  • Declaration, which contains D3DDECLMETHOD_LOOKUP or LOOKUPPRESAMPLED, should be used only with the programmable vertex pipeline.
  • Declaration, used with the DrawRectPatch/DrawTriPatch API, cannot have vertex elements with D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.
  • Declaration should have only one element with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED method.
  • Declaration with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED should not have elements other than D3DDECLMETHOD_DEFAULT, because displacement mapping is done only for N-patches.
  • Vertex elements with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED can only be used with (D3DDECLUSAGE_SAMPLE, n) semantic and vice versa.
  • If a vertex element with D3DDECLMETHOD_LOOKUP method has stream index and offset of already existing vertex element, this vertex element should have the same data type.
  • A vertex element with D3DDECLMETHOD_LOOKUP method should have data type D3DDECLTYPE_FLOAT2/3/4
  • Vertex elements with types D3DDECLMETHOD_CROSSUV, D3DDECLMETHOD_PARTIALU and D3DDECLMETHOD_PARTIALV should have an offset of a vertex element with compatible data type.
  • A vertex element with method D3DDECLMETHOD_UV or D3DDECLMETHOD_LOOKUPPRESAMPLED must have type D3DDECLTYPE_UNUSED, stream index zero and stream offset zero.
  • Declarations with methods D3DDECLMETHOD_UV, D3DDECLMETHOD_PARTIALU and D3DDECLMETHOD_PARTIALV can only be used with DrawRectPatch.
  • Usage D3DDECLUSAGE_TESSFACTOR should be used only with data type D3DDECLTYPE_FLOAT1 and usage index 0.
  • When a declaration is used for tessellation (DrawRectPatch, DrawTriPatch, N-patches) data type must be less or equal D3DDECLTYPE_SHORT4.
  • Decls that contain methods that require certain device capabilities (for example, displacement mapping, RT-patches) can only be created if the device supports them.
  • A vertex declaration, which is used to draw point and lines, cannot have methods other than D3DDECLMETHOD_DEFAULT.
  • Which decls can be created also depends on the driver capabilities.

Usage with the Programmable Vertex Pipeline

  • At draw time Direct3D looks for the same "usage - usage index" combination in the current vertex declaration and the current vertex shader function. When the combination is found the register from shader function DCL is used as destination for the vertex element.
  • When a vertex element in the current vertex declaration has a usage which is not found in the current vertex shader, that vertex element is ignored.
  • When using vertex shaders version less than 2.0, all semantics, mentioned in the shader code, need to be present in the declaration bound at the draw time. When using vertex shaders 2.0 and above this restriction does not exist, which allows applications to use different vertex declarations with the same vertex shader. This is useful when a vertex shader reads input data based on static conditions. Vertex shader registers, which are not initialized because of this, will have undefined values.

There are additional restrictions when using with hardware vertex processing on a DirectX 8.x driver :

  • Vertex elements cannot overlap or share the same offset.
  • Data types are limited to what DirectX 8.x driver can understand.

The CreateVertexDeclaration might fail if the declaration provided cannot be converted to a DirectX 8.x-style decl. For mixed mode device this failure will happen at Draw* time because that is the only time it can be known whether this shader is being used with hardware or software vertex processing.

Usage with the Fixed Function Vertex Pipeline

Only declarations that adhere to the following rules can be used:

  • There should be no gaps between vertex elements (SKIP was not allowed in a DirectX 8.x declaration, which is used for the fixed function pipeline).
  • Semantic (D3DDECLUSAGE_POSITION, 0) must be specified and should have D3DDECLTYPE_FLOAT3 data type.
  • A vertex element with method D3DDECLMETHOD_UV must specify usage D3DDECLUSAGE_TEXCOORD or D3DDECLUSAGE_BLENDWEIGHT.
  • A vertex element with method D3DDECLMETHOD_PARTIALU, _PARTIALV, or _CROSSUV can only be used with the usages: D3DDECLUSAGE_POSITION, _NORMAL, _BLENDWEIGHT or _TEXCOORD, and must use input type D3DDECLTYPE_FLOAT3.

When a declaration is used with hardware vertex processing on a DirectX 8.x driver, the Direct3D runtime converts it to a DirectX 8.x-style declaration with the following rules.

  • Vertex elements cannot share the same offset in a stream and they cannot overlap.
  • Data type must be less or equal D3DDECLTYPE_SHORT4
  • Only the following methods are allowed: D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_CROSSUV, D3DDECLMETHOD_UV
  • Usage and UsageIndex are converted to a register value according to Mapping DirectX 9.0 Declaration to DirectX 8.x.
  • Mapping DirectX 9.0 Declaration to DirectX 8.x shows which DirectX 9.0 semantics could be converted to DirectX 8.x-style declaration.
  • If there are n vertex elements in a declaration and 0 - m (m < n), map to an FVF (elements described in the Mapping DirectX 9.0 Declaration to FVF Bits), but m+1 does not, then:
    • If any of m+2 until n-1 vertex elements map to FVF/dx8decl, the decl is invalid.
    • The elements 0 to m are converted (by the runtime for DirectX 8.0 and older drivers, and by the DirectX 9.0 drivers) using the Mapping DirectX 9.0 Declaration to FVF Bits, m+1, m+2 until n-1 become mapped to contiguous texcoord(k), texcoord(k+1), starting from any texcoord in elements 0 - m.
    • The data type at a mapped texcoord is assumed to be float[1234] replacing whatever data type the current element contains (but the same size). So it is ok for the existing data type to be something that is not in Mapping DirectX 9.0 Declaration to FVF Bits.
    • If k reaches 8, then the decl is invalid for FVF/dx8decl
    • If any mappings to texcoords have occurred, then the entire declaration is required to have no elements with generation method other than DEFAULT.. else, the decl is invalid for FVF/dx8decl.

Mapping DirectX 9.0 Declaration to DirectX 8.x

DirectX 9.0 Usage | DirectX 9.0 Usage Index | DirectX 8.0
D3DDECLUSAGE_POSITION | 0 | D3DVSDE_POSITION
D3DDECLUSAGE_POSITION | 1 | D3DVSDE_POSITION2
D3DDECLUSAGE_NORMAL | 0 | D3DVSDE_NORMAL
D3DDECLUSAGE_NORMAL | 1 | D3DVSDE_NORMAL2
D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DVSDE_BLENDWEIGHT
D3DDECLUSAGE_BLENDINDICES | 0 | D3DVSDE_BLENDINDICES
D3DDECLUSAGE_PSIZE | 0 | D3DVSDE_PSIZE
D3DDECLUSAGE_COLOR | 0 | D3DVSDE_DIFFUSE
D3DDECLUSAGE_COLOR | 1 | D3DVSDE_SPECULAR
D3DDECLUSAGE_TEXCOORD | n | D3DVSDE_TEXCOORDn

When a declaration is used with hardware vertex processing on a DirectX 7.0 driver, the Direct3D runtime converts it to an FVF with the following rules.

  • Only stream 0 should be used (evident from the MaxStreams cap).
  • The order of vertex elements should be the same as order of FVF bits.
  • Gaps in texture coordinates are not allowed
  • Any vertex element not described in the Mapping DirectX 9.0 Declaration to FVF Bits cannot be converted into a valid FVF for all pre-DirectX 8.0 drivers and hence not be used on those drivers.
  • Only D3DDECLTYPE_FLOAT2 is allowed for vertex elements with D3DDECLUSAGE_TEXCOORD if device does not set any of the following caps: D3DPTEXTURECAPS_PROJECTED or D3DPTEXTURECAPS_CUBEMAP.

Mapping DirectX 9.0 Declaration to FVF Bits

Data type | Usage | Usage index | FVF
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0 | D3DFVF_XYZ
D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0 | D3DFVF_XYZRHW
D3DDECLTYPE_FLOATn | D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DFVF_XYZBn
D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_BLENDINDICES | 0 | D3DFVF_XYZB (nWeights+1)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0 | D3DFVF_NORMAL
D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0 | D3DFVF_PSIZE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0 | D3DFVF_DIFFUSE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1 | D3DFVF_SPECULAR
D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n | D3DFVF_TEXCOORDSIZEm(n)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 1 | N/A
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 1 | N/A

Using Vertex Declarations with ProcessVertices

A vertex declaration could be used to describe the output of ProcessVertices. Such declaration should adhere to the following rules.

  • Only stream 0 must be used.
  • Vertex elements cannot share the same offset or overlap with each other.
  • Only D3DDECLMETHOD_DEFAULT methods are allowed.
  • Only D3DDECLTYPE_FLOATn or D3DDECLTYPE_D3DCOLOR data types can be used.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) or (D3DDECLUSAGE_POSITIONT,0) are not required.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) and (D3DDECLUSAGE_POSITIONT,0) cannot be present in the same declaration.
  • Current vertex shader must be version 3.0 or higher when such declaration is used.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Formats

A flexible vertex format (FVF) code describes the contents of vertices stored interleaved in a single data stream. It generally specifies data to be processed by the fixed function vertex processing pipeline.

Microsoft® Direct3D® applications can define model vertices in several different ways. Support for flexible vertex definitions, also known as flexible vertex formats or flexible vertex format codes, makes it possible for your application to use only the vertex components it needs, eliminating those components that aren't used. By using only the needed vertex components, your application can conserve memory and minimize the processing bandwidth required to render models. You describe how your vertices are formatted by using a combination of D3DFVF.

The FVF specification includes formats for point size, specified by D3DFVF_PSIZE. This size is expressed in camera space units for non-TL vertices, and in device-space units for TL vertices.

The rendering methods of the IDirect3DDevice9 interface provides C++ applications with methods that accept a combination of these flags, and uses them to determine how to render primitives. Basically, these flags tell the system which vertex components - position, vertex blending weights, normal, colors, the number and format of texture coordinates - your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory and which you've omitted.

To determine device limitations, you can query a device for the D3DFVFCAPS_DONOTSTRIPELEMENTS and D3DFVFCAPS_TEXCOORDCOUNTMASK flexible vertex format flags. For more information, see the FVFCaps member of the D3DCAPS9 structure.

One significant requirement that the system places on how you format your vertices is on the order in which the data appears. The following illustration depicts the required order for all possible vertex components in memory, and their associated data types.

Vertex order diagram

Texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate or as many as four texture coordinates (for 2-D projected texture coordinates). For more information, see Texture Coordinate Formats. Use the D3DFVF_TEXCOORDSIZEn set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

No application will use every component - the reciprocal homogeneous W (RHW) and vertex normal fields are mutually exclusive. Nor will most applications try to use all eight sets of texture coordinates, but Direct3D has this capacity. There are several restrictions on which flags you can use with other flags. For example, you cannot use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices.

To use indexed vertex blending, the D3DFVF_LASTBETA_UBYTE4 flag should appear at the end of the FVF. The presence of this flag indicates that the fifth blending weight will be treated as a DWORD instead of float. For more information, see Indexed Vertex Blending.

The following code samples shows the difference between an FVF code that uses the D3DFVF_LASTBETA_UBYTE4 flag and one that doesn't. The FVF defined below does not use the D3DFVF_LASTBETA_UBYTE4 flag. The flag D3DFVF_XYZ3 is present when four blending indices are used because you always use (1 - the sum of the first three) for the fourth.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3|D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

The FVF defined below uses the D3DFVF_LAST_UBYTE4 flag.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB4 | D3DFVF_LASTBETA_UBYTE4 |D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    DWORD       indices; // Referenced as v2.xyzw in the vertex shader
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

© 2002 Microsoft Corporation. All rights reserved.


Object Geometry

Microsoft® Direct3D® supports several higher-level abstractions for handling geometry. These are broken down into the following topics.

  • Vertex Buffers
  • Index Buffers

© 2002 Microsoft Corporation. All rights reserved.


Vertex Buffers

Vertex buffers, represented by the IDirect3DVertexBuffer9 interface, are memory buffers that contain vertex data. Vertex buffers can contain any vertex type - transformed or untransformed, lit or unlit - that can be rendered through the use of the rendering methods in the IDirect3DDevice9 interface. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. Transformation is always performed.

The flexibility of vertex buffers make them ideal staging points for reusing transformed geometry. You could create a single vertex buffer, transform, light, and clip the vertices in it, and render the model in the scene as many times as needed without re-transforming it, even with interleaved render state changes. This is useful when rendering models that use multiple textures: the geometry is transformed only once, and then portions of it can be rendered as needed, interleaved with the required texture changes. Render state changes made after vertices are processed take effect the next time the vertices are processed.

  • Description
  • Memory Pool and Usage

Description

A vertex buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of vertices it can contain. All these traits are held in a D3DVERTEXBUFFER_DESC structure.

The Format member is set to D3DFMT_VERTEXDATA to indicate that this is a vertex buffer. The Type identifies the resource type of the vertex buffer. The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the vertex buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data within the vertex buffer.

Pool specifies the memory class that is allocated for the vertex buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the vertex buffer in system memory.

The Size member stores the size, in bytes, of the vertex buffer data. The FVF member contains a combination of D3DFVF that identify the type of vertices that the buffer contains.

Memory Pool and Usage

You can create vertex buffers with the IDirect3DDevice9::CreateVertexBuffer method, which takes pool (memory class) and usage parameters. IDirect3DDevice9::CreateVertexBuffer can also be created with a specified flexible vertex format (FVF) code for use in fixed function vertex processing, or as the output of process vertices. For details, see FVF Vertex Buffers.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware vertex processing in mixed mode.(D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is to be used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed as well as for software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the vertex processing is done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

This section introduces the concepts necessary to understand and use vertex buffers in a Microsoft® Direct3D® application. Information is divided into the following sections.

  • Creating a Vertex Buffer
  • Accessing the Contents of a Vertex Buffer
  • Rendering from a Vertex Buffer
  • FVF Vertex Buffers
  • Fixed Function Vertex Processing
  • Programmable Vertex Processing
  • Device Types and Vertex Processing Requirements

© 2002 Microsoft Corporation. All rights reserved.


Creating a Vertex Buffer

You create a vertex buffer object by calling the IDirect3DDevice9::CreateVertexBuffer method, which accepts five parameters. The first parameter specifies the vertex buffer length, in bytes. Use the sizeof operator to determine the size of a vertex format, in bytes. Consider the following custom vertex format.

struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // The texture coordinates.
};

// Custom FVF, which describes the custom vertex structure.

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

To create a vertex buffer to hold four CUSTOMVERTEX structures, specify [4*sizeof(CUSTOMVERTEX)] for the Length parameter.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertex buffer is capable of containing clipping information—in the form of clip flags—for vertices that exist outside the viewing area. To create a vertex buffer that cannot contain clip flags, include the D3DUSAGE_DONOTCLIP flag for the Usage parameter. The D3DUSAGE_DONOTCLIP flag is applied only if you also indicate that the vertex buffer will contain transformed vertices—the D3DFVF_XYZRHW flag is included in the FVF parameter. The IDirect3DDevice9::CreateVertexBuffer method ignores the D3DUSAGE_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

The third parameter, FVF, is a combination of D3DFVF that describe the vertex format of the vertex buffer. If you specify 0 for this parameter, then the vertex buffer is a non-FVF vertex buffer. For more information, see FVF Vertex Buffers. The fourth parameter describes the memory class into which to place the vertex buffer.

The final parameter that IDirect3DDevice9::CreateVertexBuffer accepts is the address of a variable that will be filled with a pointer to the new IDirect3DVertexBuffer9 interface of the vertex buffer object, if the call succeeds.

Note You cannot produce clip flags for a vertex buffer that was created without support for them.

The following C++ code example shows what creating a vertex buffer might look like in code.

    // For the purposes of this example, the d3dDevice variable is
    // the address of an IDirect3DDevice9 interface exposed by a
    // Direct3DDevice object, g_pVB is a variable of type
    // LPDIRECT3DVERTEXBUFFER9.

// The custom vertex type
struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // The texture coordinates
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

    // Create a clipping-capable vertex buffer. Allocate enough memory
    // in the  default memory pool to hold three CUSTOMVERTEX
    // structures.

    if( FAILED( d3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
                                                  0 /* Usage */, D3DFVF_CUSTOMVERTEX,
                                                  D3DPOOL_DEFAULT, &g_pVB ) ) )
        return E_FAIL;

© 2002 Microsoft Corporation. All rights reserved.


Accessing the Contents of a Vertex Buffer

Vertex buffer objects enable applications to directly access the memory allocated for vertex data. You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new vertex data or to read any data it already contains. The IDirect3DVertexBuffer9::Lock method accepts four parameters. The first, OffsetToLock, is the offset into the vertex data. The second parameter is the size, measured in bytes, of the vertex data. The third parameter accepted by the IDirect3DVertexBuffer9::Lock method, ppbData, is the address of a BYTE pointer that points to the vertex data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. Specify constants for the Flags parameter according to the way the vertex data will be accessed. Make sure the value chosen for D3DUSAGE matches the value chosen for D3DLOCK. For example, if you are creating a vertex buffer with write access only, it doesn't make sense to try to read the data by specifying D3DLOCK_READONLY. Wisely using these flags allows the driver to lock the memory and provide the best performance, given the requested access type.

After you finish filling or reading the vertex data, call the IDirect3DVertexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the g_pVB is a variable of type
//   LPDIRECT3DVERTEXBUFFER9 and that g_Vertices has been
//   properly initialized with vertices.

// To fill the vertex buffer, you need to lock the buffer to
//   gain access to the vertices. This mechanism is required
//   because vertex buffers may be in device memory.
VOID* pVertices;

if( FAILED( g_pVB->Lock( 0,                  // Fill from the start of
                                             //   the buffer.
                         sizeof(g_Vertices), // Size of the data to
                                             //   load.
                         (BYTE**)&pVertices, // Returned vertex data.
                         0 ) ) )             // Send default flags to
                                             //   the lock.
    return E_FAIL;

memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );
g_pVB->Unlock();
Note If you create a vertex buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the vertex buffer memory. Including this flag enables Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the IDirect3DVertexBuffer9::Lock method.

In C++, because you directly access the memory allocated for the vertex buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the vertex format that your application uses to move from one vertex in the allocated buffer to another. The vertex buffer memory is a simple array of vertices specified in flexible vertex format. Use the stride of whatever vertex format structure you define. You can calculate the stride of each vertex at run time by examining the D3DFVF contained in the vertex buffer description. The following table shows the size for each vertex component.

Vertex Format Flag | Size
D3DFVF_DIFFUSE | sizeof(DWORD)
D3DFVF_NORMAL | sizeof(float) × 3
D3DFVF_SPECULAR | sizeof(DWORD)
D3DFVF_TEXn | sizeof(float) × n × t
D3DFVF_XYZ | sizeof(float) × 3
D3DFVF_XYZRHW | sizeof(float) × 4

The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn flags (where n is a value from 0 to 8). Multiply the number of texture coordinate sets by the size of one set of texture coordinates, which can range from one to four floats, to calculate the memory required for that number of texture coordinates.

Use the total vertex stride to increment and decrement the memory pointer as needed to access particular vertices.

Retrieving Vertex Buffer Descriptions

You can retrieve information about a vertex buffer by calling the IDirect3DVertexBuffer9::GetDesc method. This method fills the members of the D3DVERTEXBUFFER_DESC structure with information about the vertex buffer.

© 2002 Microsoft Corporation. All rights reserved.


Rendering from a Vertex Buffer

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice9::SetStreamSource method, as shown in the following example.

d3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );

The first parameter of IDirect3DDevice9::SetStreamSource tells Microsoft® Direct3D® the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to inform Direct3D which vertex shader to use by calling the IDirect3DDevice9::SetVertexShader method. The following sample code sets an flexible vertex format (FVF) code for the vertex shader. This informs Direct3D of the types of vertices it is dealing with.

d3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

After setting the stream source and vertex shader, any draw methods will use the vertex buffer. The code example below shows how to render vertices from a vertex buffer with the IDirect3DDevice9::DrawPrimitive method.

d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The second parameter that IDirect3DDevice9::DrawPrimitive accepts is the index of the first vector in the vertex buffer to load.

© 2002 Microsoft Corporation. All rights reserved.


FVF Vertex Buffers

Setting the flexible vertex format (FVF) parameter of the IDirect3DDevice9::CreateVertexBuffer method to a nonzero value, which must be a valid FVF code, indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. Some methods or uses of IDirect3DDevice9 require FVF vertex buffers, and others require non-FVF vertex buffers. FVF vertex buffers are required as the destination vertex buffer argument for IDirect3DDevice9::ProcessVertices.

FVF vertex buffers can be bound to a source data stream for any stream number. However, FVF vertex buffers are not allowed to be used for inputs to programmed vertex shaders

The presence of the D3DFVF_XYZRHW component on FVF vertex buffers indicates that the vertices in that buffer have been processed. Vertex buffers used for IDirect3DDevice9::ProcessVertices destination vertex buffers must be post-processed. Vertex buffers used for fixed function shader inputs can be either pre- or post-processed. If the vertex buffer is post-processed, then the shader is effectively bypassed and the data is passed directly to the primitive clipping and setup module.

FVF vertex buffers can be used with vertex shaders. Also, vertex streams can represent the same vertex formats that non-FVF vertex buffers can. They do not have to be used to input data from separate vertex buffers. The additional flexibility of the new vertex streams enables applications that need to keep their data separate to work better, but it is not required. If the application can maintain interleaved data in advance, then that is a performance boost. If the application will only interleave the data before every rendering call, then it should enable the application programming interface (API) or hardware to do this with multiple streams.

The most important things with vertex performance is to use a 32-byte vertex, and to maintain good cache ordering.

© 2002 Microsoft Corporation. All rights reserved.


Fixed Function Vertex Processing

In the fixed function vertex pipeline, processing the vertices in a vertex buffer applies the current transformation matrices for the device. Vertex operations such as lighting, generating clip flags, and updating extents can also be applied, optionally. When using fixed function vertex processing, modifying the elements in the destination vertex buffer is controlled by the D3DPV_DONOTCOPYDATA flag. This flag applies only to fixed function vertex processing. The IDirect3DDevice9 interface exposes the IDirect3DDevice9::ProcessVertices method to process vertices. You process vertices from a vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer by calling the IDirect3DDevice9::ProcessVertices method. The method accepts five parameters that describe the location and quantity of vertices that the method targets, the destination vertex buffer, and the processing options. After the call, the destination buffer contains the processed vertex data.

The first, second, and third parameters, SrcStartIndexDestIndex, and VertexCount, reflect the index of the first vertex to load, the index within the destination buffer at which the vertices will be placed, and the total number of vertices to process and place in the destination buffer. The fourth parameter, pDestBuffer should be set to the address of the IDirect3DVertexBuffer9 interface of the vertex buffer object that will receive the source vertices. The SrcStartIndex parameter specifies the index at which the method should start processing vertices.

The final parameter, Flags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. When you set Flags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the vertex shader or set to 0. However, when using D3DPV_DONOTCOPYDATA, IDirect3DDevice9::ProcessVertices does not overwrite color and texture coordinate information in the destination buffer unless this data is generated by Microsoft® Direct3D®. Diffuse color is generated when lighting is enabled, that is, D3DRS_LIGHTING is set to TRUE. Specular color is generated when lighting is enabled and specular is enabled, that is, D3DRS_SPECULARENABLE and D3DRS_LIGHTING are set to TRUE. Specular color is also generated when fog is enabled. Texture coordinates are generated when texture transform or texture generation is enabled. xref rid="_dx_idirect3ddevice9_processvertices_graphics"/> uses the current render states to determine what vertex processing should be done.

FVF Usage Settings for Destination Vertex Buffers

The IDirect3DDevice9::ProcessVertices method requires specific settings for the D3DFVF of the destination vertex buffer. The flexible vertex format (FVF) usage settings must be compatible with the current settings for vertex processing.

For fixed function vertex processing, IDirect3DDevice9::ProcessVertices requires the following FVF settings.

  • Position type is always D3DFVF_XYZRHW; so, D3DFVF_XYZ and D3DFVF_XYZB1 through D3DFVF_XYZB5 are invalid.
  • The D3DFVF_NORMAL, D3DFVF_RESERVED0, and D3DFVF_RESERVED2 flags must not be set.
  • The D3DFVF_DIFFUSE flag must be set if an OR operation of the following conditions returns true.
    • Lighting is enabled, that is, D3DRS_LIGHTING is true.
    • Lighting is disabled, and diffuse color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
  • The D3DFVF_SPECULAR flag must be set if an OR operation of the following conditions returns true.
    • Lighting is enabled and specular color is enabled, that is, D3DRS_SPECULARENABLE is true.
    • Lighting is disabled, and specular color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
    • Vertex fog is enabled, that is, D3DRS_FOGVERTEXMODE is not set to D3DFOG_NONE.

In addition, the texture coordinate count must be set in the following manner.

  • If texture transform and texture generation are disabled for all active texture stages, and the D3DPV_DONOTCOPYDATA is not set, then the number and type of output texture coordinates are required to match those of the input vertex texture coordinates. If D3DPV_DONOTCOPYDATA is set and texture transform and texture generation are disabled, then the output texture coordinates are ignored.
  • If texture transform or texture generation is enabled for any active texture stages, the output vertex might need to contain more texture coordinate sets than the input vertex. This is due to the proliferation of texture coordinates from those being generated by texture generation or derived by texture transforms. Note that a similar proliferation of texture coordinates occurs during IDirect3DDevice9::DrawPrimitive calls, but is not visible to the application programmer. In this case, Direct3D generates a new set of texture coordinates. The new set of texture coordinates is derived by stepping through the texture stages and analyzing the settings for texture generation, texture transformation, and texture coordinate index to determine if a unique set of texture coordinates is required for that stage. Each time a new set is required it is allocated in increasing order. Note that the maximum, and typical, requirement is one set per stage, although it might be less due to sharing of nontransformed texture coordinates through D3DTSS_TEXCOORDINDEX.

Thus, for each texture stage, a new set of texture coordinates is generated if a texture is bound to that stage and any of the following conditions are true.

  • Texture generation is enabled for that stage.
  • Texture transformation is enabled for that stage.
  • Nontransformed input texture coordinates are referenced through D3DTSS_TEXCOORDINDEX for the first time.

When Direct3D is generating texture coordinates, the application is required to perform the following actions.

  1. Use a destination vertex buffer with the appropriate FVF usage.
  2. Reprogram the D3DTSS_TEXCOORDINDEX of the texture stage according to the placement of the post -processed texture coordinates. Note that the reprogramming of the D3DTSS_TEXCOORDINDEX setting occurs when the processed vertex buffer is used in subsequent IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive calls.

Finally, texture coordinate dimensionality (D3DFVF_TEX0 through D3DFVF_TEX8) must be set in the following manner.

  • For each texture coordinate set, if texture transform and texture generation are disabled, then the output texture coordinate dimensionality must match the input. If the texture transform is enabled, then the output dimensionality must match the count defined by the D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, or D3DTTFF_COUNT4 settings. If the texture transform is disabled and texture generation is enabled, then the output dimensionality must match the settings for the texture generation mode; currently all modes generate 3 float values.

When IDirect3DDevice9::ProcessVertices fails due to an incompatible destination vertex buffer FVF code, the expected code is printed to the debug output (debug builds only).

© 2002 Microsoft Corporation. All rights reserved.


Programmable Vertex Processing

When using a programmed vertex shader, the elements updated in the destination vertex buffer are controlled by the shader function program. When the application writes to one of the destination vertex registers, the corresponding element within each vertex of the destination vertex buffer is updated. Elements in the destination vertex buffer that are not written to by the application are not modified. IDirect3DDevice9::ProcessVertices will fail if the application writes to elements that are not present in the destination vertex buffer.

© 2002 Microsoft Corporation. All rights reserved.


Device Types and Vertex Processing Requirements

The performance of vertex processing operations, including transformation and lighting, depends heavily on where the vertex buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for vertex buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the vertex buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the vertex buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING constant with IDirect3DDevice9::CreateVertexBuffer enables software vertex processing on the vertex buffer data. This flag is required for software vertex processing while in mixed mode. The flag may not be used for hardware vertex processing mode. Vertex buffers used with software vertex processing include the following:

  • All input streams for IDirect3DDevice9::ProcessVertices.
  • All input streams for IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive.

The reasoning you use to determine the memory location - system or driver optimal - for vertex buffers is the same as that for textures. Vertex processing, including transformation and lighting, in hardware works best when the vertex buffers are allocated in driver-optimal memory, while software vertex processing works best with vertex buffers allocated in system memory. For textures, hardware rasterization works best when textures are allocated in driver-optimal memory, while software rasterization works best with system-memory textures.

Note Microsoft® Direct3D® for Microsoft DirectX® 9.0 supports standalone processing of vertices, without rendering any primitive with the IDirect3DDevice9::ProcessVertices method. This standalone vertex processing is always performed in software on the host processor. Because of this, vertex buffers used as sources set with IDirect3DDevice9::SetStreamSource must be created with the D3DUSAGE_SOFTWAREPROCESSING flag. The functionality provided by IDirect3DDevice9::ProcessVertices is identical to that of the IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive methods while using software vertex processing.

If your application performs its own vertex processing and passes transformed, lit, and clipped vertices to rendering methods, then the application can directly write vertices to a vertex buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. Note that this technique will not work well if your application reads data back from a vertex buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory vertex buffer is a better choice.

When using the Direct3D vertex processing features (by passing untransformed vertices to vertex-buffer rendering methods), processing can occur in either hardware or software depending on the device type and device creation flags. It is recommended that vertex buffers be allocated in pool D3DPOOL_DEFAULT for best performance in virtually all cases. When a device is using hardware vertex processing, there are a number of additional optimizations that may be done based on the flags D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY. See IDirect3DDevice9::CreateVertexBuffer for more information about using these flags.

© 2002 Microsoft Corporation. All rights reserved.


Index Buffers

Index buffers, represented by the IDirect3DIndexBuffer9 interface, are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used to render primitives using the IDirect3DDevice9::DrawIndexedPrimitive method.

Vertex Buffers and index buffers are orthogonal concepts, that is, you can use indexed primitives with or without vertex buffers, or you can use a vertex buffer with or without indexed primitives.

An index buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of indices it can contain. These traits are held in a D3DINDEXBUFFER_DESC structure.

Index buffer descriptions tell your application how an existing buffer was created. You provide an empty description structure for the system to fill with the capabilities of a previously created index buffer. For more information about this task, see Access the Contents of an Index Buffer.

The Format member describes the surface format of the index buffer data.

The Type identifies the resource type of the index buffer.

The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the index buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the index buffer memory is used only for write operations. This frees the driver to place the index data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data in the index buffer.

Pool specifies the memory class allocated for the index buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the index buffer in system memory.

The Size member stores the size, in bytes, of the vertex buffer data.

Additional information is contained in the following topics.

  • Create an Index Buffer
  • Access the Contents of an Index Buffer
  • Render from an Index Buffer

© 2002 Microsoft Corporation. All rights reserved.


Create an Index Buffer

Create an index buffer object by calling the IDirect3DDevice9::CreateIndexBuffer method, which accepts five parameters. The first parameter specifies the index buffer length, in bytes.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertices being referred to by the indices are capable of containing clipping information. To improve performance, specify D3DUSAGE_DONOTCLIP when clipping is not required.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware index processing in mixed mode (D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed and software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the index processing is being done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

The third parameter is either the D3DFMT_INDEX16 or D3DFMT_INDEX32 member of the D3DFORMAT enumerated type that specifies the size of each index.

The fourth parameter is a member of the D3DPOOL enumerated type that tells the system where in memory to place the new index buffer.

The final parameter that IDirect3DDevice9::CreateIndexBuffer accepts is the address of a variable that is filled with a pointer to the new IDirect3DIndexBuffer9 interface of the vertex buffer object, if the call succeeds.

The following C++ code example shows what creating a index buffer might look like in code.

/*
 * For the purposes of this example, the d3dDevice variable is the
 * address of an IDirect3DDevice9 interface exposed by a
 * Direct3DDevice object, g_IB is a variable of type
 * LPDIRECT3DINDEXBUFFER9.
 */

if( FAILED( d3dDevice->CreateIndexBuffer( 16384 *sizeof(WORD),
                                            D3DUSAGE_WRITEONLY, D3DFMT_INDEX16,
                                            D3DPOOL_DEFAULT, &g_IB ) ) )
    return E_FAIL;

Index Processing Requirements

The performance of index processing operations depends heavily on where the index buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for index buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the index buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the index buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the IDirect3DDevice9::CreateIndexBuffer method specifies that the index buffer is to be used with software vertex processing. This flag is required in mixed mode vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING) when software vertex processing is used.

The application can directly write indices to a index buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. This technique does not work well if your application reads data back from an index buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory index buffer is a better choice.

Note Always use D3DPOOL_DEFAULT, except when you don't want to expend video memory or expand large amounts of page-locked RAM when the driver is putting vertex or index buffers into AGP memory.

© 2002 Microsoft Corporation. All rights reserved.


Access the Contents of an Index Buffer

Index buffer objects enable applications to directly access the memory allocated for index data. You can retrieve a pointer to index buffer memory by calling the IDirect3DIndexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new index data or to read any data it contains. The IDirect3DIndexBuffer9::Lock method accepts four parameters. The first, OffsetToLock, is the offset into the index data. The second parameter is the size, measured in bytes, of the index data. The third parameter accepted by the IDirect3DIndexBuffer9::Lock method, ppbData, is the address of a BYTE pointer filled with a pointer to the index data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application accesses the data in the buffer. Specify constants for the Flags parameter according to the way the index data will be accessed by your application. This allows the driver to lock the memory and provide the best performance given the requested access type. Use D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

After you fill or read the index data, call the IDirect3DIndexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the IB is a variable of type
// LPDIRECT3DINDEXBUFFER9 and that g_Indices has been properly
// initialized with indices.

// To fill the index buffer, you must lock the buffer to gain
// access to the indices. This mechanism is required because index
// buffers may be in device memory.

VOID* pIndices;

if( FAILED( IB->Lock( 0,                 // Fill from start of the buffer.
                      sizeof(g_Indices), // Size of the data to load.
                      (BYTE**)&pIndices, // Returned index data.
                      0 ) ) )            // Send default flags to the lock.
    return E_FAIL;

memcpy( pIndices, g_Indices, sizeof(g_Indices) );
IB->Unlock();
Note

If you create an index buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the IDirect3DIndexBuffer9::Lock method, see Using Dynamic Vertex and Index Buffers.

In C++, because you directly access the memory allocated for the index buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the index format your application uses to move from one index in the allocated buffer to another.

Retrieving Index Buffer Descriptions

Retrieve information about an index buffer by calling the IDirect3DIndexBuffer9::GetDesc method. This method fills the members of the D3DINDEXBUFFER_DESC structure with information about the vertex buffer.

© 2002 Microsoft Corporation. All rights reserved.


Render from an Index Buffer

Rendering index data from an index buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice9::SetStreamSource method.

d3dDevice->SetStreamSource( 0, VB, sizeof(CUSTOMVERTEX) );

The first parameter of SetStreamSource tells Microsoft® Direct3D® the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to call the IDirect3DDevice9::SetIndices method to set the source of the index data.

d3dDevice->SetIndices( IB, 0 );

The first parameter that IDirect3DDevice9::SetIndices accepts is the address of the index buffer to set. The second parameter is the starting point in the vertex stream.

After setting the stream and indices source, use the IDirect3DDevice9::DrawIndexedPrimitive method to render vertices that use indices from the index buffer.

d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0,
                                   dwVertices, 0, dwIndices / 3);

The second parameter that IDirect3DDevice9::DrawIndexedPrimitive accepts is the minimum vertex index for vertices used during this call. The third parameter is the number of indices to use during this call starting from BaseVertexIndex + MinIndex. The fourth parameter is the location in the index array to start reading indices. The final parameter that IDirect3DDevice9::DrawIndexedPrimitive accepts is the number of primitives to render. This parameter is a function of the primitive count and the primitive type. The code sample above uses triangles, so the number of primitives to render is the number of indices divided by three.

© 2002 Microsoft Corporation. All rights reserved.


Rendering

Applications use the DrawPrimitive family of methods to render a 3-D scene. The following topics discuss rendering with DrawPrimitive.

  • Shading
  • Presenting a Scene
  • Rendering Primitives
  • Depth Buffers
  • Fog
  • Alpha Blending
  • Direct3D Extentions (D3DX) Line Drawing

© 2002 Microsoft Corporation. All rights reserved.


Shading

This section describes techniques used in Microsoft® Direct3D® to control the shading of 3-D polygons.

  • Shading Modes
  • Comparing Shading Modes
  • Setting the Shading Mode

© 2002 Microsoft Corporation. All rights reserved.


Shading Modes

The shading mode used to render a polygon has a profound effect on its appearance. Shading modes determine the intensity of color and lighting at any point on a polygon face. Microsoft® Direct3D® supports two shading modes.

  • Flat Shading
  • Gouraud Shading

Flat Shading

In the flat shading mode, the Direct3D rendering pipeline renders a polygon, using the color of the polygon material at its first vertex as the color for the entire polygon. 3-D objects that are rendered with flat shading have visibly sharp edges between polygons if they are not coplanar.

The following figure shows a teapot rendered with flat shading. The outline of each polygon is clearly visible. Flat shading is the fastest form of shading.

Rough image of teapot

Gouraud Shading

When Direct3D renders a polygon using Gouraud shading, it computes a color for each vertex by using the vertex normal and lighting parameters. Then, it interpolates the color across the face of the polygons The interpolation is done linearly. For example, if the red component of the color of vertex 1 is 0.8 and the red component of vertex 2 is 0.4, using the Gouraud shading mode and the RGB color model, the Direct3D lighting module assigns a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The following figure demonstrates Gouraud shading. This teapot is composed of many flat, triangular polygons. However, Gouraud shading makes the surface of the object appear curved and smooth.

Smooth imaage of teapot

Gouraud shading can also be used to display objects with sharp edges.

For more information, see Face and Vertex Normal Vectors.

© 2002 Microsoft Corporation. All rights reserved.


Comparing Shading Modes

In flat shading mode, the pyramid below is displayed with a sharp edge between adjoining faces. In Gouraud shading mode, however, shading values are interpolated across the edge, and the final appearance is of a curved surface.

Automatic face normals

Gouraud shading lights flat surfaces more realistically than flat shading. A face in the flat shading mode is a uniform color, but Gouraud shading enables light to fall across a face more correctly. This effect is particularly obvious if there is a nearby point source.

Gouraud shading smoothes the sharp edges between polygons that are visible with flat shading. However, it can result in Mach bands, which are bands of color or light that are not smoothly blended across adjacent polygons. Your application can reduce the appearance of Mach bands by increasing the number of polygons in an object, increasing screen resolution, or increasing the color depth of the application.

Gouraud shading can miss some details. One example is the case shown by the following illustration, in which a spotlight is completely contained within a polygon face.

In this case, Gouraud shading, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.

© 2002 Microsoft Corporation. All rights reserved.


Setting the Shading Mode

Microsoft® Direct3D® enables one shading mode to be selected at a time. By default, Gouraud shading is selected. In C++, you can change the shading mode by calling the IDirect3DDevice9::SetRenderState method. Set the State parameter to D3DRS_SHADEMODE. The State parameter must be set to a member of the D3DSHADEMODE enumeration. The following sample code examples illustrate how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

// Set to flat shading.
// This code example assumes that pDev is a valid pointer to
// an IDirect3DDevice9 interface.
hr = pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

// Set to Gouraud shading. This is the default for Direct3D.
hr = pDev->SetRenderState(D3DRS_SHADEMODE,
                            D3DSHADE_GOURAUD);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

© 2002 Microsoft Corporation. All rights reserved.


Presenting a Scene

This section introduces the presentation application programming interfaces (APIs) and discusses the issues involved in presenting a scene to the display.

Information is divided into the following topics.

  • Introduction to Presenting a Scene
  • Multiple Views in Windowed Mode
  • Multiple-Monitor Operations
  • Manipulating the Depth Buffer
  • Accessing the Color Front Buffer

© 2002 Microsoft Corporation. All rights reserved.


Introduction to Presenting a Scene

The presentation application programming interfaces (APIs) are a set of methods that control the state of the device that affects what the user sees on the monitor. These methods include setting display modes and once-per-frame methods that are used to present images to the user.

  • IDirect3DDevice9::Present
  • IDirect3DDevice9::Reset
  • IDirect3DDevice9::GetGammaRamp
  • IDirect3DDevice9::SetGammaRamp
  • IDirect3DDevice9::GetRasterStatus

Familiarity with the following terms is necessary to understand the presentation APIs.

  • front buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
  • back buffer. A surface whose contents can be promoted to the front buffer.
  • swap chain. A collection of back buffers that can be serially presented to the front buffer. Typically, a full-screen swap chain presents subsequent images with the flipping device driver interface (DDI), and a windowed swap chain presents images with the blitting DDI.

Because Microsoft® Direct3D® for Microsoft DirectX® 9.0 has one swap chain as a property of the device, there is always at least one swap chain per device. The IDirect3DDevice9 interface has a set of methods that manipulate the implicit swap chain and are a copy of the swap chain's own interface. Applications can create additional swap chains; however, this is not necessary for the typical single window or full-screen application.

The front buffer is not directly exposed in the Direct3D API for DirectX 9.0. As a result, applications cannot lock or render to the front buffer. For details, see Accessing the Color Front Buffer.

Note DirectX 7.0 provided a number of presentation APIs that were called together. A good example of this is the IDirectDraw7::SetCooperativeLevel, IDirectDraw7::SetDisplayMode, and IDirectDraw7::CreateSurface sequence. Additionally, the IDirectDrawSurface7::Flip and IDirectDrawSurface7::Blt methods signaled the transport of rendered frames to the monitor. DirectX 9.0 collapses these groups of APIs into two main methods, Reset and Present. Reset subsumes SetCooperativeLevel, SetDisplayMode, CreateSurface, and some of the parameters to flip. Present subsumes flip and the presentation uses of blit.

A call to IDirect3D9::CreateDevice represents an implicit reset of the device. The DirectX 9.0 API has no notion of a primary surface; you cannot create an object that represents the primary surface. It is considered to be an internal property of the device.

Gamma ramps are associated with a swap chain and are manipulated with the IDirect3DDevice9::GetGammaRamp and IDirect3DDevice9::SetGammaRamp methods.

© 2002 Microsoft Corporation. All rights reserved.


Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the Direct3DDevice object, an application can use the IDirect3DDevice9::CreateAdditionalSwapChain method to create additional swap chains to present multiple views from the same device.

Typically, the application creates one swap chain per view, and it associates each swap chain with a particular view. The application renders images in the back buffers of each swap chain, and then uses the IDirect3DDevice9::Present method to present them individually. Note that only one swap chain at a time can be full-screen on each adapter.

© 2002 Microsoft Corporation. All rights reserved.


Multiple-Monitor Operations

When a device is successfully reset (IDirect3DDevice9::Reset) or created (IDirect3D9::CreateDevice) in full-screen operations, the Microsoft® Direct3D® object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D object can neither assume full-screen operations nor allocate video memory. In addition, when a Direct3D object assumes exclusive mode, all devices other than the one that went full-screen are placed in lost state. For details, see Lost Devices.

Along with exclusive mode, the Direct3D object is informed of the focus window that the device will use. Exclusive mode is released when the final full-screen device owned by that Direct3D object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D object owns exclusive mode. The first category of devices have the following characteristics.

  • They are created by the same Direct3D object that created the device that is full-screen.
  • They have the same focus window as the device that is full-screen.
  • They represent a different adapter from any full-screen device.

Devices in this category have no restrictions concerning their ability to be reset or created, and they are not placed in lost state. Devices in this category can even be put into full-screen mode.

Devices that do not fall in the first category—devices created by another Direct3D object, created with a different focus window, and created for an adapter with a device that is already full-screen—cannot be reset and remain in lost state until the exclusive mode is lost. As a result, a multiple-monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D object, and share the same focus window.

© 2002 Microsoft Corporation. All rights reserved.


Manipulating the Depth Buffer

Depth buffers are associated with the device. Applications are required to move the depth buffers when they set render targets. The IDirect3DDevice9::GetDepthStencilSurface and IDirect3DDevice9::SetRenderTarget methods are used to manipulate depth buffers.

© 2002 Microsoft Corporation. All rights reserved.


Accessing the Color Front Buffer

Accessing the front buffer is allowed through the IDirect3DDevice9::GetFrontBufferData method. This method is the only way to get a screen shot of an anti-aliased scene.

© 2002 Microsoft Corporation. All rights reserved.


Rendering Primitives

The following topics introduce the IDirect3DDevice9::DrawPrimitive rendering methods and provide information about using them in your application.

  • Vertex Data Streams
  • Setting the Stream Source
  • Rendering from Vertex and Index Buffers
  • Rendering from User Memory Pointers

© 2002 Microsoft Corporation. All rights reserved.


Vertex Data Streams

The rendering interfaces for Microsoft® Direct3D® consist of methods that render primitives from vertex data stored in one or more data buffers. Vertex data consists of vertex elements combined to form vertex components. Vertex elements, the smallest unit of a vertex, represent entities such as position, normal, or color.

Vertex components are one or more vertex elements stored contiguously (interleaved per vertex) in a single memory buffer. A complete vertex consists of one or more components, where each component is in a separate memory buffer. To render a primitive, multiple vertex components are read and assembled so that complete vertices are available for vertex processing. The illustration below shows the process of rendering primitives using vertex components.

Rendering primitives consists of two steps. First, set up one or more vertex component streams; second, invoke a IDirect3DDevice9::DrawPrimitive method to render from those streams. Identification of vertex elements within these component streams is specified by the vertex shader. For details, see Vertex Shaders.

The IDirect3DDevice9::DrawPrimitive methods specify an offset in the vertex data streams so that an arbitrary contiguous subset of the primitives within one set of vertex data can be rendered with each draw invocation. This enables you to change the device rendering state between groups of primitives that are rendered from the same vertex buffers.

Both indexed and nonindexed drawing methods are supported. For more information, see Rendering from Vertex and Index Buffers.

© 2002 Microsoft Corporation. All rights reserved.


Setting the Stream Source

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on. The Stride parameter specifies the size of the component, in bytes.

© 2002 Microsoft Corporation. All rights reserved.


Rendering from Vertex and Index Buffers

Both indexed and nonindexed drawing methods are supported by Microsoft® Direct3D®. The indexed methods use a single set of indices for all vertex components. Vertex data is presented to the Direct3D application programming interface (API) in vertex buffers, and index data for the indexed drawing methods is presented in index buffers. For more information, see the following reference topics.

  • IDirect3DDevice9::DrawPrimitive
  • IDirect3DDevice9::DrawIndexedPrimitive

These methods draw primitives from the current set of data input streams. For details on setting the current index array to an index buffer, see the IDirect3DDevice9::SetIndices method.

© 2002 Microsoft Corporation. All rights reserved.


Rendering from User Memory Pointers

A secondary set of rendering interfaces supports passing vertex and index data directly from user memory pointers. These interfaces support a single stream of vertex data only. For more information, see the following reference topics.

  • IDirect3DDevice9::DrawPrimitiveUP
  • IDirect3DDevice9::DrawIndexedPrimitiveUP

These methods render with data specified by user memory pointers, instead of vertex and index buffers.

© 2002 Microsoft Corporation. All rights reserved.


Depth Buffers

A depth buffer, often called a z-buffer or a w-buffer, is a property of the device that stores depth information to be used by Microsoft® Direct3D®. When Direct3D renders a 3-D scene to a target surface, it can use the memory in an associated depth-buffer surface as a workspace to determine how the pixels of rasterized polygons occlude one another. Direct3D uses an off-screen Direct3D surface as the target to which final color values are written. The depth-buffer surface that is associated with the render-target surface is used to store depth information that tells Direct3D how deep each visible pixel is in the scene.

When a 3-D scene is rasterized with depth buffering enabled, each point on the rendering surface is tested. The values in the depth buffer can be a point's z-coordinate or its homogeneous w-coordinate—from the point's (x,y,z,w) location in projection space. A depth buffer that uses z values is often called a z-buffer, and one that uses w values is called a w-buffer. Each type of depth buffer has advantages and disadvantages, which are discussed later.

At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. The color value on the rendering surface is set to either the background color value or the color value of the background texture at that point. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value—which will be the z coordinate in a z-buffer, and the w coordinate in a w-buffer—at the current point is tested to see if it is smaller than the depth value stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer and the color value from the polygon is written to the current point on the rendering surface. If the depth value of the polygon at that point is larger, the next polygon in the list is tested. This process is shown in the following illustration.

Note Although most applications don't use this feature, you can change the comparison that Direct3D uses to determine which values are placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRS_ZFUNC render state.

Nearly all 3-D accelerators on the market support z-buffering, making z-buffers the most common type of depth buffer today. However ubiquitous, z-buffers have their drawbacks. Due to the mathematics involved, the generated z values in a z-buffer tend not to be distributed evenly across the z-buffer range (typically 0.0 to 1.0, inclusive). Specifically, the ratio between the far and near clipping planes strongly affects how unevenly z values are distributed. Using a far-plane distance to near-plane distance ratio of 100, 90% of the depth buffer range is spent on the first 10% of the scene depth range. Typical applications for entertainment or visual simulations with exterior scenes often require far-plane/near-plane ratios of anywhere between 1000 to 10000. At a ratio of 1000, 98% of the range is spent on the 1st 2% of the depth range, and the distribution becomes worse with higher ratios. This can cause hidden surface artifacts in distant objects, especially when using 16-bit depth buffers, the most commonly supported bit-depth.

A w-based depth buffer, on the other hand, is often more evenly distributed between the near and far clip planes than a z-buffer. The key benefit is that the ratio of distances for the far and near clipping planes is no longer an issue. This allows applications to support large maximum ranges, while still getting relatively accurate depth buffering close to the eye point. A w-based depth buffer isn't perfect, and can sometimes exhibit hidden surface artifacts for near objects. Another drawback to the w-buffered approach is related to hardware support: w-buffering isn't supported as widely in hardware as z-buffering.

Z-buffering requires overhead during rendering. Various techniques can be used to optimized rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the 3-D renderer.

This section presents information about using depth buffers for hidden line and hidden surface removal.

  • Querying for Depth Buffer Support
  • Creating a Depth Buffer
  • Enabling Depth Buffering
  • Retrieving a Depth Buffer
  • Clearing Depth Buffers
  • Changing Depth Buffer Write Access
  • Changing Depth Buffer Comparison Functions
  • Using Z-Bias

© 2002 Microsoft Corporation. All rights reserved.


Querying for Depth Buffer Support

As with any feature, the driver that your application uses might not support all types of depth buffering. Always check the driver's capabilities. Although most drivers support z-based depth buffering, not all will support w-based depth buffering. Drivers do not fail if you attempt to enable an unsupported scheme. They fall back on another depth buffering method instead, or sometimes disable depth buffering altogether, which can result in scenes rendered with extreme depth-sorting artifacts.

You can check for general support for depth buffers by querying Microsoft® Direct3D® for the display device that your application will use before you create a Direct3D device. If the Direct3D object reports that it supports depth buffering, any hardware devices you create from this Direct3D object will support z-buffering.

To query for depth buffering support, you can use the IDirect3D9::CheckDeviceFormat method, as shown in the following code example.

// The following example assumes that pCaps is a valid pointer to an
// initialized D3DCAPS9 structure.
if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                           pCaps->DeviceType,
                                           AdapterFormat,
                                           D3DUSAGE_DEPTHSTENCIL,
                                           D3DRTYPE_SURFACE,
                                           D3DFMT_D16 ) ) )
    return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 16-bit depth buffers are rejected.

In addition, you can use IDirect3D9::CheckDepthStencilMatch to determine whether a supported depth-stencil format is compatible with the render target format in the display mode, particularly if a depth format must be equal to the render target format.

Using IDirect3D9::CheckDepthStencilMatch to determine depth-stencil compatibility with a render target is illustrated in the following code example.

// Reject devices that cannot create a render target of RTFormat while
// the back buffer is of RTFormat and the depth-stencil buffer is
// at least 8 bits of stencil.
if( FAILED( m_pD3D->CheckDepthStencilMatch( pCaps->AdapterOrdinal,
                                            pCaps->DeviceType,
                                            AdapterFormat,
                                            RTFormat,
                                            D3DFMT_D24S8 ) ) )
    return E_FAIL;

When you know that the driver supports depth buffers, you can verify w-buffer support. Although depth buffers are supported for all software rasterizers, w-buffers are supported only by the reference rasterizer, which is not suited for use by real-world applications. Regardless of the type of device your application uses, verify support for w-buffers before you attempt to enable w-based depth buffering.

  1. After creating your device, call the IDirect3DDevice9::GetDeviceCaps method, passing an initialized D3DCAPS9 structure.
  2. After the call, the LineCaps member contains information about the driver's support for rendering primitives.
  3. If the RasterCaps member of this structure contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.

© 2002 Microsoft Corporation. All rights reserved.


Creating a Depth Buffer

A depth buffer is a property of the device. To create a depth buffer that is managed by Microsoft® Direct3D®, set the appropriate members of the D3DPRESENT_PARAMETERS structure as shown in the following code example.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed               = TRUE;
d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

By setting the EnableAutoDepthStencil member to TRUE, you instruct Direct3D to manage depth buffers for the application. Note that AutoDepthStencilFormat must be set to a valid depth buffer format. The D3DFMT_D16 flag specifies a 16-bit depth buffer, if one is available.

The following call to the IDirect3D9::CreateDevice method creates a device that then creates a depth buffer.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                    &d3dpp, &d3dDevice ) ) )
return E_FAIL;

The depth buffer is automatically set as the render target of the device. When the device is reset, the depth buffer is automatically destroyed and re-created in the new size.

To create a new depth buffer surface, use the IDirect3DDevice9::CreateDepthStencilSurface method.

To set a new depth-buffer surface for the device, use the IDirect3DDevice9::SetRenderTarget method.

To use the depth buffer in your application, you need to enable the depth buffer. For details, see Enabling Depth Buffering.

© 2002 Microsoft Corporation. All rights reserved.


Enabling Depth Buffering

After you create a depth buffer, as described in Creating a Depth Buffer, you enable depth buffering by calling the IDirect3DDevice9::SetRenderState method. Set the D3DRS_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the D3DZBUFFERTYPE enumerated type (or TRUE) to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE(or FALSE) to disable depth buffering.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Microsoft® Direct3D® transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix. The projection matrix discussed in What Is the Projection Transformation? is compliant.

© 2002 Microsoft Corporation. All rights reserved.


Retrieving a Depth Buffer

The following code example shows how to use the IDirect3DDevice9::GetDepthStencilSurface method to retrieve a pointer to the depth-buffer surface owned by the device.

LPDIRECT3DSURFACE9 pZBuffer;

m_d3dDevice->GetDepthStencilSurface( &pZBuffer );

© 2002 Microsoft Corporation. All rights reserved.


Clearing Depth Buffers

Many C++ applications clear the depth buffer before rendering each new frame. You can explicitly clear the depth buffer through Microsoft® Direct3D® by calling IDirect3DDevice9::Clear and specifying D3DCLEAR_ZBUFFER for the Flags parameter. The IDirect3DDevice9::Clear method allows you to specify an arbitrary depth value in the Z parameter.

© 2002 Microsoft Corporation. All rights reserved.


Changing Depth Buffer Write Access

By default, the Microsoft® Direct3D® system is allowed to write to the depth buffer. Most applications leave writing to the depth buffer enabled, but you can achieve some special effects by not allowing the Direct3D system to write to the depth buffer.

You can disable depth buffer writes in C++ by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZWRITEENABLE and the Value parameter set to 0.

© 2002 Microsoft Corporation. All rights reserved.


Changing Depth Buffer Comparison Functions

By default, when depth-testing is performed on a rendering surface, the Microsoft® Direct3D® system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value in the depth buffer. In a C++ application, you change how the system performs comparisons on depth values by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZFUNC. The Value parameter should be set to a value in the D3DCMPFUNC enumerated type.

© 2002 Microsoft Corporation. All rights reserved.


Using Z-Bias

Polygons that are coplanar in your 3-D space can be made to appear as if they are not coplanar by adding a z-bias to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall does. If you render the wall first and then the shadow, the shadow might not be visible, or depth artifacts might be visible. You can reverse the order in which you render the coplanar objects in hopes of reversing the effect, but depth artifacts are still likely.

A C++ application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the IDirect3DDevice9::SetRenderState method just before rendering them, setting the State parameter to D3DRS_DEPTHBIAS, and the Value parameter to a value between 0-16 inclusive. A higher z-bias value increases the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.

© 2002 Microsoft Corporation. All rights reserved.


Fog

Adding fog to a 3-D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Microsoft® Direct3D® supports two fog models, pixel fog and vertex fog, each with its own features and programming interface.

Essentially, fog is implemented by blending the color of objects in a scene with a chosen fog color based on the depth of an object in a scene or its distance from the viewpoint. As objects grow more distant, their original color blends more and more with the chosen fog color, creating the illusion that the object is being increasingly obscured by tiny particles floating in the scene. The following illustration shows a scene rendered without fog, and a similar scene rendered with fog enabled.

In this illustration, the scene on the left has a clear horizon, beyond which no scenery is visible, even though it would be visible in the real world. The scene on the right obscures the horizon by using a fog color identical to the background color, making polygons appear to fade into the distance. By combining discrete fog effects with creative scene design you can add mood and soften the color of objects in a scene.

Direct3D provides two ways to add fog to a scene: pixel fog and vertex fog, named for how the fog effects are applied. For details, see Pixel Fog and Vertex Fog. In short, pixel fog - also called table fog - is implemented in the device driver and vertex fog is implemented in the Direct3D lighting engine. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

Note Regardless of whether you use pixel or vertex fog, your application must provide a compliant projection matrix to ensure that fog effects are properly applied. This restriction applies even to applications that do not use the Direct3D transformation and lighting engine. For additional details about how you can provide an appropriate matrix, see A W-Friendly Projection Matrix.

The following topics introduce fog and present information about using various fog features in Direct3D applications.

  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Vertex Fog
  • Pixel Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.

© 2002 Microsoft Corporation. All rights reserved.


Alpha Blending

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

Color can be defined with or without alpha values. Color without alpha is RGB, color with alpha is RGBA. Vertex data, material data and texture data can be used to give object's transparency. The frame buffer can also be used to generate transparency effects.

  • Vertex Alpha
  • Material Alpha
  • Texture Alpha
  • Frame Buffer Alpha
  • Render Target Alpha

Samples that demonstrate alpha include:

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions

© 2002 Microsoft Corporation. All rights reserved.


Vertex Alpha

Alpha data can be supplied in the vertex data. To enable vertex alpha, set the D3DRENDERSTATE_DIFFUSEMATERIALSOURCE to D3DMCS_COLOR1 so that the Microsoft® Direct3D® runtime takes the diffuse value from the diffuse color rather than the material.

m_pd3dDevice->SetRenderState( D3DRENDERSTATE_DIFFUSEMATERIALSOURCE,
                              D3DMCS_COLOR1 );

Then, provide alpha values in the diffuse color. The AddAlphaToASphere function, adds alpha to the vertices of a sphere. Here's an example of how to provide the alpha information to the function.

AddAlphaToASphere( m_pObstacleVertices, 12,
           D3DRGBA(light.dcvDiffuse.r, light.dcvDiffuse.g,
                   light.dcvDiffuse.b, vAlpha ));

This is what the function looks like.

void AddAlphaToASphere(D3DLVERTEX* pVertices, DWORD dwNumRings, D3DCOLOR lightcolor)
{
 WORD x, y;
 // rings around
    for( y=0; y < dwNumRings; y++ )
        for( x=0; x < (dwNumRings*2)+1; x++ )
            (pVertices++)->color = lightcolor;

 // top and bottom
    (pVertices++)->color = lightcolor;
    (pVertices++)->color = lightcolor;
}

AddAlphaToASphere simply modifies the color member of each vertex, which are of type D3DLVERTEX, to include the alpha information.

D3DLVERTEX looks like this.

// Lit vertex
typedef struct {
 D3DVALUE x, y, z;
 DWORD dwReserved;
 D3DCOLOR color, specular;
 D3DVALUE tu, tv;
} D3DLVERTEX, *LPD3DLVERTEX;

Drawing the sphere,

  // Draw the lit sphere
 m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
                              m_pObstacleVertices, m_dwNumObstacleVertices,
                              m_pObstacleIndices,  m_dwNumObstacleIndices, 0 );

results in a transparent sphere using vertex alpha.

© 2002 Microsoft Corporation. All rights reserved.


Material Alpha

Alpha can also be supplied in a material. To enable material alpha, set the D3DRENDERSTATE_DIFFUSEMATERIALSOURCE to D3DMCS_MATERIAL so that the Microsoft® Direct3D® runtime takes the diffuse value from the material color rather than the diffuse vertex element.

   m_pd3dDevice->SetRenderState( D3DRENDERSTATE_DIFFUSEMATERIALSOURCE,   D3DMCS_MATERIAL );

Initialize the material with an alpha value to generate transparency.

mAlpha = 0.5f;
D3DUtil_InitMaterial( m_mtrl,
light.dcvDiffuse.r, light.dcvDiffuse.g, light.dcvDiffuse.b, mAlpha );

Then draw a transparent sphere using material alpha.

// Draw the lit sphere.
m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
                       m_pObstacleVertices, m_dwNumObstacleVertices,
                       m_pObstacleIndices,  m_dwNumObstacleIndices, 0 );

© 2002 Microsoft Corporation. All rights reserved.


Texture Alpha

Alpha can also be provided with textures. First, the texture must be created. Then it must be set on a texture stage and the appropriate stage operation and operands selected. Then, the primitive can be drawn with transparency.

// Create an alpha texture
CreateEmptyTexture( "gradient", 128,128,0,D3DTEXTR_32BITSPERPIXEL|D3DTEXTR_CREATEWITHALPHA);

LoadGradient( "gradient" );

The body of these routines does the work. CreateEmptyTexture sets everything up by creating an empty texture.

HRESULT LoadGradient( TCHAR* strName )
{
    TextureContainer* ptcTexture = FindTexture( strName );

    // Load a gradient
    return ptcTexture->LoadGradient32( strName );
}

It calls LoadGradient32 to load the alpha channel when it has performed a texture lookup.

HRESULT TextureContainer::LoadGradient32( TCHAR* strPathname )
{
 int  yGrad, xGrad;
 // w x h set in createempty
    m_pRGBAData = new DWORD[m_dwWidth*m_dwHeight];

    if( m_pRGBAData == NULL )
    {
        return E_FAIL;
    }

    for( DWORD y=0; y < m_dwHeight; y++ )
    {
        DWORD dwOffset = y*m_dwWidth;
        yGrad = (int)(((float)y/(float)m_dwWidth) * 255.0f);

        for( DWORD x=0; x < m_dwWidth; x )
        {
            xGrad = (int)(((float)x/(float)m_dwWidth) * 255.0f);

            DWORD b = (DWORD)(xGrad + (255 - yGrad))/2 & 0xFF;
            DWORD g = (DWORD)((255 - xGrad) + yGrad)/2 & 0xFF;
            DWORD r = (DWORD)(xGrad + yGrad)/2 & 0xFF;
            DWORD a = (DWORD)(xGrad + yGrad)/2 & 0xFF;

            m_pRGBAData[dwOffset+x] = (r<<24L)+(g<<16L)+(b<<8L)+(a);
            x++;
        }
    }

    return S_OK;
}

The alpha value is calculated based on the current pixel's relative x/y position within the texture size.

Next, assign the texture to a texture stage and set up the texture stage.

// Assign texture
m_pd3dDevice->SetTexture( 0, D3DTextr_GetSurface("gradient") );

// Texture stage states
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );

m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );

m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );

m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );

// Draw the lit sphere
m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
                              m_pObstacleVertices, m_dwNumObstacleVertices,
                              m_pObstacleIndices,  m_dwNumObstacleIndices, 0 );

This results in a transparent, textured sphere.

© 2002 Microsoft Corporation. All rights reserved.


Frame Buffer Alpha

Frame buffer alpha-blending is a bit different than vertex alpha, material alpha, and texture alpha. Vertex, material, and texture alpha set transparency values that are used only for the current primitive, and by themselves have no effect on other primitives. Frame buffer alpha-blending controls how the current primitive is combined with existing pixels in the frame buffer to yield a final pixel color.

When performing alpha blending, two colors are being combined: a source color and a destination color. The source color is from the transparent object, the destination color is the color already at the pixel location. The destination color is the result of rendering some other object that is behind the transparent object, that is, the object that will be visible through the transparent object. Alpha blending uses a formula to control the ratio between the source and destination objects.

Final Color = ObjectColor * SourceBlendFactor + PixelColor * DestinationBlendFactor

ObjectColor is the contribution from the primitive being rendered at the current pixel location. PixelColor is the contribution from the frame buffer at the current pixel location.

The set of alpha blend factors that can be used are listed below.

Blend mode factor | Description
D3DBLEND_ZERO | (0, 0, 0, 0)
D3DBLEND_ONE | (1, 1, 1, 1)
D3DBLEND_SRCCOLOR | (Rs, Gs, Bs, As)
D3DBLEND_INVSRCCOLOR | (1-Rs, 1-Gs, 1-Bs, 1-As)
D3DBLEND_SRCALPHA | (As, As, As, As)
D3DBLEND_INVSRCALPHA | (1-As, 1-As, 1-As, 1-As)
D3DBLEND_DESTALPHA | (Ad, Ad, Ad, Ad)
D3DBLEND_INVDESTALPHA | (1-Ad, 1-Ad, 1-Ad, 1-Ad)
D3DBLEND_DESTCOLOR | (Rd, Gd, Bd, Ad)
D3DBLEND_INVDESTCOLOR | (1-Rd, 1-Gd, 1-Bd, 1-Ad)
D3DBLEND_SRCALPHASAT | (f, f, f, 1); f = min(As, 1-Ad)
D3DBLEND_BOTHSRCALPHA | Obsolete for Microsoft® DirectX® 6.0 and later. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA | Obsolete for DirectX 6.0. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_INVSRCALPHA and D3DBLEND_SRCALPHA in separate calls.
D3DBLEND_BLENDFACTOR | Use color.r, color.g, color.b, and color.a obtained from the D3DRS_BLENDFACTOR setting.
D3DBLEND_INVBLENDFACTOR | Use 1-color.r, 1-color.g, 1-color.b, and 1-color.a obtained from the D3DRS_BLENDFACTOR setting.

Microsoft Direct3D® uses the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code fragment sets the source blend state to D3DBLEND_SRCCOLOR and the destination blend state to D3DBLEND_INVSRCCOLOR.

// This code fragment assumes that lpD3DDevice is a
//   valid pointer to a device.

// Enable alpha blending.
lpD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,
                            TRUE);

// Set the source blend state.
lpD3DDevice->SetRenderState(D3DRS_SRCBLEND,
                            D3DBLEND_SRCCOLOR);

// Set the destination blend state.
lpD3DDevice->SetRenderState(D3DRS_DESTBLEND,
                            D3DBLEND_INVSRCCOLOR);

This code performs a linear blend between the source color (the color of the primitive being rendered at the current location) and the destination color (the color at the current location in the frame buffer). The resulting appearance is similar to tinted glass in that some of the color of the destination object seems to be transmitted through the source object; the rest of it appears to be absorbed.

Many of these blend factors require alpha values in the texture to operate correctly. Thus, when using vertex or material alpha, the application is restricted as to which modes will produce interesting results.

© 2002 Microsoft Corporation. All rights reserved.


Render Target Alpha

The frame buffer blender can now blend alpha channels independent from color-channel blending on render targets. This control is enabled with a new render state, D3DRS_SEPARATEALPHABLENDENABLE.

When D3DRS_SEPARATEALPHABLENDENABLE is set to FALSE (which is the default condition), the render target blending factors and operations applied to alpha are the same as those defined for blending color channels. A driver needs to set the D3DPMISCCAPS_SEPARATEALPHABLEND cap to indicate that it can support render target alpha blending. Be sure to enable D3DRS_ALPHABLEND to tell the pipeline that alpha blending is needed.

To control the factors in the alpha channel of the render target blenders, two new render states are defined as follows:

D3DRS_SRCBLENDALPHA
D3DRS_DESTBLENDALPHA

Like the D3DRS_SRCBLEND and D3DRS_DESTBLEND, these can be set to one of the values in the D3DBLEND enumeration. The source and destination blend settings can be combined in several ways, depending on the settings in the SrcBlendCaps and DestBlendCaps members of D3DCAPS9.

The alpha blending is done as follows:

renderTargetAlpha = (alphain* srcBlendOp) BlendOp (alphart* destBlendOp)

Where:

  • alphain is the input alpha value.
  • srcBlendOp is one of the blend factors in D3DBLEND.
  • BlendOp is one of the blend factors in D3DBLEND.
  • alphart is the render target alpha value.
  • destBlendOp is one of the blend factors in D3DBLEND.
  • renderTargetAlpha is the final blended alpha value.

© 2002 Microsoft Corporation. All rights reserved.


Line Drawing

Support for single-pixel-wide antialiased lines has been added to the existing support for single-pixel-wide aliased lines.

Setting the D3DRS_ANTIALIASEDLINEENABLE render state to TRUE enables line antialiasing. For the best performance, it is FALSE by default. This applies to triangles drawn in wireframe mode as well as line drawing primitive types. When rendering to a multisample render target, the render state is ignored and all lines are rendered aliased. (To achieve antialiased line rendering for multisample render targets, an application can use the Direct3D extensions (D3DX) antialiased line rendering support, which generates textured polygons.) See Direct3D Extentions (D3DX) Line Drawing.

Support for line patterns is removed. The D3DRS_LINEPATTERN render state is no longer supported.

API Changes

There is a new render state and a new caps bit.

    // New RenderState
    D3DRS_ANTIALIASEDLINEENABLE
    // Can be TRUE (nonzero) or FALSE (zero)

    // New capability bit
    D3DLINECAPS_ANTIALIAS

There are also some render states that are no longer supported.

    // Deleted: D3DRS_LINEPATTERN
    // Deleted: struct D3DLINEPATTERN
    // Deleted: D3DPMISCCAPS_LINEPATTERNREP

© 2002 Microsoft Corporation. All rights reserved.


Fixed Function Pipeline

The part of Microsoft® Direct3D® that pushes geometry through the fixed function geometry pipeline is the transformation engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transformation engine also performs lighting computations to determine diffuse and specular components at each vertex.

  • Vertex and Pixel Processing
  • Vertex Formats
  • Transforms
  • Viewports and Clipping
  • Lights and Materials
  • Textures

© 2002 Microsoft Corporation. All rights reserved.


Vertex and Pixel Processing

The part of Microsoft® Direct3D® that pushes geometry through the fixed function geometry pipeline is the transformation engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transformation engine also performs lighting computations to determine diffuse and specular components at each vertex.

The geometry pipeline takes vertices as input. The transformation engine applies three transformations - the world, view, and projection transformations - to the vertices, clips the result, and passes everything to the rasterizer. The following image illustrates the sequence of steps.

At the head of the pipeline, no transformations have been applied, so all of a model's vertices are declared relative to a local coordinate system - this is a local origin and an orientation. This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.

The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transformation. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates.

In the next stage, the vertices that describe your 3-D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transformation.

The next stage is the projection transformation. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. For simplicity, this documentation refers to the space in which vertices exist after the projection transformation as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transformations scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.

In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices - seen on the screen when the scene is rasterized - exist in screen space.

  • Legacy FVF Format

© 2002 Microsoft Corporation. All rights reserved.


Legacy FVF Format

To use legacy flexible vertex format (FVF) formats, use an FVF when calling the IDirect3DDevice9::SetFVF method as shown in the code example below.

g_d3dDevice->SetFVF( CUSTOM_FVF );

This following topics cover legacy FVF format types.

  • LVertex Legacy Type
  • TLVertex Legacy Type
  • Vertex Legacy Type

© 2002 Microsoft Corporation. All rights reserved.


Vertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, a normal, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

struct Vertex
{
    FLOAT x, y, z;
    FLOAT nx, ny, nz;
    FLOAT tu, tv;
};

const DWORD VertexFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice9::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer(
                 4*sizeof(Vertex), VertexFVF,
                 D3DUSAGE_WRITEONLY,
                 D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

Vertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].nx = 0.0f;  v[0].ny = 1.0f;  v[0].nz = 0.0f;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].nx = 0.0f;  v[1].ny = 1.0f;  v[1].nz = 0.0f;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].nx = 0.0f;  v[2].ny = 1.0f;  v[2].nz = 0.0f;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].nx = 0.0f; v[3].ny = 1.0f;   v[3].nz = 0.0f;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy flexible vertex format (FVF) to draw a square.

g_d3dDevice->SetFVF( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(Vertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to IDirect3DDevice9::SetFVF specifies a legacy FVF with stream 0.

© 2002 Microsoft Corporation. All rights reserved.


LVertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and flexible vertex format (FVF) as shown in the code example below.

struct LVertex
{
    FLOAT    x, y, z;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZ | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice9::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer( 4*sizeof(LVertex), VertexFVF,
                 D3DUSAGE_WRITEONLY, D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

LVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.

g_d3dDevice->SetFVF( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(LVertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to IDirect3DDevice9::SetFVF method specifies a legacy FVF and that stream 0 is the only valid stream.

© 2002 Microsoft Corporation. All rights reserved.


TLVertex Legacy Type

The topic shows the steps necessary to initialize and use vertices that have a transformed position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and flexible vertex format (FVF) as shown in the code example below.

struct TLVertex
{
    FLOAT    x, y, z, rhw;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZRHW | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice9::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer( 4*sizeof(TLVertex), VertexFVF,
                 D3DUSAGE_WRITEONLY, D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

TLVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f; v[0].rhw = 1.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f; v[1].rhw = 1.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f; v[2].rhw = 1.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f; v[3].rhw = 1.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.

g_d3dDevice->SetFVF( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(TLVertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to IDirect3DDevice9::SetFVF specifies a legacy FVF with stream 0.

© 2002 Microsoft Corporation. All rights reserved.


Transforms

Transformations are used to convert object geoemtry from one coordinate space to another. The most common transformations are done using matrices. A matrix is an essential tool for holding the transformation values and applying them to the data. The topics below introduce matrices, and explain how to use them to generate the world, view and projection transformations.

  • Matrices
  • World Transformation

    Convert from world coordinates to view coordinates

  • View Transformation

    Convert from view coordinates to projection coordinates

  • Projection Transformation

    Convert from projection coordinates to screen coordinates

© 2002 Microsoft Corporation. All rights reserved.


Matrices

Microsoft® Direct3D® uses matrices to perform 3-D transformations. This section explains how matrices create 3-D transformations, describes some common uses for transformations, and details how you can combine matrices to produce a single matrix that encompasses multiple transformations. Information is divided into the following topics.

  • 3-D Transformations
  • Translation and Scaling
  • Rotation
  • Matrix Concatenation

© 2002 Microsoft Corporation. All rights reserved.


3-D Transformations

In applications that work with 3-D graphics, you can use geometrical transformations to do the following:

  • Express the location of an object relative to another object.
  • Rotate and size objects.
  • Change viewing positions, directions, and perspectives.

You can transform any point (x,y,z) into another point (x', y', z') using a 4 by 4 matrix.

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z').

The most common transformations are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transformations at once. For example, you can build a single matrix to translate and rotate a series of points. For more information, see Matrix Concatenation.

Matrices are written in row-column order. A matrix that evenly scales vertices along each axis, known as uniform scaling, is represented by the following matrix using mathematical notation.

In C++, Microsoft® Direct3D® declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix.

// In this example, s is a variable of type float.

D3DMATRIX scale = {
    s,               0.0f,            0.0f,            0.0f,
    0.0f,            s,               0.0f,            0.0f,
    0.0f,            0.0f,            s,               0.0f,
    0.0f,            0.0f,            0.0f,            1.0f
};

© 2002 Microsoft Corporation. All rights reserved.


Translation and Scaling

Translation

The following transformation translates the point (x, y, z) to a new point (x', y', z').

You can create a translation matrix by hand in C++. The following example shows the source code for a function that creates a matrix to translate vertices.

D3DXMATRIX Translate(const float dx, const float dy, const float dz) {
    D3DXMATRIX ret;

    D3DXMatrixIdentity(&ret);  // Implemented by Direct3D extensions (D3DX)
    ret(3, 0) = dx;
    ret(3, 1) = dy;
    ret(3, 2) = dz;
    return ret;
}    // End of Translate

For convenience, the Direct3D extensions (D3DX) utility library supplies the D3DXMatrixTranslation function.

Scaling

The following transformation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').

© 2002 Microsoft Corporation. All rights reserved.


Rotation

The transformations described here are for left-handed coordinate systems, and so may be different from transformation matrices that you have seen elsewhere. For more information, see 3-D Coordinate Systems.

The following transformation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').

x rotation matrix

The following transformation rotates the point around the y-axis.

y rotation matrix

The following transformation rotates the point around the z-axis.

z rotation matrix

In these example matrices, the Greek letter theta (?) stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

In a C++ application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the Direct3D extensions (D3DX) utility library to create rotation matrices. The following is the code for the D3DXMatrixRotationX function.

D3DXMATRIX* WINAPI D3DXMatrixRotationX
    ( D3DXMATRIX *pOut, float angle )
{
#if DBG
    if(!pOut)
        return NULL;
#endif

    float sin, cos;
    sincosf(angle, &sin, &cos);  // Determine sin and cos of angle.

    pOut->_11 = 1.0f; pOut->_12 =  0.0f;   pOut->_13 = 0.0f; pOut->_14 = 0.0f;
    pOut->_21 = 0.0f; pOut->_22 =  cos;    pOut->_23 = sin;  pOut->_24 = 0.0f;
    pOut->_31 = 0.0f; pOut->_32 = -sin;    pOut->_33 = cos;  pOut->_34 = 0.0f;
    pOut->_41 = 0.0f; pOut->_42 =  0.0f;   pOut->_43 = 0.0f; pOut->_44 = 1.0f;

    return pOut;
}

© 2002 Microsoft Corporation. All rights reserved.


Matrix Concatenation

One advantage of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following formula.

Matrix concatenation formula

In this formula, C is the composite matrix being created, and M1 through Mn are the individual transformations that matrix C contains. In most cases, only two or three matrices are concatenated, but there is no limit.

Use the D3DXMatrixMultiply function to perform matrix multiplication.

The order in which the matrix multiplication is performed is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world transformation matrix is shown in the following example. Imagine that you are creating the world transformation matrix for a stereotypical flying saucer. You would probably want to spin the flying saucer around its center - the y-axis of model space - and translate it to some other location in your scene. To accomplish this effect, you first create a rotation matrix, and then multiply it by a translation matrix, as shown in the following formula.

In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.

The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order has the visual effect of translating the flying saucer to its world space position, and then rotating it around the world origin.

No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.

© 2002 Microsoft Corporation. All rights reserved.


World Transformation

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transformation matrix in a Microsoft® Direct3D® application.

What Is a World Transformation?

A world transformation changes coordinates from model space, where vertices are defined relative to a model's local origin, to world space, where vertices are defined relative to an origin common to all the objects in a scene. In essence, the world transformation places a model into the world; hence its name. The following diagram illustrates the relationship between the world coordinate system and a model's local coordinate system.

The world transformation can include any combination of translations, rotations, and scalings. For a discussion of the mathematics of transformations, see 3-D Transformations.

Setting Up a World Matrix

As with any other transformation, you create the world transformation by concatenating a series of transformation matrices into a single matrix that contains the sum total of their effects. In the simplest case, when a model is at the world origin and its local coordinate axes are oriented the same as world space, the world matrix is the identity matrix. More commonly, the world matrix is a combination of a translation into world space and possibly one or more rotations to turn the model as needed.

The following example, from a fictitious 3-D model class written in C++, uses the helper functions included in the Direct3D extensions (D3DX) utility library to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

/*
 * For the purposes of this example, the following variables
 * are assumed to be valid and initialized.
 *
 * The m_xPos, m_yPos, m_zPos variables contain the model's
 * location in world coordinates.
 *
 * The m_fPitch, m_fYaw, and m_fRoll variables are floats that
 * contain the model's orientation in terms of pitch, yaw, and roll
 * angles, in radians.
 */

void C3DModel::MakeWorldMatrix( D3DXMATRIX* pMatWorld )
{
    D3DXMATRIX MatTemp;  // Temp matrix for rotations.
    D3DXMATRIX MatRot;   // Final rotation matrix, applied to
                         // pMatWorld.

    // Using the left-to-right order of matrix concatenation,
    // apply the translation to the object's world position
    // before applying the rotations.
    D3DXMatrixTranslation(pMatWorld, m_xPos, m_yPos, m_zPos);
    D3DXMatrixIdentity(&MatRot);

    // Now, apply the orientation variables to the world matrix
    if(m_fPitch || m_fYaw || m_fRoll) {
        // Produce and combine the rotation matrices.
        D3DXMatrixRotationX(&MatTemp, m_fPitch);         // Pitch
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationY(&MatTemp, m_fYaw);           // Yaw
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationZ(&MatTemp, m_fRoll);          // Roll
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);

        // Apply the rotation matrices to complete the world matrix.
        D3DXMatrixMultiply(pMatWorld, &MatRot, pMatWorld);
    }
}

After you prepare the world transformation matrix, call the IDirect3DDevice9::SetTransform method to set it, specifying the D3DTS_WORLD macro for the first parameter.

Note Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, thousands of times per frame—is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity, in this documentation Direct3D samples rarely employ this optimization.

© 2002 Microsoft Corporation. All rights reserved.


View Transformation

This section introduces the basic concepts of the view transformation and provides details on how to set up a view transformation matrix in a Microsoft® Direct3D® application. This information is organized into the following topics.

  • What Is a View Transformation?
  • Setting Up a View Matrix

What Is a View Transformation?

The view transformation locates the viewer in world space, transforming vertices into camera space. In camera space, the camera, or viewer, is at the origin, looking in the positive z-direction. Recall that Direct3D uses a left-handed coordinate system, so z is positive into a scene. The view matrix relocates the objects in the world around a camera's position—the origin of camera space—and orientation.

There are many ways to create a view matrix. In all cases, the camera has some logical position and orientation in world space that is used as a starting point to create a view matrix that will be applied to the models in a scene. The view matrix translates and rotates objects to place them in camera space, where the camera is at the origin. One way to create a view matrix is to combine a translation matrix with rotation matrices for each axis. In this approach, the following general matrix formula applies.

In this formula, V is the view matrix being created, T is a translation matrix that repositions objects in the world, and Rx through Rz are rotation matrices that rotate objects along the x-, y-, and z-axis. The translation and rotation matrices are based on the camera's logical position and orientation in world space. So, if the camera's logical position in the world is <10,20,100>, the aim of the translation matrix is to move objects -10 units along the x-axis, -20 units along the y-axis, and -100 units along the z-axis. The rotation matrices in the formula are based on the camera's orientation, in terms of how the much the axes of camera space are rotated out of alignment with world space. For example, if the camera mentioned earlier is pointing straight down, its z-axis is 90 degrees (pi/2 radians) out of alignment with the z-axis of world space, as shown in the following illustration.

The rotation matrices apply rotations of equal, but opposite, magnitude to the models in the scene. The view matrix for this camera includes a rotation of -90 degrees around the x-axis. The rotation matrix is combined with the translation matrix to create a view matrix that adjusts the position and orientation of the objects in the scene so that their top is facing the camera, giving the appearance that the camera is above the model.

Setting Up a View Matrix

The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions create a view matrix based on the camera location and a look-at point.

The following example creates a view matrix for right handed coordinates.

D3DXMATRIX out;
D3DXVECTOR3 eye(2,3,3);
D3DXVECTOR3 at(0,0,0);
D3DXVECTOR3 up(0,1,0);
D3DXMatrixLookAtRH(&out, &eye, &at, &up);

Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. For clarity, the samples rarely employ this optimization.

© 2002 Microsoft Corporation. All rights reserved.


Projection Transformation

You can think of the projection transformation as controlling the camera's internals; it is analogous to choosing a lens for the camera. This is the most complicated of the three transformation types. This discussion of the projection transformation is organized into the following topics.

  • What Is the Projection Transformation?
  • Setting Up a Projection Matrix
  • A W-Friendly Projection Matrix

© 2002 Microsoft Corporation. All rights reserved.


What Is the Projection Transformation?

The projection matrix is typically a scale and perspective projection. The projection transformation converts the viewing frustum into a cuboid shape. Because the near end of the viewing frustum is smaller than the far end, this has the effect of expanding objects that are near to the camera; this is how perspective is applied to the scene.

In the viewing frustum, the distance between the camera and the origin of the viewing transformation space is defined arbitrarily as D, so the projection matrix looks like:

The viewing matrix translates the camera to the origin by translating in the z direction by - D. The translation matrix is as follows:

Multiplying the translation matrix by the projection matrix (T*P) gives the composite projection matrix. It looks like:

The following illustration shows how the perspective transformation converts a viewing frustum into a new coordinate space. Notice that the frustum becomes cuboid and also that the origin moves from the upper-right corner of the scene to the center.

In the perspective transformation, the limits of the x- and y-directions are -1 and 1. The limits of the z-direction are 0 for the front plane and 1 for the back plane.

This matrix translates and scales objects based on a specified distance from the camera to the near clipping plane, but it doesn't consider the field of view (fov), and the z-values that it produces for objects in the distance can be nearly identical, making depth comparisons difficult. The following matrix addresses these issues, and it adjusts vertices to account for the aspect ratio of the viewport, making it a good choice for the perspective projection.

In this matrix, Zn is the z-value of the near clipping plane. The variables w, h, and Q have the following meanings. Note that fovw and fovk represent the viewport's horizontal and vertical fields of view, in radians.

For your application, using field-of-view angles to define the x- and y-scaling coefficients might not be as convenient as using the viewport's horizontal and vertical dimensions (in camera space). As the math works out, the following two formulas for w and h use the viewport's dimensions, and are equivalent to the preceding formulas.

In these formulas, Zn represents the position of the near clipping plane, and the Vw and Vh variables represent the width and height of the viewport, in camera space.

For a C++ application, these two dimensions correspond directly to the Width and Height members of the D3DVIEWPORT9 structure.

Whatever formula you decide to use, be sure to set Zn to as large a value as possible, because z-values extremely close to the camera don't vary by much. This makes depth comparisons using 16-bit z-buffers somewhat complicated.

As with the world and view transformations, you call the IDirect3DDevice9::SetTransform method to set the projection transformation. For more information.

© 2002 Microsoft Corporation. All rights reserved.


Setting Up a Projection Matrix

The following ProjectionMatrix sample function sets the front and back clipping planes, as well as the horizontal and vertical field of view angles. This code parallels the approach discussed in the What Is the Projection Transformation? topic. The fields of view should be less than pi radians.

D3DXMATRIX
ProjectionMatrix(const float near_plane, // Distance to near clipping
                                         // plane
                 const float far_plane,  // Distance to far clipping
                                         // plane
                 const float fov_horiz,  // Horizontal field of view
                                         // angle, in radians
                 const float fov_vert)   // Vertical field of view
                                         // angle, in radians
{
    float    h, w, Q;

    w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
    h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
    Q = far_plane/(far_plane - near_plane);

    D3DXMATRIX ret;
    ZeroMemory(&ret, sizeof(ret));

    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // End of ProjectionMatrix

After creating the matrix, set it with IDirect3DDevice9::SetTransform specifying D3DTS_PROJECTION.

The Direct3D extensions (D3DX) utility library provides the following functions to help you set up your projections matrix.

  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH

© 2002 Microsoft Corporation. All rights reserved.


A W-Friendly Projection Matrix

Microsoft® Direct3D® can use the w-component of a vertex that has been transformed by the world, view, and projection matrices to perform depth-based calculations in depth-buffer or fog effects. Computations such as these require that your projection matrix normalize w to be equivalent to world-space z. In short, if your projection matrix includes a (3,4) coefficient that is not 1, you must scale all the coefficients by the inverse of the (3,4) coefficient to make a proper matrix. If you don't provide a compliant matrix, fog effects and depth buffering are not applied correctly. The projection matrix recommended in What Is the Projection Transformation? is compliant with w-based calculations.

The following illustration shows a noncompliant projection matrix, and the same matrix scaled so that eye-relative fog will be enabled.

In the preceding matrices, all variables are assumed to be nonzero. For more information about eye-relative fog, see Eye-Relative vs. Z-Based Depth. For information about w-based depth buffering, see Depth Buffers.

Note Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use the Direct3D transformation pipeline.

© 2002 Microsoft Corporation. All rights reserved.


Viewports and Clipping

Conceptually, a viewport is a two-dimensional (2-D) rectangle into which a three-dimensional (3-D) scene is projected. In Microsoft® Direct3D®, the rectangle exists as coordinates within a Direct3D surface that the system uses as a rendering target. The projection transformation converts vertices into the coordinate system used for the viewport.

You use a viewport in Direct3D to specify the following features in your application.

  • The screen-space viewport to which the rendering will be confined.
  • The range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).

This section discusses clipping, the last stage of the geometry pipeline. The discussion is organized into the following topics.

  • Viewport Rectangle
  • The Viewing Frustum
  • Clipping Volumes
  • Viewport Scaling
  • Using Viewports

Direct3D implements clipping by way of a set of viewport parameters set in the device.

© 2002 Microsoft Corporation. All rights reserved.


Viewport Rectangle

You define the viewport rectangle in C++ by using the D3DVIEWPORT9 structure. The D3DVIEWPORT9 structure is used with the following viewport manipulation methods exposed by the IDirect3DDevice9 interface.

  • IDirect3DDevice9::GetViewport
  • IDirect3DDevice9::SetViewport

The D3DVIEWPORT9 structure contains four members—X, Y, Width, and Height—that define the area of the render-target surface into which a scene will be rendered. These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the X, Y, Width, and Height members of the D3DVIEWPORT9 structure are screen coordinates relative to the upper-left corner of the render-target surface. The structure defines two additional members (MinZ and MaxZ) that indicate the depth-ranges into which the scene will be rendered.

Microsoft® Direct3D® assumes that the viewport clipping volume ranges from -1.0 to 1.0 in X, and from 1.0 to -1.0 in Y. These were the settings used most often by applications in the past. During the projection transformation, you can adjust for viewport aspect ratio before clipping. This task is covered by topics in Projection Transformation section.

Note The D3DVIEWPORT9 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

© 2002 Microsoft Corporation. All rights reserved.


The Viewing Frustum

A viewing frustum is 3-D volume in a scene positioned relative to the viewport's camera. The shape of the volume affects how models are projected from camera space onto the screen. The most common type of projection, a perspective projection, is responsible for making objects near the camera appear bigger than objects in the distance. For perspective viewing, the viewing frustum can be visualized as a pyramid, with the camera positioned at the tip. This pyramid is intersected by a front and back clipping plane. The volume within the pyramid between the front and back clipping planes is the viewing frustum. Objects are visible only when they are in this volume.

If you imagine that you are standing in a dark room and looking through a square window, you are visualizing a viewing frustum. In this analogy, the near clipping plane is the window, and the back clipping plane is whatever finally interrupts your view—the skyscraper across the street, the mountains in the distance, or nothing at all. You can see everything inside the truncated pyramid that starts at the window and ends with whatever interrupts your view, and you can see nothing else.

The viewing frustum is defined by fov (field of view) and by the distances of the front and back clipping planes, specified in z-coordinates.

In this illustration, the variable D is the distance from the camera to the origin of the space that was defined in the last part of the geometry pipeline—the viewing transformation. This is the space around which you arrange the limits of your viewing frustum. For information about how this D variable is used to build the projection matrix, see What Is the Projection Transformation?

© 2002 Microsoft Corporation. All rights reserved.


Clipping Volumes

The results of the projection matrix determine the clipping volume in projection space. Microsoft® Direct3D® defines the clipping volume in projection space as:

In the preceding formulas, X, Y, Z, and W represent the vertex coordinates after the projection transformation is applied. Any vertices that have an x-, y-, or z-component outside these ranges are clipped, if clipping is enabled (the default behavior).

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRS_CLIPPING render state. Clipping information for vertex buffers is generated during processing, for more information see Fixed Function Vertex Processing and Programmable Vertex Processing.

Direct3D does not clip transformed vertices of a primitive from a vertex buffer unless it comes from IDirect3DDevice9::ProcessVertices. If you are doing your own transforms and need Direct3D to do the clipping you should not use vertex buffers; in this case, the application traverses the data to transform it, Direct3D traverses the data a second time to clip it, and then the driver renders the data which is inefficient. So, if the application transforms the data is should also clip the data.

When the device receives pre-transformed and lit vertices (TL-vertices) that need to be clipped, in order to perform the clipping operation, the vertices are back transformed to the clipping space using the vertex's rhw and the viewport information. Clipping is then performed. Not all devices are capable of performing this back-transform in order to clip TL-vertices.

The D3DPMISCCAPS_CLIPTLVERTS device capability indicates whether the device is capable of clipping TL-vertices. If this capability is not set, then the application is responsible for clipping the TL-vertices that it intends to send down to the device to be rendered. The device is always capable of clipping TL-vertices in the software vertex processing mode (either when the device itself is created in the software vertex processing mode or switched to the software vertex processing mode when created as a mixed mode vertex processing device using the D3DRS_SOFTWAREVERTEXPROCESSING renderstate).

© 2002 Microsoft Corporation. All rights reserved.


Viewport Scaling

The dimensions used in the X, Y, Width, and Heightmembers of the D3DVIEWPORT9 structure for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Microsoft® Direct3D® uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. The matrix also flips the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward. After this matrix is applied, vertices are still homogeneous—that is, they still exist as [x,y,z,w] vertices—and they must be converted to non-homogeneous coordinates before being sent to the rasterizer.

Note The viewport scaling matrix incorporates the MinZ and MaxZ members of the D3DVIEWPORT9 structure to scale vertices to fit the depth range [MinZ, MaxZ]. This represents different semantics from previous releases of Microsoft DirectX®, in which these members were used for clipping.
Note For more information, see Viewport Rectangle and Clipping Volumes. Applications typically set MinZ and MaxZ to 0.0 and 1.0 to cause the system to render to the entire depth range. However, you can use other values to achieve certain affects. You might set both values to 0.0 to force all objects into the foreground, or set both to 1.0 to render all objects into the background.

© 2002 Microsoft Corporation. All rights reserved.


Using Viewports

This section provides details about working with viewports. Information is divided into the following topics.

  • Setting the Viewport Clipping Volume
  • Clearing a Viewport
  • Manually Transforming Vertices

© 2002 Microsoft Corporation. All rights reserved.


Setting the Viewport Clipping Volume

The only requirement for configuring the viewport parameters for a rendering device is to set the viewport's clipping volume. To do this, you initialize and set clipping values for the clipping volume and for the render-target surface. Viewports are commonly set up to render to the full area of the render-target surface, but this isn't a requirement.

You can use the following settings for the members of the D3DVIEWPORT9 structure to achieve this in C++.

D3DVIEWPORT9 viewData = { 0, 0, width, height, 0.0f, 1.0f };

After setting values in the D3DVIEWPORT9 structure, apply the viewport parameters to the device by calling its IDirect3DDevice9::SetViewport method. The following code example shows what this call might look like.

HRESULT hr;

hr = pd3dDevice->SetViewport(&viewData);
if(FAILED(hr))
    return hr;

If the call succeeds, the viewport parameters are set and will take effect the next time a rendering method is called. To make changes to the viewport parameters, just update the values in the D3DVIEWPORT9 structure and call IDirect3DDevice9::SetViewport again.

Note The D3DVIEWPORT9 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

© 2002 Microsoft Corporation. All rights reserved.


Clearing a Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface as well as the rectangle in the depth and stencil buffer surfaces, if specified. Typically, you clear the viewport before rendering a new frame to ensure that graphics and other data is ready to accept new rendered objects without displaying artifacts.

The IDirect3DDevice9 interface offers C++ developers the IDirect3DDevice9::Clear method to clear the viewport. The method accepts one or more rectangles that define the areas on the surfaces being cleared. In cases where the scene being rendered includes motion throughout the entire viewport rectangle—in a first-person perspective game, for example—you might want to clear the entire viewport each frame. In this situation, you set the Count parameter to 1, and the pRects parameter to the address of a single rectangle that covers the entire viewport area. If it is more convenient, you can set the pRects parameter to NULL and the Count parameter to 0 to indicate that the entire viewport rectangle should be cleared.

The IDirect3DDevice9::Clear method is flexible, and it provides support for clearing stencil bits within a depth buffer. The Flags parameter accepts three flags that determine how it clears the render target and any associated depth or stencil buffers. If you include the D3DCLEAR_TARGET flag, the method clears the viewport using an arbitrary RGBA color that you provide in the Color parameter (not the material color). If you include the D3DCLEAR_ZBUFFER flag, the method clears the depth buffer to an arbitrary depth you specify in Z:. 0.0 is the closest distance, and 1.0 is the farthest. Including the D3DCLEAR_STENCIL flag causes the method to reset the stencil bits to the value you provide in the Stencil parameter. You can use integers that range from 0 to 2 -1, where n is the stencil buffer bit depth.

Note Microsoft® DirectX® 5.0 allowed background materials to have associated textures, making it possible to clear the viewport to a texture rather than a simple color. This feature was little used, and not particularly efficient. Interfaces for DirectX 6.0 and later do not accept texture handles, meaning that you can no longer clear the viewport to a texture. Rather, applications must now draw backgrounds manually. As a result, there is rarely a need to clear the viewport on the render-target surface. As long as your application clears the depth buffer, all pixels on the render-target surface will be overwritten anyway.

In some situations, you might be rendering only to small portions of the render target and depth buffer surfaces. The clear methods also enable you to clear multiple areas of your surfaces in a single call. Do this by setting the Count parameter to the number of rectangles you want cleared, and specify the address of the first rectangle in an array of rectangles in the pRects parameter.

© 2002 Microsoft Corporation. All rights reserved.


Manually Transforming Vertices

You can use three kinds of vertices in your Microsoft® Direct3D® application. Read Vertex Formats for more details on the vertex formats.

You can change from simple to complex vertex types by using vertex buffers. Vertex buffers are objects used to efficiently contain and process batches of vertices for rapid rendering, and are optimized to exploit processor-specific features. Use the IDirect3DDevice9::ProcessVertices method to perform vertex transformations. IDirect3DDevice9::ProcessVertices accepts only untransformed vertices and can optionally light and clip vertices as well. Lighting is performed at the time you call the IDirect3DDevice9::ProcessVertices methods, but clipping is performed at render time.

After processing the vertices, you can use special rendering methods to render the vertices, or you can access them directly by locking the vertex buffer memory. For more information about using vertex buffers, see Vertex Buffers.

© 2002 Microsoft Corporation. All rights reserved.


Lights and Materials

Lights are used to illuminate objects in a scene. When lighting is enabled, Microsoft® Direct3D® calculates the color of each object vertex based on a combination of:

  • The current material color and the texels in an associated texture map.
  • The diffuse and specular colors at the vertex, if specified.
  • The color and intensity of light produced by light sources in the scene or the scene's ambient light level.

When you use Direct3D lighting and materials, you allow Direct3D to handle the details of illumination for you. Advanced users can perform lighting on their own, if desired.

How you work with lighting and materials makes a big difference in the appearance of the rendered scene. Materials define how light reflects off a surface. Direct light and ambient light levels define the light that is reflected. You must use materials to render a scene if lighting is enabled. Lights are not required to render a scene, but details in a scene rendered without light are not visible. At best, rendering an unlit scene results in a silhouette of the objects in the scene. This is not enough detail for most purposes.

Additional information is contained in the following topics.

  • Direct3D Light Model vs. Nature
  • Color Values for Lights and Materials
  • Direct Light vs. Ambient Light
  • Light Properties
  • Using Lights
  • Mathematics of Lighting
  • Materials

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Light Model vs. Nature

In nature, when light is emitted from a source, it is reflected off of hundreds, if not thousands or millions of objects before reaching the user's eye. Each time it is reflected, some light is absorbed by a surface, some is scattered in random directions, and the rest goes on to another surface or to the user's eye. This process continues until the light is reduced to nothing or a user perceives the light.

Obviously, the calculations required to perfectly simulate the natural behavior of light are too time-consuming to use for real-time 3-D graphics. Therefore, with speed in mind, the Microsoft® Direct3D® light model approximates the way light works in the natural world. Direct3D describes light in terms of red, green, and blue components that combine to create a final color.

In Direct3D, when light reflects off a surface, the light color interacts mathematically with the surface itself to create the color eventually displayed on the screen. For specific information about the algorithms Direct3D uses, see Mathematics of Lighting.

The Direct3D light model generalizes light into two types: ambient light and direct light. Each has different attributes, and each interacts with the material of a surface in different ways. Ambient light is light that has been scattered so much that its direction and source are indeterminate: it maintains a low level of intensity everywhere. The indirect lighting used by photographers is a good example of ambient light. Ambient light in Direct3D, as in nature, has no real direction or source, only a color and intensity. In fact, the ambient light level is completely independent of any objects in a scene that generate light. Ambient light does not contribute to specular reflection.

Direct light is the light generated by a source within a scene; it always has color and intensity, and it travels in a specified direction. Direct light interacts with the material of a surface to create specular highlights, and its direction is used as a factor in shading algorithms, including Gouraud shading. When direct light is reflected, it does not contribute to the ambient light level in a scene. The sources in a scene that generate direct light have different characteristics that affect how they illuminate a scene. For more information, see Lights and Materials.

Additionally, a polygon's material has properties that affect how that polygon reflects the light it receives. You set a single reflectance trait that describes how the material reflects ambient light, and you set individual traits to determine the material's specular and diffuse reflectance. For more information, see Materials.

© 2002 Microsoft Corporation. All rights reserved.


Color Values for Lights and Materials

Microsoft® Direct3D® describes color in terms of four components—red, green, blue, and alpha—that combine to make a final color. The D3DCOLORVALUE C++ structure is defined to contain values for each component. Each member is a floating-point value that typically ranges from 0.0 to 1.0, inclusive. Although both lights and materials use the same structure to describe color, the values in the structure are used a little differently by each.

Color values for light sources represent the amount of a particular light component it emits. Because lights don't use an alpha component, only the red, green, and blue components of the color are relevant. You can visualize the three components as the red, green, and blue lenses on a projection television. Each lens might be off (a 0.0 value in the appropriate member), it might be as bright as possible (a 1.0 value), or it might be some level in between. The colors coming through the lenses combine to make the light's final color. A combination like R: 1.0, G: 1.0, B: 1.0 creates a white light, where R: 0.0, G: 0.0, B: 0.0 doesn't emit light at all. You can make a light that emits only one component, resulting in a pure red, green, or blue light, or, the light could use combinations to emit colors like yellow or purple. You can even set negative color component values to create a "dark light" that actually removes light from a scene. Or, you might set the components to some value larger than 1.0 to create an extremely bright light.

With materials, on the other hand, color values represent how much of a light component is reflected by a surface that is rendered with that material. A material whose color components are R: 1.0, G: 1.0, B: 1.0, A: 1.0 reflects all the light that comes its way. Likewise, a material with R: 0.0, G: 1.0, B: 0.0, A: 1.0 reflects all the green light that is directed at it. Materials have multiple reflectance values to create various types of effects; for more information, see Material Properties.

Color values for ambient light are different from those used for direct light sources and materials. For more information, see Direct Light vs. Ambient Light.

© 2002 Microsoft Corporation. All rights reserved.


Direct Light vs. Ambient Light

Although both direct and ambient light illuminate objects in a scene, they are independent of one another, they have very different effects, and they require that you work with them in completely different ways.

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a set of light parameters for direct light by calling the IDirect3DDevice9::SetLight method.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations in that scene. Ambient light has no position or direction, only color and intensity. Each light adds to the overall ambient light in a scene. Set the ambient light level with a call to the IDirect3DDevice9::SetRenderState method, specifying D3DRS_AMBIENT as the State parameter, and the desired RGBA color as the Value parameter.

Ambient light color takes the form of an RGBA value, where each component is an integer value from 0 to 255. This is unlike most color values in Microsoft® Direct3D®. For more information, see Color Values for Lights and Materials.

You can use the D3DCOLOR_RGBA macro to generate RGBA values. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. When using hardware acceleration or RGB emulation, the alpha component is ignored.

© 2002 Microsoft Corporation. All rights reserved.


Light Properties

Light properties describe a light source's type and color. Depending on the type of light being used, a light can have properties for attenuation and range, or for spotlight effects. But, not all types of lights use all properties. Microsoft® Direct3D® uses the D3DLIGHT9 structure to carry information about light properties for all types of light sources. This section contains information for all light properties. Information is divided into the following groups.

  • Light Type
  • Light Color
  • Color Vertices
  • Light Position, Range, and Attenuation
  • Light Direction

© 2002 Microsoft Corporation. All rights reserved.


Light Type

The light type property defines which type of light source you're using. The light type is set by using a value from the D3DLIGHTTYPE C++ enumeration in the Type member of the light's D3DLIGHT9 structure. There are three types of lights in Microsoft® Direct3D®—point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead.

Point Light

Point lights have color and position within a scene, but no single direction. They give off light equally in all directions, as shown in the following illustration.

A light bulb is a good example of a point light. Point lights are affected by attenuation and range, and illuminate a mesh on a vertex-by-vertex basis. During lighting, Direct3D uses the point light's position in world space and the coordinates of the vertex being lit to derive a vector for the direction of the light, and the distance that the light has traveled. Both are used, along with the vertex normal, to calculate the contribution of the light to the illumination of the surface.

Directional Light

Directional lights have only color and direction, not position. They emit parallel light. This means that all light generated by directional lights travels through a scene in the same direction. Imagine a directional light as a light source at near infinite distance, such as the sun. Directional lights are not affected by attenuation or range, so the direction and color you specify are the only factors considered when Direct3D calculates vertex colors. Because of the small number of illumination factors, these are the least computationally intensive lights to use.

SpotLight

Spotlights have color, position, and direction in which they emit light. Light emitted from a spotlight is made up of a bright inner cone and a larger outer cone, with the light intensity diminishing between the two, as shown in the following illustration.

Spotlights are affected by falloff, attenuation, and range. These factors, as well as the distance light travels to each vertex, are figured in when computing lighting effects for objects in a scene. Computing these effects for each vertex makes spotlights the most computationally time-consuming of all lights in Direct3D.

The D3DLIGHT9 C++ structure contains three members that are used only by spotlights. These members—Falloff, Theta, and Phi—control how large or small a spotlight object's inner and outer cones are, and how light decreases between them.

The Theta value is the radian angle of the spotlight's inner cone, and the Phi value is the angle for the outer cone of light. The Falloff value controls how light intensity decreases between the outer edge of the inner cone and the inner edge of the outer cone. Most applications set Falloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed.

The following illustration shows the relationship between the values for these members and how they can affect a spotlight's inner and outer cones of light.

  • Spotlight Model

    This page contains more information about how a spotlight works.

© 2002 Microsoft Corporation. All rights reserved.


Spotlight Model

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest in the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

The amount of light a vertex receives is based on the vertex's location in the inner or outer cones. Microsoft® Direct3D® computes the dot product of the spotlight's direction vector (L) and the vector from the vertex to the light (D). This value is equal to the cosine of the angle between the two vectors, and serves as an indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors.

Spotlight direction vector and vector from vertex to spotlight

The system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT9 structure, the Theta and Phi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination, rather than across the total cone angle, Direct3D divides these cone angles in half before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone and receives the maximum amount of light, still considering attenuation over distance. If the vertex is somewhere between the two regions, then Direct3D calculates falloff for the vertex by using the following formula.

Formula for light intensity at vertex, after falloff

In the formula, If is light intensity, after falloff, for the vertex being lit, a is the angle between vectors L and D, F is half of the outer cone angle, ? is half of the inner cone angle, and p is the spotlight's falloff property Falloff in the D3DLIGHT9 structure. This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The p value corresponds to the Falloff member of the D3DLIGHT9 structure and controls the shape of the falloff curve. The following illustration shows how different Falloff values can affect the falloff curve.

Graph of light intensity versus vertex distance from the light

The effect of various Falloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with Falloff values other than 1.0. For these reasons, this value is typically set to 1.0.

© 2002 Microsoft Corporation. All rights reserved.


Light Color

Lights in Microsoft® Direct3D® emit three colors that are used independently in the system's lighting computations: a diffuse color, an ambient color, and a specular color. Each is incorporated by the Direct3D lighting module, interacting with a counterpart from the current material, to produce a final color used in rendering. The diffuse color interacts with the diffuse reflectance property of the current material, the specular color with the material's specular reflectance property, and so on. For specifics about how Direct3D applies these colors, see Mathematics of Lighting.

In a C++ application, the D3DLIGHT9 structure includes three members for these colors—Diffuse, Ambient, and Specular—each one is a D3DCOLORVALUE structure that defines the color being emitted.

The type of color that applies most heavily to the system's computations is the diffuse color. The most common diffuse color is white (R:1.0 G:1.0 B:1.0), but you can create colors as needed to achieve desired effects. For example, you could use red light for a fireplace, or you could use green light for a traffic signal set to "Go."

Generally, you set the light color components to values between 0.0 and 1.0, inclusive, but this isn't a requirement. For example, you might set all the components to 2.0, creating a light that is "brighter than white." This type of setting can be especially useful when you use attenuation settings other than constant.

Note that although Direct3D uses RGBA values for lights, the alpha color component is not used. For more information, see Color Values for Lights and Materials.

© 2002 Microsoft Corporation. All rights reserved.


Color Vertices

Usually material colors are used for lighting. However, you can specify that material colors—emissive, ambient, diffuse, and specular—are to be overridden by diffuse or specular vertex colors. This is done by calling IDirect3DDevice9::SetRenderState and setting the device state variables listed in the following table.

Device state variable | Meaning | Type | Default
D3DRS_AMBIENTMATERIALSOURCE | Defines where to get ambient material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | Defines where to get diffuse material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | Defines where to get specular material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR2
D3DRS_EMISSIVEMATERIALSOURCE | Defines where to get emissive material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_COLORVERTEX | Disables or enables use of vertex colors. | BOOL | TRUE

The alpha/transparency value always comes only from the diffuse color's alpha channel.

The fog value always comes only from the specular color's alpha channel.

D3DMATERIALCOLORSOURCE can have the following values.

  • D3DMCS_MATERIAL - Material color is used as source.
  • D3DMCS_COLOR1 - Diffuse vertex color is used as source.
  • D3DMCS_COLOR2 - Specular vertex color is used as source.

© 2002 Microsoft Corporation. All rights reserved.


Light Position, Range, and Attenuation

The position, range, and attenuation properties define a light's location in world space and how the light it emits behaves over distance. As with all light properties you use in C++, these are contained in a light's D3DLIGHT9 structure.

Position

Light position is described using a D3DVECTOR structure in the Position member of the D3DLIGHT9 structure. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The Range member contains a floating-point value that represents the light's maximum range, in world space. Directional lights don't use the range property.

Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Three D3DLIGHT9 structure members represent light attenuation: Attenuation0, Attenuation1, and Attenuation2. These members contain floating-point values ranging from 0.0 through infinity, controlling a light's attenuation. Some applications set the Attenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that changes as 1 / D, where D is the distance from the light source to the vertex. The maximum light intensity is at the source, decreasing to 1 / (Light Range) at the light's range. Typically, an application sets Attenuation0 to 0.0, Attenuation1 to a constant value, and Attenuation2 to 0.0.

You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside the normal range to create even stranger attenuation effects. Negative attenuation values, however, are not allowed. See Attenuation and Spotlight Factor.

© 2002 Microsoft Corporation. All rights reserved.


Light Direction

A light's direction property determines the direction that the light emitted by the object travels, in world space. Direction is used only by directional lights and spotlights, and is described with a vector.

C++ applications set the light direction in the Direction member of the light's D3DLIGHT9 structure. Direction member is of type D3DVECTOR. Direction vectors are described as distances from a logical origin, regardless of the light's position in a scene. Therefore, a spotlight that points straight into a scene—along the positive z-axis—has a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you can simulate sunlight shining directly on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

Note Although you don't need to normalize a light's direction vector, always be sure that it has magnitude. In other words, don't use a <0,0,0> direction vector.

© 2002 Microsoft Corporation. All rights reserved.


Using Lights

Setting and Retrieving Light Properties

You set lighting properties in a C++ application by preparing a D3DLIGHT9 structure and then calling the IDirect3DDevice9::SetLight method. The IDirect3DDevice9::SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT9 structure that defines those properties. You can call IDirect3DDevice9::SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the IDirect3DDevice9::SetLight method with an index that has never been assigned properties. Applications can set a number of lights, with only a subset of the assigned lights enabled at a time. Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you no longer need a light, you can disable it or overwrite it with a new set of light properties.

The following C++ code example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
D3DLIGHT9 d3dLight;
HRESULT   hr;

// Initialize the structure.
ZeroMemory(&d3dLight, sizeof(d3dLight));

// Set up a white point light.
d3dLight.Type = D3DLIGHT_POINT;
d3dLight.Diffuse.r  = 1.0f;
d3dLight.Diffuse.g  = 1.0f;
d3dLight.Diffuse.b  = 1.0f;
d3dLight.Ambient.r  = 1.0f;
d3dLight.Ambient.g  = 1.0f;
d3dLight.Ambient.b  = 1.0f;
d3dLight.Specular.r = 1.0f;
d3dLight.Specular.g = 1.0f;
d3dLight.Specular.b = 1.0f;

// Position it high in the scene and behind the user.
// Remember, these coordinates are in world space, so
// the user could be anywhere in world space, too.
// For the purposes of this example, assume the user
// is at the origin of world space.
d3dLight.Position.x = 0.0f;
d3dLight.Position.y = 1000.0f;
d3dLight.Position.z = -100.0f;

// Don't attenuate.
d3dLight.Attenuation0 = 1.0f;
d3dLight.Range        = 1000.0f;

// Set the property information for the first light.
hr = d3dDevice->SetLight(0, &d3dLight);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

You can update a set of light properties with another call to IDirect3DDevice9::SetLight at any time. Just specify the index of the set of light properties to update and the address of the D3DLIGHT9 structure that contains the new properties.

Note Assigning a set of light properties to the device does not enable the light source whose properties are being added. Enable a light source by calling the IDirect3DDevice9::LightEnable method for the device.

You can retrieve all the properties for an existing light source from C++ by calling the IDirect3DDevice9::GetLight method for the device. When calling the IDirect3DDevice9::GetLight method, pass in the first parameter the zero-based index of the light source for which the properties will be retrieved, and supply the address of a D3DLIGHT9 structure in the second parameter. The device fills the D3DLIGHT9 structure to describe the lighting properties it uses for the light source at that index.

The following code example illustrates this process.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DLIGHT9 light;

// Get the property information for the first light.
hr = pd3dDevice->GetLight(0, &light);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

If you supply an index outside the range of the light sources assigned in the device, the IDirect3DDevice9::GetLight method fails, returning D3DERR_INVALIDCALL.

Enabling and Disabling Lights

When you assign a set of light properties for a light source in a scene, the light source can be activated by calling the IDirect3DDevice9::LightEnable method for the device. New light sources are disabled by default. The IDirect3DDevice9::LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to TRUE to enable the light or FALSE to disable it.

The following code example illustrates the use of this method by enabling the first light source in the device's list of light source properties.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;

hr = pd3dDevice->LightEnable(0, TRUE);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device.

If you enable or disable a light that has no properties that are set with IDirect3DDevice9::SetLight, the IDirect3DDevice9::LightEnable method creates a light source with the properties listed in following table and enables or disables it.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0

© 2002 Microsoft Corporation. All rights reserved.


Mathematics of Lighting

The Microsoft® Direct3D® Light Model covers ambient, diffuse, specular, and emissive lighting. This is enough flexibility to solve a wide range of lighting situations. You refer to the total amount of light in a scene as the global illumination and compute it using the following equation.

Global Illumination = Ambient Light + Diffuse Light + Specular Light + Emissive Light

Ambient Lighting is constant lighting. It is constant in all directions and it colors all pixels of an object the same. It is fast to calculate but leaves objects looking flat and unrealistic. To see how ambient lighting is calculated by Direct3D, see Ambient Lighting.

Diffuse Lighting depends on both the light direction and the object surface normal. It varies across the surface of an object as a result of the changing light direction and the changing surface numeral vector. It takes longer to calculate diffuse lighting because it changes for each object vertex, however the benefit of using it is that it shades objects and gives them three-dimensional (3-D) depth. To see how diffuse lighting is calculated in Direct3D, see Diffuse Lighting.

Specular Lighting identifies the bright specular highlights that occur when light hits an object surface and reflects back toward the camera. It is more intense than diffuse light and falls off more rapidly across the object surface. It takes longer to calculate specular lighting than diffuse lighting, however the benefit of using it is that it adds significant detail to a surface. To see how specular lighting is calculated in Direct3D, see Specular Lighting.

Emissive Lighting is light that is emitted by an object, for example, a glow. To see how emissive lighting is calculated in Direct3D, see Emissive Lighting.

Realistic lighting can be accomplished by applying each of these types of lighting to a 3-D scene. To achieve a more realistic lighting effect, you add more lights; however, the scene takes longer to render. To achieve all the effects a designer wants, some games use more CPU power than is commonly available. In this case, it is typical to reduce the number of lighting calculations to a minimum by using lighting maps and environment maps to add lighting to a scene while using texture maps.

Lighting is computed in the camera space. To see how lighting transformations are calculated, see Camera Space Transformations. Optimized lighting can be computed in model space, when special conditions exist: normal vectors are already normalized (D3DRS_NORMALIZENORMALS is True), vertex blending is not needed, transformation matrices are orthogonal, etc.

Ambient, diffuse, and specular light values can be affected by a given light's attenuation and spotlight factor. The values calculated for ambient, emissive, and diffuse components are stored in the diffuse output vertex color. Terms for both of these are included in the diffuse and specular equations. For more information, see Attenuation and Spotlight Factor.

© 2002 Microsoft Corporation. All rights reserved.


Ambient Lighting

Ambient lighting provides constant lighting for a scene. It lights all object vertices the same because it is not dependent on any other lighting factors such as vertex normals, light direction, light position, range, or attenuation. It is the fastest type of lighting but it produces the least realistic results. Microsoft® Direct3D® contains a single global ambient light property that you can use without creating any light. Alternatively, you can set any light object to provide ambient lighting. The ambient lighting for a scene is described by the following equation.

Ambient Lighting = Ca*[Ga + sum(Lai*Attenuationi*SpotFactori)]

Formula for ambient lighting is incorrect. It should be Ambient Lighting = Ca*[Ga + sum(Lai)*Atti*Spoti] Where Att and Spot are attenuation and spot factors, computed for i-light.

The parameters are defined in the following table.

Parameter | Default value | Type | Description
Ca | (0,0,0,0) | D3DCOLORVALUE | Material ambient color.
Ga | (0,0,0,0) | D3DCOLORVALUE | Global ambient color.
sum | N/A | N/A | Summation of the ambient light from the light objects.
Lai | (0,0,0,0) | D3DVECTOR | Light ambient color of the ith light.
Atteni | (0,0,0,0) | D3DCOLORVALUE | Light attenuation of the ith light. See Attenuation and Spotlight Factor.
Spoti | (0,0,0,0) | D3DVECTOR | Spotlight factor of the ith light. See Attenuation and Spotlight Factor.

The value for Ca is either:

  • vertex color1, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in vertex declaration.
  • material ambient color
Note If either AMBIENTMATERIALSOURCE option is used, and the vertex color is not provided, then the material ambient color is used.

To use the material ambient color, use SetMaterial as shown in the example code below.

Ga is the global ambient color. It is set using SetRenderState(D3DRENDERSTATE_AMBIENT). There is one global ambient color in a Direct3D scene. This parameter is not associated with a Direct3D light object.

Lai is the ambient color of the ith light in the scene. Each Direct3D light has a set of properties, one of which is the ambient color. The term, sum(Lai) is a sum of all the ambient colors in the scene.

Example

In this example, the object is colored using the scene ambient light and a material ambient color. The code is shown below.

#define GRAY_COLOR			0x00bfbfbf

// create material
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Ambient.r = 0.75f;
mtrl.Ambient.g = 0.0f;
mtrl.Ambient.b = 0.0f;
mtrl.Ambient.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState( D3DRS_AMBIENT, GRAY_COLOR);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. Ambient light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2-D circle because there is no difference in shading around the surface of the object.

Sphere with ambient lighting

To give objects a more realistic look, apply diffuse or specular lighting in addition to ambient lighting.

© 2002 Microsoft Corporation. All rights reserved.


Diffuse Lighting

After adjusting the light intensity for any attenuation effects, the lighting engine computes how much of the remaining light reflects from a vertex, given the angle of the vertex normal and the direction of the incident light. The lighting engine skips to this step for directional lights because they do not attenuate over distance. The system considers two reflection types, diffuse and specular, and uses a different formula to determine how much light is reflected for each. After calculating the amounts of light reflected, Microsoft® Direct3D® applies these new values to the diffuse and specular reflectance properties of the current material. The resulting color values are the diffuse and specular components that the rasterizer uses to produce Gouraud shading and specular highlighting.

Diffuse lighting is described by the following equation.

Diffuse Lighting = sum[Cd*Ld*(N.Ldir)*Atten*Spot]

Parameter | Default value | Type | Description
sum | N/A | N/A | Summation of each light's diffuse component.
Cd | (0,0,0,0) | D3DCOLORVALUE | Diffuse color.
Ld | (0,0,0,0) | D3DCOLORVALUE | Light diffuse color.
N | N/A | D3DVECTOR | Vertex normal
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light.
Atten | N/A | FLOAT | Light attenuation. See Attenuation and Spotlight Factor.
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor.

The value for Cd is either:

  • vertex color1, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material diffuse color
Note If either DIFFUSEMATERIALSOURCE option is used, and the vertex color is not provided, the material diffuse color is used.

To calculate the attenuation (Atten) or the spotlight characteristics (Spot), see Attenuation and Spotlight Factor.

Diffuse components are clamped to be from 0 to 255, after all lights are processed and interpolated separately. The resulting diffuse lighting value is a combination of the ambient, diffuse and emissive light values.

Example

In this example, the object is colored using the light diffuse color and a material diffuse color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

// set directional light diffuse color
light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;
light.Diffuse.a = 1.0f;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );

// if a material is used, SetRenderState must be used
// vertex color = light diffuse color * material diffuse color
mtrl.Diffuse.r = 0.75f;
mtrl.Diffuse.g = 0.0f;
mtrl.Diffuse.b = 0.0f;
mtrl.Diffuse.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. The diffuse lighting calculation takes the material and light diffuse color and modifies it by the angle between the light direction and the vertex normal using the dot product. As a result, the backside of the sphere gets darker as the surface of the sphere curves away from the light.

Diffuse lighting only

Combining the diffuse lighting with the ambient lighting from the previous example shades the entire surface of the object. The ambient light shades the entire surface and the diffuse light helps reveal the object's 3-D shape.

Sphere with diffuse lighting

Diffuse lighting is more intensive to calculate than ambient lighting. Because it depends on the vertex normals and light direction, you can see the objects geometry in 3-D space, which produces a more realistic lighting than ambient lighting. You can use specular highlights to achieve a more realistic look.

© 2002 Microsoft Corporation. All rights reserved.


Specular Lighting

Modeling specular reflection requires that the system not only know the direction that light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a halfway vector to approximate the intensity of specular reflection.

The default lighting state does not calculate specular highlights. To enable specular lighting, be sure to set D3DRS_SPECULARENABLE to TRUE.

Specular Lighting Equation

Specular Lighting is described by the following equation.

Specular Lighting = Cs*sum[Ls*(N.H)P*Atten*Spot]

The table identifies the variables, their types and their ranges.

Parameter | Default value | Type | Description
Cs | (0,0,0,0) | D3DCOLORVALUE | Specular color.
sum | N/A | N/A | Summation of each light's specular component.
N | N/A | D3DVECTOR | Vertex normal.
H | N/A | D3DVECTOR | Half way vector. See the section on the halfway vector.
P | 0.0 | FLOAT | Specular reflection power. Range is 0 to +infinity
Ls | (0,0,0,0) | D3DCOLORVALUE | Light specular color.
Atten | N/A | FLOAT | Light attenuation value. See Attenuation and Spotlight Factor.
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor.

The value for Cs is either:

  • vertex color1, if SPECULARMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if SPECULARMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material specular color

Note If either SPECULARMATERIALSOURCE option is used, and the vertex color is not provided, then the material specular color is used.

Specular components are clamped to be from 0 to 255, after all lights are processed and interpolated separately.

The halfway vector

The halfway vector (H) exists midway between two vectors: the vector from an object vertex to the light source, and the vector from an object vertex to the camera position. Microsoft® Direct3D® provides two ways to compute the halfway vector. When D3DRS_LOCALVIEWER is set to TRUE, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates this.

H = norm(norm(Cp - Vp) + Ldir)

Parameter | Default value | Type | Description
Cp | N/A | D3DVECTOR | Camera position.
Vp | N/A | D3DVECTOR | Vertex position.
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position.

Determining the halfway vector in this manner can be computationally intensive. As an alternative, setting D3DRS_LOCALVIEWER = FALSE instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This is reflected in the following formula.

H = norm((0,0,1) + Ldir)

This setting is less computationally intensive, but much less accurate, so it is best used by applications that use orthogonal projection.

Example

In this example, the object is colored using the scene specular light color and a material specular color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
light.Specular.a = 1.0f;

light.Range = 1000;
light.Falloff = 0;
light.Attenuation0 = 1;
light.Attenuation1 = 0;
light.Attenuation2 = 0;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE );

mtrl.Specular.r = 1.0f;
mtrl.Specular.g = 1.0f;
mtrl.Specular.b = 1.0f;
mtrl.Specular.a = 1.0f;
mtrl.Power = 20;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is white.

The resulting specular highlight is shown below.

Specular highlight only

Combining the specular highlight with the ambient and diffuse lighting produces the following image. With all three types of lighting applied, this more clearly resembles a realistic object.

Specular highligh applied

Specular lighting is more intensive to calculate than diffuse lighting. It is typically used to provide visual clues about the surface material. The specular highlight varies in size and color with the material of the surface.

© 2002 Microsoft Corporation. All rights reserved.


Emissive Lighting

Emissive lighting is described by a single term.

Emissive Lighting = Ce

Where:

Parameter | Default value | Type | Description
Ce | (0,0,0,0) | D3DCOLORVALUE | Emissive color.

The value for Ce is either:

  • vertex color1, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material emissive color
Note If either EMISSIVEMATERIALSOURCE option is used, and the vertex color is not provided, the material emissive color is used.

Example

In this example, the object is colored using the scene ambient light and a material ambient color. The code is shown below.

// create material
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Emissive.r = 0.0f;
mtrl.Emissive.g = 0.75f;
mtrl.Emissive.b = 0.0f;
mtrl.Emissive.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is the material color.

The image below shows the material color, which is green. Emissive light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2-D circle because there is no difference in shading around the surface of the object.

This image shows how the emissive light blends with the other three types of lights, from the previous examples. On the right side of the sphere, there is a blend of the green emissive and the red ambient light. On the left side of the sphere, the green emissive light blends with red ambient and diffuse light producing a red gradient. The specular highlight is white in the center and creates a yellow ring as the specular light value falls off sharply leaving the ambient, diffuse and emissive light values which blend together to make yellow.

Green sphere with emissive light

© 2002 Microsoft Corporation. All rights reserved.


Camera Space Transformations

Vertices in the camera space are computed by transforming the object vertices with the world view matrix.

V = V * wvMatrix

Vertex normals, in camera space, are computed by transforming the object normals with the inverse transpose of the world view matrix. The world view matrix may or may not be orthogonal.

N = N * (wvMatrix-1)T

The matrix inversion and matrix transpose operate on a 4x4 matrix. The multiply combines the normal with the 3x3 portion of the resulting 4x4 matrix.

If the render state, D3DRENDERSTATE_NORMALIZENORMALS is set to TRUE, vertex normal vectors are normalized after transformation to camera space as follows:

N = norm(N)

Light position in camera space is computed by transforming the light source position with the view matrix.

Lp = Lp * vMatrix

The direction to the light in camera space for a directional light is computed by multiplying the light source direction by the view matrix, normalizing, and negating the result.

Ldir = -norm(Ldir * wvMatrix)

For the D3DLIGHT_POINT and D3DLIGHT_SPOT the direction to light is computed as follows:

Ldir = norm(V * Lp), where the parameters are defined in the following table.

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light
V | N/A | D3DVECTOR | Vertex position in camera space
wvMatrix | Identity | D3DMATRIX | Composite matrix containing the world and view transforms
N | N/A | D3DVECTOR | Vertex normal
Lp | N/A | D3DVECTOR | Light position in camera space
vMatrix | Identity | D3DMATRIX | Matrix containing the view transform

© 2002 Microsoft Corporation. All rights reserved.


Attenuation and Spotlight Factor

The diffuse and specular lighting components of the global illumination equation contain terms that describe light attenuation and the spotlight cone. These terms are described below.

Attenuation

The attenuation of a light depends on the type of light and the distance between the light and the vertex position. To calculate attenuation, use one of the following three equations.

Atten = 1/( att0i + att1i * d + att2i * d2)

Where:

Parameter | Default value | Type | Description
att0i | 0.0 | FLOAT | Linear attenuation factor. Range is 0 to +infinity
att1i | 0.0 | FLOAT | Squared attenuation factor. Range is 0 to +infinity
att2i | 0.0 | FLOAT | Exponential attenuation factor. Range is 0 to +infinity
d | N/A | FLOAT | Distance from vertex position to light position
  • Atten = 1, if the light is a directional light.
  • Atten = 0, if the distance between the light and the vertex exceeds the light's range.

The att0, att1, att2 values are specified by the Attenuation0, Attenuation1, and Attenuation2 members of D3DLIGHT9.

The distance between the light and the vertex position is always positive.

d = | Ldir |

Where:

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

If d is greater than the light's range, that is, the Range member of a D3DLIGHT9 structure, Microsoft® Direct3D® makes no further attenuation calculations and applies no effects from the light to the vertex.

The attenuation constants act as coefficients in the formula—you can produce a variety of attenuation curves by making simple adjustments to them. You can set Attenuation1 to 1.0 to create a light that doesn't attenuate but is still limited by range, or you can experiment with different values to achieve various attenuation effects.

The attenuation at the maximum range of the light is not 0.0. To prevent lights from suddenly appearing when they are at the light range, an application can increase the light range. Or, the application can set up attenuation constants so that the attenuation factor is close to 0.0 at the light range. The attenuation value is multiplied by the red, green, and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex.

Spotlight Factor

Formula for spotlight factor

Parameter | Default value | Type | Description
rhoi | N/A | FLOAT | cosine(angle) for spotlight i
phii | 0.0 | FLOAT | Penumbra angle of spotlight i in radians. Range: [thetai, pi)
thetai | 0.0 | FLOAT | Umbra angle of spotlight i in radians. Range: [0, pi)
falloff | 0.0 | FLOAT | Falloff factor. Range: (-infinity, +infinity)

Where:

rho = norm(Ldcs).norm(Ldir)

and:

Parameter | Default value | Type | Description
Ldcs | N/A | D3DVECTOR | The negative of the light direction in camera space
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

After computing the light attenuation, Direct3D also considers: spotlight effects if applicable, the angle that the light reflects from a surface, and the reflectance of the current material to calculate the diffuse and specular components for that vertex. For more information, see Spotlight Model.

© 2002 Microsoft Corporation. All rights reserved.


Materials

Materials describe how polygons reflect light or appear to emit light in a 3-D scene. Essentially, a material is a set of properties that tell Microsoft® Direct3D® the following things about the polygons it is rendering.

  • How they reflect ambient and diffuse light
  • What their specular highlights look like
  • Whether the polygons appear to emit light

Direct3D applications written in C++ use the D3DMATERIAL9 structure to describe material properties. For more information, see Material Properties.

Setting Material Properties

Direct3D rendering devices can render with one set of material properties at a time.

In a C++ application, you set the material properties that the system uses by preparing a D3DMATERIAL9 structure, and then calling the IDirect3DDevice9::SetMaterial method.

To prepare the D3DMATERIAL9 structure for use, set the property information in the structure to create the desired effect during rendering. The following code example sets up the D3DMATERIAL9 structure for a purple material with sharp white specular highlights.

D3DMATERIAL9 mat;

// Set the RGBA for diffuse reflection.
mat.Diffuse.r = 0.5f;
mat.Diffuse.g = 0.0f;
mat.Diffuse.b = 0.5f;
mat.Diffuse.a = 1.0f;

// Set the RGBA for ambient reflection.
mat.Ambient.r = 0.5f;
mat.Ambient.g = 0.0f;
mat.Ambient.b = 0.5f;
mat.Ambient.a = 1.0f;

// Set the color and sharpness of specular highlights.
mat.Specular.r = 1.0f;
mat.Specular.g = 1.0f;
mat.Specular.b = 1.0f;
mat.Specular.a = 1.0f;
mat.Power = 50.0f;

// Set the RGBA for emissive color.
mat.Emissive.r = 0.0f;
mat.Emissive.g = 0.0f;
mat.Emissive.b = 0.0f;
mat.Emissive.a = 0.0f;

After preparing the D3DMATERIAL9 structure, you apply the properties by calling the IDirect3DDevice9::SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL9 structure as its only parameter. You can call IDirect3DDevice9::SetMaterial with new information as needed to update the material properties for the device. The following code example shows how this might look in code.

// This code example uses the material properties defined for
// the mat variable earlier in this topic. The pd3dDev is assumed
// to be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
hr = pd3dDev->SetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

When you create a Direct3D device, the current material is automatically set to the default shown in the following table.

Member | Value
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Emissive | (R:0, G:0, B:0, A:0)
Power | (0.0)

Retrieving Material Properties

You retrieve the material properties that the rendering device is currently using by calling the IDirect3DDevice9::GetMaterial method for the device. Unlike the IDirect3DDevice9::SetMaterial method, IDirect3DDevice9::GetMaterial doesn't require preparation. The IDirect3DDevice9::GetMaterial method accepts the address of a D3DMATERIAL9 structure, and fills the provided structure with information describing the current material properties before returning.

// For this example, the pd3dDev variable is assumed to
// be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DMATERIAL9 mat;

hr = pd3dDev->GetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

For more information about material properties see:

  • Material Properties
Note If your application does not specify material properties for rendering, the system uses a default material. The default material reflects all diffuse light—white, for example—with no ambient or specular reflection, and no emissive color.

© 2002 Microsoft Corporation. All rights reserved.


Material Properties

Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlight characteristics. Microsoft® Direct3D® uses the D3DMATERIAL9 structure to carry all material property information. Material properties affect the colors that Direct3D uses to rasterize polygons that use the material. With the exception of the specular property, each property is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor—the alpha component of the RGBA color. The material's specular property is described in two parts: color and power. For more information, see Color Values for Lights and Materials.

Diffuse and Ambient Reflection

The Diffuse and Ambient members of the D3DMATERIAL9 structure describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the IDirect3DDevice9::SetRenderState method with the D3DRS_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you create a material that reflects only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The Emissive member of the D3DMATERIAL9 structure is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property is useful if you want to make the crystal appear to light up, but not cast light on other objects in the scene. Remember, materials with emissive properties don't emit light that can be reflected by other objects in a scene. To achieve this reflected light, you need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL9 structure contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the Specular member to the desired RGBA color—the most common colors are white or light gray. The values you set in the Power member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger Power value creates sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that make the crystal look frosty. To make an object truly matte, set the Power member to zero and the color in Specular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models. The one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.

Specular reflection models

© 2002 Microsoft Corporation. All rights reserved.


Textures

Textures are a powerful tool in creating realism in computer-generated 3-D images. Microsoft® Direct3D® supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques.

This section will get you started using textures.

  • Basic Texturing Concepts
  • Texture Coordinates
  • Texture Filtering
  • Texture Resources
  • Texture Wrapping
  • Texture Blending
  • Surfaces

These topics will go into more detail about additional texturing functionality.

  • Automatic Generation of Mipmaps
  • Automatic Texture Management
  • Compressed Texture Resources
  • Hardware Considerations for Texturing
  • Volume Texture Resources

For improved performance, consider using dynamic textures. A dynamic texture can be locked, written to, and unlocked each frame. See Using Dynamic Textures.

© 2002 Microsoft Corporation. All rights reserved.


Basic Texturing Concepts

Early computer-generated 3-D images, although generally advanced for their time, tended to have a shiny plastic look. They lacked the types of markings—such as scuffs, cracks, fingerprints, and smudges—that give 3-D objects realistic visual complexity. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3-D images.

In its everyday use, the word texture refers to an object's smoothness or roughness. In computer graphics, however, a texture is a bitmap of pixel colors that give an object the appearance of texture.

Because Direct3D textures are bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3-D primitives that form a hill. The result is a realistic-looking hillside. You can also use texturing to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor.

In addition, Direct3D supports more advanced texturing techniques such as texture blending - with or without transparency - and light mapping. For more information, see Texture Blending and Light Mapping with Textures.

If your application creates a hardware abstraction layer (HAL) device or a software device, it can use 8-, 16-, 24-, or 32-bit textures.

Additional information is contained in the following topics.

  • Texture Addressing Modes
  • Texture Dirty Regions
  • Texture Palettes

© 2002 Microsoft Corporation. All rights reserved.


Texture Addressing Modes

Your Microsoft® Direct3D® application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates. Typically, the u- and v-texture coordinates that you assign to a vertex are in the range of 0.0 to 1.0 inclusive. However, by assigning texture coordinates outside that range, you can create certain special texturing effects.

You control what Direct3D does with texture coordinates that are outside the [0.0, 1.0] range by setting the texture addressing mode. For instance, you can have your application set the texture addressing mode so that a texture is tiled across a primitive. The following topics contain additional details.

Direct3D enables applications to perform texture wrapping. It is important to note that setting the texture addressing mode to D3DTADDRESS_WRAP is not the same as performing texture wrapping. Setting the texture addressing mode to D3DTADDRESS_WRAP results in multiple copies of the source texture being applied to the current primitive, and enabling texture wrapping changes how the system rasterizes textured polygons. For details, see Texture Wrapping.

Enabling texture wrapping effectively makes texture coordinates outside the [0.0, 1.0] range invalid, and the behavior for rasterizing such delinquent texture coordinates is undefined in this case. When texture wrapping is enabled, texture addressing modes are not used. Take care that your application does not specify texture coordinates lower than 0.0 or higher than 1.0 when texture wrapping is enabled.

Setting the Addressing Mode

You can set texture addressing modes for individual texture stages by calling the IDirect3DDevice9::SetSamplerState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW values to update the u-, v-, or w-addressing modes individually. The third parameter you pass to IDirect3DDevice9::SetSamplerState determines which mode is being set. This can be any member of the D3DTEXTUREADDRESS enumerated type. To retrieve the current texture address mode for a texture stage, call IDirect3DDevice9::GetSamplerState, using the D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW members of the D3DTEXTURESTAGESTATETYPE enumeration to identify the address mode about which you want information.

Device Limitations

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the MaxTextureRepeat member of the D3DCAPS9 structure when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of MaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the MaxTextureRepeat member of D3DCAPS9 is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, MaxTextureRepeat must be scaled by the current texture size at the largest level of detail to compute the valid texture coordinate range. For example, given a texture dimension of 32 and MaxTextureRepeat value of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.

Additional information about the texture addressing modes is contained in the following topics.

  • Wrap Texture Address Mode
  • Mirror Texture Address Mode
  • Clamp Texture Address Mode
  • Border Color Texture Address Mode

© 2002 Microsoft Corporation. All rights reserved.


Wrap Texture Address Mode

The wrap texture address mode, identified by the D3DTADDRESS_WRAP member of the D3DTEXTUREADDRESS enumerated type, makes Microsoft® Direct3D® repeat the texture on every integer junction. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP results in the texture being applied three times in both the u-and v-directions.

The effects of this texture address mode are similar to, but distinct from, those of the mirror mode. For more information, see Mirror Texture Address Mode.

© 2002 Microsoft Corporation. All rights reserved.


Mirror Texture Address Mode

The mirror texture address mode, identified by the D3DTADDRESS_MIRROR member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to mirror the texture at every integer boundary. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR results in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to is a mirror image of the preceding row or column.

The effects of this texture address mode are similar to, but distinct from, those of the wrap mode. For more information, see Wrap Texture Address Mode.

© 2002 Microsoft Corporation. All rights reserved.


Clamp Texture Address Mode

The clamp texture address mode, identified by the D3DTADDRESS_CLAMP member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to clamp your texture coordinates to the [0.0, 1.0] range. That is, it applies the texture once, then smears the color of edge pixels. For example, suppose that your application creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP results in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

This is illustrated in the following figure.

© 2002 Microsoft Corporation. All rights reserved.


Border Color Texture Address Mode

The border color texture address mode, identified by the D3DTADDRESS_BORDER member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

This is shown in the following figure in which the application specifies that the texture be applied to the primitive using a red border.

Applications set the border color by calling IDirect3DDevice9::SetSamplerState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DSAMP_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.

© 2002 Microsoft Corporation. All rights reserved.


Texture Dirty Regions

Applications can optimize which subset of a texture is copied by specifying "dirty" regions on textures. Only those regions marked as dirty are copied by a call to IDirect3DDevice9::UpdateTexture. However, the dirty regions may be expanded to optimize alignment. When a texture is created, the entire texture is considered dirty. Only the following operations affect the dirty state of a texture.

  • Adding a dirty region to a texture.
  • Locking some buffer in the texture. This operation adds the locked region as a dirty region. The application can turn off this automatic dirty region update if it has better knowledge of the actual dirty regions.
  • Using the texture as a destination in IDirect3DDevice9::UpdateSurface marks the entire texture as dirty.
  • Using the texture as a source in IDirect3DDevice9::UpdateTexture clears all the dirty regions on the source texture.
  • Using IDirect3DSurface9::GetDC to return a device context.

Dirty regions are set on the top level of a mipmapped texture, and IDirect3DDevice9::UpdateTexture can expand the dirty region down the mip chain in order to minimize the number of bytes copied for each sublevel. Note that the sublevel dirty region coordinates are rounded outward, that is, their fractional parts are rounded toward the nearest edge of the texture.

Because each type of texture has different types of dirty regions, there are methods on each texture type. 2-D textures use dirty rectangle, and volume textures use boxes.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox

Passing NULL for the pDirtyRect or pDirtyBox parameters for the above methods expands the dirty region to cover the entire texture.

Each lock method can take D3DLOCK_NO_DIRTY_UPDATE, which prevents any changes to the dirty state of the texture. For more information, see Locking Resources.

When more information about the true set of regions changed during a lock operation is available, applications should use D3DLOCK_NO_DIRTY_UPDATE. Note that a lock or a copy to a texture sublevel only (that is, without locking or copying to the top level) does not update the dirty regions for that texture. Applications assume the same responsibility for updating dirty regions when they lock lower levels without locking the topmost level.

© 2002 Microsoft Corporation. All rights reserved.


Texture Palettes

Microsoft® Direct3D® for Microsoft DirectX® 9.0 supports paletted textures through a set of 256 entry palettes associated with the IDirect3DDevice9 object. A palette is made current by calling the IDirect3DDevice9::SetCurrentTexturePalette method. The current palette is used for translating all paletted textures for all active texture stages. IDirect3DDevice9::SetPaletteEntries updates all of a palette's 256 entries. Each entry is a PALETTEENTRY structure of the format D3DFMT_A8R8G8B8. All entries default to 0xFFFFFFFF.

The IDirect3DDevice9 palettes contain an alpha channel. This alpha channel can be used when the D3DPTEXTURECAPS_ALPHAPALETTE device capability flag is set, indicating that the device supports alpha from the palette. The palette alpha channel is used when the texture format does not have an alpha channel. If the device does not support alpha from the palette and the texture format does not have an alpha channel, then a value of 0xFF is used for alpha.

There is a maximum of 65,536 (0x0000FFFF) palettes. Because memory resources associated with the set of palettes are proportional to the maximum palette number that an application references, use contiguous palette numbers starting at zero.

© 2002 Microsoft Corporation. All rights reserved.


Texture Coordinates

Most textures, like bitmaps, are a two-dimensional array of color values. Cubic environment map textures are an exception. For details, see Cubic Environment Mapping. The individual color values are called a texture element, or texel. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively.

Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3-D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Mapping Texels to Screen Space

Microsoft® Direct3D® maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering.

Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D applications specify texture coordinates in terms of u,v values, much like 2-D Cartesian coordinates are specified in terms of x,y coordinates. Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes.

A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address being used is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

A simplified version of the texel mapping process is shown in the following diagram. Admittedly, this example is extremely simple. For more detailed information, see Directly Mapping Texels to Pixels.

Pixel idealized into a square of color

For this example, a pixel, shown at the left of the illustration, is idealized into a square of color. The addresses of the four corners of the pixel are mapped into the 3-D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3-D space and because of the viewing angle. The corners of the surface area on the primitive that correspond the corners of the pixel are then mapped into texture space. The mapping process distorts the pixel's shape again, which is common. The final color value of the pixel is computed from the texels in the region to which the pixel maps. You determine the method that Direct3D uses to arrive at the pixel color when you set the texture filtering method. For more information, see Texture Filtering.

Your application can assign texture coordinates directly to vertices. This capability gives you control over which portion of a texture is mapped into a primitive. For instance, suppose you create a rectangular primitive that is exactly the same size as the texture in the following illustration. In this example, you want your application to map the whole texture onto the whole wall. The texture coordinates your application assigns to the vertices of the primitive are (0.0,0.0), (1.0,0.0), (1.0,1.0), and (0.0,1.0).

If you decide to decrease the height of the wall by one-half, you can distort the texture to fit onto the smaller wall, or you can assign texture coordinates that cause Direct3D to use the lower half of the texture.

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering.

If, instead, you decide to assign texture coordinates to make Direct3D use the lower half of the texture for the smaller wall, the texture coordinates your application assigns to the vertices of the primitive in this example are (0.0,0.5), (1.0,0.5), (1.0,1.0), and (0.0,1.0). Direct3D applies the lower half of the texture to the wall.

It is possible for texture coordinates of a vertex to be greater than 1.0. When you assign texture coordinates to a vertex that are not in the range of 0.0 to 1.0 inclusive, you should also set the texture addressing mode. For more information, see Texture Addressing Modes.

Texture Coordinates and Texture Stages

Texture coordinates are associated with textures by way of texture stages. Textures get assigned to texture stages with SetTexture(stageIndex, pTexture). See IDirect3DDevice9::SetTexture.

An flexible vertex format (FVF) code can define up to eight sets of texture coordinates. The texture coordinate data is furnished by the user in the vertex data. The data is referred to with a zero based index: 0 - 7. There are up to eight texture blending stages. A texture is associated with a particular stage using SetTexture( stageIndex, pTexture).

Once this is done, any set of texture coordinates can be used by any stage. Each set of coordinates is associated with a stage using SetTextureStageState( stageIndex, D3DTSS_TEXCOORDINDEX, textureCoordinateIndex ). See IDirect3DDevice9::SetTextureStageState. This way, the blending stages can be set up to use any texture and any texture coordinates. More than one stage can use the same textures, or texture coordinates.

Additional information is contained in the following topics.

  • Directly Mapping Texels to Pixels
  • Texture Coordinate Formats
  • Texture Coordinate Processing

© 2002 Microsoft Corporation. All rights reserved.


Directly Mapping Texels to Pixels

Applications often need to apply textures to geometry in a scene so that texels map directly to on-screen pixels. For example, take an application that needs to display text within a texture on an object within a scene. In order to clearly display textual information in a texture, the application needs some way to ensure that the textured geometry receives texels undisrupted by texture filtering. Failing this, the resulting image is often blurred, or in the case of point-sampled texture filtering, can cause rough edges.

Because the Microsoft® Direct3D® pixel and texture sampling rules are carefully defined to unify pixel and texture sampling while supporting image and texture filtering, getting the texels in a texture to map directly to on-screen pixels can be a significant and often frustrating challenge. Overcoming this challenge requires a clear understanding of how Direct3D maps the floating-point texture coordinates for a vertex to the integer pixel coordinates used by the rasterizer.

Direct3D performs the following computations to map floating point texture coordinates to texel addresses.

In these formulas, Tx and Ty are the horizontal and vertical output texel coordinates, and u and v are the horizontal and vertical texture coordinates supplied for the vertex. The Mx and My elements represent the number of horizontal or vertical texels at the current mipmap level. The remainder of this discussion targets horizontal mapping of texels to pixels; keep in mind that mapping in the vertical is identical to the horizontal case.

Placing the texture coordinate limits 0.0 and 1.0 into these formulas maps a texture coordinate of 0.0 halfway between the first and last texels of a repeated texture map. The coordinate 1.0 is mapped halfway between the last texel of the current iteration of the texture map and the next iteration. For a repeated texture that's four texels wide, at mipmap level 0, the following illustration shows where the system maps the coordinates 0.0 and 1.0.

Given an understanding of this mapping, you can apply a simple bias to your screen-space geometry coordinates to force the system to map each texel to a corresponding pixel. For example, to draw a four-sided polygon that maps each texel from the preceding texture to one, and only one, pixel on the screen, you must force geometry coordinates to overlap the pixels, effectively placing the center of each texel at the center of each pixel. The result is the 1-to-1 mapping often sought-after by applications.

To map the texture with a 4-texel width to the pixel coordinates 0 through 3, draw a four-sided polygon, from two triangles, that has screen-space coordinates of –0.5 to 3.5 and texture coordinates of 0.0 to 1.0. For example, take the pixel at screen coordinate 0.0. Because 0.0 is one-half pixel away from the first vertex, at -0.5, and the total width is 4.0, the iterated texture coordinate is 0.125. Scaling this by the texture size, which is 4, results in the coordinate 0.5. Subtracting this 0.5 bias produces a texture address of 0.0, which fully maps to the first texel in the map.

To summarize, texture coordinates overlap the texture map evenly on both sides. The following illustration shows the mapping of a texture that is four texels wide.

The system normalizes pixel coordinates in the same way it normalizes texel coordinates. Therefore, if the vertices overlap the pixels into which to render, and if the vertices use texture coordinates of 0.0 and 1.0, the pixels and texels line up. If both are of similar size and properly aligned, they match exactly, texel to pixel, as shown in the following figure.

Texture and screen coordinates

© 2002 Microsoft Corporation. All rights reserved.


Texture Coordinate Formats

Texture coordinates in Microsoft® Direct3D® can include one, two, three, or four floating point elements to address textures with varying levels of dimension. A 1-D texture—a texture surface with dimensions of 1-by-n texels—is addressed by one texture coordinate. The most common case, 2-D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports two types of 3-D textures, cubic-environment maps and volume textures. Cubic environment maps aren't truly 3-D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping.

As described in Vertex Formats, applications encode texture coordinates in the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 D3DFVF to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between one and four elements. The D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4 flags describe the number of elements in a texture coordinate in a set, but these flags aren't used by themselves. Rather, the D3DFVF_TEXCOORDSIZEn set of macros use these flags to create bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

// This vertex format contains two sets of texture coordinates.
// The first set (index 0) has 2 elements, and the second set
// has 1 element. The description for this vertex format would be:
//     dwFVF = D3DFVF_XYZ  | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2 |
//             D3DFVF_TEXCOORDSIZE2(0) | D3DFVF_TEXCOORDSIZE1(1);
//
typedef struct CVF
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DCOLOR  diffuse;
    float     u, v;   // 1st set, 2-D
    float     t;      // 2nd set, 1-D
} CustomVertexFormat;
Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using any more than two elements. Applications can supply up to three elements for a texture coordinate, but only if the texture is a cube map, a volume texture, or the D3DTTFF_PROJECTED texture transform flag is used. The D3DTTFF_PROJECTED flag causes the rasterizer to divide the first two elements by the third (or n) element. For more information, see Texture Coordinate Transformations.

© 2002 Microsoft Corporation. All rights reserved.


Texture Coordinate Processing

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

Texture coordinate path

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Microsoft® Direct3D®. For details about the latter case, see Automatically Generated Texture Coordinates. If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The D3DTEXTURETRANSFORMFLAGS enumerated type defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass one, two, three, or four elements from the output coordinates to the rasterizer.

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with another member of D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For example, when explicitly using three-element texture coordinates, or when transformation results in a three-element texture coordinate, you can combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2-D texture coordinates required to address a 2-D texture.

Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using texture coordinates with more than two elements. If you specify more elements than can be used to address the current texture for that stage, the extraneous elements are ignored. This also applies when using 2-D texture coordinates for a 1-D texture.

Additional information is contained in the following topics.

  • Automatically Generated Texture Coordinates
  • Texture Coordinate Transformations
  • Special Effects

© 2002 Microsoft Corporation. All rights reserved.


Automatically Generated Texture Coordinates

The system can use the transformed camera-space position or the normal from a vertex as texture coordinates, or it can compute the three element vectors used to address a cubic environment map. Like texture coordinates that you explicitly specify in a vertex, you can use automatically generated texture coordinates as input for texture coordinate transformations.

Automatically generated texture coordinates can significantly reduce the bandwidth required for geometry data by eliminating the need for explicit texture coordinates in the vertex format. In many cases, the texture coordinates that the system generates can be used with transformations to produce special effects. Of course, this is a special-purpose feature, and you will use explicit texture coordinates for many occasions.

Configuring Automatically Generated Texture Coordinates

In C++, the D3DTSS_TEXCOORDINDEX texture-stage state (from the D3DTEXTURESTAGESTATETYPE enumerated type) controls how the system generates texture coordinates.

Normally, this state instructs the system to use a particular set of texture coordinates encoded in the vertex format. When you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flags in the value that you assign to this state, the system behavior is quite different. If any of these flags are present, the texture stage ignores the texture coordinates within the vertex format in favor of coordinates that the system generates. The meanings for each flag are shown in the following list.

  • D3DTSS_TCI_CAMERASPACENORMAL

    Use the vertex normal, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEPOSITION

    Use the vertex position, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR

    Use the reflection vector, transformed to camera space, as input texture coordinates. The reflection vector is computed from the input vertex position and normal vector.

The preceding flags are mutually exclusive. If you include one flag, you can still specify an index value, which the system uses to determine the texture wrapping mode.

The following code example shows how these flags are used in C++.

/*
 * For this example, the d3dDevice variable is a valid
 * pointer to an IDirect3DDevice9 interface.
 *
 * Use the vertex position (camera-space) as the input
 * texture coordinates for this texture stage, and the
 * wrap mode set in the D3DRENDERSTATE_WRAP1 render state.
 */
d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEPOSITION | 1 );

Automatically generated texture coordinates are most useful as input values for a texture coordinate transformation, or to eliminate the need for your application to compute three-element vectors for cubic-environment maps.

Sphere-mapping uses a precomputed (at model time) texture map that contains the entire environment as reflected by a chrome sphere. Microsoft® Direct3D® has a texture-coordinate generation feature using render state D3DTSS_TCI_CAMERASPACENORMAL, which takes the normal of the vertex in camera space and puts it through a texture transform to generate texture coordinates. For more information, see Sphere Map Sample.

Related Topics

  • Texture Coordinate Transformations
  • Cubic Environment Mapping

© 2002 Microsoft Corporation. All rights reserved.


Texture Coordinate Transformations

Microsoft® Direct3D® devices can transform the texture coordinates for vertices by applying a 4x4 matrix. The system applies transformations to texture coordinates in the same manner as geometry. Any transformation (scale, rotation, translation, projection, shear, or any combination of these) can be done with a 4x4 matrix.

Note Direct3D does not modify transformed and lit vertices. As a result, an application using transformed and lit vertices cannot use Direct3D to transform the texture coordinates of the vertices.

Devices that support hardware-accelerated transformation and lighting operations (TnLHAL Device) also accelerate the transformation of texture coordinates. When hardware acceleration of transformations isn't available, platform-specific optimizations in the Direct3D geometry pipeline apply to texture coordinate transformations.

Texture coordinate transformations are useful for producing special effects while avoiding the need to directly modify the texture coordinates of your geometry. You could use simple translation or rotation matrices to animate textures on an object, or you can transform texture coordinates that are automatically generated by Direct3D to simplify and perhaps accelerate advanced effects such as projected textures and dynamic light-mapping. Additionally, you might use texture coordinate transforms to reuse a single set of texture coordinates for multiple purposes, in multiple texture stages.

Setting and Retrieving Texture Coordinate Transformations

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the IDirect3DDevice9::SetTransform and IDirect3DDevice9::GetTransform methods. These methods accept the D3DTS_TEXTURE0 through D3DTS_TEXTURE7 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to apply to the texture coordinates for texture stage 0.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

D3DMATRIX matTrans = D3DXMatrixIdentity( NULL );

// Set up the matrix for the desired transformation.
d3dDevice->SetTransform( D3DTS_TEXTURE0, &matTrans );

Enabling Texture Coordinate Transformations

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the D3DTEXTURETRANSFORMFLAGS enumerated type.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them.

// For this example, assume the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_DISABLE );

The other values defined in D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many resulting texture coordinate elements are passed to the rasterizer. For example, take the following code.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT2 );

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, and then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );

This example informs the system to pass three texture coordinate elements to the rasterizer. The rasterizer divides the first two elements by the third, producing the 2-D texture coordinates needed to address the texture.

© 2002 Microsoft Corporation. All rights reserved.


Special Effects

This topic contains examples of special effects accomplished with texture coordinate processing.

  • Animating textures (by translation or rotation) on a model
  • Creating texture coordinates as a linear function of a model's camera-space position
  • Performing environment mapping with a cubic environment map
  • Performing projective texturing

Animating textures (by translation or rotation) on a model

  • Define two-dimensional (2-D) texture coordinates in your vertex format.
    // Use a single texture, with 2-D texture coordinates. This
// bit-pattern should be expanded to include position, normal,
// and color information as needed.
DWORD dwFVFTex = D3FVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0);
  • Configure the rasterizer to use 2-D texture coordinates.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set an appropriate texture coordinate transformation matrix.
    // M is a D3DMATRIX being set to translate texture
// coordinates in the U and V directions.
//      1   0  0  0
//      0   1  0  0
//      du dv  1  0 (du and dv change each frame)
//      0   0  0  1

D3DMATRIX M = D3DXMatrixIdentity(); // declared in d3dutil.h
M._31 = du;
M._32 = dv;

Creating texture coordinates as a linear function of a model's camera-space position

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation.
    // The input vertices have no texture coordinates, saving
// bandwidth. Three texture coordinates are generated by
// using vertex position in camera space (x, y, z).
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Instruct the rasterizer to expect 2-D texture coordinates.
    // Two output coordinates are used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set a matrix that applies a linear function.
    // Generate texture coordinates as linear functions
// so that:
//      u = Ux*x + Uy*y + Uz*z + Uw
//      v = Vx*x + Vy*y + Vz*z + Vw
// The matrix M for this case is:
//      Ux  Vx  0  0
//      Uy  Vy  0  0
//      Uz  Vz  0  0
//      Uw  Vw  0  0

SetTransform(D3DTS_TEXTURE0, &M);

Performing environment mapping with a cubic environment map

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates as reflection vectors for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR);
  • Instruct the rasterizer to expect texture coordinates with three elements.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3);

Performing projective texturing

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Create and apply the texture projection matrix. This is beyond the scope of this documentation, and is the topic of several industry articles.
  • Instruct the rasterizer to expect three-element projected texture coordinates.
    // Two output coordinates are used.

SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3);

© 2002 Microsoft Corporation. All rights reserved.


Texture Filtering

When Microsoft® Direct3D® renders a primitive, it maps the 3-D primitive onto a 2-D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2-D rendered image. For every pixel in the primitive's on-screen image, it must obtain a color value from the texture. This process is called texture filtering.

When a texture filter operation is performed, the texture being used is typically also being magnified or minified. In other words, it is being mapped into a primitive image that is larger or smaller than itself. Magnification of a texture can result in many pixels being mapped to one texel. The result can be a chunky appearance. Minification of a texture often means that a single pixel is mapped to many texels. The resulting image can be blurry or aliased. To resolve these problems, some blending of the texel colors must be performed to arrive at a color for the pixel.

Direct3D simplifies the complex process of texture filtering. It provides you with three types of texture filtering - linear filtering, anisotropic filtering, and mipmap filtering. If you select no texture filtering, Direct3D uses a technique called nearest-point sampling.

Each type of texture filtering has advantages and disadvantages. For instance, linear texture filtering can produce jagged edges or a chunky appearance in the final image. However, it is a computationally low-overhead method of texture filtering. Filtering with mipmaps usually produces the best results, especially when combined with anisotropic filtering. However, it requires the most memory of the techniques that Direct3D supports.

Applications that use texture interface pointers should set the current texture filtering method by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the D3DTEXTUREFILTERTYPE enumerated type as the value in the third parameter.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics.

  • Nearest-Point Sampling
  • Linear Texture Filtering
  • Anisotropic Texture Filtering
  • Texture Filtering with Mipmaps
Note Although the texture-filtering render states present in the D3DRENDERSTATETYPE enumerated type are superseded by texture stage states, the IDirect3DDevice9::SetRenderState, as opposed to the IDirect3DDevice2 version, does not fail if you attempt to use them. Rather, the system maps the effects of these render states to the first stage in the multitexture cascade, stage 0. Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.

© 2002 Microsoft Corporation. All rights reserved.


Nearest-Point Sampling

Applications are not required to use texture filtering. Microsoft® Direct3D® can be set so that it computes the texel address, which often does not evaluate to integers, and copies the color of the texel with the closest integer address. This process is called nearest-point sampling. This can be a fast and efficient way to process textures if the size of the texture is similar to the size of the primitive's image on the screen. If not, the texture must be magnified or minified. The result can be a chunky, aliased, or blurred image.

Your C++ application can select nearest-point sampling by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_POINT in the third parameter.

You should use nearest-point sampling carefully, because it can sometimes cause graphic artifacts when the texture is sampled at the boundary between two texels. This boundary is the position along the texture (u or v) at which the sampled texel transitions from one texel to the next. When point sampling is used, the system chooses one sample texel or the other, and the result can change abruptly from one texel to the next texel as the boundary is crossed. This effect can appear as undesired graphic artifacts in the displayed texture. When linear filtering is used, the resulting texel is computed from both adjacent texels and smoothly blends between them as the texture index moves through the boundary.

This effect can be seen when mapping a very small texture onto a very large polygon: an operation often called magnification. For example, when using a texture that looks like a checkerboard, nearest-point sampling results in a larger checkerboard that shows distinct edges. By contrast, linear texture filtering results in an image where the checkerboard colors vary smoothly across the polygon.

In most cases, applications receive the best results by avoiding nearest-point sample wherever possible. The majority of hardware today is optimized for linear filtering, so your application should not suffer degraded performance. If the effect you desire absolutely requires the use of the nearest-point sampling - such as when using textures to display readable text characters - then your application should be extremely careful to avoid sampling at the texel boundaries, which might result in undesired effects. The following image shows what these artifacts can look like.

Six-sectioned box with noncontinuous red horizontal lines in the two upper-right squares

Notice that the two squares in the upper right of the group appear different than their neighbors, with diagonal offsets running through them. To avoid graphic artifacts like these, you must be familiar with Direct3D texture sampling rules for nearest-point filtering. Direct3D maps a floating-point texture coordinate ranging from [0.0, 1.0] (0.0 to 1.0, inclusive) to an integer texel space value ranging from [–0.5, n – 0.5], where n is the number of texels in a given dimension on the texture. The resulting texture index is rounded to the nearest integer. This mapping can introduce sampling inaccuracies at texel boundaries.

For a simple example, imagine an application that renders polygons with the D3DTADDRESS_WRAP texture addressing mode. Using the mapping employed by Direct3D, the u texture index maps as follows for a texture with a width of 4 texels.

Texture coordinates 0.0 and 1.0 at the boundary between texels

Notice that the texture coordinates, 0.0 and 1.0 for this illustration, are exactly at the boundary between texels. Using the method by which Direct3D maps values, the texture coordinates range from [–0.5, 4 – 0.5], where 4 is the width of the texture. For this case, the sampled texel is the 0 texel for a texture index of 1.0. However, if the texture coordinate was only slightly less than 1.0, the sampled texel would be the n texel instead of the 0 texel.

The implication of this is that magnifying a small texture using texture coordinates of exactly 0.0 and 1.0 with nearest-point filtering on a screen-space aligned triangle results in pixels for which the texture map is sampled at the boundary between texels. Any inaccuracies in the computation of texture coordinates, however small, results in artifacts along the areas in the rendered image which correspond to the texel edges of the texture map.

Performing this mapping of floating point texture coordinates to integer texels with perfect accuracy is difficult, computationally time-consuming, and generally not necessary. Most hardware implementations use an iterative approach for computing texture coordinates at each pixel location within a triangle. Iterative approaches tend to hide these inaccuracies because the errors are accumulated evenly during iteration.

The Direct3D reference rasterizer uses a direct-evaluation approach for computing texture indexes at each pixel location. Direct evaluation differs from the iterative approach in that any inaccuracy in the operation exhibits a more random error distribution. The result of this is that the sampling errors that occur at the boundaries can be more noticeable because the reference rasterizer does not perform this operation with perfect accuracy.

The best approach is to use nearest-point filtering only when necessary. When you must use it, it is recommended that you offset texture coordinates slightly from the boundary positions to avoid artifacts.

© 2002 Microsoft Corporation. All rights reserved.


Linear Texture Filtering

Microsoft® Direct3D® uses a form of linear texture filtering called bilinear filtering. Like Nearest-Point Sampling, bilinear texture filtering first computes a texel address, which is usually not an integer address. Bilinear filtering then finds the texel whose integer address is closest to the computed address. In addition, the Direct3D rendering module computes a weighted average of the texels that are immediately above, below, to the left of, and to the right of the nearest sample point.

Select bilinear texture filtering by invoking the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_LINEAR in the third parameter.

© 2002 Microsoft Corporation. All rights reserved.


Anisotropic Texture Filtering

The distortion visible in the texels of a 3-D object whose surface is oriented at an angle with respect to the plane of the screen is called anisotropy. When a pixel from an anisotropic primitive is mapped to texels, its shape is distorted. Microsoft® Direct3D® measures the anisotropy of a pixel as the elongation - that is, length divided by width - of a screen pixel that is inverse-mapped into texture space.

You can use anisotropic texture filtering in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to Pass D3DTEXF_ANISOTROPIC.

Your application must also set the degree of anisotropy to a value greater than one. Do this by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DSAMP_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

You can disable isotropic filtering by setting the degree of isotropy to one; any value larger than one enables it. Check the MaxAnisotropy flag in the D3DCAPS9 structure to determine the possible range of values for the degree of anisotropy.

© 2002 Microsoft Corporation. All rights reserved.


Texture Filtering with Mipmaps

A mipmap is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level, in the mipmap is a power of two smaller than the previous level. Mipmaps do not have to be square.

A high-resolution mipmap image is used for objects that are close to the user. Lower-resolution images are used as the object appears farther away. Mipmapping improves the quality of rendered textures at the expense of using more memory.

Microsoft® Direct3D® represents mipmaps as a chain of attached surfaces. The highest resolution texture is at the head of the chain and has the next level of the mipmap as an attachment. In turn, that level has an attachment that is the next level in the mipmap, and so on, down to the lowest resolution level of the mipmap.

The following illustrations shows an example of these levels. The bitmap textures represent a sign on a container in a 3-D first-person game. When created as a mipmap, the highest resolution texture is first in the set. Each succeeding texture in the mipmap set is smaller in height and width by a power of 2. In this case, the maximum-resolution mipmap is 256 pixels by 256 pixels. The next, texture is 128x128. The last texture in the chain is 64x64.

This sign has a maximum distance from which it is visible. If the user begins far away from the sign, the game displays the smallest texture in the mipmap chain, which in this case the 64x64 texture.

As the user moves the point of view closer to the sign, progressively higher-resolution textures in the mipmap chain are used. The resolution in the following illustration is 128x128.

The highest resolution texture is used when the user's point of view is at the minimum allowable distance from the sign.

This is a more efficient way of simulating perspective for textures. Rather than render a single texture at many resolutions, it is faster to use multiple textures at varying resolutions.

Direct3D can assess which texture in a mipmap set is the closest resolution to the desired output, and it can map pixels into its texel space. If the resolution of the final image is between the resolutions of the textures in the mipmap set, Direct3D can examine texels in both mipmaps and blend their color values together.

To use mipmaps, your application must build a set of mipmaps. Applications apply mipmaps by selecting the mipmap set as the first texture in the set of current textures. For more information, see Texture Blending.

Next, your application must set the filtering method that Direct3D uses to sample texels. The fastest method of mipmap filtering is to have Direct3D select the nearest texel. Use the D3DTEXF_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTEXF_LINEAR enumerated value. This selects the nearest mipmap, and then computes a weighted average of the texels surrounding the location in the texture to which the current pixel maps.

Mipmap textures are used in 3-D scenes to decrease the time required to render a scene. They also improve the scene's realism. However, they often require large amounts of memory.

Creating a Set of Mipmaps

The following example shows how your application can call the IDirect3DDevice9::CreateTexture method to build a chain of five mipmap levels: 256x256, 128x128, 64x64, 32x32, and 16x16.

// This code example assumes that the variable d3dDevice is a
//   valid pointer to a IDirect3DDevice9 interface.

IDirect3DTexture9 * pMipMap;
d3dDevice->CreateTexture(256, 256, 5, 0, D3DFMT_R8G8B8, D3DPOOL_MANAGED, &pMipMap);

The first two parameters that are accepted by IDirect3DDevice9::CreateTexture are the size and width of the top-level texture. The third parameter specifies the number of levels in the texture. If you set this to zero, Direct3D creates a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size of 1x1. The fourth parameter specifies the usage for this resource; in this case, 0 is specified to indicate no specific usage for the resource. The fifth parameter specifies the surface format for the texture. Use a value from the D3DFORMAT enumerated type for this parameter. The sixth parameter specifies a member of the D3DPOOL enumerated type indicating the memory class into which to place the created resource. Unless you are using dynamic textures, D3DPOOL_MANAGED is recommended. The final parameter takes the address of a pointer to an IDirect3DTexture9 interface.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256x128, the dimensions of the second-level mipmap are 128x64, the third-level are 64x32, and so on, down to 1x1. You cannot request a number of mipmap levels in Levels that would cause either the width or height of any mipmap in the chain to be smaller than 1. In the simple case of a 4x2 top-level mipmap surface, the maximum value allowed for Levels is three. The top-level dimensions are 4x2, the second-level dimensions are 2x1, and the dimensions for the third level are 1x1. A value larger than 3 in Levels results in a fractional value in the height of the second-level mipmap, and is therefore disallowed.

Selecting and Displaying a Mipmap

Call the IDirect3DDevice9::SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Texture Blending.

After your application selects the mipmap texture set, it must assign values from the D3DTEXTUREFILTERTYPE enumerated type to the D3DSAMP_MIPFILTER sampler state. Direct3D then automatically performs mipmap texture filtering. Enabling mipmap texture filtering is demonstrated in the following code example.

d3dDevice->SetTexture(0, pMipMap);
d3dDevice->SetTextureStageState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);

Your application can also manually traverse a chain of mipmap surfaces by using the IDirect3DTexture9::GetSurfaceLevel method and specifying the mipmap level to retrieve. The following example traverses a mipmap chain from highest to lowest resolutions.

IDirect3DSurface9 * pSurfaceLevel;
for (int iLevel = 0; iLevel < pMipMap->GetLevelCount(); iLevel++)
{
    pMipMap->GetSurfaceLevel(iLevel, &pSurfaceLevel);
    //Process this level.
    pSurfaceLevel->Release();
}

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain. An application can retrieve the number of levels in a mipmap by calling IDirect3DBaseTexture9::GetLevelCount.

© 2002 Microsoft Corporation. All rights reserved.


Texture Resources

Texture resources are implemented in the IDirect3DTexture9 interface. To obtain a pointer to a texture interface, call the IDirect3DDevice9::CreateTexture method or any of the following Direct3D extensions (D3DX) functions.

  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx

The following code example uses D3DXCreateTextureFromFile to load a texture from Tiger.bmp.

// The following code example assumes that D3dDevice
// is a valid pointer to an IDirect3DDevice9 interface.

LPDIRECT3DTEXTURE9 pTexture;

D3DXCreateTextureFromFile( d3dDevice, "tiger.bmp", &pTexture);

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to an IDirect3DDevice9 interface. The second parameter tells Microsoft® Direct3D® the name of the file from which to load the texture. The third parameter takes the address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Rendering with Texture Resources

Direct3D supports multiple texture blending through the concept of texture stages. Each texture stage contains a texture and operations that can be performed on the texture. The textures in the texture stages form the set of current textures. For more information, see Texture Blending. The state of each texture is encapsulated in its texture stage.

In a C++ application, the state of each texture must be set with the IDirect3DDevice9::SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the D3DTEXTURESTAGESTATETYPE enumerated type. The final parameter is the state value for the particular texture state.

Using texture interface pointers, your application can render a blend of up to eight textures. Set the current textures by invoking the IDirect3DDevice9::SetTexture method. Direct3D blends all current textures onto the primitives that it renders.

Note The IDirect3DDevice9::SetTexture method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Your application can set the texture wrapping state for the current textures by calling the IDirect3DDevice9::SetRenderState method. Pass a value from D3DRS_WRAP0 through D3DRS_WRAP7 as the value of the first parameter, and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in the u, v, or w directions.

Your application can also set the texture perspective and texture filtering states. See Texture Filtering.

© 2002 Microsoft Corporation. All rights reserved.


Texture Wrapping

In short, texture wrapping changes the basic way that Microsoft® Direct3D® rasterizes textured polygons using the texture coordinates specified for each vertex. While rasterizing a polygon, the system interpolates between the texture coordinates at each of the polygon's vertices to determine the texels that should be used for every pixel of the polygon. Normally, the system treats the texture as a 2-D plane, interpolating new texels by taking the shortest route from point A within a texture to point B. If point A represents the u, v position (0.8, 0.1), and point B is at (0.1,0.1), the line of interpolation looks like the following illustration.

Line of interpolation

Note that the shortest distance between A and B in this illustration runs roughly through the middle of the texture. Enabling u-texture or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u-direction and v-direction. By definition, texture wrapping causes the rasterizer to take the shortest route between texture coordinate sets, assuming that 0.0 and 1.0 are coincident. The last bit is the tricky part: You can imagine that enabling texture wrapping in one direction causes the system to treat a texture as though it were wrapped around a cylinder. For example, consider the following illustration.

This diagram shows how wrapping in the u - direction affects how the system interpolates texture coordinates. Using the same points as in the example for normal, or nonwrapped, textures, you can see that the shortest route between points A and B is no longer across the middle of the texture; it's now across the border where 0.0 and 1.0 exist together. Wrapping in the v-direction is similar, except that it wraps the texture around a cylinder that is lying on its side. Wrapping in both the u-direction and v-direction is more complex. In this situation, you can envision the texture as a torus, or doughnut.

The most common practical application for texture wrapping is to perform environment mapping. Usually, an object textured with an environment map appears very reflective, showing a mirrored image of the object's surroundings in the scene. For the sake of this discussion, picture a room with four walls, each one painted with a letter R, G, B, Y and the corresponding colors: red, green, blue, and yellow. The environment map for such a simple room might look like the following illustration.

Vertical stripes of red, green, blue, and yellow

Imagine that the room's ceiling is held up by a perfectly reflective, four-sided, pillar. Mapping the environment map texture to the pillar is simple; making the pillar look as though it is reflecting the letters and colors is not as easy. The following diagram shows a wire frame of the pillar with the applicable texture coordinates listed near the top vertices. The seam where wrapping will cross the edges of the texture is shown with a dotted line.

Rectangle with bisecting dotted line

With wrapping enabled in the u-direction, the textured pillar shows the colors and symbols from the environment map appropriately and, at the seam in the front of the texture, the rasterizer properly chooses the shortest route between the texture coordinates, assuming that u-coordinates 0.0 and 1.0 share the same location. The textured pillar looks like the following illustration.

Rectangle made up of red, green, blue, and yellow quadrants

If texture wrapping isn't enabled, the rasterizer does not interpolate in the direction needed to generate a believable, reflected image. Rather, the area at the front of the pillar contains a horizontally compressed version of the texels between u-coordinates 0.175 and 0.875, as they pass through the center of the texture. The wrap effect is ruined.

Using Texture Wrapping

To enable texture wrapping, call the IDirect3DDevice9::SetRenderState method as shown in the code example below.

d3dDevice->SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0);

The first parameter accepted by IDirect3DDevice9::SetRenderState is a render state to set. Specify one of the D3DRS_WRAP0 through D3DRS_WRAP7 enumerated values which specify which texture level to set the wrapping for. Specify the D3DWRAPCOORD_0 through D3DWRAPCOORD_3 flags in the second parameter to enable texture wrapping in the corresponding direction, or combine them to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a set of texture coordinates, set the value for the corresponding render state to 0.

Do not confuse texture wrapping with the similarly named texture addressing modes. Texture wrapping is performed before texture addressing. Be sure the texture wrapping data does not contain any texture coordinates outside of the range of [0.0, 1.0] because this will produce undefined results. For more information about texture addressing, see Texture Addressing Modes.

Displacement Map Wrapping

Displacement maps are interpolated by the tesselation engine. Because the wrap mode cannot be specified for the tessellation engine, texture wrapping cannot be performed with displacement maps. An application is able to use a set of vertices that forces the interpolation to wrap in any direction. The application can also specify the interpolation to be done as a simple linear interpolation.

© 2002 Microsoft Corporation. All rights reserved.


Texture Blending

Microsoft® Direct3D® can blend as many as eight textures onto primitives in a single pass. The use of multiple texture blending can profoundly increase the frame rate of a Direct3D application. An application employs multiple texture blending to apply textures, shadows, specular lighting, diffuse lighting, and other special effects in a single pass.

To use texture blending, your application should first check if the user's hardware supports it. This information is found in the TextureCaps member of the D3DCAPS9 structure. For details on how to query the user's hardware for texture blending capabilities, see IDirect3DDevice9::GetDeviceCaps.

Texture Stages and the Texture Blending Cascade

Direct3D supports single-pass multiple texture blending through the use of texture stages. A texture stage takes two arguments and performs a blending operation on them, passing on the result for further processing or for rasterization. You can visualize a texture stage as shown in the following illustration.

As the preceding illustration shows, texture stages blend two arguments by using a specified operator. Common operations include simple modulation or addition of the color or alpha components of the arguments, but more than two dozen operations are supported. The arguments for a stage can be an associated texture, the iterated color or alpha (iterated during Gouraud shading), arbitrary color and alpha, or the result from the previous texture stage. For more information, see Texture Blending Operations and Arguments.

Note Direct3D distinguishes color blending from alpha blending. Applications set blending operations and arguments for color and alpha individually, and the results of those settings are independent of one another.

The combination of arguments and operations used by multiple blending stages define a simple flow-based blending language. The results from one stage flow down to another stage, from that stage to the next, and so on. The concept of results flowing from stage to stage to eventually be rasterized on a polygon is often called the texture blending cascade. The following illustration shows how individual texture stages make up the texture blending cascade.

Texture blending cascade

Each stage in a device has a zero-based index. Direct3D allows up to eight blending stages, although you should always check device capabilities to determine how many stages the current hardware supports. The first blending stage is at index 0, the second is at 1, and so on, up to index 7. The system blends stages in increasing index order.

Use only the number of stages you need; the unused blending stages are disabled by default. So, if your application only uses the first two stages, it need only set operations and arguments for stage 0 and 1. The system blends the two stages, and ignores the disabled stages.

Performance Note If your application varies the number of stages it uses for different situations - such as four stages for some objects, and only two for others - you don't need to explicitly disable all previously used stages. One option is to disable the color operation for the first unused stage, then all stages with a higher index will not be applied. Another option is to disable texture mapping altogether by setting the color operation for the first texture stage (stage 0). A third option is When a texture stage has D3DTSS_COLORARG1 equal to D3DTA_TEXTURE and the texture pointer for the stage is NULL, this stage and all stages after it are not processed.

Additional information is contained in the following topics.

  • Texture Blending Operations and Arguments
  • Assigning the Current Textures
  • Creating Blending Stages
  • Alpha Texture Blending
  • Multipass Texture Blending
  • Light Mapping with Textures

© 2002 Microsoft Corporation. All rights reserved.


Texture Blending Operations and Arguments

Applications associate a blending stage with each texture in the set of current textures. Microsoft® Direct3D® evaluates each blending stage in order, beginning with the first texture in the set and ending with the eighth.

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a texture stage is used by calling IDirect3DDevice9::SetTextureStageState. You can set separate operations for the color and alpha channels, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state; specify alpha operations by using D3DTSS_ALPHAOP. Both stage states use values from the D3DTEXTUREOP enumerated type.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the D3DTEXTURESTAGESTATETYPE enumerated type. The corresponding argument values are identified using D3DTA.

Note You can disable a texture stage—and any subsequent texture blending stages in the cascade—by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

To determine the supported texture blending operations of a device, query the TextureCaps member of the D3DCAPS9 structure.

© 2002 Microsoft Corporation. All rights reserved.


Assigning the Current Textures

Microsoft® Direct3D® maintains a list of up to eight current textures. It blends these textures onto all the primitive it renders. Only textures created as texture interface pointers can be used in the set of current textures.

Applications call the IDirect3DDevice9::SetTexture method to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7, inclusive. Pass the texture interface pointer as the second parameter.

The following C++ code example demonstrates how a texture can be assigned to the set of current textures.

// This code example assumes that the variable lpd3dDev is a
// valid pointer to an IDirect3DDevice9 interface and pTexture
// is a valid pointer to an IDirect3DBaseTexture9 interface.

// Set the third texture.
d3dDevice->SetTexture(2, pTexture);
Note Software devices do not support assigning a texture to more than one texture stage at a time.

© 2002 Microsoft Corporation. All rights reserved.


Creating Blending Stages

A blending stage is a set of texture operations and their arguments that define how textures are blended. When making a blending stage, C++ applications invoke the IDirect3DDevice9::SetTextureStageState method. The first call specifies the operation that is performed. Two additional invocations define the arguments to which the operation is applied. The following code example illustrates the creation of a blending stage.

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice9 interface.

// Set the operation for the first texture.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD);

// Set argument 1 to the texture color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);

// Set argument 2 to the iterated diffuse color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

Texel data in textures contain color and alpha values. Applications can define separate operations for both color and alpha values in a single blending stage. Each operation, color, and alpha, has its own arguments. For details, see D3DTEXTURESTAGESTATETYPE.

Although not part of the Microsoft® Direct3D® application programming interface (API), you can insert the following macros into your application to abbreviate the code required for creating texture blending stages.

#define SetTextureColorStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_COLOROP, op);      \
   dev->SetTextureStageState( i, D3DTSS_COLORARG1, arg1 ); \
   dev->SetTextureStageState( i, D3DTSS_COLORARG2, arg2 );

#define SetTextureAlphaStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_ALPHAOP, op);      \
   dev->SetTextureStageState( i, D3DTSS_ALPHAARG1, arg1 );  \
   dev->SetTextureStageState( i  D3DTSS_ALPHAARG2, arg2 );

© 2002 Microsoft Corporation. All rights reserved.


Alpha Texture Blending

When Microsoft® Direct3D® renders a primitive, it generates a color for the primitive based on the primitive's material, or the colors of its vertices, and lighting information. For details, see Lights and Materials. If an application enables texture blending, Direct3D must then combine the color value of the processed polygon pixel with the pixel already stored in the frame buffer. Direct3D uses the following formula to determine the final color for each pixel in the primitive's image.

FinalColor = TexelColor × SourceBlendFactor + PixelColor × DestBlendFactor

In this formula, FinalColor is the final pixel color that is output to the target rendering surface. TexelColor represents the incoming color value, after texture filtering, that corresponds to the current pixel. For details on how Direct3D maps texels to pixels, see Texture Filtering. SourceBlendFactor is a calculated value that Direct3D uses to determine the percentage of the incoming color value to apply to the final color. PixelColor is the color of the pixel currently stored in the primitive's image. DestBlendFactor represents the percentage of the current pixel's color that will be used in the final rendered pixel. The values of SourceBlendFactor and DestBlendFactor range from 0.0 to 1.0 inclusive.

As you can see from the preceding formula, the final rendered pixel is not rendered as transparent if the SourceBlendFactor is D3DBLEND_ONE and the DestBlendFactor is D3DBLEND_ZERO. It is completely transparent if the SourceBlendFactor is D3DBLEND_ZERO and the DestBlendFactor is D3DBLEND_ONE. If an application sets these factors to any other values, the resulting final rendered pixel is blended with some degree of transparency.

After texture filtering, every pixel color value has red, green, and blue color values. By default, Direct3D uses D3DBLEND_SRCALPHA as the SourceBlendFactor and D3DBLEND_INVSRCALPHA as the DestBlendFactor. Therefore, applications can control the transparency of processed pixels by setting the alpha values in textures.

A C++ application controls the blending factors with the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Invoke the IDirect3DDevice9::SetRenderState method and pass either render state value as the value of the first parameter. The second parameter must be a member of the D3DBLEND enumerated type.

© 2002 Microsoft Corporation. All rights reserved.


Multipass Texture Blending

Microsoft® Direct3D® applications can achieve numerous special effects by applying various textures to a primitive over the course of multiple rendering passes. The common term for this is multipass texture blending. A typical use for multipass texture blending is to emulate the effects of complex lighting and shading models by applying multiple colors from several different textures. One such application is called light mapping. For more information, see Light Mapping with Textures.

Note Some devices are capable of applying multiple textures to primitives in a single pass. For details, see Texture Blending.

If the user's hardware does not support multiple texture blending, your application can use multipass texture blending to achieve the same visual effects. However, the application cannot sustain the frame rates that are possible when using multiple texture blending.

To perform multipass texture blending in a C/C++ application.

  1. Set a texture in texture stage 0 by calling the IDirect3DDevice9::SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the IDirect3DDevice9::SetTextureStageState method. The default settings are well-suited for multipass texture blending.
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states to adjust the source and destination blending factors as needed. The system blends the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.

© 2002 Microsoft Corporation. All rights reserved.


Light Mapping with Textures

For an application to realistically render a 3-D scene, it must take into account the effect that light sources have on the appearance of the scene. Although techniques such as flat and Gouraud shading are valuable tools in this respect, they can be insufficient for your needs. Microsoft® Direct3D® supports multipass and multiple texture blending. These capabilities enable your application to render scenes with a more realistic appearance than scenes rendered with shading techniques alone. By applying one or more light maps, your application can map areas of light and shadow onto its primitives.

A light map is a texture or group of textures that contains information about lighting in a 3-D scene. You can store the lighting information in the alpha values of the light map, in the color values, or in both.

If you implement light mapping using multipass texture blending, your application should render the light map onto its primitives on the first pass. It should use a second pass to render the base texture. The exception to this is specular light mapping. In that case, render the base texture first; then add the light map.

Multiple texture blending enables your application to render the light map and the base texture in one pass. If the user's hardware provides for multiple texture blending, your application should take advantage of it when performing light mapping. This significantly improves your application's performance.

Using light maps, a Direct3D application can achieve a variety of lighting effects when it renders primitives. It can map not only monochrome and colored lights in a scene, but it can also add details such as specular highlights and diffuse lighting.

Information on using Direct3D texture blending to perform light mapping is presented in the following topics.

  • Monochrome Light Maps
  • Color Light Maps
  • Specular Light Maps
  • Diffuse Light Maps

© 2002 Microsoft Corporation. All rights reserved.


Monochrome Light Maps

Some older 3-D accelerator boards do not support texture blending using the alpha value of the destination pixel. See Alpha Texture Blending for more information. These adapters also generally do not support multiple texture blending. If your application is running on an adapter such as this, it can use multipass texture blending to perform monochrome light mapping.

To perform monochrome light mapping, an application stores the lighting information in the alpha data of its light map textures. The application uses the texture filtering capabilities of Microsoft® Direct3D® to perform a mapping from each pixel in the primitive's image to a corresponding texel in the light map. It sets the source blending factor to the alpha value of the corresponding texel.

The following C++ code example illustrates how an application can use a texture as a monochrome light map.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains monochrome light map data.

// Set the light map texture as the current texture.
d3dDevice->SetTexture(0, lptexLightMap);

// Set the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);

// Set argument 1 to the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1,
       D3DTA_TEXTURE | D3DTA_ALPHAREPLICATE);

Because display adapters that do not support destination alpha blending usually do not support multiple texture blending, this example sets the light map as the first texture, which is available on all 3-D accelerator cards. The sample code sets the color operation for the texture's blending stage to blend the texture data with the primitive's existing color. It then selects the first texture and the primitive's existing color as the input data.

© 2002 Microsoft Corporation. All rights reserved.


Color Light Maps

Your application will usually render 3-D scenes more realistically if it uses colored light maps. A colored light map uses the RGB data in the light map for its lighting information.

The following C++ code example demonstrates light mapping with RGB color data.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains RGB light map data.

// Set the light map texture as the first texture.
d3dDevice->SetTexture(0, lptexLightMap);

d3dDevice->SetTextureStageState( 0,D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

This example sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.

© 2002 Microsoft Corporation. All rights reserved.


Specular Light Maps

When illuminated by a light source, shiny objects - those that use highly reflective materials - receive specular highlights. In some cases, the specular highlights produced by the lighting module is not accurate. To produce a more appealing highlight, many Microsoft® Direct3D® applications apply specular light maps to primitives.

To perform specular light mapping, add the specular light map to the primitive's texture, then modulate (multiply the result by) the RGB light map.

The following code example illustrates this process in C++.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexSpecLightMap is a valid pointer to a texture that contains RGB
// specular light map data.
// lptexLightMap is a valid pointer to a texture that contains RGB
// light map data.

// Set the base texture.
d3dDevice->SetTexture(0, lptexBaseTexture );

// Set the base texture operation and arguments.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the specular light map.
d3dDevice->SetTexture(1, lptexSpecLightMap);

// Set the specular light map operation and args.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Set the RGB light map.
d3dDevice->SetTexture(2, lptexLightMap);

// Set the RGB light map operation and arguments.
d3dDevice->SetTextureStageState(2,D3DTSS_COLOROP, D3DTOP_MODULATE);
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG2, D3DTA_CURRENT );

© 2002 Microsoft Corporation. All rights reserved.


Diffuse Light Maps

When illuminated by a light source, matte surfaces display diffuse light reflection. The brightness of diffuse light depends on the distance from the light source and the angle between the surface normal and the light source direction vector. The diffuse lighting effects simulated by lighting calculations produce only general effects.

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following C++ code example.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexDiffuseLightMap is a valid pointer to a texture that contains
// RGB diffuse light map data.

// Set the base texture.
d3dDevice->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args.
d3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the diffuse light map.
d3dDevice->SetTexture(1,lptexDiffuseLightMap );

// Set the blend stage.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );

© 2002 Microsoft Corporation. All rights reserved.


Surfaces

A surface represents a linear area of display memory. A surface usually resides in the display memory of the display card, although surfaces can exist in system memory. Surface objects are contained within the IDirect3DSurface9 interface.

An IDirect3DSurface9 interface is obtained by calling one of the following methods.

  • IDirect3DCubeTexture9::GetCubeMapSurface
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::GetBackBuffer
  • IDirect3DDevice9::GetDepthStencilSurface
  • IDirect3DDevice9::GetFrontBufferData
  • IDirect3DDevice9::GetRenderTarget
  • IDirect3DSwapChain9::GetBackBuffer
  • IDirect3DTexture9::GetSurfaceLevel

The IDirect3DSurface9 interface enables you to indirectly access memory through the IDirect3DDevice9::UpdateSurface method. This method allows you to copy a rectangular region of pixels from one IDirect3DSurface9 interface to another IDirect3DSurface9 interface. The surface interface also has methods to directly access display memory. For example, you can use the IDirect3DSurface9::LockRect method to lock a rectangular region of display memory. It is important to call IDirect3DSurface9::UnlockRect after you are done working with the locked rectangular region on the surface.

Surface formats dictate how data for each pixel in surface memory is interpreted. Microsoft® Direct3D® uses the D3DFORMAT member of the D3DSURFACE_DESC structure to describe the surface format. You can retrieve the format of an existing surface by calling the IDirect3DSurface9::GetDesc method.

Additional information can be found in the following topics.

  • Width vs. Pitch
  • Flipping Surfaces
  • Page Flipping and Back Buffering
  • Copying to Surfaces
  • Copying Surfaces
  • Accessing Surface Memory Directly
  • Private Surface Data
  • Gamma Controls

© 2002 Microsoft Corporation. All rights reserved.


Width vs. Pitch

Although the terms width and pitch are often used informally, they have very important, and distinctly different, meanings. As a result, you should understand the meanings for each, and how to interpret the values that Microsoft® Direct3D® uses to describe them.

Direct3D uses the D3DSURFACE_DESC structure to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the Height and Width members to describe the logical dimensions of the surface. Both members are measured in pixels. Therefore, the Height and Width values for a 640×480 surface are the same whether it is an 8-bit surface or a 24-bit RGB surface.

When you lock a surface using the IDirect3DSurface9::LockRect method, the method fills in a D3DLOCKED_RECT structure that contains the pitch of the surface and a pointer to the locked bits. The value in the Pitch member describes the surface's memory pitch, also called stride. Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640×480×8 surface has a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that Direct3D has reserved as a cache, so it is not safe to assume that pitch is just the width multiplied by the number of bytes per pixel. Rather, visualize the difference between width and pitch as shown in the following illustration.

Pitch and width difference

In this figure, the front buffer and back buffer are both 640×480×8, and the cache is 384×480×8.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the IDirect3DSurface9::LockRect method. Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of the problem.

For more information, see Accessing Surface Memory Directly.

© 2002 Microsoft Corporation. All rights reserved.


Flipping Surfaces

A Microsoft® Direct3D® application typically displays an animated sequence by generating the frames of the animation in back buffers and presenting them in sequence. Back buffers are organized into swap chains. A swap chain is a series of buffers that "flip" to the screen one after another. This can be used to render one scene in memory and then flip the scene to the screen when rendering is complete. This avoids the phenomenon known as tearing and allows for smoother animation.

Each device created in Direct3D has at least one swap chain. When you initialize the first Direct3D device, you set the BackBufferCount member of the D3DPRESENT_PARAMETERS structure, which tells Direct3D the number of back buffers that will be in the swap chain. The call to IDirect3D9::CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use the IDirect3DDevice9::Present method to request a surface flip operation, the pointers to surface memory for the front buffer and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. When a flipping chain contains a front buffer and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

You can create addition swap chains for a device by calling IDirect3DDevice9::CreateAdditionalSwapChain. An application can create one swap chain per view and associate each swap chain with a particular window. The application renders images in the back buffers of each swap chain, and then presents them individually. The two parameters that IDirect3DDevice9::CreateAdditionalSwapChain takes are a pointer to a D3DPRESENT_PARAMETERS structure and the address of a pointer to an IDirect3DSwapChain9 interface. You can then use IDirect3DSwapChain9::Present to display the contents of the next back buffer to the front buffer. Note that a device can only have one full-screen swap chain.

You can gain access to a specific back buffer by calling the IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer methods, which return a pointer to an IDirect3DSurface9 interface that represents the returned back buffer surface. Note that calling this method increases the internal reference count on the IDirect3DDevice9 interface so be sure to call IUnknown::Release when you are done using this surface or you will have a memory leak.

Remember, Direct3D flips surfaces by swapping surface memory pointers within the swap chain, not by swapping the surfaces themselves. This means that you will always render to the back buffer that will be displayed next.

It is important to note the distinction between a "flipping operation," as performed by a display adapter driver, and a "Present" operation applied to a swap chain created with D3DSWAPEFFECT_FLIP.

The term "flip" conventionally denotes an operation that alters the range of video memory addresses that a display adapter uses to generate its output signal, thus causing the contents of a previously hidden back buffer to be displayed. In Microsoft DirectX® 9.0, the term is often used more generally to describe the presentation of a back buffer in any swap chain created with the D3DSWAPEFFECT_FLIP swap effect.

While such "Present" operations are almost invariably implemented by flip operations when the swap chain is a full-screen one, they are necessarily implemented by copy operations when the swap chain is windowed. Furthermore, a display adapter driver may use flipping to implement Present operations against full-screen swap chains based on the D3DSWAPEFFECT_DISCARD and D3DSWAPEFFECT_COPY.

The discussion above applies to the commonly used case of a full-screen swap chain created with D3DSWAPEFFECT_FLIP.

For a more general discussion of the different swap effects for both windowed and full-screen swap chains, see D3DSWAPEFFECT.

© 2002 Microsoft Corporation. All rights reserved.


Page Flipping and Back Buffering

Page flipping is key in multimedia, animation, and game software; it is analogous to the way you can do animation with a pad of paper. On each page, the artist changes the figure slightly, so that when you flip rapidly between sheets, the drawing appears animated.

Page flipping in software is similar to this process. Microsoft® Direct3D® implements page flipping functionality through a swap chain, which is a property of the device. Initially, you set up a series of Direct3D buffers that flip to the screen in the way that the artist's paper flips to the next page. The first buffer is referred to as the color front buffer. The buffers behind it are called back buffers. Your application writes to a back buffer and then flips the color front buffer so that the back buffer appears on screen. While the system displays the image, your software is again writing to a back buffer. The process continues as long as you are animating, enabling you to animate images efficiently.

Direct3D makes it easy to set up page flipping schemes—from a simple double-buffered scheme (a color front buffer with one back buffer) to more sophisticated schemes with additional back buffers.

© 2002 Microsoft Corporation. All rights reserved.


Copying to Surfaces

When using IDirect3DDevice9::UpdateSurface, pass a rectangle on the source surface, or use NULL to specify the entire surface. You also pass a point on the destination surface to which the upper left position of the rectangle on the source image is copied. This method does not support clipping. The operation will fail unless the source rectangle and the corresponding destination rectangle are completely contained within the source and destination surfaces respectively. This method does not support alpha blending, color keys, or format conversion. Note that the destination and source surfaces must be distinct.

For other restrictions when using UpdateSurface, see IDirect3DDevice9::UpdateSurface.

The following methods are also available in C++/C for copying images to a Microsoft® Direct3D® surface.

  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • IDirect3DDevice9::UpdateSurface

Related Topics

  • IDirect3DDevice9::StretchRect

© 2002 Microsoft Corporation. All rights reserved.


Copying Surfaces

The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. The blitting device driver interface (DDI) continues to be used in Microsoft® DirectX® 9.0 as the primary mechanism for moving large rectangles of pixels on a per-frame basis, the mechanism behind the copy-oriented IDirect3DDevice9::Present method. The transportation of artwork in the blit operation is performed by the IDirect3DDevice9::UpdateTexture method. Artwork can also be copied in DirectX 9.0 by using the IDirect3DDevice9::UpdateSurface method, which copies a rectangular subset of pixels.

Note DirectX 9.0 provides Direct3D extensions (D3DX) functions that enable you to load artwork from files, apply color conversion, and resize artwork. For more information about the available functions see Texturing Functions.

Related Topics

  • IDirect3DDevice9::StretchRect

© 2002 Microsoft Corporation. All rights reserved.


Accessing Surface Memory Directly

You can directly access the surface memory by using the IDirect3DSurface9::LockRect method. When you call this method, the pRect parameter is a pointer to a RECT structure that describes the rectangle on the surface to access directly. To request that the entire surface be locked, set pRect to NULL. Also, you can specify a RECT that covers only a portion of the surface. Providing that no two rectangles overlap, two threads or processes can simultaneously lock multiple rectangles in a surface. Note that a multisample back buffer cannot be locked.

The IDirect3DSurface9::LockRect method fills a D3DLOCKED_RECT structure with all the information to properly access the surface memory. The structure includes information about the pitch and has a pointer to the locked bits. When you finish accessing the surface memory, call the IDirect3DSurface9::UnlockRect method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory.

  • Never assume a constant display pitch. Always examine the pitch information returned by the IDirect3DSurface9::LockRect method. This pitch can vary for a number of reasons, including the location of the surface memory, the display card type, or even the version of the Microsoft® Direct3D® driver. For more information, see Width vs. Pitch.
  • Make certain you copy to unlocked surfaces. Direct3D copy methods will fail if called on a locked surface.
  • Limit your application's activity while a surface is locked.
  • Always copy data aligned to display memory. Microsoft Windows® 98 uses a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to Direct3D. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.
  • A surface may not be locked if it belongs to a resource assigned to the D3DPOOL_DEFAULT memory pool unless it is a dynamic texture or a surface created using IDirect3DDevice9::CreateOffscreenPlainSurface. Back buffer surfaces, which may be accessed using the IDirect3DDevice9::GetBackBuffer and IDirect3DSwapChain9::GetBackBuffer methods, may be locked only if the swap chain was created with the Flags member of the D3DPRESENT_PARAMETERS structure set to include D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.

© 2002 Microsoft Corporation. All rights reserved.


Private Surface Data

You can store any kind of application-specific data with a surface. For example, a surface representing a map in a game might contain information about terrain.

A surface can have more than one private data buffer. Each buffer is identified by a globally unique identifier (GUID) that you supply when attaching the data to the surface.

To store private surface data, use SetPrivateData, passing a pointer to the source buffer, the size of the data, and an application-defined GUID for the data. Optionally, the source data can exist in the form of a Component Object Model (COM) object; in this case, you pass a pointer to the object's IUnknown interface pointer and you set the D3DSPD_IUNKNOWNPOINTER flag.

SetPrivateData allocates an internal buffer for the data and copies it. You can then safely free the source buffer or object. The internal buffer or interface reference is released when FreePrivateData is called. This happens automatically when the surface is freed.

To retrieve private data for a surface, you must allocate a buffer of the correct size and then call the GetPrivateData method, passing the GUID that was assigned to the data. You are responsible for freeing any dynamic memory you use for this buffer. If the data is a COM object, this method retrieves the IUnknown pointer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in pSizeOfData. If the method fails with D3DERR_MOREDATA, it returns the necessary number of bytes for the buffer.

© 2002 Microsoft Corporation. All rights reserved.


Gamma Controls

Gamma controls allow you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. Think of these controls as very simple filters that Microsoft® Direct3D® applies to data as it leaves a surface and before it is rendered on the screen.

Gamma controls are a property of a swap chain. Gamma controls make it possible to dynamically change how a surface's red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors—red when the user's character is shot, green when the character picks up a new item, and so on—without copying new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the back buffer.

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D for Microsoft DirectX® 9.0 has one swap chain as a property of the device. Because the gamma ramp is a property of the swap chain, the gamma ramp can be applied when the swap chain is windowed. The gamma ramp takes effect immediately. There is no waiting for a VSYNC operation.

The IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods allow you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display.

Gamma Ramp Levels

In Direct3D, the term gamma ramp describes a set of values that map the level of a particular color component—red, green, blue—for all pixels in the frame buffer to new levels that are received by the DAC for display. The remapping is performed by way of three look-up tables, one for each color component.

Here's how it works: Direct3D takes a pixel from the frame buffer and evaluates its individual red, green, and blue color components. Each component is represented by a value from 0 to 65535. Direct3D takes the original value and uses it to index a 256-element array (the ramp), where each element contains a value that replaces the original one. Direct3D performs this look-up and replace process for each color component of each pixel in the frame buffer, thereby changing the final colors for all the on-screen pixels.

It's handy to visualize the ramp values by graphing them. The left graph of the two following graphs shows a ramp that doesn't modify colors at all. The right graph shows a ramp that imposes a negative bias to the color component to which it is applied.

The array elements for the graph on the left contain values identical to their index—0 in the element at index 0, and 65535 at index 255. This type of ramp is the default, as it doesn't change the input values before they're displayed. The right graph provides more variation; its ramp contains values that range from 0 in the first element to 32768 in the last element, with values ranging uniformly in between. The effect is that the color component that uses this ramp appears muted on the display. You are not limited to using linear graphs; if your application can assign arbitrary mapping if needed. You can even set the entries to all zeroes to remove a color component completely from the display.

Setting and Retrieving Gamma Ramp Levels

Gamma ramp levels are effectively look-up tables that Direct3D uses to map the frame buffer color components to new levels that will be displayed. You can set and retrieve ramp levels for the primary surface by calling the IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods. IDirect3DDevice9::SetGammaRamp accepts two parameters and IDirect3DDevice9::GetGammaRamp accepts one parameter. For IDirect3DDevice9::SetGammaRamp, the first parameter is either D3DSGR_CALIBRATE or D3DSGR_NO_CALIBRATION. The second parameter, pRamp, is a pointer to a D3DGAMMARAMP structure. The D3DGAMMARAMP structure contains three 256-element arrays of WORDs, one array each to contain the red, green, and blue gamma ramps. IDirect3DDevice9::GetGammaRamp has one parameter that takes a pointer to a D3DGAMMARAMP type that will be filled with the current gamma ramp.

You can include the DDSGR_CALIBRATE value for the first parameter of IDirect3DDevice9::SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp provides a consistent and absolute gamma value for the user, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call IDirect3DDevice9::GetDeviceCaps, and examine the Caps2 member of the associated D3DCAPS9 structure after the method returns. If the D3DCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error value is returned. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 type to determine the capabilities of the device and whether a calibrator is installed.

© 2002 Microsoft Corporation. All rights reserved.


Automatic Generation of Mipmaps

Automatic generation of mipmaps takes advantage of hardware filtering during texture creation to allow functionality such as full transparency. In particular, mipmap render targets benefit from automatic generation. Because they reside in video memory, software filtering is unable to be applied efficiently.

To generate a mipmap automatically, set a new usage D3DUSAGE_AUTOGENMIPMAP at creation time. Sublevel generation from this point on is completely transparent to the application. In some instances, on some hardware, sublevel generation may take a lot of time so IDirect3DBaseTexture9::GenerateMipSubLevels can be used to provide hints to the driver to generate the sublevels at a time appropriate for the application.

IDirect3DBaseTexture9::SetAutoGenFilterType controls the filtering quality during automatic generation. Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

Use IDirect3DBaseTexture9::GetAutoGenFilterType to get the current filter type. The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT.

These methods have no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP and no failure is returned. All filter types supported by the driver for regular texture filtering are supported for autogenerated except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps.

IDirect3DDevice9::UpdateTexture is illegal when the source is an automatically generated mipmap, but the destination is not. The source can be a non-automatically generated mipmap and the destination can be an automatically generated mipmap. In this case, only the topmost matching level is updated. All other source sublevels are ignored. Similarly, when both the source and destination are automatically generated, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.

When creating an automatically generated mipmap, the Levels parameter must be set to zero or one.

To check for support for automatic generation of mipmaps, check to see that D3DCAPS2_CANAUTOGENMIPMAP is set. If it is, call IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If the return value is D3D_OK, the mipmaps are guaranteed to be autogenerated. If the return value is D3DOK_NOAUTOGEN, this means that the create call will succeed, but there won't be any mipmaps generated.

To check which filter types are supported, check to see which caps are supported by the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9.

Finally, note that D3DUSAGE_AUTOGENMIPMAP is only a hint, and specifying this during texture creation or when calling IDirect3D9::CheckDeviceFormat would not cause an error on any of the device driver interface (DDI) types.

Related Topics

  • D3DUSAGE
  • D3DCAPS2
  • D3DTEXTUREFILTERTYPE

© 2002 Microsoft Corporation. All rights reserved.


Automatic Texture Management

Texture management is the process of determining which textures are needed for rendering at a given time and ensuring that those textures are loaded into video memory. As with any algorithm, texture management schemes vary in complexity, but any approach to texture management involves the following key tasks.

  • Tracking the amount of available texture memory.
  • Calculating which textures are needed for rendering, and which are not.
  • Determining which existing texture resources can be reloaded with another texture image, and which surfaces should be destroyed and replaced with new texture resources.

Microsoft® Direct3D® implements system-supported texture management to ensure that textures are loaded for optimal performance. Texture resources that Direct3D manages are referred to as managed textures.

The texture manager tracks textures with a time-stamp that identifies when the texture was last used. It then uses a least-recently-used algorithm to determine which textures should be removed. Texture priorities are used as tie breakers when two textures are targeted for removal from memory. If two textures have the same priority value, the least-recently-used texture is removed. However, if two textures have the same time-stamp, the texture that has a lower priority is removed first.

You request automatic texture management for texture surfaces when you create them. To retrieve a managed texture in a C++ application, create a texture resource by calling IDirect3DDevice9::CreateTexture and specifying the D3DPOOL_MANAGED for the Pool parameter. You are not allowed to specify where you want the texture created. You cannot use the D3DPOOL_DEFAULT or D3DPOOL_SYSTEMMEM flags when creating a managed texture. After creating the managed texture, you can call the IDirect3DDevice9::SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the IDirect3DResource9::SetPriority method for the texture surface.

Direct3D automatically downloads textures into video memory as needed. The system might cache managed textures in local or nonlocal video memory, depending on the availability of nonlocal video memory or other factors. The cache location of your managed textures is not communicated to your application, nor is this information required to use automatic texture management. If your application uses more textures than can fit in video memory, Direct3D removes older textures from video memory to make room for the new textures. If you use a removed texture again, the system uses the original system-memory texture surface to reload the texture in the video-memory cache. Although reloading the texture is necessary, it also decreases the application's performance.

You can dynamically modify the original system-memory copy of the texture by updating or locking the texture resource. When the system detects a dirty surface—after an update is completed, or when the surface is unlocked—the texture manager automatically updates the video-memory copy of the texture. The performance hit incurred is similar to reloading a removed texture.

When entering a new level in a game, your application might need to flush all managed textures from video memory (by calling IDirect3DDevice9::EvictManagedResources).

For more information about resource management, see Managing Resources.

© 2002 Microsoft Corporation. All rights reserved.


Compressed Texture Resources

Texture maps are digitized images drawn on three-dimensional shapes to add visual detail. They are mapped into these shapes during rasterization, and the process can consume large amounts of both the system bus and memory. To reduce the amount of memory consumed by textures, Microsoft® Direct3D® supports the compression of texture surfaces. Some Direct3D devices support compressed texture surfaces natively. On such devices, when you have created a compressed surface and loaded the data into it, the surface can be used in Direct3D like any other texture surface. Direct3D handles decompression when the texture is mapped to a 3-D object.

Storage Efficiency and Texture Compression

All texture compression formats are powers of two. While this does not mean that a texture is necessarily square, it does mean that both x and y are powers of two. For example, if a texture is originally 512 by 128 bytes, the next mipmapping would be 256 by 64 and so on, with each level decreasing by a power of two. At lower levels, where the texture is filtered to 16 by 2 and 8 by 1, there will be wasted bits because the compression block is always a 4 by 4 block of texels. Unused portions of the block are padded. Although there are wasted bits at the lowest levels, the overall gain is still significant. The worst case is, in theory, a 2K by 1 texture (20 power). Here, only a single row of pixels is encoded per block, while the rest of the block is unused.

Mixing Formats Within a Single Texture

It is important to note that any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks - that is, format DXT1 - are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

Once the 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 and DXT3) or interpolated mode (format DXT4 and DXT5) for the entire texture. As with color, when interpolated mode (format DXT4 and DXT5) is selected, then either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

Direct3D provides services to compress surfaces that are used for texturing 3-D models. This section provides information about creating and manipulating the data in a compressed texture surface.

Information is contained in the following topics.

  • Opaque and 1-Bit Alpha Textures
  • Textures with Alpha Channels
  • Compressed Texture Formats
  • Using Compressed Textures

© 2002 Microsoft Corporation. All rights reserved.


Opaque and 1-Bit Alpha Textures

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or 1-bit alpha block, two 16-bit values (RGB 5:6:5 format) and a 4x4 bitmap with 2 bits per pixel are stored. This totals 64 bits for 16 texels, or four bits per texel. In the block bitmap, there are 2 bits per texel to select between the four colors, two of which are stored in the encoded data. The other two colors are derived from these stored colors by linear interpolation. This layout is shown in the following diagram.

The 1-bit alpha format is distinguished from the opaque format by comparing the two 16-bit color values stored in the block. They are treated as unsigned integers. If the first color is greater than the second, it implies that only opaque texels are defined. This means four colors are used to represent the texels. In four-color encoding, there are two derived colors and all four colors are equally distributed in RGB color space. This format is analogous to RGB 5:6:5 format. Otherwise, for 1-bit alpha transparency, three colors are used and the fourth is reserved to represent transparent texels.

In three-color encoding, there is one derived color and the fourth 2-bit code is reserved to indicate a transparent texel (alpha information). This format is analogous to RGBA 5:5:5:1, where the final bit is used for encoding the alpha mask.

The following code example illustrates the algorithm for deciding whether three- or four-color encoding is selected.

if (color_0 > color_1)
{
    // Four-color block: derive the other two colors.
    // 00 = color_0, 01 = color_1, 10 = color_2, 11 = color_3
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
    color_2 = (2 * color_0 + color_1 + 1) / 3;
    color_3 = (color_0 + 2 * color_1 + 1) / 3;
}
else
{
    // Three-color block: derive the other color.
    // 00 = color_0,  01 = color_1,  10 = color_2,
    // 11 = transparent.
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
     color_2 = (color_0 + color_1) / 2;
     color_3 = transparent;

}

It is recommended that you set the RGBA components of the transparency pixel to zero before blending.

The following tables show the memory layout for the 8-byte block. It is assumed that the first index corresponds to the y-coordinate and the second corresponds to the x-coordinate. For example, Texel[1][2] refers to the texture map pixel at (x,y) = (2,1).

This table contains the memory layout for the 8-byte (64-bit) block.

Word address | 16-bit word
0 | Color_0
1 | Color_1
2 | Bitmap Word_0
3 | Bitmap Word_1

Color_0 and Color_1, the colors at the two extremes, are laid out as follows:

Bits | Color
4:0 (LSB*) | Blue color component
10:5 | Green color component
15:11 | Red color component

*least significant bit (LSB)

Bitmap Word_0 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[0][0]
3:2 | Texel[0][1]
5:4 | Texel[0][2]
7:6 | Texel[0][3]
9:8 | Texel[1][0]
11:10 | Texel[1][1]
13:12 | Texel[1][2]
15:14 (MSB*) | Texel[1][3]

*most significant bit (MSB)

Bitmap Word_1 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[2][0]
3:2 | Texel[2][1]
5:4 | Texel[2][2]
7:6 | Texel[2][3]
9:8 | Texel[3][0]
11:10 | Texel[3][1]
13:12 | Texel[3][2]
15:14 (MSB) | Texel[3][3]

Example of Opaque Color Encoding

As an example of opaque encoding, assume that the colors red and black are at the extremes. Red is color_0, and black is color_1. There are four interpolated colors that form the uniformly distributed gradient between them. To determine the values for the 4x4 bitmap, the following calculations are used.

00 ? color_0
01 ? color_1
10 ? 2/3 color_0 + 1/3 color_1
11 ? 1/3 color_0 + 2/3 color_1

The bitmap then looks like the following graphic.

Expanded bitmap layout

This looks like the following series of colors.

Opaque encoded gradient

Example of 1-Bit Alpha Encoding

This format is selected when the unsigned 16-bit integer, color_0, is less than the unsigned 16-bit integer, color_1. An example of where this format can be used is leaves on a tree, shown against a blue sky. Some texels can be marked as transparent while three shades of green are still available for the leaves. Two colors fix the extremes, and the third is an interpolated color.

Here is an example of such a picture.

1-bit alpha example

Note that where the image is shown as white, the texel would be encoded as transparent. Also note that the RGBA components of the transparent texels should be set to zero before blending.

The bitmap encoding for the colors and the transparency is determined using the following calculations.

00 ? color_0
01 ? color_1
10 ? 1/2 color_0 + 1/2 color_1
11   ?   Transparent

The bitmap then looks like the following graphic.

Expanded bitmap layout

© 2002 Microsoft Corporation. All rights reserved.


Textures with Alpha Channels

There are two ways to encode texture maps that exhibit more complex transparency. In each case, a block that describes the transparency precedes the 64-bit block already described. The transparency is either represented as a 4x4 bitmap with 4 bits per pixel (explicit encoding), or with fewer bits and linear interpolation that is analogous to what is used for color encoding.

The transparency block and the color block are arranged as shown in the following table.

Word address | 64-bit block
3:0 | Transparency block
7:4 | Previously described 64-bit block

Explicit Texture Encoding

For explicit texture encoding (DXT2 and DXT3 formats), the alpha components of the texels that describe transparency are encoded in a 4x4 bitmap with 4 bits per texel. These four bits can be achieved through a variety of means such as dithering or by using the four most significant bits of the alpha data. However they are produced, they are used just as they are, without any form of interpolation.

The following diagram shows a 64-bit transparency block.

64-bit transparency block

Note The compression method of Microsoft® Direct3D® uses the four most significant bits.

The following tables illustrate how the alpha information is laid out in memory, for each 16-bit word.

This table contains the layout for word 0.

Bits | Alpha
3:0 (LSB*) | [0][0]
7:4 | [0][1]
11:8 | [0][2]
15:12 (MSB*) | [0][3]

*least significant bit (LSB), most significant bit (MSB)

This table contains the layout for word 1.

Bits | Alpha
3:0 (LSB) | [1][0]
7:4 | [1][1]
11:8 | [1][2]
15:12 (MSB) | [1][3]

This table contains the layout for word 2.

Bits | Alpha
3:0 (LSB) | [2][0]
7:4 | [2][1]
11:8 | [2][2]
15:12 (MSB) | [2][3]

This table contains the layout for word 3.

Bits | Alpha
3:0 (LSB) | [3][0]
7:4 | [3][1]
11:8 | [3][2]
15:12 (MSB) | [3][3]

The difference between DXT2 and DXT3 are that, in the DXT2 format, it is assumed that the color data has been premultiplied by alpha. In the DXT3 format, it is assumed that the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two four-character code (FOURCC) codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used in this format. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be the following:

if ((color_0 > color_1) OR !DXT1) {

Three-Bit Linear Alpha Interpolation

The encoding of transparency for the DXT4 and DXT5 formats is based on a concept similar to the linear encoding used for color. Two 8-bit alpha values and a 4x4 bitmap with three bits per pixel are stored in the first eight bytes of the block. The representative alpha values are used to interpolate intermediate alpha values. Additional information is available in the way the two alpha values are stored. If alpha_0 is greater than alpha_1, then six intermediate alpha values are created by the interpolation. Otherwise, four intermediate alpha values are interpolated between the specified alpha extremes. The two additional implicit alpha values are 0 (fully transparent) and 255 (fully opaque).

The following code example illustrates this algorithm.

// 8-alpha or 6-alpha block?
if (alpha_0 > alpha_1) {
    // 8-alpha block:  derive the other six alphas.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (6 * alpha_0 + 1 * alpha_1 + 3) / 7;    // bit code 010
    alpha_3 = (5 * alpha_0 + 2 * alpha_1 + 3) / 7;    // bit code 011
    alpha_4 = (4 * alpha_0 + 3 * alpha_1 + 3) / 7;    // bit code 100
    alpha_5 = (3 * alpha_0 + 4 * alpha_1 + 3) / 7;    // bit code 101
    alpha_6 = (2 * alpha_0 + 5 * alpha_1 + 3) / 7;    // bit code 110
    alpha_7 = (1 * alpha_0 + 6 * alpha_1 + 3) / 7;    // bit code 111
}
else {
    // 6-alpha block.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (4 * alpha_0 + 1 * alpha_1 + 2) / 5;    // Bit code 010
    alpha_3 = (3 * alpha_0 + 2 * alpha_1 + 2) / 5;    // Bit code 011
    alpha_4 = (2 * alpha_0 + 3 * alpha_1 + 2) / 5;    // Bit code 100
    alpha_5 = (1 * alpha_0 + 4 * alpha_1 + 2) / 5;    // Bit code 101
    alpha_6 = 0;                                      // Bit code 110
    alpha_7 = 255;                                    // Bit code 111
}

The memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 LSBs), [0][1], [0][0]
3 | [1][1] (1 LSB), [1][0], [0][3], [0][2] (1 MSB)
4 | [1][3], [1][2], [1][1] (2 MSBs)
5 | [2][2] (2 LSBs), [2][1], [2][0]
6 | [3][1] (1 LSB), [3][0], [2][3], [2][2] (1 MSB)
7 | [3][3], [3][2], [3][1] (2 MSBs)

The difference between DXT4 and DXT5 is that in the DXT4 format it is assumed that the color data has been premultiplied by alpha. In the DXT5 format, it is assumed the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used with these formats. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be:

if ((color_0 > color_1) OR !DXT1) {

© 2002 Microsoft Corporation. All rights reserved.


Compressed Texture Formats

This section contains information about the internal organization of compressed texture formats. You do not need these details to use compressed textures, because you can use Direct3D extensions (D3DX) functions for conversion to and from compressed formats. However, this information is useful if you want to operate on compressed surface data directly.

Microsoft® Direct3D® uses a compression format that divides texture maps into 4x4 texel blocks. If the texture contains no transparency—is opaque—or if the transparency is specified by a 1-bit alpha, an 8-byte block represents the texture map block. If the texture map does contain transparent texels, using an alpha channel, a 16-byte block represents it.

  • Opaque and 1-Bit Alpha Textures
  • Textures with Alpha Channels
Note Any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks—that is, format DXT1—are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

When 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 or DXT3) or interpolated mode (format DXT4 or DXT5) for the entire texture. As with color, when interpolated mode is selected, either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

The pitch for DXTn formats is different from what was returned in Microsoft DirectX® 7.0. It now refers the pitch of a row of blocks. For example, if you have a width of 16, then you will have a pitch of four blocks (4*8 for DXT1, 4*16 for DXT2-5.)

© 2002 Microsoft Corporation. All rights reserved.


Using Compressed Textures

Determining Support for Compressed Textures

Before your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling the IDirect3D9::CheckDeviceFormat method. This method determines whether a surface format can be used as a texture on a device representing the adapter.

To test the adapter, specify any pixel format that uses the DXT1, DXT2, DXT3, DXT4, or DXT5 four-character codes (FOURCCs). If IDirect3D9::CheckDeviceFormat returns D3D_OK, the device can create texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Microsoft® Direct3D® by calling the IDirect3DDevice9::SetTexture method. The following code example shows how to determine if the adapter supports a compressed texture format.

BOOL IsCompressedTextureFormatOk( D3DFORMAT TextureFormat,
                                  D3DFORMAT AdapterFormat ) {
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          TextureFormat);

    return SUCCEEDED( hr );
}

If the device does not support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing.

Creating Compressed Textures

After creating a device that supports a compressed texture format on the adapter, you can create a compressed texture resource. Call IDirect3DDevice9::CreateTexture and specify a compressed texture format for the Format parameter.

Before loading an image into a texture object, retrieve a pointer to the texture surface by calling the IDirect3DTexture9::GetSurfaceLevel method.

Now you can use any D3DXLoadSurface xxx function to load an image to the surface that was retrieved by using IDirect3DTexture9::GetSurfaceLevel. These functions handle conversion to and from compressed texture formats.

You can create and convert compressed texture (DDS) files using the DXTex Tool supplied with the software development kit (SDK).

The advantage of this behavior is that an application can copy the contents of a compressed surface to a file without calculating how much storage is required for a surface of a particular width and height in the specific format.

The following table shows the five types of compressed textures. For more information about how the data is stored, see Compressed Texture Formats. You only need this information if you are writing your own compression routines.

FOURCC | Description | Alpha premultiplied?
DXT1 | Opaque/1-bit alpha | N/A
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

Note When you transfer data from a nonpremultiplied format to a premultiplied format, Direct3D scales the colors based on the alpha values. Transferring data from a premultiplied format to a nonpremultiplied format is not supported. If you try to transfer data from a premultiplied alpha source to a nonpremultiplied alpha destination, the method returns D3DERR_INVALIDCALL. If you transfer data from a premultiplied alpha source to a destination that has no alpha, the source color components, which have been scaled by alpha, are copied as is.

Decompressing Compressed Texture Surfaces

As with compressing a texture surface, decompressing a compressed texture is performed through Direct3D copying services.

To copy a compressed texture surface to a uncompressed texture surface, use the function D3DXLoadSurfaceFromSurface. This functions handles compression to and from compressed and uncompressed surfaces.

© 2002 Microsoft Corporation. All rights reserved.


Hardware Considerations for Texturing

Current hardware does not necessarily implement all the functionality that the Microsoft® Direct3D® interface enables. Your application must test user hardware and adjust its rendering strategies accordingly.

Many 3-D accelerator cards do not support diffuse iterated values as arguments to blending units. However, your application can introduce iterated color data when it performs texture blending.

Some 3-D hardware may not have a blending stage associated with the first texture. On these adapters, your application must perform blending in the second and third texture stages in the set of current textures.

Because of limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by IDirect3DDevice9. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTEXF_POINT mipmap filter mode, which is widely supported.

© 2002 Microsoft Corporation. All rights reserved.


Volume Texture Resources

Volume textures are three-dimensional collections of pixels (texels) that can be used to paint a two-dimensional primitive such as a triangle or a line. Three-element texture coordinates are required for each vertex of a primitive that is to be textured with a volume. As the primitive is drawn, each contained pixel is filled with the color value from some pixel within the volume, in accordance with rules analogous to the two-dimensional texture case. Volumes are not rendered directly because there are no three-dimensional primitives that can be painted with them.

You can use volume textures for special effects such as patchy fog, explosions, and so on.

Volumes are organized into slices and can be thought of as width x height 2-D surfaces stacked to make a width x height x depth volume. Each slice is a single row. Volumes can have subsequent levels in which the dimensions of each level are truncated to half the dimensions of the previous level. The illustration below gives an idea of what a volume texture with multiple levels looks like.

Volume texture with 8x2x4, 4x1x2, and 2x1x1 cube representations

Creating a Volume Texture

The code examples below show the steps required to use a volume texture.

First, specify a custom vertex type that has three texture coordinates for each vertex, as shown in this code example.

struct VOLUMEVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu, tv, tw;
};

#define D3DFVF_VOLUMEVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|
                             D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE3(0))

Next, fill the vertices with data.

VOLUMEVERTEX g_vVertices[4] =
{
    { 1.0f, 1.0f, 0.0f, 0xffffffff, 1.0f, 1.0f, 0.0f },
    {-1.0f, 1.0f, 0.0f, 0xffffffff, 0.0f, 1.0f, 0.0f },
    { 1.0f,-1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 0.0f },
    {-1.0f,-1.0f, 0.0f, 0xffffffff, 0.0f, 0.0f, 0.0f }
};

Now, create a vertex buffer and fill it with data from the vertices.

The next step is to use the IDirect3DDevice9::CreateVolumeTexture method to create a volume texture, as shown in this code example.

LPDIRECT3DVOLUMETEXTURE9 pVolumeTexture;
d3dDevice->CreateVolumeTexture( 8, 4, 4, 1, 0, D3DFMT_R8G8B8,D3DPOOL_MANAGED,
                                &pVolumeTexture );

Before rendering the primitive, set the current texture to the volume texture created above. The code example below shows the entire rendering process for a strip of triangles.

if( SUCCEEDED( d3dDevice->BeginScene() ) )
{
    // Draw the quad, with the volume texture.
    d3dDevice->SetTexture( 0, pVolumeTexture );
    d3dDevice->SetFVF( D3DFVF_VOLUMEVERTEX );
    d3dDevice->SetStreamSource( 0, pVB, sizeof(VOLUMEVERTEX) );
    d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);

   // End the scene.
   d3dDevice->EndScene();
}

© 2002 Microsoft Corporation. All rights reserved.


Programmable Pipeline

In Microsoft® Direct3D® for Microsoft DirectX® 9.0, procedural models are used for specifying the behavior of the vertex transformation and lighting pipeline and the pixel texture blending pipeline.

  • Integration of Vertex Shaders into the Geometry Pipeline
  • Integration of Pixel Shaders into the Graphics Pipeline
  • Programmable Stream Model
  • Vertex Shaders
  • Pixel Shaders

There are many advantages to a program model-based syntax for specifying the behavior of the hardware.

First, a procedural model allows a more general syntax for specifying common operations. Fixed-function, as opposed to programmable, application programming interfaces (APIs) must define modes, flags, and so on for an increasing number of operations that need to be expressed. Further, with the increasing power of the hardware - more colors, more textures, more vertex streams, an so on - the token space for the operations multiplied by the data inputs becomes complex. A programmability model, on the other hand, enables even simple operations such as getting the right color and right texture into the right part of the lighting model in a more direct fashion. You do not have to search through all the possible modes; you just have to learn the computer architecture and specify the desired algorithm to be performed.

For example, the following well-known features can be supported.

  • Basic geometry transformations
  • Simple lighting models
  • Vertex blending for skinning
  • Vertex morphing (tweening)
  • Texture transforms
  • Texture generation
  • Environment mapping

Second, a procedural model provides an easy mechanism for developing new operations. There are many operations that developers find they need that are not supported in current APIs. In most cases, this is not due to limitations in the capabilities of the hardware but rather to restrictions in the APIs. In general, these operations are also simpler and therefore faster than trying to extract the same behavior by contorting a fixed function API to an extent beyond its designer's expectations.

Examples of new features expected to be commonly implemented include the following:

  • Matrix Palette Skinning. Character animation with 8-10 bones per mesh.
  • Anisotropic Lighting. Lighting that currently can be done only at the cost of textures for look-up tables.
  • Membrane Shaders. Shaders for balloons, skin, and so on (1/cos(eye DOT normal)).
  • Kubelka-Munk Shaders. Shaders that take into account light that penetrates the surface.
  • Procedural Geometry. Compositing meshes with procedural ones (spheres) to simulate muscles moving under the skin.
  • Displacement Mapping. Modifying a mesh with a wave pattern or hump that can be tiled/repeated.

Third, a procedural model provides for scalability and evolvability. Hardware capabilities are continuing to evolve rapidly, and programmatic representations can help adapt the API because they scale very well. New features and capabilities can be easily exposed in an incremental way by the following operations.

  • Adding new instructions
  • Adding new data inputs
  • Adding new capabilities from the fixed-function to the programmable portion of the pipeline

Code is the representation that has the best scaling properties for representing complexity. Further, the amount of code that must change inside Direct3D is very small for new features added to the programmable shaders.

Fourth, a procedural model offers familiarity. Software developers understand programming better than they do hardware. An API that truly caters to software developers should map hardware functionality into a code paradigm.

Fifth, a procedural model follows in the footsteps of a photo-real rendering heritage. There has been a tradition of using programmable shaders in high-end photo-real rendering for many years. In general, this area is unconstrained by performance, so programmable shaders represent the ultimate no-compromise goal for rendering technologies.

Lastly, a procedural model enables direct mapping to the hardware. Most current 3-D hardware, at the vertex processing stage at least, is actually fairly programmable. The programmability through the API enables the application to map directly to this hardware. This enables you to manage the hardware resources according to their requirements. With a limited set of registers or instructions that can be run, it is difficult to make a fixed-function implementation that can have all its features enabled independently. If you turn on too many features that require a shared resource, they can stop working in unexpected ways. The programmable API model follows in the DirectX tradition of eliminating this problem by letting the application developer talk directly to the hardware, making any such limitations transparent.

© 2002 Microsoft Corporation. All rights reserved.


Integration of Vertex Shaders into the Geometry Pipeline

When in operation, a programmable vertex shader replaces the transformation and lighting module in the Microsoft® Direct3D® geometry pipeline. In effect, state information regarding transformation and lighting operations are ignored. However, when the vertex shader is disabled and fixed function processing is returned, all current state settings apply.

Any tessellation of high-order primitives should be done before execution of the vertex shader. Implementations that perform surface tessellation after the shader processing must do so in a way that is not apparent to the application and shader code. Because no semantic information is normally provided before the shader, a special token is used to identify which input stream component represents the base position relative to which all other components are interpolated. No noninterpolable data channels are supported.

On output, the vertex shader must generate vertex positions in homogeneous clip space. Additional data that can be generated includes texture coordinates, colors, fog factors and so on.

The standard graphics pipeline processes the vertices output by the shader, including the following tasks.

  • Primitive assembly
  • Clipping against the frustum and user clipping planes
  • Homogeneous divide
  • Viewport scaling
  • Backface and viewport culling
  • Triangle setup
  • Rasterization

Clipping space is the same for Microsoft DirectX® 9.0 vertex shaders and fixed function vertex processing. For details, see Clipping Volumes.

Programmable geometry is a mode within the Direct3D application programming interface (API). When it is enabled, it partially replaces the vertex pipeline. When it is disabled, the API switches back to fixed function vertex processing. Execution of vertex shaders does not change the internal Direct3D state, and no Direct3D state is available for shaders.

Use IDirect3DDevice9::CreateVertexShader to create a vertex shader, and IDirect3DDevice9::SetVertexShader to set the programmable shader before making any Draw calls.

© 2002 Microsoft Corporation. All rights reserved.


Integration of Pixel Shaders into the Graphics Pipeline

Pixel processing is performed by pixel shaders on individual pixels. Pixel shaders can work by themselves or in concert with vertex shaders and streams. You cannot program pixel shaders in a vacuum; they depend on the upstream components.

The sequence of operations in the pixel pipeline is as follows:

  • Triangle setup
  • Pixel shader (replaces fixed format multitexture)
    • Iterate colors, texcoords, etc.
    • Sample textures
    • Texture/color blend
  • Fog blend
  • Alpha, stencil, depth testing
  • Frame-buffer blend

The inputs to the pixel shader come from the outputs of the vertex shader. Registers v0 and v1 contain the vertex colors from vertex shader output registers oD0 and oD1. The textures in the color stages, referenced by pixel shader instructions like tex t0, are sampled using the texture coordinates in the vertex shader output register corresponding to that stage, like oT0. Pixel shaders use color and alpha-blending instructions and texture-addressing instructions to manipulate these inputs and calculate a result. The result emitted by the pixel shader is the contents of register r0 or the output pixel color. Whatever it contains when the shader completes processing is sent to the fog stage and render target blender for further processing. Vertex shader outputs can provide pixel shader inputs.

The ps_3_0 shader model has a few different concepts from ps_1_X/ps_2_0.

  • In version 3_0 pixel shaders, the final fog blending is expected to be performed by the pixel shader. Consequently, the fog blending stage of the pixel pipeline is disabled and pixel shader output is sent to the alpha/stencil/depth testing stage of the pixel pipeline.
  • Version 3_0 vertex shaders no longer support color (oDn) or texture (oTn) registers. They now use output (on) registers whose meaning is defined by declaration instructions in the vertex shader. For more information about registers or declarations in vs_3_0, see Registers - vs_3_0. See dcl_usage.

© 2002 Microsoft Corporation. All rights reserved.


Programmable Stream Model

This section describes shaders that can be used for the programmable stream model.

  • ColorVertex Shader
  • Single Texture Shader
  • Multi-Texture Shader

Using Streams

Microsoft® DirectX® 8.0 introduced the notion of a stream to bind data to input registers for use by shaders. A stream is a uniform array of component data, where each component consists of one or more elements that represent a single entity such as position, normal, color, and so on. Streams enable graphic chips to perform a direct memory access (DMA) from multiple vertex buffers in parallel and also provide a more natural mapping from application data. They also enable trivial multitexture versus multipass. Think of it like this:

  • A vertex is composed of n streams.
  • A stream is composed of m elements.
  • An element is [position, color, normal, texture coordinate].

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

The mapping of the input vertex elements to the vertex input registers for programmable vertex shaders is defined in the shader declaration, but the input vertex elements do not have specific semantics about their use. The interpretation of the input vertex elements is programmed using the shader instructions. The vertex shader function is defined by an array of instructions that are applied to each vertex. The vertex output registers are explicitly written to, using instructions in the shader function.

For this discussion, though, be less concerned with the semantic mapping of elements to registers and more concerned with the questions "why use streams?" and "what problem do streams solve?". The main benefit of streams is that they remove the vertex data costs previously associated with multitexturing. Before streams, a user had to either duplicate vertex data sets to handle the single and multitexture case with no unused data elements, or carry data elements that would be unused except in the multitexture case.

Here is an example of using two sets of vertex data, one for single texture and one for multitexturing.

struct CUSTOMVERTEX_TEX1
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
};

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

The alternative is to have a single vertex element that contained both sets of texture coordinates.

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

With this vertex data, only one copy of the position and color data are carried in memory, at the expense of carrying both sets of texture coordinates around for rendering even in the single texture case.

Now that the tradeoff is clear, streams provide an elegant fix to this dilemma. Here is a set of vertex definitions to support three streams: one with position and color, one with the first set of texture coordinates, and one with the second set of texture coordinates.

// multistream vertex
// stream 0, pos, diffuse, specular
struct POSCOLORVERTEX
{
    FLOAT x, y, z;
    DWORD diffColor, specColor;
};
#define D3DFVF_POSCOLORVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_SPECULAR)

// stream 1, tex coord 0
struct TEXC0VERTEX
{
    FLOAT tu1, tv1;
};
#define D3DFVF_TEXC0VERTEX (D3DFVF_TEX1)

// stream 2, tex coord 1
struct TEXC1VERTEX
{
    FLOAT tu2, tv2;
};
#define D3DFVF_TEXC1VERTEX (D3DFVF_TEX0)

The vertex declaration would be:

// multitexture - multistream

D3DVERTEXELEMENT9 dwDecl3[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  0 },
    { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  1 },
    { 1, 36, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0 },
    { 2, 44, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0 },
    D3DDECL_END()
};

Now create the vertex declaration object and set it as shown:

LPDIRECT3DVERTEXDECLARATION9 m_pVertexDeclaration;
g_d3dDevice->CreateVertexDeclaration( dwDecl3, &m_pVertexDeclaration );

m_pd3dDevice->SetVertexDeclaration( m_pVertexDeclaration );

Examples of Combinations

One Stream Diffuse Color

The vertex declaration and stream settings for diffuse color rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  0 },
    { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  1 },
    D3DDECL_END()
};

   m_pd3dDevice->SetStreamSource( 0, m_pVBVertexShader0, 0,
                                      sizeof(CUSTOMVERTEX) );
   m_pd3dDevice->SetStreamSource( 1, NULL, 0, 0);
   m_pd3dDevice->SetStreamSource( 2, NULL, 0, 0);

Two Streams with Color and Texture

The vertex declaration and stream settings for single texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  0 },
    { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  1 },

    { 1, 36, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0 },

    D3DDECL_END()
};

   m_pd3dDevice->SetStreamSource( 0, m_pVBPosColor, 0,
                                           sizeof(POSCOLORVERTEX) );
   m_pd3dDevice->SetStreamSource( 1, m_pVBTexC0, 0,
                                           sizeof(TEXC0VERTEX) );
   m_pd3dDevice->SetStreamSource( 2, NULL, 0, 0);

Two Streams with Color and two Textures

The vertex declaration and stream settings for two-texture multi-texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  0 },
    { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR,  1 },

    { 1, 36, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0 },

    { 2, 44, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0 },

    D3DDECL_END()
};

m_pd3dDevice->SetStreamSource( 0, m_pVBPosColor, 0,
                                          sizeof(POSCOLORVERTEX) );
m_pd3dDevice->SetStreamSource( 1, m_pVBTexC0, 0,
                                          sizeof(TEXC0VERTEX) );
m_pd3dDevice->SetStreamSource( 2, m_pVBTexC1, 0,
                                          sizeof(TEXC1VERTEX) );

In every case, the following IDirect3DDevice9::DrawPrimitive invocation suffices.

       m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, NUM_TRIS );

This shows the flexibility of streams in solving the problem of data duplication/redundant data transmission across the bus (that is, of wasting bandwidth).

© 2002 Microsoft Corporation. All rights reserved.


ColorVertex Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and a diffuse color.

The first step is to declare the structures that hold the position and color as shown in the code example below.

struct XYZBuffer
{
    FLOAT x, y, z;
};

struct ColBuffer
{
    D3DCOLOR color;
};

The next step is to create a vertex shader declaration as shown in the code below.

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 1, 0, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,    0 },
    D3DDECL_END()
};

Now create the vertex declaration object:

LPDIRECT3DVERTEXDECLARATION9 m_pVertexDeclaration;
g_d3dDevice->CreateVertexDeclaration( decl, &m_pVertexDeclaration );

The next step is to call the IDirect3DDevice9::CreateVertexShader method to create the vertex shader. But first, the shader must be assembled.

TCHAR               strVertexShaderPath[512];
LPD3DXBUFFER        pCode;
LPDIRECT3DVERTEXSHADER9	m_pVertexShader;

hr = DXUtil_FindMediaFileCb( strVertexShaderPath,
                      sizeof(strVertexShaderPath), _T("ShaderFile.vsh");

hr = D3DXAssembleShaderFromFile( strVertexShaderPath, NULL, NULL,
                      dwFlags, &pCode, NULL );

g_d3dDevice->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                      &m_pVertexShader );

The code example below shows how to set the vertex shader, set the stream source, and then render the triangle list.

g_pd3dDevice->SetVertexDeclaration( m_pVertexDeclaration );
g_d3dDevice->SetVertexShader( m_pVertexShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, sizeof(XYZBuffer));
g_d3dDevice->SetStreamSource( 1, colbuf, sizeof(ColBuffer));
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,
                                   0, max - min + 1, 0, count / 3 );

© 2002 Microsoft Corporation. All rights reserved.


Single Texture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and texture coordinates.

The first step is to declare the structures that hold the position and texture coordinates as shown in the code example below.

struct XYZBuffer
{
    float x, y, z;
};

struct TEX0Buffer
{
    float tu, tv;
};

The next step is to create a vertex shader declaration as shown in the code below.

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 1, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
    D3DDECL_END()
};

The next step is to call the IDirect3DDevice9::CreateVertexShader method to create the vertex shader. But first, the shader must be assembled.

TCHAR               strVertexShaderPath[512];
LPD3DXBUFFER        pCode;
LPDIRECT3DVERTEXSHADER9  m_pVertexShader;

hr = m_pd3dDevice->CreateVertexDeclaration( decl, &m_pVertexDeclaration );

hr = DXUtil_FindMediaFileCb( strVertexShaderPath,
                sizeof(strVertexShaderPath), _T("ShaderFile.vsh");

hr = D3DXAssembleShaderFromFile( strVertexShaderPath, NULL, NULL,
                      dwFlags, &pCode, NULL );

g_d3dDevice->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                                   &m_pVertexShader );

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

g_d3dDevice->SetVertexShader( m_pVertexShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, 0, sizeof(XYZBuffer));
g_d3dDevice->SetStreamSource( 1, tex0buf, 0, sizeof(TEX0Buffer));
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,
                                  0, max - min + 1, 0, count / 3 );

© 2002 Microsoft Corporation. All rights reserved.


Multi-Texture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and multiple texture coordinates for multiple textures.

The first step is to declare the structures that holds the position and color as shown in the code example below.

struct XYZBuffer
{
    float x, y, z;
};

struct Tex0Buffer
{
    float tu, tv;
};

struct Tex1Buffer
{
    float tu2, tv2;
};

The next step is to create a vertex shader declaration as shown in the code below.

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 1, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
    { 2, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
    D3DDECL_END()
};

Now create the vertex declaration object:

LPDIRECT3DVERTEXDECLARATION9 m_pVertexDeclaration;
g_d3dDevice->CreateVertexDeclaration( decl, &m_pVertexDeclaration );

The next step is to call the IDirect3DDevice9::CreateVertexShader method to create the vertex shader. But first, the shader must be assembled.

TCHAR               strVertexShaderPath[512];
LPD3DXBUFFER        pCode;
LPDIRECT3DVERTEXSHADER9  m_pVertexShader;

hr = DXUtil_FindMediaFileCb( strVertexShaderPath,
                sizeof(strVertexShaderPath), _T("ShaderFile.vsh");

hr = D3DXAssembleShaderFromFile( strVertexShaderPath, NULL, NULL,
                      dwFlags, &pCode, NULL );

g_d3dDevice->CreateVertexShader( (DWORD*)pCode->GetBufferPointer(),
                                   &m_pVertexShader );

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

g_pd3dDevice->SetVertexDeclaration( m_pVertexDeclaration );
g_d3dDevice->SetVertexShader( m_pVertexShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, 0, sizeof(XYZBuffer) );
g_d3dDevice->SetStreamSource( 1, tex0buf, 0, sizeof(Tex0Buffer) );
g_d3dDevice->SetStreamSource( 2, tex1buf, 0, sizeof(Tex1Buffer) );
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3 );

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shaders

Prior to Microsoft® DirectX® 8.x, Microsoft Direct3D® operated a fixed function pipeline for converting 3-D geometry to rendered screen pixels. The user sets attributes of the pipeline that control how Direct3D transforms, lights, and renders pixels. The fixed function vertex format is declared at compile time and determines the input vertex format. Once defined, the user has little control over pipeline changes during runtime.

  • Create a Vertex Shader - This section contains a code sample that uses a vertex shader to apply a constant color to object vertices. This example contains a detailed explanation of the methods used.
  • Vertex Color - Additional examples shows more code samples that add textures and blend vertex colors and textures.
  • Texturing - Additional examples shows more code samples that add textures and blend vertex colors and textures.
  • Texture Map with Lighting - Additional examples shows more code samples that add textures and blend vertex colors and textures.
  • Decoupling Vertex Shaders and Vertex Declarations - Vertex shader declarations are now separate from vertex declarations. This section contains details on how to map between declarations in the fixed function and vertex shader pipelines.

Programmable shaders add a new dimension to the graphics pipeline by allowing the transform, lighting, and rendering functionality to be modified at runtime. A shader is declared at runtime but, when done, the user can change which shader is active and control the shader data dynamically, using streaming data. This gives the user a new level of dynamic flexibility over the way that pixels are rendered.

A vertex shader file contains vertex shader instructions. Vertex shaders can control vertex color and how textures are applied to vertices. Lighting can be added through the use of vertex shader instructions. The shader instruction file contains ASCII text so it is readable and in some ways looks similar to assembly language. A vertex shader is invoked after any DrawPrimitive or DrawIndexedPrimitive call. Shaders can be dynamically switched using SetVertexShader to specify a new shader file, or by changing the instructions in the ASCII text shader file using the streaming data inputs. The Vertex Shader 1_1 has a complete listing of shader instructions.

Instruction sets evolve rapidly. For details about ordering instructions to avoid problems, refer to the hardware vendor's Web site. Alternatively, use the High-Level Shader Language to get efficiently compiled shader instructions using Direct3D extensions (D3DX).

© 2002 Microsoft Corporation. All rights reserved.


Create a Vertex Shader

This example creates a vertex shader that applies a constant color to an object. The example will show the contents of the shader file as well as the code required in the application to set up the Microsoft® Direct3D® pipeline for the shader data.

If you already know how to build and run Direct3D samples, you can cut and paste code from this example into your existing application.

The following steps are discussed in this article.

  • Step 1: Declare the Vertex Data
  • Step 2: Design the Shader Functionality
  • Step 3: Check for Vertex Shader Support
  • Step 4: Declare the Vertex Shader Data
  • Step 5: Create the Shader
  • Step 6: Render the Output Pixels

Step 1: Declare the Vertex Data

This example uses a quadrilateral that is made up of two triangles. The vertex data will contain (x,y,z) position and a diffuse color. The vertex data is declared in a global array of vertices (g_Vertices). The four vertices are centered about the origin.

// Declare vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
};

// Declare the vertex position and diffuse color data.
CUSTOMVERTEX g_Vertices[]=
{
    //  x        y      z
    { -1.0f, -1.0f, 0.0f },
    { +1.0f, -1.0f, 0.0f },
    { +1.0f, +1.0f, 0.0f },
    { -1.0f, +1.0f, 0.0f },
};

Step 2: Design the Shader Functionality

This shader applies a constant color to each vertex. The shader file VertexShader.vsh follows:

vs_1_1              // version instruction
dcl_position v0     // define position data in register v0
m4x4 oPos, v0, c0   // transform vertices by view/projection matrix
mov oD0, c4         // load constant color

This file contains three arithmetic instructions and a register definition. The first instruction in a shader file must be the shader version declaration. The vs instruction declares the vertex shader version, which is 1_1 in this case.

The dcl_position instruction defines register v0 as the source of vertex position data. The m4x4 instruction transforms the object vertices using the view/projection matrix. The matrix is loaded into four constant registers c0, c1, c2, c3 (as shown below). The mov instruction copies the constant color in register c4 to the output diffuse color register oD0. This results in coloring the output vertices.

Step 3: Check for Vertex Shader Support

The device capability can be queried for vertex shader support before using a vertex shader.

D3DCAPS9 caps;
m_pd3dDevice->GetDeviceCaps(&caps);    // initialize m_pd3dDevice before using
if( caps.VertexShaderVersion < D3DVS_VERSION(1,1) )
    return E_FAIL;

The caps structure returns the functional capabilities of the hardware after IDirect3DDevice9::GetDeviceCaps is called. Use the D3DVS_VERSION macro to test the supported version number. If the version number is less than 1_1, this call will fail. The result of this method should be used to control whether vertex shaders are invoked by an application.

Step 4: Declare the Vertex Shader Data

The vertex declaration describes the vertex data.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
  { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  D3DDECL_END()
};

This declaration specifies the following: The data comes from stream 0, starts at an offset of 0 from the start of the stream, declares the position data as 3 floating-point numbers (D3DDECLTYPE_FLOAT3), tells the tessellator to copy the vertex data (D3DDECLMETHOD_DEFAULT), defines the usage for the data as position data (D3DDECLUSAGE_POSITION), and specifies the usage index of 0.

D3DDECLEND() is a macro that is used to end a vertex declaration.

Step 5: Create the Shader

The shader is assembled and created next.

LPDIRECT3DPIXELSHADER9 m_pVertexShader;
TCHAR        strShaderPath[512];
LPD3DXBUFFER pCode;                  // Buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // Buffer with error messages
DXUtil_FindMediaFileCb( strShaderPath, sizeof(strShaderPath),
                        _T("VertexShader.vsh") );

D3DXAssembleShaderFromFile( strPixelShaderPath, NULL, NULL, 0,
                            &pCode, &pErrorMsgs, NULL );
m_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),
                                  &m_pVertexShader)
pCode->Release();
pErrorMsgs->Release()

When the shader file is located, D3DXAssembleShaderFromFile reads and validates the shader instructions. IDirect3DDevice9::CreateVertexShader then takes the shader declaration and the assembled instructions and creates the shader. It returns the shader object which is used during the draw call.

CreateVertexShader is used to create a programmable shader.

Step 6: Render the Output Pixels

Here is an example of the code that could be used in the render loop to render the object, using the vertex shader. The render loop updates the vertex shader constants as a result of changes in the 3-D scene and draws the output vertices with a call to IDirect3DDevice9::DrawPrimitive.

// Update vertex shader constants from view projection matrix data.
D3DXMATRIX mat, matView, matProj;
D3DXMatrixMultiply( &mat, &matView, &matProj );
D3DXMatrixTranspose( &mat, &mat );
m_pd3dDevice->SetVertexShaderConstantF( 0, (float*)&mat, 4 );

// Declare and define the constant vertex color.
float color[4] = {0,1.0,0,0};
m_pd3dDevice->SetVertexShaderConstantF( 4, (float*)&color, 1 );

// Turn off specular light contribution because the specular value
//   is not written in the vertex shader.
m_pd3dDevice->SetRenderState( D3DRS_SPECULAR, FALSE );

// Render the output.
m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetVertexShader( m_pVertexShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

The view and projection matrixes contain camera position and orientation data. Getting updated data and updating the shader constant registers is included in the render loop because the scene may change between rendered frames.

As usual, IDirect3DDevice9::DrawPrimitive renders the output data using the vertex data provided from IDirect3DDevice9::SetStreamSource. IDirect3DDevice9::SetVertexShader is called to tell Direct3D to use the vertex shader. The result of the vertex shader is shown in the following image. It shows the constant color on the plane object.

Result of the vertex shader

© 2002 Microsoft Corporation. All rights reserved.


Vertex Color

This example applies the vertex color from the vertex data to the object. The vertex data contains position data as well as diffuse color data. These are shown following:

struct CUSTOMVERTEX_POS_COLOR
{
    float       x, y, z;
    DWORD       diffuseColor;
};

// Create vertex data with position and texture coordinates.
CUSTOMVERTEX_POS_COLOR g_Vertices[]=
{
    //  x      y     z     diffuse
    { -1.0f, 0.25f, 0.0f, 0xffff0000,  },	//  lower right - red
    {  0.0f, 0.25f, 0.0f, 0xff00ff00,  },	//  lower left - green
    {  0.0f, 1.25f, 0.0f, 0xff0000ff,  },	//  upper left - blue
    { -1.0f, 1.25f, 0.0f, 0xffffffff,  },	//  upper right - white
};

The vertex shader declaration needs to reflect the position and color data also.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
    D3DDECL_END()
};

One way for the shader to get the transformation matrix is from a constant register. This is done by calling SetVertexShaderConstant.

D3DXMATRIX mat;
D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
D3DXMatrixTranspose( &mat, &mat );
hr = m_pd3dDevice->SetVertexShaderConstantF( 1, (float*)&mat, 4 );
if(FAILED(hr))
    return hr;

This declaration declares one stream of data, which contains the position and the color data. The color data is assigned to vertex register 0. Here is the shader.

vs_1_1              ; version instruction
m4x4 oPos, v0, c0   ; transform vertices by view/projection matrix
mov oD0, v1         ; load color from register 1 to diffuse color

It contains three instructions. The first is always the version instruction. The second instruction transforms the vertices. The third instruction moves the color in the vertex register to the output diffuse color register. The result is output vertices using the vertex color data.

The resulting output looks like the following:

© 2002 Microsoft Corporation. All rights reserved.


Texturing

This example applies a texture map to the object.

The vertex data contains object position data as well as texture position or uv data. This causes changes to the vertex declaration structure. The vertex data is also shown below.

struct CUSTOMVERTEX_POS_TEX1
{
    float       x, y, z;		// object position data
    float       tu1, tv1;		// texture position data
};

CUSTOMVERTEX_POS_TEX1 g_Vertices[]=
{
    //  x      y     z      u1    v1
    { -0.75f, -0.5f, 0.0f, 0.0f, 0.0f },	//  lower right
    {  0.25f, -0.5f, 0.0f, 1.0f, 0.0f },	//  lower left
    {  0.25f,  0.5f, 0.0f, 1.0f, -1.0f },	//  upper left
    { -0.75f,  0.5f, 0.0f, 0.0f, -1.0f },	//  upper right
};

D3DUtil_CreateTexture( m_pd3dDevice, TEXT("earth.bmp"),
               &m_pTexture0, D3DFMT_R5G6B5 );

The texture image must be loaded. In this case, the file "earth.bmp" contains a 2-D texture map of the earth and will be used to color the object.

The vertex shader declaration needs to reflect the vertex position and texture coordinate data.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
    D3DDECL_END()
};

This declaration declares one stream of data that contains the vertex position and the texture coordinate data.

The rendering code tells Microsoft® Direct3D® where to find the data stream and the shader, and sets up texture stages because a texture map is being applied.

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB,
                               sizeof(CUSTOMVERTEX_POS_TEX1) );
m_pd3dDevice->SetVertexShader( m_pVertexShader );

m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,
                                               D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1,
                                               D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2,
                                               D3DTA_DIFFUSE );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );
m_pd3dDevice->SetTexture( 0, NULL );

Because there is a single texture, the texture stage states need to be set for texture state 0. These methods tell Direct3D that the texel values will be used to provide diffuse color for the object vertices. In other words, a 2-D texture map will be applied like a decal.

Here is the shader.

vs_1_1               // version instruction
dcl_position v0      // declare position register
dcl_texcoord v8      // declare texture coordinate register
def c4, 1, 1, 1, 1   // initialize a constant
m4x4 oPos, v0, c0    // transform vertices by view/projection matrix
mov oD0, c4          // move diffuse color to output color register
mov oT0, v8          // move texture color to output texture register

The shader file contains several instructions that result in a texture-mapped object, which is shown below.

© 2002 Microsoft Corporation. All rights reserved.


Texture Map with Lighting

This example uses a vertex shader to apply a texture map and add lighting to the scene. The object used is a sphere. The sample code applies a texture map of the earth to the sphere and applies diffuse lighting to simulate night and day.

The code sample adds to the Shader3 example by adding lighting to a texture mapped object. Refer to Shader3 for information about loading the texture map and setting up the texture stage states.

There is a detailed explanation of the sample code framework at Sample Framework. You can cut and paste the sample code into the sample framework to quickly get a working sample.

Vertex Shader Creation

The vertex data has been modified from the Shader3 sample to include vertex normals. For lighting to appear, the object must have vertex normals. The data structure for the vertex data is shown below.

struct CUSTOMVERTEX_POS_NORM_COLOR1_TEX1
{
    float       x, y, z;        // position
    float       nx, ny, nz;     // normal
    DWORD       color1;         // diffuse color
    float       tu1, tv1;       // texture coordinates
};

A shader declaration defines the input vertex registers and the data associated with them.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0 },
    { 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,  0 },
    { 0, 28, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
    D3DDECL_END()
};

This declares one stream of data, which contains the vertex position, normal, diffuse color, and texture coordinates.

Next, create the shader. You can create a shader from an ASCII text string or load it from a shader file that contains the same instructions. This example uses a shader file.

// v7  vertex diffuse color used for the light color
// v8  texture
// c4  view projection matrix
// c12 light direction

vs_1_1                       // version instruction
dcl_position v0              // declare register data
dcl_normal v4                // v0 is position, v4 is normal
dcl_color0 v7                // v7 is diffuse color
dcl_texcoord0 v8             // v8 is texture coordinates
m4x4 oPos, v0, c4            // transform vertices using view projection transform
dp3  r0, v4, c12             // perform lighting N dot L calculation in world
mul  oD0, r0.x , v7          // calculate final pixel color from light intensity and
                             // interpolated diffuse vertex color
mov  oT0.xy , v8             // copy texture coordinates to output

You always enter the version instruction first. The last instruction moves the texture data to the output register oT0. After you write the shader instructions, you can use them to create the shader.

LPDIRECT3DPIXELSHADER9 m_pVertexShader;
TCHAR        strShaderPath[512];
LPD3DXBUFFER pCode;                  // buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // buffer with error messages
DXUtil_FindMediaFileCb( strShaderPath, sizeof(strShaderPath),
                        _T("VertexShader3.vsh") );

D3DXAssembleShaderFromFile( strPixelShaderPath, NULL, NULL, 0,
                            &pCode, &pErrorMsgs, NULL );
m_pd3dDevice->CreateVertexShader((DWORD*)pCode->GetBufferPointer(),
                                  &m_pVertexShader)
pCode->Release();
pErrorMsgs->Release();

After the file is located, Microsoft® Direct3D® creates the vertex shader and returns a shader object. This sample uses a shader file, which is one method for creating a shader. The other method is to create an ASCII text string with the shader instructions in it.

Vertex Shader Constants

You can define vertex shader constants outside of the shader as shown in the following example. Here, you use constants to provide the shader with a view/projection matrix, a diffuse light color, RGBA, and the light direction vector.

float constants[4] = {0, 0.5f, 1.0f, 2.0f};
m_pd3dDevice->SetVertexShaderConstantF( 0, (float*)&constants, 1 );

D3DXMATRIX mat;
D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
D3DXMatrixTranspose( &mat, &mat );
m_pd3dDevice->SetVertexShaderConstantF( 4, (float*)&mat, 4 );

float color[4] = {1,1,1,1};
m_pd3dDevice->SetVertexShaderConstantF( 8, (float*)&color, 1 );

float lightDir[4] = {-1,0,1,0}; // fatter slice
m_pd3dDevice->SetVertexShaderConstantF( 12, (float*)&lightDir, 1 );

You can also define constants inside a shader using the def instruction.

Render

After you write the shader instructions, connect the vertex data to the correct vertex registers and initialize the constants, you should render the output. Rendering code tells Direct3D where to find the vertex buffer data stream and provides Direct3D with the shader handle. Because you use a texture, you must set texture stages to tell Direct3D how to use the texture data.

// Identify the vertex buffer data source.
m_pd3dDevice->SetStreamSource(0, m_pVB,  sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1));
// Identify the shader.
m_pd3dDevice->SetVertexShader( m_pVertexShader );

// Define the texture stage(s) and set the texture(s) used
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTexture( 0, m_pTexture0 );

// Draw the object.
DWORD dwNumSphereVerts = 2 * m_dwNumSphereRings*(m_dwNumSphereSegments + 1);
m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, dwNumSphereVerts - 2);

The output image follows:

With the texture map applied, the sphere looks like the planet Earth. The lighting creates a bright to dark gradient on the face of the globe.

© 2002 Microsoft Corporation. All rights reserved.


Decoupling Vertex Shaders and Vertex Declarations

In Microsoft® DirectX® 9.0, vertex shaders and vertex declarations are no longer bound together at shader create (CreateVertexShader) time. The shader validation has been broken up into two parts. The first part is run at shader creation time and the other is run at draw (DrawPrimitive) time.

  • Mapping a DirectX 8.x Vertex Declaration to a DirectX 9.0 Vertex Declaration
  • Mapping an FVF code to a DirectX 9.0 Vertex Declaration
  • Mapping a DirectX 9.0 Vertex Declaration to a DirectX 8.x Vertex Declaration
  • Mapping a DirectX 9.0 Vertex Declaration to FVF codes

Vertex shaders and vertex declarations are represented by objects. To make this work with a DirectX 8.x driver, some caching is done. At "draw time" the runtime checks to see if a combined shader object that encapsulated the current declaration and shader exists. If it does, it sends it down to the driver, or else it will create a new one for that combination of shader and declaration. Additionally, to address application programming interface (API) usability issues, there will be a separate SetFVF call that is equivalent to the SetVertexDeclaration call. This is a convenience function. When this call is made, it will clobber the currently set declaration and vice versa. If the driver is pre-DirectX 8.0 (the number of stream is 0) SetVertexDeclaration might fail for declarations that cannot be converted to an flexible vertex format (FVF).

  • SetVertexDeclaration and SetVertexShader calls are recorded by stateblocks. Setting or getting the declaration or the shader causes an increment of the refcount for that object.
  • An FVF code can be used with both the fixed function and the programmable vertex pipeline. FVF is converted to a vertex shader declaration, using the table. DCL commands in vertex shader functions should be written with this in mind.
  • Software vertex processing supports DirectX 9.0 level features besides tessellation and hence when Drawing with software VP more declarations are supported.
  • For the programmable vertex pipeline: At draw time, Microsoft Direct3D® looks for the same "usage - usage index" combination in the current vertex declaration and the current vertex shader function. When the combination is found, the register from shader function DCL is used as destination for the vertex element.
  • If an FVF has XYZRHW position type, vertices are treated as transformed and lit, and the vertex shader function is not applied when used with the programmable vertex pipeline.
  • When a vertex element in the current vertex declaration has a usage that is not found in the current vertex shader, that vertex element is ignored.

A subset of declarations are allowed on DirectX 8.x drivers (numstreams is not zero but does not support stream offset), only those that can be converted to DirectX 8.x-style declaration can be created. Hence the CreateVertexDeclaration call may fail if the declaration provided cannot be converted. For a mixed-mode device, this failure will happen at Draw xxx time because that is the only time it can be known whether this shader is being used with hardware or software vertex processing. This conversion is summarized in the table.

A further subset of decls are allowed on pre-DirectX 8.0 drivers (numstreams is zero); only those declarations that can be converted to an appropriate FVF are allowed. If that conversion is not possible, the CreateVertexDeclaration might fail. For a mixed-mode device, this failure will happen at Draw xxx time because that is the only time it can be known whether this shader is being used with hardware or software vertex processing. This conversion is summarized in the table. Only stream 0 should be used (evident from the MaxStreams cap).

The order of vertex elements should correspond to the order of the FVF codes. The usage index for D3DDECLUSAGE_POSITION and D3DDECLUSAGE_NORMAL should be 0. When switching vertex processing mode for a device with mixed vertex processing, there is no need to reset all input vertex (and index) streams, the vertex declaration, and the vertex function. NULL is an invalid input to SetVertexDeclaration. When using software vertex processing, all usages mentioned in the shader code for the programmable vertex pipeline need to be present in the declaration (or the FVF) bound at the draw time.

Declarations that use the following rules can be rendered with the fixed function pipeline (this assumes no tessellation is required).

  • Use only D3DDECLMETHOD_DEFAULT.
  • There should be no gaps between vertex elements (SKIP was not allowed in a DirectX 8.x declaration).
  • Specify usage POSITION.
  • Specify D3DDECLTYPE_FLOAT3 data type for POSITION usage.
  • Vertex elements not described in the table following cannot be converted into a valid FVF for all pre-DirectX 8.0 drivers and so cannot be used with the fixed function vertex processing on those drivers.

Mapping a DirectX 8.x Vertex Declaration to a DirectX 9.0 Vertex Declaration

DirectX 8.x | DirectX 9.0 usage | DirectX 9.0 usage index
D3DVSDE_POSITION | D3DDECLUSAGE_POSITION | 0
D3DVSDE_POSITION2 | D3DDECLUSAGE_POSITION | 1
D3DVSDE_NORMAL | D3DDECLUSAGE_NORMAL | 0
D3DVSDE_NORMAL2 | D3DDECLUSAGE_NORMAL | 1
D3DVSDE_BLENDWEIGHT | D3DDECLUSAGE_BLENDWEIGHT | 0
D3DVSDE_BLENDINDICES | D3DDECLUSAGE_BLENDINDICES | 0
D3DVSDE_PSIZE | D3DDECLUSAGE_PSIZE | 0
D3DVSDE_DIFFUSE | D3DDECLUSAGE_COLOR | 0
D3DVSDE_SPECULAR | D3DDECLUSAGE_COLOR | 1
D3DVSDE_TEXCOORDn | D3DDECLUSAGE_TEXCOORD | n

Mapping an FVF code to a DirectX 9.0 Vertex Declaration

FVF | Data type | Usage | Usage index
D3DFVF_XYZ | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZRHW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0
D3DFVF_XYZW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_UBYTE4 | D3DVSDT_FLOAT3, D3DVSDT_FLOAT4, D3DVSDT_UBYTE4 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 | D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOATn | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_UBYTE4 | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT(n-1) D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_POSITION, D3DDECLUSAGE_BLENDWEIGHT, D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_NORMAL | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0
D3DFVF_PSIZE | D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0
D3DFVF_DIFFUSE | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0
D3DFVF_SPECULAR | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1
D3DFVF_TEXCOORDSIZEm(n) | D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n

Mapping a DirectX 9.0 Vertex Declaration to a DirectX 8.x Vertex Declaration

Usage | Usage index | DirectX decl
D3DDECLUSAGE_POSITION | 0 | D3DVSDE_POSITION
D3DDECLUSAGE_POSITION | 1 | D3DVSDE_POSITION2
D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DVSDE_BLENDWEIGHT
D3DDECLUSAGE_BLENDINDICES | 0 | D3DVSDE_BLENDINDICES
D3DDECLUSAGE_NORMAL | 0 | D3DVSDE_NORMAL
D3DDECLUSAGE_NORMAL | 1 | D3DVSDE_NORMAL2
D3DDECLUSAGE_PSIZE | 0 | D3DVSDE_PSIZE
D3DDECLUSAGE_COLOR | 0 | D3DVSDE_DIFFUSE
D3DDECLUSAGE_COLOR | 1 | D3DVSDE_SPECULAR
D3DDECLUSAGE_TEXCOORD | n | D3DVSDE_TEXTUREn, n <= 7

Mapping a DirectX 9.0 Vertex Declaration to FVF codes

Additional types can be successfully converted to a valid declaration on DirectX 8.0 and newer drivers, and hence can be used by fixed function vertex processing.

  • When DirectX 8.x drivers are used, the vertex declaration is converted to a DirectX 8.x declaration by the following rules. For other combinations of usages, the Direct3D will fail.
  • For each new stream in the D3DVSD_STREAM, a token is inserted.
  • Vertex elements cannot share the same offset in a stream and they cannot overlap.
  • The data type must be less than or equal to D3DDECLTYPE_SHORT4.
  • For each vertex element with the D3DDECLMETHOD_DEFAULT method, the D3DVSD_REG token is inserted.
  • Usage and UsageIndex are converted to a register value using the table following. When using the DrawRectPatch (RT-patches), the output of the tessellator should comply with the previous rules.
Data type | Usage | Usage index | FVF
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0 | D3DFVF_XYZ
D3DDECLTYPE_FLOATn | D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DFVF_XYZBn
D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_BLENDINDICES | 0 | D3DFVF_XYZB (nWeights+1)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0 | D3DFVF_NORMAL
D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0 | D3DFVF_PSIZE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0 | D3DFVF_DIFFUSE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1 | D3DFVF_SPECULAR
D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n | D3DFVF_TEXCOORDSIZEm(n)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 1 | N/A
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 1 | N/A

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shaders

Before Microsoft® DirectX® 8.0, Microsoft Direct3D® used a fixed function pipeline for converting three-dimensional (3-D) geometry to rendered screen pixels. The user sets attributes of the pipeline that control how Direct3D transforms, lights, and renders pixels. The fixed function vertex format is declared at compile time and determines the input vertex format. Once defined, the user has little control over pipeline changes during run time.

Shaders add a new dimension to the graphics pipeline by allowing the vertex transform, lighting, and individual pixel coloring functionality to be programmed. Pixel shaders are short programs that run for each pixel when triangles are rasterized. This gives the user a new level of dynamic flexibility over the way that pixels are rendered.

A pixel shader contains pixel shader instructions made up of ASCII text. Arithmetic instructions can be used to apply diffuse and/or specular color. Texture addressing instructions provide a variety of operations for reading and applying texture data. Functionality is available for masking and swapping color components. The shader text looks similar to assembly language and is assembled using Direct3D extensions (D3DX) assembler functions from either a text string or a file. The assembler output is a series of opcodes that an application may provide to Direct3D by means of IDirect3DDevice9::CreatePixelShader. There are several pixel shader version. See Shader Reference.

  • Create a Pixel Shader - contains a code sample that uses a pixel shader to apply Gouraud interpolated diffuse colors to an object. This example contains a detailed explanation of the methods used.
  • Confirming Pixel Shader Support - gives a more detailed explanation of the structures for enumerating pixel shader support.
  • Converting Texture Operations - gives examples of converting texture operations to pixel shader instructions.
  • Texture Considerations - details the texture stage states that are ignored during pixel shaders.
  • Pixel Shader Examples - shows more code samples that add textures and blend vertex colors and textures.
  • Debugging - provides debugging information.

Instruction sets are rapidly evolving, refer to each hardware vendors web site for details on how to best order instructions to avoid stalls. Alternatively, you can make maximum use of the High-Level Shader Language in order to get very efficiently compiled shader instructions using D3DX.

© 2002 Microsoft Corporation. All rights reserved.


Create a Pixel Shader

This example uses a pixel shader to apply a Gouraud interpolated diffuse color to a geometric plane. The example will show the contents of the shader file as well as the code required in the application.

To create a pixel shader

  • Step 1: Check for pixel shader support.
  • Step 2: Declare the vertex data.
  • Step 3: Design the pixel shader.
  • Step 4: Create the pixel shader.
  • Step 5: Render the output pixels.

If you already know how to build and run Microsoft® Direct3D® samples, you should be able to cut and paste code from this example into your existing application.

Step 1

To check for pixel shader support, use the following code. This example checks for pixel shader version 1_1.

D3DCAPS9 caps;
m_pd3dDevice->GetDeviceCaps(&caps);        // init m_pd3dDevice before using
if( caps.PixelShaderVersion < D3DPS_VERSION(1,1) )
    return E_FAIL;

The caps structure returns the functional capabilities of the pipeline. Use the D3DPS_VERSION macro to test for all supported shader versions. If the version returned by caps is less than 1_1, this call will fail. Conversely, all version numbers greater than or equal to 1_1 will succeed. If the pipeline does not support the shader version that is tested, the application will have to fall back to another rendering approach (perhaps a lower shader version is available).

Step 2

This example uses a plane, which is made up of two triangles. The data structure for each vertex will contain position and diffuse color data. The D3DFVF_CUSTOMVERTEX macro defines a data structure to match the vertex data. The actual vertex data is declared in a global array of vertices called g_Vertices. The four vertices are centered about the origin, and each vertex is given a different diffuse color.

// Declare vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD diffuseColor;
};

// Declare custom FVF macro.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)

// Declare the vertex position and diffuse color data.
CUSTOMVERTEX g_Vertices[]=
{
//      x      y      z   diffuse color
    { -1.0f, -1.0f, 0.0f, 0xffff0000 },  // red   - lower left
    { +1.0f, -1.0f, 0.0f, 0xff00ff00 },  // green - lower right
    { +1.0f, +1.0f, 0.0f, 0xff0000ff },  // blue  - upper right
    { -1.0f, +1.0f, 0.0f, 0xffffffff },  // white - upper left
};

Step 3

This shader moves the Gouraud interpolated diffuse color data to the output pixels. The shader file PixelShader.txt follows:

ps_1_1        // version instruction
mov r0,v0     // Move the diffuse vertex color to the output register.

The first instruction in a pixel shader file declares the pixel shader version, which is 1_1.

The second instruction moves the contents of the color register (v0) into the output register (r0). The color register contains the vertex diffuse color because the vertex data is declared to contain the interpolated diffuse color in step 1. The output register determines the pixel color used by the render target (because there is no additional processing, such as fog, in this case).

Step 4

The pixel shader is created from the pixel shader instructions. In this example, the instructions are contained in a separate file. The instructions could also be used in a text string.

LPD3DXBUFFER pCode;                  // buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // buffer with error messages
TCHAR        strPixelShaderPath[512];// used to locate the shader file
DXUtil_FindMediaFileCb( strPixelShaderPath, sizeof(strPixelShaderPath),
                        _T("PixelShader.txt") );

This function is a helper function used by the sample framework, which is the foundation on which many of the samples are built.

LPDIRECT3DPIXELSHADER9 m_pPixelShader;
D3DXAssembleShaderFromFile( strPixelShaderPath, NULL, NULL, 0,
                            &pCode, &pErrorMsgs, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                  &m_pPixelShader );

When the shader is created, the pointer m_pPixelShader is used to refer to it.

Step 5

Rendering the output pixels is very similar to using the fixed function pipeline sequence of calls except that the pixel shader handle is now used to set the shader.

// Turn lighting off for this example. It will not contribute to the
//   final pixel color.
// Pixel color will be determined solely by interpolating the vertex colors.
m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetPixelShader( m_pPixelShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

The source of the vertex data is set with SetStreamSource. In this example, SetFVF uses the flexible vertex format (FVF) macro used during the vertex data declaration to tell Direct3D to do fixed function vertex processing. Vertex shaders and pixel shaders may be used together or separately. The fixed function pipeline can also be used instead of either pixel or vertex shaders. SetPixelShader sets the pixel shader and DrawPrimitive draws the plane.

© 2002 Microsoft Corporation. All rights reserved.


Confirming Pixel Shader Support

You can query members of D3DCAPS9 to determine the level of support for operations involving pixel shaders. The following table lists the device capabilities related to programmable pixel processing.

Device capability | Description
PixelShader1xMaxValue | Range of values that can be stored in registers is [-PixelShader1xMaxValue, PixelShader1xMaxValue]. This affects versions ps_1_1 - ps_1_4 only.
MaxSimultaneousTextures | For the fixed function pipeline, the number of texture samplers is MaxTextureBlendStages divided by MaxSimultaneousTextures. The number of texture samplers for a pixel shader is shown in the next table.
PixelShaderVersion | Version of pixel shader supported by the hardware. Pixel shaders with version numbers equal to or less than this value are supported.

The number of texture samplers available for a pixel shader depends on the pixel shader version.

Pixel shader version | Number of texture samplers
ps_1_1 - ps_1_3 | 4 texture samplers
ps_1_4 | 6 texture samplers
ps_2_0 - ps_3_0 | 16 texture samplers
Fixed function pixel shader | MaxTextureBlendStages/MaxSimultaneousTextures texture samplers

The first byte of PixelShaderVersion contains the minor version number; the second byte contains the major version number. The first token in the assembled shader is the pixel shader version. Each hardware implementation sets the version number to indicate the maximum pixel shader version that it can fully support.

© 2002 Microsoft Corporation. All rights reserved.


Converting Texture Operations

Pixel shaders extend and generalize the multi-texture capabilities of Microsoft® DirectX® 6.0 and 7.0 in the following ways.

  • A set of general read/write registers is added to enable more flexible expression. The serial cascade using D3DTA_CURRENT requires the specification of a separate result register argument for each stage.
  • The D3DTOP_MODULATE2X and D3DTOP_MODULATE4X texture operations are broken into separate modifiers applicable to any instruction orthogonally. This eliminates the need for separate D3DTOP_MODULATE and D3DTOP_MODULATE2X operations.
  • An optional third argument is added to modulate add, so the procedural pixel shader can do arg1 ×arg2 + arg0. This eliminates the D3DTOP_MODULATEALPHA_ADDCOLOR and D3DTOP_MODULATECOLOR_ADDALPHA texture operations.
  • An optional third argument is added to the blend operation, so the procedural pixel shader can use arg0 as the blend proportion between arg1 and arg2. This eliminates the D3DTOP_BLENDDIFFUSEALPHA, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, D3DTOP_BLENDTEXTUREALPHAPM, and D3DTOP_BLENDCURRENTALPHA texture operations.
  • Texture address modifying operations, such as D3DTOP_BUMPENVMAP, are broken out from the color and alpha operations and defined as a third operation type, specifically for operating on texture addresses.

To support this increased flexibility efficiently, the application programming interface (API) syntax is changed from DWORD pairs to an ASCII assemble code syntax. This exposes the functionality offered by procedural pixel shaders.

Note When you use pixel shaders, specular add is not specifically controlled by a render state, and it is up to the pixel shader to implement if needed. However, fog blending is still applied by the fixed function pipeline.

© 2002 Microsoft Corporation. All rights reserved.


Texture Considerations

The pixel shader completely replaces the pixel-blending functionality specified by the Microsoft® DirectX® 6.0 and 7.0 multi-texturing application programming interfaces (APIs), specifically those operations defined by the D3DTSS_COLOROP, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAOP, D3DTSS_ALPHAARG1, and D3DTSS_ALPHAARG2 texture stage states, and associated arguments and modifiers. When a procedural pixel shader is set, these states are ignored.

Texture Stage and Sampler States

When pixel shaders are in operation, the following texture stage states are still observed. They are version dependent as shown in the table.

Texture stage state | Version(s)
D3DTSS_BUMPENVMAT00 | 1_1 - 1_4
D3DTSS_BUMPENVMAT01 | 1_1 - 1_4
D3DTSS_BUMPENVMAT10 | 1_1 - 1_4
D3DTSS_BUMPENVMAT11 | 1_1 - 1_4
D3DTSS_BUMPENVLSCALE | 1_1 - 1_3
D3DTSS_BUMPENVLOFFSET | 1_1 - 1_3
D3DTSS_TEXCOORDINDEX | 1_1 - 1_3. Valid only for fixed function vertex processing.
D3DTSS_TEXTURETRANSFORMFLAGS | 1_1 - 1_3. Valid only for fixed function vertex processing.

When pixel shaders are in operation, the following sampler states are still observed.

Sampler state | Version(s)
D3DSAMP_ADDRESSU | All
D3DSAMP_ADDRESSV | All
D3DSAMP_ADDRESSW | All
D3DSAMP_BORDERCOLOR | All
D3DSAMP_MAGFILTER | All
D3DSAMP_MINFILTER | All
D3DSAMP_MIPFILTER | All
D3DSAMP_MIPMAPLODBIAS | All
D3DSAMP_MAXMIPLEVEL | All
D3DSAMP_MAXANISOTROPY | All
D3DSAMP_SRGBTEXTURE | All
D3DSAMP_ELEMENTINDEX | All
D3DSAMP_DMAPOFFSET | Vertex shaders only (displacement mapping)

Because these texture stage states are not part of the pixel shader, they are not available at shader compile time so the driver can make no assumptions about them. For example, the driver cannot differentiate between bilinear and trilinear filtering at that time. The application is free to change these states without requiring the regeneration of the currently bound shader.

Pixel Shaders and Texture Sampling

Texture sampling and filtering operations are controlled by the standard texture stage states for minification, magnification, mip filtering, and the wrap addressing modes. For more information, see Texture Stage States. This information is not available to the driver at shader compile time, so shaders must be able to continue operation when this state changes. The application is responsible for setting textures of the correct type (image map, cube map, volume map, etc.) needed by the pixel shader. Setting a texture of the incorrect type will produce unexpected results.

Post-Shader Pixel Processing

Other pixel operations—such as fog blending, stencil operations, and render target blending—occur after execution of the shader. Render target blending syntax is updated to support new features as described in this topic.

Pixel Shader Inputs

For pixel shader versions ps_1_1 - ps_2_0, diffuse and specular colors are saturated (clamped) to the range 0 through 1 before use by the shader because this is the range of valid inputs to the shader.

Color values input to the pixel shader are assumed to be perspective correct, but this is not guaranteed in all hardware. Colors generated from texture coordinates by the address shader are always iterated in a perspective correct manner. However, they are also clamped to the range 0 to 1 during iteration.

Pixel Shader Outputs

For pixel shader versions ps_1_1 - ps_1_4, the result emitted by the pixel shader is the contents of register r0. Whatever it contains when the shader completes processing is sent to the fog stage and render target blender.

For pixel shader versions ps_2_0 and above, output color is emitter from oC0 - oC4.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader Examples

This section contains three pixel shader examples. Each example builds on the previous example by adding a piece of pixel shader functionality.

  • Apply a Texture Map
  • Blend a Diffuse Vertex Color with a Texture
  • Blend Two Textures Using a Color Value

Apply a Texture Map

This example applies a texture map to a plane. The differences between this example and the previous example are as follows:

  • The vertex data structure and the flexible vertex format (FVF) macro include texture coordinates. The vertex data includes u,v data. The vertex data no longer needs diffuse color because the pixel colors will come from the texture map.
  • The texture is linked to texture stage 0 with IDirect3DDevice9::SetTexture.
  • The shader uses the t0 texture register instead of the v0 diffuse color register.

The sample code follows:

// Define vertex data structure.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    FLOAT u1, v1;
};

// Define corresponding FVF macro.
#define D3DFVF_CUSTOMVERTEX (
                 D3DFVF_XYZ|D3DFVF_TEX|D3DFVF_TEXCOORDSIZE2(0))

// Create vertex data with position and texture coordinates.
static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     u1    v1
    { -1.0f, -1.0f, 0.0f,  0, 1, },
    {  1.0f, -1.0f, 0.0f,  1, 1, },
    {  1.0f,  1.0f, 0.0f,  1, 0, },
    { -1.0f,  1.0f, 0.0f,  0, 0, },
    // v1 is flipped to meet the top down convention in Windows.
    // The upper left texture coordinate is (0,0).
    // The lower right texture coordinate is (1,1).
};

// Create a texture. This file is in the DirectX 9.0
//   media from the SDK download.
TCHAR        strTexturePath[512];
DXUtil_FindMediaFileCb( strTexturePath, sizeof(strTexturePath),
                        _T("DX5_Logo.bmp") );

LPDIRECT3DTEXTURE9      m_pTexture0;
D3DUtil_CreateTexture( m_pd3dDevice, strTexturePath,
                       &m_pTexture0, D3DFMT_R5G6B5 );

// Create the pixel shader.
TCHAR        strShaderPath[512];
DXUtil_FindMediaFileCb( strShaderPath, sizeof(strShaderPath),
                        _T("PixelShader2.txt") );

This function is a helper function used by the Sample Framework. The sample framework is the foundation on which many of the samples are built.

LPD3DXBUFFER pCode;                  // buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // buffer with error messages
LPDIRECT3DPIXELSHADER9 m_pPixelShader;
D3DXAssembleShaderFromFile( strShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                          &m_pPixelShader );
m_pd3dDevice->SetPixelShader( m_pPixelShader );

// Load the texture and render the output pixels.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

// Contents of the file "PixelShader2.txt"
// Applies a texture map to object vertices.
ps_1_1      // Version instruction must be first in the file.
tex t0      // Declare texture register t0
            // which is loaded from stage 0.
mov r0, t0  // Move the texture register data(t0) to the
            // output register(r0).

The resulting image is shown in the following example.

Texture map example

Blend a Diffuse Vertex Color with a Texture

This example blends or modulates the colors in a texture map with the vertex colors. The differences between this example and the previous example are as follows:

  • The vertex data structure, the FVF macro, and the vertex data include diffuse color.
  • The shader file uses the multiply (mul) instruction to blend or modulate the texture colors with the vertex diffuse color.

The texture create and load code is the same. It is included here for completeness.

struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color1;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|
                             D3DFVF_TEXCOORDSIZE2(0))
static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     diffuse     u1    v1
    { -1.0f, -1.0f, 0.0f, 0xffff0000, 0, 1, }, // red
    {  1.0f, -1.0f, 0.0f, 0xff00ff00, 1, 1, }, // green
    {  1.0f,  1.0f, 0.0f, 0xff0000ff, 1, 0, }, // blue
    { -1.0f,  1.0f, 0.0f, 0xffffffff, 0, 0, }, // white
    // v1 is flipped to meet the top down convention in Windows
    // the upper left texture coordinate is (0,0)
    // the lower right texture coordinate is (1,1).
};

// Create a texture. This file is in the DirectX 9.0 media
//   from the SDK download.
// Create a texture. This file is in the DirectX 9.0
//   media from the SDK download.
TCHAR        strTexturePath[512];
DXUtil_FindMediaFileCb( strTexturePath, sizeof(strTexturePath),
                        _T("DX5_Logo.bmp") );

LPDIRECT3DTEXTURE9      m_pTexture0;
D3DUtil_CreateTexture( m_pd3dDevice, strTexturePath,
                       &m_pTexture0, D3DFMT_R5G6B5 );

// Create the pixel shader.
TCHAR        strShaderPath[512];
DXUtil_FindMediaFileCb( strShaderPath, sizeof(strShaderPath),
                        _T("PixelShader3.txt") );

LPD3DXBUFFER pCode;                  // buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // buffer with error messages
LPDIRECT3DPIXELSHADER9 m_pPixelShader;
D3DXAssembleShaderFromFile( strShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                          &m_pPixelShader );
m_pd3dDevice->SetPixelShader( m_pPixelShader );

// Load the texture and render the output pixels.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

// Contents of the file "PixelShader3.txt"
ps_1_1          // version instruction
tex t0          // declare texture register t0,
                // to be loaded from Texture Stage 0
mul r0, v0, t0  // v0*t0, then move to r0

The inputs to the shader are shown in the following example. The first image shows the vertex colors. The second image shows the texture map.

The resulting image is shown in the following example. It shows the output, which is a blend of the vertex color and the texture image.

Blended vertex colors and texture

Blend Two Textures Using a Color Value

This example blends two texture maps, using the vertex color, to determine how much of each texture map color to use. The differences between this example and the previous example are as follows:

  • The vertex data structure, the FVF macro, and the vertex data include a second set of texture coordinates because there is a second texture. IDirect3DDevice9::SetTexture is also called twice, using two texture stage states.
  • The shader file declares two texture registers and uses the linear interpolate (lrp) instruction to blend the two textures. The values of the diffuse colors determine the ratio of texture0 to texture1 in the output color.

Here is the sample code.

struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu1, tv1;
    FLOAT tu2, tv2;    // a second set of texture coordinates
};
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3D_FVF_DIFFUSE|D3DFVF_TEX2|
                             D3DFVF_TEXCOORDSIZE4(0))
static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     color       u1    v1    u2    v2
    { -1.0f, -1.0f, 0.0f, 0xff0000ff, 1.0f, 1.0f, 1.0f, 1.0f },
    { +1.0f, -1.0f, 0.0f, 0xffff0000, 0.0f, 1.0f, 0.0f, 1.0f },
    { +1.0f, +1.0f, 0.0f, 0xffffff00, 0.0f, 0.0f, 0.0f, 0.0f },
    { -1.0f, +1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 1.0f, 0.0f },
};

// Create texture. This file is in DirectX 9.0 media from
//   the SDK download.
TCHAR        strTexturePath[512];
LPDIRECT3DTEXTURE9      m_pTexture0, m_pTexture1;

DXUtil_FindMediaFileCb( strTexturePath, sizeof(strTexturePath),
                        _T("DX5_Logo.bmp") );
D3DUtil_CreateTexture( m_pd3dDevice, strTexturePath,
                       &m_pTexture0, D3DFMT_R5G6B5 );

DXUtil_FindMediaFileCb( strTexturePath, sizeof(strTexturePath),
                        _T("snow2.jpg") );
D3DUtil_CreateTexture( m_pd3dDevice, strTexturePath,
                       &m_pTexture0, D3DFMT_R5G6B5 );

// Create the pixel shader.
TCHAR        strShaderPath[512];
DXUtil_FindMediaFileCb( strShaderPath, sizeof(strShaderPath),
                        _T("PixelShader4.txt") );

LPD3DXBUFFER pCode;                  // buffer with the assembled shader code
LPD3DXBUFFER pErrorMsgs;             // buffer with error messages
LPDIRECT3DPIXELSHADER9 m_pPixelShader;
D3DXAssembleShaderFromFile( strShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(),
                                          &m_pPixelShader );
m_pd3dDevice->SetPixelShader( m_pPixelShader );

// Load the textures stages.
m_pd3dDevice->SetTexture( 0, m_pTexture0 );
m_pd3dDevice->SetTexture( 1, m_pTexture1 );  // Use a second stage.

m_pd3dDevice->SetStreamSource( 0, m_pQuadVB, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetPixelShader( m_pPixelShader );
m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 );

// Contents of the file "PixelShader4.txt"
ps_1_1              // Pixel shader version.
tex t0              // Texture register t0 is loaded from stage 0.
tex t1              // Texture register t1 is loaded from stage 1.
mov r1, t1          // Move texture t1 into output register r1.
lrp r0, v0, t0, r1  // Linearly interpolate between t0 and r1
                    //   by a proportion specified in v0.

The resulting output is as follows:

Blending both textures

© 2002 Microsoft Corporation. All rights reserved.


Debugging

Debugging with Visual Studio

An extension to Microsoft® Visual Studio® exists to support debugging some types of vertex shaders. For more information, see Shader Debugger.

Other Shader Debuggers

Some graphics chip companies provide a shader debugging tool on their Web sites. Find these tools by searching the Web or by reading the article listed below. You can attach a debugger to a program while it is running and use the debugger to step through a shader. By setting breakpoints, you can step through the shader code one line at a time and watch register state changes. For more information about vertex shaders and debugging tips, see Using Vector Shaders: Part I World Wide Web link.

Texture Blending Debugging

Another sample application that is part of the software development kit (SDK) installation is MFC Tex Sample. This Microsoft Foundation Classes (MFC) application is a good way to learn how to perform multi-texture blending operations in the fixed function pipeline.

Diagnostic Support

Another option for help with debugging Microsoft DirectX® problems is to use the DirectX Diagnostic Viewer (DXDiag.exe) to create a dump of your computer. This is done by running DxDiag.exe after your computer has crashed and sending the dump to Microsoft, using either the Report button on the More Help tab or by sending it to directx@microsoft.com. The dump can be used to track down and reproduce the problem.

Additional debug information can be found at http://msdn.microsoft.com/directx World Wide Web link

For more information, see DirectX Diagnostic Tool.

© 2002 Microsoft Corporation. All rights reserved.


Advanced Topics

Microsoft® Direct3D® provides a powerful set of tools that you can use to increase the realistic appearance of a 3-D scene. This section presents information about common special effects that can be produced with Direct3D, but the range of possible effects is not limited to those presented here. The discussion in this section is organized into the following topics.

  • Vertex Pipeline
  • Pixel Pipeline
  • Frame Buffer
  • Effects
  • Direct3D Extentions (D3DX) Meshes
  • Direct3D Extentions (D3DX) Line Drawing
  • Other Direct3D Extentions (D3DX)
  • Asynchronous Notification
  • Multihead
  • X Files

© 2002 Microsoft Corporation. All rights reserved.


Vertex Pipeline

This is a list of advanced topics that are implemented by vertex processing.

  • Tessellation
  • Displacement Mapping
  • Geometry Blending
  • Higher-Order Primitives
  • Point Sprites
  • Matrix Stacks

© 2002 Microsoft Corporation. All rights reserved.


Tessellation

Tessellator Unit

The tessellator unit has been enhanced. You can now use it to:

  • Perform adaptive tessellation of all higher order primitives.
  • Look up per-vertex displacement values from a displacement map and pass them on to a vertex shader.
  • Support rectangle-patch tessellation. This is specified through a vertex declaration using D3DDECLMETHOD_PARTIALU or D3DDECLMETHOD_PARTIALV. If a vertex declaration containing these methods is used to draw a triangle patch, IDirect3DDevice9::DrawTriPatch will fail. For more information about vertex declarations, see D3DVERTEXELEMENT9.

In Microsoft® DirectX® 8.x, what was called ORDER was really the degree. In DirectX 9.0, the degree is now specified by D3DDEGREETYPE.

 // This used to be D3DORDERTYPE and D3DORDER*
 typedef enum _D3DDEGREETYPE
 {
 D3DDEGREE_LINEAR = 1,
 D3DDEGREE_QUADRATIC = 2,
 D3DDEGREE_CUBIC = 3,
 D3DDEGREE_QUINTIC = 5,
 D3DDEGREE_FORCE_DWORD = 0x7fffffff,
 } D3DDEGREETYPE;

The change in degree type affected two other structures.

typedef struct _D3DRECTPATCH_INFO
 {
 UINT StartVertexOffsetWidth;
 UINT StartVertexOffsetHeight;
 UINT Width;
 UINT Height;
 UINT Stride;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DRECTPATCH_INFO;

 typedef struct _D3DTRIPATCH_INFO
 {
 UINT StartVertexOffset;
 UINT NumVertices;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DTRIPATCH_INFO;

Drivers need to fix compilation errors that will result from this change when they compile with the new headers. No functionality has to be changed.

Adaptive Tessellation

Adaptive tessellation can be applied to high-order primitives including N-patches, rectangle patches, and triangle patches. This feature is enabled by the D3DRS_ENABLEADAPTIVETESSELATION and adaptively tessellates a patch, based on the depth value of the control vertex in eye space.

The z-coordinates (Zi) of control vertices (Vi), which are transformed into eye space (Zieye) by performing a dot product with a 4-vector, are used as the depth values. The 4D-vector (Mdm) is specified by the application using four render states (D3DRS_ADAPTIVETESS_X, D3DRS_ADAPTIVETESS_Y, D3DRS_ADAPTIVETESS_Z, and D3DRS_ADAPTIVETESS_W). This 4-vector could be the third column of the concatenated world and view matrices. It also could be used to apply a scale to Zieye.

The function to compute a tessellation level Ti from Zieye is assumed to be (MaxTessellationLevel / Zieye), which means that the MaxTessellationLevel is the tessellation level at Z = 1 in eye space. The MaxTessellationLevel is equal to a value set by IDirect3DDevice9::SetNPatchMode for N-patches, and for RT-patches it is equal to pNumSegs. The tessellation level is then clamped to values, defined by the two additional render states D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL, which define the minimum and maximum tessellation levels to be clamped to. The Ti's for each vertex along an edge of a patch are averaged to obtain a tessellation level for that edge. The algorithm for computing Ti for rectangle patches, triangle patches, and N-patches differs in what control vertices are used to compute the tessellation level.

For the rectangle patches with a B-spline basis, the four outermost control vertices are used. For example, with D3DORDER_CUBIC order: vertices (1,1) and (1,width-2) are used with pNumSegs[0], vertices (1,width-2) and (height-2,height-2) are used with pNumSegs[1], vertices (height-2,width-2) and (1,width-2) are used with pNumSegs[2], and vertices (2,1) and (1,1) are used with pNumSegs[3].

For the triangle patches, the corner patch vertices are used. With D3DORDER_CUBIC order: vertices (0) and (9) are used with pNumSegs[0], vertices (9) and (6) are used with pNumSegs[1] and vertices (6) and (0) are used with pNumSegs[3].

For N-patches the triangle vertices are used.

For the rectangle and triangle patches with a Bezier basis, the corner-control vertices are used.

Per-vertex tessellation rate control. An application can optionally supply a single positive floating-point value per vertex, which can be used to control the rate of tessellation. This is supplied using the D3DDECLUSAGE_TESSFACTOR, for which usage index must be 0 and input type must be D3DDECLTYPE_FLOAT1. This is multiplied to the per-vertex tessellation level.

Math

The tessellation level (Te) for an edge e, represented by two control vertices (Ve1, Ve2), is computed as shown below :

Vertex Vi: (Xi, Yi, Zi, TFactori (optional)).
Ze1eye = Ve1 . Mdm
Ze2eye = Ve2 . Mdm
Te1 = MaxTessellationLevel * TFactore1 / Ze1eye
Te2 = MaxTessellationLevel * TFactore2 / Ze2eye
Te = ( Te1 + Te2 ) / 2;
if Te > D3DRS_MAXTESSELLATIONLEVEL || Te < 0, then Te = D3DRS_MAXTESSELLATIONLEVEL
if Te < D3DRS_MINTESSELLATIONLEVEL, then Te = D3DRS_MINTESSELLATIONLEVEL

When D3DRS_ENABLEADAPTIVETESSELLATION is TRUE, triangle primitives (triangle lists, fans, strips) are drawn as N-patches, IDirect3DDevice9::SetNPatchMode has set value less than 1.0.

API Changes

New render states:

 D3DRS_ENABLEADAPTIVETESSELLATION // BOOL
 D3DRS_MAXTESSELLATIONLEVEL       // Float
 D3DRS_MINTESSELLATIONLEVEL       // Float
 D3DRS_ADAPTIVETESS_X             // Float
 D3DRS_ADAPTIVETESS_Y             // Float
 D3DRS_ADAPTIVETESS_Z             // Float
 D3DRS_ADAPTIVETESS_W             // Float

 // D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL
 // cannot be less than 1

And their default values:

D3DRS_MAXTESSELLATIONLEVEL = 1.0f
D3DRS_MINTESSELLATIONLEVEL = 1.0f
D3DRS_ADAPTIVETESS_X = 0.0f
D3DRS_ADAPTIVETESS_Y = 0.0f
D3DRS_ADAPTIVETESS_Z = 1.0f
D3DRS_ADAPTIVETESS_W = 0.0f
D3DRS_ENABLEADAPTIVETESSELLATION = FALSE

New hardware caps:

D3DDEVCAPS2_ADAPTIVETESSRTPATCH // Can adaptively tessellate RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH  // Can adaptively tessellate N-patches

© 2002 Microsoft Corporation. All rights reserved.


Displacement Mapping

Displacement maps are similar to texture maps but are accessed by the vertex engine.

Block Diagram

An additional sampler stage is present in the early part of the vertex pipe, which can sample a displacement map to provide vertex displacement data.

Tessellator block diagram

Blended composite of two objects with banana texture

The displacement map sampler state can be set by the IDirect3DDevice9::SetSamplerState using stage number 256, which is a new stage number. The displacement map texture is set by IDirect3DDevice9::SetTexture.

The map can be presampled or not, which means that it can be ordered in a way that enables the lookup of the displacement values without filtering.

  • Displacement maps are analogous to texture maps but are accessed by the vertex engine.
  • An additional sampler stage is present in the early part of the vertex pipe that can sample a displacement map. This stage is accessed by the usual SetSamplerState application programming interface (API) but the stage number is D3DDMAPSAMPLER = 256.
  • The displacement map sampler state can be set by the SetSamplerState(D3DDMAPSAMPLER, ...) API.
  • The displacement map texture is set by the SetTexture(D3DDMAPSAMPLER, texture) API.
  • The map can be pre-sampled or not. This means that it can be ordered in a particular way that enables the lookup of the displacement values without filtering.
  • The changes in the declaration structure allow the specification of the texture coordinate used to look up the texture map. For example, Stream0, Offset, FLOAT2, LOOKUP, Displacement_value. This tells the tessellator to use the 2-D float vector in stream0 at a certain offset as a texture coordinate to look up the displacement map and associate the Displacement_value usage semantic to it. The vertex shader declaration would contain a line similar to {dcl_texture0, v0} indicating that the texture0 semantic is to be associated with the v0 input register. The displacement value looked up is copied into input register v0.
  • There is a special type of displacement mapping, when the texture map is pre-sampled. Sequential index of generated vertices is used as a texture coordinate to a texture map. For example, 0,0,(D3DDECLTYPE)0,D3DDECLMETHOD_LOOKUPPRESAMPLED, Usage, UsageIndex.
  • The output of the lookup is 4 floats.
  • Displacement mapping is supported only with N-patches.
  • Drivers need to ignore D3DDMAPSAMPLER in SetTextureStageState if they do not handle displacement maps.
  • D3DTEXF_ANISOTROPIC filter mode is not supported.
  • When D3DSAMP_MIPFILTER in the displacement map sampler is not D3DTEXF_NONE, the level of detail is computed as follows (Note that the adaptive tessellation state is used even if the D3DRS_ENABLEADAPTIVETESSELLATION is FALSE):

    Tmax = render state D3DRS_MAXTESSELLATIONLEVEL
  • Compute tessellation level Te for a vertex Vi: (Xi, Yi, Zi) the same way as described in the "Adaptive tessellation" section. Level of detail L = log2(Tmax) - log2 (Te).
  • Texture filtering and sampling operations follow the same rules as the pixel pipeline (level of detail (LOD) bias is applied, etc.).
  • Not all formats can be used as displacement maps but only those that support the D3DUSAGE_DMAP. The application can query that with the CheckDeviceFormat IDirect3D9::CheckDeviceFormat.
  • D3DUSAGE_DMAP must be specified in IDirect3DDevice9::CreateTexture to notify the driver that this texture is to be used as a displacement map.
  • D3DUSAGE_DMAP can only be used with textures. It cannot be used with cube maps or volumes.
  • Textures and render targets created with D3DUSAGE_DMAP can be set at regular sampler stages and as render targets.
  • The render states to set the wrap mode for the texture coordinates are ignored in displacement mapping. In general, there are no wrap modes for the tessellator engine.
  • A displacement map sampler has behavior identical to that of the pixel texture samplers. If a texture with less than four channels (like R32f) is looked up, the looked-up values go to the appropriate channels of the destination register (the vertex shader input register tagged with the _sample semantic), while the other channels default to (1, 1, 1). When looked up, D3DFMT_L8 gets broadcast into the R, G, B channels and A defaults to 1. The reference rasterizer has the full implementation details.

Pre-Sampled Displacement Mapping

  • New sampler state is introduced: D3DSAMP_DMAPOFFSET (DWORD) - offset (in vertices) in a pre-sampled displacement map.
  • New declaration method is introduced: D3DDECLMETHOD_LOOKUPPRESAMPLED.
  • Adaptive tessellation should be disabled.
  • Texture filter settings are ignored. Point sampling is done. The mip texture filter is assumed to be D3DTEXF_NONE. All other texture filter modes are assumed to be D3DTEXF_POINT.
  • Texture coordinates are computed as: U = (Index % TextureWidthInPixeles) / (float)(TextureWidthInPixeles) V = (Index / TextureWidthInPixeles) / (float)(TextureHeightInPixeles) where Index is a sequential index of generated vertices plus TSS[D3DSAMP_DMAPOFFSET]. The sequential index is set to zero at the start of each primitive and is increased after a vertex is generated.

These are the API changes that support displacement mapping.

  • A single channel format added, D3DFMT_L16.
  • A new usage flag, D3DUSAGE_DMAP.
  • A special texture stage, used to set a displacement map texture, D3DDMAPSAMPLER.
  • New hardware caps have been added, D3DDEVCAPS2_DMAPNPATCH and D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH. See D3DDEVCAPS2.

© 2002 Microsoft Corporation. All rights reserved.


Geometry Blending

Microsoft® Direct3D® enables an application to increase the realism of its scenes by rendering segmented polygonal objects—especially characters—that have smoothly blended joints. These effects are often referred to as skinning. The system achieves this effect by applying additional world transformation matrices to a single set of vertices to create multiple results, and then performing a linear blend between the resultant vertices to create a single set of geometry for rendering. The following image of a banana illustrates this.

Blended composite of two objects with banana texture

This image shows how you might imagine the geometry-blending process. In a single rendering call, the system takes the vertices for the banana, transforms them twice—once without modification, and once with a simple rotation—and blends the results to create a bent banana. The system blends the vertex position, as well as the vertex normal when lighting is enabled. Applications are not limited to two blending paths; Direct3D can blend geometry between as many as four world matrices, including the standard world matrix, D3DTS_WORLD.

Note

When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRS_NORMALIZENORMALS render state is set to TRUE.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, consider a 3-D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following code example illustrates this.

typedef struct _Arm
{
    VERTEX upper_arm_verts[200];
    D3DMATRIX matWorld_Upper;

    VERTEX lower_arm_verts[200];
    D3DMATRIX matWorld_Lower;
} ARM, *LPARM;

ARM MyArm; // This needs to be initialized.

To render the arm, two rendering calls are made, as shown in the following code.

// Render the upper arm.
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Upper );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

// Render the lower arm, updating its world matrix to articulate
// the arm by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi/4);
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Lower );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

The following image is a banana, modified to use this technique.

Blended banana image

The differences between the blended geometry and the nonblended geometry are obvious. This example is somewhat extreme. In a real-world application, the joints of segmented models are designed so that seams are not as obvious. However, seams are visible at times, which presents constant challenges for model designers.

Geometry blending in Direct3D presents an alternative to the classic segmented-modeling scenario. However, the improved visual quality of segmented objects comes at the cost of the blending computations during rendering. To minimize the impact of these additional operations, the Direct3D geometry pipeline is optimized to blend geometry with the least possible overhead. Applications that intelligently use the geometry blending services offered by Direct3D can improve the realism of their characters while avoiding serious performance repercussions.

Blending Transform and Render States

The IDirect3DDevice9::SetTransform method recognizes the D3DTS_WORLD and D3DTS_WORLDn macros, which correspond to values that can be defined by the D3DTS_WORLDMATRIX macro. These macros are used to identify the matrices between which geometry will be blended.

The D3DRENDERSTATETYPE enumerated type includes the D3DRS_VERTEXBLEND render state to enable and control geometry blending. Valid values for this render state are defined by the D3DVERTEXBLENDFLAGS enumerated type. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

Blending Weights

A blending weight, sometimes called a beta weight, controls the extent to which a given world matrix affects a vertex. Blending weights are floating-point values that range from 0.0 to 1.0, encoded in the vertex format, where a value of 0.0 means the vertex is not blended with that matrix, and 1.0 means that the vertex is affected in full by the matrix.

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in Vertex Formats. You communicate the number of blending weights in the vertex format by including one of the D3DFVF_XYZB1 through D3DFVF_XYZB5 D3DFVF in the vertex description that you provide to the Direct3D rendering methods.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula.

Formula for linear blending, using world transformation matrices

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix (D3DTS_WORLDn). The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have –1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix so that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases supported by Direct3D.

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix. The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have –1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix so that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases supported by Direct3D.

Formulas for linear blending for three blending cases

These are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases.

Note Although Direct3D includes flexible vertex format descriptors to define vertices that contain up to five blending weights, only three can be used in this release of Microsoft DirectX®.

Additional information is contained in the following topic.

  • Using Geometry Blending

© 2002 Microsoft Corporation. All rights reserved.


Using Geometry Blending

The following user-defined structure can be used for vertices that will be blended between two matrices.

// The flexible vertex format descriptor for this vertex would be:
//   FVF = D3DFVF_XYZB1 | D3DFVF_NORMAL | D3DFVF_TEX1;

struct D3DBLENDVERTEX {
    D3DVECTOR v;
    FLOAT     blend;
    D3DVECTOR n;
    FLOAT     tu, tv;
};

The blend weight must appear after the position and RHW data in the flexible vertex format, and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTS_WORLDMATRIX(0) and D3DTS_WORLDMATRIX(1) transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

Note

Defining skin weights is easy. Using a linear function of the distance between joints is good start, but a smoother sigmoid function looks better. Choosing a skin-weight distribution function can result in sharp creases at joints, if desired, by using a large variation in skin weight over a short distance.

Setting Blending Matrices

You set the transformation matrices between which the system blends by calling the IDirect3DDevice9::SetTransform method. Set the first parameter to a value defined by the D3DTS_WORLDMATRIX macro, and set the second parameter to the address of the matrix to be set.

The following C++ code example sets two world matrices, between which geometry is blended to create the illusion of a jointed arm.

// For this example, the d3dDevice variable is assumed to be a valid pointer
//   to an IDirect3DDevice9 interface for an initialized 3-D scene.

float     BendAngle = 3.1415926f / 4.0f; // 45 degrees
D3DMATRIX matUpperArm, matLowerArm;

// The upper arm is immobile. Use the identity matrix.
D3DXMatrixIdentity( matUpperArm );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matUpperArm );

// The lower arm rotates about the x-axis, attached to the upper arm.
D3DXMatrixRotationX( matLowerArm, -BendAngle );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(1), &matLowerArm );

Setting a blending matrix merely causes the system to cache the matrix for later use; it doesn't instruct the system to begin blending vertices.

Enabling Geometry Blending

Geometry blending is disabled by default. To enable geometry blending, call the IDirect3DDevice9::SetRenderState method to set the D3DRS_VERTEXBLEND render state to a value from the D3DVERTEXBLENDFLAGS enumerated type. The following code example shows what this call might look like when setting the render state for a blend between two world matrices.

d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_1WEIGHTS );

When D3DRS_VERTEXBLEND is set to any value other than D3DVBF_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Microsoft® Direct3D® rendering methods.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.

See Also

Vertex Formats

© 2002 Microsoft Corporation. All rights reserved.


Indexed Vertex Blending

Indexed vertex blending extends the vertex blending support in Microsoft® Direct3D® to allow matrices to be used for blending. These matrices are referred to by using a matrix index. These indices are supplied on a per-vertex basis and refer to a palette of up to 256 matrices. Each index is 8 bits and each vertex can have up to four indices, which allows four matrices to be blended per vertex. The indices are packed into a DWORD. Because indices are specified on a per-vertex basis, up to 12 matrices can affect a single triangle, and any matrix in the palette can affect the vertices of one draw call. This approach has the following advantages.

  • It enables more matrices to affect a single triangle.
  • It enables more blended triangles to be passed in the same draw call.
  • It makes vertex blending independent of triangle indices. This enables progressive meshes to work in conjunction with vertex blending.

One disadvantage of this approach is that it does not work with curved-surface primitives when tessellation occurs before vertex processing.

The following illustration demonstrates how four matrices can affect a vertex. Each vertex has up to four indices, so four matrices can be blended per vertex. The illustration below uses the matrices indexed at 0, 2, 5, and 6.

Indexed vertex blending using 4 of 256 available matrices

The illustration below demonstrates how up to 12 matrices can affect a triangle. Using indices specified on a per-vertex basis, up to 12 matrices can affect the triangle.

Indexed vertex blending for a triangle, using 12 of 256 available matrices

The following formula determines the general case for how matrices effect a vertex.

Formula for the general case of indexed vertex blending

Vmodel is the input model space vertex position. Index0..Index3 are the per-vertex matrix indices packed into a DWORD. M[] is the array of world matrices that get indexed into. b0..b2 are the blend weights. Vworld is the output world space vertex position.

Additional information is contained in the following topic.

  • Using Indexed Vertex Blending

© 2002 Microsoft Corporation. All rights reserved.


Using Indexed Vertex Blending

Transform states 256-511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices. Use the macro D3DTS_WORLDMATRIX to map indices 0-255 to the corresponding transform states. The following code example shows how to use the IDirect3DDevice9::SetTransform method to set the matrix at transform state number 256 to an identity matrix.

D3DMATRIX matBlend1;
D3DXMatrixIdentity( &matBlend1 );
m_pD3DDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matBlend );

To enable or disable indexed vertex blending, set the D3DRS_INDEXEDVERTEXBLENDENABLE render state to TRUE. When the render state is enabled ,you must pass matrix indices as packed DWORDs with every vertex. When this render state is disabled and vertex blending is enabled, it is equivalent to having the matrix indices 0, 1, 2, and 3 in every vertex. The code example below uses the IDirect3DDevice9::SetRenderState method to enable indexed vertex blending.

m_pD3DDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE );

To enable or disable vertex blending, set the IDirect3DDevice9::SetRenderState render state to a value other than D3DRS_DISABLE from the D3DVERTEXBLENDFLAGS enumerated type. If this render state is not set to D3DRS_DISABLE, then you must pass the required number of weights for each vertex. The following code example uses IDirect3DDevice9::SetRenderState to enable vertex blending with three weights for each vertex.

m_pD3DDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_3WEIGHTS );

Determining Indexed Vertex Blending Support

To determine the maximum size for the indexed vertex blending matrix, check the D3DCAPS9 structure's MaxVertexBlendMatrixIndex member. The code example below uses the IDirect3DDevice9::GetDeviceCaps method to retrieve this size.

D3DCAPS9 d3dCaps;

m_pD3DDevice->GetDeviceCaps( &d3dCaps );
IndexedMatrixMaxSize = d3dCaps.MaxVertexBlendMatrixIndex;

If the value set in MaxVertexBlendMatrixIndex is 0, the device does not support indexed matrices.

Note When software vertex processing is used, 256 matrices can be used for indexed vertex blending, with or without normal blending.

Passing Matrix Indices to Direct3D

World matrix indices can be passed to Microsoft® Direct3D® by using legacy vertex shaders—flexible vertex format (FVF)—or declarations.

The code example below shows how to use legacy vertex shaders.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZB2 | D3DFVF_LASTBETA_UBYTE4 |
                             D3DFVF_NORMAL);

When a legacy vertex shader is used, matrix indices are passed together with vertex positions using D3DFVF_XYZBn flags. Matrix indices are passed as bytes inside a DWORD and must be present immediately after the last vertex weight. Vertex weights are also passed using D3DFVF_XYZBn. A packed DWORD contains index3, index2, index1, and index0, where index0 is located in the lowest byte of the DWORD. The number of used world-matrix indices is equal to the number passed to the number of matrices used for blending as defined by D3DRS_VERTEXBLEND.

When a declaration is used, D3DVSDE_BLENDINDICES defines the input vertex register to get matrix indices from. Matrix indices must be passed as D3DVSDT_UBYTE4.

The code example below shows how to use declarations. Note that the order of the components is no longer important unless using a fixed-function vertex shader.

Here is the vertex declaration.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
}

Here is the corresponding register declaration.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
    { 0, 16, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
    { 0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    D3DDECL_END()
};

© 2002 Microsoft Corporation. All rights reserved.


Vertex Blending

Vertex blending is used for creating effects such as smooth joints and bulging muscles in character animations.

The vertex blend sample demonstrates a technique called vertex blending, also known as surface skinning. See Vertex Blend Sample.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Tweening

Vertex tweening is used to blend two user-provided positions or normal streams. It can be used only with declarations. Tweening is enabled by setting D3DRS_VERTEXBLEND to D3DVBF_TWEENING. Vertex blending using weights and vertex blending tweening are mutually exclusive.

The C++ Dolphin VS Sample uses vertex tweening to animate a dolphin so that it appears to move through the water. The images below show the dolphin at two different points. Notice that the dolphin's tail has gone from an up position to a down position and its nose points downward more in the right image.

Dolphin images with tail up and tail down

Tweening is performed before lighting and clipping. The resulting vertex position (normal) is computed as follows:

POSITION = POSITION1 * (1.0 - TWEENFACTOR) + POSITION2 * TWEENFACTOR, and likewise for normals.

Additional information is contained in the following topic.

Overviews

  • Using Vertex Tweening

Vertex Shader Tweening

The code for using vertex shader tweening is similar to the code for the fixed-function tweening shown in the Using Vertex Tweening topic.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFile

© 2002 Microsoft Corporation. All rights reserved.


Using Vertex Tweening

This topic shows how to use vertex tweening

Determining Support for Vertex Tweening

To determine if Microsoft® Direct3D® supports vertex tweening, check for the D3DVTXPCAPS_TWEENING flag in the VertexProcessingCaps member of the D3DCAPS9 structure. The following code example uses the IDirect3DDevice9::GetDeviceCaps method to determine if tweening is supported.

//
// This example assumes that m_d3dDevice is
// a valid pointer to a IDirect3DDevice9 interface.
//

D3DCAPS9 d3dCaps;

m_d3dDevice->GetDeviceCaps( &d3dCaps );
if( 0 != (d3dCaps.VertexProcessingCaps & D3DVTXPCAPS_TWEENING) )
    //Vertex tweening is supported.

Setting Vertex Declaration

To use vector tweening, you must first set up a custom vertex type that uses a second normal or a second position. The following code example shows a sample declaration that includes both a second point and a second position.

struct TEX_VERTEX
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DVECTOR position2;
    D3DVECTOR normal2;
};

//Create a vertex buffer with the type TEX_VERTEX.

The next step is to set the current declaration. The code example below shows how to do this.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    { 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    D3DDECL_END()
};

For more information about creating a custom vertex type and a vertex buffer, see Creating a Vertex Buffer.

Note When vertex tweening is enabled, a second position or a second normal must be present in the current declaration.

© 2002 Microsoft Corporation. All rights reserved.


Higher-Order Primitives

Microsoft® Direct3D® for Microsoft DirectX® 9.0 supports points, lines, triangles, and grid primitives. These have been extended to support higher-order interpolation beyond linear. While triangles and lines have spatial extent, until now they were both rendered using linear interpolation. In DirectX 9.0, Direct3D supports rendering of these primitive types using higher order, up to quintic, interpolation. Furthermore, a new quad primitive type is now supported. This new type can also be rendered with higher-order interpolation. This feature is primarily driven by requirements for animation and rendering of characters. It can also be used for other surfaces such as terrain or water.

Higher-order primitives support higher-order interpolation when transmitted to the application programming interface (API) as lists, strips, fans, or indexed meshes. This is achieved by using additional information encoded in the vertices themselves. For example, normal vectors can be used to define tangent planes at the vertices to enable cubic interpolation. Most implementations support higher-order interpolation by tessellation into planar triangles. The tessellation step is applied logically before the vertex shader stage. Because the vertex shader API does not impose semantics on its input data, a special mechanism is provided to identify the vertex stream component that represents the position, and optionally the normal vector. All other components are interpolated accordingly.

This section introduces higher-order primitives and discusses how they can be used in your applications. Information is divided into the following topics.

  • Improved Quality through Resolution Enhancement
  • Direct Mapping from Spline-Based Tools

Improved Quality through Resolution Enhancement

Current primitives are not ideal for representing smooth surfaces. Higher-order interpolation methods, such as cubic polynomials, allow more accurate calculations in rendering curved shapes. This provides increased realism by reducing or eliminating faceting artifacts visible on silhouette edges or on specular surface lighting. Furthermore, when tessellation occurs on the chip, the tessellated triangles do not impact the bus bandwidth. In many cases, a small amount of tessellation can provide improvements in image quality with minimal performance impact.

Direct3D for DirectX 9.0 provides a simple way to apply resolution enhancement to content created by existing polygon-oriented tools and art pipelines. The application need only provide a desired level of tessellation, and transmit the data using standard triangle syntax that includes normal vectors.

Direct Mapping from Spline-Based Tools

Many current authoring tools support higher-order primitives to enable more powerful modeling operations than are commonly provided for with planar triangle meshes. When used efficiently, so that the number of patches generated is reasonable, such tools can produce content that can be rendered directly by the API. To meet this requirement, a new entry point has been added that interprets the incoming vertex data stream as a 2-D array of control points and tessellates it to the desired resolution.

  • Using Higher-Order Primitives

© 2002 Microsoft Corporation. All rights reserved.


Using Higher-Order Primitives

This section shows you how to use higher-order primitives in your application.

  • Determining Higher-Order Primitive Support
  • Drawing Patches
  • Generating Normals and Texture Coordinates

Determining Higher-Order Primitive Support

The D3DCAPS9 structure's DevCaps member can be queried to determine the level of support for operations involving higher-order primitives. The following table lists the device capabilities related to higher-order primitives in Microsoft® DirectX® 9.0.

Device capability | Description
D3DDEVCAPS_NPATCHES | Device supports N-patches.
D3DDEVCAPS_QUINTICRTPATCHES | Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES | Device supports rectangular and triangular patches (RT-patches).
D3DDEVCAPS_RTPATCHHANDLEZERO | RT-patches might be drawn efficiently using handle zero.

Note that D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle zero patch can always be drawn, whether this device capability is set or not. When this capability is set, the hardware architecture does not require caching of any information and that uncached patches (handle zero) be drawn as efficiently as cached ones.

Drawing Patches

DirectX 9.0 supports two types of higher order primitives, or patches. These are referred to as N-Patches and Rect/Tri patches. N-patches can be rendered using any triangle rendering call by enabling N-patches through the call to IDirect3DDevice9::SetNPatchMode( nSegments ) with nSegments value greater than 1.0. Rect/Tri patches must be rendered using the following explicit entry points.

You can use the following methods to draw patches.

  • IDirect3DDevice9::DrawRectPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DRECTPATCH_INFO.
  • IDirect3DDevice9::DrawTriPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DTRIPATCH_INFO.

IDirect3DDevice9::DrawRectPatch draws a rectangular high-order patch specified by the pRectPatchInfo parameter using the currently set streams. The Handle parameter is used to associate the patch with a handle, so that the next time the patch is drawn, there is no need to respecify pRectPatchInfo. This makes it possible to precompute and cache forward difference coefficients or other information, which in turn enables subsequent calls to IDirect3DDevice9::DrawRectPatch using the same handle to run efficiently.

It is intended that for static patches, an application would set the vertex shader and appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Microsoft Direct3D® can capture and cache information. The application can then call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. However, it is possible to override the cached pNumSegs by specifying new values for pNumSegs. Also, it is required to set the same vertex shader when rendering a cached patch as was set when it was captured.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values and does not cache any information. It is not valid to simultaneously set Handle to 0 and pPatch to NULL.

By respecifying pRectPatchInfo for the same handle, the application can overwrite the previously cached information.

IDirect3DDevice9::DrawTriPatch is similar to IDirect3DDevice9::DrawRectPatch except that it draws a triangular high-order patch.

Generating Normals and Texture Coordinates

If you are using a flexible vertex format (FVF) shader, automatic generation of normals and texture coordinates is not possible.

For normals, you can either directly supply them or have Direct3D calculate them for you.

The coordinates generated for rectangular patches are spline-based coordinates, as illustrated by the following images.

The coordinates generated for triangular patches are barycentric spline-based coordinates, as illustrated by the images below.

Barycentric spline-based coordinates

If an application must change the range of the generated texture coordinates, this can be done using texture transforms.

© 2002 Microsoft Corporation. All rights reserved.


Point Sprites

Support for point sprites in Microsoft® Direct3D® for Microsoft DirectX® 9.0 enables the high-performance rendering of points (particle systems). Point sprites are generalizations of generic points that enable arbitrary shapes to be rendered as defined by textures.

  • Point Primitive Rendering Controls
  • Point Size Computations
  • Point Rendering

Point Primitive Rendering Controls

Direct3D for DirectX 9.0 supports additional parameters to control the rendering of point sprites (point primitives). These parameters enable points to be of variable size and have a full texture map applied. The size of each point is determined by an application-specified size combined with a distance-based function computed by Direct3D. The application can specify point size either as per-vertex or by setting D3DRS_POINTSIZE, which applies to points without a per-vertex size. The point size is expressed in camera space units, with the exception of when the application is passing post-transformed flexible vertex format (FVF) vertices. In this case, the distance-based function is not applied and the point size is expressed in units of pixels on the render target.

The texture coordinates computed and used when rendering points depends on the setting of D3DRS_POINTSPRITEENABLE. When this value is set to TRUE, the texture coordinates are set so that each point displays the full texture. In general, this is only useful when points are significantly larger than one pixel. When D3DRS_POINTSPRITEENABLE is set to FALSE, each point's vertex texture coordinate is used for the entire point.

Point Size Computations

Point size is determined by D3DRS_POINTSCALEENABLE. If this value is set to FALSE, the application-specified point size is used as the screen-space (post-transformed) size. Vertices that are passed to Direct3D in screen space do not have point sizes computed; the specified point size is interpreted as screen-space size.

If D3DRS_POINTSCALEENABLE is TRUE, Direct3D computes the screen-space point size according to the following formula. The application-specified point size is expressed in camera space units.

S s = Vh * S i * sqrt(1/(A + B * D e + C *( D e2 )))

In this formula, the input point size, S i, is either per-vertex or the value of the D3DRS_POINTSIZE render state. The point scale factors, D3DRS_POINTSCALE_A, D3DRS_POINTSCALE_B, and D3DRS_POINTSCALE_C, are represented by the points A, B, and C. The height of the viewport, V h, is the D3DVIEWPORT9 structure's Height member representing the viewport. D e, the distance from the eye to the position (the eye at the origin), is computed by taking the eye space position of the point (Xe, Ye, Ze) and performing the following operation.

D e = sqrt (Xe2 + Y e2 + Z e2)

The maximum point size, Pmax, is determined by taking the smaller of either the D3DCAPS9 structure's MaxPointSize member or the D3DRS_POINTSIZE_MAX render state. The minimum point size, Pmin, is determined by querying the value of D3DRS_POINTSIZE_MIN. Thus the final screen-space point size, S, is determined in the following manner.

  • If Ss > Pmax, then S = P max
  • if S < Pmin, then S = P min
  • Otherwise, S = S s

Point Rendering

A screen-space point, P = ( X, Y, Z, W), of screen-space size S is rasterized as a quadrilateral of the following four vertices.

(( X + S/2, Y + S/2, Z, W), ( X + S/2, Y - S/2, Z, W), ( X - S/2, Y- S/2, Z, W), ( X - S/2, Y + S/2, Z, W))

The vertex color attributes are duplicated at each vertex; thus each point is always rendered with constant colors.

The assignment of texture indices is controlled by the D3DRS_POINTSPRITEENABLE render state setting. If D3DRS_POINTSPRITEENABLE is set to FALSE, then the vertex texture coordinates are duplicated at each vertex. If D3DRS_POINTSPRITEENABLE is set to TRUE, then the texture coordinates at the four vertices are set to the following values.

(0.F, 0.F), (0.F, 1.F), (1.F, 0.F), (1.F, 1.F)

This is shown in the following diagram.

Square with vertices labeled with (u,v) and (x,y) coordinate values

When clipping is enabled, points are clipped in the following manner. If the vertex exceeds the range of depth values - MinZ and MaxZ of the D3DVIEWPORT9 structure - into which a scene is to be rendered, the point exists outside of the view frustum and is not rendered. If the point, taking into account the point size, is completely outside the viewport in X and Y, then the point is not rendered; the remaining points are rendered. It is possible for the point position to be outside the viewport in X or Y and still be partially visible.

Points may or may not be correctly clipped to user-defined clip planes. If D3DPMISCCAPS_CLIPPLANESCALEDPOINTS is not set in the D3DCAPS9 structure's PrimitiveMiscCaps member, points are clipped to user-defined clip planes based only on the vertex position, ignoring the point size. In this case, scaled points are fully rendered when the vertex position is inside the clip planes, and discarded when the vertex position is outside a clip plane. Applications can prevent potential artifacts by adding a border geometry to clip planes that is as large as the maximum point size.

If the D3DPMISCCAPS_CLIPPLANESCALEDPOINTS bit is set, then the scaled points are correctly clipped to user-defined clip planes.

Hardware vertex processing may or may not support point size. For example, if a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING on a HAL device (D3DDEVTYPE_HAL) that has the D3DCAPS9 structure's MaxPointSize member set to 1.0 or 0.0, then all points are a single pixel. To render pixel point sprites less than 1.0, you must use either FVF TL (transformed and lit) vertices or software vertex processing (D3DCREATE_SOFTWARE_VERTEXPROCESSING), in which case the Direct3D run time emulates the point sprite rendering.

A hardware device that does vertex processing and supports point sprites—MaxPointSize set to greater than 1.0f—is required to perform the size computation for nontransformed sprites and is required to properly set the per-vertex or D3DRS_POINTSIZE for TL vertices.

For information about rendering rules for points, lines, and triangles, see Triangle Rasterization Rules.

© 2002 Microsoft Corporation. All rights reserved.


Matrix Stacks

The Direct3D extensions (D3DX) utility library provides the ID3DXMatrixStack interface. It supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy.

The D3DX utility library uses a matrix stack to store transformations as matrices. The various methods of the ID3DXMatrixStack interface deal with the current matrix, or the matrix located on top of the stack. You can clear the current matrix with the ID3DXMatrixStack::LoadIdentity method. To explicitly specify a certain matrix to load as the current transformation matrix, use the ID3DXMatrixStack::LoadMatrix method. Then you can call either the ID3DXMatrixStack::MultMatrix method or the ID3DXMatrixStack::MultMatrixLocal method to multiply the current matrix by the specified matrix.

The ID3DXMatrixStack::Pop method enables you to return to the previous transformation matrix and the ID3DXMatrixStack::Push method adds a transformation matrix to the stack.

The individual matrices on the matrix stack are represented as 4×4 homogeneous matrices, defined by the D3DX utility library D3DXMATRIX structure.

The D3DX utility library provides a matrix stack through a Component Object Model (COM) object.

Implementing a Scene Hierarchy

A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects.

A scene, or transform, hierarchy is usually represented by a tree data structure. Each node in the tree data structure contains a matrix. A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you are modeling a human arm, you might implement the following hierarchy.

Hierarchy of modeling of a human arm

In this hierarchy, the Body matrix places the body in the world. The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist. To determine where the hand is relative to the world, you multiply all the matrices from Body down through Hand together.

The previous hierarchy is overly simplistic, because each node has only one child. If you begin to model the hand in more detail, you will probably add fingers and a thumb. Each digit can be added to the hierarchy as children of Hand.

Hierarchy of modeling of a human hand

If you traverse the complete graph of the arm in depth-first order—traversing as far down one path as possible before moving on to the next path—to draw the scene, you perform a sequence of segmented rendering. For example, to render the hand and fingers, you implement the following pattern.

  1. Push the Hand matrix onto the matrix stack.
  2. Draw the hand.
  3. Push the Thumb matrix onto the matrix stack.
  4. Draw the thumb.
  5. Pop the Thumb matrix off the stack.
  6. Push the Finger 1 matrix onto the matrix stack.
  7. Draw the first finger.
  8. Pop the Finger 1 matrix off the stack.
  9. Push the Finger 2 matrix onto the matrix stack. You continue in this manner until all the fingers and thumb are rendered.

After you have completed rendering the fingers, you would pop the Hand matrix off the stack.

You can follow this basic process in code with the following examples. When you encounter a node during the depth-first search of the tree data structure, push the matrix onto the top of the matrix stack.

MatrixStack->Push();

MatrixStack->MultMatrix(pNode->matrix);

When you are finished with a node, pop the matrix off the top of the matrix stack.

MatrixStack->Pop();

In this way, the matrix on the top of the stack always represents the world-transform of the current node. Therefore, before drawing each node, you should set the Microsoft® Direct3D® matrix.

pD3DDevice->SetTransform(D3DTS_WORLDMATRIX(0), *MatrixStack->GetTop());

For more information about the specific methods that you can perform on a D3DX matrix stack, see the ID3DXMatrixStack reference topic.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Pipeline

This is a list of advanced topics that are implemented by pixel processing.

  • Scissor Test
  • Depth Bias
  • Stencil Buffer Techniques
  • Shadowing
  • Bump Mapping
  • Environment Mapping
  • Antialiasing
  • Multiple Render Target
  • Multielement Texture

© 2002 Microsoft Corporation. All rights reserved.


ScissorTest

Scissor Test API

The scissor rectangle is managed by a device render state. A scissor test is enabled or disabled by setting the renderstate to TRUE or FALSE. This test is performed after the fragment color is computed but before alpha testing. SetRenderTarget resets the scissor recttangle to the full render target, analogous to the viewport reset. SetScissorRect is recorded by the stateblocks (and the CreateStateBlock with pixel state and all state). The scissor test also affects the device Clear operation.

// methods
HRESULT IDirect3DDevice9::SetScissorRect( CONST RECT* pRect );
HRESULT IDirect3DDevice9::GetScissorRect( RECT* pRect );

// new RenderState, values are TRUE or FALSE
D3DRS_SCISSORTESTENABLE

// new hardware cap
D3D9CAPS.RasterCaps -> D3DPRASTERCAPS_SCISSORTEST;
};

The default scissor rect is the full viewport.

Scissor testing is done just after pixel processing is completed by a pixel shader or the fixed function pipeline, as shown below.

Scissor test flowchart

© 2002 Microsoft Corporation. All rights reserved.


Depth Bias

Depth values of fragments, generated while rasterizing a primitive, can be biased. This ability helps mitigate z-fighting issues when drawing co-planar primitives.

This ability was exposed in previous versions of Microsoft® Direct3D® but was never specified nor implemented in the Reference Device.

D3DPRASTERCAPS_DEPTHBIAS and D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS have been added to distinguish between the legacy devices that exposed the D3DPRASTERCAPS_ZBIAS and performed some unspecified behavior, and those that can perform true slope-scale based depth bias. Applications now specify two floating point values: D3DRS_DEPTHBIAS and D3DRS_SLOPESCALEDEPTHBIAS, which are used to compute the offset. The offset is added to the fragment's interpolated depth value to produce the final depth value that is used for depth testing and optionally is written into the depth buffer.

Offset = m * D3DRS_SLOPESCALEDEPTHBIAS + D3DRS_DEPTHBIAS

where m is the maximum depth slope of the triangle being rendered.

m = max(abs(delta z / delta x), abs(delta z / delta y))

The units for the D3DRS_DEPTHBIAS and D3DRS_SLOPESCALEDEPTHBIAS render states depend on whether z-buffering or w-buffering is enabled. The application must provide suitable values.

The bias is not applied to any line and point primitive. However, this bias needs to be applied to triangles drawn in wireframe mode.

API Changes

    // RenderStates
    D3DRS_SLOPESCALEDEPTHBIAS, // New, defaults to zero
    D3DRS_DEPTHBIAS,           // New, defaults to zero

    // Caps
    D3DPRASTERCAPS_DEPTHBIAS           // New
    D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS // New

© 2002 Microsoft Corporation. All rights reserved.


Stencil Buffer Techniques

Applications use the stencil buffer to mask pixels in an image. The mask controls whether the pixel is drawn. Some of the more common effects are shown below.

  • Compositing
  • Decaling
  • Dissolves, Fades, and Swipes
  • Outlines and Silhouettes
  • Two-Sided Stencil

The stencil buffer enables or disables drawing to the rendering target surface on a pixel-by-pixel basis. At its most fundamental level, it enables applications to mask sections of the rendered image so that they are not displayed. Applications often use stencil buffers for special effects such as dissolves, decaling, and outlining.

Stencil buffer information is embedded in the z-buffer data. Your application can use the IDirect3D9::CheckDeviceFormat method to check for hardware stencil support, as shown in the following code example.

// Reject devices that cannot perform 8-bit stencil buffering.
// The following example assumes that pCaps is a valid pointer
// to an initialized D3DCAPS9 structure.

if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                       pCaps->DeviceType,
                                       Format,
                                       D3DUSAGE_DEPTHSTENCIL,
                                       D3DRTYPE_SURFACE,
                                       D3DFMT_D24S8 ) ) )
        return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 8-bit stencil buffers are rejected. Note that this is only one possible use for IDirect3D9::CheckDeviceFormat; for details see Determining Hardware Support.

How the Stencil Buffer Works

Microsoft® Direct3D® performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps.

  1. Perform a bitwise AND operation of the stencil reference value with the stencil mask.
  2. Perform a bitwise AND operation of the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2, using the comparison function.

These steps are shown in the following code example.

(StencilRef & StencilMask) CompFunc (StencilBufferValue & StencilMask)

StencilBufferValue is the contents of the stencil buffer for the current pixel. This code example uses the ampersand (&) symbol to represent the bitwise AND operation. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and is ignored otherwise. The default comparison behavior is to write the pixel, no matter how each bitwise operation turns out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRS_STENCILFUNC render state, passing a member of the D3DCMPFUNC enumerated type to identify the desired comparison function.

Your application can customize the operation of the stencil buffer. It can set the comparison function, the stencil mask, and the stencil reference value. It can also control the action that Direct3D takes when the stencil test passes or fails. For more information, see Stencil Buffer State.

© 2002 Microsoft Corporation. All rights reserved.


Compositing

Your application can use the stencil buffer to composite 2-D or 3-D images onto a 3-D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2-D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3-D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3-D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3-D scene behind the driver. It is essentially a second 3-D scene composited with the driver's forward view.

© 2002 Microsoft Corporation. All rights reserved.


Decaling

Microsoft® Direct3D® applications use decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Applications apply decals to the images of primitives to enable coplanar polygons to render correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called z-fighting or flimmering.

To solve this problem, use a stencil to mask the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Although multiple texture blending can be used to solve this problem, doing so limits the number of other special effects that your application can produce. Using the stencil buffer to apply decals frees up texture blending stages for other effects.

© 2002 Microsoft Corporation. All rights reserved.


Dissolves, Fades, and Swipes

Increasingly, applications employ special effects that are commonly used in movies and video, such as dissolves, swipes, and fades.

In a dissolve, one image is gradually replaced by another in a smooth sequence of frames. Although Microsoft® Direct3D® provides methods of using multiple texture blending to achieve the same effect, applications that use the stencil buffer for dissolves can use texture-blending capabilities for other effects while they do a dissolve.

When your application performs a dissolve, it must render two different images. It uses the stencil buffer to control which pixels from each image are drawn to the rendering target surface. You can define a series of stencil masks and copy them into the stencil buffer on successive frames. Alternately, you can define a base stencil mask for the first frame and alter it incrementally.

At the beginning of the dissolve, your application sets the stencil function and stencil mask so that most of the pixels from the starting image pass the stencil test. Most of the pixels from the ending image should fail the stencil test. On successive frames, the stencil mask is updated so that fewer and fewer of the pixels in the starting image pass the test. As the frames progress, fewer and fewer of the pixels in the ending image fail the test. In this manner, your application can perform a dissolve using any arbitrary dissolve pattern.

Fading in or fading out is a special case of dissolving. When fading in, the stencil buffer is used to dissolve from a black or white image to a rendering of a 3-D scene. Fading out is the opposite, your application starts with a rendering of a 3-D scene and dissolves to black or white. The fade can be done using any arbitrary pattern you want to employ.

Direct3D applications use a similar technique for swipes. For example, when an application performs a left-to-right swipe, the ending image appears to slide gradually on top of the starting image from left to right. As in a dissolve, you must define a series of stencil masks that are loaded into the stencil buffer on successive frames, or successively modify the starting stencil mask. The stencil masks are used to disable the writing of pixels from the starting image and to enable the writing of pixels from the ending image.

A swipe is somewhat more complex than a dissolve in that your application must read pixels from the ending image in the reverse order of the swipe. That is, if the swipe is moving from left to right, your application must read pixels from the ending image from right to left.

© 2002 Microsoft Corporation. All rights reserved.


Outlines and Silhouettes

You can use the stencil buffer for more abstract effects, such as outlining and silhouetting.

If your application applies a stencil mask to the image of a primitive that is the same shape but slightly smaller, the resulting image contains only the primitive's outline. The application can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image contains a hole where the primitive should be. Your application can then fill the hole with black to produce a silhouette of the primitive.

© 2002 Microsoft Corporation. All rights reserved.


Two-Sided Stencil

Shadow Volumes are used for drawing shadows with the stencil buffer. The application computes the shadow volumes cast by occluding geometry, by computing the silhouette edges and extruding them away from the light into a set of 3-D volumes. These volumes are then rendered twice into the stencil buffer.

The first render draws forward-facing polygons, and increments the stencil-buffer values. The second render draws the back-facing polygons of the shadow volume, and decrements the stencil buffer values. Normally, all incremented and decremented values cancel each other out. However, the scene was already rendered with normal geometry causing some pixels to fail the z-buffer test as the shadow volume is rendered. Values left in the stencil buffer correspond to pixels that are in the shadow. These remaining stencil-buffer contents are used as a mask, to alpha-blend a large, all-encompassing black quad into the scene. With the stencil buffer acting as a mask, the result is to darken pixels that are in the shadows.

This means that the shadow geometry is drawn twice per light source, hence putting pressure on the vertex throughput of the GPU. The two-sided stencil feature has been designed to mitigate this situation. In this approach, there are two sets of stencil state (named below), one set each for the front-facing triangles and the other for the back-facing triangles. This way, only a single pass is drawn per shadow volume, per light.

The application programming interface (API) changes are restricted to a new set of render states. The new render state D3DRS_TWOSIDEDSTENCILMODE can be set to TRUE or FALSE. It is false by default, meaning current (Microsoft® DirectX® 8.x) behavior. When this is set to TRUE (it will work only if D3DSTENCILCAPS_TWOSIDED is set), the following render states will apply only to the front-facing (clockwise) triangles.

Render state | Description
D3DRS_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_STENCILFUNC | D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

A new set of render states apply to the back-facing (counterclockwise) triangles.

Render state | Description
D3DRS_CCW_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_CCW_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_CCW_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_CCW_STENCILFUNC | D3DCMPFUNC function. Stencil test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

The remaining stencil render states always apply to both clockwise and counterclockwise triangles.

D3DRS_TWOSIDEDSTENCILMODE is ignored for lines and point sprites, which means that the behavior is unchanged from DirectX 8.x. The D3DRS_CCW_STENCIL* render states are ignored.

A new cap bit indicates if the device supports this feature. Drivers that do not support this feature are expected to ignore these new render states. All other stencil cap bits apply to both modes of stencil buffering. Because TWOSIDEDSTENCIL implies the ability to draw with D3DCULLMODE_NONE set, the corresponding cap must be set by the driver if it supports this new stencil mode. Microsoft Windows® Hardware Quality Labs (WHQL) should enforce this.

New render states:

    D3DRS_TWOSIDEDSTENCILMODE // BOOL (default is FALSE)
    D3DRS_CCW_STENCILFAIL     // Same default as D3DRS_STENCILFAIL
    D3DRS_CCW_STENCILZFAIL    // Same default as D3DRS_STENCILZFAIL
    D3DRS_CCW_STENCILPASS     // Same default as D3DRS_STENCILPASS
    D3DRS_CCW_STENCILFUNC     // Same default as D3DRS_STENCILFUNC

New cap:

    D3DSTENCILCAPS_TWOSIDED // a flag on D3DCAPS9.StencilCaps

Related Topics

  • D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


Shadowing

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

The Shadow Volume sample uses stencil buffers to implement real-time shadows. See Shadow Volume Sample.

Related Topics

  • Two-Sided Stencil

© 2002 Microsoft Corporation. All rights reserved.


Bump Mapping

Bump mapping is a special form of specular or diffuse environment mapping that simulates the reflections of finely tessellated objects without requiring extremely high polygon counts. The following image, based on the Bump Earth Sample, demonstrates bump mapping effects.

Smooth sphere on left simulates Earth; sphere on right adds bumpmap texture

The globe on the left is a sphere textured with an image of the Earth's surface, with a specular environment map applied. The globe on the right is exactly the same, but also has a bump map applied. The polygon count for the second globe is unchanged from that of the first globe.

Bump mapping in Microsoft® Direct3D® can be accurately described as per-pixel texture coordinate perturbation of specular or diffuse environment maps, because you provide information about the contour of the bump map in terms of delta values, which the system applies to the u and v texture coordinates of an environment map in the next texture stage. The delta values are encoded in the pixel format of the bump map surface. For more information, see Bump Map Pixel Formats.

The BumpEarth sample uses a height map to store contour data. When the sample starts, it processes the pixels in the height map to compute the appropriate u and v delta values, based on the relative height of each pixel to the four neighboring pixels.

Direct3D does not natively support height maps; they are merely a convenient format in which to store and visualize contour data. The preceding image is based on the height map used by the BumpEarth sample to produce the bump map it supplies to Direct3D and is included here for descriptive purposes. Your application can store contour information in any format, or even generate a procedural bump map, as the Bump Waves Sample does.

This is the height map image that the BumpEarth sample uses to compute the delta values encoded in the pixel format of the bump map texture.

Image that encodes a height map of the Earth

Bump mapping relies completely on multiple texture blending services, and requires that the device support at least two blending stages—one for the bump map and another for an environment map. A minimum of three texture blending stages are required to apply a base texture map, the most common case. The following figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade.

Texture blending cascade used to generate polygon texture

You must prepare the texture stages appropriately to enable bump mapping.

This section provides information about performing bump mapping with Direct3D. The following topics introduce bump mapping, identify and define its key concepts, and provide details about how you can use bump-mapping in your applications.

  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping

© 2002 Microsoft Corporation. All rights reserved.


Bump Map Pixel Formats

A bump map is an IDirect3DTexture9 object that uses a specialized pixel format. Rather than storing red, green, and blue color components, each pixel in a bump map stores the delta values for u and v (DU and DV) and sometimes a luminance component, L. These values are applied by the system as described in the Bump Mapping Formulas topic.

You can specify a bump map pixel format by setting the format to one of the following: D3DFMT_CxV8U8, D3DFMT_V8U8, D3DFMT_L6V5U5, D3DFMT_X8L8V8U8, D3DFMT_Q8W8V8U8, or D3DFMT_V16U16. For descriptions, see D3DFORMAT.

The DU and DV components of a pixel are signed values that range from –1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note Before picking a bump map pixel format, check if the particular format is supported. For more information, see Using Bump Mapping.

© 2002 Microsoft Corporation. All rights reserved.


Bump Mapping Formulas

Microsoft® Direct3D® applies the following formulas to the DU and DV components in each bump map pixel.

Formula for bump mapping matrix transformation

In these formulas, the DU and DV variables are taken directly from a bump map pixel and transformed by a 2x2 matrix to produce the output delta values DU' and DU'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value that it uses to modulate the color of the environment map in the next blending stage.

Formula for output luminance, computed from scale factor and offset

In this formula, L' is the output luminance being computed. The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values DU' and DV', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.

© 2002 Microsoft Corporation. All rights reserved.


Using Bump Mapping

Detecting Support for Bump Mapping

A device can perform bump mapping if it supports either the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operation. Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_LEGACYBUMPMAP to see if a format is supported for bump mapping.

Additionally, applications should check the device capabilities to make sure the device supports an appropriate number of blending stages, usually at least three, and exposes at least one bump-mapping pixel format.

The following code example checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

BOOL SupportsBumpMapping()
{
    D3DCAPS9 d3dCaps;

    d3dDevice->GetDeviceCaps( &d3dCaps );

    // Does this device support the two bump mapping blend operations?
    if ( 0 == d3dCaps.TextureOpCaps & ( D3DTEXOPCAPS_BUMPENVMAP |
                                         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE ))
        return FALSE;

    // Does this device support up to three blending stages?
    if( d3dCaps.MaxTextureBlendStages < 3 )
        return FALSE;

    return TRUE;
}

Creating a Bump Map Texture

You create a bump map texture like any other texture. Your application verifies support for bump mapping and retrieves a valid pixel format, as discussed in Detecting Support for Bump Mapping.

After the surface is created, you can load each pixel with the appropriate delta values, and luminance, if the surface format includes luminance. The values for each pixel component are described in Bump Map Pixel Formats.

Configuring Bump Mapping Parameters

When your application has created a bump map and set the contents of each pixel, you can prepare for rendering by configuring bump mapping parameters. Bump mapping parameters include setting the required textures and their blending operations, as well as the transformation and luminance controls for the bump map itself.

  1. Set the base texture map if used, bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values as needed.

The following code example sets three textures (the base texture map, the bump map, and a specular environment map) to the appropriate texture blending stages.

// Set the three textures.
d3dDevice->SetTexture( 0, d3dBaseTexture );
d3dDevice->SetTexture( 1, d3dBumpMap );
d3dDevice->SetTexture( 2, d3dEnvMap );

After setting the textures to their blending stages, the following code example prepares the blending operations and arguments for each stage.

// Set the color operations and arguments to prepare for
//   bump mapping.

// Stage 0: The base texture
d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 1 );

// Stage 1: The bump map - Use luminance for this example.
d3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE);
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Stage 2: A specular environment map
d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, 0 );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG2, D3DTA_CURRENT );

When the blending operations and arguments are set, the following code example sets the 2x2 bump mapping matrix to the identity matrix by setting the D3DTSS_BUMPENVMAPMAT00 and the D3DTSS_BUMPENVMAPMAT11 members of D3DTEXTURESTAGESTATETYPE to 1.0. Setting the matrix to the identity causes the system to use the delta values in the bump map unmodified, but this is not a requirement.

// Set the bump mapping matrix.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(1.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(1.0f) );

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. For details, see Bump Mapping Formulas.

// Set luminance controls. This is only needed when using
// a bump map that contains luminance, and when the
// D3DTOP_BUMPENVMAPLUMINANCE texture blending operation is
// being used.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(0.5f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );

After your application configures bump mapping parameters, it can render as normal, and the rendered polygons receive bump mapping effects.

Note that the preceding example shows parameters set for specular environment mapping. When performing diffuse light mapping, applications set the texture blending operation for the last stage to D3DTOP_MODULATE. For more information, see Diffuse Light Maps.

© 2002 Microsoft Corporation. All rights reserved.


Environment Mapping

Environment mapping is a technique that simulates highly reflective surfaces without using ray tracing. In practice, environment mapping applies a special texture map that contains an image of the scene surrounding an object to the object itself. The result approximates the appearance of a reflective surface, close enough to fool the eye, without incurring any of the complex computations involved in ray tracing.

The following image is taken from the Sphere Map Sample, which, as its name implies, uses a type of environment mapping called spherical environment mapping. For details, see Spherical Environment Mapping.

Teapot image with applied texture that simulates reflection of the surroundings

The teapot in this image appears to reflect its surroundings; this is actually a texture being applied to the object. Because environment mapping uses a texture, combined with specially computed texture coordinates, it can be performed in real-time.

This section provides information about performing two common types of environment mapping with Microsoft® Direct3D®. There are many types of environment mapping in use throughout the graphics industry, but the following topics target the two most common forms: cubic environment mapping and spherical environment mapping.

  • Cubic Environment Mapping
  • Spherical Environment Mapping

© 2002 Microsoft Corporation. All rights reserved.


Cubic Environment Mapping

Cubic environment maps—sometimes referred to as cube maps—are textures that contain image data representing the scene surrounding an object, as if the object were in the center of a cube. Each face of the cubic environment map covers a 90-degree field of view in the horizontal and vertical, and there are six faces per cube map. The orientation of the faces is given in the following illustration.

Cube with central coordinate axes perpendicular to cube faces

Each face of the cube is oriented perpendicular to the x/y, y/z, or x/z plane, in world space. The following figure shows how each plane corresponds to a face.

Faces of cube with coordinate projections on each face

Cubic environment maps are implemented as a series of texture objects. Applications can use static images for cubic environment mapping, or they can render into the faces of the cube map to perform dynamic environment mapping. This technique requires that the cube-map surfaces be valid render-target surfaces, created with the D3DUSAGE_RENDERTARGET flag set.

The faces of a cube map don't need to contain extremely detailed renderings of the surrounding scene. In most cases, environment maps are applied to curved surfaces. Given the amount of curvature used by most applications, the resulting reflective distortion makes extreme detail in the environment map wasteful in terms of memory and rendering overhead.

Mipmapped Cubic Environment Maps

Cube maps can be mipmapped. To create a mipmapped cube map, set the Levels parameter of the IDirect3DDevice9::CreateCubeTexture method to the number of levels that you want. You can envision the topography of these surfaces as shown in the following graphic.

Mipmapped cube map with n mip levels

Applications that create mipmapped cubic environment maps can access each face by calling the IDirect3DCubeTexture9::GetCubeMapSurface method. Start by setting the appropriate value from the D3DCUBEMAP_FACES enumerated type, as discussed in Creating Cubic Environment Map Surfaces. Next, select the level to retrieve by setting the IDirect3DCubeTexture9::GetCubeMapSurface level parameter to the mipmap level that you want. Remember that 0 corresponds with the top-level image.

Texture Coordinates for Cubic Environment Maps

Texture coordinates that index a cubic environment map aren't simple u, v style coordinates, as used when standard textures are applied. In fact, cubic environment maps don't use texture coordinates at all. In place of a set of texture coordinates, cubic environment maps require a 3-D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Microsoft® Direct3D® offers the D3DFVF_TEXCOORDSIZEn set of macros for this purpose. These macros accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3-D vector, you include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 macro. The following code example shows how this macro is used.

// Create a flexible vertex format descriptor for a vertex that contains
//   a position, normal, and one set of 3-D texture coordinates.

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0);

In some cases, such as diffuse light mapping, you use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you use a reflection vector. Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.

Computing a reflection vector on your own requires understanding of the position of each vertex, and of a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory because you don't need to include texture coordinates for the environment map. It also reduces bandwidth and, in the case of a TnLHAL Device, it can be significantly faster than the computations that your application can make on its own. To use this feature, in the texture stage that contains the cubic environment map, set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR member of D3DTEXTURESTAGESTATETYPE and the index of a texture coordinate set. In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL member of D3DTEXTURESTAGESTATETYPE, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture. The index is only used by the system to determine the wrapping mode for the texture.

The following code example shows how this value is used.

// The m_d3dDevice variable is a valid pointer
// to an IDirect3DDevice9 interface.

// Automatically generate texture coordinates for stage 2.
// This assumes that stage 2 is assigned a cube map.
// Use the wrap mode from the texture coordinate set at index 1.

m_d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 1);

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRS_LOCALVIEWER render state is set to TRUE, the formula used is the following:

R = 2(ExN)N-E

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRS_LOCALVIEWER render state is set to FALSE, the system uses the following formula.

R = 2NzN-I

The R and N elements in this formula are identical to the previous formula. The NZ element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRS_NORMALIZENORMALS to TRUE. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.

Additional information is contained in the following topic.

  • Creating Cubic Environment Map Surfaces

© 2002 Microsoft Corporation. All rights reserved.


Creating Cubic Environment Map Surfaces

You create a cubic environment map texture by calling the IDirect3DDevice9::CreateCubeTexture method. Cubic environment map textures must be square, with dimensions that are a power of two.

The following code example shows how your C++ application might create a simple cubic environment map.

// For this example, m_d3dDevice is a valid
//   pointer to an IDirect3DDevice9 interface.

LPDIRECT3DCUBETEXTURE9 m_pCubeMap;

m_d3dDevice->CreateCubeTexture( 256, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R8G8B8,
                                D3DPOOL_DEFAULT, &m_pCubeMap );

Accessing Cubic Environment Map Faces

You can navigate between faces of a cubic environment map by using the IDirect3DCubeTexture9::GetCubeMapSurface method.

The following code example uses IDirect3DCubeTexture9::GetCubeMapSurface to retrieve the cube-map surface used for the positive-y face (face 2).

// For this example, m_pCubeMap is a valid
// pointer to a IDirect3DCubeTexture9 interface.

LPDIRECT3DSURFACE9 pFace2;
m_pCubeMap->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_Y, 0, &pFace2);

The first parameter that IDirect3DCubeTexture9::GetCubeMapSurface accepts is a D3DCUBEMAP_FACES enumerated value that describes the attached surface that the method should retrieve. The second parameter tells Microsoft® Direct3D® which level of a mipmapped cube texture to retrieve. The third parameter accepted is the address of the IDirect3DSurface9 interface, representing the returned cube texture surface. Because this cube-map is not mipmapped, 0 is used here.

Note

After calling this method, the internal reference count on the IDirect3DSurface9 interface is increased. When you are done using this surface, be sure to call the IUnknown::Release method on this IDirect3DSurface9 interface or you will have a memory leak.

Rendering to Cubic Environment Maps

You can copy images to the individual faces of the cube map just like you would any other texture or surface object. The most important thing to do before rendering to a face is set the transformation matrices so that the camera is positioned properly and points in the proper direction for that face: forward (+z), backward (-z), left (-x), right (+x), up (+y), or down (-y).

The following C++ code example prepares and sets a view matrix according to the face being rendered.

// For this example, pCubeMap is a valid pointer to a IDirect3DCubeTexture9
// interface and d3dDevice is a valid pointer to a IDirect3DDevice9 interface.

void RenderFaces()
{
    // Save transformation matrices of the device.
    D3DXMATRIX matProjSave, matViewSave;
    d3dDevice->GetTransform( D3DTS_VIEW,       &matViewSave );
    d3dDevice->GetTransform( D3DTS_PROJECTION, &matProjSave );

    // Store the current back buffer and z-buffer.
    LPDIRECT3DSURFACE9 pBackBuffer, pZBuffer;
    d3dDevice->GetRenderTarget( &pBackBuffer );
    d3dDevice->GetDepthStencilSurface( &pZBuffer );

Remember, each face of a cubic environment map represents a 90-degree field of view. Unless your application requires a different field of view angle—for special effects, for example—take care to set the projection matrix accordingly.

This code example creates and sets a projection matrix for the most common case.

    // Use 90-degree field of view in the projection.
    D3DMATRIX matProj;
    D3DXMatrixPerspectiveFovLH( matProj, D3DX_PI/2, 1.0f, 0.5f, 1000.0f );
    d3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

    // Loop through the six faces of the cube map.
    for( DWORD i=0; i<6; i++ )
    {
        // Standard view that will be overridden below.
        D3DVECTOR vEnvEyePt = D3DVECTOR( 0.0f, 0.0f, 0.0f );
        D3DVECTOR vLookatPt, vUpVec;

        switch( i )
        {
            case D3DCUBEMAP_FACE_POSITIVE_X:
                vLookatPt = D3DVECTOR( 1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_X:
                vLookatPt = D3DVECTOR(-1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Y:
                vLookatPt = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Y:
                vLookatPt = D3DVECTOR( 0.0f,-1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
        }

         D3DMATRIX matView;
         D3DXMatrixLookAtLH( matView, vEnvEyePt, vLookatPt, vUpVec );
         d3dDevice->SetTransform( D3DTS_VIEW, &matView );

When the camera is in position and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code example, provided for completeness, outlines this task.

        //Get pointer to surface in order to render to it.
        LPDIRECT3DSURFACE9 pFace;
        pCubeMap->GetCubeMapSurface( (D3DCUBEMAP_FACES)i, 0, &pFace );
        d3dDevice->SetRenderTarget ( pFace , pZBuffer );
        pFace->Release();

        d3dDevice->BeginScene();
        // Render scene here.
        d3dDevice->EndScene();
    }

    // Change the render target back to the main back buffer.
    d3dDevice->SetRenderTarget( pBackBuffer, pZBuffer );
    pBackBuffer->Release();
    pZBuffer->;Release();

    // Restore the original transformation matrices.
    d3dDevice->SetTransform( D3DTS_VIEW,       &matViewSave );
    d3dDevice->SetTransform( D3DTS_PROJECTION, &matProjSave );
}

Note the call to the IDirect3DDevice9::SetRenderTarget method. When rendering to the cube map faces, you must assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The code sample above uses the latter approach.

© 2002 Microsoft Corporation. All rights reserved.


Spherical Environment Mapping

Spherical environment maps, or sphere maps, are special textures that contain an image of the scene surrounding an object, or the lighting effects around the object. Unlike cubic environment maps, sphere maps don't directly represent an object's surroundings. The teapot image in Environment Mapping topic shows the reflection effects you can achieve with sphere mapping.

A sphere map is a 2-D representation of the full 360-degree view of the scene surrounding of an object, as if taken through a fish-eye lens. The following illustration is the sphere map used by the Sphere Map Sample.

Sphere map of the inside of a building

Texture Coordinates for Spherical Environment Maps

The texture coordinates that you specify for each vertex receiving an environment mapping should address the texture as a function of the reflective distortion created by the curvature of the surface. Applications must compute these texture coordinates for each vertex to achieve the desired effect. One simple and effective way to generate texture coordinates uses the vertex normal as input. Although several methods exist, the following formula is common among applications that perform environment mapping with sphere maps.

Formula for computing texture coordinates for a sphere map

In these formulas, u and v are the texture coordinates being computed, and NX and NY are the x and y components of the camera-space vertex normal. The formula is simple but effective. If the normal has a positive x component, the normal points to the right, and the u coordinate is adjusted to address the texture appropriately. Likewise for the v coordinate: positive y indicates that the normal points up. The opposite is true for negative values in each component.

If the normal points directly at the camera, the resulting coordinates should receive no distortion. The +0.5 bias to both coordinates places the point of zero-distortion at the center of the sphere map, and a vertex normal of (0, 0, z) addresses this point. This formula doesn't account for the z component of the normal, but applications that use the formula can optimize computations by skipping vertices with a normal that has a positive z element. This works for flat-shaded objects because, in camera space, if the normal points away from the camera (positive z), the vertex is culled when the object is rendered. For Gouraud-shaded objects, a normal can point away from the camera (positive x), and the triangle containing the vertex can still be visible. If you don't compute u and v for this vertex, the face might still be used, resulting in unexpected behavior.

Applying Spherical Environment Maps

You apply an environment map to objects in the same manner as for any other texture, by setting the texture to the appropriate texture stage with the IDirect3DDevice9::SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the IDirect3DDevice9 interface returned when you created the texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.

© 2002 Microsoft Corporation. All rights reserved.


Antialiasing

Antialiasing is a technique you can use to reduce the appearance of stair-step pixels when drawing any line that is not exactly horizontal or vertical. In three-dimensional scenes, this artifact is most noticeable on the boundaries between polygons of different colors. Antialiasing effectively blends the pixels at these boundaries to produce a more natural look to the scene.

Microsoft® Direct3D® supports two antialiasing techniques: edge antialiasing and full-surface antialiasing. Which technique is best for your application depends on your requirements for performance and visual fidelity.

  • Full-Scene Antialiasing

The section below shows how to use special effects to simulate or use antialiasing.

  • Motion Blur

© 2002 Microsoft Corporation. All rights reserved.


Full-Scene Antialiasing

Full-scene antialiasing refers to blurring the edges of each polygon in the scene as it is rasterized in a single pass; no second pass is required. Full-scene antialiasing, when supported, affects only triangles and groups of triangles. Lines cannot be antialiased by using Microsoft® Direct3D® services. Full-scene antialiasing is done in Direct3D by using multisampling on each pixel. When multisampling is enabled, all subsamples of a pixel are updated in one pass but when used for other effects that involve multiple rendering passes, the application can specify that only some subsamples are to be affected by a given rendering pass. This latter approach enables simulation of motion blur, depth-of-field focus effects, reflection blur, and so on.

In both cases, the various samples recorded for each pixel are blended together and output to the screen. This enables the improved image quality of antialiasing or other effects.

Before creating a device with the IDirect3D9::CreateDevice method, you need to determine if full-scene antialiasing is supported. Do this by calling the IDirect3D9::CheckDeviceMultiSampleType method as shown in the code example below.

/*
 * The code below assumes that pD3D is a valid pointer
 *   to a IDirect3D9 interface.
 */

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT,
                     D3DDEVTYPE_HAL , D3DFMT_R8G8B8, FALSE,
                     D3DMULTISAMPLE_2_SAMPLES, NULL ) ) )
// Full-scene antialiasing is supported. Enable it here.

The first parameter that IDirect3D9::CheckDeviceMultiSampleType accepts is an ordinal number that denotes the display adapter to query. This sample uses D3DADAPTER_DEFAULT to specify the primary display adapter. The second parameter is a value from the D3DDEVTYPE enumerated type, specifying the device type. The third parameter specifies the format of the surface. The fourth parameter tells Direct3D whether to inquire about full-windowed multisampling (TRUE) or full-scene antialiasing (FALSE). This sample uses FALSE to tell Direct3D that it is inquiring about full-scene antialiasing. The last parameter specifies the multisampling technique that you want to test. Use a value from the D3DMULTISAMPLE_TYPE enumerated type. This sample tests to see if two levels of multisampling are supported.

If the device supports the level of multisampling that you want to use, the next step is to set the presentation parameters by filling in the appropriate members of the D3DPRESENT_PARAMETERS structure to create a multisample rendering surface. After that, you can create the device. The sample code below shows how to set up a device with a multisampling render surface.

/*
 * The example below assumes that pD3D is a valid pointer
 * to a IDirect3D9 interface, d3dDevice is a pointer to a
 * IDirect3DDevice9 interface, and hWnd is a valid handle
 * to a window.
 */

D3DPRESENT_PARAMETER d3dPP
ZeroMemory( &d3dPP, sizeof( d3dPP ) );
d3dPP.Windowed        = FALSE
d3dPP.SwapEffect      = D3DSWAPEFFECT_DISCARD;
d3dPP.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                   D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                   &d3dpp, &d3dDevice)

To use multisampling, the SwapEffect member of D3DPRESENT_PARAMETER must be set to D3DSWAPEFFECT_DISCARD.

The last step is to enable multisampling antialiasing by calling the IDirect3DDevice9::SetRenderState method and setting the D3DRS_MULTISAMPLEANTIALIAS to TRUE. After setting this value to TRUE, any rendering that you do will have multisampling applied to it. You might want to enable and disable multisampling, depending on what you are rendering.

© 2002 Microsoft Corporation. All rights reserved.


Motion Blur

You can enhance the perceived speed of an object in a 3-D scene by blurring the object and leaving a blurred trail of object images behind the object. Microsoft® Direct3D® applications accomplish this by rendering the object multiple times per frame.

Recall that Direct3D applications typically render scenes into an off-screen buffer. The contents of the buffer are displayed on the screen when the application calls the IDirect3DDevice9::Present method. Your Direct3D application can render the object multiple times into a scene before it displays the frame on the screen.

Programmatically, your application makes multiple calls to a DrawPrimitive method, repeatedly passing the same 3-D object. Before each call, the position of the object is updated slightly, producing a series of blurred object images on the target rendering surface. If the object has one or more textures, your application can enhance the motion blur effect by rendering the first image of the object with all its textures nearly transparent. Each time the object renders, the transparency of the object's texture decreases. When your application renders the object in its final position, it should render the object's textures without transparency. The exception is if you're adding motion blur to another effect that requires texture transparency. In any case, the initial image of the object in the frame should be the most transparent. The final image should be the least transparent.

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the IDirect3DDevice9::Present method to display the frame on the screen.

If your application is simulating the effect of the user moving through a scene at high speed, it can add motion blur to the entire scene. In this case, your application renders the entire scene multiple times per frame. Each time the scene renders, your application must move the viewpoint slightly. If the scene is highly complex, the user may see a visible performance degradation as acceleration is increased because of the increasing number of scene renderings per frame.

© 2002 Microsoft Corporation. All rights reserved.


Multiple Render Target

Many implementations support a less restrictive form of Multiple Render Target. The biggest relaxation is the ability to have multiple render targets that can be created independently. These render targets must be of identical dimensions but can have different formats. The pipeline supports a single render target that can be set using IDirect3DDevice9::SetRenderTarget. This has been extended to allow multiple render targets to be simultaneously present in the device. A new cap expresses this ability.

Multiple render targets have the following restrictions:

  • Some implementations might require all surfaces of multiple render targets to have the same bit depth but allow different formats. Implementations that do not have this limitation indicate so by setting the cap D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS.

    If the D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS cap is set, the device can support all mixed formats regardless of format type or bit depth. If the D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS cap is not set, the device can support mixed format types for surfaces containing the same bit depth above 16 bits. The mixing of different format types for 16-bit depth surfaces is undefined.

  • All surfaces of a multiple render target should have the same width and height.
  • Some implementations cannot perform post-pixel shader operations on multiple render targets, including: no dithering, alpha test, no fogging, no blending or masking, except the z-test and stencil test. Devices that can support post-pixel shader operations set the cap bit to D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING. When the D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING cap is not set, the device is expected to turn off all post-pixel shader blending operations, regardless of what the specific surface IDirect3D9::CheckDeviceFormat with USAGE_QUERY_POSTPIXELSHADER_BLENDING is.

    When the D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING cap is set, you must first consult the IDirect3D9::CheckDeviceFormat with the USAGE_QUERY_POSTPIXELSHADER_BLENDING result for the specific surface format. If false, no post-pixel shader blending operations will be available for that specific surface format. If true, the device is expected to apply the same state to all simultaneous render targets as follows:

    • Alpha blend: The color value in oCi is blended with the ith render target.
    • Alpha test: Comparison will happen with oC0. If the comparison fails, the pixel test is terminated for all render targets.
    • Fog: Render target 0 will get fogged. Other render targets are undefined. Implementations can choose to fog them all using the same state.
    • Dithering: Undefined.
  • No antialiasing is supported.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can, have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements the device is capable of.
  • IDirect3DDevice9::Clear clears all surfaces of the multiple render target.
Note In the past, this application programming interface (API) was used to set the depth stencil as well. In Microsoft® DirectX® 9.0 however, this API has been split up as documented in the IDirect3DDevice9::SetRenderTarget and IDirect3DDevice9::SetDepthStencilSurface sections.

New hardware caps:

D3DCAPS9.NumSimultaneousRTs
// The value is 1 for all hardware except those that
//   can support this feature. It is never 0.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS - True if the hardware can support it
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING - True if the hardware can support it

© 2002 Microsoft Corporation. All rights reserved.


Multielement Texture

Traditional textures are considered to be single-element textures. Multielement textures enable applications to write out to multiple elements of a texture, simultaneously, from the pixel shader. The result in the next rendering pass is that an application can use one or more of the elements as a single-element texture—that is, as inputs to the pixel shader. These additional elements can be thought of as a temporary store for intermediate results that will be used in a later pass by the application. The first generation of hardware that exposes this feature has the following restrictions.

  • All multielement texture surfaces will be allocated automatically. This limitation is addressed by treating this as a new type of surface format with multiple RGBA channels interleaved.
  • All elements of the multielement texture can have the same bit depth. This limitation is expressed by the name of the new surface formats.
  • Multielement texture cannot be the primary/displayable. In other words, it must be off-screen only. This limitation is expressed by the surface-format enumeration.
  • No dithering, alpha test, fogging, blending, raster-op, or masking is allowed. No post-pixel shader processing is done, except the z-test and stencil test.
  • It cannot be a mipmap. Creation of the mip chain will fail.
  • The same element cannot be set as a texture at the same time it is a render target. However, different elements of the same multielement texture surface can simultaneously be textures and render targets.
  • No antialiasing is supported.
  • Multielement texture surfaces, when used as a texture, cannot be filtered. This limitation can be verified using IDirect3D9::CheckDeviceFormat.
  • Multielement texture surfaces cannot be locked.
  • Multiple multielement texture surfaces can be used simultaneously, by assigning each to various stages, like normal textures.
  • Multielement texture surfaces support gamma 2.2 -> 1.0 conversion on read, just like other texture formats.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can, have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements the device is capable of.
  • IDirect3DDevice9::Clear clears all elements of the multielement texture, set as the render target.

The usage is documented in the following list.

  • Applications discover support for this feature by checking for the availability of multielement texture formats.
  • The application creates these surfaces by calling IDirect3DDevice9::CreateTexture.
  • The application sets the surface as a render target using the IDirect3DDevice9::SetRenderTarget call. The pixel shader outputs to the surfaces using the mov instruction.
  • IDirect3DDevice9::SetTexture is called to set a multielement texture surface to a particular stage. Like other textures, the same surface is allowed to be set to multiple stages at once.
  • IDirect3DDevice9::SetSamplerState is called to set D3DSAMP_ELEMENTINDEX to the appropriate element number in the multielement texture that the sampler samples from. Default value for this state is 0, which means non-multielement textures will work. Setting this state to an inappropriate number results in an undefined behavior. For example, if the multielement texture is only two elements wide but the sampler is asked to sample from the fourth element.

API Changes

The following are the proposed application programming interface (API) changes to support this feature. New surface formats like the ones shown here express the interleaved nature of the format.

A new interleaved surface format:

D3DFMT_MULTI2_ARGB8    = MAKEFOURCC('M','E','T','1'),

A new sampler state to indicate which element to pick up:

D3DSAMP_ELEMENTINDEX

New render states:

D3DRS_COLORWRITEENABLE1
D3DRS_COLORWRITEENABLE2
D3DRS_COLORWRITEENABLE3

D3DRS_COLORWRITEENABLE applies to render target (or element) zero.

New hardware caps:

D3DPMISCCAPS_INDEPENDENTWRITEMASKS // True if they can support it

© 2002 Microsoft Corporation. All rights reserved.


Frame Buffer

  • Fog Types
  • Alpha Examples
  • Gamma

© 2002 Microsoft Corporation. All rights reserved.


Fog Types

There are two ways to add fog to a scene: with pixel fog and/or vertex fog. The following topics illustrate the formulas used in fog equations, as well as implementing vertex and pixel fog. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Vertex Fog
  • Pixel Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.

© 2002 Microsoft Corporation. All rights reserved.


Fog Formulas

C++ applications can control how fog affects the color of objects in a scene by changing how Microsoft® Direct3D® computes fog effects over distance. The D3DFOGMODE enumerated type contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets.

Linear Fog

This is set with D3DFOG_LINEAR.

Direct3D linear fog equation

where

  • start is the distance at which fog effects begin.
  • end is the distance at which fog effects no longer increase.
  • d represents depth, or the distance from the viewpoint. For range based fog, the value for d is the distance between the camera position and a vertex. For non-range based fog, the value for d is the absolute value of the Z-coordinate in camera space.

Exponential Fog

Linear and exponential formulas are supported for both pixel fog and vertex fog.

This is set with D3DFOG_EXP.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms (approximately 2.71828).
  • density is an arbitrary fog density that can range from 0.0 to 1.0.
  • d represents depth, or the distance from the viewpoint, as stated earlier.

This is set with D3DFOG_EXP2.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms as stated above.
  • density is an arbitrary fog density that can range from 0.0 to 1.0 as stated above.
  • d represents depth, or the distance from the viewpoint, as stated above.
Note The system stores the fog factor in the alpha component of the specular color for a vertex. If your application performs its own transformation and lighting, you can insert fog factor values manually, to be applied by the system during rendering.

The following illustration graphs these formulas, using common values as in the formula parameters.

D3DFOG_LINEAR is 1.0 at start and 0.0 at end. It is not measured relative to the near or far planes.

When Direct3D calculates fog effects, it uses the fog factor from one of the preceding equations in a blending formula, shown here.

This formula effectively scales the color of the current polygon C by the fog factor f, and adds the product to the fog color C, scaled by the bitwise inverse of the fog factor. The resulting color value is a blend of the fog color and the original color, as a factor of distance. The formula applies to all devices supported in Microsoft DirectX® 7.0 and later. For the legacy ramp device, the fog factor scales the diffuse and specular color components, clamped to the range of 0.0 and 1.0, inclusive. The fog factor typically starts at 1.0 for the near plane and decreases to 0.0 at the far plane.

© 2002 Microsoft Corporation. All rights reserved.


Fog Parameters

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all the fog formulas introduced in Fog Formulas. The D3DFOGMODE enumerated type defines constants that you can use to identify the fog formula you want Microsoft® Direct3D® to use. The D3DRS_FOGTABLEMODE render state controls the fog mode that Direct3D uses for pixel fog, and the D3DRS_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRS_FOGSTART and D3DRS_FOGEND render states. How the system interprets these values depends on the type of fog your application uses—pixel or vertex fog—and, when using pixel fog, if z-based or w-based depth is being used. The following table summarizes fog types and their start and end units.

Fog type | Fog start/end units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRS_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is essentially a weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRS_FOGCOLOR device render state. For more information, see Fog Color and Fog Blending.

© 2002 Microsoft Corporation. All rights reserved.


Fog Blending

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas. The D3DRS_FOGENABLE render state controls fog blending. Set this render state to TRUE to enable fog blending as shown in the following example code. The default is FALSE.

// For this example, g_pDevice is a valid pointer
// to an IDirect3DDevice9 interface.
HRESULT hr;
hr = g_pDevice->SetRenderState(
                     D3DRS_FOGENABLE,
                     TRUE);
if FAILED(hr)
    return hr;

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.

© 2002 Microsoft Corporation. All rights reserved.


Fog Color

Fog color for both pixel and vertex fog is set through the D3DRS_FOGCOLOR render state. The render state values can be any RGB color, specified as an RGBA color. The alpha component is ignored.

The following C++ example sets the fog color to white.

/* For this example, the d3dDevice variable is
 * a valid pointer to an IDirect3DDevice9 interface.
 */
HRESULT hr;
hr = d3dDevice->SetRenderState(
                    D3DRS_FOGCOLOR,
                    0x00FFFFFF); // Highest 8 bits are not used.
if(FAILED(hr))
    return hr;

Fog is applied differently by the fixed function pipeline and the programmable pipeline.

  1. If the driver supports D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, v1.w (in the pixel shader) equals the value set in fog renderstate.
    • If the programmable pipeline is used, then v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.
  2. If the driver does NOT support D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, then v1.w (in the pixel shader) equals value set in fog renderstate.
    • If oFog is explicitly written in a vertex shader, v1.w (in the pixel shader) equals oFog, clamped between 0 and 1.
    • If neither of the above two cases applies, v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.

For more information, see D3DPMISCCAPS.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Fog

When the system performs vertex fogging, it applies fog calculations at each vertex in a polygon, and then interpolates the results across the face of the polygon during rasterization. Vertex fog effects are computed by the Microsoft® Direct3D® lighting and transformation engine. For more information, see Fog Parameters.

If your application does not use Direct3D for transformation and lighting, the application must perform fog calculations. In this case, place the fog factor that is computed in the alpha component of the specular color for each vertex. You are free to use whatever formulas you want—range-based, volumetric, or otherwise. Direct3D uses the supplied fog factor to interpolate across the face of each polygon. Applications that perform their own transformation and lighting must also perform their own vertex fog calculations. As a result, such an application need only enable fog blending and set the fog color through the associated render states, as described in Fog Blending and Fog Color.

Note When using a vertex shader, you must use vertex fog. This is accomplished by using the vertex shader to write the per-vertex fog intensity to the oFog register. After the pixel shader completes, the oFog data is used to linearly interpolate with the fog color. This intensity is not available in a pixel shader.

Range-Based Fog

Note Direct3D uses range-based fog calculations only when using vertex fog with the Direct3D transformation and lighting engine. This is because pixel fog is implemented in the device driver, and no hardware currently exists to support per-pixel range-based fog. If your application performs its own transformation and lighting, it must perform its own fog calculations, range-based or otherwise.

Sometimes, using fog can introduce graphic artifacts that cause objects to be blended with the fog color in nonintuitive ways. For example, imagine a scene in which there are two visible objects: one distant enough to be affected by fog, and the other near enough to be unaffected. If the viewing area rotates in place, the apparent fog effects can change, even if the objects are stationary. The following illustration shows a top-down view of such a situation.

Effects on fog of changing the viewpoint

Range-based fog is another, more accurate, way to determine the fog effects. In range-based fog, Direct3D uses the actual distance from the viewpoint to a vertex for its fog calculations. Direct3D increases the effect of fog as the distance between the two points increases, rather than the depth of the vertex within in the scene, thereby avoiding rotational artifacts.

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE value in the RasterCaps member of D3DCAPS9 when you call the IDirect3DDevice9::GetDeviceCaps method. To enable range-based fog, set the D3DRS_RANGEFOGENABLE render state to TRUE.

Range-based fog is computed by Direct3D during transformation and lighting. Applications that don't use the Direct3D transformation and lighting engine must also perform their own vertex fog calculations. In this case, provide the range-based fog factor in the alpha component of the specular component for each vertex.

Using Vertex Fog

Use the following steps to enable vertex fog in your application.

  1. Enable fog blending by setting D3DRS_FOGENABLE to TRUE.
  2. Set the fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRS_FOGVERTEXMODE render state to a member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following example, written in C++, shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupVertexFog(DWORD Color, DWORD Mode, BOOL UseRange, FLOAT Density)
{
    float Start = 0.5f,    // Linear fog distances
          End   = 0.8f;

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if(D3DFOG_LINEAR == Mode)
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

    // Enable range-based fog if desired (only supported for
    //   vertex fog). For this example, it is assumed that UseRange
    //   is set to a nonzero value only if the driver exposes the
    //   D3DPRASTERCAPS_FOGRANGE capability.
    // Note: This is slightly more performance intensive
    //   than non-range-based fog.
    if(UseRange)
        g_pDevice->SetRenderState(D3DRS_RANGEFOGENABLE, TRUE);
}

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method only accepts DWORD values in the second parameter. This example successfully provides the floating-point values to these methods without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Fog

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver. This is different from vertex fog, which is computed by the pipeline during transformation and lighting calculations. Pixel fog is sometimes called table fog because some drivers use a precalculated lookup table to determine the fog factor, using the depth of each pixel to apply in blending computations. It can be applied using any fog formula identified by members of the D3DFOGMODE enumerated type. The implementations of these formulas are driver-specific. If a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Eye-Relative vs. Z-Based Depth

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values in a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogeneous coordinate set. Microsoft® Direct3D® takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w. If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the RasterCaps member of the D3DCAPS9 structure when you call the IDirect3DDevice9::GetDeviceCaps method. With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system automatically uses eye-relative depth rather than z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. You set the projection matrix by calling the IDirect3DDevice9::SetTransform method, using the D3DTS_PROJECTION value and passing a D3DMATRIX structure that represents the desired matrix. If the projection matrix isn't compliant with this requirement, fog effects are not applied properly. For details about producing a compliant matrix, see A W-Friendly Projection Matrix. The perspective projection matrix provided in What Is the Projection Transformation? produces a compliant projection matrix.

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, an application must set a compliant projection matrix to receive the desired w-based features, even if it does not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix. If the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.

Using Pixel Fog

Use the following steps to enable pixel fog in your application.

  1. Enable fog blending by setting the D3DRS_FOGENABLE render state to TRUE.
  2. Set the desired fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the fog formula to use by setting the D3DRS_FOGTABLEMODE render state to the corresponding member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupPixelFog(DWORD Color, DWORD Mode)
{
    float Start   = 0.5f;    // For linear mode
    float End     = 0.8f;
    float Density = 0.66f;   // For exponential modes

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if( Mode == D3DFOG_LINEAR )
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method accepts only DWORD values in the second parameter. The preceding example provides the floating-point values to IDirect3DDevice9::SetRenderState without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.

© 2002 Microsoft Corporation. All rights reserved.


Alpha Examples

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions

© 2002 Microsoft Corporation. All rights reserved.


Billboarding

When creating 3-D scenes, an application can sometimes gain performance advantages by rendering 2-D objects in a way that makes them appear to be 3-D objects. This is the basic idea behind the technique of billboarding.

A billboard in the normal sense of the word is a sign along a roadway. Microsoft® Direct3D® applications can create and render this type of billboard by defining a rectangular solid and applying a texture to it. Billboarding in the more specialized sense of 3-D graphics is an extension of this. The goal is to make 2-D objects appear to be 3-D. The technique is to apply a texture that contains the object's image to a rectangular primitive. The primitive is rotated so that it always faces the user. It doesn't matter if the object's image is not rectangular. Portions of the billboard can be made transparent, so the parts of the billboard image that you don't want seen are not visible.

Many games employ billboarding for animated sprites. For instance, when the user is moving through a 3-D maze, he or she may see weapons or rewards that can be picked up. These are typically 2-D images textured on a rectangular primitive. Billboarding is often used in games to render images of trees, bushes, and clouds.

When an image is applied to a billboard, the rectangular primitive must first be rotated so that the resulting image faces the user. Your application must then translate it into position. The application can then apply a texture to the primitive.

Billboarding works best for symmetrical objects, especially objects that are symmetrical along the vertical axis. It also requires that the altitude of the viewpoint doesn't increase too much. If the user is allowed to view the billboarded from above, it becomes readily apparent that the object is 2-D rather than 3-D.

© 2002 Microsoft Corporation. All rights reserved.


Clouds, Smoke, and Vapor Trails

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique. See Billboarding. By rotating the billboard on two axes instead of one, your application can enable the user to view a billboard from any angle. Typically, an application rotates the billboard on the horizontal and vertical axes.

To make a simple cloud, your application can rotate a rectangular primitive on one or two axes so that the primitive faces the user. A cloud-like texture can then be applied to the primitive with transparency. For details on applying transparent textures to primitives, see Texture Blending. You can animate the cloud by applying a series of textures over time.

An application can create more complex clouds by forming them from a group of primitives. Each part of the cloud is a rectangular primitive. The primitives can be moved independently over time to give the appearance of a dynamic mist. This concept is illustrated in the following figure.

Formation from a group of primitives

The appearance of smoke is displayed in a manner similar to clouds. It typically requires multiple billboards, like complex clouds. Smoke usually billows and rises over time, so the billboards that make up the smoke plume need to move accordingly. You may need to add more billboards as the plume rises and disperses.

A vapor trail is a smoke plume that doesn't rise. However, like a smoke plume, it disperses over time. The following figure illustrates the technique of using billboards to simulate a vapor trail.

© 2002 Microsoft Corporation. All rights reserved.


Fire, Flares, and Explosions

You can use Microsoft® Direct3D® to simulate natural phenomena involving energy releases. For instance, an application can generate the appearance of fire by applying flame-like textures to a set of billboards. This is especially effective if the application uses a sequence of fire textures to animate the flames on each billboard in the fire. Varying the speed of the animation playback from billboard to billboard increases the appearance of real flames. The semblance of intermingled 3-D flames can be achieved by layering the billboards and the textures on the billboards.

You can simulate flares and flashes by applying successively brighter light maps to all primitives in a scene. Although this is a computationally high-overhead technique, it allows your application to simulate a localized flare or flash. That is, the portion of the scene where the flare or flash originates can brighten first.

Another technique is to position a billboard in front of the scene so that the entire render target area is covered. The application applies successively whiter textures to the billboard and decreases the transparency over time. The entire scene fades to white as time passes. This is a low overhead method of creating a flare. However, using this technique, it can be difficult to generate the appearance of a bright flash from a single point light source.

Explosions can be displayed in a 3-D scene procedure similar to those used for fire, flashes, and flares. For instance, your application might use a billboard to display a shock wave and rising plume of smoke when the explosion occurs. At the same time, your application can use a set of billboards to simulate flames. In addition, it can position a single billboard in front of the scene to add a flare of light to the entire scene.

Energy beams can be simulated using billboards. Your application can also display them using primitives that are defined as line lists or line strips. For details, see Line Lists and Line Strips.

Your application can create force fields using billboards or primitives defined as triangle lists. To create a force field from triangle lists, define a set of disjoint triangles in a triangle list equally spaced over the region covered by the force field. The gaps between the triangles allow the user to see the scene behind the triangles, as you might expect when looking at a force field. Apply a texture to the triangle list that gives the triangles the appearance of glowing with energy. For further information, see Triangle Lists.

© 2002 Microsoft Corporation. All rights reserved.


Gamma

Texture content is often stored in sRGB format. Details of this format can be found at http://www.srgb.com World Wide Web link. Traditionally, pixel pipelines assumed the colors to be linear so blending operations were performed in linear space. However, since sRGB content is gamma corrected, blending operations in linear space will produce incorrect results. Video cards can now fix this problem by undoing the gamma correction when they read any sRGB content, and convert pixel data back to the sRGB format when writing out pixels. In this case, all operations inside the pixel pipeline are performed in the linear space.

Gamma Correction

Microsoft® DirectX® 9.0 can:

  • Indicate whether a texture is gamma 2.2 corrected or not (sRGB or not). The driver will either convert to a linear gamma for blending operations at SetTexture time, or the sampler will convert it to linear data at lookup time.
  • Indicate whether the pixel pipeline should gamma correct back to sRGB space when writing out to the render target.

All other colors (clear color, material color, vertex color, etc.) are assumed to be in linear space. Applications can gamma-correct the colors written into the frame buffer using pixel shader instructions. The linearization should be applied only to the RGB channels and not to the alpha channel.

Not all surface formats can be linearized. Only the formats that pass IDirect3D9::CheckDeviceFormat with D3DUSAGE_SRGBREAD can be linearized. The sampler state D3DSAMP_SRGBTEXTURE is ignored for the rest. Only unsigned texture formats are expected to support this conversion. Unsigned texture formats include only R, G, B, and L components. If the alpha channel is present, it is ignored. If mixed formats support sRGB linearization, only the unsigned channels are affected. Ideally, hardware should perform the linearization before filtering but in DirectX 9.0, hardware is allowed to perform the linearization after filtering.

Not all surface formats can be written in sRGB space. Only the formats that pass the IDirect3D9::CheckDeviceFormat with the usage flag D3DUSAGE_SRGBWRITE can be linearized. The render state D3DRS_SRGBWRITEENABLE is ignored for the rest. Eight bits per channel RGB unsigned formats are expected to expose this ability.

Ideally, hardware should perform the frame buffer blending operations in the linear space, but hardware is allowed to perform it after the pixel shader but before the frame buffer blender. This means that the frame buffer blending operations that take place in sRGB space will produce incorrect results. D3DRS_SRGBWRITEENABLE is honored while performing a clear of the render target. For hardware that supports Multiple Render Target or Multielement Texture, only the first render target or element is written.

API Changes

// New sampler state (DWORD)
// If this is nonzero, the texture is linearized on lookup.
D3DSAMP_SRGBTEXTURE       // Default FALSE

// New render state (DWORD)
D3DRS_SRGBWRITEENABLE     // Default FALSE

// New usage flags
D3DUSAGE_SRGBWRITE,
D3DUSAGE_SRGBREAD

Windowed Swap Chains

It is valuable for applications to keep the back buffers of their swap chains in linear space in order to enable correct blending operations. Since the desktop is typically not in linear space, a gamma correction is required before the contents of the back buffer can be presented. The application can effect this correction itself by allocating an additional buffer and performing its own correcting copy from the linear buffer to the back buffer. This necessitates an extra copy which can be avoided if the driver performs gamma correction as part of the presentation blit.

A new flag, D3DPRESENT_LINEAR_CONTENT, is available for IDirect3DSwapChain9::Present. If this flag is set:

  • The content of the back buffer to be presented is assumed to be in the linear color space. The presentation will implicitly convert from linear space to sRGB/gamma 2.2. This is the only conversion that is supported.
  • Because this flag represents a property of the content of the back buffer, the flag can be specified during a present call. In other words, an application can present linear content in one frame, and then switch to corrected content in the next.
  • This flag is ignored when the swap chain is full screen. (Note that this flag is available only on the explicit swap chain version of Present. Present method does not take a flags parameter.)
  • This flag is always accepted, but will only take effect when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION.
  • The only back buffer format supported is X8R8G8B8.

© 2002 Microsoft Corporation. All rights reserved.


Effects

Microsoft® Direct3D® provides features for creating complex and visually realistic 3-D scenes. Effects, for example, are a collection of rendering techniques that can be used by a variety of hardware devices. An effect file helps you write an application that takes full advantage of the rendering capabilities of the hardware on which the application runs.

Effects contain one or more techniques, and each technique contains one or more passes. Because effect files are text-based, they can be changed without recompiling the source application. This enables you to program games that make optimum use of video card functionality. Effect files also make it easy to upgrade an existing game to run on newer video cards as additional features are developed.

For more information about effect files, see Effect Reference.

Assembly Language Effects

Examples creating assembly language effects are shown in these two sections.

  • Create an Effect
  • Multiple Techniques
  • Getting and Setting Effect Values
  • Assembly Language Effects

Here is an example from the Microsoft DirectX® Meltdown 2001 conference, Programmable Shader Workshop.

  • Exercise 1 - 1a. Fixed Function Diffuse Lighting and 1b. Vertex Shader Diffuse Lighting.

High Level Language Effects

Effects can also be created using a high-level language. If you want to write shaders in a C-like language, see High-Level Shader Language.

  • High-Level Language Effects

© 2002 Microsoft Corporation. All rights reserved.


Create an Effect

This example uses an effect file to apply a texture map to an object. The example shows the contents of the effect file as well as the code required in the application to load and run the file.

To create an effect:

  • Create the Effect File
  • Load the Effect File
  • Render the Effect

Create the Effect File

// Step 1: Create the effect file.
// This effect file maps a 3-D texture map onto the object.
// This code needs to be in a file named "effects.fx"

texture DiffuseTexture;

technique T0
{
    pass P0
    {
        pixelshader  = NULL;
        fvf          = XYZ | Normal | Diffuse | Tex1;
        vertexshader = NULL;

        Lighting     = False;
        CullMode     = None;

        texture[0]   = < DiffuseTexture >;
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = texture;
        ColorOp[1]   = Disable;
    }
}

Load the Effect File

{
    HRESULT hr;
    TCHAR sz[512];
    DXUtil_FindMediaFileCb(sz, sizeof(sz), _T("effect.fx"));
    LPD3DXEFFECT l_pEffect;

    if(FAILED(hr = D3DXCreateEffectFromFile(m_pd3dDevice, sz,
                    NULL, NULL, 0, NULL, &l_pEffect, NULL )))
        return hr;

    D3DXHANDLE hTechnique;
    if(FAILED(hr = FindNextValidTechnique(NULL, &hTechnique)))
        return hr;

    m_pEffect->SetTechnique(hTechnique);
    m_pEffect->SetTexture("DiffuseTexture", m_pTexture0);

}

When the effect file is created, ID3DXEffect::FindNextValidTechnique returns a technique that has been validated on the hardware.

Render the Effect

{
    HRESULT hr;
    UINT uPasses;

    if(FAILED(hr = m_pd3dDevice->SetStreamSource(0, m_pVB, 0,
                     sizeof(CUSTOMVERTEX_POS_NORM_COLOR1_TEX1))))
        return hr;

    m_pEffect->Begin(&uPasses, 0 );
    // The 0 specifies that ID3DXEffect::Begin and ID3DXEffect::End will
    //   save and restore all state modified by the effect.

    for(UINT uPass = 0; uPass < uPasses; uPass++)
    {
        // Set the state for a particular pass in a technique.
        m_pEffect->Pass(uPass);
        m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0,
                                     dwNumSphereVerts - 2);
    }

    m_pEffect->End();
}

© 2002 Microsoft Corporation. All rights reserved.


Multiple Techniques

An effect file defines the techniques used. The basic layout of an effect file starts with one or more declarations and then defines each technique for that effect. This sample shows a basic effect file that contains two textures and two techniques.

Example

This effect file allows a device that doesn't support single pass rendering for two textures to use multiple passes to render the textures.

// Declare two textures.
texture tex0;        // First texture
texture tex1;        // Second texture

// Technique 't0' will render the scene in one pass.  The color
//   for each pixel is calculated to be tex0 + tex1.  Because it uses
//   two textures at once, it will work only on cards that support
//   multitexture.

technique t0
{
    pass p0
    {
        Texture[0]   = (tex0);
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;

        Texture[1]   = (tex1);
        ColorOp[1]   = Add;
        ColorArg1[1] = Texture;
        ColorArg2[1] = Current;

        ColorOp[2]   = Disable;
    }
}

// Technique 't1' renders the scene in two passes.  The first pass sets
//   each pixel to the color of tex0.  The second pass adds in the color
//   of tex1.  The result should end up looking identical to the first
//   technique.  However, this technique can be used on cards that do not
//   support multitexture.

technique t1
{
    pass p0
    {
        AlphaBlendEnable = False;

        Texture[0]   = (tex0);

        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        ColorOp[1]   = Disable;
    }

    pass p1
    {
        AlphaBlendEnable = True;
        SrcBlend    = One;
        DestBlend   = One;

        Texture[0]  = (tex1);

        ColorOp[0]  = SelectArg1;
        ColorArg[0] = Texture;
        ColorOp[1]  = Disable;
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Getting and Setting Effect Values

Getting and setting effect values can be accomplished with any of the type specific methods in ID3DXBaseEffect, or just two generic methods: ID3DXBaseEffect::GetValue and ID3DXBaseEffect::SetValue. This includes any arbitrary parameter or annotation, simple types, structs, arrays, strings, shaders, and textures. These two methods can be used in place of nearly all Get xxx and Set xxx calls in ID3DXBaseEffect.

In all of these examples, handles could be used in place of the strings shown here.

Getting Arbitrary Values

Given the following effect file parameters:

float fValue;
float4 vecLight;
float4x4 mWorld;
float3x2 m3x2matrix;
string xFile = "bigship1.x";
texture tex1;
vertexshader vsMyShader;
vertexshader vsArray[4] = {
    /* initialize 4 vertex shaders here ... */
};

struct {
    float fArray[4];
    float fSingle;
} myStruct, myStructArray[2];

// and a pointer to an effect interface
LPD3DXEFFECT pEffect;
// which needs to be initialized before using it.

Get a single floating point value.

FLOAT f;
pEffect->GetValue("fValue", (void*)&f, D3DX_DEFAULT);

Get a string.

LPCSTR szString;
pEffect->GetValue("xFile", (void*)&szString, sizeof(LPCSTR));

Get a vertex shader. Shaders are handled in exactly the same way as textures. They must be released when no longer needed.

LPDIRECT3DVERTEXSHADER9 pVShader;
pEffect->GetValue("vsMyShader", (void*)&pVShader, sizeof(LPDIRECT3DVERTEXSHADER9));
SAFE_RELEASE(pVShader);

Get a vector:

D3DXVECTOR4 vecLight;
pEffect->GetValue("vecLight", (void*)(FLOAT*)vecLight, sizeof(D3DXVECTOR4));

Get a matrix:

D3DXMATRIX matWorld;
pEffect->GetValue("mWorld", (void*)(FLOAT*)matWorld, sizeof(D3DXMATRIX));

Get a non-4x4 matrix. Matrices are stored without padding, so a 3x2 matrix is six floats.

FLOAT m3x2matrix[3 * 2];
pEffect->GetValue("m3x2matrix", (void*)m3x2matrix, desc.Bytes);

If you have a D3DXPARAMETER_DESC "desc" that has been filled in by GetParameterDesc, you can also pass in desc.Bytes.

Get a string. You are getting just a pointer to a const string. The size is always sizeof(LPCSTR), and you should copy the string if you intend to use it later because it is not guaranteed to be around after performing more operations with the effect.

LPCSTR szString;
pEffect->GetValue("xFile", (void*)&szString, sizeof(LPCSTR));

Get a texture. It sets your pointer to the texture parameter, and increments the ref count. This means that you are responsible for calling Release on that pointer when you're done with it.

LPDIRECT3DBASETEXTURE9 pTexture;
pEffect->GetValue("tex1", (void*)&pTexture, sizeof(LPDIRECT3DBASETEXTURE9));
SAFE_RELEASE(pTexture);

Get an array of pointers to vertex shaders:

LPDIRECT3DVERTEXSHADER9 pVSArray[4];
pEffect->GetValue("vsArray", (void*)pVSArray, sizeof(LPDIRECT3DVERTEXSHADER9) * 4);
// don't forget to release each object in the array

Get myStruct. Structs are always numeric types and flattened without padding. The struct has 5 floats, so initialize an array to hold it:

FLOAT pMyStruct[4 + 1];
pEffect->GetValue("myStruct", (void*)pMyStruct, sizeof(pMyStruct));

Get an array of structs:

FLOAT pMyStructArray[ (4+1) * 2 ];
pEffect->GetValue("myStructArray, (void*)pMyStructArray, sizeof(pMyStructArray));

Setting Arbitrary Values

Set a single floating point value.

FLOAT f = 1.0f;
pEffect->SetValue("fValue", (void*)&f, D3DX_DEFAULT);

Set a string.

LPCSTR szString = "some string";
pEffect->SetValue("xFile", (void*)&szString, sizeof(LPCSTR));

Set a vertex shader. Shaders are handled in exactly the same way as textures. They must be released when no longer needed.

LPDIRECT3DVERTEXSHADER9 pVShader; // needs initialization
pEffect->SetValue("vsMyShader", (void*)&pVShader, sizeof(LPDIRECT3DVERTEXSHADER9));
SAFE_RELEASE(pVShader);

Set a vector:

D3DXVECTOR4 vecLight; // needs initialization
pEffect->SetValue("vecLight", (void*)(FLOAT*)vecLight, sizeof(D3DXVECTOR4));

Set a matrix:

D3DXMATRIX matWorld; // needs initialization
pEffect->SetValue("mWorld", (void*)(FLOAT*)matWorld, sizeof(D3DXMATRIX));

Set a non-4x4 matrix. Matrices are stored without padding, so a 3x2 matrix is six floats.

FLOAT m3x2matrix[3 * 2]; // needs initialization
pEffect->SetValue("m3x2matrix", (void*)m3x2matrix, desc.Bytes);

If you have a D3DXPARAMETER_DESC "desc" that has been filled in by GetParameterDesc, you can also pass in desc.Bytes.

Set a string. You are getting just a pointer to a const string. The size is always sizeof(LPCSTR), and you should copy the string if you intend to use it later because it is not guaranteed to be around after performing more operations with the effect.

LPCSTR szString; // needs initialization
pEffect->SetValue("xFile", (void*)&szString, sizeof(LPCSTR));

Set a texture. It sets your pointer to the texture parameter, and increments the ref count. This means that you are responsible for calling Release on that pointer when you're done with it.

LPDIRECT3DBASETEXTURE9 pTexture; // needs initialization
pEffect->SetValue("tex1", (void*)&pTexture, sizeof(LPDIRECT3DBASETEXTURE9));
SAFE_RELEASE(pTexture);

Set an array of pointers to vertex shaders as follows:

LPDIRECT3DVERTEXSHADER9 pVSArray[4]; // needs initialization
pEffect->SetValue("vsArray", (void*)pVSArray, sizeof(LPDIRECT3DVERTEXSHADER9) * 4);
// Don't forget to release each object in the array.

Set myStruct. Structs are always numeric types and flattened without padding. The struct has five floats, so initialize an array to hold it.

FLOAT pMyStruct[4 + 1]; // needs initialization
pEffect->SetValue("myStruct", (void*)pMyStruct, sizeof(pMyStruct));

Set an array of structs.

FLOAT pMyStructArray[ (4+1) * 2 ]; // needs initialization
pEffect->SetValue("myStructArray, (void*)pMyStructArray, sizeof(pMyStructArray));

© 2002 Microsoft Corporation. All rights reserved.


Assembly Language Effect

Effect examples created from assembly language.

  • Vertex Shader Assembly
  • Pixel Shader Assembly
  • Exercise 1

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader Assembly

The syntax for a shader declaration is shown here.

Examples

Single Stream Example

This example uses a single stream. Data is provided to four registers, with position, normal, and two sets of texture coordinate data.

technique Assembly_Level_VertexShader
{
    pass P0
    {
        // Vertex state
        VertexShaderConstant4[0]  = (matWorld);
        VertexShaderConstant4[4]  = (matViewProj);
        VertexShaderConstant1[13] = {vecLightColor};
        VertexShaderConstant1[16] = {vecLightDir};

        VertexShader =
        asm
        {
           vs_1_1

           dcl_position  v0
           dcl_normal    v3
           dcl_texcoord  v7
           dcl_texcoord  v8

            m4x4 oPos, v0, c4  // Transform point to projection space.
            m3x3 r0,v3,c0      // Transform normal to world space,
                               //   put result into r0.
            dp3  r0,r0,-c16    // Dot product against light, r0 has lighting
                               //   constant in x, y, and z components (r,g,b).
            mul  r0,r0,c13     // Modulate against diffuse light color.
            mov oD0,r0         // Put into diffuse color output.
        }
    }
};

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader Assembly

This is an example of assembly level pixel shader instructions.

PixelShader =
asm
{
   ps_1_1
   tex t0            // get texture sample from stage 0
   tex t1            // get texture sample from stage 1
   mul_x2 r0,t1,t0;  // blend them together in an interesting way
};

© 2002 Microsoft Corporation. All rights reserved.


Exercise 1

Fixed Function Diffuse Lighting and Vertex Shader Diffuse Lighting.

Example

float3 lightDirection = {0.5f, 0.5f, 0.0f };
float4 diffuseMaterialColor = {1.0f, 0.9f, 0.9f, 1.0f };

float4x4 worldMatrix;
float4x4 worldProjViewMatrix;

// Given: The application has set the matrices before calling this technique.

technique tec0 < string purpose = "Fixed Function Diffuse Lighting" ; >
{
    pass P0
    {
        MaterialDiffuse  = {diffuseMaterialColor};
        MaterialSpecular = {0.0f,0.0f,0.0f,0.0f};
        MaterialAmbient  = {0.0f,0.0f,0.0f,0.0f};

        LightType[0]      = DIRECTIONAL;
        LightDiffuse[0]   = {1.0f,1.0f,1.0f,1.0f};
        LightSpecular[0]  = {0.0f,0.0f,0.0f,0.0f};
        LightAmbient[0]   = {0.0f,0.0f,0.0f,0.0f};
        LightDirection[0] = {lightDirection};
        LightRange[0]     = 100000.0f;

        // Turn lighting on and use light zero
        LightEnable[0]    = TRUE;
        Lighting          = TRUE;

        // Assign diffuse color to be used
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        // Only one color being used
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        // Z-buffering to be used
        ZEnable      = true;
        ZWriteEnable = true;
    }
}

technique tec1 < string purpose = "Vertex Shader Diffuse Lighting" ; >
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0]  = (worldMatrix);
        VertexShaderConstant[4]  = (worldProjViewMatrix);

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f);
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);

        // Light Properties are input from the shader application
        // Diffuse
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f);
        // Specular
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);
        // Ambient
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f);
        VertexShaderConstant[16] = {lightDirection};

        // Assign diffuse color to be used
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        // Only one color being used
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        // Definition of the vertex shader, declarations then assembly
        VertexShader =
        asm
        {
            vs_1_1

            dcl_position v0
            dcl_normal   v3
            dcl_texcoord v7
            dcl_texcoord v8

            m4x4 oPos, v0, c4 // Transform point to projection space.
            m3x3 r0,v3,c0     // Transform normal to world space,
                              //   put result into r0.
            dp3  r0,r0,-c16   // Dot product against light, r0 now has lighting
                              //   constant in x, y, and z components (r,g,b).
            mul  r0,r0,c13    // Modulate against diffuse light color.
            mov oD0,r0        // Put into diffuse color output.
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


High Level Language Effects

Effect examples created from the high level language.

  • Apply a Glow
  • Skinned Displacement with Per-Pixel Lighting

© 2002 Microsoft Corporation. All rights reserved.


Apply a Glow

This example contains two techniques. This first technique, called GlowOnly, applies a glow to an object. GlowOnly uses the function Unskinned to calculate lighting and copy the texture coordinates. The Unskinned function also uses the helper function, TransformUnskinned, to transform position and normal data.

The second technique, called GlowAndNormal, contains two passes. The first pass draws the object normally and the second pass draws an outline.

This example is representative of a high level language sample, it does not compile as shown below.

Example

// effect.fx
texture tex0 < string name = "tiger.bmp"; >;

texture tex1 < string name = "banana.bmp"; >;

string XFile = "tiger.x";   // Model to load
string BIMG  = "lake.bmp";  // Background image
DWORD  BCLR = 0xff202080;   // Background color (if no image)

// Declare the required matrices with the appropriate semantics
//   so that the viewer can supply the necessary matrix information.
float4x4 mProjection : PROJECTION;
float4x3 mWorldView  : WORLDVIEW;
float4x4 mViewProjection : VIEWPROJECTION;

// Declare data used by the shaders that the application can modify.
float3 vLightDirection = {0.0, 0.0, -1.0 };
float  vDisplace       =  0.015;
float4 vGlowColor      = { 0.5, 0.2, 0.2, 1.0 };
float4 vGlowAmbient    = { 0.2, 0.2, 0.0, 0.0 };

// Set up an output structure defining the output to the pixel shader.
struct VS_OUTPUT_TEXCOORD0
{
    float4 Position : POSITION;
    float4 Diffuse  : COLOR;
    float2 Texture0 : TEXCOORD0;
};

// Helper function to transform position/normal into view space
void TransformUnskinned
    (
    float4 vPos,
    float3 vNormal,
    float3 vTransformedPosition,
    float3 vTransformedNormal
    )
{
    // Transform the position into view space
    vTransformedPosition = mul(vPos, mWorldView);

    // Transform the normal into view space (just use the upper 3x3 of WorldView)
    vTransformedNormal = mul(vNormal, (float3x3)mWorldView);
 }

// Draws unskinned object with one texture and one directional light.
VS_OUTPUT_TEXCOORD0 Unskinned
    (
    float4 vPos : POSITION,
    float3 vNormal : NORMAL,
    float2 vTexCoord0 : TEXCOORD0
    )
{
    float3 vTransformedPosition = {0,0,0};
    float3 vTransformedNormal   = {0,0,0};
    VS_OUTPUT_TEXCOORD0 Output;
    float fDot;

    // Transform the position/normal into view space.
    TransformUnskinned(vPos, vNormal, vTransformedPosition, vTransformedNormal);

    // Calculate amount of light from the one light direction.
    fDot = dot(vTransformedNormal, vLightDirection);

    // Transform view space position into screen space.
    Output.Position = mul(float4(vTransformedPosition, 1.0), mProjection);

    // Multiple amount of light times light color.
    // Note: Color could be negative with this equation, but will be
    //   clamped to zero before pixel shader.
    Output.Diffuse = float4(1.0f, 1.0f, 1.0f, 1.0f) * fDot;

    // Just copy the texture coordinate through.
    Output.Texture0 = vTexCoord0;

    return Output;
}

// Declare the output of the GlowSkinned vertex shader to the pixel shader.
struct VS_OUTPUT
{
    float4 Position : POSITION;
    float4 Diffuse  : COLOR;
};

// Draws a transparent hull of the unskinned object.
VS_OUTPUT GlowUnskinned
    (
    float4 vPos : POSITION,
    float3 vNormal : NORMAL
    )
{
    float3 vTransformedPosition = {0,0,0};
    float3 vTransformedNormal   = {0,0,0};
    VS_OUTPUT Output;
    float fPower;

    // For standard "glow" this is the view direction.
    float3 vGlowAxis = float3(0, 0, 1);

    // Transform the position and normal into world space.
    TransformUnskinned(vPos, vNormal, vTransformedPosition, vTransformedNormal);

    // Displace the position by the normal, so that the glow will not
    //   overlap the non-glowed version.
    vTransformedPosition += vTransformedNormal * vDisplace;

    // The glow is determined by the angle between the normal and the glow axis.
    //   This ends up being similar to a fresnel approximation.
    fPower = dot(vTransformedNormal, vGlowAxis);
    fPower = 1.0f - fPower * fPower;
    fPower *= fPower;

    // Transform position into screen space from view space.
    Output.Position = mul(float4(vTransformedPosition, 1.0), mProjection);

    // Output color is the compute power times the glow color.
    Output.Diffuse = vGlowColor * fPower + vGlowAmbient;

    return Output;
}

// first technique - unskinned
// first pass draw the object normally
// second pass draw the outline
technique GlowOnly
{
    pass P1
    {
        // Generate a 1_1 vertex shader to draw the outline of the object.
        VertexShader = compile vs_1_1 GlowUnskinned();

        Texture[0]   = NULL;

        // Enable alpha blending
        AlphaBlendEnable = True;
        SrcBlend     = One;
        DestBlend    = One;

        // Set up TSS stages to just use the diffuse color.
        ColorOp[0]   = SelectArg2;
        ColorArg2[0] = Diffuse;
        AlphaOp[0]   = SelectArg2;
        AlphaArg2[0] = Diffuse;
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;
   }
}

// First technique - unskinned
// First pass draw the object normally
// Second pass draw the outline
technique GlowAndNormal
{
    pass P0
    {
        // Generate a 1_1 vertex shader for unskinned
        //   single texture/one directional light.
        VertexShader = compile vs_1_1 Unskinned();

        // Set up texture stage info for single texture.
        ColorOp[0]   = Modulate;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;
        AlphaOp[0]   = Disable;

        // Set texture filtering.
        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        // Set texture into stage 0.
        Texture[0]   = (tex0);

        // Disable Stage1.
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

    }
    pass P1
    {
        // Generate a 1_1 vertex shader to draw the outline of the object.
        VertexShader = compile vs_1_1 GlowUnskinned();

        Texture[0]   = NULL;

        // Enable alpha blending.
        AlphaBlendEnable = True;
        SrcBlend     = One;
        DestBlend    = One;

        // Set up TSS stages to just use the diffuse color.
        ColorOp[0]   = SelectArg2;
        ColorArg2[0] = Diffuse;
        AlphaOp[0]   = SelectArg2;
        AlphaArg2[0] = Diffuse;
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;
   }
}

© 2002 Microsoft Corporation. All rights reserved.


Skinned Displacement with Per Pixel Lighting

This example effect uses the high level language to perform skining using displacement mapping. It also includes per-pixel lighting.

Example

//
// Example effect: Skinned Displacement, with Per-Pixel Lighting
// Copyright (c) 2001 Microsoft Corporation. All rights reserved.
//

//----------------------------------------------------------------------------
// Types
//----------------------------------------------------------------------------

struct VS_INPUT
{
    float4 vPosition        : POSITION;
    float3 vBlendWeights    : BLENDWEIGHT;
    int4   vBlendIndices    : BLENDINDICES;
    float3 vNormal          : NORMAL;
    float2 vTexCoords       : TEXCOORD0;
    float3 vTangent         : TANGENT;
    float  fFlip            : TEXCOORD1;
    float  fDisplacement    : TEXCOORD2;
};

struct VS_OUTPUT
{
    float4  vPosition       : POSITION;
    float4  vTexCoord0      : TEXCOORD0;
    float4  vTexCoord1      : TEXCOORD1;
    float3  vDiffuse        : COLOR0;
    float3  vSpecular       : COLOR1;
};

//----------------------------------------------------------------------------
// Global parameters
//----------------------------------------------------------------------------

texture tDiffuse;                               // diffuse map
texture tNormal;                                // normal map

float4x3 mWorld[4];                             // world position transforms
float3x3 mNormal[4];                            // world normal transforms
float4x4 mViewProj;                             // view projection transform

float4 cAmbient  = { 0.3f, 0.3f, 0.3f, 1.0f };  // ambient color
float4 cDiffuse  = { 1.0f, 1.0f, 1.0f, 1.0f };  // diffuse color
float4 cSpecular = { 0.6f, 0.6f, 0.6f, 1.0f };  // specular color

float3 vDiffuse  = { 0.0f, 1.0f, 0.0f };         // diffuse direction
float3 vSpecular = { 0.0f, 0.0f, 0.0f };         // specular direction

//----------------------------------------------------------------------------
// Helper functions
//----------------------------------------------------------------------------

static float3 cross(float3 a, float3 b)
{
    return a.yzx * b.zxy - b.yzx * a.zxy;
}

//----------------------------------------------------------------------------
// Shader body
//----------------------------------------------------------------------------

VS_OUTPUT main(const VS_INPUT v)
{
    VS_OUTPUT o = (VS_OUTPUT) 0;

    // Compute last blend weight
    float fLastBlendWeight = 1 - dot(v.vBlendWeights, 1);

    // Skin position(to world space)
    float3 vPosition =
        mul(v.vPosition, mWorld[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vPosition, mWorld[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vPosition, mWorld[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vPosition, mWorld[v.vBlendIndices.w]) * fLastBlendWeight;

    // Skin normal (to world space)
    float3 vNormal =
        mul(v.vNormal, mNormal[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vNormal, mNormal[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vNormal, mNormal[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vNormal, mNormal[v.vBlendIndices.w]) * fLastBlendWeight;

    // Skin tangent (to world space)
    float3 vTangent =
        mul(v.vTangent, mNormal[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vTangent, mNormal[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vTangent, mNormal[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vTangent, mNormal[v.vBlendIndices.w]) * fLastBlendWeight;

    // Compute binormal
    float3 vBinormal = cross(vNormal, vTangent) * v.fFlip;

    // Light direction (to vertex space)
    float3x3 mLight =
        float3x3(vTangent.x, vBinormal.x, vNormal.x,
                 vTangent.y, vBinormal.y, vNormal.y,
                 vTangent.z, vBinormal.z, vNormal.z);

    // Output stuff
    o.vPosition = mul(float4(vPosition + vNormal * v.fDisplacement, 1),
                      mViewProj);
    o.vDiffuse  = mul(vDiffuse, mLight) * 0.5 + 0.5;
    o.vSpecular = mul(vSpecular, mLight) * 0.5 + 0.5;
    o.vTexCoord0.xy = o.vTexCoord1.xy = v.vTexCoords.xy;

    return o;
}

//----------------------------------------------------------------------------
// Technique
//----------------------------------------------------------------------------

technique T0
{
    pass P0
    {
        // Vertex shader
        VertexShader = compile vs_2_0 main();

        // Pixel shader
        PixelShader =
            asm
            {
                ps_1_1
                tex t0
                tex t1

                // Specular
                dp3_sat r1, t1_bx2, v1_bx2
                dp3_x4  r0, t1_bx2, v0_bx2

                mul_sat r1, r1, r0
                mul_sat r1, r1, r1
                mul_sat r1, r1, c2

                // Diffuse + Ambient
                dp3_sat r0, t1_bx2, v0_bx2
                mad_sat r0, r0, c1, c0
                mad_sat r0, r0, t0, r1
            };

        PixelShaderConstant1[0] = (cAmbient);
        PixelShaderConstant1[1] = (cDiffuse);
        PixelShaderConstant1[2] = (cSpecular);

        // Textures and filtering
        Texture[0]   = (tDiffuse);
        MinFilter[0] = LINEAR;
        MagFilter[0] = LINEAR;
        MipFilter[0] = LINEAR;

        Texture[1]   = (tNormal);
        MinFilter[1] = LINEAR;
        MagFilter[1] = LINEAR;
        MipFilter[1] = LINEAR;

        // Clip/Raster state
        CullMode = CW;
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Extensions (D3DX) Meshes

Direct3D extensions (D3DX) is a utility library that provides helper services. It is a layer above the Microsoft® Direct3D® component.

Meshes

D3DX implements the mesh construct to load, manipulate, and render .x file contents. A mesh is basically a collection of vertices defining some geometry, and a set of indices defining the faces. There are several mesh types.

ID3DXBaseMesh provides the fundamentals. ID3DXMesh and ID3DXPMesh inherit from ID3DXBaseMesh, and add, respectively, mesh optimization using per-chip vertex cache and progressive meshes modeled after Hughes Hoppes's progressive mesh work. ID3DXSPMesh provides simplification meshes and ID3DXSkinMesh provides skinned mesh support.

ID3DXBaseMesh provides methods to manipulate and query ID3DXMesh and ID3DXPMesh progressive-mesh objects, which inherit from the base mesh. This includes adjacency operations, geometry buffer retrieval, lock/unlock operations (vertex and index), and copying, rendering, face, and vertex information.

Mesh Architecture

A mesh contains the data for a complex model. It is an abstract data container that contains resources such as textures and materials, and attributes such as position data and adjacency data. There are several mesh operations that improve drawing performance and the appearance of a surface. In addition, there are a number of other mesh concepts that will effect the functionality of mesh operations. Understanding these mesh concepts so you can apply them will improve mesh performance.

Mesh Object Data

A mesh contains a vertex buffer, an index buffer, and an attribute buffer. Each of these buffers is a ID3DXBuffer type. This buffer type is always used by Direct3D to return a pointer to a memory location whose size is not known.

  • The vertex buffer contains the vertex data, which are the mesh vertices.
  • The index buffer contains vertex indices for accessing the vertex buffer. This can reduce the vertex buffer size by reducing duplicate vertices. Only an indexed mesh uses the index buffer. If a mesh is made up of a triangle list, for example, it does not use the index buffer.
  • The attribute buffer contains attribute data. Attributes are properties of the mesh vertices, in no particular order. A D3DX mesh stores attributes in a group of DWORDS, for each face.

Attibute Tables

An attribute table is a concise representation of the contents of an attribute buffer. A mesh contains an attribute table when the mesh is reordered into groups. The reordering takes place when Optimize is called, assuming an attribute sorting option (D3DXMESHOPT_ATTRSORT or higher) is supplied. Mesh drawing is done with DrawPrimitive, which uses the table to get subset groupings. SetAttributeTable is another way to create a table.

Attribute tables can only be created by calling Optimize. The faces don't have to be adjacent, because Optimize will reorder them to be adjacent. For example, the hands of a human mesh could use the same attribute. The attribute identifier (ID) helps sort the faces into groups. Meshes from .x files have automatically generated attributes for material and texture properties. You do need to call Optimize(ATTRSORT) or the more effective Optimize(VERTEXCACHE) to get good performance. The load functions try to present the data in the exact form it was saved out in. If you are using a vertex buffer/index buffer based mesh, the mesh application programming interface (API) provides optimization functions and skinning transformations with little overhead.

The optimization types are cumulative, starting from the least optimal (D3DXMESHOPT_COMPACT) to the most optimal (D3DXMESHOPT_IGNOREVERTS). D3DXMESHOPT_STRIPREORDER does a compaction and attribute sort. D3DXMESHOPT_VERTEXCACHE is always recommended, even on devices without a true vertex cache.

Application Data

Application data is mesh data that is managed by an application. There is a tight coupling between the mesh vertex data and the data managed by these buffers.

The materials buffer contains n materials. The materials are returned by the Load function when the .x file is loaded. Each subset can have its own materials and textures. The materials buffer is static.

The adjacency buffer contains information about edges, faces, and adjacent faces. Some mesh operations depend on knowing which faces are adjacent to each other. This information, called adjacency data, is kept in an adjacency buffer. It is not part of the mesh but is maintained by the application and must be supplied to the mesh methods when necessary.

The effects instance buffer contains a list of effect instances. An effect instance stores state. This state information is used to initialize the pipeline. An effect instance contains name-value pairs in an effect.

Advanced Mesh Topics

Optimized meshes build on the base mesh functionality and add vertex-cache optimization capability with two methods: Optimize, which creates a new mesh, and OptimizeInPlace, which modifies the original mesh.

Progressive meshes are based on Hughes Hoppes's SIGGRAPH papers (from the Association for Computing Machinery's Special Interest Group, Graphics), with updated error metrics. The ID3DXPMesh adds methods for copying, face and vertex manipulation, and optimization.

D3DXGeneratePMesh uses the D3DX simplification algorithm to generate a progressive mesh from the input mesh. D3DXSimplifyMesh generates a standard mesh of the given level of detail (LOD) from an input mesh using the same simplification algorithm. The user has control over the error metric used through the weights specified per-vertex component and weights specified per vertex. Per-component weights are multiplied against that components portion of error calculated per edge collapse. Per-vertex weights are multiplied against the error metric value determined for removal of that vertex. For example, if you never want a vertex to be removed, set that specific vertex's weight to a large value. Conversely, if you want it removed earlier, set it to a small value (less than 1).

ID3DXSkinInfo supports skinned characters. A skinned character is defined by a set of meshes and a set of bones that affect the vertices of the meshes. The bones are represented as a transform hierarchy. For each mesh, there is a matrix for every bone that affects it, which transforms the mesh into the local coordinate space of the bone. This matrix is the bone-space transform of the bone for the mesh. This is defined at the time the skeleton is associated with the mesh in the authoring process.

Skinning

Skinning is a technique for transforming mesh vertices using bones. Bones are typically arranged in a hierarchical skeleton, much like the bones in a human body. Object vertices are then associated with the bones, like attaching skin to the bones. When the bones get transformed, the skin is also transformed.

Skinned meshes use bones to influence a number of vertices. Bone transformation data is supplied by the user, to influence how to scale, rotate, and translate (SRT) the bones. The mesh uses the transformed bones to influence the vertices associated with the bones. Palettes are arrays of SRT transformations. Palettes are often implemented as matrices, but they can contain SRT values.

Progressive Mesh Trimming

Low detail areas can afford to lose vertices which don't change the rendered appearance of the surface. This is especially true of objects as they move farther from the camera. This is referred to as LOD. Users have API-level render controls for setting the LOD to maximize rendering efficiency.

Progressive mesh objects start with a high number of faces and use simplification to reduce the number of faces. A progressive mesh that is view independent is referred to as a view-independent progressive mesh.

Another way to reduce the number of faces is by trimming. This actually removes vertices and faces from the mesh. Trimming can be done at the high end (to limit the max number of faces) or at the low end (to limit the minimum number of faces.) Trimming improves draw performance, however, care should be used to preserve the visual quality. Trimming is demonstrated in the Progressive Mesh software development kit (SDK) Sample.

For high visibility areas, the resolution can be increased using progressive level of detail (PLOD). This is a technique for breaking a single face into two faces.

Patch Meshes

Two specialized types of patch meshes are also supported: rectangle and triangle patches. The rectangle patch mesh is a patch mesh whose control points are laid out in a winding, rectangular sequence. Rectangle and triangle patches are used to create high-order surfaces. They are not as commonly used as triangle meshes.

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Extensions (D3DX) Line Drawing

Direct3D extensions (D3DX) has been extended to support single-pixel-wide antialiased lines. Support for line patterns is removed; the D3DRS_LINEPATTERN render state is no longer supported.

The line drawing library emulates lines using texture triangles assuming:

  • Hardware is available through the Microsoft® DirectX® 9.0 interfaces.
  • At least one texture stage is available.
  • 64x64 textures are used.
  • The following modes are available.
    • Bilinear filtering.
    • Clamp address mode.
    • Wrap address mode.
    • Alpha op modulate.
    • Alpha blending (SRCBLEND = SRC_ALPHA, DESTBLEND = INV_SRC_ALPHA).
    • Alpha test if alpha blending is not available. Lower quality result.

Setting the D3DRS_ANTIALIASEDLINEENABLE render state to TRUE or FALSE enables or disables line antialiasing. The default state is FALSE.

The D3DRS_ANTIALIASEDLINEENABLE render state applies to triangles drawn in wireframe mode as well as line drawing primitive types. When rendering to a multisample render target, the D3DRS_ANTIALIASEDLINEENABLE render state is ignored and all lines are rendered aliased.

For antialiased line rendering in multisample render targets, use ID3DXLine, which generates textured polygons. The pixel coverage values, generated by antialiased line rasterization, modulate the pixel's alpha value computed by the pixel shader. An application must enable alpha blending to draw the antialiased line.

The changes include:

// New render state
D3DRS_ANTIALIASEDLINEENABLE
// Can be TRUE (nonzero) or FALSE (zero)

// New capability bit
D3DLINECAPS_ANTIALIAS

// Deleted the following
D3DRS_LINEPATTERN, struct D3DLINEPATTERN, D3DPMISCCAPS_LINEPATTERNREP

Functionality Description

The library supports drawing colored line strips with the following line features, each of which is independent of the other.

  • Line width.
  • Line pattern with repetition. The line pattern counter resets with each ID3DXLine::Draw or ID3DXLine::DrawTransform call. It does not reset with each segment of the line strip.
  • Antialiasing.
  • OpenGL-style lines.
Note No mitering is supported.

The library uses native hardware line drawing support (if available in the device) only if:

  • Line width is 1.
  • No line pattern is enabled.

Single-pixel-wide antialiased lines are supported by some hardware, so the library uses that, if available.

When the software line drawing is used, each line is expanded into a rectangle and four vertices are sent down to the driver.

Each line segment is drawn with two triangles. The width of the primitive is 1.0 + the specified width, which may result in an extra row or column of pixels. As the line gets wider, the antialias gradient in the texture becomes coarser, and more fully opaque texels are replicated around the middle. The gradient is encoded in the v-direction of the texture, and typically replicated along the u-direction. The texture addressing mode for v is clamp.

Each line segment in the list can be considered to be a separate line that happens to start from the previous end point.

Antialiasing quality along the edges parallel to the length of the original line suffers as the line gets wider. It is expected that line widths greater than 32.0 will start to exhibit artifacts along these edges.

© 2002 Microsoft Corporation. All rights reserved.


Other Direct3D Extensions (D3DX)

Direct3D extensions (D3DX) is a utility library that provides helper services. It is a layer above the Microsoft® Direct3D® component.

  • Textures
  • Math
  • Other
  • FLOAT16

The Microsoft DirectX® 7.0 software development kit (SDK) started with texture and math support to help initialize resources. With the DirectX 8.0 SDK, the simplified Direct3D initialization was largely modeled on the D3DX context initialization support. Since then, the library has been expanded to become a suite of advanced functionality, with support for meshes, shaders, effects, math, and texture mapping support.

D3DX provides extensive support for basic needs like math, texturing, and shader manipulation, as well as advanced support like effect files and meshes. There is even general purpose utility support for matrix stacks, simple shapes, and error handling.

Textures

Many different textures are supported in the following topics.

  • Texture requirements checking. See Textures.
  • Standard mipmapped texture support. See Automatic Generation of Mipmaps.
  • Cube map support. See Cubic Environment Mapping.
  • Volume texture support. See Volume Texture Resources.
  • Environment mapping support. See Environment Mapping.
  • Bump mapping support. See Bump Mapping.

Texture_Color_Conversion

When using any of the D3DXLoadSurfacexxx, D3DXLoadVolumexxx, D3DXCreateTexturexxx, D3DXCreateCubeTexturexxx, or D3DXCreateVolumeTexturexxx functions, color conversion might need to be performed. For example, one surface might be type RGBA and the other might be UVWQ. For cases of dissimilar formats, the conversion sequence is as follows:

Mapping RGBA_to_UVWQ(L)

  • R <-> U, R channel is mapped to the U channel, or vice versa.
  • G <-> V, G channel is mapped to the V channel, or vice versa.
  • B <-> W, B channel is mapped to the W channel, or vice versa.
  • A <-> Q/L, A channel is mapped to either the Q or the L channel (depending on which one is available in the destination format), or vice versa.

R->U
G->V
B->W
A->Q or A->L

Mapping UV to RGBA

  • U <-> R, U channel is mapped to the R channel, or vice versa.
  • V <-> G, V channel is mapped to the G channel, or vice versa.
  • 1 <-> B, 1 is mapped to the B channel, or vice versa.
  • 1 <-> A, 1 is mapped to the A channel, or vice versa.

If a channel does not exist in the source, it is assumed to be 1 (with the exception of A8, where R,G,B are assumed to be 0). For example:

U -> R
V -> G
1 -> B
1 -> A

Math

Math support, contained in a set of functions, is provided for:

  • Color calculations
  • Planes
  • Matrix manipulation
  • Quaternions
  • 2-D vectors
  • 3-D vectors
  • 4-D vectors

It is worth noting here that when coupled with the C++ overloads, the support for basic 3-D math types is extensive.

For more information about these functions, see Functions. To help find the function you need, they are broken up in several folders.

FLOAT16

When using the FLOAT16 data type, be sure to limit values to a maximum of D3DX_16F_MAX. Any FLOAT16 value that exceeds this will result in undefined behavior in the pipeline. See Other Direct3D Extentions (D3DX) Constants.

Other

These are the D3DX functions that did not fit into one of the earlier categories.

  • Matrix stack. See Matrix Stacks.
  • Shape generation functions. See Shape Drawing Functions.
  • Sprites. See Miscellaneous Functions.
  • Fonts. See Miscellaneous Functions.
  • Render targets. See Miscellaneous Functions.

© 2002 Microsoft Corporation. All rights reserved.


Asynchronous Notification

There are number of interesting queries on a driver that an application can make if there is no performance cost. In Microsoft® DirectX® 7.0 and DirectX 8.x, a synchronous query mechanism, GetInfo, worked well for things like statistics, but no performance-critical queries were added. There are other things (like fences) that are inherently asynchronous. This is a simple application programming interface (API) to make both synchronous and asynchronous queries. GetInfo will be retired in DirectX 9.0.

Create a query using IDirect3DDevice9::CreateQuery. This method takes a D3DQUERYTYPE, which defines what kind of query to make and returns a pointer to an IDirect3DQuery9 object. If the query type is not supported, the call returns an error D3DERR_NOTAVAILABLE. Using the query object, the application submits the query to the runtime using IDirect3DQuery9::Issue, and polls the query status using IDirect3DQuery9::GetData. If the query result is available, S_OK is returned; otherwise, S_FALSE is returned. The application is expected to pass an appropriately sized buffer for the query results.

The application has an option to force the runtime to flush the query down to the driver by using D3DGETDATA_FLUSH with IDirect3DQuery9::GetData. It causes a flush, forcing the driver to see the query. In this case, D3DERR_DEVICELOST is returned if the device becomes lost.

All queries are lost when the device is lost, the application has to re-create them. If the device does not support the query and the pQueryID is NULL, the query creation will fail with D3DERR_INVALIDCALL.

The following table summaries important information about each query type.

QuertyType | Valid issue flag | GetData buffer | Runtime | Implicit beginning of query
D3DQUERYTYPE_VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | CreateDevice
D3DQUERYTYPE_RESOURCEMANAGER | D3DISSUE_END | D3DDEVINFO_RESOURCEMANAGER | Debug only | Present
D3DQUERYTYPE_VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | Present
D3DQUERYTYPE_EVENT | D3DISSUE_END | BOOL | Retail/Debug | CreateDevice
D3DQUERYTYPE_OCCLUSION | D3DISSUE_BEGIN,D3DISSUE_END | DWORD | Retail/Debug | N/A

Flags field for IDirect3DQuery9::Issue:

#define D3DISSUE_END (1 << 0)
// Tells the runtime to issue the end of a query, changing its state to
//   "non-signaled"

#define D3DISSUE_BEGIN (1 << 1) // Tells the runtime to issue the
// beginng of a query.

Flags field for IDirect3DQuery9::GetData:

#define D3DGETDATA_FLUSH (1 << 0) // Tells the runtime to flush
// if the query is outstanding.

© 2002 Microsoft Corporation. All rights reserved.


Multihead

Multihead cards are those that have a common frame buffer and accelerator, independent digital-to-analog converters (DACs), and monitor outputs. Such devices can offer much more usable multiple monitor support than a similar number of heterogeneous display adapters.

Multihead cards are exposed in the application programming interface (API) as a single API-level device that can drive several full-screen swap chains. Consequently, all resources are shared with all the heads, and each head has exactly the same capabilities. Each head can be set to independent display modes and can be refreshed (with IDirect3DSwapChain9::Present) at different times. Use IDirect3DDevice9::Present for simultaneous presents.

Each swap chain for a multihead device must be full screen. When a device has entered multihead mode, it must remain full screen. The transition back to windowed mode requires the destruction of the device (except for the normal ALT+TAB-to-minimize operation).

The old method of dividing video memory between the heads and treating each head as a fully independent accelerator will still be a common usage scenario. This proposal does not replace that mechanism unless the application has been specifically coded to function in the Microsoft® DirectX® 9.0 multihead mode.

Drivers are given adequate knowledge to switch between the two modes of operation.

One head will be called the "master" head, and all other heads on the same card be called "subordinate" heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a "group." Groups are denoted by the adapter ordinal of their master head.

The D3DCAPS9 structure will be updated to expose the following new hardware caps.

UINT NumberOfAdaptersInGroup;
UINT MasterAdapterOrdinal;
UINT AdapterOrdinalInGroup;
  • NumberOfAdaptersInGroup is 1 for conventional adapters, and greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but might have many subordinates.
  • MasterAdapterOrdinal indicates which device is the master for this subordinate.
  • AdapterOrdinalInGroup indicates the order in which heads are referenced by the API. The master adapter always has AdapterOrdinalInGroup 0. These values do not correspond to the adapter ordinals passed to the IDirect3D9 methods, but apply only to heads within a group.

This definition allows multihead cards to continue to present multiple adapters as if they were independent cards, just as they did in DirectX 8.x.

To create a multihead device, specify the behavior flag D3DCREATE_ADAPTERGROUP_DEVICE in IDirect3D9::CreateDevice. The presentation parameters (an array of D3DPRESENT_PARAMETERS) should contain NumberOfAdaptersInGroup elements. The runtime will assign each element to each head in AdapterOrdinalInGroup numerical order. When D3DCREATE_ADAPTERGROUP_DEVICE is set, each presentation parameter must have:

  • Windowed set to FALSE (in other words, be full screen).
  • The same value for the EnableAutoDepthStencil member of D3DPRESENT_PARAMETERS.

In addition, if EnableAutoDepthStencil is TRUE, then each of the following fields must have the same value for each D3DPRESENT_PARAMETERS:

  • AutoDepthStencilFormat
  • BackBufferWidth
  • BackBufferHeight
  • BackBufferFormat

If D3DCREATE_ADAPTERGROUP_DEVICE is set, additional calls to IDirect3DDevice9::CreateAdditionalSwapChain are illegal.

If the device was created with the D3DCREATE_ADAPTERGROUP_DEVICE, IDirect3DDevice9::Reset will expect an array of D3DPRESENT_PARAMETERS.

Each D3DPRESENT_PARAMETERS passed to IDirect3DDevice9::Reset must be full screen. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

Here is a basic usage scenario.

1. Create Device multihead.
2. For each swap chain of device:
   3. Call GetBackBuffer for the i-th swapchain.
   4. Call SetRenderTarget.
   5. Call DrawPrimitive.
   6. Optionally call swapchain::Present (or wait until
      all swap chains are drawn and present outside of loop).
7. End for.
8. Optionally present all swap chains with device::Present.

For more information, see IDirect3D9::CreateDevice and IDirect3DDevice9::GetNumberOfSwapChains.

© 2002 Microsoft Corporation. All rights reserved.


X Files

The X file format refers to files with the .x file name extension. X files were introduced with Microsoft® DirectX® 2.0. A binary version of this format was subsequently released with DirectX 3.0, which is also described in this documentation. DirectX 6.0 introduced interfaces and methods that enable reading from and writing to .x files.

X files provide a template-driven format that enables the storage of meshes, textures, animations, and user-definable objects. Support for animation sets enables you to store predefined paths for playback in real time. Instancing and hierarchies are also supported. Instancing enables multiple references to an object, such as a mesh, while storing its data only once per file. Hierarchies are used to express relationships between data records.

The .x file format provides low-level data primitives on which applications define higher-level primitives through templates.

This section describes the structure of .x files and how to use them in your applications.

Information is divided into the following topics.

  • Loading an X File
  • Saving to an X File
  • Creating a Cube
  • Converting and Exporting 3-D Models to X Files

For more information about the .x file format, see X File Reference.

© 2002 Microsoft Corporation. All rights reserved.


Loading an X File

Use the following procedure to load an .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. If templates are present in the Microsoft® DirectX® file that you will load, use the IDirectXFile::RegisterTemplates method to register those templates.
  3. Use the IDirectXFile::CreateEnumObject method to create an IDirectXFileEnumObject enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the IDirectXFileEnumObject::GetNextDataObject method to retrieve each IDirectXFileData object.
    2. Use the IDirectXFileData::GetType method to retrieve the data's type.
    3. Load the data using the IDirectXFileData::GetData method.
    4. If the object has optional members, retrieve the optional members by calling the IDirectXFileData::GetNextObject method.
    5. Release the IDirectXFileData object.
  5. Release the IDirectXFileEnumObject object.
  6. Release the IDirectXFile object.

© 2002 Microsoft Corporation. All rights reserved.


Saving to an X File

Use the following procedure to save .x file templates and data to an .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. Use the IDirectXFile::RegisterTemplates method to inform the Microsoft® DirectX® file system about any templates that you will use.
  3. Use the IDirectXFile::CreateSaveObject method to create an IDirectXFileSaveObject object.
  4. Use the IDirectXFileSaveObject::SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    1. Use the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object as a top-level object in the file. If the top-level data object has optional child objects, add them to the object by using the appropriate method from the next step.
    2. Each IDirectXFileData object can have optional child objects if its template allows it. The child objects can be any of the three types of objects: IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary. Loop through the objects you need to save, adding each optional child member to the object list in the manner appropriate to its type, as illustrated in the following steps. Then, if the object type is Data, call the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object, and then call the IDirectXFileData::AddDataObject method to add it as a child of the object. If the object type is Data Reference, call the IDirectXFileData::AddDataReference method to create and add the data reference object as a child of the object. Or, if the object type is Binary, call the IDirectXFileData::AddBinaryObject method to create and add the binary object as a child of the object.
    3. Call the IDirectXFileSaveObject::SaveData method to save the data object and its children.
    4. Release the IDirectXFileData object.
  6. Release the IDirectXFileSaveObject object.
  7. Release the IDirectXFile object.

© 2002 Microsoft Corporation. All rights reserved.


Creating a Cube

This section describes a simple cube and shows how to add textures, frames, and animations.

  • Defining a Simple Cube
  • Adding Textures
  • Adding Frames and Animations

© 2002 Microsoft Corporation. All rights reserved.


Defining a Simple Cube

The following file defines a simple cube that has four red sides and two green sides. In this file, optional information is used to add information to the data object defined by the Mesh template.

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

// Define a mesh with 8 vertices and 12 faces (triangles). Use
// optional data objects in the mesh to specify materials, normals,
// and texture coordinates.
Mesh CubeMesh {
8;                                // 8 vertices.
1.000000;1.000000;-1.000000;,     // Vertex 0.
-1.000000;1.000000;-1.000000;,    // Vertex 1.
-1.000000;1.000000;1.000000;,     // And so on.
1.000000;1.000000;1.000000;,
1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;1.000000;,
1.000000;-1.000000;1.000000;;

12;                      // 12 faces.
3;0,1,2;,                // Face 0 has three vertices.
3;0,2,3;,                // And so on.
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;

// All required data has been defined. Now define optional data
// using the hierarchical nature of the file format.
MeshMaterialList {
2;                    // Number of materials used.
12;                   // A material for each face.
0,                    // Face 0 uses the first material.
0,
0,
0,
0,
0,
0,
0,
1,                    // Face 8 uses the second material.
1,
1,
1;;
{RedMaterial}         // References to the definitions
{GreenMaterial}       // of material 0 and 1.
}
MeshNormals {
8;                    // Define 8 normals.
0.333333;0.666667;-0.666667;,
-0.816497;0.408248;-0.408248;,
-0.333333;0.666667;0.666667;,
0.816497;0.408248;0.408248;,
0.666667;-0.666667;-0.333333;,
-0.408248;-0.408248;-0.816497;,
-0.666667;-0.666667;0.333333;,
0.408248;-0.408248;0.816497;;
12;                   // For the 12 faces, define the normals.
3;0,1,2;,
3;0,2,3;,
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;
}
MeshTextureCoords {
8;                        // Define texture coords for each vertex.
0.000000;1.000000;
1.000000;1.000000;
0.000000;1.000000;
1.000000;1.000000;
0.000000;0.000000;
1.000000;0.000000;
0.000000;0.000000;
1.000000;0.000000;;
}

© 2002 Microsoft Corporation. All rights reserved.


Adding Textures

To add textures, use the hierarchical nature of the file format and add an optional TextureFilename data object to the Material data objects. The Material objects now read as follows:

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "tex1.ppm"; }
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "win95.ppm"; }
}

© 2002 Microsoft Corporation. All rights reserved.


Adding Frames and Animations

This section shows how to add frames and animations to a simple cube.

Working with Frames

A frame is expected to take the following structure.

Frame Aframe {        // The frame name is chosen for convenience.
FrameTransformMatrix {
...transform data...
}
[ Meshes ] and/or [ More frames]
}

Place the defined cube mesh inside a frame with an identity transform. Then apply an animation to this frame.

Frame CubeFrame {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000;;
}
{CubeMesh}        // You could have the mesh inline, but this
                  // uses an object reference instead.
}

Working with Animations

An animation is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position.

Animation Animation0 {        // The name is chosen for convenience.
{ Frame that it applies to - normally a reference }
AnimationKey {
...animation key data...
}
{ ...more animation keys... }
}

Animations are then grouped into AnimationSets:

AnimationSet AnimationSet0 { // The name is chosen for convenience.
{ an animation - could be inline or a reference }
{ ... more animations ... }
}

Now take the cube through an animation.

AnimationSet AnimationSet0 {
Animation Animation0 {
{CubeFrame}    // Use the frame containing the cube.
AnimationKey {
2;             // Position keys
9;             // 9 keys
10; 3; -100.000000, 0.000000, 0.000000;;,
20; 3; -75.000000, 0.000000, 0.000000;;,
30; 3; -50.000000, 0.000000, 0.000000;;,
40; 3; -25.500000, 0.000000, 0.000000;;,
50; 3; 0.000000, 0.000000, 0.000000;;,
60; 3; 25.500000, 0.000000, 0.000000;;,
70; 3; 50.000000, 0.000000, 0.000000;;,
80; 3; 75.500000, 0.000000, 0.000000;;,
90; 3; 100.000000, 0.000000, 0.000000;;;
}
}
}

For more information, see the Animation and AnimationSet templates.

© 2002 Microsoft Corporation. All rights reserved.


Converting and Exporting 3-D Models to X Files

Microsoft® Direct3D® supplies the following tools to convert and export 3-D models to the .x file format.

  • Conv3ds.exe
  • XSkinExp.dle

© 2002 Microsoft Corporation. All rights reserved.


Conv3ds.exe

The Conv3ds.exe utility converts three-dimensional (3-D) models produced by Autodesk 3-D Studio and other modeling packages to the Microsoft® DirectX® file format. By default, the utility produces binary .x files with no templates.

Running Conv3ds.exe

You can run Conv3ds.exe with no options, and it will produce an .x file containing a hierarchy of frames. For example, the following command produces an .x file called File.x from the .3ds file.

conv3ds File.3ds
  • To run Conv3ds.exe with options, see Specifying Optional Arguments for Conv3ds.exe.
  • Producing 3DS Files from Lightwave Objects
  • Hints and Tips

© 2002 Microsoft Corporation. All rights reserved.


Specifying Optional Arguments for Conv3ds.exe

If the .3ds file contains key frame data, you can use the -A option to produce an .x file that contains an animation set. The following command would do this.

conv3ds -A File.3ds

The File.3ds parameter is the name of the file to be converted.

Use the -m option to make an .x file that contains a single mesh made from all the objects in the .3ds file.

conv3ds -m File.3ds

Use the -T option to wrap all the objects and frame hierarchies in a single top-level frame. Using this option, all the frames and objects in the .3ds file can be loaded with a single call. The first top-level frame hierarchy in the .x file will be loaded. The frame containing all the other frames and meshes is called x3ds_filename, without the .3ds extension. The -T option will have no effect if it is used with the -m option.

The -s option enables you to specify a scale factor for all the objects converted in the .3ds file. For example, the following command makes all objects ten times bigger.

conv3ds -s10 File.3ds

The following command makes all objects ten times smaller:

conv3ds -s0.1 File.3ds

The -r option reverses the winding order of the faces when the .3ds file is converted. If, after converting the .3ds file and viewing it in Microsoft® Direct3D®, the object appears inside-out, try converting it with the -r option. All Lightwave models exported as .3ds files need this option. For details, see Producing 3DS Files from Lightwave Objects.

The -v option turns on verbose output mode. Specify an integer with it. The following table shows the currently supported integers.

Option | Meaning
-v0 | Default. Verbose mode off.
-v1 | Prints warnings about bad objects, and prints general information about what the converter is doing.
-v2 | Prints basic key frame information, the objects being included in the conversion process, and information about the objects being saved.
-v3 | Very verbose. Most useful for debugging information.

The -e option enables you to change the extension for texture map files, as shown in the following example.

conv3ds -e"ppm" File.3ds

If File.3ds contains objects that reference the texture map file Brick.gif, the .x file will reference the texture map file Brick.ppm. The converter does not convert the texture map file. The texture map files must be in the D3DPATH when the resulting .x file is loaded. The D3DPath is an environment variable that sets the default search path.

The -x option forces the Conv3ds.exe utility to produce a text .x file, instead of a binary .x file. Text files are larger but can be easily edited by hand.

The -X option forces the Conv3ds.exe utility to include the .x file templates in the file. By default, the templates are not included.

The -t option specifies that the .x file produced will not contain texture information.

The -N option specifies that the .x file produced will not contain normal vector information. All the load calls will generate normal vectors for objects with no normal vectors in the .x file.

The -c option specifies that the .x file produced should not contain texture coordinates. By default, if you use the -m option, the mesh that is output will contain (0,0) uv texture coordinates if the .3ds object had no texture coordinates.

The -f option specifies that the .x file produced should not contain a frame transformation matrix.

The -z and -Z options enable you to adjust the alpha face color value of all the materials referenced by objects in the .x file. For example, the following command causes Conv3ds.exe to add 0.1 to all alpha values under 0.2.

conv3ds -z0.1 -Z0.2 File.3ds

The following command causes Conv3ds.exe to subtract 0.2 from the alpha values for all alphas.

conv3ds-z"-0.2" -z1 File.3ds

The -o option enables you to specify the file name for the .x file produced.

The -h option tells the converter not to try to resolve any hierarchy information in the .3ds file, usually produced by the key framer. Instead, all the objects are output in top-level frames if the -m option is not used.

© 2002 Microsoft Corporation. All rights reserved.


Producing 3DS Files from Lightwave Objects

There are several issues with .3ds files exported by the Trans3d plug-in for Lightwave. These are best handled using the following Conv3ds.exe command.

conv3ds -r -N -f -h -T|m trans3dfile.3ds

All the .3ds objects produced by Trans3d and the Lightwave object editor need their winding order reversed. Otherwise, they appear inside-out when displayed. They contain no surface normal vector information.

© 2002 Microsoft Corporation. All rights reserved.


Hints and Tips

If you cannot see objects produced by Conv3ds.exe after loading them, use the scale option -s with a scale factor of approximately 100. This increases the scale of the objects in the .x file.

If, after loading the object into the viewer and switching from flat shading into Gouraud shading, the object turns dark gray, try converting with the -N option.

If the textures are not loaded after the object is converted, check whether the object is referencing either .ppm or .bmp files by using the -e option. Also check whether the texture widths and heights are a power of 2. Make sure the textures are stored in a directory in your D3DPATH.

Currently, Conv3ds.exe cannot handle dummy frames used in .3ds animations. It ignores them. However, it converts any child objects.

© 2002 Microsoft Corporation. All rights reserved.


XSkinExp.dle

XSkinExp.dle is used as an exporter for Discreet 3ds max and is located on the Microsoft® DirectX® 9.0 software development kit (SDK) CD.

The path for this file is CDdrive:\DXF\extras\direct3d\tools\3dsmax.

See the readme file provided with XSkinExp.dle for information about how to use the .dle.

© 2002 Microsoft Corporation. All rights reserved.


Tutorials, Samples, Tools, and Tips

This section contains tutorials, samples, tools, and programming tips for using Microsoft® Direct3D® and Direct3D extensions (D3DX).

  • Tutorials
  • Samples
  • Tools
  • Programming Tips

© 2002 Microsoft Corporation. All rights reserved.


Tutorials

The tutorials in this section show how to use Microsoft® Direct3D® and Direct3D extensions (D3DX) in a C/C++ application for common tasks. The tasks are divided into required steps. In some cases, steps are organized into substeps for clarity.

The following tutorials are provided.

Tutorials

  • Tutorial 1: Creating a Device
  • Tutorial 2: Rendering Vertices
  • Tutorial 3: Using Matrices
  • Tutorial 4: Creating and Using Lights
  • Tutorial 5: Using Texture Maps
  • Tutorial 6: Using Meshes

Note The sample code in these tutorials is from source projects whose location is provided in each tutorial.

The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.

Some comments in the included sample code might differ from the source files in the Microsoft Platform Software Development Kit (SDK). Changes are made for brevity only and are limited to comments to avoid changing the behavior of the sample code.

See Also

Samples

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 1: Creating a Device

To use Microsoft® Direct3D®, you first create an application window, then you create and initialize Direct3D objects. You use the Component Object Model (COM) interfaces that these objects implement to manipulate them and to create other objects required to render a scene. The CreateDevice sample project on which this tutorial is based illustrates these tasks by creating a Direct3D device and rendering a blue screen.

This tutorial uses the following steps to initialize Direct3D, render a scene, and eventually shut down.

Steps

  • Step 1: Creating a Window
  • Step 2: Initializing Direct3D
  • Step 3: Handling System Messages
  • Step 4: Rendering and Displaying a Scene
  • Step 5: Shutting Down

Note The path of the CreateDevice sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut01_CreateDevice.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Creating a Window

The first thing any Microsoft® Windows® application must do when it is run is to create an application window to display to the user. To do this, the CreateDevice sample project begins execution at its WinMain function. The following sample code performs window initialization.
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    // Register the window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      "D3D Tutorial", NULL };

    RegisterClassEx( &wc );

    // Create the application's window.
    HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 01: CreateDevice",
                              WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

The preceding code sample is standard Windows programming. The sample starts by defining and registering a window class called "D3D Tutorial." After the class is registered, the sample code creates a basic top-level window that uses the registered class, with a client area of 300 pixels wide by 300 pixels tall. This window has no menu or child windows. The sample uses the WS_OVERLAPPEDWINDOW window style to create a window that includes Minimize, Maximize, and Close buttons common to windowed applications. (If the sample were to run in full-screen mode, the preferred window style is WS_EX_TOPMOST, which specifies that the created window should be placed above all non-topmost windows and should stay above them, even when the window is deactivated). When the window is created, the code sample calls standard Microsoft® Win32® functions to display and update the window.

With the application window ready, you can begin setting up the essential Microsoft Direct3D® objects, as described in Step 2: Initializing Direct3D.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Initializing Direct3D

The CreateDevice sample project performs Microsoft® Direct3D® initialization in the InitD3D application-defined function called from WinMain after the window is created. After you create an application window, you are ready to initialize the Direct3D object that you will use to render the scene. This process includes creating the object, setting the presentation parameters, and finally creating the Direct3D device.

After creating a Direct3D object, use the IDirect3D9::CreateDevice method to create a device, and to enumerate devices, types, modes, and so on.

if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
    return E_FAIL;

The only parameter passed to Direct3DCreate9 should always be D3D_SDK_VERSION. This informs Direct3D that the correct header files are being used. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, Direct3DCreate9 will fail.

By filling in the fields of D3DPRESENT_PARAMETERS you can specify how you want your 3-D application to behave. The CreateDevice sample project sets Windowed to TRUE, SwapEffect to D3DSWAPEFFECT_DISCARD, and BackBufferFormat to D3DFMT_UNKNOWN.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

The final step is to use the IDirect3D9::CreateDevice method to create the Direct3D device, as illustrated in the following code example.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pd3dDevice ) ) )

The preceding code sample creates the device with the default adapter by using the D3DADAPTER_DEFAULT flag. In most cases, the system will have only a single adapter, unless it has multiple graphics hardware cards installed. Indicate that you prefer a hardware device over a software device by specifying D3DDEVTYPE_HAL for the DeviceType parameter. This code sample uses D3DCREATE_SOFTWARE_VERTEXPROCESSING to tell the system to use software vertex processing. Note that if you tell the system to use hardware vertex processing by specifying D3DCREATE_HARDWARE_VERTEXPROCESSING, you will see a significant performance gain on video cards that support hardware vertex processing.

Now that the Direct3D has been initialized, the next step is to ensure that you have a mechanism to process system messages, as described in Step 3: Handling System Messages.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Handling System Messages

After you have created the application window and initialized Microsoft® Direct3D®, you are ready to render the scene. In most cases, Microsoft Windows® applications monitor system messages in their message loop, and they render frames whenever no messages are in the queue. However, the CreateDevice sample project waits until a WM_PAINT message is in the queue, telling the application that it needs to redraw all or part of its window.

// The message loop.
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
    TranslateMessage( &msg );
    DispatchMessage( &msg );
}

Each time the loop runs, DispatchMessage calls MsgProc, which handles messages in the queue. When WM_PAINT is queued, the application calls Render, the application-defined function that will redraw the window. Then the Microsoft Win32® function ValidateRect is called to validate the entire client area.

The sample code for the message-handling function is shown below.

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            Render();
            ValidateRect( hWnd, NULL );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

Now that the application handles system messages, the next step is to render the display, as described in Step 4: Rendering and Displaying a Scene.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Rendering and Displaying a Scene

To render and display the scene, the sample code in this step clears the back buffer to a blue color, transfers the contents of the back buffer to the front buffer, and presents the front buffer to the screen.

To clear a scene, call the IDirect3DDevice9::Clear method.

// Clear the back buffer to a blue color
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );

The first two parameters accepted by IDirect3DDevice9::Clear inform Microsoft® Direct3D® of the size and address of the array of rectangles to be cleared. The array of rectangles describes the areas on the render target surface to be cleared.

In most cases, you use a single rectangle that covers the entire rendering target. You do this by setting the first parameter to 0 and the second parameter to NULL. The third parameter determines the method's behavior. You can specify a flag to clear a render-target surface, an associated depth buffer, the stencil buffer, or any combination of the three. This tutorial does not use a depth buffer, so D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer. The CreateDevice sample project sets the clear color for the render target surface to blue (D3DCOLOR_XRGB(0,0,255)). The final two parameters are ignored by the IDirect3DDevice9::Clear method because the corresponding flags are not present.

After clearing the viewport, the CreateDevice sample project informs Direct3D that rendering will begin, then it signals that rendering is complete, as shown in the following code fragment.

// Begin the scene.
g_pd3dDevice->BeginScene();

// Rendering of scene objects happens here.

// End the scene.
g_pd3dDevice->EndScene();

The IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene methods signal to the system when rendering is beginning or is complete. You can call rendering methods only between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene again.

After rendering the scene, you display it by using the IDirect3DDevice9::Present method.

g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

The first two parameters accepted by Present are a source rectangle and destination rectangle. The sample code in this step presents the entire back buffer to the front buffer by setting these two parameters to NULL. The third parameter sets the destination window for this presentation. Because this parameter is set to NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is used. The fourth parameter is the DirtyRegion parameter and in most cases should be set to NULL.

The final step for this tutorial is shutting down the application, as described in Step 5: Shutting Down.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Shutting Down

At some point during execution, your application must shut down. Shutting down a Microsoft® DirectX® application not only means that you destroy the application window, but you also deallocate any DirectX objects your application uses, and you invalidate the pointers to them. The CreateDevice sample project calls Cleanup, an application-defined function to handle this when it receives a WM_DESTROY message.

VOID Cleanup()
{
    if( g_pd3dDevice != NULL)
        g_pd3dDevice->Release();
    if( g_pD3D != NULL)
        g_pD3D->Release();
}

The preceding function deallocates the DirectX objects it uses by calling the IUnknown::Release methods for each object. Because this tutorial follows COM rules, the reference count for most objects should become zero and should be automatically removed from memory.

In addition to shutdown, there are times during normal execution—such as when the user changes the desktop resolution or color depth—when you might need to destroy and re-create the Microsoft Microsoft Direct3D® objects in use. Therefore it is a good idea to keep your application's cleanup code in one place, which can be called when the need arises.

This tutorial has shown you how to create a device. Tutorial 2: Rendering Vertices shows you how to use vertices to draw geometric shapes.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 2: Rendering Vertices

Applications written in Microsoft® Direct3D® use vertices to draw geometric shapes. Each three-dimensional (3-D) scene includes one or more of these geometric shapes. The Vertices sample project creates the simplest shape, a triangle, and renders it to the display.

This tutorial shows how to use vertices to create a triangle with the following steps:

Steps

  • Step 1: Defining a Custom Vertex Type
  • Step 2: Setting Up the Vertex Buffer
  • Step 3: Rendering the Display

Note The path of the Vertices sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut02_Vertices.

The sample code in the Vertices project is nearly identical to the sample code in the CreateDevice project. The Rendering Vertices tutorial focuses only on the code unique to vertices and does not cover initializing Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Defining a Custom Vertex Type

The Vertices sample project renders a 2-D triangle by using three vertices. This introduces the concept of the vertex buffer, which is a Microsoft® Direct3D® object that is used to store and render vertices. Vertices can be defined in many ways by specifying a custom vertex structure and corresponding custom flexible vertex format (FVF). The format of the vertices in the Vertices sample project is shown in the following code fragment.

struct CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; // The transformed position for the vertex.
    DWORD color;        // The vertex color.
};

The structure above specifies the format of the custom vertex type. The next step is to define the FVF that describes the contents of the vertices in the vertex buffer. The following code fragment defines a FVF that corresponds with the custom vertex type created above.

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

D3DFVF describe what type of custom vertex is being used. The sample code above uses the D3DFVF_XYZRHW and D3DFVF_DIFFUSE flags, which tell the vertex buffer that the custom vertex type has a transformed point followed by a color component.

Now that the custom vector format and FVF are specified, the next step is to fill the vertex buffer with vertices, as described in Step 2: Setting Up the Vertex Buffer.

Note The vertices in the Vertices sample project are transformed. In other words, they are already in 2-D window coordinates. This means that the point (0,0) is at the top-left corner and the positive x-axis is right and the positive y-axis is down. These vertices are also lit, meaning that they are not using Direct3D lighting but are supplying their own color.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Setting Up the Vertex Buffer

Now that the custom vertex format is defined, it is time to initialize the vertices. The Vertices sample project does this by calling the application-defined function InitVB after creating the required Microsoft® Direct3D® objects. The following code fragment initializes the values for three custom vertices.

CUSTOMVERTEX vertices[] =
{
    { 150.0f,  50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
    { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, },
    {  50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, },
};

The preceding code fragment fills three vertices with the points of a triangle and specifies which color each vertex will emit. The first point is at (150, 50) and emits the color red (0xffff0000). The second point is at (250, 250) and emits the color green (0xff00ff00). The third point is at (50, 250) and emits the color blue-green (0xff00ffff). Each of these points has a depth value of 0.5 and an RHW of 1.0.

The next step is to call IDirect3DDevice9::CreateVertexBuffer to create a vertex buffer as shown in the following code fragment.

if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
         0 /* Usage */, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB ) ) )
    return E_FAIL;

The first two parameters of IDirect3DDevice9::CreateVertexBuffer tell Direct3D the desired size and usage for the new vertex buffer. The next two parameters specify the vector format and memory location for the new buffer. The vector format here is D3DFVF_CUSTOMVERTEX, which is the flexible vertex format (FVF) that the sample code specified earlier. The D3DPOOL_DEFAULT flag tells Direct3D to create the vertex buffer in the memory allocation that is most appropriate for this buffer. The final parameter is the address of the vertex buffer to create.

After creating a vertex buffer, it is filled with data from the custom vertices as shown in the following code fragment.

VOID* pVertices;
if( FAILED( g_pVB->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 ) ) )
    return E_FAIL;
memcpy( pVertices, g_Vertices, sizeof(vertices) );
g_pVB->Unlock();

The vertex buffer is first locked by calling IDirect3DVertexBuffer9::Lock. The first parameter is the offset into the vertex data to lock, in bytes. The second parameter is the size of the vertex data to lock, in bytes. The third parameter is the address of a BYTE pointer, filled with a pointer to vertex data. The fourth parameter tells the vertex buffer how to lock the data.

The vertices are then copied into the vertex buffer using memcpy. After the vertices are in the vertex buffer, a call is made to IDirect3DVertexBuffer9::Unlock to unlock the vertex buffer. This mechanism of locking and unlocking is required because the vertex buffer may be in device memory.

Now that the vertex buffer is filled with the vertices, it is time to render the display, as described in Step 3: Rendering the Display.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Rendering the Display

Now that the vertex buffer is filled with vertices, it is time to render the display. Rendering the display starts by clearing the back buffer to a blue color and then calling BeginScene.

g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0L );
g_pd3dDevice->BeginScene();

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source; in this case, use stream 0. The source of the stream is specified by calling IDirect3DDevice9::SetStreamSource.

g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );

The first parameter to IDirect3DDevice9::SetStreamSource identifies the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the preceding sample code, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to call IDirect3DDevice9::SetFVF to identify the fixed function vertex shader. Full, custom vertex shaders are an advanced topic, but in this case the vertex shader is only the flexible vertex format (FVF) code. The following code fragment sets the FVF code.

g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

The only parameter for SetFVF is the fixed vertex function code to define the vertex data layout.

For more information about vertex shaders, see Vertex Shaders.

The next step is to use IDirect3DDevice9::DrawPrimitive to render the vertices in the vertex buffer as shown in the following code fragment.

g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The first parameter accepted by DrawPrimitive is a flag that tells Microsoft® Direct3D® what type of primitives to draw. This sample uses the flag D3DPT_TRIANGLELIST to specify a list of triangles. The second parameter is the index of the first vertex to load. The third parameter tells the number of primitives to draw. Because this sample draws only one triangle, this value is set to 1.

For more information about different kinds of primitives, see 3-D Primitives.

The last steps are to end the scene and then present the back buffer to the front buffer. This is shown in the following code fragment.

g_pd3dDevice->EndScene();
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

After the back buffer is presented to the front buffer, the client window shows a triangle with three different colored points.

This tutorial has shown you how to use vertices to render geometric shapes. Tutorial 3: Using Matrices introduces the concept of matrices and how to use them.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 3: Using Matrices

This tutorial introduces the concept of matrices and shows how to use them. The Vertices sample project rendered 2-D vertices to draw a triangle. However, in this tutorial you will be working with transformations of vertices in 3-D. Matrices are also used to set up cameras and viewports.

Before the Matrices sample project renders geometry, it calls the SetupMatrices application-defined function to create and set the matrix transformations that are used to render the 3-D triangle. Typically, three types of transformation are set for a 3-D scene. Steps for creating each one of these typical transformations are listed below.

Steps

  • Step 1: Defining the World Transformation Matrix
  • Step 2: Defining the View Transformation Matrix
  • Step 3: Defining the Projection Transformation Matrix

Note The path of the Matrices sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut03_Matrices.

The order in which these transformation matrices are created does not affect the layout of the objects in a scene. However, Microsoft® Direct3D® applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

The sample code in the Matrices project is nearly identical to the sample code in the Vertices project. The Using Matrices tutorial focuses only on the code unique to matrices and does not cover initializing Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Defining the World Transformation Matrix

The world transformation matrix defines how to translate, scale, and rotate the geometry in the 3-D model space.

The following code fragment rotates the triangle on the y-axis and then sets the current world transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matWorld;
D3DXMatrixRotationY( &matWorld, timeGetTime()/150.0f );
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

The first step is to rotate the triangle around the Y-axis by calling the D3DXMatrixRotationY method. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter is the angle of rotation in radians.

The next step is to call IDirect3DDevice9::SetTransform to set the world transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_WORLD macro to specify that the world transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about world transformations, see World Transformation.

After defining the world transformation for the scene, you can prepare the view transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

Defining the view transformation matrix is described in Step 2: Defining the View Transformation Matrix.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Defining the View Transformation Matrix

The view transformation matrix defines the position and rotation of the view. The view matrix is the camera for the scene.

The following code fragment creates the view transformation matrix and then sets the current view transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matView;
D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 3.0f,-5.0f ),
                              &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ),
                              &D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) );
g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

The first step is to define the view matrix by calling D3DXMatrixLookAtLH. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second, third, and fourth parameters define the eye point, look-at point, and "up" direction. Here the eye is set back along the z-axis by five units and up three units, the look-at point is set at the origin, and "up" is defined as the y-direction.

The next step is to call IDirect3DDevice9::SetTransform to set the view transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_VIEW flag to specify that the view transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about view transformations, see View Transformation.

After defining the world transformation for the scene, you can prepare the projection transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

Defining the projection transformation matrix is described in Step 3: Defining the Projection Transformation Matrix.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Defining the Projection Transformation Matrix

The projection transformation matrix defines how geometry is transformed from 3-D view space to 2-D viewport space.

The following code fragment creates the projection transformation matrix and then sets the current projection transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

The first step is to call D3DXMatrixPerspectiveFovLH to set up the projection matrix. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter defines the field of view, which tells how objects in the distance get smaller. A typical field of view is 1/4 pi, which is what the sample uses. The third parameter defines the aspect ratio. The sample uses the typical aspect ratio of 1. The fourth and fifth parameters define the near and far clipping plane. This determines the distance at which geometry should no longer be rendered. The Matrices sample project has its near clipping plane set at 1 and its far clipping plane set at 100.

The next step is to call IDirect3DDevice9::SetTransform to apply the transformation to the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_PROJECTION flag to specify that the projection transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about projection transformations, see Projection Transformation.

This tutorial has shown you how to use matrices. Tutorial 4: Creating and Using Lights shows how to add lights to your scene for more realism.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 4: Creating and Using Lights

Microsoft® Direct3D® lights add more realism to 3-D objects. When used, each geometric object in the scene will be lit based on the location and type of lights that are used. The sample code in this tutorial introduces the topics of lights and materials.

This tutorial has the following steps to create a material and a light.

Steps

  • Step 1: Initializing Scene Geometry
  • Step 2: Setting Up Material and Light

Note The path of the Lights sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut04_Lights.

The sample code in the Lights project is nearly identical to the sample code in the Matrices project. The Creating and Using Lights tutorial focuses only on the code unique to creating and using lights and does not cover setting up Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Initializing Scene Geometry

One of the requirements of using lights is that each surface has a normal. To do this, the Lights sample project uses a different custom vertex type. The new custom vertex format has a 3-D position and a surface normal. The surface normal is used internally by Microsoft® Direct3D® for lighting calculations.

struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The 3-D position for the vertex.
    D3DXVECTOR3 normal;   // The surface normal for the vertex.
};
// Custom FVF.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)

Now that the correct vector format is defined, the Lights sample project calls InitGeometry, an application-defined function that creates a cylinder. The first step is to create a vertex buffer that stores the points of the cylinder as shown in the following sample code.

// Create the vertex buffer.
if( FAILED( g_pd3dDevice->CreateVertexBuffer( 50*2*sizeof(CUSTOMVERTEX),
                                              0 /* Usage */, D3DFVF_CUSTOMVERTEX,
                                              D3DPOOL_DEFAULT, &g_pVB ) ) )
    return E_FAIL;

The next step is to fill the vertex buffer with the points of the cylinder. Note that in the following sample code, each point is defined by a position and a normal.

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);
    pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
    pVertices[2*i+0].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
    pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
    pVertices[2*i+1].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
}

After the preceding sample code fills the vertex buffer with the vertices for a cylinder, the vertex buffer is ready for rendering. But first, the material and light for this scene must be set up before rendering the cylinder. This is described in Step 2: Setting Up Material and Light.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Setting Up Material and Light

To use lighting in Microsoft® Direct3D®, you must create one or more lights. To determine which color a geometric object reflects, a material is created that is used to render geometric objects. Before rendering the scene, the Lights sample project calls SetupLights, an application-defined function that sets up one material and one directional light.

  • Creating a Material
  • Creating a Light

Creating a Material

A material defines the color that is reflected off the surface of a geometric object when a light hits it. The following code fragment uses the D3DMATERIAL9 structure to create a material that is yellow.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 0.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
g_pd3dDevice->SetMaterial( &mtrl );

The diffuse color and ambient color for the material are set to yellow. The call to the IDirect3DDevice9::SetMaterial method applies the material to the Direct3D device used to render the scene. The only parameter that IDirect3DDevice9::SetMaterial accepts is the address of the material to set. After this call is made, every primitive will be rendered with this material until another call is made to IDirect3DDevice9::SetMaterial that specifies a different material.

Now that material has been applied to the scene, the next step is to create a light.

Creating a Light

There are three types of lights available in Direct3D: point lights, directional lights, and spotlights. The sample code creates a directional light, which is a light that goes in one direction, and it oscillates the direction of the light.

The following code fragment uses the D3DLIGHT9 structure to create a directional light.

D3DXVECTOR3 vecDir;
D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

The following code fragment sets the diffuse color for this light to white.

light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;

The following code fragment rotates the direction of the light around in a circle.

vecDir = D3DXVECTOR3(cosf(timeGetTime()/360.0f),
                     0.0f,
                     sinf(timeGetTime()/360.0f) );
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

The call to D3DXVec3Normalize normalizes the direction vector used to determine the direction of the light.

A range can be specified to tell Direct3D how far the light will have an effect. This member does not affect directional lights. The following code fragment assigns a range of 1000 units to this light.

light.Range = 1000.0f;

The following code fragment assigns the light to the Direct3D device by calling IDirect3DDevice9::SetLight.

g_pd3dDevice->SetLight( 0, &light );

The first parameter that IDirect3DDevice9::SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, it will be overwritten by the new light. The second parameter is a pointer to the light structure that defines the light. The Lights sample project places this light at index 0.

The following code fragment enables the light by calling IDirect3DDevice9::LightEnable.

g_pd3dDevice->LightEnable( 0, TRUE);

The first parameter that IDirect3DDevice9::LightEnable accepts is the index of the light to enable. The second parameter is a Boolean value that tells whether to turn the light on (TRUE) or off (FALSE). In the sample code above, the light at index 0 is turned on.

The following code fragment tells Direct3D to render lights by calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );

The first two parameters that IDirect3DDevice9::SetRenderState accepts is which device state variable to modify and what value to set it to. This code sample sets the D3DRS_LIGHTING device variable to TRUE, which has the effect of enabling the rendering of lights.

The final step in this code sample is to turn on ambient lighting by again calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x00202020 );

The preceding code fragment sets the D3DRS_AMBIENT device variable to a light gray color (0x00202020). Ambient lighting will light up all objects by the given color.

For more information about lighting and materials, see Lights and Materials.

This tutorial has shown you how to use lights and materials. Tutorial 5: Using Texture Maps shows you how to add texture to surfaces.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 5: Using Texture Maps

While lights and materials add a great deal of realism to a scene, nothing adds more realism than adding textures to surfaces. Textures can be thought of as wallpaper that is shrink-wrapped onto a surface. You could place a wood texture on a cube to make it look like the cube is actually made of wood. The Texture sample project adds a banana peel texture to the cylinder created in Tutorial 4: Creating and Using Lights. This tutorial covers how to load textures, set up vertices, and display objects with texture.

This tutorial implements textures using the following steps:

Steps

  • Step 1: Defining a Custom Vertex Format
  • Step 2: Initializing Screen Geometry
  • Step 3: Rendering the Scene

Note The path of the Texture sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut05_Textures.

The sample code in the Texture project is nearly identical to the sample code in the Lights project, except that the Texture sample project does not create a material or a light. The Using Texture Maps tutorial focuses only on the code unique to textures and does not cover initializing Microsoft® Direct3D®, handling Microsoft Windows® messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Defining a Custom Vertex Format

Before using textures, a custom vertex format that includes texture coordinates must be used. Texture coordinates tell Microsoft® Direct3D® where to place a texture for each vector in a primitive. Texture coordinates range from 0.0 to 1.0, where (0.0, 0.0) represents the top-left side of the texture and (1.0, 1.0) represents the lower-right side of the texture.

The following sample code shows how the Texture sample project sets up its custom vertex format to include texture coordinates.

// A structure for our custom vertex type. Texture coordinates were added.
struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The position
    D3DCOLOR    color;    // The color
#ifndef SHOW_HOW_TO_USE_TCI
    FLOAT       tu, tv;   // The texture coordinates
#endif
};

// Our custom FVF, which describes our custom vertex structure
#ifdef SHOW_HOW_TO_USE_TCI
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
#else
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#endif

For more information about texture coordinates, see Texture Coordinates.

Now that a custom vertex type has been defined, the next step is to load a texture and create a cylinder, as described in Step 2: Initializing Screen Geometry.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Initializing Screen Geometry

Before rendering, the Texture sample project calls InitGeometry, an application-defined function that creates a texture and initializes the geometry for a cylinder.

Textures are created from file-based images. The following code fragment uses D3DXCreateTextureFromFile to create a texture from Banana.bmp that will be used to cover the surface of the cylinder.

if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, "Banana.bmp",
                                       &g_pTexture ) ) )
    return E_FAIL;

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to the Microsoft® Direct3D® device that will be used to render the texture. The second parameter is a pointer to an ANSI string that specifies the filename from which to create the texture. This sample specifies Banana.bmp to load the image from that file. The third parameter is the address of a pointer to a texture object.

When the banana texture is loaded and ready to use, the next step is to create the cylinder. The following code sample fills the vertex buffer with a cylinder. Note that each point has the texture coordinates (tu, tv).

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);

        pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
        pVertices[2*i+0].color    = 0xffffffff;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+0].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+0].tv       = 1.0f;
#endif

        pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
        pVertices[2*i+1].color    = 0xff808080;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+1].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+1].tv       = 0.0f;
#endif
}

Each vertex includes position, color, and texture coordinates. The code sample above sets the texture coordinates for each point so that the texture will wrap smoothly around the cylinder.

Now that the texture is loaded and the vertex buffer is ready for rendering, it is time to render the display, as described in Step 3: Rendering the Scene.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Rendering the Scene

After scene geometry has been initialized, it is time to render the scene. In order to render an object with texture, the texture must be set as one of the current textures. The next step is to set the texture stage states values. Texture stage states enable you to define the behavior of how a texture or textures are to be rendered. For example, you could blend multiple textures together.

The Texture sample project starts by setting the texture to use. The following code fragment sets the texture that the Microsoft® Direct3D® device will use to render with IDirect3DDevice9::SetTexture.

g_pd3dDevice->SetTexture( 0, g_pTexture );

The first parameter that IDirect3DDevice9::SetTexture accepts is a stage identifier to set the texture to. A device can have up to eight set textures, so the maximum value here is 7. The Texture sample project has only one texture and places it at stage 0. The second parameter is a pointer to a texture object. The Texture sample project uses the texture object that it created in its InitGeometry application-defined function.

The following code sample sets the texture stage state values by calling the IDirect3DDevice9::SetTextureStageState method.

    // Setup texture. Using textures introduces the texture stage states, which
    //   govern how textures get blended together (in the case of multiple
    //   textures) and lighting information. In this case, you are modulating
    //   (blending) your texture with the diffuse color of the vertices.
    g_pd3dDevice->SetTexture( 0, g_pTexture );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );

#ifdef SHOW_HOW_TO_USE_TCI
    // Note: To use Direct3D texture coordinate generation, use the stage state
    // D3DTSS_TEXCOORDINDEX, as shown below. In this example, you are using
    // the position of the vertex in camera space to generate texture
    // coordinates. The tex coord index (TCI) parameters are passed into a
    // texture transform, which is a 4x4 matrix that transforms the x,y,z
    // TCI coordinates into tu, tv texture coordinates.

    // In this example, the texture matrix is set up to
    // transform the texture from (-1,+1) position coordinates to (0,1)
    // texture coordinate space:
    //    tu =  0.5*x + 0.5
    //    tv = -0.5*y + 0.5
    D3DXMATRIXA16 mat;
    mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
    mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
    mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
    mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

    g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                  D3DTTFF_COUNT2 );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                  D3DTSS_TCI_CAMERASPACEPOSITION );
#endif

The first parameter that IDirect3DDevice9::SetTextureStageState accepts is the stage index for the state variable to be set. This code sample is changing the values for the texture at stage 0, so it puts a 0 here. The next parameter is the texture state to set. For a list of all valid texture states and their meaning, see D3DTEXTURESTAGESTATETYPE. The next parameter is the value to set the texture state to. The value that you place here is based on the texture stage state value that you are modifying.

After setting up the desired values for each texture stage state, the cylinder can be rendered and texture will be added to the surface.

Another way to use texture coordinates is to have them automatically generated. This is done by using a texture coordinate index (TCI). The TCI uses a texture matrix to transform the (x,y,z) TCI coordinates into (tu, tv) texture coordinates. In the Texture sample project, the position of the vertex in camera space is used to generate texture coordinates.

The first step is to create the matrix that will be used for the transformation, as demonstrated in the following code fragment.

D3DXMATRIX mat;
mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

After the matrix is created, it must be set by calling IDirect3DDevice9::SetTransform, as shown in the following code fragment.

g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );

The D3DTS_TEXTURE0 flag tells Direct3D to apply the transformation to the texture located at texture stage 0. The next step that this sample takes is to set more texture stage state values to get the desired effect. That is done in the following code fragment.

g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                  D3DTTFF_COUNT2 );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                  D3DTSS_TCI_CAMERASPACEPOSITION );

The texture coordinates are set up, and now the scene is ready to be rendered. Notice that the coordinates are automatically created for the cylinder. This particular setup gives the effect of the texture being laid over the rendering screen after the geometric shapes have been rendered.

For more information about textures, see Textures.

This tutorial has shown you how to use textures for surfaces. Tutorial 6: Using Meshes shows you how to use complex geometric shapes with meshes.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 6: Using Meshes

Complicated geometry is usually modeled using 3-D modeling software and saved to a file. An example of this is the .x file format. Microsoft® Direct3D® uses meshes to load the objects from these files. Meshes are somewhat complicated, but Direct3D extensions (D3DX) contains functions that make using meshes easier. The Meshes sample project introduces the topic of meshes and shows how to load, render, and unload a mesh.

This tutorial shows how to load, render, and unload a mesh using the following steps.

Steps

  • Step 1: Loading a Mesh Object
  • Step 2: Rendering a Mesh Object
  • Step 3: Unloading a Mesh Object

Note The path of the Meshes sample project is:

(SDK Root)\Samples\C++\Direct3D\Tutorials\Tut06_Meshes.

The sample code in the Meshes project is nearly identical to the sample code in the Lights project, except that the code in the Meshes project does not create a material or a light. The Using Meshes tutorial focuses only on the code unique to meshes and does not cover setting up Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.

This tutorial uses textures to cover the surface of the mesh. For more information about loading and using textures, see Tutorial 5: Using Texture Maps.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Loading a Mesh Object

A Microsoft® Direct3D® application must first load a mesh before using it. The Meshes sample project loads the tiger mesh by calling InitGeometry, an application-defined function, after loading the required Direct3D objects.

A mesh needs a material buffer that will store all the materials and textures that will be used. The function starts by declaring a material buffer as shown in the following code fragment.

LPD3DXBUFFER pD3DXMtrlBuffer;

The following code fragment loads the mesh.

// Load the mesh from the specified file
if( FAILED( D3DXLoadMeshFromX( "Tiger.x", D3DXMESH_SYSTEMMEM,
            g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL,
            &g_dwNumMaterials, &g_pMesh ) ) )
    {
    // If model is not in current folder, try parent folder
    if( FAILED( D3DXLoadMeshFromX( "..\\Tiger.x",
            D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL,
            &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials,
            &g_pMesh ) ) )
        {
            MessageBox(NULL, "Could not find tiger.x",
                       "Meshes.exe", MB_OK);
            return E_FAIL;
        }
    }

The first parameter is a pointer to a string that tells the name of the Microsoft DirectX® file to load. This sample loads the tiger mesh from Tiger.x.

The second parameter specifies how to create the mesh. The sample uses the D3DXMESH_SYSTEMMEM flag, which is equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM. Both of these flags put the index buffer and vertex buffer for the mesh in system memory.

The third parameter is a pointer to a device that will be used to render the mesh.

The fourth parameter is a pointer to an ID3DXBuffer object. This object will be filled with information about neighbors for each face. This information is not required for this sample, so this parameter is set to NULL.

The fifth parameter also takes a pointer to an ID3DXBuffer object. After this method is finished, this object will be filled with D3DXMATERIAL structures for the mesh.

The sixth parameter is a pointer to the number of D3DXMATERIAL structures placed into the ppMaterials array after the method returns.

The seventh parameter is the address of a pointer to a mesh object, representing the loaded mesh.

After loading the mesh object and material information, you need to extract the material properties and texture names from the material buffer.

The Meshes sample project does this by first getting the pointer to the material buffer. The following code fragment uses the ID3DXBuffer::GetBufferPointer method to get this pointer.

D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();

The following code fragment creates new mesh and texture objects based on the total number of materials for the mesh.

g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];
g_pMeshTextures  = new LPDIRECT3DTEXTURE9[g_dwNumMaterials];

For each material in the mesh the following steps occur.

The first step is to copy the material, as shown in the following code fragment.

g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

The second step is to set the ambient color for the material, as shown in the following code fragment.

g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;

The final step is to create the texture for the material, as shown in the following code fragment.

// Create the texture.
if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice,
   d3dxMaterials[i].pTextureFilename, &g_pMeshTextures[i] ) ) )
    g_pMeshTextures[i] = NULL;
}

After loading each material, you are finished with the material buffer and need to release it by calling IUnknown::Release.

pD3DXMtrlBuffer->Release();

The mesh, along with the corresponding materials and textures are loaded. The mesh is ready to be rendered to the display, as described in Step 2: Rendering a Mesh Object.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Rendering a Mesh Object

In step 1 the mesh was loaded and is now ready to be rendered. It is divided into a subset for each material that was loaded for the mesh. To render each subset, the mesh is rendered in a loop. The first step in the loop is to set the material for the subset, as shown in the following code fragment.

g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );

The second step in the loop is to set the texture for the subset, as shown in the following code fragment.

g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );

After setting the material and texture, the subset is drawn with the ID3DXBaseMesh::DrawSubset method, as shown in the following code fragment.

g_pMesh->DrawSubset( i );

The ID3DXBaseMesh::DrawSubset method takes a DWORD that specifies which subset of the mesh to draw. This sample uses a value that is incremented each time the loop runs.

After using a mesh, it is important to properly remove the mesh from memory, as described in Step 3: Unloading a Mesh Object.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Unloading a Mesh Object

After any Microsoft® DirectX® program finishes, it needs to deallocate any DirectX objects that it used and invalidate the pointers to them. The mesh objects used in this sample also need to be deallocated. When it receives a WM_DESTROY message, the Meshes sample project calls Cleanup, an application-defined function, to handle this.

The following code fragment deletes the material list.

if( g_pMeshMaterials )
    delete[] g_pMeshMaterials;

The following code fragment deallocates each individual texture that was loaded and then deletes the texture list.

if( g_pMeshTextures )
{
    for( DWORD i = 0; i < g_dwNumMaterials; i++ )
    {
        if( g_pMeshTextures[i] )
            g_pMeshTextures[i]->Release();
    }
delete[] g_pMeshTextures;

The following code fragment deallocates the mesh object.

Delete the mesh object
if( g_pMesh )
    g_pMesh->Release();

This tutorial has shown you how to load and render meshes. This is the last tutorial in this section. To see how a typical Microsoft Direct3D® application is written, see Samples.

© 2002 Microsoft Corporation. All rights reserved.


Samples

Microsoft® DirectX® provides sample applications that help make learning to use the graphics pipeline easier.

Sample Framework

The following samples are built on a base class that includes Microsoft Windows® and Microsoft Direct3D® functionality. This base class provides many of the basic features in a Windows application, such as creating windows and handling messages. The samples include a derived class that overrides the methods necessary to add Direct3D features, such as bump maps, vertex blending, and volume textures. For more information about the sample architecture, see Sample Framework.

DirectX C/C++ Samples

  • Billboard Sample
  • Bump Mapping Samples
    • Bump Earth Sample
    • Bump Lens Sample
    • Bump Underwater Sample
    • Bump Self-Shadow Sample
    • Bump Waves Sample
    • Dot Product 3 Sample
    • Emboss Sample
  • Clip Mirror Sample
  • Clip Volume Sample
  • Cull Sample
  • Depth Of Field Sample
  • Dolphin VS Sample
  • DXTex Tool
  • EffectEdit Sample
  • Environment Map Samples
    • Cube Map Sample
    • Fish Eye Sample
    • Sphere Map Sample
  • Lighting Sample
  • Lighting Sample - Vertex Shader
  • Mesh Samples
    • Enhanced Mesh Sample
    • Optimized Mesh Sample
    • Progressive Mesh Sample
    • Skinned Mesh Sample
  • MFC Fog Sample
  • MFC Tex Sample
  • Motion Blur Sample
  • Pick Sample
  • Point Sprites Sample
  • RT Patch Sample
  • ScreenSavers
    • Moire Sample
  • Stencil Buffer Samples
    • Shadow Volume Sample
    • Stencil Depth Sample
    • Stencil Mirror Sample
  • Text 3D Sample
  • Vertex Blend Sample
  • Vertex Shader Sample
  • Volume Texture Sample
  • Water Sample

The AppWizard is available to help generate DirectX applications.

Although DirectX samples include Microsoft Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

Related Topics

  • Sample Framework
  • Tutorials

© 2002 Microsoft Corporation. All rights reserved.


Sample Framework

The Microsoft® DirectX® 9.0 and Microsoft Direct3D® software development kit (SDK) graphics sample framework is an evolution from the DirectX 8.0 graphics sample framework. The SDK samples are installed by default in (SDK root)\Samples\C++\Multimedia. The folders of interest are Common and Direct3D. The sample framework is contained in the Common folder and the Direct3D samples, based on the graphics framework, are contained in the Direct3D folder.

The graphics framework consists of five source modules.

  • D3dapp.cpp exposes the application interface used for samples. Of particular interest is class CD3DApplication.
  • D3dfile.cpp furnishes .x file support, to enable samples to load .x files. Of particular interest are classes CD3DMesh and CD3DFrame.
  • D3dfont.cpp furnishes basic font output support, to enable things like statistics views. Of particular interest is class CD3DFont.
  • D3dutil.cpp provides generally useful three-dimensional functions, such as material, light, and texture helper functions.
  • Dxutil.cpp provides generally useful DirectX functions, such as media, registry, and timer helper functions.

Corresponding header files are located in the (SDK root)\Samples\C++\Common\Include folder.

Each sample implements a subclass of CD3DApplication, which is typically named CMyD3DApplication, and a set of overridable methods that are shown below.

// Overridable functions for the 3-D scene created by the application.
virtual HRESULT ConfirmDevice(D3DCAPS9*,DWORD,D3DFORMAT)   { return S_OK; }
virtual HRESULT OneTimeSceneInit()                         { return S_OK; }
virtual HRESULT InitDeviceObjects()                        { return S_OK; }
virtual HRESULT RestoreDeviceObjects()                     { return S_OK; }
virtual HRESULT FrameMove()                                { return S_OK; }
virtual HRESULT Render()                                   { return S_OK; }
virtual HRESULT InvalidateDeviceObjects()                  { return S_OK; }
virtual HRESULT DeleteDeviceObjects()                      { return S_OK; }
virtual HRESULT FinalCleanup()                             { return S_OK; }

/*
    The prototypes for these methods are contained in D3dapp.h in the
    CD3Dapplication class. The samples create a new
    application and override those methods that are needed by the
    application.
*/

Derived Class Example

This example uses a subset of the overridable methods. The class CMyD3DApplication contains the following methods. Each of these methods is explained below.

class CMyD3DApplication : public CD3DApplication
{
public:
    CMyD3DApplication();
protected:
    HRESULT ConfirmDevice( D3DCAPS9*, DWORD, D3DFORMAT );
    HRESULT DeleteRestoreDeviceObjects();
    HRESULT RestoreDeviceObjects();
    HRESULT FrameMove();
    HRESULT Render();
private:
    LPDIRECT3DVERTEXBUFFER9 m_pVB;         // Vertex buffer to hold vertices

Constructor

The constructor initializes the window title, enables depth buffering and initializes the vertex buffer.

CMyD3DApplication::CMyD3DApplication()
{
    m_strWindowTitle    = _T("D3D Example");    // title bar string
    m_bUseDepthBuffer   = TRUE;                 // enable depth buffer
    m_pVB               = NULL;                 // initialize
}

The window title is a wide character string that is visible in the title bar or the window class when the application is invoked. It is optional.

The base class contains a member variable for enabling depth buffering. The default value for this Boolean variable is FALSE, which disables depth buffering.

The window title is a TCHAR string that supports Unicode and ANSI characters. It is visible in the title bar when the application is invoked. The string will persist for the lifetime of CMyD3DApplication.

Confirm Devices

The prototype is as follows:

HRESULT ConfirmDevice(D3DCAPS *pCaps, DWORD dwBehavior,
              D3DFORMAT fmtBackBuffer)
}

[in] pCaps - Pointer to the D3DCAPS structure for the device to be confirmed. Examine the members of this structure to determine if the required capabilities for the application are present on the proposed device.

[in] dwBehavior - Zero or more flags corresponding to the behavior flag in IDirect3D9::CreateDevice. The following flags indicate the behavior of the proposed device.

D3DCREATE_PUREDEVICE
D3DCREATE_HARDWARE_VERTEXPROCESSING
D3DCREATE_SOFTWARE_VERTEXPROCESSING
D3DCREATE_MIXED_VERTEXPROCESSING
}

CD3DApplication will attempt to confirm a device behavior in the following order.

  • Pure device with hardware vertex processing.
  • Device with hardware vertex processing.
  • Device with mixed vertex processing.
  • Device with software vertex processing.

Only devices indicating support for a pure device will be confirmed with the pure device behavior.

Only devices indicating support for hardware transform and lighting will be confirmed for hardware vertex processing.

[in] fmtBackBuffer - Proposed format of the back buffer associated with the device's default swap chain.

When overriding this method, the application should return S_OK when the proposed device capabilities, behavior and back buffer format are acceptable. Otherwise, the application should return E_FAIL.

DeleteDeviceObjects

DeleteDeviceObjects is called when the application is exiting, or if the device is being changed. You use this method to delete device dependent objects, such as the vertex buffer.

HRESULT CVShader1::DeleteDeviceObjects()
{
    m_pQuadVB->Release();
    m_pQuadVB = NULL;
    return S_OK;

RestoreDeviceObjects

This method is called when the application needs to restore device memory objects and device states. This is required after a DirectX device is created or resized. This method does most of the work of creating objects and initializing render states.

HRESULT CMyD3DApplication::RestoreDeviceObjects()
{
    // Create the vertex buffer. Allocate enough memory (from the default pool)
    //   to hold the custom vertices. Specify the flexible vertex format (FVF),
    //   so the vertex buffer knows what data it contains.
    if( FAILED( m_pd3dDevice->CreateVertexBuffer(
                          NUM_VERTS*sizeof(CUSTOMVERTEX),
                          0,
                          D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVB ) ) )
    {
        return E_FAIL;
    }
    // Fill the vertex buffer. First, lock the vertex buffer to get access to
    //   the vertices. This mechanism is required because vertex buffers
    //   may be in device memory. Then use memcpy to do a fast data copy.
    VOID* pVertices;
    if( FAILED( m_pVB->Lock( 0, sizeof(g_Vertices),
     (BYTE**)&pVertices, 0 ) ) )
        return E_FAIL;
    memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );
    m_pVB->Unlock();

    // Set the projection matrix. The size of the back buffer comes from the
    //   base class.
    D3DXMATRIX matProj;
    FLOAT fAspect = m_d3dsdBackBuffer.Width /
                    (FLOAT)m_d3dsdBackBuffer.Height;
    D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, fAspect,
                                 1.0f, 100.0f );
    m_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

    // Set up the view matrix. A view matrix can be defined from an eye
    //   point, a look-at point, and an up-direction vector. In this example,
    //   the eye position is (0,1,-4) the look-at point is (0,0,0) and the
    //   up vector is (0,1,0).
    D3DXMATRIX matView;
    D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 1.0f,-4.0f ),
                                  &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ),
                                  &D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) );
    m_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

    // Set up default texture states.
    // Set up render states (this is only one example render state).
    m_pd3dDevice->SetRenderState( D3DRS_CULLMODE,     D3DCULL_NONE );

    return S_OK;

This method creates the vertex buffer and copies the vertex data into it. It creates the view and projection matrices, which define the camera orientation to the object in the vertex buffer. Texture stage states can be set in this method although none are present in this example. Render states that are not likely to change are set. These determine how the scene renders.

FrameMove

This method contains actions that happen every frame, such as animation. In this example, it adds a y-axis rotation to the world transform.

HRESULT CMyD3DApplication::FrameMove()
{
    // For our world matrix, just rotate the object about the y-axis.
    D3DXMATRIX matWorld;
    D3DXMatrixRotationY( &matWorld, ::TimeGetTime()/150.0f );
    m_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

    return S_OK;
}

The Windows method ::TimeGetTime returns the current time. When it is divided by 150, it generates an incremental angle to rotate the object.

Render

This method is called when it is time to render the output. It clears the view port and renders the scene and state changes.

HRESULT CMyD3DApplication::Render()
{
    // Clear the viewport.
    m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,
        D3DCOLOR_XRGB(0,0,0), 1.0f, 0L );

    // Begin the scene.
    if( SUCCEEDED( m_pd3dDevice->BeginScene() ) )
    {
        m_pd3dDevice->SetStreamSource( 0, m_pVB, sizeof(CUSTOMVERTEX) );
        m_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
        m_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, NUM_TRIS );
        m_pd3dDevice->EndScene();
    }

    return S_OK;
}

The Render method first clears the viewport using Clear. Then, within the BeginScene/EndScene pair, it uses SetStreamSource to inform the runtime that it uses vertex buffer m_pVB with a stride of the size of the custom vertex type. This method next informs the runtime that it uses a flexible vertex format (FVF) shader, the simplest type. Finally, it invokes DrawPrimitive to render the quad.

Other Functions

DeleteDeviceObjects is called when the application exits or if the device changes. Use this method to delete device-dependent objects.

ConfirmDevice checks the device for some minimum set of capabilities. It is called during the device initialization.

InvalidateDeviceObjects is called when the device dependent objects might be removed. Device dependent objects such as vertex buffers are usually added to this method.

OneTimeSceneInit is provided for code that needs to run during the initial application startup.

Discussion List

Where do you find other developers working with graphics? One place is the DirectX developer's mailing list. It is a technical discussion forum for DirectX developers covering the areas of graphics, networking, and input. Archives of the mailing list can be found at DirectX Dev World Wide Web link. Like any mailing list, this is not a technical support forum. However, it is a good source for information about DirectX.

© 2002 Microsoft Corporation. All rights reserved.


Billboard Sample

Description

The Billboard sample illustrates the billboarding technique. Rather than rendering complex 3-D models, such as a high-polygon tree model, billboarding renders a 2-D image of the model and rotates it to always face the eyepoint. This technique is commonly used to render trees, clouds, smoke, explosions, and more. For more information, see Billboarding.

In this sample, a camera flies around a 3-D scene with a tree-covered hill. The trees look like 3-D objects, but they are actually 2-D billboarded images that are rotated towards the eyepoint. The hilly terrain and the skybox, a six-sided cube containing sky textures, are objects loaded from .x files. They are used for visual effect and are unrelated to the billboarding technique.

Path

Source: (SDK root)\Samples\C++\Direct3D\Billboard

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The billboarding technique is the focus of this sample. The camera is moved in each frame, so the viewpoint changes accordingly. As the viewpoint changes, a rotation matrix is generated to rotate the billboards about the y-axis so that they face the new viewpoint. The computation of the billboard matrix occurs in the FrameMove function. The trees are also sorted in this function, as required for proper alpha blending, because billboards typically have some transparent pixels. The trees are rendered from a vertex buffer in the DrawTrees function.

The billboards in this sample are constrained to rotate about the y-axis only. Otherwise, the tree trunks would appear to not be fixed to the ground. For effects such as explosions in a 3-D flight simulator or space shooter, billboards are typically not constrained to one axis.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Bump Mapping Samples

  • Bump Lens Sample
  • Bump Underwater Sample
  • Bump Self-Shadow Sample
  • Bump Waves Sample
  • Dot Product 3 Sample
  • Emboss Sample

© 2002 Microsoft Corporation. All rights reserved.


Bump Earth Sample

Description

The Bump Earth sample demonstrates the bump mapping capabilities of Microsoft® Direct3D®. Bump mapping is a texture-blending technique that renders the appearance of rough, bumpy surfaces. This sample renders a rotating, bump-mapped planet Earth.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information about bump mapping, see Bump Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\BumpEarth

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Bump Lens Sample

Description

The Bump Lens sample demonstrates a lens effect that can be achieved using bump mapping. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces but can also be used for other effects, as shown here.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information about bump mapping, see Bump Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\BumpLens

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses bump mapping in a nontraditional fashion. Because bump mapping only perturbs an environment map, it can be used for other effects. In this case, it is used to perturb a background image, which can be rendered on the fly, to make a lens effect.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Bump Underwater Sample

Description

The Bump Underwater sample demonstrates an underwater effect that can be achieved using bump mapping. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces, but can also be used for other effects as shown here.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information about bump mapping, see Bump Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\BumpUnderWater

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses bump mapping in a nontraditional fashion. Because bump mapping only perturbs an environment map, it can be used for other effects. In this case, it is used to perturb a background image, which can be rendered on the fly, to make an underwater effect.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Bump Self-Shadow Sample

Description

This project includes all source and content for the self-shadowing bump-map algorithm presented at the 2001 Game Developers Conference (GDC). This application will run without pixel shaders, as long as the hardware has render targets and Dot Product 3. However, it runs with better visual results and much more efficiently with pixel shaders.

Not all cards support all features for bump-mapping techniques. Some hardware has no, or limited, bump-mapping support. For more information about bump mapping, see Bump Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\BumpSelfShadow

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
S | Zoom out
W | Zoom in

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contains values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Bump Waves Sample

Description

The Bump Waves sample demonstrates the bump mapping capabilities of Microsoft® Direct3D®. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces. This sample renders a waterfront scene with only four triangles. The waves in the scene are completely fabricated with a bump map.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information about bump mapping, refer to the Microsoft DirectX® software development kit (SDK) documentation.

This sample also uses a technique called projected textures, which is a texture-coordinate generation technique and is not the focal point of the sample. For more information about texture-coordinate generation, see Bump Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\BumpWaves

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

In this sample, bump mapping is used to generate waves in a scene. The backdrop is used as a projective texture for the environment map, so it reflects in the waves. The waves themselves appear to be generated with many polygons. However, it is one large quad.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Dot Product 3 Sample

Description

The Dot Product 3 sample demonstrates an alternative approach to Microsoft® Direct3D® bump mapping. This technique is named after the mathematical operation that combines a light vector with a surface normal. The normals for a surface are traditional (x,y,z) vectors stored in RGBA format in a texture map—called a normal map for this technique.

Not all cards support DotProduct3 blending texture stages, and not all cards support Direct3D bump mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\BumpMapping\DotProduct3

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The lighting equation for simulating bump mapping involves using the dot product of the surface normal and the lighting vector. The lighting vector is passed into the texture factor, and the normals are encoded in a texture map. The blend stages look like this:

SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_DOTPRODUCT3 );
SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TFACTOR );

The next step is to store the normals in the texture. To do this, the components of a vector (XYZW) are each turned from a 32-bit floating value into a signed 8-bit integer and packed into a texture color (RGBA). The code shows how to do this using a custom-generated normal map, as well as one built from a bump mapping texture image.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information about bump mapping, refer to the Microsoft DirectX® software development kit (SDK) documentation.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Emboss Sample

Description

The Emboss sample demonstrates an alternative approach to Microsoft® Direct3D® bump mapping. Embossing is done by subtracting the height map from itself and having texture coordinates that are slightly changed.

Not all cards support Direct3D bump mapping. Refer to the Microsoft DirectX® software development kit (SDK) documentation for more information.

Path

Source: (SDK root)\Samples\C++\Direct3D\Emboss

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL+E | Turns emboss effect on or off.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

In this sample, bump mapping is used to emboss the surface of the tiger.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Clip Mirror Sample

Description

The Clip Mirror sample demonstrates the use of custom-defined clip planes. A 3-D scene is rendered normally, and then in a second pass as if reflected in a planar mirror. Clip planes are used to clip the reflected scene to the edges of the mirror.

Path

Source: (SDK root)\Samples\C++\Direct3D\ClipMirror

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

The mouse is also used in this sample to control the viewing position.

Programming Notes

The main feature of this sample is the use of clip planes. The rectangular mirror has four edges, so four clip planes are used. Each plane is defined by the eyepoint and two vertices of one edge of the mirror. With the clip planes in place, the view matrix is reflected in the mirror's plane, and then the scene geometry (the teapot object) can be rendered as normal. Afterward, a semi-transparent rectangle is drawn to represent the mirror itself.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Clip Volume Sample

Description

The ClipVolume sample demonstrates a technique for using shaders to "subtract" a sphere from an arbitrary model when rendering. This technique could be useful in visualization applications to see inside complex objects. The sample also shows how to perform two-sided lighting.

Path

Source: (SDK root)\Samples\C++\Direct3D\ClipVolume

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows help or available commands.
F2 | Prompts the user to select a new rendering device or a new display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

The mouse is also used in this sample to control the viewing position.

Programming Notes

The sample creates two ID3DXMesh objects, one for the teapot and one for the sphere. A vertex shader and pixel shader are used when rendering the teapot, and a different vertex shader is used to render the sphere.

The sphere's vertex shader doesn't do anything unusual; it just performs the standard world-view projection transformation on the vertex position and sets the diffuse color to be dark blue with 50 percent alpha. Note that the sphere is drawn for illustration purposes only. The rendering of the sphere is not necessary to get the clipping effect shown in the sample.

The teapot's vertex shader does three tasks as follows:

  1. Standard transformation of the vertex positions through the world-view projection matrices.
  2. Computes each vertex's distance from the sphere center (stored in the c12 register), compares that distance from the sphere's radius (stored in c12.w), and stores the difference in oT0. The same float value goes into all four (xyzw) parts of oT0. All four components are written because the pixel shader instruction, texkill, reads all four components. Note that oT0's data will be negative inside the sphere radius, and positive outside the radius.
  3. Performs two-sided diffuse lighting on the teapot. It transforms the vertex normal through the rotation matrix, and sets r3.x to 1 if the vertex is front-facing, or to 0 if the vertex is back-facing. It then uses a mad instruction to set r5 to c92 + (r3.x * c91), so it will be red (c92) if r3.x is 0, or green (c91 + c92) if r3.x is 1. Finally, r5 is multiplied by the light intensity at that vertex, which is the absolute value of r3.z.

The teapot's pixel shader uses the texkill instruction to not render any pixel if any texture coordinate is less than zero. The x-texture coordinate will be negative for all vertices and pixels inside the sphere, so this prevents any pixels inside the sphere from being rendered.

This sample uses the sample framework code that is shared with other samples in the Microsoft® DirectX® software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Cull Sample

Description

This sample illustrates how to cull objects whose object bounding box (OBB) does not intersect the viewing frustum. By not passing these objects to Microsoft® Direct3D®, you save the time that would be spent by Direct3D transforming and lighting these objects, which will never be visible. The time saved could be significant if there are many such objects or if the objects contain many vertices.

More elaborate and efficient culling can be done by creating hierarchies of objects, with bounding boxes around groups of objects, so that not every object's OBB has to be compared to the view frustum.

It is more efficient to do this OBB/frustum intersection calculation in your own code than to use Direct3D to transform the OBB and check the resulting clip flags.

You can adapt the culling routines in this sample meet the needs of programs that you write.

Path

Source: (SDK root)\Samples\C++\Direct3D\Cull

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

When you run this program, you'll see a scene with teapots rendered into two viewports. The right viewport uses the view frustum that the code will cull against. The left viewport has an independent camera, and shows the right viewport's frustum as a visible object, so you can see where culling should occur. Fifty teapots are randomly placed in the scene and they are rendered along with their semitransparent OBBs.

The teapots are colored as follows to indicate their cull status.

Color | Description | Cull status
Dark green | The object was quickly determined to be inside the frustum. | CS_INSIDE
Light green | The object was determined after some work to be inside the frustum. | CS_INSIDE_SLOW
Dark red | The object was quickly determined to be outside the frustum. | CS_OUTSIDE
Light red | The object was determined after some work to be outside the frustum | CS_OUTSIDE_SLOW

You should see only green teapots in the right window. Note that most teapots are either dark green or dark red, indicating that the slower tests are not needed for the majority of cases.

To move the camera for the right viewport, click the right side of the window, then use the camera keys listed below to move around.

To move the camera for the left viewport, click on the left side of the window, then use the camera keys listed below to move around.

You can also rotate the teapots to set up particular relationships against the view frustum. You cannot move the teapots, but you can get the same effect by moving the frustum instead.

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
F1 | Shows help or available commands
F2 | Prompts the user to select a new rendering device or display mode
ALT+ENTER | Toggles between full-screen and windowed modes
ESC | Exits the application
W, S, ARROW KEYS | Moves the camera
Q, E, A, Z | Rotates the camera
Y, U, H, J | Rotates the teapots
N | Moves the left camera to match the right camera
M | Moves the right camera to its original position

Programming Notes

The OBB/viewport intersection algorithm used by this program is:

  1. If any OBB corner point is inside the frustum, return CS_INSIDE.
  2. Else if all OBB corner points are outside a single frustum plane, return CS_OUTSIDE.
  3. Else if any frustum edge penetrates a face of the OBB, return CS_INSIDE_SLOW.
  4. Else if any OBB edge penetrates a face of the frustum, return CS_INSIDE_SLOW.
  5. Else if any point in the frustum is outside any plane of the OBB, return CS_OUTSIDE_SLOW.
  6. Else return CS_INSIDE_SLOW.

The distinction between CS_INSIDE and CS_INSIDE_SLOW, and between CS_OUTSIDE and CS_OUTSIDE_SLOW, is provided here only for educational purposes. In a shipping application, you probably would combine the cull states into just CS_INSIDE and CS_OUTSIDE, because usually you need to know only whether the OBB is inside or outside the frustum.

The culling code shown here is written in a straightforward way for readability. It is not optimized for performance. Additional optimizations can be made, especially if the bounding box is a regular box (for example, the front and back faces are parallel). This algorithm could be generalized to work for arbitrary convex bounding hulls to allow tighter fitting against the underlying models.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Depth Of Field Sample

Description

This sample shows a technique for creating a depth-of-field effect, in which objects are only in focus at a given distance from the camera, and are out of focus at other distances.

Path

Source: (SDK root)\Samples\C++\Direct3D\DepthOfField

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows help or available commands.
F2 | Prompts the user to select a new rendering device or a new display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

The mouse is also used in this sample to control the viewing position.

Programming Notes

This sample makes use of the sample framework code that is shared with other samples in the Microsoft® DirectX® software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Dolphin VS Sample

Description

The Dolphin VS sample shows an underwater scene of a dolphin swimming, with caustic effects on the dolphin and sea floor. The dolphin is animated using a technique called tweening. The underwater effect uses fog, and the water caustics use an animated set of textures. These effects are achieved using vertex shaders.

Path

Source: (SDK root)\Samples\C++\Direct3D\DolphinVS

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Several things are happening in this sample.

  • Two vertex shaders are used: one for the dolphin and one for the sea floor. The vertex shaders are assembly instructions which are assembled from two files, DolphinTween.vsh and SeaFloor.vsh.
  • The dolphin is tweened—a form of morphing—by passing three versions of the dolphin down in multiple vertex streams. The vertex shader takes the weighted positions of each mesh and produces an output position. The vertex is then lit, texture coordinates are computed, and fog is added.
  • The sea floor is handled similarly, just with no need for tweening. The caustic effects are added in a separate alpha-blended pass, using an animated set of 32 textures. The texture coordinates for the caustics are generated in the vertex shaders, stored as TEXCOORDINDEX stage 1.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


DXTex Tool

Description

The Microsoft® DirectX® Texture (DXTex) tool enables DirectX software development kit (SDK) users to create texture maps that use the new DXTn compression formats. Creating a DXTn-compressed texture is not difficult. However, Microsoft Direct3D® can do the conversion for you when using the IDirect3DTexture9 interface. Advanced developers will probably want to write their own tools that meet their specific needs, but the DXTex tool provides useful basic functionality.

Functionality

  • Opens .bmp and Microsoft DirectDraw® surface (DDS) files. For more information, see DDS File Format in this topic.
  • Opens .bmp files as alpha channel, either explicitly or implicitly, using a filename_a.bmp naming convention.
  • Saves textures in DDS format.
  • Supports conversion to all five DXTn compression formats.
  • Supports generation of mipmaps, using a box filter.
  • Supports visualization of alpha channel as a grayscale image or through a user-selectable background color.
  • Supports easy visual comparison of image quality between formats.

Note that DXTex does not currently support textures with surface formats that do not contain at least an R, G, and B texture (such as D3DFMT_G16R16 and D3DFMT_A8), although Direct3D extensions (D3DX) can load and save such textures in DDS format.

Path

Source: (SDK root)\Samples\Multimedia\Direct3D\DXTex

Executable: (SDK root)\bin\dxutils

User Interface

DXTex uses a fairly traditional user interface (UI) in that each texture map is a document, and several documents can be open at one time. However, each document can hold the texture in either one or two formats simultaneously while the document is open in DXTex. For example, you can import a .bmp file, which automatically creates a 32-bit ARGB texture. You can then choose to convert the texture to DXT1 format. The document now has the image open in both formats, and you can switch between the formats by clicking the window. You can also switch by clicking Original View or New View on the View menu. This makes it easy for you to observe any artifacts introduced by image compression, and to try different compression formats without progressive degradation of the image. For example, if this technique is not used and you convert an image from ARGB to DXT1, all but one bit of alpha is lost.

If you then decide to convert to DXT2, there are still only two alpha levels. Using the DXTex system, the second conversion is done from the original ARGB format, and the DXT2 image will contain all 16 levels of alpha supported by DXT2. When the image is saved, the original format is discarded and only the new format is stored.

Keep in mind the following when using the DXTex interface.

  • If no format conversion has been requested since the document was opened, the one format is the original format - that is, the format in which the image will be written when the document is saved.
  • If format conversion has been requested since the document was opened, the converted format is the new format - that is, the format in which the image will be written when the document is saved.
  • If a second format conversion is requested, the new format from the first conversion is replaced with the second format. The original format will be unchanged.
  • Generating mipmaps applies to both formats simultaneously.
  • If the original format has multiple mipmaps and conversion to a new format is requested, the new format will automatically have multiple mipmaps as well.

Performance

DXTex uses the Direct3D Reference Rasterizer to draw the textures, regardless of what 3-D hardware is available. So with larger textures (greater than 256-by-256 pixels), the application may be somewhat slow, depending on your CPU speed.

DDS File Format

See DDS File Reference for more detailed information about the DDS file format.

Mipmaps

Mipmapping is a technique that improves image quality and reduces texture memory bandwidth by providing prefiltered versions of the texture image at multiple resolutions.

To generate mipmaps in DXTex, the width and height of the source image must both be powers of two. To do this, go to the Format menu and click Generate Mip Maps. Filtering is done through a simple box filter. That is, the four nearest pixels are averaged to produce each destination pixel.

Alpha

Many texture formats include an alpha channel, which provides opacity information at each pixel. DXTex fully supports alpha in textures. When you import a .bmp file, if there is a file of the same size with a name that ends in "_a" - for example, Sample.bmp and Sample_a.bmp - the second file is loaded as an alpha channel. The blue channel of the second .bmp is stored in the alpha channel. When a document is open, you can explicitly load a .bmp file as the alpha channel by clicking Open As Alpha Channel on the File menu.

To view the alpha channel directly, without the RGB channels, on the View menu, click Alpha Channel Only. The alpha channel appears as a grayscale image. If no alpha channel has been loaded, every pixel has a full alpha channel and the image appears solid white when viewing "Alpha Channel Only." To turn off alpha channel viewing, click the Alpha Channel Only command a second time.

In the usual view, the effect of the alpha channel is visible because the window has a solid background color that shows through the texture where the alpha channel is less than 100 percent. You can change this background color by clicking Change Background Color on the View menu. This choice does not affect the texture itself or the data that is written when the file is saved.

The DXT2 and DXT4 formats use premultiplied alpha. This means that the red, green, and blue values stored in the surface are already multiplied by the corresponding alpha value. Direct3D cannot copy from a surface that contains premultiplied alpha to one that contains non-premultiplied alpha, so some DXTex operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. Supporting textures using these formats is difficult on Direct3D devices that do not support DXTn textures. This is because Direct3D cannot copy them to a traditional ARGB surface either, unless that ARGB surface uses premultiplied alpha as well, which is rare. For this reason, you might find it easier to use DXT3 rather than DXT2, and DXT5 rather than DXT4 when possible.

Command-Line Options

You can use command-line options to pass input files, an output file name, and processing options to DXTex. If an output file name is specified, the application exits automatically after writing the output file, and no user interface is presented.

dxtex [infilename] [-a alphaname] [-m] [DXT1|DXT2|DXT3|DXT4|DXT5] [outfilename]

infilename:               Name of the file to load.  This can be a
                            .bmp or .dds file.

-a alphaname:             The next parameter is the name of a .bmp
                            file to load as the alpha channel. If no
                            alpha filename is specified, DXTex still
                            looks for a file named Infilename_a.bmp. If
                            it exists, use that file as the alpha
                            channel.

-m:                       Mipmaps are generated.

DXT1|DXT2|DXT3|DXT4|DXT5: Compression format. If no format is
                            specified, the image will be in ARGB-8888.

outfilename:              Name of the destination file. If this
                            option is not specified, the user interface
                            shows the current file and all requested
                            operations.  If an outfilename is specified,
                            the application exits after saving the
                            processed file without presenting a user
                            interface.

© 2002 Microsoft Corporation. All rights reserved.


EffectEdit Sample

Description

The EffectEdit sample implements a tool that allows easy experimentation with Effects. Effects provide a convenient way to package multiple techniques for rendering an object, including render states, vertex shaders, pixel shaders, and multiple passes. Using EffectEdit, you can load effect files, edit them, and see an object rendered with the effect. Changes to the effect are reflected immediately on the rendered object.

Note that not all effect files will work well with EffectEdit. Effects that need a lot of parameters to be set by the application will probably not work well. EffectEdit sets only a limited number of parameters as follows:

  • Parameters with the WORLD semantic will contain the world matrix.
  • Parameters with the VIEW semantic will contain the view matrix.
  • Parameters with the PROJECTION semantic will contain the projection matrix.
  • Parameters with the WORLDVIEW semantic will contain the world*view matrix.
  • Parameters with the VIEWPROJECTION semantic will contain the view*projection matrix.
  • Parameters with the WORLDVIEWPROJECTION semantic will contain the world*view*projection matrix.
  • Parameters with the NAME annotation will cause a texture with the given name to be loaded.
  • Parameters with the FUNCTION annotation will cause a procedural texture with the given name to be loaded and used to initialize the texture.
  • Parameters with the TARGET annotation will cause the procedural texture to use the specified instruction set (Default is "tx_1_0").
  • Parameters with the WIDTH annotation will cause the texture to have the specified width.
  • Parameters with the HEIGHT annotation will cause the texture to have the specified height.
  • An integer parameter named BCLR will be used to define the background color of the scene.
  • A string parameter named BIMG will be used to define a background image for the scene.
  • A string parameter named XFile will be used to load an .x file containing the object to be rendered.

Path

Source: (SDK root)\Samples\C++\Direct3D\EffectEdit

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The user interface is a window divided into four panes. You can press CTRL+TAB to change the keyboard focus between these panes.

The Effect file source code pane shows the source code for the current effect and provides text editing capability.

The Effect compilation results pane shows the results of compiling the current effect. You can double-click on errors to jump to the offending line in the source code pane. If there are no errors, the results pane will say "Compilation successful!" and you should see the rendered object.

The Rendered scene pane shows the rendered object, using the current effect. You can drag the left mouse button to rotate the object, the right mouse button to move the object, and click the scroll wheel to zoom the object.

The Rendering options pane lets you change various aspects of how the object is rendered. The Reset Camera button moves the camera back to the default position and orientation.

Programming Notes

EffectEdit is an Microsoft Foundation Classes (MFC) application, using the single-document model. CEffectDoc is the class representing the document, which is mainly just the text contents of the effect. CMainFrame manages the display of the four different views used on this document, and the splitter windows that control the panes containing the views. CTextView is the text editor, CErrorsView is the compilation results, COptionsView is the rendering options, and CRenderView is the rendered output. Only the last class really uses Microsoft® Direct3D® and Direct3D code. CRenderView is derived from both CFormView and CD3DApplication, so it can use familiar methods like FrameMove, InitDeviceObjects, etc.

This sample uses the sample framework code that is shared with other samples in the Microsoft DirectX® software development kit (SDK). All common headers and source code can be found at (SDK root)\DXSDK\Samples\C++\Common.

© 2002 Microsoft Corporation. All rights reserved.


Environment Map Samples

  • Cube Map Sample
  • Fish Eye Sample
  • Sphere Map Sample

© 2002 Microsoft Corporation. All rights reserved.


Cube Map Sample

Description

The Cube Map sample demonstrates an environment-mapping technique called cube mapping. Environment mapping is a technique in which the environment surrounding a 3-D object, such as the lights, is put into a texture map so that the object can have complex lighting effects without the time-consuming lighting calculations.

Not all cards support all features for environment-mapping techniques such as cube mapping and projected textures. For more information about environment mapping, see Environment Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\EnvMapping\CubeMap

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Cube mapping is a technique that employs a six-sided texture. To visualize the effects of this technique, imagine a wallpapered room in which the wallpaper has been shrink-wrapped around an object. Cube mapping is superior to sphere-mapping because the latter is inherently view dependent; sphere maps are constructed for one particular viewpoint in mind. Cube maps also have no geometry distortions so they can be generated on the fly using IDirect3DDevice9::SetRenderTarget for all six cube map faces.

Cube mapping works with Microsoft® Direct3D® texture coordinate generation. By setting D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR, Direct3D generates cube map texture coordinates from the reflection vector for a vertex, thereby making this technique easy for environment mapping effects where the environment is reflected in the object.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Fish Eye Sample

Description

The Fish Eye sample shows a fish-eye lens effect that can be achieved using cube maps.

Path

Source: (SDK root)\Samples\C++\Direct3D\EnvMapping\FishEye

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The FishEye sample scene is rendered into the surfaces of a cube map, rather than the back buffer. Then the cube map is used as an environment map to reflect the scene in some distorted geometry—in this case, some geometry approximating a fish eye lens. See the Cube Map Sample for more information about cube mapping.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Sphere Map Sample

Description

The Sphere Map sample demonstrates an environment mapping technique called sphere mapping. Environment mapping is a technique in which the environment surrounding a 3-D object, such as the lights, are put into a texture map so that the object can have complex lighting effects without time-consuming lighting calculations.

Not all cards support all features for environment-mapping techniques such as cube mapping and projected textures. For more information about environment mapping, see Environment Mapping.

Path

Source: (SDK root)\Samples\C++\Direct3D\EnvMapping\SphereMap

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Sphere-mapping uses a precomputed (at model time) texture map that contains the entire environment as reflected by a chrome sphere. The idea is to consider each vertex, compute its normal, find where the normal matches on the chrome sphere, and then assign that texture coordinate to the vertex.

Although the math is not complicated, this involves computations for each vertex for every frame. Microsoft® Direct3D® has a texture-coordinate generation feature that you can use to do this. The relevant render state operation is D3DTSS_TCI_CAMERASPACENORMAL, which takes the normal of the vertex in camera space and puts it through a texture transform to generate texture coordinates. Then you set up the texture matrix to do the rest. In this simple case, the matrix only has to scale and translate the texture coordinates to get from camera space (-1, +1) to texture space (0,1).

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Lighting Sample

Description

The Lighting sample show how to use Microsoft® Direct3D® lights when rendering. It shows the difference between the various types of lights—ambient, point, directional, and spot—how to configure these lights, and how to enable and disable them.

Note This sample does not include textures, to make it easier to see the detail of the lighting.

Path

Source: (SDK root)\Samples\C++\Direct3D\Lighting

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
UP ARROW, DOWN ARROW | Increase or decrease vertices in walls.
W | Wireframe mode.
S | Solid mode.
ESC | Exits the application.

Programming Notes

Direct3D lights can be used to shade and color objects that are rendered. They modify the color at each vertex of the primitives rendered while the lights are active. Note that the walls and floor of this sample contain many vertices, so the lighting is fairly detailed. If the vertices were only at the corners of the walls and floor, the lighting effects would be much rougher because of the reduced number of vertices. You can modify the m_m and m_n member variables in this program to see how the vertex count affects the lighting of the surfaces.

There are ways to generate lighting effects other than by using Direct3D lights. Techniques like light mapping can create lighting effects that are not limited to being computed only at each vertex. Vertex shaders can generate more unusual, realistic, or customized lighting at each vertex. Pixel shaders can perform lighting computation at each pixel of the polygons being rendered.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Lighting Sample - Vertex Shader

Description

The LightingVS sample is an extension of the Lighting Sample that adds vertex shader implementations of lighting. It lets you add multiple lights and compare the output and performance between the vertex shader lights and the fixed-function pipeline lights.

Path

Source: (SDK root)\Samples\C++\Direct3D\LightingVS

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The vertex shader is in the media directory and is called LightingVS.fx.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Mesh Samples

  • Enhanced Mesh Sample
  • Optimized Mesh Sample
  • Progressive Mesh Sample
  • Skinned Mesh Sample

© 2002 Microsoft Corporation. All rights reserved.


Enhanced Mesh Sample

Description

The Enhanced Mesh sample shows how to use Direct3D extensions (D3DX) to load and enhance a mesh. The mesh is enhanced by increasing the vertex count.

Path

Source: (SDK root)\Samples\C++\Direct3D\EnhancedMesh

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
UP or DOWN ARROW | Increase or decrease the vertex count.
W | Toggle wireframe mode.
S | Toggle solid mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Optimized Mesh Sample

Description

The Optimized Mesh sample illustrates how to load and optimize a file-based mesh using the Direct3D extensions (D3DX) mesh utility functions.

For more information about D3DX, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\OptimizedMesh

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL+O | Opens the mesh file.
CTRL+M | Toggles the optimized mesh.

Programming Notes

Many Microsoft Direct3D® samples in the DirectX SDK use file-based meshes. However, the OptimizedMesh sample is a good example of the basic code necessary for loading a mesh. The D3DX mesh loading functionality collapses the frame hierarchy of an .x file into one mesh.

For other samples, the bare bones D3DX mesh functionality is wrapped in a common class CD3DMesh. If you want to keep the frame hierarchy, you can use the common class CD3DFile.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Progressive Mesh Sample

Description

The Progressive Mesh sample illustrates how to load and optimize a file-based mesh using the Direct3D extensions (D3DX) mesh utility functions. A progressive mesh is one in which the vertex information is stored internally in a special tree that can be accessed to render the mesh with any number of vertices. This procedure is fast, so progressive meshes are ideal for level-of-detail scenarios, where objects in the distance are rendered with fewer polygons.

For more information about D3DX, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\ProgressiveMesh

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
UP ARROW | Adds one vertex to the progressive mesh.
DOWN ARROW | Subtracts one vertex from the progressive mesh.
PAGE UP | Adds 100 vertices to the progressive mesh.
PAGE DOWN | Subtracts 100 vertices from the progressive mesh.
HOME | Displays all available vertices for the progressive mesh.
END | Displays the minimum vertices for the progressive mesh.

Programming Notes

Many Microsoft Direct3D® samples in the DirectX SDK use file-based meshes. However, the ProgressiveMesh sample is a good example of the basic code necessary for loading a mesh. The D3DX mesh loading functionality collapses the frame hierarchy of an .x file into one mesh.

The primary reason to use progressive meshes is the call to ID3DXPMesh::SetNumVertices for the mesh.

For other samples, the basic D3DX mesh functionality is wrapped in a common class CD3DMesh. To keep the frame hierarchy, you can use the common class CD3DFile.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Skinned Mesh Sample

Description

The Skinned Mesh sample shows how to load and render a skinned mesh.

Path

Source: (SDK root)\Samples\C++\Direct3D\SkinnedMesh

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


MFC Fog Sample

Description

The MFC Fog sample illustrates how to use Microsoft® Direct3D® with Microsoft Foundation Classes (MFC), using a CFormView. Various controls are used to control fog parameters for the 3-D scene.

Path

Source: (SDK root)\Samples\C++\Direct3D\MFCFog

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

All user interaction for this sample is implemented through the visible MFC controls—sliders, radio buttons, and so on. You are encouraged to play with the controls and observe the various effects they have on the rendered 3-D scene.

Programming Notes

All the MFC code is contained with the CFormView class's derived member functions. You can find the MFC code and Direct3D initialization code in the D3dapp.cpp source file. This file can be ported to work with another application by stripping out the fog-related code.

The Direct3D fog code is contained in Fog.cpp. It includes functions to initialize, animate, render, and clean up the scene.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


MFC Tex Sample

Description

The Microsoft Foundation Classes (MFC) Tex sample illustrates how to use Microsoft® Direct3D® with MFC, using a CFormView. Various controls are used to the control the texture appearance.

Path

Source: (SDK root)\Samples\C++\Direct3D\MFCTex

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

All user interaction for this sample is implemented through the visible MFC controls—sliders, radio buttons, and so on. You are encouraged to play with controls and observe the various effects they have on the rendered 3-D scene.

Programming Notes

All the MFC code is contained with the CFormView class's derived member functions. You can find the MFC code and Direct3D initialization code in the D3dapp.cpp source file. This file can be ported to work with another application by stripping out the fog-related code.

The Direct3D fog code is contained in Fog.cpp. It includes functions to initialize, animate, render, and clean up the scene.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Motion Blur Sample

Description

The MotionBlur sample demonstrates a vertex shader that creates a motion blur effect by stretching some vertices along the direction of motion and fading their transparency.

Path

Source: (SDK root)\Samples\C++\Direct3D\MotionBlur

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
UP ARROW | Increase the motion blur trail length.
DOWN ARROW | Decrease the motion blur trail length.
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or a new display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

The mouse is also used in this sample to control the viewing position.

Programming Notes

The sample shows two spheres, both represented by the same ID3DXMesh object. The spheres move in an ellipse, and each sphere remembers the matrix for its current position and last-computed position. Each sphere is rendered once using the "normal" (ordinary) shader, and once using the motion-blur shader.

The motion-blur shader starts by transforming the vertex position (v0) through the last-frame world matrix (c0) and the current-frame world matrix (c4), and stores the results in r0 and r1. The normal vector (v1) is also transformed through the current-frame world matrix (c4) and the result is stored in r2.

r3 gets the motion delta vector from r0 to r1, and is normalized. Then r4.x gets set to the dot product of the vertex normal and the motion delta vector. So the closer the vertex normal is to the motion delta vector, the larger r4.x will be for that vertex. If r4.x is less than zero, the vertex normal points away from the motion delta vector. Only these vertices will be blurred.

In the next section, r4.y gets set to 1 if r4.x is less than zero (c20.y), or 0 if r4.x is zero or positive. So the motion blur will only be applied to vertices whose normal faces away from the direction of motion. If r4.y is zero, r1 is unchanged. If r4.y is 1, r1 will get -r3 (the motion direction) added to it.

Next r1 is transformed through the rotation and projection matrices, and the result goes into oPos.

Finally, the diffuse color is computed and stored in oD0, with oD0's alpha being set to 0 if r4.x (the dot product of the vertex normal and the direction of motion) is negative, or 1 otherwise. This makes the blur fade out as it gets further from the real object.

This sample uses the sample framework code that is shared with other samples in the Microsoft® DirectX® software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Pick Sample

Description

The Pick sample shows how to implement picking; that is, finding which triangle in a mesh is intersected by a ray. In this case, the ray comes from mouse coordinates.

Path

Source: (SDK root)\Samples\C++\Direct3D\Pick

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Use the mouse to pick any spot in the mesh to see that triangle.

Programming Notes

When you click the mouse, the code reads the screen coordinates of the cursor. These coordinates are converted, through the projection and view matrices, into a ray that goes from the eyepoint through the point clicked on the screen and into the scene. This ray is passed to IntersectTriangle along with each triangle of the loaded model to determine which triangles, if any, are intersected by the ray. The texture coordinates of the intersected triangle is also determined.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Point Sprites Sample

Description

The Point Sprites sample shows how to use the new Microsoft® Direct3D® point sprites feature. A point sprite is a forward-facing, textured quad that is referenced only by (x,y,z) position coordinates. Point sprites are most often used for particle systems and related effects.

Not all cards support all features for point sprites. For more information about point sprites, refer to the Microsoft DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\PointSprites

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
F3 | Animates the emitter.
F4 | Changes color.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Without Direct3D support, point sprites can be implemented with four vertices that are oriented each frame towards the eyepoint, much like a billboard. With Direct3D, though, you can refer to each point sprite just by its center position and a radius. This saves processor computation time and bandwidth when uploading vertex information to the graphics card.

In this sample, each particle is implemented using multiple alpha-blended point sprites, giving the particle a motion-blur effect.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


RT Patch Sample

Description

The RT Patch sample shows how uses patches in Microsoft® Direct3D®.

Path

Source: (SDK root)\Samples\C++\Direct3D\RTPatch

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
UP ARROW | Increase number of patches per segment.
DOWN ARROW | Decrease number of patches per segment.
W | Toggles the wireframe.

Programming Notes

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


ScreenSavers

  • Moire Sample

© 2002 Microsoft Corporation. All rights reserved.


Moire Sample

Description

The Moire sample shows how to use the Microsoft® Direct3D® software development kit (SDK) screen saver framework to write a screen saver that uses Direct3D. The screen saver framework is similar to the sample application framework, using many methods and variables with the same names. After writing a program with the screen saver framework, you end up with a fully-functional Microsoft Windows® screen saver, rather than with a regular Windows application.

The moire screen saver appears as a mesmerizing sequence of spinning lines and colors. It uses texture transformation and alpha blending to create a highly animated scene, even though the polygons that make up the scene do not move at all.

Path

Source: (SDK root)\Samples\C++\Direct3D\ScreenSavers\Moire

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

Moire.scr can be started in five modes: configuration, preview, full, test, and password change. You can choose some modes by clicking the right mouse button (right-click) on the Moire.scr file and choosing Configure or Preview. Or you can start Moire.scr from the command line with the following command-line parameters:
-c | Configuration mode
-t | Test mode
-p | Preview mode
-a | Password-change mode
-s | Full mode

When the screen saver is running in full mode, press any key or move the mouse to exit.

Programming Notes

Programs that use the screen saver framework are very similar to programs that use the Direct3D sample application framework. Each screen saver needs to create a class derived from the main application class, CD3DScreensaver. To provide functionality specific to each screen saver, the screen saver implements its own versions of the virtual functions FrameMove, Render, InitDeviceObjects, and so forth.

Screen savers can be written to be multimonitor-compatible, without much extra effort. If you do not want your screen saver to run on multiple monitors, you can just set the m_bOneScreenOnly variable to TRUE. This value is set to FALSE by default. The function SetDevice will be called each time the device changes. The way that moire deals with this is to create a structure called DeviceObjects, which contains all device-specific pointers and values. CMoireScreensaver holds an array of DeviceObjects structures, called m_DeviceObjectsArray. When SetDevice is called, m_pDeviceObjects is changed to point to the DeviceObjects structure for the specified device. When rendering, m_rcRenderTotal refers to the rendering area that spans all monitors, and m_rcRenderCurDevice refers to the rendering area for the current device's monitor. The function SetProjectionMatrix shows one way to set up a projection matrix that makes proper use of these variables to either render a scene that spans all the monitors, or display a copy of the scene on each monitor. The projection matrix used depends on the value of m_bAllScreensSame, which you can enable the user to control in the configuration dialog.

The ReadSettings function is called by the screen saver framework at program startup time, to read various screen saver settings from the registry. DoConfig is called when the user wants to configure the screen saver settings. The program should respond to this by creating a dialog box with controls for the various screen saver settings. This dialog box should also have a button called Display Settings which, when pressed, should call DoScreenSettingsDialog. This common dialog box allows the user to configure what renderer and display mode should be used on each monitor. You should set the member variable m_strRegPath to a registry path that will hold the screen saver's settings. You can use this variable in your registry read/write functions. The screen saver framework will also use this variable to store information about the default display mode in some cases.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Stencil Buffer Samples

  • Enhanced Mesh Sample
  • Optimized Mesh Sample
  • Progressive Mesh Sample
  • Skinned Mesh Sample

© 2002 Microsoft Corporation. All rights reserved.


Shadow Volume Sample

Description

The Shadow Volume sample uses stencil buffers to implement real-time shadows. In the sample, a complex object is rendered and used as a shadow caster to cast real-time shadows on itself and on the terrain below.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Not all cards support all features for stencil-buffer techniques. Some hardware has no, or limited, stencil-buffer support. For more information about stencil buffers, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\StencilBuffer\ShadowVolume

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Creating real-time shadows is a fairly advanced technique. In each frame, or as the geometry or lights in the scene are moved, an object called a shadow volume is computed. A shadow volume is a 3-D object that is the silhouette of the shadowcasting object, as protruded away from the light source.

In this sample, the 3-D object that casts shadows is a bi-plane. The silhouette of the plane is computed in each frame. This technique uses an edge-detection algorithm in which silhouette edges are found. This can be done because the normals of adjacent polygons will have opposing normals with respect to the light vector. The resulting edge list (the silhouette) is protruded into a 3-D object away from the light source. This 3-D object is known as the shadow volume, as every point inside the volume is inside a shadow.

Next, the shadow volume is rendered into the stencil buffer twice. First, only forward-facing polygons are rendered, and the stencil-buffer values are incremented each time. Then the back-facing polygons of the shadow volume are drawn, decrementing values in the stencil buffer. Normally, all incremented and decremented values cancel each other out. However, because the scene was already rendered with normal geometry, in this case the plane and the terrain, some pixels fail the z-buffer test as the shadow volume is rendered. Any values left in the stencil buffer correspond to pixels that are in the shadow.

Finally, these remaining stencil-buffer contents are used as a mask, as a large all-encompassing black quad is alpha-blended into the scene. With the stencil buffer as a mask, only pixels in shadow are darkened

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Stencil Depth Sample

Description

The Stencil Depth sample uses stencil buffers to display the depth complexity of a scene. The depth complexity of a scene is defined as the average number of times each pixel is rendered.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Path

Source: (SDK root)\Samples\C++\Direct3D\StencilBuffer\StencilDepth

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Displaying depth complexity is a valuable tool to analyze the performance of a scene. Scenes that draw the same pixels more than once can benefit from some scene optimization such as sorting the geometry in a front-to-back order.

Not all cards support all features for stencil-buffer techniques. Some hardware has no, or limited, stencil buffer support. For more information about stencil buffers, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Stencil Mirror Sample

Description

The Stencil Mirror sample uses stencil buffers to implement a mirror effect. In the sample, a watery terrain scene is rendered with the water reflecting a helicopter that flies above.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Not all cards support all features for stencil buffer techniques. Some hardware has no, or limited, stencil buffer support. For more information about stencil buffers, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\StencilBuffer\StencilMirror

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

In this sample, a stencil buffer is used to create the effect of a reflection coming off the water. The geometry of the water is rendered into the stencil buffer. Then the stencil buffer is used as a mask to render the scene again, this time with the geometry translated and rendered upside down, to appear as if it were reflected in the mirror.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Text 3D Sample

Description

The Text 3D sample shows how to draw 2-D text in a 3-D scene. This is useful for displaying statistics or game menus, for example.

Path

Source: (SDK root)\Samples\C++\Direct3D\Text3D

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses the common class, CD3DFont, to display 2-D text in a 3-D scene. The source code for the class is of most interest to this sample. The class uses Microsoft® Windows® Graphics Device Interface (GDI) to load a font and output each letter to a bitmap. That bitmap, in turn, is used to create a texture.

When the CD3DFont class's DrawText function is called, a vertex buffer is filled with polygons that are textured using the font texture created as mentioned above. The polygons may be drawn as a 2-D overlay—useful, for example, for printing statistics—or truly integrated in the 3-D scene.

This sample uses common Microsoft DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Blend Sample

Description

The Vertex Blend sample demonstrates a technique called vertex blending, also known as surface skinning. It displays a file-based object that is made to bend in various spots.

Vertex blending is used for creating effects such as smooth joints and bulging muscles in character animations.

Not all cards support all features for vertex blending. For more information about vertex blending, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\VertexBlend

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL+V | Switches between a custom vertex shader and Microsoft Direct3D® vertex blending.

Programming Notes

Vertex blending requires each vertex to have an associated blend weight. Multiple world transforms are set up using SetTransformState and the blend weights determine how much contribution each world matrix has when positioning each vertex.

In this sample, a mesh is loaded using the common helper code. Note how a custom vertex and a custom flexible vertex format (FVF) is declared and used to build the mesh; see the SetFVF call for the mesh object. Without using the mesh helper code, the technique is the same. Create a vertex buffer full of vertices that have a blend weight, and use the appropriate FVF.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader Sample

Description

The Vertex Shader sample shows some effects that can be achieved using vertex shaders. Vertex shaders use a set of instructions, run by the 3-D device on a per-vertex basis, that can affect the properties of the vertex—positions, normal, color, texture coordinates, and so on—in interesting ways.

Not all cards support all features for vertex shaders. For more information about vertex shaders, refer to the Microsoft® DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\VertexShader

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Programming vertex shaders is not a trivial task. Refer to the DirectX SDK documentation for more information.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Volume Texture Sample

Description

The Volume Texture sample illustrates how to use the new volume textures in Microsoft® Direct3D®. Normally, a texture is thought of as a 2-D image, which has a width and a height and whose texels are addressed with two coordinate, tu and tv. Volume textures are the 3-D counterparts, with a width, height, and depth, are addressed with three coordinates, tu, tv, and tw.

You can use volume textures for interesting effects such as patchy fog, explosions, and so on.

Not all cards support all features for volume textures. For more information about volume textures, refer to the Microsoft DirectX® software development kit (SDK) documentation.

Path

Source: (SDK root)\Samples\C++\Direct3D\VolumeTexture

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Volume textures are no more difficult to use than 3-D textures. In this sample source code, note the vertex declaration, which has a third texture coordinate; texture creation, which also takes a depth dimension; and texture locking, again with the third dimension. The 3-D rasterizer interpolates texel values much as for 2-D textures.

This sample uses common DirectX code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Water Sample

Description

The Water sample illustrates using Direct3D extensions (D3DX) techniques stored in shader files.

The sample shows a square pond inside a building, with rippling water effects including water caustics.

Path

Source: (SDK root)\Samples\C++\Direct3D\Water

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
D | Starts a water drop.
PAGE DOWN | Displays next technique.
PAGE UP | Displays previous technique.
SHIFT+PAGE DOWN | Displays next technique with no validation.
SHIFT+PAGE UP | Displays previous technique with no validation.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The D3DX shaders technique is the focus of this sample.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Tools

This section contains tools to help you develop Microsoft® DirectX® Graphics applications efficiently.

  • D3DSpy
  • Mesh Viewer
  • DXTex Tool

© 2002 Microsoft Corporation. All rights reserved.


D3DSpy

D3DSpy is a tool that monitors function calls to the Microsoft® Direct3D® application programming interface (API), and shows a representation of Direct3D's internal state. This is valuable when writing a Direct3D program, or when trying to understand why a program is behaving as it is. D3DSpy can also be used to improve the performance of a Direct3D program by identifying redundant or inefficient use of the Direct3D API.

D3DSpy can monitor a program running on the same computer as the D3DSpy user interface or on a different computer, communicating by way of Microsoft DirectPlay®. D3DSpy works by providing a proxy dynamic-link library (DLL), which the application connects to and treats like the real D3d9.dll. It intercepts all the Direct3D calls and gathers various information before making the real Direct3D call.

Elements of D3DSpy

The elements of D3DSpy are defined as follows:

  • Target program. This is the program that you want to monitor with D3DSpy. The program must use Direct3D version 9.0 to work with D3DSpy.
  • Proxy DLL (D3dspy9.dll). This is a DLL that the target program connects to as though it were the real D3d9.dll. The proxy DLL gathers call information and communicates with the main D3DSpy user interface.
  • Main D3DSpy user interface (D3dspy.exe). This program provides the user interface that lets the user monitor the state of Direct3D, step through calls to Direct3D, and set breakpoints. It also acts as the network host when running D3DSpy across the network.
  • D3DSpy remote helper (D3dspy.exe). When running D3DSpy across the network, D3DSpy can optionally be run on the target computer in the role of a remote helper program. This enables the user to send requests from the main D3DSpy user interface to the remote helper to launch the target program on the remote computer.

The communication between the elements is shown here.

Running D3DSpy on a Direct3D Program

To start using D3DSpy, choose Start, All Programs, Microsoft DirectX 9.0 SDK, DirectX Utilities, D3DSpy. You will see the startup dialog:

Choose the mode you want. Local mode runs both the D3DSpy user interface and the target program on the same computer. Remote mode runs the D3DSpy user interface and the target program on two different computers. Remote mode is designed to support monitoring Direct3D programs running in full-screen mode.

  1. To run in local mode, click the first option button (radio button).
  2. To run in remote mode:
    • Click the second option button (to run the target program on a remote computer).

      - or -

    • Click the third option button (to run the D3DSpy user interface on a remote computer).

Press Continue. If you are running in remote mode, the D3DSpy Remote Helper will show the Looking For Host dialog box.

Looking For Host dialog box

Click the Start button to show the Start Target Program dialog box:

Start Target screen

Enter the path to the target program, either by typing or by clicking the Browse button. In addition, you can enter the target name, the initial working directory for the target program, and any command-line arguments that you want to pass to the target program.

When the target program starts, it needs to connect to the D3DSpy proxy DLL rather than to the real D3d9.dll. The easiest way to do this is to have D3DSpy copy the proxy DLL to the same directory as the target program. To do this, click the Copy DLL from option button, and fill in the text box with the path to the proxy DLL by typing or by clicking the Browse button. Note that the proxy DLL is stored in the software development kit (SDK) as D3dspy9.dll, but it will be renamed to D3d9.dll while it is copied. You will generally want to select the Delete copied DLL after target program exits check box. If the proxy DLL is not deleted, then the next time you run the target program it will connect to the proxy DLL and attempt to use D3DSpy, which may not be what you want.

Once you hit OK from the Start Target Program dialog box, the DLL will be copied and target program should be launched automatically. If you want, you can start the target program manually (perhaps under a debugger or development environment). If you start the target program manually, you are responsible for having the proxy DLL copied and named properly.

When the target program starts, it should connect to the proxy DLL, which will then connect to the main D3DSpy user interface (and the helper program, if it is present). At this point, the main D3DSpy dialog box will appear:

Main User Interface

The main dialog box has tabs allowing navigation between several pages, each of which shows a different function of D3DSpy or a different section of the current state of Direct3D as the program runs.

Interacting with D3DSpy from a program

D3DSpy works on any program that uses Direct3D version 9.0, without special modification. However, you can add D3DSpy-specific code to your program to achieve several useful results, as follows:

To find out if D3DSpy is currently running on a program, add the following code to the program.

    typedef VOID (*D3DSPYBREAK)();
    HMODULE hModule;
    D3DSPYBREAK D3DSpyBreak;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        D3DSpyBreak = (D3DSPYBREAK)GetProcAddress( hModule, "D3DSpyBreak" );
        if( D3DSpyBreak != NULL )
        {
            // D3DSpy is monitoring this program.
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }

To block D3DSpy from monitoring a program, add the following code to the program.

    typedef VOID (*DISABLED3DSPY)();
    HMODULE hModule;
    DISABLED3DSPY DisableD3DSpy;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        DisableD3DSpy = (DISABLED3DSPY)GetProcAddress( hModule, "DisableD3DSpy" );
        if( DisableD3DSpy != NULL )
        {
            // D3DSpy is monitoring this program.
            DisableD3DSpy();
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }

To generate a breakpoint in D3DSpy at a certain point in your program, add the following code to the program.

    typedef VOID (*D3DSPYBREAK)();
    HMODULE hModule;
    D3DSPYBREAK D3DSpyBreak;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        D3DSpyBreak = (D3DSPYBREAK)GetProcAddress( hModule, "D3DSpyBreak" );
        if( D3DSpyBreak != NULL )
        {
            // D3DSpy is monitoring this program.
            D3DSpyBreak();
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }

© 2002 Microsoft Corporation. All rights reserved.


Mesh Viewer

The Mesh Viewer tool enables you to easily modify meshes.

Menu Descriptions

Mesh Viewer includes the menu item listed here.

File

  • Open mesh file. Opens a dialog to select a file in the .x or .m file format to be loaded and viewed.
  • Open pMesh file. Opens a dialog to select a file in the progressive mesh format to be loaded and viewed.
  • Create shape. Opens a sub-dialog to create some basic shapes that are defined programmatically (text, polygon, box, cylinder, torus, teapot, sphere, cone).
  • Save mesh as. Opens a dialog to save the selected mesh to a file. The file can be written as a text or binary file.
  • Close selected. Closes and deletes the currently selected mesh.
  • Close non-selected. Closes and deletes the meshes that are not currently selected.

View

  • Wireframe. View all content in wireframe mode.
  • Edges. View all content in solid-shaded mode with the edges drawn in black.
  • Creases. Highlight the creases on the visible meshes. A crease is an edge with a vertex that has a different piece of data on it for multiple faces that refer to it, that is, a different normal for the vertex per face.
  • Strips. Show the strips that are generated by this mesh in blue. The blue line goes from the center of each triangle to the next triangle in the triangle strip.
  • Adjacency. Show the adjacency of the polygons in a mesh by drawing a line from the center of a polygon to the center of the adjacent polygon.
  • Bounding box. Draw the bounding boxes for the visible meshes.
  • Normals. Draw the normals of the vertices on the visible meshes in yellow.
  • Texture coords. Show the texture coordinates for the viewed geometry as rays projecting from the vertices. Because a vertex in Microsoft® Direct3D® can have up to eight texture coordinates, users must specify which sets they would like to view. This viewing mode is especially useful when the texture coordinates are filled with tangents for use in pixel shaders for example.
  • Textures. Display the textures on the visible geometry.
  • Lighting. Show the geometry in the scene with lighting calculations still on.
  • Culling. Perform back face culling on the visible geometry when disabled polygons facing away from the camera are not drawn.
  • Hierarchy. Display the frame hierarchy of the meshes that are currently loaded. This is displayed in a separate floating window. To make the window disappear, on the View menu, clear the Hierarchy command.
  • Play animation. Play the current animation for the currently loaded geometry if one exists.
  • Pause animation. Stop the animation at the current frame when playing.
  • Normal speed. Interpret the time value in the animation from an .x file as 4800 units per second. Otherwise, the interpreted value is 30 units per second.

MeshOps

  • Optimize. Optimizes the currently selected mesh with the selected optimization method. See the Direct3D extensions (D3DX) reference pages to see the differences in methods.
  • Weld vertices. Removes duplicate vertices and makes polygons that use these vertices use the nondeleted vertex.
  • Split mesh. Splits the selected mesh into multiple meshes that are less than specified size in vertices and faces.
  • Collapse meshes. Collapses the currently selected meshes into a single mesh.
  • Reset matrices. Resets the matrices for the frames that are loaded to their initial position.
  • Mesh properties. Shows the selected mesh's flexible vertex format (FVF) render states and whether it is a 32-bit mesh.
  • Skinning method. Allows the user to select the skinning method while animating a skinned mesh. The choices are nonindexed, indexed, and software skinning.
  • Face selection. Enters a mode for the user to select an individual face on the current mesh.
  • Vertex selection. Enters a mode for the user to select an individual vertex on the current mesh.

PMeshes

  • Convert selected to PM. Convert the selected mesh to a progressive mesh. The conversion uses the error parameters that are entered in a dialog box. For more information about these parameters refer to the D3DX documentation of progressive meshes.
  • Snapshot to mesh. Convert the current progressive mesh object to a static mesh object using the current settings of the progressive mesh.
  • Set number of faces. Set the current number of faces in the progressive mesh to a specific number.
  • Set number of vertices. Set the current number of vertices in the progressive mesh to a specific number.
  • Trim. Set the minimum and maximum number of faces for a progressive mesh. When the user has set the trim values to the desired minimum and maximum, the progressive mesh can be trimmed to the selected values, thereby reducing the dynamic range of the progressive mesh.

N-Patches

  • N-patch selected. Draw the current object as an N-patch object. The scroll bar in this mode selects the amount of N-patch iterations for the current object.
  • Snapshot to mesh. Convert the selected object to a static mesh based on the current N-patch settings to create a high-resolution static mesh.

Icons and Usage

Icons

  • Selection modes. The first three icons are easy ways for the user to select the selection mode. They are Mesh Selection Mode (Arrow), Face Selection Mode (yellow outlined triangle), and Vertex Selection Mode (Red point highlighted triangle). These are the same modes that are available from the menus in MeshOps.
  • Display modes. The next icons are easy ways to select the most common display modes for geometry. They are Shaded mode (nonoutlined tri-color cube), Wire frame mode (wire frame cube), and Edge mode (outlined tri-color cube). These are the same modes that are available from the menus in View.
  • Topology display modes. The next icons display specific topological information about the geometry displayed. They are adjacency (A), Strips (S), Creases (C), and Normals (N). These are the same modes that are available from the menus in View.
  • Info. The next icon is the button that will display information about the currently selected element.
  • Animation controls. The last two icons are animation controls for playing and pausing the animation for the currently visible mesh.

Status Bar

The status bar in MView displays the current status of the visible geometry. The order from left to right of the displayed information is currently selected element (face or vertex only), Mesh mode (polygonor pMesh), display frames per second, display triangles per second, number of displayed triangles, and number of displayed vertices.

Scroll Bar

The scroll bar will appear in two of the three mesh modes, pMesh and N-patch mode. In pMesh mode, the scroll bar indicates the range of displayed triangles for the progressive mesh. You can slide the scroll bar up or down to change the number of triangles displayed. In N-patch mode, the scroll bar indicates how many N-patch levels are being used. As the scroll bar is moved up or down, the number of N-patch interactions performed are adjusted accordingly.

More Information

For more information about any of the functions used by MView, refer to the D3DX documentation included in the Microsoft DirectX® software development kit (SDK).

© 2002 Microsoft Corporation. All rights reserved.


Programming Tips

This section contains information to help you develop Microsoft® DirectX® Graphics applications efficiently. The following topics are covered.

Tips

  • Driver Internal Errors
  • Multithreading Issues
  • Performance Optimizations
  • Presenting Multiple Views in Windowed Mode
  • Troubleshooting
  • Working with Device Windows
  • Working with Earlier Drivers
  • Working with Multiple Monitor Systems

© 2002 Microsoft Corporation. All rights reserved.


Driver Internal Errors

In Microsoft® DirectX® 8.0, applications could receive D3DERR_DRIVERINTERNALERROR from Create xxx calls; 3-D rendering calls would never return it. Instead, if D3DERR_DRIVERINTERNALERROR happened in the 3-D rendering operations, the runtime would partially reset the internal data structures and then attempt to carry on with debug information, saying that something failed. This usually resulted in an application fault or an operating system failure.

In DirectX 9.0, the following happens:

  • If D3DERR_DRIVERINTERNALERROR is returned from a Create xxx call, it should not be considered fatal. The driver should treat it similar to a D3DERR_UNSUPPORTED or D3DERR_OUTOFMEMORY error.
  • If D3DERR_DRIVERINTERNALERROR happens during 3-D rendering, the runtime returns it at the IDirect3DDevice9::Present call. The application can do one of the following:
    • End, with the pop-up window saying that the application cannot continue because of problems in the display adapter and that the user should contact the adapter manufacturer.
    • Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same path as recovering from a lost device. If IDirect3DDevice9::Reset fails with D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message that the user should contact the adapter manufacturer.

© 2002 Microsoft Corporation. All rights reserved.


Multithreading Issues

Full-screen Microsoft® Direct3D® applications provide a window handle to the Direct3D run time. The window is hooked by the run time. This means that all messages passed to the application's window message procedure have first been examined by the Direct3D run time's own message-handling procedure.

Display mode changes are affected by support routines built into the underlying operating system. When mode changes occur, the system broadcasts several messages to all applications. In Direct3D applications, the messages are received on the window procedure thread, which is not necessarily the same thread that called IDirect3DDevice9::Reset or IDirect3D9::CreateDevice (or the final IUnknown::Release of IDirect3DDevice9, which can cause a display mode change). The Direct3D run time maintains several critical sections internally. Because at least one of these critical sections is held across the mode switch caused by IDirect3DDevice9::Reset or IDirect3D9::CreateDevice, these critical sections are still held when the application receives the mode-change related window messages.

This design has some implications for multithreaded applications. In particular, an application must be sure to strongly segregate its window message handling threads from its Direct3D threads. An application that causes a mode change on one thread but makes Direct3D calls on a different thread in its window procedure is in danger of deadlock.

For these reasons, Direct3D is designed so that the methods IDirect3DDevice9::Reset, IDirect3D9::CreateDevice, IDirect3DDevice9::TestCooperativeLevel, or the final Release of IDirect3DDevice9 can only be called from the same thread that handles window messages.

© 2002 Microsoft Corporation. All rights reserved.


Performance Optimizations

Every developer who creates real-time applications that use 3-D graphics is concerned about performance optimization. This section provides guidelines for getting the best performance from your code.

General Performance Tips

Follow these general guidelines to increase the performance of your application.

  • Clear only when you must.
  • Minimize state changes and group the remaining state changes.
  • Use smaller textures, if you can do so.
  • Draw objects in your scene from front to back.
  • Use triangle strips instead of lists and fans. For optimal vertex cache performance, arrange strips to reuse triangle vertices sooner, rather than later.
  • Gracefully degrade special effects that require a disproportionate share of system resources.
  • Constantly test your application's performance.
  • Minimize vertex buffer switches.
  • Use static vertex buffers where possible.
  • Use one large static vertex buffer per flexible vertex format (FVF) for static objects, rather than one per object.
  • If your application needs random access into the vertex buffer in accelerated graphics port (AGP) memory, choose a vertex format size that is a multiple of 32 bytes. Otherwise, select the smallest appropriate format.
  • Draw using indexed primitives. This can allow for more efficient vertex caching within hardware.
  • If the depth buffer format contains a stencil channel, always clear the depth and stencil channels at the same time.
  • Combine the shader instruction and the data output where possible. For example:
    // Rather than doing a multiply and add, and then output the data with
//   two instructions:
mad r2, r1, v0, c0
mov oD0, r2

// Combine both in a single instruction, because this eliminates an
//   additional register copy.
mad oD0, r1, v0, c0

Databases and Culling

Building a reliable database of the objects in your world is key to excellent performance in Microsoft® Direct3D®. It is more important than improvements to rasterization or hardware.

You should maintain the lowest polygon count you can possibly manage. Design for a low polygon count by building low-polygon models from the start. Add polygons if you can do so without sacrificing performance later in the development process. Remember, the fastest polygons are the ones you don't draw.

Batching Primitives

To get the best rendering performance during execution, try to work with primitives in batches and keep the number of render-state changes as low as possible. For example, if you have an object with two textures, group the triangles that use the first texture and follow them with the necessary render state to change the texture. Then group all the triangles that use the second texture. The simplest hardware support for Direct3D is called with batches of render states and batches of primitives through the hardware abstraction layer (HAL). The more effectively the instructions are batched, the fewer HAL calls are performed during execution.

Lighting Tips

Because lights add a per-vertex cost to each rendered frame, you can improve performance significantly by being careful about how you use them in your application. Most of the following tips derive from the maxim, "the fastest code is code that is never called."

  • Use as few light sources as possible. To increase the overall lighting level, for example, use the ambient light instead of adding a new light source.
  • Directional lights are more efficient than point lights or spotlights. For directional lights, the direction to the light is fixed and doesn't need to be calculated on a per-vertex basis.
  • Spotlights can be more efficient than point lights, because the area outside the cone of light is calculated quickly. Whether spotlights are more efficient depends on how much of your scene is lit by the spotlight.
  • Use the range parameter to limit your lights to only the parts of the scene you need to illuminate. All the light types exit fairly early when they are out of range.
  • Specular highlights almost double the cost of a light. Use them only when you must. Set the D3DRS_SPECULARENABLE render state to 0, the default value, whenever possible. When defining materials, you must set the specular power value to zero to turn off specular highlights for that material; just setting the specular color to 0,0,0 is not enough.

Texture Size

Texture-mapping performance is heavily dependent on the speed of memory. There are a number of ways to maximize the cache performance of your application's textures.

  • Keep the textures small. The smaller the textures are, the better chance they have of being maintained in the main CPU's secondary cache.
  • Do not change the textures on a per-primitive basis. Try to keep polygons grouped in order of the textures they use.
  • Use square textures whenever possible. Textures whose dimensions are 256x256 are the fastest. If your application uses four 128x128 textures, for example, try to ensure that they use the same palette and place them all into one 256x256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256x256 textures unless your application requires that much texturing because, as mentioned, textures should be kept as small as possible.

Using Dynamic Textures

To find out if the driver supports dynamic textures, check the D3DCAPS2_DYNAMICTEXTURES flag of the D3DCAPS9 structure.

Keep the following things in mind when working with dynamic textures.

  • They cannot be managed. For example, their pool cannot be D3DPOOL_MANAGED.
  • Dynamic textures can be locked, even if they are created in D3DPOOL_DEFAULT.
  • D3DLOCK_DISCARD is a valid lock flag for dynamic textures.

It is a good idea to create only one dynamic texture per format and possibly per size. Dynamic mipmaps, cubes, and volumes are not recommended because of the additional overhead in locking every level. For mipmaps, D3DLOCK_DISCARD is allowed only on the top level. All levels are discarded by locking just the top level. This behavior is the same for volumes and cubes. For cubes, the top level and face 0 are locked.

The following pseudocode shows an example of using a dynamic texture.

DrawProceduralTexture(pTex)
{
    // pTex should not be very small because overhead of
    //   calling driver every D3DLOCK_DISCARD will not
    //   justify the performance gain. Experimentation is encouraged.
    pTex->Lock(D3DLOCK_DISCARD);
    <Overwrite *entire* texture>
    pTex->Unlock();
    pDev->SetTexture();
    pDev->DrawPrimitive();
}

Using Dynamic Vertex and Index Buffers

Locking a static vertex buffer while the buffer is in use by the graphics processor can have a significant performance penalty. The lock call must wait until the graphics processor is finished reading vertex or index data from the buffer before it can return to the calling application, a significant delay. Locking and then rendering from a static buffer several times per frame will also prevent the graphics processor from buffering rendering commands, since it will need to finish commands before returning the lock pointer. Without buffered commands, the graphics processor will remain idle until after the application is finished filling the vertex buffer or index buffer and issues a rendering command.

Ideally the vertex or index data would never change, however this is not always possible. There are many situations where the application would like to change vertex or index data every frame, perhaps even multiple times per frame. For these situations the vertex or index buffer should be created with D3DUSAGE_DYNAMIC. This usage flag causes Direct3D to optimize for frequent lock operations. D3DUSAGE_DYNAMIC is only useful when the buffer is locked frequently, data that remains constant should be placed in a static vertex or index buffer.

To receive a performance improvement when using dynamic vertex buffers the application must call IDirect3DVertexBuffer9::Lock or IDirect3DIndexBuffer9::Lock with the appropriate flags. D3DLOCK_DISCARD indicates that the application does not need to keep the old vertex or index data in the buffer. If the graphics processor is still using the buffer when lock is called with D3DLOCK_DISCARD, a pointer to a new region of memory will be returned instead of the old buffer data. This allows the graphics processor to continue using the old data while the application places data in the new buffer. No additional memory management is required in the application; the old buffer will be reused or destroyed automatically when the graphics processor is finished with it. Note that locking a buffer with D3DLOCK_DISCARD always discards the entire buffer, specifying a nonzero offset or limited size field will not preserve information in unlocked areas of the buffer.

There are cases where the amount of data the application needs to store per lock is small, such as adding four vertices to render a sprite. D3DLOCK_NOOVERWRITE indicates that the application will not overwrite data already in use in the dynamic buffer. The lock call will return a pointer to the old data, allowing the application to add new data in unused regions of the vertex or index buffer. The application should not modify vertices or indices used in a draw operation as they might still be in use by the graphics processor. The application should then use D3DLOCK_DISCARD after the dynamic buffer is full to receive a new region of memory, discarding the old vertex or index data after the graphics processor is finished.

The asynchronous query mechanism is useful to determine if vertices are still in use by the graphics processor. Issue a query of type D3DQUERYTYPE_EVENT after the last DrawPrimitive call that uses the vertices. The vertices are no longer in use when IDirect3DQuery9::GetData returns S_OK. Locking a buffer with D3DLOCK_DISCARD or no flags will always guarantee the vertices are synchronized properly with the graphics processor, however using lock without flags will incur the performance penalty described above. Other API calls such as IDirect3DDevice9::BeginScene, IDirect3DDevice9::EndScene, and IDirect3DDevice9::Present do not guarantee the graphics processor is finished using vertices.

Below are ways to use dynamic buffers and the proper lock flags.

    // USAGE STYLE 1
    // Discard the entire vertex buffer and refill with thousands of vertices.
    // Might contain multiple objects and/or require multiple DrawPrimitive
    //   calls separated by state changes, etc.

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // Discard and refill the used portion of the vertex buffer.
    CONST DWORD dwLockFlags = D3DLOCK_DISCARD;

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( 0, 0, &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, nNumberOfVertices/3)

    // USAGE STYLE 2
    // Reusing one vertex buffer for multiple objects

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // No overwrite will be used if the vertices can fit into
    //   the space remaining in the vertex buffer.
    DWORD dwLockFlags = D3DLOCK_NOOVERWRITE;

    // Check to see if the entire vertex buffer has been used up yet.
    if( m_nNextVertexData > m_nSizeOfVB - nSizeOfData )
    {
        // No space remains. Start over from the beginning
        //   of the vertex buffer.
        dwLockFlags = D3DLOCK_DISCARD;
        m_nNextVertexData = 0;
    }

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( (UINT)m_nNextVertexData, nSizeOfData,
               &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST,
               m_nNextVertexData/m_nVertexStride, nNumberOfVertices/3)

    // Advance to the next position in the vertex buffer.
    m_nNextVertexData += nSizeOfData;

Using Meshes

You can optimize meshes by using Direct3D indexed triangles instead of indexed triangle strips. The hardware will discover that 95 percent of successive triangles actually form strips and adjust accordingly. Many drivers do this for legacy hardware also.

Direct3D extensions (D3DX) mesh objects can have each triangle, or face, tagged with a DWORD, called the attribute of that face. The semantics of the DWORD are user-defined. They are used by D3DX to classify the mesh into subsets. The application sets per-face attributes using the ID3DXMesh::LockAttributeBuffer call. The ID3DXMesh::Optimize method has an option to group the mesh vertices and faces on attributes using the D3DXMESHOPT_ATTRSORT option. When this is done, the mesh object calculates an attribute table that can be obtained by the application by calling ID3DXBaseMesh::GetAttributeTable. This call returns 0 if the mesh is not sorted by attributes. There is no way for an application to set an attribute table because it is generated by the ID3DXMesh::Optimize method. The attribute sort is data sensitive, so if the application knows that a mesh is attribute sorted, it still needs to call ID3DXMesh::Optimize to generate the attribute table.

The following topics describe the different attributes of a mesh.

Attribute ID

An attribute identifier (ID) is a value that associates a group of faces with an attribute group. This ID describes which subset of faces ID3DXBaseMesh::DrawSubset should draw. Attribute IDs are specified for the faces in the attribute buffer. The actual values of the attribute IDs can be anything that fits in 32 bits, but it is common to use 0 to n where n is the number of attributes.

Attribute Buffer

The attribute buffer is an array of DWORDs (one per face) that specifies which attribute group each face belongs in. This buffer is initialized to zero on creation of a mesh, but is either filled by the load routines or must be filled by the user if more than one attribute with ID 0 is desired. This buffer contains the information that is used to sort the mesh based on attributes in ID3DXMesh::Optimize. If no attribute table is present, ID3DXBaseMesh::DrawSubset scans this buffer to select the faces of the given attribute to draw.

Attribute Table

The attribute table is a structure owned and maintained by the mesh. The only way for one to be generated is by calling ID3DXMesh::Optimize with attribute sorting or stronger optimization enabled. The attribute table is used to quickly initiate a single draw primitive call to ID3DXBaseMesh::DrawSubset. The only other use is that progressing meshes also maintain this structure, so it is possible to see what faces and vertices are active at the current level of detail.

Z-Buffer Performance

Applications can increase performance when using z-buffering and texturing by ensuring that scenes are rendered from front to back. Textured z-buffered primitives are pretested against the z-buffer on a scan line basis. If a scan line is hidden by a previously rendered polygon, the system rejects it quickly and efficiently. Z-buffering can improve performance, but the technique is most useful when a scene draws the same pixels more than once. This is difficult to calculate exactly, but you can often make a close approximation. If the same pixels are drawn less than twice, you can achieve the best performance by turning z-buffering off and rendering the scene from back to front.

© 2002 Microsoft Corporation. All rights reserved.


Presenting Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the IDirect3DDevice9 interface, an application can create additional swap chains in order to present multiple views from the same device. The application typically creates one swap chain per view by using the IDirect3DDevice9::CreateAdditionalSwapChain method, and associates each swap chain with a particular window. The application renders images into the back buffers of each swap chain, and then presents them individually.

Only one swap chain at a time can be full-screen on each adapter.

© 2002 Microsoft Corporation. All rights reserved.


Troubleshooting

This topic lists common categories of problems that you might encounter when writing Microsoft® Direct3D® applications, and how to prevent them.

Device Creation

If your application fails during device creation, check for the following common errors.

  • Make sure you check the device capabilities, particularly the render depths.
  • Examine the error code. D3DERR_OUTOFVIDEOMEMORY is always possible.
  • Use the debug Microsoft DirectX® dynamic-link libraries (DLLs) and review output messages under the debugger.

Using Lit Vertices

Applications that use lit vertices should disable the Direct3D lighting engine by setting the D3DRS_LIGHTING render state to FALSE. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices don't, by their nature, contain a vertex normal, any color information passed to Direct3D is lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRS_LIGHTING to FALSE.

If your application runs but nothing is visible, check for the following common errors.

  • Ensure that your triangles are not degenerate.
  • Ensure that your triangles are not being culled.
  • Make sure that your transformations are internally consistent.
  • Check the viewport settings to be sure they allow your triangles to be seen.

Debugging

Debugging a Direct3D application can be challenging. Try the following techniques, in addition to checking all the return values—a particularly important piece of advice in Direct3D programming, which is dependent on very different hardware implementations.

  • Switch to debug DLLs.
  • Force a software-only device, turning off hardware acceleration even when it is available.
  • Force surfaces into system memory.
  • Create an option to run in a window, so that you can use an integrated debugger.

The second and third options in this list can help you avoid the Win16 lock which can otherwise cause your debugger to hang.

Also, try adding the following entries to Win.ini.

[Direct3D]
debug=3
[DirectDraw]
debug=3

Borland Floating-Point Initialization

Compilers from Borland report floating-point exceptions in a manner that is incompatible with Direct3D. To solve this problem, include a _matherr exception handler like the following:

// Borland floating point initialization
#include
#include

void initfp(void)
{
    // Disable floating point exceptions.
    _control87(MCW_EM,MCW_EM);
}

int _matherr(struct _exception  *e)
{
    e;               // Dummy reference to catch the warning.
    return 1;        // Error has been handled.
}

Parameter Validation

For performance reasons, the debug version of the Direct3D Immediate Mode run time performs more parameter validation than the retail version, which sometimes performs no validation at all. This enables applications to perform robust debugging with the slower debug run-time component before using the faster retail version for performance tuning and final release.

Although several Direct3D Immediate Mode methods impose limits on the values that they can accept, these limits are often only checked and enforced by the debug version of the Direct3D Immediate Mode run time. Applications must conform to these limits, or unpredictable and undesirable results can occur when running on the retail version of Direct3D. For example, the IDirect3DDevice9::DrawPrimitive method accepts a parameter ( PrimitiveCount) that indicates the number of primitives that the method will render. The method can only accept values between 0 and D3DMAXNUMPRIMITIVES. In the debug version of Direct3D, if you pass more than D3DMAXNUMPRIMITIVES primitives, the method fails gracefully, printing an error message to the error log, and returning an error value to your application. Conversely, if your application makes the same error when it is running with the retail version of the run time, behavior is undefined. For performance reasons, the method does not validate the parameters, resulting in unpredictable and completely situational behavior when they are not valid. In some cases the call might work, and in other cases it might cause a memory fault in Direct3D. If an invalid call consistently works with a particular hardware configuration and DirectX version, there is no guarantee that it will continue to function on other hardware or with later releases of DirectX.

If your application encounters unexplained failures when running with the retail Direct3D run-time file, test against the debug version and look closely for cases where your application passes invalid parameters. Use the DirectX control panel applet, switch to the debug runtime if necessary, and check the "Break on D3DError" option. This option will force the runtime to use the Windows DebugBreak method in order to force the application to stop when an application bug is detected.

© 2002 Microsoft Corporation. All rights reserved.


Working with Device Windows

This section lists issues that you might encounter when working with device windows in Microsoft® Direct3D® applications.

  • Direct3D only hooks up the focus windows instead of the device window with the Direct3D message processing function, and only processes the focus window messages. So, the focus window should be the parent of any device window.
  • For any application, multiple monitor or single monitor, at least one device window must be the focus window. In practical terms, this means that you cannot use a child window of your focus window as the device window in single monitor systems. You must use the parent focus window as both the focus and device windows. For a multiple monitor system, at least one monitor must use the focus window as its device window.

© 2002 Microsoft Corporation. All rights reserved.


Working with Earlier Drivers

This section lists issues that can be encountered when working with Microsoft® DirectX® 9.0 on drivers written for versions of DirectX earlier than DirectX 9.0.

  • When working with a TnLHAL device, the fog intensity is computed but the absolute value operation is not applied to this value. Rather, the value is left negative if that is what is computed. The best way to avoid this situation is to set up transforms appropriately. A less-preferred method is to make the fog-start and fog-end values negative to match.

To check for a DirectX 9.0 driver, look for a nonzero value for D3DDEVCAPS2_STREAMOFFSET in the DevCaps2 member of D3DCAPS9.

© 2002 Microsoft Corporation. All rights reserved.


Working with Multiple Monitor Systems

The concept of exclusive full-screen mode is retained in Microsoft® DirectX® 9.0, but it is kept entirely implicit in the IDirect3D9::CreateDevice and IDirect3DDevice9::Reset method calls. Whenever a device is successfully reset or created in full-screen operation, the Microsoft Direct3D® object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and at this point the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D9 object can neither assume full-screen operation nor allocate video memory. In addition, when a Direct3D9 object assumes exclusive mode, all devices other than the device that went full-screen are placed into the lost state. For information about how to handle lost devices, see Lost Devices.

Along with exclusive mode, the Direct3D9 object is informed of the focus window to be used by the device. Exclusive mode is released when the last full-screen device owned by that Direct3D9 object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D9 object owns exclusive mode. The first category of devices are those that were created by the same Direct3D9 object that created the device that is already full-screen, have the same focus window as the device that is already full-screen, and represent a different adapter from any full-screen device. Devices in this category have no restrictions concerning their ability to be reset or created and are not placed into the lost state. Devices in this category can even be placed into full-screen mode.

Devices not in this category, which would be those created by a different Direct3D9 object, or with a different focus window, or for some adapter with a device already full-screen cannot be reset and remain in the lost state until exclusive mode is lost.

The practical implication is that a multiple monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D9 object, and all share the same focus window.

Note When you create a new device using the same IDirect3D9 object and focus window, your original device will lose its surfaces. You will need to call IDirect3DDevice9::Reset on the first device in order for your application to use it. For example, to create two devices, do the following:

  1. Create Device 1.
  2. Create Device 2.
  3. Reset Device 1.

© 2002 Microsoft Corporation. All rights reserved.


Reference

This section contains the reference pages for the Microsoft® Direct3D® application programming interface (API). Information is contained in the following sections.

  • Direct3D C/C++ Reference
  • Direct3D Extentions (D3DX) C/C++ Reference
  • DDS File Reference
  • X File Reference
  • Shader Reference
  • Effect Reference

© 2002 Microsoft Corporation. All rights reserved.


Direct3D C/C++ Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft® Direct3D®. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Macros
  • Structures
  • Enumerated Types
  • Constants

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains reference information for the Component Object Model (COM) interfaces provided by Microsoft® Direct3D®. The following interfaces are used with Direct3D.

Interfaces

  • IDirect3D9
  • IDirect3DBaseTexture9
  • IDirect3DCubeTexture9
  • IDirect3DDevice9
  • IDirect3DIndexBuffer9
  • IDirect3DPixelShader9
  • IDirect3DQuery9
  • IDirect3DResource9
  • IDirect3DStateBlock9
  • IDirect3DSurface9
  • IDirect3DSwapChain9
  • IDirect3DTexture9
  • IDirect3DVertexBuffer9
  • IDirect3DVertexDeclaration9
  • IDirect3DVertexShader9
  • IDirect3DVolume9
  • IDirect3DVolumeTexture9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9 Interface

Applications use the methods of the IDirect3D9 interface to create Microsoft® Direct3D® objects and set up the environment. This interface includes methods for enumerating and retrieving capabilities of the device.

IDirect3D9 Members

CheckDepthStencilMatch

Determines whether a depth-stencil format is compatible with a render target format in a particular display mode.

CheckDeviceFormat

Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.

CheckDeviceFormatConversion | Tests the device to see if it supports conversion from one display format to another.
CheckDeviceMultiSampleType

Determines if a multisampling technique is available on this device.

CheckDeviceType

Verifies whether a hardware accelerated device type can be used on this adapter.

CreateDevice

Creates a device to represent the display adapter.

EnumAdapterModes | Enumerate the available adapter modes.
GetAdapterCount

Returns the number of adapters on the system.

GetAdapterDisplayMode

Retrieves the current display mode of the adapter.

GetAdapterIdentifier

Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.

GetAdapterModeCount

Returns the number of display modes available on this adapter.

GetAdapterMonitor

Returns the handle of the monitor associated with the Direct3D object.

GetDeviceCaps

Retrieves device-specific information about a device.

RegisterSoftwareDevice

Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

Remarks

The IDirect3D9 is obtained by calling the Direct3DCreate9 function.

The LPDIRECT3D9 and PDIRECT3D9 types are defined as pointers to the IDirect3D9 interface.

typedef struct IDirect3D9 *LPDIRECT3D9, *PDIRECT3D9;

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Direct3DCreate9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CheckDepthStencilMatch Method

Determines whether a depth-stencil format is compatible with a render target format in a particular display mode.

Syntax

HRESULT CheckDepthStencilMatch(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT AdapterFormat,
    D3DFORMAT RenderTargetFormat,
    D3DFORMAT DepthStencilFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
RenderTargetFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the render target surface to be tested.
DepthStencilFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the depth-stencil surface to be tested.

Return Value

If the depth-stencil format is compatible with the render target format in the display mode, this method returns D3D_OK.

D3DERR_INVALIDCALL can be returned if one or more of the parameters is invalid. If a depth-stencil format is not compatible with the render target in the display mode, then this method returns D3DERR_NOTAVAILABLE.

Remarks

This method is provided to enable applications to work with hardware requiring that certain depth formats can only work with certain render target formats.

The behavior of this method has been changed for Microsoft® DirectX® 8.1. This method now pays attention to the D24x8 and D32 depth-stencil formats. The previous version assumed that these formats would always be useable with 32- or 16-bit render targets. This method will now return D3D_OK for these formats only if the device is capable of mixed-depth operations.

The following code fragment shows how you could use IDirect3D9::CheckDeviceFormat to validate a depth stencil format.

BOOL IsDepthFormatOk( D3DFORMAT DepthFormat,
                      D3DFORMAT AdapterFormat,
                      D3DFORMAT BackBufferFormat ) {

    // Verify that the depth format exists.
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          DepthFormat);

    if( FAILED( hr ) ) return FALSE;

    // Verify that the depth format is compatible.
    hr = pD3D->CheckDepthStencilMatch( D3DADAPTER_DEFAULT,
                                       D3DDEVTYPE_HAL,
                                       AdapterFormat,
                                       BackBufferFormat,
                                       DepthFormat);

    return SUCCEEDED( hr );

}

The preceding call will return FALSE if DepthFormat cannot be used in conjunction with AdapterFormat and BackBufferFormat.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CheckDeviceFormat Method

Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.

Syntax

HRESULT CheckDeviceFormat(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT AdapterFormat,
    DWORD Usage,
    D3DRESOURCETYPE RType,
    D3DFORMAT CheckFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
Usage
[in] Requested usage options for the surface. Usage options are any combination of D3DUSAGE and D3DUSAGE_QUERY constants (only a subset of the D3DUSAGE constants are valid for CheckDeviceFormat, see the table on the D3DUSAGE page).
RType
[in] Resource type requested for use with the queried format. Member of D3DRESOURCETYPE.
CheckFormat
[in] Format of the surfaces which may be used, as defined by Usage. Member of D3DFORMAT.

Return Value

If the format is compatible with the specified device for the requested usage, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system, or if DeviceType is unsupported. This method returns D3DERR_NOTAVAILABLE if the format is not acceptable to the device for this usage.

Remarks

An application can discover support for autogeneration on a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. The request to automatically generate mipmaps is considered a hint. Therefore, this method can return DDOK_NOAUTOGEN, which is a valid success code, if the only thing that fails is the mipmap generation. If the mipmap automatic generation fails, the application will get a non-mipmapped texture. For more information, see Automatic Generation of Mipmaps.

To check for an off-screen plain surface format, specify Usage = 0 and RType = RTYPE_SURFACE.

A typical use of IDirect3D9::CheckDeviceFormat is to verify the existence of a particular depth-stencil surface format. See Selecting a Device for more detail on the enumeration process. The following code fragment shows how you could use IDirect3D9::CheckDeviceFormat to verify the existence of a depth-stencil format.

BOOL IsDepthFormatExisting( D3DFORMAT DepthFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          CheckFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if CheckFormat does not exist on the system.

Another typical use of IDirect3D9::CheckDeviceFormat would be to verify if textures existing in particular surface formats can be rendered, given the current display mode. The following code fragment shows how you could use IDirect3D9::CheckDeviceFormat to verify that texture formats are compatible with specific back buffer formats.

BOOL IsTextureFormatOk( D3DFORMAT TextureFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          CheckFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if CheckFormat cannot be used to render textures while the adapter surface format is AdapterFormat.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CheckDeviceFormatConversion Method

Tests the device to see if it supports conversion from one display format to another.

Syntax

HRESULT CheckDeviceFormatConversion(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT SourceFormat,
    D3DFORMAT TargetFormat
);

Parameters

Adapter
[in] Display adapter ordinal number. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Device type. Member of the D3DDEVTYPE enumerated type.
SourceFormat
[in] Source adapter format. Member of the D3DFORMAT enumerated type.
TargetFormat
[in] Target adapter format. Member of the D3DFORMAT enumerated type.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL.

The method will return D3DERR_NOTAVAILABLE when the hardware doesn't support conversion between the two formats.

Remarks

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.

IDirect3D9::CheckDeviceFormatConversion can also be used to determine which combinations of source surface formats and destination surface formats are permissible in calls to IDirect3DDevice9::StretchRect.

Color conversion is restricted to the following source and target formats.

  • The source format must be a four-character code (FOURCC) format or a valid back buffer format. For a list of these, see FourCC Formats and BackBuffer or Display Formats.
  • The target format must be one of these unsigned formats:
    D3DFMT_X1R5G5B5 | D3DFMT_A1R5G5B5 | D3DFMT_R5G6B5
    D3DFMT_R8G8B8 | D3DFMT_X8R8G8B8 | D3DFMT_A8R8G8B8
    D3DFMT_A2R10G10B10 | D3DFMT_A16B16G16R16 | D3DFMT_A2B10G10R10
    D3DFMT_A8B8G8R8 | D3DFMT_X8B8G8R8 | D3DFMT_A16B16G16R16F
    D3DFMT_A32B32G32R32F

See Also

IDirect3DDevice9::ColorFill, IDirect3DDevice9::StretchRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CheckDeviceMultiSampleType Method

Determines if a multisampling technique is available on this device.

Syntax

HRESULT CheckDeviceMultiSampleType(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT SurfaceFormat,
    BOOL Windowed,
    D3DMULTISAMPLE_TYPE MultiSampleType,
    DWORD* pQualityLevels
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns FALSE when this value equals or exceeds the number of display adapters in the system. See Remarks.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
SurfaceFormat
[in] Member of the D3DFORMAT enumerated type that specifies the format of the surface to be multisampled. For more information, see Remarks.
Windowed
[in] BOOL value. Specify TRUE to inquire about windowed multisampling, and specify FALSE to inquire about full-screen multisampling.
MultiSampleType
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, identifying the multisampling technique to test.
pQualityLevels
[out] The number of quality stops available for a given multisample type. This can be NULL if it is not necessary to return the values.

Return Value

If the device can perform the specified multisampling method, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if the Adapter or MultiSampleType parameters are invalid. This method returns D3DERR_NOTAVAILABLE if the queried multisampling technique is not supported by this device. D3DERR_INVALIDDEVICE is returned if DeviceType does not apply to this adapter.

Remarks

This method is intended for use with both render-target and depth-stencil surfaces because you must create both surfaces multisampled if you want to use them together.

The following code fragment shows how you could use IDirect3D9::CheckDeviceMultiSampleType to test for devices that support a specific multisampling method.

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, BackBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) &&
         SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, DepthBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) )
    return S_OK;

The preceding code will return S_OK if the device supports the full-screen D3DMULTISAMPLE_3_SAMPLES multisampling method with the surface format.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CheckDeviceType Method

Verifies whether a hardware accelerated device type can be used on this adapter.

Syntax

HRESULT CheckDeviceType(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT DisplayFormat,
    D3DFORMAT BackBufferFormat,
    BOOL Windowed
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, indicating the device type to check.
DisplayFormat
[in] Member of the D3DFORMAT enumerated type, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices will operate only in 16-bits-per-pixel modes.
BackBufferFormat
[in] Back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render target formats. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format.

For windowed applications, the back buffer format does not need to match the display mode format if the hardware supports color conversion. The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. There is the additional requirement that the device be operable in the desktop mode because devices typically do not operate in 8 bits per pixel modes.

Full-screen applications cannot do color conversion.

D3DFMT_UNKNOWN is allowed for windowed mode.

Windowed
[in] Value indicating whether the device type will be used in full-screen or windowed mode. If set to TRUE, the query is performed for windowed applications; otherwise, this value should be set FALSE.

Return Value

If the device can be used on this adapter, D3D_OK is returned.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system. D3DERR_INVALIDCALL is also returned if IDirect3D9::CheckDeviceType specified a device that does not exist.

D3DERR_NOTAVAILABLE is returned if the requested back buffer format is not supported, or if hardware acceleration is not available for the specified formats.

Remarks

A hardware abstraction layer (HAL) device type requires hardware acceleration. Applications can use CheckDeviceType to determine if the needed hardware and drivers are present to support a HAL device.

Full-screen applications should not specify a DisplayFormat that contains an alpha channel. This will result in a failed call. Note that an alpha channel can be present in the back buffer but the two display formats must be identical in all other respects. For example, if DisplayFormat = D3DFMT_X1R5G5B5, valid values for BackBufferFormat include D3DFMT_X1R5G5B5 and D3DFMT_A1R5G5B5 but exclude D3DFMT_R5G6B5.

The following code fragment shows how you could use CheckDeviceType to test whether a certain device type can be used on this adapter.
if(SUCCEEDED(pD3Device->CheckDeviceType(D3DADAPTER_DEFAULT,
                                        D3DDEVTYPE_HAL,
                                        DisplayFormat,
                                        BackBufferFormat,
                                        bIsWindowed)))

     return S_OK;
// There is no HAL on this adapter using this render target format.
// Try again, using another format.

This code returns S_OK if the device can be used on the default adapter with the specified surface format.

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back-buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::CreateDevice Method

Creates a device to represent the display adapter.

Syntax

HRESULT CreateDevice(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    HWND hFocusWindow,
    DWORD BehaviorFlags,
    D3DPRESENT_PARAMETERS *pPresentationParameters,
    IDirect3DDevice9** ppReturnedDeviceInterface
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
[in] Window handle to which focus belongs for this Microsoft® Direct3D® device. The window specified must be a top-level window for full-screen.
BehaviorFlags
[in] Combination of one or more options that control device creation. For more information, see D3DCREATE.
pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created.

For Microsoft Windows® 2000 and Windows XP, the full-screen device display refresh rate is set in the following order.

  1. User-specified nonzero ForcedRefreshRate registry key, if supported by the device.
  2. Application-specified nonzero refresh rate value in the presentation parameter.
  3. Refresh rate of the latest desktop mode, if supported by the device.
  4. 75 hertz if supported by the device.
  5. 60 hertz if supported by the device.
  6. Device default.

An unsupported refresh rate will default to the closest supported refresh rate below it. For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz.

Calling this method changes the value of several members of D3DPRESENT_PARAMETERS.

  • BackBufferCount, BackBufferWidth, and BackBufferHeight = 0 for windowed or full-screen mode.
  • BackBufferFormat = D3DFMT_UNKNOWN for windowed mode only. Full-screen mode must specify a format.

If D3DCREATE_ADAPTERGROUP_DEVICE is set, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created.

ppReturnedDeviceInterface
[out, retval] Address of a pointer to the returned IDirect3DDevice9 interface, which represents the created device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in D3DPRESENT_PARAMETERS).

This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE. Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window.

Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and that at least one of these vertex processing flags must be specified when calling this method.

Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.)

The methods IDirect3DDevice9::Reset, IUnknown::Release, and IDirect3DDevice9::TestCooperativeLevel must be called from the same thread that used this method to create a device.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

See Also

Direct3DCreate9, D3DDEVICE_CREATION_PARAMETERS, IDirect3DDevice9::Reset, Multihead

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::EnumAdapterModes Method

Enumerate the available adapter modes.

Syntax

HRESULT EnumAdapterModes(

    UINT Adapter,
    D3DFORMAT Format,
    UINT Mode,
    D3DDISPLAYMODE* pMode
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
Format
[in] Allowable pixel formats. The application specifies a pixel format, and the enumeration is restricted to those display modes that exactly match the format. Valid formats are: D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_A2R10G10B10, D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, and D3DFMT_R5G6B5, which are members of D3DFORMAT.
Mode
[in] Represents the adapter mode. This must be set to the display-mode index, which must be in the range of zero to one less than the value returned by IDirect3D9::GetAdapterModeCount. See Remarks.
pMode
[out] Array of display modes. Each is of type D3DDISPLAYMODE. See Remarks.

Return Value

  • If the device can be used on this adapter, D3D_OK is returned.
  • If Adapter equals or exceeds the number of display adapters in the system, D3DERR_INVALIDCALL is returned.
  • If either surface format is not supported, or if hardware acceleration is not available for the specified formats, D3DERR_NOTAVAILABLE is returned.

Remarks

The display-mode parameter supports an expanding set of display modes. To protect applications from enumerating formats that were not invented when the application shipped, the application must tell Microsoft® Direct3D® the format for which display modes should be enumerated. The resulting array of display modes will differ only by width, height, and refresh rate.

The application specifies a pixel format and the enumeration is restricted to those display modes that exactly match the format. Allowed formats are D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_A2B10G10R10, D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, and D3DFMT_R5G6B5.

Enumeration is equivalent for alpha and non-alpha versions of the same format. The returned format will always be filled with the same format supplied by the application. See D3DDISPLAYMODE

This method treats 565 and 555 as equivalent, and returns the correct version in the format. The difference comes into play only when the application locks the back buffer, and there is an explicit flag that the application must set in order to accomplish this.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetAdapterCount Method

Returns the number of adapters on the system.

Syntax

UINT GetAdapterCount(VOID);

Return Value

A UINT value that denotes the number of adapters on the system at the time this IDirect3D9 interface was instantiated.

See Also

IDirect3D9::GetAdapterIdentifier

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetAdapterDisplayMode Method

Retrieves the current display mode of the adapter.

Syntax

HRESULT GetAdapterDisplayMode(

    UINT Adapter,
    D3DDISPLAYMODE *pMode
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
pMode
[in, out] Pointer to a D3DDISPLAYMODE structure, to be filled with information describing the current adapter's mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If Adapter is out of range or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

IDirect3D9::GetAdapterDisplayMode will not return the correct format when the display is in an extended format, such as 2:10:10:10. Instead, it returns the format X8R8G8B8.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetAdapterIdentifier Method

Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.

Syntax

HRESULT GetAdapterIdentifier(

    UINT Adapter,
    DWORD Flags,
    D3DADAPTER_IDENTIFIER9 *pIdentifier
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter. The minimum value for this parameter is 0, and the maximum value for this parameter is one less than the value returned by IDirect3D9::GetAdapterCount.
Flags
[in] Flags sets the WHQLLevel member of D3DADAPTER_IDENTIFIER9. Flags can be set to either D3DENUM_WHQL_LEVEL or zero. The default value is zero. If D3DENUM_WHQL_LEVEL is specified, this call can connect to the Internet to download new Microsoft® Windows® Hardware Quality Labs (WHQL) certificates.
pIdentifier
[out] Pointer to a D3DADAPTER_IDENTIFIER9 structure to be filled with information describing this adapter. If Adapter is greater than or equal to the number of adapters in the system, this structure will be zeroed.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter is out of range, if Flags contains unrecognized parameters, or if pIdentifier is NULL or points to unwriteable memory.

See Also

IDirect3D9::GetAdapterCount

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetAdapterModeCount Method

Returns the number of display modes available on this adapter.

Syntax

UINT GetAdapterModeCount(

    UINT Adapter,
    D3DFORMAT Format
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
Format
[in] Identifies the format of the surface type using D3DFORMAT. Use IDirect3D9::EnumAdapterModes to see the valid formats.

Return Value

This method returns the number of display modes on this adapter or zero if Adapter is greater than or equal to the number of adapters on the system.

See Also

IDirect3D9::EnumAdapterModes

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetAdapterMonitor Method

Returns the handle of the monitor associated with the Microsoft® Direct3D® object.

Syntax

HMONITOR GetAdapterMonitor(

    UINT Adapter
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Value

Handle of the monitor associated with the Direct3D object.

Remarks

As shown in the following code fragment, which illustrates how to obtain a handle to the monitor associated with a given device, use IDirect3DDevice9::GetDirect3D to return the Direct3D enumerator from the device and use IDirect3DDevice9::GetCreationParameters to retrieve the value for Adapter.

    if( FAILED( pDevice->GetCreationParameters(  &Parameters ) ) )
        return D3DERR_INVALIDCALL;

    if( FAILED( pDevice->GetDirect3D(&pD3D) ) )
        return D3DERR_INVALIDCALL;

    hMonitor = pD3D->GetAdapterMonitor(Parameters.AdapterOrdinal);

    pD3D->Release();

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3DDevice9::GetDirect3D

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::GetDeviceCaps Method

Retrieves device-specific information about a device.

Syntax

HRESULT GetDeviceCaps(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DCAPS9 *pCaps
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type. Denotes the device type.
pCaps
[out] Pointer to a D3DCAPS9 structure to be filled with information describing the capabilities of the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_INVALIDDEVICE | The requested device type is not valid.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

The application should not assume the persistence of vertex processing capabilities across Microsoft® Direct3D® device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to IDirect3D9::CreateDevice. For example, the capabilities may yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information see the description of D3DCAPS9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3D9::RegisterSoftwareDevice Method

Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

Syntax

HRESULT RegisterSoftwareDevice(

    void *pInitializeFunction
);

Parameters

pInitializeFunction
[in] Pointer to the initialization function for the software device to be registered.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

If the user's computer provides no special hardware acceleration for 3-D operations, your application might emulate 3-D hardware in software. Software rasterization devices emulate the functions of color 3-D hardware in software. A software device runs more slowly than a hardware abstraction layer (HAL). However, software devices take advantage of any special instructions supported by the CPU to increase performance. Instruction sets include the AMD 3DNow! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Microsoft® Direct3D® uses the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization.

Software devices communicate with Direct3D through an interface similar to the hardware device driver interface (DDI).

Software devices are loaded by the application and registered with the IDirect3D9 object. Direct3D uses the software device for rendering.

The Direct3D Driver Development Kit (DDK) provides the documentation and headers for developing pluggable software devices.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9 Interface

Applications use the methods of the IDirect3DBaseTexture9 interface to manipulate texture resources including cube and volume textures.

IDirect3DBaseTexture9 Members

FreePrivateData

Frees the specified private data associated with this resource.

GenerateMipSubLevels

Generate mipmap sublevels.

GetAutoGenFilterType

Get the filter type that is used for automatically generated mipmap sublevels.

GetDevice

Retrieves the device associated with a resource.

GetLevelCount

Returns the number of texture levels in a multilevel texture.

GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

PreLoad

Preloads a managed resource.

SetAutoGenFilterType

Set the filter type that is used for automatically generated mipmap sublevels.

SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Remarks

The IDirect3DBaseTexture9 interface assigned to a particular stage for a device is obtained by calling the IDirect3DDevice9::GetTexture method.

The LPDIRECT3DBASETEXTURE9 and PDIRECT3DBASETEXTURE9 types are defined as pointers to the IDirect3DBaseTexture9 interface.

typedef struct IDirect3DBaseTexture9 *LPDIRECT3DBASETEXTURE9, *PDIRECT3DBASETEXTURE9;

Interface Information

Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DBaseTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time, specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with USAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DBaseTexture9::GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

See Also

IDirect3DBaseTexture9::SetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DBaseTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DBaseTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DBaseTexture9::SetLOD communicates to the Microsoft® Direct3D® texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9 Interface

Applications use the methods of the IDirect3DCubeTexture9 interface to manipulate a cube texture resource.

IDirect3DCubeTexture9 Members

AddDirtyRect

Adds a dirty region to a cube texture resource.

FreePrivateData

Frees the specified private data associated with this resource.

GenerateMipSubLevels

Generate mipmap sublevels.

GetAutoGenFilterType

Get the filter type that is used for automatically generated mipmap sublevels.

GetCubeMapSurface

Retrieves a cube texture map surface.

GetDevice

Retrieves the device associated with a resource.

GetLevelCount

Returns the number of texture levels in a multilevel texture.

GetLevelDesc

Retrieves a description of one face of the specified cube texture level.

GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

LockRect Locks a rectangle on a cube texture resource.
PreLoad

Preloads a managed resource.

SetAutoGenFilterType

Set the filter type that is used for automatically generated mipmap sublevels.

SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

UnlockRect

Unlocks a rectangle on a cube texture resource.

Remarks

The IDirect3DCubeTexture9 interface is obtained by calling the IDirect3DDevice9::CreateCubeTexture method.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits additional functionality from the IUnknown interface.

The LPDIRECT3DCUBETEXTURE9 and PDIRECT3DCUBETEXTURE9 types are defined as pointers to the IDirect3DCubeTexture9 interface.

typedef struct IDirect3DCubeTexture9 *LPDIRECT3DCUBETEXTURE9, *PDIRECT3DCUBETEXTURE9;

Interface Information

Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateCubeTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::AddDirtyRect Method

Adds a dirty region to a cube texture resource.

Syntax

HRESULT AddDirtyRect(

    D3DCUBEMAP_FACES FaceType,
    CONST RECT *pDirtyRect
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying the cube map face.
pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region. Specifying NULL expands the dirty region to cover the entire cube texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a IDirect3DDevice9::UpdateSurface call is marked dirty.

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetCubeMapSurface Method

Retrieves a cube texture map surface.

Syntax

HRESULT GetCubeMapSurface(

    D3DCUBEMAP_FACES FaceType,
    UINT Level,
    IDirect3DSurface9 **ppCubeMapSurface
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
ppCubeMapSurface
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned cube texture map surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetLevelDesc Method

Retrieves a description of one face of the specified cube texture level.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DSURFACE_DESC *pDesc
);

Parameters

Level
[in] Specifies a level of a mipmapped cube texture.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing one face of the specified cube texture level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Remarks

The D3DSURFACE_DESC structure contains a Size member, which is the size of one face in the cube. To get the size of the entire cube, multiply the Size data by six.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::LockRect Method

Locks a rectangle on a cube texture resource.

Syntax

HRESULT LockRect(

    D3DCUBEMAP_FACES FaceType,
    UINT Level,
    D3DLOCKED_RECT *pLockedRect,
    CONST RECT *pRect,
    DWORD Flags
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the region to lock.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire cube texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments is invalid.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

Cube textures created with D3DPOOL_DEFAULT are not lockable. Cube textures created in video memory are lockable when created with USAGE_DYNAMIC. For more information about usages, see D3DUSAGE.

The only lockable format for a depth-stencil texture is D3DFMT_D16_LOCKABLE.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::UnlockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::UnlockRect Method

Unlocks a rectangle on a cube texture resource.

Syntax

HRESULT UnlockRect(

    D3DCUBEMAP_FACES FaceType,
    UINT Level
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments is invalid.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9 Interface

Applications use the methods of the IDirect3DDevice9 interface to perform DrawPrimitive-based rendering, create resources, work with system-level variables, adjust gamma ramp levels, work with palettes, and create shaders.

IDirect3DDevice9 Members

BeginScene

Begins a scene.

BeginStateBlock

Signals Microsoft® Direct3D® to begin recording a device-state block.

Clear

Clears the viewport, or a set of rectangles in the viewport, to a specified RGBA color, clears the depth buffer, and erases the stencil buffer.

ColorFill | Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.
CreateAdditionalSwapChain

Creates an additional swap chain for rendering multiple views.

CreateCubeTexture

Creates a cube texture resource.

CreateDepthStencilSurface

Creates a depth-stencil resource.

CreateIndexBuffer

Creates an index buffer.

CreateOffscreenPlainSurface | Create an off-screen surface.
CreatePixelShader

Creates a pixel shader.

CreateQuery

Creates a status query.

CreateRenderTarget

Creates a render target surface.

CreateStateBlock

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

CreateTexture

Creates a texture resource.

CreateVertexBuffer

Creates a vertex buffer.

CreateVertexDeclaration | Create a vertex shader declaration from the device and the vertex elements.
CreateVertexShader

Creates a vertex shader.

CreateVolumeTexture

Creates a volume texture resource.

DeletePatch

Frees a cached high-order patch.

DrawIndexedPrimitive

Renders the specified geometric primitive, based on indexing into an array of vertices.

DrawIndexedPrimitiveUP

Renders the specified geometric primitive with data specified by a user memory pointer.

DrawPrimitive

Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.

DrawPrimitiveUP

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

DrawRectPatch

Draws a rectangular patch using the currently set streams.

DrawTriPatch

Draws a triangular patch using the currently set streams.

EndScene

Ends a scene that was begun by calling the IDirect3DDevice9::BeginScene method.

EndStateBlock

Signals Direct3D to stop recording a device-state block and retrieve a handle to the state block.

EvictManagedResources

Evicts all managed resources, including both Direct3D and driver-managed resources.

GetAvailableTextureMem | Returns an estimate of the amount of available texture memory.
GetBackBuffer | Retrieves a back buffer from the device's swap chain.
GetClipPlane | Retrieves the coefficients of a user-defined clipping plane for the device.
GetClipStatus | Retrieves the clip status.
GetCreationParameters | Retrieves the creation parameters of the device.
GetCurrentTexturePalette | Retrieves the current texture palette.
GetDepthStencilSurface | Gets the depth-stencil surface owned by the Direct3DDevice object.
GetDeviceCaps | Retrieves the capabilities of the rendering device.
GetDirect3D | Returns an interface to the instance of the Direct3D object that created the device.
GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
GetFrontBufferData | Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.
GetFVF | Gets the fixed vertex function declaration.
GetGammaRamp | Retrieves the gamma correction ramp for the swap chain.
GetIndices | Retrieves index data.
GetLight | Retrieves a set of lighting properties that this device uses.
GetLightEnable | Retrieves the activity status
GetMaterial | Retrieves the current material properties for the device.
GetNPatchMode | Gets the N-patch mode segments.
GetNumberOfSwapChains | Gets the number of implicit swap chains.
GetPaletteEntries | Retrieves palette entries.
GetPixelShader | Retrieves the currently set pixel shader.
GetPixelShaderConstantB | Gets a Boolean shader constant.
GetPixelShaderConstantF | Gets a floating-point shader constant.
GetPixelShaderConstantI | Gets an integer shader constant.
GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
GetRenderState | Retrieves a render-state value for a device.
GetRenderTarget | Retrieves a render target surface.
GetRenderTargetData | Copies the render target data from device memory to system memory.
GetSamplerState | Gets the sampler state value.
GetScissorRect | Gets the scissor rectangle.
GetSoftwareVertexProcessing | Gets the vertex processing (hardware or software) mode.
GetStreamSource | Retrieves a vertex buffer bound to the specified data stream.
GetStreamSourceFreq | Gets the stream source frequency divider value.
GetSwapChain | Gets a pointer to a swap chain.
GetTexture | Retrieves a texture assigned to a stage for a device.
GetTextureStageState | Retrieves a state value for an assigned texture.
GetTransform | Retrieves a matrix describing a transformation state.
GetVertexDeclaration | Gets a vertex shader declaration.
GetVertexShader | Retrieves the currently set vertex shader.
GetVertexShaderConstantB | Gets a Boolean vertex shader constant.
GetVertexShaderConstantF | Gets a floating-point vertex shader constant.
GetVertexShaderConstantI | Gets an integer vertex shader constant.
GetViewport | Retrieves the viewport parameters currently set for the device.
LightEnable | Enables or disables a set of lighting parameters within a device.
MultiplyTransform | Multiplies a device's world, view, or projection matrices by a specified matrix.
Present | Presents the contents of the next buffer in the sequence of back buffers owned by the device.
ProcessVertices | Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.
Reset | Resets the type, size, and format of the swap chain.
SetClipPlane | Sets the coefficients of a user-defined clipping plane for the device.
SetClipStatus | Sets the clip status.
SetCurrentTexturePalette | Sets the current texture palette.
SetCursorPosition | Sets the cursor position and update options.
SetCursorProperties | Sets properties for the cursor.
SetDepthStencilSurface | Sets the depth stencil surface.
SetDialogBoxMode | This method allows the use of Microsoft Windows® Graphics Device Interface (GDI) dialog boxes in full-screen mode applications.
SetFVF | Sets the current vertex stream declaration.
SetGammaRamp | Sets the gamma correction ramp for the implicit swap chain.
SetIndices | Sets index data.
SetLight | Assigns a set of lighting properties for this device.
SetMaterial | Sets the material properties for the device.
SetNPatchMode | Enable or disable N-patches.
SetPaletteEntries | Sets palette entries.
SetPixelShader | Sets the current pixel shader to a previously created pixel shader.
SetPixelShaderConstantB | Sets a Boolean shader constant.
SetPixelShaderConstantF | Sets a floating-point shader constant.
SetPixelShaderConstantI | Sets an integer shader constant.
SetRenderState | Sets a single device render-state parameter.
SetRenderTarget | Sets a new color buffer for the device.
SetSamplerState | Sets the sampler state value.
SetScissorRect | Sets the scissor rectangle.
SetSoftwareVertexProcessing | Use this method to switch between software and hardware vertex processing.
SetStreamSource | Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source.
SetStreamSourceFreq | Sets the stream source frequency divider value.
SetTexture | Assigns a texture to a stage for a device.
SetTextureStageState | Sets the state value for the currently assigned texture.
SetTransform | Sets a single device transformation-related state.
SetVertexDeclaration | Sets a vertex shader declaration.
SetVertexShader | Sets the vertex shader.
SetVertexShaderConstantB | Sets a Boolean vertex shader constant.
SetVertexShaderConstantF | Sets a floating-point vertex shader constant.
SetVertexShaderConstantI | Sets an integer vertex shader constant.
SetViewport | Sets the viewport parameters for the device.
ShowCursor | Displays or hides the cursor.
StretchRect | Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.
TestCooperativeLevel | Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.
UpdateSurface

Copies rectangular subsets of pixels from one surface to another.

UpdateTexture | Updates the dirty portions of a texture.
ValidateDevice | Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

Remarks

The IDirect3DDevice9 interface is obtained by calling the IDirect3D9::CreateDevice method.

This interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods.

The LPDIRECT3DDEVICE9 and PDIRECT3DDEVICE9 types are defined as pointers to the IDirect3DDevice9 interface.

typedef struct IDirect3DDevice9 *LPDIRECT3DDEVICE9, *PDIRECT3DDEVICE9;

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3D9::CreateDevice

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::BeginScene Method

Begins a scene.

Syntax

HRESULT BeginScene(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

The method will fail with D3DERR_INVALIDCALL if BeginScene is called while already in a BeginScene/EndScene pair. This happens only when BeginScene is called twice without first calling EndScene.

Remarks

Applications must call this method before performing any rendering and must call IDirect3DDevice9::EndScene when rendering is complete and before calling IDirect3DDevice9::BeginScene again.

If the IDirect3DDevice9::BeginScene method fails, the device was unable to begin the scene, and there is no need to call the IDirect3DDevice9::EndScene method. In fact, calls to IDirect3DDevice9::EndScene will fail if the previous call to IDirect3DDevice9::BeginScene failed.

See Also

IDirect3DDevice9::EndScene

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::BeginStateBlock Method

Signals Microsoft® Direct3D® to begin recording a device-state block.

Syntax

HRESULT BeginStateBlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Applications can ensure that all recorded states are valid by calling the IDirect3DDevice9::ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block, after calling IDirect3DDevice9::BeginStateBlock and before IDirect3DDevice9::EndStateBlock.

  • IDirect3DDevice9::LightEnable
  • IDirect3DDevice9::SetClipPlane
  • IDirect3DDevice9::SetIndices
  • IDirect3DDevice9::SetLight
  • IDirect3DDevice9::SetMaterial
  • IDirect3DDevice9::SetPixelShader
  • IDirect3DDevice9::SetPixelShaderConstantB
  • IDirect3DDevice9::SetPixelShaderConstantF
  • IDirect3DDevice9::SetPixelShaderConstantI
  • IDirect3DDevice9::SetRenderState
  • IDirect3DDevice9::SetStreamSource
  • IDirect3DDevice9::SetTexture
  • IDirect3DDevice9::SetTextureStageState
  • IDirect3DDevice9::SetTransform
  • IDirect3DDevice9::SetViewport
  • IDirect3DDevice9::SetVertexShader
  • IDirect3DDevice9::SetVertexShaderConstantB
  • IDirect3DDevice9::SetVertexShaderConstantF
  • IDirect3DDevice9::SetVertexShaderConstantI

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state block, only the last value is used.

See Also

IDirect3DDevice9::EndStateBlock, IDirect3DDevice9::CreateStateBlock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::Clear Method

Clears the viewport, or a set of rectangles in the viewport, to a specified RGBA color, clears the depth buffer, and erases the stencil buffer.

Syntax

HRESULT Clear(

    DWORD Count,
    const D3DRECT *pRects,
    DWORD Flags,
    D3DCOLOR Color,
    float Z,
    DWORD Stencil
);

Parameters

Count
[in] Number of rectangles in the array at pRects. If you set pRects to NULL, this parameter must be set to 0.
pRects
[in] Pointer to an array of D3DRECT structures that describe the rectangles to clear. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target surface. Coordinates are clipped to the bounds of the viewport rectangle. This parameter can be set to NULL to indicate that the entire viewport rectangle is to be cleared.
Flags
[in] Flags that indicate which surfaces should be cleared. This parameter can be any combination of the following flags, but at least one flag must be used.
D3DCLEAR_STENCIL
Clear the stencil buffer to the value in the Stencil parameter.
D3DCLEAR_TARGET
Clear the render target to the color in the Color parameter.
D3DCLEAR_ZBUFFER
Clear the depth buffer to the value in the Z parameter.
Color
[in] A 32-bit ARGB color value to which the render target surface is cleared.
Z
[in] New z value that this method stores in the depth buffer. This parameter can be in the range from 0.0 through 1.0 (for z-based or w-based depth buffers). A value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance.
Stencil
[in] Integer value to store in each stencil-buffer entry. This parameter can be in the range from 0 through 2n–1, where n is the bit depth of the stencil buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format does not contain stencil buffer information, this method fails.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::ColorFill Method

Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.

Syntax

HRESULT ColorFill(

    IDirect3DSurface9 *pSurface,
    CONST RECT *pRect,
    D3DCOLOR color
);

Parameters

pSurface
[in] Pointer to the surface to be filled.
pRect
[in] Pointer to the source rectangle. Using NULL means that the entire surface will be filled.
color
[in] Color used for filling.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method can only be applied to a render target, a render target texture surface, or an off-screen plain surface with a pool type of D3DPOOL_DEFAULT.

IDirect3DDevice9::ColorFill will work with all formats. However, when using a reference or software device, the only formats supported are D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_YUY2, D3DFMT_G8R8_G8B8, D3DFMT_UYVY, D3DFMT_R8G8_B8G8, D3DFMT_R16F, D3DFMT_G16R16F, D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F, and D3DFMT_A32B32G32R32F.

When using a Microsoft® DirectX® 7.0 or DirectX 8.x driver, the only YUV formats supported are D3DFMT_UYVY and D3DFMT_YUY2.

See Also

D3DPOOL

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateAdditionalSwapChain Method

Creates an additional swap chain for rendering multiple views.

Syntax

HRESULT CreateAdditionalSwapChain(

    D3DPRESENT_PARAMETERS* pPresentationParameters,
    IDirect3DSwapChain9** ppSwapChain
);

Parameters

pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, containing the presentation parameters for the new swap chain. This value cannot be NULL.

Calling this method changes the value of members of the D3DPRESENT_PARAMETERS structure.

  • If BackBufferCount == 0, calling CreateAdditionalSwapChain will increase it to 1.
  • If the application is in windowed mode, and if either the BackBufferWidth or the BackBufferHeight == 0, they will be set to the client area width and height of the hwnd.
ppSwapChain
[out, retval] Address of a pointer to an IDirect3DSwapChain9 interface, representing the additional swap chain.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE This device does not support the queried multisample type.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D for Microsoft DirectX® 9.0 has one swap chain as a property of the device.

Note that any given device can support only one full-screen swap chain.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset and CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

See Also

Presenting Multiple Views in Windowed Mode

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateCubeTexture Method

Creates a cube texture resource.

Syntax

HRESULT CreateCubeTexture(

    UINT EdgeLength,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DCubeTexture9 **ppCubeTexture,
    HANDLE* pHandle
);

Parameters

EdgeLength
[in] Size of the edges of all the top-level faces of the cube texture. The pixel dimensions of subsequent levels of each face will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] Number of levels in each face of the cube texture. If this is zero, Microsoft® Direct3D® will generate all cube texture sublevels down to 1x1 pixels for each face for hardware that supports mipmapped cube textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateCubeTexture with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in all faces of the cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out, retval] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

The method can also return:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

A mipmap (texture) is a collection of successively downsampled (mipmapped) surfaces. On the other hand, a cube texture (created by IDirect3DDevice9::CreateCubeTexture) is a collection of six textures (mipmaps), one for each face. All faces must be present in the cube texture. Also, a cube map surface must be the same pixel size in all three dimensions (x, y, and z).

An application can discover support for Automatic Generation of Mipmaps in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateCubeTexture will succeed, but it will return a one level texture.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateDepthStencilSurface Method

Creates a depth-stencil resource.

Syntax

HRESULT CreateDepthStencilSurface(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    D3DMULTISAMPLE_TYPE MultiSample,
    DWORD MultisampleQuality,
    BOOL Discard,
    IDirect3DSurface9** ppSurface,
    HANDLE* pHandle
);

Parameters

Width
[in] Width of the depth-stencil surface, in pixels.
Height
[in] Height of the depth-stencil surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to IDirect3DDevice9::SetDepthStencilSurface, its multisample type must be the same as that of the render target set by IDirect3DDevice9::SetRenderTarget.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the MultiSample type must all match.
Discard
[in] Set this flag to TRUE to enable z-buffer discarding, and FALSE otherwise.

If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

This flag has the same behavior as the constant, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL, in D3DPRESENTFLAG.

ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the created depth-stencil surface resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE This device does not support the queried multisample type.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

See Also

IDirect3DDevice9::UpdateSurface

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateIndexBuffer Method

Creates an index buffer.

Syntax

HRESULT CreateIndexBuffer(

    UINT Length,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DIndexBuffer9** ppIndexBuffer,
    HANDLE* pHandle
);

Parameters

Length
[in] Size of the index buffer, in bytes.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateIndexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the index buffer. The valid settings are the following: See Remarks.
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppIndexBuffer
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the created index buffer resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Index buffers are memory resources used to hold indices, they are similar to both surfaces and vertex buffers. The use of index buffers enables Direct3D to avoid unnecessary data copying and to place the buffer in the optimal memory type for the expected usage.

To use index buffers, create an index buffer, lock it, fill it with indices, unlock it, pass it to IDirect3DDevice9::SetIndices, set up the vertices, set up the vertex shader, and call IDirect3DDevice9::DrawIndexedPrimitive for rendering.

The MaxVertexIndex member of the D3DCAPS9 structure indicates the types of index buffers that are valid for rendering.

See Also

IDirect3DIndexBuffer9::GetDesc

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateOffscreenPlainSurface Method

Create an off-screen surface.

Syntax

HRESULT CreateOffscreenPlainSurface(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    DWORD Pool,
    IDirect3DSurface9** ppSurface,
    HANDLE* pHandle
);

Parameters

Width
[in] Width of the surface.
Height
[in] Height of the surface.
Format
[in] Format of the surface. See D3DFORMAT.
Pool
[in] Surface pool type. See D3DPOOL.
ppSurface
[out, retval] Pointer to the IDirect3DSurface9 interface created.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the Microsoft® DirectX® 8.x method CreateImageSurface.

D3DPOOL_DEFAULT is the appropriate pool for use with the IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DPOOL_MANAGED is not allowed when creating an offscreen plain surface. For more information about memory pools, see D3DPOOL.

Off-screen plain surfaces are always lockable, regardless of their pool types.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreatePixelShader Method

Creates a pixel shader.

Syntax

HRESULT CreatePixelShader(

    CONST DWORD *pFunction,
    IDirect3DPixelShader9** ppShader
);

Parameters

pFunction
[in] Pointer to the pixel shader function token array, specifying the blending operations. This value cannot be NULL.
ppShader
[out, retval] Pointer to the returned pixel shader interface. See IDirect3DPixelShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

See Also

D3DXAssembleShader, D3DXAssembleShaderFromFile

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateQuery Method

Creates a status query.

Syntax

HRESULT CreateQuery(

    D3DQUERYTYPE Type,
    IDirect3DQuery9** ppQuery
);

Parameters

Type
[in] Identifies the query type. For more information, see D3DQUERYTYPE.
ppQuery
[out, retval] Returns a pointer to the query interface that manages the query object. See IDirect3DQuery9.

This parameter can be set to NULL to see if a query is supported. If the query is not supported, the method returns D3DERR_NOTAVAILABLE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_NOTAVAILABLE or E_OUTOFMEMORY.

Remarks

This method is provided for both synchronous and asynchronous queries. It takes the place of GetInfo, which is no longer supported in Microsoft® DirectX® 9.0.

Synchronous and asynchronous queries are created with IDirect3DDevice9::CreateQuery with D3DQUERYTYPE. Once a query has been created and the application programming interface (API) calls have been made that are being queried, use IDirect3DQuery9::Issue to issue a query and IDirect3DQuery9::GetData to get the results of the query.

See Also

Asynchronous Notification

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateRenderTarget Method

Creates a render target surface.

Syntax

HRESULT CreateRenderTarget(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    D3DMULTISAMPLE_TYPE MultiSample,
    DWORD MultisampleQuality,
    BOOL Lockable,
    IDirect3DSurface9** ppSurface,
    HANDLE* pHandle
);

Parameters

Width
[in] Width of the render target surface, in pixels.
Height
[in] Height of the render target surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the render target.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, which describes the multisampling buffer type. This parameter specifies the antialiasing type for this render target. When this surface is passed to IDirect3DDevice9::SetRenderTarget, its multisample type must be the same as that of the depth-stencil set by IDirect3DDevice9::SetDepthStencilSurface.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the multisample type must all match.
Lockable
[in] Render targets are not lockable unless the application specifies TRUE for Lockable. Note that lockable render targets reduce performance on some graphics hardware.
ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried multisample type.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Not enough display memory to perform the operation.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.

Remarks

Render target surfaces are placed in the D3DPOOL_DEFAULT memory class.

The creation of lockable, multisampled render targets is not supported.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateStateBlock Method

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

Syntax

HRESULT CreateStateBlock(

    D3DSTATEBLOCKTYPE Type,
    IDirect3DStateBlock9** ppSB
);

Parameters

Type
[in] Type of state data that the method should capture. This parameter can be set to a value defined in the D3DSTATEBLOCKTYPE enumerated type.
ppSB
[out, retval] Pointer to a state block interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::EndStateBlock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateTexture Method

Creates a texture resource.

Syntax

HRESULT CreateTexture(

    UINT Width,
    UINT Height,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DTexture9** ppTexture,
    HANDLE* pHandle
);

Parameters

Width
[in] Width of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Height
[in] Height of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Levels
[in] Number of levels in the texture. If this is zero, Microsoft® Direct3D® will generate all texture sublevels down to 1 by 1 pixels for hardware that supports mipmapped textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter with the behavior flags in IDirect3D9::CreateDevice.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the created texture resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

The method may also return:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

An application can discover support for Automatic Generation of Mipmaps in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateTexture will succeed, but it will return a one level texture.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateVertexBuffer Method

Creates a vertex buffer.

Syntax

HRESULT CreateVertexBuffer(

    UINT Length,
    DWORD Usage,
    DWORD FVF,
    D3DPOOL Pool,
    IDirect3DVertexBuffer9** ppVertexBuffer,
    HANDLE* pHandle
);

Parameters

Length
[in] Size of the vertex buffer, in bytes. For flexible vertex format (FVF) vertex buffers, Length must be large enough to contain at least one vertex, but it need not be a multiple of the vertex size. Length is not validated for non-FVF buffers. See Remarks.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateVertexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
FVF
[in] Combination of D3DFVF, a usage specifier that describes the vertex format of the vertices in this buffer. If this parameter is set to a valid FVF code, the created vertex buffer is an FVF vertex buffer (see Remarks). Otherwise, if this parameter is set to zero, the vertex buffer is a non-FVF vertex buffer.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppVertexBuffer
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the created vertex buffer resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

A vertex buffer can be used with either hardware or software vertex processing. This is determined by how the device and the vertex buffer are created.

When a device is created, CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities.

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.
  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING.

Mixed-mode devices might need to switch between software and hardware processing after the device is created. In this case, set the D3DRS_SOFTWAREVERTEXPROCESSING render state using IDirect3DDevice9::SetRenderState.

When a vertex buffer is created, CreateVertexBuffer uses the usage parameter to decide whether to process vertices in hardware or software.

  • If CreateDevice uses D3DCREATE_HARDWARE_VERTEXPROCESSING, CreateVertexBuffer must use 0.
  • Else if CreateDevice uses D3DCREATE_SOFTWARE_VERTEXPROCESSING, CreateVertexBuffer must use either 0 or D3DUSAGE_SOFTWAREPROCESSING. For either value, vertices will be processed in software.
  • Else If CreateDevice uses D3DCREATE_MIXED_VERTEXPROCESSING, CreateVertexBuffer can use either 0 or D3DUSAGE_SOFTWAREPROCESSING.

To use a vertex buffer with a mixed mode device, create a single vertex buffer which can be used for both hardware or software processing. Use IDirect3DDevice9::SetStreamSource to set the current vertex buffer and use IDirect3DDevice9::SetRenderState, if necessary, to change the device behavior to match. It is recommended that the vertex buffer usage matches the device behavior. Note that a vertex buffer created for software processing cannot be located in video memory.

The IDirect3DDevice9 interface supports rendering of primitives using vertex data stored in vertex buffer objects. Vertex buffers are created from the IDirect3DDevice9, and are usable only with the IDirect3DDevice9 object from which they are created.

When set to a nonzero value, which must be a valid FVF code, the FVF parameter indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. For more information, see FVF Vertex Buffers.

Non-FVF buffers can be used to interleave data during multipass rendering or multitexture rendering in a single pass. To do this, one buffer contains geometry data and the others contain texture coordinates for each texture to be rendered. When rendering, the buffer containing the geometry data is interleaved with each of the buffers containing the texture coordinates. If FVF buffers were used instead, each of them would need to contain identical geometry data in addition to the texture coordinate data specific to each texture rendered. This would result in either a speed or memory penalty, depending on the strategy used. For more information about texture coordinates, see Texture Coordinates.

See Also

IDirect3DVertexBuffer9::GetDesc, IDirect3DDevice9::ProcessVertices

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateVertexDeclaration Method

Create a vertex shader declaration from the device and the vertex elements.

Syntax

HRESULT CreateVertexDeclaration(

    CONST D3DVERTEXELEMENT9* pVertexElements,
    IDirect3DVertexDeclaration9** ppDecl
);

Parameters

pVertexElements
[in] An array of vertex elements.
ppDecl
[out, retval] Pointer to an IDirect3DVertexDeclaration9 pointer that returns the created vertex shader declaration.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

See the Vertex Declaration page for a detailed description of how to map vertex declarations between different versions of Microsoft® DirectX®.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateVertexShader Method

Creates a vertex shader.

Syntax

HRESULT CreateVertexShader(

    const DWORD *pFunction,
    IDirect3DVertexShader9** ppShader
);

Parameters

pFunction
[in] Pointer to the vertex shader function token array. This parameter defines the operations to apply to each vertex.
ppShader
[out, retval] Pointer to the returned vertex shader interface. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

When a device is created, IDirect3D9::CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities.

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.

  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING.

    Mixed-mode devices might need to switch between software and hardware processing after the device is created. In this case, use IDirect3DDevice9::SetSoftwareVertexProcessing.

See Also

IDirect3D9::CreateDevice, D3DXAssembleShader

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::CreateVolumeTexture Method

Creates a volume texture resource.

Syntax

HRESULT CreateVolumeTexture(

    UINT Width,
    UINT Height,
    UINT Depth,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DVolumeTexture9** ppVolumeTexture,
    HANDLE* pHandle
);

Parameters

Width
[in] Width of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by two results in 0 (zero), 1 will be taken instead.
Height
[in] Height of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Depth
[in] Depth of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] Number of levels in the texture. If this is zero, Microsoft® Direct3D® will generate all texture sublevels down to 1x1 pixels for hardware that supports mipmapped volume textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. If usage is desired, use D3DUSAGE_DYNAMIC or D3DUSAGE_SOFTWAREPROCESSING. For more information, see D3DUSAGE.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out, retval] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture resource.
pHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DeletePatch Method

Frees a cached high-order patch.

Syntax

HRESULT DeletePatch(

    UINT Handle
);

Parameters

Handle
[in] Handle of the cached high-order patch to delete.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::DrawRectPatch, IDirect3DDevice9::DrawTriPatch, Drawing Patches

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawIndexedPrimitive Method

Renders the specified geometric primitive, based on indexing into an array of vertices.

Syntax

HRESULT DrawIndexedPrimitive(

    D3DPRIMITIVETYPE Type,
    INT BaseVertexIndex,
    UINT MinIndex,
    UINT NumVertices,
    UINT StartIndex,
    UINT PrimitiveCount
);

Parameters

Type
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render. D3DPT_POINTLIST is not supported with this method. See Remarks.
BaseVertexIndex
[in] Offset from the start of the index buffer to the first vertex index.
MinIndex
[in] Minimum vertex index for vertices used during this call.
NumVertices
[in] Number of vertices used during this call, starting from BaseVertexIndex + MinIndex
StartIndex
[in] Location in the index array to start reading vertices.
PrimitiveCount
[in] Number of primitives to render. The number of vertices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method draws indexed primitives from the current set of data input streams.

MinIndex and all the indices in the index stream are relative to the BaseVertexIndex.

The MinIndex and NumVertices parameters specify the range of vertex indices used for each IDirect3DDevice9::DrawIndexedPrimitive call. These are used to optimize vertex processing of indexed primitives by processing a sequential range of vertices prior to indexing into these vertices. It is invalid for any indices used during this call to reference any vertices outside of this range.

IDirect3DDevice9::DrawIndexedPrimitive fails if no index array is set.

The D3DPT_POINTLIST member of the D3DPRIMITIVETYPE enumerated type is not supported and is not a valid type for this method.

When converting a fixed function legacy application to Microsoft® DirectX® 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::SetStreamSource, Rendering Primitives

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawIndexedPrimitiveUP Method

Renders the specified geometric primitive with data specified by a user memory pointer.

Syntax

HRESULT DrawIndexedPrimitiveUP(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT MinVertexIndex,
    UINT NumVertexIndices,
    UINT PrimitiveCount,
    const void *pIndexData,
    D3DFORMAT IndexDataFormat,
    CONST void* pVertexStreamZeroData,
    UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
MinVertexIndex
[in] Minimum vertex index, relative to zero (the start of pVertexStreamZeroData), for vertices used during this call.
NumVertexIndices
[in] Number of vertices used during this call, starting from MinVertexIndex.
PrimitiveCount
[in] Number of primitives to render. The number of indices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.
pIndexData
[in] User memory pointer to the index data.
IndexDataFormat
[in] Member of the D3DFORMAT enumerated type, describing the format of the index data. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
pVertexStreamZeroData
[in] User memory pointer to vertex data to use for vertex stream 0.
VertexStreamZeroStride
[in] Stride between data for each vertex, in bytes.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers.

This method supports only a single vertex stream, which must be declared as stream 0.

Following any IDirect3DDevice9::DrawIndexedPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL. Also, the index buffer setting for IDirect3DDevice9::SetIndices is set to NULL.

The vertex data passed to IDirect3DDevice9::DrawIndexedPrimitiveUP does not need to persist after the call. Microsoft® Direct3D® completes its access to that data prior to returning from the call.

When converting a fixed function legacy application to Microsoft DirectX® 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

IDirect3DDevice9::DrawPrimitiveUP, IDirect3DDevice9::SetStreamSource, Rendering Primitives

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawPrimitive Method

Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.

Syntax

HRESULT DrawPrimitive(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT StartVertex,
    UINT PrimitiveCount
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
StartVertex
[in] Index of the first vertex to load. Beginning at StartVertex the correct number of vertices will be read out of the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure. PrimitiveCount is the number of primitives as determined by the primitive type. If it is a line list, each primitive has two vertices. If it is a triangle list, each primitive has three vertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

IDirect3DDevice9::DrawPrimitive should not be called with a single triangle at a time.

When converting a fixed function legacy application to Microsoft® DirectX® 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::SetStreamSource, Rendering Primitives

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawPrimitiveUP Method

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

Syntax

HRESULT DrawPrimitiveUP(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT PrimitiveCount,
    const void *pVertexStreamZeroData,
    UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.
pVertexStreamZeroData
[in] User memory pointer to vertex data to use for vertex stream 0.
VertexStreamZeroStride
[in] Stride between data for each vertex, in bytes.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream. The effect of this call is to use the provided vertex data pointer and stride for vertex stream 0. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream 0.

Following any IDirect3DDevice9::DrawPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL.

The vertex data passed to IDirect3DDevice9::DrawPrimitiveUP does not need to persist after the call. Microsoft® Direct3D® completes its access to that data prior to returning from the call.

When converting a fixed function legacy application to Microsoft DirectX® 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::SetStreamSource, Rendering Primitives

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawRectPatch Method

Draws a rectangular patch using the currently set streams.

Syntax

HRESULT DrawRectPatch(

    UINT Handle,
    const float* pNumSegs,
    const D3DRECTPATCH_INFO* pRectPatchInfo
);

Parameters

Handle
[in] Handle to the rectangular patch to draw.
pNumSegs
[in] Pointer to an array of four floating-point values that identify the number of segments each edge of the rectangle patch should be divided into when tessellated. See D3DRECTPATCH_INFO.
pRectPatchInfo
[in] Pointer to a D3DRECTPATCH_INFO structure, describing the rectangular patch to draw.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Microsoft® Direct3D® can capture and cache information. Call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawRectPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawTriPatch call.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pRectPatchInfo to NULL.

See Also

IDirect3DDevice9::DeletePatch, Drawing Patches

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::DrawTriPatch Method

Draws a triangular patch using the currently set streams.

Syntax

HRESULT DrawTriPatch(

    UINT Handle,
    const float* pNumSegs,
    const D3DTRIPATCH_INFO* pTriPatchInfo
);

Parameters

Handle
[in] Handle to the triangular patch to draw.
pNumSegs
[in] Pointer to an array of three floating-point values that identify the number of segments each edge of the triangle patch should be divided into when tessellated. See D3DTRIPATCH_INFO.
pTriPatchInfo
[in] Pointer to a D3DTRIPATCH_INFO structure, describing the triangular high-order patch to draw.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pTriPatchInfo parameter, and specify a handle so that Microsoft® Direct3D® can capture and cache information. To efficiently draw the patch, call IDirect3DDevice9::DrawTriPatch with pTriPatchInfo set to NULL. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawTriPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawRectPatch call.

For dynamic patches, the patch data changes for every rendering of the patch so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pTriPatchInfo to NULL.

See Also

Using Higher-Order Primitives

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::EndScene Method

Ends a scene that was begun by calling the IDirect3DDevice9::BeginScene method.

Syntax

HRESULT EndScene(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL The method failed because EndScene was called before BeginScene.

Remarks

When this method succeeds, the scene has been queued up for rendering by the driver. This is not a synchronous method, so the scene is not guaranteed to have completed rendering when this method returns.

When scene rendering begins successfully, you must call this method before you can call the IDirect3DDevice9::BeginScene method to start rendering another scene. If a prior call to IDirect3DDevice9::BeginScene method fails, the scene did not begin and this method should not be called.

See Also

IDirect3DDevice9::BeginScene

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::EndStateBlock Method

Signals Microsoft® Direct3D® to stop recording a device-state block and retrieve a handle to the state block.

Syntax

HRESULT EndStateBlock(

    IDirect3DStateBlock9 **ppSB
);

Parameters

ppSB
[in, retval] Pointer to a state block interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::CreateStateBlock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::EvictManagedResources Method

Evicts all managed resources, including both Microsoft® Direct3D® and driver-managed resources.

Syntax

HRESULT EvictManagedResources(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
D3DERR_COMMAND_UNPARSED | The driver could not parse this batch of commands.

Remarks

This function causes only the D3DPOOL_DEFAULT copy of resources to be evicted. The resource copy in system memory is retained. See D3DPOOL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetAvailableTextureMem Method

Returns an estimate of the amount of available texture memory.

Syntax

UINT GetAvailableTextureMem(VOID);

Return Value

The function returns an estimate of the available texture memory.

Remarks

The returned value is rounded to the nearest MB. This is done to reflect the fact that video memory estimates are never precise due to alignment and other issues that affect consumption by certain resources. Applications can use this value to make gross estimates of memory availability to make large-scale resource decisions such as how many levels of a mipmap to attempt to allocate, but applications cannot use this value to make small-scale decisions such as if there is enough memory left to allocate another resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetBackBuffer Method

Retrieves a back buffer from the device's swap chain.

Syntax

HRESULT GetBackBuffer(

    UINT iSwapChain,
    UINT BackBuffer,
    D3DBACKBUFFER_TYPE Type,
    IDirect3DSurface9 **ppBackBuffer
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method.
Type
[in] Stereo view is not supported in Microsoft® DirectX® 9.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetClipPlane Method

Retrieves the coefficients of a user-defined clipping plane for the device.

Syntax

HRESULT GetClipPlane(

    DWORD Index,
    float *pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are retrieved.
pPlane
[out] Pointer to a four-element array of values that represent the coefficients of the clipping plane in the form of the general plane equation. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device, or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

The coefficients that this method reports take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the IDirect3DDevice9::SetClipPlane method.

See Also

IDirect3DDevice9::SetClipPlane

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetClipStatus Method

Retrieves the clip status.

Syntax

HRESULT GetClipStatus(

    D3DCLIPSTATUS9 *pClipStatus
);

Parameters

pClipStatus
[out] Pointer to a D3DCLIPSTATUS9 structure that describes the clip status.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft® Direct3D® computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

See Also

IDirect3DDevice9::SetClipStatus

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetCreationParameters Method

Retrieves the creation parameters of the device.

Syntax

HRESULT GetCreationParameters(

    D3DDEVICE_CREATION_PARAMETERS *pParameters
);

Parameters

pParameters
[out] Pointer to a D3DDEVICE_CREATION_PARAMETERS structure, describing the creation parameters of the device.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

You can query the AdapterOrdinal member of the returned D3DDEVICE_CREATION_PARAMETERS structure to retrieve the ordinal of the adapter represented by this device.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetCurrentTexturePalette Method

Retrieves the current texture palette.

Syntax

HRESULT GetCurrentTexturePalette(

    UINT *pPaletteNumber
);

Parameters

pPaletteNumber
[out, retval] Pointer to a returned value that identifies the current texture palette.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetDepthStencilSurface Method

Gets the depth-stencil surface owned by the Direct3DDevice object.

Syntax

HRESULT GetDepthStencilSurface(

    IDirect3DSurface9 **ppZStencilSurface
);

Parameters

ppZStencilSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned depth-stencil surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the device doesn't have a depth stencil buffer associated with it, the return value will be D3DERR_NOTFOUND. Otherwise, if the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetDepthStencilSurface

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetDeviceCaps Method

Retrieves the capabilities of the rendering device.

Syntax

HRESULT GetDeviceCaps(

    D3DCAPS9 *pCaps
);

Parameters

pCaps
[out] Pointer to a D3DCAPS9 structure, describing the returned device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::GetDeviceCaps retrieves the software vertex pipeline capabilities when the device is being used in software vertex processing mode.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetDirect3D Method

Returns an interface to the instance of the Microsoft® Direct3D® object that created the device.

Syntax

HRESULT GetDirect3D(

    IDirect3D9 **ppD3D9
);

Parameters

ppD3D9
[out, retval] Address of a pointer to an IDirect3D9 interface, representing the interface of the Direct3D object that created the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling IDirect3DDevice9::GetDirect3D increases the reference count on the interface, so applications should call IUnknown::Release through this pointer when finished with the interface.

Note Calling this method will increase the internal reference count on the IDirect3D9 interface. Failure to call IUnknown::Release when finished using this IDirect3D9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetDisplayMode Method

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

Syntax

HRESULT GetDisplayMode(

    UINT iSwapChain,
    D3DDISPLAYMODE *pMode
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetFrontBufferData Method

Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.

Syntax

HRESULT GetFrontBufferData(

    UINT iSwapChain,
    IDirect3DSurface9 *pDestSurface
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pDestSurface
[in] Pointer to an IDirect3DSurface9 interface that will receive a copy of the contents of the front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row on the device's output to the lowest.

For windowed mode, the size of the destination surface should be the size of the desktop. For full-screen mode, the size of the destination surface should be the screen size.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The buffer pointed to by pDestSurface will be filled with a representation of the front buffer, converted to the standard 32 bits per pixel format D3DFMT_A8R8G8B8.

This method is the only way to capture an antialiased screen shot.

This function is very slow, by design, and should not be used in any performance-critical path.

For more information, see Lost Devices and Retrieved Data.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetFVF Method

Gets the fixed vertex function declaration.

Syntax

HRESULT GetFVF(

    DWORD *pFVF
);

Parameters

pFVF
[out] A DWORD pointer to the fixed function vertex type. For more information, see D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The fixed vertex function declaration is a set of flexible vertex format (FVF) flags that determine how vertices processed by the fixed function pipeline will be used. For more information, see Vertex and Pixel Processing.

See Also

IDirect3DDevice9::SetFVF

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetGammaRamp Method

Retrieves the gamma correction ramp for the swap chain.

Syntax

void GetGammaRamp(

    UINT iSwapChain,
    D3DGAMMARAMP *pRamp
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRamp
[in, out] Pointer to an application-supplied D3DGAMMARAMP structure to fill with the gamma correction ramp.

Return Value

None.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::SetGammaRamp

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetIndices Method

Retrieves index data.

Syntax

HRESULT GetIndices(

    IDirect3DIndexBuffer9 **ppIndexData
);

Parameters

ppIndexData
[out] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the returned index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note Calling this method will increase the internal reference count on the IDirect3DIndexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DIndexBuffer9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetIndices

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetLight Method

Retrieves a set of lighting properties that this device uses.

Syntax

HRESULT GetLight(

    DWORD Index,
    D3DLIGHT9 *pLight
);

Parameters

Index
[in] Zero-based index of the lighting property set to retrieve. This method will fail if a lighting property has not been set for this index by calling the IDirect3DDevice9::SetLight method.
pLight
[out] Pointer to a D3DLIGHT9 structure that is filled with the retrieved lighting-parameter set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::SetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetLightEnable Method

Retrieves the activity status—enabled or disabled—for a set of lighting parameters within a device.

Syntax

HRESULT GetLightEnable(

    DWORD Index,
    BOOL *pEnable
);

Parameters

Index
[in] Zero-based index of the set of lighting parameters that are the target of this method.
pEnable
[out, retval] Pointer to a variable to fill with the status of the specified lighting parameters. After the call, a nonzero value at this address indicates that the specified lighting parameters are enabled; a value of 0 indicates that they are disabled.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::LightEnable, IDirect3DDevice9::SetLight

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetMaterial Method

Retrieves the current material properties for the device.

Syntax

HRESULT GetMaterial(

    D3DMATERIAL9 *pMaterial
);

Parameters

pMaterial
[out] Pointer to a D3DMATERIAL9 structure to fill with the currently set material properties.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::SetMaterial

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetNPatchMode Method

Gets the N-patch mode segments.

Syntax

FLOAT GetNPatchMode(VOID);

Return Value

Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

See Also

IDirect3DDevice9::SetNPatchMode

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetNumberOfSwapChains Method

Gets the number of implicit swap chains.

Syntax

UINT GetNumberOfSwapChains(VOID);

Return Value

Number of implicit swap chains. See Remarks.

Remarks

Implicit swap chains are created by the device during IDirect3D9::CreateDevice. This method returns the number of swap chains created by CreateDevice.

An application may create additional swap chains using IDirect3DDevice9::CreateAdditionalSwapChain.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetPaletteEntries Method

Retrieves palette entries.

Syntax

HRESULT GetPaletteEntries(

    UINT PaletteNumber,
    PALETTEENTRY *pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette to retrieve.
pEntries
[in, out] Pointer to a PALETTEENTRY structure, representing the returned palette entries.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For more information about PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK).

Note As of Microsoft DirectX® 9.0, the peFlags member of the PALETTEENTRY structure does not work the way it is documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::SetCurrentTexturePalette, IDirect3DDevice9::SetPaletteEntries, Texture Palettes

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetPixelShader Method

Retrieves the currently set pixel shader.

Syntax

HRESULT GetPixelShader(

    IDirect3DPixelShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a pixel shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::SetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetPixelShaderConstantB Method

Gets a Boolean shader constant.

Syntax

HRESULT GetPixelShaderConstantB(

    UINT StartRegister,
    BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantB

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetPixelShaderConstantF Method

Gets a floating-point shader constant.

Syntax

HRESULT GetPixelShaderConstantF(

    UINT StartRegister,
    float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantF

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetPixelShaderConstantI Method

Gets an integer shader constant.

Syntax

HRESULT GetPixelShaderConstantI(

    UINT StartRegister,
    int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantI

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetRasterStatus Method

Returns information describing the raster of the monitor on which the swap chain is presented.

Syntax

HRESULT GetRasterStatus(

    UINT iSwapChain,
    D3DRASTER_STATUS *pRasterStatus
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

D3DRASTER_STATUS

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetRenderState Method

Retrieves a render-state value for a device.

Syntax

HRESULT GetRenderState(

    D3DRENDERSTATETYPE State,
    DWORD *pValue
);

Parameters

State
[in] Device state variable that is being queried. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
pValue
[out, retval] Pointer to a variable that receives the value of the queried render state variable when the method returns.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

IDirect3DDevice9::SetRenderState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetRenderTarget Method

Retrieves a render target surface.

Syntax

HRESULT GetRenderTarget(

    DWORD RenderTargetIndex,
    IDirect3DSurface9 **ppRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
ppRenderTarget
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned render target surface for this device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL if one of the arguments is invalid, or D3DERR_NOTFOUND if there's no render target available for the given index.

Remarks

The device can now support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Target.

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using the IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetRenderTarget

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetRenderTargetData Method

Copies the render target data from device memory to system memory.

Syntax

HRESULT GetRenderTargetData(

    IDirect3DSurface9* pRenderTarget,
    IDirect3DSurface9* pDestSurface
);

Parameters

pRenderTarget
[in] Pointer to an IDirect3DSurface9 object, representing a render target.
pDestSurface
[in] Pointer to an IDirect3DSurface9 object, representing a destination surface.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

The destination surface must be either an off-screen plain surface or a level of a texture (mipmap or cube texture) created with D3DPOOL_SYSTEMMEM.

The source surface must be a regular render target or a level of a render target texture (mipmap or cube texture) created with POOL_DEFAULT.

This method will fail if:

  • The render target is multisampled.
  • The source render target is a different size than the destination surface.
  • The source render target and destination surface formats do not match.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetSamplerState Method

Gets the sampler state value.

Syntax

HRESULT GetSamplerState(

    DWORD Sampler,
    D3DSAMPLERSTATETYPE Type,
    DWORD* pValue
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
pValue
[out] State value to get. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

IDirect3DDevice9::SetSamplerState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetScissorRect Method

Gets the scissor rectangle.

Syntax

HRESULT GetScissorRect(

    CONST RECT *pRect
);

Parameters

pRect
[out] Returns a pointer to the RECT structure, which defines the rendering area within the render target if scissor test is enabled.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The scissor rectangle is used as a rectangular clipping region.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetSoftwareVertexProcessing Method

Gets the vertex processing (hardware or software) mode.

Syntax

BOOL GetSoftwareVertexProcessing(VOID);

Return Value

Returns TRUE if software vertex processing is set. Otherwise, it returns FALSE.

Remarks

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in Microsoft® DirectX® 8.x, use IDirect3DDevice9::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate BOOL argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In DirectX 9.0, use SetSoftwareVertexProcessing instead. This new application programming interface (API) is not recorded by StateBlocks.

See Also

IDirect3DDevice9::SetSoftwareVertexProcessing

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetStreamSource Method

Retrieves a vertex buffer bound to the specified data stream.

Syntax

HRESULT GetStreamSource(

    UINT StreamNumber,
    IDirect3DVertexBuffer9 **ppStreamData,
    UINT *pOffsetInBytes,
    UINT *pStride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams minus one.
ppStreamData
[in, out] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the returned vertex buffer bound to the specified data stream.
pOffsetInBytes
[out] Pointer containing the offset from the beginning of the stream to the beginning of the vertex data. The offset is measured in bytes. See Remarks.
pStride
[out] Pointer to a returned stride of the component, in bytes. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on.

When a flexible vertex format (FVF) vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

Note Calling this method will increase the internal reference count on the IDirect3DVertexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVertexBuffer9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetStreamSource

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetStreamSourceFreq Method

Gets the stream source frequency divider value.

Syntax

HRESULT GetStreamSourceFreq(

    UINT StreamNumber,
    UINT* pDivider
);

Parameters

StreamNumber
[in] Stream source number.
pDivider
[out] Returns the frequency divider value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Vertex shaders can now be invoked more than once per vertex. See Vertex Stream Frequency.

See Also

IDirect3DDevice9::SetStreamSourceFreq

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetSwapChain Method

Gets a pointer to a swap chain.

Syntax

HRESULT GetSwapChain(

    UINT iSwapChain,
    IDirect3DSwapChain9 **ppSwapChain
);

Parameters

iSwapChain
[in] The swap chain ordinal value. For more information, see NumberOfAdaptersInGroup in D3DCAPS9.
ppSwapChain
[in] Pointer to an IDirect3DSwapChain9 interface that will receive a copy of swap chain.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetTexture Method

Retrieves a texture assigned to a stage for a device.

Syntax

HRESULT GetTexture(

    DWORD Stage,
    IDirect3DBaseTexture9 **ppTexture
);

Parameters

Stage
[in] Stage identifier of the texture to retrieve. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
ppTexture
[out, retval] Address of a pointer to an IDirect3DBaseTexture9 interface, representing the returned texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DTexture9 interface. Failure to call IUnknown::Release when finished using this IDirect3DTexture9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetTexture, IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetTextureStageState Method

Retrieves a state value for an assigned texture.

Syntax

HRESULT GetTextureStageState(

    DWORD Stage,
    D3DTEXTURESTAGESTATETYPE Type,
    DWORD *pValue
);

Parameters

Stage
[in] Stage identifier of the texture for which the state is retrieved. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to retrieve. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
pValue
[out, retval] Pointer a variable to fill with the retrieved state value. The meaning of the retrieved value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE."

See Also

IDirect3DDevice9::SetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetTransform Method

Retrieves a matrix describing a transformation state.

Syntax

HRESULT GetTransform(

    D3DTRANSFORMSTATETYPE State,
    D3DMATRIX *pMatrix
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[out] Pointer to a D3DMATRIX structure, describing the returned transformation state.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE.

See Also

IDirect3DDevice9::SetTransform

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetVertexDeclaration Method

Gets a vertex shader declaration.

Syntax

HRESULT GetVertexDeclaration(

    IDirect3DVertexDeclaration9** ppDecl
);

Parameters

ppDecl
[out] Pointer to an IDirect3DVertexDeclaration9 object that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::SetVertexDeclaration

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetVertexShader Method

Retrieves the currently set vertex shader.

Syntax

HRESULT GetVertexShader(

    IDirect3DVertexShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a vertex shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If ppShader is invalid, D3DERR_INVALIDCALL is returned.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE.

See Also

IDirect3DDevice9::SetVertexShader

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetVertexShaderConstantB Method

Gets a Boolean vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantB(

    UINT StartRegister,
    BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetVertexShaderConstantF Method

Gets a floating-point vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantF(

    UINT StartRegister,
    float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetVertexShaderConstantI Method

Gets an integer vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantI(

    UINT StartRegister,
    int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::GetViewport Method

Retrieves the viewport parameters currently set for the device.

Syntax

HRESULT GetViewport(

    D3DVIEWPORT9 *pViewport
);

Parameters

pViewport
[out] Pointer to a D3DVIEWPORT9 structure, representing the returned viewport parameters.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the pViewport parameter is invalid.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method is an exception, because Microsoft® Direct3D® needs to track viewport data, even on a pure device.

See Also

IDirect3DDevice9::SetViewport

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::LightEnable Method

Enables or disables a set of lighting parameters within a device.

Syntax

HRESULT LightEnable(

    DWORD LightIndex,
    BOOL bEnable
);

Parameters

LightIndex
[in] Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
[in] Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If a value for LightIndex is outside the range of the light property sets assigned within the device, the IDirect3DDevice9::LightEnable method creates a light source represented by a D3DLIGHT9 structure with the following properties and sets its enabled state to the value specified in bEnable.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::SetLight

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::MultiplyTransform Method

Multiplies a device's world, view, or projection matrices by a specified matrix.

Syntax

HRESULT MultiplyTransform(

    D3DTRANSFORMSTATETYPE State,
    CONST D3DMATRIX *pMatrix
);

Parameters

State
[in] Member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro that identifies which device matrix is to be modified. The most common setting, D3DTS_WORLDMATRIX(0), modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

The multiplication order is pMatrix times State.

An application might use the IDirect3DDevice9::MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy.

shoulder_transformation
    upper_arm geometry
    elbow transformation
        lower_arm geometry
        wrist transformation
            hand geometry

An application might use the following series of calls to render this hierarchy. Not all the parameters are shown in this pseudocode.

IDirect3DDevice9::SetTransform(D3DTS_WORLDMATRIX(0),
    shoulder_transform)
IDirect3DDevice9::DrawPrimitive(upper_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    elbow_transform)
IDirect3DDevice9::DrawPrimitive(lower_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    wrist_transform)
IDirect3DDevice9::DrawPrimitive(hand)

See Also

IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::Present Method

Presents the contents of the next buffer in the sequence of back buffers owned by the device.

Syntax

HRESULT Present(

    CONST RECT *pSourceRect,
    CONST RECT *pDestRect,
    HWND hDestWindowOverride,
    CONST RGNDATA *pDirtyRegion
);

Parameters

pSourceRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pSourceRect is a pointer to a RECT structure containing the source rectangle. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pDestRect is a pointer to a RECT structure containing the destination rectangle, in window client coordinates. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Pointer to a destination window whose client area is taken as the target for this presentation. If this value is NULL, then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] Value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. For more information about swap chains, see Flipping Surfaces and D3DSWAPEFFECT.

If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation can choose to copy the whole source rectangle.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

Present will fail, returning D3DERR_INVALIDCALL, if called between BeginScene and EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for Microsoft® DirectX® 9.0.

See Also

IDirect3DDevice9::Reset

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::ProcessVertices Method

Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.

Syntax

HRESULT ProcessVertices(

    UINT SrcStartIndex,
    UINT DestIndex,
    UINT VertexCount,
    IDirect3DVertexBuffer9 *pDestBuffer,
    IDirect3DVertexDeclaration9* pVertexDecl,
    DWORD Flags
);

Parameters

SrcStartIndex
[in] Index of first vertex to load.
DestIndex
[in] Index of first vertex in the destination vertex buffer into which the results are placed.
VertexCount
[in] Number of vertices to process.
pDestBuffer
[in] Pointer to an IDirect3DVertexBuffer9 interface, the destination vertex buffer representing the stream of interleaved vertex data.
pVertexDecl
[in] Pointer to an IDirect3DVertexDeclaration9 interface that represents the output vertex data declaration. When vertex shader 3.0 or above is set as the current vertex shader, the output vertex declaration must be present.
Flags
[in] Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the vertex operation into the destination buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The order of operations for this method is as follows:

  • Transform vertices to projection space using the world + view + projection matrix
  • Compute screen coordinates using viewport settings
  • If clipping is enabled, compute clipping codes and store them in an internal buffer, associated with the destination vertex buffer. If a vertex is inside the viewing frustum, its screen coordinates are computed. If the vertex is outside the viewing frustum, the vertex is stored in the destination vertex buffer in projection space coordinates.
  • Other notes: The user does not have access to the internal clip code buffer. No clipping is done on triangles or any other primitives.

The destination vertex buffer, pDestBuffer, must be created with a nonzero FVF parameter. The flexible vertex format (FVF) code specified during the call to the IDirect3DDevice9::CreateVertexBuffer method specifies the vertex elements present in the destination vertex buffer.

When Microsoft® Direct3D® generates texture coordinates, or copies or transforms input texture coordinates, and the output texture coordinate format defines more texture coordinate components than Direct3D generates, Direct3D does not change these extra components.

See Also

Device Types and Vertex Processing Requirements

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::Reset Method

Resets the type, size, and format of the swap chain.

Syntax

HRESULT Reset(

    D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the new presentation parameters. This value cannot be NULL.

When switching to full-screen mode, Microsoft® Direct3D® will try to find a desktop format that matches the back buffer format, so that back buffer and front buffer formats will be identical (to eliminate the need for color conversion).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

If a call to IDirect3DDevice9::Reset fails, the device will be placed in the "lost" state (as indicated by a return value of D3DERR_DEVICELOST from a call to IDirect3DDevice9::TestCooperativeLevel) unless it is already in the "not reset" state (as indicated by a return value of D3DERR_DEVICENOTRESET from a call to IDirect3DDevice9::TestCooperativeLevel). Refer to IDirect3DDevice9::TestCooperativeLevel and Lost Devices for further information concerning the use of IDirect3DDevice9::Reset in the context of lost devices.

Calling IDirect3DDevice9::Reset causes all texture memory surfaces to be lost, managed textures to be flushed from video memory, and all state information to be lost. Before calling the IDirect3DDevice9::Reset method for a device, an application should release any explicit render targets, depth stencil surfaces, additional swap chains, state blocks and D3DPOOL_DEFAULT resources associated with the device.

The different types of swap chains are full-screen or windowed. If the new swap chain is full-screen, the adapter will be placed in the display mode that matches the new size.

Microsoft DirectX® 9.0 applications can expect messages to be sent to them during this call (for example, before this call is returned); applications should take precautions not to call into Direct3D at this time. In addition, when IDirect3DDevice9::Reset fails, the only valid methods that can be called are IDirect3DDevice9::Reset, IDirect3DDevice9::TestCooperativeLevel, and the various Release member functions. Calling any other method can result in an exception.

A call to IDirect3DDevice9::Reset will fail if called on a different thread than that used to create the device being reset.

Pixel shaders and vertex shaders survive IDirect3DDevice9::Reset calls for DirectX 9.0. They do not need to be re-created explicitly by the application.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. Setting BackBufferCount = 0 results in one back buffer.

See Also

D3DSWAPEFFECT, D3DPRESENT_PARAMETERS, IDirect3DDevice9::Present, Multihead

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetClipPlane Method

Sets the coefficients of a user-defined clipping plane for the device.

Syntax

HRESULT SetClipPlane(

    DWORD Index,
    const float *pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are to be set.
pPlane
[in] Pointer to an address of a four-element array of values that represent the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

The coefficients that this method sets take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist behind the clipping plane are clipped from the scene.

When the fixed function pipeline is used the plane equations are assumed to be in world space. When the programmable pipeline is used the plane equations are assumed to be in the clipping space (the same space as output vertices).

This method does not enable the clipping plane equation being set. To enable a clipping plane, set the corresponding bit in the DWORD value applied to the D3DRS_CLIPPLANEENABLE render state.

See Also

IDirect3DDevice9::GetClipPlane

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetClipStatus Method

Sets the clip status.

Syntax

HRESULT SetClipStatus(

    const D3DCLIPSTATUS9 *pClipStatus
);

Parameters

pClipStatus
[in] Pointer to a D3DCLIPSTATUS9 structure, describing the clip status settings to be set.

Return Value

If the method succeeds, the return value is D3D_OK.

If one of the arguments is invalid, the return value is D3DERR_INVALIDCALL.

Remarks

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft® Direct3D® computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

See Also

IDirect3DDevice9::GetClipStatus

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetCurrentTexturePalette Method

Sets the current texture palette.

Syntax

HRESULT SetCurrentTexturePalette(

    UINT PaletteNumber
);

Parameters

PaletteNumber
[in] Value that specifies the texture palette to set as the current texture palette.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A single logical palette is associated with the device, and is shared by all texture stages.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, Texture Palettes

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetCursorPosition Method

Sets the cursor position and update options.

Syntax

void SetCursorPosition(

    INT X,
    INT Y,
    DWORD Flags
);

Parameters

X
[in] The new X-position of the cursor in virtual desktop coordinates. See Remarks.
Y
[in] The new Y-position of the cursor in virtual desktop coordinates. See Remarks.
Flags
[in] Specifies the update options for the cursor. Currently, only one flag is defined.
D3DCURSOR_IMMEDIATE_UPDATE
Update cursor at the refresh rate.

If this flag is specified, the system guarantees that the cursor will be updated at a minimum of half the display refresh rate, but never more frequently than the display refresh rate. Otherwise, the method delays cursor updates until the next IDirect3DDevice9::Present call. Not setting this flag usually results in better performance than if the flag is set. However, applications should set this flag if the rate of calls to Present is low enough that users would notice a significant delay in cursor motion. This flag has no effect in a windowed-mode application. Some video cards implement hardware color cursors. This flag doesn't have an effect on these cards.

Return Value

None.

Remarks

When running in full-screen mode, screen space coordinates are the back buffer coordinates appropriately scaled to the current display mode. When running in windowed mode, screen space coordinates are the desktop coordinates. The cursor image is drawn at the specified position minus the hotspot-offset specified by the IDirect3DDevice9::SetCursorProperties method.

If the cursor has been hidden by IDirect3DDevice9::ShowCursor, the cursor is not drawn.

See Also

IDirect3DDevice9::SetCursorProperties, IDirect3DDevice9::ShowCursor

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetCursorProperties Method

Sets properties for the cursor.

Syntax

HRESULT SetCursorProperties(

    UINT XHotSpot,
    UINT YHotSpot,
    IDirect3DSurface9 *pCursorBitmap
);

Parameters

XHotSpot
[in] X-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
YHotSpot
[in] Y-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
pCursorBitmap
[in] Pointer to an IDirect3DSurface9 interface. This parameter must point to an 8888 ARGB surface (format D3DFMT_A8R8G8B8). The contents of this surface will be copied and potentially format-converted into an internal buffer from which the cursor is displayed. The dimensions of this surface must be less than the dimensions of the display mode, and must be a power of two in each direction, although not necessarily the same power of two. The alpha channel must be either 0.0 or 1.0.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An operating system cursor is created and used under either of these conditions:

  • The hardware has set D3DCURSORCAPS_COLOR (see D3DCURSORCAPS), and the cursor size is 32x32 (which is the cursor size in the operating system).
  • The application is running in windowed mode.

Otherwise, Microsoft® DirectX® uses an emulated cursor. An application uses IDirect3DDevice9::SetCursorPosition to move an emulated cursor to follow mouse movement.

It is recommended for applications to always trap WM_MOUSEMOVE events and call DXSetCursorPosition.

Microsoft Direct3D® cursor functions use either Microsoft Windows® Graphics Device Interface (GDI) cursor or software emulation, depending on the hardware. Users typically want to respond to a WM_SETCURSOR message. For example, they might want to write the message handler as follows:

case WM_SETCURSOR:
// Turn off window cursor.
SetCursor( NULL );
m_pd3dDevice->ShowCursor( TRUE );
return TRUE; // Prevent Windows from setting cursor to window class cursor.
break;

Or, users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor.

The application can determine what hardware support is available for cursors by examining appropriate members of the D3DCAPS9 structure. Typically, hardware supports only 32x32 cursors and, when windowed, the system might support only 32x32 cursors. In this case, IDirect3DDevice9::SetCursorProperties still succeeds but the cursor might be reduced to that size. The hot spot is scaled appropriately.

The cursor does not survive when the device is lost. This method must be called after the device is reset.

See Also

IDirect3DDevice9::ShowCursor, D3DCAPS9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetDepthStencilSurface Method

Sets the depth stencil surface.

Syntax

HRESULT SetDepthStencilSurface(

    IDirect3DSurface9 *pZStencilSurface
);

Parameters

pZStencilSurface
[in] Address of a pointer to an IDirect3DSurface9 interface, representing the depth stencil surface. Setting this to NULL disables the depth stencil operation and releases the previous depth stencil buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If pZStencilSurface is other than NULL, the return value is D3DERR_INVALIDCALL when the stencil surface is invalid.

Remarks

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be >= to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetDepthStencilSurface with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetDepthStencilSurface.

See Also

IDirect3DDevice9::GetDepthStencilSurface

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetDialogBoxMode Method

This method allows the use of Microsoft® Windows® Graphics Device Interface (GDI) dialog boxes in full-screen mode applications.

Syntax

HRESULT SetDialogBoxMode(

    BOOL bEnableDialogs
);

Parameters

bEnableDialogs
[in] TRUE to enable GDI dialog boxes, and FALSE to disable them.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL unless all of the following are true.

  • The application specified a back buffer format compatible with GDI, in other words, one of D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, or D3DFMT_X8R8G8B8.
  • The application specified no multisampling.
  • The application specified D3DSWAPEFFECT_DISCARD.
  • The application specified D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.
  • The application did not specify D3DCREATE_ADAPTERGROUP_DEVICE.
  • The application is not between BeginScene and EndScene.

Remarks

The GDI dialog boxes must be created as child to the device window. They should also be created within the same thread that created the device because this enables the parent window to manage redrawing the child window.

The method has no effect for windowed mode applications, but this setting will be respected if the application resets the device into full-screen mode. If SetDialogBoxMode succeeds in a windowed mode application, any subsequent reset to full-screen mode will be checked against the restrictions listed above. Also, SetDialogBoxMode causes all back buffers on the swap chain to be discarded, so an application is expected to refresh its content for all back buffers after this call.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetFVF Method

Sets the current vertex stream declaration.

Syntax

HRESULT SetFVF(

    DWORD FVF
);

Parameters

FVF
[in] DWORD containing the fixed function vertex type. For more information, see D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetFVF

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetGammaRamp Method

Sets the gamma correction ramp for the implicit swap chain.

Syntax

void SetGammaRamp(

    UINT iSwapChain,
    DWORD Flags,
    CONST D3DGAMMARAMP *pRamp
);

Parameters

iSwapChain
[in] Unsigned integer specifying the swap chain.
Flags
[in] Indicates whether correction should be applied. Gamma correction results in a more consistent display, but can incur processing overhead and should not be used frequently. Short-duration effects such as flashing the whole screen red should not be calibrated, but long-duration gamma changes should be calibrated. One of the following values can be set.
D3DSGR_CALIBRATE
If a gamma calibrator is installed, the ramp will be modified before being sent to the device to account for the system and monitor response curves. If a calibrator is not installed, the ramp will be passed directly to the device.
D3DSGR_NO_CALIBRATION
No gamma correction is applied. The supplied gamma table is transferred directly to the device.
pRamp
[in] Pointer to a D3DGAMMARAMP structure, representing the gamma correction ramp to be set for the implicit swap chain.

Return Value

None.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device, because Microsoft® Direct3D® for Microsoft DirectX® 9.0 has one swap chain as a property of the device.

Starting with version DirectX 8.x, setting a gamma ramp has no effect unless the swap chain is full-screen. To change the gamma ramp in windowed mode, use the Microsoft Windows® Graphics Device Interface (GDI) function SetDeviceGammaRamp, which will impact the entire screen(not just the active window). SetDeviceGammaRamp will not allow "extreme" gamma ramps, such as an all red gamma ramp. In contrast, IDirect3DDevice9::SetGammaRamp will clean up the gamma ramp when the application is minimized or exits, and then restore it again when the application is restored.

The gamma ramp takes effect immediately. No wait for VSYNC is performed.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error return is given. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 structure to determine the capabilities of the device and whether a calibrator is installed.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::GetGammaRamp

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetIndices Method

Sets index data.

Syntax

HRESULT SetIndices(

    IDirect3DIndexBuffer9 *pIndexData
);

Parameters

pIndexData
[in] Pointer to an IDirect3DIndexBuffer9 interface, representing the index data to be set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When an application no longer holds a references to this interface, the interface will automatically be freed.

The IDirect3DDevice9::SetIndices method sets the current index array to an index buffer. The single set of indices is used to index all streams.

See Also

IDirect3DDevice9::GetIndices

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetLight Method

Assigns a set of lighting properties for this device.

Syntax

HRESULT SetLight(

    DWORD Index,
    CONST D3DLIGHT9 *pLight
);

Parameters

Index
[in] Zero-based index of the set of lighting properties to set. If a set of lighting properties exists at this index, it is overwritten by the new properties specified in pLight.
pLight
[in] Pointer to a D3DLIGHT9 structure, containing the lighting parameters to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetMaterial Method

Sets the material properties for the device.

Syntax

HRESULT SetMaterial(

    CONST D3DMATERIAL9 *pMaterial
);

Parameters

pMaterial
[in] Pointer to a D3DMATERIAL9 structure, describing the material properties to set.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

See Also

IDirect3DDevice9::GetMaterial

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetNPatchMode Method

Enable or disable N-patches.

Syntax

HRESULT SetNPatchMode(

    float nSegments
);

Parameters

nSegments
[in] Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

Return Value

If the method succeeds, the return value is D3D_OK.

See Also

IDirect3DDevice9::GetNPatchMode

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetPaletteEntries Method

Sets palette entries.

Syntax

HRESULT SetPaletteEntries(

    UINT PaletteNumber,
    const PALETTEENTRY *pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette upon which the operation is to be performed.
pEntries
[in] Pointer to a PALETTEENTRY structure, representing the palette entries to set. The number of PALETTEENTRY structures pointed to by pEntries is assumed to be 256. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For Microsoft® DirectX® 9.0 applications, any palette sent to this method must conform to the D3DPTEXTURECAPS_ALPHAPALETTE capability bit of the D3DCAPS9 structure. If D3DPTEXTURECAPS_ALPHAPALETTE is not set, every entry in the palette must have alpha set to 1.0 or this method will fail with D3DERR_INVALIDCALL. If D3DPTEXTURECAPS_ALPHAPALETTE is set, then any set of alpha values are allowed. Note that the debug runtime will print a warning message if all palette entries have alpha set to 0.

A single logical palette is associated with the device, and is shared by all texture stages.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::GetPaletteEntries, IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetPixelShader Method

Sets the current pixel shader to a previously created pixel shader.

Syntax

HRESULT SetPixelShader(

    IDirect3DPixelShader9* pShader
);

Parameters

pShader
[in] Pixel shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetPixelShaderConstantB Method

Sets a Boolean shader constant.

Syntax

HRESULT SetPixelShaderConstantB(

    UINT StartRegister,
    CONST BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantB

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetPixelShaderConstantF Method

Sets a floating-point shader constant.

Syntax

HRESULT SetPixelShaderConstantF(

    UINT StartRegister,
    CONST float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantF

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetPixelShaderConstantI Method

Sets an integer shader constant.

Syntax

HRESULT SetPixelShaderConstantI(

    UINT StartRegister,
    CONST int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantI

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetRenderState Method

Sets a single device render-state parameter.

Syntax

HRESULT SetRenderState(

    D3DRENDERSTATETYPE State,
    DWORD Value
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
Value
[in] New value for the device render state to be set. The meaning of this parameter is dependent on the value specified for State. For example, if State were D3DRS_SHADEMODE, the second parameter would be one member of the D3DSHADEMODE enumerated type.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetTransform

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetRenderTarget Method

Sets a new color buffer for the device.

Syntax

HRESULT SetRenderTarget(

    DWORD RenderTargetIndex,
    IDirect3DSurface9 *pRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
pRenderTarget
[in] Pointer to a new color buffer. If NULL, the color buffer for the corresponding RenderTargetIndex is disabled. If this parameter is other than NULL, the reference count on the new render target is incremented. Devices always must be associated with a color buffer.

The new render target surface must have at least D3DUSAGE_RENDERTARGET specified.

Return Value

If the method succeeds, the return value is D3D_OK.

This method will return D3DERR_INVALIDCALL if either:

  • pRenderTarget = NULL and RenderTargetIndex = 0
  • pRenderTarget is != NULL and the render target is invalid.

Remarks

The device can now support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Target.

Some hardware tests the compatibility of the depth stencil buffer with the color buffer. If this is done, it is only done in a debug build.

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be greater than or equal to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetSamplerState Method

Sets the sampler state value.

Syntax

HRESULT SetSamplerState(

    DWORD Sampler,
    D3DSAMPLERSTATETYPE Type,
    DWORD Value
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetSamplerState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetScissorRect Method

Sets the scissor rectangle.

Syntax

HRESULT SetScissorRect(

    CONST RECT *pRect
);

Parameters

pRect
[in] Pointer to a RECT structure that defines the rendering area within the render target if scissor test is enabled. This parameter may not be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The scissor rectangle is used as a rectangular clipping region.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetSoftwareVertexProcessing Method

Use this method to switch between software and hardware vertex processing.

Syntax

HRESULT SetSoftwareVertexProcessing(

    BOOL bSoftware
);

Parameters

bSoftware
[in] TRUE to specify software vertex processing; FALSE to specify hardware vertex processing.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The restrictions for changing modes are as follows:

  • If a device is created with D3DCREATE_SOFTWARE_VERTEXPROCESSING, the vertex processing will be done in software and cannot be changed.
  • If a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING, the vertex processing will be done in hardware and cannot be changed.
  • If a device is created with D3DCREATE_MIXED_VERTEXPROCESSING, the vertex processing will be done in hardware by default. The processing can be switched to software (or back to hardware) using IDirect3DDevice9::SetSoftwareVertexProcessing.

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in Microsoft® DirectX® 8.x, use IDirect3DDevice8::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate DWORD argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In DirectX 9.0, use SetSoftwareVertexProcessing instead. This new application programming interface (API) is not recorded by StateBlocks.

See Also

IDirect3DDevice9::GetSoftwareVertexProcessing

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetStreamSource Method

Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source.

Syntax

HRESULT SetStreamSource(

    UINT StreamNumber,
    IDirect3DVertexBuffer9 *pStreamData,
    UINT OffsetInBytes,
    UINT Stride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams -1.
pStreamData
[in] Pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer to bind to the specified data stream.
OffsetInBytes
[in] Offset from the beginning of the stream to the beginning of the vertex data, in bytes. To find out if the device supports stream offsets, see the D3DDEVCAPS2_STREAMOFFSET constant in D3DDEVCAPS2.
Stride
[in] Stride of the component, in bytes. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When a flexible vertex format (FVF) vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

When an application no longer holds a references to this interface, the interface will automatically be freed.

See Also

IDirect3DDevice9::GetStreamSource, IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetStreamSourceFreq Method

Sets the stream source frequency divider value.

Syntax

HRESULT SetStreamSourceFreq(

    UINT StreamNumber,
    UINT Divider
);

Parameters

StreamNumber
[in] Stream source number.
Divider
[in] Frequency divider value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Vertex shaders can now be invoked more than once per vertex. See Vertex Stream Frequency.

See Also

IDirect3DDevice9::GetStreamSourceFreq

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetTexture Method

Assigns a texture to a stage for a device.

Syntax

HRESULT SetTexture(

    DWORD Stage,
    IDirect3DBaseTexture9 *pTexture
);

Parameters

Stage
[in] Stage identifier to which the texture is set. Stage identifiers are zero-based. The maximum number of stages supported is determined from two caps: D3DCAPS.MaxSimultaneousTextureStages and D3DCAPS9.MaxTextureBlendingStages.

Displacement Mapping uses a special stage index, called D3DDDMAPSAMPLER.

Vertex Textures use a special stage index called D3DVERTEXTEXTURESAMPLER.

pTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the texture being set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::SetTexture is not allowed if the texture is created with a pool type of D3DPOOL_SCRATCH. IDirect3DDevice9::SetTexture is not allowed with a pool type of D3DPOOL_SYSTEMMEM texture unless DevCaps is set with D3DDEVCAPS_TEXTURESYSTEMMEMORY.

See Also

IDirect3DDevice9::GetTexture, IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetTextureStageState Method

Sets the state value for the currently assigned texture.

Syntax

HRESULT SetTextureStageState(

    DWORD Stage,
    D3DTEXTURESTAGESTATETYPE Type,
    DWORD Value
);

Parameters

Stage
[in] Stage identifier of the texture for which the state value is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to set. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetTransform Method

Sets a single device transformation-related state.

Syntax

HRESULT SetTransform(

    D3DTRANSFORMSTATETYPE State,
    CONST D3DMATRIX *pMatrix
);

Parameters

State
[in] Device-state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::SetRenderState, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetVertexDeclaration Method

Sets a vertex shader declaration.

Syntax

HRESULT SetVertexDeclaration(

    IDirect3DVertexDeclaration9 *pDecl
);

Parameters

pDecl
[in] Pointer to an IDirect3DVertexDeclaration9 object, which contains the vertex declaration.

Return Value

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetVertexDeclaration

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetVertexShader Method

Sets the vertex shader.

Syntax

HRESULT SetVertexShader(

    IDirect3DVertexShader9* pShader
);

Parameters

pShader
[in] Vertex shader interface. For more information, see IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

To set a fixed-function vertex shader (after having set a programmable vertex shader), call IDirect3DDevice9::SetVertexShader(NULL) to release the programmable shader, and then call IDirect3DDevice9::SetFVF with the fixed-function vertex format.

See Also

IDirect3DDevice9::GetVertexShader

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetVertexShaderConstantB Method

Sets a Boolean vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantB(

    UINT StartRegister,
    CONST BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetVertexShaderConstantF Method

Sets a floating-point vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantF(

    UINT StartRegister,
    CONST float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetVertexShaderConstantI Method

Sets an integer vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantI(

    UINT StartRegister,
    CONST int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::SetViewport Method

Sets the viewport parameters for the device.

Syntax

HRESULT SetViewport(

    CONST D3DVIEWPORT9 *pViewport
);

Parameters

pViewport
[in] Pointer to a D3DVIEWPORT9 structure, specifying the viewport parameters to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, it will return D3DERR_INVALIDCALL. This will happen if pViewport is invalid, or if pViewport describes a region that cannot exist within the render target surface.

Remarks

Microsoft® Direct3D® sets the following default values for the viewport.

D3DVIEWPORT9 vp;
vp.X      = 0;
vp.Y      = 0;
vp.Width  = RenderTarget.Width;
vp.Height = RenderTarget.Height;
vp.MinZ   = 0.0f;
vp.MaxZ   = 1.0f;

IDirect3DDevice9::SetViewport can be used to draw on part of the screen. Make sure to call it before any geometry is drawn so the viewport settings will take effect.

To draw multiple views within a scene, repeat the IDirect3DDevice9::SetViewport and draw geometry sequence for each view.

See Also

IDirect3DDevice9::GetViewport

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::ShowCursor Method

Displays or hides the cursor.

Syntax

BOOL ShowCursor(

    BOOL bShow
);

Parameters

bShow
[in] If bShow is TRUE, the cursor is shown. If bShow is FALSE, the cursor is hidden.

Return Value

Value indicating whether the cursor was previously visible. TRUE if the cursor was previously visible, or FALSE if the cursor was not previously visible.

Remarks

Microsoft® Direct3D® cursor functions use either Microsoft Windows® Graphics Device Interface (GDI) cursor or software emulation, depending on the hardware. Users usually want to respond to a WM_SETCURSOR message. For example, the users might want to write the message handler like this:

case WM_SETCURSOR:
    // Turn off window cursor
    SetCursor( NULL );
    m_pd3dDevice->ShowCursor( TRUE );
    return TRUE; // prevent Windows from setting cursor to window class cursor
break;

Or users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor. See the code in the Microsoft DirectX® Graphics C/C++ Samples for more detail.

See Also

IDirect3DDevice9::SetCursorPosition, IDirect3DDevice9::SetCursorProperties

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::StretchRect Method

Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.

Syntax

HRESULT StretchRect(

    IDirect3DSurface9 *pSourceSurface,
    CONST RECT *pSourceRect,
    IDirect3DSurface9 *pDestSurface,
    CONST RECT *pDestRect,
    D3DTEXTUREFILTERTYPE Filter
);

Parameters

pSourceSurface
[in] Pointer to the source surface. See IDirect3DSurface9.
pSourceRect
[in] Pointer to the source rectangle. A NULL for this parameter causes the entire source surface to be used.
pDestSurface
[in] Pointer to the destination surface. See IDirect3DSurface9.
pDestRect
[in] Pointer to the destination rectangle. A NULL for this parameter causes the entire destination surface to be used.
Filter
[in] Filter type. Allowable values are D3DTEXF_NONE, D3DTEXF_POINT, or D3DTEXF_LINEAR. For more information, see D3DTEXTUREFILTERTYPE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

General Restrictions

There are many restrictions as to which surface combinations are valid for IDirect3DDevice9::StretchRect. Factors include whether the driver is a Microsoft® DirectX® 9.0 driver or older, and whether the operation will result in stretching/shrinking. Since applications are not expected to recognize if the driver is a DirectX 9.0 driver or not, Microsoft Direct3D® will automatically set a new D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES cap in the D3DDEVCAPS2 structure for DirectX 9.0-level drivers and above.

DirectX 8.x Driver (no stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | Yes | Yes | Yes | Yes

DirectX 8.x Driver (stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
RT texture | No | No | No | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | No

DirectX 9.0 Driver (no stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | Yes

DirectX 9.0 Driver (stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | No

IDirect3DDevice9::StretchRect requires that both the source and destination surfaces must be D3DPOOL_DEFAULT surfaces.

If filtering is specified, IDirect3DDevice9::StretchRect will fail unless the driver sets the appropriate StretchRectFilterCaps in D3DCAPS9. If D3DTEXF_NONE is specified, the driver will choose a filtering algorithm.

The stretch operation supports color-space conversion from YUV to high-precision RGBA only. Stretching between rectangles on the same surface is not supported. Use IDirect3D9::CheckDeviceFormatConversion to test the hardware for color conversion support because software emulation for the conversion is not supported.

Texture Restrictions

IDirect3DDevice9::StretchRect will work for a texture surface (or a cube texture surface) only for DirectX 9.0 drivers (drivers that set D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES).

Depth and Stencil Restrictions

Depth and stencil surfaces can be copied using IDirect3DDevice9::StretchRect with the following restrictions.
  • Both the source and destination surfaces must be created with IDirect3DDevice9::CreateDepthStencilSurface, because they must be plain depth stencil surfaces (not textures).
  • Both surfaces must be the same format (no format conversion).
  • No stretching or shrinking is allowed.
  • Subrectangle copies are not allowed. The entire surface must be copied. In other words, pSourceRect and pDestRect must be NULL, or point to rectangles that cover the whole surface.
  • StretchRect cannot be called inside of IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pairs.
  • The source or destination surface can't be a mip level of a texture (cube texture) created with D3DUSAGE_DEPTHSTENCIL.
  • Neither of the surfaces can be created as "discardable."
  • Drivers must set D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES. See D3DDEVCAPS2.

IDirect3DDevice9::StretchRect will fail for any of the following:

  • If pSourceSurface and pDestSurface are the same.
  • If stretching or shrinking is involved and either surface has a DXTn compressed format.
  • If the source surface is multisampled (created with MultiSampleType != D3DMULTISAMPLE_NONE).
  • If the destination surface is an off-screen plain surface but the source is not. If the destination surface is an off-screen plain surface and stretching is involved.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::TestCooperativeLevel Method

Reports the current cooperative-level status of the Microsoft® Direct3D® device for a windowed or full-screen application.

Syntax

HRESULT TestCooperativeLevel(VOID);

Return Value

If the method succeeds, the return value is D3D_OK, indicating that the device is operational and the calling application can continue.

If the method fails, the return value can be one of the following values (see Remarks).

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DEVICENOTRESET | The device has been lost but can be reset at this time.

Remarks

If the device is lost but cannot be restored at the current time, IDirect3DDevice9::TestCooperativeLevel returns the D3DERR_DEVICELOST return code. This would be the case, for example, when a full-screen device has lost focus. If an application detects a lost device, it should pause and periodically call IDirect3DDevice9::TestCooperativeLevel until it receives a return value of D3DERR_DEVICENOTRESET. The application may then attempt to reset the device by calling IDirect3DDevice9::Reset and, if this succeeds, restore the necessary resources and resume normal operation. Note that IDirect3DDevice9::Present will return D3DERR_DEVICELOST if the device is either "lost" or "not reset".

A call to IDirect3DDevice9::TestCooperativeLevel will fail if called on a different thread than that used to create the device being reset.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::UpdateSurface Method

Copies rectangular subsets of pixels from one surface to another.

Syntax

HRESULT UpdateSurface(

    IDirect3DSurface9* pSourceSurface,
    CONST RECT* pSourceRect,
    IDirect3DSurface9* pDestinationSurface,
    CONST POINT* pDestinationPoint
);

Parameters

pSourceSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface. This parameter must point to a different surface than pDestinationSurface.
pSourceRect
[in] Pointer to a rectangle on the source surface. Specifying NULL for this parameter causes the entire surface to be copied.
pDestinationSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the destination surface.
pDestinationPoint
[in] Pointer to the upper left corner of the destination rectangle. Specifying NULL for this parameter causes the entire surface to be copied.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is similar to CopyRects in Microsoft® DirectX® 8.0.

This function has the following restrictions.

  • The source surface must have been created with D3DPOOL_SYSTEMMEM.
  • The destination surface must have been created with D3DPOOL_DEFAULT.
  • Neither surface can be locked or holding an outstanding device context.
  • Neither surface can be created with multisampling. The only valid flag for both surfaces is D3DMULTISAMPLE_NONE.
  • The surface format cannot be a depth stencil format.
  • The source and dest rects must fit within the surface.
  • No stretching or shrinking is allowed (the rects must be the same size).
  • The source format must match the dest format.

The following table shows the supported combinations.

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | Yes | Yes | Yes* | Yes
RT texture | No | No | No | No
RT | No | No | No | No
Off-screen plain | Yes | Yes | Yes | Yes

* If the driver does not support the requested copy, it will be emulated using lock and copy.

If the application needs to copy data from a D3DPOOL_DEFAULT render target to a D3DPOOL_SYSTEMMEM surface, it can use IDirect3DDevice9::GetRenderTargetData.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::UpdateTexture Method

Updates the dirty portions of a texture.

Syntax

HRESULT UpdateTexture(

    IDirect3DBaseTexture9 *pSourceTexture,
    IDirect3DBaseTexture9 *pDestinationTexture
);

Parameters

pSourceTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the source texture. The source texture must be in system memory (D3DPOOL_SYSTEMMEM).
pDestinationTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the destination texture. The destination texture must be in the D3DPOOL_DEFAULT memory pool.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

You can dirty a portion of a texture by locking it, or by calling one of the following methods.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox
  • IDirect3DDevice9::UpdateSurface

IDirect3DDevice9::UpdateTexture retrieves the dirty portions of the texture by calculating what has been accumulated since the last update operation.

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

This method fails if the textures are of different types, if their bottom-level buffers are of different sizes, or if their matching levels do not match. For example, consider a six-level source texture with the following dimensions.

32x16, 16x8, 8x4, 4x2, 2x1, 1x1

This six-level source texture could be the source for the following one-level destination.

1x1

For the following two-level destination.

2x1, 1x1

Or, for the following three-level destination.

4x2, 2x1, 1x1

In addition, this method will fail if the textures are of different formats. If the destination texture has fewer levels than the source, only the matching levels are copied. If the source texture has fewer levels than the destination, the method will fail.

If the source texture has dirty regions, the copy can be optimized by restricting the copy to only those regions. It is not guaranteed that only those bytes marked dirty will be copied.

Here are the possibilities for source and destination surface combinations:

  • If pSourceTexture is a non-autogenerated mipmap and pDestinationTexture is an autogenerated mipmap, only the topmost matching level is updated, and the destination sublevels are regenerated. All other source sublevels are ignored.
  • If both pSourceTexture and pDestinationTexture are autogenerated mipmaps, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.
  • If pSourceTexture is an autogenerated mipmap and pDestinationTexture a non-autogenerated mipmap, UpdateTexture will fail.

See Also

IDirect3D9::CreateDevice

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DDevice9::ValidateDevice Method

Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

Syntax

HRESULT ValidateDevice(

    DWORD *pNumPasses
);

Parameters

pNumPasses
[out, retval] Pointer to a DWORD value to fill with the number of rendering passes needed to complete the desired effect through multipass rendering.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_CONFLICTINGTEXTUREFILTER | The current texture filters cannot be used together.
D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_TOOMANYOPERATIONS | The application is requesting more texture-filtering operations than the device supports.
D3DERR_UNSUPPORTEDALPHAARG | The device does not support a specified texture-blending argument for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION | The device does not support a specified texture-blending operation for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG | The device does not support a specified texture-blending argument for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION | The device does not support a specified texture-blending operation for color values.
D3DERR_UNSUPPORTEDFACTORVALUE | The device does not support the specified texture factor value.
D3DERR_UNSUPPORTEDTEXTUREFILTER | The device does not support the specified texture filter.
D3DERR_WRONGTEXTUREFORMAT | The pixel format of the texture surface is not valid.

Remarks

The IDirect3DDevice9::ValidateDevice method should be used to validate scenarios only when other capabilities are deficient. For example, in a multistage texturing scenario, you could query the MaxTextureBlendStages and MaxSimultaneousTextures members of a D3DCAPS9 structure to determine if multistage texturing is possible on the device.

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given arguments by setting the desired blending operation, and then calling the IDirect3DDevice9::ValidateDevice method.

The IDirect3DDevice9::ValidateDevice method uses the current render states, textures, and texture-stage states to perform validation at the time of the call. Changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

For best performance, call IDirect3DDevice9::ValidateDevice at initialization time; do not use it within a render loop.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSED3DTOP_BLENDDIFFUSEALPHA) is rarely supported on current hardware. Most hardware can introduce iterated color data only at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first argument, rather than the second argument.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are available only at the first or last texture-blending stage.

Many cards do not have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels or inverting the input. Therefore, your application might need to use only the second texture stage, if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color argument set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than or substantially different from the color operations are less likely to be supported.

Some hardware does not support simultaneous use of D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering and revalidate. In this case, you might want to perform multipass rendering instead.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9 Interface

Applications use the methods of the IDirect3DIndexBuffer9 interface to manipulate an index buffer resource.

IDirect3DIndexBuffer9 Members

FreePrivateData

Frees the specified private data associated with this resource.

GetDesc

Retrieves a description of the index buffer resource.

GetDevice

Retrieves the device associated with a resource.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

Lock

Locks a range of index data and obtains a pointer to the index buffer memory.

PreLoad

Preloads a managed resource.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Unlock

Unlocks index data.

Remarks

The IDirect3DIndexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateIndexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DINDEXBUFFER9 and PDIRECT3DINDEXBUFFER9 types are defined as pointers to the IDirect3DIndexBuffer9 interface.

typedef struct IDirect3DIndexBuffer9 *LPDIRECT3DINDEXBUFFER9, *PDIRECT3DINDEXBUFFER9;

Interface Information

Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::GetDesc Method

Retrieves a description of the index buffer resource.

Syntax

HRESULT GetDesc(

    D3DINDEXBUFFER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DINDEXBUFFER_DESC structure, describing the returned index buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::Lock Method

Locks a range of index data and obtains a pointer to the index buffer memory.

Syntax

HRESULT Lock(

    UINT OffsetToLock,
    UINT SizeToLock,
    VOID **ppbData,
    DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned index data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. IDirect3DDevice9::DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

See Programming Tips for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE.

See Also

IDirect3DIndexBuffer9::Unlock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::Unlock Method

Unlocks index data.

Syntax

HRESULT Unlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DIndexBuffer9::Lock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DPixelShader9 Interface

Applications use the methods of the IDirect3DPixelShader9 interface to encapsulate the functionality of a pixel shader.

IDirect3DPixelShader9 Members

GetDevice | Gets the device.
GetFunction | Gets a pointer to the shader data.

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DPixelShader9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DPixelShader9::GetFunction Method

Gets a pointer to the shader data.

Syntax

HRESULT GetFunction(

    void* pData,
    UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9 Interface

Applications use the methods of the IDirect3DQuery9 interface to perform asynchronous queries on a driver.

IDirect3DQuery9 Members

GetData | Gets the query information.
GetDataSize | Gets the number of bytes in the query data.
GetDevice | Gets the device that is being queried.
GetType | Gets the query type.
Issue | Issue a query.

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9::GetData Method

Gets the query information.

Syntax

HRESULT GetData(

    void* pData,
    DWORD dwSize,
    DWORD dwGetDataFlags
);

Parameters

pData
[in, out] Pointer to a buffer containing the query data.
dwSize
[in] Number of bytes of data. See Remarks.
dwGetDataFlags
[in] Data flags specifying the query type. Valid values are either 0 or D3DGETDATA_FLUSH, which will force the runtime to flush the query down to the driver. See Remarks.

Return Value

The method returns S_OK if the query data is available and S_FALSE if it is not. These are considered successful return values.

If the method fails when D3DGETDATA_FLUSH is used, the return value can be D3DERR_DEVICELOST.

Remarks

The application is expected to pass the right amount of data for the query results. If the query result is available, the runtime returns the query data.

The size of dwSize depends on the query type given as follows:
Query Type | Size
D3DQUERYTYPE_VCACHE | sizeof(D3DDEVINFO_VCACHE)
D3DQUERYTYPE_RESOURCEMANAGER | sizeof(D3DDEVINFO_RESOURCEMANAGER)
D3DQUERYTYPE_VERTEXSTATS | sizeof(D3DDEVINFO_D3DVERTEXSTATS)
D3DQUERYTYPE_EVENT | sizeof(BOOL)
D3DQUERYTYPE_OCCLUSION | sizeof(DWORD)

Use D3DGETDATA_FLUSH to flush the internally batched queries to the driver. For applications writing their own version of waiting, results of queries from the driver are batched (not realized) until the driver receives a flush.

When D3DGETDATA_FLUSH is specified, this method can also return D3DERR_DEVICELOST in response to a device that is lost. This allows an application to prevent threads from polling forever due to a lost device (which cannot respond to the query).

See Also

D3DDEVINFO_VCACHE, D3DDEVINFO_RESOURCEMANAGER, D3DDEVINFO_D3DVERTEXSTATS

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9::GetDataSize Method

Gets the number of bytes in the query data.

Syntax

DWORD GetDataSize(VOID);

Return Value

Returns the number of bytes of query data.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9::GetDevice Method

Gets the device that is being queried.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **pDevice
);

Parameters

pDevice
[out] Pointer to the device being queried. See IDirect3DDevice9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9::GetType Method

Gets the query type.

Syntax

D3DQUERYTYPE GetType(VOID);

Return Value

Returns the query type. See D3DQUERYTYPE.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DQuery9::Issue Method

Issue a query.

Syntax

HRESULT Issue(

    DWORD dwIssueFlags
);

Parameters

dwIssueFlags
[in] Query flags specify the type of state change for the query. See D3DISSUE_BEGIN and D3DISSUE_END.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A signaled query means the query has completed, the data is available, and IDirect3DQuery9::GetData will return S_OK.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9 Interface

Applications use the methods of the IDirect3DResource9 interface to query and prepare resources.

IDirect3DResource9 Members

FreePrivateData

Frees the specified private data associated with this resource.

GetDevice

Retrieves the device associated with a resource.

GetLevelCount

Returns the number of texture levels in a multilevel texture.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

PreLoad

Preloads a managed resource.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Remarks

To create a texture resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

To create a geometry-oriented resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateVertexBuffer

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DRESOURCE9 and PDIRECT3DRESOURCE9 types are defined as pointers to the IDirect3DResource9 interface.

typedef struct IDirect3DResource9 *LPDIRECT3DRESOURCE9, *PDIRECT3DRESOURCE9;

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DResource9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DResource9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DResource9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DResource9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DResource9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DStateBlock9 Interface

Applications use the methods of the IDirect3DStateBlock9 interface to encapsulate render states.

IDirect3DStateBlock9 Members

Apply | Apply the state block to the current device state.
Capture | Capture the device's current state.
GetDevice | Gets the device.

Remarks

This interface can be used to save and restore pipeline state. It can also be used to capture the current state.

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DStateBlock9::Apply Method

Apply the state block to the current device state.

Syntax

HRESULT Apply(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails while in record mode, the return value is D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DStateBlock9::Capture Method

Capture the device's current state.

Syntax

HRESULT Capture(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails because capture cannot be done while in record mode, the return value is D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DStateBlock9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[in, out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9 Interface

Applications use the methods of the IDirect3DSurface9 interface to query and prepare surfaces.

IDirect3DSurface9 Members

GetContainer

Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.

GetDC

Retrieves a device context.

GetDesc

Retrieves a description of the surface.

LockRect

Locks a rectangle on a surface.

ReleaseDC

Release a device context handle.

UnlockRect

Unlocks a rectangle on a surface.

Remarks

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSURFACE9 and PDIRECT3DSURFACE9 types are defined as pointers to the IDirect3DSurface9 interface.

typedef struct IDirect3DSurface9 *LPDIRECT3DSURFACE9, *PDIRECT3DSURFACE9;

Interface Information

Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Surfaces

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::GetContainer Method

Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.

Syntax

HRESULT GetContainer(

    REFIID riid,
    void **ppContainer
);

Parameters

riid
[in] Reference identifier of the container being requested.
ppContainer
[out] Address of a pointer to fill with the container pointer if the query succeeds. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the surface is created using IDirect3DDevice9::CreateRenderTarget or IDirect3DDevice9::CreateOffscreenPlainSurface or IDirect3DDevice9::CreateDepthStencilSurface, the surface is considered stand alone. In this case, IDirect3DSurface9::GetContainer will return the Microsoft® Direct3D® device used to create the surface.

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent texture of a mip surface.

// Assumes pSurface is a valid IDirect3DSurface9 pointer
void *pContainer = NULL;
IDirect3DTexture9 *pTexture = NULL;
HRESULT hr = pSurface->GetContainer(IID_IDirect3DTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pTexture = (IDirect3DTexture9 *)pContainer;
}

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::GetDC Method

Retrieves a device context.

Syntax

HRESULT GetDC(

    HDC* phdc
);

Parameters

phdc
[out] Pointer to the device context for the surface.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

The following restrictions apply.

  • IDirect3DSurface9::GetDC is valid on the following formats only: D3DFMT_R5G6B5, D3DFMT_X1R5G5B5, D3DFMT_R8G8B8, and D3DFMT_X8R8G8B8. Formats that contain Alpha are not supported because the Microsoft® Windows® Graphics Device Interface (GDI) implementations don't have a well-defined behavior on the alpha channel. For more information about formats, see D3DFORMAT.
  • Only one device context per surface can be returned at a time.
  • IDirect3DSurface9::GetDC will fail if the surface is already locked. If the surface is a member of a mipmap or cubemap, IDirect3DSurface9::GetDC fails if any other mipmap or cubemap member is locked.
  • IDirect3DSurface9::GetDC fails on render targets unless they were created lockable (or, in the case of back buffers, with the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag).
  • For surfaces not created with IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DSurface9::GetDC will fail on default pool (D3DPOOL_DEFAULT) surfaces unless they are dynamic (D3DUSAGE_DYNAMIC) or are lockable render targets.
  • IDirect3DSurface9::GetDC will fail on D3DPOOL_SCRATCH surfaces.

When a device context is outstanding on a surface, the application may not call these methods:

IDirect3DCubeTexture9 | IDirect3DCubeTexture9::LockRect
IDirect3DDevice9 | IDirect3DDevice9::ColorFill
IDirect3DDevice9::StretchRect
IDirect3DDevice9::UpdateSurface
IDirect3DDevice9::UpdateTexture
IDirect3DSurface9 | IDirect3DSurface9::LockRect
IDirect3DSwapChain9 | IDirect3DSwapChain9::Present *
IDirect3DTexture9 | IDirect3DTexture9::LockRect

* (on a swap chain that contains the surface)

IDirect3DSurface9::GetDC causes an implicit lock; do not retain the device context for later use. Call IDirect3DSurface9::ReleaseDC to release it.

It is valid to call IDirect3DSurface9::GetDC/IDirect3DSurface9::ReleaseDC on levels of a mipmap or cubemap, however, these calls will be slow to all miplevels except the topmost level, and GDI operations to these miplevels will not be accelerated.

The handle to a device context (HDC) provides access to Microsoft Win32® and GDI functionality.

See Also

IDirect3DSurface9::ReleaseDC, D3DUSAGE, D3DPOOL, D3DPRESENT_PARAMETERS

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::GetDesc Method

Retrieves a description of the surface.

Syntax

HRESULT GetDesc(

    D3DSURFACE_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the surface.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::LockRect Method

Locks a rectangle on a surface.

Syntax

HRESULT LockRect(

    D3DLOCKED_RECT *pLockedRect,
    const RECT *pRect,
    DWORD Flags
);

Parameters

pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure that describes the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire surface.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, all of the flags in D3DLOCK are valid except D3DLOCK_NOOVERWRITE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL or D3DERR_WASSTILLDRAWING.

Remarks

If the D3DLOCK_DONOTWAIT flag is specified and the driver cannot lock the surface immediately, IDirect3DSurface9::LockRect will return D3DERR_WASSTILLDRAWING so that an application can use the CPU cycles while waiting for the driver to lock the surface.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE. See D3DFORMAT.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DSurface9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

A multisample back buffer cannot be locked.

See Also

IDirect3DSurface9::UnlockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::ReleaseDC Method

Release a device context handle.

Syntax

HRESULT ReleaseDC(

    HDC hdc
);

Parameters

hdc
[in] Handle to a device context.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

An handle to a device context (HDC) is a Microsoft® Windows® resource. It must be released after use so Windows can return it to the pool of available resources.

This method will release only the device context returned by IDirect3DSurface9::GetDC. Otherwise, this method will fail.

See Also

IDirect3DSurface9::GetDC

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSurface9::UnlockRect Method

Unlocks a rectangle on a surface.

Syntax

HRESULT UnlockRect(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DSurface9::LockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9 Interface

Applications use the methods of the IDirect3DSwapChain9 interface to manipulate a swap chain.

IDirect3DSwapChain9 Members

GetBackBuffer | Retrieves a back buffer from the swap chain of the device.
GetDevice

Retrieves the device associated with the swap chain.

GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
GetFrontBufferData | Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.
GetPresentParameters

Retrieves the presentation parameters associated with a swap chain.

GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
Present | Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

Remarks

There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created by calling the IDirect3DDevice9::CreateAdditionalSwapChain method.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSWAPCHAIN9 and PDIRECT3DSWAPCHAIN9 types are defined as pointers to the IDirect3DSwapChain9 interface.

typedef struct IDirect3DSwapChain9 *LPDIRECT3DSWAPCHAIN9, *PDIRECT3DSWAPCHAIN9;

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateAdditionalSwapChain

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetBackBuffer Method

Retrieves a back buffer from the swap chain of the device.

Syntax

HRESULT GetBackBuffer(

    UINT BackBuffer,
    D3DBACKBUFFER_TYPE Type,
    IDirect3DSurface9 **ppBackBuffer
);

Parameters

BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method.
Type
[in] Stereo view is not supported in Microsoft® DirectX® 9.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetDevice Method

Retrieves the device associated with the swap chain.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetDisplayMode Method

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

Syntax

HRESULT GetDisplayMode(

    D3DDISPLAYMODE *pMode
);

Parameters

pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetFrontBufferData Method

Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.

Syntax

HRESULT GetFrontBufferData(

    IDirect3DSurface9 *pDestSurface
);

Parameters

pDestSurface
[in, out] Pointer to an IDirect3DSurface9 interface that will receive a copy of the swapchain's front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row to the lowest.

For windowed mode, the size of the destination surface should be the size of the desktop. For full screen mode, the size of the destination surface should be the screen size.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetPresentParameters Method

Retrieves the presentation parameters associated with a swap chain.

Syntax

HRESULT GetPresentParameters(

    D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[out, retval] Pointer to the presentation parameters. See D3DPRESENT_PARAMETERS.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method can be used to see the presentation parameters of the parent swap chain of a surface (a back buffer, for instance). The parent swap chain can be retrieved with IDirect3DSurface9::GetContainer.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::GetRasterStatus Method

Returns information describing the raster of the monitor on which the swap chain is presented.

Syntax

HRESULT GetRasterStatus(

    D3DRASTER_STATUS *pRasterStatus
);

Parameters

pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

D3DRASTER_STATUS

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DSwapChain9::Present Method

Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

Syntax

HRESULT Present(

    const RECT *pSourceRect,
    CONST RECT *pDestRect,
    HWND hDestWindowOverride,
    CONST RGNDATA *pDirtyRegion,
    DWORD dwFlags
);

Parameters

pSourceRect
[in] Pointer to a RECT structure that contains the source rectangle. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a RECT structure containing the destination rectangle, in window client coordinates. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Destination window whose client area is taken as the target for this presentation. If this value is NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. For more information about swap chains, see Flipping Surfaces and D3DSWAPEFFECT.

If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation may choose to copy the whole source rectangle.
dwFlags
[in] Allows the application to request that the method return immediately when the driver reports that it cannot schedule a presentation. Valid values are 0, or any combination of D3DPRESENT_DONOTWAIT and D3DPRESENT_LINEAR_CONTENT.

If dwFlags = 0, this method behaves as it did prior to Microsoft® DirectX® 9.0. Present will spin until the hardware is free, without returning an error.

If dwFlags = D3DPRESENT_DONOTWAIT, and the hardware is busy processing or waiting for a vsync interval, the method will return D3DERR_WASSTILLDRAWING.

If dwFlags = D3DPRESENT_LINEAR_CONTENT, gamma correction is performed from linear space to sRGB for windowed swap chains. This flag will take effect only when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION. For more information about gamma correction, see Gamma.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The IDirect3DDevice9::Present method is a shortcut to the IDirect3DSwapChain9::Present. The swap chain method has been updated to take a flag allowing the application to request that the method return immediately when the driver reports that it cannot schedule a presentation.

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

IDirect3DDevice9::Present will fail if called between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for DirectX 9.0.

See Also

IDirect3DDevice9::Reset

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9 Interface

Applications use the methods of the IDirect3DTexture9 interface to manipulate a texture resource.

IDirect3DTexture9 Members

AddDirtyRect | Adds a dirty region to a texture resource.
FreePrivateData

Frees the specified private data associated with this resource.

GenerateMipSubLevels

Generate mipmap sublevels.

GetAutoGenFilterType

Get the filter type that is used for automatically generated mipmap sublevels.

GetDevice

Retrieves the device associated with a resource.

GetLevelCount

Returns the number of texture levels in a multilevel texture.

GetLevelDesc | Retrieves a level description of a texture resource.
GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetSurfaceLevel | Retrieves the specified texture surface level.
GetType

Returns the type of the resource.

LockRect | Locks a rectangle on a texture resource.
PreLoad

Preloads a managed resource.

SetAutoGenFilterType

Set the filter type that is used for automatically generated mipmap sublevels.

SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

UnlockRect | Unlocks a rectangle on a texture resource.

Remarks

The IDirect3DTexture9 interface is obtained by calling the IDirect3DDevice9::CreateTexture method.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DTEXTURE9 and PDIRECT3DTEXTURE9 types are defined as pointers to the IDirect3DTexture9 interface.

typedef struct IDirect3DTexture9 *LPDIRECT3DTEXTURE9, *PDIRECT3DTEXTURE9;

Interface Information

Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::AddDirtyRect Method

Adds a dirty region to a texture resource.

Syntax

HRESULT AddDirtyRect(

    CONST RECT *pDirtyRect
);

Parameters

pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

Applications can optimize what subset of a resource is copied by specifying dirty regions on the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetLevelDesc Method

Retrieves a level description of a texture resource.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DSURFACE_DESC *pDesc
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the returned level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetSurfaceLevel Method

Retrieves the specified texture surface level.

Syntax

HRESULT GetSurfaceLevel(

    UINT Level,
    IDirect3DSurface9 **ppSurfaceLevel
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface for the level specified by this parameter. The top-level surface is denoted by 0.
ppSurfaceLevel
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::LockRect Method

Locks a rectangle on a texture resource.

Syntax

HRESULT LockRect(

    UINT Level,
    D3DLOCKED_RECT *pLockedRect,
    CONST RECT *pRect,
    DWORD Flags
);

Parameters

Level
[in] Specifies the level of the texture resource to lock.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Textures created with D3DPOOL_DEFAULT are not lockable. Textures created in video memory are lockable when created with USAGE_DYNAMIC. For more information about usages, see D3DUSAGE.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

The only lockable format for a depth-stencil texture is D3DFMT_D16_LOCKABLE.

Video memory textures cannot be locked, but must be modified by calling IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture. There are exceptions for some proprietary driver pixel formats that Microsoft® DirectX® 9.0 does not recognize. These can be locked.

See Also

IDirect3DTexture9::UnlockRect, IDirect3DDevice9::UpdateTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::UnlockRect Method

Unlocks a rectangle on a texture resource.

Syntax

HRESULT UnlockRect(

    UINT Level
);

Parameters

Level
[in] Specifies the level of the texture resource to unlock.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DTexture9::LockRect

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9 Interface

Applications use the methods of the IDirect3DVertexBuffer9 interface to manipulate vertex buffer resources.

IDirect3DVertexBuffer9 Members

FreePrivateData

Frees the specified private data associated with this resource.

GetDesc | Retrieves a description of the vertex buffer resource.
GetDevice

Retrieves the device associated with a resource.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

Lock | Locks a range of vertex data and obtains a pointer to the vertex buffer memory.
PreLoad

Preloads a managed resource.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Unlock | Unlocks vertex data.

Remarks

The IDirect3DVertexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateVertexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVERTEXBUFFER9 and PDIRECT3DVERTEXBUFFER9 types are defined as pointers to the IDirect3DVertexBuffer9 interface.

typedef struct IDirect3DVertexBuffer9 *LPDIRECT3DVERTEXBUFFER9, *PDIRECT3DVERTEXBUFFER9;

Interface Information

Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::GetDesc Method

Retrieves a description of the vertex buffer resource.

Syntax

HRESULT GetDesc(

    D3DVERTEXBUFFER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVERTEXBUFFER_DESC structure, describing the returned vertex buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::Lock Method

Locks a range of vertex data and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT Lock(

    UINT OffsetToLock,
    UINT SizeToLock,
    VOID **ppbData,
    DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned vertex data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE with IDirect3DVertexBuffer9::Lock, see Using Dynamic Vertex and Index Buffers.

See Also

IDirect3DVertexBuffer9::Unlock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::Unlock Method

Unlocks vertex data.

Syntax

HRESULT Unlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVertexBuffer9::Lock

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexDeclaration9 Interface

Applications use the methods of the IDirect3DVertexDeclaration9 interface to encapsulate the vertex shader declaration.

IDirect3DVertexDeclaration9 Members

GetDeclaration | Gets the vertex shader declaration.
GetDevice | Gets the current device.

Remarks

A vertex shader declaration is made up of an array of vertex elements.

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexDeclaration9::GetDeclaration Method

Gets the vertex shader declaration.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9* pDecl,
    UINT* pNumElements
);

Parameters

pDecl
[in, out] Array of vertex elements that make up a vertex shader declaration. The application needs to allocate enough room for this. The vertex element array ends with the D3DDECL_END macro.
pNumElements
[in, out] Number of elements in the array. The application needs to allocate enough room for this.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The number of elements, pNumElements, includes the D3DDECL_END macro, which ends the declaration. So the element count is actually one higher than the number of valid vertex elements.

Here's an example that will return the vertex declaration array of up to 256 elements.

// assumes a valid pointer to a vertex declaration object
D3DVERTEXELEMENTS9 decl[256];
UINT numElements;
HRESULT hr = m_pVertexDeclaration->GetDeclaration( decl, &numElements);

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexDeclaration9::GetDevice Method

Gets the current device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexShader9 Interface

Applications use the methods of the IDirect3DVertexShader9 interface to encapsulate the functionality of a vertex shader.

IDirect3DVertexShader9 Members

GetDevice | Gets the device.
GetFunction | Gets a pointer to the shader data.

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexShader9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexShader9::GetFunction Method

Gets a pointer to the shader data.

Syntax

HRESULT GetFunction(

    void* pData,
    UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9 Interface

Applications use the methods of the IDirect3DVolume9 interface to manipulate volume resources.

IDirect3DVolume9 Members

FreePrivateData

Frees the specified private data associated with this volume.

GetContainer

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

GetDesc

Retrieves a description of the volume.

GetDevice

Retrieves the device associated with a volume.

GetPrivateData

Copies the private data associated with the volume to a provided buffer.

LockBox

Locks a box on a volume resource.

SetPrivateData

Associates data with the volume that is intended for use by the application, not by Microsoft® Direct3D®.

UnlockBox

Unlocks a box on a volume resource.

Remarks

The IDirect3DVolume9 interface is obtained by calling the IDirect3DVolumeTexture9::GetVolumeLevel method.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUME9 and PDIRECT3DVOLUME9 types are defined as pointers to the IDirect3DVolume9 interface.

typedef struct IDirect3DVolume9 *LPDIRECT3DVOLUME9, *PDIRECT3DVOLUME9;

Interface Information

Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::FreePrivateData Method

Frees the specified private data associated with this volume.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a volume is released.

See Also

IDirect3DVolume9::GetPrivateData, IDirect3DVolume9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::GetContainer Method

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

Syntax

HRESULT GetContainer(

    REFIID riid,
    void **ppContainer
);

Parameters

riid
[in] Reference identifier of the volume being requested.
ppContainer
[out, retval] Address of a pointer to fill with the container pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent volume texture of a volume texture.

// Assumes pSurface is a valid IDirect3DVolume9 pointer
void *pContainer = NULL;
IDirect3DVolumeTexture9 *pVolumeTexture = NULL;
HRESULT hr = pVolume->GetContainer(IID_IDirect3DVolumeTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pVolumeTexture = (IDirect3DVolumeTexture9 *)pContainer;

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::GetDesc Method

Retrieves a description of the volume.

Syntax

HRESULT GetDesc(

    D3DVOLUME_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the volume.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::GetDevice Method

Retrieves the device associated with a volume.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::GetPrivateData Method

Copies the private data associated with the volume to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data, such as 0, the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::LockBox Method

Locks a box on a volume resource.

Syntax

HRESULT LockBox(

    D3DLOCKED_BOX *pLockedVolume,
    const D3DBOX *pBox,
    DWORD Flags
);

Parameters

pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to a box to lock. Specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolume9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

See Also

IDirect3DVolume9::UnlockBox

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::SetPrivateData Method

Associates data with the volume that is intended for use by the application, not by Microsoft® Direct3D®.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to associate with the volume.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVolume9::SetPrivateData with the same globally unique identifier (GUID), a subsequent call to IDirect3DVolume9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single volume.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::GetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolume9::UnlockBox Method

Unlocks a box on a volume resource.

Syntax

HRESULT UnlockBox(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVolume9::LockBox

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9 Interface

Applications use the methods of the IDirect3DVolumeTexture9 interface to manipulate a volume texture resource.

IDirect3DVolumeTexture9 Members

AddDirtyBox

Adds a dirty region to a volume texture resource.

FreePrivateData

Frees the specified private data associated with this resource.

GenerateMipSubLevels

Generate mipmap sublevels.

GetAutoGenFilterType

Get the filter type that is used for automatically generated mipmap sublevels.

GetDevice

Retrieves the device associated with a resource.

GetLevelCount

Returns the number of texture levels in a multilevel texture.

GetLevelDesc | Retrieves a level description of a volume texture resource.
GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

GetPriority

Retrieves the priority for this resource.

GetPrivateData

Copies the private data associated with the resource to a provided buffer.

GetType

Returns the type of the resource.

GetVolumeLevel | Retrieves the specified volume texture level.
LockBox | Locks a box on a volume texture resource.
PreLoad

Preloads a managed resource.

SetAutoGenFilterType

Set the filter type that is used for automatically generated mipmap sublevels.

SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

SetPriority

Assigns the resource-management priority for this resource.

SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

UnlockBox

Unlocks a box on a volume texture resource.

Remarks

The IDirect3DVolumeTexture9 interface is obtained by calling the IDirect3DDevice9::CreateVolumeTexture method.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUMETEXTURE9 and PDIRECT3DVOLUMETEXTURE9 types are defined as pointers to the IDirect3DVolumeTexture9 interface.

typedef struct IDirect3DVolumeTexture9 *LPDIRECT3DVOLUMETEXTURE9, *PDIRECT3DVOLUMETEXTURE9;

Interface Information

Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateVolumeTexture

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::AddDirtyBox Method

Adds a dirty region to a volume texture resource.

Syntax

HRESULT AddDirtyBox(

    CONST D3DBOX *pDirtyBox
);

Parameters

pDirtyBox
[in] Pointer to a D3DBOX structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire volume texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

Applications can optimize what subset of a resource is copied by specifying boxes on the resource. However, the dirty regions may be expanded to optimize alignment.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetLevelDesc Method

Retrieves a level description of a volume texture resource.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DVOLUME_DESC *pDesc
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the returned volume texture level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetVolumeLevel Method

Retrieves the specified volume texture level.

Syntax

HRESULT GetVolumeLevel(

    UINT Level,
    IDirect3DVolume9 **ppVolumeLevel
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume for the level specified by this parameter.
ppVolumeLevel
[out, retval] Address of a pointer to an IDirect3DVolume9 interface, representing the returned volume level.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DVolume9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVolume9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::LockBox Method

Locks a box on a volume texture resource.

Syntax

HRESULT LockBox(

    UINT Level,
    D3DLOCKED_BOX *pLockedVolume,
    const D3DBOX *pBox,
    DWORD Flags
);

Parameters

Level
[in] Specifies the level of the volume texture resource to lock.
pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to the volume to lock. This parameter is specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume level.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. For more information, see IDirect3DDevice9::UpdateTexture.

See Also

IDirect3DVolumeTexture9::UnlockBox

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::UnlockBox Method

Unlocks a box on a volume texture resource.

Syntax

HRESULT UnlockBox(

    UINT Level
);

Parameters

Level
[in] Specifies the level of the volume texture resource to unlock.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVolumeTexture9::LockBox

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section contains reference information for the functions that you need to use when you work with Microsoft® Direct3D®. The following function is implemented.

Functions

  • Direct3DCreate9

© 2002 Microsoft Corporation. All rights reserved.


Direct3DCreate9 Function

Creates an instance of an IDirect3D9 object.

Syntax

IDirect3D9 *Direct3DCreate9(

    UINT SDKVersion
);

Parameters

SDKVersion
The value of this parameter should be D3D_SDK_VERSION. See Remarks.

Return Value

If successful, this function returns a pointer to an IDirect3D9 interface; otherwise, a NULL pointer is returned.

Remarks

This function creates a Direct3D9 object that supports enumeration and allows the creation of IDirect3DDevice9 objects.

The D3D_SDK_VERSION identifier is passed to this function in order to ensure that an application was built against the correct header files. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, this function will fail.

Note that calling this function samples the current set of active display adapters. If the user dynamically adds adapters, either by adding devices to the desktop or by hot-docking a laptop, then those devices will not be enumerated for the lifetime of this IDirect3D9 object. Creating a new IDirect3D9 object will expose the new devices.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Macros

This section contains reference information for the macros provided by Microsoft® Direct3D®.

  • D3DCLIPPLANEn
  • D3DCOLOR_ARGB
  • D3DCOLOR_COLORVALUE
  • D3DCOLOR_RGBA
  • D3DCOLOR_XRGB
  • D3DFVF_TEXCOORDSIZEn
  • D3DTS_WORLD
  • D3DTS_WORLDMATRIX
  • D3DTS_WORLDn

© 2002 Microsoft Corporation. All rights reserved.


D3DCLIPPLANEn Macro

Defines bit patterns that enable user-defined clipping planes. These macros are defined as a convenience when setting values for the D3DRS_CLIPPLANEENABLE render state.

Syntax

#define D3DCLIPPLANE0 (1 << 0)
#define D3DCLIPPLANE1 (1 << 1)
#define D3DCLIPPLANE2 (1 << 2)
#define D3DCLIPPLANE3 (1 << 3)
#define D3DCLIPPLANE4 (1 << 4)
#define D3DCLIPPLANE5 (1 << 5)

Remarks

User-defined clipping planes are enabled when the value set in the D3DRS_CLIPPLANEENABLE render state contains one or more set bits (that is, is not 0). The value of the render-state is not important; the system does not interpret the value as a number. Rather, the value enables the clipping plane whose corresponding bit is set. Bit 0 controls the state of the first clipping plane (at index 0), bit 1 the second plane, and so on.

The bit patterns that these macros create can be combined by using a logical OR operation to simultaneously enable multiple clipping planes. Omitting one of these macros from the combination effectively disables the clipping plane at that index.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLOR_ARGB Macro

Initializes a color with the supplied alpha, red, green, and blue values.

Syntax

#define D3DCOLOR_ARGB(a,r,g,b) \
    ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))

Parameters

a
Alpha component of the color. This value must be in the range 0 through 255.
r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied ARGB values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_RGBA, D3DCOLOR_XRGB

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLOR_COLORVALUE Macro

Initializes a color with the supplied red, green, blue, and alpha floating-point values.

Syntax

#define D3DCOLOR_COLORVALUE(r,g,b,a) \
    D3DCOLOR_RGBA((DWORD)((r)*255.f),(DWORD)((g)*255.f),(DWORD)((b)*255.f),(DWORD)((a)*255.f))

Parameters

r
Red component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
g
Green component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
b
Blue component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
a
Alpha component of the color. This value must be a floating-point value in the range 0.0 through 1.0.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLOR_RGBA Macro

Initializes a color with the supplied red, green, blue, and alpha values.

Syntax

#define D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.
a
Alpha component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_XRGB

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLOR_XRGB Macro

Initializes a color with the supplied red, green, and blue values.

Syntax

#define D3DCOLOR_XRGB(r,g,b) D3DCOLOR_ARGB(0xff,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGB values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_RGBA

© 2002 Microsoft Corporation. All rights reserved.


D3DFVF_TEXCOORDSIZEn Macro

Constructs bit patterns that are used to identify texture coordinate formats within a flexible vertex format description. The results of these macros can be combined within a flexible vertex format description by using the OR operator.

Syntax

#define D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2)
#define D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16))

Parameters

CoordIndex
Value that identifies the texture coordinate set at which the texture coordinate size (1-, 2-, 3-, or 4-dimensional) applies.

Remarks

The D3DFVF_TEXCOORDSIZEn macros use the following constants.

#define D3DFVF_TEXTUREFORMAT1 3 // one floating point value
#define D3DFVF_TEXTUREFORMAT2 0 // two floating point values
#define D3DFVF_TEXTUREFORMAT3 1 // three floating point values
#define D3DFVF_TEXTUREFORMAT4 2 // four floating point values

The following flexible vertex format description identifies a vertex format that has a position; a normal; diffuse and specular colors; and two sets of texture coordinates. The first set of texture coordinates includes a single element, and the second set includes two elements:

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_SPECULAR | D3DFVF_TEX2 |
              D3DFVF_TEXCOORDSIZE1(0) |  // Uses 1-D texture coordinates for
                                         // texture coordinate set 1 (index 0).
              D3DFVF_TEXCOORDSIZE2(1);   // And 2-D texture coordinates for
                                         // texture coordinate set 2 (index 1).

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DFVF

© 2002 Microsoft Corporation. All rights reserved.


D3DTS_WORLD Macro

Identifies the transformation matrix being set as the world transformation matrix.

Syntax

#define D3DTS_WORLD  D3DTS_WORLDMATRIX(0)

Remarks

This macro is provided to facilitate porting existing applications to Microsoft® DirectX® 9.0

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


D3DTS_WORLDMATRIX Macro

Maps indices in the range 0 through 255 to the corresponding transform states.

Syntax

#define D3DTS_WORLDMATRIX(index) (D3DTRANSFORMSTATETYPE)(index + 256)

Parameters

index
An index value in the range 0 through 255.

Remarks

Transform states in the range 256 through 511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform

© 2002 Microsoft Corporation. All rights reserved.


D3DTS_WORLDn Macro

Identifies subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.

Syntax

#define D3DTS_WORLD1 D3DTS_WORLDMATRIX(1)
#define D3DTS_WORLD2 D3DTS_WORLDMATRIX(2)
#define D3DTS_WORLD3 D3DTS_WORLDMATRIX(3)

Remarks

These macros are provided to facilitate porting existing applications to Microsoft® DirectX® 9.0.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains information about the structures used with Microsoft® Direct3D®.

Structures

  • D3DADAPTER_IDENTIFIER9
  • D3DBOX
  • D3DCAPS9
  • D3DCLIPSTATUS9
  • D3DCOLORVALUE
  • D3DDEVICE_CREATION_PARAMETERS
  • D3DDEVINFO_D3DVERTEXSTATS
  • D3DDEVINFO_RESOURCEMANAGER
  • D3DDEVINFO_VCACHE
  • D3DDISPLAYMODE
  • D3DGAMMARAMP
  • D3DINDEXBUFFER_DESC
  • D3DLIGHT9
  • D3DLOCKED_BOX
  • D3DLOCKED_RECT
  • D3DMATERIAL9
  • D3DMATRIX
  • D3DPRESENT_PARAMETERS
  • D3DPSHADERCAPS2_0
  • D3DRANGE
  • D3DRASTER_STATUS
  • D3DRECT
  • D3DRECTPATCH_INFO
  • D3DRESOURCESTATS
  • D3DSURFACE_DESC
  • D3DTRIPATCH_INFO
  • D3DVECTOR
  • D3DVERTEXBUFFER_DESC
  • D3DVERTEXELEMENT9
  • D3DVIEWPORT9
  • D3DVOLUME_DESC
  • D3DVSHADERCAPS2_0
  • PALETTEENTRY

© 2002 Microsoft Corporation. All rights reserved.


D3DADAPTER_IDENTIFIER9 Structure

Contains information identifying the adapter.

Syntax

typedef struct _D3DADAPTER_IDENTIFIER9 {
    char Driver[MAX_DEVICE_IDENTIFIER_STRING];
    char Description[MAX_DEVICE_IDENTIFIER_STRING];
    char DeviceName[32];
    LARGE_INTEGER DriverVersion;
    DWORD DriverVersionLowPart;
    DWORD DriverVersionHighPart;
    DWORD VendorId;
    DWORD DeviceId;
    DWORD SubSysId;
    DWORD Revision;
    GUID DeviceIdentifier;
    DWORD WHQLLevel;
} D3DADAPTER_IDENTIFIER9;

Members

Driver
Used for presentation to the user. This should not be used to identify particular drivers, because many different strings might be associated with the same device and driver from different vendors.
Description
Used for presentation to the user.
DeviceName
Device name for Microsoft® Windows® Graphics Device Interface (GDI).
DriverVersion
Identify the version of the Microsoft Direct3D® driver. It is legal to do less than and greater than comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionLowPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionHighPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
VendorId
Can be used to help identify a particular chip set. Query this member to identify the manufacturer. The value can be zero if unknown.
DeviceId
Can be used to help identify a particular chip set. Query this member to identify the type of chip set. The value can be zero if unknown.
SubSysId
Can be used to help identify a particular chip set. Query this member to identify the subsystem, typically the particular board. The value can be zero if unknown.
Revision
Can be used to help identify a particular chip set. Query this member to identify the revision level of the chip set. The value can be zero if unknown.
DeviceIdentifier
Can be queried to check changes in the driver and chip set. This globally unique identifier (GUID) is a unique identifier for the driver and chip set pair. Query this member to track changes to the driver and chip set in order to generate a new profile for the graphics subsystem. DeviceIdentifier can also be used to identify particular problematic drivers.
WHQLLevel

Used to determine the Windows Hardware Quality Labs (WHQL) validation level for this driver and device pair. The DWORD is a packed date structure defining the date of the release of the most recent WHQL test passed by the driver. It is legal to perform < and > operations on this value. The following illustrates the date format.

Bits
31-16 | The year, a decimal number from 1999 upwards.
15-8 | The month, a decimal number from 1 to 12.
7-0 | The day, a decimal number from 1 to 31.

The following values are also used.

0 | Not certified.
1 | WHQL validated, but no date information is available.

Remarks

The following pseudocode example illustrates the version format encoded in the DriverVersion, DriverVersionLowPart, and DriverVersionHighPart members.

Product = HIWORD(DriverVersion.HighPart)
Version = LOWORD(DriverVersion.HighPart)
SubVersion = HIWORD(DriverVersion.LowPart)
Build = LOWORD(DriverVersion.LowPart)

See the Microsoft Platform Software Development Kit (SDK) for more information about the HIWORD macro, the LOWORD macro, and the LARGE_INTEGER structure.

MAX_DEVICE_IDENTIFIER_STRING is a constant with the following definition.

#define MAX_DEVICE_IDENTIFIER_STRING        512

The VendorId, DeviceId, SubSysId, and Revision members can be used in tandem to identify particular chip sets. However, use these members with caution.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DBOX Structure

Defines a volume.

Syntax

typedef struct _D3DBOX {
    UINT Left;
    UINT Top;
    UINT Right;
    UINT Bottom;
    UINT Front;
    UINT Back;
} D3DBOX;

Members

Left
Position of the left side of the box on the x-axis.
Top
Position of the top of the box on the y-axis.
Right
Position of the right side of the box on the x-axis.
Bottom
Position of the bottom of the box on the y-axis.
Front
Position of the front of the box on the z-axis.
Back
Position of the back of the box on the z-axis.

Remarks

D3DBOX includes the left, top, and front edges; however, the right, bottom, and back edges are not included. For example, a box that is 100 units wide and begins at 0 (thus, including the points up to and including 99) would be expressed with a value of 0 for the Left member and a value of 100 for the Right member. Note that a value of 99 is not used for the Right member.

The restrictions on side ordering observed for D3DBOX are left to right, top to bottom, and front to back.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCAPS9 Structure

Represents the capabilities of the hardware exposed through the Microsoft® Direct3D® object.

Syntax

typedef struct _D3DCAPS9 {
    D3DDEVTYPE DeviceType;
    UINT AdapterOrdinal;
    DWORD Caps;
    DWORD Caps2;
    DWORD Caps3;
    DWORD PresentationIntervals;
    DWORD CursorCaps;
    DWORD DevCaps;
    DWORD PrimitiveMiscCaps;
    DWORD RasterCaps;
    DWORD ZCmpCaps;
    DWORD SrcBlendCaps;
    DWORD DestBlendCaps;
    DWORD AlphaCmpCaps;
    DWORD ShadeCaps;
    DWORD TextureCaps;
    DWORD TextureFilterCaps;
    DWORD CubeTextureFilterCaps;
    DWORD VolumeTextureFilterCaps;
    DWORD TextureAddressCaps;
    DWORD VolumeTextureAddressCaps;
    DWORD LineCaps;
    DWORD MaxTextureWidth;
    DWORD MaxTextureHeight;
    DWORD MaxVolumeExtent;
    DWORD MaxTextureRepeat;
    DWORD MaxTextureAspectRatio;
    DWORD MaxAnisotropy;
    float MaxVertexW;
    float GuardBandLeft;
    float GuardBandTop;
    float GuardBandRight;
    float GuardBandBottom;
    float ExtentsAdjust;
    DWORD StencilCaps;
    DWORD FVFCaps;
    DWORD TextureOpCaps;
    DWORD MaxTextureBlendStages;
    DWORD MaxSimultaneousTextures;
    DWORD VertexProcessingCaps;
    DWORD MaxActiveLights;
    DWORD MaxUserClipPlanes;
    DWORD MaxVertexBlendMatrices;
    DWORD MaxVertexBlendMatrixIndex;
    float MaxPointSize;
    DWORD MaxPrimitiveCount;
    DWORD MaxVertexIndex;
    DWORD MaxStreams;
    DWORD MaxStreamStride;
    DWORD VertexShaderVersion;
    DWORD MaxVertexShaderConst;
    DWORD PixelShaderVersion;
    float PixelShader1xMaxValue;
    DWORD DevCaps2;
    float MaxNpatchTesselationLevel;
    float MinAntialiasedLineWidth;
    float MaxAntialiasedLineWidth;
    UINT MasterAdapterOrdinal;
    UINT AdapterOrdinalInGroup;
    UINT NumberOfAdaptersInGroup;
    DWORD DeclTypes;
    DWORD NumSimultaneousRTs;
    DWORD StretchRectFilterCaps;
    D3DVSHADERCAPS2_0 VS20Caps;
    D3DPSHADERCAPS2_0 PS20Caps;
    DWORD VertexTextureFilterCaps;
    DWORD MaxVShaderInstructionsExecuted;
    DWORD MaxPShaderInstructionsExecuted;
    DWORD MaxVertexShader30InstructionSlots;
    DWORD MaxPixelShader30InstructionSlots;
    DWORD Reserved2;
    DWORD Reserved3;
} D3DCAPS9;

Members

DeviceType
Member of the D3DDEVTYPE enumerated type, which identifies what type of resources are used for processing vertices.
AdapterOrdinal
Adapter on which this Direct3DDevice object was created. This ordinal is valid only to pass to methods of the IDirect3D9 interface that created this Direct3DDevice object. The IDirect3D9 interface can always be retrieved by calling IDirect3DDevice9::GetDirect3D.
Caps

The following driver-specific capability.

D3DCAPS_READ_SCANLINE
Display hardware is capable of returning the current scan line.
Caps2

Driver-specific capabilities identified in D3DCAPS2.

Caps3

Driver-specific capabilities identified in D3DCAPS3.

PresentationIntervals

Bit mask of values representing what presentation swap intervals are available.

D3DPRESENT_INTERVAL_IMMEDIATE
The driver supports an immediate presentation swap interval.
D3DPRESENT_INTERVAL_ONE
The driver supports a presentation swap interval of every screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver supports a presentation swap interval of every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver supports a presentation swap interval of every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver supports a presentation swap interval of every fourth screen refresh.
CursorCaps

Bit mask indicating what hardware support is available for cursors. Microsoft DirectX® 9.0 does not define alpha-blending cursor capabilities.

D3DCURSORCAPS_COLOR
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports at least a hardware color cursor in high-resolution modes (with scan lines greater than or equal to 400).
D3DCURSORCAPS_LOWRES
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports a hardware color cursor in both high-resolution and low-resolution modes (with scan lines less than 400).
DevCaps

Flags identifying the capabilities of the device.

D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability means that the device is relatively fast.
D3DDEVCAPS_DRAWPRIMITIVES2
Device can support DrawPrimitives2.
D3DDEVCAPS_DRAWPRIMITIVES2EX
Device can support extended DrawPrimitives2; that is, this is a DirectX 7.0-compliant driver.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports an DrawPrimitive-aware hardware abstraction layer (HAL).
D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device can support transformation and lighting in hardware.
D3DDEVCAPS_NPATCHES
Device supports N patches.
D3DDEVCAPS_PUREDEVICE
Device can support rasterization, transform, lighting, and shading in hardware.
D3DDEVCAPS_QUINTICRTPATCHES
Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES
Device supports rectangular and triangular patches.
D3DDEVCAPS_RTPATCHHANDLEZERO
When this device capability is set, the hardware architecture does not require caching of any information and uncached patches (handle zero) will be drawn as efficiently as cached ones. Note that setting D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle-zero patch can always be drawn whether this cap is set or not.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device is texturing from separate memory pools.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from non-local video memory.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
PrimitiveMiscCaps

Miscellaneous driver primitive capabilities. See D3DPMISCCAPS.

RasterCaps

Information on raster-drawing capabilities. This member can be one or more of the following flags.

D3DPRASTERCAPS_ANISOTROPY
Device supports anisotropic filtering.
D3DPRASTERCAPS_COLORPERSPECTIVE
Device iterates colors perspective correctly.
D3DPRASTERCAPS_DITHER
Device can dither to improve color resolution.
D3DPRASTERCAPS_DEPTHBIAS
Device supports legacy depth bias. For true depth bias, see D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS.
D3DPRASTERCAPS_FOGRANGE
Device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene.
D3DPRASTERCAPS_FOGTABLE
Device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
Device calculates the fog value during the lighting operation and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
Device supports level of detail (LOD) bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about LOD bias in mipmaps, see D3DSAMP_MIPMAPLODBIAS.
D3DPRASTERCAPS_MULTISAMPLE_TOGGLE
Device supports toggling multisampling on and off between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene (using D3DRS_MULTISAMPLEANTIALIAS).
D3DPRASTERCAPS_SCISSORTEST
Device supports scissor test. See Scissor Test.
D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS
Device performs true slope-scale based depth bias. This is in contrast to the legacy style D3DPRASTERCAPS_DEPTHBIAS.
D3DPRASTERCAPS_WBUFFER
Device supports depth buffering using w.
D3DPRASTERCAPS_WFOG
Device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_ZBUFFERLESSHSR
Device can perform hidden-surface removal (HSR) without requiring the application to sort polygons and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform HSR is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is associated with the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRS_ZENABLE enumeration constant is set to TRUE).

D3DPRASTERCAPS_ZFOG
Device supports z-based fog.
D3DPRASTERCAPS_ZTEST
Device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
ZCmpCaps

Z-buffer comparison capabilities. This member can be one or more of the following flags.

D3DPCMPCAPS_ALWAYS
Always pass the z-test.
D3DPCMPCAPS_EQUAL
Pass the z-test if the new z equals the current z.
D3DPCMPCAPS_GREATER
Pass the z-test if the new z is greater than the current z.
D3DPCMPCAPS_GREATEREQUAL
Pass the z-test if the new z is greater than or equal to the current z.
D3DPCMPCAPS_LESS
Pass the z-test if the new z is less than the current z.
D3DPCMPCAPS_LESSEQUAL
Pass the z-test if the new z is less than or equal to the current z.
D3DPCMPCAPS_NEVER
Always fail the z-test.
D3DPCMPCAPS_NOTEQUAL
Pass the z-test if the new z does not equal the current z.
SrcBlendCaps

Source-blending capabilities. This member can be one or more of the following flags. (The RGBA values of the source and destination are indicated by the subscripts s and d.)

D3DPBLENDCAPS_BLENDFACTOR
The driver supports both D3DBLEND_BLENDFACTOR and D3DBLEND_INVBLENDFACTOR. See D3DBLEND.
D3DPBLENDCAPS_BOTHINVSRCALPHA
Source blend factor is (1-As,1-As,1-As,1-As) and destination blend factor is (As,As,As,As); the destination blend selection is overridden.
D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete. For more information, see D3DBLEND.)
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As, 1-As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
DestBlendCaps
Destination-blending capabilities. This member can be the same capabilities that are defined for the SrcBlendCaps member.
AlphaCmpCaps
Alpha-test comparison capabilities. This member can include the same capability flags defined for the ZCmpCaps member. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing.
ShadeCaps
Shading operations capabilities. It is assumed, in general, that if a device supports a given command at all, it supports the D3DSHADE_FLAT mode (as specified in the D3DSHADEMODE enumerated type). This flag specifies whether the driver can also support Gouraud shading and whether alpha color components are supported. When alpha components are not supported, the alpha value of colors generated is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver.

This member can be one or more of the following flags.

D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud-blended transparency (the D3DSHADE_GOURAUD state for the D3DSHADEMODE enumerated type). In this mode, the alpha color component of a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the RGB color model. In this mode, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In the RGB lighting model, the red, green, and blue components are interpolated.
D3DPSHADECAPS_FOGGOURAUD
Device can support fog in the Gouraud shading mode.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device supports Gouraud shading of specular highlights.
TextureCaps

Miscellaneous texture-mapping capabilities. This member can be one or more of the following flags.

D3DPTEXTURECAPS_ALPHA
Alpha in texture pixels is supported.
D3DPTEXTURECAPS_ALPHAPALETTE
Device can draw alpha from texture palettes.
D3DPTEXTURECAPS_CUBEMAP
Supports cube textures.
D3DPTEXTURECAPS_CUBEMAP_POW2
Device requires that cube texture maps have dimensions specified as powers of two.
D3DPTEXTURECAPS_MIPCUBEMAP
Device supports mipmapped cube textures.
D3DPTEXTURECAPS_MIPMAP
Device supports mipmapped textures.
D3DPTEXTURECAPS_MIPVOLUMEMAP
Device supports mipmapped volume textures.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
Conditionally supports the use of 2-D textures with dimensions that are not powers of two. A device that exposes this capability can use such a texture if all of the following requirements are met.
  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRS_WRAP n set to 0).
  • Mipmapping is not in use (use magnification filter only).
  • Texture formats must not be DXT1-5.

A texture that is not a power of two cannot be set at a stage that will be read based on a shader computation (such as the bem, beml, or texm3x3 instructions in pixel shaders versions 1_0 to 1_3). For example, these textures can be used to store bumps that will be fed into texture reads, but not the environment maps that are used in texbem, texbeml, or texm3x3spec. This means that a texture with dimensions that are not powers of two cannot be addressed or sampled using texture coordinates computed within the shader. This type of operation is known as a dependent read and cannot be performed on these types of textures.

D3DPTEXTURECAPS_NOPROJECTEDBUMPENV
Device does not support a projected bump-environment loopkup operation in programmable and fixed function shaders.
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction texturing is supported.
D3DPTEXTURECAPS_POW2
All textures must have widths and heights specified as powers of two. This requirement does not apply to either cube textures or volume textures.
D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate. If this capability is present, then the projective divide occurs per pixel. If this capability is not present, but the projective divide needs to occur anyway, then it is performed on a per-vertex basis by the Direct3D runtime.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_VOLUMEMAP
Device supports volume textures.
D3DPTEXTURECAPS_VOLUMEMAP_POW2
Device requires that volume texture maps have dimensions specified as powers of two.
TextureFilterCaps
Texture-filtering capabilities for a Direct3DTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
CubeTextureFilterCaps
Texture-filtering capabilities for a Direct3DCubeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
VolumeTextureFilterCaps
Texture-filtering capabilities for a Direct3DVolumeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
TextureAddressCaps

Texture-addressing capabilities for Direct3DTexture objects. This member can be one or more of the following flags.

D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DSAMP_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DSAMP_ADDRESSU and D3DSAMP_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_MIRRORONCE
Device can take the absolute value of the texture coordinate (thus, mirroring around 0) and then clamp to the maximum value.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
VolumeTextureAddressCaps
Texture-addressing capabilities for Direct3DVolumeTexture objects. This member can be one or more of the flags defined for the TextureAddressCaps member.
LineCaps

Defines the capabilities for line-drawing primitives.

D3DLINECAPS_ALPHACMP
Supports alpha-test comparisons.
D3DLINECAPS_ANTIALIAS
Antialiased lines are supported.
D3DLINECAPS_BLEND
Supports source-blending.
D3DLINECAPS_FOG
Supports fog.
D3DLINECAPS_TEXTURE
Supports texture-mapping.
D3DLINECAPS_ZTEST
Supports z-buffer comparisons.
MaxTextureWidth
Maximum texture width for this device.
MaxTextureHeight
Maximum texture height for this device.
MaxVolumeExtent
Maximum value for any of the three dimensions (width, height, and depth) of a volume texture.
MaxTextureRepeat

This number represents the maximum range of the integer bits of the post-normalized texture coordinates. A texture coordinate is stored as a 32-bit signed integer using 27 bits to store the integer part and 5 bits for the floating point fraction. The maximum integer index, 227, is used to determine the maximum texture coordinate, depending on how the hardware does texture-coordinate scaling.

Some hardware reports the cap D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE. For this case, the device defers scaling texture coordinates by the texture size until after interpolation and application of the texture address mode, so the number of times a texture can be wrapped is given by the integer value in MaxTextureRepeat.

Less desirably, on some hardware D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set and the device scales the texture coordinates by the texture size (using the highest level of detail) prior to interpolation. This limits the number of times a texture can be wrapped to MaxTextureRepeat / texture size.

For example, assume that MaxTextureRepeat is equal to 32 KB and the size of the texture is 4 KB. If the hardware sets D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE, then the number of times a texture can be wrapped is equal to MaxTextureRepeat, which is 32 KB in this example. Otherwise, the number of times a texture can be wrapped is equal to MaxTextureRepeat divided by texture size, which is 227/4 KB in this example.

MaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware, typically a power of 2.
MaxAnisotropy
Maximum valid value for the D3DSAMP_MAXANISOTROPY texture-stage state.
MaxVertexW
Maximum W-based depth value that the device supports.
GuardBandLeft
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandTop
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandRight
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandBottom
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
ExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
StencilCaps
Flags specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRS_STENCILFAIL, D3DRS_STENCILPASS, and D3DRS_STENCILZFAIL).

For more information, see D3DSTENCILCAPS.

FVFCaps

Flexible vertex format capabilities.

D3DFVFCAPS_DONOTSTRIPELEMENTS
It is preferable that vertex elements not be stripped. That is, if the vertex format contains elements that are not used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format provides better performance.
D3DFVFCAPS_PSIZE

Point size is determined by either the render state or the vertex data.

If D3DFVFCAPS_PSIZE is set, point size can come from D3DFVF_PSIZE data in the FVF vertex declaration. Otherwise, point size is determined by the render state D3DRS_POINTSIZE.

If the application provides point size in both (the render state and the FVF data), the vertex data overrides the render-state data.

D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low WORD of FVFCaps. These bits, cast to the WORD data type, describe the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can blend using only the specified number of texture coordinate sets.)
TextureOpCaps

Combination of flags describing the texture operations supported by this device. The following flags are defined.

D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_LERP
The D3DTOP_LERP texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATECOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MULTIPLYADD
The D3DTOP_MULTIPLYADD texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture-blending operation is supported.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
MaxTextureBlendStages
Maximum number of texture-blending stages supported in the fixed function pipeline. This value is the number of blenders available. In the programmable pixel pipeline, this corresponds to the number of unique texture registers used by pixel shader instructions.
MaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the fixed function pipeline texture blending stages. This value is the number of textures that can be used in a single pass. If the same texture is used in two blending stages, it counts as two when compared against the MaxSimultaneousTextures value. In the programmable pipeline, this indicates the number of texture/sampler registers supported by pixel shaders on this particular piece of hardware, as well as the number of texture declaration instructions that can be present.
VertexProcessingCaps

Vertex processing capabilities. For a given physical device, this capability might vary across Direct3DDevice objects depending on the parameters supplied to IDirect3D9::CreateDevice. See D3DVTXPCAPS.

MaxActiveLights
Maximum number of lights that can be active simultaneously. For a given physical device, this capability might vary across Direct3DDevice objects depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can range from 0 through D3DMAXUSERCLIPPLANES. For a given physical device, this capability may vary across Direct3DDevice objects depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending. For a given physical device, this capability may vary across Direct3DDevice objects depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrixIndex
DWORD value that specifies the maximum matrix index that can be indexed into using the per-vertex indices. The number of matrices is MaxVertexBlendMatrixIndex + 1, which is the size of the matrix palette. If normals are present in the vertex data that needs to be blended for lighting, then the number of matrices is half the number specified by this capability flag. If MaxVertexBlendMatrixIndex is set to zero, the driver does not support indexed vertex blending. If this value is not zero then the valid range of indices is zero through MaxVertexBlendMatrixIndex.

A zero value for MaxVertexBlendMatrixIndex indicates that the driver does not support indexed matrices.

When software vertex processing is used, 256 matrices could be used for indexed vertex blending, with or without normal blending.

For a given physical device, this capability may vary across Direct3DDevice objects depending on the parameters supplied to IDirect3D9::CreateDevice.

MaxPointSize
Maximum size of a point primitive. If set to 1.0f then device does not support point size control. The range is greater than or equal to 1.0f.
MaxPrimitiveCount
Maximum number of primitives for each DrawPrimitive call. Note that when Direct3D is working with a DirectX 6.0 or DirectX 7.0 driver, this field is set to 0xFFFF. This means that not only the number of primitives but also the number of vertices is limited by this value.
MaxVertexIndex
Maximum size of indices supported for hardware vertex processing. It is possible to create 32-bit index buffers by specifying D3DFMT_INDEX32; however, you will not be able to render with the index buffer unless this value is greater than 0x0000FFFF.
MaxStreams
Maximum number of concurrent data streams for IDirect3DDevice9::SetStreamSource. The valid range is 1 to 16. Note that if this value is 0, then the driver is not a DirectX 9.0 driver.
MaxStreamStride
Maximum stride for IDirect3DDevice9::SetStreamSource.
VertexShaderVersion
Two numbers that represent the vertex shader main and sub versions. For more information about the instructions supported for each vertex shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
MaxVertexShaderConst
The number of vertex shader Registers - vs_1_1 that are reserved for constants.
PixelShaderVersion
Two numbers that represent the pixel shader main and sub versions. For more information about the instructions supported for each pixel shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
PixelShader1xMaxValue
Maximum value of pixel shader arithmetic component. This value indicates the internal range of values supported for pixel color blending operations. Within the range that they report to, implementations must allow data to pass through pixel processing unmodified (unclamped). Normally, the value of this member is an absolute value. For example, a 1.0 indicates that the range is -1.0 to 1, and an 8.0 indicates that the range is -8.0 to 8.0. The value must be >= 1.0 for any hardware that supports pixel shaders.
DevCaps2
Device driver capabilities for adaptive tessellation. For more information, see D3DDEVCAPS2
MaxNpatchTesselationLevel
Maximum number of N-patch subdivision levels. The driver will clamp applications to this value, if they are using presampled displacement mapping. See Tessellation and Displacement Mapping.
MinAntialiasedLineWidth
The minimum antialiased line width. The minimum value of the width is 0.0.
MaxAntialiasedLineWidth
The maximum antialiased line width. The minimum value of the width is 1.0.
MasterAdapterOrdinal

This number indicates which device is the master for this subordinate. This number is taken from the same space as the adapter values passed to the IDirect3D9 methods.

For multihead support, one head will be denoted the "master" head, and all other heads on the same card be denoted "subordinate" heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a "group."

AdapterOrdinalInGroup
This number indicates the order in which heads are referenced by the application programming interface (API). The master adapter always has AdapterOrdinalInGroup = 0. These values do not correspond to the adapter ordinals passed to the IDirect3D9 methods. They apply only to heads within a group.
NumberOfAdaptersInGroup
Number of adapters in this adapter group (only if master). This will be 1 for conventional adapters. The value will be greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but may have many subordinates.
DeclTypes
A combination of one or more data types contained in a vertex declaration. See D3DDTCAPS.
NumSimultaneousRTs
Number of simultaneous render targets. This number must be at least one.
StretchRectFilterCaps

Combination of constants that describe the operations supported by IDirect3DDevice9::StretchRect. The flags that may be set in this field are:

Constant | Description
D3DPTFILTERCAPS_MINFPOINT | Device supports point-sample filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MAGFPOINT | Device supports point-sample filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MINFLINEAR | Device supports bilinear interpolation filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports bilinear interpolation filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.

For more information, see D3DTEXTUREFILTERTYPE and D3DTEXTUREFILTERTYPE.

VS20Caps
Device supports vertex shader version 2_0 extended capability. See D3DVS20CAPS.
PS20Caps
Device supports pixel shader version 2_0 extended capability. See D3DPS20CAPS.
VertexTextureFilterCaps
Device supports vertex shader texture filter capability. See D3DPTFILTERCAPS.
MaxVShaderInstructionsExecuted
Maximum number of vertex shader instructions that can be run.
MaxPShaderInstructionsExecuted
Maximum number of vertex shader instructions that can be run.
MaxVertexShader30InstructionSlots
Maximum number of vertex shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support vs_3_0 are required to support at least 512 instruction slots.
MaxPixelShader30InstructionSlots
Maximum number of pixel shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support vs_3_0 are required to support at least 512 instruction slots.
Reserved2
Reserved.
Reserved3
Reserved.

Remarks

The MaxTextureBlendStages and MaxSimultaneousTextures members might seem similar, but they contain different information. The MaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the MaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the IDirect3DDevice9::SetTexture method.

When the driver fills this structure, it can set values for execute-buffer capabilities, even when the interface being used to retrieve the capabilities (such as IDirect3DDevice9) does not support execute buffers.

In general, performance problems may occur if you use a texture and then modify it during a scene. Ensure that no texture used in the current IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene block is evicted unless absolutely necessary. In the case of extremely high texture usage within a scene, the results are undefined. This occurs when you modify a texture that you have used in the scene and there is no spare texture memory available. For such systems, the contents of the z-buffer become invalid at EndScene. Applications should not call IDirect3DDevice9::UpdateSurface to or from the back buffer on this type of hardware inside an BeginScene and EndScene pair. In addition, applications should not try to access the z-buffer if the D3DPRASTERCAPS_ZBUFFERLESSHSR capability flag is set. Finally, applications should not lock the back buffer or the z-buffer inside an BeginScene and EndScene pair.

The following flags concerning mipmapped textures are not supported in DirectX 9.0.

  • D3DPTFILTERCAPS_NEAREST
  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_LINEARMIPNEAREST
  • D3DPTFILTERCAPS_LINEARMIPLINEAR

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::GetDeviceCaps, IDirect3DDevice9::GetDeviceCaps

© 2002 Microsoft Corporation. All rights reserved.


D3DCLIPSTATUS9 Structure

Describes the current clip status.

Syntax

typedef struct _D3DCLIPSTATUS9 {
    DWORD ClipUnion;
    DWORD ClipIntersection;
} D3DCLIPSTATUS9;

Members

ClipUnion

Clip union flags that describe the current clip status. This member can be one or more of the following flags.

D3DCS_ALL
Combination of all clip flags.
D3DCS_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCS_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustrum.
D3DCS_FRONT
All vertices are clipped by the front plane of the viewing frustrum.
D3DCS_LEFT
All vertices are clipped by the left plane of the viewing frustrum.
D3DCS_RIGHT
All vertices are clipped by the right plane of the viewing frustrum.
D3DCS_TOP
All vertices are clipped by the top plane of the viewing frustrum.
D3DCS_PLANE0 through D3DCS_PLANE5
Application-defined clipping planes.
ClipIntersection
Clip intersection flags that describe the current clip status. This member can take the same flags as ClipUnion.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft® Direct3D® computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise OR of all vertex clip codes and ClipIntersection is a bitwise AND of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetClipStatus, IDirect3DDevice9::SetClipStatus

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLORVALUE Structure

Describes color values.

Syntax

typedef struct _D3DCOLORVALUE {
    float r;
    float g;
    float b;
    float a;
} D3DCOLORVALUE;

Members

r
Floating-point value specifying the red component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
g
Floating-point value specifying the green component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
b
Floating-point value specifying the blue component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
a
Floating-point value specifying the alpha component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.

Remarks

You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights that actually remove light from a scene.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

Color Values for Lights and Materials

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVICE_CREATION_PARAMETERS Structure

Describes the creation parameters for a device.

Syntax

typedef struct _D3DDEVICE_CREATION_PARAMETERS {
    UINT AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    HWND hFocusWindow;
    DWORD BehaviorFlags;
} D3DDEVICE_CREATION_PARAMETERS;

Members

AdapterOrdinal

Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Use this ordinal as the Adapter parameter for any of the IDirect3D9 methods. Note that different instances of Microsoft® Direct3D® 9.0 objects can use different ordinals. Adapters can enter or leave a system when users, for example, add or remove monitors from a multiple-monitor system or when they hot-swap a laptop. Consequently, use this ordinal only in a Direct3D 9.0 instance known to be valid, that is, either the Direct3D 9.0 that created this IDirect3DDevice9 interface or the Direct3D 9.0 returned from IDirect3DDevice9::GetDirect3D, as called through this IDirect3DDevice9 interface.

DeviceType
Member of the D3DDEVTYPE enumerated type. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
hFocusWindow
Window handle to which focus belongs for this Direct3D device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
BehaviorFlags

A combination of one or more D3DCREATE constants that control global behavior of the device. These constants mirror the constants passed to IDirect3D9::CreateDevice when the device was created.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3D9::CreateDevice

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVINFO_D3DVERTEXSTATS Structure

Vertex statistics detailing how many triangles are getting processed and clipped.

Syntax

typedef struct _D3DDEVINFO_D3DVERTEXSTATS {
    DWORD NumRenderedTriangles;
    DWORD NumExtraClippingTriangles;
} D3DDEVINFO_D3DVERTEXSTATS;

Members

NumRenderedTriangles
Total number of triangles that are not clipped in this frame.
NumExtraClippingTriangles
Number of new triangles generated by clipping.

Remarks

D3DDEVINFO_D3DVERTEXSTATS reports the number of triangles that have been processed and clipped by the runtime's software vertex processing. Use the debug runtime and software vertex processing to get the number of non-clipped and clipped primitives for a particular scene. Primitives will typically be clipped based on a guard band (if one is present). The clipping guard band is set with parameters such as GuardBandLeft in D3DCAPS9.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVINFO_RESOURCEMANAGER Structure

Resource usage statistics.

Syntax

typedef struct _D3DDEVINFO_RESOURCEMANAGER {
    D3DRESOURCESTATS stats[D3DRTYPECOUNT];
} D3DDEVINFO_RESOURCEMANAGER;

Members

stats
Array of resource statistics elements. See D3DRESOURCESTATS.

Remarks

D3DRTYPECOUNT refers to the number of enumerations in D3DRESOURCETYPE.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVINFO_VCACHE Structure

Vertex cache optimization hints.

Syntax

typedef struct D3DDEVINFO_VCACHE {
    DWORD Pattern;
    DWORD OptMethod;
    DWORD CacheSize;
    DWORD MagicNumber;
} D3DDEVINFO_VCACHE;

Members

Pattern
Bit pattern. Return value must be the four-character code (FOURCC) ('C', 'A', 'C', 'H').
OptMethod
Optimizations method. Use 0 to get the longest strips. Use 1 to optimize the vertex cache usage.
CacheSize
Cache size used as a target for optimization. This is required only if OptMethod is 1.
MagicNumber
Used by internal optimization methods to determine when to restart strips. This cannot be set or modified by a user. This is required only if OptMethod is 1.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData

© 2002 Microsoft Corporation. All rights reserved.


D3DDISPLAYMODE Structure

Describes the display mode.

Syntax

typedef struct _D3DDISPLAYMODE {
    UINT Width;
    UINT Height;
    UINT RefreshRate;
    D3DFORMAT Format;
} D3DDISPLAYMODE;

Members

Width
Screen width, in pixels.
Height
Screen height, in pixels.
RefreshRate
Refresh rate. The value of 0 indicates an adapter default.
Format
Member of the D3DFORMAT enumerated type, describing the surface format of the display mode.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::EnumAdapterModes, IDirect3D9::GetAdapterDisplayMode, IDirect3DDevice9::GetDisplayMode

© 2002 Microsoft Corporation. All rights reserved.


D3DGAMMARAMP Structure

Contains red, green, and blue ramp data.

Syntax

typedef struct _D3DGAMMARAMP {
    WORD red[256];
    WORD green[256];
    WORD blue[256];
} D3DGAMMARAMP;

Members

red
Array of 256 WORD element that describes the red gamma ramp.
green
Array of 256 WORD element that describes the green gamma ramp.
blue
Array of 256 WORD element that describes the blue gamma ramp.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetGammaRamp, IDirect3DDevice9::SetGammaRamp

© 2002 Microsoft Corporation. All rights reserved.


D3DINDEXBUFFER_DESC Structure

Describes an index buffer.

Syntax

typedef struct _D3DINDEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
} D3DINDEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the index buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as an index buffer.
Usage

Combination of one or more of the following flags, specifying the usage for this resource.

D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_DYNAMIC

Set to indicate that the index buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static index buffers are placed in video memory and dynamic index buffers are placed in accelerated graphics port (AGP) memory. Note that there is no separate static usage; if you do not specify D3DUSAGE_DYNAMIC the index buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are only valid on index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic index buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed index buffers. For more information, see Managing Resources.

D3DUSAGE_RTPATCHES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the index buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the index buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from an index buffer that is created with this capability can result in degraded performance.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this index buffer.
Size
Size of the index buffer, in bytes.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DIndexBuffer9::GetDesc

© 2002 Microsoft Corporation. All rights reserved.


D3DLIGHT9 Structure

Defines a set of lighting properties.

Syntax

typedef struct _D3DLIGHT9 {
    D3DLIGHTTYPE Type;
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Ambient;
    D3DVECTOR Position;
    D3DVECTOR Direction;
    float Range;
    float Falloff;
    float Attenuation0;
    float Attenuation1;
    float Attenuation2;
    float Theta;
    float Phi;
} D3DLIGHT9;

Members

Type
Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
Diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
Specular
Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
Ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
Position
Position of the light in world space, specified by a D3DVECTOR structure. This member has no meaning for directional lights and is ignored in that case.
Direction
Direction that the light is pointing in world space, specified by a D3DVECTOR structure. This member has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
Range
Distance beyond which the light has no effect. The maximum allowable value for this member is the square root of FLT_MAX. This member does not affect directional lights.
Falloff
Decrease in illumination between a spotlight's inner cone (the angle specified by Theta) and the outer edge of the outer cone (the angle specified by Phi).

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

Attenuation0
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Position, Range, and Attenuation. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation1
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Position, Range, and Attenuation. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation2
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Position, Range, and Attenuation. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Theta
Angle, in radians, of a spotlight's inner cone—that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by Phi.
Phi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::SetLight

© 2002 Microsoft Corporation. All rights reserved.


D3DLOCKED_BOX Structure

Describes a locked box (volume).

Syntax

typedef struct _D3DLOCKED_BOX {
    int RowPitch;
    int SlicePitch;
    void *pBits;
} D3DLOCKED_BOX;

Members

RowPitch
Byte offset from the left edge of one row to the left edge of the next row.
SlicePitch
Byte offset from the top-left of one slice to the top-left of the next deepest slice.
pBits
Pointer to the beginning of the volume box. If a D3DBOX was provided to the LockBox call, pBits will be appropriately offset from the start of the volume.

Remarks

Volumes can be visualized as being organized into slices of width x height 2-D surfaces stacked up to make a width x height x depth volume. For more information, see Volume Texture Resources.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVolume9::LockBox, IDirect3DVolumeTexture9::LockBox

© 2002 Microsoft Corporation. All rights reserved.


D3DLOCKED_RECT Structure

Describes a locked rectangular region.

Syntax

typedef struct _D3DLOCKED_RECT {
    INT Pitch;
    void *pBits;
} D3DLOCKED_RECT;

Members

Pitch
Pitch of surface, in bytes.
pBits
Pointer to the locked bits. If a RECT was provided to the IDirect3DSurface9::LockRect call, pBits will be appropriately offset from the start of the surface.

Remarks

The pitch for DXTn formats is different from what was returned in Microsoft® DirectX® 7.0. It now refers to the number of bytes in a row of blocks. For example, if you have a width of 16, then you will have a pitch of 4 blocks (4*8 for DXT1, 4*16 for DXT2-5.)

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::LockRect, IDirect3DSurface9::LockRect, IDirect3DTexture9::LockRect

© 2002 Microsoft Corporation. All rights reserved.


D3DMATERIAL9 Structure

Specifies material properties.

Syntax

typedef struct _D3DMATERIAL9 {
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Ambient;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Emissive;
    float Power;
} D3DMATERIAL9;

Members

Diffuse
Value specifying the diffuse color of the material. See D3DCOLORVALUE.
Ambient
Value specifying the ambient color of the material. See D3DCOLORVALUE.
Specular
Value specifying the specular color of the material. See D3DCOLORVALUE.
Emissive
Value specifying the emissive color of the material. See D3DCOLORVALUE.
Power
Floating-point value specifying the sharpness of specular highlights. The higher the value, the sharper the highlight.

Remarks

To turn off specular highlights, set D3DRS_SPECULARENABLE to FALSE, using D3DRENDERSTATETYPE. This is the fastest option because no specular highlights will be calculated.

For more information about using the lighting engine to calculate specular lighting, see Specular Lighting.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetMaterial, IDirect3DDevice9::SetMaterial

© 2002 Microsoft Corporation. All rights reserved.


D3DMATRIX Structure

Describes a matrix.

Syntax

typedef struct _D3DMATRIX {
    union {
        struct {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;

        };
        float m[4][4];
    };
} D3DMATRIX;

Members

_ij
An array of floats that represent a 4x4 matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34].

Remarks

In Microsoft® Direct3D®, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by –1 instead.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform

© 2002 Microsoft Corporation. All rights reserved.


D3DPRESENT_PARAMETERS Structure

Describes the presentation parameters.

Syntax

typedef struct _D3DPRESENT_PARAMETERS_ {
    UINT BackBufferWidth, BackBufferHeight;
    D3DFORMAT BackBufferFormat;
    UINT BackBufferCount;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    D3DSWAPEFFECT SwapEffect;
    HWND hDeviceWindow;
    BOOL Windowed;
    BOOL EnableAutoDepthStencil;
    D3DFORMAT AutoDepthStencilFormat;
    DWORD Flags;
    UINT FullScreen_RefreshRateInHz;
    UINT PresentationInterval;
} D3DPRESENT_PARAMETERS;

Members

BackBufferWidth, BackBufferHeight

Width and height of the new swap chain's back buffers, in pixels. If Windowed is FALSE (the presentation is full-screen), these values must equal the width and height of one of the enumerated display modes found through IDirect3D9::EnumAdapterModes. If Windowed is TRUE and either of these values is zero, the corresponding dimension of the client area of the hDeviceWindow (or the focus window, if hDeviceWindow is NULL) is taken.

BackBufferFormat

The back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render target formats as validated by IDirect3D9::CheckDeviceType. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format.

In fact, D3DFMT_UNKNOWN can be specified for the BackBufferFormat while in windowed mode. This tells the runtime to use the current display-mode format and eliminates the need to call IDirect3DDevice9::GetDisplayMode.

For windowed applications, the back buffer format no longer needs to match the display-mode format because color conversion can now be done by the hardware (if the hardware supports color conversion). The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. (There is the additional requirement that the device be operable in the desktop mode; devices typically do not operate in 8 bits per pixel modes.)

Full-screen applications cannot do color conversion.

BackBufferCount

This value can be 0 (or 1), 2, or 3. 0 is treated as 1. If the number of back buffers cannot be created, the runtime will fail the method call and fill this value with the number of back buffers that could be created. As a result, an application can call the method twice with the same D3DPRESENT_PARAMETERS structure and expect it to work the second time.

The method fails if one back buffer cannot be created. The value of BackBufferCount influences what set of swap effects are allowed. Specifically, any D3DSWAPEFFECT_COPY swap effect requires that there be exactly one back buffer.

MultiSampleType

Member of the D3DMULTISAMPLE_TYPE enumerated type. The value must be D3DMULTISAMPLE_NONE unless SwapEffect has been set to D3DSWAPEFFECT_DISCARD. Multisampling is supported only if the swap effect is D3DSWAPEFFECT_DISCARD.

MultiSampleQuality
Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. Paired values of render targets or depth stencil surfaces, and D3DMULTISAMPLE_TYPE must match.

SwapEffect

Member of the D3DSWAPEFFECT enumerated type. The runtime will guarantee the implied semantics concerning buffer swap behavior. So if Windowed is TRUE and SwapEffect is set to D3DSWAPEFFECT_FLIP, the runtime will create one extra back buffer, and copy whichever becomes the front buffer at presentation time.

D3DSWAPEFFECT_COPY requires that BackBufferCount be set to 1.

D3DSWAPEFFECT_DISCARD will be enforced in the debug runtime by filling any buffer with noise after it is presented.

hDeviceWindow

If full-screen, this is the cover window. If windowed, this will be the default target window for IDirect3DDevice9::Present. If this value is NULL, the focus window will be taken. For applications that use multiple full-screen devices, such as a multimonitor system, exactly one device should use the focus window as the device window. All other devices should have unique device windows. Otherwise, behavior is undefined and applications will not work as expected.

Note that no attempt is made by the runtime to reflect user changes in window size. The back buffer is not implicitly reset when this window is reset. However, the IDirect3DDevice9::Present method does automatically track window position changes.

Windowed

TRUE if the application runs windowed; FALSE if the application runs full-screen.

EnableAutoDepthStencil

If this value is TRUE, Microsoft® Direct3D® will manage depth buffers for the application. The device will create a depth-stencil buffer when it is created. The depth-stencil buffer will be automatically set as the render target of the device. When the device is reset, the depth-stencil buffer will be automatically destroyed and re-created in the new size.

If EnableAutoDepthStencil is TRUE, then AutoDepthStencilFormat must be a valid depth-stencil format.

AutoDepthStencilFormat

Member of the D3DFORMAT enumerated type. The format of the automatic depth-stencil surface that the device will create. This member is ignored unless EnableAutoDepthStencil is TRUE.

Flags

One of the D3DPRESENTFLAG.

FullScreen_RefreshRateInHz

The rate at which the display adapter refreshes the screen. For windowed mode, this value must be 0. Otherwise, this value must be one of the refresh rates returned by IDirect3D9::EnumAdapterModes or one of the following values.

D3DPRESENT_RATE_DEFAULT
The runtime chooses the presentation rate or adopts the current rate, if windowed.
PresentationInterval

Refer to D3DPRESENT for a list of possible values and their meanings.

A windowed swap chain can use one of the following values: D3DPRESENT_INTERVAL_DEFAULT, D3DPRESENT_INTERVAL_ONE (this is equivalent to D3DPRESENT_INTERVAL_DEFAULT), or D3DPRESENT_INTERVAL_IMMEDIATE.

For a full-screen swap chain, the value can be D3DPRESENT_INTERVAL_DEFAULT or the value corresponding to exactly one of the flags enumerated in the PresentationIntervals member in D3DCAPS9. Note that for a full-screen swap chain, D3DPRESENT_INTERVAL_IMMEDIATE is always a valid option. If this presentation interval is selected and the driver does not support an immediate page-flipping operation, the runtime will implement an IDirect3DDevice9::Present operation by copying the back buffer contents to the front buffer using a blit operation.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::CreateDevice, IDirect3DDevice9::CreateAdditionalSwapChain, IDirect3DDevice9::Present, IDirect3DDevice9::Reset

© 2002 Microsoft Corporation. All rights reserved.


D3DPSHADERCAPS2_0 Structure

Pixel shader driver caps.

Syntax

typedef struct _D3DPSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
    INT NumInstructionSlots;
} D3DPSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DPS20CAPS.
NumTemps
The number of temporary registers supported. See D3DPS20CAPS.
StaticFlowControlDepth
The depth of nesting of the loop/rep and call/callnz instructions. See D3DPS20CAPS.
NumInstructionSlots
The number of instruction slots supported. See D3DPS20CAPS.

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9

© 2002 Microsoft Corporation. All rights reserved.


D3DRANGE Structure

Defines a range.

Syntax

typedef struct _D3DRANGE {
    UINT Offset;
    UINT Size;
} D3DRANGE;

Members

Offset
Offset, in bytes.
Size
Size, in bytes.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DRASTER_STATUS Structure

Describes the raster status.

Syntax

typedef struct _D3DRASTER_STATUS {
    BOOL InVBlank;
    UINT ScanLine;
} D3DRASTER_STATUS;

Members

InVBlank
TRUE if the raster is in the vertical blank period. FALSE if the raster is not in the vertical blank period.
ScanLine
If InVBlank is FALSE, then this value is an integer roughly corresponding to the current scan line painted by the raster. Scan lines are numbered in the same way as Microsoft® Direct3D® surface coordinates: 0 is the top of the primary surface, extending to the value (height of the surface - 1) at the bottom of the display.

If InVBlank is TRUE, then this value is set to zero and can be ignored.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetRasterStatus

© 2002 Microsoft Corporation. All rights reserved.


D3DRECT Structure

Defines a rectangle.

Syntax

typedef struct _D3DRECT {
    LONG x1, y1;
    LONG x2, y2;
} D3DRECT;

Members

x1, y1
Coordinates of the upper-left corner of the rectangle.
x2, y2
Coordinates of the lower-right corner of the rectangle.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::Clear

© 2002 Microsoft Corporation. All rights reserved.


D3DRECTPATCH_INFO Structure

Describes a rectangular high-order patch.

Syntax

typedef struct _D3DRECTPATCH_INFO {
    UINT StartVertexOffsetWidth;
    UINT StartVertexOffsetHeight;
    UINT Width;
    UINT Height;
    UINT Stride;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DRECTPATCH_INFO;

Members

StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.
StartVertexOffsetHeight
Starting vertex offset height, in number of vertices.
Width
Width of each vertex, in number of vertices.
Height
Height of each vertex, in number of vertices.
Stride
Width of the imaginary two-dimensional vertex array, which occupies the same space as the vertex buffer. For an example, see the diagram below.
Basis
Member of the D3DBASISTYPE enumerated type, defining the basis type for the rectangular high-order patch.

Value | Order supported | Width and height
D3DBASIS_BEZIER | Linear, cubic, and quintic | Width = height = (DWORD)order + 1
D3DBASIS_BSPLINE | Linear, cubic, and quintic | Width = height > (DWORD)order
D3DBASIS_INTERPOLATE | Cubic | Width = height > (DWORD)order

Degree
Member of the D3DDEGREETYPE enumerated type, defining the degree for the rectangular patch.

Remarks

The following diagram identifies the parameters that specify a rectangle patch.

Rectangular high-order patch with parameters that specify it

Each of the vertices in the vertex buffer is shown as a black dot. In this case, the vertex buffer has 20 vertices in it, 16 of which are in the rectangle patch. The stride is the number of vertices in the width of the vertex buffer, in this case five. The x offset to the first vertex is called the StartIndexVertexWidth and is in this case 1. The y offset to the first patch vertex is called the StartIndexVertexHeight and is in this case 0.

To render a stream of individual rectangular patches (non-mosaic), you should interpret your geometry as a long narrow (1×N) rectangular patch. The D3DRECTPATCH_INFO structure for such a strip (cubic Bézier) would be set up in the following manner.

D3DRECTPATCH_INFO RectInfo;

RectInfo.Width = 4;
RectInfo.Height = 4;
RectInfo.Stride = 4;
RectInfo.Basis = D3DBASIS_BEZIER;
RectInfo.Order = D3DORDER_CUBIC;
RectInfo.StartVertexOffsetWidth = 0;
RectInfo.StartVertexOffsetHeight = 4*i;  // The variable i is the index of the
                                         //   patch you want to render.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawRectPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DRESOURCESTATS Structure

Describes a volume.

Syntax

typedef struct D3DRESOURCESTATS {
    BOOL bThrashing;
    DWORD ApproxBytesDownloaded;
    DWORD NumEvicts;
    DWORD NumVidCreates;
    DWORD LastPri;
    DWORD NumUsed;
    DWORD NumUsedInVidMem;
    DWORD WorkingSet;
    DWORD WorkingSetBytes;
    DWORD TotalManaged;
    DWORD TotalBytes;
} D3DRESOURCESTATS;

Members

bThrashing
Indicates if thrashing is occuring.
ApproxBytesDownloaded
Approximate number of bytes downloaded by the resource manager.
NumEvicts
Number of objects evicted.
NumVidCreates
Number of objects created in video memory.
LastPri
Priority of last object evicted.
NumUsed
Number of objects set to the device.
NumUsedInVidMem
Number of objects set to the device, which are already in video memory.
WorkingSet
Number of objects in video memory.
WorkingSetBytes
Number of bytes in video memory.
TotalManaged
Total number of managed objects.
TotalBytes
Total number of bytes of managed objects.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DSURFACE_DESC Structure

Describes a surface.

Syntax

typedef struct _D3DSURFACE_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    UINT Width;
    UINT Height;
} D3DSURFACE_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a surface.
Usage

Either the D3DUSAGE_DEPTHSTENCIL or D3DUSAGE_RENDERTARGET values. For more information, see D3DUSAGE.

Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this surface.

MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type, specifying the levels of full-scene multisampling supported by the surface.

MultiSampleQuality
Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces and the MultiSample type must all match.
Width
Width of the surface, in pixels.
Height
Height of the surface, in pixels.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DSurface9::GetDesc, IDirect3DTexture9::GetLevelDesc

© 2002 Microsoft Corporation. All rights reserved.


D3DTRIPATCH_INFO Structure

Describes a triangular high-order patch.

Syntax

typedef struct _D3DTRIPATCH_INFO {
    UINT StartVertexOffset;
    UINT NumVertices;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DTRIPATCH_INFO;

Members

StartVertexOffset
Starting vertex offset, in number of vertices.
NumVertices
Number of vertices.
Basis
Member of the D3DBASISTYPE enumerated type, which defines the basis type for the triangular high-order patch. The only valid value for this member is D3DBASIS_BEZIER.
Degree

Member of the D3DDEGREETYPE enumerated type, defining the degree type for the triangular high-order patch.

Value | Number of vertices
D3DORDER_CUBIC | 10
D3DORDER_LINEAR | 3
D3DORDER_QUADRATIC | N/A
D3DORDER_QUINTIC | 21

N/A - Not available. Not supported.

Remarks

For example, the following diagram identifies the vertex order and segment numbers for a cubic Bézier triangle patch. The vertex order determines the segment numbers used by IDirect3DDevice9::DrawTriPatch. The offset is the number of bytes to the first triangle patch vertex in the vertex buffer.

Triangular high-order patch with nine vertices

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawTriPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DVECTOR Structure

Defines a vector.

Syntax

typedef struct _D3DVECTOR {
    float x, y, z;
} D3DVECTOR;

Members

x, y, z
Floating-point values describing the vector.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DVERTEXBUFFER_DESC Structure

Describes a vertex buffer.

Syntax

typedef struct _D3DVERTEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
    DWORD FVF;
} D3DVERTEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the vertex buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a vertex buffer.
Usage

Combination of one or more D3DUSAGE flags.

Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this vertex buffer.
Size
Size of the vertex buffer, in bytes.
FVF
Combination of D3DFVF that describes the vertex format of the vertices in this buffer.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVertexBuffer9::GetDesc

© 2002 Microsoft Corporation. All rights reserved.


D3DVERTEXELEMENT9 Structure

Defines input vertex data to the pipeline.

Syntax

typedef struct _D3DVERTEXELEMENT9 {
    BYTE Stream;
    BYTE Offset;
    BYTE Type;
    BYTE Method;
    BYTE Usage;
    BYTE UsageIndex;
} D3DVERTEXELEMENT9;

Members

Stream
Stream number.
Offset
Offset (if any) from the beginning of the stream to the start of the data.
Type
Data type. One of several predefined types that define the data size. For more information, see D3DDECLTYPE.
Method
Tessellator processing method. This method determines how the tessellator interprets/operates on the vertex data. For more information, see D3DDECLMETHOD.
Usage
Defines the intended use of the data. For more information, see D3DDECLUSAGE.
UsageIndex
Modifies the usage data to allow the user to specify multiple usage types.

Remarks

Vertex data is defined using an array of VERTEXELEMENT9 structures.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DVIEWPORT9 Structure

Defines the window dimensions of a render target surface onto which a 3-D volume projects.

Syntax

typedef struct _D3DVIEWPORT9 {
    DWORD X;
    DWORD Y;
    DWORD Width;
    DWORD Height;
    float MinZ;
    float MaxZ;
} D3DVIEWPORT9;

Members

X
Pixel coordinate of the upper-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Y
Pixel coordinate of the upper-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Width
Width dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the width dimension of the render target surface.
Height
Height dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the height dimension of the render target surface.
MinZ
Together with MaxZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 0.0. Clipping is performed after applying the projection matrix.
MaxZ
Together with MinZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 1.0. Clipping is performed after applying the projection matrix.

Remarks

The X, Y, Width, and Height members describe the position and dimensions of the viewport on the render target surface. Usually, applications render to the entire target surface; when rendering on a 640×480 surface, these members should be 0, 0, 640, and 480, respectively. The MinZ and MaxZ are typically set to 0.0 and 1.0 but can be set to other values to achieve specific effects. For example, you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (because of a call to the IDirect3DDevice9::SetViewport method), the driver builds a new transformation matrix.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetViewport, IDirect3DDevice9::SetViewport

© 2002 Microsoft Corporation. All rights reserved.


D3DVOLUME_DESC Structure

Describes a volume.

Syntax

typedef struct _D3DVOLUME_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Width;
    UINT Height;
    UINT Depth;
} D3DVOLUME_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the volume.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a volume.
Usage
Currently not used. Always returned as 0.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this volume.
Width
Width of the volume, in pixels.
Height
Height of the volume, in pixels.
Depth
Depth of the volume, in pixels.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVolume9::GetDesc, IDirect3DVolumeTexture9::GetLevelDesc

© 2002 Microsoft Corporation. All rights reserved.


D3DVSHADERCAPS2_0 Structure

Vertex shader caps.

Syntax

typedef struct _D3DVSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
} D3DVSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DVS20CAPS.
NumTemps
The number of temporary registers supported. See D3DVS20CAPS.
StaticFlowControlDepth
The depth of nesting of the loop/rep and call/callnz instructions. See D3DVS20CAPS.

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

D3DPSHADERCAPS2_0, D3DCAPS9

© 2002 Microsoft Corporation. All rights reserved.


PALETTEENTRY Structure

Specifies the color and usage of an entry in a logical palette.

Syntax

typedef struct tagPALETTEENTRY {
    BYTE peRed;
    BYTE peGreen;
    BYTE peBlue;
    BYTE peFlags;
} PALETTEENTRY;

Members

peRed
The red intensity value for the palette entry.
peGreen
The green intensity value for the palette entry.
peBlue
The blue intensity value for the palette entry.
peFlags
The alpha intensity value for the palette entry. Note that as of Microsoft® DirectX® 8.0, this member is treated differently than documented in the Microsoft Platform Software Development Kit (SDK).

Structure Information

Header | wingdi.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Enumerated Types

This section contains information about the following enumerated types used with Microsoft® Direct3D®.

Enumerations

  • D3DBACKBUFFER_TYPE
  • D3DBASISTYPE
  • D3DBLEND
  • D3DBLENDOP
  • D3DCMPFUNC
  • D3DCUBEMAP_FACES
  • D3DCULL
  • D3DDEBUGMONITORTOKENS
  • D3DDECLMETHOD
  • D3DDECLTYPE
  • D3DDECLUSAGE
  • D3DDEGREETYPE
  • D3DDEVTYPE
  • D3DERR
  • D3DFILLMODE
  • D3DFOGMODE
  • D3DFORMAT
  • D3DLIGHTTYPE
  • D3DMATERIALCOLORSOURCE
  • D3DMULTISAMPLE_TYPE
  • D3DPATCHEDGESTYLE
  • D3DPOOL
  • D3DPRIMITIVETYPE
  • D3DQUERYTYPE
  • D3DRENDERSTATETYPE
  • D3DRESOURCETYPE
  • D3DSAMPLER_TEXTURE_TYPE
  • D3DSAMPLERSTATETYPE
  • D3DSHADEMODE
  • D3DSTATEBLOCKTYPE
  • D3DSWAPEFFECT
  • D3DTEXTUREADDRESS
  • D3DTEXTUREFILTERTYPE
  • D3DTEXTUREOP
  • D3DTEXTURESTAGESTATETYPE
  • D3DTEXTURETRANSFORMFLAGS
  • D3DTRANSFORMSTATETYPE
  • D3DVERTEXBLENDFLAGS
  • D3DZBUFFERTYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DBACKBUFFER_TYPE Enumerated Type

Defines constants that describe the type of back buffer.

Syntax

typedef enum _D3DBACKBUFFER_TYPE {
    D3DBACKBUFFER_TYPE_MONO = 0,
    D3DBACKBUFFER_TYPE_LEFT = 1,
    D3DBACKBUFFER_TYPE_RIGHT = 2,
    D3DBACKBUFFER_TYPE_FORCE_DWORD = 0x7fffffff
} D3DBACKBUFFER_TYPE;

Constants

D3DBACKBUFFER_TYPE_MONO

Specifies a nonstereo swap chain.

D3DBACKBUFFER_TYPE_LEFT

Specifies the left side of a stereo pair in a swap chain.

D3DBACKBUFFER_TYPE_RIGHT

Specifies the right side of a stereo pair in a swap chain.

D3DBACKBUFFER_TYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Microsoft® DirectX® 9.0 does not support stereo view, so Microsoft Direct3D® does not use the D3DBACKBUFFER_TYPE_LEFT and D3DBACKBUFFER_TYPE_RIGHT values of this enumerated type.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetBackBuffer, IDirect3DSwapChain9::GetBackBuffer

© 2002 Microsoft Corporation. All rights reserved.


D3DBASISTYPE Enumerated Type

Defines the basis type of a high-order patch surface.

Syntax

typedef enum _D3DBASISTYPE {
    D3DBASIS_BEZIER = 0,
    D3DBASIS_BSPLINE = 1,
    D3DBASIS_CATMULL_ROM = 2,
    D3DBASIS_FORCE_DWORD = 0x7fffffff
} D3DBASISTYPE;

Constants

D3DBASIS_BEZIER

Input vertices are treated as a series of Bézier patches. The number of vertices specified must be divisible by 3 + 1. Portions of the mesh beyond this criterion will not be rendered. Full continuity is assumed between sub-patches in the interior of the surface rendered by each call. Only the vertices at the corners of each sub-patch are guaranteed to lie on the resulting surface.

D3DBASIS_BSPLINE

Input vertices are treated as control points of a B-spline surface. The number of apertures rendered is two fewer than the number of apertures in that direction. In general, the generated surface does not contain the control vertices specified.

D3DBASIS_CATMULL_ROM

An interpolating basis defines the surface so that the surface goes through all the input vertices specified. In Microsoft® DirectX® 8.0, this was D3DBASIS_INTERPOLATE.

D3DBASIS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of D3DBASISTYPE specify the formulation to be used in evaluating the high-order patch surface primitive during tessellation.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO

© 2002 Microsoft Corporation. All rights reserved.


D3DBLEND Enumerated Type

Defines the supported blend mode.

Syntax

typedef enum _D3DBLEND {
    D3DBLEND_ZERO = 1,
    D3DBLEND_ONE = 2,
    D3DBLEND_SRCCOLOR = 3,
    D3DBLEND_INVSRCCOLOR = 4,
    D3DBLEND_SRCALPHA = 5,
    D3DBLEND_INVSRCALPHA = 6,
    D3DBLEND_DESTALPHA = 7,
    D3DBLEND_INVDESTALPHA = 8,
    D3DBLEND_DESTCOLOR = 9,
    D3DBLEND_INVDESTCOLOR = 10,
    D3DBLEND_SRCALPHASAT = 11,
    D3DBLEND_BOTHSRCALPHA = 12,
    D3DBLEND_BOTHINVSRCALPHA = 13,
    D3DBLEND_BLENDFACTOR = 14,
    D3DBLEND_INVBLENDFACTOR = 15,
    D3DBLEND_FORCE_DWORD = 0x7fffffff
} D3DBLEND;

Constants

D3DBLEND_ZERO

Blend factor is (0, 0, 0, 0).

D3DBLEND_ONE

Blend factor is (1, 1, 1, 1).

D3DBLEND_SRCCOLOR

Blend factor is (Rs,Gs,Bs,As).

D3DBLEND_INVSRCCOLOR

Blend factor is (1 - Rs, 1 - Gs, 1 - Bs, 1 - As).

D3DBLEND_SRCALPHA

Blend factor is (As, As, As, As).

D3DBLEND_INVSRCALPHA

Blend factor is ( 1 - As, 1 - As, 1 - As, 1 - As).

D3DBLEND_DESTALPHA

Blend factor is (Ad, Ad, Ad, Ad).

D3DBLEND_INVDESTALPHA

Blend factor is (1 - Ad, 1 - Ad, 1 - Ad, 1 - Ad).

D3DBLEND_DESTCOLOR

Blend factor is (Rd, Gd, Bd, Ad).

D3DBLEND_INVDESTCOLOR

Blend factor is (1 - Rd, 1 - Gd, 1 - Bd, 1 - Ad).

D3DBLEND_SRCALPHASAT

Blend factor is (f, f, f, 1); f = min(A, 1 - Ad).

D3DBLEND_BOTHSRCALPHA

Obsolete. For Microsoft® DirectX® 6.0 and later, you can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.

D3DBLEND_BOTHINVSRCALPHA

Source blend factor is (1 - As, 1 - As, 1 - As, 1 - As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden. This blend mode is supported only for the D3DRS_SRCBLEND render state.

D3DBLEND_BLENDFACTOR

Constant color blending factor used by the frame-buffer blender. This blend mode is supported only if D3DPBLEND_BLENDFACTOR is on.

D3DBLEND_INVBLENDFACTOR

Inverted constant color-blending factor used by the frame-buffer blender. This blend mode is supported only if the D3DPBLEND_BLENDFACTOR bit is set in the SrcBlendCaps or DestBlendCaps members of D3DCAPS9.

D3DBLEND_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In the member descriptions above, the RGBA values of the source and destination are indicated by the s and d subscripts.

The values in this enumerated type are used by the D3DRS_DESTBLEND render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DBLENDOP Enumerated Type

Defines the supported blend operations.

Syntax

typedef enum _D3DBLENDOP {
    D3DBLENDOP_ADD = 1,
    D3DBLENDOP_SUBTRACT = 2,
    D3DBLENDOP_REVSUBTRACT = 3,
    D3DBLENDOP_MIN = 4,
    D3DBLENDOP_MAX = 5,
    D3DBLENDOP_FORCE_DWORD = 0x7fffffff
} D3DBLENDOP;

Constants

D3DBLENDOP_ADD

The result is the destination added to the source.

Result = Source + Destination

D3DBLENDOP_SUBTRACT

The result is the destination subtracted from to the source.

Result = Source - Destination

D3DBLENDOP_REVSUBTRACT

The result is the source subtracted from the destination.

Result = Destination - Source

D3DBLENDOP_MIN

The result is the minimum of the source and destination.

Result = MIN(Source, Destination)

D3DBLENDOP_MAX

The result is the maximum of the source and destination.

Result = MAX(Source, Destination)

D3DBLENDOP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

This enumerated type defines values used by the D3DRS_BLENDOP render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9, D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DCMPFUNC Enumerated Type

Defines the supported compare functions.

Syntax

typedef enum _D3DCMPFUNC {
    D3DCMP_NEVER = 1,
    D3DCMP_LESS = 2,
    D3DCMP_EQUAL = 3,
    D3DCMP_LESSEQUAL = 4,
    D3DCMP_GREATER = 5,
    D3DCMP_NOTEQUAL = 6,
    D3DCMP_GREATEREQUAL = 7,
    D3DCMP_ALWAYS = 8,
    D3DCMP_FORCE_DWORD = 0x7fffffff
} D3DCMPFUNC;

Constants

D3DCMP_NEVER

Always fail the test.

D3DCMP_LESS

Accept the new pixel if its value is less than the value of the current pixel.

D3DCMP_EQUAL

Accept the new pixel if its value equals the value of the current pixel.

D3DCMP_LESSEQUAL

Accept the new pixel if its value is less than or equal to the value of the current pixel.

D3DCMP_GREATER

Accept the new pixel if its value is greater than the value of the current pixel.

D3DCMP_NOTEQUAL

Accept the new pixel if its value does not equal the value of the current pixel.

D3DCMP_GREATEREQUAL

Accept the new pixel if its value is greater than or equal to the value of the current pixel.

D3DCMP_ALWAYS

Always pass the test.

D3DCMP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type define the supported compare functions for the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DCUBEMAP_FACES Enumerated Type

Defines the faces of a cubemap.

Syntax

typedef enum _D3DCUBEMAP_FACES {
    D3DCUBEMAP_FACE_POSITIVE_X = 0,
    D3DCUBEMAP_FACE_NEGATIVE_X = 1,
    D3DCUBEMAP_FACE_POSITIVE_Y = 2,
    D3DCUBEMAP_FACE_NEGATIVE_Y = 3,
    D3DCUBEMAP_FACE_POSITIVE_Z = 4,
    D3DCUBEMAP_FACE_NEGATIVE_Z = 5,
    D3DCUBEMAP_FACE_FORCE_DWORD = 0xffffffff
} D3DCUBEMAP_FACES;

Constants

D3DCUBEMAP_FACE_POSITIVE_X

Positive x-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_X

Negative x-face of the cubemap.

D3DCUBEMAP_FACE_POSITIVE_Y

Positive y-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_Y

Negative y-face of the cubemap.

D3DCUBEMAP_FACE_POSITIVE_Z

Positive z-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_Z

Negative z-face of the cubemap.

D3DCUBEMAP_FACE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetCubeMapSurface, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect

© 2002 Microsoft Corporation. All rights reserved.


D3DCULL Enumerated Type

Defines the supported culling modes.

Syntax

typedef enum _D3DCULL {
    D3DCULL_NONE = 1,
    D3DCULL_CW = 2,
    D3DCULL_CCW = 3,
    D3DCULL_FORCE_DWORD = 0x7fffffff
} D3DCULL;

Constants

D3DCULL_NONE

Do not cull back faces.

D3DCULL_CW

Cull back faces with clockwise vertices.

D3DCULL_CCW

Cull back faces with counterclockwise vertices.

D3DCULL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_CULLMODE render state. The culling modes define how back faces are culled when rendering a geometry.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9, D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DDEBUGMONITORTOKENS Enumerated Type

Defines the debug monitor tokens.

Syntax

typedef enum _D3DDEBUGMONITORTOKENS {
    D3DDMT_ENABLE = 0,
    D3DDMT_DISABLE = 1,
    D3DDMT_FORCE_DWORD = 0x7fffffff
} D3DDEBUGMONITORTOKENS;

Constants

D3DDMT_ENABLE

Enable the debug monitor.

D3DDMT_DISABLE

Disable the debug monitor.

D3DDMT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_DEBUGMONITORTOKEN render state and are only relevant for debug builds.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DDECLMETHOD Enumerated Type

Defines the vertex declaration method. The method tells the tessellator what data needs to be generated from the vertex data during tessellation.

Syntax

typedef enum _D3DDECLMETHOD {
    D3DDECLMETHOD_DEFAULT = 0,
    D3DDECLMETHOD_PARTIALU = 1,
    D3DDECLMETHOD_PARTIALV = 2,
    D3DDECLMETHOD_CROSSUV = 3,
    D3DDECLMETHOD_UV = 4,
    D3DDECLMETHOD_LOOKUP,
    D3DDECLMETHOD_LOOKUPPRESAMPLED
} D3DDECLMETHOD;

Constants

D3DDECLMETHOD_DEFAULT

Default value. The tessellator copies the vertex data (spline data for patches) as is, with no additional calculations. When the tessellator is used, this element is interpolated. Otherwise vertex data is copied into the input register. The input and output type can be any value.

D3DDECLMETHOD_PARTIALU

Computes the tangent at a point on the rectangle or triangle patch in the U direction. The input type can be D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4, D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, D3DDECLTYPE_SHORT4. The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_PARTIALV

Computes the tangent at a point on the rectangle or triangle patch in the V direction. The input type can be D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT4, D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, or D3DDECLTYPE_SHORT4. The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_CROSSUV

Computes the normal at a point on the rectangle or triangle patch by taking the cross product of the two tangents. The input type can be D3DDECLTYPE_FLOAT[43], D3DDECLTYPE_D3DCOLOR, D3DDECLTYPE_UBYTE4, or D3DDECLTYPE_SHORT4. The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_UV

Copy out the U, V values at a point on the rectangle or triangle patch. This results in a 2-D float. The input type must be set to D3DDECLTYPE_UNUSED. The output data type is always D3DDECLTYPE_FLOAT2. The input stream and offset are also unused (but must be set to 0).

D3DDECLMETHOD_LOOKUP

Look up a displacement map. The input type can be D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT3, or D3DDECLTYPE_FLOAT4. Only the .x and .y components are used for the texture map lookup. The output type is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping. This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled.

D3DDECLMETHOD_LOOKUPPRESAMPLED

Look up a presampled displacement map. The input type must be set to D3DDECLTYPE_UNUSED. The stream index and the stream offset must be set to 0. The output type for this operation is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping. This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled.

Remarks

The tessellator looks at the method to determine what data to calculate from the vertex data during tessellation. Mesh data should use the default value. Patches can use any of the other implemented types.

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration method.

In addition to using D3DDECLMETHOD_DEFAULT, a normal mesh can use D3DDECLMETHOD_LOOKUP and D3DDECLMETHOD_LOOKUPPRESAMPLED methods when N-patches are enabled.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DDECLTYPE Enumerated Type

Defines a vertex declaration data type.

Syntax

typedef enum _D3DDECLTYPE {
    D3DDECLTYPE_FLOAT1,
    D3DDECLTYPE_FLOAT2,
    D3DDECLTYPE_FLOAT3,
    D3DDECLTYPE_FLOAT4,
    D3DDECLTYPE_D3DCOLOR,
    D3DDECLTYPE_UBYTE4,
    D3DDECLTYPE_SHORT2,
    D3DDECLTYPE_SHORT4,
    D3DDECLTYPE_UBYTE4N,
    D3DDECLTYPE_SHORT2N,
    D3DDECLTYPE_SHORT4N,
    D3DDECLTYPE_USHORT2N,
    D3DDECLTYPE_USHORT4N,
    D3DDECLTYPE_UDEC3,
    D3DDECLTYPE_DEC3N,
    D3DDECLTYPE_FLOAT16_2,
    D3DDECLTYPE_FLOAT16_4,
    D3DDECLTYPE_UNUSED
} D3DDECLTYPE;

Constants

D3DDECLTYPE_FLOAT1

1-D float expanded to (float, 0, 0, 1).

D3DDECLTYPE_FLOAT2

2-D float expanded to (float, float, 0, 1).

D3DDECLTYPE_FLOAT3

3-D float expanded to (float, float, float, 1).

D3DDECLTYPE_FLOAT4

4-D float expanded to (float, float, float, float).

D3DDECLTYPE_D3DCOLOR

4-D packed unsigned bytes mapped to 0 to 1 range. Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A).

D3DDECLTYPE_UBYTE4

4-D unsigned byte.

D3DDECLTYPE_SHORT2

2-D signed short expanded to (value, value, 0, 1).

D3DDECLTYPE_SHORT4

4-D signed short expanded to (value, value, value, value).

D3DDECLTYPE_UBYTE4N

Each of 4 bytes is normalized by dividing to 255.0. This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_SHORT2N

Normalized, 2-D signed short, expanded to (First byte/32767.0, second byte/32767.0, 0, 1). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_SHORT4N

Normalized, 4-D signed short, expanded to (First byte/32767.0, second byte/32767.0, third byte/32767.0, fourth byte/32767.0). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_USHORT2N

Normalized, 2-D unsigned short, expanded to (First byte/65535.0, second byte/65535.0, 0, 1). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_USHORT4N

Normalized 4-D unsigned short, expanded to (First byte/65535.0, second byte/65535.0, third byte/65535.0, fourth byte/65535.0). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_UDEC3

3-D unsigned 10 10 10 format expanded to (value, value, value, 1).

D3DDECLTYPE_DEC3N

3-D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).

D3DDECLTYPE_FLOAT16_2

Two 16-bit floating point values expanded to (value, value, 0, 1). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_FLOAT16_4

Four 16-bit floating point values expanded to (value, value, value, value). This type is valid for vertex shader version 2.0 or higher.

D3DDECLTYPE_UNUSED

Type field in the declaration is unused. This is designed for use with D3DDECLMETHOD_UV and D3DDECLMETHOD_LOOKUPPRESAMPLED.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration data type.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DDECLMETHOD

© 2002 Microsoft Corporation. All rights reserved.


D3DDECLUSAGE Enumerated Type

Identifies the intended use of vertex data.

Syntax

typedef enum _D3DDECLUSAGE {
    D3DDECLUSAGE_POSITION = 0,
    D3DDECLUSAGE_BLENDWEIGHT = 1,
    D3DDECLUSAGE_BLENDINDICES = 2,
    D3DDECLUSAGE_NORMAL = 3,
    D3DDECLUSAGE_PSIZE = 4,
    D3DDECLUSAGE_TEXCOORD = 5,
    D3DDECLUSAGE_TANGENT = 6,
    D3DDECLUSAGE_BINORMAL = 7,
    D3DDECLUSAGE_TESSFACTOR = 8,
    D3DDECLUSAGE_POSITIONT = 9,
    D3DDECLUSAGE_COLOR = 10,
    D3DDECLUSAGE_FOG = 11,
    D3DDECLUSAGE_DEPTH = 12,
    D3DDECLUSAGE_SAMPLE = 13
} D3DDECLUSAGE;

Constants

D3DDECLUSAGE_POSITION

Position data. (D3DDECLUSAGE_POSITION with UsageIndex = 0 ) specifies un-transformed position in fixed function vertex processing and the n-patch tessellator. (D3DDECLUSAGE_POSITION with UsageIndex = 1) specifies un-transformed position in the fixed function vertex shader for skinning.

D3DDECLUSAGE_BLENDWEIGHT

Blending weight data. (D3DDECLUSAGE_BLENDWEIGHT with UsageIndex = 0) specifies The blend weights in fixed function vertex processing.

D3DDECLUSAGE_BLENDINDICES

Blending indices data. (D3DDECLUSAGE_BLENDINDICES with UsageIndex = 0) specifies matrix indices for fixed function vertex processing using indexed pa letted skinning.

D3DDECLUSAGE_NORMAL

Vertex normal data. (D3DDECLUSAGE_NORMAL with UsageIndex = 0) specifies vertex normals for fixed function vertex processing and the n-patch tessellator. (D3DDECLUSAGE_NORMAL with UsageIndex = 1) specifies vertex normals for fixed function vertex processing for skinning.

D3DDECLUSAGE_PSIZE

Point size data. (D3DDECLUSAGE_PSIZE with UsageIndex = 0) specifies the point-size attribute used by the setup engine of the rasterizer to expand a point into a quad for the point-sprite functionality.

D3DDECLUSAGE_TEXCOORD

Texture coordinate data. (D3DDECLUSAGE_TEXCOORD, n) specifies texture coordinates in fixed function vertex processing and in pixel shaders prior to ps_3_0. These can be used to pass user defined data.

D3DDECLUSAGE_TANGENT

Vertex tangent data.

D3DDECLUSAGE_BINORMAL

Vertex binormal data.

D3DDECLUSAGE_TESSFACTOR

Single positive floating point value. (D3DDECLUSAGE_TESSFACTOR with UsageIndex = 0) specifies a tessellation factor used in the tessellation unit to control the rate of tessellation. For more information about the data type, see D3DDECLTYPE_FLOAT1.

D3DDECLUSAGE_POSITIONT

Vertex data contains transformed position data. (D3DDECLUSAGE_POSITIONT with UsageIndex = 0) specifies transformed position. When a declaration containing this is set, the pipeline does not perform vertex processing.

D3DDECLUSAGE_COLOR

Vertex data contains diffuse or specular color. (D3DDECLUSAGE_COLOR with UsageIndex = 0) specifies the diffuse color in the fixed function vertex shader and pixel shaders prior to ps_3_0. (D3DDECLUSAGE_COLOR with UsageIndex = 1) specifies the specular color in the fixed function vertex shader and pixel shaders prior to ps_3_0.

D3DDECLUSAGE_FOG

Vertex data contains fog data. (D3DDECLUSAGE_FOG with UsageIndex = 0) specifies a fog blend value used after pixel shading finishes. This applies to pixel shaders prior to version ps_3_0.

D3DDECLUSAGE_DEPTH

Vertex data contains depth data.

D3DDECLUSAGE_SAMPLE

Vertex data contains sampler data. (D3DDECLUSAGE_SAMPLE with UsageIndex = 0) specifies the displacement value to look up. It can be used only with D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a usage type.

For more information about decoupling vertex shaders and vertex declarations, see Decoupling Vertex Shaders and Vertex Declarations.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

Vertex Declaration

© 2002 Microsoft Corporation. All rights reserved.


D3DDEGREETYPE Enumerated Type

Defines the degree of the variables in the equation that describes a curve.

Syntax

typedef enum _D3DDEGREETYPE {
    D3DDEGREE_LINEAR = 1,
    D3DDEGREE_QUADRATIC = 2,
    D3DDEGREE_CUBIC = 3,
    D3DDEGREE_QUINTIC = 5,
    D3DCULL_FORCE_DWORD = 0x7fffffff
} D3DDEGREETYPE;

Constants

D3DDEGREE_LINEAR

Curve is described by variables of first order.

D3DDEGREE_QUADRATIC

Curve is described by variables of second order.

D3DDEGREE_CUBIC

Curve is described by variables of third order.

D3DDEGREE_QUINTIC

Curve is described by variables of fourth order.

D3DCULL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumeration are used to describe the curves used by rectangle and triangle patches. For more information, see D3DRS_CULLMODE.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 95

See Also

D3DCAPS9, D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVTYPE Enumerated Type

Defines device types.

Syntax

typedef enum _D3DDEVTYPE {
    D3DDEVTYPE_HAL = 1,
    D3DDEVTYPE_REF = 2,
    D3DDEVTYPE_SW = 3,
    D3DDEVTYPE_FORCE_DWORD = 0xffffffff
} D3DDEVTYPE;

Constants

D3DDEVTYPE_HAL

Hardware rasterization. Shading is done with software, hardware, or mixed transform and lighting.

D3DDEVTYPE_REF

Microsoft® Direct3D® features are implemented in software; however, the reference rasterizer does make use of special CPU instructions whenever it can.

D3DDEVTYPE_SW

A pluggable software device that has been registered with IDirect3D9::RegisterSoftwareDevice.

D3DDEVTYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::CheckDeviceFormat, IDirect3D9::CheckDeviceMultiSampleType, IDirect3D9::CheckDeviceType, IDirect3D9::CreateDevice, IDirect3D9::GetDeviceCaps, D3DDEVICE_CREATION_PARAMETERS

© 2002 Microsoft Corporation. All rights reserved.


D3DERR Enumerated Type

Errors are represented by negative values and cannot be combined. The following lists the values that can be returned by Microsoft® Direct3D® methods. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

Syntax

typedef enum {
    D3D_OK,
    D3DOK_NOAUTOGEN,
    D3DERR_CONFLICTINGRENDERSTATE,
    D3DERR_CONFLICTINGTEXTUREFILTER,
    D3DERR_CONFLICTINGTEXTUREPALETTE,
    D3DERR_DEVICELOST,
    D3DERR_DEVICENOTRESET,
    D3DERR_DRIVERINTERNALERROR,
    D3DERR_INVALIDCALL,
    D3DERR_INVALIDDEVICE,
    D3DERR_MOREDATA,
    D3DERR_NOTAVAILABLE,
    D3DERR_NOTFOUND,
    D3DERR_OUTOFVIDEOMEMORY,
    D3DERR_TOOMANYOPERATIONS,
    D3DERR_UNSUPPORTEDALPHAARG,
    D3DERR_UNSUPPORTEDALPHAOPERATION,
    D3DERR_UNSUPPORTEDCOLORARG,
    D3DERR_UNSUPPORTEDCOLOROPERATION,
    D3DERR_UNSUPPORTEDFACTORVALUE,
    D3DERR_UNSUPPORTEDTEXTUREFILTER,
    D3DERR_WRONGTEXTUREFORMAT,
    E_FAIL,
    E_INVALIDARG,
    E_INVALIDCALL,
    E_OUTOFMEMORY,
    S_OK
} D3DERR;

Constants

D3D_OK

No error occurred.

D3DOK_NOAUTOGEN

This is a success code. However, the autogeneration of mipmaps is not supported for this format. This means that resource creation will succeed but the mipmap levels will not be automatically generated.

D3DERR_CONFLICTINGRENDERSTATE

The currently set render states cannot be used together.

D3DERR_CONFLICTINGTEXTUREFILTER

The current texture filters cannot be used together.

D3DERR_CONFLICTINGTEXTUREPALETTE

The current textures cannot be used simultaneously.

D3DERR_DEVICELOST

The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.

D3DERR_DEVICENOTRESET

The device has been lost but can be reset at this time.

D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL

The method call is invalid. For example, a method's parameter may not be a valid pointer.

D3DERR_INVALIDDEVICE

The requested device type is not valid.

D3DERR_MOREDATA

There is more data available than the specified buffer size can hold.

D3DERR_NOTAVAILABLE

This device does not support the queried technique.

D3DERR_NOTFOUND

The requested item was not found.

D3DERR_OUTOFVIDEOMEMORY

Direct3D does not have enough display memory to perform the operation.

D3DERR_TOOMANYOPERATIONS

The application is requesting more texture-filtering operations than the device supports.

D3DERR_UNSUPPORTEDALPHAARG

The device does not support a specified texture-blending argument for the alpha channel.

D3DERR_UNSUPPORTEDALPHAOPERATION

The device does not support a specified texture-blending operation for the alpha channel.

D3DERR_UNSUPPORTEDCOLORARG

The device does not support a specified texture-blending argument for color values.

D3DERR_UNSUPPORTEDCOLOROPERATION

The device does not support a specified texture-blending operation for color values.

D3DERR_UNSUPPORTEDFACTORVALUE

The device does not support the specified texture factor value.

D3DERR_UNSUPPORTEDTEXTUREFILTER

The device does not support the specified texture filter.

D3DERR_WRONGTEXTUREFORMAT

The pixel format of the texture surface is not valid.

E_FAIL

An undetermined error occurred inside the Direct3D subsystem.

E_INVALIDARG

An invalid parameter was passed to the returning function.

E_INVALIDCALL

The method call is invalid. For example, a method's parameter may have an invalid value.

E_OUTOFMEMORY

Direct3D could not allocate sufficient memory to complete the call.

S_OK

No error occurred.

Enumerated Type Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DFILLMODE Enumerated Type

Defines constants describing the fill mode.

Syntax

typedef enum _D3DFILLMODE {
    D3DFILL_POINT = 1,
    D3DFILL_WIREFRAME = 2,
    D3DFILL_SOLID = 3,
    D3DFILL_FORCE_DWORD = 0x7fffffff
} D3DFILLMODE;

Constants

D3DFILL_POINT

Fill points.

D3DFILL_WIREFRAME

Fill wireframes.

D3DFILL_SOLID

Fill solids.

D3DFILL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FILLMODE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DFOGMODE Enumerated Type

Defines constants that describe the fog mode.

Syntax

typedef enum _D3DFOGMODE {
    D3DFOG_NONE = 0,
    D3DFOG_EXP = 1,
    D3DFOG_EXP2 = 2,
    D3DFOG_LINEAR = 3,
    D3DFOG_FORCE_DWORD = 0x7fffffff
} D3DFOGMODE;

Constants

D3DFOG_NONE

No fog effect.

D3DFOG_EXP

Fog effect intensifies exponentially, according to the following formula.

Fog-effect intensity formula

D3DFOG_EXP2

Fog effect intensifies exponentially with the square of the distance, according to the following formula.

Fog-effect intensity formula

D3DFOG_LINEAR

Fog effect intensifies linearly between the start and end points, according to the following formula.

Fog-effect intensity formula

This is the only fog mode currently supported.

D3DFOG_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states.

Fog can be considered a measure of visibility—the lower the fog value produced by a fog equation, the less visible an object is.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DFORMAT

Defines the various types of surface formats.

Syntax

typedef enum _D3DFORMAT {

... (values)

} D3DFORMAT;

There are several types of formats.

  • Unsigned Formats
  • Signed Formats
  • Mixed Formats
  • FOURCC Formats
  • Buffer Formats
  • Floating-Point Formats
  • IEEE Formats
  • BackBuffer or Display Formats

All formats are listed from left to right, most significant bit (MSB) to least significant bit (LSB). For example, D3DFORMAT_ARGB is ordered from the MSB channel A (alpha), to the LSB channel B (blue). When traversing surface data, the data is stored in memory from LSB to MSB, which means that the channel order in memory is from LSB (blue) to MSB (alpha).

The default value for formats that contain undefined channels (G16R16, A8 etc.) is 1. The only exception is the A8 format, which is initialized to 000 for the three color channels.

Unsigned Formats

These constants refer to opcodes for texture address instructions for pixel shaders.

Data in an unsigned format must be positive. Unsigned formats use combinations of (R)ed, (G)reen, (B)lue, (A)lpha, (L)uminance, and (P)alette data. Palette data is also referred to as color indexed data because the data is used to index a color palette.

Unsigned format flags | Value | Format
D3DFMT_R8G8B8 | 20 | 24-bit RGB pixel format with 8 bits per channel.
D3DFMT_A8R8G8B8 | 21 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8R8G8B8 | 22 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_R5G6B5 | 23 | 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for blue.
D3DFMT_X1R5G5B5 | 24 | 16-bit pixel format where 5 bits are reserved for each color.
D3DFMT_A1R5G5B5 | 25 | 16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha.
D3DFMT_A4R4G4B4 | 26 | 16-bit ARGB pixel format with 4 bits for each channel.
D3DFMT_R3G3B2 | 27 | 8-bit RGB texture format using 3 bits for red, 3 bits for green, and 2 bits for blue.
D3DFMT_A8 | 28 | 8-bit alpha only.
D3DFMT_A8R3G3B2 | 29 | 16-bit ARGB texture format using 8 bits for alpha, 3 bits each for red and green, and 2 bits for blue.
D3DFMT_X4R4G4B4 | 30 | 16-bit RGB pixel format using 4 bits for each color.
D3DFMT_A2B10G10R10 | 31 | 32-bit pixel format using 10 bits for each color and 2 bits for alpha.
D3DFMT_A8B8G8R8 | 32 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8B8G8R8 | 33 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_G16R16 | 34 | 32-bit pixel format using 16 bits each for green and red.
D3DFMT_A2R10G10B10 | 35 | 32-bit pixel format using 10 bits each for red, green, and blue, and 2 bits for alpha.
D3DFMT_A16B16G16R16 | 36 | 64-bit pixel format using 16 bits for each component.
D3DFMT_A8P8 | 40 | 8-bit color indexed with 8 bits of alpha.
D3DFMT_P8 | 41 | 8-bit color indexed.
D3DFMT_L8 | 50 | 8-bit luminance only.
D3DFMT_L16 | 81 | 16-bit luminance only.
D3DFMT_A8L8 | 51 | 16-bit using 8 bits each for alpha and luminance.
D3DFMT_A4L4 | 52 | 8-bit using 4 bits each for alpha and luminance.

Signed Formats

Data in a signed format can be both positive and negative. Signed formats use combinations of (U), (V), (W), and (Q) data.

Signed format flags | Value | Format
D3DFMT_V8U8 | 60 | 16-bit bump-map format using 8 bits each for u and v data.
D3DFMT_Q8W8V8U8 | 63 | 32-bit bump-map format using 8 bits for each channel.
D3DFMT_V16U16 | 64 | 32-bit bump-map format using 16 bits for each channel.
D3DFMT_Q16W16V16U16 | 110 | 64-bit bump-map format using 16 bits for each component.
D3DFMT_CxV8U8 | 117 | 16-bit normal compression format. The texture sampler computes the C channel from: C = sqrt(1 - U2 - V2).

Mixed Formats

Data in mixed formats can contain a combination of unsigned data and signed data.

Mixed format flags | Value | Format
D3DFMT_L6V5U5 | 61 | 16-bit bump-map format with luminance using 6 bits for luminance, and 5 bits each for v and u.
D3DFMT_X8L8V8U8 | 62 | 32-bit bump-map format with luminance using 8 bits for each channel.
D3DFMT_A2W10V10U10 | 67 | 32-bit bump-map format using 2 bits for alpha and 10 bits each for w, v, and u.

FOURCC Formats

Data in a four-character code (FOURCC) format is compressed data.

MAKEFOURCC

A macro for generating four-character codes follows:

#define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
                ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) |   \
                ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))

Here are the defined FOURCC formats.

FOURCC flags | Value | Format
D3DFMT_MULTI2_ARGB8 | MAKEFOURCC('M','E','T','1') | MultiElement texture (not compressed)
D3DFMT_G8R8_G8B8 | MAKEFOURCC('G', 'R', 'G', 'B') | A 16-bit packed RGB format analogous to YUY2 (Y0U0, Y1V0, Y2U2, etc.). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the high 8 bits) and 8 bits of red (in the low 8 bits). The second pixel contains 8 bits of green (in the high 8 bits) and 8 bits of blue (in the low 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (G0R0, G1B0, G2R2, etc.). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have the PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_R8G8_B8G8 | MAKEFOURCC('R', 'G', 'B', 'G') | A 16-bit packed RGB format analogous to UYVY (U0Y0, V0Y1, U2Y2, etc.). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the low 8 bits) and 8 bits of red (in the high 8 bits). The second pixel contains 8 bits of green (in the low 8 bits) and 8 bits of blue (in the high 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (R0G0, B0G1, R2G2, etc.). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_DXT1 | MAKEFOURCC('D', 'X', 'T', '1') | DXT1 compression texture format
D3DFMT_DXT2 | MAKEFOURCC('D', 'X', 'T', '2') | DXT2 compression texture format
D3DFMT_DXT3 | MAKEFOURCC('D', 'X', 'T', '3') | DXT3 compression texture format
D3DFMT_DXT4 | MAKEFOURCC('D', 'X', 'T', '4') | DXT4 compression texture format
D3DFMT_DXT5 | MAKEFOURCC('D', 'X', 'T', '5') | DXT5 compression texture format
D3DFMT_UYVY | MAKEFOURCC('U', 'Y', 'V', 'Y') | UYVY format (PC98 compliance)
D3DFMT_YUY2 | MAKEFOURCC('Y', 'U', 'Y', '2') | YUY2 format (PC98 compliance)

Buffer Formats

Depth, stencil, vertex, and index buffers each have unique formats.

Buffer flags | Value | Format
D3DFMT_D16_LOCKABLE | 70 | 16-bit z-buffer bit depth.
D3DFMT_D32 | 71 | 32-bit z-buffer bit depth.
D3DFMT_D15S1 | 73 | 16-bit z-buffer bit depth where 15 bits are reserved for the depth channel and 1 bit is reserved for the stencil channel.
D3DFMT_D24S8 | 75 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel.
D3DFMT_D24X8 | 77 | 32-bit z-buffer bit depth using 24 bits for the depth channel.
D3DFMT_D24X4S4 | 79 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel.
D3DFMT_D32F_LOCKABLE | 82 | A lockable format where the depth value is represented as a standard IEEE floating-point number.
D3DFMT_D24FS8 | 83 | A non-lockable format that contains 24 bits of depth (in a 24-bit floating point format - 20e4) and 8 bits of stencil.
D3DFMT_D16 | 80 | 16-bit z-buffer bit depth.
D3DFMT_VERTEXDATA | 100 | Describes a vertex buffer surface.
D3DFMT_INDEX16 | 101 | 16-bit index buffer bit depth.
D3DFMT_INDEX32 | 102 | 32-bit index buffer bit depth.

All depth-stencil formats except D3DFMT_D16_LOCKABLE indicate no particular bit ordering per pixel, and the driver is allowed to consume more than the indicated number of bits-per-depth channel (but not stencil channel).

Floating-Point Formats

These flags are used for floating-point surface formats. These 16-bits-per-channel formats are also known as s10e5 formats.

Floating-point flags | Value | Format
D3DFMT_R16F | 111 | 16-bit float format using 16 bits for the red channel.
D3DFMT_G16R16F | 112 | 32-bit float format using 16 bits for the red channel and 16 bits for the green channel.
D3DFMT_A16B16G16R16F | 113 | 64-bit float format using 16 bits for the each channel (alpha, blue, green, red).

IEEE Formats

These flags are used for floating-point surface formats. These 32-bits-per-channel formats are also known as s23e8 formats.

Floating-point flags | Value | Format
D3DFMT_R32F | 114 | 32-bit float format using 32 bits for the red channel.
D3DFMT_G32R32F | 115 | 64-bit float format using 32 bits for the red channel and 32 bits for the green channel.
D3DFMT_A32B32G32R32F | 116 | 128-bit float format using 32 bits for the each channel (alpha, blue, green, red).

Other

This only other flag used is for undefined formats.

Other flags | Value | Format
D3DFMT_UNKNOWN | 0 | Surface format is unknown

BackBuffer or Display Formats

These formats are the only valid formats for a back buffer or a display.

Format | Back buffer | Display
A2R10G10B10 | x | x (full-screen mode only)
A8R8G8B8 | x |
X8R8G8B8 | x | x
A1R5G5B5 | x |
X1R5G5B5 | x | x
R5G6B5 | x | x

Remarks

The order of the bits are from the most significant byte first, so D3DFMT_A8L8 indicates that the high byte of this 2-byte format is alpha. D3DFMT_D16 indicates a 16-bit integer value and an application-lockable surface.

Pixel formats have been chosen to enable the expression of hardware-vendor-defined extension formats, as well as to include the well-established FOURCC method. The set of formats understood by the Microsoft® Direct3D® runtime is defined by D3DFORMAT.

Note that formats are supplied by independent hardware vendors (IHVs) and many FOURCC codes are not listed. The formats in this enumeration are unique in that they are sanctioned by the runtime, meaning that the reference rasterizer will operate on all these types. IHV-supplied formats will be supported by the individual IHVs on a card-by-card basis.

Related Topics

  • IDirect3D9::CheckDeviceFormat

© 2002 Microsoft Corporation. All rights reserved.


D3DLIGHTTYPE Enumerated Type

Defines the light type.

Syntax

typedef enum _D3DLIGHTTYPE {
    D3DLIGHT_POINT = 1,
    D3DLIGHT_SPOT = 2,
    D3DLIGHT_DIRECTIONAL = 3,
    D3DLIGHT_FORCE_DWORD = 0x7fffffff
} D3DLIGHTTYPE;

Constants

D3DLIGHT_POINT

Light is a point source. The light has a position in space and radiates light in all directions.

D3DLIGHT_SPOT

Light is a spotlight source. This light is like a point light, except that the illumination is limited to a cone. This light type has a direction and several other parameters that determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT9 structure.

D3DLIGHT_DIRECTIONAL

Light is a directional source. This is equivalent to using a point light source at an infinite distance.

D3DLIGHT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Directional lights are slightly faster than point light sources, but point lights look a little better. Spotlights offer interesting visual effects but are computationally time-consuming.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DLIGHT9

© 2002 Microsoft Corporation. All rights reserved.


D3DMATERIALCOLORSOURCE Enumerated Type

Defines the location at which a color or color component must be accessed for lighting calculations.

Syntax

typedef enum _D3DMATERIALCOLORSOURCE {
    D3DMCS_MATERIAL = 0,
    D3DMCS_COLOR1 = 1,
    D3DMCS_COLOR2 = 2,
    D3DMCS_FORCE_DWORD = 0x7fffffff
} D3DMATERIALCOLORSOURCE;

Constants

D3DMCS_MATERIAL

Use the color from the current material.

D3DMCS_COLOR1

Use the diffuse vertex color.

D3DMCS_COLOR2

Use the specular vertex color.

D3DMCS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

These flags are used to set the value of the following render states in the D3DRENDERSTATETYPE enumerated type.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DMULTISAMPLE_TYPE Enumerated Type

Defines levels of full-scene multisampling that the device can apply.

Syntax

typedef enum _D3DMULTISAMPLE_TYPE {
    D3DMULTISAMPLE_NONE = 0,
    D3DMULTISAMPLE_NONMASKABLE = 1,
    D3DMULTISAMPLE_2_SAMPLES = 2,
    D3DMULTISAMPLE_3_SAMPLES = 3,
    D3DMULTISAMPLE_4_SAMPLES = 4,
    D3DMULTISAMPLE_5_SAMPLES = 5,
    D3DMULTISAMPLE_6_SAMPLES = 6,
    D3DMULTISAMPLE_7_SAMPLES = 7,
    D3DMULTISAMPLE_8_SAMPLES = 8,
    D3DMULTISAMPLE_9_SAMPLES = 9,
    D3DMULTISAMPLE_10_SAMPLES = 10,
    D3DMULTISAMPLE_11_SAMPLES = 11,
    D3DMULTISAMPLE_12_SAMPLES = 12,
    D3DMULTISAMPLE_13_SAMPLES = 13,
    D3DMULTISAMPLE_14_SAMPLES = 14,
    D3DMULTISAMPLE_15_SAMPLES = 15,
    D3DMULTISAMPLE_16_SAMPLES = 16,
    D3DMULTISAMPLE_FORCE_DWORD = 0xffffffff
} D3DMULTISAMPLE_TYPE;

Constants

D3DMULTISAMPLE_NONE

No level of full-scene multisampling is available.

D3DMULTISAMPLE_NONMASKABLE

Enable the multisample quality value. See the remarks.

D3DMULTISAMPLE_2_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_3_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_4_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_5_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_6_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_7_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_8_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_9_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_10_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_11_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_12_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_13_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_14_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_15_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_16_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In addition to enabling full-scene multisampling at IDirect3DDevice9::Reset time, there will be render states that turn various aspects on and off at fine-grained levels.

Multisampling is valid only on a swap chain that is being created or reset with the D3DSWAPEFFECT_DISCARD swap effect.

The multisampling antialiasing value can be set with the parameters (or sub-parameters) in the following methods.

Method | Parameters | Sub-parameters
IDirect3D9::CheckDeviceMultiSampleType | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateDepthStencilSurface | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateRenderTarget | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateAdditionalSwapChain | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3D9::CreateDevice | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3DDevice9::Reset | pPresentationParameters | MultiSampleType and pQualityLevels

It is not good practice to switch from one multisample type to another to raise the quality of the antialiasing.

D3DMULTISAMPLE_NONE enables swap effects other than discarding, locking, etc.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DPRESENT_PARAMETERS, D3DSURFACE_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DPATCHEDGESTYLE Enumerated Type

Defines whether the current tessellation mode is discrete or continuous.

Syntax

typedef enum _D3DPATCHEDGESTYLE {
    D3DPATCHEDGE_DISCRETE = 0,
    D3DPATCHEDGE_CONTINUOUS = 1,
    D3DPATCHEDGE_FORCE_DWORD = 0x7fffffff
} D3DPATCHEDGESTYLE;

Constants

D3DPATCHEDGE_DISCRETE

Discrete edge style. In discrete mode, you can specify float tessellation but it will be truncated to integers.

D3DPATCHEDGE_CONTINUOUS

Continuous edge style. In continuous mode, tessellation is specified as float values which can be smoothly varied to reduce "popping" artifacts.

D3DPATCHEDGE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Note that continuous tessellation produces a completely different tessellation pattern from the discrete one for the same tessellation values (this is more apparent in wireframe mode). Thus, 4.0 continuous is not the same as 4 discrete.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DPOOL Enumerated Type

Defines the memory class that holds a resource's buffers.

Syntax

typedef enum _D3DPOOL {
    D3DPOOL_DEFAULT = 0,
    D3DPOOL_MANAGED = 1,
    D3DPOOL_SYSTEMMEM = 2,
    D3DPOOL_SCRATCH = 3,
    D3DPOOL_FORCE_DWORD = 0x7fffffff
} D3DPOOL;

Constants

D3DPOOL_DEFAULT

Resources are placed in the memory pool most appropriate for the set of usages requested for the given resource. This is usually video memory, including both local video memory and accelerated graphics port (AGP) memory. The D3DPOOL_DEFAULT pool is separate from D3DPOOL_MANAGED and D3DPOOL_SYTEMMEM, and it specifies that the resource is placed in the preferred memory for device access. Note that D3DPOOL_DEFAULT never indicates that either D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM should be chosen as the memory pool type for this resource. Textures placed in the D3DPOOL_DEFAULT pool cannot be locked unless they are dynamic textures or they are private, four-character code (FOURCC), driver formats. To access unlockable textures, you must use functions such as IDirect3DDevice9::UpdateSurface, IDirect3DDevice9::UpdateTexture, IDirect3DDevice9::GetFrontBufferData and IDirect3DDevice9::GetRenderTargetData. D3DPOOL_MANAGED is probably a better choice than D3DPOOL_DEFAULT for most applications. Note that some textures created in driver proprietary pixel formats, unknown to the Microsoft® Direct3D® runtime, can be locked. Also note that - unlike textures - swap chain back buffers, render targets, vertex buffers, and index buffers can be locked. When a device is lost, resources created using D3DPOOL_DEFAULT must be released before calling IDirect3DDevice9::Reset. For more information, see Lost Devices.

When creating resources with D3DPOOL_DEFAULT, if video card memory is already committed, managed resources will be evicted to free enough memory to satisfy the request.

D3DPOOL_MANAGED

Resources are copied automatically to device-accessible memory as needed. Managed resources are backed by system memory and do not need to be re-created when a device is lost. See Managing Resources for more information. Managed resources can be locked. Only the system-memory copy is directly modified. Direct3D copies your changes to driver-accessible memory as needed.

D3DPOOL_SYSTEMMEM

Memory that is not typically accessible by the 3-D device. Consumes system RAM but does not reduce pageable RAM. These resources do not need to be re-created when a device is lost. Resources in this pool can be locked and can be used as the source for a IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture operation to a memory resource created with D3DPOOL_DEFAULT.

D3DPOOL_SCRATCH

Resources are placed in system RAM and do not need to be re-created when a device is lost. These resources are not bound by device size or format restrictions. Because of this, these resources cannot be accessed by the Direct3D device nor set as textures or render targets. However, these resources can always be created, locked, and copied.

D3DPOOL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

All pool types are valid with all resources. This includes: vertex buffers, index buffers, textures, and surfaces.

There are some restrictions on the pool types for render targets and depth stencil surfaces.

Pool | D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED
D3DPOOL_SCRATCH
D3DPOOL_SYSTEMMEM

There are also restrictions on the pool types for dynamic and mipmap usages.

Pool | D3DUSAGE_DYNAMIC | D3DUSAGE_AUTOGENMIPMAP
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED | x
D3DPOOL_SCRATCH
D3DPOOL_SYSTEMMEM | x

For more information about usage types, see D3DUSAGE.

Pools cannot be mixed for different objects contained within one resource (mip levels in a mipmap) and, when a pool is chosen, it cannot be changed.

Applications should use D3DPOOL_MANAGED for most static resources because this saves the application from having to deal with lost devices. (Managed resources are restored by the runtime.) This is especially beneficial for UMA systems. Other dynamic resources are not a good match for D3DPOOL_MANAGED. In fact, index buffers and vertex buffers cannot be created using D3DPOOL_MANAGED together with D3DUSAGE_DYNAMIC.

For dynamic textures, it is sometimes desirable to use a pair of video memory and system memory textures, allocating the video memory using D3DPOOL_DEFAULT and the system memory using D3DPOOL_SYSTEMMEM. You can lock and modify the bits of the system memory texture using a locking method. Then you can update the video memory texture using IDirect3DDevice9::UpdateTexture.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateCubeTexture, IDirect3DDevice9::CreateIndexBuffer, IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateVolumeTexture, IDirect3DDevice9::CreateVertexBuffer, D3DINDEXBUFFER_DESC, D3DSURFACE_DESC, D3DVERTEXBUFFER_DESC, D3DVOLUME_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DPRIMITIVETYPE Enumerated Type

Defines the primitives supported by Microsoft® Direct3D®.

Syntax

typedef enum _D3DPRIMITIVETYPE {
    D3DPT_POINTLIST = 1,
    D3DPT_LINELIST = 2,
    D3DPT_LINESTRIP = 3,
    D3DPT_TRIANGLELIST = 4,
    D3DPT_TRIANGLESTRIP = 5,
    D3DPT_TRIANGLEFAN = 6,
    D3DPT_FORCE_DWORD = 0x7fffffff
} D3DPRIMITIVETYPE;

Constants

D3DPT_POINTLIST

Renders the vertices as a collection of isolated points. This value is unsupported for indexed primitives.

D3DPT_LINELIST

Renders the vertices as a list of isolated straight line segments. Calls using this primitive type fail if the count is less than two or is odd.

D3DPT_LINESTRIP

Renders the vertices as a single polyline. Calls using this primitive type fail if the count is less than two.

D3DPT_TRIANGLELIST

Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle.

Back-face culling is affected by the current winding-order render state.

D3DPT_TRIANGLESTRIP

Renders the vertices as a triangle strip. The backface-culling flag is automatically flipped on even-numbered triangles.

D3DPT_TRIANGLEFAN

Renders the vertices as a triangle fan.

D3DPT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Using Triangle Strips or Triangle Fans is often more efficient than using triangle lists because fewer vertices are duplicated.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP

© 2002 Microsoft Corporation. All rights reserved.


D3DQUERYTYPE Enumerated Type

Identifies the query type.

Syntax

typedef enum _D3DQUERYTYPE {
    D3DQUERYTYPE_VCACHE = 4,
    D3DQUERYTYPE_RESOURCEMANAGER = 5,
    D3DQUERYTYPE_VERTEXSTATS = 6,
    D3DQUERYTYPE_EVENT = 8,
    D3DQUERYTYPE_OCCLUSION = 9
} D3DQUERYTYPE;

Constants

D3DQUERYTYPE_VCACHE

Query for driver hints about data layout for vertex caching.

D3DQUERYTYPE_RESOURCEMANAGER

Query the resource manager.

D3DQUERYTYPE_VERTEXSTATS

Query vertex statistics.

D3DQUERYTYPE_EVENT

Query for any and all asynchronous events that have been issued from application programming interface (API) calls.

D3DQUERYTYPE_OCCLUSION

An occlusion query returns the number of pixels that pass z-testing. These pixels are for primitives drawn between the issue of D3DISSUE_BEGIN and D3DISSUE_END. This enables an application to check the occlusion result against 0. Zero is "fully occluded," which means the pixels are not visible from the current camera position.

Remarks

QuertyType | Valid issue flag | GetData buffer | Runtime | Implicit beginning of query
D3DQUERYTYPE_VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | CreateDevice()
D3DQUERYTYPE_RESOURCEMANAGER | D3DISSUE_END | D3DDEVINFO_RESOURCEMANAGER | Debug only | Present()
D3DQUERYTYPE_VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | Present()
D3DQUERYTYPE_EVENT | D3DISSUE_END | BOOL | Retail/Debug | CreateDevice()
D3DQUERYTYPE_OCCLUSION | D3DISSUE_BEGIN, D3DISSUE_END | DWORD | Retail/Debug | N/A

For a D3DQUERYTYPE_RESOURCEMANAGER query, the device behavior flags must include D3DCREATE_DISABLE_DRIVER_MANAGEMENT.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateQuery, D3DISSUE_BEGIN, D3DISSUE_END

© 2002 Microsoft Corporation. All rights reserved.


D3DRENDERSTATETYPE Enumerated Type

Defines device render states.

Syntax

typedef enum _D3DRENDERSTATETYPE {
    D3DRS_ZENABLE = 7,
    D3DRS_FILLMODE = 8,
    D3DRS_SHADEMODE = 9,
    D3DRS_ZWRITEENABLE = 14,
    D3DRS_ALPHATESTENABLE = 15,
    D3DRS_LASTPIXEL = 16,
    D3DRS_SRCBLEND = 19,
    D3DRS_DESTBLEND = 20,
    D3DRS_CULLMODE = 22,
    D3DRS_ZFUNC = 23,
    D3DRS_ALPHAREF = 24,
    D3DRS_ALPHAFUNC = 25,
    D3DRS_DITHERENABLE = 26,
    D3DRS_ALPHABLENDENABLE = 27,
    D3DRS_FOGENABLE = 28,
    D3DRS_SPECULARENABLE = 29,
    D3DRS_FOGCOLOR = 34,
    D3DRS_FOGTABLEMODE = 35,
    D3DRS_FOGSTART = 36,
    D3DRS_FOGEND = 37,
    D3DRS_FOGDENSITY = 38,
    D3DRS_RANGEFOGENABLE = 48,
    D3DRS_STENCILENABLE = 52,
    D3DRS_STENCILFAIL = 53,
    D3DRS_STENCILZFAIL = 54,
    D3DRS_STENCILPASS = 55,
    D3DRS_STENCILFUNC = 56,
    D3DRS_STENCILREF = 57,
    D3DRS_STENCILMASK = 58,
    D3DRS_STENCILWRITEMASK = 59,
    D3DRS_TEXTUREFACTOR = 60,
    D3DRS_WRAP0 = 128,
    D3DRS_WRAP1 = 129,
    D3DRS_WRAP2 = 130,
    D3DRS_WRAP3 = 131,
    D3DRS_WRAP4 = 132,
    D3DRS_WRAP5 = 133,
    D3DRS_WRAP6 = 134,
    D3DRS_WRAP7 = 135,
    D3DRS_CLIPPING = 136,
    D3DRS_LIGHTING = 137,
    D3DRS_AMBIENT = 139,
    D3DRS_FOGVERTEXMODE = 140,
    D3DRS_COLORVERTEX = 141,
    D3DRS_LOCALVIEWER = 142,
    D3DRS_NORMALIZENORMALS = 143,
    D3DRS_DIFFUSEMATERIALSOURCE = 145,
    D3DRS_SPECULARMATERIALSOURCE = 146,
    D3DRS_AMBIENTMATERIALSOURCE = 147,
    D3DRS_EMISSIVEMATERIALSOURCE = 148,
    D3DRS_VERTEXBLEND = 151,
    D3DRS_CLIPPLANEENABLE = 152,
    D3DRS_POINTSIZE = 154,
    D3DRS_POINTSIZE_MIN = 155,
    D3DRS_POINTSPRITEENABLE = 156,
    D3DRS_POINTSCALEENABLE = 157,
    D3DRS_POINTSCALE_A = 158,
    D3DRS_POINTSCALE_B = 159,
    D3DRS_POINTSCALE_C = 160,
    D3DRS_MULTISAMPLEANTIALIAS = 161,
    D3DRS_MULTISAMPLEMASK = 162,
    D3DRS_PATCHEDGESTYLE = 163,
    D3DRS_DEBUGMONITORTOKEN = 165,
    D3DRS_POINTSIZE_MAX = 166,
    D3DRS_INDEXEDVERTEXBLENDENABLE = 167,
    D3DRS_COLORWRITEENABLE = 168,
    D3DRS_TWEENFACTOR = 170,
    D3DRS_BLENDOP = 171,
    D3DRS_POSITIONDEGREE = 172,
    D3DRS_NORMALDEGREE = 173,
    D3DRS_SCISSORTESTENABLE = 174,
    D3DRS_SLOPESCALEDEPTHBIAS = 175,
    D3DRS_ANTIALIASEDLINEENABLE = 176,
    D3DRS_MINTESSELLATIONLEVEL = 178,
    D3DRS_MAXTESSELLATIONLEVEL = 179,
    D3DRS_ADAPTIVETESS_X = 180,
    D3DRS_ADAPTIVETESS_Y = 181,
    D3DRS_ADAPTIVETESS_Z = 182,
    D3DRS_ADAPTIVETESS_W = 183,
    D3DRS_ENABLEADAPTIVETESSELATION = 184,
    D3DRS_TWOSIDEDSTENCILMODE = 185,
    D3DRS_CCW_STENCILFAIL = 186,
    D3DRS_CCW_STENCILZFAIL = 187,
    D3DRS_CCW_STENCILPASS = 188,
    D3DRS_CCW_STENCILFUNC = 189,
    D3DRS_COLORWRITEENABLE1 = 190,
    D3DRS_COLORWRITEENABLE2 = 191,
    D3DRS_COLORWRITEENABLE3 = 192,
    D3DRS_BLENDFACTOR = 193,
    D3DRS_SRGBWRITEENABLE = 194,
    D3DRS_DEPTHBIAS = 195,
    D3DRS_WRAP8 = 198,
    D3DRS_WRAP9 = 199,
    D3DRS_WRAP10 = 200,
    D3DRS_WRAP11 = 201,
    D3DRS_WRAP12 = 202,
    D3DRS_WRAP13 = 203,
    D3DRS_WRAP14 = 204,
    D3DRS_WRAP15 = 205,
    D3DRS_SEPARATEALPHABLENDENABLE = 206,
    D3DRS_SRCBLENDALPHA = 207,
    D3DRS_DESTBLENDALPHA = 208,
    D3DRS_BLENDOPALPHA = 209,
    D3DRS_FORCE_DWORD = 0x7fffffff
} D3DRENDERSTATETYPE;

Constants

D3DRS_ZENABLE

Depth-buffering state as one member of the D3DZBUFFERTYPE enumerated type. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth stencil was created along with the swap chain by setting the EnableAutoDepthStencil member of the D3DPRESENT_PARAMETERS structure to TRUE, and D3DZB_FALSE otherwise.

D3DRS_FILLMODE

One or more members of the D3DFILLMODE enumerated type. The default value is D3DFILL_SOLID.

D3DRS_SHADEMODE

One or more members of the D3DSHADEMODE enumerated type. The default value is D3DSHADE_GOURAUD.

D3DRS_ZWRITEENABLE

TRUE to enable the application to write to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRS_ZFUNC, assuming that depth buffering is taking place, but depth values are not written to the buffer.

D3DRS_ALPHATESTENABLE

TRUE to enable per pixel alpha testing. If the test passes, the pixel is processed by the frame buffer. Otherwise, all frame-buffer processing is skipped for the pixel.

The test is done by comparing the incoming alpha value with the reference alpha value, using the comparison function provided by the D3DRS_ALPHAFUNC render state. The reference alpha value is determined by the value set for D3DRS_ALPHAREF. For more information, see Alpha Testing State.

The default value of this parameter is FALSE.

D3DRS_LASTPIXEL

The default value is TRUE, which enables drawing of the last pixel in a line. To prevent drawing of the last pixel, set this value to FALSE. For more information, see Outline and Fill State.

D3DRS_SRCBLEND

One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ONE.

D3DRS_DESTBLEND

One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ZERO.

D3DRS_CULLMODE

Specifies how back-facing triangles are culled, if at all. This can be set to one member of the D3DCULL enumerated type. The default value is D3DCULL_CCW.

D3DRS_ZFUNC

One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state is TRUE.

Software rasterizers and many hardware accelerators work faster if the depth test fails, because there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRS_ALPHAREF

Value that specifies a reference alpha value against which pixels are tested when alpha testing is enabled. This is an 8-bit value placed in the low 8 bits of the DWORD render-state value. Values can range from 0x00000000 through 0x000000FF. The default value is 0.

D3DRS_ALPHAFUNC

One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.

D3DRS_DITHERENABLE

TRUE to enable dithering. The default value is FALSE.

D3DRS_ALPHABLENDENABLE

TRUE to enable alpha-blended transparency. The default value is FALSE.

The type of alpha blending is determined by the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states.

D3DRS_FOGENABLE

TRUE to enable fog blending. The default value is FALSE. For more information about using fog blending, see Fog.

D3DRS_SPECULARENABLE

TRUE to enable specular highlights. The default value is FALSE.

Specular highlights are calculated as though every vertex in the object being lit is at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large. In other cases the results as undefined.

When this member is set to TRUE, the specular color is added to the base color after the texture cascade but before alpha blending.

D3DRS_FOGCOLOR

Value whose type is D3DCOLOR. The default value is 0. For more information about fog color, see Fog Color.

D3DRS_FOGTABLEMODE

The fog formula to be used for pixel fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information about pixel fog, see Pixel Fog.

D3DRS_FOGSTART

Depth at which pixel or vertex fog effects begin for linear fog mode. The default value is 0.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and world-world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for the this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_FOGSTART, *((DWORD*) (&fFogStart)));

D3DRS_FOGEND

Depth at which pixel or vertex fog effects end for linear fog mode. The default value is 1.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and in world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_FOGEND, *((DWORD*) (&fFogEnd)));

D3DRS_FOGDENSITY

Fog density for pixel or vertex fog used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 through 1.0. The default value is 1.0. For more information, see Fog Parameters.

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_FOGDENSITY, *((DWORD*) (&fFogDensity)));

D3DRS_RANGEFOGENABLE

TRUE to enable range-based vertex fog. The default value is FALSE, in which case the system uses depth-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is time-consuming to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the fogginess of peripheral objects change as the viewer's eye moves—in this case, the depth changes and the range remains constant.

Because no hardware currently supports per-pixel range-based fog, range correction is offered only for vertex fog.

For more information, see Vertex Fog.

D3DRS_STENCILENABLE

TRUE to enable stenciling, or FALSE to disable stenciling. The default value is FALSE.

For more information, see Stencil Buffer Techniques.

D3DRS_STENCILFAIL

Stencil operation to perform if the stencil test fails. This can be one constants in D3DSTENCILCAPS. The default value is D3DSTENCILOP_KEEP.

For more information, see Stencil Buffer Techniques.

D3DRS_STENCILZFAIL

Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. This can be one constants in D3DSTENCILCAPS. The default value is D3DSTENCILOP_KEEP.

D3DRS_STENCILPASS

Stencil operation to perform if both the stencil and the depth (z) tests pass. This can be one constants in D3DSTENCILCAPS. The default value is D3DSTENCILOP_KEEP.

D3DRS_STENCILFUNC

Comparison function for the stencil test. This can be one member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison applies only to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRS_STENCILMASK render state). If TRUE, the stencil test passes.

D3DRS_STENCILREF

An int reference value for the stencil test. The default value is 0.

D3DRS_STENCILMASK

Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.

D3DRS_STENCILWRITEMASK

Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.

D3DRS_TEXTUREFACTOR

Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The associated value is a D3DCOLOR variable. The default value is opaque white (0xFFFFFFFF).

D3DRS_WRAP0

Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for this render state can be any combination of the D3DWRAPCOORD_0 (or D3DWRAP_U), D3DWRAPCOORD_1 (or D3DWRAP_V), D3DWRAPCOORD_2 (or D3DWRAP_W), and D3DWRAPCOORD_3 flags. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions, sometimes referred to as the s, t, r, and q directions, for a given texture. The default value for this render state is 0 (wrapping disabled in all directions).

D3DRS_WRAP1

See D3DRS_WRAP0.

D3DRS_WRAP2

See D3DRS_WRAP0.

D3DRS_WRAP3

See D3DRS_WRAP0.

D3DRS_WRAP4

See D3DRS_WRAP0.

D3DRS_WRAP5

See D3DRS_WRAP0.

D3DRS_WRAP6

See D3DRS_WRAP0.

D3DRS_WRAP7

See D3DRS_WRAP0.

D3DRS_CLIPPING

TRUE to enable primitive clipping by Microsoft® Direct3D®, or FALSE to disable it. The default value is TRUE.

D3DRS_LIGHTING

TRUE to enable Direct3D lighting, or FALSE to disable it. The default value is TRUE. Only vertices that include a vertex normal are properly lit; vertices that do not contain a normal employ a dot product of 0 in all lighting calculations.

D3DRS_AMBIENT

Ambient light color. This value is of type D3DCOLOR. The default value is 0.

D3DRS_FOGVERTEXMODE

Fog formula to be used for vertex fog. Set to one member of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE.

D3DRS_COLORVERTEX

TRUE to enable per-vertex color or FALSE to disable it. The default value is TRUE. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations.

For more information, see the following render states.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

D3DRS_LOCALVIEWER

TRUE to enable camera-relative specular highlights, or FALSE to use orthogonal specular highlights. The default value is TRUE. Applications that use orthogonal projection should specify false.

D3DRS_NORMALIZENORMALS

TRUE to enable automatic normalization of vertex normals, or FALSE to disable it. The default value is FALSE. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally time-consuming.

D3DRS_DIFFUSEMATERIALSOURCE

Diffuse color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRS_COLORVERTEX render state is set to TRUE.

D3DRS_SPECULARMATERIALSOURCE

Specular color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.

D3DRS_AMBIENTMATERIALSOURCE

Ambient color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.

D3DRS_EMISSIVEMATERIALSOURCE

Emissive color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.

D3DRS_VERTEXBLEND

Number of matrices to use to perform geometry blending, if any. Valid values are members of the D3DVERTEXBLENDFLAGS enumerated type. The default value is D3DVBF_DISABLE.

D3DRS_CLIPPLANEENABLE

Enables or disables user-defined clipping planes. Valid values are any DWORD in which the status of each bit (set or not set) toggles the activation state of a corresponding user-defined clipping plane. The least significant bit (bit 0) controls the first clipping plane at index 0, and subsequent bits control the activation of clipping planes at higher indexes. If a bit is set, the system applies the appropriate clipping plane during scene rendering. The default value is 0.

The D3DCLIPPLANEn macros are defined to provide a convenient way to enable clipping planes.

D3DRS_POINTSIZE

A float value that specifies the size to use for point size computation in cases where point size is not specified for each vertex. This value is not used when the vertex contains point size. This value is in screen space units if D3DRS_POINTSCALEENABLE is FALSE; otherwise this value is in world space units. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_POINTSIZE, *((DWORD*)&PointSize));

D3DRS_POINTSIZE_MIN

A float value that specifies the minimum size of point primitives. Point primitives are clamped to this size during rendering. Setting this to values smaller than 1.0 results in points dropping out when the point does not cover a pixel center and antialiasing is disabled or being rendered with reduced intensity when antialiasing is enabled. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_POINTSIZE_MIN, *((DWORD*)&PointSizeMin));

D3DRS_POINTSPRITEENABLE

BOOL value. When TRUE, texture coordinates of point primitives are set so that full textures are mapped on each point. When FALSE, the vertex texture coordinates are used for the entire point. The default value is FALSE. You can achieve Microsoft DirectX® 7.0 style single-pixel points by setting D3DRS_POINTSCALEENABLE to FALSE and D3DRS_POINTSIZE to 1.0, which are the default values.

D3DRS_POINTSCALEENABLE

BOOL value that controls computation of size for point primitives. When TRUE, the point size is interpreted as a camera space value and is scaled by the distance function and the frustum to viewport y-axis scaling to compute the final screen-space point size. When FALSE, the point size is interpreted as screen space and used directly. The default value is FALSE.

D3DRS_POINTSCALE_A

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_POINTSCALE_A, *((DWORD*)&PointScaleA));

D3DRS_POINTSCALE_B

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_POINTSCALE_B, *((DWORD*)&PointScaleB));

D3DRS_POINTSCALE_C

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_POINTSCALE_C, *((DWORD*)&PointScaleC));

D3DRS_MULTISAMPLEANTIALIAS

BOOL value that determines how individual samples are computed when using a multisample render target buffer. When set to TRUE, the multiple samples are computed so that full-scene antialiasing is performed by sampling at different sample positions for each multiple sample. When set to FALSE, the multiple samples are all written with the same sample value, sampled at the pixel center, which allows non-antialiased rendering to a multisample buffer. This render state has no effect when rendering to a single sample buffer. The default value is TRUE.

D3DRS_MULTISAMPLEMASK

Each bit in this mask, starting at the least significant bit (LSB), controls modification of one of the samples in a multisample render target. Thus, for an 8-sample render target, the low byte contains the eight write enables for each of the eight samples. This render state has no effect when rendering to a single sample buffer. The default value is 0xFFFFFFFF.

This render state enables use of a multisample buffer as an accumulation buffer, doing multipass rendering of geometry where each pass updates a subset of samples.

This render state is not supported if the D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE member of the D3DCAPS9 structure is enabled.

If there are n multisamples and k enabled samples, the resulting intensity of the rendered image should be k/n. Each component RGB of every pixel is factored by k/n.

D3DRS_PATCHEDGESTYLE

Sets whether patch edges will use float style tessellation. Possible values are defined by the D3DPATCHEDGESTYLE enumerated type. The default value is D3DPATCHEDGE_DISCRETE.

D3DRS_DEBUGMONITORTOKEN

Set only for debugging the monitor. Possible values are defined by the D3DDEBUGMONITORTOKENS enumerated type. Note that if D3DRS_DEBUGMONITORTOKEN is set, the call is treated as passing a token to the debug monitor. For example, if—after passing D3DDMT_ENABLE or D3DDMT_DISABLE to D3DRS_DEBUGMONITORTOKEN—other token values are passed in, the state (enabled or disabled) of the debug monitor will still persist.

This state is only useful for debug builds. The debug monitor defaults to D3DDMT_ENABLE.

D3DRS_POINTSIZE_MAX

A float value that specifies the maximum size to which point sprites will be clamped. The value must be less than or equal to the MaxPointSize member of D3DCAPS9 and greater than or equal to D3DRS_POINTSIZE_MIN. The default value is 64.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_PONTSIZE_MAX, *((DWORD*)&PointSizeMax));

D3DRS_INDEXEDVERTEXBLENDENABLE

BOOL value that enables or disables indexed vertex blending. The default value is FALSE. When set to TRUE, indexed vertex blending is enabled. When set to FALSE, indexed vertex blending is disabled. If this render state is enabled, the user must pass matrix indices as a packed DWORDwith every vertex. When the render state is disabled and vertex blending is enabled through the D3DRS_VERTEXBLEND state, it is equivalent to having matrix indices 0, 1, 2, 3 in every vertex.

D3DRS_COLORWRITEENABLE

UINT value that enables a per-channel write for the render target color buffer. A set bit results in the color channel being updated during 3-D rendering. A clear bit results in the color channel being unaffected. This functionality is available if the D3DPMISCCAPS_COLORWRITEENABLE capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. This render state does not affect the clear operation. The default value is 0x0000000F.

Valid values for this render state can be any combination of the D3DCOLORWRITEENABLE_ALPHA, D3DCOLORWRITEENABLE_BLUE, D3DCOLORWRITEENABLE_GREEN, or D3DCOLORWRITEENABLE_RED flags.

D3DRS_TWEENFACTOR

A float value that controls the tween factor. The default value is 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_TWEENFACTOR, *((DWORD*)&TweenFactor));

D3DRS_BLENDOP

Value used to select the arithmetic operation applied when the alpha blending render state, D3DRS_ALPHABLENDENABLE, is set to TRUE. Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed.

D3DRS_POSITIONDEGREE

N-patch position interpolation degree. The values can be D3DDEGREE_CUBIC (default) or D3DDEGREE_LINEAR. For more information, see D3DDEGREETYPE.

D3DRS_NORMALDEGREE

N-patch normal interpolation degree. The values can be D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC. For more information, see D3DDEGREETYPE.

D3DRS_SCISSORTESTENABLE

TRUE to enable scissor testing and FALSE to disable it. The default value is FALSE.

D3DRS_SLOPESCALEDEPTHBIAS

Used to determine how much bias can be applied to co-planar primitives to reduce z fighting. The default value is 0.

bias = (max * D3DRS_SLOPESCALEDEPTHBIAS) + D3DRS_DEPTHBIAS.

where max is the maximum depth slope of the triangle being rendered.

D3DRS_ANTIALIASEDLINEENABLE

TRUE to enable line antialiasing, FALSE to disable line antialiasing. The default value is FALSE.

When rendering to a multisample render target, D3DRS_ANTIALIASEDLINEENABLE is ignored and all lines are rendered aliased. Use ID3DXLine for antialiased line rendering in a multisample render target.

D3DRS_MINTESSELLATIONLEVEL

Minimum tessellation level. The default value is 1.0f. See Tessellation.

D3DRS_MAXTESSELLATIONLEVEL

Maximum tessellation level. The default value is 1.0f. See Tessellation.

D3DRS_ADAPTIVETESS_X

Amount to adaptively tessellate, in the x-direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_Y

Amount to adaptively tessellate, in the y direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_Z

Amount to adaptively tessellate, in the z direction. Default value is 1.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_W

Amount to adaptively tessellate, in the w direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ENABLEADAPTIVETESSELATION

TRUE to enable adaptive tessellation, FALSE to disable it. The default value is FALSE. See Adaptive Tessellation.

D3DRS_TWOSIDEDSTENCILMODE

TRUE enables two-sided stenciling, FALSE disables it. The default value is FALSE. The application should set D3DRS_CULLMODE to D3DCULL_NONE to enable two-sided stencil mode. If the triangle winding order is clockwise, the D3DRS_STENCIL* operations will be used. If the winding order is counterclocwise, the D3DRS_CCW_STENCIL* operations will be used.

To see if two-sided stencil is supported, check the StencilCaps member of D3DCAPS9 for D3DSTENCILCAPS_TWOSIDED. See also D3DSTENCILCAPS.

D3DRS_CCW_STENCILFAIL

Stencil operation to perform if CCW stencil test fails. The default value is 0x00000001.

D3DRS_CCW_STENCILZFAIL

Stencil operation to perform if CCW stencil test passes and z-test fails. The default value is 0x00000001.

D3DRS_CCW_STENCILPASS

Stencil operation to perform if both CCW stencil and z-tests pass. The default value is 0x00000001.

D3DRS_CCW_STENCILFUNC

The comparison function. CCW stencil test passes if ((ref & mask) stencil function (stencil & mask)) is true. The default value is 0x00000008.

D3DRS_COLORWRITEENABLE1

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_COLORWRITEENABLE2

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_COLORWRITEENABLE3

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_BLENDFACTOR

D3DCOLOR used for a constant blend-factor during alpha blending. This functionality is available if the D3DPBLENDCAPS_BLENDFACTOR capabilities bit is set in the SrcBlendCaps member of D3DCAPS9 or the DestBlendCaps member of D3DCAPS9. See D3DRENDERSTATETYPE. The default value is 0xffffffff.

D3DRS_SRGBWRITEENABLE

Enable render-target writes to be gamma corrected to sRGB. The format must expose D3DUSAGE_SRGBWRITE. The default value is 0.

D3DRS_DEPTHBIAS

A floating-point value that is used for comparison of depth values. See Depth Bias. The default value is 0.

D3DRS_WRAP8

See D3DRS_WRAP0.

D3DRS_WRAP9

See D3DRS_WRAP0.

D3DRS_WRAP10

See D3DRS_WRAP0.

D3DRS_WRAP11

See D3DRS_WRAP0.

D3DRS_WRAP12

See D3DRS_WRAP0.

D3DRS_WRAP13

See D3DRS_WRAP0.

D3DRS_WRAP14

See D3DRS_WRAP0.

D3DRS_WRAP15

See D3DRS_WRAP0.

D3DRS_SEPARATEALPHABLENDENABLE

TRUE enables the separate blend mode for the alpha channel. The default value is FALSE.

When set to false, the render target blending factors and operations applied to alpha are forced to be the same as those defined for color. This mode is effectively hardwired to false on implementations that don't set the cap D3DPMISCCAPS_SEPARATEALPHABLEND. See D3DPMISCCAPS.

The type of separate alpha blending is determined by the D3DRS_SRCBLENDALPHA and D3DRS_DESTBLENDALPHA render states.

D3DRS_SRCBLENDALPHA

One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHAENABLE is true. The default value is D3DBLEND_ONE.

D3DRS_DESTBLENDALPHA

One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHAENABLE is true. The default value is D3DBLEND_ZERO.

D3DRS_BLENDOPALPHA

Value used to select the arithmetic operation applied to separate alpha blending when the render state, D3DRS_SEPARATEALPHABLENDENABLE, is set to TRUE.

Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed. See D3DPMISCCAPS.

D3DRS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping, based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRS_WRAP n state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAP n value that corresponds to that index, as shown in the following example.

// Enable U/V wrapping for textures that use the texture
//   coordinate set at the index within the dwIndex variable.

HRESULT hr = pd3dDevice->SetRenderState(
    dwIndex + D3DRENDERSTATE_WRAPBIAS,
    D3DWRAPCOORD_0 | D3DWRAPCOORD_1);

// If dwIndex is 3, the value that results from
//   the addition equals D3DRS_WRAP3 (131).

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetRenderState

© 2002 Microsoft Corporation. All rights reserved.


D3DRESOURCETYPE Enumerated Type

Defines resource types.

Syntax

typedef enum _D3DRESOURCETYPE {
    D3DRTYPE_SURFACE = 1,
    D3DRTYPE_VOLUME = 2,
    D3DRTYPE_TEXTURE = 3,
    D3DRTYPE_VOLUMETEXTURE = 4,
    D3DRTYPE_CUBETEXTURE = 5,
    D3DRTYPE_VERTEXBUFFER = 6,
    D3DRTYPE_INDEXBUFFER = 7,
    D3DRTYPE_FORCE_DWORD = 0x7fffffff
} D3DRESOURCETYPE;

Constants

D3DRTYPE_SURFACE

Surface resource.

D3DRTYPE_VOLUME

Volume resource.

D3DRTYPE_TEXTURE

Texture resource.

D3DRTYPE_VOLUMETEXTURE

Volume texture resource.

D3DRTYPE_CUBETEXTURE

Cube texture resource.

D3DRTYPE_VERTEXBUFFER

Vertex buffer resource.

D3DRTYPE_INDEXBUFFER

Index buffer resource.

D3DRTYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DResource9::GetType

© 2002 Microsoft Corporation. All rights reserved.


D3DSAMPLER_TEXTURE_TYPE Enumerated Type

Defines the sampler texture types for vertex shaders.

Syntax

typedef enum _D3DSAMPLER_TEXTURE_TYPE {
    D3DSTT_UNKNOWN,
    D3DSTT_1D,
    D3DSTT_2D,
    D3DSTT_CUBE,
    D3DSTT_VOLUME,
    D3DSTT_FORCE_DWORD
} D3DSAMPLER_TEXTURE_TYPE;

Constants

D3DSTT_UNKNOWN

Uninitialized value. The value of this element is D3DSP_TEXTURETYPE_SHIFT.

D3DSTT_1D

Declaring a 1-D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 2.

D3DSTT_2D

Declaring a 2-D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 4.

D3DSTT_CUBE

Declaring a cube texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 8.

D3DSTT_VOLUME

Declaring a volume texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 16.

D3DSTT_FORCE_DWORD

Force 32-bit size enum. The value of this element is 0x7fffffff.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DSAMPLERSTATETYPE Enumerated Type

Defines the sampler state types.

Syntax

typedef enum _D3DSAMPLERSTATETYPE {
    D3DSAMP_ADDRESSU = 1,
    D3DSAMP_ADDRESSV = 2,
    D3DSAMP_ADDRESSW = 3,
    D3DSAMP_BORDERCOLOR = 4,
    D3DSAMP_MAGFILTER = 5,
    D3DSAMP_MINFILTER = 6,
    D3DSAMP_MIPFILTER = 7,
    D3DSAMP_MIPMAPLODBIAS = 8,
    D3DSAMP_MAXMIPLEVEL = 9,
    D3DSAMP_MAXANISOTROPY = 10,
    D3DSAMP_SRGBTEXTURE = 11,
    D3DSAMP_ELEMENTINDEX = 12,
    D3DSAMP_DMAPOFFSET = 13,
    D3DSAMP_FORCE_DWORD = 0x7fffffff
} D3DSAMPLERSTATETYPE;

Constants

D3DSAMP_ADDRESSU

Texture-address mode for the u coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_ADDRESSV

Texture-address mode for the v coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_ADDRESSW

Texture-address mode for the w coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_BORDERCOLOR

Border color or type D3DCOLOR. The default color is 0x00000000.

D3DSAMP_MAGFILTER

Magnification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.

D3DSAMP_MINFILTER

Minification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.

D3DSAMP_MIPFILTER

Mipmap filter to use during minification. See D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_NONE.

D3DSAMP_MIPMAPLODBIAS

Mipmap level of detail (LOD) bias. The default value is zero.

D3DSAMP_MAXMIPLEVEL

LOD index of largest map to use. Values range from 0 to (n-1) where 0 is the largest. The default value is zero.

D3DSAMP_MAXANISOTROPY

DWORD maximum anisotropy. The default value is 1.

D3DSAMP_SRGBTEXTURE

Gamma correction value. The default value is 0, which means gamma is 1.0 and no correction is required. Otherwise, this value means that the sampler should assume gamma of 2.2 on the content and convert it to linear (gamma 1.0) before presenting it to the pixel shader.

D3DSAMP_ELEMENTINDEX

When a multielement texture is assigned to the sampler, this indicates which element index to use. The default value is 0.

D3DSAMP_DMAPOFFSET

Vertex offset in the presampled displacement map. This is a constant used by the tessellator, its value is 256.

D3DSAMP_FORCE_DWORD

This value forces a 32-bit enumeration.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DSHADEMODE Enumerated Type

Defines constants that describe the supported shading modes.

Syntax

typedef enum _D3DSHADEMODE {
    D3DSHADE_FLAT = 1,
    D3DSHADE_GOURAUD = 2,
    D3DSHADE_PHONG = 3,
    D3DSHADE_FORCE_DWORD = 0x7fffffff
} D3DSHADEMODE;

Constants

D3DSHADE_FLAT

Flat shading mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they are not interpolated. The specular alpha is interpolated. See Remarks.

D3DSHADE_GOURAUD

Gouraud shading mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.

D3DSHADE_PHONG

Not supported.

D3DSHADE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The first vertex of a triangle for flat shading mode is defined in the following manner.

  • For a triangle list, the first vertex of the triangle i is i * 3.
  • For a triangle strip, the first vertex of the triangle i is vertex i.
  • For a triangle fan, the first vertex of the triangle i is vertex i + 1.

The members of this enumerated type define the vales for the D3DRS_SHADEMODE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DSTATEBLOCKTYPE Enumerated Type

Defines logical groups of device states.

Syntax

typedef enum _D3DSTATEBLOCKTYPE {
    D3DSBT_ALL = 1,
    D3DSBT_PIXELSTATE = 2,
    D3DSBT_VERTEXSTATE = 3,
    D3DSBT_FORCE_DWORD = 0xffffffff
} D3DSTATEBLOCKTYPE;

Constants

D3DSBT_ALL

Capture all of the current device state. This is all of the current vertex and pixel state as shown below.

D3DSBT_PIXELSTATE

Capture the current pixel-related device states including:

  • Pixel Pipe Render States
  • Pixel Shader States
  • Pixel Shader Constant States
  • Sampler States
  • Sampler Stage States
  • Texture States
  • Texture Stage States

D3DSBT_VERTEXSTATE

Capture the current vertex-related device states including:

  • Light States
  • Vertex Pipe Render States
  • Vertex Shader States
  • Vertex Shader Constant States
  • Transform States

D3DSBT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values identify different logical groups of device states, though some states are common to both groups. The union of D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE is not equal to D3DSBT_ALL. The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values enable the capture of these frequently modified states between calls to IDirect3DDevice9::DrawPrimitive without incurring the performance penalty of capturing the entire state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateStateBlock

© 2002 Microsoft Corporation. All rights reserved.


D3DSWAPEFFECT Enumerated Type

Defines swap effects.

Syntax

typedef enum _D3DSWAPEFFECT {
    D3DSWAPEFFECT_DISCARD = 1,
    D3DSWAPEFFECT_FLIP = 2,
    D3DSWAPEFFECT_COPY = 3,
    D3DSWAPEFFECT_FORCE_DWORD = 0xFFFFFFFF
} D3DSWAPEFFECT;

Constants

D3DSWAPEFFECT_DISCARD

When a swap chain is created with a swap effect of D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_COPY, the runtime will guarantee that an IDirect3DDevice9::Present operation will not affect the content of any of the back buffers. Unfortunately, meeting this guarantee can involve substantial video memory or processing overheads, especially when implementing flip semantics for a windowed swap chain or copy semantics for a full-screen swap chain. An application may use the D3DSWAPEFFECT_DISCARD swap effect to avoid these overheads and to enable the display driver to select the most efficient presentation technique for the swap chain. This is also the only swap effect that may be used when specifying a value other than D3DMULTISAMPLE_NONE for the MultiSampleType member of D3DPRESENT_PARAMETERS.

Like a swap chain that uses D3DSWAPEFFECT_FLIP, a swap chain that uses D3DSWAPEFFECT_DISCARD might include more than one back buffer, any of which may be accessed using IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer. The swap chain is best envisaged as a queue in which 0 always indexes the back buffer that will be displayed by the next Present operation and from which buffers are discarded when they have been displayed.

An application that uses this swap effect cannot make any assumptions about the contents of a discarded back buffer and should therefore update an entire back buffer before invoking a Present operation that would display it. Although this is not enforced, the debug version of the runtime will overwrite the contents of discarded back buffers with random data to enable developers to verify that their applications are updating the entire back buffer surfaces correctly.

D3DSWAPEFFECT_FLIP

The swap chain might include multiple back buffers and is best envisaged as a circular queue that includes the front buffer. Within this queue, the back buffers are always numbered sequentially from 0 to (n - 1), where n is the number of back buffers, so that 0 denotes the least recently presented buffer. When Present is invoked, the queue is "rotated" so that the front buffer becomes back buffer (n - 1), while the back buffer 0 becomes the new front buffer.

D3DSWAPEFFECT_COPY

This swap effect may be specified only for a swap chain comprising a single back buffer. Whether the swap chain is windowed or full-screen, the runtime will guarantee the semantics implied by a copy-based Present operation, namely that the operation leaves the content of the back buffer unchanged, instead of replacing it with the content of the front buffer as a flip-based Present operation would.

For a full-screen swap chain, the runtime uses a combination of flip operations and copy operations, supported if necessary by hidden back buffers, to accomplish the Present operation. Accordingly, the presentation is synchronized with the display adapter's vertical retrace and its rate is constrained by the chosen presentation interval. A swap chain specified with the D3DPRESENT_INTERVAL_IMMEDIATE flag is the only exception. (Refer to the description of the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure.) In this case, a Present operation copies the back buffer content directly to the front buffer without waiting for the vertical retrace.

D3DSWAPEFFECT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The state of the back buffer after a call to Present is well-defined by each of these swap effects, and whether the Microsoft® Direct3D® device was created with a full-screen swap chain or a windowed swap chain has no effect on this state. In particular, the D3DSWAPEFFECT_FLIP swap effect operates the same whether windowed or full-screen, and the Direct3D runtime guarantees this by creating extra buffers. As a result, it is recommended that applications use D3DSWAPEFFECT_DISCARD whenever possible to avoid any such penalties. This is because this swap effect will always be the most efficient in terms of memory consumption and performance.

Applications that use D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD should not expect full-screen destination alpha to work. This means that the D3DRS_DESTBLEND render state will not work as expected because full-screen swap chains with these swap effects do not have an explicit pixel format from the driver's point of view. The driver infers that they should take on the display format, which does not have an alpha channel. Take the following steps to work around this.

  • Use D3DSWAPEFFECT_COPY.
  • Check the D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD flag in the Caps3 member of the D3DCAPS9 structure. This flag indicates whether the driver can do alpha blending when D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD are used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::Reset, D3DPRESENT_PARAMETERS

© 2002 Microsoft Corporation. All rights reserved.


D3DTEXTUREADDRESS Enumerated Type

Defines constants that describe the supported texture-addressing modes.

Syntax

typedef enum _D3DTEXTUREADDRESS {
    D3DTADDRESS_WRAP = 1,
    D3DTADDRESS_MIRROR = 2,
    D3DTADDRESS_CLAMP = 3,
    D3DTADDRESS_BORDER = 4,
    D3DTADDRESS_MIRRORONCE = 5,
    D3DTADDRESS_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREADDRESS;

Constants

D3DTADDRESS_WRAP

Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times; no mirroring is performed.

D3DTADDRESS_MIRROR

Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again, and so on.

D3DTADDRESS_CLAMP

Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.

D3DTADDRESS_BORDER

Texture coordinates outside the range [0.0, 1.0] are set to the border color.

D3DTADDRESS_MIRRORONCE

Similar to D3DTADDRESS_MIRROR and D3DTADDRESS_CLAMP. Takes the absolute value of the texture coordinate (thus, mirroring around 0), and then clamps to the maximum value. The most common usage is for volume textures, where support for the full D3DTADDRESS_MIRRORONCE texture-addressing mode is not necessary, but the data is symmetric around the one axis.

D3DTADDRESS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DTEXTURESTAGESTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DTEXTUREFILTERTYPE Enumerated Type

Defines texture filtering modes for a texture stage.

Syntax

typedef enum _D3DTEXTUREFILTERTYPE {
    D3DTEXF_NONE = 0,
    D3DTEXF_POINT = 1,
    D3DTEXF_LINEAR = 2,
    D3DTEXF_ANISOTROPIC = 3,
    D3DTEXF_PYRAMIDALQUAD = 6,
    D3DTEXF_GAUSSIANQUAD = 7,
    D3DTEXF_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREFILTERTYPE;

Constants

D3DTEXF_NONE

Mipmapping disabled. The rasterizer should use the magnification filter instead.

D3DTEXF_POINT

Point filtering used as a texture magnification or minification filter. The texel with coordinates nearest to the desired pixel value is used. The texture filter to be used between mipmap levels is nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.

D3DTEXF_LINEAR

Bilinear interpolation filtering used as a texture magnification or minification filter. A weighted average of a 2x2 area of texels surrounding the desired pixel is used. The texture filter to use between mipmap levels is trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.

D3DTEXF_ANISOTROPIC

Anisotropic texture filtering used as a texture magnification or minification filter. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.

D3DTEXF_PYRAMIDALQUAD

A 4-sample tent filter used as a texture magnification or minification filter.

D3DTEXF_GAUSSIANQUAD

A 4-sample Gaussian filter used as a texture magnification or minification filter.

D3DTEXF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

To check if a format supports texture filter types other than D3DTEXF_POINT (which is always supported), call IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_FILTER.

Set a texture stage's magnification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MAGFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set a texture stage's minification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MINFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set the texture filter to use between-mipmap levels by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MIPFILTER value as the second parameter and one member of this enumeration as the third parameter.

Not all valid filtering modes for a device will apply to volume maps. In general, D3DTEXF_POINT and D3DTEXF_LINEAR magnification filters will be supported for volume maps. If D3DPTEXTURECAPS_MIPVOLUMEMAP is set, then the D3DTEXF_POINT mipmap filter and D3DTEXF_POINT and D3DTEXF_LINEAR minification filters will be supported for volume maps. The device may or may not support the D3DTEXF_LINEAR mipmap filter for volume maps. Devices that support anisotropic filtering for 2-D maps do not necessarily support anisotropic filtering for volume maps. However, applications that enable anisotropic filtering will receive the best available filtering (probably linear) if anisotropic filtering is not supported.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

ID3DXPatchMesh::GetDisplaceParam, ID3DXPatchMesh::SetDisplaceParam, D3DTEXTURESTAGESTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DTEXTUREOP Enumerated Type

Defines per-stage texture-blending operations.

Syntax

typedef enum _D3DTEXTUREOP {
    D3DTOP_DISABLE = 1,
    D3DTOP_SELECTARG1 = 2,
    D3DTOP_SELECTARG2 = 3,
    D3DTOP_MODULATE = 4,
    D3DTOP_MODULATE2X = 5,
    D3DTOP_MODULATE4X = 6,
    D3DTOP_ADD = 7,
    D3DTOP_ADDSIGNED = 8,
    D3DTOP_ADDSIGNED2X = 9,
    D3DTOP_SUBTRACT = 10,
    D3DTOP_ADDSMOOTH = 11,
    D3DTOP_BLENDDIFFUSEALPHA = 12,
    D3DTOP_BLENDTEXTUREALPHA = 13,
    D3DTOP_BLENDFACTORALPHA = 14,
    D3DTOP_BLENDTEXTUREALPHAPM = 15,
    D3DTOP_BLENDCURRENTALPHA = 16,
    D3DTOP_PREMODULATE = 17,
    D3DTOP_MODULATEALPHA_ADDCOLOR = 18,
    D3DTOP_MODULATECOLOR_ADDALPHA = 19,
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20,
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21,
    D3DTOP_BUMPENVMAP = 22,
    D3DTOP_BUMPENVMAPLUMINANCE = 23,
    D3DTOP_DOTPRODUCT3 = 24,
    D3DTOP_MULTIPLYADD = 25,
    D3DTOP_LERP = 26,
    D3DTOP_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREOP;

Constants

D3DTOP_DISABLE

Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

D3DTOP_SELECTARG1

Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture-stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2

Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_MODULATE

Multiply the components of the arguments.

D3DTOP_MODULATE2X

Multiply the components of the arguments, and shift the products to the left 1 bit (effectively multiplying them by 2) for brightening.

D3DTOP_MODULATE4X

Multiply the components of the arguments, and shift the products to the left 2 bits (effectively multiplying them by 4) for brightening.

D3DTOP_ADD

Add the components of the arguments.

D3DTOP_ADDSIGNED

Add the components of the arguments with a –0.5 bias, making the effective range of values from –0.5 through 0.5.

D3DTOP_ADDSIGNED2X

Add the components of the arguments with a –0.5 bias, and shift the products to the left 1 bit.

D3DTOP_SUBTRACT

Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH

Add the first and second arguments; then subtract their product from the sum.

D3DTOP_BLENDDIFFUSEALPHA

Linearly blend this texture stage, using the interpolated alpha from each vertex.

D3DTOP_BLENDTEXTUREALPHA

Linearly blend this texture stage, using the alpha from this stage's texture.

D3DTOP_BLENDFACTORALPHA

Linearly blend this texture stage, using a scalar alpha set with the D3DRS_TEXTUREFACTOR render state.

D3DTOP_BLENDTEXTUREALPHAPM

Linearly blend a texture stage that uses a premultiplied alpha.

D3DTOP_BLENDCURRENTALPHA

Linearly blend this texture stage, using the alpha taken from the previous texture stage.

D3DTOP_PREMODULATE

D3DTOP_PREMODULATE is set in stage n. The output of stage n is arg1. Additionally, if there is a texture in stage n+1, any D3DTA_CURRENT in stage n+1 is premultiplied by texture in stage n+1.

D3DTOP_MODULATEALPHA_ADDCOLOR

Modulate the color of the second argument, using the alpha of the first argument; then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA

Modulate the arguments; then add the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR

Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA

Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the color of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_BUMPENVMAP

Perform per-pixel bump mapping, using the environment map in the next texture stage, without luminance. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_BUMPENVMAPLUMINANCE

Perform per-pixel bump mapping, using the environment map in the next texture stage, with luminance. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_DOTPRODUCT3

Modulate the components of each argument as signed components, add their products; then replicate the sum to all color channels, including alpha. This operation is supported for color and alpha operations.

In Microsoft® DirectX® 6.0 and DirectX 7.0 multitexture operations the above inputs are all shifted down by half (y = x - 0.5) before use to simulate signed data, and the scalar result is automatically clamped to positive values and replicated to all three output channels. Also, note that as a color operation this does not updated the alpha it just updates the rgb components.

However, in DirectX 8.1 shaders you can specify that the output be routed to the .rgb or the .a components or both (the default). You can also specify a separate scalar operation on the alpha channel.

D3DTOP_MULTIPLYADD

Performs a multiply-accumulate operation. It takes the last two arguments, multiplies them together, and adds them to the remaining input/source argument, and places that into the result.

SRGBA = Arg1 + Arg2 * Arg3

D3DTOP_LERP

Linearly interpolates between the 2nd and 3rd source arguments by a proportion specified in the 1st source argument.

SRGBA = (Arg1) * Arg2 + (1- Arg1) * Arg3.

D3DTOP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the IDirect3DDevice9::SetTextureStageState method.

In the above formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1, Arg2, and Arg3 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument 1 would be shown as Arg1A.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DTEXTURESTAGESTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DTEXTURESTAGESTATETYPE Enumerated Type

Defines texture stage states.

Syntax

typedef enum _D3DTEXTURESTAGESTATETYPE {
    D3DTSS_COLOROP = 1,
    D3DTSS_COLORARG1 = 2,
    D3DTSS_COLORARG2 = 3,
    D3DTSS_ALPHAOP = 4,
    D3DTSS_ALPHAARG1 = 5,
    D3DTSS_ALPHAARG2 = 6,
    D3DTSS_BUMPENVMAT00 = 7,
    D3DTSS_BUMPENVMAT01 = 8,
    D3DTSS_BUMPENVMAT10 = 9,
    D3DTSS_BUMPENVMAT11 = 10,
    D3DTSS_TEXCOORDINDEX = 11,
    D3DTSS_BUMPENVLSCALE = 22,
    D3DTSS_BUMPENVLOFFSET = 23,
    D3DTSS_TEXTURETRANSFORMFLAGS = 24,
    D3DTSS_COLORARG0 = 26,
    D3DTSS_ALPHAARG0 = 27,
    D3DTSS_RESULTARG = 28,
    D3DTSS_CONSTANT = 32,
    D3DTSS_FORCE_DWORD = 0x7fffffff
} D3DTEXTURESTAGESTATETYPE;

Constants

D3DTSS_COLOROP

Texture-stage state is a texture color blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE, and for all other stages the default is D3DTOP_DISABLE.

D3DTSS_COLORARG1

Texture-stage state is the first color argument for the stage, identified by one of the D3DTA. The default argument is D3DTA_TEXTURE.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_COLORARG2

Texture-stage state is the second color argument for the stage, identified by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_ALPHAOP

Texture-stage state is a texture alpha blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.

D3DTSS_ALPHAARG1

Texture-stage state is the first alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_ALPHAARG2

Texture-stage state is the second alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_BUMPENVMAT00

Texture-stage state is a floating-point value for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT01

Texture-stage state is a floating-point value for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT10

Texture-stage state is a floating-point value for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT11

Texture-stage state is a floating-point value for the [1][1] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_TEXCOORDINDEX

Index of the texture coordinate set to use with this texture stage. You can specify up to eight sets of texture coordinates per vertex. If a vertex does not include a set of texture coordinates at the specified index, the system defaults to the u and v coordinates (0,0).

This flag is used only for fixed function vertex processing. For example, it should not be used with vertex shaders. When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value. The default index for each stage is equal to the stage index. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses.

Additionally, applications can include, as logical OR with the index being set, one of the constants to request that Microsoft® Direct3D® automatically generate the input texture coordinates for a texture transformation. For a list of all the constants, see D3DTSS.

With the exception of D3DTSS_TCI_PASSTHRU, which resolves to zero, if any of the following values is included with the index being set, the system uses the index strictly to determine texture wrapping mode. These flags are most useful when performing environment mapping.

D3DTSS_BUMPENVLSCALE

Floating-point scale value for bump-map luminance. The default value is 0.0.

D3DTSS_BUMPENVLOFFSET

Floating-point offset value for bump-map luminance. The default value is 0.0.

D3DTSS_TEXTURETRANSFORMFLAGS

Member of the D3DTEXTURETRANSFORMFLAGS enumerated type that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.

D3DTSS_COLORARG0

Settings for the third color operand for triadic operations (multiply add and linear interpolation), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_ALPHAARG0

Settings for the alpha channel selector operand for triadic operations (multiply add and linear interpolation), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default argument is (0.0, 0.0, 0.0, 0.0).

D3DTSS_RESULTARG

Setting to select destination register for the result of this stage, identified by D3DTA. This value can be set to D3DTA_CURRENT (the default value) or to D3DTA_TEMP, which is a single temporary register that can be read into subsequent stages as an input argument. The final color passed to the fog blender and frame buffer is taken from D3DTA_CURRENT, so the last active texture stage state must be set to write to current. This setting is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present.

D3DTSS_CONSTANT

Per-stage constant color. To see if a device supports a per-stage constant color, see the D3DPMISCCAPS_PERSTAGECONSTANT constant in D3DPMISCCAPS. D3DTSS_CONSTANT is used by D3DTA_CONSTANT. See D3DTA.

D3DTSS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the IDirect3DDevice9::GetTextureStageState and IDirect3DDevice9::SetTextureStageState methods to retrieve and set texture state values.

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to -8.0 and less than 8.0. This range, expressed in mathematical notation is (-8.0,8.0).

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState

© 2002 Microsoft Corporation. All rights reserved.


D3DTEXTURETRANSFORMFLAGS Enumerated Type

Defines texture-stage state values.

Syntax

typedef enum _D3DTEXTURETRANSFORMFLAGS {
    D3DTTFF_DISABLE = 0,
    D3DTTFF_COUNT1 = 1,
    D3DTTFF_COUNT2 = 2,
    D3DTTFF_COUNT3 = 3,
    D3DTTFF_COUNT4 = 4,
    D3DTTFF_PROJECTED = 256,
    D3DTTFF_FORCE_DWORD = 0x7fffffff
} D3DTEXTURETRANSFORMFLAGS;

Constants

D3DTTFF_DISABLE

Texture coordinates are passed directly to the rasterizer.

D3DTTFF_COUNT1

The rasterizer should expect 1-D texture coordinates.

D3DTTFF_COUNT2

The rasterizer should expect 2-D texture coordinates.

D3DTTFF_COUNT3

The rasterizer should expect 3-D texture coordinates.

D3DTTFF_COUNT4

The rasterizer should expect 4-D texture coordinates.

D3DTTFF_PROJECTED

The texture coordinates are all divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates is divided by the third coordinate before being passed to the rasterizer.

D3DTTFF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

These flags are used to set the value of the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the D3DTEXTURESTAGESTATETYPE enumerated type.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DTEXTURESTAGESTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DTRANSFORMSTATETYPE Enumerated Type

Defines constants that describe transformation state values.

Syntax

typedef enum _D3DTRANSFORMSTATETYPE {
    D3DTS_VIEW = 2,
    D3DTS_PROJECTION = 3,
    D3DTS_TEXTURE0 = 16,
    D3DTS_TEXTURE1 = 17,
    D3DTS_TEXTURE2 = 18,
    D3DTS_TEXTURE3 = 19,
    D3DTS_TEXTURE4 = 20,
    D3DTS_TEXTURE5 = 21,
    D3DTS_TEXTURE6 = 22,
    D3DTS_TEXTURE7 = 23,
    D3DTS_FORCE_DWORD = 0x7fffffff
} D3DTRANSFORMSTATETYPE;

Constants

D3DTS_VIEW

Identifies the transformation matrix being set as the view transformation matrix. The default value is NULL (the identity matrix).

D3DTS_PROJECTION

Identifies the transformation matrix being set as the projection transformation matrix. The default value is NULL (the identity matrix).

D3DTS_TEXTURE0

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE1

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE2

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE3

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE4

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE5

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE6

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE7

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The transform states in the range 256 through 511 are reserved to store up to 256 world matrices that can be indexed using the D3DTS_WORLDMATRIX and D3DTS_WORLD macros.

Macros
D3DTS_WORLD | Equivalent to D3DTS_WORLDMATRIX(0).
D3DTS_WORLDMATRIX(index) | Identifies the transform matrix to set for the world matrix at index. Multiple world matrices are used only for Vertex Blending. Otherwise only D3DTS_WORLD is used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


D3DVERTEXBLENDFLAGS Enumerated Type

Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending.

Syntax

typedef enum _D3DVERTEXBLENDFLAGS {
    D3DVBF_DISABLE = 0,
    D3DVBF_1WEIGHTS = 1,
    D3DVBF_2WEIGHTS = 2,
    D3DVBF_3WEIGHTS = 3,
    D3DVBF_TWEENING = 255,
    D3DVBF_0WEIGHTS = 256
} D3DVERTEXBLENDFLAGS;

Constants

D3DVBF_DISABLE

Disable vertex blending; apply only the world matrix set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation state is 0.

D3DVBF_1WEIGHTS

Enable vertex blending between the two matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0 and 1.

D3DVBF_2WEIGHTS

Enable vertex blending between the three matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, and 2.

D3DVBF_3WEIGHTS

Enable vertex blending between the four matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, 2, and 3.

D3DVBF_TWEENING

Vertex blending is done by using the value assigned to D3DRS_TWEENFACTOR.

D3DVBF_0WEIGHTS

Use a single matrix with a weight of 1.0.

Remarks

Members of this type are used with the D3DRS_VERTEXBLEND render state.

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX

© 2002 Microsoft Corporation. All rights reserved.


D3DZBUFFERTYPE Enumerated Type

Defines constants that describe depth-buffer formats.

Syntax

typedef enum _D3DZBUFFERTYPE {
    D3DZB_FALSE = 0,
    D3DZB_TRUE = 1,
    D3DZB_USEW = 2,
    D3DZB_FORCE_DWORD = 0x7fffffff
} D3DZBUFFERTYPE;

Constants

D3DZB_FALSE

Disable depth buffering.

D3DZB_TRUE

Enable z-buffering.

D3DZB_USEW

Enable w-buffering.

D3DZB_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the D3DRS_ZENABLE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE

© 2002 Microsoft Corporation. All rights reserved.


Constants

This section contains reference information for the constants defined in Microsoft® Direct3D®.

  • D3DCAPS2 - Driver capability flags
  • D3DCAPS3 - Driver capability flags
  • D3DCLEAR - Stencil clear constants
  • D3DCREATE - Device creation constants
  • D3DCURSORCAPS - Device cursor constants
  • D3DDEVCAPS2 - Driver capability constants
  • D3DDEVINFO_VCACHE - Vertex cache optimization hints
  • D3DDTCAPS - Vertex data constants
  • D3DENUM - Enumeration constants
  • D3DERR - Error constants
  • D3DFVF - Flexible vertex format constants
  • D3DLOCK - Locking constants
  • D3DPMISCCAPS - Driver primitive constants
  • D3DPRESENT - Presentation timing constants
  • D3DPRESENTFLAG - Presentation constants
  • D3DPS20CAPS - Pixel shader "2_0 Extended" constants
  • D3DPTFILTERCAPS - Texture filtering constants
  • D3DSTENCILCAPS - Driver stencil capability flags
  • D3DTA - Texture argument constants
  • D3DTSS - Texture coordinate constants
  • D3DUSAGE - Resource usage constants
  • D3DUSAGE_QUERY - Resource query usage constants
  • D3DVS20CAPS - Vertex shader "2_0 Extended" constants
  • D3DVERTEXTEXTURESAMPLER - Vertex shader samplers
  • D3DVTXPCAPS - Device create constants
  • Other Direct3D Constants - Other constants

© 2002 Microsoft Corporation. All rights reserved.


D3DCAPS2

Driver capability flags.

#define | Value | Description
D3DCAPS2_CANAUTOGENMIPMAP | 0x40000000L | The driver is capable of automatically generating mipmaps. For more information, see Automatic Generation of Mipmaps.
D3DCAPS2_CANCALIBRATEGAMMA | 0x00100000L | The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the D3DSGR_CALIBRATE flag when calling IDirect3DDevice9::SetGammaRamp. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
D3DCAPS2_CANMANAGERESOURCE | 0x10000000L | The driver is capable of managing resources. On such drivers, D3DPOOL_MANAGED resources will be managed by the driver. To have Microsoft® Direct3D® override the driver so that Direct3D manages resources, use the D3DCREATE_DISABLE_DRIVER_MANAGEMENT flag when calling IDirect3D9::CreateDevice.
D3DCAPS2_DYNAMICTEXTURES | 0x20000000L | The driver supports dynamic textures.
D3DCAPS2_FULLSCREENGAMMA | 0x00020000L | The driver supports dynamic gamma ramp adjustment in full-screen mode.
D3DCAPS2_RESERVED | 0x02000000L | Reserved; not used.

These constants are used by the D3CAPS2 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCAPS3

Driver capability flags.

#define | Description | Value
D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD | 0x00000020L | Indicates that the device can respect the D3DRS_ALPHABLENDENABLE render state in full-screen mode while using the FLIP or DISCARD swap effect. COPY and COPYVSYNC swap effects work whether or not this flag is set.
D3DCAPS3_COPY_TO_VIDMEM | 0x00000100L | Device can accelerate a memory copy from system memory to local video memory. This cap guarantees that IDirect3DDevice9::UpdateSurface and IDirect3DDevice9::UpdateTexture calls will be hardware accelerated. If this cap is absent, these calls will succeed but will be slower.
D3DCAPS3_COPY_TO_SYSTEMMEM | 0x00000200L | Device can accelerate a memory copy from local video memory to system memory. This cap guarantees that IDirect3DDevice9::GetRenderTargetData calls will be hardware accelerated. If this cap is absent, this call will succeed but will be slower.
D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION | 0x00000080L | Indicates that the device can perform gamma correction from a windowed back buffer (containing linear content) to an sRGB desktop.
D3DCAPS3_RESERVED | 0x8000001fL | Reserved; not used.

These constants are used by the D3CAPS3 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCLEAR

Stencil Clear Options. Define the target to clear.

#define | Description
D3DCLEAR_TARGET | The clear target is a surface.
D3DCLEAR_ZBUFFER | The clear target is a z-buffer.
D3DCLEAR_STENCIL | Clear the stencil planes.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCREATE

A combination of one or more flags that control the device create behavior.

#define | Description
D3DCREATE_FPU_PRESERVE | Indicates that the application needs either double-precision floating-point unit (FPU) or FPU exceptions enabled. Microsoft® Direct3D® sets the FPU state each time it is called. By default, the pipeline uses single precision. Be sure to use this flag to get double precision. Setting the flag will reduce Direct3D performance.
D3DCREATE_MULTITHREADED | Indicates that the application requests Direct3D to be multithread safe. This makes Direct3D take its global critical section more frequently, which can degrade performance.
D3DCREATE_PUREDEVICE | Specifies that Direct3D does not support Get* calls for anything that can be stored in state blocks. It also tells Direct3D not to provide any emulation services for vertex processing. This means that if the device does not support vertex processing, then the application can use only post-transformed vertices.
D3DCREATE_HARDWARE_VERTEXPROCESSING | Specifies hardware vertex processing.
D3DCREATE_SOFTWARE_VERTEXPROCESSING | Specifies software vertex processing.
D3DCREATE_MIXED_VERTEXPROCESSING | Specifies mixed (both software and hardware) vertex processing.
D3DCREATE_DISABLE_DRIVER_MANAGEMENT | Specifies that Direct3D should manage resources instead of the driver.
D3DCREATE_ADAPTERGROUP_DEVICE | Application asks the device to drive all the heads that this master adapter owns. The flag is illegal on nonmaster adapters. If this flag is set, the presentation parameters passed to IDirect3D9::CreateDevice should point to an array of D3DPRESENT_PARAMETERS. There should be the same as the number in NumberOfAdaptersInGroup elements in this array, and the runtime will assign each element to each head in AdapterOrdinalInGroup numerical order.
D3DCREATE_MANAGED | Device in which all resources are swapped between accelerator-accessible memory and system memory as needed. A managed device frees the application from memory management chores.

D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags. At least one of these vertex processing flags must be specified when calling IDirect3D9::CreateDevice.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCURSORCAPS

Driver cursor capability flags.

#define | Value | Description
D3DCURSORCAPS_COLOR | 0x00000001L | The driver supports hardware color cursor in at least high resolution modes (height >= 400).
D3DCURSORCAPS_LOWRES | 0x00000002L | The driver supports hardware color cursor in low resolution modes (height < 400).

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DDEVCAPS2

D3DDEVCAPS2 driver capability flags.

#define | Description
D3DDEVCAPS2_ADAPTIVETESSRTPATCH | Device supports adaptive tessellation of RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH | Device supports adaptive tessellation of N-patches.
D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES | Device supports IDirect3DDevice9::StretchRect using a texture as the source.
D3DDEVCAPS2_DMAPNPATCH | Device supports displacement maps for N-patches.
D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH | Device supports presampled displacement maps for N-patches. For more information about displacement mapping, see Displacement Mapping.
D3DDEVCAPS2_STREAMOFFSET | Device supports stream offsets.
D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET | Multiple vertex elements can share the same offset in a stream if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by the device and the vertex declaration does not have an element with D3DDECLUSAGE_POSITIONT0.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DDTCAPS

Constants describing the vertex data types supported by a device.

#define | Description | Value
D3DDTCAPS_UBYTE4 | 0x00000001L | 4-D unsigned byte.
D3DDTCAPS_UBYTE4N | 0x00000002L | Normalized, 4-D unsigned byte. Each of the four bytes is normalized by dividing to 255.0.
D3DDTCAPS_SHORT2N | 0x00000004L | Normalized, 2-D signed short, expanded to (first byte/32767.0, second byte/32767.0, 0, 1).
D3DDTCAPS_SHORT4N | 0x00000008L | Normalized, 4-D signed short, expanded to (first byte/32767.0, second byte/32767.0, third byte/32767.0, fourth byte/32767.0).
D3DDTCAPS_USHORT2N | 0x00000010L | Normalized, 2-D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, 0, 1).
D3DDTCAPS_USHORT4N | 0x00000020L | Normalized 4-D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, third byte/65535.0, fourth byte/65535.0).
D3DDTCAPS_UDEC3 | 0x00000040L | 3-D unsigned 10 10 10 format expanded to (value, value, value, 1).
D3DDTCAPS_DEC3N | 0x00000080L | 3-D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).
D3DDTCAPS_FLOAT16_2 | 0x00000100L | 2-D 16-bit floating point numbers.
D3DDTCAPS_FLOAT16_4 | 0x00000200L | 4-D 16-bit floating point numbers.

These constants are used by the DeclTypes member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DENUM

Driver capability flag.

#define | Value | Description
D3DENUM_WHQL_LEVEL | 0x00000002L | Microsoft® Windows® Hardware Quality Labs (WHQL) driver testing. This is a time-consuming test requiring a one-second or two-second time penalty. This constant is used by the WHQLLevel member of D3DADAPTER_IDENTIFIER9.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DFVF

Flexible Vertex Format Constants

The flexible vertex format (FVF) is used to describe the contents of vertices stored interleaved in a single data stream. An FVF code is generally used to specify data to be processed by fixed function vertex processing.

The following flags describe a vertex format. For information regarding vertex formats, see Vertex Formats.

Vertex data related flags

#define | Description
D3DFVF_DIFFUSE | Vertex format includes a diffuse color component.
D3DFVF_NORMAL | Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_PSIZE | Vertex format specified in point size. This size is expressed in camera space units for vertices that are not transformed and lit, and in device-space units for transformed and lit vertices.
D3DFVF_SPECULAR | Vertex format includes a specular color component.
D3DFVF_XYZ | Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_XYZRHW | Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags.
D3DFVF_XYZB1 through D3DFVF_XYZB5 | Vertex format contains position data, and a corresponding number of weighting (beta) values to use for multimatrix vertex blending operations. Currently, Microsoft® Direct3D® can blend with up to three weighting values and four blending matrices. For more information about using blending matrices, see Indexed Vertex Blending.
D3DFVF_XYZW | Vertex format contains transformed and clipped x,y,z w data. ProcessVertices does not invoke the clipper, instead outputting data in clip coordinates. This constant is designed for, and can only be used with, the programmable vertex pipeline.

Texture-related flags

#define | Description
D3DFVF_TEX0 - D3DFVF_TEX8 | Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.
D3DFVF_TEXCOORDSIZEn(coordIndex) | Define a texture coordinate data set. n indicates the dimension of the texture coordinates. coordIndex indicates texture coordinate index number. See D3DFVF_TEXCOORDSIZEn and Texture_coordinates_and_Texture_Stages.

Mask values

#define | Description
D3DFVF_POSITION_MASK | Mask for position bits.
D3DFVF_RESERVED0, D3DFVF_RESERVED2 | Mask values for reserved bits in the flexible vertex format. Do not use.
D3DFVF_TEXCOUNT_MASK | Mask value for texture flag bits.

Miscellaneous

#define | Description
D3DFVF_LASTBETA_D3DCOLOR | The last beta field in the vertex position data will be of type D3DCOLOR. The data in the beta fields are used with matrix palette skinning to specify matrix indices.
D3DFVF_LASTBETA_UBYTE4

The last beta field in the vertex position data will be of type UBYTE4. The data in the beta fields are used with matrix malette skinning to specify matrix indices.

// Given the following vertex data definition:
struct VERTEXPOSITION
{
   float pos[3];
   union
   {
      float beta[5];
      struct
      {
         float weights[4];
         DWORD MatrixIndices;  // Used as UBYTEs
      }
   }
};

Given the FVF is declared as: D3DFVF_XYZB5 | D3DFVF_LASTBETA_UBYTE4. Weight and MatrixInidices are included in beta[], where D3DFVF_LASTBETA_UBYTE4 says to interpret the last DWORD (beta[5]) as type UBYTE4.

The last beta is determined by the D3DRS_VERTEXBLEND, not by the number of betas in the position format. For example, if D3DRS_VERTEXBLEND is D3DVBF_2WEIGHTS and you have the position format above, the last beta will be beta[2] will be used as a DWORD with 4-byte indices.

D3DFVF_TEXCOUNT_SHIFT | The number of bits by which to shift an integer value that identifies the number of a texture coordinates for a vertex. This value might be used as shown below
DWORD dwNumTextures = 1;  // Vertex has only one set of coordinates.

// Shift the value for use when creating an FVF combination.
dwFVF = dwNumTextures << D3DFVF_TEXCOUNT_SHIFT;

// Now, create an FVF combination using the shifted value.

The following examples show other common flag combinations.

// Untransformed vertex for lit, untextured, Gouraud-shaded content.
dwFVF = ( D3DFVF_XYZ | D3DFVF_DIFFUSE );

// Untransformed vertex for unlit, untextured, Gouraud-shaded
//   content with diffuse material color specified per vertex.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE );

// Untransformed vertex for light-map-based lighting.
dwFVF = ( D3DFVF_XYZ | D3DFVF_TEX2 );

// Transformed vertex for light-map-based lighting with shared rhw.
dwFVF = ( D3DFVF_XYZRHW | D3DFVF_TEX2 );

// Heavyweight vertex for unlit, colored content with two
//   sets of texture coordinates.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
          D3DFVF_SPECULAR | D3DFVF_TEX2 );

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • Vertex Formats
  • Geometry Blending

© 2002 Microsoft Corporation. All rights reserved.


D3DLOCK

A combination of zero or more locking options that describe the type of lock to perform.

#define | Description
D3DLOCK_DISCARD The application overwrites (with a write-only operation) every location within the region being locked. This is a valid option when using dynamic textures, dynamic vertex buffers, and dynamic index buffers.

For vertex and index buffers, the application discards the entire buffer. A pointer to a new memory area is returned so that the dynamic memory access (DMA) and rendering from the previous area do not stall.

For textures, the application overwrites (with a write-only operation) every location within the region being locked.

D3DLOCK_DONOTWAIT | Allows an application to gain back CPU cycles if the driver cannot lock the surface immediately. If this flag is set and the driver cannot lock the surface immediately, the lock call will return D3DERRR_WASSTILLDRAWING. This flag can only be used when calling LockRect on surfaces created using IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DDevice9::CreateRenderTarget, or IDirect3DDevice9::CreateDepthStencilSurface. This flag can also be used with a back buffer.
D3DLOCK_NO_DIRTY_UPDATE | By default, a lock on a resource adds a dirty region to that resource. This option prevents any changes to the dirty state of the resource. Applications should use this option when they have additional information about the set of regions changed during the lock operation.
D3DLOCK_NOOVERWRITE | The application promises not to overwrite any data in the vertex and index buffers. Specifying this flag allows the driver to return immediately and continue rendering, using this buffer. If this flag is not used, the driver must finish rendering before returning from locking.
D3DLOCK_NOSYSLOCK

The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This option causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is time consuming, but can enable the system to perform other duties, such as moving the mouse cursor. This option is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY | The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • IDirect3DCubeTexture9::LockRect
  • IDirect3DIndexBuffer9::Lock
  • IDirect3DSurface9::LockRect
  • IDirect3DTexture9::LockRect
  • IDirect3DVertexBuffer9::Lock
  • IDirect3DVolume9::LockBox
  • IDirect3DVolumeTexture9::LockBox
  • ID3DXBaseMesh::LockIndexBuffer
  • ID3DXBaseMesh::LockVertexBuffer
  • ID3DXMesh::LockAttributeBuffer
  • ID3DXPatchMesh::LockAttributeBuffer
  • ID3DXPatchMesh::LockIndexBuffer
  • ID3DXPatchMesh::LockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


D3DPMISCCAPS

Miscellaneous driver primitive capability flags.

#define | Value | Description
D3DPMISCCAPS_MASKZ | 0x00000002L | Device can enable and disable modification of the depth buffer on pixel operations.
D3DPMISCCAPS_CULLNONE | 0x00000010L | The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCW | 0x00000020L | The driver supports clockwise triangle culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCCW | 0x00000040L | The driver supports counterclockwise culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CCW member of the D3DCULL enumerated type.
D3DPMISCCAPS_COLORWRITEENABLE | 0x00000100L | Device supports per-channel writes for the render target color buffer through the D3DRS_COLORWRITEENABLE state.
D3DPMISCCAPS_CLIPPLANESCALEDPOINTS | 0x00000200L | Device correctly clips scaled points of size greater than 1.0 to user-defined clipping planes.
D3DPMISCCAPS_CLIPTLVERTS | 0x00000200L | Device clips post-transformed vertex primitives. Specify D3DUSAGE_DONOTCLIP when the pipeline should not do any clipping. If D3DPMISCCAPS_CLIPTLVERTS is set, the output vertex buffer should be in system memory (D3DPOOL_SYSTEMMEM). Otherwise, the vertex buffer should be in the default memory pool (D3DPOOL_DEFAULT).
D3DPMISCCAPS_TSSARGTEMP | 0x00000400L | Device supports D3DTA for temporary register.
D3DPMISCCAPS_BLENDOP | 0x00000800L | Device supports alpha-blending operations other than D3DBLENDOP_ADD.
D3DPMISCCAPS_NULLREFERENCE | 0x00000100L | A reference device that does not render.
D3DPMISCCAPS_INDEPENDENTWRITEMASKS | 0x00004000L | Device supports independent write masks for multiple element textures or multiple render targets.
D3DPMISCCAPS_PERSTAGECONSTANT | 0x00008000L | Device supports per-stage constants. See D3DTSS_CONSTANT in D3DTEXTURESTAGESTATETYPE.
D3DPMISCCAPS_FOGANDSPECULARALPHA | 0x00010000L | Device supports separate fog and specular alpha. Many devices use the specular alpha channel to store the fog factor.
D3DPMISCCAPS_SEPARATEALPHABLEND | 0x00020000L | Device supports separate blend settings for the alpha channel.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS | 0x00040000L | Device supports different bit depths for multiple render targets.
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING | 0x00080000L | Device supports post-pixel shader operations for multiple render targets.
D3DPMISCCAPS_FOGVERTEXCLAMPED | 0x00100000L | Device clamps fog blend factor per vertex.

These constants are used by the PrimitiveMiscCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DPRESENT

Describes the relationship between the adapter refresh rate and the rate at which IDirect3DDevice9::Present operations are completed. These values also serve as flag values for the PresentationIntervals field of D3DCAPS9.

#define | Description
D3DPRESENT_INTERVAL_DEFAULT | This is equivalent to D3DPRESENT_INTERVAL_ONE.
D3DPRESENT_INTERVAL_ONE | The driver will wait for the vertical retrace period (the runtime will "beam follow" to prevent tearing). IDirect3DDevice9::Present operations will not be affected more frequently than the screen refresh; the runtime will complete at most one IDirect3DDevice9::Present operation per adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPYVSYNC in Microsoft® DirectX® 8.1. This option is always available for both windowed and full-screen swap chains.
D3DPRESENT_INTERVAL_TWO | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every second screen refresh. Check the PresentationIntervals cap in D3DCAPS9 to see if D3DPRESENT_INTERVAL_TWO is supported by the driver.
D3DPRESENT_INTERVAL_THREE | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every third screen refresh. Check the PresentationIntervals cap in D3DCAPS9 to see if D3DPRESENT_INTERVAL_THREE is supported by the driver.
D3DPRESENT_INTERVAL_FOUR | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every fourth screen refresh. Check the PresentationIntervals member in D3DCAPS9 to see if D3DPRESENT_INTERVAL_FOUR is supported by the driver.
D3DPRESENT_INTERVAL_IMMEDIATE | The runtime updates the window client area immediately and might do so more than once during the adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPY in DirectX 8.0. IDirect3DDevice9::Present operations might be affected immediately. This option is always available for both windowed and full-screen swap chains.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DPRESENTFLAG

Constants used by D3DPRESENT_PARAMETERS.

#define | Description | Value
D3DPRESENTFLAG_LOCKABLE_BACKBUFFER 0x00000001 Set this flag if the application requires the ability to lock the back buffer directly. Note that back buffers are not lockable unless the application specifies D3DPRESENTFLAG_LOCKABLE_BACKBUFFER when calling IDirect3D9::CreateDevice or IDirect3DDevice9::Reset. Lockable back buffers incur a performance cost on some graphics hardware configurations.

Performing a lock operation (or using IDirect3DDevice9::UpdateSurface to write) on the lockable back buffer decreases performance on many cards. In this case, consider using textured triangles to move data to the back buffer.

D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL 0x00000002 Set this flag when the device or swap chain is created to enable z-buffer discarding. If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data can increase performance and is driver dependent. The debug runtime will enforce discarding by clearing the z-buffer to some constant value after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data is illegal for all lockable formats, D3DFMT_D16_LOCKABLE and D3DFMT_D32F_LOCKABLE. Any use of IDirect3D9::CreateDevice specifying a lockable format and z-buffer discarding will fail. For more information about formats, see D3DFORMAT.

D3DPRESENTFLAG_DEVICECLIP | 0x00000004 | Clip a windowed IDirect3DDevice9::Present blit into the window client area, within the monitor screen area of the video adapter that created the Microsoft® Direct3D® device. This constant works on Microsoft Windows® 2000 and Windows XP only.
D3DPRESENTFLAG_VIDEO | 0x00000010 | This is a hint to the driver that the back buffers will contain video data.

These constants are used by D3DPRESENT_PARAMETERS.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DPS20CAPS

Pixel shader capability flags.

#define | Value | Description
D3DPS20CAPS_ARBITRARYSWIZZLE | (1 << 0) | Arbitrary swizzling is supported.
D3DPS20CAPS_GRADIENTINSTRUCTIONS | (1 << 1) | Gradient instructions are supported.
D3DPS20CAPS_PREDICATION | (1 << 2) | Instruction predication is supported. See setp.
D3DPS20CAPS_NODEPENDENTREADLIMIT | (1 << 3) | There is no limit on the number of dependent reads per instruction.
D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT | (1 << 4) | There is no limit on the number of tex instructions.
D3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MAX_NUMTEMPS | 32 | The driver will support at most this many temporary register.
D3DPS20_MIN_NUMTEMPS | 12 | The driver will support at least this many temporary register.
D3DPS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop/rep and call/callnz instructions.
D3DPS20_MIN_STATICFLOWCONTROLDEPTH | 0 | The minimum depth of nesting of the loop/rep and call/callnz instructions.
D3DPS20_MAX_NUMINSTRUCTIONSLOTS | 512 | The driver will support at most this many instructions.
D3DPS20_MIN_NUMINSTRUCTIONSLOTS | 96 | The driver will support at least this many instructions.

These constants are used by the PS20Caps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

Related Topics

  • D3DPSHADERCAPS2_0

© 2002 Microsoft Corporation. All rights reserved.


D3DPTFILTERCAPS

Texture filtering constants.

#define | Description
D3DPTFILTERCAPS_MAGFPOINT | Device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports per-stage bilinear interpolation filtering for magnifying mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFANISOTROPIC | Device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for magnifying textures. The pyramidal magnifying filter is represented by the D3DTEXF_PYRAMIDALQUAD member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for magnifying textures.
D3DPTFILTERCAPS_MINFPOINT | Device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFLINEAR | Device supports per-stage linear filtering for minifying textures. The linear minification filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFANISOTROPIC | Device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for minifying textures.
D3DPTFILTERCAPS_MINFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for minifying textures.
D3DPTFILTERCAPS_MIPFPOINT | Device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MIPFLINEAR | Device supports per-stage bilinear interpolation filtering for mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.

These constants are used by TextureFilterCaps, CubeTextureFilterCaps, VolumeTextureFilterCaps, and VertexTextureFilterCaps members of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DSTENCILCAPS

Driver stencil capability flags.

#define | Value | Description
D3DSTENCILCAPS_KEEP | 0x00000001L | Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILCAPS_ZERO | 0x00000002L | Set the stencil-buffer entry to 0.
D3DSTENCILCAPS_REPLACE | 0x00000004L | Replace the stencil-buffer entry with reference value.
D3DSTENCILCAPS_INCRSAT | 0x00000008L | Increment the stencil-buffer entry, clamping to the maximum value.
D3DSTENCILCAPS_DECRSAT | 0x00000010L | Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILCAPS_INVERT | 0x00000020L | Invert the bits in the stencil-buffer entry.
D3DSTENCILCAPS_INCR | 0x00000040L | Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value.
D3DSTENCILCAPS_DECR | 0x00000080L | Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILCAPS_TWOSIDED | 0x00000100L | The device supports two-sided stencil.

Stencil-buffer entries are integer values ranging from 0 through 2 n - 1, where n is the bit depth of the stencil buffer.

These constants are used by the StencilCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DTA

Texture Argument constants

Each texture stage for a device can have two texture arguments that affect the color or alpha channel of the texture.

Set and retrieve texture arguments by calling the IDirect3DDevice9::SetTextureStageState and IDirect3DDevice9::GetTextureStageState methods, and specifying the D3DTSS_COLORARG0, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG0, D3DTSS_ALPHAARG1, D3DTSS_ALPHAARG2, or D3DTSS_RESULTARG member of the D3DTEXTURESTAGESTATETYPE enumerated type.

The following flags, organized as arguments and modifiers, can be used with color and alpha arguments for a texture stage. You can combine an argument flag with a modifier, but two argument flags cannot be combined.

Argument flags

#define | Description
D3DTA_CURRENT | The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. If s represents the current texture stage and s - 1 contains a bump-map texture, this argument becomes the result output by texture stage s - 2. Permissions are read/write.
D3DTA_DIFFUSE | The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF. Permissions are read-only.
D3DTA_SELECTMASK | Mask value for all arguments; not used when setting texture arguments.
D3DTA_SPECULAR | The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a specular color, the default color is 0xFFFFFFFF. Permissions are read-only.
D3DTA_TEMP | The texture argument is a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0). Permissions are read/write.
D3DTA_TEXTURE | The texture argument is the texture color for this texture stage. Permissions are read-only.
D3DTA_TFACTOR | The texture argument is the texture factor set in a previous call to the IDirect3DDevice9::SetRenderState with the D3DRS_TEXTUREFACTOR render-state value. Permissions are read-only.

Modifier flags

#define | Description
D3DTA_ALPHAREPLICATE | Replicate the alpha information to all color channels before the operation completes. This is a read modifier.
D3DTA_COMPLEMENT | Invert the argument so that, if the result of the argument were referred to by the variable x, the value would be 1.0 minus x. This is a read modifier.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DTSS_TCI

Driver texture coordinate capability flags.

#define | Value | Description
D3DTSS_TCI_PASSTHRU | 0x00000000L | Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL | 0x00010000L | Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION | 0x00020000L | Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 0x00030000L | Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_TCI_SPHEREMAP | 0x00040000L | Use the specified texture coordinates for sphere mapping.

These constants are used by D3DTSS_TEXCOORDINDEX.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DUSAGE

Options identify how resources are to be used. The table below summarizes the usages that available to each resource type. The second table identifies which usages are available for each resource type.

Usages

#define | Description
D3DUSAGE_AUTOGENMIPMAP The resource will automatically generate mipmaps. See Automatic Generation of Mipmaps. Automatic generation of mipmaps is not supported for volume textures and depth stencil surfaces/textures.

This usage is not valid for a resource in system memory (D3DPOOL_SYSTEMMEM).

D3DUSAGE_DEPTHSTENCIL | The resource will be a depth stencil buffer. D3DUSAGE_DEPTHSTENCIL can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_DMAP | The resource will be a displacement map.
D3DUSAGE_DONOTCLIP | Set to indicate that the vertex buffer content will never require clipping. When rendering with buffers that have this flag set, the D3DRS_CLIPPING render state must be set to false.
D3DUSAGE_DYNAMIC

Set to indicate that the vertex buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static vertex buffers are placed in video memory and dynamic vertex buffers are placed in accelerated graphics port (AGP) memory. Note that there is no separate static use. If you do not specify D3DUSAGE_DYNAMIC, the vertex buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are valid only on vertex buffers created with D3DUSAGE_DYNAMIC. They are not valid flags on static vertex buffers. For more information, see Managing Resources.

For more information about using dynamic vertex buffers, see Performance Optimizations.

D3DUSAGE_DYNAMIC and D3DPOOL_MANAGED are incompatible and should not be used together. See D3DPOOL.

Textures can specify D3DUSAGE_DYNAMIC. However, managed textures cannot use D3DUSAGE_DYNAMIC. For more information about dynamic textures, see Using Dynamic Textures.

D3DUSAGE_NPATCHES | Set to indicate when the vertex buffer is to be used for drawing N-patches.
D3DUSAGE_POINTS | Set to indicate when the vertex buffer is to be used for drawing points.
D3DUSAGE_RENDERTARGET | The resource will be a render target. D3DUSAGE_RENDERTARGET can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_RTPATCHES | Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_SOFTWAREPROCESSING If this flag is used, vertex processing is done in software. If this flag is not used, vertex processing is done in hardware.

D3DUSAGE_SOFTWAREPROCESSING is used with IDirect3D9::CheckDeviceFormat to find out if a particular texture format can be used as a vertex texture during software vertex processing. If it can, the texture must be created in D3DPOOL_SCRATCH.

D3DUSAGE_WRITEONLY | Informs the system that the application writes only to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability will fail. Buffers created with D3DPOOL_DEFAULT that do not specify D3DUAGE_WRITEONLY might suffer a severe performance penalty.

Usage and Pool Combinations

Certain usages can be used with certain pool types. See D3DPOOL for more information.

Usage and Resource Combinations

Usages are either specified when a resource is created, or specified with CheckDeviceFormat to test the capability of an existing resource. This table identifies which usages can be applied to which resource types.

Usage | Vertex buffer create | Index buffer create | Texture create | Cube texture create | Volume texture create | Surface create | Check device format
D3DUSAGE_AUTOGENMIPMAP |  |  | x | x |  |  | x
D3DUSAGE_DEPTHSTENCIL |  |  | x | x |  | x | x
D3DUSAGE_DMAP |  |  | x |  |  |  | x
D3DUSAGE_DONOTCLIP | x | x |  |  |  |  |
D3DUSAGE_DYNAMIC | x | x | x | x | x |  | x
D3DUSAGE_NPATCHES | x | x |  |  |  |  |
D3DUSAGE_POINTS | x | x |  |  |  |  |
D3DUSAGE_RTPATCHES | x | x |  |  |  |  |
D3DUSAGE_RENDERTARGET |  |  | x | x |  | x | x
D3DUSAGE_SOFTWAREPROCESSING | x | x | x | x | x |  | x
D3DUSAGE_WRITEONLY | x | x |  |  |  |  |

Use IDirect3D9::CheckDeviceFormat to check hardware support for these usages.

Each of the resource creation methods is listed here.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateOffscreenPlainSurface
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVertexBuffer
  • IDirect3DDevice9::CreateVolumeTexture

For more information about pool types, see D3DPOOL.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • D3DUSAGE_QUERY

© 2002 Microsoft Corporation. All rights reserved.


D3DUSAGE_QUERY

These options identify query resource types.

#define | Description
D3DUSAGE_QUERY_FILTER | Query the resource format to see if it supports texture filter types other than D3DTEXF_POINT (which is always supported).
D3DUSAGE_QUERY_LEGACYBUMPMAP | Query the resource about a legacy bump map.
D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING | Query the resource to verify support for post pixel shader blending support. If IDirect3D9::CheckDeviceFormat fails with D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, post pixel blending operations are not supported. These include alpha test, pixel fog, render target blending, color write enable, and dithering.
D3DUSAGE_QUERY_SRGBREAD | Query the resource to verify if a texture supports gamma correction during a read operation.
D3DUSAGE_QUERY_SRGBWRITE | Query the resource to verify if a texture supports gamma correction during a write operation.
D3DUSAGE_QUERY_VERTEXTEXTURE | Query the resource to verify support for vertex shader texture sampling.

Use IDirect3D9::CheckDeviceFormat to query hardware support for these usages, and some other usages listed in D3DUSAGE.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

    © 2002 Microsoft Corporation. All rights reserved.


D3DVS20CAPS

Vertex shader capability constants.

#define | Value | Description
D3DVS20CAPS_PREDICATION | (1 << 0) | Instruction predication is supported. See setp.
D3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DVS20_MAX_NUMTEMPS | 32 | The maximum number of temporary registers supported.
D3DVS20_MIN_NUMTEMPS | 12 | The minimum number of temporary registers supported.
D3DVS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop/rep and call/callnz instructions.
D3DVS20_MIN_STATICFLOWCONTROLDEPTH | 1 | The minimum depth of nesting of the loop/rep and call/callnz instructions.

These constants are used by the VS20Caps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

Related Topics

  • D3DVSHADERCAPS2_0

© 2002 Microsoft Corporation. All rights reserved.


D3DVERTEXTEXTURESAMPLER

Vertex texture sampler constants.

These constants identify the texture samplers used by vertex shaders.

#define | Description
D3DVERTEXTEXTURESAMPLER0 | (D3DDMAPSAMPLER+1)
D3DVERTEXTEXTURESAMPLER1 | (D3DDMAPSAMPLER+2)
D3DVERTEXTEXTURESAMPLER2 | (D3DDMAPSAMPLER+3)
D3DVERTEXTEXTURESAMPLER3 | (D3DDMAPSAMPLER+4)

D3DDMAPSAMPLER

This is an internal constant used by the texture sampler in the tessellator.

#define | Description
D3DDMAPSAMPLER | 256

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DVTXPCAPS

A combination of one or more flags that control the device create behavior.

#define | Description
D3DVTXPCAPS_DIRECTIONALLIGHTS | Device can do directional lights.
D3DVTXPCAPS_LOCALVIEWER | Device can do local viewer.
D3DVTXPCAPS_MATERIALSOURCE7 | Device can do Microsoft® DirectX® 7.0 colormaterialsource operations.
D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER | Device does not support texture generation in non-local viewer mode.
D3DVTXPCAPS_POSITIONALLIGHTS | Device can do positional lights (includes point and spot).
D3DVTXPCAPS_TEXGEN | Device can do texgen.
D3DVTXPCAPS_TEXGEN_SPHEREMAP | Device supports D3DTSS_TCI_SPHEREMAP.
D3DVTXPCAPS_TWEENING | Device can do vertex tweening.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Other Direct3D Constants

  • D3DCAPS_
  • D3DCURSORCAPS_
  • D3DDEVCAPS_
  • D3DPMISCCAPS_
  • D3DLINECAPS_
  • D3DPRASTERCAPS_
  • D3DPCMPCAPS_
  • D3DPBLENDCAPS_
  • D3DPSHADECAPS_
  • D3DPTEXTURECAPS_
  • D3DPTFILTERCAPS_
  • D3DPTADDRESSCAPS_
  • D3DSTENCILCAPS_
  • D3DTEXOPCAPS_

Internal Use Constants

The following constants are used internally.

#define | Value
D3DDP_MAXTEXCOORD | 8
D3DDMAPSAMPLER | 256
D3D_MAX_SIMULTANEOUS_RENDERTARGETS | 4
D3DMAXDECLLENGTH | 18
D3DMAXDECLMETHOD | D3DDECLMETHOD_LOOKUPPRESAMPLED
D3DMAXDECLUSAGE | D3DDECLUSAGE_DEPTH
D3DMAXDECLUSAGE_DX8 | D3DDECLUSAGE_TEXCOORD
D3DMAXDECLUSAGEINDEX | 15
D3DMAXDECLTYPE | D3DDECLTYPE_UNUSED
D3DPRESENT_BACK_BUFFER_MAX | 3L

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Direct3D Extension (D3DX) C/C++ Reference

This section contains reference information for the application programming interface (API) elements provided by the Direct3D extensions (D3DX) utility library. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Callback Functions
  • Macros
  • Structures
  • Enumerated Types
  • Constants

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains reference information for the Component Object Model (COM) interfaces provided by the Direct3D extensions (D3DX) utility library. The following interfaces are used with the D3DX utility library.

Interfaces

  • ID3DXAllocateHierarchy
  • ID3DXAnimationController
  • ID3DXAnimationSet
  • ID3DXBaseEffect
  • ID3DXBaseMesh
  • ID3DXBuffer
  • ID3DXConstantTable
  • ID3DXEffect
  • ID3DXEffectCompiler
  • ID3DXEffectPool
  • ID3DXFont
  • ID3DXFragmentLinker
  • ID3DXInclude
  • ID3DXInterpolator
  • ID3DXKeyFrameInterpolator
  • ID3DXLine
  • ID3DXLoadUserData
  • ID3DXMatrixStack
  • ID3DXMesh
  • ID3DXPatchMesh
  • ID3DXPMesh
  • ID3DXRenderToEnvMap
  • ID3DXRenderToSurface
  • ID3DXSaveUserData
  • ID3DXSkinInfo
  • ID3DXSPMesh
  • ID3DXSprite

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAllocateHierarchy Interface

This interface is implemented by the application to allocate or free frame and mesh container objects. Methods on this are called during loading and destroying frame hierarchies.

ID3DXAllocateHierarchy Members

CreateFrame | Requests allocation of a frame object.
CreateMeshContainer | Requests allocation of a mesh container object.
DestroyFrame | Requests deallocation of a frame object.
DestroyMeshContainer | Requests deallocation of a mesh container object.

Interface Information

Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAllocateHierarchy::CreateFrame Method

Requests allocation of a frame object.

Syntax

HRESULT CreateFrame(

    LPCSTR pMesh,
    LPD3DXFRAME *ppNewFrame
);

Parameters

pMesh
[in] Name of the frame to be created.
ppNewFrame
[out, retval] Returns the created frame object.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAllocateHierarchy::CreateMeshContainer Method

Requests allocation of a mesh container object.

Syntax

HRESULT CreateMeshContainer(

    LPCSTR Name,
    LPD3DXMESHDATA pMeshData,
    LPD3DXMATERIAL pMaterials,
    LPD3DXEFFECTINSTANCE pEffectInstances,
    DWORD NumMaterials,
    DWORD *pAdjacency,
    LPD3DXSKININFO pSkinInfo,
    LPD3DXMESHCONTAINER *ppNewMeshContainer
);

Parameters

Name
[in] Name of the mesh.
pMeshData
[in] Pointer to the mesh data structure. See D3DXMESHDATA.
pMaterials
[in] Array of materials used in the mesh.
pEffectInstances
[in] Array of effect instances used in the mesh. See D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of materials in the materials array.
pAdjacency
[in] Adjacency array for the mesh.
pSkinInfo
[in] Pointer to the skin mesh object if skin data is found. See ID3DXSkinInfo.
ppNewMeshContainer
[out, retval] Returns the created mesh container. See D3DXMESHCONTAINER.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAllocateHierarchy::DestroyFrame Method

Requests deallocation of a frame object.

Syntax

HRESULT DestroyFrame(

    LPD3DXFRAME pFrameToFree
);

Parameters

pFrameToFree
[in] Pointer to the frame to be deallocated.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAllocateHierarchy::DestroyMeshContainer Method

Requests deallocation of a mesh container object.

Syntax

HRESULT DestroyMeshContainer(

    LPD3DXMESHCONTAINER pMeshContainerToFree
);

Parameters

pMeshContainerToFree
[in] Pointer to the mesh container object to be deallocated.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController Interface

This interface implements the animation controller, which is derived from the animation mixer (ID3DXAnimationMixer). The animation controller adds methods to modify blending parameters over time to enable smooth transitions.

ID3DXAnimationController Members

CloneAnimationController | Clones, or copies an animation controller.
GetAnimationSet | Gets the animation set.
GetMaxNumAnimationSets | Gets the maximum number of animation sets the controller can support.
GetMaxNumEvents | Gets the maximum number of events the controller can support.
GetMaxNumMatrices | Gets the maximum number of matrices the controller can support.
GetMaxNumTracks | Gets the maximum number of tracks in the mixer.
GetNumAnimationSets | Returns the number of animation sets currently registered in the mixer.
GetPriorityBlend | Gets the track blending weight.
GetTime | Gets the global animation time.
GetTrackAnimationSet | Gets the animation set for the given track.
GetTrackDesc | Gets the track description.
KeyPriorityBlend | Blends together the low priority and high priority blended tracks.
KeyTrackAnimationTime | Keys, or sets, the new animation time of the track.
KeyTrackEnable | Keys, or sets the track enable. This enables or disables the track settings.
KeyTrackSpeed | Keys, or sets the track speed. This is a speed modifier that adjusts the rate of play of the track.
KeyTrackWeight | Keys, or sets the track weight. The weight is used as a multiplier when combining two tracks together.
RegisterAnimationSet | Adds an animation set to the animation mixer.
RegisterMatrix | Registers or sets the matrix in the mixer.
SetPriorityBlend | Sets the track blending weight.
SetTime | Sets the global time in the animation controller and updates the frame hierarchy's transformation matrices based on the track settings and the animation sets. The animation sets are controlled by the tracks.
SetTrackAnimationSet | Applies the animation set to the specified track.
SetTrackAnimationTime | Sets the animation time for this track.
SetTrackDesc | Sets the track's description.
SetTrackEnable | Enables or disables a track in the animation mixer.
SetTrackSpeed | Sets the track speed. The track speed is like a multiplier that is used to speed up or slow down the playback of the track.
SetTrackWeight | Sets the track weight. The weight is used to determine how to blend multiple tracks together.
UnregisterAnimationSet | Remove an animation set from the animation mixer.

Interface Information

Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::CloneAnimationController Method

Clones, or copies an animation controller.

Syntax

HRESULT CloneAnimationController(

    UINT MaxNumMatrices,
    UINT MaxNumAnimationSets,
    UINT MaxNumTracks,
    UINT MaxNumEvents,
    LPD3DXANIMATIONCONTROLLER *ppAnimController
);

Parameters

MaxNumMatrices
[in] Set the maximum number of matrices the controller can support.
MaxNumAnimationSets
[in] Set the maximum number of animation sets the controller can support.
MaxNumTracks
[in] Set the maximum number of tracks the controller can support.
MaxNumEvents
[in] Set the maximum number of events the controller can support.
ppAnimController
[in] Returns the cloned animation controller.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetAnimationSet Method

Gets the animation set.

Syntax

HRESULT GetAnimationSet(

    DWORD iAnimationSet,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

iAnimationSet
[in] Index of the animation set.
ppAnimSet
[out, retval] Pointer to the animation set that is returned.

Return Value

Returns S_OK if successful, or an error value otherwise.

Remarks

The mixer contains an array of animation sets. This method returns one of them at the given index.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetMaxNumAnimationSets Method

Gets the maximum number of animation sets the controller can support.

Syntax

UINT GetMaxNumAnimationSets(VOID);

Return Value

The maximum number of animation sets the controller can manage.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetMaxNumEvents Method

Gets the maximum number of events the controller can support.

Syntax

UINT GetMaxNumEvents(VOID);

Return Value

The maximum number of events the controller can manage.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetMaxNumMatrices Method

Gets the maximum number of matrices the controller can support.

Syntax

UINT GetMaxNumMatrices(VOID);

Return Value

The maximum number of matrices the controller can manage.

See Also

D3DXMATRIX

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetMaxNumTracks Method

Gets the maximum number of tracks in the mixer.

Syntax

UINT GetMaxNumTracks(VOID);

Return Value

Number of tracks.

Remarks

The mixer contains any number of tracks that can be combined to produce animations.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetNumAnimationSets Method

Returns the number of animation sets currently registered in the mixer.

Syntax

UINT GetNumAnimationSets(VOID);

Return Value

Number of animation sets.

Remarks

The mixer contains any number of animations sets and tracks. Animation sets can be registered with ID3DXAnimationController::RegisterAnimationSet. An animation controller created by a call to D3DXLoadMeshHierarchyFromX will automatically register loaded animation sets.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetPriorityBlend Method

Gets the track blending weight.

Syntax

FLOAT GetPriorityBlend(VOID);

Return Value

Returns the blend weight.

Remarks

Blend weight is used to blend high and low priority tracks together.

See Also

ID3DXAnimationController::SetPriorityBlend

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetTime Method

Gets the global animation time.

Syntax

DOUBLE GetTime(VOID);

Return Value

Returns the global animation time.

Remarks

Animations are designed using a local animation time and mixed into global time with ID3DXAnimationController::SetTime.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetTrackAnimationSet Method

Gets the animation set for the given track.

Syntax

HRESULT GetTrackAnimationSet(

    DWORD Track,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

Track
[in] Track.
ppAnimSet
[out, retval] Pointer to the animation set for the given track.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::GetTrackDesc Method

Gets the track description.

Syntax

HRESULT GetTrackDesc(

    DWORD Track,
    D3DXTRACK_DESC *pDesc
);

Parameters

Track
[in] Track.
pDesc
[out, retval] Pointer to the description.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::KeyPriorityBlend Method

Blends together the low priority and high priority blended tracks.

Syntax

HRESULT KeyPriorityBlend(

    FLOAT BlendWeight,
    DOUBLE StartTime,
    DOUBLE Duration,
    DWORD Method
);

Parameters

BlendWeight
[in] Number between 0 and 1 that is used to blend tracks together.
StartTime
[in] Global time to start the blend.
Duration
[in] Global time duration of the blend.
Method
[in] Specifies the transition type between tracks. For more information, see D3DXTRANSITIONTYPE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The animation controller blends in three phases: low priority tracks are blended first, high priority tracks are blended second, and then the results of both are blended.

See Also

ID3DXAnimationController::SetPriorityBlend

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::KeyTrackAnimationTime Method

Keys, or sets, the new animation time of the track.

Syntax

HRESULT KeyTrackAnimationTime(

    DWORD Track,
    DOUBLE NewAnimTime,
    DOUBLE StartTime
);

Parameters

Track
[in] Track to modify.
NewAnimTime
[in] New animation time of the track.
StartTime
[in] Global time key. Specifies the global time that the change will take place.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method sets the time value that the animation set should switch to at the specified StartTime. It is equivalent to saying: "For track n at global time (StartTime), set the animation set for the track to position (NewAnimTime)."

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::KeyTrackEnable Method

Keys, or sets the track enable. This enables or disables the track settings.

Syntax

HRESULT KeyTrackEnable(

    DWORD Track,
    BOOL NewEnable,
    DOUBLE StartTime
);

Parameters

Track
[in] Track to modify.
NewEnable
[in] Enable flag. Set this to TRUE to enable the track and to FALSE to disable it.
StartTime
[in] Global time key. Specifies the global time that the change will take place.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXAnimationController::KeyTrackAnimationTime, ID3DXAnimationController::KeyTrackSpeed, ID3DXAnimationController::KeyTrackWeight

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::KeyTrackSpeed Method

Keys, or sets the track speed. This is a speed modifier that adjusts the rate of play of the track.

Syntax

HRESULT KeyTrackSpeed(

    DWORD Track,
    FLOAT NewSpeed,
    DOUBLE StartTime,
    DOUBLE Duration,
    DWORD Method
);

Parameters

Track
[in] Track to modify.
NewSpeed
[in] New speed of the track.
StartTime
[in] Global time key. Specifies the global time that the change will take place.
Duration
[in] Transition time, which specifies how long the smooth transition will take to complete.
Method
[in] Specifies the transition type between tracks. For more information, see D3DXTRANSITIONTYPE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::KeyTrackWeight Method

Keys, or sets the track weight. The weight is used as a multiplier when combining two tracks together.

Syntax

HRESULT KeyTrackWeight(

    DWORD Track,
    FLOAT NewWeight,
    DOUBLE StartTime,
    DOUBLE Duration,
    DWORD Method
);

Parameters

Track
[in] Track to modify.
NewWeight
[in] New weight of the track.
StartTime
[in] Global time key. Specifies the global time that the change will take place.
Duration
[in] Transition time which specifies how long the smooth transition will take to complete.
Method
[in] Specifies the transition type between tracks. For more information, see D3DXTRANSITIONTYPE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The weight is used like a multiplier to determine how much of this track to blend together with other tracks.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::RegisterAnimationSet Method

Adds an animation set to the animation mixer.

Syntax

HRESULT RegisterAnimationSet(

    LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] Animation set to add.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Animation sets created with D3DXLoadMeshHierarchyFromX automatically register all loaded animation sets.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::RegisterMatrix Method

Registers or sets the matrix in the mixer.

Syntax

HRESULT RegisterMatrix(

    LPCSTR Name,
    D3DXMATRIX *pMatrix
);

Parameters

Name
[in] Name of the matrix.
pMatrix
[in] Pointer to the matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Animation sets created with D3DXLoadMeshHierarchyFromX automatically register all loaded named matrices.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetPriorityBlend Method

Sets the track blending weight.

Syntax

HRESULT SetPriorityBlend(

    FLOAT BlendWeight
);

Parameters

BlendWeight
[in] Number between 0 and 1 that is used to blend tracks together.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The blend weight is used to blend high and low priority tracks together.

See Also

ID3DXAnimationController::GetPriorityBlend

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTime Method

Sets the global time in the animation controller and updates the frame hierarchy's transformation matrices based on the track settings and the animation sets. The animation sets are controlled by the tracks.

Syntax

HRESULT SetTime(

    DOUBLE Time
);

Parameters

Time
[in] Global time.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Call ID3DXAnimationController::SetTime every frame to animate the mesh. It sets the global animation time to the specified time and clears any past events.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackAnimationSet Method

Applies the animation set to the specified track.

Syntax

HRESULT SetTrackAnimationSet(

    DWORD Track,
    LPD3DXANIMATIONSET pAnimSet
);

Parameters

Track
[in] Track that is adding this animation set.
pAnimSet
[in] Animation set to be added to the track.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method sets the animation set to the specified track for mixing. Each track's animation set is blended according to the track's weight and speed when ID3DXAnimationController::SetTime is called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackAnimationTime Method

Sets the animation time for this track.

Syntax

HRESULT SetTrackAnimationTime(

    DWORD Track,
    DOUBLE AnimTime
);

Parameters

Track
[in] Track whose time is being set.
AnimTime
[in] Set the local time in this track.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Animation tracks are designed in local time. One or more tracks are then combined in the mixer. This method sets the time for this track to be started within the mixer.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackDesc Method

Sets the track's description.

Syntax

HRESULT SetTrackDesc(

    DWORD Track,
    D3DXTRACK_DESC *pDesc
);

Parameters

Track
[in] Track to modify.
pDesc
[in] Description of the track.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackEnable Method

Enables or disables a track in the animation mixer.

Syntax

HRESULT SetTrackEnable(

    DWORD Track,
    BOOL Enable
);

Parameters

Track
[in] Track to be mixed.
Enable
[in] Enable value. Set to TRUE to enable this track in the mixer, or FALSE to prevent it from being mixed.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

To mix a track with other tracks, this flag must be enabled. Conversely, setting this flag to false will prevent it from being mixed with other tracks.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackSpeed Method

Sets the track speed. The track speed is like a multiplier that is used to speed up or slow down the playback of the track.

Syntax

HRESULT SetTrackSpeed(

    DWORD Track,
    FLOAT Speed
);

Parameters

Track
[in] Track to set the speed on.
Speed
[in] New speed.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::SetTrackWeight Method

Sets the track weight. The weight is used to determine how to blend multiple tracks together.

Syntax

HRESULT SetTrackWeight(

    DWORD Track,
    FLOAT Weight
);

Parameters

Track
[in] Track to set the weight on.
Weight
[in] Weight.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationController::UnregisterAnimationSet Method

Remove an animation set from the animation mixer.

Syntax

HRESULT UnregisterAnimationSet(

    LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] The animation set to remove.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet Interface

This interface encapsulates an animation set.

ID3DXAnimationSet Members

GetInterpolatorByIndex | Gets an interpolator using an index into an array of interpolators.
GetInterpolatorByName | Gets an interpolator using its name to index it from an array of interpolators.
GetName | Gets the animation set name.
GetNumInterpolators | Gets the number of interpolators in the animation set.
GetPeriod | Gets the period of the animation set.

Remarks

An animation set consists of interpolators for many nodes for the same animation.

Interface Information

Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet::GetInterpolatorByIndex Method

Gets an interpolator using an index into an array of interpolators.

Syntax

HRESULT GetInterpolatorByIndex(

    UINT Index,
    LPD3DXINTERPOLATOR *ppInterpolator
);

Parameters

Index
[in] The index of the interpolater.
ppInterpolator
[out, retval] Returns a pointer to an interpolator.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

An animation set consists of a set of interpolators.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet::GetInterpolatorByName Method

Gets an interpolator using its name to index it from an array of interpolators.

Syntax

HRESULT GetInterpolatorByName(

    LPCSTR pName,
    LPD3DXINTERPOLATOR *ppInterpolator
);

Parameters

pName
[in] Name of the interpolater.
ppInterpolator
[out, retval] Returns a pointer to an interpolator.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

An animation set consists of a set of interpolators.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet::GetName Method

Gets the animation set name.

Syntax

LPCSTR GetName(VOID);

Return Value

The name of the animation set.

Remarks

An animation set consists of interpolators for many nodes of the same animation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet::GetNumInterpolators Method

Gets the number of interpolators in the animation set.

Syntax

UINT GetNumInterpolators(VOID);

Return Value

The number of interpolators, or key frames, in the animation set.

Remarks

An animation set consists of interpolators for many nodes of the same animation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXAnimationSet::GetPeriod Method

Gets the period of the animation set.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

The period of the animation set.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh Interface

Applications use the methods of the ID3DXBaseMesh interface to manipulate and query mesh and progressive mesh objects.

ID3DXBaseMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset

Draws a subset of a mesh.

GenerateAdjacency | Generates adjacency information based on mesh indices.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

GetDevice | Retrieves the device associated with the mesh.
GetFVF

Get the fixed function vertex value.

GetIndexBuffer

Retrieves the data in an index buffer.

GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces

Retrieves the number of faces in the mesh.

GetNumVertices

Retrieves the number of vertices in the mesh.

GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer

Retrieves the data in a vertex buffer.

LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

UnlockIndexBuffer

Unlocks an index buffer.

UnlockVertexBuffer

Unlocks a vertex buffer.

UpdateSemantics

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

The ID3DXBaseMesh interface, like all COM interfaces, inherits the IUnknown interface methods.

A mesh is an object made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh).

The LPD3DXBASEMESH type is defined as a pointer to the ID3DXBaseMesh interface.

typedef struct ID3DXBaseMesh *LPD3DXBASEMESH;

Interface Information

Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXMesh, ID3DXPMesh

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GenerateAdjacency Method

Generates adjacency information based on mesh indices.

Syntax

HRESULT GenerateAdjacency(

    FLOAT fEpsilon,
    DWORD* pAdjacency
);

Parameters

fEpsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft® Direct3D® device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetFVF Method

Get the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBuffer Interface

The ID3DXBuffer interface is used as a data buffer, storing vertex, adjacency, and material information during mesh optimization and loading operations. The buffer object is used to return arbitrary length data. Also, buffer objects are used to return object code and error messages in methods that assemble vertex and pixel shaders.

ID3DXBuffer Members

GetBufferPointer | Retrieves a pointer to the data in the buffer.
GetBufferSize | Retrieves the total size of the data in the buffer.

Remarks

The ID3DXBuffer interface is obtained by calling the D3DXCreateBuffer function.

The ID3DXBuffer interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods.

The LPD3DXBUFFER type is defined as a pointer to the ID3DXBuffer interface.

typedef struct ID3DXBuffer *LPD3DXBUFFER;

Interface Information

Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBuffer::GetBufferPointer Method

Retrieves a pointer to the data in the buffer.

Syntax

LPVOID GetBufferPointer(VOID);

Return Value

Returns a pointer to the data in the buffer.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBuffer::GetBufferSize Method

Retrieves the total size of the data in the buffer.

Syntax

DWORD GetBufferSize(VOID);

Return Value

Returns the total size of the data in the buffer, in bytes.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable Interface

The ID3DXConstantTable interface is used to access the constant table. This table contains the variables that are used by high-level language shaders and effects.

ID3DXConstantTable Members

GetBufferPointer | Gets a pointer to the buffer that contains the constant table.
GetBufferSize | Gets the buffer size of the constant table.
GetConstant | Gets a constant by looking up its index.
GetConstantByName | Gets a constant by looking up its name.
GetConstantDesc | Gets a pointer to the descriptions of constants in the constant table.
GetConstantElement | Gets a constant from an array of constants. An array is made up of elements.
GetDesc | Gets a description of the constant table.
SetBool | Sets a Boolean value.
SetBoolArray | Sets an array of Boolean values.
SetDefaults | Sets the constants to their default values. The default values are declared in the variable declarations in the shader.
SetFloat | Sets a floating-point number.
SetFloatArray | Sets an array of floating-point numbers.
SetInt | Sets an integer value.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a nontransposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to non-transposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetValue | Sets the contents of the buffer to the constant table.
SetVector | Sets a 4-D vector.
SetVectorArray | Sets an array of 4-D vectors.

Interface Information

Inherits from | IUnknown
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetBufferPointer Method

Gets a pointer to the buffer that contains the constant table.

Syntax

LPVOID GetBufferPointer(VOID);

Return Value

Returns a pointer the buffer.

See Also

ID3DXConstantTable::GetBufferSize

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetBufferSize Method

Gets the buffer size of the constant table.

Syntax

DWORD GetBufferSize(VOID);

Return Value

Returns the size of the buffer, in bytes.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetConstant Method

Gets a constant by looking up its index.

Syntax

D3DXHANDLE GetConstant(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
Index
[in] Zero-based index of the constant.

Return Value

Returns a unique identifier to the constant.

Remarks

To get a constant from an array of constants, use ID3DXConstantTable::GetConstantElement.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetConstantByName Method

Gets a constant by looking up its name.

Syntax

D3DXHANDLE GetConstantByName(

    D3DXHANDLE hConstant,
    LPCSTR pName
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pName
[in] Name of the constant.

Return Value

Returns a unique identifier to the constant.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetConstantDesc Method

Gets a pointer to the descriptions of constants in the constant table.

Syntax

HRESULT GetConstantDesc(

    D3DXHANDLE hConstant,
    D3DXCONSTANT_DESC* pDesc,
    UINT* pCount
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pDesc
[in, out] Returns a pointer to an array of descriptions. See D3DXCONSTANT_DESC.
pCount
[in, out] The input suppiled must be the maximum size of the array. The output is the number of elements that are filled in the array when the function returns.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Since samplers can appear more than once in a constant table, this method can return an array of descriptions, each one with a different register index.

See Also

ID3DXConstantTable::GetDesc

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetConstantElement Method

Gets a constant from an array of constants. An array is made up of elements.

Syntax

D3DXHANDLE GetConstantElement(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] Unique identifier to the array of constants. This value may not be NULL.
Index
[in] Zero-based index of the element in the array.

Return Value

Returns a unique identifier to the element constant.

Remarks

To get a constant that is not part of an array, use ID3DXConstantTable::GetConstant or ID3DXConstantTable::GetConstantByName.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::GetDesc Method

Gets a description of the constant table.

Syntax

HRESULT GetDesc(

    D3DXCONSTANTTABLE_DESC* pDesc
);

Parameters

pDesc
[in] Description of the constant table. See D3DXCONSTANTTABLE_DESC.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXConstantTable::GetConstantDesc

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetBool Method

Sets a Boolean value.

Syntax

HRESULT SetBool(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    BOOL b
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the parameter is a top-level parameter (there is no parent data structure), use NULL.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST BOOL* pB,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the array is a top-level parameter (there is no parent data structure), use NULL.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetDefaults Method

Sets the constants to their default values. The default values are declared in the variable declarations in the shader.

Syntax

HRESULT SetDefaults(

    LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetFloat Method

Sets a floating-point number.

Syntax

HRESULT SetFloat(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    FLOAT f
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the parameter is a top-level parameter (there is no parent data structure), use NULL.
f
[in] Floating-point number.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetFloatArray Method

Sets an array of floating-point numbers.

Syntax

HRESULT SetFloatArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the array is a top-level parameter (there is no parent data structure), use NULL.
pf
[in] Array of floating-point numbers.
Count
[in] Number of floating-point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetInt Method

Sets an integer value.

Syntax

HRESULT SetInt(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    INT n
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the integer is a top-level parameter (there is no parent data structure), use NULL.
n
[in] Integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST INT* pn,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the array is a top-level parameter (there is no parent data structure), use NULL.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrix Method

Sets a nontransposed matrix.

Syntax

HRESULT SetMatrix(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the matrix is a top-level parameter (there is no parent data structure), use NULL.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the matrix is a top-level parameter (there is no parent data structure), use NULL.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrixPointerArray Method

Sets an array of pointers to non-transposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to non-transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the matrix is a top-level parameter (there is no parent data structure), use NULL.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the matrix is a top-level parameter (there is no parent data structure), use NULL.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetValue Method

Sets the contents of the buffer to the constant table.

Syntax

HRESULT SetValue(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    LPCVOID pData,
    UINT Bytes
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the value is a top-level parameter (there is no parent data structure), use NULL.
pData
[in] Buffer containing data.
Bytes
[in] Size of the buffer, in bytes.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetVector Method

Sets a 4-D vector.

Syntax

HRESULT SetVector(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the vector is a top-level parameter (there is no parent data structure), use NULL.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXConstantTable::SetVectorArray Method

Sets an array of 4-D vectors.

Syntax

HRESULT SetVectorArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the parent data structure. If the array is a top-level parameter (there is no parent data structure), use NULL.
pVector
[in] Array of 4-D vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont Interface

The ID3DXFont interface is used to encapsulate the textures and resources needed to render a specific font on a specific device.

ID3DXFont Members

Begin

Prepares a device for drawing text.

DrawText

Draws formatted text. This method supports ANSI and Unicode strings.

End

Restores the device state to how it was when ID3DXFont::Begin was called.

GetDevice

Retrieves the Microsoft® Direct3D® device associated with the font object.

GetLogFont

Retrieves the attributes of the font.

OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

OnResetDevice

Should be called after the device has been reset.

Remarks

The ID3DXFont interface is obtained by calling the D3DXCreateFont or D3DXCreateFontIndirect functions.

The ID3DXFont interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods.

The LPD3DXFONT type is defined as a pointer to the ID3DXFont interface.

typedef interface ID3DXFont *LPD3DXFONT;

Interface Information

Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::Begin Method

Prepares a device for drawing text.

Syntax

HRESULT Begin(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This method is optional. If a DrawText method is called outside of a Begin and ID3DXFont::End pair, then Microsoft® Direct3D® will call Begin and End.

See Also

ID3DXFont::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::DrawText Method

Draws formatted text. This method supports ANSI and Unicode strings.

Syntax

INT DrawText(

    LPCSTR pString,
    INT Count,
    LPRECT pRect,
    DWORD Format,
    D3DCOLOR Color
);

Parameters

pString
[in] Pointer to a string to draw. This parameter supports ANSI and Unicode text strings. If UNICODE or _UNICODE is defined, the string must be of type LPCWSTR, otherwise, the string must be of type LPCSTR.

If the Count parameter is -1, the string must be null-terminated.

If Format includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.
Count
[in] Specifies the number of characters in the string. If Count is -1, then the pString parameter is assumed to be a pointer to a null-terminated string and ID3DXFont::DrawText computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values.
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, ID3DXFont::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DXFont::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DXFont::DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EDITCONTROL
Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS or DT_PATH_ELLIPSIS

Truncates the string without adding ellipses so that the result fits in the specified rectangle. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Specify DT_END_ELLIPSIS to truncate characters at the end of the string, or DT_PATH_ELLIPSIS to truncate characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much of the text as possible after the last backslash.

DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
DT_EXTERNALLEADING
Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_HIDEPREFIX
Microsoft® Windows® 2000: Ignores the ampersand prefix character in the text. The letter that follows is not underlined, but other mnemonic-prefix characters are still processed.

Example:

input string: "A&bc&&d"

normal: "A&d"

HIDEPREFIX: "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.

DT_INTERNAL
Uses the system font to calculate text metrics.
DT_LEFT
Aligns text to the left.
DT_MODIFYSTRING
Modifies the string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.
DT_NOCLIP
Draws without clipping. ID3DXFont::DrawText is somewhat faster when DT_NOCLIP is used.
DT_NOFULLWIDTHCHARBREAK
Windows 98, Windows 2000: Prevents a line break at a double-byte character set (DBCS), so that the line-breaking rule is equivalent to a single-byte character set (SBCS). For example, this can be used in Korean windows for more readability of icon labels. This is effective only if DT_WORDBREAK is specified.
DT_NOPREFIX
Turns off processing of prefix characters. Normally, ID3DXFont::DrawText interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. Compare with DT_HIDEPREFIX and DT_PREFIXONLY.
DT_PREFIXONLY
Windows 2000: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any character in the string.
DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bi-directional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TABSTOP
Sets tab stops. Bits 15 –8 (high-order byte of the low-order word) of the Format parameter specify the number of characters for each tab. The default number of characters per tab is eight. The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.
DT_TOP
Top-justifies text (single line only).
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
DT_WORD_ELLIPSIS
Truncates text that does not fit in the rectangle and adds ellipses.
Color
[in] Color of the text. For more information, see D3DCOLOR.

Return Value

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from lpRect->top to the bottom of the drawn text.

If the function fails, the return value is zero.

Remarks

This function supports both ANSI and Unicode strings.

This method must be called inside a IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene block.

Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font.

This method method supports only fonts whose escapement and orientation are both zero.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::End Method

Restores the device state to how it was when ID3DXFont::Begin was called.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXFont::Begin

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::GetDevice Method

Retrieves the Microsoft® Direct3D® device associated with the font object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the font object.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL can be returned if the parameter is invalid.

Remarks

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::GetLogFont Method

Retrieves the attributes of the font.

Syntax

HRESULT GetLogFont(

    LOGFONT *pLogFont
);

Parameters

pLogFont
[in, out] Pointer to the returned LOGFONT structure, describing the attributes of the font.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL can be returned if the parameter is invalid.

Remarks

For more information about the LOGFONT structure, see the Microsoft® Platform Software Development Kit (SDK).

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXFont::OnResetDevice method called.

See Also

ID3DXFont::OnResetDevice

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFont::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method should be called after the device has been reset, before any other methods are called.

See Also

ID3DXFont::OnLostDevice

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker Interface

The ID3DXFragmentLinker interface is used to link shader fragments at runtime.

ID3DXFragmentLinker Members

AddFragments | Add the fragments from a buffer to the fragment linker.
ClearCache | Clear the fragment linker cache.
GetAllFragments | Create a buffer containing the linker fragments. Suitable for saving to disk.
GetDevice | Get the device.
GetFragment | Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.
GetFragmentDesc | Get the D3DXFRAGMENT_DESC structure which describes the named fragment.
GetFragmentHandleByIndex | Get a fragment handle by index.
GetFragmentHandleByName | Get a fragment handle by name.
GetNumberOfFragments | Get the number of fragments in the linker.
LinkShader | Link a compiled shader at runtime. This is a very lightweight operation.
LinkVertexShader | Link a compiled vertex shader at runtime. This is a very lightweight operation.

Interface Information

Inherits from | IUnknown
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::AddFragments Method

Add the fragments from a buffer to the fragment linker.

Syntax

HRESULT AddFragments(

    CONST DWORD* pFragments
);

Parameters

pFragments
[in] Pointer to a buffer containing shader fragments. See D3DXGatherFragments.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_DUPLICATENAMEDFRAGMENT | Multiple fragments with the same name were found. No fragments were added.
E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::ClearCache Method

Clear the fragment linker cache.

Syntax

HRESULT ClearCache(VOID);

Return Value

This method always returns the value S_OK.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetAllFragments Method

Create a buffer containing the linker fragments. Suitable for saving to disk.

Syntax

HRESULT GetAllFragments(

    LPD3DXBUFFER* ppBuffer
);

Parameters

ppBuffer
[out] Returns a buffer containing compiled shader fragments. See ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetDevice Method

Get the device.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Get a pointer to the IDirect3DDevice9 object, which represents the device.

Return Value

This method always returns the value S_OK.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetFragment Method

Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.

Syntax

HRESULT GetFragment(

    D3DXHANDLE Name,
    LPD3DXBUFFER* ppBuffer
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
ppBuffer
[out] Returns a buffer containing a compiled shader fragment. See ID3DXBuffer.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value can be E_OUTOFMEMORY.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetFragmentDesc Method

Get the D3DXFRAGMENT_DESC structure which describes the named fragment.

Syntax

HRESULT GetFragmentDesc(

    D3DXHANDLE Name,
    LPD3DXFRAGMENT_DESC FragDesc
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
FragDesc
[in] Returns a description of the fragment. See D3DXFRAGMENT_DESC.

Return Value

This method always returns the value S_OK.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetFragmentHandleByIndex Method

Get a fragment handle by index.

Syntax

D3DXHANDLE GetFragmentHandleByIndex(

    UINT Index
);

Parameters

Index
[in] Zero-based index for the fragment.

Return Value

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the name was found.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetFragmentHandleByName Method

Get a fragment handle by name.

Syntax

D3DXHANDLE GetFragmentHandleByName(

    LPCSTR Name
);

Parameters

Name
[in] Fragment name.

Return Value

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the name was found.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::GetNumberOfFragments Method

Get the number of fragments in the linker.

Syntax

UINT GetNumberOfFragments(VOID);

Return Value

Returns the number of fragments.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::LinkShader Method

Link a compiled shader at runtime. This is a very lightweight operation.

Syntax

HRESULT LinkShader(

    LPCSTR Target,
    DWORD Flags,
    LPD3DXHANDLE rgFragmentHandles,
    UINT cFragments,
    LPD3DXBUFFER* ppBuffer,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

Target
[in] Vertex shader compile target. A compile target consists of the type of shader and the shader version number. Valid targets are vs_1_1, vs_2_0, vs_2_x and vs_2_sw.
Flags
[in] Link options. See D3DXSHADER.
rgFragmentHandles
[in] Unique identifier to the fragments. See Handles.
cFragments
[in] Number of fragments to be linked.
ppBuffer
[out] Pointer to a buffer that contains compiled shader code. See ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXFragmentLinker::LinkVertexShader Method

Link a compiled vertex shader at runtime. This is a very lightweight operation.

Syntax

HRESULT LinkVertexShader(

    LPCSTR Target,
    DWORD Flags,
    LPD3DXHANDLE rgFragmentHandles,
    UINT cFragments,
    LPDIRECT3DVERTEXSHADER9* pVShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

Target
[in] Vertex shader compile target. A compile target consists of the type of shader and the shader version number. Valid targets are vs_1_1, vs_2_0, vs_2_x and vs_2_sw.
Flags
[in] Link options. See D3DXSHADER.
rgFragmentHandles
[in] Unique identifier to the fragments. See Handles.
cFragments
[in] Number of fragments to be linked.
pVShader
[out] Pointer to a vertex shader. See IDirect3DVertexShader9.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInterpolator Interface

This interface defines a scale, rotate, and translate (SRT) interpolator.

ID3DXInterpolator Members

GetLastSRT | Returns the previous scale, rotation, and translation values.
GetName | Gets the name of the interpolator.
GetPeriod | Gets the interpolator period.
GetSRT | Returns the scale, rotation, and translation at a given time.

Remarks

This is an abstract interface. ID3DXKeyFrameInterpolator inherits from this. An application can implement this for custom SRT interpolator.

Interface Information

Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInterpolator::GetLastSRT Method

Returns the previous scale, rotation, and translation values.

Syntax

HRESULT GetLastSRT(

    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotate,
    D3DXVECTOR3 *pTranslate
);

Parameters

pScale
[in] Returns the scale vector.
pRotate
[in] Returns the rotation quaternion.
pTranslate
[in] Returns the translate vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInterpolator::GetName Method

Gets the name of the interpolator.

Syntax

LPCSTR GetName(VOID);

Return Value

Returns a pointer to the name that identifies the interpolator.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInterpolator::GetPeriod Method

Gets the interpolator period.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

The value of the interpolator period.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInterpolator::GetSRT Method

Returns the scale, rotation, and translation at a given time.

Syntax

HRESULT GetSRT(

    DOUBLE Time,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotate,
    D3DXVECTOR3 *pTranslate
);

Parameters

Time
[in] Time at which the interpolator should be queried.
pScale
[in] Returns the scale vector.
pRotate
[in] Returns the rotation quaternion.
pTranslate
[in] Returns the translate vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator Interface

This interface implements an interpolator.

ID3DXKeyFrameInterpolator Members

GetLastSRT | Returns the previous scale, rotation, and translation values.
GetName | Gets the name of the interpolator.
GetNumRotationKeys | Returns the number of rotation key frames.
GetNumScaleKeys | Returns the number of scale key frames.
GetNumTranslationKeys | Returns the number of translation key frames.
GetPeriod | Gets the interpolator period.
GetRotationKeys | Returns an array of rotation values.
GetScaleKeys | Returns an array of scale values.
GetSourceTicksPerSecond | Returns the time scale factor passed to D3DXCreateKeyFrameInterpolator. This value is used to scale local time to global (or application) time.
GetSRT | Returns the scale, rotation, and translation at a given time.
GetTranslationKeys | Returns an array of translation vectors.

Remarks

Interpolators are the basic building blocks for animation. Each interpolator defines the scale, rotate, and translation values at a unique point in time. Scale and rotation values are stored as vectors, rotations are stored as quaternions.

Interface Information

Inherits from | ID3DXInterpolator
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetNumRotationKeys Method

Returns the number of rotation key frames.

Syntax

UINT GetNumRotationKeys(VOID);

Return Value

The number of rotation keys contained in the array of rotation keys.

Remarks

An interpolator defines the scale, rotate, and translation values in a matrix for a single key frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetNumScaleKeys Method

Returns the number of scale key frames.

Syntax

UINT GetNumScaleKeys(VOID);

Return Value

The number of scale keys contained in the array of scale keys.

Remarks

An interpolator defines the scale, rotate, and translation values in a matrix for a single key frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetNumTranslationKeys Method

Returns the number of translation key frames.

Syntax

UINT GetNumTranslationKeys(VOID);

Return Value

The number of translation keys contained in the array of translation keys.

Remarks

An interpolator defines the scale, rotate, and translation values in a matrix for a single key frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetRotationKeys Method

Returns an array of rotation values.

Syntax

HRESULT GetRotationKeys(

    LPD3DXKEY_QUATERNION pKeys
);

Parameters

pKeys
[out, retval] Returns an array of LPD3DXKEY_QUATERNION values. Each quaternion contains the rotation values at a single key frame.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetScaleKeys Method

Returns an array of scale values.

Syntax

HRESULT GetScaleKeys(

    LPD3DXKEY_VECTOR3 pKeys
);

Parameters

pKeys
[out, retval] Returns an array of LPD3DXKEY_VECTOR3 values. Each vector contains the scale values at a single key frame.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetSourceTicksPerSecond Method

Returns the time scale factor passed to D3DXCreateKeyFrameInterpolator. This value is used to scale local time to global (or application) time.

Syntax

DOUBLE GetSourceTicksPerSecond(VOID);

Return Value

The time scaling factor.

Remarks

An interpolator defines the scale, rotate, and translation values in a matrix for a single key frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetTranslationKeys Method

Returns an array of translation vectors.

Syntax

HRESULT GetTranslationKeys(

    LPD3DXKEY_VECTOR3 pKeys
);

Parameters

pKeys
[out, retval] Returns an array of LPD3DXKEY_VECTOR3 values. Each vector contains a translation vector at a single key frame.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine Interface

The ID3DXLine interface implements line drawing using textured triangles.

ID3DXLine Members

Begin

Prepares a device for drawing lines.

Draw

Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.

DrawTransform

Draws a line strip in screen space with a specified input transformation matrix.

End

Restores the device state to how it was when ID3DXLine::Begin was called.

GetAntialias

Get the line antialiasing state.

GetDevice

Retrieves the Microsoft® Direct3D® device associated with the line object.

GetGLLines

Get the OpenGL-style line-drawing mode.

GetPattern

Get the line stipple pattern.

GetPatternScale

Get the stipple-pattern scale value.

GetWidth

Get the thickness of the line.

OnLostDevice

Releases all references to video memory resources and deletes all state blocks.

OnResetDevice

Should be called after the device has been reset.

SetAntialias

Toggles line antialiasing.

SetGLLines

Toggles the mode to draw OpenGL-style lines.

SetPattern

Applies a stipple pattern to the line.

SetPatternScale

Stretches the stipple pattern along the line direction.

SetWidth

Specifies the thickness of the line.

Interface Information

Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::Begin Method

Prepares a device for drawing lines.

Syntax

HRESULT Begin(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Calling Begin is optional. If called outside of a Begin/ID3DXLine::End sequence, the draw functions will internally call Begin and End. To avoid extra overhead, this method should be used if more than one draw function will be called successively.

This method must be called from inside an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene sequence.

Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::Draw Method

Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.

Syntax

HRESULT Draw(

    CONST D3DXVECTOR2* pVertexList,
    DWORD dwVertexListCount,
    D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR2.
dwVertexListCount
[in] Number of vertices in the vertex list.
Color
[in] Color of the line. See D3DCOLOR.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::DrawTransform Method

Draws a line strip in screen space with a specified input transformation matrix.

Syntax

HRESULT DrawTransform(

    CONST D3DXVECTOR3* pVertexList,
    DWORD dwVertexListCount,
    CONST D3DXMATRIX* pTransform,
    D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR3.
dwVertexListCount
[in] Number of vertices in the vertex list.
pTransform
[in] A scale, rotate, and translate (SRT) matrix for transforming the points. See D3DXMATRIX. If this matrix is a projection matrix, any stippled lines will be drawn with a perspective-correct stippling pattern. Or, you can transform the vertices and use ID3DXLine::Draw to draw the line with a nonperspective-correct stipple pattern.
Color
[in] Color of the line. See D3DCOLOR.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::End Method

Restores the device state to how it was when ID3DXLine::Begin was called.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

ID3DXLine::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

See Also

ID3DXLine::Begin

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetAntialias Method

Get the line antialiasing state.

Syntax

BOOL GetAntialias(VOID);

Return Value

Returns the antialiasing switch value. TRUE means antialiasing is on, and FALSE means antialiasing is off.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetDevice Method

Retrieves the Microsoft® Direct3D® device associated with the line object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the line object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetGLLines Method

Get the OpenGL-style line-drawing mode.

Syntax

BOOL GetGLLines(VOID);

Return Value

Returns TRUE if OpenGL-style lines are enabled, and FALSE if Microsoft® Direct3D®-style lines are enabled.

See Also

ID3DXLine::SetGLLines

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetPattern Method

Get the line stipple pattern.

Syntax

DWORD GetPattern(VOID);

Return Value

Returns the line stipple pattern: 1 is opaque, 0 is transparent.

See Also

ID3DXLine::SetPattern

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetPatternScale Method

Get the stipple-pattern scale value.

Syntax

FLOAT GetPatternScale(VOID);

Return Value

Returns the value used to scale the stipple-pattern. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

See Also

ID3DXLine::SetPatternScale

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::GetWidth Method

Get the thickness of the line.

Syntax

FLOAT GetWidth(VOID);

Return Value

The line thickness.

See Also

ID3DXLine::SetWidth

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::OnLostDevice Method

Releases all references to video memory resources and deletes all state blocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXLine::OnResetDevice method called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::SetAntialias Method

Toggles line antialiasing.

Syntax

HRESULT SetAntialias(

    BOOL bAntiAlias
);

Parameters

bAntiAlias
[in] Toggles antialiasing on and off. TRUE turns antialiasing on, and FALSE turns antialiasing off.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXLine::GetAntialias

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::SetGLLines Method

Toggles the mode to draw OpenGL-style lines.

Syntax

HRESULT SetGLLines(

    BOOL bGLLines
);

Parameters

bGLLines
[in] Toggles OpenGL-style line drawing. TRUE enables OpenGL-style lines, and FALSE enables Microsoft® Direct3D®-style lines.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::SetPattern Method

Applies a stipple pattern to the line.

Syntax

HRESULT SetPattern(

    DWORD dwPattern
);

Parameters

dwPattern
[in] Describes the stipple pattern: 1 is opaque, 0 is transparent.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::SetPatternScale Method

Stretches the stipple pattern along the line direction.

Syntax

HRESULT SetPatternScale(

    FLOAT fPatternScale
);

Parameters

fPatternScale
[in] Stipple pattern scaling value. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLine::SetWidth Method

Specifies the thickness of the line.

Syntax

HRESULT SetWidth(

    FLOAT fWidth
);

Parameters

fWidth
[in] Describes the line width.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLoadUserData Interface

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXLoadMeshHierarchyFromX, and Direct3D extensions (D3DX) calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXLoadUserData::LoadFrameChildData is called and passed the child data.

ID3DXLoadUserData Members

LoadFrameChildData | Load frame child data from an .x file.
LoadMeshChildData | Load top level data from an .x file.
LoadTopLevelData | Load top level data from an .x file.

Interface Information

Inherits from | Nothing
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLoadUserData::LoadFrameChildData Method

Load frame child data from an .x file.

Syntax

HRESULT LoadFrameChildData(

    LPD3DXFRAME pFrame,
    LPDIRECTXFILEDATA pXofChildData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofChildData
[in] Pointer to an .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLoadUserData::LoadMeshChildData Method

Load top level data from an .x file.

Syntax

HRESULT LoadMeshChildData(

    LPD3DXMESHCONTAINER pMeshContainer,
    LPDIRECTXFILEDATA pXofChildData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofChildData
[in] Pointer to an .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXLoadUserData::LoadTopLevelData Method

Load top level data from an .x file.

Syntax

HRESULT LoadTopLevelData(

    LPDIRECTXFILEDATA pXofChildData
);

Parameters

pXofChildData
[in] Pointer to an .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack Interface

Applications use the methods of the ID3DXMatrixStack interface to manipulate a matrix stack.

ID3DXMatrixStack Members

GetTop

Retrieves the current matrix at the top of the stack.

LoadIdentity

Loads identity in the current matrix.

LoadMatrix

Loads the given matrix into the current matrix.

MultMatrix

Determines the product of the current matrix and the given matrix.

MultMatrixLocal

Determines the product of the given matrix and the current matrix.

Pop

Removes the current matrix from the top of the stack.

Push

Adds a matrix to the stack.

RotateAxis

Determines the product of the current matrix and the computed rotation matrix.

RotateAxisLocal

Determines the product of the computed rotation matrix and the current matrix.

RotateYawPitchRoll

Determines the product of the current matrix and the computed rotation matrix (composed of a given yaw, pitch, and roll).

RotateYawPitchRollLocal

Determines the product of the computed rotation matrix (composed of a given yaw, pitch, and roll) and the current matrix.

Scale

Determines the product of the current matrix and the computed scale matrix composed from the given point (x, y, and z).

ScaleLocal

Determines the product of the computed scale matrix composed from the given point (x, y, and z) and the current matrix.

Translate

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

TranslateLocal

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Remarks

The ID3DXMatrixStack interface is obtained by calling the D3DXCreateMatrixStack function.

The ID3DXMatrixStack interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods.

Interface Information

Inherits from | IUnknown
Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::GetTop Method

Retrieves the current matrix at the top of the stack.

Syntax

D3DXMATRIX *GetTop(VOID);

Return Value

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.

See Also

ID3DXMatrixStack::Pop, ID3DXMatrixStack::Push

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::LoadIdentity Method

Loads identity in the current matrix.

Syntax

HRESULT LoadIdentity(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

See Also

ID3DXMatrixStack::LoadMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::LoadMatrix Method

Loads the given matrix into the current matrix.

Syntax

HRESULT LoadMatrix(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the supplied matrix.

See Also

ID3DXMatrixStack::LoadIdentity

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::MultMatrix Method

Determines the product of the current matrix and the given matrix.

Syntax

HRESULT MultMatrix(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).

m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);

This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.

See Also

ID3DXMatrixStack::MultMatrixLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::MultMatrixLocal Method

Determines the product of the given matrix and the current matrix.

Syntax

HRESULT MultMatrixLocal(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).

m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];

This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.

See Also

ID3DXMatrixStack::MultMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::Pop Method

Removes the current matrix from the top of the stack.

Syntax

HRESULT Pop(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Push

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::Push Method

Adds a matrix to the stack.

Syntax

HRESULT Push(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Pop

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::RotateAxis Method

Determines the product of the current matrix and the computed rotation matrix.

Syntax

HRESULT RotateAxis(

    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pV
[in] Pointer to a D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the current world origin).

    D3DXMATRIX tmp;
    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::RotateAxisLocal Method

Determines the product of the computed rotation matrix and the current matrix.

Syntax

HRESULT RotateAxisLocal(

    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pV
[in] Pointer to a D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the local origin of the object).

    D3DXMATRIX tmp;
    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::RotateYawPitchRoll Method

Determines the product of the current matrix and the computed rotation matrix (composed of a given yaw, pitch, and roll).

Syntax

HRESULT RotateYawPitchRoll(

    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the current world origin.

    D3DXMATRIX tmp;
    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRollLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::RotateYawPitchRollLocal Method

Determines the product of the computed rotation matrix (composed of a given yaw, pitch, and roll) and the current matrix.

Syntax

HRESULT RotateYawPitchRollLocal(

    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the local origin of the object.

    D3DXMATRIX tmp;
    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::Scale Method

Determines the product of the current matrix and the computed scale matrix composed from the given point (x, y, and z).

Syntax

HRESULT Scale(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix (transformation is about the current world origin).

    D3DXMATRIX tmp;
    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::ScaleLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::ScaleLocal Method

Determines the product of the computed scale matrix composed from the given point (x, y, and z) and the current matrix.

Syntax

HRESULT ScaleLocal(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix (transformation is about the local origin of the object).

    D3DXMATRIX tmp;
    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::Scale

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::Translate Method

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

Syntax

HRESULT Translate(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).

    D3DXMATRIX tmp;
    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::TranslateLocal

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMatrixStack::TranslateLocal Method

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Syntax

HRESULT TranslateLocal(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).

    D3DXMATRIX tmp;
    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::Translate

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh Interface

Applications use the methods of the ID3DXMesh interface to manipulate mesh objects.

ID3DXMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset

Draws a subset of a mesh.

GenerateAdjacency | Generates adjacency information based on mesh indices.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

GetDevice | Retrieves the device associated with the mesh.
GetFVF

Get the fixed function vertex value.

GetIndexBuffer

Retrieves the data in an index buffer.

GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces

Retrieves the number of faces in the mesh.

GetNumVertices

Retrieves the number of vertices in the mesh.

GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer

Retrieves the data in a vertex buffer.

LockAttributeBuffer

Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.

LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Optimize | Controls the reordering of mesh faces and vertices to optimize performance, generating an output mesh.
OptimizeInplace | Controls the reordering of mesh faces and vertices to optimize performance.
SetAttributeTable

UnlockAttributeBuffer

Unlocks an attribute buffer.

UnlockIndexBuffer

Unlocks an index buffer.

UnlockVertexBuffer

Unlocks a vertex buffer.

UpdateSemantics

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

To obtain the ID3DXMesh interface, call either the D3DXCreateMesh or D3DXCreateMeshFVF function.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

This interface, like all Component Object Model (COM) interfaces, inherits additional functionality from the IUnknown interface.

The LPD3DXMESH type is defined as a pointer to the ID3DXMesh interface.

typedef struct ID3DXMesh *LPD3DXMESH;

Interface Information

Inherits from | ID3DXBaseMesh
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::LockAttributeBuffer Method

Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.

Syntax

HRESULT LockAttributeBuffer(

    DWORD Flags,
    DWORD** ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out] Address of a pointer to a buffer containing the mesh attribute data. The array is an array of D3DXATTRIBUTERANGE elements that describe the mesh vertices and edges.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If ID3DXMesh::Optimize has been called, the mesh attribute buffer will contain an attribute table.

See Also

ID3DXMesh::UnlockAttributeBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::Optimize Method

Controls the reordering of mesh faces and vertices to optimize performance, generating an output mesh.

Syntax

HRESULT Optimize(

    DWORD Flags,
    CONST DWORD *pAdjacencyIn,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    LPD3DXMESH *ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH32_BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[in, out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method is very similar to the ID3DXBaseMesh::CloneMesh method, except that it can perform optimization while generating the new clone of the mesh.

The output mesh inherits all of the creation parameters of the input mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::OptimizeInplace Method

Controls the reordering of mesh faces and vertices to optimize performance.

Syntax

HRESULT OptimizeInplace(

    DWORD Flags,
    CONST DWORD *pAdjacencyIn,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap
);

Parameters

Flags
[in] Combination of one or more D3DXMESHOPT flags, specifying the type of optimization to perform.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. If the value supplied for this argument is NULL, adjacency data is not returned.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface containing the new index for each vertex. If the value supplied for this argument is NULL, vertex remap data is not returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Note This method will fail if the mesh is sharing its vertex buffer with another mesh, unless the D3DXMESHOPT_IGNOREVERTS flag is set in the Flags parameter.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::SetAttributeTable Method

Syntax

HRESULT SetAttributeTable(

    CONST D3DXATTRIBUTERANGE * pAttribTable,
    DWORD cAttribTableSize
);

Parameters

pAttribTable
[in] Pointer to the attribute table. The attribute table is an array of attributes, of type D3DXATTRIBUTERANGE.
cAttribTableSize
[in] Number of attributes in the attribute table.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If an application keeps track of the information in an attributes table, and rearranges the table as a result of changes to attributes or faces, this method allows the application to update the attributes tables instead of calling ID3DXMesh::Optimize again.

See Also

ID3DXMesh::LockAttributeBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::UnlockAttributeBuffer Method

Unlocks an attribute buffer.

Syntax

HRESULT UnlockAttributeBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXMesh::LockAttributeBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh Interface

This interface encapsulates patch mesh functionality.

ID3DXPatchMesh Members

CloneMesh | Creates a new patch mesh with the specified vertex declaration.
GenerateAdjacency | Generates adjacency information based on mesh indices.
GetControlVerticesPerPatch | Gets the number of control vertices per patch.
GetDeclaration | Gets the vertex declaration.
GetDevice | Gets the device that created the mesh.
GetDisplaceParam | Gets mesh geometry displacement parameters.
GetIndexBuffer | Gets the mesh index buffer.
GetNumPatches | Gets the number of patches in the mesh.
GetOptions | Gets the type of patch.
GetPatchInfo | Gets the attributes of the patch.
GetTessSize | Gets the size of the tessellated mesh, given a tessellation level.
GetVertexBuffer | Gets the mesh vertex buffer.
LockAttributeBuffer | Lock the attribute buffer.
LockIndexBuffer | Lock the index buffer.
LockVertexBuffer | Lock the vertex buffer.
Optimize | Optimizes the patch mesh for efficient tessellation.
SetDisplaceParam | Sets mesh geometry displacement parameters.
Tessellate | Performs uniform tessellation based on the tessellation level.
TessellateAdaptive | Performs adaptive tessellation based on the z-based adaptive tessellation criterion.
UnlockAttributeBuffer | Unlock the attribute buffer.
UnlockIndexBuffer | Unlock the index buffer.
UnlockVertexBuffer | Unlock the vertex buffer.

Remarks

A patch mesh is a mesh that consists of a series of patches.

To obtain the ID3DXPatchMesh interface, call the D3DXCreatePatchMesh function.

The LPD3DXPATCHMESH type is defined as a pointer to the ID3DXPatchMesh interface, as follows:

typedef struct ID3DXPatchMesh *LPD3DXPATCHMESH;

Interface Information

Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetControlVerticesPerPatch Method

Gets the number of control vertices per patch.

Syntax

DWORD GetControlVerticesPerPatch(VOID);

Return Value

The number of control vertices per patch.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetDeclaration Method

Gets the vertex declaration.

Syntax

HRESULT GetDeclaration(

    LPD3DVERTEXELEMENT9 pDeclaration
);

Parameters

pDeclaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetDevice Method

Gets the device that created the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Pointer to the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetDisplaceParam Method

Gets mesh geometry displacement parameters.

Syntax

HRESULT GetDisplaceParam(

    LPDIRECT3DBASETEXTURE9* Texture,
    D3DTEXTUREFILTERTYPE* MinFilter,
    D3DTEXTUREFILTERTYPE* MagFilter,
    D3DTEXTUREFILTERTYPE* MipFilter,
    D3DTEXTUREADDRESS* Wrap,
    DWORD* dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS.
dwLODBias
[in] Level of detail bias value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Displacement maps can only be 2-D textures. Mipmapping is ignored for nonadaptive tessellation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetIndexBuffer Method

Gets the mesh index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Pointer to the index buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The index buffer contains the vertex ordering in the vertex buffer. The index buffer is used to access the vertex buffer when the mesh is rendered.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetNumPatches Method

Gets the number of patches in the mesh.

Syntax

DWORD GetNumPatches(VOID);

Return Value

The number of patches.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetOptions Method

Gets the type of patch.

Syntax

DWORD GetOptions(VOID);

Return Value

The patch type.

Remarks

For more information about patch types, see D3DXPATCHMESHTYPE.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetPatchInfo Method

Gets the attributes of the patch.

Syntax

HRESULT GetPatchInfo(

    LPD3DXPATCHINFO PatchInfo
);

Parameters

PatchInfo
[out, retval] Pointer to the structures containing the patch attributes. For more information about patch attributes, see D3DXPATCHINFO.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetTessSize Method

Gets the size of the tessellated mesh, given a tessellation level.

Syntax

HRESULT GetTessSize(

    FLOAT fTessLevel,
    DWORD Adaptive,
    DWORD *NumTriangles,
    DWORD *NumVertices
);

Parameters

fTessLevel
[in] Tessellation level.
Adaptive
[in] Adaptive tessellation. For adaptive tessellation, set this value to TRUE and set fTessLevel to the maximum tessellation value. This will result in the maximum mesh size necessary for adaptive tessellation.
NumTriangles
[out] Pointer to the number of triangles generated by the tessellated mesh.
NumVertices
[out] Pointer to the number of vertices generated by the tessellated mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method assumes uniform tessellation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GetVertexBuffer Method

Gets the mesh vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out] Pointer to the vertex buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method assumes uniform tessellation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::LockAttributeBuffer Method

Lock the attribute buffer.

Syntax

HRESULT LockAttributeBuffer(

    DWORD Flags,
    DWORD **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] Returns a pointer that contains a pointer to the locked buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::LockIndexBuffer Method

Lock the index buffer.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a memory buffer containing the returned index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading. Patch mesh index buffers are 16-bit buffers.

See Also

D3DXCreatePatchMesh

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::LockVertexBuffer Method

Lock the vertex buffer.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a memory buffer containing the returned vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.

Patch meshes use 16-bit index buffers.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::Optimize Method

Optimizes the patch mesh for efficient tessellation.

Syntax

HRESULT Optimize(

    DWORD Flags
);

Parameters

Flags
[in] Currently unused.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function performs one-time optimization for patch meshes that need to be tessellated repeatedly by calling the Tessellate method. The optimization performed is independent of the actual tessellation level used. If vertices are changed, this method must be called again.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::SetDisplaceParam Method

Sets mesh geometry displacement parameters.

Syntax

HRESULT SetDisplaceParam(

    LPDIRECT3DBASETEXTURE9 Texture,
    D3DTEXTUREFILTERTYPE MinFilter,
    D3DTEXTUREFILTERTYPE MagFilter,
    D3DTEXTUREFILTERTYPE MipFilter,
    D3DTEXTUREADDRESS Wrap,
    DWORD dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS
dwLODBias
[in] Level of detail bias value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Displacement maps can only be 2-D textures. Mipmapping is ignored for nonadaptive tessellation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::Tessellate Method

Performs uniform tessellation based on the tessellation level.

Syntax

HRESULT Tessellate(

    FLOAT fTessLevel,
    LPD3DXMESH pMesh
);

Parameters

fTessLevel
[in] Tessellation level. This is the number of vertices introduced between existing vertices. The range of this float parameter is 0 < fTessLevel <= 32.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::TessellateAdaptive Method

Performs adaptive tessellation based on the z-based adaptive tessellation criterion.

Syntax

HRESULT TessellateAdaptive(

    D3DXVECTOR4* pTrans,
    DWORD dwMaxTessLevel,
    LPD3DXMESH pMesh
);

Parameters

pTrans
[in] Specifies a 4-D vector that is dotted with the vertices to get the per-vertex adaptive tessellation amount. Each edge is tessellated to the average value of the tessellation levels for the two vertices it connects.
dwMaxTessLevel
[in] Maximum limit for adaptive tessellation. This is the number of vertices introduced between existing vertices. The range of this integer value is 1 <= dwMaxTessLevel <= 32.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::UnlockAttributeBuffer Method

Unlock the attribute buffer.

Syntax

HRESULT UnlockAttributeBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::UnlockIndexBuffer Method

Unlock the index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::UnlockVertexBuffer Method

Unlock the vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh Interface

Applications use the methods of the ID3DXPMesh interface to manipulate progressive mesh objects. A progressive mesh enables progressive refinement of the mesh object.

ID3DXPMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ClonePMesh | Clones a progressive mesh using a declarator.
ClonePMeshFVF | Clones a progressive mesh using a FVF code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset

Draws a subset of a mesh.

GenerateAdjacency | Generates adjacency information based on mesh indices.
GenerateVertexHistory | Generate an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.
GetAdjacency | Returns the face adjacency array of the mesh.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

GetDevice | Retrieves the device associated with the mesh.
GetFVF

Get the fixed function vertex value.

GetIndexBuffer

Retrieves the data in an index buffer.

GetMaxFaces

Retrieves the maximum number of faces that the progressive mesh supports.

GetMaxVertices

Retrieves the maximum number of vertices that the progressive mesh supports.

GetMinFaces

Retrieves the minimum number of faces that the progressive mesh supports.

GetMinVertices

Retrieves the minimum number of vertices that the progressive mesh supports.

GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces

Retrieves the number of faces in the mesh.

GetNumVertices

Retrieves the number of vertices in the mesh.

GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer

Retrieves the data in a vertex buffer.

LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Optimize | Generates an output mesh with reordered faces and vertices to optimize performance.
OptimizeBaseLOD | Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.
Save | Saves the progressive mesh to the specified stream object.
SetNumFaces | Sets the current level of detail to as close to the specified number of faces as possible.
SetNumVertices | Sets the current level of detail to as close to the specified number of vertices as possible.
TrimByFaces | Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.
TrimByVertices | Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.
UnlockIndexBuffer

Unlocks an index buffer.

UnlockVertexBuffer

Unlocks a vertex buffer.

UpdateSemantics

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

To obtain the ID3DXPMesh interface, call the D3DXGeneratePMesh function.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

This interface, like all Component Object Model (COM) interfaces, inherits additional functionality from the IUnknown interface.

The LPD3DXPMESH type is defined as a pointer to the ID3DXPMesh interface, as shown below.

typedef struct ID3DXPMesh *LPD3DXPMESH;

Interface Information

Inherits from | ID3DXBaseMesh
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::ClonePMesh Method

Clones a progressive mesh using a declarator.

Syntax

HRESULT ClonePMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::ClonePMeshFVF Method

Clones a progressive mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT ClonePMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXPMesh::ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

ID3DXBaseMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GenerateVertexHistory Method

Generate an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.

Syntax

HRESULT GenerateVertexHistory(

    DWORD* pVertexHistory
);

Parameters

pVertexHistory
[in]

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer must be equal to or greater than the maximum number of vertices in the progressive mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetAdjacency Method

Returns the face adjacency array of the mesh.

Syntax

HRESULT GetAdjacency(

    DWORD *pAdjacency
);

Parameters

pAdjacency
[out] Pointer to the returned face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. If the edge has no adjacent faces, the value is 0xffffffff. The size of the adjacency array is the maximum number of faces multiplied by 3.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXPMesh::GetMaxFaces

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetMaxFaces Method

Retrieves the maximum number of faces that the progressive mesh supports.

Syntax

DWORD GetMaxFaces(VOID);

Return Value

Returns the maximum number of faces supported by the progressive mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetMaxVertices Method

Retrieves the maximum number of vertices that the progressive mesh supports.

Syntax

DWORD GetMaxVertices(VOID);

Return Value

Returns the maximum number of vertices supported by the progressive mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetMinFaces Method

Retrieves the minimum number of faces that the progressive mesh supports.

Syntax

DWORD GetMinFaces(VOID);

Return Value

Returns the minimum number of faces supported by the progressive mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetMinVertices Method

Retrieves the minimum number of vertices that the progressive mesh supports.

Syntax

DWORD GetMinVertices(VOID);

Return Value

Returns the minimum number of vertices supported by the progressive mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::Optimize Method

Generates an output mesh with reordered faces and vertices to optimize performance.

Syntax

HRESULT Optimize(

    DWORD Flags,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    LPD3DXMESH *ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH32_BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. The size of this array is the maximum number of faces multiplied by 3.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::OptimizeBaseLOD Method

Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.

Syntax

HRESULT OptimizeBaseLOD(

    DWORD Flags,
    DWORD *pFaceMap
);

Parameters

Flags
[in] A combination of one or more flags from the D3DXMESHOPT enumeration, specifying the type of optimization to perform.
pFaceMap
[in] Face remap array that indcates how the triangles were rearranged.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::Save Method

Saves the progressive mesh to the specified stream object.

Syntax

HRESULT Save(

    IStream *pStream,
    const D3DXMATERIAL *pMaterials,
    CONST D3DXEFFECTINSTANCE* pEffectInstances,
    DWORD NumMaterials
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object to which the file data is written.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the stream object.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

For more information about the IStream interface, see the Microsoft Platform Software Development Kit (SDK).

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::SetNumFaces Method

Sets the current level of detail to as close to the specified number of faces as possible.

Syntax

HRESULT SetNumFaces(

    DWORD Faces
);

Parameters

Faces
[in] Target number of faces. This value specifies the desired change in the level of detail (LOD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of faces is greater than the maximum number of faces, it is capped at the maximum number of faces returned by ID3DXPMesh::GetMaxFaces. If the number of faces is less than the minimum number of faces, it is capped at the minimum number of faces returned by ID3DXPMesh::GetMinFaces.

The number of faces after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::SetNumVertices Method

Sets the current level of detail to as close to the specified number of vertices as possible.

Syntax

HRESULT SetNumVertices(

    DWORD Vertices
);

Parameters

Vertices
[in] Target number of vertices. This value specifies the desired change in the level of detail (LOD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of vertices is greater than the maximum number of vertices, it is capped at the maximum number of vertices returned by ID3DXPMesh::GetMaxVertices. If the number of vertices is less than the minimum number of vertices, it is capped at the minimum number of vertices returned by ID3DXPMesh::GetMinVertices.

The number of vertices after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::TrimByFaces Method

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

Syntax

HRESULT TrimByFaces(

    DWORD NewFacesMin,
    DWORD NewFacesMax,
    DWORD *rgiFaceRemap,
    DWORD *rgiVertRemap
);

Parameters

NewFacesMin
[in] New minimum number of faces. This parameter must be between current minimum and maximum number of faces.
NewFacesMax
[in] New maximum number of faces. This parameter must be between current minimum and maximum number of faces.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contians vertex remap information.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXPMesh::TrimByVertices

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::TrimByVertices Method

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

Syntax

HRESULT TrimByVertices(

    DWORD NewVerticesMin,
    DWORD NewVerticessMax,
    DWORD *rgiFaceRemap,
    DWORD *rgiVertRemap
);

Parameters

NewVerticesMin
[in] New minimum number of vertices. This parameter must be between current minimum and maximum number of vertices.
NewVerticessMax
[in] New maximum number of vertices. This parameter must be between current minimum and maximum number of vertices.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contains vertex remap information.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXPMesh::TrimByFaces

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap Interface

The ID3DXRenderToEnvMap interface is used to generalize the process of rendering to environment maps.

ID3DXRenderToEnvMap Members

BeginCube | Begins a scene for an environmental cube map.
BeginHemisphere | Begins a scene for a hemisphere environment map.
BeginParabolic | Begins a scene for a parabolic environment map.
BeginSphere | Begins a scene for a spherical environment map.
End

Ends a scene for an environmental map.

Face

Ends the current scene if one is active and begins a new scene on the specified face.

GetDesc

Retrieves the description of the render surface.

GetDevice

Retrieves the Microsoft® Direct3D® device associated with the environment map.

OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

OnResetDevice

Should be called after the device has been reset.

Remarks

An environment map is used to texture-map scene geometry to provide a more sophisticated scene without using complex geometry. This interface supports creating surfaces for the following kinds of geometry: cube, half sphere or hemispheric, parabolic, or sphere. An example using a cubic environment map is in the Cube Map Sample.

The ID3DXRenderToEnvMap interface is obtained by calling the D3DXCreateRenderToEnvMap function.

The LPD3DXRenderToEnvMap type is defined as a pointer to the ID3DXRenderToEnvMap interface.

typedef interface ID3DXRenderToEnvMap* LPD3DXRenderToEnvMap;

Interface Information

Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::BeginCube Method

Begins a scene for an environmental cube map.

Syntax

HRESULT BeginCube(

    LPDIRECT3DCUBETEXTURE9 pCubeTex
);

Parameters

pCubeTex
[in] Pointer to an IDirect3DCubeTexture9 interface that represents the cube texture to render to.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXRenderToEnvMap::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::BeginHemisphere Method

Begins a scene for a hemisphere environment map.

Syntax

HRESULT BeginHemisphere(

    LPDIRECT3DTEXTURE9 pTexZPos,
    LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive texture render surface.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative texture render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.

See Also

ID3DXRenderToEnvMap::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::BeginParabolic Method

Begins a scene for a parabolic environment map.

Syntax

HRESULT BeginParabolic(

    LPDIRECT3DTEXTURE9 pTexZPos,
    LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive render texture.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative render texture.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.

See Also

ID3DXRenderToEnvMap::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::BeginSphere Method

Begins a scene for a spherical environment map.

Syntax

HRESULT BeginSphere(

    LPDIRECT3DTEXTURE9 pTex
);

Parameters

pTex
[in] Pointer to an IDirect3DTexture9 interface that represents the texture to render to.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.

See Also

ID3DXRenderToEnvMap::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::End Method

Ends a scene for an environmental map.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_FAIL | An undetermined error occurred inside the Microsoft® Direct3D® subsystem.

See Also

ID3DXRenderToEnvMap::BeginCube, ID3DXRenderToEnvMap::BeginHemisphere, ID3DXRenderToEnvMap::BeginParabolic, ID3DXRenderToEnvMap::BeginSphere

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::Face Method

Ends the current scene if one is active and begins a new scene on the specified face.

Syntax

HRESULT Face(

    D3DCUBEMAP_FACES Face
);

Parameters

Face
[in] D3DCUBEMAP_FACES enumerated type that specifies which face of the environmental cube map to begin a scene for.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::GetDesc Method

Retrieves the description of the render surface.

Syntax

HRESULT GetDesc(

    D3DXRTE_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DXRTE_DESC structure that describes the rendering surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::GetDevice Method

Retrieves the Microsoft® Direct3D® device associated with the environment map.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface that represents the Direct3D device object associated with the environment map.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method increases the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXRenderToEnvMap::OnResetDevice method called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToEnvMap::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface Interface

The ID3DXRenderToSurface interface is used to generalize the process of rendering to surfaces.

ID3DXRenderToSurface Members

BeginScene

Begins a scene.

EndScene

Ends a scene.

GetDesc

Retrieves the parameters of the render surface.

GetDevice

Retrieves the Microsoft® Direct3D® device associated with the render surface.

OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

OnResetDevice

Should be called after the device has been reset.

Remarks

Surfaces can be used in a variety of ways including render targets, off-screen rendering, or rendering to textures. An example of off-screen rendering can be seen in the Water Sample.

A surface can be configured using a separate viewport using the ID3DXRenderToSurface::BeginScene method, to provide a custom render view.

If the surface is not a render target, a compatible render target is used, and the result is copied to the surface at the end of the scene.

The ID3DXRenderToSurface interface is obtained by calling the D3DXCreateRenderToSurface function.

The LPD3DXRENDERTOSURFACE type is defined as a pointer to the ID3DXRenderToSurface interface.

typedef interface ID3DXRenderToSurface* LPD3DXRENDERTOSURFACE;

Interface Information

Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::BeginScene Method

Begins a scene.

Syntax

HRESULT BeginScene(

    LPDIRECT3DSURFACE9 pSurface,
    CONST D3DVIEWPORT9 *pViewport
);

Parameters

pSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the render surface.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, describing the viewport for the scene.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXRenderToSurface::EndScene

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::EndScene Method

Ends a scene.

Syntax

HRESULT EndScene(

    DWORD MipFilter
);

Parameters

MipFilter
[in] Filter options, enumerated in D3DX_FILTER.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXRenderToSurface::BeginScene

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::GetDesc Method

Retrieves the parameters of the render surface.

Syntax

HRESULT GetDesc(

    D3DXRTS_DESC *pParameters
);

Parameters

pParameters
[out] Pointer to a D3DXRTS_DESC structure, describing the parameters of the render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::GetDevice Method

Retrieves the Microsoft® Direct3D® device associated with the render surface.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXRenderToSurface::OnResetDevice method called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXRenderToSurface::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData Interface

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXSaveMeshHierarchyToFile, and Direct3D extensions (D3DX) calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXSaveUserData::AddFrameChildData is called and passed the child data.

ID3DXSaveUserData Members

AddFrameChildData | Add child data to the frame.
AddMeshChildData | Add child data to the mesh.
AddTopLevelDataObjectsPost | Add a top level object after the frame hierarchy.
AddTopLevelDataObjectsPre | Add a top level object before the frame hierarchy.
RegisterTemplates | A callback for the user to register an .x file template.
SaveTemplates | A callback for the user to save an .x file template.

Interface Information

Inherits from | Nothing
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::AddFrameChildData Method

Add child data to the frame.

Syntax

HRESULT AddFrameChildData(

    LPD3DXFRAME pFrame,
    LPDIRECTXFILESAVEOBJECT pXofSave,
    LPDIRECTXFILEDATA pXofFrameData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofSave
[in] Pointer to an .x file save object. Use the pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Do not save the data with IDirectXFileSaveObject::SaveData.
pXofFrameData
[in] Pointer to an .x file data structure. Use the pointer to call IDirectXFileData::AddDataObject with the new data object to save it.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to an .x file for saving user data, using the interface contained in the pXofSave parameter.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::AddMeshChildData Method

Add child data to the mesh.

Syntax

HRESULT AddMeshChildData(

    LPD3DXMESHCONTAINER pMeshContainer,
    LPDIRECTXFILESAVEOBJECT pXofSave,
    LPDIRECTXFILEDATA pXofMeshData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofSave
[in] Pointer to an .x file save object. Use the pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Do not save the data with IDirectXFileSaveObject::SaveData.
pXofMeshData
[in] Pointer to an .x file data structure. Use the pointer to call IDirectXFileData::AddDataObject with the new data object to save it.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::AddTopLevelDataObjectsPost Method

Add a top level object after the frame hierarchy.

Syntax

HRESULT AddTopLevelDataObjectsPost(

    LPDIRECTXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to an .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::AddTopLevelDataObjectsPre Method

Add a top level object before the frame hierarchy.

Syntax

HRESULT AddTopLevelDataObjectsPre(

    LPDIRECTXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to an .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::RegisterTemplates Method

A callback for the user to register an .x file template.

Syntax

HRESULT RegisterTemplates(

    LPDIRECTXFILE pXFileApi
);

Parameters

pXFileApi
[in] Use this pointer to register user-defined .x file templates. See IDirectXFile. Do not use this parameter to add data objects.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to an .x file for saving user data.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSaveUserData::SaveTemplates Method

A callback for the user to save an .x file template.

Syntax

HRESULT SaveTemplates(

    LPDIRECTXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to an .x file save object. Do not use this parameter to add data objects. See IDirectXFileSaveObject.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to an .x file for saving user data.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo Interface

Applications use the methods of the ID3DXSkinInfo interface to manipulate bone matrices, which are used to skin vertex data for animation. This interface is no longer strictly tied to ID3DXMesh and can be used to skin any set of vertex data.

ID3DXSkinInfo Members

Clone

Clone a skin info object.

ConvertToBlendedMesh

Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.

ConvertToIndexedBlendedMesh

Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.

GetBoneInfluence

Get the vertices and weights that a bone influences.

GetBoneName

Get the bone name, from the bone index.

GetBoneOffsetMatrix

Get the bone offset matrix.

GetDeclaration

Get the vertex declaration.

GetFVF

Get the fixed function vertex value.

GetMaxFaceInfluences

Get the maximum face influences in a triangle mesh with the specified index buffer.

GetMaxVertexInfluences

Get the number of influences for a bone.

GetMinBoneInfluence

Get the minimum bone influence. Influence values smaller than this are ignored.

GetNumBoneInfluences

Get the number of influences for a bone.

GetNumBones

Get the number of bones.

Remap

Update bone influence information to match vertices after they are reordered. This should be called if the target vertex buffer has been reordered externally.

SetBoneInfluence

Set the influence value for a bone.

SetBoneName

Set the bone name.

SetBoneOffsetMatrix

Set the bone offset matrix.

SetDeclaration

Set the vertex declaration.

SetFVF

Set the flexible vertex format (FVF) type.

SetMinBoneInfluence

Set the minimum bone influence. Influence values smaller than this are ignored.

UpdateSkinnedMesh

Apply software skinning to the target vertices based on the current matrices.

Remarks

This interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface.

Interface Information

Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::Clone Method

Clone a skin info object.

Syntax

HRESULT Clone(

    LPD3DXSKININFO *ppSkinInfo
);

Parameters

ppSkinInfo
[in, out] Address of a pointer to an ID3DXSkinInfo object, which will contain the cloned object if the method is successful.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::ConvertToBlendedMesh Method

Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.

Syntax

HRESULT ConvertToBlendedMesh(

    LPD3DXMESH pMesh,
    DWORD Options,
    CONST LPDWORD pAdjacencyIn,
    LPDWORD pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    DWORD *pMaxFaceInfl,
    DWORD *pNumBoneCombinations,
    LPD3DXBUFFER *ppBoneCombinationTable,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] Input mesh. See ID3DXMesh.
Options
[in] Currently unused.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. This parameter is optional, NULL may be used.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains the new index for each vertex. This parameter is optional, NULL may be used.
pMaxFaceInfl
[out] Pointer to a DWORD that will contain the maximum number of bone influences required per face for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap arrays specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::ConvertToIndexedBlendedMesh Method

Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.

Syntax

HRESULT ConvertToIndexedBlendedMesh(

    LPD3DXMESH pMesh,
    DWORD Options,
    DWORD paletteSize,
    CONST LPDWORD pAdjacencyIn,
    LPDWORD pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    DWORD *pMaxFaceInfl,
    DWORD *pNumBoneCombinations,
    LPD3DXBUFFER *ppBoneCombinationTable,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] The input mesh. See ID3DXMesh.
Options
[in] Currently unused.
paletteSize
[in] Number of bone matrices available for matrix palette skinning.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. This parameter is optional, NULL may be used.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains the new index for each vertex. This parameter is optional, NULL may be used.
pMaxFaceInfl
[out] Pointer to a DWORD which will contain the maximum number of bone influences required per face for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap arrays specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetBoneInfluence Method

Get the vertices and weights that a bone influences.

Syntax

HRESULT GetBoneInfluence(

    DWORD Bone,
    DWORD *vertices,
    FLOAT *weights
);

Parameters

Bone
[in] Bone number.
vertices
[in, out] Get the array of vertices influenced by a bone.
weights
[in, out] Get the array of weights influenced by a bone.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Use ID3DXSkinInfo::GetNumBoneInfluences to find out how many vertices the bone influences.

See Also

ID3DXSkinInfo::SetBoneInfluence

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetBoneName Method

Get the bone name, from the bone index.

Syntax

LPCSTR GetBoneName(

    DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Value

Returns the bone name. Do not free this string.

See Also

ID3DXSkinInfo::SetBoneName, ID3DXSkinInfo::GetNumBones

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetBoneOffsetMatrix Method

Get the bone offset matrix.

Syntax

LPD3DXMATRIX GetBoneOffsetMatrix(

    DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Value

Returns a pointer to the bone offset matrix. Do not free this pointer.

See Also

ID3DXSkinInfo::SetBoneOffsetMatrix, ID3DXSkinInfo::GetNumBones

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetDeclaration Method

Get the vertex declaration.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXSkinInfo::SetDeclaration

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetFVF Method

Get the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

See Also

ID3DXSkinInfo::SetFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetMaxFaceInfluences Method

Get the maximum face influences in a triangle mesh with the specified index buffer.

Syntax

HRESULT GetMaxFaceInfluences(

    LPDIRECT3DINDEXBUFFER9 pIB,
    DWORD NumFaces,
    DWORD *maxFaceInfluences
);

Parameters

pIB
[in] Pointer to the index buffer that contains the mesh index data.
NumFaces
[in] Number of faces in the mesh.
maxFaceInfluences
[in] Pointer to the maximum face influences.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetMaxVertexInfluences Method

Get the number of influences for a bone.

Syntax

HRESULT GetMaxVertexInfluences(

    DWORD *maxVertexInfluences
);

Parameters

maxVertexInfluences
[in] Pointer to the maximum vertex influence.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetMinBoneInfluence Method

Get the minimum bone influence. Influence values smaller than this are ignored.

Syntax

FLOAT GetMinBoneInfluence(VOID);

Return Value

Returns the minimum bone influence value.

See Also

ID3DXSkinInfo::SetMinBoneInfluence

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetNumBoneInfluences Method

Get the number of influences for a bone.

Syntax

DWORD GetNumBoneInfluences(

    DWORD bone
);

Parameters

bone
[in] Bone number.

Return Value

Returns the number of influences for a bone.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::GetNumBones Method

Get the number of bones.

Syntax

DWORD GetNumBones(VOID);

Return Value

Returns the number of bones.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::Remap Method

Update bone influence information to match vertices after they are reordered. This should be called if the target vertex buffer has been reordered externally.

Syntax

HRESULT Remap(

    DWORD NumVertices,
    DWORD *pVertexRemap
);

Parameters

NumVertices
[in] Number of vertices to remap.
pVertexRemap
[in] Array of DWORDS whose length is specified by NumVertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in pVertexRemap specifies the previous vertex index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap should contain 3. The vertex remap array returned by ID3DXMesh::Optimize can be used.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetBoneInfluence Method

Set the influence value for a bone.

Syntax

HRESULT SetBoneInfluence(

    DWORD Bone,
    DWORD numInfluences,
    CONST DWORD *vertices,
    CONST FLOAT *weights
);

Parameters

Bone
[in] Bone number.
numInfluences
[in] Number of influences.
vertices
[in] The array of vertices influenced by a bone.
weights
[in] The array of weights influenced by a bone.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetBoneInfluence, ID3DXSkinInfo::GetNumBoneInfluences

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetBoneName Method

Set the bone name.

Syntax

HRESULT SetBoneName(

    DWORD BoneNumber,
    LPCSTR BoneName
);

Parameters

BoneNumber
[in] Bone number
BoneName
[in] Bone name

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

See Also

ID3DXSkinInfo::GetBoneName

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetBoneOffsetMatrix Method

Set the bone offset matrix.

Syntax

HRESULT SetBoneOffsetMatrix(

    DWORD Bone,
    LPD3DXMATRIX pBoneTransform
);

Parameters

Bone
[in] Bone number.
pBoneTransform
[in] Pointer to the bone offset matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

See Also

ID3DXSkinInfo::GetBoneOffsetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetDeclaration Method

Set the vertex declaration.

Syntax

HRESULT SetDeclaration(

    CONST LPD3DVERTEXELEMENT9 pDeclaration
);

Parameters

pDeclaration
[in] Pointer to an array of D3DVERTEXELEMENT9 elements.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetDeclaration

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetFVF Method

Set the flexible vertex format (FVF) type.

Syntax

HRESULT SetFVF(

    DWORD FVF
);

Parameters

FVF
[in] Flexible vertex format. See D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::SetMinBoneInfluence Method

Set the minimum bone influence. Influence values smaller than this are ignored.

Syntax

HRESULT SetMinBoneInfluence(

    FLOAT minInfluence
);

Parameters

minInfluence
[in] Minimum influence value. Influence values smaller than this are ignored.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetMinBoneInfluence

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSkinInfo::UpdateSkinnedMesh Method

Apply software skinning to the target vertices based on the current matrices.

Syntax

HRESULT UpdateSkinnedMesh(

    CONST D3DXMATRIX *pBoneTransforms,
    CONST D3DXMATRIX *pBoneInvTransposeTransforms,
    PVOID pVerticesSrc,
    PVOID pVerticesDst
);

Parameters

pBoneTransforms
[in] Bone transform matrix.
pBoneInvTransposeTransforms
[in] Inverse transpose of the bone transform matrix.
pVerticesSrc
[in] Pointer to the buffer containing the source vertices.
pVerticesDst
[in] Pointer to the buffer containing the destination vertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh Interface

Applications use the methods of the ID3DXSPMesh interface to manipulate simplification mesh objects. A simplification mesh is used to simplify a given mesh to a lower number of faces.

ID3DXSPMesh Members

CloneMesh

Clones a mesh using a declarator.

CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

ClonePMesh

Clones a progressive mesh using a declarator.

ClonePMeshFVF

Clones a progressive mesh using a FVF code.

GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

GetDevice

Retrieves the device object associated with the simplification mesh.

GetFVF

Retrieves the FVF of the vertices in the simplification mesh.

GetMaxFaces

Retrieves the maximum number of faces that the simplification mesh supports.

GetMaxVertices

Retrieves the maximum number of vertices that the simplification mesh supports.

GetNumFaces

Retrieves the number of faces in the simplification mesh.

GetNumVertices

Retrieves the number of vertices in the simplification mesh.

GetOptions

Retrieves the mesh options enabled for this simplification mesh at creation time.

GetVertexAttributeWeights

Returns the per-vertex attribute weights used to create the ID3DXSPMesh object.

GetVertexWeights

Returns the per-vertex weights used to create the ID3DXSPMesh object.

ReduceFaces

Reduces the number of faces in a simplification mesh.

ReduceVertices

Reduces the number of vertices in a simplification mesh.

Remarks

The ID3DXSPMesh interface is obtained by calling the D3DXCreateSPMesh function.

The ID3DXSPMesh interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface.

The LPD3DXSPMESH type is defined as a pointer to the ID3DXSPMesh interface.

typedef struct ID3DXSPMesh *LPD3DXSPMESH;

Interface Information

Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    DWORD *pAdjacencyOut,
    DWORD *pVertexRemapOut,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, specifying the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    DWORD *pAdjacencyOut,
    DWORD *pVertexRemapOut,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::ClonePMesh Method

Clones a progressive mesh using a declarator.

Syntax

HRESULT ClonePMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    DWORD *pVertexRemapOut,
    FLOAT *pErrorsByFace,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh. The following flags are defined.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::ClonePMeshFVF Method

Clones a progressive mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT ClonePMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    DWORD *pVertexRemapOut,
    FLOAT *pErrorsByFace,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXSPMesh::GetFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetDevice Method

Retrieves the device object associated with the simplification mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft® Direct3D® device object associated with the simplification mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetFVF Method

Retrieves the flexible vertex format (FVF) of the vertices in the simplification mesh.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns an FVF that describes the vertex format of the vertices in the simplification mesh.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

See Also

ID3DXSPMesh::GetDeclaration

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetMaxFaces Method

Retrieves the maximum number of faces that the simplification mesh supports.

Syntax

DWORD GetMaxFaces(VOID);

Return Value

Returns the maximum number of faces in the original mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetMaxVertices Method

Retrieves the maximum number of vertices that the simplification mesh supports.

Syntax

DWORD GetMaxVertices(VOID);

Return Value

Returns the maximum number of vertices in the original mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetNumFaces Method

Retrieves the number of faces in the simplification mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the simplification mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetNumVertices Method

Retrieves the number of vertices in the simplification mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the simplification mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetOptions Method

Retrieves the mesh options enabled for this simplification mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more flags from the D3DXMESH enumeration, indicating the options enabled for this mesh at creation time.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetVertexAttributeWeights Method

Returns the per-vertex attribute weights used to create the ID3DXSPMesh object.

Syntax

HRESULT GetVertexAttributeWeights(

    LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights
);

Parameters

pVertexAttributeWeights
[out] Array of vertex attribute weights. See D3DXATTRIBUTEWEIGHTS.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

D3DXCreateSPMesh

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::GetVertexWeights Method

Returns the per-vertex weights used to create the ID3DXSPMesh object.

Syntax

HRESULT GetVertexWeights(

    FLOAT *pVertexWeights
);

Parameters

pVertexWeights
[in, out] Array of floats that will be filled with vertex weights. Each float contains one vertex. The array should be large enough to handle the maximum number of vertices in the original ID3DXMesh (which was used to create the simplification mesh).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

D3DXCreateSPMesh

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::ReduceFaces Method

Reduces the number of faces in a simplification mesh.

Syntax

HRESULT ReduceFaces(

    DWORD Faces
);

Parameters

Faces
[in] Number of faces to which to reduce the primitive count.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Faces. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSPMesh::ReduceVertices Method

Reduces the number of vertices in a simplification mesh.

Syntax

HRESULT ReduceVertices(

    DWORD Vertices
);

Parameters

Vertices
[in] Number of vertices to which to reduce the primitive count.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Vertices. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite Interface

The ID3DXSprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft® Direct3D®.

ID3DXSprite Members

Begin | Prepares a device for drawing sprites.
Draw | Draws a simple sprite in screen space.
DrawTransform | Provides a mechanism for drawing a sprite that is transformed by a specified matrix.
End | Restores the device state to how it was when ID3DXSprite::Begin was called.
GetDevice | Retrieves the Direct3D device associated with the sprite object.
OnLostDevice

Releases all references to video memory resources and deletes all stateblocks.

OnResetDevice

Should be called after the device has been reset.

Remarks

The ID3DXSprite interface is obtained by calling the D3DXCreateSprite function.

The ID3DXSprite interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface.

The LPD3DXSPRITE type is defined as a pointer to the ID3DXSprite interface.

typedef interface ID3DXSprite *LPD3DXSPRITE;

Interface Information

Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::Begin Method

Prepares a device for drawing sprites.

Syntax

HRESULT Begin(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Calling Begin is optional. If called outside of a Begin/ID3DXSprite::End sequence, the draw functions will internally call Begin and End. To avoid extra overhead, this method should be used if more than one draw function will be called successively.

This method must be called from inside an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene sequence.

Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.

See Also

ID3DXSprite::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::Draw Method

Draws a simple sprite in screen space.

Syntax

HRESULT Draw(

    LPDIRECT3DTEXTURE9 pSrcTexture,
    CONST RECT *pSrcRect,
    CONST D3DXVECTOR2 *pScaling,
    CONST D3DXVECTOR2 *pRotationCenter,
    FLOAT Rotation,
    CONST D3DVECTOR2 *pTranslation,
    D3DCOLOR Color
);

Parameters

pSrcTexture
[in] Pointer to an IDirect3DTexture9 interface, representing the source image used for the sprite.
pSrcRect
[in] Pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a subrectangle of the source image instead. Before transformation, the size of the sprite is defined by pSrcRect with the upper left corner at the origin (0,0).
pScaling
[in] Pointer to a D3DXVECTOR2 structure, containing the scaling vector. If this parameter is NULL, the value (1.0, 1.0) is used. Since pScaling is vector, a multiplier of 1.0 would preserve the source image size.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, containing the point in screen pixels that identifies the center of rotation. If this argument is NULL, the point (0,0) is used, which is the upper-left corner of the texture.
Rotation
[in] Value that specifies the rotation in radians, counterclockwise.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, containing the translation in screen pixels. If this argument is NULL, the point (0,0) is used.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value. A value of 0xFFFFFFFF maintains the original source color and alpha data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The transformation order is specified by:

(Msc)-1 * (Msr)-1 * Ms * Msr * Msc * (Mrc)-1 * Mr * Mrc * Mt

Where:

  • Msc is the center scaling matrix.
  • Msr is the scaling rotation matrix.
  • Ms is the scaling matrix.
  • Mrc is the center of rotation matrix.
  • Mr is the rotation matrix.
  • Mt is the translation matrix.

This method must be called between an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene pair.

If ID3DXSprite::Begin has not been called, this method will internally call ID3DXSprite::Begin and ID3DXSprite::End. When making successive calls to this method and/or ID3DXSprite::DrawTransform, be sure to call ID3DXSprite::Begin to avoid the extra overhead of ID3DXSprite::DrawTransform and this method internally calling ID3DXSprite::Begin and ID3DXSprite::End each time.

The image can be mirrored by specifying a negative vector in the appropriate direction (x, y, or both) for the pScaling parameter and adding the width and/or height of the source rectangle, specified in the pSrcRect parameter, to the values specified in the pTranslation parameter. Note that this will change the point of origin for rotations.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::DrawTransform Method

Provides a mechanism for drawing a sprite that is transformed by a specified matrix.

Syntax

HRESULT DrawTransform(

    LPDIRECT3DTEXTURE9 pSrcTexture,
    CONST RECT *pSrcRect,
    CONST D3DXMATRIX *pTransform,
    D3DCOLOR Color
);

Parameters

pSrcTexture
[in] Pointer to an IDirect3DTexture9 interface, representing the source image used for the sprite.
pSrcRect
[in] Pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a subrectangle of the source image instead. Before transformation, the size of the sprite is defined by pSrcRect with the top-left corner at the origin (0,0).
pTransform
[in] Pointer to a D3DXMATRIX structure, specifying the transformation that will be applied.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value. A value of 0xFFFFFFFF maintains the original source color and alpha data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method must be called between an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene pair.

If ID3DXSprite::Begin has not been called, this method will internally call ID3DXSprite::Begin and ID3DXSprite::End. When making successive calls to ID3DXSprite::Draw and/or this method, be sure to call ID3DXSprite::Begin to avoid the extra overhead of ID3DXSprite::Draw and ID3DXSprite::DrawTransform internally calling ID3DXSprite::Begin and ID3DXSprite::End each time.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::End Method

Restores the device state to how it was when ID3DXSprite::Begin was called.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

ID3DXSprite::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

See Also

ID3DXSprite::Begin

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::GetDevice Method

Retrieves the Microsoft® Direct3D® device associated with the sprite object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the sprite object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXSprite::OnResetDevice method called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXSprite::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section contains reference information for the functions that you need to implement when you work with the Direct3D extensions (D3DX) utility library. The following functions are implemented.

  • Animation Functions
  • Math Functions
  • Mesh Functions
  • Miscellaneous Functions
  • Shader Functions
  • Shape Drawing Functions
  • Texturing Functions

© 2002 Microsoft Corporation. All rights reserved.


Animation Functions

Direct3D extensions (D3DX) supplies the following animation functions.

  • D3DXCreateAnimationController
  • D3DXCreateAnimationSet
  • D3DXCreateKeyFrameInterpolator
  • D3DXFrameAppendChild
  • D3DXFrameCalculateBoundingSphere
  • D3DXFrameDestroy
  • D3DXFrameFind
  • D3DXFrameNumNamedMatrices
  • D3DXFrameRegisterNamedMatrices
  • D3DXLoadMeshHierarchyFromX
  • D3DXLoadMeshHierarchyFromXInMemory
  • D3DXSaveMeshHierarchyToFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateAnimationController Function

Create an animation controller object.

Syntax

HRESULT D3DXCreateAnimationController(

    UINT MaxNumMatrices,
    UINT MaxNumAnimationSets,
    UINT MaxNumTracks,
    UINT MaxNumEvents,
    LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

MaxNumMatrices
[in] Maximum number of matrices that can be animated.
MaxNumAnimationSets
[in] Maximum number of animation sets that can be mixed.
MaxNumTracks
[in] Maximum number of animation sets that can be mixed simultaneously.
MaxNumEvents
[in] Maximum number of outstanding events that the controller will support.
ppAnimController
[out, retval] Pointer to the animation controller object created. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

An animation controller controls an animation mixer. The controller adds methods to modify blending parameters over time to enable smooth transitions.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateAnimationSet Function

Creates an animation set, given a set of interpolators.

Syntax

HRESULT D3DXCreateAnimationSet(

    LPCSTR Name,
    LPD3DXINTERPOLATOR *ppInterpolators,
    UINT NumInterpolators,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

Name
[in] Name of the animation set.
ppInterpolators
[in] Array of interpolators. See ID3DXInterpolator.
NumInterpolators
[in] Number of elements in the array of interpolators.
ppAnimSet
[out, retval] Returns the animation set interface. See ID3DXAnimationSet.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

A walk cycle can be implemented using an animation set, which can also be called a frame hierarchy. The frame hierarchy consists of nodes in a tree. Each node is associated with one or more mesh objects and a transformation matrix. Each node uses an interpolator to encapsulate the transformation matrix.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateKeyFrameInterpolator Function

Creates a scale, rotate, and translate (SRT) key frame interpolator object from the given set of keys.

Syntax

HRESULT D3DXCreateKeyFrameInterpolator(

    LPCSTR Name,
    LPD3DXKEY_VECTOR3 ScaleKeys,
    UINT NumScaleKeys,
    LPD3DXKEY_QUATERNION RotationKeys,
    UINT NumRotationKeys,
    LPD3DXKEY_VECTOR3 TranslateKeys,
    UINT NumTranslationKeys,
    DOUBLE ScaleInputTimeBy,
    LPD3DXKEYFRAMEINTERPOLATOR *ppNewInterpolator
);

Parameters

Name
[in] Interpolator name.
ScaleKeys
[in] Array of scale key vectors.
NumScaleKeys
[in] Number of elements in RotationKeys array.
RotationKeys
[in] Array of rotation key quaternions. See D3DXKEY_QUATERNION.
NumRotationKeys
[in] Number of elements in RotationKeys array.
TranslateKeys
[in] Array of translation key vectors. See D3DXKEY_VECTOR3.
NumTranslationKeys
[in] Number of elements in TranslateKeys array.
ScaleInputTimeBy
[in] All key times are scaled by this factor.
ppNewInterpolator
[out, retval] Returns the keyframe interpolator interface. See ID3DXKeyFrameInterpolator.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameAppendChild Function

Add a child frame to a frame.

Syntax

HRESULT D3DXFrameAppendChild(

    LPD3DXFRAME pFrameParent,
    LPD3DXFRAME pFrameChild
);

Parameters

pFrameParent
[in] Pointer to the parent node.
pFrameChild
[in] Pointer to the child node.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameCalculateBoundingSphere Function

Computes the bounding sphere of all the meshes in the frame hierarchy.

Syntax

HRESULT D3DXFrameCalculateBoundingSphere(

    LPD3DXFRAME pFrameRoot,
    LPD3DXVECTOR3 pObjectCenter,
    FLOAT *pObjectRadius
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pObjectCenter
[out] Returns the center of the bounding sphere.
pObjectRadius
[out] Returns the radius of the bounding sphere.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameDestroy Function

Destroys the subtree of frames under the root, including the root.

Syntax

HRESULT D3DXFrameDestroy(

    LPD3DXFRAME pFrameRoot,
    LPD3DXALLOCATEHIERARCHY pAlloc
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pAlloc
[in] Allocation interface used to deallocate nodes of the frame hierarchy.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameFind Function

Find the child frame of a root frame.

Syntax

LPD3DXFRAME D3DXFrameFind(

    LPD3DXFRAME pFrameRoot,
    LPCSTR Name
);

Parameters

pFrameRoot
[in] Pointer to the root frame. See D3DXFRAME.
Name
[in] Name of the child frame to find.

Return Value

Returns the child frame if it is found, or NULL otherwise. See D3DXFRAME.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameNumNamedMatrices Function

Counts number of frames in a subtree that have non-null names.

Syntax

UINT D3DXFrameNumNamedMatrices(

    LPD3DXFRAME pFrameRoot
);

Parameters

pFrameRoot
[in] Pointer to the root node of the subtree.

Return Value

Returns the frame count.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFrameRegisterNamedMatrices Function

Given a frame hierarchy, registers all the named matrices in the animation mixer.

Syntax

HRESULT D3DXFrameRegisterNamedMatrices(

    LPD3DXFRAME pFrameRoot,
    LPD3DXANIMATIONMIXER pAnimMixer
);

Parameters

pFrameRoot
[in] The top level node in the frame hierarchy.
pAnimMixer
[in] Pointer to the animation mixer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Animation mixers created with D3DXLoadMeshHierarchyFromX automatically register all loaded named matrices.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshHierarchyFromX Function

Loads the first frame hierarchy from an .x file.

Syntax

HRESULT D3DXLoadMeshHierarchyFromX(

    LPCTSTR Filename,
    DWORD MeshOptions,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXALLOCATEHIERARCHY pAlloc,
    LPD3DXLOADUSERDATA pUserDataLoader,
    LPD3DXFRAME* ppFrameHeirarchy,
    LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

Filename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHeirarchy
[out, retval] Returns a pointer to the loaded frame hierarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshHeirarchyFromXW. Otherwise, the function call resolves to D3DXLoadMeshHeirarchyFromXA because ANSI strings are being used.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

D3DXLoadMeshHierarchyFromX loads the animation data and frame hierarchy from an .x file. It scans the .x file and builds a frame hierarchy and animation controller according to the ID3DXAllocateHierarchy-derived object passed to it through pAlloc. Loading the data requires several steps as follows:

  1. Derive ID3DXAllocateHierarchy, implementing each method. This controls how frames and meshes are allocated and freed.
  2. Derive ID3DXLoadUserData, implementing each method. If your .x file has no embedded user-defined data, or if you do not need it, you can skip this part.
  3. Create an object of your ID3DXAllocateHierarchy class, and optionally of your LoadUserData class. You do not need to call any methods of these objects yourself.
  4. Call D3DXLoadMeshHierarchyFromX, passing in your ID3DXAllocateHierarchy object and your ID3DXLoadUserData object (or NULL) to create the frame hierarchy and animation controller. All the animation sets and frames are automatically registered to the animation controller.

During the load, ID3DXAllocateHierarchy::CreateFrame and ID3DXLoadUserData::LoadFrameChildData are called back on each frame to control loading and allocation of the frame. The application defines these methods to control how frames are stored. ID3DXAllocateHierarchy::CreateMeshContainer and ID3DXLoadUserData::LoadMeshChildData are called back on each mesh object to control loading and allocation of mesh objects. ID3DXLoadUserData::LoadTopLevelData is called back for each top level object that doesn't get loaded by the other methods.

To free this data, call ID3DXAnimationController::Release to free the animation sets, and D3DXFrameDestroy, passing in the root node of the frame hierarchy and an object of your derived ID3DXAllocateHierarchy class. ID3DXAllocateHierarchy::DestroyFrame and ID3DXAllocateHierarchy::DestroyMeshContainer will each be called for every frame and mesh object in the frame hierarchy. Your implementation of ID3DXAllocateHierarchy::DestroyFrame should release everything allocated by ID3DXAllocateHierarchy::CreateFrame, and likewise for the mesh container methods.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshHierarchyFromXInMemory Function

Loads the first frame heirarchy from an .x file.

Syntax

HRESULT D3DXLoadMeshHierarchyFromXInMemory(

    LPCVOID pMemory,
    DWORD SizeOfMemory,
    DWORD MeshOptions,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXALLOCATEHIERARCHY pAlloc,
    LPD3DXLOADUSERDATA pUserDataLoader,
    LPD3DXFRAME* ppFrameHeirarchy,
    LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

pMemory
[in] ] Pointer to a buffer that contains the mesh hierarchy.
SizeOfMemory
[in] Size of the pMemory buffer, in bytes.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHeirarchy
[out, retval] Returns a pointer to the loaded frame heirarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSaveMeshHierarchyToFile Function

Creates an .x file and saves the mesh hierarchy and corresponding animations in it.

Syntax

HRESULT D3DXSaveMeshHierarchyToFile(

    LPCTSTR pFilename,
    DWORD XFormat,
    LPD3DXFRAME pFrameRoot,
    LPD3DXANIMATIONCONTROLLER pAnimController,
    LPD3DXSAVEUSERDATA pUserDataSaver
);

Parameters

pFilename
[in] Pointer to a string that specifies the name of the .x file identifying the saved mesh. See Remarks.
XFormat
[in] Format of the .x file (text or binary, compressed or not, etc.). See Remarks.
pFrameRoot
[in] Root node of the hierarchy to be saved. See D3DXFRAME.
pAnimController
[in] Animation controller whose animation sets are to be stored. See ID3DXAnimationController.
pUserDataSaver
[in] Application-provided interface that allows saving of user data. See ID3DXSaveUserData.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshHeirarchyToFileW. Otherwise, the function call resolves to D3DXSaveMeshHeirarchyToFileA because ANSI strings are being used.

For more information about .x files, see X Files.

The default value for the file format is DXFILEFORMAT_BINARY. DXFILEFORMAT_COMPRESSED can be combined (using a logical OR) with either the text or binary flag to reduce the file size. If a file is specified with both binary (DXFILEFORMAT_BINARY) and text (DXFILEFORMAT_TEXT) flags, it will be saved as a text file.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Math Functions

The math library provided by the Direct3D extensions (D3DX) utility library supplies functions to compute 3-D mathematical operations. Each of the functions can take the same object as the passed [in] and returned [out] parameters. Also, out parameters are typically returned as return values, so that the output of one math function can be used as a parameter for another math function.

The 3-D math application functions can be organized into the following groups.

Functions

  • D3DXColorAdd
  • D3DXColorAdjustContrast
  • D3DXColorAdjustSaturation
  • D3DXColorLerp
  • D3DXColorModulate
  • D3DXColorNegative
  • D3DXColorScale
  • D3DXColorSubtract
  • D3DXCreateMatrixStack
  • D3DXFloat16To32Array
  • D3DXFloat32To16Array
  • D3DXFresnelTerm
  • D3DXMatrixAffineTransformation
  • D3DXMatrixDeterminant
  • D3DXMatrixIdentity
  • D3DXMatrixInverse
  • D3DXMatrixIsIdentity
  • D3DXMatrixLookAtLH
  • D3DXMatrixLookAtRH
  • D3DXMatrixMultiply
  • D3DXMatrixMultiplyTranspose
  • D3DXMatrixOrthoLH
  • D3DXMatrixOrthoOffCenterLH
  • D3DXMatrixOrthoOffCenterRH
  • D3DXMatrixOrthoRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixReflect
  • D3DXMatrixRotationAxis
  • D3DXMatrixRotationQuaternion
  • D3DXMatrixRotationX
  • D3DXMatrixRotationY
  • D3DXMatrixRotationYawPitchRoll
  • D3DXMatrixRotationZ
  • D3DXMatrixScaling
  • D3DXMatrixShadow
  • D3DXMatrixTransformation
  • D3DXMatrixTranslation
  • D3DXMatrixTranspose
  • D3DXPlaneDot
  • D3DXPlaneDotCoord
  • D3DXPlaneDotNormal
  • D3DXPlaneFromPointNormal
  • D3DXPlaneFromPoints
  • D3DXPlaneIntersectLine
  • D3DXPlaneNormalize
  • D3DXPlaneTransform
  • D3DXPlaneTransformArray
  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionSquadSetup
  • D3DXQuaternionToAxisAngle
  • D3DXVec2Add
  • D3DXVec2BaryCentric
  • D3DXVec2CatmullRom
  • D3DXVec2CCW
  • D3DXVec2Dot
  • D3DXVec2Hermite
  • D3DXVec2Length
  • D3DXVec2LengthSq
  • D3DXVec2Lerp
  • D3DXVec2Maximize
  • D3DXVec2Minimize
  • D3DXVec2Normalize
  • D3DXVec2Scale
  • D3DXVec2Subtract
  • D3DXVec2Transform
  • D3DXVec2TransformArray
  • D3DXVec2TransformCoord
  • D3DXVec2TransformCoordArray
  • D3DXVec2TransformNormal
  • D3DXVec2TransformNormalArray
  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3ProjectArray
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformArray
  • D3DXVec3TransformCoord
  • D3DXVec3TransformCoordArray
  • D3DXVec3TransformNormal
  • D3DXVec3TransformNormalArray
  • D3DXVec3Unproject
  • D3DXVec3UnprojectArray
  • D3DXVec4Add
  • D3DXVec4BaryCentric
  • D3DXVec4CatmullRom
  • D3DXVec4Cross
  • D3DXVec4Dot
  • D3DXVec4Hermite
  • D3DXVec4Length
  • D3DXVec4LengthSq
  • D3DXVec4Lerp
  • D3DXVec4Maximize
  • D3DXVec4Minimize
  • D3DXVec4Normalize
  • D3DXVec4Scale
  • D3DXVec4Subtract
  • D3DXVec4Transform
  • D3DXVec4TransformArray

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorAdd Function

Adds two color values together to create a new color value.

Syntax

D3DXCOLOR *D3DXColorAdd(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the sum of two color values.

Remarks

The return value for this function is the same value returned in pOut. In this way, the D3DXColorAdd function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorModulate, D3DXColorSubtract

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorAdjustContrast Function

Adjusts the contrast value of a color.

Syntax

D3DXCOLOR *D3DXColorAdjustContrast(

    D3DXCOLOR *pOut,
    D3DXCOLOR *pC,
    FLOAT c
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
c
[in] Contrast value. This parameter linearly interpolates between 50 percent gray and the color, pC. There are not limits on the value of c. If this parameter is zero, then the returned color is 50 percent gray. If this parameter is 1, then the returned color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between 50 percent gray and a specified contrast value, as shown in the following example.

pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, the contrast is increased.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdjustSaturation

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorAdjustSaturation Function

Adjusts the saturation value of a color.

Syntax

D3DXCOLOR *D3DXColorAdjustSaturation(

    D3DXCOLOR *pOut,
    D3DXCOLOR *pC,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Saturation value. This parameter linearly interpolates between the color converted to grayscale and the original color, pC. There are no limits on the value of s. If s is 0, the returned color is the grayscale color. If s is 1, the returned color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a color, as shown in the following example.

    // Approximate values for each component's contribution to luminance.
    // Based upon the NTSC standard described in ITU-R Recommendation BT.709.
    FLOAT grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

    pOut->r = grey + s * (pC->r - grey);

If s is greater than 0 and less than 1, the saturation is decreased. If s is greater than 1, the saturation is increased.

The grayscale color is computed as:

r = g = b = 0.2125*r + 0.7154*g + 0.0721*b

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdjustContrast

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorLerp Function

Uses linear interpolation to create a color value.

Syntax

D3DXCOLOR *D3DXColorLerp(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Parameter that linearly interpolates between the colors, pC1 and pC2, treating them both as 4-D vectors. There are no limits on the value of s.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the linear interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorLerp function can be used as a parameter for another function.

This function interpolates the red, green, blue, and alpha components of a D3DXCOLOR structure between two colors, as shown in the following example.

    pOut->r = pC1->r + s * (pC2->r - pC1->r);

If you are linearly interpolating between the colors A and B, and s is 0, the resulting color is A. If s is 1, the resulting color is color B.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorModulate Function

Blends two colors.

Syntax

D3DXCOLOR *D3DXColorModulate(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the blending operation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorModulate function can be used as a parameter for another function.

This function blends together two colors by multiplying matching color components, as shown in the following example.

    pOut->r = pC1->r * pC2->r;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorNegative Function

Creates the negative color value of a color value.

Syntax

D3DXCOLOR *D3DXColorNegative(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the negative color value of the color value.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorNegative function can be used as a parameter for another function.

This function returns the negative color value by subtracting 1.0 from the color components of the D3DXCOLOR structure, as shown in the following example.

pOut->r = 1.0f - pC->r;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorScale Function

Scales a color value.

Syntax

D3DXCOLOR *D3DXColorScale(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Scale factor. It scales the color, treating it like a 4-D vector. There are no limits on the value of s. If s is 1, the resulting color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the scaled color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorScale function can be used as a parameter for another function.

This function computes the scaled color value by multiplying the color components of the D3DXCOLOR structure by the specified scale factor, as shown in the following example.

    pOut->r = pC->r * s;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative

© 2002 Microsoft Corporation. All rights reserved.


D3DXColorSubtract Function

Subtracts two color values to create a new color value.

Syntax

D3DXCOLOR *D3DXColorSubtract(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the difference between two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorSubtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdd

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateMatrixStack Function

Creates an instance of the ID3DXMatrixStack interface.

Syntax

HRESULT D3DXCreateMatrixStack(

    DWORD Flags,
    ID3DXMatrixStack **ppStack
);

Parameters

Flags
[in] Not implemented. Specify zero.
ppStack
[out] Address of a pointer filled with an ID3DXMatrixStack interface pointer if the function succeeds.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFloat16To32Array Function

Converts an array of 16-bit floats to 32-bit floats.

Syntax

D3DXFLOAT *WINAPI D3DXFloat16To32Array(

    D3DXFLOAT* pOut,
    CONST FLOAT16* pIn,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 32-bit floats.
pIn
[in] Pointer to an array of 16-bit floats.
n
[in] Number of elements in the array.

Return Value

Pointer to an array of 32-bit floats.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFloat32To16Array Function

Converts an array of 32-bit floats to 16-bit floats.

Syntax

D3DXFLOAT16 *WINAPI D3DXFloat32To16Array(

    D3DXFLOAT16* pOut,
    CONST FLOAT* pIn,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 16-bit floats.
pIn
[in] Pointer to an array of 32-bit floats.
n
[in] The number of elements in the array.

Return Value

Pointer to an array of 16-bit floats.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFresnelTerm Function

Calculate the Fresnel term.

Syntax

FLOAT D3DXFresnelTerm(

    FLOAT CosTheta,
    FLOAT RefractionIndex
);

Parameters

CosTheta
[in] The value must be between 0 and 1.
RefractionIndex
[in] The refraction index of a material. The value must be greater than 1.

Return Value

This function returns the Fresnel term for unpolarized light. CosTheta is the cosine of the incident angle.

Remarks

To find the Fresnel term (F):

If A is angle of incidence and B is the angle of refraction, then

F = 0.5 * [tan2(A - B) / tan2(A + B) + sin2(A - B) / sin2(A + B)]
  = 0.5 * sin2(A - B) / sin2(A + B) * [cos2(A + B) / cos2(A - B) + 1]

Let r   = sina(A) / sin(B)      (the relative refractive index)
Let c   = cos(A)
Let g   = (r2 + c2 - 1)1/2

Then, expanding using the trig identities and simplifying, you get:

F = 0.5 * (g + c)2 / (g - c)2 * ([c(g + c) - 1]2 / [c(g - c) + 1]2 + 1)

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixAffineTransformation Function

Builds an affine transformation matrix.

Syntax

D3DXMATRIX *D3DXMatrixAffineTransformation(

    D3DXMATRIX *pOut,
    FLOAT scaling,
    CONST D3DXVECTOR3 *pRotationCenter,
    CONST D3DXQUATERNION *pRotation,
    CONST D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, it is treated as identity.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Value

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

The D3DXMatrixAffineTransformation function calculates the affine transformation matrix with the following formula: Ms * (Mrc)-1 * Mr * Mrc * Mt, where Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixDeterminant Function

Returns the determinant of a matrix.

Syntax

FLOAT D3DXMatrixDeterminant(

    CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Returns the determinant of the matrix.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixIdentity Function

Creates an identity matrix.

Syntax

D3DXMATRIX *D3DXMatrixIdentity(

    D3DXMATRIX *pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.

Return Value

Pointer to a D3DXMATRIX structure that is the identity matrix.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4 ×4 matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixIdentity function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixIsIdentity

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixInverse Function

Calculates the inverse of a matrix.

Syntax

D3DXMATRIX *D3DXMatrixInverse(

    D3DXMATRIX *pOut,
    FLOAT *pDeterminant,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pDeterminant
[in, out] Pointer to a FLOAT value containing the determinant of the matrix. If the determinant is not needed, set this parameter to NULL.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the inverse of the matrix. If matrix inversion fails, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixIsIdentity Function

Determines if a matrix is an identity matrix.

Syntax

BOOL D3DXMatrixIsIdentity(

    CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure that will be tested for identity.

Return Value

If the matrix is an identity matrix, this function returns TRUE. Otherwise, this function returns FALSE.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixIdentity

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixLookAtLH Function

Builds a left-handed, look-at matrix.

Syntax

D3DXMATRIX *D3DXMatrixLookAtLH(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pEye,
    CONST D3DXVECTOR3 *pAt,
    CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixLookAtRH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixLookAtRH Function

Builds a right-handed, look-at matrix.

Syntax

D3DXMATRIX *D3DXMatrixLookAtRH(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pEye,
    CONST D3DXVECTOR3 *pAt,
    CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(Eye - At)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixLookAtLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixMultiply Function

Determines the product of two matrices.

Syntax

D3DXMATRIX *D3DXMatrixMultiply(

    D3DXMATRIX *pOut,
    CONST D3DXMATRIX *pM1,
    CONST D3DXMATRIX *pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M1 followed by the transformation M2 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionMultiply

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixMultiplyTranspose Function

Calculates the transposed product of two matrices.

Syntax

D3DXMATRIX *D3DXMatrixMultiplyTranspose(

    D3DXMATRIX* pOut,
    const D3DXMATRIX* pM1,
    const D3DXMATRIX* pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result is the transposed of the product of two transformation matrices, Out = T(M1*M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiplyTranspose function can be used as a parameter for another function.

This function is useful to set matrices as constants for vertex and pixel shaders.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixMultiply, D3DXQuaternionMultiply

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixOrthoLH Function

Builds a left-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixOrthoLH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that contains the resulting matrix.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume which is referred to as z-near.
zf
[in] Maximum z-value of the view volume which is referred to as z-far.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zf-zn)   0
0    0    zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixOrthoOffCenterLH Function

Builds a customized, left-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixOrthoOffCenterLH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoLH function is a special case of the D3DXMatrixOrthoOffCenterLH function. To create the same projection using D3DXMatrixOrthoOffCenterLH, use the following values:
                l = -w/2,
                r = w/2,
                b = -h/2, and
                t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zf-zn)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixOrthoOffCenterRH Function

Builds a customized, right-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixOrthoOffCenterRH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT t,
    FLOAT b,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
t
[in] Minimum y-value of view volume.
b
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoRH function is a special case of the D3DXMatrixOrthoOffCenterRH function. To create the same projection using D3DXMatrixOrthoOffCenterRH, use the following values:
                l = -w/2,
                r = w/2,
                b = -h/2, and
                t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zn-zf)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixOrthoRH Function

Builds a right-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixOrthoRH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zn-zf)   0
0    0    zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveFovLH Function

Builds a left-handed perspective projection matrix based on a field of view.

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveFovLH(

    D3DXMATRIX *pOut,
    FLOAT fovY,
    FLOAT Aspect,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovY
[in] Field of view, in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space height divided by width.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

This function computes the returned matrix as shown.

w       0       0               0
0       h       0               0
0       0       zf/(zf-zn)      1
0       0       -zn*zf/(zf-zn)  0
where:
h is the view space height. It is calculated from
h = cot(fovY/2);

w is the view space width. It is calculated from
w = h / Aspect.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveFovRH Function

Builds a right-handed perspective projection matrix based on a field of view.

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveFovRH(

    D3DXMATRIX *pOut,
    FLOAT fovY,
    FLOAT Aspect,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovY
[in] Field of view, in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space height divided by width.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovRH function can be used as a parameter for another function.

This function computes the returned matrix as shown.

w       0       0                0
0       h       0                0
0       0       zf/(zn-zf)      -1
0       0       zn*zf/(zn-zf)    0
where:
h is the view space height. It is calculated from
h = cot(fovY/2);

w is the view space width. It is calculated from
w = h / Aspect.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveLH Function

Builds a left-handed perspective projection matrix

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveLH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zf-zn)     1
0       0       zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveOffCenterLH Function

Builds a customized, left-handed perspective projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveOffCenterLH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0              0
0            2*zn/(t-b)   0              0
(l+r)/(l-r)  (t+b)/(b-t)  zf/(zf-zn)     1
0            0            zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveOffCenterRH Function

Builds a customized, right-handed perspective projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveOffCenterRH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0                0
0            2*zn*(t-b)   0                0
(l+r)/(r-l)  (t+b)/(t-b)  zf/(zn-zf)      -1
0            0            zn*zf/(zn-zf)    0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixPerspectiveRH Function

Builds a right-handed perspective projection matrix.

Syntax

D3DXMATRIX *D3DXMatrixPerspectiveRH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zn-zf)    -1
0       0       zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixReflect Function

Builds a matrix that reflects the coordinate system about a plane.

Syntax

D3DXMATRIX *D3DXMatrixReflect(

    D3DXMATRIX *pOut,
    CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXMATRIX structure that reflects the coordinate system about the source plane.

Remarks

This function normalizes the plane equation before it creates the reflected matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);

-2 * P.a * P.a + 1  -2 * P.b * P.a      -2 * P.c * P.a        0
-2 * P.a * P.b      -2 * P.b * P.b + 1  -2 * P.c * P.b        0
-2 * P.a * P.c      -2 * P.b * P.c      -2 * P.c * P.c + 1    0
-2 * P.a * P.d      -2 * P.b * P.d      -2 * P.c * P.d        1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationAxis Function

Builds a matrix that rotates around an arbitrary axis.

Syntax

D3DXMATRIX *D3DXMatrixRotationAxis(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationQuaternion Function

Builds a rotation matrix from a quaternion.

Syntax

D3DXMATRIX *D3DXMatrixRotationQuaternion(

    D3DXMATRIX *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXMATRIX structure built from the source quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

See D3DXQUATERNION to see how to calculate quaternion values from a pt (x,y,z) and an angle of rotation.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationX Function

Builds a matrix that rotates around the x-axis.

Syntax

D3DXMATRIX *D3DXMatrixRotationX(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationY Function

Builds a matrix that rotates around the y-axis.

Syntax

D3DXMATRIX *D3DXMatrixRotationY(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationYawPitchRoll Function

Builds a matrix with a specified yaw, pitch, and roll.

Syntax

D3DXMATRIX *D3DXMatrixRotationYawPitchRoll(

    D3DXMATRIX *pOut,
    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Value

Pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

The order of transformations is roll first, then pitch, then yaw. Relative to the object's local coordinate axis, this is equivalent to rotation around the z-axis, followed by rotation around the x-axis, followed by rotation around the y-axis.

Roll, pitch, yaw diagram

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixRotationZ Function

Builds a matrix that rotates around the z-axis.

Syntax

D3DXMATRIX *D3DXMatrixRotationZ(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixScaling Function

Builds a matrix that scales along the x-axis, the y-axis, and the z-axis.

Syntax

D3DXMATRIX *D3DXMatrixScaling(

    D3DXMATRIX *pOut,
    FLOAT sx,
    FLOAT sy,
    FLOAT sz
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
sx
[in] Scaling factor that is applied along the x-axis.
sy
[in] Scaling factor that is applied along the y-axis.
sz
[in] Scaling factor that is applied along the z-axis.

Return Value

Pointer to the scaling transformation D3DXMATRIX.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixShadow Function

Builds a matrix that flattens geometry into a plane.

Syntax

D3DXMATRIX *D3DXMatrixShadow(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR4 *pLight,
    CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
[in] Pointer to a D3DXVECTOR4 structure describing the light's position.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXMATRIX structure that flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.
P = normalize(Plane);
L = Light;
d = dot(P, L)

P.a * L.x + d  P.a * L.y      P.a * L.z      P.a * L.w
P.b * L.x      P.b * L.y + d  P.b * L.z      P.b * L.w
P.c * L.x      P.c * L.y      P.c * L.z + d  P.c * L.w
P.d * L.x      P.d * L.y      P.d * L.z      P.d * L.w + d

If the light's w-component is 0, the ray from the origin to the light represents a directional light. If it is 1, the light is a point light.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixTransformation Function

Builds a transformation matrix.

Syntax

D3DXMATRIX *D3DXMatrixTransformation(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pScalingCenter,
    CONST D3DXQUATERNION *pScalingRotation,
    CONST D3DXVECTOR3 *pScaling,
    CONST D3DXVECTOR3 *pRotationCenter,
    CONST D3DXQUATERNION *pRotation,
    CONST D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
[in] Pointer to a D3DXVECTOR3 structure, identifying the scaling center point. If this argument is NULL, it is treated as identity.
pScalingRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the scaling rotation If this argument is NULL, it is treated as identity.
pScaling
[in] Pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, it is treated as identity.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point that identifies the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, it is treated as identity.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Value

Pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

The D3DXMatrixTransformation function calculates the transformation matrix with the following formula: (Msc)-1 * (Msr)-1 * Ms * Msr * Msc * (Mrc)-1 * Mr * Mrc * Mt, where Msc is the center scaling matrix, Msr is the scaling rotation matrix, Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixAffineTransformation

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixTranslation Function

Builds a matrix using the specified offsets.

Syntax

D3DXMATRIX *D3DXMatrixTranslation(

    D3DXMATRIX *pOut,
    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
x
[in] X-coordinate offset.
y
[in] Y-coordinate offset.
z
[in] Z-coordinate offset.

Return Value

Pointer to a D3DXMATRIX structure that contains a translated transformation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranslation can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMatrixTranspose Function

Returns the matrix transpose of a matrix.

Syntax

D3DXMATRIX *D3DXMatrixTranspose(

    D3DXMATRIX *pOut,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to the D3DXMATRIX structure that is the matrix transpose of the matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneDot Function

Computes the dot product of a plane and a 4-D vector.

Syntax

FLOAT D3DXPlaneDot(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR4 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a D3DXVECTOR4 structure.

Return Value

The dot product of the plane and 4-D vector.

Remarks

Given a plane (a, b, c, d) and a 4-D vector (x, y, z, w) the return value of this function is a*x + b*y + c*z + d*w. The D3DXPlaneDot function is useful for determining the plane's relationship with a homogeneous coordinate. For example, this function could be used to determine if a particular coordinate is on a particular plane, or on which side of a particular plane a particular coordinate lies.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneDotCoord Function

Computes the dot product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 1.

Syntax

FLOAT D3DXPlaneDotCoord(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*1. The D3DXPlaneDotCoord function is useful for determining the plane's relationship with a coordinate in 3-D space.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDot, D3DXPlaneDotNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneDotNormal Function

Computes the dot product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 0.

Syntax

FLOAT D3DXPlaneDotNormal(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*0. The D3DXPlaneDotNormal function is useful for calculating the angle between the normal of the plane, and another normal.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDot, D3DXPlaneDotCoord

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneFromPointNormal Function

Constructs a plane from a point and a normal.

Syntax

D3DXPLANE *D3DXPlaneFromPointNormal(

    D3DXPLANE *pOut,
    CONST D3DXVECTOR3 *pPoint,
    CONST D3DXVECTOR3 *pNormal
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pPoint
[in] Pointer to a D3DXVECTOR3 structure, defining the point used to construct the plane.
pNormal
[in] Pointer to a D3DXVECTOR3 structure, defining the normal used to construct the plane.

Return Value

Pointer to the D3DXPLANE structure constructed from the point and the normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneFromPoints

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneFromPoints Function

Constructs a plane from three points.

Syntax

D3DXPLANE *D3DXPlaneFromPoints(

    D3DXPLANE *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pV1
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV2
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV3
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.

Return Value

Pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneFromPointNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneIntersectLine Function

Finds the intersection between a plane and a line.

Syntax

D3DXVECTOR3 *D3DXPlaneIntersectLine(

    D3DXVECTOR3 *pOut,
    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to a D3DXVECTOR3 structure, identifying the intersection between the specified plane and line.
pP
[in] Pointer to the source D3DXPLANE structure.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Value

Pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneNormalize Function

Normalizes the plane coefficients so that the plane normal has unit length.

Syntax

D3DXPLANE *D3DXPlaneNormalize(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXPLANE structure that represents the normal of the plane.

Remarks

This function normalizes a plane so that |a,b,c| == 1.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneTransform Function

Transforms a plane by a matrix. The input matrix is the inverse transpose of the actual transformation.

Syntax

D3DXPLANE *D3DXPlaneTransform(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See Example.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the plane that will be transformed. The vector (a,b,c) that describes the plane must be normalized before this function is called. See Example.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the transformation values. This matrix must contain the inverse transpose of the transformation values.

Return Value

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Examples

This example transforms a plane by applying a non-uniform scale.

D3DXPLANE   planeNew;
D3DXPLANE   plane(0,1,1,0);
D3DXPlaneNormalize(&plane, &plane);

D3DXMATRIX  matrix;
D3DXMatrixScaling(&matrix, 1.0f,2.0f,3.0f);
D3DXMatrixInverse(&matrix, NULL, &matrix);
D3DXMatrixTranspose(&matrix, &matrix);
D3DXPlaneTransform(&planeNew, &plane, &matrix);

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM, contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


D3DXPlaneTransformArray Function

Transforms a plane by a matrix. The input matrix is the inverse transpose of the actual transformation.

Syntax

D3DXPLANE *D3DXPlaneTransformArray(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See Example.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the plane that will be transformed. The vector (a,b,c) that describes the plane must be normalized before this function is called. See Example.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the transformation values. This matrix must contain the inverse transpose of the transformation values.

Return Value

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Examples

This example transforms a plane by applying a non-uniform scale.

D3DXPLANE   planeNew;
D3DXPLANE   plane(0,1,1,0);
D3DXPlaneNormalize(&plane, &plane);

D3DXMATRIX  matrix;
D3DXMatrixScaling(&matrix, 1.0f,2.0f,3.0f);
D3DXMatrixInverse(&matrix, NULL, &matrix);
D3DXMatrixTranspose(&matrix, &matrix);
D3DXPlaneTransform(&planeNew, &plane, &matrix);

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM, contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionBaryCentric Function

Returns a quaternion in Barycentric coordinates.

Syntax

D3DXQUATERNION *D3DXQuaternionBaryCentric(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2,
    CONST D3DXQUATERNION *pQ3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

To compute the Barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations: Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionConjugate Function

Returns the conjugate of a quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionConjugate(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the conjugate of the quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionConjugate function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionInverse

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionDot Function

Returns the dot product of two quaternions.

Syntax

FLOAT D3DXQuaternionDot(

    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2
);

Parameters

pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Value

The dot product of two quaternions.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionExp Function

Calculates the exponential.

Syntax

D3DXQUATERNION *D3DXQuaternionExp(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

This method converts a pure quaternion to a unit quaternion. D3DXQuaternionExp expects a pure quaternion, where w is ignored in the calculation (w == 0).

Given a pure quaternion defined by:
q = (0, theta * v);

This method calculates the exponential result.
exp(Q) = (cos(theta), sin(theta) * v)

where v is the vector portion of a quaternion.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

The D3DXQuaternionSquadSetup method can also be used to set up the control points of a quaternion.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLn, D3DXQuaternionSquad

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionIdentity Function

Returns the identity quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionIdentity(

    D3DXQUATERNION *pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.

Return Value

Pointer to the D3DXQUATERNION structure that is the identity quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionIdentity function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionIsIdentity

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionInverse Function

Conjugates and renormalizes a quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionInverse(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the inverse quaternion of the quaternion.

Remarks

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionIsIdentity Function

Determines if a quaternion is an identity quaternion.

Syntax

BOOL D3DXQuaternionIsIdentity(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the D3DXQUATERNION structure that will be tested for identity.

Return Value

If the quaternion is an identity quaternion, this function returns TRUE. Otherwise, this function returns FALSE.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionIdentity

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionLength Function

Returns the length of a quaternion.

Syntax

FLOAT D3DXQuaternionLength(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

The quaternion's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLengthSq

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionLengthSq Function

Returns the square of the length of a quaternion.

Syntax

FLOAT D3DXQuaternionLengthSq(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

The quaternion's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLength

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionLn Function

Calculates the natural logarithm.

Syntax

D3DXQUATERNION *D3DXQuaternionLn(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function works only for unit quaternions.

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionExp, D3DXQuaternionSquad

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionMultiply Function

Multiplies two quaternions.

Syntax

D3DXQUATERNION *D3DXQuaternionMultiply(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q1 followed by the rotation Q2 (Out = Q1 * Q2). This is done so that D3DXQuaternionMultiply maintain the same semantics as D3DXMatrixMultiply because unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);

D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixMultiply

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionNormalize Function

Computes a unit length quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionNormalize(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the normal of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionInverse

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionRotationAxis Function

Rotates a quaternion about an arbitrary axis.

Syntax

D3DXQUATERNION *D3DXQuaternionRotationAxis(

    D3DXQUATERNION *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionRotationMatrix Function

Builds a quaternion from a rotation matrix.

Syntax

D3DXQUATERNION *D3DXQuaternionRotationMatrix(

    D3DXQUATERNION *pOut,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to the D3DXQUATERNION structure built from a rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionRotationYawPitchRoll Function

Builds a quaternion with the given yaw, pitch, and roll.

Syntax

D3DXQUATERNION *D3DXQuaternionRotationYawPitchRoll(

    D3DXQUATERNION *pOut,
    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Value

Pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionSlerp Function

Interpolates between two quaternions, using spherical linear interpolation.

Syntax

D3DXQUATERNION *D3DXQuaternionSlerp(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2,
    FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Value

Pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionSquad Function

Interpolates between quaternions, using spherical quadrangle interpolation.

Syntax

D3DXQUATERNION *D3DXQuaternionSquad(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pA,
    CONST D3DXQUATERNION *pB,
    CONST D3DXQUATERNION *pC,
    FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pA
[in] Pointer to a source D3DXQUATERNION structure.
pB
[in] Pointer to a source D3DXQUATERNION structure.
pC
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Value

Pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

This function uses the following sequence of spherical linear interpolation operations: Slerp(Slerp(pQ1, pC, t), Slerp(pA, pB, t), 2t(1 - t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

For an example of interpolating between quaternions, see Skinned Mesh Sample.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionExp, D3DXQuaternionLn, D3DXQuaternionSquadSetup

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionSquadSetup Function

Setup control points for spherical quadrangle interpolation.

Syntax

void D3DXQuaternionSquadSetup(

    D3DXQUATERNION *pAOut,
    D3DXQUATERNION *pBOut,
    D3DXQUATERNION *pCOut,
    const D3DXQUATERNION *pQ0,
    const D3DXQUATERNION *pQ1,
    const D3DXQUATERNION *pQ2,
    const D3DXQUATERNION *pQ3
);

Parameters

pAOut
[out] Pointer to AOut.
pBOut
[out] Pointer to BOut.
pCOut
[out] Pointer to COut.
pQ0
[in] Pointer to the input control point, Q0.
pQ1
[in] Pointer to the input control point, Q1.
pQ2
[in] Pointer to the input control point, Q2.
pQ3
[in] Pointer to the input control point, Q3.

Return Value

None.

Remarks

This function takes four control points, which are supplied to the inputs pQ0, pQ1, pQ2, and pQ3. The function then alters these values to find a curve that flows along the shortest path. The values of q0, q2, and q3 are calculated as shown below.

q0 = |Q0 + Q1| < |Q0 - Q1| ? -Q0 : Q0
q2 = |Q1 + Q2| < |Q1 - Q2| ? -Q2 : Q2
q3 = |Q2 + Q3| < |Q2 - Q3| ? -Q3 : Q3

Having calculated the new Q values, the values for AOut, BOut, and COut are calculated as shown below.

AOut = q1 * e[-0.25 *( Ln[Exp(q1)*q2] + Ln[Exp(q1)*q0] ) ]

BOut = q2 * e[-0.25 *( Ln[Exp(q2)*q3] + Ln[Exp(q2)*q1] ) ]

COut = q2

Note Ln is the application programming interface (API) method D3DXQuaternionLn and Exp is the API method D3DXQuaternionExp.

Examples

The following example shows how to use a set of quaternion keys (Q0, Q1, Q2, Q3) to compute the inner quadrangle points (A, B, C). This ensures that the tangents are continuous across adjacent segments.

        A     B
  Q0    Q1    Q2    Q3

This is how you can interpolate between Q1 and Q2.

// Rotation about the z-axis
D3DXQUATERNION Q0 = D3DXQUATERNION(0,  0, 0.707f, -.707f);
D3DXQUATERNION Q1 = D3DXQUATERNION(0,  0, 0.000f, 1.000f);
D3DXQUATERNION Q2 = D3DXQUATERNION(0,  0, 0.707f, 0.707f);
D3DXQUATERNION Q3 = D3DXQUATERNION(0,  0, 1.000f, 0.000f);
D3DXQUATERNION A, B, C, Qt;
FLOAT time = 0.5f;

D3DXQuaternionSquadSetup(&A, &B, &C, &Q0, &Q1, &Q2, &Q3);
D3DXQuaternionSquad(&Qt, &Q1, &A, &B, &C, time);

Note:

  • C is +/- Q2 depending on the result of the function
  • Qt is the result of the function

The result is a rotation of 45 degrees around the z-axis for time = 0.5.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionSquad

© 2002 Microsoft Corporation. All rights reserved.


D3DXQuaternionToAxisAngle Function

Computes a quaternion's axis and angle of rotation.

Syntax

void D3DXQuaternionToAxisAngle(

    CONST D3DXQUATERNION *pQ,
    D3DXVECTOR3 *pAxis,
    FLOAT *pAngle
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.
pAxis
[in, out] When this function returns, pointer to a D3DXVECTOR3 structure that identifies the quaternion's axis.
pAngle
[in, out] This function returns a pointer to a FLOAT value that identifies the quaternion's angle of rotation in radians.

Return Value

No return value.

Remarks

This function expects unit quaternions.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Add Function

Adds two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Add(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Subtract, D3DXVec2Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2BaryCentric(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2,
    CONST D3DXVECTOR2 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
pV3
[in] Pointer to a source D3DXVECTOR2 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result, and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2CatmullRom(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2,
    CONST D3DXVECTOR2 *pV3,
    CONST D3DXVECTOR2 *pV4,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV4
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where: v1 is the contents of pV1, v2 is the contents of pV2, p3 is the contents of pV3, and p4 is the contents of pV4.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1
         + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s) (p3 - p1)/2
         + (s3 - s2)(p4 - p2)/2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 +
         (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3CatmullRom, D3DXVec4CatmullRom

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2CCW Function

Returns the z-component by taking the cross product of two 2-D vectors.

Syntax

FLOAT D3DXVec2CCW(

    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

The z-component.

Remarks

This function determines the z-component by determining the cross-product based on the following formula: ((x1,y1,0) cross (x2,y2,0)). Or as shown in the following example.

pV1->x * pV2->y - pV1->y * pV2->x

If the value of the z-component is positive, the vector V2 is counterclockwise from the vector V1. This information is useful for back-face culling.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Dot

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Dot Function

Determines the dot product of two 2-D vectors.

Syntax

FLOAT D3DXVec2Dot(

    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

The dot product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CCW

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Hermite Function

Performs a Hermite spline interpolation, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2Hermite(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pT1,
    CONST D3DXVECTOR2 *pV2,
    CONST D3DXVECTOR2 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Length Function

Returns the length of a 2-D vector.

Syntax

FLOAT D3DXVec2Length(

    CONST D3DXVECTOR2 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2LengthSq

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2LengthSq Function

Returns the square of the length of a 2-D vector.

Syntax

FLOAT D3DXVec2LengthSq(

    CONST D3DXVECTOR2 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Length

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Lerp Function

Performs a linear interpolation between two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Lerp(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Maximize Function

Returns a 2-D vector that is made up of the largest components of two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Maximize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Minimize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Minimize Function

Returns a 2-D vector that is made up of the smallest components of two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Minimize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Maximize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Normalize Function

Returns the normalized version of a 2-D vector.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2Normalize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Scale Function

Scales a 2-D vector.

Syntax

D3DXVECTOR2 *D3DXVec2Scale(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
s
[in] Scaling value.

Return Value

Pointer to a D3DXVECTOR2 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Add, D3DXVec2Subtract

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Subtract Function

Subtracts two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Subtract(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Add, D3DXVec2Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2Transform Function

Transforms a 2-D vector by a given matrix.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2TransformArray Function

Transforms an array of 2-D vectors by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec2TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR2 *pV,
    UINT VStride,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the array of vectors, pV (x, y, 0, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2TransformCoord Function

Transforms a 2-D vector by a given matrix, projecting the result back into w = 1.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformCoord(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Transform, D3DXVec2TransformNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2TransformCoordArray Function

Transforms array (x, y, 0, 1) by a given matrix, and projects the result back into w = 1.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec2TransformCoordArray(

    D3DXVECTOR4* pOut,
    UINT OutStride,
    CONST D3DXVECTOR2* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoordArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2TransformNormal Function

Transforms the 2-D vector normal by the given matrix.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformNormal(

    D3DXVECTOR2* pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, pV, by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Transform, D3DXVec2TransformCoord

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec2TransformNormalArray Function

Transforms array (x, y, 0, 0) by a given matrix.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformNormalArray(

    D3DXVECTOR2* pOut,
    UINT OutStride,
    CONST D3DXVECTOR2* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure. To transpose a normal with a non-affine matrix, this matrix should be a transposed-inverse transformation matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, pV, by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Add Function

Adds two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Add(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the sum of the two 3-D vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Subtract, D3DXVec3Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3BaryCentric(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
pV3
[in] Pointer to a source D3DXVECTOR3 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3CatmullRom(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3,
    CONST D3DXVECTOR3 *pV4,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source. D3DXVECTOR3 structure, a position vector.
pV2
[in] Pointer to a source. D3DXVECTOR3 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV4
[in] Pointer to a source. D3DXVECTOR3 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where v1 is the contents of pV1, v2 is the contents of pV2, p3 is the contents of pV3, and p4 is the contents of pV4.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1
         + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s) (p3 - p1)/2
         + (s3 - s2)(p4 - p2)/2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 +
         (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CatmullRom, D3DXVec4CatmullRom

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Cross Function

Determines the cross-product of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Cross(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the cross product of two 3-D vectors.

Remarks

This function determines the cross-product with the following code.

    D3DXVECTOR3 v;

    v.x = pV1->y * pV2->z - pV1->z * pV2->y;

    v.y = pV1->z * pV2->x - pV1->x * pV2->z;

    v.z = pV1->x * pV2->y - pV1->y * pV2->x;

    *pOut = v;

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Cross function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Dot

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Dot Function

Determines the dot-product of two 3-D vectors.

Syntax

FLOAT D3DXVec3Dot(

    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot-product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Cross

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Hermite Function

Performs a Hermite spline interpolation, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Hermite(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pT1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Length Function

Returns the length of a 3-D vector.

Syntax

FLOAT D3DXVec3Length(

    CONST D3DXVECTOR3 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3LengthSq

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3LengthSq Function

Returns the square of the length of a 3-D vector.

Syntax

FLOAT D3DXVec3LengthSq(

    CONST D3DXVECTOR3 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Length

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Lerp Function

Performs a linear interpolation between two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Lerp(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Maximize Function

Returns a 3-D vector that is made up of the largest components of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Maximize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Minimize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Minimize Function

Returns a 3-D vector that is made up of the smallest components of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Minimize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Maximize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Normalize Function

Returns the normalized version of a 3-D vector.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Normalize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Project Function

Projects a vector from object space into screen space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Project(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Unproject

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3ProjectArray Function

Projects a vector from object space into screen space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3ProjectArray(

    D3DXVECTOR3 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXVECTOR2* pV,
    UINT VStride,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Unproject

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Scale Function

Scales a 3-D vector.

Syntax

D3DXVECTOR3 *D3DXVec3Scale(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
s
[in] Scaling value.

Return Value

Pointer to a D3DXVECTOR3 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Subtract

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Subtract Function

Subtracts two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Subtract(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Transform Function

Transforms vector (x, y, z, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec3Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3TransformArray Function

Transforms array (x, y, z, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec3TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array of vectors, pV (x, y, 0, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4TransformArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3TransformCoord Function

Transforms a 3-D vector by a given matrix, projecting the result back into w = 1.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformCoord(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Transform, D3DXVec3TransformNormal

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3TransformCoordArray Function

Transforms array (x, y, z, 1) by a given matrix, and projects the result back into w = 1.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformCoordArray(

    D3DXVECTOR3* pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3TransformNormal Function

Transforms the 3-D vector normal by the given matrix.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformNormal(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, z, 0) of the vector, pV, by the matrix, pM.

If you transform a normal by a non-affine matrix, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a coordinate.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3TransformNormalArray Function

Transforms array (x, y, z, 0) by a given matrix.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformNormalArray(

    D3DXVECTOR3* pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure. To transpose a normal with a non-affine matrix, this matrix should be a transposed-inverse transformation matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 array that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, pV, by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormalArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3Unproject Function

Projects a vector from screen space into object space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Unproject(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Project

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec3UnprojectArray Function

Projects a vector from screen space into object space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3UnprojectArray(

    D3DXVECTOR3 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3 *pV,
    UINT VStride,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Project

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Add Function

Adds two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Add(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Subtract, D3DXVec4Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4BaryCentric(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4CatmullRom(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pV3,
    CONST D3DXVECTOR4 *pV4,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV4
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given 4 points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where: v1 is the contents of pV1, v2 in the contents of pV2, p3 is the contents of pV3, and p4 is the contents of pV4.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1
         + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s) (p3 - p1)/2
         + (s3 - s2)(p4 - p2)/2

This can be rearranging, as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 +
         (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CatmullRom, D3DXVec3CatmullRom

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Cross Function

Determines the cross-product in four dimensions.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Cross(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Dot

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Dot Function

Determines the dot product of two 4-D vectors.

Syntax

FLOAT D3DXVec4Dot(

    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

The dot product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Cross

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Hermite Function

Performs a Hermite spline interpolation, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Hermite(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pT1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Length Function

Returns the length of a 4-D vector.

Syntax

FLOAT D3DXVec4Length(

    CONST D3DXVECTOR4 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4LengthSq

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4LengthSq Function

Returns the square of the length of a 4-D vector.

Syntax

FLOAT D3DXVec4LengthSq(

    CONST D3DXVECTOR4 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Length

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Lerp Function

Performs a linear interpolation between two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Lerp(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Maximize Function

Returns a 4-D vector that is made up of the largest components of two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Maximize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Minimize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Minimize Function

Returns a 4-D vector that is made up of the smallest components of two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Minimize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Maximize

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Normalize Function

Returns the normalized version of a 4-D vector.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Normalize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Scale Function

Scales a 4-D vector.

Syntax

D3DXVECTOR4 *D3DXVec4Scale(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
s
[in] Scaling value.

Return Value

Pointer to the D3DXVECTOR4 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Add, D3DXVec4Subtract

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Subtract Function

Subtracts two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Subtract(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Scale

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4Transform Function

Transforms a 4-D vector by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed 4-D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVec4TransformArray Function

Transforms a vector array by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR4* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR4 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the array of vectors, pV (x, y, 0, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4TransformArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Mesh Functions

Direct3D extensions (D3DX) supplies the following mesh functions.

Functions

  • D3DXBoxBoundProbe
  • D3DXCleanMesh
  • D3DXComputeBoundingBox
  • D3DXComputeBoundingSphere
  • D3DXComputeNormals
  • D3DXComputeTangent
  • D3DXConvertMeshSubsetToSingleStrip
  • D3DXConvertMeshSubsetToStrips
  • D3DXCreateMesh
  • D3DXCreateMeshFVF
  • D3DXCreateNPatchMesh
  • D3DXCreatePatchMesh
  • D3DXCreatePMeshFromStream
  • D3DXCreateSkinInfo
  • D3DXCreateSkinInfoFromBlendedMesh
  • D3DXCreateSkinInfoFVF
  • D3DXCreateSPMesh
  • D3DXDeclaratorFromFVF
  • D3DXFVFFromDeclarator
  • D3DXGeneratePMesh
  • D3DXIntersect
  • D3DXIntersectSubset
  • D3DXIntersectTri
  • D3DXLoadMeshFromX
  • D3DXLoadMeshFromXInMemory
  • D3DXLoadMeshFromXof
  • D3DXLoadMeshFromXResource
  • D3DXLoadPatchMeshFromXof
  • D3DXLoadSkinMeshFromXof
  • D3DXRectPatchSize
  • D3DXSaveMeshToX
  • D3DXSimplifyMesh
  • D3DXSphereBoundProbe
  • D3DXSplitMesh
  • D3DXTessellateNPatches
  • D3DXTessellateRectPatch
  • D3DXTessellateTriPatch
  • D3DXTriPatchSize
  • D3DXValidMesh
  • D3DXWeldVertices

© 2002 Microsoft Corporation. All rights reserved.


D3DXBoxBoundProbe Function

Determines if a ray intersects the volume of a box's bounding box.

Syntax

BOOL D3DXBoxBoundProbe(

    CONST D3DXVECTOR3 *pMin,
    CONST D3DXVECTOR3 *pMax,
    D3DXVECTOR3 *pRayPosition,
    D3DXVECTOR3 *pRayDirection
);

Parameters

pMin
[in] Pointer to a D3DXVECTOR3 structure, describing the lower-left corner of the bounding box. See Remarks.
pMax
[in] Pointer to a D3DXVECTOR3 structure, describing the upper-right corner of the bounding box. See Remarks.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Value

Returns TRUE if the ray intersects the volume of the box's bounding box. Otherwise, returns FALSE.

Remarks

D3DXBoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The values passed to D3DXBoxBoundProbe are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -1

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXComputeBoundingBox

© 2002 Microsoft Corporation. All rights reserved.


D3DXCleanMesh Function

Cleans a mesh, preparing it for simplification.

Syntax

HRESULT D3DXCleanMesh(

    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    LPD3DXMESH *ppMeshOut,
    DWORD *pAdjacencyOut,
    LPD3DXBUFFER *ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be cleaned.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be cleaned.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned cleaned mesh. The same mesh is returned that was passed in if no cleaning was necessary.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the output mesh.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method cleans the mesh by adding another vertex where two fans of triangles share the same vertex.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXComputeBoundingBox Function

Computes a coordinate-axis oriented bounding box.

Syntax

HRESULT D3DXComputeBoundingBox(

    LPD3DXVECTOR3 pFirstPosition,
    DWORD NumVertices,
    DWORD dwStride,
    D3DXVECTOR3 *pMin,
    D3DXVECTOR3 *pMax
);

Parameters

pFirstPosition
[in] Pointer to the first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Count or number of bytes between vertices.
pMin
[out] Pointer to a D3DXVECTOR3 structure, describing the returned lower-left corner of the bounding box. See Remarks.
pMax
[out] Pointer to a D3DXVECTOR3 structure, describing the returned upper-right corner of the bounding box. See Remarks.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXComputeBoundingSphere Function

Computes a bounding sphere for the mesh.

Syntax

HRESULT D3DXComputeBoundingSphere(

    LPD3DXVECTOR3 pFirstPosition,
    DWORD NumVertices,
    DWORD dwStride,
    D3DXVECTOR3 *pCenter,
    FLOAT *pRadius
);

Parameters

pFirstPosition
[in] Pointer to first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Number of bytes between position vectors. Use D3DXGetFVFVertexSize to get the stride for a flexible vertex format (FVF).
pCenter
[out] D3DXVECTOR3 structure, defining the coordinate center of the returned bounding sphere.
pRadius
[out] Radius of the returned bounding sphere.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXComputeNormals Function

Computes normals for each vertex in a mesh.

Syntax

HRESULT D3DXComputeNormals(

    LPD3DXBASEMESH pMesh,
    const DWORD *pAdjacency
);

Parameters

pMesh
[in, out] Pointer to an ID3DXBaseMesh interface, representing the normalized mesh object.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh. This parameter is optional and should be set to NULL if it is unused.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The input mesh must have the D3DFVF_NORMAL flag specified in its flexible vertex format (FVF).

A normal for a vertex is generated by averaging the normals of all faces that share that vertex.

If adjacency is provided, replicated vertices are ignored and "smoothed" over. If adjacency is not provided, replicated vertices will have normals averaged in from only the faces explicitly referencing them.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXComputeTangent Function

Computes the tangent vectors for the texture coordinates given in the texture stage.

Syntax

HRESULT D3DXComputeTangent(

    LPD3DXMESH InMesh,
    DWORD TexStageIndex,
    DWORD TangentIndex,
    DWORD BinormIndex,
    DWORD Wrap,
    DWORD* pAdjacency
);

Parameters

InMesh
[in] Pointer to an ID3DXMesh interface that represent the input mesh.
TexStageIndex
[in] Index that represents the texture stage.
TangentIndex
[in] Index that provides the usage index for the tangent data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about usage indexes, see Decoupling Vertex Shaders and Vertex Declarations.
BinormIndex
[in] Index that provides the usage index for the binormal data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about usage indexes, see Decoupling Vertex Shaders and Vertex Declarations.
Wrap
[in] Set this value to 0 for no wrapping, or to 1 for wrapping in the U and V directions.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

If the mesh vertex declaration specifies tangent or binormal fields, D3DXComputeTangent will update any user-supplied tangent or binormal data. Alternatively, set TangentIndex = D3DXDefault to not update the user-supplied tangent data, and set BinormIndex = D3DXDefault to not update the user-supplied binormal data. TexStageIndex cannot be set to D3DXDefault.

D3DXComputeTangent depends on the mesh vertex declaration containing either the binormal field, the tangent field, or both. If both are missing, this function will fail.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXConvertMeshSubsetToSingleStrip Function

Converts the specified mesh subset into a single triangle strip.

Syntax

HRESULT D3DXConvertMeshSubsetToSingleStrip(

    LPD3DXBASEMESH MeshIn,
    DWORD AttribId,
    DWORD IBOptions,
    LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer,
    DWORD *pNumIndices
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXConvertMeshSubsetToStrips Function

Convert the specified mesh subset into a series of strips.

Syntax

HRESULT D3DXConvertMeshSubsetToStrips(

    LPD3DXBASEMESH MeshIn,
    DWORD AttribId,
    DWORD IBOptions,
    LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer,
    DWORD *pNumIndices,
    LPD3DXBUFFER *ppStripLengths,
    DWORD *pNumStrips
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.
ppStripLengths
[out] Buffer containing an array of one DWORD per strip, that specifies the number of triangles in the that strip.
pNumStrips
[out] Number of individual strips in the index buffer and corresponding strip length array.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateMesh Function

Creates a mesh object using a declarator.

Syntax

HRESULT D3DXCreateMesh(

    DWORD NumFaces,
    DWORD NumVertices,
    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the maximum DWORD (typically 65534), because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh. This parameter must map directly to a flexible vertex format (FVF).
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateMeshFVF Function

Creates a mesh object using a flexible vertex format (FVF) code.

Syntax

HRESULT D3DXCreateMeshFVF(

    DWORD NumFaces,
    DWORD NumVertices,
    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the max DWORD value, typically 232-1, because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned mesh. This function does not support D3DFVF_XYZRHW.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateNPatchMesh Function

Creates an N-patch mesh from a triangle mesh.

Syntax

HRESULT D3DXCreateNPatchMesh(

    LPD3DXMESH* pMeshSysMem,
    LPD3DXPATCHMESH* pPatchMesh
);

Parameters

pMeshSysMem
[in] Address of a pointer to an ID3DXMesh interface that represents the triangle mesh object.
pPatchMesh
[in, out] Address of a pointer to an ID3DXPatchMesh interface that represents the created patch mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreatePatchMesh Function

Creates a mesh from a control-patch mesh.

Syntax

HRESULT D3DXCreatePatchMesh(

    CONST LPD3DXPATCHINFO pInfo,
    CONST DWORD dwNumPatches,
    CONST DWORD dwNumVertices,
    CONST DWORD dwOptions,
    CONST LPD3DVERTEXELEMENT9 pDecl,
    CONST LPDIRECT3DDEVICE9 pDevice,
    LPD3DXPATCHMESH* pPatchMesh
);

Parameters

pInfo
[in] Patch information structure. For more information, see D3DXPATCHINFO.
dwNumPatches
[in] Number of patches.
dwNumVertices
[in] Number of control vertices in the patch.
dwOptions
[in] Unused. Reserved for later use.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
pDevice
[in] Pointer the device that creates the patch mesh. See IDirect3DDevice9.
pPatchMesh
[out] Pointer to the ID3DXPatchMesh object that is created.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method takes an input patch mesh and converts it to a tessellated mesh. Patch meshes use 16-bit index buffers. Therefore, indices to ID3DXPatchMesh::LockIndexBuffer are 16 bits.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPATCHINFO

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreatePMeshFromStream Function

Creates a progressive mesh from a stream object.

Syntax

HRESULT D3DXCreatePMeshFromStream(

    IStream *pStream,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXPMESH *ppPMesh
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object from which to create the progressive mesh. The data in this stream was generated with the ID3DXPMesh::Save method.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the progressive mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the stream object.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterialsarray, when the method returns.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

For more information about the IStream interface, see the Microsoft Platform Software Development Kit (SDK).

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXPMesh::Save

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSkinInfo Function

Creates an empty skin mesh object using a declarator.

Syntax

HRESULT D3DXCreateSkinInfo(

    DWORD numVertices,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    DWORD numBones,
    LPD3DXSKININFO* ppSkinInfo
);

Parameters

numVertices
[in] Number of vertices for the skin mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
numBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXSkinInfo::SetBoneInfluence

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSkinInfoFromBlendedMesh Function

Creates a skin mesh from another mesh.

Syntax

HRESULT D3DXCreateSkinInfoFromBlendedMesh(

    LPD3DXBASEMESH pMesh,
    DWORD numBoneCombinations,
    LPD3DXBONECOMBINATION pBoneCombinationTable,
    LPD3DXSKININFO* ppSkinInfo
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh object, the mesh from which to create the skin mesh.
numBoneCombinations
[in] The number of elements in the bone combination table in pBoneCombinationTable.
pBoneCombinationTable
[in] Pointer to an array of bone combinations. See D3DXBONECOMBINATION.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

E_OUTOFMEMORY Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSkinInfoFVF Function

Creates an empty skin mesh object using a flexible vertex format (FVF) code.

Syntax

HRESULT D3DXCreateSkinInfoFVF(

    DWORD numVertices,
    DWORD FVF,
    DWORD numBones,
    LPD3DXSKININFO* ppSkinInfo
);

Parameters

numVertices
[in] Number of vertices for the skin mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned skin mesh.
numBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin information object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXSkinInfo::SetBoneInfluence

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSPMesh Function

Creates a simplification mesh.

Syntax

HRESULT D3DXCreateSPMesh(

    LPD3DXMESH pMesh,
    CONST DWORD *pAdjacency,
    CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
    CONST FLOAT *pVertexWeights,
    LPD3DXSPMESH *ppSMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to simplify.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created simplification mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
ppSMesh
[out] Address of a pointer to an ID3DXSPMesh interface, representing the created simplification mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

A simplification mesh is used to simplify a mesh to a lower number of triangles and faces.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXDeclaratorFromFVF Function

Returns a declarator from a flexible vertex format (FVF) code.

Syntax

HRESULT D3DXDeclaratorFromFVF(

    DWORD FVF,
    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

FVF
[in] Combination of D3DFVF that describes the FVF from which to generate the returned declarator array.
Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DXERR_INVALIDMESH.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


D3DXFVFFromDeclarator Function

Returns a flexible vertex format (FVF) code from a declarator.

Syntax

HRESULT D3DXFVFFromDeclarator(

    CONST LPD3DVERTEXELEMENT9 *pDeclaration,
    DWORD *pFVF
);

Parameters

pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the FVF code.
pFVF
[out] Pointer to a DWORD value, representing the returned combination of D3DFVF that describes the vertex format returned from the declarator.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This function will fail for any declarator that does not map directly to an FVF.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


D3DXGeneratePMesh Function

Generates a progressive mesh.

Syntax

HRESULT D3DXGeneratePMesh(

    LPD3DXMESH pMesh,
    CONST DWORD *pAdjacency,
    CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
    CONST FLOAT *pVertexWeights,
    DWORD MinValue,
    DWORD Options,
    LPD3DXPMESH *ppPMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One flag from the D3DXMESHSIMP enumeration can be set.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function generates a mesh where the level of detail (LOD) can be adjusted from the current value to the MinValue.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXIntersect Function

Determines if a ray intersects with a mesh.

Syntax

HRESULT D3DXIntersect(

    LPD3DXBASEMESH pMesh,
    CONST D3DXVECTOR3 *pRayPos,
    CONST D3DXVECTOR3 *pRayDir,
    BOOL *pHit,
    DWORD *pFaceIndex,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist,
    LPD3DXBUFFER *ppAllHits,
    DWORD *pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Pointer to an ID3DXBuffer object, containing an array of D3DXINTERSECTINFO structures.
pCountOfHits
[out] Pointer to a DWORD that contains the number of entries in the ppAllHits array.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2-V1) + V(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result and the parameter V controls how much V3 gets weighted into the result. Lastly, 1-U-V controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXIntersectSubset Function

Intersects the specified ray with the given mesh subset. This provides similar functionality to D3DXIntersect.

Syntax

HRESULT D3DXIntersectSubset(

    LPD3DXBASEMESH pMesh,
    DWORD AttribId,
    const D3DXVECTOR3 *pRayPos,
    const D3DXVECTOR3 *pRayDir,
    BOOL *pHit,
    DWORD *pFaceIndex,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist,
    LPD3DXBUFFER *ppAllHits,
    DWORD *pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested. The mesh must be attribute sorted.
AttribId
[in] Attribute identifier of the subset to intersect with.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Array of D3DXINTERSECTINFO structures, representing all hits, not just closest hits.
pCountOfHits
[out] Number of elements in the array returned from ppAllHits.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following value.

E_OUTOFMEMORY Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The D3DXIntersectSubset function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2-V1) + V(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result and the parameter V controls how much V3 gets weighted into the result. Lastly, 1-U-V controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXIntersectTri Function

Computes a per-vertex coordinate system based on texture coordinate gradients.

Syntax

BOOL D3DXIntersectTri(

    const D3DXVECTOR3 *p0,
    const D3DXVECTOR3 *p1,
    const D3DXVECTOR3 *p2,
    const D3DXVECTOR3 *pRayPos,
    const D3DXVECTOR3 *pRayDir,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist
);

Parameters

p0
[in] Pointer to a D3DXVECTOR3 structure, describing first triangle vertex position.
p1
[in] Pointer to a D3DXVECTOR3 structure, describing second triangle vertex position.
p2
[in] Pointer to a D3DXVECTOR3 structure, describing third triangle vertex position.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the position of the ray.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the position of the ray.
pU
[out] Barycentric hit coordinates, U.
pV
[out] Barycentric hit coordinates, V.
pDist
[out] Ray-intersection parameter distance.

Return Value

Returns TRUE if the ray intersects the area of the triangle. Otherwise, returns FALSE.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2-V1) + V(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result and the parameter V controls how much V3 gets weighted into the result. Lastly, 1-U-V controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshFromX Function

Loads a mesh from a Microsoft® DirectX® .x file.

Syntax

HRESULT D3DXLoadMeshFromX(

    LPCTSTR pFilename,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER* ppAdjacency,
    LPD3DXBUFFER* ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    DWORD* pNumMaterials,
    LPD3DXMESH* ppMesh
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, which specifies creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[out] Pointer to a buffer containing materials data. The buffer contains an array of D3DXMATERIAL structures, containing information from the DirectX file. For more information about accessing the buffer, see ID3DXBuffer.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshFromXW. Otherwise, the function call resolves to D3DXLoadMeshFromXA because ANSI strings are being used.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshFromXInMemory Function

Loads a mesh from memory.

Syntax

HRESULT D3DXLoadMeshFromXInMemory(

    LPCVOID Memory,
    DWORD SizeOfMemory,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER* ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

Memory
[in] Pointer to the memory buffer which contains the mesh data.
SizeOfMemory
[in] Size of the file in memory, in bytes.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the Microsoft® DirectX® file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D® could not allocate sufficient memory to complete the call.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshFromXof Function

Loads a mesh from an IDirectXFileData object.

Syntax

HRESULT D3DXLoadMeshFromXof(

    LPDIRECTXFILEDATA pXofObjMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    WORD* pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

pXofObjMesh
[in] Pointer to an IDirectXFileData interface, representing the file data object to load.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[in, out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[in, out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Calling D3DXLoadMeshFromXof on an IDirectXFileData interface obtained using IDirectXFileDataReference::Resolve will fail because of a know problem handling references.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadMeshFromXResource Function

Loads a mesh from a resource.

Syntax

HRESULT D3DXLoadMeshFromXResource(

    HMODULE Module,
    LPCTSTR Name,
    LPCTSTR Type,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

Module
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
Name
[in] Pointer to a string that specifies the resource to create the mesh from. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Type
[in] Pointer to a string that specifies the resource type. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the Microsoft® DirectX® file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshFromResourceW. Otherwise, the function call resolves to D3DXLoadMeshFromResourceA because ANSI strings are being used.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadPatchMeshFromXof Function

Loads a patch mesh from an IDirectXFileData object.

Syntax

HRESULT D3DXLoadPatchMeshFromXof(

    LPDIRECTXFILEDATA pXofObjMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    PDWORD pNumMaterials,
    LPD3DXPATCHMESH* ppMesh
);

Parameters

pXofObjMesh
[in] Pointer to an IDirectXFileData interface, representing the file data object to load.
Options
[in] Combination of one or more D3DXMESH flags, specifying creation options for the mesh.
pDevice
[in] Pointer to the device that the mesh is created from.
ppMaterials
[out] Array of materials contained in the mesh. Each material is indexed by an ID3DXBuffer interface.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer that contains the number of materials in the mesh.
ppMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSkinMeshFromXof Function

Loads a skin mesh from a Microsoft® DirectX® .x file data object.

Syntax

HRESULT D3DXLoadSkinMeshFromXof(

    LPDIRECTXFILEDATA pXofObjMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER* ppAdjacency,
    LPD3DXBUFFER* ppMaterials,
    LPD3DXBUFFER* ppEffectInstances,
    DWORD* pMatOut,
    LPD3DXSKININFO* ppSkinInfo,
    LPD3DXMESH* ppMesh
);

Parameters

pXofObjMesh
[in] Pointer to an IDirectXFileData interface, representing the DirectX file data object to load.
Options
[in] Combination of one or more flags, from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pMatOut
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppSkinInfo
[out] Address of a pointer to an ID3DXSkinInfo interface, which represents the skinning information.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, which represents the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method takes a pointer to an internal object in the .x file, enabling you to load the frame hierarchy.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Calling D3DXLoadMeshFromXof on an IDirectXFileData interface obtained using IDirectXFileDataReference::Resolve will fail because of a know problem handling references.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXRectPatchSize Function

Gets the size of the rectangle patch.

Syntax

HRESULT D3DXRectPatchSize(

    CONST float* pNumSegs,
    DWORD* pdwTriangles,
    DWORD* pwdVertices
);

Parameters

pNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pwdVertices
[out] Pointer to a DWORD that contains the number of vertices in the patch.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateRectPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DXSaveMeshToX Function

Saves a mesh to an .x file.

Syntax

HRESULT D3DXSaveMeshToX(

    LPCTSTR pFilename,
    LPD3DXMESH pMesh,
    CONST DWORD* pAdjacency,
    CONST D3DXMATERIAL* pMaterials,
    CONST D3DXEFFECTINSTANCE* pEffectInstances,
    DWORD NumMaterials,
    DWORD Format
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to save to an .x file.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the .x file.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.
Format
[in] Indicates the format to use when saving the .x file. For more information, see Remarks.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshToXW. Otherwise, the function call resolves to D3DXSaveMeshToXA because ANSI strings are being used.

The default value for the file format is DXFILEFORMAT_BINARY. DXFILEFORMAT_COMPRESSED can be combined (using a logical OR) with either the text or binary flag to reduce the file size. If a file is specified with both binary (DXFILEFORMAT_BINARY) and text (DXFILEFORMAT_TEXT) flags, it will be saved as a text file.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


D3DXSimplifyMesh Function

Generates a simplified mesh using the provided weights that come as close as possible to the given MinValue.

Syntax

HRESULT D3DXSimplifyMesh(

    LPD3DXMESH pMesh,
    CONST DWORD *pAdjacency,
    CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
    CONST FLOAT *pVertexWeights,
    DWORD MinValue,
    DWORD Options,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One of the flags in D3DXSimplifyMesh can be set.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the returned simplification mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function generates a mesh that has MinValue vertices or faces.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSphereBoundProbe Function

Determines if a ray intersects the volume of a sphere's bounding box.

Syntax

BOOL D3DXSphereBoundProbe(

    CONST D3DXVECTOR3* pCenter,
    FLOAT Radius,
    CONST D3DXVECTOR3* pRayPosition,
    CONST D3DXVECTOR3* pRayDirection
);

Parameters

pCenter
[in] Pointer to a D3DXVECTOR3 structure, specifying the center coordinate of the sphere.
Radius
[in] Radius of the sphere.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Value

Returns TRUE if the ray intersects the volume of the sphere's bounding box. Otherwise, returns FALSE.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSplitMesh Function

Splits a mesh into meshes smaller than the specified size.

Syntax

void D3DXSplitMesh(

    const LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    const DWORD MaxSize,
    const DWORD Options,
    DWORD *pMeshesOut,
    LPD3DXBUFFER *ppMeshArrayOut,
    LPD3DXBUFFER *ppAdjacencyArrayOut,
    LPD3DXBUFFER *ppFaceRemapArrayOut,
    LPD3DXBUFFER *ppVertRemapArrayOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
MaxSize
[in] Maximum number of vertices in the resulting mesh.
Options
[in] Option flags for the new meshes.
pMeshesOut
[out, retval] Number of meshes returned.
ppMeshArrayOut
[out, retval] Buffer containing an array of ID3DXMesh interfaces for the new meshes. For a source mesh split into n meshes, ppMeshArrayOut is an array of n ID3DXMesh pointers.
ppAdjacencyArrayOut
[out, retval] Buffer containing an array of adjacency arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppFaceRemapArrayOut
[out, retval] Buffer containing an array of face remap arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppVertRemapArrayOut
[out, retval] Buffer containing an array of vertex remap arrays for the new meshes. See ID3DXBuffer. This parameter is optional.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

A common use of this function is to split a mesh with 32-bit indices (more than 65535 vertices) into more than one mesh, each of which has 16-bit indices.

The adjacency, vertex remap and face remap arrays are arrays are DWORDs where each array contains n DWORD pointers, followed by the DWORD data referenced by the pointers. For example, to obtain the face remap information for face 3 in mesh 2, the following code could be used, assuming the face remap data was returned in a variable named ppFaceRemapArrayOut.

const DWORD **face_remaps =
    static_cast<DWORD **>(ppFaceRemapArrayOut->GetBufferPointer());
const DWORD remap = face_remaps[2][3];

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXTessellateNPatches Function

Tessellates the given mesh using the N-patch tessellation scheme.

Syntax

HRESULT D3DXTessellateNPatches(

    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    FLOAT NumSegs,
    BOOL QuadraticInterpNormals,
    LPD3DXMESH *ppMeshOut,
    LPD3DXBUFFER *ppAdjacencyOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to tessellate.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. This parameter may be NULL.
NumSegs
[in] Number of segments per edge to tessellate.
QuadraticInterpNormals
[in] If set to TRUE, use quadratic interpolation for normals. If set to FALSE, use linear interpolation.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned tessellated mesh.
ppAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the output mesh. This parameter may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This function tessellates by using the N-patch algorithm.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXTessellateRectPatch Function

Tessellates a rectangular higher-order surface patch into a triangle mesh.

Syntax

HRESULT D3DXTessellateRectPatch(

    LPDIRECT3DVERTEXBUFFER9 pVB,
    CONST float *pNumSegs,
    LPD3DVERTEXELEMENT9 pInDecl,
    CONST D3DRECTPATCH_INFO *pRectPatchInfo,
    LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Number of segments per edge to tessellate.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pRectPatchInfo
[in] Describes a rectangular patch. See D3DRECTPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Use D3DXRectPatchSize to get the number of output vertices and indices that the tessellation function needs.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateTriPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DXTessellateTriPatch Function

Tessellates a triangular higher-order surface patch into a triangle mesh.

Syntax

HRESULT D3DXTessellateTriPatch(

    LPDIRECT3DVERTEXBUFFER9 pVB,
    CONST float *pNumSegs,
    LPD3DVERTEXELEMENT9 pInDecl,
    CONST D3TRIPATCH_INFO *pTriPatchInfo,
    LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Number of segments per edge to tessellate.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pTriPatchInfo
[in] Describes a triangle patch. See D3DTRIPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Use D3DXTriPatchSize to get the number of output vertices and indices that the tessellation function needs.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateRectPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DXTriPatchSize Function

Gets the size of the triangle patch.

Syntax

HRESULT D3DXTriPatchSize(

    CONST FLOAT* pNumSegs,
    DWORD* pdwTriangles,
    DWORD* pdwVertices
);

Parameters

pNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pdwVertices
[out] Pointer to a DWORD that contains the number of vertices in the triangle patch.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateTriPatch

© 2002 Microsoft Corporation. All rights reserved.


D3DXValidMesh Function

Validates a mesh.

Syntax

HRESULT D3DXValidMesh(

    LPD3DXMESH pMeshIn,
    CONST DWORD *pAdjacency,
    LPD3DXBUFFER *ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be tested.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be tested.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_INVALIDMESH | The mesh is invalid.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method validates the mesh by checking for invalid indices. Error information is available from the debug spew.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXWeldVertices Function

Welds together replicated vertices that have equal attributes. This method uses specified epsilons for equality comparisons.

Syntax

HRESULT D3DXWeldVertices(

    const LPD3DXMESH pMesh,
    DWORD Flags,
    CONST D3DXWELDEPSILONS* pEpsilon,
    CONST DWORD* pAdjacencyIn,
    DWORD* pAdjacencyOut,
    DWORD* pFaceRemap,
    LPD3DXBUFFER* ppVertexRemap
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh object, the mesh from which to weld vertices.
Flags
[in] Combination of one or more flags from D3DXMESH.
pEpsilon
[in] Pointer to a D3DXWELDEPSILONS structure, specifying the epsilon values to be used for this method.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff. If this parameter is set to NULL, ID3DXBaseMesh::GenerateAdjacency will be called to create logical adjacency information.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, containing the new index for each vertex.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method uses the provided adjacency information to determine the points that are replicated. This method uses an epsilon compare to merge vertices, and requires vertices with equal position to already have been calculated and represented by point-representative data.

This method takes logically welded vertices and combines the ones that have similar components, such as normals within pEpsilon or texture coordinates within pEpsilon.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Miscellaneous Functions

Direct3D extensions (D3DX) supplies the following general purpose functions.

  • D3DXCreateBuffer
  • D3DXCreateFont
  • D3DXCreateFontIndirect
  • D3DXCreateRenderToEnvMap
  • D3DXCreateRenderToSurface
  • D3DXCreateSprite
  • D3DXGetFVFVertexSize

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateBuffer Function

Creates a buffer object.

Syntax

HRESULT D3DXCreateBuffer(

    DWORD NumBytes,
    LPD3DXBUFFER *ppBuffer
);

Parameters

NumBytes
[in] Size of the buffer to create, in bytes.
ppBuffer
[out] Address of a pointer to an ID3DXBuffer interface, representing the created buffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

E_OUTOFMEMORY Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateFont Function

Creates a font object for a device and font.

Syntax

HRESULT D3DXCreateFont(

    LPDIRECT3DDEVICE9 pDevice,
    HFONT hFont,
    LPD3DXFONT *ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
hFont
[in] Handle to the font object.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateFontIndirect Function

Creates an font object indirectly for a device and font.

Syntax

HRESULT D3DXCreateFontIndirect(

    LPDIRECT3DDEVICE9 pDevice,
    CONST LOGFONT *pLogFont,
    LPD3DXFONT *ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
pLogFont
[in] Pointer to a LOGFONT structure, describing the attributes of the font object to create.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

For more information about the LOGFONT structure, see the Microsoft Platform Software Development Kit (SDK).

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateRenderToEnvMap Function

Creates a render environment map.

Syntax

HRESULT D3DXCreateRenderToEnvMap(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Size,
    UINT MipLevels,
    D3DFORMAT Format,
    BOOL DepthStencil,
    D3DFORMAT DepthStencilFormat,
    LPD3DXRENDERTOENVMAP *ppRenderToEnvMap
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, which is the device to associate with the render surface.
Size
[in] Size of the render surface.
MipLevels
[in] The number of mipmap levels.
Format
[in] Member of the D3DFORMAT enumerated type that describes the pixel format of the environment map.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type that describes the depth-stencil format of the environment map.
ppRenderToEnvMap
[out, retval] Address of a pointer to an ID3DXRenderToEnvMap interface that represents the created render environment map.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateRenderToSurface Function

Creates a render surface.

Syntax

HRESULT D3DXCreateRenderToSurface(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    BOOL DepthStencil,
    D3DFORMAT DepthStencilFormat,
    LPD3DXRENDERTOSURFACE *ppRenderToSurface
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the render surface.
Width
[in] Width of the render surface, in pixels.
Height
[in] Height of the render surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE. This function will create a new depth buffer.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.
ppRenderToSurface
[out, retval] Address of a pointer to an ID3DXRenderToSurface interface, representing the created render surface.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSprite Function

Creates a sprite object which is associated with a particular device. Sprite objects are used to draw 2-D images to the screen.

Syntax

HRESULT D3DXCreateSprite(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXSPRITE *ppSprite
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the sprite.
ppSprite
[out] Address of a pointer to an ID3DXSprite interface. This interface allows the user to access sprite functions.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This interface can be used to draw two dimensional images in screen space of the associated device.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetFVFVertexSize Function

Returns the size of a vertex for a flexible vertex format (FVF).

Syntax

UINT D3DXGetFVFVertexSize(

    DWORD FVF
);

Parameters

FVF
[in] FVF to be queried. A combination of D3DFVF.

Return Value

The flexible vertex format vertex size, in bytes.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Shader Functions

Direct3D extensions (D3DX) supplies the following shader functions.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFile
  • D3DXAssembleShaderFromResource
  • D3DXCompileShader
  • D3DXCompileShaderFromFile
  • D3DXCompileShaderFromResource
  • D3DXCreateFragmentLinker
  • D3DXFindShaderComment
  • D3DXGatherFragments
  • D3DXGatherFragmentsFromFile
  • D3DXGatherFragmentsFromResource
  • D3DXGetShaderConstantTable
  • D3DXGetShaderDebugInfo
  • D3DXGetShaderInputSemantics
  • D3DXGetShaderOutputSemantics
  • D3DXGetShaderSamplers

For more information about using vertex shaders, see Vertex Shaders.

For more information about using pixel shaders, see Pixel Shaders.

© 2002 Microsoft Corporation. All rights reserved.


D3DXAssembleShader Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShader(

    LPCTSTR pSrcData,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a memory buffer that contains the shader data. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderW. Otherwise, the function call resolves to D3DXAssembleShaderA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXAssembleShaderFromFile Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShaderFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromFileW. Otherwise, the function call resolves to D3DXAssembleShaderFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXAssembleShaderFromResource Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShaderFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromResourceW. Otherwise, the function call resolves to D3DXAssembleShaderFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCompileShader Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShader(

    LPCTSTR pSrcData,
    UINT srcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCTSTR pFunctionName,
    LPCTSTR pTarget,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER* ppErrorMsgs,
    LPD3DXSHADER_CONSTANTTABLE* ppConstantTable
);

Parameters

pSrcData
[in] Pointer to a string that contains the shader. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
srcDataLen
[in] Length of the data in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to a string that contains the name of the shader entry point function where execution begins. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pTarget
[in] Pointer to a string that contains the compile target. See Remarks.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns a pointer to the D3DXSHADER_CONSTANTTABLE block which is embedded inside the shader. Use this block to access shader constants using D3DXGetShaderConstantTable. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Targets can be specified for vertex shaders, pixel shaders, and texture fill functions.

Vertex shader targets | vs_1_1, vs_2_0, vs_2_sw
Pixel shader targets | ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw
Texture fill targets | tx_0, tx_1

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderW. Otherwise, the function call resolves to D3DXCompileShaderA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCompileShaderFromFile Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShaderFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCTSTR pFunctionName,
    LPCTSTR pTarget,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs,
    LPD3DXSHADER_CONSTANTTABLE *ppConstantTable
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to to the shader entry point function where execution begins. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pTarget
[in] Pointer to a string that contains the compile target. See Remarks.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns a pointer to the D3DXSHADER_CONSTANTTABLE block which is embedded inside the shader. Use this block to access shader constants using D3DXGetShaderConstantTable. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Targets can be specified for vertex shaders, pixel shaders, and texture fill functions.

Vertex shader targets | vs_1_1, vs_2_0, vs_2_sw
Pixel shader targets | ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw
Texture fill targets | tx_0, tx_1

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderFromFileW. Otherwise, the function call resolves to D3DXCompileShaderFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCompileShaderFromResource Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShaderFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCTSTR pFunctionName,
    LPCTSTR pTarget,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs,
    LPD3DXSHADER_CONSTANTTABLE *ppConstantTable
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file, or will error when compiled from a resource or memory.
pFunctionName
[in] Pointer to the shader entry point function where execution begins. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pTarget
[in] Pointer to a string that contains the compile target. See Remarks.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns a pointer to the D3DXSHADER_CONSTANTTABLE block which is embedded inside the shader. Use this block to access shader constants using D3DXGetShaderConstantTable. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

Targets can be specified for vertex shaders, pixel shaders, and texture fill functions.

Vertex shader targets | vs_1_1, vs_2_0, vs_2_sw
Pixel shader targets | ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw
Texture fill targets | tx_0, tx_1

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderFromResourceW. Otherwise, the function call resolves to D3DXCompileShaderFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateFragmentLinker Function

Create a fragment linker. This can be used to link one or more shader fragments together.

Syntax

HRESULT WINAPI D3DXCreateFragmentLinker(

    LPDIRECT3DDEVICE9 pDevice,
    UINT ShaderCacheSize,
    LPD3DXFRAGMENTLINKER *ppFragmentLinker
);

Parameters

pDevice
[in] Pointer to the current device. See IDirect3DDevice9.
ShaderCacheSize
[in] Shader cache size in bytes. This can be used for optimization.
ppFragmentLinker
[out] Returns a pointer to the new fragment linker interface. See ID3DXFragmentLinker.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFindShaderComment Function

Searches through a shader for a particular comment. The comment is identified by a four-character code (FOURCC) in the first DWORD of the comment.

Syntax

HRESULT WINAPI D3DXFindShaderComment(

    CONST DWORD* pFunction,
    DWORD FourCC,
    LPCVOID* ppData,
    UINT* pSizeInBytes
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
FourCC
[in] FOURCC code that identifies the comment block.
ppData
[in] Returns a pointer to the comment data (not including the comment token and FOURCC code). This value can be NULL.
pSizeInBytes
[out] Returns the size of the comment data in bytes. This value can be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the comment is not found, and no other error has occurred, S_FALSE is returned.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGatherFragments Function

Gathers shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragments(

    LPCTSTR pSrcFile,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsW. Otherwise, the function call resolves to D3DXGatherFragmentsA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateFragmentLinker

© 2002 Microsoft Corporation. All rights reserved.


D3DXGatherFragmentsFromFile Function

Gathers shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragmentsFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromFileW. Otherwise, the function call resolves to D3DXGatherFragmentsFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

See Also

D3DXCreateFragmentLinker

© 2002 Microsoft Corporation. All rights reserved.


D3DXGatherFragmentsFromResource Function

Gather shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragmentsFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromResourceW. Otherwise, the function call resolves to D3DXGatherFragmentsFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

See Also

D3DXCreateFragmentLinker

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetShaderConstantTable Function

Gets the shader constant table embedded inside shader.

Syntax

HRESULT WINAPI D3DXGetShaderConstantTable(

    CONST DWORD* pFunction,
    LPD3DXCONSTANTTABLE* ppConstantTable
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.
ppConstantTable
[out, retval] Returns the constant table interface that manages the constant table. See ID3DXConstantTable.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

A constant table is generated by D3DXCompileShader and embedded in the body of the shader.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetShaderDebugInfo Function

Gets shader debug information.

Syntax

HRESULT WINAPI D3DXGetShaderDebugInfo(

    CONST DWORD* pFunction,
    LPD3DXBUFFER* ppDebugInfo
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
ppDebugInfo
[out] Pointer to an optional buffer used to return debug information. This buffer will be set to NULL and unused if the debug information is already in Microsoft® DirectX® 9.0 format. The data in the buffer is organized by this structure, D3DXSHADER_DEBUGINFO.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The shader debug information is included as a comment block inside shaders. All offsets are measured in bytes from the beginning of the structure.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSHADER_INSTRUCTIONINFO

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetShaderInputSemantics Function

Get the semantics for all shader input elements.

Syntax

HRESULT WINAPI D3DXGetShaderInputSemantics(

    CONST DWORD* pFunction,
    D3DXSEMANTICS* pSemantics,
    UINT* pSizeInBytes
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each input element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderInputSemantics with pSemantics = NULL will return the size of the array needed for pSizeInBytes.
pSizeInBytes
[out] Returns the size of the shader semantics, in bytes.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetShaderOutputSemantics Function

Get the semantics for all shader output elements.

Syntax

HRESULT WINAPI D3DXGetShaderOutputSemantics(

    CONST DWORD* pFunction,
    D3DXSEMANTICS* pSemantics,
    UINT* pSizeInBytes
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each output element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderOutputSemantics with pSemantics = NULL will return the size of the array needed for pSizeInBytes.
pSizeInBytes
[out] Returns the size of the shader semantics, in bytes.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetShaderSamplers Function

Get the sampler names referenced in a shader.

Syntax

HRESULT WINAPI D3DXGetShaderSamplers(

    CONST DWORD* pFunction,
    LPCSTR* pSamplers,
    UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSamplers
[in, out] Pointer to an array of LPCSTRs. The function will fill this array with pointers to the sampler names contained within pFunction. The maximum array size is the maximum number of sampler registers (16 for vs_3_0 and ps_3_0).

To find the number of samplers used, check pCount after calling D3DXGetShaderSamplers with pSamplers = NULL.

pCount
[out] Returns the number of samplers referenced by the shader.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Shape Drawing Functions

Direct3D extensions (D3DX) supplies the following shape-drawing functions.

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateText
  • D3DXCreateTorus

All shapes are returned as mesh objects.

These functions can be used in either a left-handed or right-handed coordinate system.

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateBox Function

Uses a left-handed coordinate system to create a mesh containing an axis-aligned box.

Syntax

HRESULT D3DXCreateBox(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Width,
    FLOAT Height,
    FLOAT Depth,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
Width
[in] Width of the box, along the x-axis.
Height
[in] Height of the box, along the y-axis.
Depth
[in] Depth of the box, along the z-axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The created box is centered at the origin.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCylinder Function

Uses a left-handed coordinate system to create a mesh containing a cylinder.

Syntax

HRESULT D3DXCreateCylinder(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Radius1,
    FLOAT Radius2,
    FLOAT Length,
    UINT Slices,
    UINT Stacks,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created cylinder mesh.
Radius1
[in] Radius at the negative Z end. Value should be greater than or equal to 0.0f.
Radius2
[in] Radius at the positive Z end. Value should be greater than or equal to 0.0f.
Length
[in] Length of the cylinder along the z-axis.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The created cylinder is centered at the origin, and its axis is aligned with the z-axis.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreatePolygon Function

Uses a left-handed coordinate system to create a mesh containing an n-sided polygon.

Syntax

HRESULT D3DXCreatePolygon(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Length,
    UINT Sides,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created polygon mesh.
Length
[in] Length of each side.
Sides
[in] Number of sides for the polygon. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The created polygon is centered at the origin.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateSphere Function

Uses a left-handed coordinate system to create a mesh containing a sphere.

Syntax

HRESULT D3DXCreateSphere(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Radius,
    UINT Slices,
    UINT Stacks,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created sphere mesh.
Radius
[in] Radius of the sphere. This value should be greater than or equal to 0.0f.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The created sphere is centered at the origin, and its axis is aligned with the z-axis.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTeapot Function

Uses a left-handed coordinate system to create a mesh containing a teapot.

Syntax

HRESULT D3DXCreateTeapot(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created teapot mesh.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateText Function

Creates a mesh containing the specified text, using the font associated with the device context.

Syntax

HRESULT D3DXCreateText(

    LPDIRECT3DDEVICE9 pDevice,
    HDC hDC,
    LPCTSTR pText,
    FLOAT Deviation,
    FLOAT Extrusion,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency,
    LPGLYPHMETRICSFLOAT pGlyphMetrics
);

Parameters

pDevice
[in] Pointer to the device that created the mesh.
hDC
[in] Device context, containing the font for output. The font selected by the device context must be a TrueType font.
pText
[in] Pointer to a string that specifies the text to generate. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Deviation
[in] Maximum chordal deviation from TrueType font outlines.
Extrusion
[in] Amount to extrude text in the negative z-direction.
ppMesh
[out] Pointer to the returned mesh.
ppAdjacency
[out] Pointer to a buffer containing adjacency information.
pGlyphMetrics
[out] Pointer to an array of LPGLYPHMETRICSFLOAT structures that contain the glyph metric data. Each element contains information about the position and orientation of the corresponding glyph in the string. The number of elements in the array should be equal to the number of characters in the string. Note that the origin in each structure is not relative to the entire string, but rather is relative to that character cell. To compute the entire bounding box, add the increment for each glyph while traversing the string.

If you are not concerned with the glyph sizes, set this parameter to NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextW. Otherwise, the function call resolves to D3DXCreateTextA because ANSI strings are being used.

For more information about the LPGLYPHMETRICSFLOAT structure, see the Microsoft Platform Software Development Kit (SDK).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTorus Function

Uses a left-handed coordinate system to create a mesh containing a torus.

Syntax

HRESULT D3DXCreateTorus(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT InnerRadius,
    FLOAT OuterRadius,
    UINT Sides,
    UINT Rings,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created torus mesh.
InnerRadius
[in] Inner-radius of the torus. Value should be greater than or equal to 0.0f.
OuterRadius
[in] Outer-radius of the torus. Value should be greater than or equal to 0.0f.
Sides
[in] Number of sides in a cross-section. Value must be greater than or equal to 3.
Rings
[in] Number of rings making up the torus. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The D3DXCreateTorus function draws a doughnut, centered at (0, 0, 0) whose axis is aligned with the z-axis. The inner-radius of the torus is the radius of the cross-section (the minor-radius), and the outer-radius of the torus is the radius of the central hole.

This function returns a mesh that can be used later for drawing or manipulation by the application.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Texturing Functions

Direct3D extensions (D3DX) supplies the following texturing functions.

Functions

  • D3DXCheckCubeTextureRequirements
  • D3DXCheckTextureRequirements
  • D3DXCheckVolumeTextureRequirements
  • D3DXComputeNormalMap
  • D3DXCreateCubeTexture
  • D3DXCreateCubeTextureFromFile
  • D3DXCreateCubeTextureFromFileEx
  • D3DXCreateCubeTextureFromFileInMemory
  • D3DXCreateCubeTextureFromFileInMemoryEx
  • D3DXCreateCubeTextureFromResource
  • D3DXCreateCubeTextureFromResourceEx
  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx
  • D3DXCreateVolumeTexture
  • D3DXCreateVolumeTextureFromFile
  • D3DXCreateVolumeTextureFromFileEx
  • D3DXCreateVolumeTextureFromFileInMemory
  • D3DXCreateVolumeTextureFromFileInMemoryEx
  • D3DXCreateVolumeTextureFromResource
  • D3DXCreateVolumeTextureFromResourceEx
  • D3DXFillCubeTexture
  • D3DXFillCubeTextureTX
  • D3DXFillTexture
  • D3DXFillTextureTX
  • D3DXFillVolumeTexture
  • D3DXFillVolumeTextureTX
  • D3DXFilterTexture
  • D3DXGetImageInfoFromFile
  • D3DXGetImageInfoFromFileInMemory
  • D3DXGetImageInfoFromResource
  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • D3DXLoadVolumeFromFile
  • D3DXLoadVolumeFromFileInMemory
  • D3DXLoadVolumeFromMemory
  • D3DXLoadVolumeFromResource
  • D3DXLoadVolumeFromVolume
  • D3DXSaveSurfaceToFile
  • D3DXSaveTextureToFile
  • D3DXSaveVolumeToFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXCheckCubeTextureRequirements Function

Checks cube-texture-creation parameters.

Syntax

HRESULT D3DXCheckCubeTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pSize,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSize
[in, out] Pointer to the requested width and height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCheckTextureRequirements Function

Checks texture-creation parameters.

Syntax

HRESULT D3DXCheckTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pWidth,
    UINT *pHeight,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTargetmethod. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCheckVolumeTextureRequirements Function

Checks volume-texture-creation parameters.

Syntax

HRESULT D3DXCheckVolumeTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pWidth,
    UINT *pHeight,
    UINT *pDepth,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pDepth
[in, out] Pointer to the requested depth in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] Currently not used, set to 0.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXComputeNormalMap Function

Converts a height map into a normal map. The (x,y,z) components of each normal are mapped to the (r,g,b) channels of the output texture.

Syntax

HRESULT D3DXComputeNormalMap(

    LPDIRECT3DTEXTURE9 pTexture,
    LPDIRECT3DTEXTURE9 pSrcTexture,
    const PALETTEENTRY *pSrcPalette,
    DWORD Flags,
    DWORD Channel,
    FLOAT Amplitude
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the destination texture.
pSrcTexture
[in, retval] Pointer to an IDirect3DTexture9 interface, representing the source height-map texture.
pSrcPalette
[in] Pointer to a PALETTEENTRY type that contains the source palette of 256 colors or NULL.
Flags
[in] One or more D3DX_NORMALMAP flags that control generation of normal maps.
Channel
[in, out] One D3DX_CHANNEL flag specifying the source of height information.
Amplitude
[in] Constant value by which the height information is multiplied.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following value.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method computes the normal by using the central difference with a kernel size of 3x3. RGB channels in the destination contain biased (x,y,z) components of the normal.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTexture Function

Creates an empty cube texture, adjusting the calling parameters as needed.

Syntax

HRESULT D3DXCreateCubeTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces.

Internally, D3DXCreateCubeTexture uses D3DXCheckCubeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateCubeTexture will often succeed where calls to IDirect3DDevice9::CreateCubeTexture would fail.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromFile Function

Creates a cube texture from a file.

Syntax

HRESULT D3DXCreateCubeTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromFile uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromFileEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromFileEx Function

Creates a cube texture from a file. This is a more advanced function than D3DXCreateCubeTextureFromFile.

Syntax

HRESULT D3DXCreateCubeTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromFileEx uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromFile, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromFileInMemory Function

Creates a cube texture from a file in memory.

Syntax

HRESULT D3DXCreateCubeTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cubemap. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

D3DXCreateCubeTextureFromFileInMemory uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromFileInMemoryEx Function

Creates a cube texture from a file in memory. This is a more advanced function than D3DXCreateCubeTextureFromFileInMemory.

Syntax

HRESULT D3DXCreateCubeTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cube texture. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
Size
[in] Width (or height) in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget .

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

For details on PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateCubeTextureFromFileInMemoryEx uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromResource Function

Creates a cube texture from a resource.

Syntax

HRESULT D3DXCreateCubeTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromResourceA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromResource uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateCubeTextureFromResourceEx Function

Creates a cube texture from a resource specified by a string. This is a more advanced function than D3DXCreateCubeTextureFromResource.

Syntax

HRESULT D3DXCreateCubeTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCSTR hSrcModule,
    LPCTSTR pSrcResource,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports both Unicode and ANSI strings.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromResourceEx uses the Microsoft DirectDraw® surface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromResource, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTexture Function

Creates an empty texture, adjusting the calling parameters as needed.

Syntax

HRESULT D3DXCreateTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Width
[in] Width in pixels. If this value is 0, a value of 1 is used. See Remarks.
Height
[in] Height in pixels. If this value is 0, a value of 1 is used. See Remarks.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget" parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture may be a different format from that specified, if the device does not support the requested format. Applications should check the format of the returned texture to see if it matches the format requested.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Internally, D3DXCreateTexture uses D3DXCheckTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateTexture will often succeed where calls to IDirect3DDevice9::CreateTexture would fail.

If both Height and Width are set to D3DX_DEFAULT, a value of 256 is used for both parameters. If Height and Width are set to D3DX_DEFAULT and the other parameter is set to a numeric value, the texture is square, with the height and width of the texture equal to the numeric value.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromFile Function

Creates a texture from a file.

Syntax

HRESULT D3DXCreateTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileW. Otherwise, the function call resolves to D3DXCreateTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

The function is equivalent to D3DXCreateTextureFromFileExW(pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture).

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

For the best performance when using D3DXCreateTextureFromFile:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of two dimensions, create and store images using power of two dimensions.
  2. Consider using Microsoft DirectDraw® surface (DDS) files. Because DDS files can be used to represent any Microsoft DirectX® 9.0 texture format, they are very easy for Direct3D extensions (D3DX) to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromFileEx Function

Creates a texture from a file. This is a more advanced function than D3DXCreateTextureFromFile.

Syntax

HRESULT D3DXCreateTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Performance OptimizationsUsing Dynamic Textures.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For the best performance when using D3DXCreateTextureFromFileEx:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of 2 dimensions, then create and store images using power of 2 dimensions.
  2. For mipmap image creation at load time, filter using D3DXFILTER_BOX. A box filter is much faster than other filter types such as D3DXFILTER_TRIANGLE.
  3. Consider using DDS files. Since DDS files can be used to represent any Microsoft DirectX® 9.0 texture format, they are very easy for Direct3D extensions (D3DX) to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFile, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromFileInMemory Function

Creates a texture from a file in memory.

Syntax

HRESULT D3DXCreateTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcData,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcData
[in] Size of the file in memory, in bytes.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileInMemoryEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromFileInMemoryEx Function

Creates a texture from a file in memory. This is a more advanced function than D3DXCreateTextureFromFileInMemory.

Syntax

HRESULT D3DXCreateTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. Each valid filter must contain one of the flags in D3DX_FILTER.
MipFilter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. Each valid filter must contain one of the flags in D3DX_FILTER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

For details about PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileInMemory, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromResource Function

Creates a texture from a resource.

Syntax

HRESULT D3DXCreateTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateTextureFromResourceEx Function

Creates a texture from a resource. This is a more advanced function than D3DXCreateTextureFromResource.

Syntax

HRESULT D3DXCreateTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Performance OptimizationsUsing Dynamic Textures.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format . Applications should check the format of the returned texture. If Formatis D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceExA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromResource, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTexture Function

Creates an empty volume texture, adjusting the calling parameters as needed.

Syntax

HRESULT D3DXCreateVolumeTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
Width
[in] Width in pixels. This value must be nonzero.
Height
[in] Height in pixels. This value must be nonzero.
Depth
[in] Depth in pixels. This value must be nonzero.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_DYNAMIC. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the volume texture. The returned volume texture might have a different format from that specified by Format. Applications should check the format of the returned volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Internally, D3DXCreateVolumeTexture uses D3DXCheckVolumeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateVolumeTexture will often succeed where calls to IDirect3DDevice9::CreateVolumeTexture would fail.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromFile Function

Creates a volume texture from a file.

Syntax

HRESULT D3DXCreateVolumeTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DVOLUMETEXTURE9 ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromFileEx Function

Creates a volume texture from a file.

Syntax

HRESULT D3DXCreateVolumeTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Mipmapped textures automatically have each level filled with the loaded volume texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromFileInMemory Function

Creates a volume texture from a file in memory.

Syntax

HRESULT D3DXCreateVolumeTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcFile,
    UINT SrcData,
    LPDIRECT3DVOLUMETEXTURE9 ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to the file in memory from which to create the volume texture.
SrcData
[in] Size of the file in memory, in bytes.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromFileInMemoryEx Function

Creates a volume texture from a file. This is a more advanced function than D3DXCreateVolumeTextureFromFileInMemory.

Syntax

HRESULT D3DXCreateVolumeTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the volume texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromResource Function

Creates a volume texture from a resource.

Syntax

HRESULT D3DXCreateVolumeTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DVOLUMETEXTURE9 ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceA because ANSI strings are being used.

The resource being loaded must be a bitmap resource (RT_BITMAP).

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResourceEx, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateVolumeTextureFromResourceEx Function

Creates a volume texture from a resource specified by a string. This is a more advanced function than D3DXCreateVolumeTextureFromResource.

Syntax

HRESULT D3DXCreateVolumeTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft® Direct3D® does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceExA because ANSI strings are being used.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillCubeTexture Function

Uses a user-provided function to fill each texel of each mip level of a given cube texture.

Syntax

HRESULT D3DXFillCubeTexture(

    LPDIRECT3DCUBETEXTURE9 pTexture,
    LPD3DXFILL3D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DCubeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Here is an example that creates a function called ColorCubeFill, which relies on D3DXFillCubeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorCubeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Create volume texture using D3DXFillCubeTexture
if (FAILED (hr = D3DXFillCubeTexture (m_pTexture, ColorCubeFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillCubeTextureTX Function

Uses a high-level language texture target to fill each texel of each mipmap level of a texture.

Syntax

HRESULT D3DXFillCubeTextureTX(

    LPDIRECT3DCUBETEXTURE9 pTexture,
    CONST WORD* pFunction,
    CONST D3DXVECTOR4* pConstants,
    UINT dxConstants
);

Parameters

pTexture
[in] Pointer to an IDirect3DCubeTexture9 object, representing the texture to be filled.
pFunction
[in] Pointer to a buffer containing the compiled function.
pConstants
[in] Array of constants. This is provided by the application from the constant table. See D3DXVECTOR4.
dxConstants
[in] Number of constants.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The high-level language texture target should be a compiled function taking two parameters and returning a color.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillTextureTX, D3DXFillVolumeTextureTX

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillTexture Function

Uses a user-provided function to fill each texel of each mip level of a given texture.

Syntax

HRESULT D3DXFillTexture(

    LPDIRECT3DTEXTURE9 pTexture,
    LPD3DXFILL2D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DFILL2D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Here is an example that creates a function called ColorFill, which relies on D3DXFillTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorFill (D3DXVECTOR4* pOut, const D3DXVECTOR2* pTexCoord,
const D3DXVECTOR2* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, 0.0f, 0.0f);
}

// Create volume texture using D3DXFillTexture
if (FAILED (hr = D3DXFillTexture (m_pTexture, ColorFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillTextureTX Function

Uses a high-level language texture target to fill each mipmap level of a texture.

Syntax

HRESULT D3DXFillTextureTX(

    LPDIRECT3DTEXTURE9 pTexture,
    CONST WORD* pFunction,
    CONST D3DXVECTOR4* pConstants,
    UINT dxConstants
);

Parameters

pTexture
[in, out] Pointer to an IDirect3DTexture9 object, representing the texture to be filled.
pFunction
[in] Pointer to a buffer containing the compiled shader function. This can be created using D3DXCompileShader.
pConstants
[in] Array of constants. This is provided by the application from the constant table. See D3DXVECTOR4. This value can be NULL.
dxConstants
[in] Number of constants. This can be 0 if pConstants = NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

EffectEdit Sample demonstrates the use of this function.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillCubeTextureTX, D3DXFillVolumeTextureTX

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillVolumeTexture Function

Uses a user-provided function to fill each texel of each mip level of a given volume texture.

Syntax

HRESULT D3DXFillVolumeTexture(

    LPDIRECT3DVOLUMETEXTURE9 pTexture,
    LPD3DXFILL3D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DVolumeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXFillVolumeTexture will fail because Direct3D extensions (D3DX) cannot lock nondynamic volumes located in video memory.

Here is an example that creates a function called ColorCubeFill, which relies on D3DXFillVolumeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorVolumeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Create volume texture using D3DXFillVolumeTexture
if (FAILED (hr = D3DXFillVolumeTexture (m_pTexture, ColorVolumeFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFillVolumeTextureTX Function

Uses a high-level language texture target to fill each texel of each texture mipmap level.

Syntax

HRESULT D3DXFillVolumeTextureTX(

    LPDIRECT3DVOLUMETEXTURE9 pTexture,
    CONST WORD* pFunction,
    CONST D3DXVECTOR4* pConstants,
    UINT dxConstants
);

Parameters

pTexture
[in] Pointer to an IDirect3DVolumeTexture9 object, representing the texture to be filled.
pFunction
[in] Pointer to a buffer containing the compiled function.
pConstants
[in] Array of constants. This is provided by the application from the constant table. See D3DXVECTOR4.
dxConstants
[in] Number of constants.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The high-level language texture target should be a compiled function taking two parameters and returning a color.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillTextureTX, D3DXFillCubeTextureTX

© 2002 Microsoft Corporation. All rights reserved.


D3DXFilterTexture Function

Filters mipmap levels of a texture.

Syntax

HRESULT D3DXFilterTexture(

    LPDIRECT3DBASETEXTURE9 pBaseTexture,
    CONST PALETTEENTRY *pPalette,
    UINT SrcLevel,
    DWORD MipFilter
);

Parameters

pBaseTexture
[in] Pointer to an IDirect3DBaseTexture9 interface that represents the texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure that represents a 256-color palette to fill in, or NULL for nonpalletized formats. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] Level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

A box filter is recursively applied to each texture level to generate the next texture level.

Writing to a non-level-zero surface of the texture will not cause the dirty rectangle to be updated. If D3DXFilterTexture is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the texture.

Textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterTexture because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool.

For details on PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

There is only one texture filtering function, but two macros that call this method.

#define D3DXFilterCubeTexture D3DXFilterTexture
#define D3DXFilterVolumeTexture D3DXFilterTexture

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetImageInfoFromFile Function

Retrieves information about a given image file.

Syntax

HRESULT D3DXGetImageInfoFromFile(

    LPCSTR pSrcFile,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pSrcFile
[in] File name of image to retrieve information about. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This function supports both Unicode and ANSI strings.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFileInMemory, D3DXGetImageInfoFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetImageInfoFromFileInMemory Function

Retrieves information about a given image file in memory.

Syntax

HRESULT D3DXGetImageInfoFromFileInMemory(

    LPCVOID pSrcData,
    UINT SrcDataSize,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pSrcData
[in] VOID pointer to the source file in memory.
SrcDataSize
[in] Size of file in memory, in bytes. .
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXGetImageInfoFromResource Function

Retrieves information about a given image in a resource.

Syntax

HRESULT D3DXGetImageInfoFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcFile,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

hSrcModule
[in] Module where the resource is loaded. Set this parameter to NULL to specify the module associated with the image that the operating system used to create the current process.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGetImageInfoFromResourceW. Otherwise, the function call resolves to D3DXGetImageInfoFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromFileInMemory

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSurfaceFromFile Function

Loads a surface from a file.

Syntax

HRESULT D3DXLoadSurfaceFromFile(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY* pDestPalette,
    CONST RECT* pDestRect,
    LPCTSTR pSrcFile,
    CONST RECT* pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromFileW. Otherwise, the function call resolves to D3DXLoadSurfaceFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSurfaceFromFileInMemory Function

Loads a surface from a file in memory.

Syntax

HRESULT D3DXLoadSurfaceFromFileInMemory(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPCVOID pSrcData,
    UINT SrcData,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcData
[in] Pointer to the file in memory from which to load the surface.
SrcData
[in] Size of the file in memory, in bytes.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFileInMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSurfaceFromMemory Function

Loads a surface from memory.

Syntax

HRESULT D3DXLoadSurfaceFromMemory(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPCVOID pSrcMemory,
    D3DFORMAT SrcFormat,
    UINT SrcPitch,
    CONST PALETTEENTRY *pSrcPalette,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcMemory
[in] Pointer to the upper left corner of the source image in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source image.
SrcPitch
[in] Pitch of source image, in bytes. For DXT formats, this number should represent the width of one row of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the dimensions of the source image in memory. This value cannot be NULL.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSurfaceFromResource Function

Loads a surface from a resource.

Syntax

HRESULT D3DXLoadSurfaceFromResource(

    LPDIRECT3DSURFACE9 pDestSurface,
    const PALETTEENTRY *pDestPalette,
    const RECT *pDestRect,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    const RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromResourceW. Otherwise, the function call resolves to D3DXLoadSurfaceFromResourceA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadSurfaceFromSurface Function

Loads a surface from another surface with color conversion.

Syntax

HRESULT D3DXLoadSurfaceFromSurface(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPDIRECT3DSURFACE9 pSrcSurface,
    CONST PALETTEENTRY *pSrcPalette,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromSurface is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadVolumeFromFile Function

Loads a volume from a file.

Syntax

HRESULT D3DXLoadVolumeFromFile(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    LPCTSTR pSrcFile,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadVolumeFromFileW. Otherwise, the function call resolves to D3DXLoadVolumeFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadVolumeFromFileInMemory Function

Loads a volume from a file in memory.

Syntax

HRESULT D3DXLoadVolumeFromFileInMemory(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcData
[in] Pointer to the file in memory from which to load the volume.
SrcDataSize
[in] Size of the file in memory, in bytes.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .jpg, .png, and .tga.

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFileInMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadVolumeFromMemory Function

Loads a volume from memory.

Syntax

HRESULT D3DXLoadVolumeFromMemory(

    LPDIRECT3DVOLUME9 pDestVolume,
    CONST PALETTEENTRY *pDestPalette,
    CONST D3DBOX *pDestBox,
    LPCVOID pSrcMemory,
    D3DFORMAT SrcFormat,
    UINT SrcRowPitch,
    UINT SrcSlicePitch,
    CONST PALETTEENTRY *pSrcPalette,
    CONST D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcMemory
[in] Pointer to the top-left corner of the source volume in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source volume.
SrcRowPitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one row of cells, in bytes.
SrcSlicePitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one slice of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. NULL is not a valid value for this parameter.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadVolumeFromResource Function

Loads a volume from a resource.

Syntax

HRESULT D3DXLoadVolumeFromResource(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    HMODULE hSrcModule,
    LPCSTR pSrcResource,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the file name of the source image. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

This function supports both Unicode and ANSI strings.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromVolume, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXLoadVolumeFromVolume Function

Loads a volume from another volume.

Syntax

HRESULT D3DXLoadVolumeFromVolume(

    LPDIRECT3DVOLUME9 pDestVolume,
    CONST PALETTEENTRY *pDestPalette,
    CONST D3DBOX *pDestBox,
    LPDIRECT3DVOLUME9 pSrcVolume,
    CONST PALETTEENTRY *pSrcPalette,
    CONST D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcVolume
[in] A Pointer to an IDirect3DVolume9 interface. Specifies the source volume.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromVolume is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, Texture Color Conversions

© 2002 Microsoft Corporation. All rights reserved.


D3DXSaveSurfaceToFile Function

Saves a surface to a file.

Syntax

HRESULT D3DXSaveSurfaceToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DSURFACE9 pSrcSurface,
    const PALETTEENTRY *pSrcPalette,
    const RECT *pSrcRect
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying file format to use when saving.
pSrcSurface
[in] Pointer to IDirect3DSurface9 interface, containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveSurfaceToFileW. Otherwise, the function call resolves to D3DXSaveSurfaceToFileA because ANSI strings are being used.

This function supports the following file formats: .bmp and .dds.

This function handles conversion to and from compressed texture formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveTextureToFile, D3DXSaveVolumeToFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXSaveTextureToFile Function

Saves a texture to a file.

Syntax

HRESULT D3DXSaveTextureToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DBASETEXTURE9 pSrcTexture,
    const PALETTEENTRY *pSrcPalette
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying file format to use when saving.
pSrcTexture
[in] Pointer to IDirect3DBaseTexture9 interface, containing the texture to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveTextureToFileW. Otherwise, the function call resolves to D3DXSaveTextureToFileA because ANSI strings are being used.

This function supports the following file formats: .bmp and .dds.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because Direct3D extensions (D3DX) cannot lock nondynamic volumes located in video memory.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveSurfaceToFile, D3DXSaveVolumeToFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXSaveVolumeToFile Function

Saves a volume to a file.

Syntax

HRESULT D3DXSaveVolumeToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DVOLUME9 pSrcVolume,
    const PALETTEENTRY *pSrcPalette,
    const D3DBOX *pSrcBox
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying file format to use when saving.
pSrcVolume
[in] Pointer to IDirect3DVolume9 interface, containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveVolumeToFileW. Otherwise, the function call resolves to D3DXSaveVolumeToFileA because ANSI strings are being used.

This function supports the following file formats: .bmp and .dds.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because Direct3D extensions (D3DX) cannot lock nondynamic volumes located in video memory.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveSurfaceToFile, D3DXSaveTextureToFile

© 2002 Microsoft Corporation. All rights reserved.


Callback Functions

This section contains information about the following callback functions.

  • LPD3DFILL2D
  • LPD3DFILL3D

© 2002 Microsoft Corporation. All rights reserved.


LPD3DXFILL2D

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
D3DXVECTOR4* pOut,
CONST D3DXVECTOR2* pTexCoord,
CONST D3DXVECTOR2* pTexelSize,
LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

None.

Remarks

Be sure to specify the WINAPI calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

Related Topics

  • LPD3DFILL3D

© 2002 Microsoft Corporation. All rights reserved.


LPD3DXFILL3D

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
D3DXVECTOR4* pOut,
CONST D3DXVECTOR3* pTexCoord,
CONST D3DXVECTOR3* pTexelSize,
LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

None.

Remarks

Be sure to specify the WINAPI calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

Related Topics

  • LPD3DFILL2D

© 2002 Microsoft Corporation. All rights reserved.


Macros

This section contains reference information for the macros provided by the Direct3D extensions (D3DX) utility library.

Macros

  • D3DSINCOSCONST1
  • D3DSINCOSCONST2
  • D3DXToDegree
  • D3DXToRadian

© 2002 Microsoft Corporation. All rights reserved.


D3DSINCOSCONST1 Macro

Creates the first constant (in register src2) for the sincos pixel shader instruction.

Syntax

#define D3DSINCOSCONST1 -1.5500992e-006f, -2.1701389e-005f,  0.0026041667f, 0.00026041668f

Return Value

Returns the first constant needed by sincos.

Macro Information

Header | d3dx9types.h
Minimum operating systems | Windows 98

See Also

sincos, D3DSINCOSCONST2

© 2002 Microsoft Corporation. All rights reserved.


D3DSINCOSCONST2 Macro

Creates the second constant (in register src3) for the sincos pixel shader instruction.

Syntax

#define D3DSINCOSCONST2 -0.020833334f, -0.12500000f, 1.0f, 0.50000000f

Return Value

Returns the second constant needed by sincos.

Macro Information

Header | d3dx9types.h
Minimum operating systems | Windows 98

See Also

sincos, D3DSINCOSCONST1

© 2002 Microsoft Corporation. All rights reserved.


D3DXToDegree Macro

Converts radians into degrees.

Syntax

#define D3DXToDegree( radian ) ((radian) * (180.0f / D3DX_PI))

Parameters

radian
The value, in radians, to convert to degrees.

Return Value

The macro returns the radian value in degrees.

Remarks

The constant D3DX_PI is declared with the following define.

#define D3DX_PI    ((FLOAT)  3.141592654f)

Macro Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

D3DXToRadian

© 2002 Microsoft Corporation. All rights reserved.


D3DXToRadian Macro

Converts degrees into radians.

Syntax

#define D3DXToRadian( degree ) ((degree) * (D3DX_PI / 180.0f))

Parameters

degree
The value, in degrees, to convert to radians.

Return Value

The macro returns the degree value in radians.

Remarks

The constant D3DX_PI is declared with the following define.

#define D3DX_PI    ((FLOAT)  3.141592654f)

Macro Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

D3DXToDegree

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains information about the structures included in the Direct3D extensions (D3DX) utility library.

Structures

  • D3DXATTRIBUTERANGE
  • D3DXATTRIBUTEWEIGHTS
  • D3DXBONECOMBINATION
  • D3DXCOLOR
  • D3DXCOLOR Extensions
  • D3DXCONSTANT_DESC
  • D3DXCONSTANTTABLE_DESC
  • D3DXFRAME
  • D3DXIMAGE_INFO
  • D3DXINTERSECTINFO
  • D3DXKEY_QUATERNION
  • D3DXKEY_VECTOR3
  • D3DXMACRO
  • D3DXMATERIAL
  • D3DXMATRIX
  • D3DXMATRIX Extensions
  • D3DXMATRIXA16
  • D3DXMESHCONTAINER
  • D3DXMESHDATA
  • D3DXPATCHINFO
  • D3DXPLANE
  • D3DXPLANE Extensions
  • D3DXQUATERNION
  • D3DXQUATERNION Extensions
  • D3DXRTE_DESC
  • D3DXRTS_DESC
  • D3DXSHADER_CONSTANTINFO
  • D3DXSHADER_CONSTANTTABLE
  • D3DXSHADER_DEBUGINFO
  • D3DXSHADER_FILEINFO
  • D3DXSHADER_INSTRUCTIONINFO
  • D3DXSHADER_STRUCTMEMBERINFO
  • D3DXSHADER_TYPEINFO
  • D3DXSHADER_VARIABLEINFO
  • D3DXSHADER_WRITEINFO
  • D3DXTRACK_DESC
  • D3DXVECTOR2
  • D3DXVECTOR2 Extensions
  • D3DXVECTOR3
  • D3DXVECTOR3 Extensions
  • D3DXVECTOR4
  • D3DXVECTOR4 Extensions
  • D3DXWELDEPSILONS

© 2002 Microsoft Corporation. All rights reserved.


D3DXATTRIBUTERANGE Structure

Stores an attribute table entry.

Syntax

typedef struct _D3DXATTRIBUTERANGE {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
} D3DXATTRIBUTERANGE;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

The LPD3DXATTRIBUTERANGE type is defined as a pointer to the D3DXATTRIBUTERANGE structure.

typedef D3DXATTRIBUTERANGE* LPD3DXATTRIBUTERANGE;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

ID3DXBaseMesh::DrawSubset

© 2002 Microsoft Corporation. All rights reserved.


D3DXATTRIBUTEWEIGHTS Structure

Specifies mesh weight attributes.

Syntax

typedef struct _D3DXATTRIBUTEWEIGHTS {
    FLOAT Position;
    FLOAT Boundary;
    FLOAT Normal;
    FLOAT Diffuse;
    FLOAT Specular;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
} D3DXATTRIBUTEWEIGHTS;

Members

Position
Position.
Boundary
Blend weight.
Normal
Normal.
Diffuse
Diffuse lighting value.
Specular
Specular lighting value.
Texcoord
Eight texture coordinates.
Tangent
Tangent.
Binormal
Binormal.

Remarks

This structure describes how a simplification operation will consider vertex data when calculating relative costs between collapsing edges. For example, if the Normal field is 0.0, the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, the simplification operation will use the vertex normal component. If the Normal field is 2.0, double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

The LPD3DXATTRIBUTEWEIGHTS type is defined as a pointer to the D3DXATTRIBUTEWEIGHTS structure.

typedef D3DXATTRIBUTEWEIGHTS* LPD3DXATTRIBUTEWEIGHTS;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXCreateSPMesh, D3DXGeneratePMesh, D3DXSimplifyMesh

© 2002 Microsoft Corporation. All rights reserved.


D3DXBONECOMBINATION Structure

Describes a subset of the mesh that has the same attribute and bone combination.

Syntax

typedef struct _D3DXBONECOMBINATION {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
    DWORD *BoneId;
} D3DXBONECOMBINATION, *LPD3DXBONECOMBINATION;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.
BoneId
Pointer to an array of values that identify each of the bones that can be drawn in a single drawing call. Note that the array can be of variable length to accommodate variable length bone combinations of ID3DXSkinInfo::ConvertToIndexedBlendedMesh.

The size of the array varies based on the type of mesh generated. A non-indexed mesh array size is equal to the number of weights per vertex. An indexed mesh array size is equal to the number of bone matrix palette entries.

Remarks

The subset of the mesh described by D3DXBONECOMBINATION can be rendered in a single drawing call.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCOLOR Structure

Describes color values.

Syntax

typedef struct D3DXCOLOR {
    FLOAT r;
    FLOAT g;
    FLOAT b;
    FLOAT a;
} D3DXCOLOR;

Members

r
Red component of the color.
g
Green component of the color.
b
Blue component of the color.
a
Alpha component of the color.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXCOLOR Extensions, which implement overloaded constructors, as well as assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCOLOR Extensions Structure

Supplies the following operator overloads and type casts for D3DXCOLOR structures.

Syntax

#ifdef __cplusplus
public:
    D3DXCOLOR() {}
    D3DXCOLOR(DWORD argb);
    D3DXCOLOR(CONST FLOAT*);
    D3DXCOLOR(CONST D3DCOLORVALUE&);
    D3DXCOLOR(FLOAT r, FLOAT g, FLOAT b, FLOAT a);

    // casting
    operator DWORD()const;

    operator FLOAT*();
    operator CONST FLOAT*()const;

    operator D3DCOLORVALUE*();
    operator CONST D3DCOLORVALUE*() const;

    operator D3DCOLORVALUE&();
    operator CONST D3DCOLORVALUE&() const;

    // assignment operators
    D3DXCOLOR& operator += (CONST D3DXCOLOR&);
    D3DXCOLOR& operator -= (CONST D3DXCOLOR&);
    D3DXCOLOR& operator *= (FLOAT);
    D3DXCOLOR& operator /= (FLOAT);

    // unary operators
    D3DXCOLOR operator + () const;
    D3DXCOLOR operator - () const;

    // binary operators
    D3DXCOLOR operator + (CONST D3DXCOLOR&) const;
    D3DXCOLOR operator - (CONST D3DXCOLOR&) const;
    D3DXCOLOR operator * (FLOAT) const;
    D3DXCOLOR operator / (FLOAT) const;

    friend D3DXCOLOR operator * (FLOAT, CONST D3DXCOLOR&);

    bool operator == (CONST D3DXCOLOR&)const;
    bool operator != (CONST D3DXCOLOR&)const;

#endif //__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXCONSTANT_DESC Structure

A description of a constant in a constant table.

Syntax

typedef struct _D3DXCONSTANT_DESC {
    LPCSTR Name;
    D3DXREGISTER_SET RegisterSet;
    UINT RegisterIndex;
    UINT RegisterCount;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT StructMembers;
    UINT Bytes;
    LPCVOID DefaultValue;
} D3DXCONSTANT_DESC;

Members

Name
Name of the constant.
RegisterSet
Constant data type. See D3DXREGISTER_SET.
RegisterIndex
Zero-based index of the constant in the table.
RegisterCount
Number of registers that contain data.
Class
Parameter class. See D3DXPARAMETER_CLASS.
Type
Parameter type. See D3DXPARAMETER_TYPE.
Rows
Number of rows.
Columns
Number of columns.
Elements
Number of elements in the array.
StructMembers
Number of structure member sub-parameters.
Bytes
Data size in number of bytes.
DefaultValue
Pointer to the default value.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCONSTANTTABLE_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXCONSTANTTABLE_DESC Structure

A description of the constant table.

Syntax

typedef struct _D3DXCONSTANTTABLE_DESC {
    LPCSTR Creator;
    DWORD Version;
    UINT Constants;
} D3DXCONSTANTTABLE_DESC;

Members

Creator
Name of the constant table creator.
Version
Shader version.
Constants
Number of constants in the constant table.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCONSTANT_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXFRAME Structure

Encapsulates a transform frame in a transformation frame hierarchy.

Syntax

typedef struct _D3DXFRAME {
    LPTSTR Name;
    D3DXMATRIX TransformationMatrix;
    LPD3DXMESHCONTAINER pMeshContainer;
    struct _D3DXFRAME *pFrameSibling;
    struct _D3DXFRAME *pFrameFirstChild;
} D3DXFRAME, *LPD3DXFRAME;

Members

Name
Name of the frame.
TransformationMatrix
Transformation matrix.
pMeshContainer
Pointer to the mesh container.
pFrameSibling
Pointer to a sibling frame.
pFrameFirstChild
Pointer to a child frame.

Remarks

An application can derive from this structure to add other data.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXIMAGE_INFO Structure

Returns a description of the original contents of an image file.

Syntax

typedef struct _D3DXIMAGE_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT MipLevels;
    D3DFORMAT Format;
    D3DRESOURCETYPE ResourceType;
    D3DXIMAGE_FILEFORMAT ImageFileFormat;
} D3DXIMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
MipLevels
Number of mip levels in original image.
Format
A value from the D3DFORMAT enumerated type that most closely describes the data in the original image.
ResourceType
Represents the type of the texture stored in the file. It is either D3DRTYPE_TEXTURE, D3DRTYPE_VOLUMETEXTURE, or D3DRTYPE_CUBETEXTURE.
ImageFileFormat
Represents the format of the image file.

Structure Information

Header | d3dx9tex.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXINTERSECTINFO Structure

Describes a ray-triangle intersection.

Syntax

typedef struct _D3DXINTERSECTINFO {
    DWORD FaceIndex;
    FLOAT U;
    FLOAT V;
    FLOAT Dist;
} D3DXINTERSECTINFO, *LPD3DXINTERSECTINFO;

Members

FaceIndex
Index of the triangle that hit the ray.
U
Barycentric coordinate within the triangle where the ray intersects.
V
Barycentric coordinate within the triangle where the ray intersects.
Dist
Distance along the ray where the intersection occurred.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXKEY_QUATERNION Structure

Describes a quaternion key for use in keyframe animation. A quaternion key is a quaternion value at a given time.

Syntax

typedef struct _D3DXKEY_QUATERNION {
    FLOAT Time;
    D3DXQUATERNION Value;
} D3DXKEY_QUATERNION, *LPD3DXKEY_QUATERNION;

Members

Time
Time.
Value
Quaternion containing the value.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXKEY_VECTOR3 Structure

Describes a vector key for use in keyframe animation. It specifies a vector at a given time. This is used for scale and translation keys.

Syntax

typedef struct _D3DXKEY_VECTOR3 {
    FLOAT Time;
    D3DXVECTOR3 Value;
} D3DXKEY_VECTOR3, *LPD3DXKEY_VECTOR3;

Members

Time
Keyframe time stamp.
Value
3-D vector that supplies scale and/or rotation values.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMACRO Structure

Describes preprocessor definitions used by an effect object.

Syntax

typedef struct D3DXMACRO {
    LPCSTR Name;
    LPCSTR Definition;
} D3DXMACRO;

Members

Name
Preprocessor name.
Definition
Definition name.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectFromFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXMATERIAL Structure

Returns material information saved in Microsoft® Direct3D® (.x) files.

Syntax

typedef struct D3DXMATERIAL {
    D3DMATERIAL9 MatD3D;
    LPSTR pTextureFilename;
} D3DXMATERIAL;

Members

MatD3D
D3DMATERIAL9 structure that describes the material properties.
pTextureFilename
Pointer to a string that specifies the file name of the texture.

Remarks

The D3DXLoadMeshFromX and D3DXLoadMeshFromXof functions return an array of D3DXMATERIAL structures that specify the material color and name of the texture for each material in the mesh. The application is then required to load the texture.

The LPD3DXMATERIAL type is defined as a pointer to the D3DXMATERIAL structure.

typedef struct D3DXMATERIAL* LPD3DXMATERIAL;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXLoadMeshFromX, D3DXLoadMeshFromXof

© 2002 Microsoft Corporation. All rights reserved.


D3DXMATRIX Structure

Describes a matrix.

Syntax

typedef struct D3DXMATRIX : public D3DMATRIX {
public:
    D3DXMATRIX() {};
    D3DXMATRIX( CONST FLOAT * );
    D3DXMATRIX( CONST D3DMATRIX& );
    D3DXMATRIX( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // access grants
    FLOAT& operator () ( UINT Row, UINT Col );
    FLOAT  operator () ( UINT Row, UINT Col ) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator *= ( FLOAT );
    D3DXMATRIX& operator /= ( FLOAT );

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator * ( FLOAT ) const;
    D3DXMATRIX operator / ( FLOAT ) const;

    friend D3DXMATRIX operator * ( FLOAT, CONST D3DXMATRIX& );

    BOOL operator == ( CONST D3DXMATRIX& ) const;
    BOOL operator != ( CONST D3DXMATRIX& ) const;

} D3DXMATRIX, *LPD3DXMATRIX;

Members

Remarks

This structure inherits members from the D3DMATRIX structure. C programmers cannot use the D3DXMATRIX structure. They must use the D3DMATRIX structure.

In Direct3D extensions (D3DX), the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1, instead.

C++ programmers can take advantage of operator overloading and type casting with the D3DXMATRIX Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMATRIX Extensions Structure

Supplies the following operator overloads and type casts for D3DXMATRIX structures.

Syntax

#ifdef __cplusplus
typedef struct D3DXMATRIX : public D3DMATRIX
{
public:
    D3DXMATRIX() {};
    D3DXMATRIX(CONST FLOAT*);
    D3DXMATRIX(CONST D3DMATRIX&);
    D3DXMATRIX(FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
               FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
               FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
               FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44);

    // access grants
    FLOAT& operator () (UINT Row, UINT Col);
    FLOAT  operator () (UINT Row, UINT Col) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= (CONST D3DXMATRIX&);
    D3DXMATRIX& operator += (CONST D3DXMATRIX&);
    D3DXMATRIX& operator -= (CONST D3DXMATRIX&);
    D3DXMATRIX& operator *= (FLOAT);
    D3DXMATRIX& operator /= (FLOAT);

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * (CONST D3DXMATRIX&) const;
    D3DXMATRIX operator + (CONST D3DXMATRIX&) const;
    D3DXMATRIX operator - (CONST D3DXMATRIX&) const;
    D3DXMATRIX operator * (FLOAT) const;
    D3DXMATRIX operator / (FLOAT) const;

    friend D3DXMATRIX operator * (FLOAT, CONST D3DXMATRIX&);

    BOOL operator == (CONST D3DXMATRIX&) const;
    BOOL operator != (CONST D3DXMATRIX&) const;

} D3DXMATRIX, *LPD3DXMATRIX;

#else //!__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMATRIXA16 Structure

Defines a 16-byte aligned matrix.

Syntax

typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16();
    _D3DXMATRIXA16( CONST FLOAT * f);
    _D3DXMATRIXA16( CONST D3DMATRIX& m);
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
    void* operator new(size_t s);
    void* operator new[](size_t s);

    // The two operators below are not virtual operators. If you cast
    //   to D3DXMATRIX, do not delete using them
    void operator delete(void* p);
    void operator delete[](void* p);

    struct _D3DXMATRIXA16& operator=(CONST D3DXMATRIX& rhs);
} _D3DXMATRIXA16;

Members

Remarks

A 16-byte aligned matrix, when used by Direct3D extensions (D3DX) math functions, has been optimized for improved performance on Intel Pentium 4 processors. Matrices are aligned independent of where they are created: on the program stack, in the heap, or in global scope. Alignment is accomplished using __declspec(align(16)), which works with Microsoft® Visual C++® .NET and with Visual C++ 6.0 only when the processor pack is installed. Unfortunately, there is no way to detect the processor pack, so byte alignment is turned on by default only with Visual C++ .NET.

Vectors and quaternions are not byte aligned in D3DX. When using vectors and quaternions with D3DX math functions, use _declspec(align(16)) to generate byte aligned vectors and quaternions, because they will perform significantly better. The definition of _declspec is shown here.

#define _ALIGN_16 __declspec(align(16))

Other compilers interpret D3DXMATRIXA16 as D3DXMATRIX. Using this structure on a compiler that does not actually align the matrix can be problematic because it will not expose bugs that ignore alignment. For example, if a D3DXMATRIXA16 object is inside a structure or class, a memcpy World Wide Web link might be done with tight packing (ignoring 16-byte boundaries). This would cause build breaks if the compiler were to sometime add matrix aligning.

Structure Information

Header | d3dx9math.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESHCONTAINER Structure

Encapsulates a mesh object in a transformation frame hierarchy.

Syntax

typedef struct _D3DXMESHCONTAINER {
    LPTSTR Name;
    D3DXMESHDATA MeshData;
    LPD3DXMATERIAL pMaterials;
    LPD3DXEFFECTINSTANCE pEffects;
    DWORD NumMaterials;
    DWORD *pAdjacency;
    LPD3DXSKININFO pSkinInfo;
    struct _D3DXMESHCONTAINER *pNextMeshContainer;
} D3DXMESHCONTAINER, *LPD3DXMESHCONTAINER;

Members

Name
Mesh name.
MeshData
Type of data in the mesh. See D3DXMESHDATA.
pMaterials
Array of mesh materials. See D3DXMATERIAL.
pEffects
Pointer to the effect interface. See D3DXEFFECTINSTANCE.
NumMaterials
Number of materials in the mesh.
pAdjacency
Pointer to an array of three DWORDs per triangle of the mesh that contains adjacency information.
pSkinInfo
Pointer to the skin information interface. See ID3DXSkinInfo.
pNextMeshContainer
Pointer to the next mesh container.

Remarks

An application can derive from this structure to add other data.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESHDATA

Mesh data structure.

Syntax

typedef struct D3DXMESHDATA {

    D3DXMESHDATATYPE Type;

    union
    {
    LPD3DXMESH pMesh;
    LPD3DXMESH pPMesh;
    LPD3DXPATCHMESH pPatchMesh;
    }

} D3DXMESHDATA, *LPD3DXMESHDATA;

Members

Type - Defines the mesh data type. See D3DXMESHDATATYPE.

pMesh - Pointer to a mesh. See ID3DXMesh.

pPMesh - Pointer to a progressive mesh. See ID3DXPMesh.

pPatchMesh - Pointer to a patch mesh. See ID3DXPatchMesh.

Remarks

Header | d3dx9mesh.h
Minimum Operating System | Windows 98

Related Topics

  • D3DXMESHCONTAINER

© 2002 Microsoft Corporation. All rights reserved.


D3DXPATCHINFO Structure

Structure that contains the attributes of a patch mesh.

Syntax

typedef struct _D3DXPATCHINFO {
    DWORD PatchType;
    D3DDEGREETYPE Degree;
    D3DBASISTYPE D3DBasis;
} D3DXPATCHINFO;

Members

PatchType
The patch type. For information about patch types, see D3DXPATCHMESHTYPE.
Degree
Degree of the curves used to construct the patch. For information about the degrees supported, see D3DDEGREETYPE.
D3DBasis
Type of curve used to construct the patch. For information about the basis types supported, see D3DBASISTYPE.

Remarks

A mesh is a set of faces, each of which is described by a simple polygon. Objects can be created by connecting several meshes together. A patch mesh is constructed from patches. A patch is a four-sided piece of geometry constructed from curves. The type of curve used and the order of the curve can be varied so that the patch surface will fit almost any surface shape.

The following types of patch combinations are supported:

Patch Type | Basis | Degree
Rectangle | Bezier | 2,3,5
Rectangle | B-Spline | 2,3,5
Rectangle | Catmull-Rom | 3
Triangle | Bezier | 2,3,5
N-patch | N/A | 3

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO, D3DXCreatePatchMesh

© 2002 Microsoft Corporation. All rights reserved.


D3DXPLANE Structure

Describes a plane.

Syntax

typedef struct D3DXPLANE {
    FLOAT a;
    FLOAT b;
    FLOAT c;
    FLOAT d;
} D3DXPLANE;

Members

a
The a coefficient of the clipping plane in the general plane equation. See Remarks.
b
The b coefficient of the clipping plane in the general plane equation. See Remarks.
c
The c coefficient of the clipping plane in the general plane equation. See Remarks.
d
The d coefficient of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation so that a x + b y + c z + d w = 0.

C++ programmers can take advantage of operator overloading and type casting with the D3DXPLANE Extensions which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPLANE Extensions Structure

Supplies the following operator overloads and type casts for D3DXPLANE structures.

Syntax

#ifdef __cplusplus
public:
    D3DXPLANE() {}
    D3DXPLANE( CONST FLOAT* );
    D3DXPLANE( FLOAT a, FLOAT b, FLOAT c, FLOAT d );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // unary operators
    D3DXPLANE operator + () const;
    D3DXPLANE operator - () const;

    // binary operators
    BOOL operator == ( CONST D3DXPLANE& ) const;
    BOOL operator != ( CONST D3DXPLANE& ) const;

#endif //__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXQUATERNION Structure

Describes a quaternion.

Syntax

typedef struct D3DXQUATERNION {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXQUATERNION;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

Quaternions add a fourth element to the [ x, y, z] values that define a vector, resulting in arbitrary 4-D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x

q.y = sin(theta/2) * axis.y

q.z = sin(theta/2) * axis.z

q.w = cos(theta/2)

C++ programmers can take advantage of operator overloading and type casting with the D3DXQUATERNION Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXQUATERNION Extensions Structure

Supplies the following operator overloads and type casts for D3DXQUATERNION structures.

Syntax

#ifdef __cplusplus
public:
    D3DXQUATERNION() {}
    D3DXQUATERNION( CONST FLOAT * );
    D3DXQUATERNION( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXQUATERNION& operator += ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator -= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( FLOAT );
    D3DXQUATERNION& operator /= ( FLOAT );

    // unary operators
    D3DXQUATERNION  operator + () const;
    D3DXQUATERNION  operator - () const;

    // binary operators
    D3DXQUATERNION operator + ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator - ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( FLOAT ) const;
    D3DXQUATERNION operator / ( FLOAT ) const;

    friend D3DXQUATERNION operator * (FLOAT, CONST D3DXQUATERNION& );

    BOOL operator == ( CONST D3DXQUATERNION& ) const;
    BOOL operator != ( CONST D3DXQUATERNION& ) const;

#endif //__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXRTE_DESC Structure

Describes an off-screen render target used by an instance of ID3DXRenderToEnvMap.

Syntax

typedef struct _D3DXRTE_DESC {
    UINT Size;
    UINT MipLevels;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTE_DESC;

Members

Size
Width and height in pixels.
MipLevels
Maximum level of detail (LOD) number.
Format
Color buffer format.
DepthStencil
Indicates if the z-buffer is needed.
DepthStencilFormat
Format of the depth buffer.

Remarks

This method is used to return the creation parameters used when creating an ID3DXRenderToEnvMap object.

Structure Information

Header | d3dx9core.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXRTS_DESC Structure

Describes a render surface.

Syntax

typedef struct _D3DXRTS_DESC {
    UINT Width;
    UINT Height;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTS_DESC;

Members

Width
Width of the render surface, in pixels.
Height
Height of the render surface, in pixels.
Format
Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
If TRUE, the render surface supports a depth-stencil surface; otherwise this member is set to FALSE.
DepthStencilFormat
If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.

Structure Information

Header | d3dx9core.h
Minimum operating systems | Windows 98

See Also

ID3DXRenderToSurface::GetDesc

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_CONSTANTINFO Structure

Syntax

typedef struct _D3DXSHADER_CONSTANTINFO {
    DWORD Name;
    WORD RegisterSet;
    WORD RegisterIndex;
    WORD RegisterCount;
    WORD Reserved;
    DWORD TypeInfo;
    DWORD DefaultValue;
} D3DXSHADER_CONSTANTINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the constant information.
RegisterSet
Register set. See D3DXREGISTER_SET.
RegisterIndex
The register index.
RegisterCount
Number of registers.
Reserved
Reserved.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the D3DXSHADER_TYPEINFO information.
DefaultValue
Offset from the beginning of this structure, in bytes, to the string that contains the default value.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_CONSTANTTABLE Structure

Helper structure for managing a shader constant table. This can also be done using ID3DXConstantTable.

Syntax

typedef struct _D3DXSHADER_CONSTANTTABLE {
    DWORD Size;
    DWORD Creator;
    DWORD Version;
    DWORD Constants;
    DWORD ConstantInfo;
} D3DXSHADER_CONSTANTTABLE;

Members

Size
Size of the structure. See Remarks.
Creator
Offset from the beginning of this structure, in bytes, to the string that contains the name of the creator.
Version
Shader version.
Constants
Number of constants.
ConstantInfo
Array of constant information, D3DXSHADER_CONSTANTINFO[Constants]. See D3DXSHADER_CONSTANTINFO.

Remarks

Shader constant information is included in a tab-delimited table of comments. All offsets are measured in bytes from the beginning of the structure. Entries in the constant table are sorted by Creator in ascending order.

A shader constant table can be managed with the ID3DXConstantTable interfaces. Alternatively, you can manage the constant table with D3DXSHADER_CONSTANTTABLE.

This size member is often initialized using the following:

D3DXSHADER_CONSTANTTABLE constantTable;
constantTable.Size = sizeof(D3DXSHADER_CONSTANTTABLE)

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXGetShaderConstantTable

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_DEBUGINFO Structure

Structure containing shader debug information.

Syntax

typedef struct _D3DXSHADER_DEBUGINFO {
    DWORD Size;
    DWORD Creator;
    DWORD SourceCode;
    DWORD Files;
    DWORD FileInfo;
    DWORD Instructions;
    DWORD InstructionInfo;
    DWORD Variables;
    DWORD VariableInfo;
    DWORD EntrypointName;
} D3DXSHADER_DEBUGINFO;

Members

Size
Size of the debug information structure, in bytes. See Remarks.
Creator
Offset from the beginning of this structure, in bytes, to the string that contains the shader creator.
SourceCode
Offset from the beginning of this structure, in bytes, to the string that contains the source code.
Files
Number of source files.
FileInfo
Offset from the beginning of this structure, in bytes, to the string that contains array of file information, D3DXSHADER_FILEINFO[Files]. See D3DXSHADER_FILEINFO.
Instructions
Number of instructions.
InstructionInfo
Offset from the beginning of this structure, in bytes, to the string that contains the array of instruction information, D3DXSHADER_INSTRUCTIONINFO[Instructions]. See D3DXSHADER_INSTRUCTIONINFO.
Variables
Number of variables.
VariableInfo
Offset from the beginning of this structure, in bytes, to the string that contains the array of variable information, D3DXSHADER_VARIABLEINFO[Variables]. See D3DXSHADER_VARIABLEINFO.
EntrypointName
Offset from the beginning of this structure, in bytes, to the string that contains the name of the entry point.

Remarks

The shader debugger, Shader Debugger, uses the D3DXSHADER_ structures while debugging applications. These structures are documented in case you want to build your own shader debugger.

The shader debug information is included as a comment block inside shaders. All offsets are measured in bytes from the beginning of the structure.

This size member is often initialized using the following:

D3DXSHADER_DEBUGINFO debugInfo;
debugInfo.Size = sizeof(D3DXSHADER_DEBUGINFO)

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXGetShaderDebugInfo

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_FILEINFO Structure

Structure containing shader file information.

Syntax

typedef struct _D3DXSHADER_FILEINFO {
    DWORD Name;
} D3DXSHADER_FILEINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the file name.

Remarks

The shader file information is part of D3DXSHADER_DEBUGINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_DEBUGINFO

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_INSTRUCTIONINFO Structure

Shader instruction information.

Syntax

typedef struct _D3DXSHADER_INSTRUCTIONINFO {
    DWORD LineNumber;
    DWORD File;
    DWORD Offset;
} D3DXSHADER_INSTRUCTIONINFO;

Members

LineNumber
Shader line number that contains the instruction.
File
File index.
Offset
Offset from the beginning of this structure, in bytes, to the filename string.

Remarks

The shader instruction information is part of D3DXSHADER_DEBUGINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_STRUCTMEMBERINFO Structure

A helper structure containing member structure information.

Syntax

typedef struct _D3DXSHADER_STRUCTMEMBERINFO {
    DWORD Name;
    DWORD TypeInfo;
} D3DXSHADER_STRUCTMEMBERINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the structure member name.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the type information. See D3DXSHADER_TYPEINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_TYPEINFO Structure

A helper structure containing member type information.

Syntax

typedef struct _D3DXSHADER_TYPEINFO {
    WORD Class;
    WORD Type;
    WORD Rows;
    WORD Columns;
    WORD Elements;
    WORD StructMembers;
    DWORD StructMemberInfo;
} D3DXSHADER_TYPEINFO;

Members

Class
Shader object type. See D3DXPARAMETER_CLASS.
Type
Data type. See D3DXPARAMETER_TYPE.
Rows
Number of matrix rows (matrices).
Columns
Number of columns (vectors and matrices).
Elements
Array dimension.
StructMembers
Number of structure members.
StructMemberInfo
Array of structure member information, D3DXSHADER_STRUCTMEMBERINFO[StructMembers]. See D3DXSHADER_STRUCTMEMBERINFO.

Remarks

The type information is part of D3DXSHADER_STRUCTMEMBERINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_CONSTANTINFO

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_VARIABLEINFO Structure

Specifies the shader variable information.

Syntax

typedef struct _D3DXSHADER_VARIABLEINFO {
    DWORD Scope;
    DWORD Name;
    DWORD TypeInfo;
    DWORD Writes;
    DWORD WriteInfo;
} D3DXSHADER_VARIABLEINFO;

Members

Scope
Scope identifier.
Name
Offset from the beginning of this structure, in bytes, to the string that contains the variable name.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the type information. See D3DXSHADER_TYPEINFO.
Writes
Number of writes allowed.
WriteInfo
Array of "writable" information, contained in D3DXSHADER_WRITEINFO[Writes]. See D3DXSHADER_DEBUGINFO.

Remarks

The variable info is one member of the D3DXSHADER_DEBUGINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER_WRITEINFO Structure

Identifies writable information.

Syntax

typedef struct _D3DXSHADER_WRITEINFO {
    DWORD Instruction;
    WORD Component[4];
} D3DXSHADER_WRITEINFO;

Members

Instruction
Instruction index.
Component
Variable component per output value.

Remarks

An array of write info is part of D3DXSHADER_VARIABLEINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXTRACK_DESC Structure

Describes an animation track and specifies a tracks's weight and speed at a given time. This data is used to scale and translate animation key frames.

Syntax

typedef struct _D3DXTRACK_DESC {
    DWORD Flags;
    FLOAT Weight;
    FLOAT Speed;
    DOUBLE AnimTime;
    BOOL Enable;
} D3DXTRACK_DESC, *LPD3DXTRACK_DESC;

Members

Flags
Unused.
Weight
Weight value. The weight determines how much of this track to blend with other tracks in the mixer.
Speed
Speed value. This is like a multiplier to scale the period of the track.
AnimTime
Local animation time.
Enable
Track enable/disable. To enable this track in the mixer, set to TRUE. To disable it, set to FALSE.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR2 Structure

Describes a vector in 2-D space.

Syntax

typedef struct D3DXVECTOR2 {
    FLOAT x;
    FLOAT y;
} D3DXVECTOR2;

Members

x
The x-component.
y
The y-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR2 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR2 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR2 structures.

Syntax

#ifdef __cplusplus
public:
    D3DXVECTOR2() {};
    D3DXVECTOR2( CONST FLOAT * );
    D3DXVECTOR2( FLOAT x, FLOAT y );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR2& operator += ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator -= ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator *= ( FLOAT );
    D3DXVECTOR2& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR2 operator + () const;
    D3DXVECTOR2 operator - () const;

    // binary operators
    D3DXVECTOR2 operator + ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator - ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator * ( FLOAT ) const;
    D3DXVECTOR2 operator / ( FLOAT ) const;

    friend D3DXVECTOR2 operator * ( FLOAT, CONST D3DXVECTOR2& );

    BOOL operator == ( CONST D3DXVECTOR2& ) const;
    BOOL operator != ( CONST D3DXVECTOR2& ) const;

public:
#endif //__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR3 Structure

Describes a vector in three-dimensional (3-D) space.

Syntax

typedef struct D3DXVECTOR3 : public D3DVECTOR {
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

Members

x
The x-component.
y
The y-component.
z
The z-component.

Remarks

This structure inherits the x, y and z members from the D3DVECTOR structure. C programmers cannot use the D3DXVECTOR3 structure. They must use the D3DVECTOR structure.

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR3 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR3 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR3 structures.

Syntax

#ifdef __cplusplus
typedef struct D3DXVECTOR3 : public D3DVECTOR
{
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

#else //!__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR4 Structure

Describes a vector in 4-D space.

Syntax

typedef struct D3DXVECTOR4 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXVECTOR4;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR4 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXVECTOR4 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR4 structures.

Syntax

#ifdef __cplusplus
public:
    D3DXVECTOR4() {};
    D3DXVECTOR4( CONST FLOAT* );
    D3DXVECTOR4( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR4& operator += ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator -= ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator *= ( FLOAT );
    D3DXVECTOR4& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR4 operator + () const;
    D3DXVECTOR4 operator - () const;

    // binary operators
    D3DXVECTOR4 operator + ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator - ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator * ( FLOAT ) const;
    D3DXVECTOR4 operator / ( FLOAT ) const;

    friend D3DXVECTOR4 operator * ( FLOAT, CONST D3DXVECTOR4& );

    BOOL operator == ( CONST D3DXVECTOR4& ) const;
    BOOL operator != ( CONST D3DXVECTOR4& ) const;

public:
#endif //__cplusplus

Members

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXWELDEPSILONS Structure

Specifies tolerance values for each vertex component when comparing vertices to determine if they are similar enough to be welded together.

Syntax

typedef struct _D3DXWELDEPSILONS {
    FLOAT Position;
    FLOAT BlendWeights;
    FLOAT Normal;
    FLOAT PSize;
    FLOAT Specular;
    FLOAT Diffuse;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
    FLOAT Tess Factor;
} D3DXWELDEPSILONS;

Members

Position
Position
BlendWeights
Blend weight
Normal
Normal
PSize
Point size value
Specular
Specular lighting value
Diffuse
Diffuse lighting value
Texcoord
Eight texture coordinates
Tangent
Tangent
Binormal
Binormal
Tess Factor
Tessellation factor

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Enumerated Types

This section contains information about the following enumerated types and flags used with Direct3D extensions (D3DX).

Enumerations

  • D3DXEFFECTDEFAULTTYPE
  • D3DXERR
  • D3DXIMAGE_FILEFORMAT
  • D3DXMESH
  • D3DXMESHDATATYPE
  • D3DXMESHOPT
  • D3DXMESHSIMP
  • D3DXPARAMETER_CLASS
  • D3DXPARAMETER_TYPE
  • D3DXPATCHMESHTYPE
  • D3DXREGISTER_SET
  • D3DXTRACKFLAG
  • D3DXTRANSITIONTYPE
  • D3DXWELDEPSILONSFLAGS
  • MAX_FVF_DECL_SIZE

© 2002 Microsoft Corporation. All rights reserved.


D3DXEFFECTDEFAULTTYPE Enumerated Type

Effect data types. The data is contained in the pValue member of D3DXEFFECTDEFAULT.

Syntax

typedef enum _D3DXEFFECTDEFAULTTYPE {
    D3DXEDT_STRING = 1,
    D3DXEDT_FLOATS = 2,
    D3DXEDT_DWORD = 3,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXEFFECTDEFAULTTYPE;

Constants

D3DXEDT_STRING

The data type is a NULL terminated ASCII text string.

D3DXEDT_FLOATS

The data type is an array of floats. The number of floats in the array is specified by NumBytes in D3DXEFFECTDEFAULT.

D3DXEDT_DWORD

The data type in pValue is a DWORD.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXERR Enumerated Type

Errors are represented by negative values and cannot be combined. The following lists the values that can be returned by methods included with the Direct3D extensions (D3DX) utility library. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

Syntax

typedef enum _D3DXERR {
    D3DXERR_CANNOTMODIFYINDEXBUFFER,
    D3DXERR_INVALIDMESH,
    D3DXERR_CANNOTATTRSORT,
    D3DXERR_SKINNINGNOTSUPPORTED,
    D3DXERR_TOOMANYINFLUENCES,
    D3DXERR_INVALIDDATA,
    D3DXERR_LOADEDMESHASNODATA
} D3DXERR;

Constants

D3DXERR_CANNOTMODIFYINDEXBUFFER

The index buffer cannot be modified.

D3DXERR_INVALIDMESH

The mesh is invalid.

D3DXERR_CANNOTATTRSORT

Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.

D3DXERR_SKINNINGNOTSUPPORTED

Skinning is not supported.

D3DXERR_TOOMANYINFLUENCES

Too many influences specified.

D3DXERR_INVALIDDATA

The data is invalid.

D3DXERR_LOADEDMESHASNODATA

The mesh has no data.

Enumerated Type Information

Header | d3dx9.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXIMAGE_FILEFORMAT Enumerated Type

Describes the supported image file formats.

Syntax

typedef enum _D3DXIMAGE_FILEFORMAT {
    D3DXIFF_BMP = 0,
    D3DXIFF_DDS = 4,
    D3DXIFF_DIB = 6,
    D3DXIFF_JPG = 1,
    D3DXIFF_PNG = 3,
    D3DXIFF_PPM = 5,
    D3DXIFF_TGA = 2,
    D3DXIFF_FORCE_DWORD = 0x7fffffff
} D3DXIMAGE_FILEFORMAT;

Constants

D3DXIFF_BMP

Microsoft® Windows® Bitmap (BMP) file format.

D3DXIFF_DDS

Microsoft DirectDraw® surface (DDS) file format.

D3DXIFF_DIB

Windows device-independent bitmap (DIB) file format.

D3DXIFF_JPG

Joint Photographics Experts Group (JPEG) compressed file format.

D3DXIFF_PNG

Portable Network Graphics (PNG) file format.

D3DXIFF_PPM

Portable pixmap (PPM) file format.

D3DXIFF_TGA

Truevision (Targa, or TGA) image file format.

D3DXIFF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Functions that begin with D3DXLoad xxx support all of the formats listed. Functions that begin with D3DXSave xxx support .bmp, .dds, and .dib formats.

Enumerated Type Information

Header | d3dx9tex.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESH Enumerated Type

Flags used to specify creation options for a mesh.

Syntax

typedef enum _D3DXMESH {
    D3DXMESH_32BIT = 0x001,
    D3DXMESH_DONOTCLIP = 0x002,
    D3DXMESH_POINTS = 0x004,
    D3DXMESH_RTPATCHES = 0x008,
    D3DXMESH_NPATCHES = 0x4000,
    D3DXMESH_VB_SYSTEMMEM = 0x010,
    D3DXMESH_VB_MANAGED = 0x020,
    D3DXMESH_VB_WRITEONLY = 0x040,
    D3DXMESH_VB_DYNAMIC = 0x080,
    D3DXMESH_VB_SOFTWAREPROCESSING = 0x8000,
    D3DXMESH_IB_SYSTEMMEM = 0x100,
    D3DXMESH_IB_MANAGED = 0x200,
    D3DXMESH_IB_WRITEONLY = 0x400,
    D3DXMESH_IB_DYNAMIC = 0x800,
    D3DXMESH_IB_SOFTWAREPROCESSING = 0x10000,
    D3DXMESH_VB_SHARE = 0x1000,
    D3DXMESH_USEHWONLY = 0x2000,
    D3DXMESH_SYSTEMMEM = 0x110,
    D3DXMESH_MANAGED = 0x220,
    D3DXMESH_WRITEONLY = 0x440,
    D3DXMESH_DYNAMIC = 0x880,
    D3DXMESH_SOFTWAREPROCESSING = 0x18000
} D3DXMESH;

Constants

D3DXMESH_32BIT

The mesh has 32-bit indices instead of 16-bit indices. See Remarks.

D3DXMESH_DONOTCLIP

Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.

D3DXMESH_POINTS

Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.

D3DXMESH_RTPATCHES

Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.

D3DXMESH_NPATCHES

Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-patch enhancement using Microsoft® Direct3D®.

D3DXMESH_VB_SYSTEMMEM

Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.

D3DXMESH_VB_MANAGED

Use the D3DPOOL_MANAGED memory class for vertex buffers.

D3DXMESH_VB_WRITEONLY

Use the D3DPOOL_MANAGED memory class for vertex buffers.

D3DXMESH_VB_DYNAMIC

Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.

D3DXMESH_VB_SOFTWAREPROCESSING

Use the D3DUSAGE_SOFTWAREPROCESSING for flag for vertex buffers.

D3DXMESH_IB_SYSTEMMEM

Use the D3DPOOL_SYSTEMMEM memory class for index buffers.

D3DXMESH_IB_MANAGED

Use the D3DPOOL_MANAGED memory class for index buffers.

D3DXMESH_IB_WRITEONLY

Use the D3DUSAGE_WRITEONLY usage flag for index buffers.

D3DXMESH_IB_DYNAMIC

Use the D3DUSAGE_DYNAMIC usage flag for index buffers.

D3DXMESH_IB_SOFTWAREPROCESSING

Use the D3DUSAGE_SOFTWAREPROCESSING usage flag for index buffers.

D3DXMESH_VB_SHARE

Forces the cloned meshes to share vertex buffers.

D3DXMESH_USEHWONLY

Use hardware processing only. For mixed-mode device, this flag will cause the system to use hardware (if supported in hardware) or will default to software processing.

D3DXMESH_SYSTEMMEM

Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.

D3DXMESH_MANAGED

Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.

D3DXMESH_WRITEONLY

Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

D3DXMESH_DYNAMIC

Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.

D3DXMESH_SOFTWAREPROCESSING

Equivalent to specifying both D3DXMESH_VB_SOFTWAREPROCESSING and D3DXMESH_IB_SOFTWAREPROCESSING.

Remarks

A 32-bit mesh (D3DXMESH_32BIT) can theoretically support (2^32)-1 faces and vertices. However, allocating memory for a mesh that large on a 32-bit operating system is not practical.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESHDATATYPE Enumerated Type

Defines the type of mesh data present in D3DXMESHDATA.

Syntax

typedef enum D3DXMESHDATATYPE {
    D3DXMESHTYPE_MESH = 0x001,
    D3DXMESHTYPE_PMESH = 0x002,
    D3DXMESHTYPE_PATCHMESH = 0x003,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXMESHDATATYPE;

Constants

D3DXMESHTYPE_MESH

The data type is a mesh. See ID3DXMesh.

D3DXMESHTYPE_PMESH

The data type is a progressive mesh. See ID3DXPMesh.

D3DXMESHTYPE_PATCHMESH

The data type is a patch mesh. See ID3DXPatchMesh.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

See Also

D3DXMESHDATA

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESHOPT Enumerated Type

Specifies the type of mesh optimization to be performed.

Syntax

typedef enum {
    D3DXMESHOPT_COMPACT = 0x01000000,
    D3DXMESHOPT_ATTRSORT = 0x02000000,
    D3DXMESHOPT_VERTEXCACHE = 0x04000000,
    D3DXMESHOPT_STRIPREORDER = 0x08000000,
    D3DXMESHOPT_IGNOREVERTS = 0x10000000,
    D3DXMESHOPT_DONOTSPLIT = 0x20000000,
    D3DXMESHOPT_DEVICEINDEPENDENT = 0x40000000
} D3DXMESHOPT;

Constants

D3DXMESHOPT_COMPACT

Reorders faces to remove unused vertices and faces.

D3DXMESHOPT_ATTRSORT

Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.

D3DXMESHOPT_VERTEXCACHE

Reorders faces to increase the cache hit rate of vertex caches.

D3DXMESHOPT_STRIPREORDER

Reorders faces to maximize length of adjacent triangles.

D3DXMESHOPT_IGNOREVERTS

Optimize the faces only; do not optimize the vertices.

D3DXMESHOPT_DONOTSPLIT

While attribute sorting, do not split vertices that are shared between attribute groups.

D3DXMESHOPT_DEVICEINDEPENDENT

Affects the vertex cache size. Using this flag specifies a default vertex cache size that works well on legacy hardware.

Remarks

The D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

The D3DXMESHOPT_SHAREVB flag has been removed from this enumeration. Use D3DXMESH_VB_SHARE instead, in D3DXMESH.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXMESHSIMP Enumerated Type

Specifies simplification options for a mesh.

Syntax

typedef enum _D3DXMESHSIMP {
    D3DXMESHSIMP_VERTEX = 1,
    D3DXMESHSIMP_FACE = 2
} D3DXMESHSIMP;

Constants

D3DXMESHSIMP_VERTEX

The mesh will be simplified by the number of vertices specified in the MinValue parameter.

D3DXMESHSIMP_FACE

The mesh will be simplified by the number of faces specified in the MinValue parameter.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXGeneratePMesh, D3DXSimplifyMesh

© 2002 Microsoft Corporation. All rights reserved.


D3DXPARAMETER_CLASS Enumerated Type

The type of object.

Syntax

typedef enum _D3DXPARAMETER_CLASS {
    D3DXPC_SCALAR,
    D3DXPC_VECTOR,
    D3DXPC_MATRIX_ROWS,
    D3DXPC_MATRIX_COLUMNS,
    D3DXPC_OBJECT,
    D3DXPC_STRUCT,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXPARAMETER_CLASS;

Constants

D3DXPC_SCALAR

Constant is a scalar.

D3DXPC_VECTOR

Constant is a vector.

D3DXPC_MATRIX_ROWS

Constant is a row major matrix.

D3DXPC_MATRIX_COLUMNS

Constant is a column major matrix.

D3DXPC_OBJECT

Constant is either a texture, shader or a string.

D3DXPC_STRUCT

Constant is a structure.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXPARAMETER_TYPE Enumerated Type

Describes the data contained by the enumeration.

Syntax

typedef enum _D3DXPARAMETER_TYPE {
    D3DXPT_VOID,
    D3DXPT_BOOL,
    D3DXPT_INT,
    D3DXPT_FLOAT,
    D3DXPT_STRING,
    D3DXPT_TEXTURE,
    D3DXPT_TEXTURE2D,
    D3DXPT_TEXTURE3D,
    D3DXPT_TEXTURECUBE,
    D3DXPT_SAMPLER,
    D3DXPT_SAMPLER2D,
    D3DXPT_SAMPLER3D,
    D3DXPT_SAMPLERCUBE,
    D3DXPT_PIXELSHADER,
    D3DXPT_VERTEXSHADER,
    D3DXPT_PIXELFRAGMENT,
    D3DXPT_VERTEXFRAGMENT,
    D3DXPT_FORCE_DWORD = 0x7fffffff
} D3DXPARAMETER_TYPE;

Constants

D3DXPT_VOID

Parameter is a void pointer.

D3DXPT_BOOL

Parameter is a Boolean.

D3DXPT_INT

Parameter is an integer.

D3DXPT_FLOAT

Parameter is a floating-point number.

D3DXPT_STRING

Parameter is a string.

D3DXPT_TEXTURE

Parameter is a texture.

D3DXPT_TEXTURE2D

Parameter is a 2-D texture.

D3DXPT_TEXTURE3D

Parameter is a 3-D texture.

D3DXPT_TEXTURECUBE

Parameter is a cube texture.

D3DXPT_SAMPLER

Parameter is a sampler.

D3DXPT_SAMPLER2D

Parameter is a 2-D sampler.

D3DXPT_SAMPLER3D

Parameter is a 3-D sampler.

D3DXPT_SAMPLERCUBE

Parameter is a cube sampler.

D3DXPT_PIXELSHADER

Parameter is a pixel shader.

D3DXPT_VERTEXSHADER

Parameter is a vertex shader.

D3DXPT_PIXELFRAGMENT

Parameter is a pixel shader fragment.

D3DXPT_VERTEXFRAGMENT

Parameter is a vertex shader fragment.

D3DXPT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXPATCHMESHTYPE Enumerated Type

Mesh patch types.

Syntax

typedef enum _D3DXPATCHMESHTYPE {
    D3DXPATCHMESH_RECT = 0x001,
    D3DXPATCHMESH_TRI = 0x002,
    D3DXPATCHMESH_NPATCH = 0x003
} D3DXPATCHMESHTYPE;

Constants

D3DXPATCHMESH_RECT

Rectangle patch mesh type.

D3DXPATCHMESH_TRI

Triangle patch mesh type.

D3DXPATCHMESH_NPATCH

N-patch mesh type.

Remarks

Triangle patches have three sides and are described in D3DTRIPATCH_INFO. Rectangle patches are four-sided and are described in D3DRECTPATCH_INFO.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXREGISTER_SET Enumerated Type

Data type of the register.

Syntax

typedef enum _D3DXREGISTER_SET {
    D3DXRS_BOOL,
    D3DXRS_INT4,
    D3DXRS_FLOAT4,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXREGISTER_SET;

Constants

D3DXRS_BOOL

Boolean value.

D3DXRS_INT4

4-D integer number.

D3DXRS_FLOAT4

4-D floating-point number.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_CONSTANTINFO, D3DXCONSTANT_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXTRACKFLAG Enumerated Type

The type of transition performed.

Syntax

typedef enum D3DXTRACKFLAG {
    D3DXTF_LOWPRIORITY = 0x000,
    D3DXTF_HIGHPRIORITY = 0x001,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXTRACKFLAG;

Constants

D3DXTF_LOWPRIORITY

Track should be blended with all the low priority tracks, before mixing with the high priority result.

D3DXTF_HIGHPRIORITY

Track should be blended with all the high priority tracks, before mixing with the low priority result.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXTRANSITIONTYPE Enumerated Type

Flags used to specify the transition style between values of a mesh animation.

Syntax

typedef enum _D3DXTRANSITIONTYPE {
    D3DXTRANSITION_LINEAR = 0x000,
    D3DXTRANSITION_EASEINEASEOUT = 0x001,
    D3DXTRANSITION_FORCE_DWORD = 0x7fffffff
} D3DXTRANSITIONTYPE;

Constants

D3DXTRANSITION_LINEAR

Linear transition between values.

D3DXTRANSITION_EASEINEASEOUT

Ease-in, ease-out spline transition between values.

D3DXTRANSITION_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size.

Remarks

The calculation for the ramp from ease-in to ease-out is calculated as follows:

Q(t) = 2(x - y)t3 + 3(y - x)t2 + x.

where the ramp is a function Q(t) with the following properties:

  • Q(t) is a cubic spline.
  • Q(t) interpolates between x and y as t ranges from 0 to 1.
  • Q(t) is horizontal when t = 0 and t = 1.

Mathematically, this translates into:

Q(t) = At3 + Bt2 + Ct + D (and therefore, Q'(t) = 3At2 + 2Bt + C)
a) Q(0) = x
b) Q(1) = y

a) Q'(0) = 0
b) Q'(1) = 0

Solving for A, B, C, D:

D = x   (from 2a)
C = 0  (from 3a)
3A + 2B = 0 (from 3b)
A + B = y - x (from 2b and D = x)

Therefore:

A = 2(x - y), B = 3(y - x), C = 0, D = x.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXWELDEPSILONSFLAGS Enumerated Type

Options for welding together vertices.

Syntax

typedef enum {
    D3DXWELDEPSILONS_WELDALL = 1,
    D3DXWELDEPSILONS_WELDPARTIALMATCHES = 2,
    D3DXWELDEPSILONS_DONOTREMOVEVERTICES = 4
} D3DXWELDEPSILONSFLAGS;

Constants

D3DXWELDEPSILONS_WELDALL

Weld all vertices marked by adjacency as being overlapping.

D3DXWELDEPSILONS_WELDPARTIALMATCHES

If a given vertex component is within epsilon, modify partially matched vertices so that both components are identical. If all components are equal, remove one of the vertices.

D3DXWELDEPSILONS_DONOTREMOVEVERTICES

Instructs the weld to allow only modifications to vertices and not removal. This flag is valid only if D3DXWELDEPSILONS_WELDPARTIALMATCHES is set. It is useful to modify vertices to be equal, but not to allow vertices to be removed.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXWELDEPSILONS

© 2002 Microsoft Corporation. All rights reserved.


MAX_FVF_DECL_SIZE Enumerated Type

This constant is the maximum number of vertex declarators for a mesh.

Syntax

typedef enum {
    MAX_FVF_DECL_SIZE = 18
} MAX_FVF_DECL_SIZE;

Constants

MAX_FVF_DECL_SIZE

A mesh contains an array of vertex declarations. This constant is the maximum number of declarations in the array.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

ID3DXBaseMesh, IDirect3DVertexDeclaration9::GetDeclaration, ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF, ID3DXSkinInfo

© 2002 Microsoft Corporation. All rights reserved.


Constants

This section contains reference information for the constants defined in Direct3D extensions (D3DX).

  • D3DXCONSTANT_DESC - Describe a constant
  • D3DXCONSTANTTABLE_DESC - Describe the constant table
  • D3DX_CHANNEL - Texture channel constants
  • D3DX_FILTER - Texture filter constants
  • D3DX_NORMALMAP - Normal map generation constants
  • D3DXSHADER - Shader compile options
  • Other Direct3D Extentions (D3DX) Constants - Other constants

© 2002 Microsoft Corporation. All rights reserved.


D3DX_CHANNEL

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_CHANNEL_RED | Indicates the red channel should be used.
D3DX_CHANNEL_BLUE | Indicates the blue channel should be used.
D3DX_CHANNEL_GREEN | Indicates the green channel should be used.
D3DX_CHANNEL_ALPHA | Indicates the alpha channel should be used.
D3DX_CHANNEL_LUMINANCE | Indicates the luminances of the red, green, and blue channels should be used.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DX_FILTER

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_FILTER_NONE | No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT | Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_LINEAR | Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_TRIANGLE | Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.
D3DX_FILTER_BOX | Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_MIRROR_U | Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V | Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W | Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR | Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_DITHER | The resulting image must be dithered using a 4x4 ordered dither algorithm.
D3DX_FILTER_SRGB_IN | Input data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB_OUT | The output data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB | Same as specifying D3DX_FILTER_SRGB_IN | D3DX_FILTER_SRGB_OUT.

Each valid filter must contain exactly one of the following flags: D3DX_FILTER_NONE, D3DX_FILTER_POINT, D3DX_FILTER_LINEAR, D3DX_FILTER_TRIANGLE, or D3DX_FILTER_BOX. In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter: D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, D3DX_FILTER_MIRROR_W, D3DX_FILTER_MIRROR, D3DX_FILTER_DITHER, D3DX_FILTER_SRGB_IN, D3DX_FILTER_SRGB_OUT or D3DX_FILTER_SRGB.

Specifying D3DX_DEFAULT for this parameter is usually the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. However, D3DX_DEFAULT can have different meanings, depending on which method uses the filter. For example:

  • When using D3DXCreateTextureFromFileEx, D3DX_DEFAULT maps to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
  • When using D3DXFilterTexture, D3DX_DEFAULT maps to D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Reference each method to check for information about how D3DX_DEFAULT filter is mapped.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DX_NORMALMAP

Normal maps generation constants.

#define | Description
D3DX_NORMALMAP_MIRROR_U | Indicates that pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR_V | Indicates that pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR | Same as specifying D3DX_NORMALMAP_MIRROR_U | D3DX_NORMALMAP_MIRROR_V.
D3DX_NORMALMAP_INVERTSIGN | Inverts the direction of each normal.
D3DX_NORMALMAP_COMPUTE_OCCLUSION | Computes the per-pixel occlusion term and encodes it into the alpha. An alpha of 1 means that the pixel is not obscured in any way, and an alpha of 0 means that the pixel is completely obscured.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98

Related Topics

  • D3DXComputeNormalMap

© 2002 Microsoft Corporation. All rights reserved.


D3DXSHADER

Control the compile options during a shader compile.

#define | Description
D3DXSHADER_DEBUG | Insert debug filename and line number information during shader compile.
D3DXSHADER_SKIPVALIDATION | Do not validate the generated code against known capabilities and constraints. This option is recommended only when compiling shaders that are known to work (that is, shaders that have compiled before, without this option). Shaders are always validated by Microsoft® Direct3D® before they are set to the device.
D3DXSHADER_SKIPOPTIMIZATION | Instructs the compiler to skip optimization steps during code generation. This option is not recommended unless you are trying to isolate a code problem and you suspect the compiler. This option is valid only when calling D3DXCompileShader.

Constant Information

Header | d3dx9shader.h
Minimum operating system | Windows 98

Related Topics

  • ID3DXEffectCompiler::CompileEffect

© 2002 Microsoft Corporation. All rights reserved.


Other Direct3D Extensions (D3DX) Constants

Other Direct3D extensions (D3DX) constants include the following:

16-Bit Floating Point Numbers

#define | Value | Description
D3DX_16F_DIG | 3 | Number of decimal digits of precision
D3DX_16F_EPSILON | 4.8875809e-4f | Smallest such that 1.0 + epsilon != 1.0
D3DX_16F_MANT_DIG | 11 | Number of bits in mantissa
D3DX_16F_MAX | 6.5519996e+4f | Maximum value
D3DX_16F_MAX_10_EXP | 4 | Maximum decimal exponent
D3DX_16F_MAX_EXP | 15 | Maximum binary exponent
D3DX_16F_MIN | 6.1035156e-5f | Minimum positive value
D3DX_16F_MIN_10_EXP | (-4) | Minimum decimal exponent
D3DX_16F_MIN_EXP | (-12) | Minimum binary exponent
D3DX_16F_RADIX | 2 | Exponent radix
D3DX_16F_ROUNDS | 1 | Addition rounding: near

These #defines are declared in D3dx9math.h.

© 2002 Microsoft Corporation. All rights reserved.


DDS File Reference

The Microsoft® DirectDraw® Surface (DDS) file format is used to store textures and cubic environment maps, both with and without mipmap levels. This format can store uncompressed and compressed pixel formats, and is the preferred file format for storing DXTn compressed data. This file format is supported by the Microsoft DirectX® Texture tool (DXTex Tool), as well as some third party tools, and by the Direct3D extensions (D3DX) library.

This format was introduced with DirectX 7.0. In DirectX 8.0, support for volume textures was added.

  • File Layout
  • Surface Format Header

File Layout

The basic structure of a DDS file is a header, and one or more surfaces written to a binary file. The header consists of a four-character code (FOURCC) and a DDSURFACEDESC2 structure. This header contains all the information needed to determine the contents of the entire file. The image below shows the layout of a DDS file.

DDS file format layout

Surface Format Header

The DDSURFACEDESC2 structure describes the file contents using the standard flags and values defined in the DirectDraw documentation, but files should use a restricted set of values to ensure full compatibility. A robust reader should verify key values and a robust writer should ensure all required flags are set for the different fields and options to ensure easy loading by the application or other tool. Also, a robust reader should not use a field unless the corresponding flag is set, and a robust writer should set all undefined fields to 0.

The table below shows the members of the DDSURFACEDESC2 structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 124.
DWORD dwFlags | Flags to indicate valid fields. Always include DDSD_CAPS, DDSD_PIXELFORMAT, DDSD_WIDTH, DDSD_HEIGHT.
DWORD dwHeight | Height of the main image in pixels
DWORD dwWidth | Width of the main image in pixels
DWORD dwPitchOrLinearSize | For uncompressed formats, this is the number of bytes per scan line (DWORD> aligned) for the main image. dwFlags should include DDSD_PITCH in this case. For compressed formats, this is the total number of bytes for the main image. dwFlags should be include DDSD_LINEARSIZE in this case.
DWORD dwDepth | For volume textures, this is the depth of the volume. dwFlags should include DDSD_DEPTH in this case.
DWORD dwMipMapCount | For items with mipmap levels, this is the total number of levels in the mipmap chain of the main image. dwFlags should include DDSD_MIPMAPCOUNT in this case.
DWORD dwReserved1[11] |
DDPIXELFORMAT ddpfPixelFormat | 32-byte value that specifies the pixel format structure.
DDCAPS2 ddsCaps | 16-byte value that specifies the capabilities structure.
DWORD dwReserved2 |

Note that the field names used in this description do not correspond exactly with the DDSURFACEDESC2 fields due to the restrictions placed on the DDS file format, but a standard DDSURFACEDESC2 structure can and should be used. Use the magic DDS value and the header dwSize value to validate the file.

The pixel format of the image is given in the ddpfPixelFormat field of the header, and can describe all the formats supported by Microsoft Direct3D®. DDS files are usually restricted to either RGB or FOURCC formats, and the use of other formats is not generally supported. Restrict usage to RGB formats A8R8G8B8, A1R5G5B5, A4R4G4B4, R8G8B8, R5G6B5; and FOURCC formats DXT1, DXT2, DXT3, DXT4, and DXT5 to ensure the best support. A well-written reader should handle more formats, if possible.

The following table shows the layout of the DDPIXELFORMAT structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 32.
DWORD dwFlags | Flags to indicate valid fields. Uncompressed formats will usually use DDPF_RGB to indicate an RGB format, while compressed formats will use DDPF_FOURCC with a four-character code.
DWORD dwFourCC | This is the four-character code for compressed formats. dwFlags should include DDPF_FOURCC in this case. For DXTn compression, this is set to "DXT1", "DXT2", "DXT3", "DXT4", or "DXT5".
DWORD dwRGBBitCount | For RGB formats, this is the total number of bits in the format. dwFlags should include DDPF_RGB in this case. This value is usually 16, 24, or 32. For A8R8G8B8, this value would be 32.
DWORD dwRBitMask DWORD dwGBitMask DWORD dwBBitMask | For RGB formats, these three fields contain the masks for the red, green, and blue channels. For A8R8G8B8, these values would be 0x00ff0000, 0x0000ff00, and 0x000000ff respectively.
DWORD dwRGBAlphaBitMask | For RGB formats, this contains the mask for the alpha channel, if any. dwFlags should include DDPF_ALPHAPIXELS in this case. For A8R8G8B8, this value would be 0xff000000.

The final details of the format are inferred from the capabilities bits set in the ddsCaps field of the header. The layout of the ddsCaps structure is shown in the table below.

Member | Description
DWORD dwCaps1 | DDS files should always include DDSCAPS_TEXTURE. If the file contains mipmaps, DDSCAPS_MIPMAP should be set. For any DDS file with more than one main surface, such as a mipmaps, cubic environment map, or volume texture, DDSCAPS_COMPLEX should also be set.
DWORD dwCaps2 | For cubic environment maps, DDSCAPS2_CUBEMAP should be included as well as one or more faces of the map (DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, DDSCAPS2_CUBEMAP_NEGATIVEZ). For volume textures, DDSCAPS2_VOLUME should be included.
DWORD Reserved[2] |

Note that as of DirectX 8.0, cubic environment maps are always written with all faces defined.

  • DDS File Layout for Textures
  • DDS File Layout for Cubic Environment Maps
  • DDS File Layout for Volume Textures
  • DDS Bit Flag Values

© 2002 Microsoft Corporation. All rights reserved.


DDS File Layout for Textures

For simple uncompressed textures, the file should contain DDSD_PITCH and a DDPF_RGB pixel format surface. The pitch value should be DWORD-aligned. In this case, the main image should be (dwPitchOrLinearSize-by-dwHeight) bytes total.

If the file also contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_MIPMAP, and DDSCAPS_COMPLEX flags should be set, and the dwMipMapCount field should contain the total number of levels defined in the file (for a 256-by-256 image, this field would be 9). The pitch for each mipmap-level image is computed from dwWidth and the pixel format, which is then DWORD-aligned. For example, a 256-by-256 main image, with a pixel format of R8G8B8 (three bytes per pixel) and all mipmap levels, would contain the following:

"DDS", (256, 256), (pitch=768), (pixel format=R8G8B8,bitcount=24), (mipmapcount=9), (TEXTURE, PITCH, COMPLEX, MIPMAP, RGB) | 128 bytes
256-by-256 main image | 196608 bytes
128-by-128 mipmap image | 49152 bytes
64-by-64 mipmap image | 12288 bytes
32-by-32 mipmap image | 3072 bytes
16-by-16 mipmap image | 768 bytes
8-by-8 mipmap image | 192 bytes
4-by-4 mipmap image | 48 bytes
2-by-2 mipmap image | 12 bytes
1-by-1 mipmap image | 4 bytes

For simple compressed textures, the file should contain DDSD_LINEARSIZE and a DDPF_FOURCC pixel format surface. In this case, the image should be dwPitchOrLinearSize bytes total. If the file contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_COMPLEX, DDSCAPS_MIPMAP, and dwMipMapCount fields should be set.

For DXTn compressed formats, the size of each mipmap level image is one-fourth the size of the previous, with a minimum of 8 (DXT1) or 16 (DXT2-5) bytes (this is true only for square textures). For example, a 256-by-256 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

DDS, (256, 256), (linearsize=32768), 128 bytes (pixel format=DXT1), (mipmapcount=9), (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256-by-256 main image | 32768 bytes
128-by-128 mipmap image | 8192 bytes
64-by-64 mipmap image | 2048 bytes
32-by-32 mipmap image | 512 bytes
16-by-16 mipmap image | 128 bytes
8-by-8 mipmap image | 32 bytes
4-by-4 mipmap image | 8 bytes
2-by-2 mipmap image | 8 bytes
1-by-1 mipmap image | 8 bytes

If mipmaps are generated, all levels down to 1-by-1 are usually written. Some tools may not support partial mipmap chains.

When computing DXTn compressed sizes for non-square textures, the following formula should be used at each mipmap level:

max(1,width ÷ 4)x max(1,height ÷ 4)x 8 (DXT1) or 16 (DXT2-5)

A 256-by-64 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

"DDS ", (256, 64), (linearsize=8192), (pixel format=DXT1), (mipmapcount=9), (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256-by-64 main image | 8192 bytes
128-by-32 mipmap image | 2048 bytes
64-by-16 mipmap image | 512 bytes
32-by-8 mipmap image | 128 bytes
16-by-4 mipmap image | 32 bytes
8-by-2 mipmap image | 16 bytes
4-by-1 mipmap image | 8 bytes
2-by-1 mipmap image | 8 bytes
1-by-1 mipmap image | 8 bytes

© 2002 Microsoft Corporation. All rights reserved.


DDS File Layout for Cubic Environment Maps

For cubic environment maps, one or more faces of a cube are written to the file, using either uncompressed or compressed formats, and all faces must be the same size. Each face can have mipmaps defined, although all faces must have the same number of mipmap levels. If a file contains a cube map, DDSCAPS_COMPLEX, DDSCAPS2_CUBEMAP, and one or more of DSCAPS2_CUBEMAP_POSITIVEX/Y/Z and/or DDSCAPS2_CUBEMAP_NEGATIVEX/Y/Z should be set. The faces are written in the order: positive x, negative x, positive y, negative y, positive z, negative z, with any missing faces omitted. Each face is written with its main image, followed by any mipmap levels.

For example, a 256-by-256 cube map with positive x, negative y, and positive z faces, a pixel format of DXT1, and all mipmap levels would contain the following:

"DDS ",
(256, 256),
(linearsize=32768),
(pixel format=DXT1), | 128 bytes
(TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, CUBEMAP, POSITIVEX, NEGATIVEY, POSITIVEZ, FOURCC)
256-by-256 positive x main image | 32768 bytes
128-by-128 positive x mipmap image | 8192 bytes
64-by-64 positive x mipmap image | 2048 bytes
32-by-32 positive x mipmap image | 512 bytes
16-by-16 positive x mipmap image | 128 bytes
8-by-8 positive x mipmap image | 32 bytes
4-by-4 positive x mipmap image | 8 bytes
2-by-2 positive x mipmap image | 8 bytes
1-by-1 positive x mipmap image | 8 bytes
256-by-256 negative y main image | 32768 bytes
128-by-128 negative y mipmap image | 8192 bytes
64-by-64 negative y mipmap image | 2048 bytes
32-by-32 negative y mipmap image | 512 bytes
16-by-16 negative y mipmap image | 128 bytes
8-by-8 negative y mipmap image | 32 bytes
4-by-4 negative y mipmap image | 8 bytes
2-by-2 negative y mipmap image | 8 bytes
1-by-1 negative y mipmap image | 8 bytes
256-by-256 positive z main image | 32768 bytes
128-by-128 positive z mipmap image | 8192 bytes
64-by-64 positive z mipmap image | 2048 bytes
32-by-32 positive z mipmap image | 512 bytes
16-by-16 positive z mipmap image | 128 bytes
8-by-8 positive z mipmap image | 32 bytes
4-by-4 positive z mipmap image | 8 bytes
2-by-2 positive z mipmap image | 8 bytes
1-by-1 positive z mipmap image | 8 bytes

Note As of Microsoft® DirectX® 8.0, cube maps are always written with all faces defined.

© 2002 Microsoft Corporation. All rights reserved.


DDS File Layout for Volume Textures

A volume texture is an extension of the standard texture for Microsoft® DirectX® 9.0. x, and can be defined with or without mipmaps. If a file contains a volume texture, DDSCAPS_COMPLEX, DDSCAPS2_VOLUME, DDSD_DEPTH, and dwDepth should be set. For volumes without mipmaps, each depth slice is written to the file in order. If mipmaps are included, all depth slices for a given mipmap level are written together, with each level containing half as many slices as the previous level with a minimum of 1. Volume textures do not support DXTn compression as of DirectX 9.0.

For example, a 64-by-64-by-4 volume map, a pixel format of R8G8B8 (3 bytes per pixel), and all mipmap levels would contain the following:

"DDS ",
(64, 64, 4),
(pitch=768), | 128 bytes
(pixel format=R8G8B8, bitcount=24),
(mipmapcount=7),
(DEPTH, TEXTURE, PITCH, COMPLEX, MIPMAP, VOLUME, RGB)
64-by-64 slice 1 of 4 main image. | 12288 bytes
64-by-64 slice 2 of 4 main image. | 12288 bytes
64-by-64 slice 3 of 4 main image. | 12288 bytes
64-by-64 slice 4 of 4 main image. | 12288 bytes
32-by-32 slice 1 of 2 mipmap image. | 3072 bytes
32-by-32 slice 2 of 2 mipmap image. | 3072 bytes
16-by-16 slice 1 of 1 mipmap image. | 768 bytes
8-by-8 slice 1 of 1 mipmap image. | 192 bytes
4-by-4 slice 1 of 1 mipmap image. | 48 bytes
2-by-2 slice 1 of 1 mipmap image. | 12 bytes
1-by-1 slice 1 of 1 mipmap image. | 4 bytes

© 2002 Microsoft Corporation. All rights reserved.


DDS Bit Flag Values

A number of fields make use of the standard Microsoft® DirectDraw® bit flags. Those that are used for DDS files are included here for reference.

The dwFlags member of the original DDSURFACEDESC2structure can be set to one or more of the following values.

Flag | Value
DDSD_CAPS | 0x00000001
DDSD_HEIGHT | 0x00000002
DDSD_WIDTH | 0x00000004
DDSD_PITCH | 0x00000008
DDSD_PIXELFORMAT | 0x00001000
DDSD_MIPMAPCOUNT | 0x00020000
DDSD_LINEARSIZE | 0x00080000
DDSD_DEPTH | 0x00800000
Flag | Value
DDPF_ALPHAPIXELS | 0x00000001
DDPF_FOURCC | 0x00000004
DDPF_RGB | 0x00000040

The dwCaps1 member of the DDSCAPS2 structure can be set to one or more of the following values.

Flag | Value
DDSCAPS_COMPLEX | 0x00000008
DDSCAPS_TEXTURE | 0x00001000
DDSCAPS_MIPMAP | 0x00400000

The dwCaps2 member of the DDSCAPS2 structure can be set to one or more of the following values.

Flag | Value
DDSCAPS2_CUBEMAP | 0x00000200
DDSCAPS2_CUBEMAP_POSITIVEX | 0x00000400
DDSCAPS2_CUBEMAP_NEGATIVEX | 0x00000800
DDSCAPS2_CUBEMAP_POSITIVEY | 0x00001000
DDSCAPS2_CUBEMAP_NEGATIVEY | 0x00002000
DDSCAPS2_CUBEMAP_POSITIVEZ | 0x00004000
DDSCAPS2_CUBEMAP_NEGATIVEZ | 0x00008000
DDSCAPS2_VOLUME | 0x00200000

© 2002 Microsoft Corporation. All rights reserved.


X File Reference

This section contains reference information for the application programming interface (API) elements used to work with Microsoft® DirectX® (.x) files.

  • Interfaces
  • Functions
  • Structures
  • DXFILE
  • Return Values

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains reference information for the Component Object Model (COM) interfaces used to read to and write from Microsoft® DirectX® .x files.

Interfaces

  • IDirectXFile
  • IDirectXFileBinary
  • IDirectXFileData
  • IDirectXFileDataReference
  • IDirectXFileEnumObject
  • IDirectXFileObject
  • IDirectXFileSaveObject

The following tables illustrate the relationship between the .x file interfaces.

Interface | Derives from | Derives from
 | IDirectXFile | IUnknown
IDirectXFileBinary | IDirectXFileObject | IUnknown
IDirectXFileData | IDirectXFileObject | IUnknown
IDirectXFileReference | IDirectXFileObject | IUnknown
 | IDirectXFileSaveObject | IUnknown

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFile Interface

Applications use the methods of the IDirectXFile interface to create instances of the IDirectXFileEnumObject and IDirectXFileSaveObject interfaces, and to register templates.

IDirectXFile Members

CreateEnumObject

Creates an enumerator object.

CreateSaveObject

Creates a save object.

RegisterTemplates

Registers custom templates.

Remarks

The globally unique identifier (GUID) for the IDirectXFile interface is IID_IDirectXFile.

The IDirectXFile interface is obtained by calling the DirectXFileCreate function.

Interface Information

Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFile::CreateEnumObject Method

Creates an enumerator object.

Syntax

HRESULT CreateEnumObject(

    LPVOID pvSource,
    DXFILELOADOPTIONS dwLoadOptions,
    LPDIRECTXFILEENUMOBJECT *ppEnumObj
);

Parameters

pvSource
[out] Pointer to data whose contents depend on the value of dwLoadOptions
dwLoadOptions
[in] Value that specifies the source of the data. This value can be one of the DXFILELOAD_xxx flags in DXFILE.
ppEnumObj
[out, retval] Address of a pointer to an IDirectXFileEnumObject interface, representing the created enumerator object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADFILEFLOATSIZE | Floating-point size is invalid.
DXFILEERR_BADFILETYPE | File is not a Microsoft® DirectX® (.x) file.
DXFILEERR_BADFILEVERSION | File version is not valid.
DXFILEERR_BADRESOURCE | Resource is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_FILENOTFOUND | File could not be found.
DXFILEERR_RESOURCENOTFOUND | Resource could not be found.
DXFILEERR_URLNOTFOUND | URL could not be found.

Remarks

After using this method, use one of the IDirectXFileEnumObject methods to retrieve a data object.

See Also

IDirectXFileEnumObject

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFile::CreateSaveObject Method

Creates a save object.

Syntax

HRESULT CreateSaveObject(

    LPCSTR szFileName,
    DXFILEFORMAT dwFileFormat,
    LPDIRECTXFILESAVEOBJECT* ppSaveObj
);

Parameters

szFileName
[in] Pointer to the name of the file to use for saving data.
dwFileFormat
[in] Indicates the format to use when saving the Microsoft® DirectX® file. This value can be one of the DXFILEFORMAT_xxx flags in DXFILE. For more information, see Remarks.
ppSaveObj
[out, retval] Address of a pointer to an IDirectXFileSaveObject interface, representing the created save object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADFILE | File is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

After using this method, use methods of the IDirectXFileSaveObject interface to create data objects and to save templates or data.

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

See Also

IDirectXFileSaveObject

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFile::RegisterTemplates Method

Registers custom templates.

Syntax

HRESULT RegisterTemplates(

    LPVOID pvData,
    DWORD cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a Microsoft® DirectX® file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADFILEFLOATSIZE | Floating-point size is invalid.
DXFILEERR_BADFILETYPE | File is not a DirectX (.x) file.
DXFILEERR_BADFILEVERSION | File version is not valid.
DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_PARSEERROR | File could not be parsed.

Remarks

The following code fragment provides an example call to RegisterTemplates and example contents for the buffer to which pvData points.

TIDirectXFile * pDXFile;
char *szTemplates = "xof 0303txt 0032\
    template SimpleData { \
        <2b934580-9e9a-11cf-ab39-0020af71e433> \
        DWORD item1;DWORD item2;DWORD item3;} \
    template ArrayData { \
        <2b934581-9e9a-11cf-ab39-0020af71e433> \
        DWORD cItems; array DWORD aItem[2][cItems]; [...] } \
    template RestrictedData { \
        <2b934582-9e9a-11cf-ab39-0020af71e433> \
        DWORD item; [SimpleData]}";
hr = pDXFile->RegisterTemplates(szTemplates, strlen(szTemplates));

All templates must specify a name and a Universally Unique Identifier (UUID).

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary Interface

Applications use the methods of the IDirectXFileBinary interface to read and retrieve information about binary data.

IDirectXFileBinary Members

GetId

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

GetMimeType

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data.

GetName

Retrieves a pointer to a DirectX file object's name.

GetSize

Retrieves the size of the binary data.

Read

Reads the binary data.

Remarks

The GUID for the IDirectXFileBinary interface is IID_IDirectXFileBinary.

Interface Information

Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary::GetMimeType Method

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data.

Syntax

HRESULT GetMimeType(

    LPCSTR *pszMimeType
);

Parameters

pszMimeType
[out] Address of a pointer to receive the MIME type string.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

When there is no MIME type specified in a Microsoft® DirectX® file for a binary object, the function will set pszMimeType to NULL.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary::GetSize Method

Retrieves the size of the binary data.

Syntax

HRESULT GetSize(

    DWORD *pcbSize
);

Parameters

pcbSize
[out] Pointer to the returned size of the binary data, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary::Read Method

Reads the binary data.

Syntax

HRESULT Read(

    LPVOID pvData,
    DWORD cbSize,
    LPDWORD pcbRead
);

Parameters

pvData
[out] Pointer to the buffer that receives the data that has been read.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.
pcbRead
[out] Pointer to the number of bytes actually read.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREDATA | No further data is available.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData Interface

Applications use the methods of the IDirectXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy. Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. The children can be another data object, a reference to an earlier data object, or a binary object.

IDirectXFileData Members

AddBinaryObject

Creates a binary object and adds it as a child object.

AddDataObject

Adds a data object as a child object.

AddDataReference

Creates and adds a data reference object as a child object.

GetData

Retrieves the data for one of the object's members or the data for all members.

GetId

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

GetName

Retrieves a pointer to a DirectX file object's name.

GetNextObject

Retrieves the next child data object, data reference object, or binary object in the DirectX file.

GetType

Retrieves the globally unique identifier (GUID) of the object's template.

Remarks

The GUID for the IDirectXFileData interface is IID_IDirectXFileData.

Interface Information

Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::AddBinaryObject Method

Creates a binary object and adds it as a child object.

Syntax

HRESULT AddBinaryObject(

    LPCSTR szName,
    const GUID *pguid,
    LPCSTR szMimeType,
    LPVOID pvData,
    DWORD cbSize
);

Parameters

szName
[in] Pointer to the name of the object. Specify NULL if the object does not need a name.
pguid
[in] Pointer to the globally unique identifier (GUID) representing the object. Specify NULL if the object does not need a GUID.
szMimeType
[in] Pointer to the object's MIME type.
pvData
[in] Pointer to the object's data.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

See Also

IDirectXFileBinary::GetMimeType

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::AddDataObject Method

Adds a data object as a child object.

Syntax

HRESULT AddDataObject(

    LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to add as a child object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

Use the IDirectXFileSaveObject::CreateDataObject method to create the IDirectXFileData object before calling this method.

See Also

IDirectXFileSaveObject::CreateDataObject

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::AddDataReference Method

Creates and adds a data reference object as a child object.

Syntax

HRESULT AddDataReference(

    LPCSTR szRef,
    const GUID *pguidRef
);

Parameters

szRef
[in] Pointer to the name of the referenced data object. This parameter can be NULL if pguidRef provides a reference to the globally unique identifier (GUID).
pguidRef
[in] Pointer to the GUID representing the data. This parameter can be NULL if szRef provides a reference to the name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

For this method to succeed, either the szRef or pguidRef parameter must be non-NULL.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::GetData Method

Retrieves the data for one of the object's members or the data for all members.

Syntax

HRESULT GetData(

    LPCSTR szMember,
    DWORD *pcbSize,
    void **ppvData
);

Parameters

szMember
[in] Pointer to the name of the member for which to retrieve data. Specify NULL to retrieve all required members' data.
pcbSize
[out] Pointer to receive the ppvData buffer size, in bytes.
ppvData
[out] Address of a pointer to the buffer to receive the data associated with szMember. If szMember is NULL, ppvData is set to point to a buffer containing all required members' data in a contiguous block of memory.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE | Array size is invalid.
DXFILEERR_BADDATAREFERENCE | Data reference is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use IDirectXFileData::GetNextObject to retrieve child objects.

See Also

IDirectXFileData::GetNextObject

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::GetNextObject Method

Retrieves the next child data object, data reference object, or binary object in the Microsoft® DirectX® file.

Syntax

HRESULT GetNextObject(

    LPDIRECTXFILEOBJECT *ppChildObj
);

Parameters

ppChildObj
[out, retval] Address of a pointer to an IDirectXFileObject interface, representing the returned child object's file object interface.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREOBJECTS | All objects have been enumerated.

Remarks

To determine the type of object retrieved, use QueryInterface to query the retrieved object for support of IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary interfaces. The interface supported indicates the type of object (data, data reference, or binary).

See Also

IDirectXFileBinary, IDirectXFileData, IDirectXFileDataReference

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::GetType Method

Retrieves the globally unique identifier (GUID) of the object's template.

Syntax

HRESULT GetType(

    const GUID **ppguid
);

Parameters

ppguid
[out, retval] Address of a pointer to receive the GUID of the object's template.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileDataReference Interface

Applications use the methods of the IDirectXFileDataReference interface to support data reference objects. A data reference object refers to a data object that is defined earlier in the file. This enables you to use the same object multiple times without repeating it in the file.

IDirectXFileDataReference Members

GetId

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

GetName

Retrieves a pointer to a DirectX file object's name.

Resolve

Resolves data references.

Remarks

After you have determined that an object is a data reference object, use the IDirectXFileDataReference::Resolve method to retrieve the referenced object defined earlier in the file. For information about how to identify a data reference object, see the IDirectXFileData interface.

The GUID for the IDirectXFileDataReference interface is IID_IDirectXFileDataReference.

Interface Information

Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileDataReference::Resolve Method

Resolves data references.

Syntax

HRESULT Resolve(

    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileEnumObject Interface

Applications use the methods of the IDirectXFileEnumObject interface to cycle through the data objects in the file and to retrieve a data object by its globally unique identifier (GUID) or by its name.

IDirectXFileEnumObject Members

GetDataObjectById

Retrieves the data object that has the specified globally unique identifier (GUID).

GetDataObjectByName

Retrieves the data object that has the specified name.

GetNextDataObject

Retrieves the next top-level object in the Microsoft® DirectX® file.

Remarks

The GUID for the IDirectXFileEnumObject interface is IID_IDirectXFileEnumObject.

Interface Information

Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileEnumObject::GetDataObjectById Method

Retrieves the data object that has the specified globally unique identifier (GUID).

Syntax

HRESULT GetDataObjectById(

    REFGUID rguid,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

rguid
[in] Reference to the requested globally unique identifier (GUID).
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileEnumObject::GetDataObjectByName Method

Retrieves the data object that has the specified name.

Syntax

HRESULT GetDataObjectByName(

    LPCSTR szName,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

szName
[in] Pointer to the requested name.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileEnumObject::GetNextDataObject Method

Retrieves the next top-level object in the Microsoft® DirectX® file.

Syntax

HRESULT GetNextDataObject(

    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREOBJECTS | All objects have been enumerated.

Remarks

Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileObject Interface

Applications use the methods of the IDirectXFileObject interface to retrieve information about Microsoft® DirectX® file objects.

IDirectXFileObject Members

GetId

Retrieves a pointer to the globally unique identifier (GUID) that identifies a DirectX file object.

GetName

Retrieves a pointer to a DirectX file object's name.

Remarks

The GUID for the IDirectXFileObject interface is IID_IDirectXFileObject.

Interface Information

Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileObject::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileObject::GetName Method

Retrieves a pointer to a Microsoft® DirectX® file object's name.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileSaveObject Interface

Applications use the methods of the IDirectXFileSaveObject interface to create data objects and to save templates and data objects. Note that templates are not required in every file. For example, you could put all templates into a single Microsoft® DirectX® file rather than duplicating them in every DirectX file.

IDirectXFileSaveObject Members

CreateDataObject

Creates a data object.

SaveData

Saves a data object and its children to a DirectX file.

SaveTemplates

Saves templates to a DirectX file.

Remarks

The globally unique identifier (GUID) for the IDirectXFileSaveObject interface is IID_IDirectXFileSaveObject.

The IDirectXFileSaveObject interface is obtained by calling the IDirectXFile::CreateSaveObject method.

Interface Information

Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileSaveObject::CreateDataObject Method

Creates a data object.

Syntax

HRESULT CreateDataObject(

    REFGUID rguidTemplate,
    LPCSTR szName,
    const GUID *pguid,
    DWORD cbSize,
    LPVOID pvData,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

rguidTemplate
[in] Globally unique identifier (GUID) representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pguid
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required member's data.
ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the created file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

If a data reference object will reference the data object, either the szName or pguid parameter must be non-NULL.

Save any templates by using the IDirectXFileSaveObject::SaveTemplates method before saving the data created by this method. Save the created data by using the IDirectXFileSaveObject::SaveData method.

If you need to save optional data, use the IDirectXFileData::AddDataObject method after using this method and before using IDirectXFileSaveObject::SaveData. If the object has child objects, add them before calling IDirectXFileSaveObject::SaveData.

See Also

IDirectXFileData::AddDataObject, IDirectXFileSaveObject::SaveData, IDirectXFileSaveObject::SaveTemplates

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileSaveObject::SaveData Method

Saves a data object and its children to a Microsoft® DirectX® file.

Syntax

HRESULT SaveData(

    LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to save.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE | Array size is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileSaveObject::SaveTemplates Method

Saves templates to a Microsoft® DirectX® file.

Syntax

HRESULT SaveTemplates(

    DWORD cTemplates,
    const GUID **ppguidTemplates
);

Parameters

cTemplates
[in] Total number of templates to save.
ppguidTemplates
[in] Address of a pointer to an array of the globally unique identifiers (GUIDs) for all templates to save.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

The following code fragment provides an example call to IDirectXFileSaveObject::SaveTemplates and example contents for the array to which ppguidTemplates points.

IDirectXFileSaveObject * pDXFileSaveObject;

const GUID *aIds[] = {
    &DXFILEOBJ_SimpleData,
    &DXFILEOBJ_ArrayData,
    &DXFILEOBJ_RestrictedData};

hr = pDXFileSaveObject->SaveTemplates(3, aIds);

After using this method to save the templates, use the IDirectXFileSaveObject::CreateDataObject method to create a data object.

See Also

IDirectXFileSaveObject::CreateDataObject

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section contains reference information for the functions that you need to implement when you work with Microsoft® DirectX® files. The following function is implemented.

Functions

  • DirectXFileCreate

© 2002 Microsoft Corporation. All rights reserved.


DirectXFileCreate Function

Creates an instance of a DirectXFile object.

Syntax

STDAPI DirectXFileCreate(

    LPDIRECTXFILE *lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an IDirectXFile interface, representing the created DirectXFile object.

Return Value

If the function succeeds, the return value is DXFILE_OK.

If the function fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

After using this function, use IDirectXFile::RegisterTemplates to register templates, IDirectXFile::CreateEnumObject to create an enumerator object, or IDirectXFile::CreateSaveObject to create a save object.

Function Information

Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, IDirectXFile::CreateSaveObject, IDirectXFile::RegisterTemplates

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains information about the structures used with Microsoft® DirectX® files.

Structures

  • DXFILELOADMEMORY
  • DXFILELOADRESOURCE

© 2002 Microsoft Corporation. All rights reserved.


DXFILELOADMEMORY Structure

Identifies memory data.

Syntax

typedef struct _DXFILELOADMEMORY {
    LPVOID lpMemory;
    DWORD dSize;
} DXFILELOADMEMORY, *LPDXFILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMMEMORY.

Structure Information

Header | dxfile.h
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, DXFILE

© 2002 Microsoft Corporation. All rights reserved.


DXFILELOADRESOURCE Structure

Identifies resource data.

Syntax

typedef struct _DXFILELOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
} DXFILELOADRESOURCE, *LPDXFILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMRESOURCE.

Structure Information

Header | dxfile.h
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, DXFILE

© 2002 Microsoft Corporation. All rights reserved.


DXFILE

The following flags are used to specify which channels in a texture to operate on.

DXFILEFORMAT

#define | Description
DXFILEFORMAT_BINARY | Binary file.
DXFILEFORMAT_TEXT | Text file.
DXFILEFORMAT_COMPRESSED | Compressed file.

These #defines are declared in Dxfile.h.

DXFILELOAD

#define | Description
DXFILELOAD_FROMFILE | 0x00L | Load a file from a file.
DXFILELOAD_FROMRESOURCE | 0x01L | Load a file from a resource.
DXFILELOAD_FROMMEMORY | 0x02L | Load a file from memory.
DXFILELOAD_FROMSTREAM | 0x04L | Load a file from a stream.
DXFILELOAD_FROMURL | 0x08L | Load a file from a URL.

These #defines are declared in Dxfile.h.

© 2002 Microsoft Corporation. All rights reserved.


Return Values Enumerated Type

The methods used to work with Microsoft® DirectX® .x files can return the following values in addition to the standard Component Object Model (COM) return values.

Syntax

typedef enum {
    DXFILE_OK,
    DXFILEERR_BADALLOC,
    DXFILEERR_BADARRAYSIZE,
    DXFILEERR_BADCACHEFILE,
    DXFILEERR_BADDATAREFERENCE,
    DXFILEERR_BADFILE,
    DXFILEERR_BADFILECOMPRESSIONTYPE,
    DXFILEERR_BADFILEFLOATSIZE,
    DXFILEERR_BADFILETYPE,
    DXFILEERR_BADFILEVERSION,
    DXFILEERR_BADINTRINSICS,
    DXFILEERR_BADOBJECT,
    DXFILEERR_BADRESOURCE,
    DXFILEERR_BADTYPE,
    DXFILEERR_BADVALUE,
    DXFILEERR_FILENOTFOUND,
    DXFILEERR_INTERNALERROR,
    DXFILEERR_NOINTERNET,
    DXFILEERR_NOMOREDATA,
    DXFILEERR_NOMOREOBJECTS,
    DXFILEERR_NOMORESTREAMHANDLES,
    DXFILEERR_NOTDONEYET,
    DXFILEERR_NOTFOUND,
    DXFILEERR_PARSEERROR,
    DXFILEERR_RESOURCENOTFOUND,
    DXFILEERR_NOTEMPLATE,
    DXFILEERR_URLNOTFOUND
} Return Values;

Constants

DXFILE_OK

Command completed successfully.

DXFILEERR_BADALLOC

Memory allocation failed.

DXFILEERR_BADARRAYSIZE

Array size is invalid.

DXFILEERR_BADCACHEFILE

The cache file containing the .x file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.

DXFILEERR_BADDATAREFERENCE

Data reference is invalid.

DXFILEERR_BADFILE

File is invalid.

DXFILEERR_BADFILECOMPRESSIONTYPE

File compression type is invalid.

DXFILEERR_BADFILEFLOATSIZE

Floating-point size is invalid.

DXFILEERR_BADFILETYPE

File is not a DirectX .x file.

DXFILEERR_BADFILEVERSION

File version is not valid.

DXFILEERR_BADINTRINSICS

Intrinsics are invalid.

DXFILEERR_BADOBJECT

Object is invalid.

DXFILEERR_BADRESOURCE

Resource is invalid.

DXFILEERR_BADTYPE

Object type is invalid.

DXFILEERR_BADVALUE

Parameter is invalid.

DXFILEERR_FILENOTFOUND

File could not be found.

DXFILEERR_INTERNALERROR

Internal error occurred.

DXFILEERR_NOINTERNET

Internet connection not found.

DXFILEERR_NOMOREDATA

No further data is available.

DXFILEERR_NOMOREOBJECTS

All objects have been enumerated.

DXFILEERR_NOMORESTREAMHANDLES

No stream handles are available.

DXFILEERR_NOTDONEYET

Operation has not completed.

DXFILEERR_NOTFOUND

Object could not be found.

DXFILEERR_PARSEERROR

File could not be parsed.

DXFILEERR_RESOURCENOTFOUND

Resource could not be found.

DXFILEERR_NOTEMPLATE

No template available.

DXFILEERR_URLNOTFOUND

URL could not be found.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


X File Format Reference

This section contains reference information for the Microsoft® DirectX® (.x) file format.
  • Binary Encoding
  • Text Encoding
  • X File Templates

© 2002 Microsoft Corporation. All rights reserved.


Binary Encoding

This section details the binary version of the Microsoft® DirectX® (.x) file format as introduced with the release of DirectX 3.0.

The binary format is a tokenized representation of the text format. Tokens can be stand-alone or accompanied by primitive data records. Stand-alone tokens give grammatical structure, and record-bearing tokens supply the necessary data.

Note that all data is stored in little-endian format. A valid binary data stream consists of a header followed by templates and/or data objects.

This section discusses the following components of the binary file format and provides an example template and binary data object.

  • Header
  • Tokens
  • Token Records
  • Templates
  • Data
  • Examples

© 2002 Microsoft Corporation. All rights reserved.


Header

The following definitions should be used when directly reading and writing the binary header.

Note Compressed data streams are not currently supported and are therefore not detailed here.
#define XOFFILE_FORMAT_MAGIC \
  ((long)'x' + ((long)'o' << 8) + ((long)'f' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_VERSION \
  ((long)'0' + ((long)'3' << 8) + ((long)'0' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_BINARY \
  ((long)'b' + ((long)'i' << 8) + ((long)'n' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_TEXT   \
  ((long)'t' + ((long)'x' << 8) + ((long)'t' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_COMPRESSED \
  ((long)'c' + ((long)'m' << 8) + ((long)'p' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_32 \
  ((long)'0' + ((long)'0' << 8) + ((long)'3' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_64 \
  ((long)'0' + ((long)'0' << 8) + ((long)'6' << 16) + ((long)'4' << 24))

© 2002 Microsoft Corporation. All rights reserved.


Tokens

Tokens are written as little-endian WORDs. The following list of token values is divided into record-bearing and stand-alone tokens.

The record-bearing tokens are defined as follows.

#define TOKEN_NAME         1
#define TOKEN_STRING       2
#define TOKEN_INTEGER      3
#define TOKEN_GUID         5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST   7

The stand-alone tokens are defined as follows.

#define TOKEN_OBRACE      10
#define TOKEN_CBRACE      11
#define TOKEN_OPAREN      12
#define TOKEN_CPAREN      13
#define TOKEN_OBRACKET    14
#define TOKEN_CBRACKET    15
#define TOKEN_OANGLE      16
#define TOKEN_CANGLE      17
#define TOKEN_DOT         18
#define TOKEN_COMMA       19
#define TOKEN_SEMICOLON   20
#define TOKEN_TEMPLATE    31
#define TOKEN_WORD        40
#define TOKEN_DWORD       41
#define TOKEN_FLOAT       42
#define TOKEN_DOUBLE      43
#define TOKEN_CHAR        44
#define TOKEN_UCHAR       45
#define TOKEN_SWORD       46
#define TOKEN_SDWORD      47
#define TOKEN_VOID        48
#define TOKEN_LPSTR       49
#define TOKEN_UNICODE     50
#define TOKEN_CSTRING     51
#define TOKEN_ARRAY       52

© 2002 Microsoft Corporation. All rights reserved.


Token Records

This section describes the format of the records for each of the record-bearing tokens. Information is divided into the following sections.

  • TOKEN_NAME
  • TOKEN_STRING
  • TOKEN_INTEGER
  • TOKEN_GUID
  • TOKEN_INTEGER_LIST
  • TOKEN_FLOAT_LIST

TOKEN_NAME

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the name field. An ASCII name of length count completes the record.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_NAME
count | DWORD | 4 | Length of name field, in bytes
name | BYTE array | count | ASCII name

TOKEN_STRING

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the string field. An ASCII string of length count continues the record, which is completed by a terminating token. The choice of terminator is determined by syntax issues discussed elsewhere.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_STRING
count | DWORD | 4 | Length of string field in bytes
string | BYTE array | count | ASCII string
terminator | DWORD | 4 | TOKEN_SEMICOLON or TOKEN_COMMA

TOKEN_INTEGER

A fixed length record. The token is followed by the integer value required.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER
value | DWORD | 4 | Single integer

TOKEN_GUID

A fixed-length record. The token is followed by the four data fields as defined by the OSF DCE standard.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_GUID
data1 | DWORD | 4 | UUID data field 1
data2 | WORD | 2 | UUID data field 2
data3 | WORD | 2 | UUID data field 3
data4 | BYTE array | 8 | UUID data field 4

TOKEN_INTEGER_LIST

A variable-length record. The token is followed by a count value that specifies the number of integers that follow in the list field. For efficiency, consecutive integer lists should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER_LIST
count | DWORD | 4 | Number of integers in list field
list | DWORD | 4 × count | Integer list

TOKEN_FLOAT_LIST

A variable-length record. The token is followed by a count value that specifies the number of floats or doubles that follow in the list field. The size of the floating point value (float or double) is determined by the value of float sizespecified in the file header. For efficiency, consecutive TOKEN_FLOAT_LISTs should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_FLOAT_LIST
count | DWORD | 4 | Number of floats or doubles in list field
list | float/double array | 4 or 8 × count | Float or double list

© 2002 Microsoft Corporation. All rights reserved.


Templates

A template has the following syntax definition.

template              : TOKEN_TEMPLATE name TOKEN_OBRACE
                            class_id
                            template_parts
                            TOKEN_CBRACE

template_parts        : template_members_part TOKEN_OBRACKET
                        template_option_info
                        TOKEN_CBRACKET
                      | template_members_list

template_members_part : /* Empty */
                      | template_members_list

template_option_info  : ellipsis
                      | template_option_list

template_members_list :    template_members
                      | template_members_list template_members

template_members      : primitive
                      | array
                      | template_reference

primitive             : primitive_type optional_name TOKEN_SEMICOLON

array                 : TOKEN_ARRAY array_data_type name dimension_list
                        TOKEN_SEMICOLON

template_reference    : name optional_name YT_SEMICOLON

primitive_type        : TOKEN_WORD
                      | TOKEN_DWORD
                      | TOKEN_FLOAT
                      | TOKEN_DOUBLE
                      | TOKEN_CHAR
                      | TOKEN_UCHAR
                      | TOKEN_SWORD
                      | TOKEN_SDWORD
                      | TOKEN_LPSTR
                      | TOKEN_UNICODE
                      | TOKEN_CSTRING

array_data_type       : primitive_type
                      | name

dimension_list        : dimension
                      | dimension_list dimension

dimension             : TOKEN_OBRACKET dimension_size TOKEN_CBRACKET

dimension_size        : TOKEN_INTEGER
                      | name

template_option_list  : template_option_part
                      | template_option_list template_option_part

template_option_part  : name optional_class_id

name                  : TOKEN_NAME

optional_name         : /* Empty */
                      | name

class_id              : TOKEN_GUID

optional_class_id     : /* Empty */
                      | class_id

ellipsis              : TOKEN_DOT TOKEN_DOT TOKEN_DOT

© 2002 Microsoft Corporation. All rights reserved.


Data

A data object has the following syntax definition.

object                : identifier optional_name TOKEN_OBRACE
                            optional_class_id
                            data_parts_list
                            TOKEN_CBRACE

data_parts_list       : data_part
                      | data_parts_list data_part

data_part             : data_reference
                      | object
                      | number_list
                      | float_list
                      | string_list

number_list           : TOKEN_INTEGER_LIST

float_list            : TOKEN_FLOAT_LIST

string_list           : string_list_1 list_separator

string_list_1         : string
                      | string_list_1 list_separator string

list_separator        : comma
                      | semicolon

string                : TOKEN_STRING

identifier            : name
                      | primitive_type

data_reference        : TOKEN_OBRACE name optional_class_id TOKEN_CBRACE

Note that in number_list and float_list data in binary files, TOKEN_COMMA and TOKEN_SEMICOLON are not used. The comma and semicolon are used in string_list data. Also note that you can only use data_reference for optional data members.

© 2002 Microsoft Corporation. All rights reserved.


Examples

Two example binary template definitions and an example of a binary data object follow.

Note Data is stored in little-endian format, which is not shown in these examples.

The closed template RGB is identified by the UUID {55b6d780-37ec-11d0-ab39-0020af71e433} and has three members—r, g, and b—each of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_OBRACE,
TOKEN_GUID, 55b6d780, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_FLOAT, TOKEN_NAME, 1, 'r', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'g', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'b', TOKEN_SEMICOLON,
TOKEN_CBRACE

The closed template Matrix4x4 is identified by the UUID {55b6d781-37ec-11d0-ab39-0020af71e433} and has one member—a two-dimensional array named matrix—of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 9, 'M', 'a', 't', 'r', 'i', 'x', '4', 'x', '4', TOKEN_OBRACE,
TOKEN_GUID, 55b6d781, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_ARRAY, TOKEN_FLOAT, TOKEN_NAME, 6, 'm', 'a', 't', 'r', 'i', 'x',
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_CBRACE

The binary data object that follows shows an instance of the RGB template defined earlier. The example object is named blue, and its three members—r, g, and b—have the values 0.0, 0.0, and 1.0, respectively.

TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_NAME, 4, 'b', 'l', 'u', 'e', TOKEN_OBRACE,
TOKEN_FLOAT_LIST, 3, 0.0, 0.0, 1.0, TOKEN_CBRACE

© 2002 Microsoft Corporation. All rights reserved.


Text Encoding

The Microsoft® DirectX® .x file format is not specific to any application. It uses templates that don't depend on how the file is used. This allows the .x file format to be used by any client application.

This following sections deal with the content and syntax of the file format, which uses the .x extension in the DirectX software development kit (SDK).

  • Data
  • Reserved Words, Header, and Comments
  • Templates
  • Use of Commas and Semicolons

© 2002 Microsoft Corporation. All rights reserved.


Data

Data objects contain the actual data or a reference to that data. Each data object has a corresponding template that specifies the data type. The following sections discuss the form and parts of data objects.

Form, Identifier, and Name

Data objects have the following form.

<Identifier> [name] { [<UUID>]
<member 1>;
...
<member n>;
}

The identifier is compulsory and must match a previously defined data type or primitive. However, the name is optional.

Data Members

Data members can be one of the following: data object, data reference, integer list, float list, or string list.

A data object is a nested data object. This enables the hierarchical nature of the file format to be expressed. The types of nested data objects allowed in the hierarchy may be restricted. See Templates for more information.

A data reference is a reference to a previously encountered data object as shown in the following example.

{
  name |
  UUID |
  name UUID
}

An integer list is a semicolon-separated list of integers, as shown in the following example.

1; 2; 3;

A float list is a semicolon-separated list of floats, as shown in the following example.

1.0; 2.0; 3.0;

A string list is a semicolon-separated list of strings, as shown in the following example.

"Moose"; "Goats"; "Sheep";

© 2002 Microsoft Corporation. All rights reserved.


Reserved Words, Header, and Comments

The table below shows which words are reserved and must not be used.

ARRAY | DWORD | UCHAR
BINARY | FLOAT | ULONGLONG
BINARY_RESOURCE | SDWORD | UNICODE
CHAR | STRING | WORD
CSTRING | SWORD |
DOUBLE | TEMPLATE |

The variable-length header is compulsory and must be at the beginning of the data stream. The header contains the following data.

Type | Required | Size (in bytes) | Value | Description
Magic Number | x | 4 | "xof " |
Version Number | x | 2 | "03" | Major version 3
 |  |  | "03" | Minor version 3
Format Type | x | 4 | "txt " | Text File
 |  |  | "bin " | Binary file
 |  |  | "tzip" | MSZip compressed text file
 |  |  | "bzip" | MSZip compressed binary file
Float Size | x |  | "0064" | 64-bit floats
 | x |  | "0032" | 32-bit floats

The values in the table are delimited by quotes to call attention to the number of characters in each value. Those with 4 bytes contain four characters, those with 2 bytes contain two characters.

Comments are applicable only in text files. Comments can occur anywhere in the data stream. A comment begins with either C++ style double-slashes (//), or a number sign (#). The comment runs to the next new line. The following example shows valid comments.

#  This is a comment.
// This is another comment.

© 2002 Microsoft Corporation. All rights reserved.


Templates

Templates define how the data stream is interpreted—the data is modulated by the template definition. This section discusses the following aspects of a template and provides an example template.

There is one special template - the header template. It is recommended that each application define a header template and use it to define application-specific information, such as version information. If present, this header is read by the .x file format application programming interface (API). If a flags member is available, it is used to determine how the following data is interpreted. The flags member, if defined, should be a DWORD. One bit is currently defined - bit 0. If this bit is clear, the following data in the file is binary. If set, the following data is text. You can use multiple header data objects to switch between binary and text within the file.

Template Form, Name, and UUID

A template has the following form.

template <template-name> {
<UUID>
<member 1>;
...
<member n>;
[restrictions]
}

The template name is an alphanumeric name that can include the underscore character (_). It must not begin with a digit. The UUID is a universally unique identifier formatted to the Open Software Foundation's Distributed Computing Environment standard and enclosed by angle brackets (< >). For example: <3D82AB43-62DA-11cf-AB39-0020AF71E433>.

Template Members

Template members consist of a named data type followed by an optional name or an array of a named data type. Valid primitive data types are defined in the following table.

Type | Size
WORD | 16 bits
DWORD | 32 bits
FLOAT | IEEE float
DOUBLE | 64 bits
CHAR | 8 bits
UCHAR | 8 bits
BYTE | 8 bits
STRING | NULL terminated string
CSTRING | Formatted C string (not supported)
UNICODE | Unicode string (not supported)

Additional data types defined by templates encountered earlier in the data stream can also be referenced within a template definition. No forward references are allowed.

Any valid data type can be expressed as an array in the template definition. The basic syntax is shown in the following example.

array <data-type> <name>[<dimension-size>];

<dimension-size> can either be an integer or a named reference to another template member whose value is then substituted. Arrays can be n-dimensional, where n is determined by the number of paired square brackets trailing the statement, as in the following example.

array DWORD FixedHerd[24];
array DWORD Herd[nCows];
array FLOAT Matrix4x4[4][4];

Template Restrictions

Templates can be open, closed, or restricted. These restrictions determine which data types can appear in the immediate hierarchy of a data object defined by the template. An open template has no restrictions, a closed template rejects all data types, and a restricted template allows a named list of data types.

The syntax for indicating an open template is three periods enclosed by square brackets.

[ ... ]

A comma-separated list of named data types followed optionally by their universally unique identifiers (UUIDs) enclosed by square brackets indicates a restricted template.

[ { data-type [ UUID ] , } ... ]

The absence of either of the above indicates a closed template.

Template Example

The following shows an example template.

template Mesh {
<3D82AB44-62DA-11cf-AB39-0020AF71E433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
 [ ... ]                // An open template
}
template Vector {
<3D82AB5E-62DA-11cf-AB39-0020AF71E433>
FLOAT x;
FLOAT y;
FLOAT z;
}                        // A closed template
template FileSystem {
<UUID>
STRING name;
[ Directory <UUID>, File <UUID> ]    // A restricted template
}

© 2002 Microsoft Corporation. All rights reserved.


Use of Commas and Semicolons

Using commas and semicolons can be the most complex syntax issue in the file format, and this usage is very strict. Commas are used to separate array members; semicolons terminate each data item.

For example, if a template is defined in the following manner:

template mytemp {
DWORD myvar;
}

Then an instance of this template looks like the following:

mytemp dataTemp {
1;
}

If a template containing another template is defined in the following manner;

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
FLOAT aFloat;
mytemp aTemp;
}

Then an instance of this template looks like the following:

container dataContainer {
1.1;
2; 3;;
}

Note that the second line that represents the mytemp inside container has two semicolons at the end of the line. The first semicolon indicates the end of the data item, aTemp (inside container), and the second semicolon indicates the end of the container.

If an array is defined in the following manner:

Template mytemp {

array DWORD myvar[3];

}

Then an instance of this looks like the following:

mytemp aTemp {
1, 2, 3;
}

In the array example, there is no need for the data items to be separated by semicolons because they are delineated by commas. The semicolon at the end marks the end of the array.

Consider a template that contains an array of data items defined by a template.

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
DWORD count;
array mytemp tempArray[count];
}

An instance of this would look like the following example.

container aContainer {
3;
1;2;,3;4;,5;6;;
}

© 2002 Microsoft Corporation. All rights reserved.


X File Templates

This section lists the .x file templates.

  • Animation
  • AnimationKey
  • AnimationOptions
  • AnimationSet
  • AnimTicksPerSecond
  • Boolean
  • Boolean2d
  • ColorRGB
  • ColorRGBA
  • Coords2d
  • DeclData
  • EffectDWord
  • EffectFloats
  • EffectInstance
  • EffectParamDWord
  • EffectParamFloats
  • EffectString
  • FaceAdjacency
  • FloatKeys
  • Frame
  • FrameTransformMatrix
  • FVFData
  • IndexedColor
  • Material
  • Matrix4x4
  • Mesh
  • MeshFace
  • MeshFaceWraps
  • MeshMaterialList
  • MeshNormals
  • MeshTextureCoords
  • MeshVertexColors
  • Patch
  • PatchMesh
  • PatchMesh9
  • PMAttributeRange
  • PMInfo
  • PMVSplitRecord
  • SkinWeights
  • TextureFilename
  • TimedFloatKeys
  • Vector
  • VertexDuplicationIndices
  • VertexElement
  • XSkinMeshHeader

© 2002 Microsoft Corporation. All rights reserved.


Animation

Contains animations referencing a previous frame. It should contain one reference to a frame and at least one set of AnimationKey templates. It also can contain an AnimationOptions data object.

        template Animation \
        { \
            < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 > \
            DWORD AnimationKey; \
            DWORD AnimationOptions; \
        }

Where:

  • AnimKey - An animation key. See AnimationKey.
  • AnimOptions - An animation option. If this element is not present, an animation is closed. See AnimationOptions.

© 2002 Microsoft Corporation. All rights reserved.


AnimationKey

Defines a set of animation keys. A matrix key is useful for sets of animation data that need to be represented as transformation matrices.

        template AnimationKey \
        { \
            < 10DD46A8-775B-11cf-8F52-0040333594A3 > \
            DWORD keyType; \
            DWORD nKeys; \
            DWORD keys; \
        }

Where:

  • keyType - Specifies whether the keys are rotation, scale position, or matrix keys (using the integers 0, 1, 2, or 3 respectively).
  • nKeys - Number of keys.
  • keys - See TimedFloatKeys.

© 2002 Microsoft Corporation. All rights reserved.


AnimationOptions

Enables you to set animation options.

        template AnimationOptions \
        { \
            < E2BF56C0-840F-11cf-8F52-0040333594A3 > \
            DWORD openclosed; \
            DWORD positionquality; \
        }

Where:

  • openclosed - Use 0 for a closed animation, or 1 for an open animation. By default, an animation is closed.
  • positionquality - Set the position quality for any position keys specified. Use 0 for spline positions or 1 for linear positions.

© 2002 Microsoft Corporation. All rights reserved.


AnimationSet

Contains one or more Animation objects. Each animation within an animation set has the same time at any given point. Increasing the animation set's time increases the time for all the animations it contains.

        template AnimationSet \
        { \
            < 3D82AB50-62DA-11cf-AB39-0020AF71E433 > \
            [ Animation ] \
        }

Where:

  • [ Animation ] - Optional animation template.

© 2002 Microsoft Corporation. All rights reserved.


AnimTicksPerSecond

Describes an animation scale factor.

        template AnimTicksPerSecond \
        { \
            < 9E415A43-7BA6-4a73-8743-B73D47E88476 > \
            DWORD AnimTicksPerSecond; \
        }

Where:

  • AnimTicksPerSecond - A scale factor to convert animation time stamps to global time. Its value divides the animation time by either 30, 60, 24 or 25.

© 2002 Microsoft Corporation. All rights reserved.


Boolean

Defines a simple Boolean type.

        template Boolean \
        { \
            < 4885AE61-78E8-11cf-8F52-0040333594A3 > \
            DWORD truefalse; \
        }

Where:

  • truefalse - True for a Boolean, false otherwise.

© 2002 Microsoft Corporation. All rights reserved.


Boolean2d

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

        template Boolean2d \
        { \
            < 4885AE63-78E8-11cf-8F52-0040333594A3 > \
            bool u; \
            bool v; \
        }

© 2002 Microsoft Corporation. All rights reserved.


ColorRGB

Defines the basic RGB color object.

        template ColorRGB \
        { \
            < D3E16E81-7835-11cf-8F52-0040333594A3 > \
            float red; \
            float green; \
            float blue; \
        }

© 2002 Microsoft Corporation. All rights reserved.


ColorRGBA

Defines a color object with an alpha component. This is used for the face color in the material template definition.

        template ColorRGBA \
        { \
            < 35FF44E0-6C7C-11cf-8F52-0040333594A3 > \
            float red; \
            float green; \
            float blue; \
            float alpha; \
        }

© 2002 Microsoft Corporation. All rights reserved.


Coords2d

A two dimensional vector used to define a mesh's texture coordinates.

        template Coords2d \
        { \
            < F6F23F44-7686-11cf-8F52-0040333594A3 > \
            float u; \
            float v; \
        }

© 2002 Microsoft Corporation. All rights reserved.


DeclData

Describes a vertex declaration.

        template DeclData \
        { \
            < BF22E553-292C-4781-9FEA-62BD554BDD93 > \
            DWORD nElements; \
            array VertexElement Elements[nElements]; \
            DWORD nDWords; \
            array DWORD data[nDWords]; \
        }

Where:

  • nElements - Number of vertex declaration elements.
  • Elements[nElements] - Array of vertex declaration elements.
  • nDWords - Number of DWORDS.
  • data[nDWords] - Array of DWORDS that contain the data in each vertex element.

© 2002 Microsoft Corporation. All rights reserved.


EffectDWord

Defines a legacy effect DWORD. This template has been replaced by the EffectParamDWord template.

        template EffectDWord \
        { \
            < 622C0ED0-956E-4da9-908A-2AF94F3CE716 > \
            DWORD Value; \
        }

© 2002 Microsoft Corporation. All rights reserved.


EffectFloats

Defines a legacy effect FLOAT. This template has been replaced by the EffectParamFloats template.

        template EffectFloats \
        { \
            < F1CFE2B3-0DE3-4e28-AFA1-155A750A282D > \
            DWORD nFloats; \
            array float Floats[nFloats]; \
        }

Where:

  • nFloats - Number of floats.
  • Floats[nFloats] - Array of float values.

© 2002 Microsoft Corporation. All rights reserved.


EffectInstance

Defines an effect instance.

        template EffectInstance \
        { \
            < E331F7E4-0559-4cc2-8E99-1CEC1657928F > \
            STRING EffectFilename; \
            [ ... ] \
        }

Where:

  • EffectFilename - Effect filename.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

© 2002 Microsoft Corporation. All rights reserved.


EffectParamDWord

Defines an effect DWORD. This template replaced the EffectDWord template.

        template EffectParamDWord \
        { \
            < E13963BC-AE51-4c5d-B00F-CFA3A9D97CE5 > \
            STRING ParamName; \
            DWORD Value; \
        }

Where:

  • ParamName - Parameter name.
  • Value - Parameter value.

© 2002 Microsoft Corporation. All rights reserved.


EffectParamFloats

Defines effect floating-point numbers. This template replaces the EffectFloats template.

        template EffectParamFloats \
        { \
            < 3014B9A0-62F5-478c-9B86-E4AC9F4E418B > \
            STRING ParamName; \
            DWORD nFloats; \
            array float Floats[nFloats]; \
        }

Where:

  • ParamName - Name of the array of floats.
  • nFloats - Number of floating-point values in the array.
  • Floats[nFloats] - Array of floating-point values.

© 2002 Microsoft Corporation. All rights reserved.


EffectParamString

Defines an effect string.

        template EffectParamString \
        { \
            < 1DBC4C88-94C1-46ee-9076-2C28818C9481 > \
            STRING ParamName; \
            STRING Value; \
        }

© 2002 Microsoft Corporation. All rights reserved.


EffectString

Defines a legacy effect string. This template has been replaced by the EffectParamString template.

        template EffectString \
        { \
            < D55B097E-BDB6-4c52-B03D-6051C89D0E42 > \
            STRING Value; \
        }

© 2002 Microsoft Corporation. All rights reserved.


FaceAdjacency

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

        template FaceAdjacency \
        { \
            < A64C844A-E282-4756-8B80-250CDE04398C > \
            DWORD nIndices; \
            array DWORD indices[nIndices]; \
        }

Where:

  • nIndices - Number of indices in the mesh.
  • indices[nIndices] - Array of indices.

© 2002 Microsoft Corporation. All rights reserved.


FloatKeys

Defines an array of floating-point numbers (floats) and the number of floats in that array. This is used for defining sets of animation keys.

        template FloatKeys \
        { \
            < 10DD46A9-775B-11cf-8F52-0040333594A3 > \
            DWORD nValues; \
            array float values[nValues]; \
        }

© 2002 Microsoft Corporation. All rights reserved.


Frame

Defines a coordinate frame, or "frame of reference." The Frame template is open and can contain any object. The Direct3D extensions (D3DX) mesh-loading functions recognize Mesh, FrameTransformMatrix, and Frame template instances as child objects when loading a Frame instance.

        template Frame \
        { \
            < 3D82AB46-62DA-11cf-AB39-0020AF71E433 > \
            FrameTransformMatrix frameTransformMatrix; \
            Mesh mesh; \
        }

Where:

  • frameTransformMatrix - A transform template. See FrameTransformMatrix.
  • mesh - A mesh template. See Mesh.

© 2002 Microsoft Corporation. All rights reserved.


FrameTransformMatrix

Defines a local transform for a frame (and all its child objects).

        template FrameTransformMatrix \
        { \
            < F6F23F41-7686-11cf-8F52-0040333594A3 > \
            Matrix4x4 frameMatrix; \
        }

Where:

  • frameMatrix - A Matrix4x4 template. See Matrix4x4.

© 2002 Microsoft Corporation. All rights reserved.


FVFData

Specifies the mesh data minus the position data.

        template FVFData \
        { \
            <B6E70A0E-8EF9-4e83-94AD-ECC8B0C04897 > \
            DWORD dwFVF; \
            DWORD nDWords; \
            array DWORD data[nDWords]; \
        }

Where:

  • dwFVF - A flexible vertex format (FVF) code.
  • nDWords - Binary data. The number of DWORDS.
  • data[nDWords] - Binary data. The vertex data without the position data.

It is like a vertex buffer with the FVF code and the vertex data, except that the vertex position data is removed.

© 2002 Microsoft Corporation. All rights reserved.


IndexedColor

Consists of an index parameter and an RGBA color and is used for defining mesh vertex colors. The index defines the vertex to which the color is applied.

        template IndexedColor \
        { \
            < 1630B820-7842-11cf-8F52-0040333594A3 > \
            DWORD index; \
            COLORRGBA indexColor; \
        }

Where:

  • indexColor - A ColorRGBA template. See ColorRGBA.

© 2002 Microsoft Corporation. All rights reserved.


Material

Defines a basic material color that can be applied to either a complete mesh or a mesh's individual faces. The power is the specular exponent of the material.

Note The ambient color requires an alpha component.

TextureFilename is an optional data object. If this object is not present, the face is untextured.

        template Material \
        { \
            < 3D82AB4D-62DA-11cf-AB39-0020AF71E433 > \
            DWORD faceColor; \
            float power; \
            DWORD specularColor; \
            DWORD emissiveColor; \
        }

Where:

  • faceColor - Face color. A ColorRGBA template. See ColorRGBA.
  • power - Material specular color exponent.
  • specularColor - Material specular color. A ColorRGB template. See ColorRGB.
  • emissiveColor - Material emissive color. A ColorRGB template. See ColorRGB.

© 2002 Microsoft Corporation. All rights reserved.


Matrix4x4

Defines a 4×4 matrix. This is used as a frame transformation matrix.

        template Matrix4x4 \
        { \
            < F6F23F45-7686-11cf-8F52-0040333594A3 > \
            array float matrix[16]; \
        }

Where:

  • array float matrix[16] - Array of 16 floats.

© 2002 Microsoft Corporation. All rights reserved.


Mesh

Defines a simple mesh. The first array is a list of vertices, and the second array defines the faces of the mesh by indexing into the vertex array.

        template Mesh \
        { \
            < 3D82AB44-62DA-11cf-AB39-0020AF71E433 > \
            DWORD nVertices; \
            array vertices[Vector]; \
            DWORD nFaces; \
            array faces[Vector]; \

            // optional:
            meshFaceWraps template; \
            meshTextureCoordinates template; \
            meshNormals template; \
            meshVertexColors template; \
            meshMaterialList template; \
        }

Where:

  • nVertices - Number of vertices.
  • array vertices[Vector] - Array of vertices. See Vector.
  • nFaces - Number of faces.
  • array faces[Vector] - Array of faces. See Vector.

The following data elements are optional:

  • meshFaceWraps - If this is not present, wrapping for both u and v defaults to false. See MeshFaceWraps.
  • meshTextureCoordinates - If this is not present, there are no texture coordinates. See MeshTextureCoords.
  • meshNormals - If this is not present, normals are generated. See MeshNormals.
  • meshVertexColors - If this is not present, the colors default to white. See MeshVertexColors.
  • meshMaterialList - If this is not present, the material defaults to white. See MeshMaterialList.

© 2002 Microsoft Corporation. All rights reserved.


MeshFace

Used by the Mesh template to define a mesh's faces. Each element of the nFaceVertexIndices array references a mesh vertex used to build the face.

        template MeshFace \
        { \
            < 3D82AB5F-62DA-11cf-AB39-0020AF71E433 > \
            DWORD nFaceVertexIndices; \
            array DWORD faceVertexIndices[nFaceVertexIndices]; \
        }

Where:

  • nFaceVertexIndices - Number of indices.
  • array DWORD faceVertexIndices[nFaceVertexIndices] - Array of indices.

© 2002 Microsoft Corporation. All rights reserved.


MeshFaceWraps

Used to define the texture topology of each face in a wrap. The value of the nFaceWrapValues member should be equal to the number of faces in a mesh.

        template MeshFaceWraps \
        { \
            <4885AE62-78E8-11cf-8F52-0040333594A3> \
            DWORD nFaceWrapValues; \
            boolean2D faceWrapValues; \
        }

This template is no longer used.

© 2002 Microsoft Corporation. All rights reserved.


MeshMaterialList

Used in a mesh object to specify which material applies to which faces. The nMaterials member specifies how many materials are present, and materials specify which material to apply.

        template MeshMaterialList \
        { \
            < F6F23F42-7686-11cf-8F52-0040333594A3 > \
            DWORD nMaterials; \
            DWORD nFaceIndexes; \
            DWORD FaceIndexes; \
        }

© 2002 Microsoft Corporation. All rights reserved.


MeshNormals

Defines normals for a mesh. The first array of vectors is the normal vectors themselves, and the second array is an array of indexes specifying which normals should be applied to a given face. The value of the nFaceNormals member should be equal to the number of faces in a mesh.

        template MeshNormals \
        { \
            < F6F23F43-7686-11cf-8F52-0040333594A3 > \
            DWORD nNormals; \
            array Vector normals[nNormals]; \
            DWORD nFaceNormals; \
            array MeshFace meshFaces[nFaceNormals]; \

        }

Where:

  • nNormals - Number of normals.
  • array Vector normals[nNormals] - Array of normals. See Vector.
  • nFaceNormals - Number of face normals.
  • array MeshFace meshFaces[nFaceNormals] - Array of mesh face normals.See MeshFace.

© 2002 Microsoft Corporation. All rights reserved.


MeshTextureCoords

Defines a mesh's texture coordinates.

        template MeshTextureCoords \
        { \
            < F6F23F40-7686-11cf-8F52-0040333594A3 > \
            DWORD nTextureCoords; \
            array coords2d textureCoords[nTextureCoords] ; \
        }

Where:

  • nTextureCoords - Number of texture coordinates.
  • array coords2d textureCoords[nTextureCoords] - Array of 2-D texture coordinates. See Coords2d.

© 2002 Microsoft Corporation. All rights reserved.


MeshVertexColors

Specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

        template MeshVertexColors \
        { \
            <1630B821-7842-11cf-8F52-0040333594A3> \
            DWORD nVertexColors; \
            array IndexColor vertexColors[nVertexColors]; \
        }

Where:

  • nVertexColors - Number of colors. This matches the number of vertices in the mesh.
  • array IndexColor vertexColors[nVertexColors] - Array of indexed colors. See IndexedColor.

© 2002 Microsoft Corporation. All rights reserved.


Patch

Defines a Bézier control patch. The array defines the control points for the patch.

        template Patch \
        { \
            < A3EB5D44-FC22-429D-9AFB-3221CB9719A6 > \
            DWORD nControlIndices; \
            array DWORD controlIndices[nControlIndices]; \
        }

Where:

  • nControlIndices - Number of control point indices.
  • array DWORD controlIndices[nControlIndices] - Array of control point indices.

The type of patch is defined by the number of control points, as shown in the following table.

Number of control points | Type
10 | Cubic Bézier triangular patch
15 | Quartic Bézier triangular patch
16 | Cubic Bézier quad rectangle patch

The order of the control points are given in a spiral pattern, as shown in the following diagrams for triangular and rectangular patches.

Triangular patches used the following pattern.

Rectangular patches use the following pattern.

© 2002 Microsoft Corporation. All rights reserved.


PatchMesh

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

        template PatchMesh \
        { \
            < D02C95CC-EDBA-4305-9B5D-1820D7704BBF > \
            DWORD nVertices; \
            array Vector vertices[nVertices]; \
            DWORD nPatches; \
            array Patch patches[nPatches]; \
            [ ... ] \
        }

Where:

  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch. This is a legacy template. The latest patch mesh template is PatchMesh9.

© 2002 Microsoft Corporation. All rights reserved.


PatchMesh9

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

        template PatchMesh9 \
        { \
            < B9EC94E1-B9A6-4251-BA18-94893F02C0EA > \
            DWORD Type; \
            DWORD Degree; \
            DWORD Basis; \
            DWORD nVertices; \
            array Vector vertices[nVertices]; \
            DWORD nPatches; \
            array Patch patches[nPatches]; \
            [ ... ] \
        }

Where:

  • Type - Patch mesh type: rectangle, triangle, or N-patch.
  • Degree - Degree of the variables in the curve equation.
  • Basis - Basis type of a high-order patch surface.
  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch.

© 2002 Microsoft Corporation. All rights reserved.


PMAttributeRange

This is an internal progressive mesh format.

        template PMAttributeRange \
        { \
            < 917E0427-C61E-4a14-9C64-AFE65F9E9844 > \
            DWORD iFaceOffset; \
            DWORD nFacesMin; \
            DWORD nFacesMax; \
            DWORD iVertexOffset; \
            DWORD nVerticesMin; \
            DWORD nVerticesMax; \
        }

It is not intended for use in an application.

© 2002 Microsoft Corporation. All rights reserved.


PMInfo

This is an internal progressive mesh format.

        template PMInfo \
        { \
            < B6C3E656-EC8B-4b92-9B62-681659522947 > \
            DWORD nAttributes; \
            array PMAttributeRange attributeRanges[nAttributes]; \
            DWORD nMaxValence; \
            DWORD nMinLogicalVertices; \
            DWORD nMaxLogicalVertices; \
            DWORD nVSplits; \
            array PMVSplitRecord splitRecords[nVSplits]; \
            DWORD nAttributeMispredicts; \
            array DWORD attributeMispredicts[nAttributeMispredicts]; \
        }

It is not intended for use in an application.

© 2002 Microsoft Corporation. All rights reserved.


PMVSplitRecord

This is an internal progressive mesh format.

        template PMVSplitRecord \
        { \
            < 574CCC14-F0B3-4333-822D-93E8A8A08E4C > \
            DWORD iFaceCLW; \
            DWORD iVlrOffset; \
            DWORD iCode; \
        }

It is not intended for use in an application.

© 2002 Microsoft Corporation. All rights reserved.


SkinWeights

This template is instantiated on a per-mesh basis. Within a mesh, a sequence of n instances of this template will appear, where n is the number of bones (X file frames) that influence the vertices in the mesh. Each instance of the template basically defines the influence of a particular bone on the mesh. There is a list of vertex indices, and a corresponding list of weights.

        template SkinWeights \
        { \
            < 6F0D123B-BAD2-4167-A0D0-80224F25FABB > \
            STRING transformNodeName; \
            DWORD nWeights; \
            array DWORD vertexIndices[nWeights]; \
            array float weights[nWeights]; \
            Matrix4x4 matrixOffset; \
        }

Where:

  • The name of the bone whose influence is being defined is transformNodeName, and nWeights is the number of vertices affected by this bone.
  • The vertices influenced by this bone are contained in vertexIndices, and the weights for each of the vertices influenced by this bone are contained in weights.
  • The matrix matrixOffset transforms the mesh vertices to the space of the bone. When concatenated to the bone's transform, this provides the world space coordinates of the mesh as affected by the bone. See Matrix4x4.

© 2002 Microsoft Corporation. All rights reserved.


TextureFilename

Enables you to specify the file name of a texture to apply to a mesh or a face. This template should appear within a material object.

        template TextureFilename \
        { \
            < A42790E1-7810-11cf-8F52-0040333594A3 > \
            string filename; \
        }

© 2002 Microsoft Corporation. All rights reserved.


TimedFloatKeys

Defines a set of floats and a positive time used in animations.

        template TimedFloatKeys \
        { \
            < F406B180-7B3B-11cf-8F52-0040333594A3 > \
            DWORD time; \
            FloatKeys tfkeys; \
        }

Where:

  • tfkeys - See FloatKeys.

© 2002 Microsoft Corporation. All rights reserved.


Vector

Defines a vector.

        template Vector \
        { \
            < 3D82AB5E-62DA-11cf-AB39-0020AF71E433 > \
            float x; \
            float y; \
            float z; \
        }

© 2002 Microsoft Corporation. All rights reserved.


VertexDuplicationIndices

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

        template VertexDuplicationIndices \
        { \
            < B8D65549-D7C9-4995-89CF-53A9A8B031E3 > \
            DWORD nIndices; \
            DWORD nOriginalVertices; \
            array DWORD indices[nIndices]; \
        }

Where:

  • nIndices - Number of vertex indices. This is the number of vertices in the mesh.
  • nOriginalVertices - Number of vertices in the mesh before any duplication occurs.
  • The value indices[n] holds the vertex index that vertex[n] in the vertex array for the mesh would have had if no duplication had occurred. Indices in this array that are the same, therefore, indicate duplicate vertices.

© 2002 Microsoft Corporation. All rights reserved.


VertexElement

Describes an individual vertex element in a vertex declaration.

        template VertexElement \
        { \
            < F752461C-1E23-48f6-B9F8-8350850F336F > \
            DWORD Type; \
            DWORD Method; \
            DWORD Usage; \
            DWORD UsageIndex; \
        }

Where:

  • Type - Vertex data type. See D3DDECLTYPE.
  • Method - Tessellator processing method. See D3DDECLMETHOD.
  • Usage - Intended use of the vertex data. See D3DDECLUSAGE.
  • UsageIndex - Modifies the usage data. See D3DDECLUSAGE.

Related Topics

  • D3DVERTEXELEMENT9

© 2002 Microsoft Corporation. All rights reserved.


XSkinMeshHeader

This template is instantiated on a per-mesh basis only in meshes that contain exported skinning information. The purpose of this template is to provide information about the nature of the skinning information that was exported.

        template XSkinMeshHeader \
        { \
            < 3CF169CE-FF7C-44ab-93C0-F78F62D172E2 >  \
            WORD nMaxSkinWeightsPerVertex; \
            WORD nMaxSkinWeightsPerFace; \
            WORD nBones; \
        }

Where:

  • nMaxSkinWeightsPerVertex - Maximum number of transforms that affect a vertex in the mesh.
  • nMaxSkinWeightsPerFace - Maximum number of unique transforms that affect the three vertices of any face.
  • nBones - Number of bones that affect vertices in this mesh.

© 2002 Microsoft Corporation. All rights reserved.


Shader Reference

Shaders drive the programmable graphics pipeline.

Vertex Shader Reference

  • Vertex Shader 1_1
  • Vertex Shader 2_0
  • Vertex Shader 2_0 Extended
  • Vertex Shader 3_0

Vertex Shader Differences summarizes the differences between vertex shader versions.

Mapping Vertex Declarations contains information about the new style of vertex declarations.

Pixel Shader Reference

  • Pixel Shader 1_X
  • Pixel Shader 2_0
  • Pixel Shader 2_0 Extended
  • Pixel Shader 3_0

Pixel Shader Differences summarizes the differences between pixel shader versions.

Relative Addressing demonstrates relative address registers.

CountingFlowControlInstructions identifies flow control instruction counting restrictions.

Shader Debugger introduces the shader debugger.

High-Level Shader Language summarizes the high-level shader language.

Shader Driver Model Requirements

Microsoft® DirectX® 9.0 interfaces are restricted to device driver interface (DDI) drivers that are DirectX 7.0-level and above. To check the DDI level, run the DirectX Diagnostic Tool and examine the saved text file.

For reference, DirectX 8.0 interfaces work only on DDI drivers that are DirectX 6.0-level and above.

Shader Binary Format

The bitwise layout of the shader instruction stream is defined in D3d9types.h. If you want to design your own shader compiler or construction tools and you want more information about the shader token stream, refer the DirectX 9.0 Driver Development Kit (DDK).

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader 1_1

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • The Programmable Vertex Shader Architecture illustrates the relationship between shader registers and the vertex shader ALU.
  • Instructions - vs_1_1 contains a list of the available instructions.
  • Registers - vs_1_1 lists the different types of registers used by the vertex shader ALU.
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - vs_1_1

This section contains reference information for the vertex shader version 1_1 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | New
add | Add two vectors | 1 |  | x |  | x
dcl_usage | Declare input vertex registers. See Registers - vs_1_1 | 0 | x |  |  | x
def | Define constants | 0 | x |  |  | x
dp3 | Three-component dot product | 1 |  | x |  | x
dp4 | Three-component dot product | 1 |  | x |  | x
dst | Distance | 1 |  | x |  | x
exp | Full precision 2x | 10 |  |  | x | x
expp | Partial precision 2x | 1 |  |  | x | x
frc | Fractional component | 3 |  |  | x | x
lit | Calculate lighting | 1 |  | x |  | x
log | Full precision log2(x) | 10 |  |  | x | x
logp | Partial precision log2(x) | 1 |  |  | x | x
m3x2 | 3x2 matrix multiply | 2 |  |  | x | x
m3x3 | 3x3 matrix multiply | 3 |  |  | x | x
m3x4 | 3x4 matrix multiply | 4 |  |  | x | x
m4x3 | 4x3 matrix multiply | 3 |  |  | x | x
m4x4 | 4x4 matrix multiply | 4 |  |  | x | x
mad | Multiply and add | 1 |  | x |  | x
max | Maximum | 1 |  | x |  | x
min | Minimum | 1 |  | x |  | x
mov | Move | 1 |  | x |  | x
mul | Multiply | 1 |  | x |  | x
nop | No operation | 0 |  | x |  | x
rcp | Reciprocal | 1 |  | x |  | x
rsq | Reciprocal square root | 1 |  | x |  | x
sge | Greater than or equal compare | 1 |  | x |  | x
slt | Less than compare | 1 |  | x |  | x
sub | Subtract | 1 |  | x |  | x
vs | Version | 0 | x |  |  | x

© 2002 Microsoft Corporation. All rights reserved.


Registers - vs_1_1

This section contains reference information for the input and output registers implemented by vertex shader version 1_1. Vector elements are designated as x, y, z, w (or the r, g, b, a equivalents).

Input Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Read port | Read / Instruction | Rel-Address | Defaults | Requires DCL
a0 | address | 1 | integer | 4-D vector (1) | write / use | 1 | 3 | no | none | no
c# | float constant | 96 (2) | floating-point | 4-D vector | define / read | 1 | 3 | a0.x | (0, 0, 0, 0) | no
r# | temporary | 12 | floating-point | 4-D vector | write / read | 3 | 3 | no | none | no
v# | input | 16 | floating-point | 4-D vector | read | 1 | 3 | no | (0, 0, 0, 1) | yes

(1) In vs_1_1, though a0 is a 4-D vector, only the .x component can be referenced.

(2) 96 is the minimum c# register count required by vs_1_1. The D3DCAPS9.MaxVertexShaderConst cap contains the actual c# register count supported by the device.

See Input Registers.

Output Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Rel-Address | Default | Require DCL
oD# | diffuse / specular (3) | 2 | floating-point | 4-D vector | write | no | none | no
oFog | fog | 1 | floating-point | scalar | write | no | none | no
oPos (4) | position | 1 | floating-point | 4-D vector | write | no | none | no
oPts | point size | 1 | floating-point | scalar | write | no | none | no
oT# | texture coordinate | 8 | floating-point | 4-D vector | write | no | none | no

(3) oD0 = diffuse color; oD1 = specular color.

(4) All four components of oPos must be written.

See Output Registers.

© 2002 Microsoft Corporation. All rights reserved.


Instruction Modifiers (Vertex Shader)

Instruction modifiers affect the result of the instruction before it is written into the destination register.

Sat

Saturates or clamps the instruction result to [0,1] range before writing to the destination register.

add_sat rDest, rSrc0, rSrc1

Where:

rDest = clamp_between_0_and_1(rSrc0 + rSrc1).

The saturate instruction modifier costs no additional instruction slots.

The _sat instruction modifier can be used with any arithmetic instruction (including macro-ops), except the frc and sincos instructions.

_sat cannot be used with texture addressing instructions texld* and texkill.

_sat cannot be used with instructions writing to output o# registers.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
_sat |  |  |  |  | x | x

© 2002 Microsoft Corporation. All rights reserved.


Masking (Vertex Shader)

A write mask controls which components of a destination register are written after an instruction is completed. An output write mask is allowed as long as the components are in the order of .rgba or .xyzw. That is, .rba and .xw are valid masks. Texture registers have one set of rules and non-texture registers have another set of rules.

Destination Register Masking

As shown in the following table, masking can be applied to the individual components of a destination register.

Component modifier | Description
r.{x}{y}{z}{w} | Destination mask

Any combination of components may be specified (including none) as long as x precedes y, y precedes z, and z precedes w.

The following output registers have restrictions for write mask:

Register Type | Required Write Mask
oFog | no explicit write mask allowed on a scalar register
oPts | no explicit write mask allowed on a scalar register
oPos | combined mask: .xyzw(which is the default)
oT# | combined mask: .x | .xy | .xyz | .xyzw (which is the default)

The following versions support masking.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
destination register masking | x | x | x | x | x | x

© 2002 Microsoft Corporation. All rights reserved.


Source Modifiers (Vertex Shader)

Source modifiers can be applied to modify the data read from a source register before the data is used by the instruction.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2, m3x3, m3x4, m4x3, m4x4.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.

© 2002 Microsoft Corporation. All rights reserved.


Swizzling (Vertex Shader)

Source swizzle allows individual component of a source register to take on the value of any of the four components of the same source register before the register is read for computation.

Source Swizzling

For example, the .zxxy swizzle means:

  • .x component will take on the value of .z component
  • .y component will take on the value of .x component
  • .z component will take on the value of .x component
  • .w component will take on the value of .y component

The components can appear in any order. If fewer than four components are specified, the last component is repeated. For example:

.xy  = .xyyy
.wzx = .wzxx
.z   = .zzzz

If no component is specified, no swizzling is applied.

Some instructions have restrictions for source swizzle. They are listed in the respected instruction reference pages.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
swizzling | x | x | x | x | x | x

Arbitrary Swizzle

Swizzles can be applied to source registers in an arbitrary order; that is, any source register can take any component mask, in any order.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
arbitrary swizzling | x | x | x | x | x | x

Replicate Swizzle

Replicate swizzle, is used to replicate or copy one component to another. This is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader 2_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - vs_2_0 contains a list of the available instructions.
  • Registers - vs_2_0 lists the different types of registers used by the vertex shader arithmetic logic unit (ALU).
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

Instruction Count

Shaders have restrictions for maximum instruction counts.

Each vertex shader can have up to 256 instructions stored.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - vs_2_0

This section contains reference information for the vertex shader version 2_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Flow control - These instructions add flow control capabilities such as loop...endloop, if...else...endif, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Flow control | New
abs | Absolute value | 1 |  | x |  |  | x
add | Add two vectors | 1 |  | x |  |  |
call | Call a subroutine | 2 |  |  |  | x | x
callnz | Call a subroutine if not zero | 3 |  |  |  | x | x
crs | Cross product | 2 |  | x |  |  | x
dcl_usage | Declare input vertex registers (see Registers - vs_2_0) | 0 | x |  |  |  |
def | Define a floating-point constant | 0 | x |  |  |  |
defb | Define a Boolean constant | 0 | x |  |  |  | x
defi | Define an integer constant | 0 | x |  |  |  | x
dp3 | Three-component dot product | 1 |  | x |  |  |
dp4 | Four-component dot product | 1 |  | x |  |  |
dst | Calculate a distance vector | 1 |  | x |  |  |
else | Begin an else block | 1 |  | x |  | x | x
endif | End an if...else block | 1 |  |  |  | x | x
endloop | End of a loop block | 2 |  |  |  | x | x
endrep | End of a repeat block | 2 |  |  |  | x | x
exp | Full precision 2x | 1 |  |  | x |  |
expp | Partial precision 2x | 1 |  |  | x |  | x
frc | Fractional component | 1 |  |  | x |  |
if | Begin an if block | 3 |  |  |  | x | x
label | Label | 0 |  |  |  | x | x
lit | Partial lighting calculation | 3 |  | x |  |  |
log | Full precision log2(x) | 1 |  |  | x |  |
logp | Partial precision log2(x) | 1 |  |  | x |  |
loop | Loop | 3 |  |  |  | x | x
lrp | Linear interpolation | 2 |  |  | x |  | x
m3x2 | 3x2 matrix multiply | 2 |  |  | x |  |
m3x3 | 3x3 matrix multiply | 3 |  |  | x |  |
m3x4 | 3x4 matrix multiply | 4 |  |  | x |  |
m4x3 | 4x3 matrix multiply | 3 |  |  | x |  |
m4x4 | 4x4 matrix multiply | 4 |  |  | x |  |
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  | x |  |  |
min | Minimum | 1 |  | x |  |  |
mov | Move | 1 |  | x |  |  |
mova | Move data from a floating point register to the address register (a0) | 1 |  | x |  |  | x
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize a 4-D vector | 3 |  |  | x |  | x
pow | xy | 3 |  |  | x |  | x
rcp | Reciprocal | 1 |  | x |  |  |
rep | Repeat | 3 |  |  |  | x | x
ret | End of either a subroutine or main | 1 |  |  |  | x | x
rsq | Reciprocal square root | 1 |  | x |  |  |
sge | Greater than or equal compare | 1 |  | x |  |  |
sgn | Sign | 3 |  |  | x |  | x
sincos | Sine and cosine | 8 |  |  | x |  | x
slt | Less than compare | 1 |  | x |  |  |
vs | Vertex shader version | 0 | x |  |  |  |

© 2002 Microsoft Corporation. All rights reserved.


Registers - vs_2_0

This section contains reference information for the input and output registers implemented by vertex shader version 2_0. Vector elements are designated as x, y, z, w (or the r, g, b, a equivalents).

Input Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Read port | Read / Instruction | Rel-Address | Defaults | Requires DCL
v# | Input Register | 16 | floating-point | 4-D vector | read | 1 | 3 | no | Partial(0001) | yes
r# | Temporary Register | 12 | floating-point | 4-D vector | write / read | 3 | 3 | no | none | no
c# | Constant Float Register | 256 (1) | floating-point | 4-D vector | define / read | 1 | 2 | a0 / aL | (0, 0, 0, 0) | no
i# | Constant Integer Register | 16 | integer | 4-D vector | define / use | 1 | 1 | no | (0, 0, 0, 0) | no
b# | Constant Boolean Register | 16 | boolean | scalar | define / use | 1 | 1 | no | FALSE | no
a0 | Address Register | 1 | integer | 4-D vector | write / use | 1 | 2 | no | none | no
aL | Loop Counter Register | 1 | integer | scalar | use | 1 | 2 | no | none | no

Where:

  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • The number of readports is the number of different registers (for each register type) that can be read in a single instruction. For example, a readport of two for a constant register means that all of these are legal since they use 2 or fewer unique constant registers:
    mad r0, c0, c0, c1
mad r0, c2, t1, c1
mad r0, c3, c3, c3

    But the following is illegal because it uses mnore than 2 unique constant registers:

    mad r0, c1, c2, c3

(1) 256 is the minimum c# register count required by vs_2_0. The D3DCAPS9.MaxVertexShaderConst cap contains the actual c# register count supported by the device.

Output Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Rel-Address | Default | Require DCL
oD# | Diffuse/Specular Register | (2) 2 | floating-point | 4-D vector | write | no | none | no
oFog | Fog Register | 1 | floating-point | scalar | write | no | none | no
oPos (3) | Position Register | 1 | floating-point | 4-D vector | write | no | none | no
oPts | Point Size Register | 1 | floating-point | scalar | write | no | none | no
oT# | Texture Coordinates Register | 8 | floating-point | 4-D vector | write | no | none | no

(2) oD0 = diffuse color; oD1 = specular color.

(3) All four components of oPos must be written.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader 2_0 Extended

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

Vertex shader version 2_x extends the feature set supported by vs_2_0. Each additional feature is represented by a corresponding cap in the D3DCAPS9 structure within the VS20Caps member. To use any of the enhanced features represented by these caps, the vertex shader version must be specified as vs_2_x.

  • Instructions - vs_2_x contains a list of the available instructions.
  • Registers - vs_2_x lists the different types of registers used by the vertex shader ALU.
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied, or written.

New Features

New features are as follows:

Dynamic Flow Control

D3DCAPS9.VS20Caps.DynamicFlowControlDepth represents the nesting depth of dynamic flow control instructions: if, if_comp, if_pred, break, and break_comp. The value is equal to the nesting depth of the if_comp block. The range of values for this cap is 0 to 24. If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

This cap represents the number of temporary registers (r#) supported by the device. The range of values for this cap is 12 to 32.

Static Flow Control Nesting Depth

D3DCAPS9.VS20Caps.StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop/rep and call/callnz. The range of values for this cap is 1 to 4. loop/rep instructions can be nested up to StaticFlowControlDepth deep. Independently, call/callnz instructions can be nested up to StaticFlowControlDepth deep.

Predication

If the D3DVS20CAPS_PREDICATION flag is set on D3DCAPS9.VS20Caps, the device supports predication.

Instruction Count

Each vertex shader can have up to 256 instructions stored. The number of instructions run can be much higher because of the looping support. The MaxVShaderInstructionsExecuted cap in D3DCAPS9 should be at least 2^16.

The total number of instructions run should be clamped to the device driver render state D3DRS_MAXVERTEXSHADERINST. The legal values for this render state are numbers that are powers of 2; if any other integer is set, the next nearest pow2 number is assumed. This defaults to D3DINFINITEINSTRUCTIONS.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - vs_2_x

This section contains reference information for the vertex shader version 2_x instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Flow control - These instructions add flow control capabilities such as loop...endloop, if...else...endif, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Flow control | New
abs | Absolute value | 1 |  |  | x |  |
add | Add two vectors | 1 |  | x |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  | x | x
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  | x | x
break pred | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  | x | x
call | Call a subroutine | 2 |  |  |  | x |
callnz | Call a subroutine if a boolean register is not zero | 3 |  |  |  | x | x
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x | x
crs | Cross product | 2 |  |  | x |  |
dcl_usage | Declare input vertex registers (see Registers - vs_2_x) | 0 | x |  |  |  |
def | Define constants | 0 | x |  |  |  |
defb | Define a Boolean constant | 0 | x |  |  |  |
defi | Define an integer constant | 0 | x |  |  |  |
dp3 | Three-component dot product | 1 |  | x |  |  |
dp4 | Four-component dot product | 1 |  | x |  |  |
dst | Calculate the distance vector | 1 |  | x |  |  |
else | Begin an else block | 1 |  |  |  | x |
endif | End an if...else block | 1 |  |  |  | x |
endloop | End of a loop block | 2 |  |  |  | x |
endrep | End of a repeat block | 2 |  |  |  | x |
exp | Full precision 2x | 1 |  |  | x |  |
expp | Partial precision 2x | 1 |  |  | x |  |
frc | Fractional component | 1 |  |  | x |  |
if | Begin an if block (using a boolean condition) | 3 |  |  |  | x |
if comp | Begin an if block, with a comparison | 3 |  |  |  | x | x
if pred | Begin an if block with a predicate condition | 3 |  |  |  | x | x
label | Label | 0 |  |  |  | x |
lit | Partial lighting calculation | 3 |  | x |  |  |
log | Full precision log2(x) | 1 |  |  | x |  |
logp | Partial precision log2(x) | 1 |  |  | x |  |
loop | Loop | 3 |  |  |  | x |
lrp | Linear interpolation | 2 |  |  | x |  |
m3x2 | 3x2 multiply | 2 |  |  | x |  |
m3x3 | 3x3 multiply | 3 |  |  | x |  |
m3x4 | 3x4 multiply | 4 |  |  | x |  |
m4x3 | 4x3 multiply | 3 |  |  | x |  |
m4x4 | 4x4 multiply | 4 |  |  | x |  |
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  | x |  |  |
min | Minimum | 1 |  | x |  |  |
mov | Move | 1 |  | x |  |  |
mova | Move data from a floating-point register to the address register (a0) | 1 |  | x |  |  |
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize a 4-D vector | 3 |  |  | x |  |
pow | xy | 3 |  |  | x |  |
rcp | Reciprocal | 1 |  | x |  |  |
rep | Repeat | 3 |  |  |  | x |
ret | End of either a subroutine or main | 1 |  |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |  |
setp | Set the predicate register | 1 |  |  |  | x | x
sge | Greater than or equal compare | 1 |  | x |  |  |
sgn | Sign | 3 |  |  | x |  |
sincos | Sine and cosine | 8 |  |  | x |  |
slt | Less than compare | 1 |  | x |  |  |
vs | Version | 0 | x |  |  |  |

© 2002 Microsoft Corporation. All rights reserved.


Registers - vs_2_x

This section contains reference information for the input and output registers implemented by vertex shader version 2_x. Vector elements are designated as x, y, z, w (or the r, g, b, a equivalents).

Input Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Read port | Read / Instruction | Rel-Address | Defaults | Requires DCL
v# | Input Register | 16 | floating-point | 4-D vector | read | 1 | 3 | no | Partial(0001) | yes
r# | Temporary Register | 12 (1) | floating-point | 4-D vector | read / write | 3 | 3 | no | none | no
c# | Constant Float Register | 256 (2) | floating-point | 4-D vector | define / read | 1 | 2 | a0 / aL | (0, 0, 0, 0) | no
i# | Constant Integer Register | 16 | integer | 4-D vector | define / use | 1 | 1 | no | (0, 0, 0, 0) | no
b# | Constant Boolean Register | 16 | boolean | scalar | define / use | 1 | 1 | no | FALSE | no
a0 | Address Register | 1 | integer | 4-D vector | write / use | 1 | 2 | no | none | no
aL | Loop Counter Register | 1 | integer | scalar | use | 1 | 2 | no | none | no
p0 | Predicate | 1 | boolean | 4-D vector | write / use | 1 | 1 | no | none | no

Where:

  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • The number of readports is the number of different registers (for each register type) that can be read in a single instruction. For example, a readport of two for a constant register means that all of these are legal since they use 2 or fewer unique constant registers:
    mad r0, c0, c0, c1
mad r0, c2, t1, c1
mad r0, c3, c3, c3

    But the following is illegal because it uses mnore than 2 unique constant registers:

    mad r0, c1, c2, c3

(1) - 12 is the minimum r# register counted required by vs_2_x. The D3DCAPS9.VS20Caps.NumTemps cap contains the actual r# register count supported by the device. See D3DCAPS9.

(2) - 256 is the minimum c# register count required by vs_2_x. The MaxVertexShaderConst cap contains the actual c# register count supported by the device. See D3DCAPS9.

Output Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Rel-Address | Default | Require DCL
oD# | Diffuse/Specular Register | 2 (3) | floating-point | 4-D vector | write | no | none | no
oFog | Fog Register | 1 | floating-point | scalar | write | no | none | no
oPos (4) | Position Register | 1 | floating-point | 4-D vector | write | no | none | no
oPts | Point Size Register | 1 | floating-point | scalar | write | no | none | no
oT# | Texture Coordinates Register | 8 | floating-point | 4-D vector | write | no | none | no

(3) oD0 = diffuse color; oD1 = specular color.

(4) All four components of oPos must be written.

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader 3_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - vs_3_0 contains a list of the available instructions.
  • Registers - vs_3_0 lists the different types of registers used by the vertex shader arithmetic logic unit (ALU).
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

New Features

New features include the following:

Indexing Registers

In the earlier shader models, only the constant register bank could be indexed. In this model, the following register banks can be indexed, using the loop counter register (aL).

  • Input register (v#)
  • Output register (o#)

Vertex Textures

This shader model supports texture lookup in the vertex shader using texldl. The vertex engine has four texture sampler stages (distinct from the displacement map sampler and the texture samplers in the pixel engine) that can be used to sample textures set at those stages. See Vertex Textures.

Vertex Stream Frequency

This feature allows a subset of the input registers to be initialized at a rate different from once per vertex. See Vertex Stream Frequency.

Shader Output

Similar to vs_2_0, the output of the shader can vary with static flow control. Be careful with dynamic branching as this can cause shader outputs to vary per vertex. This will produce unpredictable results on different hardware.

Dynamic Flow Control

Dynamic flow control instructions are supported. The depth values allowed is a maximum of 24.

Static Flow Control Nesting Depth

Static flow control instructions are supported. The depth value allowed is a maximum of 4.

Instruction Count

Each vertex shader is allowed anywhere from 512 up to the number of slots in the MaxVertexShader30InstructionSlots member of D3DCAPS9. The number of instructions run can be much higher because of the looping support. The MaxVShaderInstructionsExecuted cap in D3DCAPS9 should be at least 2^16.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - vs_3_0

This section contains reference information for the vertex shader version 3_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Flow control - These instructions add flow control such as loops, repeats, and if...else...endif comparisons.
  • Texture - These instructions support texture address lookup.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Texture | Flow control | New
abs | Absolute value | 1 |  |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  |  | x | x
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  |  | x | x
break pred | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  |  | x | x
call | Call a subroutine | 2 |  |  |  |  | x | x
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  |  | x | x
crs | Cross product | 2 |  |  | x |  |  |
dcl_usage | Declare input vertex registers (see Registers - vs_3_0) | 0 | x |  |  |  |  |
dcl_textureType | Declare the texture dimension for a sampler | 0 | x |  |  |  |  | x
def | Define constants | 0 | x |  |  |  |  |
defb | Declare a Boolean constant | 0 | x |  |  |  |  |
defi | Declare an integer constant | 0 | x |  |  |  |  |
dp3 | Three-component dot product | 1 |  | x |  |  |  |
dp4 | Three-component dot product | 1 |  | x |  |  |  |
dst | Distance | 1 |  | x |  |  |  |
else | Begin an else block | 1 |  |  |  |  | x |
endif | End an if...else block | 1 |  |  |  |  | x |
endloop | End of a loop block | 2 |  |  |  |  | x |
endrep | End of a repeat block | 2 |  |  |  |  | x |
exp | Full precision 2x | 1 |  |  | x |  |  |
expp | Partial precision 2x | 1 |  |  | x |  |  |
frc | Fractional component | 1 |  |  | x |  |  |
if | Begin an if block (using a boolean condition) | 3 |  |  |  |  | x | x
if comp | Begin an if block, with a comparison | 3 |  |  |  |  | x | x
if pred | Begin an if block with a predicate condition | 3 |  |  |  |  | x | x
label | Label | 0 |  |  |  |  | x |
lit | Calculate lighting | 3 |  | x |  |  |  |
log | Full precision log2(x) | 1 |  |  | x |  |  |
logp | Partial precision log2(x) | 1 |  |  | x |  |  |
loop | Loop | 3 |  |  |  |  | x |
lrp | Linear interpolation | 2 |  |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |  |
max | Maximum | 1 |  | x |  |  |  |
min | Minimum | 1 |  | x |  |  |  |
mov | Move | 1 |  | x |  |  |  |
mova | Move data from a floating point register to an integer register | 1 |  | x |  |  |  |
mul | Multiply | 1 |  | x |  |  |  |
nop | No operation | 1 |  | x |  |  |  |
nrm | Normalize | 3 |  |  | x |  |  |
pow | 2x | 3 |  |  | x |  |  |
rcp | Reciprocal | 1 |  | x |  |  |  |
rep | Repeat | 3 |  |  |  |  | x |
ret | End of a subroutine | 1 |  |  |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |  |  |
setp | Set the predicate register | 1 |  |  |  |  | x |
sge | Greater than or equal compare | 1 |  | x |  |  |  |
sgn | Sign | 3 |  |  | x |  |  |
sincos | Sine and cosine | 8 |  |  | x |  |  |
slt | Less than compare | 1 |  | x |  |  |  |
texldl | Texture load with user-adjustable level of detail (LOD) | 2+3CUBE |  |  |  | x |  | x
vs | Version | 0 | x |  |  |  |  |

© 2002 Microsoft Corporation. All rights reserved.


Registers - vs_3_0

One additional register is introduced in this version. This section contains reference information for the input and output registers implemented by vertex shader version 3_0.

Input Registers

Name | Register type | Count | Data type | Dimension | I/O permissions | Read port | Read / Instruction | Rel-Address | Defaults | Requires DCL
v# | Input Register | 16 | floating-point | 4-D vector | read | 1 | 3 | no | Partial(0001) | yes
r# | Temporary Register | 12 (1) | floating-point | 4-D vector | read / write | 3 | 3 | no | none | no
c# | Constant Float Register | 256 (2) | floating-point | 4-D vector | define / read | 1 | 2 | a0 / aL | (0, 0, 0, 0) | no
i# | Constant Integer Register | 16 | integer | 4-D vector | define / use | 1 | 1 | no | (0, 0, 0, 0) | no
b# | Constant Boolean Register | 16 | boolean | scalar | define / use | 1 | 1 | no | FALSE | no
a0 | Address Register | 1 | integer | 4-D vector | write / use | 1 | 2 | no | none | no
aL | Loop Counter Register | 1 | integer | scalar | use | 1 | 2 | no | none | no
p0 | Predicate | 1 | boolean | 4-D vector | write / use | 1 | 1 | no | none | no
s# | Sampler Register | 4 | R | 1 | 1 | 1 | No | None | Yes | Yes

Where:

  • r is read, w is write, u is used.
  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • The number of readports is the number of different registers (for each register type) that can be read in a single instruction. For example, a readport of two for a constant register means that all of these are legal since they use 2 or fewer unique constant registers:
    mad r0, c0, c0, c1
mad r0, c2, t1, c1
mad r0, c3, c3, c3

    But the following is illegal because it uses mnore than 2 unique constant registers:

    mad r0, c1, c2, c3

(1) - 12 is the minimum r# register counted required by vs_2_x. The D3DCAPS9.VS20Caps.NumTemps cap contains the actual r# register count supported by the device. See D3DCAPS9.

(2) - 256 is the minimum c# register count required by vs_2_x. The MaxVertexShaderConst cap contains the actual c# register count supported by the device. See D3DCAPS9.

Register Defaults

It is unwise to use uninitialized address or temporary registers. All other defaults are specified in the table above.

Output Registers

Output registers have been collapsed into 12 o# (output) registers. These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, etc.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL | New
Output Register - on | 12 | W | N/A | N/A | 4 | aL only | None | Yes | Yes

Output declarations are introduced, whereby semantics are assigned to each register. Old oPos and oPts are replaced by declaring an o register with a position or pointsize semantic, further described below.

  • All four components of one of the 12 output registers must be declared as a position register (for example: dcl_position0 v#).
  • Ten other registers are also 4-component registers (xyzw). The remaining register can contain scalar pointsize data (for example: dcl_psize o#).

See dcl_usage for examples declaring output registers.

Indexing Registers Extended

In the earlier shader models, only the constant register bank could be indexed. In this model, the following register banks can be indexed using the loop counter register (aL).

  • Input registers (vn)
  • Output registers (on)

© 2002 Microsoft Corporation. All rights reserved.


Vertex Textures

This shader model supports texture lookup in the vertex shader using texldl. The vertex engine contains four texture sampler stages, named D3DVERTEXTEXTURESAMPLER, D3DVERTEXTEXTURESAMPLER+1, D3DVERTEXTEXTURESAMPLER+2, and D3DVERTEXTEXTURESAMPLER+3 (these are distinct from the displacement map sampler and texture samplers in the pixel engine).

To sample textures set at those four stages, you can use the vertex engine and program the stages with IDirect3D9::CheckDeviceFormat. Set textures at those stages using IDirect3DDevice9::SetTexture, with the stage index D3DVERTEXTEXTURESAMPLER through D3DVERTEXTEXTURESAMPLER+3. A new register has been introduced in the vertex shader, the sampler register (like in ps_2_0), which represents the vertex texture sampler. This register needs to be defined in the shader before using it.

An application can query if a format is supported as a vertex texture by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE.

Note This is a query flag so it is not accepted in the Create xxx function. A vertex texture created in POOL_DEFAULT can be set as a pixel texture and vice versa. However, to use the software vertex processing, the vertex texture must be created in the POOL_SCRATCH (no matter if it is a mixed-mode device or a software vertex processing device).

The functionality is identical to the pixel textures, except for the following:

  • Anisotropic texture filtering is not supported, hence D3DSAMP_MAXANISOTROPY is ignored and D3DTEXF_ANISOTROPIC cannot be set for MAGFILTER or MINFILTER, for these stages.
  • Rate of change information is not available, hence the application has to compute the level of detail (LOD) and provide that information as a parameter to texldl.

Restrictions include:

  • As in pixel shaders, if multielement textures are supported, D3DSAMP_ELEMENTINDEX is used to figure out which element to sample from.
  • The state D3DSAMP_DMAPOFFSET is ignored for these stages.
  • Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE to query a texture to see if it can be used as a vertex texture.
  • A new D3DCAPS9 field, VertexTextureFilterCaps, indicates what kind of filters are allowed at the vertex texture samplers. D3DPTFILTERCAPS_MINFANISOTROPIC and D3DPTFILTERCAPS_MAGFANISOTROPIC are disallowed.

Sampling Stage Registers

A sampling stage register identifies a sampling unit that can be used in texture load statements. A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided in IDirect3DDevice9::SetSamplerState.

Each sampler uniquely identifies a single texture surface that is set to the corresponding sampler using IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because vs_3_0 supports four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler register might appear only as an argument in the texture load statement: texldl.

In vs_3_0, if you use a sampler, it must be declared at the beginning of the shader program, using the dcl_textureType (as in ps_2_0).

Software Processing

This feature will be supported in software vertex processing. The specific filter types supported can be checked by calling IDirect3DDevice9::GetDeviceCaps and checking the VertexTextureFilterCaps member of D3DCAPS9. All published texture formats will be supported as vertex textures in software vertex processing.

Applications can check if a particular texture format is supported in the software vertex processing mode by calling IDirect3D9::CheckDeviceFormat and providing (D3DUSAGE_QUERY_VERTEXTEXTURE | D3DUSAGE_SOFTWAREPROCESSING) as usage. All formats are supported for software vertex processing. POOL_SCRATCH is required for software vertex processing.

API Changes

// New define
#define D3DVERTEXTEXTURESAMPLER0 (D3DDMAPSAMPLER+1)
#define D3DVERTEXTEXTURESAMPLER1 (D3DDMAPSAMPLER+2)
#define D3DVERTEXTEXTURESAMPLER2 (D3DDMAPSAMPLER+3)
#define D3DVERTEXTEXTURESAMPLER3 (D3DDMAPSAMPLER+4)

// New usage
#define D3DUSAGE_QUERY_VERTEXTEXTURE  (0x00100000L)

// New caps field in D3DCAPS9
DWORD VertexTextureFilterCaps;

© 2002 Microsoft Corporation. All rights reserved.


Vertex Stream Frequency

In the older shader models, including the fixed function, the vertex shader was invoked once per vertex. With every invocation, the input registers were initialized with unique vertex elements from the vertex streams.

This feature allows a subset of the input registers to be initialized at a less frequent rate. This feature is supported by all devices that support vs_3_0.

The application sets a frequency for a given stream. All elements in that stream are affected by this value. Frequency is "after how many vertices is the data from that stream fetched into the vertex processing machine." That is, if it is 2, the data from that stream is fetched into the Vn registers every two vertices.

The vertex offset (in the vertex buffer) is computed using the following formula.

VertexOffset = VertexIndex / Divider * StreamStride + StreamOffset

The division is an integer division.

This state is recorded in state blocks as vertex state.

Stream frequency is ignored for indexed primitives and if the current vertex shader set is less than version 3_0 (including fixed function).

API Changes

Two new methods have been introduced.

    HRESULT IDirect3DDevice9::SetStreamSourceFreq(
        UINT StreamIndex, UINT Frequency );

    HRESULT IDirect3DDevice9::GetStreamSourceFreq(
                UINT StreamIndex, UINT* Frequency );

The frequency range is:

0 < frequency <= 216 - 1

© 2002 Microsoft Corporation. All rights reserved.


Vertex Shader Differences

These are the differences between the vertex shader versions.

Version | Maximum number of instructions
1_1 | 128
2_0 | 256
2_0 Extended | 256. The number of instructions that run can be much higher because of looping.
3_0 | 512 minimum, and up to the number of slots in the D3DCAPS9.MaxVertexShader30InstructionSlots. See D3DCAPS9.

Version 3_0

New features:

  • Static flow control nesting depth
  • Dynamic flow control instructions - break, breakc, ifc
  • Predication - setp instruction, p# register
  • Number of temporary registers
  • Indexing registers
  • Vertex textures - texld texture address instruction
  • Vertex stream frequency

Version 2_0 Extended

New features (with a cap set):

  • Dynamic flow control instructions - break, breakc, ifc
  • Predication - setp instruction, p# register
  • Static flow control nesting depth
  • Number of temporary registers

Version 2_0

New instructions:

  • Setup instructions - defb, defi
  • Arithmetic instructions - mova
  • Macros - abs, crs, expp, logp, lrp, nrm, pow, sincos, slt
  • Static flow control instructions - call, callnz, else, end, endif, endloop, endrep, if, label, loop, rep, ret

New registers - constant float, constant integer, constant Boolean, loop counter

Version 1_x

New instructions:

  • Setup instructions - dcl, def, vs
  • Arithmetic instructions - add, dp3, dp4, dst, lit, mad, max, min, mov, mul, nop, rcp, rsq, sge, slt, sub
  • Macros - exp, frc, log, m3x2, m3x3, m3x4, m4x3, m4x4

© 2002 Microsoft Corporation. All rights reserved.


Mapping Vertex Declarations

The vertex declaration programs the vertex data direct memory access (DMA) and programs the tessellator engine of the graphics pipeline. It expresses the data layout and the tessellator operations concisely. To address the complexity and extensibility of declarations, a new format for expressing vertex streams has been introduced.

Vertex Declarations

Vertex declarations are no longer expressed as streams of DWORDs; they are expressed as a an array of D3DVERTEXELEMENT9 structures. Each element of the array describes one vertex element.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader 1_X

The pixel shader assembler is made up of a set of instructions that operate on pixel data contained in registers. Operations are expressed as instructions comprised of an operator and one or more operands. Instructions use registers to transfer data in and out of the pixel shader arithmetic logic unit (ALU). Registers can also be used by some instructions to hold temporary results.

Architecture

Architecture contains a block diagram of the pixel shader ALU and the shader registers.

Instructions

There are two main categories of pixel shader instructions: arithmetic instructions and texture addressing instructions. Arithmetic instructions modify color data. Texture addressing operations process texture coordinate data and in most cases, sample a texture. Pixel shader instructions are run on a per-pixel basis, that is, they have no knowledge of other pixels in the pipeline.

Texture addressing instructions each consume one slot, but arithmetic instructions can be paired to enable both color components (RGB) and an alpha component instruction in a single slot.

Instructions - ps_1_X contains a list of the available instructions.

When multisampling is enabled, pixel shaders only get run once per pixel, not once for every subpixel. Multisampling only increases the resolution of polygon edges, as well as depth and stencil tests. For example, if 3x3 multisampling is enabled, and a triangle being rasterized is found to cover five of the nine subpixels for a particular pixel, the pixel shader gets run once and the same color result is applied to all five subpixels.

Registers

Registers - ps_1_X lists the different registers used by the shader ALU.

Modifiers

Modifiers - ps_1_X can be used to change the functionality of an instruction, or the data read from or written to a register.

Microsoft® DirectX® 9.0 requires intermediate computations to maintain at least 8-bit precision for all surface formats. Both higher precision (12-bit) for in-stage math, and saturation to 8-bits between texture stages are recommended. No modifiable rounding modes or exceptions are supported. Multiplication should be supported with a round-to-nearest precision to keep precision loss to a minimum.

© 2002 Microsoft Corporation. All rights reserved.


Architecture

  • Pixel Shader ALU. Contains a flow diagram showing what happens to register data as it is processed by the pixel shader processor.
  • Pixel Shader Texture Addressing. Contains block diagrams to help visualize how texture data is used by the pixel shader processor.
  • Counting Instructions. Details the limits on the number of instructions that can be used in a programmable shader.
  • Instruction Flow. Highlights the order of the different types of instructions in pixel shaders.
  • Instruction Pairing. Describes how some instructions can be paired to minimize execution time.
  • Order of Operations. Shows the order or operations for instructions that use Register Modifiers, Source Register Selectors, and Register Write Masks.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - ps_1_X

This section contains reference information for the pixel shader version 1_X instructions.

There are several types of pixel shader instructions, as shown in the following table.

Instruction Set

Version |  | Instruction slots | 1_1 | 1_2 | 1_3 | 1_4
ps | Version number | 0 | x | x | x | x
Constant instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
def | Define constants | 0 | x | x | x | x
Phase instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
phase | Transition between phase 1 and phase 2 | 0 |  |  |  | x
Arithmetic instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
add | Add two vectors | 1 | x | x | x | x
bem | Apply a fake bump environment-map transform | 2 |  |  |  | x
cmp | Compare source to 0 | 1 |  | x | x | x
cnd | Compare source to 0.5 | 1 | x | x | x | x
dp3 | Three-component dot product | 1 | x | x | x | x
dp4 | Four-component dot product | 1 |  | x | x | x
lrp | Linear interpolate | 1 | x | x | x | x
mad | Multiply and add | 1 | x | x | x | x
mov | Move | 1 | x | x | x | x
mul | Multiply | 1 | x | x | x | x
nop | No operation | 0 | x | x | x | x
sub | Subtract | 1 | x | x | x | x
Texture instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
tex | Sample a texture | 1 | x | x | x |
texbem | Apply a fake bump environment-map transform | 1 | x | x | x |
texbeml | Apply a fake bump environment-map transform with luminance correction | 1+1 | x | x | x |
texcoord | Interpret texture coordinate data as color data | 1 | x | x | x |
texcrd | Copy texture coordinate data as color data | 1 |  |  |  | x
texdepth | Calculate depth values | 1 |  |  |  | x
texdp3 | Three-component dot product between texture data and the texture coordinates | 1 |  | x | x |
texdp3tex | Three-component dot product and 1-D texture lookup | 1 |  | x | x |
texkill | Cancels rendering of pixels based on a comparison | 1 | x | x | x | x
texld | Sample a texture | 1 |  |  |  | x
texm3x2depth | Calculate per-pixel depth values | 1 |  |  | x |
texm3x2pad | First row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x2tex | Final row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x3 | 3x3 matrix multiply | 1 |  | x | x |
texm3x3pad | First or second row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3spec | Final row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3tex | Texture look up using a 3x3 matrix multiply | 1 | x | x | x |
texm3x3vspec | Texture look up using a 3x3 matrix multiply, with non-constant eye-ray vector | 1 | x | x | x |
texreg2ar | Sample a texture using the alpha and red components | 1 | x | x | x |
texreg2gb | Sample a texture using the green and blue components | 1 | x | x | x |
texreg2rgb | Sample a texture using the red, green and blue components | 1 |  | x | x |

Where 1 + 1 counts as 1 arithmetic instruction + 1 texture instruction.

© 2002 Microsoft Corporation. All rights reserved.


Registers - ps_1_X

Pixel shaders depend on registers to get vertex data, to output pixel data to the rasterizer, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 1_X.

Registers hold data for use by the pixel shader. Registers are fully described in the following sections.

  • Register Types describes the four types of registers available and their purposes.
  • Read Port Limit details the restrictions on using multiple registers in a single instruction.
  • Read-only, Read/Write describes which registers can be used for reading, writing, or both.
  • Range details the range of the component data.

Register Types

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
cn | Constant register | 8 | 8 | 8 | 8
rn | Temporary register | 2 | 2 | 2 | 6
tn | Texture register | 4 | 4 | 4 | 6
vn | Color register | 2 | 2 | 2 | 2 in phase 2
  • Constant registers contain constant data organized in four fixed-point values. Data can be loaded into a constant register using SetPixelShaderConstant or it can be defined using def. Constant registers are not usable by texture address instructions. The only exception is the texm3x3spec instruction, which uses a constant register to supply an eye-ray vector.
    Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
    Constant Registers | x | x | x | x | x | x | x | x | x
  • Temporary registers are used to store intermediate results, as four fixed-point values. r0 additionally serves as the pixel shader output. The value in r0 at the end of the shader is the pixel color for the shader.

    Shader pre-processing will fail CreatePixelShader on any shader that attempts to read from a temporary register that has not been written by a previous instruction. D3DXAssembleShader will fail similarly, assuming validation is enabled (do not use D3DXASM_SKIPVALIDATION).

    Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
    Temporary Registers | x | x | x | x | x | x | x | x | x
  • Texture registers

    For pixel shader version 1_1 to 1_3, texture registers contain texture data, organized in four fixed-point values. Texture data is loaded into a texture register when a texture is sampled. Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes. The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. There is a default one-to-one association between texture stage number and texture coordinate declaration order. By default, the first set of texture coordinates defined in the vertex format is associated with texture stage 0.

    For these pixel shader versions, texture registers behave just like temporary registers when used by arithmetic instructions.

    For pixel shader version 1_4, texture registers (t#) contain read-only texture coordinate data. This means that the texture coordinate set and the texture stage number are independent from each other. The texture stage number (from which to sample a texture) is determined by the destination register number (r0 to r5). For the texld instruction, the texture coordinate set is determined by the source register (t0 to t5), so the texture coordinate set can be mapped to any texture stage. In addition, the source register (specifying texture coordinates) for texld can also be a temporary register (r#), in which case the contents of the temporary register are used as texture coordinates.

    For this pixel shader version, texture registers contain texture coordinate data and are also available to texture addressing instructions as source parameters.

    Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
    Texture Registers | x | x | x | x | x | x | x | x | x
  • Color registers contain per-pixel color values. The values are obtained by per-pixel iteration of the diffuse and specular color values in the vertex data. Color registers store data in four fixed-point values. For pixel shader version 1_4 shaders, color registers are available only during the second phase.

    If the shade mode is set to D3DSHADE_FLAT, the application iteration of both vertex colors (diffuse and specular) is disabled. Regardless of the shade mode, fog will still be iterated by the pipeline if pixel fog is enabled. Keep in mind that fog is applied later in the pipeline than the pixelshader.

    It is common to load the v0 register with the vertex diffuse color data. It is also common to load the v1 register with the vertex specular color data.

    Input color data values are clamped (saturated) to the range 0 through 1 because this is the valid input range for color registers in the pixel shader.

    Pixel shaders have read only access to color registers. The contents of these registers are iterated values, but iteration is performed at much lower precision than texture coordinates.

    Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
    Color Registers | x | x | x | x | x | x | x | x | x

Read Port Limit

The read port limit specifies the number of different registers of each register type that can be used as a source register in a single instruction.

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
cn | Constant register | 2 | 2 | 2 | 2
rn | Temporary register | 2 | 2 | 2 | 3
tn | Texture register | 2 | 3 | 3 | 1
vn | Color register | 2 | 2 | 2 | 2 in phase 2

For example, the color registers for almost all versions have a read port limit of two. This means that a single instruction can use a maximum of two different color registers (v0 and v1 for instance) as source registers. This example shows two color registers being used in the same instruction.

Read-only, Read/Write

The register types are identified according to read-only (RO) capability or read/write (RW) capability in the following table. Read-only registers can be used only as source registers in an instruction; they can never be used as a destination register.

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
cn | Constant register | RO | RO | RO | RO
rn | Temporary register | RW | RW | RW | RW
tn | Texture register | See following note | RW | RW | RW
vn | Color register | RO | RO | RO | RO

Registers that are RW capable can be used to store intermediate results. This includes the temporary registers and texture registers for some of the shader versions.

Note
  • For pixel shader version 1_4, texture registers are RO for texture addressing instructions, and texture registers can be neither read from nor written to by arithmetic instructions. Also, because texture registers have become texture coordinate registers, having RO access is not a regression of previous functionality.

Range

The range is the maximum and minimum register data value. The ranges vary based on the type of register. The ranges for some of the registers can be queried from the device caps using GetDeviceCaps.

Name | Type | Range | Versions
cn | Constant register | -1 to +1 | All versions
rn | Temporary register | - MaxPixelShaderValue to + MaxPixelShaderValue | All versions
tn | Texture register | - MaxPixelShaderValue to + MaxPixelShaderValue | 1_1 to 1_3
tn | Texture register | - MaxTextureRepeat to + MaxTextureRepeat | 1_4
vn | Color register |  | 1_4

Early pixel shader hardware represents data in registers using a fixed-point number. This limits precision to a maximum of approximately eight bits for the fractional part of a number. Keep this in mind when designing a shader.

For pixel shader version 1_1 to 1_3, MaxTextureRepeat must be a minimum of one. For 1_4, MaxTextureRepeat must be a minimum of eight.

© 2002 Microsoft Corporation. All rights reserved.


Modifiers - ps_1_X

Modifiers are used to modify instructions, source registers, and destination registers. This section contains reference information for the modifiers implemented by pixel shader version 1_X.

  • Instruction Modifiers
  • Register Modifiers
  • Source Register Selectors
  • Register Write Masks

Pixel Shader Version 1_4

Pixel shader version 1_4 includes two new instructions, texld and texcrd, which contain custom register modifier functionality. These instructions support different register modifiers, register selectors, and register write masks. For more information, see Texture Register Modifiers.

Modifiers - ps_1_X may not be used with constant registers in pixel shader version 1_4.

© 2002 Microsoft Corporation. All rights reserved.


Instruction Modifiers

Use instruction modifiers to change the output of an instruction. For instance, use them to multiply or divide the result by a factor of two, or to clamp the result between zero and one. Instruction modifiers are applied after the instruction runs but before writing the result to the destination register.

A list of the modifiers is shown below.

Modifier | Description | Syntax | Version
 |  |  | 1_1 | 1_2 | 1_3 | 1_4
_x2 | Multiply by 2 | register_x2 | X | X | X | X
_x4 | Multiply by 4 | register_x4 | X | X | X | X
_x8 | Multiply by 8 | register_x8 |  |  |  | X
_d2 | Divide by 2 | register_d2 | X | X | X | X
_d4 | Divide by 4 | register_d4 |  |  |  | X
_d8 | Divide by 8 | register_d8 |  |  |  | X
_sat | Saturate (clamp from 0 and 1) | register_sat | X | X | X | X
  • The multiply modifier multiplies the register data by a power of two after it is read. This is the same as a shift left.
  • The divide modifier divides the register data by a power of two after it is read. This is the same as a shift right.
  • The saturate modifier clamps the range of register values from zero to one.

Instruction modifiers can be used on arithmetic instructions. They may not be used on texture address instructions.

Multiply modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and multiplies the result by two.

add_x2 dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is then multiplied by two, and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1

Divide modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and divides the result by two.

add_d2 dest, src0, src1

Saturate modifier

For arithmetic instructions, the saturation modifier clamps the result of this instruction into the range 0.0 to 1.0 for each component. The following example shows how to use this instruction modifier.

dp3_sat r0, t0_bx2, v0_bx2    ; t0 is bump, v0 is light direction

This operation occurs after any multiply or divide instruction modifier. _sat is most often used to clamp dot product results. However, it also enables consistent emulation of multipass methods where the frame buffer is always in the range 0 to 1, and of Microsoft® DirectX® 6.0 and 7.0 multitexture syntax, in which saturation is defined to occur at every stage.

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1), and clamps the result into the range 0.0 to 1.0 for each component.

add_sat dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is multiplied by two and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1

© 2002 Microsoft Corporation. All rights reserved.


Source Register Selectors

This modifier replicates a single channel of a source-register argument to all channels.

Syntax

source register.channel

Channel | Syntax | Version
 |  | 1_1 | 1_2 | 1_3 | 1_4
Red replicate | source register.r |  |  |  | X
Green replicate | source register.g |  |  |  | X
Blue replicate | source register.b | X | X | X | X
Alpha replicate | source register.a | X | X | X | X

Register

Source register. For more about register types, see Registers - ps_1_X.

In version 1_1, 1_2, and 1_3, blue replicate is available only on the source register of arithmetic instruction, which uses alpha Register Write Masks.

Remarks

Source register selectors are applied before any Register Modifiers and before the instruction runs.

Copying the contents of a channel into one or more other channels is commonly referred to as "swizzling."

These selectors are valid on source registers for arithmetic instructions. The four selectors operate on different channels.

An alternate syntax for the r,g,b,a channels is x,y,z,w.

Source selectors and source modifiers may be combined freely. In this example, register r0 uses the invert, bias, and signed scaling modifier, as well as the green selector. The contents of the source register are unaffected; the modifier modifies only the data read.

-r0_bx2.g

To understand the order of the execution of these modifiers and selectors, see Order of Operations.

This operator can be used in conjunction with the Invert or Negate operators.

Alpha replicate functionality is analogous to the D3DTA_ALPHAREPLICATE flag in the Microsoft® DirectX® 6.0 and 7.0 multitexture syntax.

These examples illustrate each of the four selectors.

// Replicate the red color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.r    // the result is r1.rgba = r1.r

// Replicate the green color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.g    // the result is r1.rgba = r1.g

// Replicate the blue color channel to the all channels before
// doing the multiply.
mul r0, r0, r1.b    // the result is r1.rgba = r1.b

// For ps 1_1, 1_2, 1_3, the blue replicate example
// would require a destination write mask.
mul r0.a, r0, r1.b

// alpha replicate
mul r0, r0, r1.a    ; Replicate the alpha color channel to all channels.

alpha write mask

The alpha write mask is also referred to as the scalar write mask, because it uses the scalar pipeline.

add r0.a, t1, v1

So this instruction effectively puts the sum of the alpha component of t1 and the alpha component of v1 into r0.a.

color write mask.

The color write mask is used to control writing to the color channels.

// The color write mask is also referred to as the vector write mask,
// because it uses the vector pipeline.
mul r0.rgb, t0, v0

© 2002 Microsoft Corporation. All rights reserved.


Register Write Masks

Write masks control which channels (red, green, blue, alpha) are updated in the destination register.

Syntax

destination register.writemask

Register

Destination register. For more about register types, see Registers - ps_1_X.

Remarks

The following destination write masks are available.

Write Mask | Syntax | Version
 |  | 1.0 | 1.1 | 1.2 | 1.3 | 1.4, 2.0, 3.0
red, green, blue, alpha | destination register.rgba | X | X | X | X | X
none | destination register | X | X | X | X | X
color (red, green, blue) | destination register.rgb | X | X | X | X | X
alpha | destination register.a | X | X | X | X | X
red | destination register.r |  |  |  |  | X
green | destination register.g |  |  |  |  | X
blue | destination register.b |  |  |  |  | X
arbitrary | destination register.rgba |  |  |  |  | See following note.
Note The arbitrary mask allows any set of channels to be combined to produce a mask. The channels must be listed in the order r, g, b, a—for example, register.rba, which updates the red, blue, and alpha channels of the destination. The arbitrary mask is available only in version 1.4.

If no destination write mask is specified, the destination write mask defaults to the rgba case. In other words, all channels in the destination register are updated.

An alternate syntax for the r,g,b,a channels is x,y,z,w.

For versions 1.0 to 1.3, the dp3 arithmetic instruction can use only the .rgb or .rgba output write masks.

Destination register write masks are supported for arithmetic operations only. They cannot be used on texture addressing instructions, with the exception of the version 1.4 instructions, texcrd and texld.

The default is to write all four color channels.

// All four color channels can be written by explicitly listing them.
mul r0.rgba, t0, v0

// Or, the default mask can be used to write all four channels.
mul r0, t0, v0

The alpha write mask is also referred to as the scalar write mask, because it uses the scalar pipeline.

add r0.a, t1, v1

So this instruction effectively puts the sum of the alpha component of t1 and the alpha component of v1 into r0.a.

The color write mask is used to control writing to the color channels.

// The color write mask is also referred to as the vector write mask,
//   because it uses the vector pipeline.
mul r0.rgb, t0, v0

For version 1.4, destination write masks can be used in any combination as long as the masks are ordered r,g,b,a.

// This example updates the red, blue, and alpha channels.
mov r0.rba, r1

A co-issued instruction allows two potentially different instructions to be issued simultaneously. This is accomplished by executing the instructions in the alpha pipeline and the RGB pipeline.

// For example, the default example shown above:
mul r0, t0, v0

// is also equivalent to the following co-issued instruction
  mul r0.rgb, t0, v0
+ mul r0.a,   t0, v0

The advantage of pairing instructions this way is that it allows different operations to be performed in the vector and scalar pipeline in parallel.

© 2002 Microsoft Corporation. All rights reserved.


Register Modifiers

Use source register modifiers to change the value read from a register before an instruction runs. The contents of a source register are left unchanged. Modifiers are useful for adjusting the range of register data in preparation for the instruction. A set of modifiers called selectors copies or replicates the data from a single channel (r,g,b,a) into the other channels.

Version 1_4 shaders have modifier functionality specific to shader instructions texld and texcrd. These modifiers affect version 1_4 texture registers and are detailed in Texture Register Modifiers.

Source register modifiers | Syntax | Version
 |  | 1_1 | 1_2 | 1_3 | 1_4
bias | register_bias | X | X | X | X
invert | 1 - register | X | X | X | X
negate | - register | X | X | X | X
scale by 2 | register_x2 |  |  |  | X
signed scaling | register_bx2 | X | X | X | X

Source register modifiers can be used only on arithmetic instructions. They cannot be used on texture address instructions. The exception to this is the Scale x 2 modifier (_bx2). For version 1_1, signed scale can be used on the source argument of any texm* instruction. For version 1_2 or 1_3, signed scale can be used on the source argument of any texture address instruction.

Some modifier specific restrictions:

  • Negate can be combined with either the bias, signed scaling, or scalex2 modifier. When combined, negate is run last.
  • Invert cannot be combined with any other modifier.
  • Invert, negate, bias, signed scaling, and scalex2 can be combined with any of the selectors.
  • Source register modifiers should not be used on constant registers because they will cause undefined results. For version 1_4, modifiers on constants are not allowed and will fail validation.

© 2002 Microsoft Corporation. All rights reserved.


Bias

Subtract 0.5 from all components.

Registers

Source register. For more about register types, see Registers - ps_1_X.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The bias is applied to all four color channels (RGBA) as follows:

output = (input - 0.5)

The effect is to modify data that was in the range 0 to 1 to be in the range -0.5 to 0.5. Applying bias to data outside this range may produce undefined results.

Note This modifier is mutually exclusive with Invert, so it cannot be applied to the same register.

This modifier is for use with the arithmetic instructions.

Example

This example performs the same operation as D3DTOP_ADDSIGNED in Microsoft® DirectX® 6.0 and 7.0 multiple texture syntax.

add r0, r0, t0_bias    ; Shift down by 0.5.

© 2002 Microsoft Corporation. All rights reserved.


Invert

Performs a (1 - value) calculation for each channel of the specified register.

Syntax

1 - source register

Registers

Source Register. For more about register types, see Registers - ps_1_X.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The invert operation is applied to all four color channels (RGBA).

This modifier can be used only with arithmetic instructions. In addition, this modifier cannot be combined with the other Register Modifiers.

Example

This example uses inversion to generate the complement of register r1.

mul r0, r0, 1-r1    ; Multiply by (1.0 - r1).

© 2002 Microsoft Corporation. All rights reserved.


Negate

Performs a negate (y = -x), on all register components.

Syntax

- source register

Registers

Source Register. For more about register types, see Registers - ps_1_X.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The negate operation is applied to all four color channels (RGBA).

This operation is performed after any other modifiers present on the same argument.

This modifier is mutually exclusive with Invert so it cannot be applied to the same register.

This modifier is for use with the arithmetic instructions.

Example

The following example shows how to use this modifier.

mul r0, r0, -v1    ; Multiply by specular color.

© 2002 Microsoft Corporation. All rights reserved.


Scale x 2

Multiply the value by two before using it in the instruction.

Syntax

source register_x2

Register

Source register. For more about register types, see Registers - ps_1_X.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

This modifier is mutually exclusive with Invert, so it cannot be applied to the same register.

This modifier is only available to arithmetic instructions in version 1_4.

© 2002 Microsoft Corporation. All rights reserved.


Signed Scaling

Subtracts 0.5 from each channel and scales the result by 2.0. The name "bx2" comes from bias times two, which is the operation it performs.

Syntax

source register_bx2

Register

Source Register. For more about register types, see Registers - ps_1_X.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

The signed scaling operation is applied to the data read from the register before the next instruction is run. The operation is applied to all four color channels (RGBA) as follows:

y = 2(x - 0.5)

This operation is commonly used to expand data from [0.0 to 1.0] to [-1.0 to 1.0]. Using _bx2 on data outside the range 0 to 1 may produce undefined results.

This modifier is designed for use with the arithmetic instructions. This modifier is commonly used on inputs to the dot product instruction (dp3).

This modifier is mutually exclusive with Invert so it cannot be applied to the same register.

For shader version 1_1, input arguments to any of the texture address instructions of the form texm3x2* and texm3x3* can use the _bx2 modifier.

For shader versions 1_2 and 1_3, the source register to any tex* instruction can use the _bx2 modifier. For version 1_0 and 1_1, _bx2 cannot be used on the source register for texreg2ar or texreg2gb.

Example

This example samples a texture, converts data to the range of -1 to +1, and calculates a dot product.

tex t0                        ; Read a texture color.
dp3_sat r0, t0_bx2, v0_bx2    ; Calculate a dot product.

© 2002 Microsoft Corporation. All rights reserved.


Texture Register Modifiers

Two pixel shader version 1_4 texture address instructions, texld and texcrd, have custom syntax. These instructions support their own set of source register modifiers, source register selectors, and destination-register write masks, as shown here.

Source Register Modifiers for texld and texcrd

These modifiers provide projective divide functionality by dividing the x and y values by either the z or w values.

Source register modifiers | Description | Syntax | Version
_dz | Divide x,y components by z | source register_dz | 1_4
_db |  | source register_db | 1_4
_dw | Divide x,y components by w | source register_dw | 1_4
_da |  | source register_da | 1_4

Remarks

The _dz or _db modifier does the following:

x' = x/z ( x' = 1.0 if z == 0)
y' = y/z ( y' = 1.0 if z == 0)
z' is undefined
w' is undefined

The _dw or _da modifier does the following:

x' = x/w ( x' = 1.0 if w == 0)
y' = y/w ( y' = 1.0 if w == 0)
z' is undefined
w' is undefined

Source Register Selectors for texld and texcrd

Selectors replicate the contents of one channel into other channels. Replicating the contents of a channel to one or more other channels is commonly referred to as "swizzling."

Source register selectors | Description | Syntax | Version
xyz | Maps x,y,z data to channels x,y,z,z | source register.xyz | 1_4
rgb |  | source register.rgb | 1_4
xyw | Maps x,y,w data to channels x,y,w,w | source register.xyw | 1_4
rga |  | source register.rga | 1_4

Remarks

The texld and texcrd instructions never read more than the first three components. So, these selectors provide the option of taking the third component from either the third or the fourth component of the source register.

Destination Register Write Masks for texld and texcrd

Write masks control which channels (red, green, blue, alpha) are updated in the destination register.

Destination register write masks | Description | Syntax | Used by | Version
xyzw | Updates the x,y,z,w channels | destination register.xyzw | texld only | 1_4
rgba |  | destination register.rgba | texld only | 1_4
none |  | destination register | texld only | 1_4
xyz | Updates the x,y,z channels | destination register.xyz | texcrd only | 1_4
rgb |  | destination register.rgb | texcrd only | 1_4
xy | Updates the x,y channels | destination register.xy | texcrd only | 1_4
rg |  | destination register.rg | texcrd only | 1_4

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader 2_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - ps_2_0 contains a list of the available instructions.
  • Registers - ps_2_0 lists the different types of registers used by the vertex shader arithmetic logic unit (ALU).
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

Instruction Count

Shaders have restrictions for maximum instuction counts.

Total Instruction slots: 96 (64 arithmetic and 32 texture)

© 2002 Microsoft Corporation. All rights reserved.


Instructions - ps_2_0

This section contains reference information for the pixel shader version 2_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Texture | New
abs | Absolute value | 1 |  |  | x |  | x
add | Add two vectors | 1 |  | x |  |  |
cmp | Compare source to 0 | 1 |  | x |  |  |
crs | Cross product | 2 |  |  | x |  | x
dcl | Map a vertex element type to an input vertex register | 0 | x |  |  |  | x
dcl_textureType | Declare the texture coordinate dimension for a sampler register | 0 | x |  |  |  | x
def | Define constants | 0 | x |  |  |  |
dp2add | 2-D dot product and add | 2 |  | x |  |  | x
dp3 | 3-D dot product | 1 |  | x |  |  |
dp4 | 4-D dot product | 1 |  | x |  |  |
exp | Full precision 2x | 1 |  |  | x |  | x
frc | Fractional component | 1 |  |  | x |  | x
log | Full precision log2(x) | 1 |  |  | x |  | x
lrp | Linear interpolate | 2 |  |  | x |  | x
m3x2 | 3x2 multiply | 2 |  |  | x |  | x
m3x3 | 3x3 multiply | 3 |  |  | x |  | x
m3x4 | 3x4 multiply | 4 |  |  | x |  | x
m4x3 | 4x3 multiply | 3 |  |  | x |  | x
m4x4 | 4x4 multiply | 4 |  |  | x |  | x
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  |  | x |  |
min | Minimum | 1 |  |  | x |  |
mov | Move | 1 |  | x |  |  |
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize | 3 |  |  | x |  | x
pow | 2x | 3 |  |  | x |  | x
ps | Version | 0 | x |  |  |  | x
rcp | Reciprocal | 1 |  | x |  |  | x
rsq | Reciprocal square root | 1 |  | x |  |  | x
sincos | Sine and cosine | 8 |  |  | x |  | x
sub | Subtract | 1 |  | x |  |  |
texkill | Kill pixel render | 1(tex) |  |  |  | x |
texld | Sample a texture | 1 + 3CUBE |  |  |  | x | x
texldb | Texture sampling with level of detail (LOD) bias from w-component | 1(tex) |  |  |  | x | x
texldp | Texture sampling with projective divide by w-component | 1(tex) |  |  |  | x | x

Where:

  • tex - 1 texture instruction slot. However, if D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, this instruction is counted against the instruction ( non texture) count.
  • 1 + 3CUBE means 1 + 3 if the texture is a cube map.
  • 3 + 1CUBE means 3 + 1 if the texture is a cube map.

© 2002 Microsoft Corporation. All rights reserved.


Registers - ps_2_0

Pixel shaders depend on registers to get vertex data, to output pixel data to the rasterizer, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_0.

Input Register Types

Register | Name | Description | New
v0, v1 | Color Register | Contains interpolated vertex data. | No
c0 to c31 | Constant Float Register | Contains constants used by the shader. | Yes
t0 to t7 | Input Texture Coordinate Register | Contains interpolated texture coordinates. | No
s0 to s15 | Sampler Register | Identifies a texture sampling stage. | Yes
r0 to r11 | Temporary Register | Holds intermediate results. | No

Output Register Types

Register | Name | Description | New
oC0, oC1, oC2, oC3 | Output Color Register | Each register represents a different texture element. | Yes
oDepth | Output Depth Register | The register contains a depth value. | Yes

© 2002 Microsoft Corporation. All rights reserved.


Instruction Modifiers (Pixel Shader)

Instruction modifiers affect the result of the instruction before it is written into the destination register.

Centroid

Centroid is an optional instruction modifier supported on dcl_usage (which declares input registers) and on texture lookup instructions. The _centroid modifier is appended to an instruction with no space.

The _color usage has special behavior: it assumes that _centroid is set (as a default), so specifying color along with _centroid has no effect. When centroid is set on an input register declaration that is not a _color usage, the attribute evaluation is altered when multisampling. It defines the attribute interpolation to be clamped to the range of the attribute across the primitive when the multisample pixel center is not covered by the primitive. Note that gradients computed from such data are not guaranteed to be accurate. Take care when an attribute marked with _centroid is used for texture sampling. Normally the evaluation is performed at the pixel center. This has no effect on input registers with the _color usage.

This modifier can be also set on the texld* instructions, dsx and dsy. When a texture-coordinate is evaluated at the centroid, the gradient information computed might not be accurate. When this hint is provided, implementations can adjust this gradient computation to be more accurate.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
centroid |  |  |  |  |  |  |  | x | x

This instruction modifier is not supported on any vertex shader instructions.

Partial Precision

The partial precision hint (represented as _pp in the assembly) can be used by the application to indicate to the device that the operation can be performed and the result stored at a lower precision (at least s10e5). This is a hint and many implementations might ignore it.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pp |  |  |  |  | x | x | x | x | x

Sat

Saturates or clamps the instruction result to [0,1] range before writing to the destination register.

add_sat rDest, rSrc0, rSrc1

Where:

rDest = clamp_between_0_and_1(rSrc0 + rSrc1).

The saturate instruction modifier costs no additional instruction slots.

The _sat instruction modifier can be used with any arithmetic instruction (including macro-ops), except the frc and sincos instructions.

_sat cannot be used with texture addressing instructions texld* and texkill.

_sat cannot be used with instructions writing to output o# registers.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
_sat | x | x | x | x | x | x | x | x | x

© 2002 Microsoft Corporation. All rights reserved.


Masking (Pixel Shader)

A write mask controls which components of a destination register are written after an instruction is completed. An output write mask is allowed as long as the components are in the order of .rgba or .xyzw. That is, .rba and .xw are valid masks. Texture registers have one set of rules and non-texture registers have another set of rules.

Destination Register Masking

As shown in the following table, masking can be applied to the individual components of a destination register.

Component modifier | Description
r.{x}{y}{z}{w} | Destination mask

In general, specifying destination register write masks is good coding style. It makes code easier to read and maintain. Any combination of components may be specified (including none) as long as x precedes y, y precedes z, and z precedes w.

The following output registers have restrictions for write mask:

Register Type | Required Write Mask
oFog | no explicit write mask allowed on a scalar register
oPts | no explicit write mask allowed on a scalar register
oPos | combined mask: .xyzw(which is the default)
oT# | combined mask: .x | .xy | .xyz | .xyzw (which is the default)

The following versions support masking.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
destination register masking | x | x | x | x | x | x | x | x | x

© 2002 Microsoft Corporation. All rights reserved.


Source Modifiers (Pixel Shader)

Source modifiers can be applied to modify the data read from a source register before the data is used by the instruction.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2, m3x3, m3x4, m4x3, and m4x4.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.

© 2002 Microsoft Corporation. All rights reserved.


Swizzling (Pixel Shader)

Swizzling refers to the ability to copy any source register component to any temporary register component. Swizzling does not affect the source register data. Before an instruction runs, the data in a source register is copied to a temporary register.

Source Swizzling

Source swizzle allows individual component of a source register to take on the value of any of the four components of the same source register before the register is read for computation.

For example, the .zxxy swizzle means:

  • .x component will take on the value of .z component
  • .y component will take on the value of .x component
  • .z component will take on the value of .x component
  • .w component will take on the value of .y component

The components can appear in any order. If fewer than four components are specified, the last component is repeated. For example:

.xy  = .xyyy
.wzx = .wzxx
.z   = .zzzz

If no component is specified, no swizzling is applied.

Some instructions have restrictions for source swizzle. They are listed in the respected instruction reference pages.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
swizzling | x | x | x | x | x | x | x | x | x

Arbitrary Swizzle

Swizzles can be applied to source registers in an arbitrary order; that is, any source register can take any component mask, in any order.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
arbitrary swizzling |  |  |  |  |  | x | x | x | x

Replicate Swizzle

Replicate swizzle, is used to replicate or copy one component to another. This is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader 2_0 Extended

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - ps_2_x contains a list of the available instructions.
  • Registers - ps_2_x lists the different types of registers used by the vertex shader arithmetic logic unit (ALU).
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

Dynamic Flow Control

D3DCAPS9.PS20Caps.DynamicFlowControlDepth represents the nesting depth of dynamic flow control instructions: if, if_comp, if_pred, break, and break_comp. The value is equal to the nesting depth of the if_comp block. The range of values for this cap is 0 to 24. If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

The number of temporary registers supported by the device. The range is from 12 to 32.

Static Flow Control Nesting Depth

D3DCAPS9.PS20Caps.StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop/rep and call/callnz. The range of values for this cap is 1 to 4. loop/rep instructions can be nested up to StaticFlowControlDepth deep. Independently, call/callnz instructions can be nested up to StaticFlowControlDepth deep.

Number of Instruction Slots

The number of instruction slots can range from 96 to a maximum of 512, and is specified by the D3DCAPS9.PS20Caps.MaxPixelShaderInstructionSlots cap. The total number of instructions that can run is defined by D3DCAPS9.MaxPixelShaderInstructionsExecuted. This can be larger than the number of instruction slots due to looping and subroutine calls.

Arbitrary Swizzle

If D3DPS20CAPS_ARBITRARYSWIZZLE flag is set, arbitrary swizzle is supported. See Arbitrary Swizzle.

Gradient Instructions

If D3DPS20CAPS_GRADIENTINSTRUCTIONS is set, gradient instructions are supported. See dsx, dsy, and texldd.

Predication

If D3DPS20CAPS_PREDICATION flag is set, instruction predication is supported. See Predicate.

Dependent Read Limit

If D3DPS20CAPS_NODEPENDENTREADLIMIT is set, there are no dependent read limits.

Texture Instruction Limit

If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT flag is set, there are no limit on texture instructions.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - ps_2_x

This section contains reference information for the pixel shader version 2_x instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Texture | Flow Control | New
abs | Absolute value | 1 |  |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  |  | x | x
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  |  | x | x
break pred | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  |  | x | x
call | Call a subroutine | 2 |  |  |  |  | x | x
callnz | Call a subroutine if a boolean register is not zero | 3 |  |  |  |  | x | x
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  |  | x | x
cmp | Compare source to 0 | 1 |  | x |  |  |  |
crs | Cross product | 2 |  |  | x |  |  |
dcl | Map a vertex element type to an input vertex register | 0 | x |  |  |  |  |
dcl_textureType | Declare the texture dimension for a sampler | 0 | x |  |  |  |  |
def | Define constants | 0 | x |  |  |  |  |
dp2add | 2-D dot product and add | 1 |  | x |  |  |  |
dp3 | 3-D dot product | 1 |  | x |  |  |  |
dp4 | 4-D dot product | 1 |  | x |  |  |  |
dsx | Rate of change in the x-direction | 2 |  | x |  |  |  | x
dsy | Rate of change in the y direction | 2 |  | x |  |  |  | x
else | Begin an else block | 1 |  |  |  |  | x | x
endif | End an if...else block | 1 |  |  |  |  | x | x
endrep | End of a repeat block | 2 |  |  |  |  | x | x
exp | Full precision 2x | 1 |  |  | x |  |  | x
frc | Fractional component | 1 |  |  | x |  |  |
if | Begin an if block | 3 |  |  |  |  | x | x
if comp | Begin an if block with a comparison | 3 |  |  |  |  | x | x
if pred | Begin an if block with predication | 3 |  |  |  |  | x | x
label | Label | 0 |  |  |  |  | x | x
log | Full precision log2(x) | 1 |  |  | x |  |  |
lrp | Linear interpolate | 2 |  |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |  |
max | Maximum | 1 |  |  | x |  |  |
min | Minimum | 1 |  |  | x |  |  |
mov | Move | 1 |  | x |  |  |  |
mul | Multiply | 1 |  | x |  |  |  |
nop | No operation | 1 |  | x |  |  |  |
nrm | Normalize | 3 |  |  | x |  |  |
pow | 2x | 3 |  |  | x |  |  |
ps | Version | 0 | x |  |  |  |  |
rcp | Reciprocal | 1 |  | x |  |  |  |
rep | Repeat | 3 |  |  |  |  | x | x
ret | End of a subroutine | 1 |  |  |  |  | x | x
rsq | Reciprocal square root | 1 |  | x |  |  |  |
setp | Set the predicate register | 1 |  |  |  | x |  | x
sincos | Sine and cosine | 8 |  |  | x |  |  |
sub | Subtract | 1 |  | x |  |  |  |
texkill | Kill pixel render | 2(tex) |  |  |  | x |  |
texld | Sample a texture | 1 + 3CUBE |  |  |  | x |  |
texldb | Texture sampling with level of detail (LOD) bias from w-component | 6(tex) |  |  |  | x |  |
texldd | Texture sampling with user-provided gradients | 3 |  |  |  | x |  | x
texldp | Texture sampling with projective divide by w-component | 3 + 1CUBE |  |  |  | x |  |

Where:

  • tex - 1 texture instruction slot. However, if D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, this instruction is counted against the instruction ( non texture) count.
  • 1 + 3CUBE means 1 + 3 if the texture is a cube map.
  • 3 + 1CUBE means 3 + 1 if the texture is a cube map.

Instruction Count and Nesting Depth

Shaders have restrictions for maximum instuction counts, as well as nesting depths for static and dynamic flow control instructions.

Overall Instruction Count

Total Instruction slots: 512 maximum

The maximum number of instructions run is indicated by the MaxPShaderInstructionsExecuted cap in D3DCAPS9.

  • On hardware that supports ps_2_0, it should be at least 96 (more if they support the flow control caps).

This can be set to the #define D3DINFINITEINSTRUCTIONS, indicating that the actual number of instructions run is unlimited.

The total number of instructions run should be clamped to the device driver D3DRS_MAXPIXELSHADERINST. The legal values for this renderstate are numbers that are powers of 2; if any other integer is set, the next nearest pow2 number is assumed. This renderstate defaults to D3DINFINITEINSTRUCTIONS.

Dynamic Flow Control Nesting Depth

D3DCAPS9.D3DPSHADERCAPS2_0.DynamicFlowControlDepth represents the nesting depth of static flow control instructions: if, break, and break_comp. The value is equal to the nesting depth of the if_comp block. The range of values for this cap is 0 to 24. If this cap is zero, the device does not support dynamic flow control instructions.

Static Flow Control Nesting Depth

D3DCAPS9.D3DPSHADERCAPS2_0.StaticFlowControlDepth represents the nesting depth of static flow control instructions: loop/rep and call/callnz. The range of values for this cap is 1 to 4. Note that loop/rep count toward the same nesting depth, and call/callnz count toward the same nesting depth. If this cap is zero, the device does not support static flow control instructions.

© 2002 Microsoft Corporation. All rights reserved.


Registers - ps_2_x

Pixel shaders depend on registers to get vertex data, to output pixel data to the rasterizer, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_x.

There is one additional register introduced in this version. It is used for predication.

Input Register Types

Name | Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Color Register | 2 | R | 1 | Unlimited | 4 | N | Partial(0001) | N
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 224 | R | 1 | Unlimited | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | N | FALSE | N
p | Predicate | 1 | R | 1 | 1 | 1 | N | None | Y
s# | Sampler Register | 16 | R | 1 | 1 | 4 | N | Depends* | Y
t# | Input Texture Coordinate Register | 8 | R | 1 | 1 | 1 | N | None | Y

Where:

  • r is read, w is write, u is used.
  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • The number of readports is the number of different registers (for each register type) that can be read in a single instruction. For example, a readport of two for a constant register means that all of these are legal since they use 2 or fewer unique constant registers:
    mad r0, c0, c0, c1
mad r0, c2, t1, c1
mad r0, c3, c3, c3

    But the following is illegal because it uses mnore than 2 unique constant registers:

    mad r0, c1, c2, c3
  • Defaults for sampler lookups exist, but values depend on texture format. It is usually 1111, except 0001 for a8 format.

Output Register Types

Name | Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multielement Texture | w | 0 | 0 | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 0 | 0 | 1 | N | None | N

Where:

  • R is read, W is write, U is used.
  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • aL only - These register banks can be addressed using only the aL register. If it is out of range then the hardware and the result is undefined except for the floating point constant bank which should return (0,0,0,0).

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader 3_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the ALU. Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • Instructions - ps_3_0 contains a list of the available instructions.
  • Registers - ps_3_0 lists the different types of registers used by the vertex shader arithmetic logic unit (ALU).
  • InstructionModifiers are used to modify the way an instruction works.
  • Masking determines what components of the destination register get written.
  • SourceModifiers alter the source register data before the instruction runs.
  • Swizzling gives additional control over which register components are read, copied or written.

New Features

Add a face register. Add a position register. Color registers (v#) are now fully floating point and the texture coordinate registers (t#) have been consolidated. Input declarations take the usage names, and multiple usages are permitted for components of a given register.

Dynamic Flow Control

The device supports dynamic flow control (if, break, and break_comp). The depth of nesting ranges from 0 to 24.

Number of Temporary Registers

The number of temporary registers supported is 32.

Static Flow Control Nesting Depth

The call/callnz/call_pred can be nested to a maximum depth of 4. Independently, loop/rep instructions can be nested to a maximum depth of 4.

Arbitrary Swizzle

Arbitrary swizzle is supported. See Arbitrary Swizzle.

Gradient Instructions

Gradient instructions are supported. See dsx, dsy, and texldd.

Predication

Instruction predication is supported. See Predicate.

Dependent Read Limit

There are no dependent read limits.

Texture Instruction Limit

There is no limit on texture instructions.

Instruction Count

Each pixel shader is allowed anywhere from 512 up to the number of slots in the MaxPixelShader30InstructionSlots member of D3DCAPS9 (not more than 32768). The number of instructions run can be much higher because of the looping support. The MaxPShaderInstructionsExecuted cap in D3DCAPS9 should be at least 2^16.

© 2002 Microsoft Corporation. All rights reserved.


Instructions - ps_3_0

This section contains reference information for the pixel shader version 3_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Macro-ops - These instructions combine arithmetic instructions to provide higher level functionality. The use of macro-ops is optional. It is preferable to use macro-ops, especially the matrix multiply instructions (m3x2, m3x3, m3x4, m4x3, m4x4), because they provide optimization opportunities to the underlying implementation.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Macro-ops | Texture | Flow control | New
abs | Absolute value | 1 |  |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  | x | x |
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  | x | x |
break pred | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  | x | x |
call | Call a subroutine | 2 |  |  |  | x | x |
callnz | Call a subroutine if a boolean register is not zero | 3 |  |  |  |  | x |
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x | x |
cmp | Compare source to 0 | 1 |  | x |  |  |  |
crs | Cross product | 2 |  |  | x |  |  |
dcl_textureType | Declare the texture dimension for a sampler | 0 | x |  |  |  |  |
dcl_usage | Declare the association between vertex shader output registers and pixel shader input registers. | 0 | x |  |  |  |  | x
def | Define constants | 0 | x |  |  |  |  |
defb | Define a Boolean constant | 0 | x |  |  |  |  | x
defi | Define an integer constant | 0 | x |  |  |  |  | x
dp2add | 2-D dot product and add | 2 |  | x |  |  |  |
dp3 | 3-D dot product | 1 |  | x |  |  |  |
dp4 | 4-D dot product | 1 |  | x |  |  |  |
dsx | Rate of change in the x-direction | 2 |  | x |  |  |  |
dsy | Rate of change in the y direction | 2 |  | x |  |  |  |
else | Begin an else block | 1 |  |  |  |  | x |
endif | End an if...else block | 1 |  |  |  |  | x |
endloop | endloop | 2 |  |  |  |  | x | x
endrep | End of a repeat block | 2 |  |  |  |  | x |
exp | Full precision 2x | 1 |  |  | x |  |  |
frc | Fractional component | 1 |  |  | x |  |  |
if | Begin an if block | 3 |  |  |  |  | x | x
if comp | Begin an if block with a comparison | 3 |  |  |  |  | x | x
if pred | Begin an if block with predication | 3 |  |  |  |  | x | x
label | Label | 0 |  |  |  |  | x |
log | Full precision log2(x) | 1 |  |  | x |  |  |
loop | Loop | 3 |  |  |  |  | x | x
lrp | Linear interpolate | 2 |  |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |  |
max | Maximum | 1 |  |  | x |  |  |
min | Minimum | 1 |  |  | x |  |  |
mov | Move | 1 |  | x |  |  |  |
mul | Multiply | 1 |  | x |  |  |  |
nop | No operation | 1 |  | x |  |  |  |
nrm | Normalize | 3 |  |  | x |  |  |
pow | 2x | 3 |  |  | x |  |  |
ps | Version | 0 | x |  |  |  |  | x
rcp | Reciprocal | 1 |  | x |  |  |  |
rep | Repeat | 3 |  |  |  |  | x |
ret | End of a subroutine | 1 |  |  |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |  |  |
setp | Set the predicate register | 1 |  |  |  | x |  |
sincos | Sine and cosine | 8 |  |  | x |  |  |
sub | Subtract | 1 |  | x |  |  |  |
texkill | Kill pixel render | 2 |  |  |  | x |  |
texld | Sample a texture | 1 + 3CUBE |  |  |  | x |  |
texldb | Texture sampling with level of detail (LOD) bias from w-component | 6 |  |  |  | x |  |
texldl | Texture sampling with LOD from w-component | 2 + 3CUBE |  |  |  | x |  | x
texldd | Texture sampling with user-provided gradients | 3 |  |  |  | x |  | x
texldp | Texture sampling with projective divide by w-component | 3 + 1CUBE |  |  |  | x |  |

Where:

  • tex - 1 texture instruction slot. However, if D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, this instruction is counted against the instruction ( non texture) count.
  • 1 + 3CUBE means 1 + 3 if the texture is a cube map.
  • 1 + 2CUBE means 1 + 2 if the texture is a cube map.
  • 3 + 1CUBE means 3 + 1 if the texture is a cube map.

© 2002 Microsoft Corporation. All rights reserved.


Registers - ps_3_0

Pixel shaders depend on registers to get vertex data, to output pixel data to the rasterizer, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 3_0.

Input Register Types

Name | Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 10 | R |  | Unlimited | 4 | aL only | Partial(0001) | Y
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 224 | R | 1 | Unlimited | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | N | FALSE | N
aL | Loop Counter Register | 1 | U | N/A | Unlimited | 1 | N/A | None | N
p0 | Predicate | 1 | R | 1 | 1 | 1 | N | None | Y
s# | Sampler Register | 16 | R | 1 | 1 | 4 | N | Depends* | Y
vFace | Face Register | 1 | R | 1 | 1 | 1 | N | None | Y
vPos | Position Register | 1 | R | 1 | 1 | 4 | N | None | Y

Where:

  • r is read, w is write, u is used.
  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • aL only - These register banks can be addressed using only the aL register. If it is out of range then the hardware and the result is undefined.
  • The number of readports is the number of different registers (for each register type) that can be read in a single instruction. For example, a readport of one for a constant register means that all of these are legal since they use at most one constant register in the single instruction:
    mad r0, c0, c0, v0
mad r0, c2, t1, v0
mad r0, c3, c3, c3

    But the following is illegal because it uses more than 1 constant registers:

    mad r0, c1, c2, v0
  • Defaults for unspecified channels of sampler register lookups exist, but values depend on texture format. It is usually 1111, except 000a for a8 format.

Output Register Types

Name | Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multielement Texture | W | 0 | 0 | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 0 | 0 | 1 | N | None | N

Where:

  • R is read, W is write, U is used.
  • partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  • aL only - These register banks can be addressed using only the aL register. If it is out of range then the hardware and the result is undefined except for the floating point constant bank which should return (0,0,0,0).

Input Register

The input registers are now fully floating point and the texture registers have been consolidated with them into a single register type. The register declaration uses a semantic to describe what is contained in a particular input register(v#). No clamping is performed when the input registers are defined as colors (like texture coordinates).

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Input Register |  |  |  |  |  |  |  | x | x

Face Register

The face register is a new floating-point scalar register. In ps_3_0 only, the sign of this register is valid. If the value is less than zero, the primitive is a back face (the area is negative). The face register can be used inside a pixel shader to make decisions about which lighting technique (two-sided lighting for example). This register requires a declaration (example: dcl vFace), so undeclared usage will be flagged as an error. This register is undefined for lines and point primitives. The face register can only be used with the setp and if comp instructions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Face Register |  |  |  |  |  |  |  | x | x

Position Register

This register contains the current pixel position (x, y) in the corresponding channels. The (z, w) channels are undefined. This register needs to be declared (example: dcl vPos.xy).

When multisampling, the position will contain the pixel coordinates and not the sample coordinates (multisampling happens once per pixel). When the driver performs super sampling and the pixel shader is run multiple times per pixel, the position will will contain the resolved coordinates, that is, they will be normalized by the render-target bloat factor.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register |  |  |  |  |  |  |  | x | x

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader Differences

These are the differences between the pixel shader versions.

Version | Maximum number of instructions
1_x | 8 for version 1_1. 12 for versions 1_2 and 1_3. 14 for version 1_4.
2_0 | 64 arithmetic and 32 texture instructions.
2_0 Extended | 96 minimum, up to 512 maximum. The exact number is specified by D3DCAPS9.PS20Caps.MaxPixelShaderInstructionSlots. See D3DCAPS9.
3_0 | 512 minimum, up to the number of slots in the D3DCAPS9.MaxPixelShader30InstructionSlots (not more than 32768). See D3DCAPS9.

New Features

New features for each version include the following:

Version 3_0

  • Static flow control instructions: call, callnz, else, end, endif, endloop, endrep, if, label, loop, rep, ret
  • Static flow control nesting depth
  • Number of temporary registers
  • Dynamic flow control instructions: break, breakc, ifc
  • Predication: setp instruction, p# register

New registers: constant integer, constant Boolean, loop counter, predicate

New modifiers: arbitrary swizzle

Version 2_0 Extended

  • New static flow control instructions (with a cap set): call, callnz, else, end, endif, endloop, endrep, if, label, loop, rep, ret
  • Static flow control nesting depth
  • Number of temporary registers
  • Dynamic flow control instructions: break, breakc, ifc
  • Gradient instructions: dsx and dsy
  • Texture instructions: texldd
  • Predication - setp instruction, p# register

New registers: constant integer, constant Boolean, loop counter, predicate

New modifiers (with a cap set): arbitrary swizzle

Version 2_0

New instructions:

  • Setup instructions: def, ps
  • Arithmetic instructions: add, cmp, cnd, dp3, dp4, lrp, mad, mov, mul, nop, sub
  • Macros: exp, frc, log, m3x2, m3x3, m3x4, m4x3, m4x4
  • Texture instructions:
    • Added: texldb, texldp
    • Removed: tex, texbem, texbeml, texcoord, texcrd, texdepth, texdp3, texdp3tex, texm3x2depth, texm3x2pad, texm3x2tex, texm3x3, texm3x3pad, texm3x3tex, texm3x3spec, texm3x3vspec, texreg2ar, texreg2gb, texreg2rgb

New registers: constant float, sampler, output color, output depth

New modifiers: negate, partial precision, saturate

Removed co-issuing of instructions

Version 1_X

New instructions:

  • Setup instructions: def, ps
  • Arithmetic instructions: add, cmp, cnd, dp3, dp4, lrp, mad, mov, mul, nop, sub
  • Macros: exp, frc, log, m3x2, m3x3, m3x4, m4x3, m4x4
  • Texture instructions: tex, texbem, texbeml, texcoord, texcrd, texdepth, texdp3, texdp3tex, texkill, texld, texm3x2depth, texm3x2pad, texm3x2tex, texm3x3, texm3x3pad, texm3x3tex, texm3x3spec, texm3x3vspec, texreg2ar, texreg2gb, texreg2rgb

New registers: constant, temporary, texture, color

New modifiers: instruction modifiers, register modifiers, source register selectors, register write masks

© 2002 Microsoft Corporation. All rights reserved.


Relative Addressing

The [ ] syntax can be used only in register types that can be relatively addressed in certain shader models. The supported forms of [ ] syntax are listed as follows:

Where:

  • "R" denotes any register type that can be relatively addressed.
  • "A" denotes any register that can be used as an index to relatively address other registers.
  • n0 - ni, m0 - mj, and k are integers >= 0.
[ ] syntax | Effective index | Examples
R[ A + m0 + ... + mj ] | A + m0 + ... + mj | c[ a0.x + 3 + 7 ]
R[ k ] ( = Rk ) | k | c[ 10 ] ( = c10 )
R[ A ] | A | c[ a0.y ]
Rk[ n0 + ... + ni + A + m0 + ... + mj ] | A + k + n0 + ... + ni + m0 + ... + mj | c8[ 3 + 2 + a0.w + 5 + 6 + 1 ]
R[ n0 + ... + ni + A + m0 + ... + mj ] | A + n0 + ... + ni + m0 + ... + mj | c[ 2 + 1 + aL + 3 + 4 + 5 ]
Rk[ A ] | A + k | c12[ aL ], c0[ a0.z ]
Rk[ A + m0 + ... + mj ] | A + k + m0 + ... + mj | v1[ aL + 4 + 8 ]
R[ n0 + ... + ni + A ] | A + n0 + ... + ni | o[ 3 + 1 + aL ]
Rk[ n0 + ... + ni + A ] | A + k + n0 + ... + ni | o1[ 2 + 1 + 3 + aL ]

The registers are available in the following versions:

Register type | Shader versions
a0 | vs_1_1 and higher
aL | vs_2_0 and higher, ps_3_0
cn | vs_1_1 and higher, ps_3_0
on | vs_3_0

© 2002 Microsoft Corporation. All rights reserved.


Software Shaders

Software shaders are implemented to allow development of shaders without underlying hardware support. They support the full feature set. Because they are implemented in software, they will not produce the best performance.

Shader Version | Description
ps_2_sw | Implements all the features of ps_2_x. See Pixel Shader 2_0 Extended.
ps_3_sw | Implements all the features of ps_3_0. See Pixel Shader 3_0.
vs_2_sw | Implements all the features of vs_2_x. See Vertex Shader 2_0 Extended.
vs_3_sw | Implements all the features of vs_3_0. See Vertex Shader 3_0.

© 2002 Microsoft Corporation. All rights reserved.


Shader Debugger

Microsoft® Visual Studio® .NET supports debugging assembly level and high-level language vertex and pixel shaders.

DirectX Extensions for Visual Studio .NET

The debugger works with the debug version of the runtime, as well as with certain device types. Any vertex or pixel shader can be debugged when using a reference device. Vertex shaders can be debugged, providing they are running on a hardware abstraction layer (HAL) device created for software vertex processing. No debugging support is provided for hardware vertex processing or "pure" HAL devices. For more information about device types, see D3DDEVTYPE.

  • Building with Debug Information
  • Starting the Debugger
  • Breakpoints
  • Viewing Device State
  • Debugging C++ Code and Direct3D Code Simultaneously

Building with Debug Information

To do source-level debugging of a shader, the shader must be built with debug information and it must have an on-disk source file associated with it. You can create such a shader in the following two ways.

  • Compile the shader at build time using vsa.exe (the vertex shader assembler), psa.exe (the pixel shader assembler), or fxc.exe (the high level language compiler) and specify the /Zi command-line flag.
  • Compile the shader at run time using D3DXAssembleShaderFromFile or D3DXCompileShaderFromFileand specify the D3DXSHADER_DEBUG flag. For more information about the compiler flags, see D3DXSHADER.
  • For debugging purposes, disable optimizations by supplying the /Od command line flag or the D3DXSHADER_SKIPOPTIMIZATION flag.

Starting the Debugger

To debug an application, the application must be using the debug version of the Microsoft Direct3D® runtime and must have shader debugging enabled. You can configure these options through the Direct3D tab in the Microsoft DirectX® control panel applet. The DirectX debug service must also be running on the target computer. This service is installed automatically when you install the DirectX extensions for Visual Studio .NET.

  • When using a HAL device, only vertex shaders created for software vertex processing can be debugged. Pixel shaders cannot be debugged at all. No debugging whatsoever is supported for "pure" HAL devices.
  • When using a reference device, any vertex or pixel shader may be debugged. Debugging of "pure" reference devices works the same as it does for non-pure reference devices.

There are two ways to start the debugger:

  1. Clicking Debug, Direct3D, Start D3D (CTRL+ALT+F5) will start the debugger.
  2. You can "attach" to an already running Direct3D process. The easiest way to do this from Visual Studio .NET is as follows:
    • On the Debug menu, start your application with the Start Without Debugging command.
    • On the Debug menu, choose Processes to open the Processes window.
    • Choose your application from the process list and press the Attach button.
    • In the Attach to Process dialog box, select Native to debug your C++ code, and select Direct3D to debug your Direct3D code. You can debug both C++ and Direct3D code simultaneously (see Debugging C++ Code and Direct3D Code Simultaneously near the bottom of this topic).

Visual Studio .NET also supports remote debugging of Direct3D applications. To attach to a Direct3D process on a remote computer, in the Processes dialog box, enter the name of the remote computer in the Name box and then attach to the process the same as for a local process.

Breakpoints

The module window can be used to view all shaders that are currently loaded. When debugging native code, right-click on the window and choose Show Modules for All Programs to view the shaders that are loaded.

File/Line Breakpoints

To set a breakpoint in a vertex or pixel shader source file, the shader must have debug information present (see Building with Debug Information). You can set a source code breakpoint in a shader the same ways you would set a source code breakpoint in C++ source code, that is:

  • Open the source file in the Visual Studio .NET text editor; move the cursor to the line on which to set the breakpoint; and choose the Toggle Breakpoint command (F9 by default).
  • Right-click the line in the source code where you want to set the breakpoint and then choose Insert Breakpoint from the shortcut menu.
  • Select the New Breakpoint command (CTRL+B by default). Using the File tab in the New Breakpoint dialog box, enter the file name and optionally the line number of the breakpoint.
Function Breakpoints

Type the case-sensitive name of the shader function as the name, and set the language to D3D Shader. The function name is the name of the shader function stored in the debug information, the name of the file containing the shader, or the shader handle number preceded by the shader type (for example, VS1). The module window lists all currently loaded shaders and their names. IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene breakpoints work as before.

Conditional Breakpoints

Any of the following types of breakpoints can have a condition, as long as the breakpoint is set to fire when the condition is true (as opposed to when the condition changes):

  • Function
  • File/Line
  • Address

The expression must evaluate to a single-element bool result.

Memory Breakpoints

A memory breakpoint triggers at the first instruction of any pixel shader that is about to modify a pixel within a given rectangle. Set a memory breakpoint by going to the Memory tab in the Breakpoint dialog, selecting D3D Shader as the language, and entering a region in one of the following formats:

  • (x,y) : Break when the pixel at (x, y) is being computed.
  • (left,top)-(right,bottom) : Break when any of the pixels in a rectangle are being computed. Standard RECT semantics apply: Left and top edges are in the rect, right and bottom edges are not.

Assembly Code (Address) Breakpoints

Setting a breakpoint on a specific instruction of a shader does not require debug information. You can set an address breakpoint in the following ways.

  • Move the cursor in the Disassembly window to the line containing the instruction on which you want to set the breakpoint, and choose the Toggle Breakpoint command (F9 by default).
  • Right-click the line in the Disassembly window containing the instruction on which to set the breakpoint and choose Insert Breakpoint from the shortcut menu.
  • By selecting the New Breakpoint command (CTRL+B by default), selecting the Address tab, selecting Direct3D Shader from the Language combo box, and entering the address of the instruction on which you want to set the breakpoint.

    The format of an address is <Shader Type>ShaderHandle:InstructionIndex, where Shader Type is either "v" for Vertex Shader or "p" for Pixel Shaders, ShaderHandle is the value of the handle returned by IDirect3DDevice9::CreateVertexShader or IDirect3DDevice9::CreatePixelShader, and InstructionIndex is the one-based byte offset for the shader instruction. For example, to set a breakpoint on the first instruction of vertex shader number 2, you would enter the address as v2:1.

BeginScene or EndScene Breakpoints

To set a breakpoint when the application you are debugging reaches IDirect3DDevice9::BeginScene or IDirect3DDevice9::EndScene, select the New Breakpoint command (CTRL+B by default), select the Function tab, select Direct3D Shader from the Language combo box, and type either BeginScene or EndScene as the name of the function.

Stepping

You can step through shader code using the Debug menu's Step Over command (F10 by default). Stepping in Direct3D code will cause the application you are debugging to stop at the next vertex or pixel shader instruction it runs.

Expression Evaluation

When the application you are debugging is stopped in a vertex or pixel shader, or at a BeginScene or EndScene breakpoint, you can use the Watch window to inspect the state of the application you are debugging. You can also quickly view the contents of a register by briefly resting the mouse pointer on the register in the Disassembly window or in your shader source code.

The expression syntax supports register names, swizzles, and the following operators, which all operate per component.

+ - * / == != < <= > >= [] ! || &&

In addition, the following two intrinsic functions are supported.

  • any( e ) - Returns true if any of the bool elements of e are true.
  • all( e ) - Returns true if all of the bool elements of e are true.

All types must match exactly. Floating-point literals must have a decimal point; otherwise, they are treated as integers.

Examples

This expression returns true if all of the first three components of r0 are less than the corresponding components of c4.

all( r0.xyz < c4.xyz )

Constant register are indexed by one plus the x-component of a0.

c[a0.x+1]

Viewing Register Contents

To view the contents of a register in the watch window, use the following expression syntax.

registerName[.swizzle][,format][,w]

Where:

  • registerName is the name of the register to inspect (for example, r0, oPos, t7).
  • swizzle is the optional swizzle specifier, the same as used on a source register in the shader assembly language (for example, v0.xxyy, r2.rgb).
  • format is the optional floating-point format specifier, the same as for C++ debugging. Valid format specifiers are:
    • e - Exponential notation (for example, 1.23e+1)
    • f - Standard notation (for example, 12.3)
    • g - Same as either 'e' or 'f', whichever is more compact
    • w - Divide first three components by fourth component before displaying

Viewing Device State

To view the current values of render states and texture stage states on the device, enter $DeviceState in the Watch window.

Viewing the Current Pixel Position

The coordinates of the pixel currently being rendered by a pixel shader are contained in register vPos.

Viewing Surface Contents

Viewing the render target - To view the contents of the current render target surface, open the Render Target window by selecting the Debug menu's Direct3D, Render Target menu options. This window will be updated with the current contents of the render target whenever the application you are debugging enters "break" mode.

Viewing textures - To view the contents of the texture currently selected into a texture stage, open a Texture window by selecting the appropriate texture stage from the Debug menu's Direct3D, Textures menu. The texture windows will be updated with the current contents of the corresponding texture stage whenever the application you are debugging enters "break" mode.

If the contents of a surface (either the render target or a texture) are not available, the surface's window will show the text as "Unavailable." Possible reasons for a surface being unavailable include:

  • The surface is not lockable. The surface must be created to allow it to be locked for read-only access. To create a lockable back buffer, specify the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag in D3DPRESENT_PARAMETERS when calling IDirect3D9::CreateDevice.
  • The surface is a volume texture. The texture windows do not support the display of volume textures in this release.
  • The surface is in an unsupported pixel format. The debugger currently supports the display of most standard RGB and RGBA pixel formats, as well as the DXTn compressed texture formats.
  • The application you are debugging is running on a remote computer. In this release, the surface views are not supported when debugging remotely.

Debugging C++ Code and Direct3D Code Simultaneously

The Visual Studio .NET debugger supports debugging of multiple program types at the same time. Typical C++ debugging uses the "Native" program type. Direct3D debugging uses the "Direct3D" program type. When the application you are debugging stops in C++ code, the current program will be set to Native, and the call stack, watch window, and other debug windows will reflect the state of the Native program. Similarly, when the application you are debugging stops in shader code, the current program will be set to Direct3D, and the debug windows will reflect the state of the Direct3D program. To switch between program types, use the Program combo box on the Debug Location toolbar. Note that when the application you are debugging is stopped in Native code, most of the state of the Direct3D program will be unavailable. The reverse is not true, however. If you stop at a breakpoint in a shader, for example, you can switch to the Native program and see the C++ call stack that caused your shader to be invoked.

For more information about debugging multiple program types simultaneously, see "Debugging Multiple Programs" in the Visual Studio .NET documentation.

Debugging Without Debug Information

If possible, build your shaders with debug information enabled (see Building with Debug Information). In cases where building with debug information is not feasible, such as for shaders that are built up "on the fly," debugging is possible but is much more difficult. Source code is not available, so source code breakpoints don't work. One approach to debugging without debug information is to set a BeginScene breakpoint, and when that breakpoint is reached, step into the shader code of the first shader run by pressing F10. Once you're stepping through disassembly code, you can set breakpoints in the Disassembly window. You can also use the Modules window to view the names of all shaders currently loaded and selectively set breakpoints on them as needed.

Another approach is to set a breakpoint in your C++ code immediately before calling IDirect3DDevice9::DrawPrimitive or IDirect3DDevice9::DrawIndexedPrimitive. When this breakpoint is reached, you can then set an address breakpoint using the current shader handle and then run until that breakpoint is reached.

© 2002 Microsoft Corporation. All rights reserved.


High-Level Shader Language

Tired of writing shaders in assembly language? Try the high-level shader language. Microsoft® DirectX® 9.0 contains the first release of a high-level shader language for developing and debugging shaders in a C-like language. This capability is in addition to the assembly language shader capability that is used to generate vertex shaders, pixel shaders, and effects, which began with DirectX 8.0.

The high-level shader language supports the development of shaders from C-like functions. The language will support many standard language features such as functions, expressions, statements, standard data types, user-designed data types, and preprocessor directives.

  • Data Types
    • Scalar Types
    • Vector Types
    • Matrix Types
    • Object Types
    • Structure Types
    • User-Defined Types
    • Type Casts
    • Variables
  • Statements and Expressions
    • Expressions
  • Functions
    • User-Defined Functions
    • Intrinsic Functions
  • Shader Semantics
    • Vertex Shader Input Semantics
    • Vertex Shader Output Semantics
    • Pixel Shader Input Semantics
    • Pixel Shader Output Semantics
  • Examples
  • Appendix
    • Keywords
    • Preprocessor Directives
    • Lexical Conventions
    • Language Syntax

Data Types

Scalar Types

bool | true of false
int | 32-bit signed integer
half | 16-bit floating point value
float | 32-bit floating point value
double | 64-bit floating point value

Not all target platforms have native support for integer values. Integer values might need to be emulated using floating point hardware. Integer operations that go outside the range of integers that can be expressed as floats on these platforms are not guaranteed to function as expected.

Not all target platforms have native support for half or double values. If the target platform does not, these will be emulated using float. Intermediate results of floating point expressions may be evaluated at a precision higher than the operands or the result.

Vector Types

vector | A vector of dimension 4; each component is of type float.
vector < type, size > | A vector of dimension size; each component is of scalar type type.

Individual components of a vector can be accessed by index, using the array access syntax. For example:

vec[0]		(same as vec.x)
vec[3]		(same as vec.w)

Individual components of a vector can be accessed by name, using the structure member access syntax. The following component name sets for vectors are defined.

Default set
 x	 y	 z	 w

Color set
 r	 g	 b	 a

Vectors containing swizzled components of the vector can be formed by concatenating two or more component names together. For example, yyzw or bgr. The concatenated names all must come from the same name set. The same component can be repeated more than once, but if it is, the swizzle is not valid as the target of an assignment.

Matrix Types

matrix | A matrix with four rows and four columns, each component is of type float.
matrix < type, rows, columns > | A matrix with rows rows and cols columns; each component is of scalar type type.

Individual row-vectors of a matrix can be accessed by index, using the array access syntax. For example:

mat[2]     (same as mat.m20m21m22m23)
mat[2].w   (same as mat.m23)
mat[2][3]  (same as mat.m23)

Individual components of a matrix can be accessed by name, using the structure member access syntax. The following component name sets for matrices are defined.

One-based set

_11	_12	_13	_14
_21	_22	_23	_24
_31	_32	_33	_34
_41	_42	_43	_44

Zero-based set

_m00	_m01	_m02	_m03
_m10	_m11	_m12	_m13
_m20	_m21	_m22	_m23
_m30	_m31	_m32	_m33

Vectors containing swizzled components of the matrix can be formed by concatenating two or more component names together. For example, _41_42_43 or _m01_m02_m03_m04. The concatenated names all must come from the same name set. The same component can be repeated more than once, but if it is, the swizzle is not valid as the target of an assignment.

Object Types

string

ASCII string type. There are no operations or states that accept strings. String parameters and annotations can, however, be queried by the application through the ID3DXEffect interface.

pixelshader

A pixelshader object represents a Microsoft Direct3D® pixel shader object. While no operation within a shader function directly accepts pixel shaders, a pixel shader can be set to the device from within a technique. The following properties can be queried from a pixelshader object, using structure member access syntax.

const string version;

Literal pixelshader values can be expressed as an assembly block,

pixelshader ps = asm { ps.2.0 mov oC0, c0 };

or as a compile call.

pixelshader ps = compile ps_2_0 psmain();

sampler

A sampler object represents a Direct3D sampler stage. Sampler stages are used to sample textures. Samplers are assigned textures and filtering types.

sampler s = sampler_state { texture = NULL; mipfilter = LINEAR; };

texture

A texture object represents a Direct3D texture object. While no operation within a shader function directly accepts textures, textures can be set to the device from within a technique. The following properties can be queried from a texture object, using structure member access syntax.

const string type;
const string format;
const int width;
const int height;
const int depth;

vertexshader

A vertexshader object represents a Direct3D vertex shader object. While no operation within a shader function directly accepts vertex shaders, a vertex shader can be set to the device from within a technique. The following properties can be queried from a vertexshader object, using structure member access syntax.

const string version;

Literal vertexshader values can be expressed as an assembly block,

vertexshader vs = asm { vs.2.0 mov oPos, c0 };

or as a compile call.

vertexshader vs = compile vs_2_0 psmain();

Struct member access of object properties is not yet implemented.

Structure Types

The struct keyword is used to define a structure type. Once a structure has been defined, it can be referenced by using its identifier (ID).

    struct [id] { member_list }

A member_list consists of one or more member declarations. Member declarations are similar to variable declarations (described below), except they cannot have initializers and cannot individually be declared static, extern, volatile, or const.

User-Defined Types

The typedef keyword can be used to declare a name for a type. The const keyword can be used to explicitly mark the type as constant. Array suffixes can follow each ID (Or "id"). Once a type has been declared, it can be referenced by using its ID.

    typedef [const] type id [array_suffix] [, id ...] ;

An array_suffix consists of one or more [ literal_integer_expression ], representing the dimension.

For compatibility with Direct3D extensions (D3DX) 8.0 effects, the following types are automatically defined in a case-insensitive manner at the super-global scope.

    typedef int DWORD;
    typedef float FLOAT;
    typedef vector VECTOR;
    typedef matrix MATRIX;
    typedef string STRING;
    typedef texture TEXTURE;
    typedef pixelshader PIXELSHADER;
    typedef vertexshader VERTEXSHADER;

For convenience, the following types are automatically defined at the super-global scope. (In these definitions, the pound sign represents a digit between 1 and 4.)

    typedef vector bool#;
    typedef vector int#;
    typedef vector half#;
    typedef vector float#;
    typedef vector double#;

    typedef matrix bool#x#;
    typedef matrix int#x#;
    typedef matrix half#x#;
    typedef matrix float#x#;
    typedef matrix double#x#;

Type Casts

Scalar-to-scalar | Always valid. When casting from bool type to an integer or floating point type, false is considered to be zero, and true is considered to be one. When casting from an integer or floating point type to bool, a zero value is considered to be false, and a nonzero value is considered to be true. When casting from a floating point type to an integer type, the value is rounded toward zero.
Scalar-to-vector | Always valid. This cast operates by replicating the scalar to fill the vector.
Scalar-to-matrix | Always valid. This cast operates by replicating the scalar to fill the matrix.
Scalar-to-object | Never valid.
Scalar-to-structure | Valid if all elements of the structure are numeric. This cast operates by replicating the scalar to fill the structure.
Vector-to-scalar | Always valid. This selects the first component of the vector
Vector-to-vector | The destination vector must not be larger than the source vector. The cast operates by keeping the left-most values, and truncating the rest. For the purposes of this cast, column matrices, row matrices, and numeric structures are treated as vectors.
Vector-to-matrix | The size of the vector must be equal to the size of the matrix.
Vector-to-object | Never valid.
Vector-to-structure | Valid if the structure is not larger than the vector, and all components of the structure are numeric.
Matrix-to-scalar | Always valid. This selects the upper-left component of the matrix.
Matrix-to-vector | The size of the matrix must be equal to the size of the vector.
Matrix-to-matrix | The destination matrix must not be larger than the source matrix, in both dimensions. The cast operates by keeping the upper-left values, and truncating the rest.
Matrix-to-object | Never valid.
Matrix-to-structure | The size of the structure must be equal to the size of the matrix, and all components of the structure are numeric.
Object-to-scalar | Never valid.
Object-to-vector | Never valid.
Object-to-matrix | Never valid.
Object-to-object | Valid only if the object types are identical.
Object-to-structure | The structure must not contain more than one member. The type of that member must be identical to the type of the object.
Structure-to-scalar | The structure must contain at least one member. This member must be numeric.
Structure-to-vector | The structure must be at least the size of the vector. The first components must be numeric, up to the size of the vector.
Structure-to-matrix | The structure must be at least the size of the matrix. The first components must be numeric, up to the size of the matrix.
Structure-to-object | The structure must contain at least one member. The type of this member must be identical to the type of the object.
Structure-to-structure | The destination structure must not be larger than the source structure. A valid cast must exist between all respective source and destination components.

Variables

Variables are declared as follows:

[static uniform extern shared volatile] [const]
type id [array_suffix] [: semantic] [= initializers] [annotations] [, id ...] ;

Variable declarations can be prefixed with the static keyword. For global variables, this indicates that the variable is internal to the shader and not to be exposed externally. For local variables, this indicates that its value will persist from call to call. Initialization of local static variables happens only once. If they are not explicitly initialized, their initial value is assumed to be zero.

Global variable declarations can be prefixed with the uniform keyword, explicitly indicating that they are uniform inputs to the shader. All non-static global variables are uniform by default.

Global variable declarations can be prefixed with the extern keyword, explicitly indicating that they are external inputs to the shader. All non-static global variables are extern by default.

Global variable declarations can be prefixed with the shared keyword. This a hint to the effect framework that the value of this parameter is intended to be shared between effect objects.

Global variable declarations can be prefixed with the volatile keyword. This a hint to the effect framework that the value of this parameter changes frequently.

The initializers represents either an expression, or { expression [, expression [, ...]] }. For global externs, these expressions must be literal. For other global variables, and static local variables, these expressions must be constant.

Variables can be given a semantic. Semantics have no meaning in the language. They are simply associated with the variable, and passed down to the back-end. They are not case-sensitive. What semantics are valid, and what they mean, depends on what kind of function you are defining. (For vertex shaders, the semantics are used by the back-end to map inputs, and assign output registers. A complete list of shader input and output semantics appears later in this document.)

Global variables can have annotations. Annotations are of the form { member_list }. Where member_list represents a list of member declarations, where each member is initialized to a literal value. Annotation are only a method of communicating metadata about a parameter to an effect. They cannot be referenced from inside the program. Annotation members cannot have semantics.

Component Access and Swizzles

Individual float components of base types can be addressed much like accessing a structure member, using a subscript from the name table below.

_11, x, r | _12, y, g | _13, z, b | _14, w, a
_21 | _22 | _23 | _24
_31 | _32 | _33 | _34
_41 | _42 | _43 | _44

Vectors containing specific components (swizzles) can be specified by using a subscript formed by concatenating two to four of these names together. Valid examples are:

bgr, yyzw, _12_22_32_42

All the names must come from the same subscript set, (xyzw, rgba, or _11 to _44). Sets cannot be mixed. The same component may be repeated more than once. However, if a component is repeated, the swizzle is not valid as the target of an assignment.

Statements and Expressions

Statements

Statements are used to control the flow of execution. The following kinds of statements are supported.

{ [statements] }
[expression] ;
return [expression] ;
if ( expression ) statement [else statement]
for ( [expression | variable_declaration] ; [expression] ; [expression] ) statement
do statement while ( expression ) ;
while ( expression ) statement ;

The for, do, while statements are not yet implemented.

Expressions

Expressions are literals, variables, or some combination of literals and variables composed using operators from the operator precedence table in the Appendix.

Operator | Usage | Meaning | Associativity
() | (value) | Sub expression | Left to right
() | id(arguments) | Function call | Left to right
 | type(arguments) | Type constructor | Left to right
[] | array[int] | Array subscript | Left to right
. | structure.id | Member selection | Left to right
 | value.swizzle | Component swizzle | Left to right
++ | variable++ | Postfix increment (per component) | Left to right
-- | variable-- | Postfix decrement (per component) | Left to right
++ | ++variable | Prefix increment (per component) | Right to left
-- | --variable | Prefix decrement (per component) | Right to left
! | !value | Logical not (per component) | Right to left
- | -value | Unary minus (per component) | Right to left
+ | +value | Unary plus (per component) | Right to left
() | (type) value | Type cast | Right to left
* | value*value | Multiplication (per component) | Left to right
/ | value/value | Division (per component) | Left to right
% | value%value | Modulus (per component) | Left to right
+ | value+value | Addition (per component) | Left to right
- | value-value | Subtraction (per component) | Left to right
< | value < value | Less than (per component) | Left to right
> | value > value | Greater than (per component) | Left to right
<= | value <= value | Less than or equal to (per component) | Left to right
>= | value >= value | Greater than or equal to (per component) | Left to right
== | value == value | Equality (per component) | Left to right
!= | value != value | Inequality (per component) | Left to right
&& | value && value | Logical AND (per component) | Left to right
|| | value||value | Logical OR (per component) | Left to right
?: | float?value:value | Conditional | Right to left
= | variable=value | Assignment (per component) | Right to left
*= | variable*=value | Multiplication assignment (per component) | Right to left
/= | variable/=value | Division assignment (per component) | Right to left
%= | variable%=value | Modulus assignment (per component) | Right to left
+= | variable+=value | Addition assignment (per component) | Right to left
-= | variable-=value | Subtraction assignment (per component) | Right to left
, | value,value | Comma | Left to right

Unlike C, short-circuit evaluation of &&, ||, and ?: expressions never short-circuit any evaluation because they are vector operations, and all sides of the expression are always evaluated.

The % operator is defined only in cases where either both sides are positive, or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integer.

Many of the operators are designated as being "per component." This indicates that, for each component of the input, some operation is performed (independent from the operations happening on the other components), and the result is placed in the corresponding component of the output vector.

Comparison and binary operators also function on a per component basis. This means that if you compare two vectors, the result is a vector containing the Boolean result of the comparison for each component.

For expressions of binary operators, the size and component type of each side are promoted to be the same before the operation occurs. The promoted type determines the resolution at which the operation takes place, as well as the result type of the expression. For example an (int3 + float) expression would be promoted to (float3 + float3) for evaluation, and its result would be of type float3.

Functions

  • User-Defined Functions
  • Intrinsic Functions

User-Defined Functions

Functions are defined very much like C functions.

[static inline target] [const] type id ( [parameter_list] ) ;
[static inline target] [const] type id ( [parameter_list] ) { [statements] } ;

The target represents an optional identifier specifying the platform for which the function has been authored. The parameter_list represents a list of one or more parameter declarations separated by commas.

[uniform in out inout] type id [: semantic] [= default]

Parameter values are always passed by value. The in parameter usage indicates that the value of the parameter should be copied in from the caller before the function begins. The out parameter usage indicates that the last value of the parameter should be copied out, and returned to the caller when the function returns. The inout parameter usage is simply a shorthand for specifying both in and out. The uniform parameter usage is a special of kind of in, indicating to a top-level function that the value for parameter comes from constant data. For non-top-level functions, uniform is synonymous with in. If no parameter usage is specified, the parameter usage is assumed to be in.

If a function is defined without a body, it is considered to be a prototype. The function must be redefined, with a body, later on in the code. If no body is defined and the function gets referenced, this is an error.

Functions can be overloaded. A function is uniquely identified by its name, the types of its parameters, and the target platform, if provided. Function overloading is not yet implemented.

Currently, all functions are inlined. Recursion is not supported.

Intrinsic Functions

abs | value abs(value a) | Absolute value (per component).
acos | acos(x) | Returns the arccosine of each component of x. Each component should be in the range [-1, 1].
all | all(x) | Test if all components of x are nonzero.
any | any(x) | Test is any component of x is nonzero.
asin | asin(x) | Returns the arcsine of each component of x. Each component should be in the range [-pi/2, pi/2].
atan | atan(x) | Returns the arctangent of x. The return values are in the range [-pi/2, pi/2].
atan2 | atan2(y, x) | Returns the arctangent of y/x. The signs of y and x are used to determine the quadrant of the return values in the range [-pi, pi]. atan2 is well-defined for every point other than the origin, even if x equals 0 and y does not equal 0.
ceil | ceil(x) | Returns the smallest integer which is greater than or equal to x.
clamp | clamp(x, min, max) | Clamps x to the range [min, max].
clip | clip(x) | Discards the current pixel, if any component of x is less than zero. This can be used to simulate clip planes, if each component of x represents the distance from a plane.
cos | cos(x) | Returns the cosine of x.
cosh | cosh(x) | Returns the hyperbolic cosine of x.
cross | cross(a, b) | Returns the cross product of two 3-D vectors a and b.
D3DCOLORtoUBYTE4 | D3DCOLORtoUBYTE4(x) | Swizzles and scales components of the 4-D vector x to compensate for the lack of UBYTE4 support in some hardware.
ddx | ddx(x) | Returns the partial derivative of x with respect to the screen-space x-coordinate.
ddy | ddy(x) | Returns the partial derivative of x with respect to the screen-space y-coordinate.
degrees | degrees(x) | Converts x from radians to degrees.
determinant | determinant(m) | Returns the determinant of the square matrix m.
distance | distance(a, b) | Returns the distance between two points a and b.
dot | dot(a, b) | Returns the dot product of two vectors a and b.
exp | exp(x) | Returns the base-e exponent ex.
exp2 | value exp2(value a) | Base 2 Exp (per component).
faceforward | faceforward(n, i, ng) | Returns -n * sign(dot(i, ng)).
floor | floor(x) | Returns the greatest integer which is less than or equal to x.
fmod | fmod(a, b) | Returns the floating point remainder f of a / b such that a = i * b + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of b.
frac | frac(x) | Returns the fractional part f of x, such that f is a value greater than or equal to 0, and less than 1.
frc | value frc(value a) | Fractional part (per component).
frexp | frexp(x, out exp) | Returns the mantissa and exponent of x. frexp returns the mantissa, and the exponent is stored in the output parameter exp. If x is 0, the function returns 0 for both the mantissa and the exponent.
fwidth | fwidth(x) | Returns abs(ddx(x))+abs(ddy(x)).
isfinite | isfinite(x) | Returns true if x is finite, false otherwise.
isinf | isinf(x) | Returns true if x is +INF or -INF, false otherwise.
isnan | isnan(x) | Returns true if x is NAN or QNAN, false otherwise.
ldexp | ldexp(x, exp) | Returns x * 2exp.
len | float len(value a) | Vector length.
length | length(v) | Returns the length of the vector v.
lerp | lerp(a, b, s) | Returns a + s(b - a). This linearly interpolates between a and b, such that the return value is a when s is 0, and b when s is 1.
lit | lit(ndotl, ndoth, m) | Returns a lighting vector (ambient, diffuse, specular, 1): ambient = 1; diffuse = (ndotl < 0) ? 0 : ndotl; specular = (ndotl < 0) || (ndoth < 0) ? 0 : (ndoth * m);
log | log(x) | Returns the base-e logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log10 | log10(x) | Returns the base-10 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log2 | log2(x) | Returns the base-2 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
max | max(a, b) | Selects the greater of a and b.
min | min(a, b) | Selects the lesser of a and b.
modf | modf(x, out ip) | Splits the value x into fractional and integer parts, each of which has the same sign and x. The signed fractional portion of x is returned. The integer portion is stored in the output parameter ip.
mul | mul(a, b) | Performs matrix multiplication between a and b. If a is a vector, it treated as a row vector. If b is a vector, it is treated as a column vector. The inner dimension acolumns and brows must be equal. The result has the dimension arows x bcolumns.
noise | noise(x) | Not yet implemented.
normalize | normalize(v) | Returns the normalized vector v / length(v). If the length of v is 0, the result is indefinite.
pow | pow(x, y) | Returns xy.
radians | radians(x) | Converts x from degrees to radians.
reflect | reflect(i, n) | Returns the reflection vector v, given the entering ray direction i, and the surface normal n. Such that v = i - 2 * dot(i, n) * n
refract | refract(i, n, eta) | Returns the refraction vector v, given the entering ray direction i, the surface normal n, and the relative index of refraction eta. If the angle between i and n is too great for a given eta, refract returns (0,0,0).
round | round(x) | Rounds x to the nearest integer.
rsqrt | rsqrt(x) | Returns 1 / sqrt(x).
saturate | saturate(x) | Clamps x to the range [0, 1].
sign | sign(x) | Computes the sign of x. Returns -1 if x is less than 0, 0 if x equals 0, and 1 if x is greater than zero.
sin | sin(x) | Returns the sine of x.
sincos | sincos(x, out s, out c) | Returns the sine and cosine of x. sin(x) is stored in the output parameter s. cos(x) is stored in the output parameter c.
sinh | sinh(x) | Returns the hyperbolic sine of x.
smoothstep | smoothstep(min, max, x) | Returns 0 if x < min. Returns 1 if x > max. Returns a smooth Hermite interpolation between 0 and 1, if x is in the range [min, max].
sqrt | value sqrt(value a) | Square root (per component).
step | step(a, x) | Returns (x >= a) ? 1 : 0.
tan | tan(x) | Returns the tangent of x.
tanh | tanh(x) | Returns the hyperbolic tangent of x.
tex1D | tex1D(s, t) | 1-D texture lookup. s is a sampler or a sampler1D object. t is a scalar.
tex1D | tex1D(s, t, ddx, ddy) | 1-D texture lookup, with derivatives. s is a sampler or sampler1D object. t, ddx, and ddy are scalars.
tex1Dproj | tex1Dproj(s, t) | 1-D projective texture lookup. s is a sampler or sampler1D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex1Dbias | tex1Dbias(s, t) | 1-D biased texture lookup. s is a sampler or sampler1D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
tex2D | tex2D(s, t) | 2-D texture lookup. s is a sampler or a sampler2D object. t is a 2-D texture coordinate.
tex2D | tex2D(s, t, ddx, ddy) | 2-D texture lookup, with derivatives. s is a sampler or sampler2D object. t, ddx, and ddy are 2-D vectors.
tex2Dproj | tex2Dproj(s, t) | 2-D projective texture lookup. s is a sampler or sampler2D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex2Dbias | tex2Dbias(s, t) | 2-D biased texture lookup. s is a sampler or sampler2D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
tex3D | tex3D(s, t) | 3-D volume texture lookup. s is a sampler or a sampler3D object. t is a 3-D texture coordinate.
tex3D | tex3D(s, t, ddx, ddy) | 3-D volume texture lookup, with derivatives. s is a sampler or sampler3D object. t, ddx, and ddy are 3-D vectors.
tex3Dproj | tex3Dproj(s, t) | 3-D projective volume texture lookup. s is a sampler or sampler3D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex3Dbias | tex3Dbias(s, t) | 3-D biased texture lookup. s is a sampler or sampler3D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
texCUBE | texCUBE(s, t) | 3-D cube texture lookup. s is a sampler or a samplerCUBE object. t is a 3-D texture coordinate.
texCUBE | texCUBE(s, t, ddx, ddy) | 3-D cube texture lookup, with derivatives. s is a sampler or samplerCUBE object. t, ddx, and ddy are 3-D vectors.
texCUBEproj | texCUBEproj(s, t) | 3-D projective cube texture lookup. s is a sampler or samplerCUBE object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
texCUBEbias | texCUBEbias(s, t) | 3-D biased cube texture lookup. s is a sampler or samplerCUBE object. t is a 4-dimensional vector. The mip level is biased by t.w before the lookup takes place.
transpose | transpose(m) | Returns the transpose of the matrix m. If the source is dimension mrows x mcolumns, the result is dimension mcolumns x mrows.

Shader Semantics

  • Vertex Shader Input Semantics
  • Vertex Shader Output Semantics
  • Pixel Shader Input Semantics
  • Pixel Shader Output Semantics

Vertex Shader Input Semantics

Input semantics are annotations that identify data usage for the vertex shader input data. This is similar to the D3DDECLUSAGE parameter in the fixed function pipeline.

POSITION[n] | position
BLENDWEIGHT[n] | blend weights
BLENDINDICES[n] | blend indices
NORMAL[n] | normal vector
PSIZE[n] | point size
DIFFUSE[n] | diffuse color
SPECULAR[n] | specular color
TEXCOORD[n] | texture coordinates
TANGENT[n] | tangent
BINORMAL[n] | binormal
TESSFACTOR[n] | tessellation factor

n is an optional, integer. As an example, PSIZE0, DIFFUSE1, etc.

Vertex Shader Output Semantics

Output semantics are annotations that identify data usage for the vertex shader output data. This is similar to the D3DDECLUSAGE parameter in the fixed function pipeline.

POSITION | Position
PSIZE | Point size
FOG | Vertex fog
COLOR[n] | Color (example: COLOR0)
TEXCOORD[n] | Texture coordinates (example: TEXCOORD0)

n is an optional, integer. As an example, texcoord0.

Pixel Shader Input Semantics

Input semantics are annotations that identify data usage for the pixel shader input data. This is similar to the D3DDECLUSAGE parameter in the fixed function pipeline.

COLOR[n] | Diffuse of specular color (example: COLOR0 or COLOR1)
TEXCOORD[n] | Texture coordinates (example: TEXCOORD0)

n is an optional, integer. As an example, TEXCOORD0, TEXCOORD1, etc.

Pixel Shader Output Semantics

Output semantics are annotations that identify data usage for the pixel shader output data.

COLOR[n] | Color (example: COLOR0)
TEXCOORD[n] | Texture coordinates (example: TEXCOORD0)

n is an optional, integer. As an example, texcoord0.

Examples

Glow Example

See Apply a Glow.

Indexed blended character skinning

//----------------------------------------------------------------------------
// Global parameters
//----------------------------------------------------------------------------

texture tDiffuse;
texture tNormal;

float4 cAmbient  = { 0.3f, 0.3f, 0.3f, 1.0f };  // ambient color
float4 cDiffuse  = { 1.0f, 1.0f, 1.0f, 1.0f };  // diffuse color
float4 cSpecular = { 0.6f, 0.6f, 0.6f, 1.0f };  // specular color

float3 vDiffuse  = { 0.0f, 1.0f, 0.0f };        // diffuse direction
float3 vSpecular = { 0.0f, 0.0f, 0.0f };        // specular direction

struct VS_INPUT
{
    float4 vPosition        : POSITION;
    float3 vBlendWeights    : BLENDWEIGHT;
    float4 vBlendIndices    : BLENDINDICES;
    float3 vNormal          : NORMAL;
    float2 vTexCoords       : TEXCOORD0;
    float3 vTangent         : TANGENT;
    float  fFlip            : TEXCOORD1;
    float  fDisplacement    : TEXCOORD2;
};

struct VS_OUTPUT
{
    float4 vPosition        : POSITION;
    float4 vTexCoord0       : TEXCOORD0;
    float4 vTexCoord1       : TEXCOORD1;
    float3 vDiffuse         : COLOR0;
    float3 vSpecular        : COLOR1;
};

struct PS_OUTPUT
{
    float4 vColor           : COLOR0;
};

//----------------------------------------------------------------------------
// Shader body
//----------------------------------------------------------------------------

VS_OUTPUT main(const VS_INPUT v)
{
    VS_OUTPUT o = (VS_OUTPUT) 0;

    // Compute last blend weight.
    // An application supplies one fewer bone weights than
    //   the number of bones. So, the last bone weight is
    //   calculated using a dot product.

    float fLastBlendWeight = 1 - dot(v.vBlendWeights, 1);

    // The dot product is a convenient way of subtracting
    //   the other three weights from 1.

    // Skin position(to world space)
    // Each vertex is influenced by four bones. Each bone
    //   must be transformed to world space, and then the result
    //   is combined using the bone weight.

    float3 vPosition =
        mul(v.vPosition, mWorld[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vPosition, mWorld[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vPosition, mWorld[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vPosition, mWorld[v.vBlendIndices.w]) * fLastBlendWeight;

    // Each normal is also influenced by four bones. Because normals
    //   cannot be transformed using the world matrix (because they
    //   end up with orientation problems if x,y,z scaling is not
    //   uniform), normals need to be transformed using an
    //   inverse-transpose matrix (mNormal). Otherwise, the mathematics
    //   is nearly the same (the data types are different) as the
    //   vertex position computation.

    // Skin normal (to world space)
    float3 vNormal =
        mul(v.vNormal, mNormal[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vNormal, mNormal[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vNormal, mNormal[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vNormal, mNormal[v.vBlendIndices.w]) * fLastBlendWeight;

    // Skin tangent (to world space)
    // A tangent is also influenced by four bones. Tangents, like
    //   normals, cannot be transformed using the world matrix
    //   (because they end up with orientation problems if x,y,z
    //   scaling is not uniform). Tangents need to be transformed
    //   using the inverse-transpose matrix (mNormal). Otherwise, the transform
    //   is the same for tangents as it is for normals - each tangent
    //   is transformed into world space ( using the world matrix
    //   transpose ) resulting in 4 possible tangent vectors. Weights
    //   are used to combine all four tangent vectors into a final
    //   tangent vector.

    float3 vTangent =
        mul(v.vTangent, mNormal[v.vBlendIndices.x]) * v.vBlendWeights.x +
        mul(v.vTangent, mNormal[v.vBlendIndices.y]) * v.vBlendWeights.y +
        mul(v.vTangent, mNormal[v.vBlendIndices.z]) * v.vBlendWeights.z +
        mul(v.vTangent, mNormal[v.vBlendIndices.w]) * fLastBlendWeight;

    // Compute binormal
    // The binormal vector is the third axis in tangent space. You already
    //   have the vertex normal vector and the vertex tangent vector. So,
    //   a cross product will give you the third axis that is perpendicular
    //   to the other two axes. To generate an axis in left-handed
    //   coordinates, the result has to be flipped.

    float3 vBinormal = cross(vNormal, vTangent) * v.fFlip;

    // Light direction (to vertex space)
    // Load the vertex tangent, bi-normal, and normal unit vectors
    //   into a matrix for transforming the light direction vector.

    float3x3 mLight =
        float3x3(vTangent.x, vBinormal.x, vNormal.x,
                 vTangent.y, vBinormal.y, vNormal.y,
                 vTangent.z, vBinormal.z, vNormal.z);

    // Displace position
    // To find the final vertex position, move each vertex with
    // displacement data in the direction of the normal vector and
    // transform the vertices into projection space.

    o.vPosition = mul(float4(vPosition + vNormal * v.fDisplacement, 1),
                      mViewProj);

    // vDiffuse and vSpecular contain the lights diffuse and specular
    //   direction. This is a float3 vector. Theses direction vectors
    //   need to be transformed to projection space also. Once transformed,
    //   the direction vectors may contain components between -1 and +1.
    // Because they are being loaded into the pixel shader diffuse and
    //   specular registers, the data needs to be in the 0 to +1 range.
    // The data is converted by scaling (* 0.5) and biasing (+ 0.5)
    //   the data.

    o.vDiffuse  = mul(vDiffuse, mLight) * 0.5 + 0.5;
    o.vSpecular = mul(vSpecular, mLight) * 0.5 + 0.5;

    // No change is needed for the texture coordinates, so copy them
    //   as is to both sets of output texture coordinates.

    o.vTexCoord0.xy = o.vTexCoord1.xy = v.vTexCoords.xy;

    return o;
}

sampler DiffuseMap = sampler_state
{
Texture   = <tDiffuse>;
MinFilter = LINEAR;
MagFilter = LINEAR;
MipFilter = LINEAR;
};

sampler NormalMap = sampler_state
{
Texture   = <tNormal>;
MinFilter = LINEAR;
MagFilter = LINEAR;
MipFilter = LINEAR;
};

technique T0
{
    pass P0
    {
        // Vertex shader
        VertexShader = compile vs_1_1 main();

        // Pixel shader
        PixelShader =
            asm
            {
                ps_1_1
                tex t0
                tex t1

                // Specular
                dp3_sat r1, t1_bx2, v1_bx2
                dp3_x4  r0, t1_bx2, v0_bx2

                mul_sat r1, r1, r0
                mul_sat r1, r1, r1
                mul_sat r1, r1, c2

                // Diffuse + Ambient
                dp3_sat r0, t1_bx2, v0_bx2
                mad_sat r0, r0, c1, c0
                mad_sat r0, r0, t0, r1
            };

        PixelShaderConstant1[0] = <cAmbient>;
        PixelShaderConstant1[1] = <cDiffuse>;
        PixelShaderConstant1[2] = <cSpecular>;

        Sampler[0] = (DiffuseMap);
        Sampler[1] = (NormalMap);

        // Clip/Raster state
        CullMode = CW;
    }
}

Appendix

  • Keywords
  • Preprocessor Directives
  • Lexical Conventions
  • Language Syntax

Keywords

Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program. The following keywords are reserved. (Keywords marked with '*' are case insensitive.

asm* | bool | compile | const
decl * | do | double | else
extern | false | float | for
half | if | in | inline
inout | int | matrix | out
pass * | pixelshader | return | sampler
shared | static | string | struct
technique * | texture | true | typedef
uniform | vector | vertexshader | void
volatile | while |  |

The following keywords are unused, but are reserved.

asm* | bool | compile | const
auto | break | case | catch
char | class | const_cast | continue
default | delete | dynamic_cast | enum
explicit | friend | goto | long
mutable | namespace | new | operator
private | protected | public | register
reinterpret_cast | short | signed | sizeof
static_cast | switch | template | this
throw | try | typename | union
unsigned | using | virtual |

Preprocessor Directives

The preprocessor recognizes the following directives. These are all implemented to be compatible with the Microsoft Visual C++® preprocessor, except as noted below. Please refer to the Visual C++ documentation for a full description of these directives.

#define | #elif | #else | #endif
#error | #if | #ifdef | #ifndef
#include | #line | pragma | #undef
#row_major | #column_major |  |

Function-style #defines are not yet implemented. The following tokens are automatically defined.

#define D3DX
#define D3DX_VERSION 0x0900
#define DIRECT3D
#define DIRECT3D_VERSION 0x0900
#define __FILE__
#define __LINE__

The #include directive is valid only when compiling from a file. The filename specified can be either an absolute or relative path. If it is a relative path, it is assumed to be relative to the directory of the file issuing the #include. Because there is no concept of an INCLUDE path, the <filename> syntax is unsupported and invalid. Use "filename" instead.

There are no defined uses for the #pragma directive yet; unrecognized pragmas are silently ignored.

row_major and column_major specify how a matrix variable is stored. Some examples and their sizes:

row_major half1x4 fh1By4;
column_major half1x4 fh4By1;
row_major half3x2 fh3By2;
column_major half3x2 fh2By3;

//   matrix name   constant register   size
//     fh4By1            c620           4
//     fh3By2            c624           3
//     fh2By3            c627           2
//     fh1By4            c636           1

These can also be specified by compiler pragma's.

#pragma PACK_MATRIX (ROW_MAJOR)
#pragma PACK_MATRIX (COLUMN_MAJOR)

Register is used to specify a particular constant to associate with a variable. For instance:

float4 vColor : register(vs_2_0, c14) ;

associates the variable vColor with register c14.

Other examples include:

float4 vDisplace : register (c0); // puts the vDisplace constant into C0

It can be used in more complicated expressions like:

float4 vDisplace : register (c0)

which puts the vDisplace constant into C0 for pixel shader versions != 2.0.

float4 vDisplace : register(vs, c10)

which puts the vDisplace constant into C10 for all vertex shaders.

float4 vDisplace : register(ps_2_0, c10)

which puts the vDisplace constant into C10 for pixel shader version 2.0

Lexical Conventions

Whitespace

SPACE
TAB
EOL
C style comments (/* */)
C++ style comments (//)
Assembly style comments in asm blocks (;)

Floating point numbers

  • fractional-constant exponent-part(opt) floating-suffix(opt)

    digit-sequence exponent-part floating-suffix(opt)

  • fractional-constant :

    digit-sequence(opt) . digit-sequence

    digit-sequence .

  • exponent-part :

    e sign(opt) digit-sequence

    E sign(opt) digit-sequence

  • sign : one of

    + -

  • digit-sequence :

    digit

    digit-sequence digit

  • floating-suffix : one of

    h H f F

Integer numbers

  • integer-constant integer-suffix(opt)
  • integer-constant: one of

    # (decimal number)

    0# (octal number)

    0x# (hex number)

  • integer-suffix can be any one of these:

    u U l L

Characters

'c' | (character)
'\a' '\b' '\f' '\b' '\r' '\t' '\v' | (escapes)
'\###' | (octal escape, each # is an octal digit)
'\x#' | (hex escape, # is hex number, any number of digits)
'\c' | (c is other character, including backslash and quotation marks)

Escapes are not supported in preprocessor expressions.

Strings

"s" (s is any string with escapes).

Identifiers

    [A-Za-z_][A-Za-z0-9_]*

Operators

    ##, #@, ++, --, &&, ||, ==, ::, <<, <<=, >>, >>=, ...,
    <=, >=, !=, *=, /=, +=, -=, %=, &=, |=, ^=, ->

Also any other single character that did not match another rule.

Language Syntax

Program Options

///////////////////////////////////////////////////
Program         :
                | Decls
                ;
///////////////////////////////////////////////////
Decls           : Decl
                | Decl Decls
                ;
///////////////////////////////////////////////////
Decl            : TypeDecl
                | VariableDecl
                | VarStructDecl
                | FunctionDecl
                | TechniqueDecl
                ;
///////////////////////////////////////////////////

Usages

///////////////////////////////////////////////////
Usages          : Usage
                | Usage Usages
                ;
///////////////////////////////////////////////////
Usage           : T_KW_STATIC
                | T_KW_UNIFORM
                | T_KW_EXTERN
                | T_KW_VOLATILE
                | T_KW_INLINE
                | T_KW_SHARED
                | Target
                ;
///////////////////////////////////////////////////
UsageType       : Type
                | Usages Type
                ;
///////////////////////////////////////////////////
UsageStructDef  : StructDef
                | Usages StructDef
                ;
///////////////////////////////////////////////////

Types

TypeDecl        : T_KW_TYPEDEF Type TypeDefs ';'
                | StructDef ';'
                ;
///////////////////////////////////////////////////
TypeDefs        : VariableDim
                | VariableDim ',' TypeDefs
                ;
///////////////////////////////////////////////////
TypeDim         : Type
                | TypeDim '[' ConstantExpr ']'
                ;
///////////////////////////////////////////////////
Type            : SimpleType
                | T_KW_CONST SimpleType
                ;
///////////////////////////////////////////////////
SimpleType      : BaseType
                | Struct
                | TypeId
                ;
///////////////////////////////////////////////////
BaseType        : T_KW_VOID
                | ScalarType
                | VectorType
                | MatrixType
                | ObjectType
                ;
///////////////////////////////////////////////////
ScalarType      : T_KW_BOOL
                | T_KW_INT
                | T_KW_HALF
                | T_KW_FLOAT
                | T_KW_DOUBLE
                ;
///////////////////////////////////////////////////
VectorType      : T_KW_VECTOR
                | T_KW_VECTOR '<' ScalarType ',' AddExpr '>'
                ;
///////////////////////////////////////////////////
MatrixType      : T_KW_VECTOR
                | T_KW_VECTOR '<' ScalarType ',' ConstantExpr ',' AddExpr '>'
                ;
///////////////////////////////////////////////////
ObjectType      : T_KW_STRING
                | T_KW_TEXTURE
                | T_KW_SAMPLER
                | T_KW_PIXELSHADER
                | T_KW_VERTEXSHADER
                ;
///////////////////////////////////////////////////

Structures

///////////////////////////////////////////////////
Struct          : T_KW_STRUCT StructStart StructEnd
                | T_KW_STRUCT StructStart StructDecls StructEnd
                ;
///////////////////////////////////////////////////
StructDef       : SimpleStructDef
                | T_KW_CONST SimpleStructDef
                ;
///////////////////////////////////////////////////
SimpleStructDef : T_KW_STRUCT Id StructStart StructEnd
                | T_KW_STRUCT Id StructStart StructDecls StructEnd
                ;
///////////////////////////////////////////////////
StructStart     : '{'
                ;
///////////////////////////////////////////////////
StructDecls     : VariableDecl
                | VariableDecl StructDecls
                ;
///////////////////////////////////////////////////
StructEnd       : '}'
                ;
///////////////////////////////////////////////////

Annotations

///////////////////////////////////////////////////
Annotation      : AnnotationStart AnnotationEnd
                | AnnotationStart AnnotationDecls AnnotationEnd
                ;
///////////////////////////////////////////////////
AnnnotationStart : '{'
                 ;
///////////////////////////////////////////////////
AnnotationDecls : VariableDecl
                | VariableDecl AnnotationDecls
                ;
///////////////////////////////////////////////////
AnnotationEnd   : '}'
                ;
///////////////////////////////////////////////////

Variables

///////////////////////////////////////////////////
VariableDecl    : UsageType Variables ';'
                ;
///////////////////////////////////////////////////
VarStructDecl   : UsageStructDef Variables ';'
                ;
///////////////////////////////////////////////////
Variables       : Variable
                | Variable ',' Variables
                ;
///////////////////////////////////////////////////
Variable        : VariableAnn
                | VariableAnn '=' InitExpr
                ;
///////////////////////////////////////////////////
VariableAnn     : VariableSem
                | VariableSem Annotation
                ;
///////////////////////////////////////////////////
VariableSem     : VariableDim
                | VariableDim ':' Id
                ;
///////////////////////////////////////////////////
VariableDim     : Id
                | VariableDim '[' ConstantExpr ']'
                ;
///////////////////////////////////////////////////

Functions

///////////////////////////////////////////////////
FunctionDecl    : FunctionDef FunctionBody
                ;
///////////////////////////////////////////////////
FunctionDef     : UsageType Id ParamList
                | UsageType Id ParamList ':' Id
                ;
///////////////////////////////////////////////////
FunctionBody    : ';'
                | StmtBlock
                ;
///////////////////////////////////////////////////
ParamList       : ParamListStart ParamListEnd
                | ParamListStart T_KW_VOID ParamListEnd
                | ParamListStart ParameterDecls ParamListEnd
                ;
///////////////////////////////////////////////////
ParamListStart  : '('
                ;
///////////////////////////////////////////////////
ParamListEnd    : ')'
                ;
///////////////////////////////////////////////////
ParameterDecls  : ParameterDecl
                | ParameterDecl ',' ParameterDecls
                ;
///////////////////////////////////////////////////
ParameterDecl   : ParamUsageType Variable
                ;
///////////////////////////////////////////////////
ParamUsageType  : Type
                : ParamUsages Type
                ;
///////////////////////////////////////////////////
ParamUsages     : ParamUsage
                : ParamUsage ParamUsages
                ;
///////////////////////////////////////////////////
ParamUsages     : T_KW_IN
                : T_KW_OUT
                : T_KW_INOUT
                : T_KW_UNIFORM
                ;
///////////////////////////////////////////////////

Techniques

///////////////////////////////////////////////////
TechniqueDecl   : T_KW_TECHNIQUE TechniqueBegin TechniqueEnd
                | T_KW_TECHNIQUE Id TechniqueBegin TechniqueEnd
                ;
///////////////////////////////////////////////////
TechniqueBegin  : '{'
                ;
///////////////////////////////////////////////////
TechniqueEnd    : '}'
                | Passes '}'
                ;
///////////////////////////////////////////////////
Passes          : Pass
                | Pass Passes
                ;
///////////////////////////////////////////////////
Pass            : T_KW_PASS PassBegin PassEnd
                | T_KW_PASS Id PassBegin PassEnd
                | VariableDecl
                ;
///////////////////////////////////////////////////
PassBegin       : '{'
                ;
///////////////////////////////////////////////////
PassEnd         : '}'
                | States '}'
                ;
///////////////////////////////////////////////////
States          : State
                | State States
                ;
///////////////////////////////////////////////////
State           : Id StateExprBegin StateExpr StateExprEnd
                | Id '[' Uint ']' StateExprBegin StateExpr StateExprEnd
                ;
///////////////////////////////////////////////////
StateExprBegin  : '='
                ;
///////////////////////////////////////////////////
StateExprEnd    : DwordExpr ';'
                ;
///////////////////////////////////////////////////

Statements

SimpleStmt      : ';'
                | Expr ';'
                | T_KW_RETURN ';'
                | T_KW_RETURN Expr ';'
                | T_KW_DO Stmt T_KW_WHILE '(' Expr ')' ';'
                | StmtBlock
                ;
///////////////////////////////////////////////////
NonIfStmt       : SimpleStmt
                | T_KW_WHILE '(' Expr ')' NonIfStmt
                | T_KW_FOR '(' ForInit ForCond ForStep ')' NonIfStmt
                ;
///////////////////////////////////////////////////
Stmt            : SimpleStmt
                | T_KW_WHILE '(' Expr ')' Stmt
                | T_KW_FOR '(' ForInit ForCond ForStep ')' Stmt
                | T_KW_IF '(' Expr ')' Stmt
                | T_KW_IF '(' Expr ')' NonIfStmt T_KW_ELSE Stmt
                ;
///////////////////////////////////////////////////
ForInit         : ';'
                | Expr ';'
                | VariableDecl
                ;
///////////////////////////////////////////////////
ForCond         : ';'
                | Expr ';'
                ;
///////////////////////////////////////////////////
ForStep         :
                | Expr
                ;
///////////////////////////////////////////////////
DeclStmt        : TypeDecl
                | VariableDecl
                | VarStructDecl
                | Stmt
                ;
///////////////////////////////////////////////////
DeclStmts       : DeclStmt
                | DeclStmt DeclStmts
                ;
///////////////////////////////////////////////////
StmtBlock       : StmtBlockStart StmtBlockEnd
                | StmtBlockStart DeclStmts StmtBlockEnd
                ;
///////////////////////////////////////////////////
StmtBlockStart  : '{'
                ;
///////////////////////////////////////////////////
StmtBlockEnd    : '}'
                ;
///////////////////////////////////////////////////

Expressions

///////////////////////////////////////////////////
DwordExpr       : Dword
                | Dword '|' DwordExpr
                ;
///////////////////////////////////////////////////
StateExpr       : DwordExpr
                | ComplexExpr
                | '{' InitExprs '}'
                | '<' RelationalExpr '>'
                ;
///////////////////////////////////////////////////
SimpleExpr      : T_KW_TRUE
                | T_KW_FALSE
                | UINT
                | Float
                | String
                | NonTypeId
                ;
///////////////////////////////////////////////////
ComplexExpr     : '(' Expr ')'
                | TypeId '(' ArgumentExprs ')'
                | BaseType '(' ArgumentExprs ')'
                | NonTypeId '(' ArgumentExprs ')'
                | Asm
                | AsmDecl
                | AsmDecl Asm
                | T_KW_COMPILE Target NonTypeId '(' ArgumentExpr ')'
                ;
///////////////////////////////////////////////////
Primary         : SimpleExpr
                | ComplexExpr
                ;
///////////////////////////////////////////////////
PostfixExpr     : PrimaryExpr
                | PostfixExpr '[' Expr ']'
                | PostfixExpr '.' Id
                | PostfixExpr T_OP_INC
                | PostfixExpr T_OP_DEC
                ;
///////////////////////////////////////////////////
UnaryExpr       : PostfixExpr
                | T_OP_INC UnaryExpr
                | T_OP_DEC UnaryExpr
                | '!' CastExpr
                | '-' CastExpr
                | '+' CastExpr
                ;
///////////////////////////////////////////////////
CastExpr        : UnaryExpr
                | '(' TypeDim ')' CastExpr
                ;
///////////////////////////////////////////////////
MulExpr         : CastExpr
                | MulExpr '*' CastExpr
                | MulExpr '/' CastExpr
                | MulExpr '%' CastExpr
                ;
///////////////////////////////////////////////////
AddExpr         : MulExpr
                | AddExpr '+' MulExpr
                | AddExpr '-' MulExpr
                ;
///////////////////////////////////////////////////
RelationalExpr  : AddExpr
                | RelationalExpr '<' AddExpr
                | RelationalExpr '>' AddExpr
                | RelationalExpr T_OP_LE AddExpr
                | RelationalExpr T_OP_GE AddExpr
                ;
///////////////////////////////////////////////////
EqualityExpr    : RelationalExpr
                | EqualityExpr T_OP_EQ RelationalExpr
                | EqualityExpr T_OP_NE RelationalExpr
                ;
///////////////////////////////////////////////////
AndExpr         : EqualityExpr
                | AndExpr T_OP_AND EqualityExpr
                ;
///////////////////////////////////////////////////
OrExpr          : AndExpr
                | OrExpr T_OP_OR AndExpr
                ;
///////////////////////////////////////////////////
AssignmentExpr  : OrExpr
                | CastExpr '=' AssignmentExpr
                | CastExpr T_OP_ME AssignmentExpr
                | CastExpr T_OP_DE AssignmentExpr
                | CastExpr T_OP_RE AssignmentExpr
                | CastExpr T_OP_AE AssignmentExpr
                | CastExpr T_OP_SE AssignmentExpr
                ;
///////////////////////////////////////////////////
ConditionalExpr : AssignmentExpr
                | AssignmentExpr  '?' AssignmentExpr  ':' ConditionalExpr
                ;
///////////////////////////////////////////////////
ArgumentExprs   : ConditionalExpr
                | ConditionalExpr ',' ArgumentExprs
                ;
///////////////////////////////////////////////////
ArgumentExpr    : ArgumentExpr
                ;
///////////////////////////////////////////////////
ArgumentExprs   : ArgumentExpr
                ;
///////////////////////////////////////////////////
InitExpr        : ConditionalExpr
                | '{' InitExprs '}'
                ;
///////////////////////////////////////////////////
InitExprs       : InitExpr
                | InitExpr ',' InitExprs
                ;
///////////////////////////////////////////////////
ConstantExpr    : ConditionalExpr
                ;
///////////////////////////////////////////////////
Expr            : ConditionalExpr
                | ConditionalExpr ',' Expr
                ;
///////////////////////////////////////////////////

Tokens

///////////////////////////////////////////////////
Dword           : Uint
                | '-' Uint
                | Float
                | '-' Float
                | DwordId
                | Uint DwordId
                ;
///////////////////////////////////////////////////
DwordId         : Id
                | T_KW_TRUE
                | T_KW_FALSE
                | T_KW_TEXTURE
                ;
///////////////////////////////////////////////////
Id              : TypeId
                | NonTypeId
                ;
///////////////////////////////////////////////////
Target          : NonTypeId
                ;
///////////////////////////////////////////////////
Uint            : T_UINT
                | T_INT32
                | T_UINT32
                ;
///////////////////////////////////////////////////
Float           : T_FLOAT
                | T_FLOAT16
                | T_FLOAT32
                | T_FLOAT64
                ;
///////////////////////////////////////////////////
String          : T_STRING
                ;
///////////////////////////////////////////////////
TypeId          : T_TYPE_ID
                ;
///////////////////////////////////////////////////
NonTypeId       : T_NON_TYPE_ID
                ;
///////////////////////////////////////////////////
Asm             : T_KW_ASM '{'
                ;
///////////////////////////////////////////////////
AsmDecl         : T_KW_DECL '{'
                ;
///////////////////////////////////////////////////

© 2002 Microsoft Corporation. All rights reserved.


Effect Reference

Effects are a higher level abstraction that take advantage of vertex and pixel shaders to encapsulate rendering effects. Effects can be written with the high-level language or with the shader assembly language.

Here are the application programming interface (API) topics.

  • Interfaces
  • Functions
  • Structures
  • Constants

As an alternative to using the API to create effects, you can also use a command line compile tool. See Effect Command Line Compile.

Related Topics

  • Effect Format

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

Effects are implemented with the following interfaces.

  • ID3DXBaseEffect
  • ID3DXEffect
  • ID3DXEffectCompiler
  • ID3DXEffectPool
  • ID3DXInclude
Interface | Derives from | Derives from
 | ID3DXBaseEffect | IUnknown
ID3DXEffect | ID3DXBaseEffect | IUnknown
ID3DXCompileEffect | ID3DXBaseEffect | IUnknown
 | ID3DXEffectPool | IUnknown
 | ID3DXInclude | IUnknown

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect Interface

Provides methods for getting and setting effect parameters such as constants, functions, shaders, and techniques.

ID3DXBaseEffect Members

GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetDesc | Gets the effect description.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a nontransposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetString | Sets a string.
SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.

Interface Information

Inherits from | IUnknown
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffect

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParent,
    UINT Index
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParent,
    LPCSTR pName
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParent,
    LPCSTR pSemantic
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name or the semantic index cast to an LPCSTR.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParent,
    UINT ElementIndex
);

Parameters

hParent
[in] Handle of the parent array parameter. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParent or ElementIndex are invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::SetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrix Method

Sets a nontransposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    CONST LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::GetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXBaseEffect::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect Interface

Used to set and query effects, and to choose techniques. An effect object can contain multiple techniques to render the same effect.

ID3DXEffect Members

Begin | Begins the application of the technique.
CloneEffect | Creates a clone of an effect.
End | End the application of the technique.
FindNextValidTechnique | Searches for the next valid technique, starting at the technique after the specified technique.
GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetCurrentTechnique | Gets the current technique.
GetDesc | Gets the effect description.
GetDevice | Retrieves the device associated with the effect.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetPool | Gets a pointer to the pool of shared parameters.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
IsParameterUsed

Determines if a parameter is used by the technique.

OnLostDevice

Releases all references to video memory resources and deletes all state blocks.

OnResetDevice

Should be called after the device has been reset.

Pass | Applies the state settings for the specified pass of the technique.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a nontransposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetString | Sets a string.
SetTechnique

Sets the active technique.

SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.
ValidateTechnique | Validate a technique.

Remarks

The ID3DXEffect interface is obtained by calling D3DXCreateEffect, D3DXCreateEffectFromFile, or D3DXCreateEffectFromResource.

The LPD3DXEFFECT type is defined as a pointer to the ID3DXEffect interface.

typedef struct ID3DXEffect *LPD3DXEFFECT;

Interface Information

Inherits from | ID3DXBaseEffect
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffect, D3DXCreateEffectFromFile, D3DXCreateEffectFromResource

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::Begin Method

Begins the application of the technique.

Syntax

HRESULT Begin(

    UINT* pPasses,
    DWORD Flags
);

Parameters

pPasses
[out] Pointer to a value indicating the number of passes needed to render the current technique.
Flags
[in] DWORD that determines if state modified by an effect is saved and restored. The default value 0 specifies that ID3DXEffect::Begin and ID3DXEffect::End will save and restore all state modified by the effect (including pixel and vertex shader constants). This flag parameter can be set to one or both of the following flags.
  • D3DXFX_DONOTSAVESTATE - Device state is not saved and restored.
  • D3DXFX_DONOTSAVESHADERSTATE - Shader device state is not saved and restored.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This method returns the number of passes needed to render the technique. The application must incrementally call ID3DXEffect::Pass for each pass before drawing the geometry to which the effect needs to be applied. After all passes are rendered, ID3DXEffect::End must be called.

See Also

ID3DXEffect::End, ID3DXEffect::Pass

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::CloneEffect Method

Creates a clone of an effect.

Syntax

HRESULT CloneEffect(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXEFFECT* ppEffect
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.
ppEffect
[out] Pointer to an ID3DXEffect interface, containing the cloned effect.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::End Method

End the application of the technique.

Syntax

HRESULT End(VOID);

Return Value

This method always returns the value S_OK.

See Also

ID3DXEffect::Begin, ID3DXEffect::Pass

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::FindNextValidTechnique Method

Searches for the next valid technique, starting at the technique after the specified technique.

Syntax

HRESULT FindNextValidTechnique(

    D3DXHANDLE hTechnique,
    D3DXHANDLE* pTechnique
);

Parameters

hTechnique
[in] Unique identifier to a technique. See Handles. Specify NULL for this parameter to find the first valid technique.
pTechnique
[out] Pointer to an identifier for the next technique. NULL is returned if this is the last technique. See Handles.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

D3DXTECHNIQUE_DESC, ID3DXEffect::ValidateTechnique

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetCurrentTechnique Method

Gets the current technique.

Syntax

D3DXHANDLE GetCurrentTechnique(VOID);

Return Value

A unique identifier to the current technique. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetDevice Method

Retrieves the device associated with the effect.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count for the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetPool Method

Gets a pointer to the pool of shared parameters.

Syntax

HRESULT GetPool(

    LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Pointer to a ID3DXEffectPool object.

Return Value

This method always returns the value S_OK.

Remarks

Pools contain shared parameters between effects. See Cloning and Sharing.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::IsParameterUsed Method

Determines if a parameter is used by the technique.

Syntax

BOOL IsParameterUsed(

    D3DXHANDLE hParameter,
    D3DXHANDLE hTechnique
);

Parameters

hParameter
[in] Unique identifier for the parameter. See Handles.
hTechnique
[in] Unique identifier for the technique. See Handles.

Return Value

Returns TRUE if the parameter is being used and returns FALSE if the parameter is not being used.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::OnLostDevice Method

Releases all references to video memory resources and deletes all state blocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXEffect::OnResetDevice method called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called after the device has been reset, before any other methods are called.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::Pass Method

Applies the state settings for the specified pass of the technique.

Syntax

HRESULT Pass(

    UINT iPass
);

Parameters

iPass
[in] Identifies the pass to be applied.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

After calling Pass, the application must draw the geometry to the device to which the effect is set.

See Also

ID3DXEffect::Begin, ID3DXEffect::End

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetTechnique Method

Sets the active technique.

Syntax

HRESULT SetTechnique(

    D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique handle to the technique. See Handles.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::ValidateTechnique Method

Validate a technique.

Syntax

HRESULT ValidateTechnique(

    D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique identifier. See Handles.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXEffect::SetTechnique

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler Interface

The ID3DXEffectCompiler interface compiles an effect from a function or from a vertex shader.

ID3DXEffectCompiler Members

CompileEffect | Compile an effect.
CompileShader | Compile a shader from an effect that contains one or more functions.
GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetDesc | Gets the effect description.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetLiteral | Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetLiteral | Toggle the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.
SetMatrix | Sets a nontransposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetString | Sets a string.
SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.

Remarks

The ID3DXEffectCompiler interface is obtained by calling D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, or D3DXCreateEffectCompilerFromResource.

The LPD3DXEFFECT type is defined as a pointer to the ID3DXEffect interface.

typedef struct ID3DXEffectCompiler *LPD3DXEFFECTCOMPILER;

Interface Information

Inherits from | ID3DXBaseEffect
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::CompileEffect Method

Compile an effect.

Syntax

HRESULT CompileEffect(

    DWORD Flags,
    LPD3DXBUFFER *ppEffect,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

Flags
[in] Compile options. For more information, see D3DXSHADER.
ppEffect
[out, retval] Buffer containing the compiled effect. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

See Also

High-Level Shader Language

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::CompileShader Method

Compile a shader from an effect that contains one or more functions.

Syntax

HRESULT CompileShader(

    D3DXHANDLE hFunction,
    DWORD Target,
    DWORD Flags,
    LPD3DXBUFFER *ppShader,
    LPD3DXBUFFER *ppErrorMsgs,
    LPD3DXSHADER_CONSTANTTABLE *ppConstantTable
);

Parameters

hFunction
[in] Unique identifier to the function to be compiled. This value must not be NULL. See Handles.
Target
[in] Identifies the compile target. The compile target is the shader version encoded in a DWORD. Use the D3DVS_VERSION macro to generate the encoded version number. This method currently supports compiling a vertex shader only.
Flags
[in] Compile options. For more information, see D3DXSHADER.
ppShader
[out, retval] Buffer containing the compiled shader. The compiler shader is an array of DWORDs. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.
ppConstantTable
[out, retval] Pointer to the constant table. For more information about the contents of the constant table, see D3DXSHADER_CONSTANTTABLE. Alternatively, the constant table can be accessed using D3DXGetShaderConstantTable.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

This method compiles a shader from a function that is written in a C-like language. For more information, see High-Level Shader Language.

See Also

D3DXSHADER_CONSTANTINFO, D3DXSHADER_CONSTANTTABLE, D3DXGetShaderConstantTable

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetLiteral Method

Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

Syntax

HRESULT GetLiteral(

    D3DXHANDLE hParameter,
    BOOL* pLiteral
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
pLiteral
[out] Returns True if the parameter is a literal, and False otherwise.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

Usages and Literals, ID3DXEffectCompiler::SetLiteral

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetLiteral Method

Toggle the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

Syntax

HRESULT SetLiteral(

    D3DXHANDLE hParameter,
    BOOL Literal
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
Literal
[in] Set to True to make the parameter a literal, and False if the parameter can change value during the shader lifetime.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

Usages and Literals, ID3DXEffectCompiler::GetLiteral

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectPool Interface

Applications use the ID3DXEffectPool interface to identify parameters that are going to be shared across effects. See parameter sharing in Cloning and Sharing.

Interface Information

Inherits from | IUnknown
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInclude Interface

The ID3DXInclude interface is implemented by an application to provide callbacks for #include directives, which are in an effect created by the D3DXCreateEffect xxx functions.

ID3DXInclude Members

Close | Closes an include file. If ID3DXInclude::Open was successful, ID3DXInclude::Close is guaranteed to be called before the application programming interface (API) using this interface returns.
Open | Opens an include file.

Remarks

ID3DXInclude gives an application the ability to override default behaviour for #include directives.

This interface must be provided for effects containing #include directives, which are created with D3DXCreateEffect xxx functions that don't end with "FromFile."

Interface Information

Inherits from | Nothing
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInclude::Close Method

Closes an include file. If ID3DXInclude::Open was successful, ID3DXInclude::Close is guaranteed to be called before the application programming interface (API) using this interface returns.

Syntax

HRESULT Close(

    LPCVOID pData
);

Parameters

pData
[in] Pointer that was returned by the corresponding ID3DXInclude::Open call.

Return Value

The return values of this method are implemented by an application programmer. In general, the method show be programmed to return D3D_OK if no error occurs. Otherwise the method should return any error message which will cause the calling function (such as D3DXCompileShader) to return an error. One of the most common error returns is E_OUTOFMEMORY.

See Also

ID3DXInclude::Open

© 2002 Microsoft Corporation. All rights reserved.


ID3DXInclude::Open Method

Opens an include file.

Syntax

HRESULT Open(

    LPCSTR pName,
    LPCVOID *ppData,
    UINT *pBytes
);

Parameters

pName
[in] Name of the include file.
ppData
[in] Pointer to the returned buffer that contains the include directives. This pointer remains valid until ID3DXInclude::Close is called.
pBytes
[out] Number of bytes returned in ppData.

Return Value

The return values of this method are implemented by an application programmer. In general, the method show be programmed to return D3D_OK if no error occurs. Otherwise the method should return any error message which will cause the calling function (such as D3DXCompileShader) to return an error. One of the most common error returns is E_OUTOFMEMORY.

See Also

ID3DXInclude::Close

© 2002 Microsoft Corporation. All rights reserved.


Functions

There are several functions that help create and compile effects.

Functions

  • D3DXCreateEffect
  • D3DXCreateEffectCompiler
  • D3DXCreateEffectCompilerFromFile
  • D3DXCreateEffectCompilerFromResource
  • D3DXCreateEffectFromFile
  • D3DXCreateEffectFromResource
  • D3DXCreateEffectPool

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffect Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffect(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXBUFFER* ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a buffer containing the compiled effect.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectCompiler Function

Creates an effect from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffectCompiler(

    LPCSTR pSrcData,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCompiler *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

pSrcData
[in] Pointer to a buffer containing an effect description. This parameter supports both Unicode and ANSI strings. See Remarks.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffect interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also detemines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerW. Otherwise, the function call resolves to D3DXCreateEffectCompilerA since ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectCompilerFromFile Function

Creates an effect compiler from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffectCompilerFromFile(

    LPCSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCompiler *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromFileW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectCompilerFromResource Function

Creates an effect compiler from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffectCompilerFromResource(

    HMODULE hSrcModule,
    LPCSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCompiler *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectFromFile Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffectFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXEFFECT* ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Optional NULL-terminated array of preprocessor macro definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to a buffer containing the compiled effect. See ID3DXEffect.
ppCompilationErrors
[out] Returns a pointer to a buffer containing a listing of compile errors. See ID3DXBuffer.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromFileW. Otherwise, the function call resolves to D3DXCreateEffectFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectFromResource Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT D3DXCreateEffectFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXBUFFER* ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device.
hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a buffer containing the compiled effect.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectFromResourceA because ANSI strings are being used.

D3DXCreateEffectFromResource loads data from a resource of type RT_RCDATA. See MSDN for more information about Windows resources.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateEffectPool Function

Create an effect pool. A pool is used to share parameters between effects.

Syntax

HRESULT D3DXCreateEffectPool(

    LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Returns a pointer to the created pool.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

For effects within a pool, shared parameters with the same name share values.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Effect Structures

This section contains information about the structures used by effects.

  • D3DXEFFECT_DESC
  • D3DXEFFECTDEFAULT
  • D3DXEFFECTINSTANCE
  • D3DXFRAGMENT_DESC
  • D3DXFUNCTION_DESC
  • D3DXPARAMETER_DESC
  • D3DXPASS_DESC
  • D3DXSEMANTIC
  • D3DXTECHNIQUE_DESC

© 2002 Microsoft Corporation. All rights reserved.


D3DXEFFECT_DESC Structure

Describes an effect object.

Syntax

typedef struct _D3DXEFFECT_DESC {
    LPCSTR Creator;
    UINT Parameters;
    UINT Techniques;
    UINT Functions;
} D3DXEFFECT_DESC;

Members

Creator
String that contains the name of the effect creator.
Parameters
Number of parameters used for effect.
Techniques
Number of techniques that can render the effect.
Functions
Number of functions that can render the effect.

Remarks

An effect object can contain multiple rendering techniques and parameters for the same effect.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXEFFECTDEFAULT Structure

Effect default parameters.

Syntax

typedef struct _D3DXEFFECTDEFAULT {
    LPSTR pParamName;
    D3DXEFFECTDEFAULTTYPE Type;
    DWORD NumBytes;
    LPVOID pValue;
} D3DXEFFECTDEFAULT;

Members

pParamName
Parameter name.
Type
Data type in pValue. For more information, see D3DXEFFECTDEFAULTTYPE
NumBytes
Size, in bytes, of the data pointed to by pValue.
pValue
Pointer to the memory location that contains the data.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXEFFECTINSTANCE Structure

Data type for managing a set of default effect parameters.

Syntax

typedef struct _D3DXEFFECTINSTANCE {
    LPSTR pEffectFilename;
    DWORD NumDefaults;
    LPD3DXEFFECTDEFAULT pDefaults;
} D3DXEFFECTINSTANCE;

Members

pEffectFilename
Name of the effect file.
NumDefaults
Number of default parameters.
pDefaults
Pointer to an array of D3DXEFFECTDEFAULT elements, each of which contains an effect parameter.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFRAGMENT_DESC Structure

Describes an annotation used by an effect object.

Syntax

typedef struct D3DXFRAGMENT_DESC {
    LPCSTR Name;
    DWORD Target;
} D3DXFRAGMENT_DESC;

Members

Name
Fragment name.
Target
Fragment compile target. The compile target identifies the shader type (vertex or pixel) and the version number.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXFUNCTION_DESC Structure

Describes a function used by an effect.

Syntax

typedef struct D3DXFUNCTION_DESC {
    LPCSTR Name;
    UINT Annotations;
} D3DXFUNCTION_DESC;

Members

Name
Function name.
Annotations
Unused. This member will always be set to zero by ID3DXBaseEffect::GetFunctionDesc.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPARAMETER_DESC Structure

Describes a parameter used for an effect object.

Syntax

typedef struct _D3DXPARAMETER_DESC {
    LPCSTR Name;
    LPCSTR Semantic;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT Annotations;
    UINT StructMembers;
    DWORD Flags;
    UINT Bytes;
} D3DXPARAMETER_DESC;

Members

Name
Name of the parameter.
Semantic
Semantic meaning, also called the usage.
Class
Parameter class. Set this to one of the values in D3DXPARAMETER_CLASS.
Type
Parameter type. Set this to one of the values in D3DXPARAMETER_TYPE.
Rows
Number of rows in the array.
Columns
Number of columns in the array.
Elements
Number of elements in the array.
Annotations
Number of annotations.
StructMembers
Number of structure members.
Flags
Parameter attributes. See Constants.
Bytes
The size of the parameter, in bytes.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXPASS_DESC Structure

Describes a pass for an effect object.

Syntax

typedef struct _D3DXPASS_DESC {
    LPCSTR Name;
    UINT Annotations;
    DWORD VSVersion;
    DWORD PSVersion;
    UINT VSSemanticUsed;
    D3DXSEMANTIC VSSemantics[MAXD3DDECLLENGTH];
    UINT PSSemanticUsed;
    D3DXSEMANTIC PSSemantics[MAXD3DDECLLENGTH];
    UINT PSSamplersUsed;
    LPCSTR PSSampers[16];
} D3DXPASS_DESC;

Members

Name
String value used for the pass.
Annotations
Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Annotations.
VSVersion
Vertex shader version number. This can be NULL if there is no vertex shader.
PSVersion
Pixel shader version number. This can be NULL if there is no pixel shader.
VSSemanticUsed
The number of vertex shader semantics used.
VSSemantics
An array of the vertex shader semantics. See IDs and Semantics.
PSSemanticUsed
The number of pixel shader semantics used.
PSSemantics
An array of the pixel shader semantics. See IDs and Semantics.
PSSamplersUsed
The number of sampler registers used by pixel shaders.
PSSampers
An array of pixel shader samplers.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DXSEMANTIC Structure

Semantics map a parameter to vertex or pixel shader registers. They can also be optional descriptive strings attached to non-register parameters.

Syntax

typedef struct _D3DXSEMANTIC {
    UINT Usage;
    UINT UsageIndex;
} D3DXSEMANTIC;

Members

Usage
Options that identify how resources are used. See D3DUSAGE.
UsageIndex
Options that modify how the usage is interpreted. See Decoupling Vertex Shaders and Vertex Declarations.

Remarks

Semantics are required for vertex and pixel shader, input and output registers.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

IDs and Semantics

© 2002 Microsoft Corporation. All rights reserved.


D3DXTECHNIQUE_DESC Structure

Describes a technique used by an effect.

Syntax

typedef struct _D3DXTECHNIQUE_DESC {
    LPCSTR Name;
    UINT Passes;
    UINT Annotations;
} D3DXTECHNIQUE_DESC;

Members

Name
String that contains the technique name.
Passes
Number of rendering passes the technique requires. See Remarks.
Annotations
The number of annotations. See Annotations.

Remarks

Some video cards can render two textures in a single pass. However, if a card does not have this capability, it is often possible to render the same effect in two passes, using one texture for each pass.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Constants

These are shader and effect constants.

Effect Parameters

#define | Description
D3DX_PARAMETER_SHARED | The value of a parameter will be shared by all effects in the same namespace. Changing the value in one effect will change it in all shared effects. See Sharing Parameters.
D3DX_PARAMETER_LITERAL | This parameter is marked as a literal value. Literal parameters cannot change after compile, allowing the compiler to optimize their usage. Shared parameters cannot be marked as a literal. See Usages and Literals.
D3DX_PARAMETER_ANNOTATION | This parameter is marked as an annotation. See Annotations.

D3DX_PARAMETER_SHARED cannot be combined with LITERAL or ANNOTATION.

Effect parameter constants are used by D3DXPARAMETER_DESC.

D3DXHANDLE

Effects use handles to reference techniques, passes, annotations, and parameters.

typedef LPCSTR D3DXHANDLE

For more information, see Handles.

Shader State

#define | Description
D3DXFX_DONOTSAVESTATE | Device state is not saved when calling ID3DXEffect::Begin or restored when calling ID3DXEffect::End.
D3DXFX_DONOTSAVESHADERSTATE | Shader state is not saved when calling ID3DXEffect::Begin or restored when calling ID3DXEffect::End.

© 2002 Microsoft Corporation. All rights reserved.


Effect Format

This section contains reference information for the effect format.

An effect is made up of parameters, techniques, and functions.

  • Parameters
  • Techniques and Passes
  • Functions

These are made up of id's, semantics, annotations, etc.

  • Annotations
  • Cloning and Sharing
  • Expressions
  • Handles
  • IDs and Semantics
  • States
  • Usages and Literals
  • Validation

© 2002 Microsoft Corporation. All rights reserved.


Parameters

Parameters are effect variables.

Syntax

usage  type  id  [: semantic]  [< annotation(s) >]  [= expression];

Parameters can be read from and written to by the application with ID3DXEffect or ID3DXEffectCompiler.

Parameters can be referenced in functions and in techniques (specifically, in the right side of state assignments).

  • usage - Scope of the parameter. See Usages and Literals.
  • type - Any valid High-Level Shader Language type.
  • id - A unique identifier. See IDs and Semantics.
  • semantic - A tag following identifer rules that typically indicates the usage of the parameter. Must be a particular type. See IDs and Semantics.
  • annotations - Zero or more pieces of user-specific information. May be any type. See Annotations.
  • expression - Initializes the parameter's value. See Expressions.

Parameters can be initialized to any valid High-Level Shader Language expression that reduces to a literal value.

Parameter values are not changed by the execution of state assignment or function calls.

© 2002 Microsoft Corporation. All rights reserved.


Techniques and Passes

Techniques provide the rendering muscle. A technique encapsulates the effect state that determines a rendering style. A technique is made up of one or more passes.

Techniques

technique [ id ]  [< annotation(s) >]
    { pass(es) };
  • id - Optional unique identifier. See IDs and Semantics.
  • annotation - Zero or more optional pieces of user-specific information. See Annotations.
  • pass(es) - Zero or more passes. Each pass contains state assignments. See below.

Passes

A pass contains the state assignments required to render.

pass  [ id ]  [< annotation(s) >]
    { state assignment(s) }
  • id - Optional unique identifier. See IDs and Semantics.
  • annotation - One or more optional piece of user-specific information. See Annotations.
  • assignment(s) - Assign zero or more state values, or evaluate one or more expressions. See States and Expressions.

Passes ignore all but the last assignment in a set of repeated assignments to the same state.

© 2002 Microsoft Corporation. All rights reserved.


Functions

A function is the building block for a shader created in the high-level language. If you prefer to write shaders in a C-style language instead of in assembly language, you will want to write functions.

Syntax

type id ( [ parameters ] )
    { body }

Functions do not change parameter values in an effect.

  • type - Any valid High-Level Shader Language type.
  • id - A unique identifier. See IDs and Semantics.
  • parameters - Function parameters.
  • body - The body of the function.

Functions are built from the high-level language. See High-Level Shader Language.

© 2002 Microsoft Corporation. All rights reserved.


Annotations

Annotations are user-specific data that can be attached to any technique, pass, or parameter. An annotation is a flexible way to add information to individual parameters. The information can be read back and used any way the application chooses. An annotation can be any data type.

Syntax

type id = expression ;
  • type - Any valid High-Level Shader Language numeric or string type.
  • id - A unique identifier. See IDs and Semantics.
  • expression - Evaluate an expression. See Expressions.

Remarks

Restrictions for using annotations include that they:

  • Must be either numeric or strings.
  • Must always be initialized with a default value.
  • Can be associated with Techniques and Passes and top-level Parameters.
  • Can be written to and read from with either ID3DXEffect or ID3DXEffectCompiler.
  • Can be added with ID3DXEffect.
  • Cannot be referenced inside the effect.
  • Cannot have sub-semantics or sub-annotations.

© 2002 Microsoft Corporation. All rights reserved.


Cloning and Sharing

Cloning Parameters

Cloning has the following restrictions.

  • Clones inherit the original effect's pool. See the Sharing Parameters section.
  • Clones inherit the original effect's techniques, passes, parameters, and annotations (including all annotations added with ID3DXEffect).
  • Clones inherit the original effect's dynamically added annotations.
  • Cloning onto a new device will fail if the original effect's pool was not NULL and the original effect contained a shared device-dependent parameter (such as a texture or shader).

Sharing Parameters

A pool is a buffer that shares effect parameters between different effects. To add parameters to a pool, specify a shared usage when the effect is created.

A pool has the following restrictions.

  • A parameter is added to the pool the first time an effect containing that (shared) parameter is added to the pool.
  • A pool gets initial values from the first shared parameter; parameters shared subsequently get their values from the pool.
  • A parameter is deleted from the pool when all effect references to the shared parameter are released.
  • All effects in the pool that contain the same (shared) device-dependent parameter must have the same device.

NULL can be used to specify no pool, in which case no parameters are shared. This is almost equivalent to specifying a unique pool just for this effect. The single difference is that when the effect is cloned, the clone will not share its shared parameters with the original.

© 2002 Microsoft Corporation. All rights reserved.


Expressions

Expressions are mathematical or logical statements that are used on the right hand side of an equals sign. There are many types of expressions.

Expressions

  1. Variable Reference
    ( variable ) or < variable >
  2. Numeric Scalar
    scalar
  3. Numeric Expression
    ( numeric expression )

    All standard numeric HLL expressions are supported here.

  4. Constructor
    type ( constructor arguments )
  5. List of Initializers
    { scalar value [, scalar value ...  ] }

    The scalars must be literal scalar values.

    The number of initializers must be compatible with the variable (state) on the left hand side of the equals sign.

  6. OR Expression
    token [ | token ... ]

    The tokens must be compatible with the variable (state) on the left hand side of the equals sign.

    The tokens are not case sensitive.

  7. NULL
    NULL

    NULL can only be assigned to a shader, sampler, or a texture object.

  8. Assembly Block
    asm { code }

    PS Assembly Blocks must be assigned to the PIXELSHADER state.

    VS Assembly Blocks must be assigned to the VERTEXSHADER state.

  9. Sampler State Block
    sampler state { [ state = expression ; [ state = ... ] ] }

    Sampler state blocks are sequences of un-indexed sampler stage state or texture assignments.

    Sampler state blocks must be assigned to the SAMPLER effect state.

  10. High-Level Language Compile
    compile target entrypoint ( [ arguments ] )

    The vertex shader vs_m_n target indicates D3DVS_VERSION(m, n) vertex shader version. The pixel shader ps_m_n target indicates D3DPS_VERSION(m, n) pixel shader version.

    Vertex shader high-level language compile expressions can only be assigned to the VERTEXSHADER effect state. Pixel shader high-level language compile expressions can only be assigned to the PIXELSHADER effect state.

© 2002 Microsoft Corporation. All rights reserved.


Handles

Handles provide an efficient means for referencing the techniques, passes, annotations, and parameters with ID3DXEffectCompiler or ID3DXEffect. They are generated dynamically when you call functions of the form Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element].

While running a program, generating a handle to the same object multiple times will return the same handle back every time. But don't rely on the handle staying constant when you run your program multiple times. Also be aware that handles generated by different instances of ID3DXEffect and ID3DXEffectCompiler will be different.

If you view the header files, you'll notice that handles (D3DXHANDLEs) are technically string pointers. See Constants.

The handles that you pass into functions such as GetParameter[ByName|Element|BySemantic] or GetAnnotation[ByName] can be in three forms as follows:

  1. Handles that were returned by functions such as GetParameter[ByName|Element|BySemantic].
  2. Strings such as MyVariableName, MyTechniqueName, or MyArray[0].
  3. Handle = NULL. There are four cases.
    • If it is a method return value, the method failed to find the handle.
    • If a NULL handle is passed in as the first parameter of GetParameter[ByName|Element|BySemantic], the function returns a top-level parameter. Conversely, if the handle is non-NULL, the function returns a structure member or element identified by the handle.
    • If a NULL handle is passed in as the first argument of ValidateTechnique or the second argument of IsParameterUsed, the current technique is validated.
    • If a NULL handle is passed in as the first argument of FindNextValidTechnique, the search for a valid technique starts at the first technique in the effect.

Performance tip At the start of your application, perform an initialization pass to generate handles from the strings. From that point on, use only handles. Passing in strings instead of generated handles is slower.

Examples

Here are some examples using the Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element] functions to generate handles.

// Gets handle of second top-level parameter handle in the effect file
h1 = GetParameter(NULL, 1);

// Gets handle of the third struct member of MyStruct
h2 = GetParameter("MyStruct", 2);

// Gets handle of the third array element handle of MyArray
h3 = GetParameterElement("MyArray", 2);

// Gets handle of first member of h1 (that is, the second top-level param)
h4 = GetParameter(h1, 0);

// Gets handle of MyStruct.Data
h5 = GetParameterByName("MyStruct", "Data");
// or
h6 = GetParameterByName(NULL, "MyStruct.Data");

// Gets handle of MyStruct.Data.SubData
h7 = GetParameterByName("MyStruct.Data", "SubData");
// or
h8 = GetParameter(NULL, "MyArray[2]");

// Gets handle of fifth annotation of h1 (that is, second top-level param)
h9 = GetAnnotation(h1, 4);

// Gets handle of MyStruct's annotation, called Author
h10 = GetAnnotationByName("MyStruct", "Author");
// or
h11 = GetParameterByName(NULL, "MyStruct@Author");

© 2002 Microsoft Corporation. All rights reserved.


IDs and Semantics

An identifier (ID) is a unique identifier.

IDs

IDs have the following restrictions.

  • They must contain only upper and lower case letters, digits, and underscores.
  • They must not start with a digit.
  • They must be distinct from all keywords and other IDs in the same scope.
  • They are case sensitive.

Semantics

Parameter identifier tags that indicate a usage class. The usage class is how this parameter will typically be used by the application (or compiler). They provide a mechanism for adding user-specific information to a parameter.

Semantic strings have the following restrictions.

  • They must contain only upper and lower case letters, digits, and underscores.
  • They must not start with a digit.
  • They must be distinct from all keywords.
  • They are case sensitive.

© 2002 Microsoft Corporation. All rights reserved.


States

Effect states are used to initialize pipeline states in preparation for vertex and pixel processing.

effect state [ [index] ] = expression

Where:

  • effect states - Similar to the traditional fixed function pipeline states. A complete list of states is listed below.
  • [ [index] ] - Optional integer index. The index identifies a particular state within an array of effect states. The outer brackets indicate that an index is optional. If an index is used, be sure to use the inner brackets.
  • expression - State assignment expression. See Expressions.

Effect states can be broken up into the following categories.

  • Light States
  • Material States
  • Render States
    • Pixel Pipe Render States
    • Vertex Pipe Render States
  • Sampler States
  • Sampler Stage States
  • Shader States
  • Shader Constant States
    • Pixel Shader Constant States
    • Vertex Shader Constant States
  • Texture States
  • Texture Stage States
  • Transform States

Light States

To enable the best performance for applying an effect, all components of a light or a material should be specified in the effect file. States that you fail to declare are set to some default value because there is no way for Microsoft® Direct3D® to set light states individually.

Light state | Type | Values
LightAmbient[n] | float4 | See the Ambient member of D3DLIGHT9.
LightAttenuation0[n] | float | See the Attenuation0 member of D3DLIGHT9.
LightAttenuation1[n] | float | See the Attenuation1 member of D3DLIGHT9.
LightAttenuation2[n] | float | See the Attenuation2 member of D3DLIGHT9.
LightDiffuse[n] | float4 | See the Diffuse member of D3DLIGHT9.
LightDirection[n] | float3 | See the Direction member of D3DLIGHT9.
LightEnable[n] | bool | True of False. See the bEnable argument in IDirect3DDevice9::LightEnable.
LightFalloff[n] | float | D3DCOLORVALUE. See the Falloff member of D3DLIGHT9.
LightPhi[n] | float | See the Phi member of D3DLIGHT9.
LightPosition[n] | float3 | See the Position member of D3DLIGHT9.
LightRange[n] | float | See the Range member of D3DLIGHT9.
LightSpecular[n] | float4 | See the Specular member of D3DLIGHT9.
LightTheta[n] | float | See the Theta member of D3DLIGHT9.
LightType[n] | dword | Same value as the array of up to n D3DLIGHTTYPE values without the D3DLIGHT_ prefix.

Material States

States that you fail to declare are set to some default value because there is no way for Direct3D to set material states individually.

Material state | Type | Values
MaterialAmbient | float4 | Same value as Ambient.
MaterialDiffuse | float4 | Same value as Diffuse.
MaterialEmissive | float4 | Same value as Emissive.
MaterialPower | float | Same values as Power.
MaterialSpecular | float4 | Same value as Specular.

Render States

Render states are as follows:

Vertex Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render state | Type | Values
Ambient | float4 | Same values as D3DRS_AMBIENT.
AmbientMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_AMBIENTMATERIALSOURCE.
Clipping | bool | True or False. Same values as D3DRS_CLIPPING.
ClipPlaneEnable | dword | Bitwise combination of D3DCLIPPLANE0 - D3DCLIPPLANE5 macros. See D3DCLIPPLANEn and D3DRS_CLIPPLANEENABLE.
ColorVertex | bool | True or False. Same values as D3DRS_COLORVERTEX.
CullMode | dword | Same values as D3DCULL without the D3DCULL_ prefix.
DiffuseMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_DIFFUSEMATERIALSOURCE.
EmissiveMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_EMISSIVEMATERIALSOURCE.
FogColor | dword | Same values as D3DCOLOR. See D3DRS_FOGCOLOR.
FogDensity | float | Same values as D3DRS_FOGDENSITY.
FogEnable | bool | True or False. Same values as D3DRS_FOGENABLE.
FogEnd | float | Same values as D3DRS_FOGEND.
FogStart | float | Same values as D3DRS_FOGSTART.
FogTableMode | dword | Same values as D3DFOGMODE. See D3DRS_FOGTABLEMODE in D3DRENDERSTATETYPE.
FogVertexMode | dword | Same values as D3DFOGMODE without the D3DFOG_ prefix.
IndexedVertexBlendEnable | bool | True or False. Same values as D3DRS_INDEXEDVERTEXBLENDENABLE.
Lighting | bool | True or False. Same values as D3DRS_LIGHTING.
LocalViewer | bool | True or False. Same values as D3DRS_LOCALVIEWER.
MultiSampleAntialias | bool | Same values as D3DRS_MULTISAMPLEANTIALIAS.
MultiSampleMask | dword | Same values as D3DRS_MULTISAMPLEMASK.
NormalizeNormals | bool | True or False. Same values as D3DRS_NORMALIZENORMALS.
PatchSegments | float | Same values as nSegments in IDirect3DDevice9::SetNPatchMode.
PointScale_A | float | Same values as D3DRS_POINTSCALE_A.
PointScale_B | float | Same values as D3DRS_POINTSCALE_B.
PointScale_C | float | Same values as D3DRS_POINTSCALE_C.
PointScaleEnable | bool | Same values as D3DRS_POINTSCALEENABLE.
PointSize | float | Same values as D3DRS_POINTSIZE.
PointSize_Min | float | Same values as D3DRS_POINTSIZE_MIN.
PointSize_Max | float | Same values as D3DRS_POINTSIZE_MAX without the D3DRS_ prefix.
PointSpriteEnable | bool | True or False. Same values as D3DRS_POINTSPRITEENABLE.
RangeFogEnable | bool | True or False. Same values as D3DRS_RANGEFOGENABLE.
SpecularEnable | bool | True or False. Same values as D3DRS_SPECULARENABLE.
SpecularMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_SPECULARMATERIALSOURCE.
TweenFactor | float | Same values as D3DRS_TWEENFACTOR.
VertexBlend | dword | Same values as D3DVERTEXBLENDFLAGS without the D3DVBF_ prefix. See D3DRS_VERTEXBLEND.

Pixel Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render state | Type | Values
AlphaBlendEnable | bool | True or False. Same values as D3DRS_ALPHABLENDENABLE in D3DRENDERSTATETYPE.
AlphaFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ALPHAFUNC.
AlphaRef | dword | Same values as D3DRS_ALPHAREF.
AlphaTestEnable | dword | True or False. See D3DRS_ALPHATESTENABLE.
BlendOp | dword | Same values as D3DBLENDOP without the D3DBLENDOP_ prefix.
ColorWriteEnable | dword | Bitwise combination of RED|GREEN|BLUE|ALPHA. See D3DRS_COLORWRITEENABLE.
DepthBias | int | Same values as D3DRS_DEPTHBIAS.
DestBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
DitherEnable | bool | True or False. Same values as D3DRS_DITHERENABLE.
FillMode | dword | Same values as D3DFILLMODE without the D3DFILL_ prefix.
LastPixel | dword | True or False. See D3DRS_LASTPIXEL.
ShadeMode | dword | Same values as D3DSHADEMODE without the D3DSHADE_ prefix.
SrcBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
StencilEnable | bool | True or False. Same values as D3DRS_STENCILENABLE.
StencilFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILFAIL.
StencilFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_STENCILFUNC.
StencilMask | dword | Same values as D3DRS_STENCILMASK.
StencilPass | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILPASS.
StencilRef | int | Same values as D3DRS_STENCILREF.
StencilWriteMask | dword | Same values as D3DRS_STENCILWRITEMASK.
StencilZFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILZFAIL.
TextureFactor | dword | Same values as D3DCOLOR. Same values as D3DRS_TEXTUREFACTOR.
Wrap0 | dword | Same values as D3DRS_WRAP0 without the D3DDRS_ prefix in D3DRENDERSTATETYPE.
Wrap1 | dword | Same values as in D3DRS_WRAP1 without the D3DDRS_ prefix.
Wrap2 | dword | Same values as in D3DRS_WRAP2 without the D3DDRS_ prefix.
Wrap3 | dword | Same values as in D3DRS_WRAP3 without the D3DDRS_ prefix.
Wrap4 | dword | Same values as in D3DRS_WRAP4 without the D3DDRS_ prefix.
Wrap5 | dword | Same values as in D3DRS_WRAP5 without the D3DDRS_ prefix.
Wrap6 | dword | Same values as in D3DRS_WRAP6 without the D3DDRS_ prefix.
Wrap7 | dword | Same values as in D3DRS_WRAP7 without the D3DDRS_ prefix.
Wrap8 | dword | Same values as D3DRS_WRAP0 without the D3DDRS_ prefix in D3DRENDERSTATETYPE.
Wrap9 | dword | Same values as in D3DRS_WRAP1 without the D3DDRS_ prefix.
Wrap10 | dword | Same values as in D3DRS_WRAP2 without the D3DDRS_ prefix.
Wrap11 | dword | Same values as in D3DRS_WRAP3 without the D3DDRS_ prefix.
Wrap12 | dword | Same values as in D3DRS_WRAP4 without the D3DDRS_ prefix.
Wrap13 | dword | Same values as in D3DRS_WRAP5 without the D3DDRS_ prefix.
Wrap14 | dword | Same values as in D3DRS_WRAP6 without the D3DDRS_ prefix.
Wrap15 | dword | Same values as in D3DRS_WRAP7 without the D3DDRS_ prefix.
ZEnable | dword | Same values as D3DZBUFFERTYPE without the D3DZB_ prefix.
ZFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ZFUNC.
ZWriteEnable | bool | True or False. See D3DRS_ZWRITEENABLE.

Sampler States

State | Type | Values
Sampler | sampler | NULL, or a sampler state block.

Sampler Stage States

Sampler state | Type | Values
AddressU[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_ADDRESSU.
AddressV[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_ADDRESSV.
AddressW[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_ADDRESSW.
BorderColor[16] | float4 | D3DCOLORVALUE. Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_BORDERCOLOR.
MagFilter[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_MAGFILTER.
MaxAnisotropy[16] | dword | Same values as D3DSAMP_MAXANISOTROPY without the D3DSAMP_ prefix.
MaxMipLevel[16] | int | Same values as D3DSAMP_MAXMIPLEVEL without the D3DSAMP_ prefix.
MinFilter[16] | dword | Same values as D3DSAMP_MINFILTER without the D3DSAMP_ prefix.
MipFilter[16] | dword | Same values as D3DSAMP_MIPFILTER without the D3DSAMP_ prefix.
MipMapLodBias[16] | float | Same values as D3DSAMP_MIPMAPLODBIAS without the D3DSAMP_ prefix.
SRGBTexture | float | Same value as D3DSAMP_SRGBTEXTURE without the D3DSAMP_ prefix.

Shader States

Shader states are as follows:

Pixel Shader States

State | Type | Values
PixelShader | pixelshader | NULL, an assembly block, a compile target, or a pixel shader parameter.

Vertex Shader States

State | Type | Values
VertexShader | vertexshader | NULL, an assembly block, a compile target, or a pixel shader parameter.

Shader Constant States

Shader constant states are as follows:

Pixel Shader Constant States

State | Type | Values
PixelShaderConstant | float[m[n]] | m x n array of floats; m and n are optional.
PixelShaderConstant1 | float4 | One 4-D float.
PixelShaderConstant2 | float4x2 | Two 4-D floats.
PixelShaderConstant3 | float4x3 | Three 4-D floats.
PixelShaderConstant4 | float4x4 | Four 4-D floats.
PixelShaderConstantB | bool[m[n]] | m x n array of bools; m and n are optional.
PixelShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
PixelShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.

Vertex Shader Constant States

State | Type | Values
VertexShaderConstant | float[m[n]] | m x n array of floats. m and n are optional.
VertexShaderConstant1 | float4 | One 4-D float.
VertexShaderConstant2 | float4x2 | Two 4-D floats.
VertexShaderConstant3 | float4x3 | Three 4-D floats.
VertexShaderConstant4 | float4x4 | Four 4-D floats.
VertexShaderConstantB | bool[m[n]] | m x n array of bools. m and n are optional.
VertexShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
VertexShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.

Texture States

Texture state | Type | Values
Texture[8] | texture | NULL, or a texture parameter.

Texture Stage States

Type | Texture stage state | Values
AlphaOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_ALPHAOP.
AlphaArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG0.
AlphaArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG1.
AlphaArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG2.
ColorArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG0.
ColorArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG1.
ColorArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG2.
ColorOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_COLOROP.
BumpEnvLScale[8] | float | Same values as D3DTSS_BUMPENVLSCALE without the D3DTSS_TCI prefix.
BumpEnvLOffset[8] | float | Same values as D3DTSS_BUMPENVLOFFSET without the D3DTSS_TCI prefix.
BumpEnvMat00[8] | float | Same values as D3DTSS_BUMPENVMAT00.
BumpEnvMat01[8] | float | Same values as D3DTSS_BUMPENVMAT01.
BumpEnvMat10[8] | float | Same values as D3DTSS_BUMPENVMAT10.
BumpEnvMat11[8] | float | Same values as D3DTSS_BUMPENVMAT11.
ResultArg[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_RESULTARG.
TexCoordIndex[8] | dword | Same values as D3DTSS_TEXCOORDINDEX without the D3DTSS_TCI prefix.
TextureTransformFlags[8] | dword | Same values as D3DTEXTURETRANSFORMFLAGS values without the D3DTTFF_ prefix. See D3DTSS_TEXTURETRANSFORMFLAGS.

Transform States

Effects use transposed matrices for efficiency. You can provide transposed matrices to an effect, or an effect will automatically transpose the matrices before using them.

State | Type | Values
ProjectionTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_PROJECTION without the D3DTS_ prefix.
TextureTransform[8] | float4x4 | A 4x4 matrix of floats. Same values as D3DTRANSFORMSTATETYPE without the D3DTS_ prefix.
ViewTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_VIEW without the D3DTS_ prefix.
WorldTransform | float4x4 | A 4x4 matrix of floats.

© 2002 Microsoft Corporation. All rights reserved.


Usages and Literals

Usage

Usage is similar to a parameter's scope, because it defines the scope in which the parameter is valid.

Value | Description
const | The parameter will be constant within the scope of all functions. (Note that such parameters can still be written to with either ID3DXEffect or ID3DXEffectCompiler, because this occurs outside the scope of all functions.)
shared | The parameter will be shared in the effect pool.
static | The parameter will be invisible to the application, that is, you cannot access them from ID3DXEffectCompiler or ID3DXEffectCompiler.

Literals

Marking a parameter as literal indicates that its value will never change. This enables the effect compiler to do extra optimization.

Only non-shared top-level parameters can be marked as literal. Parameters can only be marked as literal with ID3DXEffectCompiler. Literal values cannot be set with ID3DXEffect.

© 2002 Microsoft Corporation. All rights reserved.


Validation

Validation is performed during the effect compile. To validate the current technique, specify NULL as the technique handle to be validated.

Validation will fail for any of the following:

  • If the specified technique handle does not exist.
  • If the application of any state in any pass of the technique fails.
  • If device validation fails after the application of all the states in any pass of the technique.
  • If the PIXELSHADER or VERTEXSHADER effect states are assigned invalid shaders in any pass of the technique.
  • If the device caps do not support cube mapping, and a TEXTURE effect state is assigned a value of type textureCUBE in any pass of the technique.
  • If the device caps do not support volume mapping and a TEXTURE effect state is assigned a value of type texture3D in any pass of the technique.

For more information, see States.

© 2002 Microsoft Corporation. All rights reserved.


Effect Command-Line Compile

Effects can be compiled into object files using the Fxc.exe utility in DXSDK/bin/DXUtils/ with a target of fx_2_0. The object file can then be used to create an effect directly, using D3DXCreateEffect. The usage is:

Usage: fxc <options> <file>

The switch options are as follows:

Switch option | Description
/T <target> | Target instruction set. The default value is vs_2_0.
/E <name> | Entrypoint name. The default value is main.
/Od | Disable optimizations.
/Vd | Disable validation.
/Zi | Enable debugging information.
/Zpr | Pack matrices in row-major order.
/Zpc | Pack matrices in column-major order.
/Fo <file> | Output object file.
/Fc <file> | Output listing of generated code.
/Fh <file> | Output header containing generated code.
/D <id>= <text> | Define macro.
/nologo | Suppress copyright message.

The valid targets are vs_1_1, vs_2_0, vs_2_sw, ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw, and fx_2_0.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput

This section provides information about the Microsoft® DirectInput® component of the Microsoft DirectX® application programming interface (API). The DirectInput API is used to process data from a keyboard, mouse, joystick, or other game controller.

Roadmap

Information on using DirectInput is presented in the following sections. Use this page to guide you through the documentation based on your level of experience as a DirectInput developer.

What's New in DirectInput. Summary of features new to this version of DirectX. Read this section if you've used DirectInput before but want to take advantage of the new capabilities.

Introduction to DirectInput. High-level overview of the capabilities of DirectInput and the steps you'll take to implement it. Start with this section if you're new to DirectInput.

Understanding DirectInput. Introduction to the objects and interfaces of DirectInput and how they are related to the Microsoft Windows® message system. Read this section if you're new to DirectInput.

Using DirectInput. Guide to the API. This section contains more detailed conceptual information than the previous two sections, as well as information about the API elements you'll use for setting up devices, retrieving data, and implementing force-feedback effects. If you're a novice, at least familiarize yourself with the contents of this section. Later, you can refer to topics as you need them. Use this section in conjunction with the DirectInput C/C++ Reference.

Programming Tips and Tools. Advanced programming topics and a guide to the DirectInput tools provided with the DirectX software development kit (SDK).

DirectInput C/C++ Tutorials. Step-by-step tutorials, often based on samples in the SDK. If you learn best from sample code, this is a good place to start after reading Introduction to DirectInput and Understanding DirectInput.

DirectInput C/C++ Samples. A guide to the DirectInput C/C++ samples included in the SDK, illustrating the use and capabilities of DirectInput.

DirectInput C/C++ Reference. Reference information for the API. Use this section when you need to know the details of an interface, method, structure, macro, or other element.

© 2002 Microsoft Corporation. All rights reserved.


What's New in DirectInput

Version 9.0 primarily includes compatibility improvements for Microsoft® DirectInput®. There are no application programming interface (API) changes.

To learn more about new features in Microsoft DirectX®, see What's New in DirectX 9.0.

Note For important information about using IDirectInput8::ConfigureDevices within a Microsoft Direct3D® 9.0 environment, see the IDirectInput8::ConfigureDevices Remarks.

© 2002 Microsoft Corporation. All rights reserved.


Introduction to DirectInput

Microsoft® DirectInput® is an application programming interface (API) for input devices including the mouse, keyboard, joystick, and other game controllers, as well as for force-feedback (input/output) devices.

This topic provides a brief overview of the capabilities of DirectInput and how to set it up in an application. It includes the following:

  • The Power of DirectInput
  • Getting Started with DirectInput

For a more comprehensive view of how DirectInput works, see Understanding DirectInput.

For a step-by-step guide to using the DirectInput API, see the following topics.

  • Using DirectInput
  • DirectInput C/C++ Tutorials

The Power of DirectInput

Apart from providing services for devices not supported by the Microsoft Win32® API, DirectInput gives faster access to input data by communicating directly with the hardware drivers rather than relying on Microsoft Windows® messages.

DirectInput enables an application to retrieve data from input devices even when the application is in the background. It also provides full support for any type of input device, as well as for force feedback.

Through action mapping, applications can retrieve input data without needing to know what kind of device is being used to generate it.

The extended services and improved performance of DirectInput make it a valuable tool for games, simulations, and other real-time interactive applications running under Windows.

DirectInput does not provide any advantages for applications that use the keyboard for text entry or the mouse for navigation. For more information, see Interaction with Windows.

Getting Started with DirectInput

This topic is an overview of what is involved in setting up and using DirectInput in a simple application.

For details and examples of these steps, see Using DirectInput and DirectInput C/C++ Tutorials.

Note To understand DirectInput, it is essential to understand the following terms.
  • DirectInput object: The root DirectInput interface.
  • Device: A keyboard, mouse, joystick, or other input device.
  • DirectInputDevice object: Code representing a keyboard, mouse, joystick, or other input device.
  • Device object: Code representing a key, button, trigger, and so on found on a DirectInput device object. Also called device object instance.

The following steps represent a simple implementation of DirectInput in which the application takes responsibility for ascertaining what device object (button, axis, and so on) generated each item of data.

  1. Create the DirectInput object. You use methods of this object to enumerate devices and create DirectInput device objects.
  2. Enumerate devices. This is not an essential step if you intend to use only the system mouse or keyboard. To ascertain what other input devices are available on the user's system, have DirectInput enumerate them. Each time DirectInput finds a device that matches the criteria you set, it gives you the opportunity to examine the device's capabilities. It also retrieves a unique identifier that you can use to create a DirectInput device object representing the device.
  3. Create a DirectInputDevice object for each device you want to use. To do this, you need the unique identifier retrieved during enumeration. For the system mouse or keyboard, you can use a standard globally unique identifier (GUID).
  4. Set up the device. For each device, first set the cooperative level, which determines the way the device is shared with other applications or the system. You must also set the data format used for identifying device objects, such as buttons and axes, within data packets. If you intend to retrieve buffered data—that is, events rather than states—you also need to set a buffer size. Optionally, at this stage you can retrieve information about the device and tailor the application's behavior accordingly. You can also set properties such as the range of values returned by joystick axes.
  5. Acquire the device. At this stage you tell DirectInput that you are ready to receive data from the device.
  6. Retrieve data. At regular intervals, typically on each pass through the message loop or rendering loop, get either the current state of each device or a record of events that have taken place since the last retrieval. If you prefer, you can have DirectInput notify you whenever an event occurs.
  7. Act on the data. The application can respond either to the state of buttons and axes or to events such as a key being pressed or released.
  8. Close DirectInput. Before exiting, your application should unacquire all devices and release them, then release the DirectInput object.

This is not the only approach to implementing DirectInput. To take advantage of the great variety of input devices available now and later, and to simplify configuration for the user, you can use action mapping.

By setting an action map for a device, you let DirectInput decide which device object to use for each application action. For example, instead of specifying that the throttle in your racing game must always be controlled by the y-axis, you can create an action called AXIS_THROTTLE and have DirectInput assign that action to the most appropriate axis available on the device. When you retrieve events, you identify them by their associated actions rather than by the device objects that generated them.

For more information, see Action Mapping.

© 2002 Microsoft Corporation. All rights reserved.


Understanding DirectInput

This topic covers the underlying structure of Microsoft® DirectInput® and its relationship to the Microsoft Windows® message system.

  • DirectInput Objects
  • Interaction with Windows

For practical information about how to implement the elements of DirectInput introduced here, see Using DirectInput.

DirectInput Objects

An input-only DirectInput implementation consists of the DirectInput object, which supports the IDirectInput8 Component Object Model (COM) interface, and a DirectInputDevice object for each input device that provides data. Each DirectInputDevice object in turn has device objects, which are individual controls or switches such as keys, buttons, or axes. Device objects are also called device object instances.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. In the DirectInput application programming interface (API), the word joystick means any type of input device other than a mouse or keyboard. A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

DirectInputDevice objects instantiate the IDirectInputDevice8 interface. The application ascertains the number and type of device objects available by using the IDirectInputDevice8::EnumObjects method. Individual device objects are not encapsulated as code objects, but are described in DIDEVICEOBJECTINSTANCE structures.

Force-feedback effects are represented by the IDirectInputEffect interface. Methods of this interface are used to create, modify, start, and stop effects.

All DirectInput interfaces are available in ANSI and Unicode versions. If "UNICODE" is defined during compilation, the Unicode versions are used.

Interaction with Windows

Because DirectInput works directly with the device drivers, it either suppresses or ignores Windows mouse and keyboard messages. It also ignores mouse and keyboard settings made by the user in Control Panel. It does, however, use the calibrations set for a joystick or other game controller.

DirectInput does not recognize keyboard character repeat settings. When using buffered data, DirectInput interprets each press and release as a single event with no repetition. When using immediate data, DirectInput is concerned only with the present physical state of the keys, not with keyboard events as interpreted by Windows.

DirectInput does not perform any character conversion or translation. For example, the SHIFT key is treated like any other key, not as a modifier of another keypress. Keys return the same identifiers regardless of the user's system language settings.

Under Windows 2000, acquiring the keyboard in exclusive mode prevents any applications that are subsequently launched from receiving keyboard data.

Because DirectInput works directly with the mouse driver, it bypasses the subsystem of Windows that interprets mouse data for windowed applications. Applications that rely on the Windows cursor for navigation should continue to use the standard Windows mouse messages and Microsoft Win32® functions.

When using the system mouse in exclusive mode, DirectInput suppresses mouse messages, and therefore Windows is unable to show the standard cursor.

DirectInput ignores Control Panel settings such as acceleration and swapped buttons. However, DirectInput recognizes settings in the driver itself. For example, if the user has a three-button mouse and uses the driver-utility software to make the middle button a double-click shortcut, DirectInput reports a click of the middle button as two clicks of the primary button.

© 2002 Microsoft Corporation. All rights reserved.


Using DirectInput

This topic is a guide to implementing Microsoft® DirectX®. It includes information about the following:

  • Creating DirectInput
  • DirectInput Device Enumeration

For a broader overview, see Understanding DirectInput.

For related information, see the following:

  • DirectInput Devices
  • DirectInput Device Data
  • Action Mapping
  • Force Feedback

Creating DirectInput

The first step in any Microsoft DirectInput® application is obtaining the IDirectInput8 interface. You can do this most easily by calling the DirectInput8Create function.

You should create a single DirectInput object and not release it until the application terminates.

DirectInput Device Enumeration

DirectInput can query the system for all available input devices, determine whether they are connected, and return information about them. This process is called enumeration.

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating a DirectInput Device, you can use predefined global variables when calling the IDirectInput8::CreateDevice method.

For all other input devices, and for systems with multiple keyboards or mouse devices, call IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics to enumerate available devices and find one that is suitable. You might also want to enumerate in order to give the user a choice of available devices.

The following is a sample implementation of the IDirectInput8::EnumDevices method:

/* lpdi is a valid IDirectInput8 interface pointer. */

GUID KeyboardGUID = GUID_SysKeyboard;

lpdi->EnumDevices(DIDEVTYPE_KEYBOARD,
                  DIEnumDevicesCallback,
                  &KeyboardGUID,
                  DIEDFL_ATTACHEDONLY);

The first parameter determines what types of devices are to be enumerated. It is NULL if you want to enumerate all devices, regardless of type; otherwise it is one of the DIDEVTYPE_* values described in DIDEVICEINSTANCE.

The second parameter is a pointer to a callback function to be called once for each device enumerated. This function can be declared by any name; the documentation uses the placeholder name DIEnumDevicesCallback.

The third parameter to the IDirectInput8::EnumDevices method is any 32-bit value that you want to pass into the callback function. In this example, it is a pointer to a variable of type globally unique identifier (GUID), passed in so that the callback can assign a keyboard instance identifier to this variable.

The fourth parameter is a flag to request enumeration of either all devices or only those that are attached (DIEDFL_ALLDEVICES or DIEDFL_ATTACHEDONLY).

If your application is using more than one input device, the callback function is a good place to initialize each device as it is enumerated. (For an example, see Tutorial 3: Using the Joystick.) You obtain the instance GUID of the device from the callback function. You can also perform other processing here, such as looking for particular subtypes of devices or adding the device name to a list box.

The following sample callback function checks for the presence of an enhanced keyboard and stops the enumeration as soon as it finds one. It assigns the instance GUID of the last keyboard found to the KeyboardGUID variable (the address of which was passed in the pvRef variable by the call to IDirectInput8::EnumDevices in the previous example), which can then be passed to IDirectInput8::CreateDevice.

BOOL  hasEnhanced;

BOOL CALLBACK DIEnumKbdCallback(LPCDIDEVICEINSTANCE lpddi,
                                LPVOID pvRef)
{
  *(GUID*) pvRef = lpddi->guidInstance;
  if (GET_DIDEVICE_SUBTYPE(lpddi->dwDevType) ==
                       DIDEVTYPEKEYBOARD_PCENH)
  {
    hasEnhanced = TRUE;
    return DIENUM_STOP;
  }
  return DIENUM_CONTINUE;
} // End of callback

The first parameter points to a DIDEVICEINSTANCE structure containing information about the device. This structure is created by DirectInput.

The second parameter points to data passed in from IDirectInput8::EnumDevices. In this case, it is a pointer to the variable KeyboardGUID. This variable was assigned a default value earlier, but it is given a new value each time a device is enumerated. It is not important what instance GUID you use for a single keyboard, but the code does illustrate a technique for retrieving an instance GUID from the callback.

Rather than saving the instance GUID so that you can create the DirectInputDevice later, you can save the device created by DirectInput during enumeration. For more information, see Creating a DirectInput Device.

The return value in the example indicates that enumeration is to stop if the sought-for device has been found, or continue otherwise. Enumeration automatically stops as soon as all devices have been enumerated.

For more information about enumerating devices by using IDirectInput8::EnumDevicesBySemantics, see Action Mapping.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput Devices

This section contains information about the code objects that represent devices such as a mouse, keyboards, or joysticks. The following topics are covered:

  • Acquiring Devices
  • Cooperative Levels
  • Creating a DirectInput Device
  • Device Capabilities
  • Device Data Formats
  • Device Object Enumeration
  • Device Properties
  • Device Setup

For information about how to retrieve and interpret data from devices, see DirectInput Device Data.

© 2002 Microsoft Corporation. All rights reserved.


Acquiring Devices

Acquiring a Microsoft® DirectInput® device means giving your application access to it. As long as a device is acquired, DirectInput is making its data available to your application. If the device is not acquired, you can manipulate its characteristics but not obtain any data.

Acquisition is not permanent. Your application might acquire and unacquire a device many times.

In certain cases, depending on the cooperative level, a device is unacquired automatically whenever the application moves to the background. The mouse is automatically unacquired when the user clicks a menu, because at this point Microsoft Windows® assumes control of the device.

You must unacquire a device before changing its properties. The only exception is that you can change the gain for a force-feedback device while it is in an acquired state.

The acquisition mechanism is needed for two reasons:

First, DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For instance, if the user has switched to another application with ALT+TAB and has used the input device in that application, your application needs to know that the input no longer belongs to it and that the state of the buffers might have changed. Or consider an application with the DISCL_FOREGROUND cooperative level. The user holds down the SHIFT key and switches to another application. Then the user releases the key and switches back to the first application. As far as the first application is concerned, the SHIFT key is still down. The acquisition mechanism, by telling the application that input was lost, enables it to recover from these conditions.

Second, because your application can alter the properties of the device, without safeguards DirectInput would have to check the properties each time you wanted to retrieve data. This would be very inefficient. Even worse, a potential disaster could happen such as a hardware interrupt accessing a data buffer just as you were changing the buffer size. Therefore DirectInput requires your application to unacquire the device before changing properties. When you reacquire it, DirectInput checks the properties and decides on the optimal way of transferring data from the device to the application. This is done only once, so the data retrieval methods can be very fast.

Since the most common cause of losing a device is that your application moves to the background, you may want to reacquire devices whenever your application is activated. Be careful, though, about relying on a WM_ACTIVATE handler at startup time. The first WM_ACTIVATE message will likely arrive when your window is being initialized before DirectInput has been set up. To ensure that the device is acquired at startup, call IDirectInputDevice8::Acquire as soon as the device has been initialized.

Even acquiring the device on activation of your program window might not cover all cases in which a device is unacquired, especially for devices other than the standard mouse or keyboard. Because your application might unacquire a device unexpectedly, you need a mechanism for checking the acquisition state before attempting to get data from the device. The Scrawl Sample does this in the OnMouseInput function, in which a DIERR_INPUTLOST error triggers a message to reacquire the mouse. (See also Tutorial 2: Using the Mouse.)

Attempting to reacquire a device that is already acquired does no harm. Redundant calls to IDirectInputDevice8::Acquire are ignored, and the device can always be unacquired with a single call to IDirectInputDevice8::Unacquire.

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want Windows to acquire the mouse, you must release it. The Scrawl Sample responds to a right-click by unacquiring the mouse, putting the Windows cursor in the same spot as its own, displaying a shortcut menu, and letting Windows handle the input until a menu choice is made.

© 2002 Microsoft Corporation. All rights reserved.


Cooperative Levels

The cooperative level of a device determines how the input is shared with other applications and with the Microsoft® Windows® system. You set it by using the IDirectInputDevice8::SetCooperativeLevel method, as in the following code example:

/* hwnd is the top-level window handle. */
lpdiDevice->SetCooperativeLevel(hwnd,
        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags.

Although Microsoft DirectInput® provides a default setting, you should still explicitly set the cooperative level because this is the only way to give DirectInput the window handle. Without this handle, DirectInput cannot react to situations that involve window messages, such as joystick recalibration.

The valid flag combinations are shown in the following table.

Flags | Notes
DISCL_NONEXCLUSIVE DISCL_BACKGROUND | The default setting
DISCL_NONEXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_BACKGROUND | Not valid for keyboard or mouse

For the keyboard, you can also include DISCL_NOWINKEY in combination with DISCL_NONEXCLUSIVE. This flag disables the Windows logo key so that users cannot inadvertently break out of the application. In exclusive mode, the Windows logo key is always disabled.

Note Even if the cooperative level for the application is disabling the Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The cooperative level has two main components: whether the device is being used in the foreground or the background, and whether it is being used exclusively or nonexclusively.

Foreground vs. Background

A foreground cooperative level means that the input device is available only when the application is in the foreground or, in other words, has the input focus. If the application moves to the background, the device is automatically unacquired, or made unavailable.

A background cooperative level really means foreground and background. A device with a background cooperative level can be acquired and used by an application at any time.

You will usually want to have foreground access only, since most applications are not designed to respond to input that takes place when another program is in the foreground.

While developing an application, it is useful to employ conditional compilation so that the background cooperative level is always set for debugging. This prevents your application from losing access to the device every time it moves to the background as you switch to the debugging environment.

Exclusive vs. Nonexclusive

In most cases, the fact that your application is using a device at the exclusive level does not mean that other applications cannot get data from the device. Also, an application that requests background exclusive mode may lose access if another application requests exclusive access. The application can regain access to the device by manually unacquiring the device and reaquiring it.

Consider the example of a music player that accepts input from a hand-held remote-control device, even when the application is running in the background. Now suppose you run a similar application that plays movies in response to signals from the same remote control. What happens when the user presses Play? Both programs start playing, which is probably not what the user wants. To prevent this from happening, each application should have the DISCL_EXCLUSIVE flag set so that only one of them can be running at a time.

To use force-feedback effects, an application must have exclusive access to the device.

Windows itself requires exclusive access to the system mouse. The reason is that system mouse events such as a click on an inactive window could force an application to unacquire the device, with potentially harmful results such as a loss of data from the input buffer. So when an application has exclusive access to the system mouse, created by passing GUID_SysMouse to IDirectInput8::CreateDevice, Windows is not allowed any access and no mouse messages are generated. A further side effect is that the cursor disappears.

© 2002 Microsoft Corporation. All rights reserved.


Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

The IDirectInput8::CreateDevice method is used to obtain a pointer to the IDirectInputDevice8 interface. Methods of this interface are then used to manipulate the device and obtain data.

The following code example, where lpdi is a pointer to the IDirectInput8 interface, creates a keyboard device:

LPDIRECTINPUTDEVICE8  lpdiKeyboard;

lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL);

The first parameter in IDirectInput8::CreateDevice is an instance globally unique identifier (GUID) that identifies the instance of the device for which the interface is to be created. Microsoft® DirectInput® has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass one of these identifiers into the IDirectInput8::CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for IDirectInput8::CreateDevice because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing.

  • GUID_SysKeyboardEm

  • GUID_SysKeyboardEm2

  • GUID_SysMouseEm

  • GUID_SysMouseEm2.

Passing one of these GUIDs to IDirectInput8::CreateDevice grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in later sessions.

© 2002 Microsoft Corporation. All rights reserved.


Device Capabilities

Before you begin asking for input from a device, you need to know something about its capabilities. Does the joystick have a point-of-view hat? Is the mouse currently attached to the user's computer?

Such questions are answered with a call to the IDirectInputDevice8::GetCapabilities method, which returns the data in a DIDEVCAPS structure. As with other such structures in Microsoft® DirectX®, you must initialize the dwSize member before passing this structure to the method.

Note To optimize speed or memory usage, you can use the smaller DIDEVCAPS_DX3 structure instead. For structure details, see Dinput.h.

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel). Assume that lpdiMouse is a valid Microsoft DirectInput® device.

DIDEVCAPS  DIMouseCaps;
HRESULT    hr;
BOOLEAN    WheelAvailable;

DIMouseCaps.dwSize = sizeof(DIDEVCAPS);
hr = lpdiMouse->GetCapabilities(&DIMouseCaps);
WheelAvailable = ((DIMouseCaps.dwFlags & DIDC_ATTACHED)
        && (DIMouseCaps.dwAxes > 2));

Another way to check for a button or axis is to call IDirectInputDevice8::GetObjectInfo for that object. If the call returns DIERR_OBJECTNOTFOUND, the object is not present. The following code determines whether there is a z-axis, even if it is not the third axis:

DIDEVICEOBJECTINSTANCE  didoi;

didoi.dwSize = sizeof(DIDEVICEOBJECTINSTANCE);
hr = lpdiMouse->GetObjectInfo(&didoi, DIMOFS_Z, DIPH_BYOFFSET);
WheelAvailable = SUCCEEDED(hr);

© 2002 Microsoft Corporation. All rights reserved.


Device Data Formats

If you are not using Action Mapping, setting the data format for a device is an essential step before you can acquire and begin using the device. This is true even if you do not intend to retrieve immediate (state) data from the device. Microsoft® DirectInput® uses the data format in many methods to identify particular device objects.

The IDirectInputDevice8::SetDataFormat method tells DirectInput what device objects will be used and how the data will be arranged.

The examples in the reference for the DIDATAFORMAT and DIOBJECTDATAFORMAT structures show how to set up custom data formats for nonstandard devices. Fortunately, this step is not necessary for the joystick, keyboard, and mouse. DirectInput provides five global variables, c_dfDIJoystick, c_dfDIJoystick2, c_dfDIKeyboard, c_dfDIMouse, and c_dfDIMouse2, which can be passed in to IDirectInputDevice8::SetDataFormat to create a standard data format for these devices.

In the following code example, lpdiMouse is an initialized pointer to a DirectInputDevice object:

lpdiMouse->SetDataFormat(&c_dfDIMouse);
Note You cannot change the dwFlags member in the predefined DIDATAFORMAT global variables (for example, to change the property of an axis), because they are const variables. To change properties, use the IDirectInputDevice8::SetProperty method after setting the data format, but before acquiring the device.

© 2002 Microsoft Corporation. All rights reserved.


Device Object Enumeration

It might be necessary for your application to determine what buttons or axes are available on a given device. To do this, you enumerate the device objects in much the same way as you enumerate devices.

Note Because of limitations imposed by device drivers, enumeration of keyboard keys and indicator lights is not reliable. Objects might falsely be reported as present. You can get basic information about available keys from the device subtype, but there is no way to determine whether extra objects such as the menu key are available, other than asking the user for input.

To some extent, IDirectInputDevice8::EnumObjects overlaps the functionality of IDirectInputDevice8::GetCapabilities. Either method can be used to determine how many buttons or axes are available. However, IDirectInputDevice8::EnumObjects is intended for cataloging all the available objects rather than checking for a particular one.

Like IDirectInput8::EnumDevices, the IDirectInputDevice8::EnumObjects method has a callback function that enables you to do other processing on each object—for example, adding it to a list or creating a corresponding element on a user interface.

The following sample callback extracts the name of each object so that it can be added to a string list or array. This standard callback is documented under the placeholder name DIEnumDeviceObjectsCallback, but you can give it any name you like. Remember, this function is called once for each object enumerated.

char  szName[MAX_PATH];

BOOL CALLBACK DIEnumDeviceObjectsCallback(
                      LPCDIDEVICEOBJECTINSTANCE lpddoi,
                      LPVOID pvRef)
{
  HRESULT hr = StringCchCopy(szName, MAX_PATH, lpddoi->tszName);
  if(SUCCEEDED(hr))
  {
     // Now add szName to a list or array.
     .
     .
     .
  }
  else
     // Handle errors.

  return DIENUM_CONTINUE;
}

The first parameter points to a structure containing information about the object. This structure is created for you by Microsoft® DirectInput®.

The second parameter is an application-defined pointer to data, equivalent to the second parameter to IDirectInputDevice8::EnumObjects. In the example, this parameter is not used.

The return value in this case indicates that enumeration is to continue as long as there are objects to be enumerated.

Now here's the call to the IDirectInputDevice8::EnumObjects method, which puts the callback function to work.

lpdiMouse->EnumObjects(DIEnumDeviceObjectsCallback,
                       NULL, DIDFT_ALL);

The first parameter is the address of the callback function. The second parameter can be a pointer to any data you want to use or modify in the callback. The example does not use this parameter and so passes NULL. The third parameter is a flag to indicate which type or types of objects are to be included in the enumeration. In the example, all objects are to be enumerated. To restrict the enumeration, you can use one or more of the other DIDFT_* flags listed at IDirectInputDevice8::EnumObjects.

Note Some of the DIDFT_* flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS | DIDFT_RELAXIS.

When an application has exclusive access to the keyboard, DirectInput suppresses all keyboard messages except CTRL+ALT+DEL and, on Microsoft Windows® 95 and Windows 98, ALT+TAB. Under Windows 2000, no application launched subsequently to the exclusive-mode DirectInput application can get keyboard data.

© 2002 Microsoft Corporation. All rights reserved.


Device Properties

Properties of Microsoft® DirectInput® devices include the size of the data buffer, the range and granularity of values returned from an axis, whether axis data is relative or absolute, and the dead zone and saturation values for a joystick axis. Specialized devices can have other properties as well. For a list of properties defined by DirectInput, see IDirectInputDevice8::GetProperty.

With one exception—the gain property of a force-feedback device—properties can be changed only when the device is in an unacquired state.

Before calling the IDirectInputDevice8::SetProperty or the IDirectInputDevice8::GetProperty method you must set up a property structure that consists of a DIPROPHEADER structure and one or more elements for data. There is potentially a great variety of properties for input devices, and IDirectInputDevice8::SetProperty must be able to work with all sorts of structures defining those properties. The purpose of the DIPROPHEADER structure is to define the size of the property structure and how the data is to be interpreted.

DirectInput includes the following predefined property structures:

  • DIPROPDWORD defines a structure containing a DIPROPHEADER and a DWORD data member for properties that require a single value, such as a buffer size.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). It consists of a DIPROPHEADER and two LONG data members.
  • DIPROPGUIDANDPATH is a specialized property structure that enables applications to perform operations on a Human Interface Device (HID) that is not supported by DirectInput. The structure consists of a DIPROPHEADER, a globally unique identifier (GUID), and a Unicode string for the path.
  • DIPROPSTRING is for Unicode string properties. The structure comprises a DIPROPHEADER and a Unicode string.

For IDirectInputDevice8::SetProperty, the data members of the property structure are the values that you want to set. For IDirectInputDevice8::GetProperty, the current value is returned in these members.

Before the call to IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, the DIPROPHEADER structure must be initialized with the following:

  • The size of the property structure.
  • The size of the DIPROPHEADER structure itself.
  • An object identifier.
  • A value indicating how the object identifier should be interpreted.

When getting or setting properties for a whole device, the object identifier dwObj is 0, and the dwHow member is DIPH_DEVICE. If you want to get or set properties for a device object (for example, a particular axis), the combination of dwObj and dwHow values identifies the object. For details, see DIPROPHEADER.

After setting up the property structure, pass the address of its header into IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, along with an identifier for the property that you want to obtain or change.

The following values are used to identify the property passed to IDirectInputDevice8::SetProperty and IDirectInputDevice8::GetProperty.

  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data. The buffer size can also be set by using the IDirectInputDevice8::SetActionMap method.
  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_CALIBRATIONMODE
  • DIPROP_GRANULARITY
  • DIPROP_FFGAIN
  • DIPROP_FFLOAD
  • DIPROP_AUTOCENTER
  • DIPROP_RANGE
  • DIPROP_DEADZONE
  • DIPROP_SATURATION

For more information about the last three properties, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device to hold up to 10 data items:

DIPROPDWORD  dipdw;
HRESULT      hr;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 10;
hr = lpdiDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

© 2002 Microsoft Corporation. All rights reserved.


Device Setup

Your application must obtain a Microsoft® DirectInput® device object for each device from which it expects input. It must also prepare each device for use, which requires, at the very least, setting the data format and acquiring the device. You might also want to carry out other preparatory tasks such as getting information about the devices and changing their properties.

The following tasks are part of the setup process. Certain steps are always required. Other steps may be necessary if you need further information about devices or need to change default values.

  1. Create the DirectInput device (required). See Creating a DirectInput Device.
  2. Get the device capabilities (optional).
  3. Enumerate the keys, buttons, and axes on the device (optional). See Device Object Enumeration.
  4. Set the cooperative level (highly recommended).
  5. Set the data format (required).
  6. Set the device properties (you must at least set the buffer size if you intend to get buffered data).
  7. When ready to read data, acquire the device (required). See Acquiring Devices.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput Device Data

This section covers the following basic concepts of getting data from Microsoft® DirectInput® devices.

Overviews

  • Buffered and Immediate Data
  • Polling and Event Notification
  • Relative and Absolute Axis Coordinates
  • Time Stamps and Sequence Numbers

The following topics describe specific details about output data and mouse, keyboard, and joystick input data.

  • Joystick Data
  • Keyboard Data
  • Mouse Data
  • Output Data

DirectInput provides two mechanisms for identifying data retrieved from devices. Using the traditional mechanism, the application identifies the data as coming from a particular device object, such as a the x-axis on a mouse or the F1 key on a keyboard. With the newer system, available for the first time in Microsoft DirectX® 8.0, DirectInput associates application-defined values (for instance, identifiers for particular game actions such as moving or shooting) with the most suitable device objects available. When data is retrieved, the application does not concern itself with the actual device or device object from which the data comes. It acts only on the meaning of that data.

Most of the information in this section applies to both mechanisms. For more information about the newer way of identifying device data, see Action Mapping.

© 2002 Microsoft Corporation. All rights reserved.


Buffered and Immediate Data

Microsoft® DirectInput® supplies two types of data: buffered and immediate. Buffered data is a record of events that are stored until an application retrieves them. Immediate data is a snapshot of the current state of a device.

You might use immediate data in an application that is concerned only with the current state of a device—for example, a flight combat simulation that responds to the current position of the joystick and the state of one or more buttons. Buffered data might be the better choice where events are more important than states—for example, in an application that responds to movement of the mouse and button clicks. You can also use both types of data, as you might, for example, if you wanted to get immediate data for joystick axes but buffered data for the buttons.

Note If you are using Action Mapping, you will want to retrieve buffered data because the buffered data packets contain the application-defined data associated with the input. Doing so means that you are responsible for tracking the position of absolute axes, since events but not states are reported in buffered data packets.

An application retrieves immediate data by calling the IDirectInputDevice8::GetDeviceState method. As the name implies, this method returns the current state of the device—for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. For example, if a user presses and releases a button between two calls to IDirectInputDevice8::GetDeviceState, your application will never be given this input. On the other hand, if the user is holding a button down, IDirectInputDevice8::GetDeviceState continues reporting that fact until the user releases it.

This way of reporting the device state is different from the way Microsoft Windows® reports events with one-time messages such as WM_LBUTTONDOWN. It is more like the results from the Microsoft Win32® GetKeyboardState function. If you are polling a device with IDirectInputDevice8::GetDeviceState, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it's not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA structure in the buffer. If the buffer overflows, new data is lost. Your application reads the buffer with a call to IDirectInputDevice8::GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of peeking without deleting.

To get buffered data, you must first set the buffer size with the IDirectInputDevice8::SetProperty or IDirectInputDevice8::SetActionMap method. (See the example under Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes.

Check the value of the pdwInOut parameter after a call to the IDirectInputDevice8::GetDeviceData method. The number of items retrieved from the buffer is returned in this variable.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the IDirectInputDevice8::Poll method. For more information, see Polling and Event Notification.

For examples of retrieving buffered data, see IDirectInputDevice8::GetDeviceData.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data

© 2002 Microsoft Corporation. All rights reserved.


Polling and Event Notification

There are two ways to find out whether input data is available: polling and event notification.

Polling a device means regularly getting the current state of the device objects or checking the contents of the event buffer. Polling is typically used by real-time games that are never idle, but instead are constantly updating and rendering the game world.

Polling

In a C++ application, polling would typically be done within the message loop.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the IDirectInputDevice8::Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. IDirectInputDevice8::Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call IDirectInputDevice8::Poll each time you want to retrieve data, first set the data format for the device, then call the IDirectInputDevice8::GetCapabilities method and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS structure.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling, regardless of data format. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice8::GetObjectInfo method and checking for the DIDOI_POLLED flag in the DIDEVICEOBJECTINSTANCE structure.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, a Human Interface Device (HID) mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. If you want to retrieve only the standard button and axis data, polling the device under these conditions is not necessary. However, there is no harm in calling the IDirectInputDevice8::Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.

Event Notification

Event notification is suitable for applications such as the Scrawl Sample that wait for input before doing anything.

To use event notification, set up a thread-synchronization object with the Microsoft® Win32® CreateEvent function, and then associate this event with the device by passing its handle to the IDirectInputDevice8::SetEventNotification method. The event is then signaled by Microsoft DirectInput® whenever the state of the device changes. Your application can receive notification of the event with a Win32 function such as WaitForSingleObject, and then respond by checking the input buffer to find out what the event was. For code examples, see the Scrawl Sample and IDirectInputDevice8::SetEventNotification.

© 2002 Microsoft Corporation. All rights reserved.


Relative and Absolute Axis Coordinates

Axis coordinates can be returned as relative values—that is, the amount by which they have changed since the application last retrieved the device state or, in the case of buffered input, since the last item was put in the buffer.

Absolute axis coordinates are a running total of all the relative coordinates returned by the system since the device was acquired. In other words, they show the position of the axis in relation to a fixed point.

By default, mouse axes are reported as relative coordinates and joystick axes as absolute coordinates. You can change the coordinate system for a device by setting a property. For more information, see Device Properties.

© 2002 Microsoft Corporation. All rights reserved.


Time Stamps and Sequence Numbers

When Microsoft® DirectInput® input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA structure contains not only information about the type of event and the device object associated with it. It also contains a time stamp and a sequence number.

The dwTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Microsoft Win32® GetTickCount function, but at a higher resolution.

The dwSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each buffered event from any device. (Simultaneous events on the same device, such as diagonal mouse movements, increment the count only once.) Use this number to compare events from different devices and see which came first. The DISEQUENCE_COMPARE macro, used for comparing DirectInput sequence numbers, takes wraparound into account.

Note Events are always placed in the buffer in chronological order, so you don't need to check the sequence numbers to sort the events from a single device.

© 2002 Microsoft Corporation. All rights reserved.


Joystick Data

To set up the joystick device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIJoystick or the c_dfDIJoystick2 global variable as the parameter value. (See Device Data Formats.)

Because some device drivers do not notify Microsoft® DirectInput® of changes in state until explicitly asked to do so, you should always call the IDirectInputDevice8::Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Event Notification.

The following sections cover retrieval and interpretation of data from a joystick or other similar input device such as a game pad or steering wheel:

  • Buffered Joystick Data
  • Checking for Lost Joystick Input
  • Immediate Joystick Data
  • Interpreting Joystick Axis Data
  • Using CPOINTs

© 2002 Microsoft Corporation. All rights reserved.


Buffered Joystick Data

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties) and declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the IDirectInputDevice8::GetDeviceData method.(See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the following values:

  • DIJOFS_X
  • DIJOFS_Y
  • DIJOFS_Z
  • DIJOFS_Rx
  • DIJOFS_Ry
  • DIJOFS_Rz
  • DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n)
  • DIJOFS_POV(n)
  • DIJOFS_SLIDER(n)

Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE structure. For example, DIJOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIJOYSTATE structure. You can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* JoyBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &JoyBuffer[n];
if (( (int) lpdidod->dwOfs == DIJOFS_BUTTON0)
   && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to press of primary button.
}

If the data format was set with c_dfDIJoystick2, you can use the predefined offsets for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button is pressed, and it is clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.

© 2002 Microsoft Corporation. All rights reserved.


Checking for Lost Joystick Input

If your application is using the joystick in foreground mode (see Cooperative Levels), it will lose the device when the focus shifts to another application.

Check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method and attempt to reacquire the joystick, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the joystick on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail again, you would get another DIERR_NOTACQUIRED error, and so on.

Because access to the joystick is not lost except when your application moves to the background—unlike the mouse and keyboard, the joystick is never used by the Microsoft® Windows® system—an alternative method is to reacquire the device in response to a WM_ACTIVATE message.

© 2002 Microsoft Corporation. All rights reserved.


Immediate Joystick Data

To retrieve the current state of the joystick, call the IDirectInputDevice8::GetDeviceState method with a pointer to a DIJOYSTATE or a DIJOYSTATE2 structure, depending on whether the data format was set with c_dfDIJoystick or c_dfDIJoystick2. (See Device Data Formats.) The joystick state returned in the structure includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The first seven members of the DIJOYSTATE structure hold the axis coordinates. The last of these seven, rglSlider, is an array of two values. (See Interpreting Joystick Axis Data.)

The rgdwPOV member contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center (neutral) position is reported as —1. For controllers that have only five positions, the position is one of the following values:

  • —1
  • 0
  • 90 * DI_DEGREES
  • 180 * DI_DEGREES
  • 270 * DI_DEGREES.

Some drivers report a value of 65,535, instead of —1, for the center position. You should check for a centered POV indicator as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

The rgbButtons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data format. For each button, the high bit is set if the button is down and it is clear if the button is up or not present.

The DIJOYSTATE2 structure has additional members for information about the velocity, acceleration, force, and torque of the axes.

See also

Buffered and Immediate Data

© 2002 Microsoft Corporation. All rights reserved.


Interpreting Joystick Axis Data

Axis values for the joystick are like those for the mouse. The value returned for the x-axis is greater as the stick moves to the right, and the value for the y-axis increases as the stick moves toward the user.

Data is in arbitrary units determined by the range property of the axis. For example, if the range for the stick's x-axis is from 0 through 10,000, a unit is one ten-thousandth of the stick's left-right travel, and the center position is 5,000. For some axes, the granularity property might be greater than 1. In this case, values are rounded off. For example, if the granularity is 10, values are reported as 0, 10, 20, and so on.

Axis data is also affected by the dead zone, a region around the center position in which motion is ignored. The dead zone provides tolerance for a slight deviation from the true center position for either or both axes of the stick. An axis value within the range of the dead zone is reported as true center.

The saturation property of an axis is a zone of tolerance at the minimum and maximum of the range. An axis value within this zone is reported as the minimum or maximum value. The purpose of the saturation property is to allow for slight differences between, for example, the minimum x-axis value reported at the top-left and bottom-left positions of the stick.

The following illustration shows the effect of the dead zone and the saturation zones. The vertical axis represents the returned axis values, where min and max are the lower and upper limits of the reported range and ctr is the reported center. The horizontal axis shows the physical position of the stick, where pmin and pmax are the extremes of the physical range, pctr is neutral position of the axis, dmin and dmax are the limits of the dead zone, and smin and smax are the boundaries of the lower and upper saturation zones. The lower saturation zone lies between pmin and smin, the upper saturation zone lies between smax and pmax, and the dead zone lies between dmin and dmax.

Graph of dead zone and saturation zones

For more information about joystick properties, see the following:

  • IDirectInputDevice8::GetProperty
  • IDirectInputDevice8::SetProperty
  • DIPROPRANGE
  • DIACTIONFORMAT

Axis coordinates from the joystick can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a joystick is an absolute device—unlike a mouse, it cannot travel infinitely far along any axis—absolute data is returned by default. When the axis mode for the joystick is set to relative, the axis coordinate represents the number of units of movement along the axis since the last value was returned.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to relative, call the IDirectInputDevice8::SetProperty method with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_REL in the dwData member of the DIPROPDWORD structure.

© 2002 Microsoft Corporation. All rights reserved.


Using CPOINTs

The CPOINT structure is used to calibrate segments of the response curve of a device axis. Up to eight CPOINTs can be set through the DIPROPCPOINTS structure. Each CPOINT structure contains a raw data value representing the position of the joystick along the axis, and a logical value. When your application receives the raw value, the logical value is used to calculate the returned value that is actually used. Raw values that fall between specific CPOINT raw data values are interpolated to logical values based on a line drawn between the CPOINTs to either side of the value.

The following is an example of the effect of five CPOINTs applied to the response curve of a joystick's x-axis. Before application of the DIPROPCPOINTS structure, the response graph for the example axis would appear as shown below, including saturation and dead zones.

Graph of CPOINTs before applying DIPROPCPOINTS

A DIPROPCPOINTS structure is initialized as follows, assuming the physical range to be -500 to 500.

DIPROPCPOINTS dipcp;

dipcp.diph.dwSize = sizeof(DIPROPCPOINTS);
dipcp.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipcp.diph.dwObj = GUID_XAxis;
dipcp.diph.dwHow = DIPH_BYID;
dipcp.dwCPointsNum = 5;
dipcp.cp[0].lP = -500;
dipcp.cp[0].dwLog = 0;
dipcp.cp[1].lP = -300;
dipcp.cp[1].dwLog = 1000;
dipcp.cp[2].lP = -100;
dipcp.cp[2].dwLog = 5000;
dipcp.cp[3].lP = 200;
dipcp.cp[3].dwLog = 9000;
dipcp.cp[4].lP = 500;
dipcp.cp[4].dwLog = 10000;

Note that you do not need to know the actual maximum returned value as the values in the dwLog member of the CPOINT structure are expressed as a percentage of the total, multiplied by 10000 (the number of discrete divisions in the total range). For instance, the example sets the curve so that 10% of the maximum value is returned at the -300 point in the joystick's range. 0.10 * 10000 = 1000, so that value is given to the dwLog member while -300 is assigned to the corresponding lP member.

After applying this DIPROPCPOINTS structure through IDirectInputDevice8::SetProperty, the curve responds as seen below.

Graph of CPOINTs after applying DIPROPCPOINTS

© 2002 Microsoft Corporation. All rights reserved.


Keyboard Data

When using Microsoft® DirectInput®, consider the keyboard not as a text input device but as a game pad with many buttons. When your application requires text input, do not use DirectInput methods. It is far easier to retrieve the data from the normal Microsoft Windows® messages, which enable you take advantage of services such as character repeat and translation of physical keys to virtual keys. This is particularly important for languages other than English, which can require special translations of key presses.

To set up the keyboard device for data retrieval, you must first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIKeyboard global variable as the parameter. (See Device Data Formats.)

The following sections give more information about obtaining and interpreting keyboard data:

  • Buffered Keyboard Data
  • Checking for Lost Keyboard Input
  • Immediate Keyboard Data
  • Interpreting Keyboard Data

© 2002 Microsoft Corporation. All rights reserved.


Buffered Keyboard Data

To retrieve buffered data from the keyboard, you must first set the buffer size (see Device Properties). This step is essential because the default size of the buffer is 0.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key—that is, a press or release. Because Microsoft® DirectInput® gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the DirectInput Keyboard Device. (See also Interpreting Keyboard Data.)

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the key event from the uAppData member.

The data for the change of state of the key is located in the dwData member of the DIDEVICEOBJECTDATA structure. Only the low byte of dwData is significant. The high bit of this byte is set if the key was pressed, and it is clear if it was released. In other words, the key was pressed if (dwData & 0x80) is nonzero.

© 2002 Microsoft Corporation. All rights reserved.


Checking for Lost Keyboard Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, Microsoft® Windows® might force your application to unacquire the keyboard. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or IDirectInputDevice8::GetDeviceState methods and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.

© 2002 Microsoft Corporation. All rights reserved.


Immediate Keyboard Data

To retrieve the current state of the keyboard, call the IDirectInputDevice8::GetDeviceState method with a pointer to an array of 256 bytes that will hold the returned data.

The IDirectInputDevice8::GetDeviceState method behaves in the same way as the Microsoft® Win32® GetKeyboardState function. It returns a snapshot of the current state of the keyboard. Each key is represented by a byte in the array of 256 bytes whose address was passed as the lpvData parameter. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the Microsoft DirectInput® Keyboard Device. (See also Interpreting Keyboard Data.)

The following code example calls a function in response to the ESC key being down. Assume that lpdiKeyboard is an acquired DirectInput device.

BYTE  diKeys[256];
if (lpdiKeyboard->GetDeviceState(256, diKeys) == DI_OK)
{
  if (diKeys[DIK_ESCAPE] & 0x80) DoSomething();
}

© 2002 Microsoft Corporation. All rights reserved.


Interpreting Keyboard Data

This topic covers the identification of keys for which data is reported by the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods. For more information about interpreting the data from IDirectInputDevice8::GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, Microsoft® DirectInput® applications read the keyboard differently from the way Microsoft Windows® does. For DirectInput applications, keyboard data refers not to virtual keys but to the actual physical keys—that is, the scan codes. DIK_ENTER, for example, refers only to the ENTER key on the main keyboard, not to the ENTER key on the numerical keypad.

Additionally, differences among keyboards can affect the way DirectInput applications interpret keyboard data. For example, DirectInput defines a constant for each key on the enhanced keyboard, as well as the additional keys on international keyboards. Because NEC keyboards support different scan codes than the PC-enhanced keyboards, DirectInput translates NEC key-scan codes into PC-enhanced scan codes where possible.

Other keyboard differences to consider are:

  • Not all PC-enhanced keyboards have the Windows logo keys (DIK_LWIN, DIK_RWIN, and DIK_APPS), there is no way to determine whether the keys are physically available.
  • Laptops and other small computers often do not implement a full set of keys. Instead, some keys (typically numeric keypad keys) are multiplexed with other keys, which are selected by an auxiliary mode key that does not generate a separate scan code.
  • If the keyboard subtype indicates a PC XT or PC AT keyboard, the following keys are not available: DIK_F11, DIK_F12, and all the extended keys (DIK_* values greater than 0x7F). Furthermore, the PC XT keyboard lacks DIK_SYSRQ.

  • Japanese keyboards, particularly the NEC PC-98 keyboards, contain a substantially different set of keys than U.S. keyboards. For more information, see DirectInput and Japanese Keyboards.

© 2002 Microsoft Corporation. All rights reserved.


Mouse Data

To set up the mouse device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIMouse or c_dfDIMouse2 global variable as the parameter value. Use c_dfDIMouse2 if you want to support more than four mouse buttons.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE | DISCL_FOREGROUND. Note that the exclusive setting causes the Microsoft® Windows® cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to a debugging window. Changing to DISCL_BACKGROUND enables you to debug the application more easily, but at a cost in performance.

The following sections give more information about retrieval and interpretation of immediate and buffered mouse data.

  • Buffered Mouse Data
  • Checking for Lost Mouse Input
  • Immediate Mouse Data
  • Interpreting Mouse Axis Data

See Also

Device Data Formats, Cooperative Levels

© 2002 Microsoft Corporation. All rights reserved.


Buffered Mouse Data

To retrieve buffered data from the mouse, you must first set the buffer size (see Device Properties). The default size of the buffer is 0, so this step is essential.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush events in the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For example, if the user presses button 0 and moves the mouse diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the values returned by the following macros:

  • DIMOFS_BUTTON0 to DIMOFS_BUTTON7
  • DIMOFS_X
  • DIMOFS_Y
  • DIMOFS_Z

Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 structure. For example, DIMOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIMOUSESTATE structure. DIMOFS_BUTTON4 to DIMOFS_BUTTON7 are supported only for DIMOUSESTATE2. With the macros you can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* MouseBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &MouseBuffer[n];
if (( (int) lpdidod->dwOfs == DIMOFS_BUTTON0)
      && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to left button press.
}

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button was pressed, and it is clear if the button was released. In other words, the button was pressed if (dwData & 0x80) is nonzero.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

For more information about the other members of the DIDEVICEOBJECTDATA structure, see Time Stamps and Sequence Numbers.

© 2002 Microsoft Corporation. All rights reserved.


Checking for Lost Mouse Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application (or even to the menu in your own application), Microsoft® Windows® might force your application to unacquire the mouse. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop—acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.

© 2002 Microsoft Corporation. All rights reserved.


Immediate Mouse Data

To retrieve the current state of the mouse, call IDirectInputDevice8::GetDeviceState with a pointer to a DIMOUSESTATE or a DIMOUSESTATE2 structure, depending on the data format. The mouse state returned in the structure includes axis data and the state of each of the buttons.

The first three members of the structure hold the axis coordinates. (See Interpreting Mouse Axis Data.)

The rgbButtons member is an array of bytes, one for each of four or eight buttons. For a traditional mouse, the first element in the array is generally the left button, the second is the right button, and the third is the middle button. The high bit is set if the button is down, and it is clear if the button is up or not present.

See also

Buffered and Immediate Data

© 2002 Microsoft Corporation. All rights reserved.


Interpreting Mouse Axis Data

The data returned for the x-axis and y-axis of a mouse indicates the movement of the mouse itself, not the cursor. The units of measurement are based on the values returned by the mouse hardware and have nothing to do with pixels or any other form of screen measurement. Because Microsoft® DirectInput® communicates directly with the mouse driver, the values for mouse speed and acceleration set by the user in Control Panel do not affect this data.

Axis data returned from the mouse can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a mouse is a relative device—unlike a joystick, it does not have a home position—relative data is returned by default.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call IDirectInputDevice8::SetProperty with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_ABS in the dwData member of the DIPROPDWORD structure.

When the axis mode for the mouse is set to relative, the axis coordinate represents the number of units that the device has been moved along the axis since the last value was returned. A negative value indicates that the mouse was moved to the left for the x-axis, or away from the user for the y-axis, or that the z-axis (the wheel) was rotated toward the user. Positive values indicate movement in the opposite direction.

When the axis mode is set to absolute, the coordinates are a running total of all relative motions received by DirectInput. The axis coordinates are not initialized to any particular value when the device is acquired, so your application should treat absolute values as relative to an unknown origin. You can record the current absolute position whenever the device is acquired and save it as the virtual origin. This virtual origin can then be subtracted from subsequent absolute coordinates retrieved from the device to compute the relative distance that the mouse has moved from the point of acquisition.

The data returned for the axis coordinates is also affected by the granularity property of the device. For the x-axis and y-axis of the mouse, granularity is normally 1. In other words, the minimum change in value is 1. For the wheel axis, it might be larger.

© 2002 Microsoft Corporation. All rights reserved.


Output Data

Some Human Interface Devices both generate input and accept output. The IDirectInputDevice8::SendDeviceData method is used to send packets of data to such devices.

IDirectInputDevice8::SendDeviceData may be viewed as IDirectInputDevice8::GetDeviceData in reverse. As with that method, it uses the DIDEVICEOBJECTDATA structure as the basic unit of data. In this case, however, the dwOfs member contains the instance ID of the device object associated with the data rather than its offset in the data format for the device. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The dwData member contains whatever data is appropriate for the object. The dwTimeStamp and dwSequence members are not used and must be set to 0.

To send data to the device, set up an array of DIDEVICEOBJECTDATA structures, fill the required number of elements with data, and then pass the array address and the number of elements used to IDirectInputDevice8::SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices may treat fields as optional. In other words, if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0 and that they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag. In this case, the data for the other two LEDs is the value you most recently sent them.

The device object type identifiers are obtained from the dwType member of the DIDEVICEOBJECTINSTANCE structure after passing the HID usage page and usage code to IDirectInputDevice8::GetObjectInfo. For example, the type identifier of the Scroll Lock LED can be obtained by using the following code, where pdev is an IDirectInputDevice8 interface pointer representing the keyboard.

DIDEVICEOBJECTINSTANCE didoi;
DWORD NumLockID;

HRESULT hr = pdev->GetObjectInfo(&didoi,
        DIMAKEUSAGEDWORD(0x07,0x53), DIPH_BYUSAGE);
NumLockID = didoi.dwType;

The following sample function, when called repeatedly, causes the LEDs on the keyboard to flash in a recurring pattern. It is assumed that the high bit of the data byte determines the state of the LED. The DWORDs NumLockID, CapsLockID, and ScrollLockID have all been obtained as shown above.

#define ARRAYSIZE 4
void FlashLEDs(void)
    {
    static int         rgiBits[] = { 1, 2, 4, 2 };
    static int         iLooper = 0;
    DWORD              cdod = 3;                  // Number of items
    DIDEVICEOBJECTDATA rgdod[ARRAYSIZE-1];
    HRESULT            hres;

    // Must clear dwTimeStamp and dwSequence
    ZeroMemory(rgdod, sizeof(rgdod));

    rgdod[0].dwOfs = NumLockID;
    rgdod[1].dwOfs = CapsLockID;
    rgdod[2].dwOfs = ScrollLockID;

    rgdod[0].dwData = (rgiBits[iLooper] & 1) ? 0x80 : 0;
                                           // NumLock light on/off
    rgdod[1].dwData = (rgiBits[iLooper] & 2) ? 0x80 : 0;
                                           // CapsLock light on/off
    rgdod[2].dwData = (rgiBits[iLooper] & 4) ? 0x80 : 0;
                                           // ScrollLock light on/off

    iLooper = (iLooper + 1) % ARRAYSIZE; // Loops from 0 to 3

    hres = pdev->SendDeviceData(sizeof(DIDEVICEOBJECTDATA),
            rgdod, &cdod, 0);
    }

© 2002 Microsoft Corporation. All rights reserved.


Action Mapping

Traditionally, applications have done their own mapping of events to particular buttons and axes. A car-racing game, for example, might assume that the x-axis on the user's joystick or mouse was the most suitable control for steering the car. The only way to accommodate new or unusual devices was to provide configuration options so that the user could specify some other axis, such as a rotational axis, to use for steering. Moreover, the application had no way of knowing which installed device was the best fit for the game, so the user typically had to choose a device from a menu or make sure only the preferred device was attached.

Using action mapping, you no longer need to make assumptions about the best use of devices and device objects. Instead, your application binds actions to virtual controls wherever possible. Rather than getting data from the x-axis and steering the car to the left or the right accordingly, the application might get data from a virtual control called DIAXIS_DRIVINGR_STEER. Microsoft® DirectInput® assigns the virtual control to a physical control—that is, a device object. It does so by taking into account the application genre, user preferences, information from the device manufacturer, and the user's configuration of the device.

Action mapping also simplifies the input loop by returning data for all devices in a form independent of the particular device. A single action can be mapped to more than one device, and the input loop can respond to the action the same way regardless of which device is being read.

The following topics contain more information about the steps required to implement action mapping.

  • Configuring the Action Map
  • Finding Matching Devices
  • Maintaining Files During Development
  • Preparing the Action Map
  • Retrieving Action Data
  • User Configuration of the Device

© 2002 Microsoft Corporation. All rights reserved.


Configuring the Action Map

As each device is enumerated, you can obtain a pointer to it, retrieve the default action map, make changes in the default map, and apply the final mappings.

1. Obtaining the Device

Obtain the IDirectInputDevice8 interface pointer for each enumerated device from the lpdid parameter of the enumeration callback. See DIEnumDevicesBySemanticsCallback. If you want to save the device interface for use in your application, call AddRef on the pointer and assign it to a global variable.

2. Obtaining the Default Action Map

To obtain the default action map for the device, call IDirectInputDevice8::BuildActionMap. Microsoft® DirectInput® takes the list of virtual controls specified in your DIACTIONFORMAT structure and attempts to map these to physical device objects, returning the results in the same structure. You should examine the dwHow member of each DIACTION element to determine whether the control was successfully mapped. If it was, you can also ascertain what criterion was used in choosing the object—for example, configuration by the user or by the device manufacturer.

3. Making Changes to the Action Map

You now have the option of changing the default mappings, although it is not recommended that you do so. After examining the dwSemantic member of the DIACTION structure to determine which device object was mapped to an action, you can change that value. For example, if an action is mapped to DIJOFS_BUTTON9, but you want that action to be mapped to the trigger button instead, change the value to DIJOFS_BUTTON0 before applying the action map.

4. Applying the Action Map

When you are satisfied that the DIACTIONFORMAT structure contains suitable mappings for the device, call IDirectInputDevice8::SetActionMap. The value you assigned to the uAppData member of each DIACTION structure now becomes bound to the control specified in the dwSemantic member, which in turn is bound to a particular device object.

5. Mapping More than One Device

Repeat steps 1 though 4 for each device you want to use in your application. Suppose you want to map actions to both a joystick and the keyboard. In the racing-game example, the action defined in the game as eB_DRIVERVIEW was mapped to a keyboard key in the following element of the DIACTION array.

{eB_DRIVERVIEW, DIKEYBOARD_1, "Driver View", },

In that example, when BuildActionMap is called on any device that is not a keyboard, the dwHow member of the DIACTION structure for that element is set to DIAH_UNMAPPED. Continue examining the dwHow member as each device in turn is enumerated, until a value other than DIAH_UNMAPPED is returned. This indicates that the device being currently mapped is a keyboard and the action has been successfully mapped to the requested key.

Even actions that have been successfully mapped can be mapped to another device. In the example, eB_UPSHIFT is given two DIACTION structures, as follows:

{eB_UPSHIFT, DIBUTTON_DRIVINGR_SHIFTUP, 0, "Upshift", },
...
{eB_UPSHIFT, DIKEYBOARD_PRIOR,          0, "Upshift", },

As devices are successively enumerated, the eB_UPSHIFT action is mapped to a suitable button on one or more joysticks or other game controllers, and then again to the keyboard.

6. Displaying the Configuration

To show the user how actions have been mapped to devices, pass the DICD_DEFAULT flag to IDirectInput8::ConfigureDevices. The property sheet for the device, containing a graphical representation of mappings, is displayed in view-only mode as in the following diagram. For more information about the mechanics of displaying the image, refer to the Using Action Mapping tutorial.

Graphical user interface for configuring the action map

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Text user interface for configuring the action map

Note Even if the cooperative level for the application is disabling the Microsoft Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping user interface (UI) is displayed.

For more information about this property sheet, see User Configuration of the Device.

© 2002 Microsoft Corporation. All rights reserved.


Finding Matching Devices

After you define the application actions and the virtual controls or device objects to which these actions are to be mapped, the next step is to enumerate devices on the system to find those that best support the desired virtual controls.

To do so, pass the DIACTIONFORMAT structure to IDirectInput8::EnumDevicesBySemantics. This method works in much the same way as IDirectInput8::EnumDevices and takes a similar callback function.

Devices that have been configured by the user to match certain controls are always enumerated first. For example, if a user has configured a wheel as the primary steering device for driving games, then the wheel is enumerated first whenever devices that support DIAXIS_DRIVINGR_STEER are requested, taking precedence over other capable devices such as joysticks that have not been configured by the user. Otherwise, the order in which available devices are enumerated is determined by the degree to which they match the requested controls. However, the order in which devices are enumerated by Microsoft® DirectInput® is not guaranteed.

In the enumeration callback, you can retrieve the default action mapping for each device, change any mappings you don't like, give the user an opportunity to reconfigure the device, and apply the action map. These steps are covered in Configuring the Action Map. Flags returned in the DIEnumDevicesBySemanticsCallback will provide information about why a particular device was enumerated. These flags will indicate whether a device has been used recently, is newly installed, or will accept mappings of priority 1 or priority 2 controls.

© 2002 Microsoft Corporation. All rights reserved.


Maintaining Files During Development

During a development cycle, unused and out of date .ini files may accumulate due to frequent action map changes, Microsoft® DirectInput® reinstallations, multiple users, and other normal development situations. These files could possibly cause unexpected mappings or reports of "recent" (DIEDBS_RECENTDEVICE) for devices that would not be expected to return that value. For this reason, it is good practice to occasionally delete any unused .ini files. These files can be found in C:\Program Files\Common Files\DirectX\DirectInput\User Maps.

Note The procedure suggested above is meant to be performed only manually during a development cycle to ensure that the development environment is in a cleaner state. A shipping application should never delete user maps as this could result in the loss of a user's preferred settings.

© 2002 Microsoft Corporation. All rights reserved.


Preparing the Action Map

The action map is a DIACTIONFORMAT structure containing information about application actions and their mapping to virtual controls or device objects. The structure is passed back and forth between the application and Microsoft® DirectInput® to establish the final mapping. This section explains how to initialize the map.

1. Define Application Actions

The first step in implementing DirectInput action mapping is to determine what input-driven actions in your application need to be mapped to device objects. For actions that can be performed either by an axis or by a button, you must define separate actions for both input types. It is recommended that you define button actions for all important functions, in case the device does not have the appropriate axes.

The following sample enumeration of action values might be defined by a car-racing game. Axis actions begin with "eA" and button actions with "eB".

enum eGameActions
{
    eA_STEER,       // Steering
    eB_STEER_LEFT,  // Steer left
    eB_STEER_RIGHT, // Steer right
    eA_ACCELERATE,  // Change speed
    eB_ACCELERATE,  // Speed up
    eB_DECELERATE,  // Slow down
    eA_BRAKE,       // Brake
    eB_BRAKE,       // Brake
    eB_UPSHIFT,     // Shift to higher gear
    eB_DOWNSHIFT,   // Shift to lower gear
    eB_CYCLEVIEW,   // Cycle to next view
    eB_COURSEVIEW,  // Toggle course view
    eB_DRIVERVIEW,  // View from driver's seat
    eB_BRAKEBIAS,   // Brake bias
    eA_VOLUME,      // Sound volume
    eB_MUTE         // Toggle sound
};

#define NUM_MY_ACTIONS 16

In the example, actions are defined as enumerated values. However, they could be other 32-bit data types, such as pointers to functions. When you retrieve device data, you get whatever action value you have defined, and you can handle it in any way you like.

2. Define the Genre

The next step is to decide what genre your application belongs to. A genre defines a set of virtual controls. By selecting the proper genre, you can obtain the best possible fit of virtual controls to application actions. Manufacturers who choose to supply default mappings for their devices must support one or more of the genres defined by DirectInput. See Action Mapping Constants for a list of these genres.

For the game in the example, the obvious choice is the DIVIRTUAL_DRIVING_RACE genre, which contains the following virtual controls.

Priority 1 Controls

DIAXIS_DRIVINGR_STEER

DIAXIS_DRIVINGR_ACCELERATE

DIAXIS_DRIVINGR_BRAKE

DIBUTTON_DRIVINGR_SHIFTUP

DIBUTTON_DRIVINGR_SHIFTDOWN

DIBUTTON_DRIVINGR_VIEW

DIBUTTON_DRIVINGR_MENU

Priority 2 Controls

DIAXIS_DRIVINGR_ACCEL_AND_BRAKE

DIHATSWITCH_DRIVINGR_GLANCE

DIBUTTON_DRIVINGR_ACCELERATE_LINK

DIBUTTON_DRIVINGR_AIDS

DIBUTTON_DRIVINGR_BOOST

DIBUTTON_DRIVINGR_BRAKE

DIBUTTON_DRIVINGR_DASHBOARD

DIBUTTON_DRIVINGR_DEVICE

DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK

DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK

DIBUTTON_DRIVINGR_MAP

DIBUTTON_DRIVINGR_PAUSE

DIBUTTON_DRIVINGR_PIT

DIBUTTON_DRIVINGR_STEER_LEFT_LINK

DIBUTTON_DRIVINGR_STEER_RIGHT_LINK

There is no difference in functionality between Priority 1 and Priority 2 controls. Priority 1 controls are those most likely to be supported by device manufacturers in their default mappings. However, there is no guarantee that any virtual control will be supported by a device.

3. Assign Actions to Controls or Device Objects

The next step in creating the action map is to associate each application action with one or more of the virtual controls defined for the genre. You do this by declaring and initializing an array of DIACTION structures. Each structure in the array specifies the action value, the virtual control to associate with it, and a friendly name that describes the action. Leave other members as zero; they will be filled in later by DirectInput.

You can also use elements of the DIACTION array to map actions to particular keys or buttons on the keyboard or mouse or to channels on a Microsoft DirectPlay® voice device. By doing so, you can take advantage of the simplified input loop for all input, not just that from virtual controls. For example, suppose you map the application-defined action eB_UPSHIFT to both the DIBUTTON_DRIVINGR_SHIFTUP virtual control and to the Page Up key. When retrieving data, you get back eB_UPSHIFT whether the input came from a joystick button or the keyboard.

The following example declares an action map for the car-racing game.

DIACTION rgActions[]=
{
//Genre-defined virtual axes

  {eA_STEER,       DIAXIS_DRIVINGR_STEER,        0, "Steer",      },
  {eA_ACCELERATE,  DIAXIS_DRIVINGR_ACCELERATE,   0, "Accelerate", },
  {eA_BRAKE,       DIAXIS_DRIVINGR_BRAKE,        0, "Brake",      },

//Genre-defined virtual buttons

  {eB_UPSHIFT,     DIBUTTON_DRIVINGR_SHIFTUP,    0, "Upshift",    },
  {eB_DOWNSHIFT,   DIBUTTON_DRIVINGR_SHIFTDOWN,  0, "DownShift",  },
  {eB_CYCLEVIEW,   DIBUTTON_DRIVINGR_VIEW,       0, "Change View",},

// Actions not defined in the genre that can be assigned to any
// button or axis

  {eA_VOLUME,      DIAXIS_ANY_1,                 0, "Volume",      },
  {eB_MUTE,        DIBUTTON_ANY(0),              0, "Toggle Sound",},

// Actions not defined in the genre that must be assigned to
// particular keys

  {eB_DRIVERVIEW,  DIKEYBOARD_1,                 0, "Driver View",},
  {eB_COURSEVIEW,  DIKEYBOARD_C,                 0, "Course View",},
  {eB_BRAKEBIAS,   DIKEYBOARD_B,                 0, "Brake Bias", },

// Actions mapped to keys as well as to virtual controls

  {eB_UPSHIFT,     DIKEYBOARD_PRIOR,              0, "Upshift",    },
  {eB_DOWNSHIFT,   DIKEYBOARD_NEXT,               0, "Downshift",  },
  {eB_STEER_LEFT,  DIKEYBOARD_LEFT,               0, "Steer Left", },
  {eB_STEER_RIGHT, DIKEYBOARD_RIGHT,              0, "Steer Right",},
  {eB_ACCELERATE,  DIKEYBOARD_UP,                 0, "Accelerate", },
  {eB_DECELERATE,  DIKEYBOARD_DOWN,               0, "Decelerate", },
  {eB_BRAKE,       DIKEYBOARD_END,                0, "Brake",      },

// Actions mapped to buttons as well as to virtual controls and keys

  {eB_UPSHIFT,     DIMOUSE_BUTTON0,              0, "Upshift",   },
  {eB_DOWNSHIFT,   DIMOUSE_BUTTON1,              0, "Downshift", },
};

In the example, some actions are mapped to actual keys by using Keyboard Mapping. Similar mappings to the mouse buttons and axes can be made by using Mouse Mapping.

The DIACTION array is contained within a DIACTIONFORMAT structure that also contains information about the genre, the application, and the desired scaling of axis data. Use the same instance of this structure throughout the action mapping process. Some members will not be used immediately, but you can fill in the entire structure before the next step, Finding Matching Devices.

© 2002 Microsoft Corporation. All rights reserved.


Retrieving Action Data

You retrieve buffered data from action-mapped devices just as you would from unmapped devices: by calling IDirectInputDevice8::GetDeviceData. However, instead of identifying device objects by examining the dwOfs member of the DIDEVICEOBJECTDATA structure, you obtain the action associated with the object from the uAppData member. This is the same value you passed to the device in the DIACTION structure. It can be a simple identifier or a pointer to a function designed to handle the action.

Remember that an action can be associated with more than one device. You still have to obtain data from both devices independently, but you can use the same routine to handle the data regardless of where it comes from.

The following sample code, which might be part of the game loop in a driving simulation, retrieves data from all devices in the g_lpIdiDevices array. This array contains g_nDevices elements.

for (int iDevice = 0x0; iDevice < g_nDevices; iDevice++)
{
    DIDEVICEOBJECTDATA didod;
    DWORD dwObjCount = 1;

    // Poll the device for data.
    g_lpDiDevices[iDevice]->Poll();

    // Retrieve the data.
    g_lpDiDevices[iDevice]->GetDeviceData( sizeof(didod),
                                           &didod,
                                           &dwObjCount, 0 );

    // Handle the actions regardless of what device returned them.
    switch(didod.uAppData)
    {
        case eA_STEER:
            SteerCar(didod.dwData);
            break;
        case eB_UPSHIFT
            if (didod.dwData & 0x80) ShiftGears(UPSHIFT);
            break;
        .
        .
        .

        default:
            break;
    }
}
Note Axis constants for specific genres, such as DIAXIS_DRIVINGR_STEER or DIAXIS_SPACESIM_LATERAL, are used for absolute joystick data. The action mapper attempts to map this virtual control to a device object that returns absolute data. The data returned from that device should be processed accordingly in the application. Device constants such as DIMOUSE_XAXIS, however, are expected to return relative data.

When retrieving data, each potential source of data should be processed separately to keep one device object from possibly overwriting the data from another. For instance, the following DIACTION structures are used in an action map to control direction.

{INPUT_LEFTRIGHT_ABS_AXIS, DIAXIS_SPACESIM_LATERAL, 0,   _T("Turn"),},
{INPUT_LEFTRIGHT_REL_AXIS, DIMOUSE_XAXIS,           0,   _T("Turn"),},
{INPUT_TURNLEFT,           DIKEYBOARD_LEFT,     0,  _T("Turn left"),},
{INPUT_TURNRIGHT,          DIKEYBOARD_RIGHT,    0, _T("Turn right"),},

The application's input loop processes data from these actions in the following case statement.

switch (adod[j].uAppData)
{
    case INPUT_LEFTRIGHT_ABS_AXIS:
        g_dwAbsLR = adod[j].dwData
        break;
    case INPUT_LEFTRIGHT_REL_AXIS:
        g_dwRelLR = adod[j].dwData;
        break;
    case INPUT_TURNLEFT:
        g_bLeft = (adod[j].dwData != 0);
        break;
    case INPUT_TURNRIGHT:
        g_bRight = (adod[j].dwData != 0)
        break;
}

Note that each data source is assigned to a separate variable rather than all data sources being assigned a generic "turn" variable. If they were to share a generic variable, holding down the LEFT ARROW key and then moving the joystick would cause the keyboard information to be lost. This is because the joystick data would overwrite the variable.

In addition to individual variables, there are many ways to process the data. Whatever method is used, care should be taken in the processing of data to avoid unexpectedly lost information.

© 2002 Microsoft Corporation. All rights reserved.


User Configuration of the Device

Microsoft® DirectInput® provides a property sheet that can be called from an application, enabling the user to configure devices for the application and view the current configuration. This property sheet can display various views of the device as provided by the manufacturer.

To enable user configuration, pass a DICONFIGUREDEVICESPARAMS structure containing a pointer to the DIACTIONFORMAT structure describing the desired mapping, along with the DICD_EDIT flag, to the IDirectInput8::ConfigureDevices method. Normally you would do this after calling IDirectInputDevice8::BuildActionMap on all devices that will be used in the application.

The following illustration shows a typical property sheet in edit mode.

Graphical user interface for configuring the action map

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Text user interface for configuring the action map

Note Even if the cooperative level for the application is disabling the Microsoft Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The property page for a device lists the friendly names that were provided by you in the lptszActionName member of each DIACTION structure. If you have already called IDirectInputDevice8::BuildActionMap for a device, the page also shows these names as callouts on the image of the device, with lines pointing to the device objects to which the actions have been mapped.

The user now has the opportunity to reassign game actions by first choosing a control then choosing an action from the menu. When the user closes the property sheet, the method returns and the modifications are stored in the DIACTIONFORMAT structure that you passed in. You can now pass the same structure to IDirectInputDevice8::SetActionMap in order to implement the new mapping scheme.

© 2002 Microsoft Corporation. All rights reserved.


Force Feedback

Force feedback is the generation of push or resistance in an input/output device—for example, by motors mounted in the base of a joystick. Microsoft® DirectInput® enables you to generate force-feedback effects for devices that have compatible drivers.

The following sections introduce the elements of force feedback:

  • Basic Concepts of Force Feedback
  • Changing an Effect
  • Creating an Effect
  • Downloading and Unloading Effects
  • Effect Direction
  • Effect Enumeration
  • Effect Object Enumeration
  • Effect Playback
  • Envelopes and Offsets
  • Force-Feedback State
  • Gain
  • Information About a Supported Effect
  • Loading Effects from a File

  • Effect Types

© 2002 Microsoft Corporation. All rights reserved.


Basic Concepts of Force Feedback

A particular instance of force feedback is called an effect, and the push or resistance is called the force. Most effects fall into one of the following categories:

  • Constant force. A steady force in a single direction.
  • Ramp force. A force that steadily increases or decreases in magnitude.
  • Periodic effect. A force that pulsates according to a defined wave pattern.
  • Condition. A reaction to motion or position along an axis. Two examples are a friction effect that generates resistance to movement of the joystick, and a spring effect that pushes the stick back toward a certain position after it has been moved from that position.

The strength of the force is called its magnitude. Magnitude is measured in units ranging from 0 (no force) through 10,000 (maximum force for the device, defined for C/C++ and Microsoft® Visual Basic® as DI_FFNOMINALMAX). A negative value indicates force in the opposite direction. Magnitudes are linear: a force of 10,000 is twice as great as one of 5,000.

Ramp forces have a beginning and ending magnitude. For a periodic effect, the basic magnitude is the force at the peak of the wave.

The direction of a force is the direction from which it comes. A positive force on a given axis pushes from the positive toward the negative.

Effects also have duration, measured in microseconds. Periodic effects have a period, or the duration of one cycle, also measured in microseconds. The phase of a periodic effect is the point along the wave at which playback begins.

The following illustration represents a sawtooth periodic effect with a magnitude of 5,000, or half the maximum force for the device. The horizontal axis represents the duration of the effect, and the vertical axis represents the magnitude. Points above the center line represent positive force in the direction defined for the effect, and points below the center line represent negative force, or force in the opposite direction.

Graph of sawtooth force feedback

A force may be further shaped by an envelope. An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect. Attack and fade also have duration, which determines how long the magnitude takes to reach or fall away from the sustain value, the magnitude in the middle portion of the effect.

The following diagram shows an envelope. The attack level is set to 8,000 and the fade level to 1,000. The sustain level is defined by the basic magnitude of the force to which the envelope is being applied; in the example, it is 5,000. In this case, the attack is greater than the sustain, giving the effect an initial strong kick. Both the attack and the fade level can be either greater or less than the sustain level.

Graph of envelope force feedback

The next diagram shows the result of the envelope being applied to the periodic effect in the first diagram. The envelope is mirrored on the negative side of the magnitude. An attack value of 8,000 means that the initial magnitude of the force in either direction is 80 percent of the maximum possible.

Graph of sawtooth and envelope force feedback

Periodic effects and conditions can also be modified by the addition of an offset, which defines the amount by which the waveform is shifted up or down from the base level. The practical effect of applying a positive offset to the sawtooth example would be to strengthen the positive force and weaken the negative one—in other words, the force would peak more strongly in one direction than in the other.

Finally, the overall magnitude of an effect can be scaled by gain, which is analogous to a volume control in audio. A single gain value can be applied to all effects for a device. You might want to do this to compensate for stronger or weaker forces on different hardware or to accommodate the user's preferences.

© 2002 Microsoft Corporation. All rights reserved.


Changing an Effect

You can modify the parameters of an effect, in some cases even while the effect is playing. Do this by using the IDirectInputEffect::SetParameters method.

The dwDynamicParams member of the DIEFFECTINFO structure tells you which effect parameters can be changed while an effect is playing. If you attempt to modify an effect parameter that cannot be modified while the effect is playing, and the effect is still playing, Microsoft® DirectInput® normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag.

The following code example changes the magnitude of the constant force that was set in the example under Creating an Effect.

DIEFFECT        diEffect;           // Parameters for effect
DICONSTANTFORCE diConstantForce;    // Type-specific parameters

diConstantForce.lMagnitude = 5000;
diEffect.dwSize = sizeof(DIEFFECT);
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;
hr = lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

The DIEP_TYPESPECIFICPARAMS flag ensures that the transfer of data from the DIEFFECT structure is restricted to the relevant members, so that you do not have to initialize the entire structure and so that the minimum possible amount of data needs to be sent to the device.

© 2002 Microsoft Corporation. All rights reserved.


Creating an Effect

Create an effect object by using the IDirectInputDevice8::CreateEffect method, as in the following code example, where g_lpdid points to an instance of the interface. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

HRESULT  hr;
LPDIRECTINPUTEFFECT lpdiEffect;  // receives pointer to created effect
DIEFFECT diEffect;               // parameters for created effect

DWORD    dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG     lDirection[2] = { 18000, 0 };

DICONSTANTFORCE diConstantForce;

diConstantForce.lMagnitude = DI_FFNOMINALMAX;   // Full force

diEffect.dwSize          = sizeof(DIEFFECT);
diEffect.dwFlags         = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration      = (DWORD)(0.5 * DI_SECONDS);
diEffect.dwSamplePeriod  = 0;                 // = default
diEffect.dwGain          = DI_FFNOMINALMAX;   // No scaling
diEffect.dwTriggerButton = DIEB_NOTRIGGER;    // Not a button response
diEffect.dwTriggerRepeatInterval = 0;         // Not applicable
diEffect.cAxes                   = 2;
diEffect.rgdwAxes                = &dwAxes[0];
diEffect.rglDirection            = &lDirection[0];
diEffect.lpEnvelope              = NULL;
diEffect.cbTypeSpecificParams    = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams   = &diConstantForce;

hr = g_lpdid->CreateEffect(GUID_ConstantForce,
                           &diEffect,
                           &lpdiEffect,
                           NULL);

In the method call, the first parameter identifies the supported effect with which the created effect is to be associated. The example uses one of the predefined globally unique identifier (GUID)s found in Dinput.h. If you use a predefined GUID, the call fails if the device does not support the effect.

The second parameter sets the parameters as specified in the DIEFFECT structure.

The third parameter receives a pointer to the effect object if the call is successful.

The DIEFF_POLAR flag specifies the type of coordinates used for the direction of the force. (See Effect Direction.) It is combined with DIEFF_OBJECTOFFSETS, which indicates that any buttons or axes used in other members are identified by their offsets within the DIDATAFORMAT structure for the device. The alternative is to use the DIEFF_OBJECTIDS flag, signifying that buttons and axes are identified by the dwType member of the DIDEVICEOBJECTINSTANCE structure returned for the object when it was enumerated with the IDirectInputDevice8::EnumObjects method.

For more information about the members of the DIEFFECT structure, see Effect Direction.

© 2002 Microsoft Corporation. All rights reserved.


Downloading and Unloading Effects

Before an effect can be played, it must be downloaded to the device. Downloading an effect means telling the driver to prepare the effect for playback. It is entirely up to the driver to determine how this is done. Generally, the driver places the parameters of the effect in hardware memory to minimize the subsequent transfer of data between the device and the system. The consequent reduction in latency is particularly important for conditions and for effects played in response to a trigger, such as a fire button. Ideally the device does not have to communicate with the system at all in order to respond to axis movements and button presses.

Downloading is done automatically when you create an effect, provided the device is not full and is acquired at the exclusive cooperative level. By default, it is also done when you start the effect or change its parameters.

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the IDirectInputEffect::Download method to download or update the effect.

When the device is unacquired—for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background—effects are unloaded and must be downloaded again when the application regains the foreground. This is done automatically when you call the IDirectInputEffect::Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button, since the IDirectInputEffect::Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the IDirectInputEffect::Unload method. You can also remove all effects by resetting the device through a call to the IDirectInputDevice8::SendForceFeedbackCommand method.

© 2002 Microsoft Corporation. All rights reserved.


Effect Direction

Directions can be defined for one or more axes. As with the mouse and joystick, the x-axis increases from left to right, and the y-axis increases from far to near. For three-dimensional devices, the z-axis increases from up to down.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). If the user must push the stick toward the left to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar, spherical, or Cartesian coordinates.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Spherical coordinates are also in hundredths of a degree but can contain two or more angles For each angle, the direction is rotated in the positive direction of the next axis. For a 3-D device, the first angle would normally be rotated from the positive x-axis toward the positive y-axis (clockwise from east), and the second angle would be rotated toward the positive z-axis (down). Thus a force with a direction of (0, 0) would be to the user's right and parallel to the tabletop. A direction of 27,000 for the first angle and 4,500 for the second would be directly away from the user (270 degrees clockwise from east) and angling toward the floor (45 degrees downward from the tabletop); to counteract a force with this direction, the user would have to push forward and down.

Cartesian coordinates are similar to 3-D vectors. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, —2) and a direction of (5, —10) are exactly the same.

Note The coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

When an effect is created or modified, the cAxes, rgdwAxes, and rglDirection members of the DIEFFECT structure are used to specify the direction of the force.

The cAxes member specifies the number of axes involved in the effect. This will also be the number of elements in each of the arrays pointed to by the next two members.

The array pointed to by rgdwAxes identifies the axes to which the effects will be applied. If the DIEFF_OBJECTOFFSETS flag has been set, the axes are identified by the offsets within the data format structure. These offsets are most readily identified by using the DIJOFS_* defines. (For a list of these values, see Joystick Device Constants.)

Finally, the rglDirection member specifies the direction of the force.

Note The cAxes and rgdwAxes members cannot be modified once they have been set. An effect always has the same axis list.

Regardless of whether you are using Cartesian, polar, or spherical coordinates, you must provide exactly as many elements in rglDirection as there are axes in the array pointed to by rgdwAxes.

In the polar coordinate system, north (0 degrees) lies along the vector (0, —1), where the elements of the vector correspond to the elements in the axis list pointed to by rgdwAxes. Normally those axes are x and y, so north is directly along the negative y-axis; that is, away from the user. The last element of rglDirection must be 0.

In the example in Creating an Effect, the direction of a two-dimensional force is defined in polar coordinates. The force has a south direction—it comes from the direction of the user, so the user has to pull the stick to counteract it. The direction is 180 degrees clockwise from north, and can be assigned as follows:

LONG  lDirection[2] = { 18000, 0 };

For greater clarity, the assignment could also be expressed this way:

LONG  lDirection[2] = { 180 * DI_DEGREES, 0 };

For spherical coordinates, presuming that you are working with a three-axis device, the same direction is assigned as follows:

LONG  lDirection[3] = { 90 * DI_DEGREES, 0, 0 }

The first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1); the second angle is measured in hundredths of a degree toward (0, 0, 1). The elements of the vector notation again correspond to elements in the array pointed to by the rgdwAxes member. Assume that the elements of this array represent the x, y, and z axes, in that order. The point of origin is at x = 1 and y = 0; that is, to the user's right. The direction of rotation is toward the positive y-axis (0, 1); that is, toward the user, or clockwise. The force in the example is 90 degrees clockwise from the right; that is, south. Because the second element of lDirection is 0, there is no rotation on the third axis.

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the dwFlags member, you would specify the direction like this:

LONG  lDirection[2] = { 0, 1 };

Here again, the elements of the array correspond to the axes listed in the array pointed to by rgdwAxes. The example sets the x-axis to 0 and the y-axis to 1; that is, the direction lies directly along the positive y-axis, or to the south.

The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward.

Examples of Setting Effect Direction

Single-Axis Effects

Setting up the direction for a single-axis effect is easy because there is nothing to specify. Put the DIEFF_CARTESIAN flag in the dwFlags member of the DIEFFECT structure and set rglDirection to point to a single LONG containing the value 0.

The following code example sets up the direction and axis parameters for an x-axis effect:

DIEFFECT eff;
LONG     lZero  = 0;                       // No direction
DWORD    dwAxis = DIJOFS_X;                // X-axis effect

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 1;                                     // One axis
eff.dwFlags      = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = &lZero;                                // Direction
eff.rgdwAxes     = &dwAxis;                         // Axis for effect

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is only a little more complicated. Set the DIEFF_POLAR flag in dwFlags and set rglDirection to point to an array of two LONGs. The first element in this array is the direction from which you want the effect to come. The second element in the array must be 0.

The following example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 90 * DI_DEGREES, 0 };
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };   // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 2;                                  // Two axes
eff.dwFlags      = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;  // Flags
eff.rglDirection = rglDirection;                       // Direction
eff.rgdwAxes     = rgdwAxes;                     // Axis for effect

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is a bit trickier. Set the DIEFF_CARTESIAN flag in dwFlags, and again set rglDirection to point to an array of two LONGs. This time the first element in the array is the x-coordinate of the direction vector, and the second is the y-coordinate.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 1, 0 };            // Positive x = east
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes = 2;                                       // Two axes
eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = rglDirection;                     // Direction
eff.rgdwAxes = rgdwAxes;                       // Axis for effect

© 2002 Microsoft Corporation. All rights reserved.


Effect Enumeration

The IDirectInputDevice8::EnumEffects method returns information about the support offered by the device for various kinds of effects.

It is important to distinguish between supported effectsand created effects, or effect objects. A supported effect is a basic type which a device is capable of playing, such as a constant force. However, a constant force by itself has no properties such as magnitude, direction, duration, attack, or fade. These properties are set when you create a specific effect object in your application by shaping the raw effect type with an envelope or setting the values of a DIEFFECT structure. A supported effect can be represented by many effect objects, each with different parameters—for example, several constant forces, each with different duration, magnitude, and direction.

For information about enumerating created effects, see Effect Object Enumeration.

Like other Microsoft® DirectInput® enumerations, the IDirectInputDevice8::EnumEffects method requires a callback function. This is documented with the placeholder name DIEnumEffectsCallback, but you can use a different name if you prefer. This function is called for each effect enumerated. Within the function you can obtain the globally unique identifier (GUID) for each effect, get information about the extent of hardware support, and create one or more effect objects whose methods you can use to manipulate the effect.

The following code example sets the enumeration in motion. Assume that g_lpdid is an initialized pointer to the IDirectInputDevice8 interface of the device.

HRESULT hr = g_lpdid->EnumEffects(&DIEnumEffectsCallback,
        g_lpdid, DIEFT_ALL);

A skeletal callback is shown in the following code. The pvRef parameter of the callback could be any 32-bit value, but in this case it is a pointer to the device interface (the global g_lpdid in the previous example), which is used for getting information about effects supported by the device and for creating effect objects.

BOOL CALLBACK DIEnumEffectsCallback(LPCDIEFFECTINFO pdei,
                                LPVOID pvRef)
{
    HRESULT              hr;
    LPDIRECTINPUTDEVICE8 lpdid = (LPDIRECTINPUTDEVICE8)pvRef;
// Pointer to calling device
    LPDIRECTINPUTEFFECT  lpdiEffect;      // Pointer to created effect
    DIEFFECT             diEffect;        // Params for created effect
    DICONSTANTFORCE      diConstantForce; // Type-specific parameters

    if (DIEFT_GETTYPE(pdei->dwEffType) == DIEFT_CONSTANTFORCE)
    {
       /* Here you can extract information about support for the
          effect type (from pdei), and tailor your effects
          accordingly. For example, the device might not support
          envelopes for this type of effect. */
       .
       .
       .
       // Create one or more constant force effects.
       // For each, you have to initialize a DICONSTANTFORCE
       // and a DIEFFECT structure.
       .
       .
       .
        hr = lpdid->CreateEffect(pdei->guid,
                                &diEffect,
                                &lpdiEffect,
                                NULL);
       .
       .
       .
    }
    // And so on for other types of effect
   .
   .
   .

    return DIENUM_CONTINUE;
}  // End of callback

For a detailed example of creating an effect, and for more information about how to initialize an effect, see Creating an Effect.

© 2002 Microsoft Corporation. All rights reserved.


Effect Object Enumeration

When you need to examine or manipulate all the effects you have created, you can use the IDirectInputDevice8::EnumCreatedEffectObjects method. As no flags are currently defined for this method, you cannot restrict the enumeration to particular kinds of effects; all effects will be enumerated.

Note This method enumerates created effects, not effects supported by a device. For more information about the distinction between the two, see Effect Enumeration.

Like other Microsoft® DirectInput® enumerations, the IDirectInputDevice8::EnumCreatedEffectObjects method requires a callback function. This standard callback is documented with the placeholder name DIEnumCreatedEffectObjectsCallback, but you can use a different name. The function is called for each effect enumerated. Within the function, you can perform any processing you want. However, it is not safe to create a new effect while enumeration is going on.

The following is a skeletal example of the callback function. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the IDirectInputDevice8 interface that is performing the enumeration.

HRESULT  hr;

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
                             LPDIRECTINPUTEFFECT peff, LPVOID pvRef);
{
    LPDIRECTINPUTDEVICE pdid = (IDirectInputDevice*)pvRef;
                                        // Pointer to calling device
    DIEFFECT            diEffect;      // Params for created effect

    diEffect.dwSize = sizeof(DIEFFECTINFO);
    peff->GetParameters(&diEffect, DIEP_ALLPARAMS);
    // Check or set parameters, or do anything else.
    .
    .
    .
}  // End of callback

Here's the call that sets the enumeration in motion, passing in the DirectInputDevice pointer lpdid:

hr = lpdid->EnumCreatedEffectObjects(
         &DIEnumCreatedEffectObjectsCallback,
         &lpdid, 0);

© 2002 Microsoft Corporation. All rights reserved.


Effect Playback

There are two principal ways to start playback of an effect: manually by a call to the IDirectInputEffect::Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the IDirectInputEffect::SetParameters method with the DIEP_START flag.

Passing INFINITE in the dwIterations parameter of the IDirectInputEffect::Start method has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope—for example, to begin with a strong kick, then settle down to a steady throb—set dwIterations to 1, and set the dwDuration member of the DIEFFECT structure to INFINITE. (This is the structure passed to the IDirectInputDevice8::CreateEffect method.)

Note Some devices do not support multiple iterations of an effect, and they accept only the value 1 in the dwIterations parameter to the IDirectInputEffect::Start method. Always check the return value from IDirectInputEffect::Start to be sure the effect played successfully.

To associate an effect with a button press, set the dwTriggerButton member of the DIEFFECT structure. Also set the dwTriggerRepeatIntervalmember to the desired delay between playbacks when the button is held down. This is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button. If you associate more than one effect with a button, the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the IDirectInputEffect::Unload method or set the parameters for the effect with dwTriggerButton set to DIEB_NOTRIGGER.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. See Downloading and Unloading Effects. This step is not necessary for effects not associated with a trigger, because they are automatically downloaded if necessary whenever the IDirectInputEffect::Start method is called.

If an effect has a finite duration and is started by a call to the IDirectInputEffect::Start method, it stops playing when the time has elapsed. If its duration was set to INFINITE, playback ends only when the IDirectInputEffect::Stop method is called. An effect associated with a trigger button starts when the button is pressed and stops when the button is released or the duration has elapsed, whichever comes sooner.

© 2002 Microsoft Corporation. All rights reserved.


Envelopes and Offsets

You can modify the basic magnitude of some effects by applying an envelope and an offset. For an overview, see Basic Concepts of Force Feedback.

To apply an envelope when creating or modifying an effect, initialize a DIENVELOPE structure and put a pointer to it in the lpEnvelope member of the DIEFFECT structure.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the IDirectInputDevice8::GetEffectInfo method and check for the DIEP_ENVELOPE flag in the dwStaticParams member of the DIEFFECTINFO structure.

To apply an offset, set the lOffset member of the DIPERIODIC or DICONDITION structure pointed to by the lpvTypeSpecificParams member of the DIEFFECT structure. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed DI_FFNOMINALMAX.

You cannot apply an offset to a constant force or ramp force. In these cases, you can achieve the same effect by altering the magnitude.

© 2002 Microsoft Corporation. All rights reserved.


Force-Feedback State

The IDirectInputDevice8::SendForceFeedbackCommand method enables you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause, stop, or continue playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the IDirectInputDevice8::GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and whether the device is currently powered.

© 2002 Microsoft Corporation. All rights reserved.


Gain

You might want to scale the force of your effects according to the force exerted by different devices. For example, if an application's effects feel right on a device that puts out a maximum force of n newtons on a given axis, you might want to adjust the gain for a device that puts out more force. (You cannot use the gain to increase the maximum force of the axis, so you should set the basic effect magnitudes to values suitable for devices that put out less force.)

Gain can also be used to decrease the magnitude of a hardware-defined effect.

The actual force generated by a device object such as an axis or button is returned in the dwFFMaxForce member of the DIDEVICEOBJECTINSTANCE structure when objects are enumerated. (See Device Object Enumeration.)

You can set the gain for the entire device by using the IDirectInputDevice8::SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the dwGain member of the DIEFFECT structure. (If dwGain is 0, the effect will not be felt.) You can change this value later by using IDirectInputEffect::SetParameters, passing DIEP_GAIN in the dwFlags parameter.

The purpose of setting the device gain is to allow your application to have control over the strength of all effects all at once. For example, you might have a slider control in your application to enable the user to specify how strong the force-feedback effects should be, such as the master volume control on a sound mixer. When the device gain is set, your application does not need to adjust the gain of each individual effect to suit the user's preferences.

A gain value can be in the range from 0 through 10,000, where 10,000 indicates that magnitudes are not to be scaled, 7,500 means that forces are to be scaled to 75 percent of their nominal magnitudes, and so on.

© 2002 Microsoft Corporation. All rights reserved.


Information About a Supported Effect

The IDirectInputDevice8::GetEffectInfo method can be used to retrieve information about the device's support for an effect whose globally unique identifier (GUID) is known. It retrieves the same information that is returned in the DIEFFECTINFO structure during enumeration. For more information, see Effect Enumeration.

The following code fetches information about an effect whose GUID is stored in the EffectGuid variable, and determines whether the direction of the effect can be changed without stopping and restarting it:

DIEFFECTINFO diEffectInfo;
diEffectInfo.dwSize = sizeof(DIEFFECTINFO);
g_lpdid->GetEffectInfo(&diEffectInfo, EffectGuid);
if (diEffectInfo.dwDynamicParams & DIEP_DIRECTION)
{
  // Can reset parameter dynamically
}

© 2002 Microsoft Corporation. All rights reserved.


Loading Effects from a File

Using the Force Editor supplied with the Microsoft® DirectX® software development kit (SDK), or another application that uses the same file format, you can design effects and save them in a file. You can then use these effects in any application by loading them at run time.

To load effects, call the IDirectInputDevice8::EnumEffectsInFile method. By default, the enumeration is limited to the standard Microsoft DirectInput® effects, but you can enumerate other effects by setting the DIFEF_INCLUDENONSTANDARD flag. By setting the DIFEF_MODIFYIFNEEDED flag, you can also instruct DirectInput to modify the parameters of effects, if necessary, so that they work on the device. (For example, an effect authored for two axes can be made to work on a single-axis steering wheel.)

In the following code example, the first three standard effects are loaded from a file and created as DirectInputEffect objects.

// g_lpdid is a valid IDirectInputDevice8 pointer to a
// force feedback device.

// The array of effect pointers is declared globally.
LPDIRECTINPUTEFFECT pEff[3];
.
.
.
g_lpdid->EnumEffectsInFile("FEdit1.ffe",
                            EnumEffectsInFileProc,
                            NULL,
                            DIFEF_MODIFYIFNEEDED);
.
.
.

The following callback function is called once for each effect in the file or until it returns DIENUM_STOP. Note that because the DIFEF_MODIFYIFNEEDED flag was passed, the effect parameters may have been modified in lpdife->lpDiEffect. The callback creates the effect with these modified parameters.

BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife,
        LPVOID pvRef)

{
    HRESULT     hr;
    static int  i;

    hr = g_lpdid->CreateEffect(lpdife->GuidEffect,
                               lpdife->lpDiEffect,
                               &pEff[i],
                               NULL);
    if (FAILED(hr))
    {
        // Error handling
    }
    if (++i > 2) return DIENUM_STOP;
    else return DIENUM_CONTINUE;
}

© 2002 Microsoft Corporation. All rights reserved.


Effect Types

This section contains information about force-feedback effects.

  • Conditions
  • Constant Forces
  • Custom Forces
  • Device-Specific Effects
  • Periodic Effects
  • Ramp Forces

© 2002 Microsoft Corporation. All rights reserved.


Conditions

Conditions are forces applied in response to current sensor values within the device. In other words, conditions require information about device motion, such as position or velocity of a joystick handle.

In general, conditions are not associated with individual events during a game or other application. They represent ambient phenomena, such as the stiffness or looseness of a flight stick, or the tendency of a steering wheel to return to a straight-ahead position.

A condition does not have a predefined magnitude. The magnitude is scaled in proportion to the movement or position of the input object.

Microsoft® DirectInput® defines the following types of condition effects:

  • Friction. The force is applied when the axis is moved and depends on the defined friction coefficient.
  • Damper. The force increases in proportion to the velocity with which the user moves the axis.
  • Inertia. The force increases in proportion to the acceleration of the axis.
  • Spring. The force increases in proportion to the distance of the axis from a defined neutral point.

Most hardware devices do not support the application of envelopes to conditions.

Conditions have the following type-specific parameters:

Offset | The offset from the zero reading of the appropriate sensor value at which the condition begins to be applied. For a spring effect, the neutral point—that is, the point along the axis at which the spring would be considered at rest—would be defined by the offset for the condition. For a damper, the offset would define the greatest velocity value for which damping force is zero. Offset is not normally used for inertia or friction effects.
Coefficient | A multiplier that scales the effect. For some devices, you can set separate coefficients for the positive and negative direction along the axis associated with the condition. For example, a flight stick controlling a damaged aircraft might move more easily to the right than to the left.
Saturation | In force feedback, saturation is an expression of the maximum possible force for an effect. For example, suppose a flight stick has a spring condition on the x-axis. The offset is 0 and the coefficient is 10,000, so the maximum force is normally exerted when the stick is furthest from the center. But if you define a positive and negative saturation of 5,000, the force does not increase after the stick has been moved halfway to the right or left. Not all devices support saturation.
Deadband | The deadband is a zone around the offset of an axis at which the condition is not active. In the case of a spring that is at rest in the middle of an axis, the deadband enlarges this area of rest. Not all devices support deadband.

Conditions can have duration, although in most cases you would probably want to set the duration to infinite (—1) and stop the effect only in response to some event in the application.

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific structure for conditions is DICONDITION. For multiple-axis conditions, you can provide an array of such structures, one for each axis, or a single structure that defines the condition in the specified direction. In either case, you must set the cbTypeSpecificParams member of the DIEFFECT structure to the number of bytes used; that is, to sizeof(DICONDITION) * n, where n is the number of structures provided. For more information about how to use either single or multiple structures, see the DICONDITION structure.

An application should call the IDirectInputDevice8::GetEffectInfo method or the IDirectInputDevice8::EnumEffects method and examine the dwEffType member of the DIEFFECTINFO structure to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in the lNegativeCoefficient member, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in dwNegativeSaturation, and the value in dwPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the dwPositiveSaturation and dwNegativeSaturation values, and no saturation is applied.

You should also check DIEFFECTINFO.dwEffType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION structure will be ignored.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point rather than pulling toward it.

© 2002 Microsoft Corporation. All rights reserved.


Constant Forces

A constant force is a force with a defined magnitude and duration.

You can apply an envelope to a constant force to give it shape. For example, suppose you have an effect with a nominal magnitude of 2,000 and a duration of 2 seconds. Then you apply an envelope with the following values:

Parameter | Value
Attack time | 0.5 second
Initial attack level | 5,000
Fade time | 1 second
Fade level | 0

When you play the effect, you get the following:

Elapsed time | Magnitude
0.0 | 5,000
0.1 | 4,400
0.2 | 3,800
0.3 | 3,200
0.4 | 2,600
0.5 | 2,000
(Duration of sustain) | 2,000
1.0: | 2,000
1.1 | 1,800
1.2 | 1,600
1.3 | 1,400
1.4 | 1,200
1.5 | 1,000
1.6 | 800
1.7 | 600
1.8 | 400
1.9 | 200
2.0 | 0

You cannot apply an offset to a constant force.

To create a constant force, pass GUID_ConstantForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

A constant force uses a DICONSTANTFORCE structure to define the magnitude. A negative magnitude has the effect of reversing the direction of the force.

© 2002 Microsoft Corporation. All rights reserved.


Custom Forces

Application writers can create their own effects by creating a custom force. A custom force is an array of constant force values played back by the device.

The type-specific structure for custom waveform effects is DICUSTOMFORCE.

Set the dwSamplePeriod member of the DICUSTOMFORCE structure and the dwSamplePeriod member of the DIEFFECT structure to the same value. This is the time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the dwDuration member of the DIEFFECT structure has elapsed.

© 2002 Microsoft Corporation. All rights reserved.


Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by Microsoft® DirectInput®. The type-specific parameters for these effects may be either hard-coded or modifiable by the application.

If type-specific parameters are modifiable, the application developer must obtain a header file declaring the data structure required by the effect.

The hardware vendor must provide a globally unique identifier (GUID) identifying the device-specific effect and might provide a custom structure for the type-specific parameters of the effect. Your application then must initialize a DIEFFECT structure and a type-specific structure, as with any other effect. You then call the IDirectInputDevice8::CreateEffect method, passing the device-specific GUID and a pointer to the DIEFFECT structure.

When you obtain information about a device-specific effect in a DIEFFECTINFO structure, the low byte of the dwEffType member (DIEFT_GETTYPE(dwEffType)) indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the lpvTypeSpecificParams member of the DIEFFECT structure must point to the corresponding DICONSTANTFORCE, DIRAMPFORCE, DIPERIODIC, or DICONDITION structure, and the cbTypeSpecificParams member must be equal to the size of that structure.

If (DIEFT_GETTYPE(dwEffType) == DIEFT_HARDWARE), the values of the lpvTypeSpecificParams and cbTypeSpecificParams members depend on whether the effect requires custom type-specific parameters. If it does, these values must refer to the appropriate structure defined in the manufacturer's header file and declared and initialized by your application. If the effect does not require custom parameters—that is, if the dwStaticParams member of the DIEFFECTINFO structure for the hardware effect does not have the DIEP_TYPESPECIFICPARAMS flag—lpvTypeSpecificParams must be NULL and cbTypeSpecificParams must be 0.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.

© 2002 Microsoft Corporation. All rights reserved.


Periodic Effects

Periodic effects are waveform effects. Microsoft® DirectInput® defines the following waveforms.

  • Square.
  • Sine.
  • Cosine.
  • Triangle.
  • SawtoothUp. The waveform drops vertically after it reaches maximum positive force. See Basic Concepts of Force Feedback for an example.
  • SawtoothDown. The waveform rises vertically after it reaches maximum negative force.

An envelope can be applied to periodic effects. See the example in Basic Concepts of Force Feedback.

The phase of a periodic effect is the point along the waveform where the effect begins. Phase is measured in hundredths of a degree, from 0 to 35,999. The following table indicates where selected phase values (in degrees) lie along the various waveforms. Max is the top (+) or bottom (—) of the wave, and Mid is the midpoint, where no force is applied in either direction.

Waveform | 0 | 90 | 180 | 270
Square | +Max | +Max | —Max | —Max
Sine | Mid | +Max | Mid | —Max
Triangle | +Max | Mid | —Max | Mid
SawtoothUp | —Max | —Max/2 | Mid | +Max/2 (reaches +Max just before the cycle repeats)
SawtoothDown | +Max | +Max/2 | Mid | —Max/2 (reaches —Max just before the cycle repeats)

A driver may round off a phase value to the nearest supported value. For example, for a sine effect some drivers support only values of 0 and 9,000 (to create a cosine); for other effects, only values of 0 and 18,000 are supported.

To create a periodic force, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific forces designed by the manufacturer. For example, a hardware device might support a periodic effect that rotates the stick in a small circle.

The type-specific structure for periodic effects is DIPERIODIC.

Do not confuse the period of a periodic effect (DIPERIODIC.dwPeriod) with the sample period (DIEFFECT.dwSamplePeriod). The period is the time that it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.

© 2002 Microsoft Corporation. All rights reserved.


Ramp Forces

A ramp force is a force with defined starting and ending magnitudes and a finite duration. A ramp force can continue in a single direction, or it can start as a strong push in one direction, weaken, stop, and then strengthen in the opposite direction.

The following illustration shows a ramp force that starts at a magnitude of -5,000 and ends at 5,000:

Graph of ramp force

You can apply an envelope to a ramp force to shape it further. The following diagram shows the effect of applying an envelope, shown in green, to the ramp force in the previous diagram.

Graph of ramp force with envelope

Note that during the sustain portion of the envelope, the magnitude of the effect follows the same straight line as before the envelope was applied. For the duration of the attack and fade, the slope of the ramp is modified by the attack and fade levels.

You cannot apply an offset to a ramp force.

To create a ramp force, pass GUID_RampForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

A ramp force uses a DIRAMPFORCE structure to define the starting and ending magnitude of the force, whereas the duration is taken from the DIEFFECT structure. Duration must never be set to INFINITE.

© 2002 Microsoft Corporation. All rights reserved.


Programming Tips and Tools

This topic covers the following specialized programming tips.

  • Designing for Previous Versions of DirectInput
  • Preventing Response Delays During Debugging
  • Avoiding Duplicate Registry Keys
  • Force Editor
  • GetDeviceData and an Unacquired Device

Designing for Previous Versions of DirectInput

In the DirectInput8Create, IDirectInput8::Initialize, IDirectInputDevice8::Initialize, and IDirectInputEffect::Initialize methods, you are required to pass the Microsoft® DirectInput® version number. This parameter specifies which version of Microsoft DirectX® the DirectInput subsystem should emulate.

Applications designed for the latest version of DirectInput should pass the value DIRECTINPUT_VERSION as defined in Dinput.h.

Applications designed to run under previous versions should pass a value corresponding to the version of DirectInput for which they were designed, with the main version number in the high-order byte. For example, an application designed to run on DirectInput 3.0 should pass a value of 0x0300.

If you define DIRECTINPUT_VERSION as 0x0300 before including the Dinput.h header file, the header file generates structure definitions compatible with DirectInput 3.0.

If you do not define DIRECTINPUT_VERSION before including the Dinput.h header file, the header file generates structure definitions compatible with the current version of DirectInput. However, the DirectX 3–compatible structures are available under the same names with "_DX3" appended. For example, the DirectX 3–compatible DIDEVCAPS structure is called DIDEVCAPS_DX3.

You must also use the appropriate versions of the DirectInput and DirectInputDevice interfaces. For versions of DirectX prior to DirectX 7.0, you must use IDirectInput and either IDirectInputDevice or IDirectInputDevice2 (the latter is available for DirectX 5.0 or later.)

Preventing Response Delays During Debugging

When using the keyboard or mouse with DirectInput under Microsoft Windows® 2000, you might notice short delays in response when you step through code during a debugging session. This behavior occurs only in debug mode, so it is not seen by your application's end users. However, this behavior can be eliminated in debug mode as well by adding the emulation value to the following registry key.

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            DirectInput
Name | Type | Data
Emulation | DWORD | 0x08 (for the keyboard) 0x10 (for the mouse) 0x18 (for both)

You can also switch to use emulation from the DirectX control panel by following these steps.

  1. Open the Windows control panel
  2. Open the DirectX control panel. Note that if you are using Windows XP, you might need to click Switch to Classic View to see the DirectX icon.
  3. Select the DirectInput tab.
  4. In the Debug Input Device Emulation section, you can check the Emulate Keyboard and Emulate Mouse boxes.

Without changing how DirectInput returns data, this value invokes an emulation mode that is not susceptible to those delays. These settings are global and affect all DirectInput clients. Performance only improves when using the debug binaries and only for applications that employ foreground exclusive device access. Some features, such as masking the Windows keys, are not available when devices are emulated so emulation is recommended only for debugging.

Note If you are using earlier versions of DirectX, you must do a debug software development kit (SDK) install in order to get the correct debug dynamic-link library (DLL) onto your computer.

Avoiding Duplicate Registry Keys

For every application that uses DirectInput 8.0 or later versions, DirectInput creates a key in the following registry.

HKEY_CURRENT_USER
    SOFTWARE
        Microsoft
            DirectInput

This allows the independent hardware vendors (IHVs) to turn off their own device mapping for certain applications. During debugging, however, each build will generate a new key which contains a time stamp and the file size. To avoid generating multiple keys in the registry, use the binary value, AppldFlag.

The following table lists the possible values for AppldFlag.

1 | The time stamp is ignored when generating the key.
2 | The file size is ignored when generating the key.
3 | Both the time stamp and file size are ignored when generating the key.

If AppldFlag is set to 3, all builds of applications with the same file name will use the same key.

Note The AppldFlag value should only be set on test computers to avoid the possibility of two applications that ship with the same file name interfering with each other's input control mappings.

Force Editor

Force Editor has the following characteristics.

Description

The Force Editor application enables you to design force-feedback effects and test them singly or in combination. Effects can be saved to file and then loaded into DirectInput applications.

Path

Executable: (SDK root)\Bin\Dxutils\Fedit.exe

User's Guide

The Force Editor has its own documentation. When you've launched Fedit.exe, press F1 for online Help. The Help file can also be launched directly.

(SDK root)\Bin\Dxutils\Fedit.chm

GetDeviceData and an Unacquired Device

When using the debug version of Microsoft DirectPlay®, you may notice some unusual behavior from the IDirectInputDevice8::GetDeviceData method when a device is unacquired. If you call IDirectInputDevice8::GetDeviceData and the device is not acquired, random bytes will be placed in the device data buffer and the value of the pdwInOut parameter will not be changed. Therefore, if your application does not check for the DPNERR_UNACQUIRED error code, your application will mistakenly determine that there is data in the buffer.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput C/C++ Tutorials

This section contains five tutorials, each providing step-by-step instructions for implementing basic Microsoft® DirectInput® functionality in a C or C++ application.

Tutorials

  • Tutorial 1: Using the Keyboard
  • Tutorial 2: Using the Mouse
  • Tutorial 3: Using the Joystick
  • Tutorial 4: Using Force Feedback
  • Tutorial 5: Using Action Mapping

Note These tutorials are written using C++ style function calls. For instructions on writing Microsoft DirectX® function calls in a C environment, see Using C to Access COM Objects.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 1: Using the Keyboard

To prepare for keyboard input, first create an instance of a Microsoft® DirectInput® object. You then use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Object
  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard
  • Step 6: Retrieving Data from the Keyboard
  • Step 7: Closing Down the DirectInput System

Adding DirectInput keyboard support to an application is relatively simple, so this tutorial is not based on the complete Keyboard Sample application. All of the tutorial steps are illustrated by code fragments within the text. All related steps for initializing the system are gathered in Sample Function 1: DI_Init. Another function, Sample Function 2: DI_Term, is called whenever the system needs to be closed down. Much of the content of these functions are reused in subsequent tutorials.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Creating the DirectInput Object

The first step in setting up the Microsoft® DirectInput® system is to create a single DirectInput object as overall manager. This is done with a call to the DirectInput8Create function.

// HINSTANCE  g_hinst; // initialized earlier
HRESULT         hr;
LPDIRECTINPUT8  g_lpDI;

hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
        IID_IDirectInput8, (void**)&g_lpDI, NULL);
if FAILED(hr)
{
    // DirectInput not available; take appropriate action
}

The first parameter for DirectInput8Create is the instance handle to the application or dynamic-link library (DLL) that is creating the object.

The second parameter tells the DirectInput object which version of the DirectInput system should be used. You can design your application to be compatible with earlier versions of DirectInput. For more information, see Designing for Previous Versions of DirectInput.

The third parameter determines which interface is returned. Most applications obtain the most recent version, by passing IID_IDirectInput8.

The fourth parameter is the address of a variable that is initialized with a valid interface pointer if the call succeeds.

The last parameter specifies the address of the controlling object's IUnknown interface for use in Component Object Model (COM) aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

After creating a single DirectInput object as overall manager, go to Step 2: Creating the DirectInput Keyboard Device.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Creating the DirectInput Keyboard Device

After creating the Microsoft® DirectInput® object, your application must create the keyboard object—the device—and retrieve a pointer to an IDirectInputDevice8 interface. The device performs most of the keyboard-related tasks, using the methods of the interface.

To do this your application must call the IDirectInput8::CreateDevice method, as shown in Sample Function 1: DI_Init. IDirectInput8::CreateDevice accepts three parameters.

The first parameter is the globally unique identifier (GUID) for the device being created. Because the system keyboard is used, your application should pass the GUID_SysKeyboard predefined global variable.

The second parameter is the address of a variable that is initialized with the interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following example attempts to retrieve a pointer to an IDirectInputDevice8 interface. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

Note In all the examples, g_lpdi is the initialized pointer to the DirectInput object.
HRESULT               hr;
LPDIRECTINPUTDEVICE8  g_lpDIDevice

hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);
if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After creating the DirectInput keyboard device, go to Step 3: Setting the Keyboard Data Format.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Setting the Keyboard Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format, as shown in Tutorial 1 Samples. For keyboards, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided by Microsoft® DirectInput® in the c_dfDIKeyboard global variable.

The following example attempts to set the data format. If this fails, it calls the DI_Term sample function to deallocate existing DirectInput objects, if any.

hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard data format, go to Step 4: Setting the Keyboard Behavior.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Setting the Keyboard Behavior

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice8::SetCooperativeLevel method, as shown in Tutorial 1 Samples. This method accepts the handle to the window to be associated with the device and a combination of flags that determine the cooperative level. In this case the application is requesting foreground, nonexclusive access.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing Microsoft® DirectInput® objects, if any.

// Set the cooperative level

hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
        DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

 if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard behavior, go to Step 5: Gaining Access to the Keyboard.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Gaining Access to the Keyboard

After your application sets the keyboard's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8::Acquire method accepts no parameters.

The following line of sample code acquires the keyboard device that was created in Step 2: Creating the DirectInput Keyboard Device.

if (g_lpDIDevice) g_lpDIDevice->Acquire();

Now that your application has acquired access to the keyboard, go to Step 6: Retrieving Data from the Keyboard.

© 2002 Microsoft Corporation. All rights reserved.


Step 6: Retrieving Data from the Keyboard

After a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the IDirectInputDevice8::GetDeviceState method, which takes a snapshot of the device's state at the time of the call.

The IDirectInputDevice8::GetDeviceState method accepts two parameters: the size of a buffer to be filled with device state data, and a pointer to that buffer. For keyboards, always declare a buffer of 256 unsigned bytes.

The following sample attempts to retrieve the state of the keyboard. If this fails, it calls an application-defined sample function to deallocate existing Microsoft® DirectInput® objects, if any. For more information, see Sample Function 2: DI_Term.

After retrieving the keyboard's current state, your application can respond to specific keys that were pressed down at the time of the call. Each element in the buffer represents a key. If an element's high bit is 1, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the DirectInput Keyboard Device to index the buffer for a given key.

The following skeleton function, called from the main loop of a hypothetical spaceship game, uses the IDirectInputDevice8::GetDeviceState method to poll the keyboard. It then checks to see if the LEFT ARROW, RIGHT ARROW, UP ARROW or DOWN ARROW keys were pressed when the device state was retrieved. This is accomplished with the KEYDOWN macro defined in the body of the function. The macro accepts a buffer's variable name and an index value, and then checks the byte at the specified index to see if the high bit is set and returns TRUE if it is.

void WINAPI ProcessKBInput()
{
    #define KEYDOWN(name, key) (name[key] & 0x80)

     char     buffer[256];
    HRESULT  hr;

    hr = g_lpDIDevice->GetDeviceState(sizeof(buffer),(LPVOID)&buffer);
    if FAILED(hr)
    {
        // If it failed, the device has probably been lost.
        // Check for (hr == DIERR_INPUTLOST)
        // and attempt to reacquire it here.
        return;
    }

     // Turn the spaceship right or left
    if (KEYDOWN(buffer, DIK_RIGHT));
        // Turn right.
    else if(KEYDOWN(buffer, DIK_LEFT));
        // Turn left.

     // Thrust or stop the spaceship
    if (KEYDOWN(buffer, DIK_UP)) ;
        // Move the spaceship forward.
    else if (KEYDOWN(buffer, DIK_DOWN));
        // Stop the spaceship.
}

Now that your application can retrieve data from the keyboard, go to Step 7: Closing Down the DirectInput System.

© 2002 Microsoft Corporation. All rights reserved.


Step 7: Closing Down the DirectInput System

When an application is about to close, it should destroy all Microsoft® DirectInput® objects. This is a three-step process.

  • Release access to all DirectInput devices (IDirectInputDevice8::Unacquire).
  • Release all DirectInput devices (IDirectInputDevice8::Release).
  • Release the DirectInput object (IDirectInput8::Release).

For a sample function that closes down the DirectInput system, see Sample Function 2: DI_Term.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 1 Samples

Sample Function 1: DI_Init

This application-defined sample function creates a Microsoft® DirectInput® object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. For more information, see Sample Function 2: DI_Term.

In addition to creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps.

  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard

The following is the DI_Init function.

/* The following variables are presumed to be initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/

LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;

BOOL WINAPI DI_Init()
{
    HRESULT hr;

    // Create the DirectInput object.
    hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
                            IID_IDirectInput8, (void**)&g_lpDI, NULL);

    if FAILED(hr) return FALSE;

    // Retrieve a pointer to an IDirectInputDevice8 interface
    hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Now that you have an IDirectInputDevice8 interface, get
    // it ready to use.

    // Set the data format using the predefined keyboard data
    // format provided by the DirectInput object for keyboards.

    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Set the cooperative level
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                             DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Get access to the input device.
    hr = g_lpDIDevice->Acquire();
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    return TRUE;
}

Sample Function 2: DI_Term

This application-defined sample function deallocates existing DirectInput interface pointers in preparation for program shutdown or in the event of a failure to properly initialize a device.

/* The following variables are presumed initialized:
LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;
*/

void WINAPI DI_Term()
{
    if (g_lpDI)
    {
        if (g_lpDIDevice)
        {
        // Always unacquire device before calling Release().
            g_lpDIDevice-&gt;Unacquire();
            g_lpDIDevice-&gt;Release();
            g_lpDIDevice = NULL;
        }
        g_lpDI-&gt;Release();
        g_lpDI = NULL;
    }
}

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 2: Using the Mouse

This tutorial guides you through the process of setting up a mouse device and retrieving buffered input data. The examples are based on the Scrawl Sample.

To prepare for mouse input, you first create an instance of a Microsoft® DirectInput® object. Then you use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The first step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Mouse Device
  • Step 2: Setting the Mouse Data Format
  • Step 3: Setting the Mouse Behavior
  • Step 4: Preparing for Buffered Input from the Mouse
  • Step 5: Managing Access to the Mouse
  • Step 6: Retrieving Buffered Data from the Mouse
Note When an application acquires the mouse at the exclusive cooperative level, Microsoft Windows® does not show a pointer on the screen. For this, your application needs a simple sprite engine. The Scrawl sample application uses the Microsoft Win32® function DrawIcon to display a crosshair cursor.

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Creating the DirectInput Mouse Device

After creating the Microsoft® DirectInput® object, your application should retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most mouse-related tasks. To do this, call the IDirectInput8::CreateDevice method.

The first parameter of IDirectInput8::CreateDevice is the globally unique identifier (GUID) for the device your application is creating. In this case, because the system mouse is used, your application should pass the predefined global variable GUID_SysMouse.

The second parameter is the address of a variable that is initialized with a valid IDirectInputDevice8 interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following sample code attempts to retrieve a pointer to an IDirectInputDevice8 interface. If the call fails, FALSE is returned. It is assumed that g_pDI is a valid pointer to IDirectInput8.

LPDIRECTINPUTDEVICE g_pMouse;
HRESULT             hr;

hr = g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL);

if (FAILED(hr)) {
    return FALSE;
}

After creating the DirectInput mouse device, go to Step 2: Setting the Mouse Data Format.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Setting the Mouse Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format. For mouse devices, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided for your convenience by Microsoft® DirectInput® in the c_dfDIMouse global variable.

The following code fragment attempts to set the device's data format. If the call fails, FALSE is returned.

hr = g_pMouse->SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse data format, go to Step 3: Setting the Mouse Behavior.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Setting the Mouse Behavior

Before it can gain access to the mouse, your application must set the mouse device's behavior using the IDirectInputDevice8::SetCooperativeLevel method. This method accepts the handle to the window to be associated with the device. In Scrawl, the DISCL_EXCLUSIVE flag is included to ensure that this application is the only one that can have exclusive access to the device. This flag is combined with DISCL_FOREGROUND because Scrawl should not allow data input when another application is in the foreground.

The following code sample attempts to set the device's cooperative level. If this attempt fails, FALSE is returned. It is assumed that hWnd is a valid window handle.

hr = g_pMouse->SetCooperativeLevel(hWnd,
               DISCL_EXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse behavior, go to Step 4: Preparing for Buffered Input from the Mouse.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Preparing for Buffered Input from the Mouse

The Scrawl application demonstrates how to use event notification to find out about mouse activity, and how to read buffered input from the mouse. Both of these techniques require some setup. You can perform these steps at any time after creating the mouse device and before acquiring it.

First, create an event and associate it with the mouse device. You are instructing Microsoft® DirectInput® to notify the mouse device object whenever a hardware interrupt indicates that new data is available.

This is how it is done in Scrawl, where g_hevtMouse is a global HANDLE.

g_hMouseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

if (g_hMouseEvent == NULL) {
    return FALSE;
}

hr = g_pMouse->SetEventNotification(g_hMouseEvent);

if (FAILED(hr)) {
    return FALSE;
}

Now set the buffer size so that DirectInput can store any input data until you are ready to view it. Note that by default the buffer size is zero, so this step is essential if you want to use buffered data.

It is not necessary to used buffered data with event notification. If you prefer, you can retrieve immediate data when an event is signaled.

To set the buffer size, initialize a DIPROPDWORD structure with information about itself and about the property you want to set. Most of the values are boilerplate. The key value is the last one, dwData, which is initialized with the number of items you want the buffer to hold.

#define SAMPLE_BUFFER_SIZE  16

DIPROPDWORD dipdw;
    // the header
    dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj        = 0;
    dipdw.diph.dwHow        = DIPH_DEVICE;
    // the data
    dipdw.dwData            = SAMPLE_BUFFER_SIZE;

You then pass the address of the header (the DIPROPHEADER structure within the DIPROPDWORD structure ), along with the identifier of the property you want to change, to the IDirectInputDevice8::SetProperty method, as follows:

hr = g_pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

if (FAILED(hr)) {
    return FALSE;
}

The setup is now complete, and you are ready to acquire the mouse and start collecting data.

After preparing your application for buffered input from the mouse, go to Step 5: Managing Access to the Mouse.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Managing Access to the Mouse

Microsoft® DirectInput® provides the IDirectInputDevice8::Acquire and IDirectInputDevice8::Unacquire methods to manage device access. Your application must call the IDirectInputDevice8::Acquire method to gain access to the device before requesting mouse information with the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods.

Most of the time your application has the device in an acquired state. However, if you have only foreground access, the mouse is automatically unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.

Scrawl handles this message by setting a global variable, g_bActive, according to whether the application is gaining or losing the focus. It then calls a helper function, SetAcquire, which acquires the mouse if g_bActive is TRUE and unacquires it otherwise.

case WM_ACTIVATE:
    if (WA_INACTIVE == wParam)
        g_bActive = FALSE;
    else
        g_bActive = TRUE;

    // Set exclusive mode access to the mouse based on active state
    SetAcquire();
    return 0;

If you have exclusive access, your application might need to unacquire the mouse to enable the user to interact with Microsoft Windows®—for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.

The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_bActive to FALSE and calling the SetAcquire function. This handler enables Windows to have the mouse and display its own cursor.

When the user is done using a menu, Windows sends the application a WM_EXITSIZEMOVE message. In this case, the Scrawl window process sets g_bActive appropriately and calls SetAcquire.

Scrawl also unacquires the mouse in response to a right-button click, which displays a shortcut menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it is unacquired here first so that the position of the Windows cursor can be set before the menu appears.

Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.

In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to surrender access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.

Once your application can manage access to the mouse, go to Step 6: Retrieving Buffered Data from the Mouse.

© 2002 Microsoft Corporation. All rights reserved.


Step 6: Retrieving Buffered Data from the Mouse

Once the mouse is acquired, your application can begin to retrieve data from it.

In the Scrawl sample, retrieval is triggered by a signaled event. In the WinMain function, the application sleeps until MsgWaitForMultipleObjects indicates that there is either a signal or a message. If there is a signal associated with the mouse, the OnMouseInput function is called. This function is a good illustration of how buffered input is handled, as shown in the following process.

First, the function makes sure that the old cursor position is cleaned up. Note that Scrawl is maintaining its own cursor and is wholly responsible for drawing and erasing it.

VOID OnMouseInput(HWND hWnd)
{
    /* Invalidate the old cursor so that it will be erased */
    InvalidateCursorRect(hWnd);

Next, the function enters a loop to read and respond to the entire contents of the buffer. Because it retrieves just one item at a time, it needs only a single DIDEVICEOBJECTDATA structure to hold the data.

    while (!bDone) {
        DIDEVICEOBJECTDATA od;
        DWORD dwElements = 1;   // number of items to be retrieved
Note Another way to go about handling input would be to read the entire buffer at once and then loop through the retrieved items, responding to each one in turn. In that case, dwElements would be the size of the buffer, and od would be an array with the same number of elements.

The application calls the IDirectInputDevice8::GetDeviceData method in order to fetch the data. The second parameter tells Microsoft® DirectInput® where to put the data, and the third tells it how many items are wanted. The final parameter would be DIGDD_PEEK if the data was to be left in the buffer, but in this case the data is not needed again, and so it is removed.

        hr = g_pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA),
                                     &od, &dwElements, 0);

Next, the application checks to see if access to the device has been lost and, if so, attempts to reacquire the mouse at the first opportunity. This step was discussed in Step 5: Managing Access to the Mouse.

        if (hr == DIERR_INPUTLOST)
        {
            SetAcquire();
            break;
        }

Next, the application makes sure the call to the IDirectInputDevice8::GetDeviceData method succeeded and that there was actually data to be retrieved. Note that after the call to IDirectInputDevice8::GetDeviceData the dwElements variable shows how many items were actually retrieved.

        /* Unable to read data or no data available */

        if (FAILED(hr) || dwElements == 0)
        {
            break;
        }

If execution has proceeded to this point, the call succeeded and there is an item of data in the buffer. Now the application looks at the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which object on the device reported a change of state, and it calls helper functions to respond appropriately. The value of the dwData member, which contains information about what occurred with the device object, is passed to these functions.

        /* View the element to see what occurred */

        switch (od.dwOfs)
        {
            // Mouse horizontal motion
            case DIMOFS_X:
                UpdateCursorPosition(od.dwData, 0);
                break;

            // Mouse vertical motion
            case DIMOFS_Y:
                UpdateCursorPosition(0, od.dwData);
                break;

            // DIMOFS_BUTTON0: Right button pressed or released
            case DIMOFS_BUTTON0:

            // DIMOFS_BUTTON1: Left button pressed or released
            case DIMOFS_BUTTON1:
                // Is the right button or a swapped left button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs))
                {
                    if (od.dwData & 0x80)  // Left button pressed, so
                                           // go into button-down mode
                    {
                        bDone = TRUE;
                        OnLeftButtonDown(hWnd);
                    }
                // Is the left button or a swapped right button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs))
                {
                    if(!(od.dwData & 0x80))  // button release, so
                                             // check shortcut menu
                    {
                        bDone = TRUE;
                        OnRightButtonUp(hWnd);
                    }
                }
                break;
        }

Finally, in the event that the cursor has been moved by one of the helper functions, the OnMouseInput sample function invalidates the screen rectangle occupied by the cursor.

    // Invalidate the new cursor so that it will be drawn
    InvalidateCursorRect(hWnd);
}

Scrawl also collects mouse data in the OnLeftButtonDown function. This is where the application keeps track of mouse movements while the primary button is being held down—that is, while the user is drawing. This function does not rely on event notification, but repeatedly polls the DirectInput buffer until the button is released.

Note that in the OnLeftButtonDown function no drawing is done until all pending data has been read. This is because each horizontal or vertical movement of the mouse is reported as a separate event. (Both events are, however, placed in the buffer at the same time. ) If a line were immediately drawn in response to each separate axis movement, a diagonal mouse movement would produce two lines at right angles.

Another way you can be sure that the movement in both axes is taken into account before responding in your application is to check the sequence numbers of the x-axis item and the y-axis item. If the numbers are the same, the two events took place simultaneously. For more information, see Time Stamps and Sequence Numbers.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 3: Using the Joystick

This tutorial shows you how to enumerate a joystick attached to a system and set it up for input. Code samples are based on the Joystick Sample.

The first step of setting up the Microsoft® DirectInput® system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

The first step in this tutorial is to enumerate devices; that is, to see what joysticks are available. As part of this process you initialize each joystick device and set its desired characteristics. You then use the IDirectInputDevice8 interface methods to retrieve data from each joystick.

This tutorial divides the required tasks into the following steps.

Steps

  • Step 1: Enumerating the Joysticks
  • Step 2: Creating the DirectInput Joystick Device
  • Step 3: Setting the Joystick Data Format
  • Step 4: Setting the Joystick Behavior
  • Step 5: Gaining Access to the Joystick
  • Step 6: Retrieving Data from the Joystick

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Enumerating the Joysticks

After creating the Microsoft® DirectInput® system, call the IDirectInput8::EnumDevices method to enumerate the joysticks, as in the following sample code.

//g_pDI is an initialized pointer to IDirectInput8
g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback,
                       NULL, DIEDFL_ATTACHEDONLY)

The DI8DEVCLASS_GAMECTRL constant, passed as the first parameter, specifies the class of device to be enumerated.

EnumJoysticksCallback is the address of a callback function to be called each time a joystick is found. This is where the individual devices are created in Step 2: Creating the DirectInput Joystick Device.

The third parameter can be any 32-bit value that you want to make available to the callback function. In this case, nothing is being sent.

The last parameter, DIEDFL_ATTACHEDONLY, is a flag that restricts enumeration to devices that are attached to the computer.

When your application can enumerate the joysticks, go to Step 2: Creating the DirectInput Joystick Device.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Creating the DirectInput Joystick Device

After creating the Microsoft® DirectInput® object, the application must retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most joystick-related tasks. In the Joystick Sample, this is done in the callback function EnumJoysticksCallback, which is called each time a joystick is enumerated.

The following sample code is the first part of the callback function.

BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE*
                                       pdidInstance, VOID* pContext)
{
    HRESULT hr;

    // Obtain an interface to the enumerated joystick.
    hr = g_pDI->CreateDevice(pdidInstance->guidInstance,
                                &g_pJoystick, NULL);
    if(FAILED(hr))
        return DIENUM_CONTINUE;

    return DIENUM_STOP;

The EnumJoysticksCallback callback function parameters are as follows:

  • A pointer to the device instance, supplied by the DirectInput system when the device is enumerated.
  • A pointer to a 32-bit value that you supplied as a parameter to IDirectInput8::EnumDevices. This parameter could be any 32-bit value such as a pointer to an interface so that you could use its methods. In this case, however, NULL was passed.

The first task of the callback function is to create the device. The IDirectInput8::CreateDevice method accepts three parameters.

The first parameter is a reference to the globally unique identifier (GUID) for the instance of the device. In this case, the GUID is taken from the DIDEVICEINSTANCE structure supplied by DirectInput when it enumerated the device.

The second parameter is the address of the variable that is initialized with a valid interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. The Joystick Sample does not use aggregation, so the parameter is NULL.

Note that if the device interface cannot be created, DIENUM_CONTINUE is returned from the callback function. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

After creating the DirectInput joystick device, go to Step 3: Setting the Joystick Data Format.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Setting the Joystick Data Format

Now that the application has a pointer to a Microsoft® DirectInput® device, it can call the IDirectInputDevice8 methods to manipulate that device. The first step, which is essential, is to set the data format for the joystick. This step tells DirectInput how to format the input data.

if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))
    return hr;

The IDirectInputDevice8::SetDataFormat method takes one parameter, a pointer to a DIDATAFORMAT structure containing information about how the data for the device is to be formatted. For the joystick, you can use the predefined global variable c_dfDIJoystick2, which signifies use of the DIJOYSTATE2 structure to retrieve data.

After setting the joystick data format, go to Step 4: Setting the Joystick Behavior.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Setting the Joystick Behavior

The joystick device has been created, and its data format has been set. The next step is to set its cooperative level. As in the previous step, g_pJoystick is a pointer to the device interface.

if (FAILED(hr = g_pJoystick->SetCooperativeLevel(hDlg,
                    DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
    return hr;

The first parameter to IDirectInputDevice8::SetCooperativeLevel is a window handle. In this case, the handle to the dialog box serving as the main program window is passed to the function.

The final parameter is a combination of flags describing the desired cooperative level. The Joystick sample requires input from the joystick only when it is the foreground application. Also, when the joystick sample is in the foreground, it should be the only application with exclusive access to the joystick. Therefore, the flags are set to DISCL_EXCLUSIVE | DISCL_FOREGROUND. See Cooperative Levels for a full explanation of these flags.

The next step is to gather information about the capabilities of the joystick. This information includes the number of axes, buttons, and other controllers, whether the device supports force feedback, and other details about the joystick's behavior and supported options.

A DIDEVCAPS structure is used to hold the capability information. The dwSize member of the DIDEVCAPS structure must first be initialized, then the address of the structure sent to IDirectInputDevice8::GetCapabilities. In the example below, g_diDevCaps is a previously declared DIDEVCAPS structure.

g_diDevCaps.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = g_pJoystick->GetCapabilities(&g_diDevCaps)))
    return hr;

At this point, you could proceed using the device defaults or you could customize the device properties. The Joystick sample enumerate the axes on the joystick and sets a range for each by calling IDirectInputDevice8::EnumObjects.

if (FAILED(hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                       (VOID*)hDlg, DIDFT_AXIS)))
    return hr;

The first parameter to the IDirectInputDevice8::EnumObjects method, EnumAxesCallback, is the address of a callback function which processes the enumerated objects as desired.

The second parameter can be any 32-bit value that you might want to provide to the callback function. Here, the handle to the main dialog window is passed so that it can update the display to indicate which axes are found on the joystick.

The last parameter, DIDFT_AXIS, tells the callback function to enumerate only device axes.

In the sample, the properties changed will be the range for any axis or slider detected (a slider is considered an axis ).

By setting the range, you are telling Microsoft® DirectInput® what maximum and minimum values you want returned for an axis. If you set a range of -1,000 to +1,000 for the x-axis, as in the example, you are asking that a value of -1,000 be returned when the stick is at the extreme left, +1,000 when it is at the extreme right, and zero when it is in the middle.

The following sample code sets the range of an enumerated axis. The pdidoi variable is the address of a DIDEVICEOBJECTINSTANCE structure passed by the system to the callback function. This variable contains information about the object currently being enumerated.

DIPROPRANGE diprg;

diprg.diph.dwSize       = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow        = DIPH_BYID;
diprg.diph.dwObj        = pdidoi->dwType;
diprg.lMin              = -1000;
diprg.lMax              = +1000;
.
.
hr = g_pJoystick->SetProperty(DIPROP_RANGE, &diprg.diph);
if (FAILED(hr))
    return DIENUM_STOP;

The first task here is to set up the DIPROPRANGE structure diprg, whose address is passed into the IDirectInputDevice8::SetProperty method. Note that it is not the address of the structure itself that is passed but rather the address of its first member, which is a DIPROPHEADER structure. For more information, see Device Properties.

The property header is initialized with the following values.

  • The size of the property structure
  • The size of the header structure
  • A flag to indicate how the dwObj member is to be interpreted.
  • The value found in the dwType member of the DIDEVICEOBJECTINSTANCE structure indicating the object whose property is being changed.

The lmin and lmax members of the DIPROPRANGE structure are assigned the desired range values.

The application now calls the IDirectInputDevice8::SetProperty method. The first parameter is a flag indicating which property is being changed. The second parameter is the address of the DIPROPHEADER member of the property structure.

After setting the joystick behavior, go to Step 5: Gaining Access to the Joystick.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Gaining Access to the Joystick

After your application sets a joystick's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8::Acquire method accepts no parameters.

The Joystick sample performs initial acquisition in the message loop as the application is activated. This loop also automatically reacquires the device whenever the application regains focus after having lost it. Acquisition is also performed if access to the joystick is lost or a DIERR_INPUTLOST error is returned when the application attempts to get input data. This is shown in the following code sample.

hr = g_pJoystick->Poll();
if (FAILED(hr))
{
    hr = g_pJoystick->Acquire();
    while(hr == DIERR_INPUTLOST)
        hr = g_pJoystick->Acquire();
    return S_OK;
}

Once your application can gain access to the joystick go to Step 6: Retrieving Data from the Joystick.

© 2002 Microsoft Corporation. All rights reserved.


Step 6: Retrieving Data from the Joystick

Because your application is more likely concerned with the position of the joystick axes than with their movement, you probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice8::GetDeviceState. Note that not all device drivers notify Microsoft® DirectInput® when the state of the device changes. Therefore, it is always good policy to call the IDirectInputDevice8::Poll method before checking the device state.

The Joystick application calls the following function from the Microsoft Windows® message loop.

HRESULT UpdateInputState(HWND hDlg)
{
    HRESULT     hr;
    CHAR        strText[128]; // Device state text
    DIJOYSTATE2 js;           // Direct Input joystick state
    CHAR*       str;

    if (NULL == g_pJoystick)
        return S_OK;

    // Poll the device to read the current state
    hr = g_pJoystick->Poll();
    if (FAILED(hr))
    {
        // Attempt to reacquire joystick
    }
    hr = g_pJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &js);
    if (FAILED(hr))
        return hr;

Note the call to IDirectInputDevice8::GetDeviceState. The first parameter is the size of the structure in which the data is returned, and the second parameter is the address of this structure, which is of type DIJOYSTATE2. This structure holds data for up to six axes, 128 buttons, and four point-of-view hats. The sample program proceeds to view the state of all axes and buttons, and one slider. This information is then displayed in the main dialog window.

Joystick buttons work just like keys or mouse buttons. If the high bit of the returned byte is 1, the button is pressed.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 4: Using Force Feedback

This tutorial takes you through the process of creating, playing, and modifying a simple effect on a force-feedback joystick. The effect is based on the feel of running a chain saw. Effects are created that simulate a chain saw starting with some difficulty, running normally, and cutting into wood.

The first step of setting up the Microsoft® DirectInput® system and the final step of closing it down are essentially the same for any application and are covered in Tutorial 1: Using the Keyboard. However, when closing down the DirectInput force-feedback system, you are required to take the additional step of releasing any effects you have created.

This tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating Force-Feedback Devices
  • Step 2: Creating the DirectInput Force-Feedback Device
  • Step 3: Enumerating Supported Effects
  • Step 4: Creating an Effect
  • Step 5: Playing an Infinite Effect
  • Step 6: Changing an Effect

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Enumerating Force-Feedback Devices

The first step is to ensure that a force-feedback device is available on the system. You do this by calling the IDirectInput8::EnumDevices method. In the following example, the global pointer to the game device interface is initialized only if the enumeration has succeeded in finding at least one suitable device:

LPDIRECTINPUTDEVICE8  g_lpDIDevice = NULL;

hr = g_lpDI->EnumDevices(DI8DEVTYPE_GAMECTRL,
                         DIEnumDevicesProc,
                         NULL,
                         DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
  // No force-feedback joystick available; take appropriate action.
}

In the example, g_lpDI is an initialized pointer to the IDirectInput8 interface. The first parameter to IDirectInput8::EnumDevices restricts the enumeration to joystick-type devices. The second parameter is the callback function that is called whenever Microsoft® DirectInput® identifies a device that qualifies for enumeration. The third parameter is for user-defined data to be passed in or out of the callback function; in this case it is not used. Finally, the flags further restrict the enumeration to devices attached to the system that support force feedback.

The callback function is a convenient place to initialize the device as soon as it has been found. (It is assumed that the first device found is the one you want to use.) You do this in Step 2: Creating the DirectInput Force-Feedback Device.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Creating the DirectInput Force-Feedback Device

To have Microsoft® DirectInput® enumerate devices, create a callback function of the same type as DIEnumDevicesCallback. In Step 1 you passed the address of this function to the IDirectInput8::EnumDevices method.

DirectInput passes into the callback, as the first parameter, a pointer to a DIDEVICEINSTANCE structure that tells you what you need to know about the device. The structure member of most interest in the example is guidInstance, the unique identifier for the particular piece of hardware on the user's system. You must pass this globally unique identifier (GUID) to the IDirectInput8::CreateDevice method.

The following code fragment is the first part of the callback, which extracts the GUID and creates the device object.

BOOL CALLBACK DIEnumDevicesProc( LPCDIDEVICEINSTANCE lpddi,
                                 LPVOID pvRef )
{
    HRESULT hr;
    GUID DeviceGuid = lpddi->guidInstance;

    // Create game device.

    hr = g_lpDI->CreateDevice(DeviceGuid, &g_lpDIDevice, NULL);

    if (FAILED(hr))
        // Continue enumerating until successful or finished
        return DIENUM_CONTINUE;

The next steps of the callback function are similar to those for setting up any input device. Note that you need the exclusive cooperative level for any force-feedback device.

    // Set cooperative level.
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                                  DISCL_EXCLUSIVE | DISCL_FOREGROUND);
    if (FAILED(hr))
        return hr;

    // set game data format
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIJoystick);
    if (FAILED(hr))
        return hr;

Finally, you might want to turn off the device's autocenter feature. Autocenter is essentially a condition effect that uses the motors to simulate the springs in a standard joystick. It is a good idea to turn it off so that it does not interfere with other effects.

    DIPROPDWORD DIPropAutoCenter;

    DIPropAutoCenter.diph.dwSize       = sizeof(DIPropAutoCenter);
    DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    DIPropAutoCenter.diph.dwObj        = 0;
    DIPropAutoCenter.diph.dwHow        = DIPH_DEVICE;
    DIPropAutoCenter.dwData            = DIPROPAUTOCENTER_OFF;

    hr = g_lpDIDevice->SetProperty(DIPROP_AUTOCENTER,
                                   &DIPropAutoCenter.diph);
    if (FAILED(hr))
    {
        // Handle the failure as appropriate
    }

    return DIENUM_STOP;   // One is enough.
}   // end DIEnumDevicesProc

Before using the device, you must acquire it. See Step 5: Gaining Access to the Joystick in Tutorial 3: Using the Joystick for an example of how to handle acquisition. Note that unlike other property changes, force-feedback effects can be downloaded to a device when it is in an acquired state.

After you have created the DirectInput force-feedback device, go to Step 3: Enumerating Supported Effects.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Enumerating Supported Effects

Now that you have successfully enumerated and created a force-feedback device, you can enumerate the effect types it supports.

Effect enumeration is not strictly necessary if you want to create only standard effects that will be available on any device, such as constant forces. When creating the effect object, you can identify the desired effect type by using one of the predefined globally unique identifiers (GUIDs), such as GUID_ConstantForce. For a complete list of these identifiers, see IDirectInputDevice8::CreateEffect.

Another more flexible approach is to enumerate supported effects of a particular type, then obtain the GUID for the effect from the callback function. You could use the callback to obtain more information about the device's support for the effect— for example, whether it supports an envelope—but in this tutorial you obtain only the effect GUID.

First, create the callback function that Microsoft® DirectInput® calls for each effect enumerated. For information about this standard callback, see DIEnumEffectsCallback. You can give the function any name you like.

BOOL  EffectFound = FALSE;  // global flag
BOOL CALLBACK DIEnumEffectsProc(LPCDIEFFECTINFO pei, LPVOID pv)
{
    *((GUID *)pv) = pei->guid;
    EffectFound = TRUE;
    return DIENUM_STOP;  // one is enough
}

The GUID variable pointed to by the application-defined value pv is assigned the value passed in the DIEFFECTINFO structure created by DirectInput for the effect.

To obtain the effect GUID, set the callback in motion by calling the IDirectInputDevice8::EnumEffects method, as follows:

HRESULT  hr;
GUID     guidEffect;
hr = g_lpDIDevice->EnumEffects(
                         (LPDIENUMEFFECTSCALLBACK) DIEnumEffectsProc,
                          &guidEffect,
                          DIEFT_PERIODIC);
if (FAILED(hr))
{
    // Note that success does not mean that any effects were found,
    // only that the process went smoothly.
}

Note that you pass the address of a GUID variable, guidEffect, to the IDirectInputDevice8::EnumEffects method. This address is passed in turn to the callback as the pv parameter. You also restrict the enumeration to periodic effects by setting the flag DIEFT_PERIODIC.

Once your application can enumerate supported effects, go to Step 4: Creating an Effect.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Creating an Effect

If the EffectFound value is no longer FALSE after effect enumeration, you can safely assume that Microsoft® DirectInput® has found support for at least one effect of the periodic type you requested by passing the DIEFT_PERIODIC flag. Knowing the effect globally unique identifier (GUID), you can now create the effect object.

Before calling the IDirectInputDevice8::CreateEffect method, you set up the following arrays and structures.

  • An array of axes that will be involved in the effect. For a joystick, this array normally consists of the identifiers for the x-axis and the y-axis.
  • An array of values for setting the direction. The values differ according to both the number of axes and whether you want to use polar, spherical, or Cartesian coordinates. For a full explanation, see Effect Direction.
  • A structure of type-specific parameters. In the example, because you are creating a periodic effect, this is of type DIPERIODIC.
  • A DIENVELOPE structure for defining an envelope to be applied to the effect.
  • A DIEFFECT structure to contain the basic parameters for the effect.

Arrays can be initialized when they, along with the structures, are declared.

DWORD      dwAxes[2] = {DIJOFS_X, DIJOFS_Y};
LONG       lDirection[2] = {0, 0};

DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

Next, initialize the type-specific parameters. The values in this example create a full-force periodic effect with a period of one-twentieth of a second.

diPeriodic.dwMagnitude = DI_FFNOMINALMAX;
diPeriodic.lOffset = 0;
diPeriodic.dwPhase = 0;
diPeriodic.dwPeriod = (DWORD)(0.05 * DI_SECONDS);

To produce an effect of the chain-saw motor trying to start, briefly coughing into life, and then slowly dying, you set an envelope with an attack time of one-half second and a fade time of one second.

diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0;
diEnvelope.dwAttackTime = (DWORD)(0.5 * DI_SECONDS);
diEnvelope.dwFadeLevel = 0;
diEnvelope.dwFadeTime = (DWORD)(1.0 * DI_SECONDS);

Next, set up the basic effect parameters. These include flags to determine how the directions and device objects (buttons and axes) are identified, the sample period and gain for the effect, and pointers to the other data that you have just prepared. You also associate the effect with the joystick's fire button so that it is automatically played whenever that button is pressed.

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = (DWORD)(2 * DI_SECONDS);

diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0;
diEffect.dwTriggerRepeatInterval = 0;
diEffect.cAxes = 2;
diEffect.rgdwAxes = dwAxes;
diEffect.rglDirection = &lDirection[0];
diEffect.lpEnvelope = &diEnvelope;
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;

Finally, you can create the effect.

LPDIRECTINPUTEFFECT  g_lpdiEffect;  // global effect object

hr = g_lpDIDevice->CreateEffect(
                     guidEffect,     // GUID from enumeration
                     &diEffect,      // where the data is
                     &g_lpdiEffect,  // where to put interface pointer
                     NULL);          // no aggregation
if (FAILED(hr))
{
    return hr;
}

Note that, by default, the effect is downloaded to the device as soon as it has been created, provided that the device is in an acquired state at the exclusive cooperative level. You should now be able to compile, run, press the fire button, and feel the sputtering of a chain saw that's out of gas.

After creating an effect object, go to Step 5: Playing an Infinite Effect.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Playing an Infinite Effect

The effect created in the previous step starts in response to the press of a button. To create an effect that is to be played in response to an explicit call, return to Step 4: Creating an Effect and modify the dwTriggerButton member of the DIEFFECT structure as follows:

diEffect.dwTriggerButton = DIEB_NOTRIGGER;

To make a chain saw that starts and keeps going, change the dwDuration member as follows:

diEffect.dwDuration = INFINITE;

Next, start the effect.

g_lpdiEffect->Start(1, 0);

The effect keeps running until you stop it.

g_lpdiEffect->Stop();

Note that it is not necessary to change the envelope you created in the previous step. The attack is played as the effect starts, but the fade value is ignored.

Once your application can play an infinite effect, go to Step 6: Changing an Effect.

© 2002 Microsoft Corporation. All rights reserved.


Step 6: Changing an Effect

Next, you modify the effect to simulate the slowing down of the engine as the saw bites into wood. Microsoft® DirectInput® enables you to modify the parameters of an effect while it is playing.

To change the effect, set up a new DIEFFECT structure or have access to the one you used to create the effect. If you are setting up a new structure with local scope, initialize only the dwSize member and any members that contain or point to data that is to be changed.

In this case, you want to change a type-specific parameter—the period of the effect—so you need to have access to the DIPERIODIC structure you used when creating the effect. Alternatively, you can create a local copy with all members initialized. Make sure that the address of the DIPERIODIC structure is in the lpvTypeSpecificParams member of the DIEFFECT structure.

First, set the new period of the effect.

diPeriodic.dwPeriod = (DWORD)(0.08 * DI_SECONDS);

Next, call the IDirectInputEffect::SetParameters method to make the changes.

hr = g_lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

Note the DIEP_TYPESPECIFICPARAMS flag that restricts the changes to a single member of the DIEFFECT structure.

You can control the way changes are handled by using other flags. For example, by using the DIEP_NODOWNLOAD flag you could change the parameters immediately after starting the effect but delay the implementation until a specific call to the IDirectInputEffect::Download method. For more information concerning use of the various control flags, see IDirectInputEffect::SetParameters.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 5: Using Action Mapping

This tutorial guides you through the setup, modification, and application of an action map. Examples are based written as though they were to be used in a space combat game.

The first step of setting up the Microsoft® DirectInput® system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard. The keyboard, a mouse, and a joystick are all used in the sample, so each of those devices needs to be set up.

This tutorial divides the required tasks into the following steps.

  • Step 1: Defining the Game Actions
  • Step 2: Defining the Action Map
  • Step 3: Mapping Actions to Devices
  • Step 4: Configuring and Applying the Action Map
  • Step 5: Displaying the Action Map
  • Step 6: User Configuration of the Action Map
  • Step 7: Retrieval of Action Mapped Data

© 2002 Microsoft Corporation. All rights reserved.


Step 1: Defining the Game Actions

The first step toward creating an action map is the definition of the game actions. These actions are specific to the application and are defined by the developer. In the case of this example, the actions chosen reflect its needs as a space combat simulator. These values can be defined in many ways as the developer sees fit. They could be defined as an enumeration, as in the Preparing the Action Map overview, or they could be defined as constants as in this code fragment.

#define INPUT_LEFTRIGHT_AXIS   1L
#define INPUT_UPDOWN_AXIS      2L
#define INPUT_TURNLEFT         3L
#define INPUT_TURNRIGHT        4L
#define INPUT_FORWARDTHRUST    5L
#define INPUT_REVERSETHRUST    6L
#define INPUT_FIREWEAPONS      7L
#define INPUT_ENABLESHIELD     8L
#define INPUT_DISPLAYGAMEMENU  9L
#define INPUT_QUITGAME        10L

Once these values are defined, they can be assigned to genre-specific action-mapping constants. This is done in Step 2: Defining the Action Map.

© 2002 Microsoft Corporation. All rights reserved.


Step 2: Defining the Action Map

Next, each game action should be assigned to at least one virtual control or device object. These controls are defined as action-mapping constants and are defined by genre and subgenre. In this case, the best choice is the Space Combat subgenre of the flight-games genre. This subgenre makes the following constants available.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL

DIAXIS_SPACESIM_MOVE

DIAXIS_SPACESIM_THROTTLE

DIBUTTON_SPACESIM_FIRE

DIBUTTON_SPACESIM_MENU

DIBUTTON_SPACESIM_TARGET

DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls
DIAXIS_SPACESIM_CLIMB

DIAXIS_SPACESIM_ROTATE

DIBUTTON_SPACESIM_BACKWARD_LINK

DIBUTTON_SPACESIM_DEVICE

DIBUTTON_SPACESIM_DISPLAY

DIBUTTON_SPACESIM_FASTER_LINK

DIBUTTON_SPACESIM_FIRESECONDARY

DIBUTTON_SPACESIM_FORWARD_LINK

DIBUTTON_SPACESIM_GEAR

DIBUTTON_SPACESIM_GLANCE_DOWN_LINK

DIBUTTON_SPACESIM_GLANCE_LEFT_LINK

DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK

DIBUTTON_SPACESIM_GLANCE_UP_LINK

DIBUTTON_SPACESIM_LEFT_LINK

DIBUTTON_SPACESIM_LOWER

DIBUTTON_SPACESIM_PAUSE

DIBUTTON_SPACESIM_RAISE

DIBUTTON_SPACESIM_RIGHT_LINK

DIBUTTON_SPACESIM_SLOWER_LINK

DIBUTTON_SPACESIM_TURN_LEFT_LINK

DIBUTTON_SPACESIM_TURN_RIGHT_LINK

DIBUTTON_SPACESIM_VIEW

DIHATSWITCH_SPACESIM_GLANCE

Priority 1 controls are those controls that, at the minimum, should be mapped to a device object if possible. Priority 2 controls are less critical to basic game operation and may be mapped as needed.

Game actions are assigned to action-mapping constant controls in an array of DIACTION structures. Each DIACTION structure contains at least one game action, its associated action-mapping constant, any necessary flags, and either a friendly name or identifier (ID) string for the action. The remaining DIACTION members are not used at this point. The following code sample shows definition of the array of DIACTION structures.

#define NUMBER_OF_ACTIONS 18

DIACTION g_rgGameAction[NUMBER_OF_ACTIONS] =
{
    // Device input pre-defined by DirectInput, according to genre
    {INPUT_LEFTRIGHT_AXIS, DIAXIS_SPACESIM_LATERAL, 0, "Turn",},
    {INPUT_UPDOWN_AXIS, DIAXIS_SPACESIM_MOVE, 0, "Move",},
    {INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, "Shoot",},
    {INPUT_ENABLESHIELD, DIBUTTON_SPACESIM_GEAR, 0, "Shield",},
    {INPUT_DISPLAYGAMEMENU, DIBUTTON_SPACESIM_DISPLAY, 0, "Display",},
    {INPUT_QUITGAME, DIBUTTON_SPACESIM_MENU, 0, "Quit Game",},

    // Keyboard input mappings
    {INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, "Turn left", },
    {INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, "Turn right", },
    {INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, "Forward thrust", },
    {INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, "Reverse thrust", },
    {INPUT_FIREWEAPONS, DIKEYBOARD_F, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIKEYBOARD_S, 0, "Enable shields", },
    {INPUT_DISPLAYGAMEMENU, DIKEYBOARD_D, DIA_APPFIXED,
                                      "Display game menu"), },
    {INPUT_QUITGAME, DIKEYBOARD_ESCAPE, DIA_APPFIXED, "Quit game", },

    // Mouse input mappings
    {INPUT_LEFTRIGHT_AXIS, DIMOUSE_XAXIS, 0, "Turn", },
    {INPUT_UPDOWN_AXIS, DIMOUSE_YAXIS, 0, "Move", },
    {INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIMOUSE_BUTTON1, 0, "Enable shields", },
};

A DIACTIONFORMAT structure is then initialized to contain the DIACTION array g_rgGameAction defined above. The DIACTIONFORMAT structure also defines the genre, buffer size, axis scaling, and a friendly name for the action map. The g_AppGuid value is a globally unique identifier (GUID) defined in the application to identify the action map. For more information about creating GUIDs, see GUIDs.

DIACTIONFORMAT diaf;
diaf.dwSize        = sizeof(DIACTIONFORMAT);
diaf.dwActionSize  = sizeof(DIACTION);
diaf.dwDataSize    = NUMBER_OF_ACTIONS * sizeof(DWORD);
diaf.dwNumActions  = NUMBER_OF_ACTIONS;
diaf.guidActionMap = g_AppGuid;
diaf.dwGenre       = DIVIRTUAL_SPACESIM;
diaf.rgoAction     = g_rgGameAction;
diaf.dwBufferSize  = 16;
diaf.lAxisMin      = -100;
diaf.lAxisMax      = 100;
diaf.tszActionMap  = "DI Test";

This DIACTIONFORMAT structure is matched against enumerated devices to find the best match in Step 3: Mapping Actions to Devices.

© 2002 Microsoft Corporation. All rights reserved.


Step 3: Mapping Actions to Devices

Once the desired mapping has been defined, it must be applied to physical devices. IDirectInput8::EnumDevicesBySemantics begins this process in the following code fragment, where m_pDI is a previously defined IDirectInput8 object.

HRESULT hr;

hr = m_pDI->EnumDevicesBySemantics(m_strUserName, &m_diaf,
                                EnumSuitableDevicesCB, this, 0L);

The first parameter, m_strUserName is useful in the case of multiple users who might have different mapping preferences. However, in the case of this example, this value is NULL, indicating the user currently logged onto the system.

The second parameter is the address of the DIACTIONFORMAT structure containing the mapping information.

The third parameter is the address of a callback function that is called for each device found on the system. The function used in the sample is based on the DIEnumDevicesBySemanticsCallback function.

The fourth parameter could be any 32-bit value that you want to make available to the callback function. Here, this is a this pointer to the class object used by the MultiMapper sample for the various action-mapping setup and manipulation functions. This gives the callback function access to the class' functions.

The final parameter is used for flags. None are used in this example.

The EnumSuitableDevicesCB callback function calls the application-defined function AddDevices, which in turn calls the IDirectInputDevice8::BuildActionMap function on the device pdidDevice currently being enumerated. This call is shown in the following code fragment.

hr = pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0L );

The first parameter is once again the address of the DIACTIONFORMAT structure containing the action map.

The second parameter is again the name of the user if desired, though NULL in this case.

The final parameter holds control flags, with none being passed in this case.

IDirectInputDevice8::BuildActionMap takes the list of control assignments specified in the DIACTIONFORMAT structure and attempts to map them to specific device objects on the device being enumerated. The results of the mapping are returned in the same structure. Each pass maps different controls depending on the nature of the currently enumerated device. A keyboard, for instance, maps controls that specify a mapping to a particular key, but leaves controls that specify buttons, sliders, or axes unmapped. If a joystick is enumerated next, IDirectInputDevice8::BuildActionMap ignores those controls mapped to keyboard keys, but it attempts to map the buttons, sliders, and axes to the joystick's device objects.

The results of this default mapping can be examined and manipulated. This is done in Step 4: Configuring and Applying the Action Map.

© 2002 Microsoft Corporation. All rights reserved.


Step 4: Configuring and Applying the Action Map

Once the mapping has been returned in the DIACTIONFORMAT structure, it can be manipulated before being applied by IDirectInputDevice8::SetActionMap.

The dwHow member of each DIACTIONFORMAT structure might be examined at this point to determine both whether the mapping was successful and what the criteria were in selecting the device object to which that action was mapped. For instance, you can determine if the mapping was specified by the hardware manufacturer or requested by the user.

The actual mapping itself may be changed as well by editing the dwSemantic member of the appropriate DIACTIONFORMAT structure returned in the default mapping. You can choose to make those changes, but it is not recommended that you do so.

Once the action map configuration is finalized, it must be applied to the device to bind the physical controls to the game actions. This is done by calling IDirectInputDevice8::SetActionMap as follows:

    hr = pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0L );

Action maps, once created, can be displayed for and easily altered by the user. This is explained in Step 5: Displaying the Action Map.

© 2002 Microsoft Corporation. All rights reserved.


Step 5: Displaying the Action Map

In addition to the advantage of action mapping in enabling the developer to define game actions independently of specific controller hardware, action mapping also benefits the user by providing a user interface (UI) for easy reconfiguration.

The UI can be displayed in two forms, text-only or graphics. In addition, each of those two options can be viewed in two modes: view-only or edit.

To display the UI, some initial setup is involved. First, a DICOLORSET structure is declared and initialized. This structure, as its name implies, describes the color set used to display the UI. The following code fragment shows the setup of this structure.

DICOLORSET dics;
ZeroMemory(&dics, sizeof(DICOLORSET));
dics.dwSize = sizeof(DICOLORSET);

By using the ZeroMemory function to set the memory block to zeroes, it indicates that the default color scheme should be used. Beyond this, the only element that requires initialization is the dwSize member, which is set equal to the size of the DICOLORSET structure.

The DICOLORSET structure is then included as part of a larger DICONFIGUREDEVICESPARAMS structure as seen in this code fragment.

DICONFIGUREDEVICESPARAMS dicdp;
ZeroMemory(&dicdp, sizeof(dicdp));
dicdp.dwSize = sizeof(dicdp);
dicdp.dwcUsers       = 1;
dicdp.lptszUserNames = m_strUserName;

dicdp.dwcFormats     = 1;
dicdp.lprgFormats    = &m_diaf;
dicdp.hwnd           = m_hWnd;
dicdp.lpUnkDDSTarget = NULL;

The DICONFIGUREDEVICESPARAMS structure is declared and its allotted memory is set to contain nothing but zeroes. Once again, the dwSize member is set to the size of the structure. Only the currently logged user is being used in this example, so dwcUsers is set to 1. Recall that the m_strUserName variable is set to NULL so that the user's name is the name of the user currently logged onto the system.

Only one DIACTIONFORMAT structure containing the action map is being passed, so dwcFormats is set to 1 and the address of the DIACTIONFORMAT structure is passed as lprgFormats.

The hwnd variable is assigned the handle of the application window and the lpUnkDDSTarget is set to NULL to indicate that the Microsoft® Windows® Windows Graphics Device Interface (GDI) functions should be used to draw the configuration user interface image.

The initialized DICONFIGUREDEVICESPARAMS structure is then passed to IDirectInput8::ConfigureDevices as illustrated in this code fragment.

hr = m_pDI->ConfigureDevices(NULL, &dicdp, dwFlags, NULL);

The first and last parameters, which are used with an optional callback function, are set to NULL as they are not used in this sample.

The second parameter is the address of the DICONFIGUREDEVICESPARAMS structure containing the data to be displayed and other auxiliary information.

The third parameter is used for flags that determine whether the display is in read-only or edit mode. If you want to display the configuration for informational purposes without giving the user the option of changing it, you use the DICD_DEFAULT flag in this parameter. However, in this sample the dwFlags variable had been set earlier to DICD_EDIT, so the display allows user configuration. This is discussed in Step 6: User Configuration of the Action Map.

© 2002 Microsoft Corporation. All rights reserved.


Step 6: User Configuration of the Action Map

At this point, the user configuration interface is displayed. If the device manufacturer has provided a graphic, users see an image of the device with labels indicating the action assigned to each device object. If no graphic is available, a simple text list of available device objects with their associated actions is displayed. An example of the former is shown here.

Graphical user interface for configuring the action map

Users can now reassign controllers to actions as they see fit. Any changes made will be reflected in the DIACTIONFORMAT structure. When the user interface is closed, the new action map must be sent to IDirectInputDevice8::SetActionMap before it can be implemented.

Using the data associated with the controls in an action map is described in Step 7: Retrieval of Action Mapped Data.

© 2002 Microsoft Corporation. All rights reserved.


Step 7: Retrieval of Action Mapped Data

Action mapping was designed with buffered data in mind and will most often be used in that manner. The only difference between retrieving data from an action-mapped device and a device with no mapping is where you get it. Without action mapping, you would look to the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which device object reported a change. However, with action mapping, you look to the uAppData member. Data is found in the dwData member.

For more detailed information about retrieving action-mapped data, see Retrieving Action Data.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput C/C++ Samples

The following sample programs demonstrate the use and capabilities of Microsoft® DirectInput®.

Samples

  • ActionBasic Sample
  • ActionMapper Sample
  • CustomFormat Sample
  • DeviceView Sample
  • DIConfig Sample
  • DrumPad Sample
  • FFConst Sample
  • Joystick Sample
  • Keyboard Sample
  • Mouse Sample
  • MultiMapper Sample
  • ReadFFE Sample
  • Scrawl Sample

Although Microsoft DirectX® samples include Microsoft Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

© 2002 Microsoft Corporation. All rights reserved.


ActionBasic Sample

Description

The ActionBasic sample is intended to be an introduction to action mapping. The source code includes a step by step approach to creating an action mapped application.

Path

Source: (SDK root)\Samples\C++\DirectInput\ActionBasic

Executable: (SDK root)\Samples\C++\DirectInput\Bin\ActionBasic.exe

User's Guide

When you start the sample, a window will open displaying a chart that lists the detected devices plotted against the sample game actions. Actions which were not successfully mapped to an object on the device are given a crosshatch-filled cell on the chart. When you trigger a mapped keyboard device or a mapped mouse device, the corresponding cell will be highlighted. Triggered axis actions will also feature an arrow to indicate the axis position.

To view the current action mappings for all the detected devices, click the View Configuration button. This will open the default configuration user interface (UI) managed by Microsoft® DirectInput®. These mappings cannot be changed for this sample.

Programming Notes

The ActionBasic sample is intended to be an introduction to the action mapping features of DirectInput. The source code is commented and labeled according to the primary steps to be followed when writing an action mapped application. If you're already familiar with the fundamentals of action mapping, you may want to refer to the ActionMapper Sample, which shows how the framework supplied with this software development kit (SDK) can simplify development.

© 2002 Microsoft Corporation. All rights reserved.


ActionMapper Sample

Description

The ActionMapper sample program demonstrates the retrieval of action-mapped data. It also enables reconfiguration of the keyboard, mouse, and other controller action mappings through the user interface.

Path

Source: (SDK root)\Samples\C++\DirectInput\ActionMapper

Executable: (SDK root)\Samples\C++\DirectInput\Bin\ActionMapper.exe

User's Guide

When you run the ActionMapper sample, a window opens where you can watch the input state change as you press keys or click the mouse button. The World State tells you where you are located in the two-dimensional grid space. If you click Configure Input, a window opens where you can change the keys that control various options such as moving forward or backward or firing your weapon. Click OK to return to the World State window.

Programming Notes

The application retrieves action-mapped data in the UpdateInput function by calling the IDirectInputDevice8::GetDeviceData method.

© 2002 Microsoft Corporation. All rights reserved.


CustomFormat Sample

Description

The CustomFormat Sample illustrates the use of a custom data format.

Path

Source: (SDK root)\Samples\C++\DirectInput\CustomFormat

Executable: (SDK root)\Samples\C++\DirectInput\Bin\CustomFormat.exe

User's Guide

After you have started the sample, the sample displays the mouse location and which mouse button is clicked.

Note If your mouse has more than four buttons, not all of the buttons will be used by this sample.

Programming Notes

The comments in CustomFormat.cpp explain how to create, initialize, and retrieve data with a custom data format. You might want to use a custom data format for adding support for a non-standard input device. By enumerating the device objects, you can determine exactly what data is available. The data format you create specifies how the data you are interested in will be stored.

For compatibility, this sample creates a new format to store mouse data. Usually, you would want to use one of the provided c_dfDIMouse types, but the steps taken to create the custom format will be the same for any hardware device. For more information, see IDirectInputDevice8::SetDataFormat.

© 2002 Microsoft Corporation. All rights reserved.


DeviceView Sample

Description

This sample shows how the DIDevImage framework provided with the samples, located in the (SDK root)\samples\C++\Common folder, can be used to create a custom device configuration interface.

DIDevImage framework handles issues such as bookkeeping involved with bitmaps, ToolTips, and image scaling. If extra functionality is needed, you can modify the source code for the DIDevImage framework at (SDK root)\samples\cpp\common\src\didevimg.cpp.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\DeviceView

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\DeviceView.exe

User's Guide

When you run the application, it will display a tab for each Microsoft® DirectInput® device on your system. For each device, you scroll through multiple pages by entering a value for the desired page or by using the scroll arrows.

To select a device object, click the mouse on the name of the device or activate the device object. This will highlight the name of the current device object and display the object's image overlay (if available).

To hide unmapped objects, select the Hide Unmapped check box.

Programming Notes

This sample is built on the DIDevImage framework, which handles the device image loading, scaling, and rendering. To use the framework:

  1. Create an instance of the CDIDevImage class.
  2. Initialize the CIDevImage object by passing a pointer to an IDirectInputDevice8 object to the CIDevImage::Init method.
  3. Set the desired names associated with each object through a series of calls to the CIDevImage::SetCalloutText method.
  4. Render the image associated with the object to your client application by passing either a device context to the CIDevImage::RenderToDC method, or an IDirect3DTexture9 object to the CIDevImage::Render method.
  5. Highlight, display full name, or hide names associate with each object by passing the appropriate flags to the DIDevImage::SetCalloutState method.

The CIDevImage framework has some optimizations for quick renderings, but your application should not call the Render method for each frame. Instead, try to call the framework's Render method only when the device image changes due to user input.

Read the inline comments included with the CIDevImage framework source code for information about using some of the more advanced features, such as transparent backgrounds for Microsoft Direct3D® surfaces.

It is not necessary to create a device configuration user interface (UI). DirectInput provides a UI that can be customized and is called by the IDirectInput8::ConfigureDevices method. The source code for the default UI is also provided with this software development kit (SDK) (samples\cpp\DirectInput\diconfig). The DirectInput UI, as well as the DIDevImage framework UI, call the IDirectInputDevice8::GetImageInfo method to retrieve the device images.

© 2002 Microsoft Corporation. All rights reserved.


DIConfig Sample

Description

The DIConfig code demonstrates the implementation of a configuration user interface based upon the Microsoft® DirectInput® Mapper technology. This sample code is very complex and is intended to be used more as a reference implementation than as a learning tool.

Path

Source: (SDK root )\Samples\C++\DirectInput\DIConfig

Executable: None (see Programming Notes ).

User's Guide

This sample does not create an executable file, so there are no end-user instructions.

Programming Notes

This code generates Diconfig.dll, a binary file that contains all of the functionality used in the default Mapper user interface (UI). This code is very complex and is intended as a reference implementation of a DirectInput-based configuration user interface.

For more information about this sample, see the comments within the sample code itself. The following major features are supported.

  • Display of device images.
  • Reconfiguration of devices.
  • Support for multiple device views to illustrate alternate viewing angles.
  • Support for control activation overlays.
  • Use of the IDirectInputDevice8::GetImageInfo method.
  • Device ownership for multiuser applications on the same computer.
  • Persistence of user settings through the IDirectInputDevice8::SetActionMap method.

© 2002 Microsoft Corporation. All rights reserved.


DrumPad Sample

Description

The DrumPad sample transforms every input device on your computer (joysticks, joypads, keyboard, and mouse) into an audio drum machine using Action Mapping and Microsoft® DirectX® Audio. You can load different sound files to be played for each "drum".

Path

Source: (SDK root)\Samples\C++\DirectInput\DrumPad

Executable: (SDK root)\Samples\C++\DirectInput\Bin\DrumPad.exe

User's Guide

DrumPad has eight sound slots that are mapped to controls on the input devices on your system. The sample attempts to load default sound files from the ..\..\media directory. However, you can load any sound file into each of the slots.

To play the sounds, hit the mapped buttons on your joystick,joypad, keyboard, or mouse. You should see the corresponding green box light up on the right. Any number of devices can used simultaneously.

To load a sound into one of the slots, for example Bass Drum, click the corresponding Bass Drum button. This will open the Open Sound File window. Choose a new .wav file and click Open to finalize your choice.

To see which sound slot is mapped to which button, click View Device Mappings. You cannot change the device mappings in this sample.

Programming Notes

DrumPad uses action mapping to have Microsoft DirectInput® map each sound action to a control. The sound actions include:
  • eB_BASS_DRUM
  • eB_SNARE_DRUM
  • eB_HIHAT_OPEN
  • eB_HIHAT_CLOSE
  • eB_CRASH
  • eB_USER1
  • eB_USER2
  • eB_USER3

Actions are mapped to Action Mapping Constants, which include genre-specific joystick actions, keyboard buttons, and mouse buttons. The DrumPad sample uses an arbitrary genre. You can observe how everything is mapped by seeing the device mappings during runtime.

The audio is done by encapsulating an array of DirectSoundBuffers or DirectMusicSegments. The game loop polls the devices and process the input by calling the DrumPad class and playing a sound.

© 2002 Microsoft Corporation. All rights reserved.


FFConst Sample

Description

The FFConst sample program applies raw forces to a force-feedback input device, illustrating how a simulator-type application can use force feedback to generate forces computed by a physics engine.

You must have a force-feedback device connected to your system in order to run the application.

Path

Source: (SDK root )\Samples\C++\DirectInput\FFConst

Executable: (SDK root )\Samples\C++\DirectInput\Bin\FFConst.exe

User's Guide

When you run the application, it displays a window with a crosshair and a black spot in it. Click anywhere within the window's client area to move the black spot. (Note that moving the device itself does not do anything.) FFConst exerts a constant force on the device from the direction of the spot, in proportion to the distance from the crosshair. You can also hold down the mouse button and move the spot continuously.

Programming Notes

This sample program enumerates the input devices and acquires the first force-feedback device that it finds. If none are detected, it displays a message and terminates.

When the user moves the black spot, the joySetForcesXY function converts the cursor coordinates to a force direction and magnitude. This data is used to modify the parameters of the constant force effect.

© 2002 Microsoft Corporation. All rights reserved.


Joystick Sample

Description

The Joystick sample program obtains and displays joystick data.

Path

Source: (SDK root )\Samples\C++\DirectInput\Joystick

Executable: (SDK root )\Samples\C++\DirectInput\Bin\Joystick.exe

User's Guide

Observe how the displayed data changes when you move and twist the stick, rotate the throttle wheel, and press buttons in various combinations.

Programming Notes

The application polls the joystick for immediate data in response to a timer set inside the dialog procedure.

© 2002 Microsoft Corporation. All rights reserved.


Keyboard Sample

Description

The Keyboard sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the keyboard.

Path

Source: (SDK root )\Samples\C++\DirectInput\Keyboard

Executable: (SDK root )\Samples\C++\DirectInput\Bin\Keyboard.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

Programming Notes

Note that holding down a key in immediate mode holds that key indefinitely as subsequent snapshots of the keyboard are taken by Microsoft® DirectInput®. This is an optical illusion because DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the keyboard at that time is considered, while anything that has happened between snapshots is ignored.

Holding down a key in buffered mode briefly displays the data indicating that the key has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the key generates another briefly displayed key-up event. This is a significant difference from immediate mode.

© 2002 Microsoft Corporation. All rights reserved.


Mouse Sample

Description

The Mouse sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the mouse.

Path

Source: (SDK root )\Samples\C++\DirectInput\Mouse

Executable: (SDK root )\Samples\C++\DirectInput\Bin\Mouse.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

To release the mouse, press ENTER.

Programming Notes

Note that in immediate mode, all device objects are visible and you can see the data change as the mouse is moved. This is an optical illusion because Microsoft® DirectInput® is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the device at that time is considered, while anything that has happened between device snapshots is ignored.

Holding down a button in buffered mode briefly displays the data indicating that the button has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the button generates another briefly displayed button up event. This is a significant difference from immediate mode.

© 2002 Microsoft Corporation. All rights reserved.


MultiMapper Sample

Description

The MultiMapper sample program shows how to set up, apply, and retrieve data using the Action Mapping functionality. It also demonstrates remapping through the user interface.

Path

Source: (SDK root )\Samples\C++\DirectInput\MultiMapper

Executable: (SDK root )\Samples\C++\DirectInput\MultiMapper.exe

User's Guide

First, assign a number of players. The MultiMapper sample program accepts up to four. There must be one device, including the keyboard and the mouse, for each player. If more players are chosen than there are devices available, the program automatically scales back to the maximum number of players based on the devices attached.

The MultiMapper sample program is designed as though it were a space combat application. Each player is assigned a basic set of actions such as turning, firing, and activating thrusters. These actions are then mapped to device controls. Activation of those controls is then reflected by data in the display window.

To activate the action mapping user interface, press D. Each device has a separate tab for mapping that particular device. Double-clicking a device object label activates the list of possible actions to be assigned to that device object. Make a selection from the action list to map that action to the selected device object. You can also reassign devices among players.

Programming Notes

If a controller such as a joystick or a wheel is attached to the system, it displays a graphic of the device with actions as callouts to each device object. The display of this graphic depends on the presence of a provided bitmap for that device.

© 2002 Microsoft Corporation. All rights reserved.


ReadFFE Sample

Description

The ReadFFE sample program enumerates and plays all of the Microsoft® DirectInput® force-feedback effects stored in a DirectInput effects file created by the Force Editor.

Path

Source: (SDK root )\Samples\C++\DirectInput\ReadFFE

Executable: (SDK root )\Samples\C++\DirectInput\ReadFFE.exe

Media: (SDK root )\Samples\Multimedia\Media\*.ffe

User's Guide

Click Read File and open an existing Force Feedback Effects (FFE) file. If it was successfully read, click Play Effects to play the effects on the force-feedback device. FFE files can be authored using the Force Feedback Editor utility packaged with the Microsoft DirectX® software development kit (SDK).

Programming Notes

For each file effect enumerated, the EnumAndCreateEffectsCallback function initializes an IDirectInputEffect pointer and adds it to a linked list. The OnPlayEffects function traverses this list and plays all effects.

© 2002 Microsoft Corporation. All rights reserved.


Scrawl Sample

Description

The Scrawl application demonstrates using the mouse in exclusive mode in a windowed application. It functions in the same way as a pencil tool in a paint program.

Path

Source: (SDK root )\Samples\C++\DirectInput\Scrawl

Executable: (SDK root )\Samples\C++\DirectInput\Bin\Scrawl.exe

User's Guide

To draw, hold down the left mouse button and move the mouse. Click the right mouse button to invoke a shortcut menu. From the shortcut menu you can clear the client window, set the mouse sensitivity, or close the application. If the mouse buttons have been switched through Control Panel settings, Scrawl will detect and mimic this behavior. Note that Microsoft® DirectInput® ignores Control Panel settings and the application itself must make the switch.

Programming Notes

The Scrawl sample program demonstrates many aspects of DirectInput programming, including the following:

  • Using the mouse in non-exclusive mode in a windowed application.
  • Releasing the mouse when Microsoft Windows® needs to use it for menu access.
  • Reacquiring the mouse when Windows no longer needs it.
  • Reading buffered device data.
  • Deferring screen updates until movement on both axes has been fully processed.
  • Displaying event notifications of device activity.
  • Restricting the cursor to an arbitrary region.
  • Scaling raw mouse coordinates before using them.
  • Using relative axis mode.

© 2002 Microsoft Corporation. All rights reserved.


DirectInput C/C++ Reference

Reference material for the Microsoft® DirectInput® C/C++ application programming interface (API) is divided into the following categories.

  • Interfaces
  • Callback Functions
  • Functions
  • Macros
  • Structures
  • Device Constants
  • Action Mapping Constants
  • Return Values

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains references for methods of the following Microsoft® DirectInput® interfaces.

Interfaces

  • IDirectInput8
  • IDirectInputDevice8
  • IDirectInputEffect

Note All DirectInput methods have corresponding macros that expand to C or C++ syntax depending on which language is defined. These macros are found in the Dinput.h header file and are not documented separately.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8 Interface

Applications use the methods of the IDirectInput8 interface to enumerate, create, and retrieve the status of Microsoft® DirectInput® devices, initialize the DirectInput object, and invoke an instance of the Microsoft Windows® Control Panel.

IDirectInput8 Members

ConfigureDevices

Displays property pages for connected input devices and enables the user to map actions to device controls.

CreateDevice

Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 interface.

EnumDevices

Enumerates available devices.

EnumDevicesBySemantics

Enumerates devices that most closely match the application-specified action map.

FindDevice

Retrieves the instance GUID of a device that has been newly attached to the system. It is called in response to a Microsoft Win32® device management notification.

GetDeviceStatus

Retrieves the status of a specified device.

Initialize

Initializes a DirectInput object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

RunControlPanel

Runs Control Panel to enable the user to install a new input device or modify configurations.

Remarks

IDirectInput8 supersedes the IDirectInput, IDirectInput2, and IDirectInput7 interfaces used in earlier versions of Microsoft DirectX®.

IDirectInput8 is an interface to a new class of object, represented by the class identifier CLSID_DirectInput8, and cannot be obtained by calling QueryInterface on an interface to objects of class CLSID_DirectInput. Instead, obtain the IDirectInput8 interface by using the DirectInput8Create function.

The LPDIRECTINPUT8 type is defined as a pointer to the IDirectInput8 interface:

typedef struct IDirectInput8    *LPDIRECTINPUT8;

Interface Information

Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::ConfigureDevices Method

Displays property pages for connected input devices and enables the user to map actions to device controls.

Syntax

HRESULT ConfigureDevices(

    LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
    LPDICONFIGUREDEVICESPARAMS lpdiCDParams,
    DWORD dwFlags,
    LPVOID pvRefData
);

Parameters

lpdiCallback
Address of a callback function to be called each time the contents of the surface change. See DIConfigureDevicesCallback. Pass NULL if the application does not handle the display of the property sheet. In this case, Microsoft® DirectInput® displays the property sheet and returns control to the application when the user closes the property sheet. If you supply a callback pointer, you must also supply a valid surface pointer in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure.
lpdiCDParams
Address of a DICONFIGUREDEVICESPARAMS structure that contains information about users and genres for the game, as well as information about how the user interface is displayed.
dwFlags
DWORD value that specifies the mode in which the control panel should be invoked. The dwFlags parameter must be one of the following values.
DICD_DEFAULT
Open the property sheet in view-only mode.
DICD_EDIT
Open the property sheet in edit mode. This mode enables the user to change action-to-control mappings. After the call returns, the application should assume current devices are no longer valid, release all device interfaces, and reinitialize them by calling IDirectInput8::EnumDevicesBySemantics.
pvRefData
Application-defined value to pass to the callback function.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

IDirectInput8::ConfigureDevices was designed to work in the Microsoft Direct3D® 8.x environment. Developers should use the DIConfig Sample to produce the same results in the Direct3D 9.0 environment.

Hardware vendors provide bitmaps and other display information for their device.

Before calling the method, an application can modify the text labels associated with each action by changing the value in the lptszActionName member of the DIACTION structure.

Configuration is stored for each user of each device for each game. The information can be retrieved by the IDirectInputDevice8::BuildActionMap method.

By default, acceleration is supported for these pixel formats:

  • A1R5G5B5

    16-bit pixel format with 5 bits reserved for each color and 1 bit reserved for alpha (transparent texel).

  • A8R8G8B8

    32-bit ARGB pixel format with alpha.

  • R9G8B8

    24-bit RGB pixel format.

  • X1R5G5B5

    16-bit pixel format with 5 bits reserved for each color.

  • X8R8G8B8

    32-bit RGB pixel format with 8 bits reserved for each color.

Other formats will result in color conversion and dramatically slow the frame rate.

Note Even if the cooperative level for the application is disabling the Microsoft Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping user interface (UI) is displayed.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::CreateDevice Method

Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 interface.

Syntax

HRESULT CreateDevice(

    REFGUID rguid,
    LPDIRECTINPUTDEVICE *lplpDirectInputDevice,
    LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the instance GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput8::EnumDevices method, or it can be one of the predefined GUIDs listed below. For the following GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.
lplpDirectInputDevice
Address of a variable to receive the IDirectInputDevice8 interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for Component Object Model (COM) aggregation, or NULL if the interface is not aggregated. Most callers pass NULL.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft® DirectInput®. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOINTERFACE | The specified interface is not supported by the object. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

Calling this method with pUnkOuter = NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, NULL, CLSCTX_INPROC_SERVER, riid, lplpDirectInputDevice) and then initializing it with Initialize.

Calling this method with pUnkOuter != NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInputDevice). The aggregated object must be initialized manually.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::EnumDevices Method

Enumerates available devices.

Syntax

HRESULT EnumDevices(

    DWORD dwDevType,
    LPDIENUMDEVICESCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

dwDevType
Device type filter.

To restrict the enumeration to a particular type of device, set this parameter to a DI8DEVTYPE_* value. See DIDEVICEINSTANCE.

To enumerate a class of devices, use one of the following values.

DI8DEVCLASS_ALL
All devices.
DI8DEVCLASS_DEVICE
All devices that do not fall into another class.
DI8DEVCLASS_GAMECTRL
All game controllers.
DI8DEVCLASS_KEYBOARD
All keyboards. Equivalent to DI8DEVTYPE_KEYBOARD.
DI8DEVCLASS_POINTER
All devices of type DI8DEVTYPE_MOUSE and DI8DEVTYPE_SCREENPOINTER.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesCallback.
pvRef
Application-defined 32-bit value to be passed to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values:
DIEDFL_ALLDEVICES
All installed devices are enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.
DIEDFL_FORCEFEEDBACK
Only devices that support force feedback.
DIEDFL_INCLUDEALIASES
Include devices that are aliases for other devices.
DIEDFL_INCLUDEHIDDEN
Include hidden devices. For more information about hidden devices, see DIDEVCAPS.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

All installed devices can be enumerated, even if they are not present. For example, a flight stick might be installed on the system but not currently plugged into the computer. Set the dwFlags parameter to indicate whether only attached or all installed devices should be enumerated. If the DIEDFL_ATTACHEDONLY flag is not present, all installed devices are enumerated.

A preferred device type can be passed as a dwDevType filter so that only the devices of that type are enumerated.

On Microsoft® Windows® XP, Microsoft DirectInput® enumerates only one mouse and one keyboard device, referred to as the system mouse and the system keyboard. These devices represent the combined output of all mice and keyboards respectively on a system. For information about how to read from multiple mice or keyboards individually on Windows XP, see the WM_INPUT documentation.

Note The order in which devices are enumerated by DirectInput is not guaranteed.

See Also

IDirectInput8::EnumDevicesBySemantics

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::EnumDevicesBySemantics Method

Enumerates devices that most closely match the application-specified action map.

Syntax

HRESULT EnumDevicesBySemantics(

    LPCTSTR ptszUserName,
    LPDIACTIONFORMAT lpdiActionFormat,
    LPDIENUMDEVICESBYSEMANTICSCB lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

ptszUserName
String identifying the current user, or NULL to specify the user logged onto the system. The user name is taken into account when enumerating devices. A device with user mappings is preferred to a device without any user mappings. By default, devices in use by other users are not enumerated for this user.
lpdiActionFormat
Address of a DIACTIONFORMAT structure that specifies the action map for which suitable devices are enumerated.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesBySemanticsCallback.
pvRef
Application-defined 32-bit value to pass to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values.
DIEDBSFL_ATTACHEDONLY
Only attached and installed devices are enumerated.
DIEDBSFL_AVAILABLEDEVICES
Only unowned, installed devices are enumerated.
DIEDBSFL_FORCEFEEDBACK
Only devices that support force feedback are enumerated.
DIEDBSFL_MULTIMICEKEYBOARDS
Only secondary (non-system) keyboard and mouse devices.
DIEDBSFL_NONGAMINGDEVICES
Only HID-compliant devices whose primary purpose is not as a gaming device. Devices such as USB speakers and multimedia buttons on some keyboards would fall within this value.
DIEDBSFL_THISUSER
All installed devices for the user identified by ptszUserName, and all unowned devices, are enumerated.
DIEDBSFL_VALID
DIEDBSFL_VALID is also defined in Dinput.h, but is not used by applications.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The keyboard and mouse are enumerated last.

Note The order in which devices are enumerated by Microsoft® DirectInput® is not guaranteed.

See Also

IDirectInput8::EnumDevices, Action Mapping

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::FindDevice Method

Retrieves the instance globally unique identifier (GUID) of a device that has been newly attached to the system. It is called in response to a Microsoft® Win32® device management notification.

Syntax

HRESULT FindDevice(

    REFGUID rguidClass,
    LPCTSTR ptszName,
    LPGUID pguidInstance
);

Parameters

rguidClass
Unique identifier of the device class for the device that the application is to locate. The application obtains the class GUID from the device arrival notification. For more information, see the documentation on the DBT_DEVICEARRIVAL event in the Microsoft Platform Software Development Kit (SDK).
ptszName
Name of the device. The application obtains the name from the device arrival notification.
pguidInstance
Address of a variable to receive the instance GUID for the device, if the device is found. This value can be passed to IDirectInput8::CreateDevice.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG. Failure results if the GUID and name do not correspond to a device class that is registered with Microsoft DirectInput®. For example, they might refer to a storage device, rather than an input device.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::GetDeviceStatus Method

Retrieves the status of a specified device.

Syntax

HRESULT GetDeviceStatus(

    REFGUID rguidInstance
);

Parameters

rguidInstance
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device whose status is being checked.

Return Value

If the method succeeds, the return value is DI_OK if the device is attached to the system, or DI_NOTATTACHED otherwise.

If the method fails, the return value can be one of the following error values:

DIERR_GENERIC | An undetermined error occurred inside the Microsoft® DirectInput® subsystem. This value is equal to the E_FAIL standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::Initialize Method

Initializes a Microsoft® DirectInput® object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle of the parent application. For example, a Microsoft ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle of the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION | The application was written for an unsupported prerelease version of DirectInput.
DIERR_OLDDIRECTINPUTVERSION | The application requires a newer version of DirectInput.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInput8::RunControlPanel Method

Runs Control Panel to enable the user to install a new input device or modify configurations.

Syntax

HRESULT RunControlPanel(

    HWND hwndOwner,
    DWORD dwFlags
);

Parameters

hwndOwner
Handle of the window to be used as the parent window for the subsequent user interface. If this parameter is NULL, no parent window is used.
dwFlags
Currently not used and must be set to 0.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

See Also

IDirectInputDevice8::RunControlPanel

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8 Interface

Applications use the methods of the IDirectInputDevice8 interface to gain and release access to Microsoft® DirectInput® devices, manage device properties and information, set behavior, perform initialization, create and play force-feedback effects, and invoke a device's control panel.

IDirectInputDevice8 Members

Acquire

Obtains access to the input device.

BuildActionMap

Builds an action map for the device and retrieves information about it.

CreateEffect

Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).

EnumCreatedEffectObjects

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

EnumEffects

Enumerates all the effects supported by the force-feedback system on the device. The enumerated GUIDs can represent predefined effects, as well as effects peculiar to the device manufacturer.

EnumEffectsInFile

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

EnumObjects

Enumerates the input and output objects available on a device.

Escape

Sends a hardware-specific command to the force-feedback driver.

GetCapabilities

Obtains the capabilities of the DirectInputDevice object.

GetDeviceData

Retrieves buffered data from the device.

GetDeviceInfo

Obtains information about the device's identity.

GetDeviceState

Retrieves immediate data from the device.

GetEffectInfo

Obtains information about an effect.

GetForceFeedbackState

Retrieves the state of the device's force-feedback system.

GetImageInfo

Retrieves information about a device image for use in a configuration property sheet.

GetObjectInfo

Retrieves information about a device object, such as a button or axis.

GetProperty

Retrieves information about the input device.

Initialize

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

Poll

Retrieves data from polled objects on a DirectInput device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

RunControlPanel

Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

SendDeviceData Sends data to a device that accepts output.
Note There are no devices that accept output from IDirectInputDevice8::SendDeviceData. See Remarks.
SendForceFeedbackCommand

Sends a command to the device's force-feedback system.

SetActionMap Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.
SetCooperativeLevel

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

SetDataFormat

Sets the data format for the DirectInput device.

SetEventNotification

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

SetProperty

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

Unacquire

Releases access to the device.

WriteEffectToFile

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

Remarks

The IDirectInputDevice8 interface is obtained by using the IDirectInput8::CreateDevice method. For an example, see Creating a DirectInput Device.

IDirectInputDevice8 supersedes the IDirectInputDevice, IDirectInputDevice2, and IDirectInputDevice7 interfaces used in previous versions of Microsoft DirectX®, but does not inherit from them. Methods that share names with those from older interfaces perform similar services, but may not have exactly the same functionality or behavior. You cannot obtain the earlier interfaces by using QueryInterface.

The LPDIRECTINPUTDEVICE8 type is defined as a pointer to the IDirectInputDevice8 interface:

typedef struct IDirectInputDevice8    *LPDIRECTINPUTDEVICE8;

Interface Information

Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::Acquire Method

Obtains access to the input device.

Syntax

HRESULT Acquire(VOID);

Return Value

If the method succeeds, the return value is DI_OK, or S_FALSE if the device was already acquired.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OTHERAPPHASPRIO | Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.

Remarks

Before a device can be acquired, a data format must be set by using the IDirectInputDevice8::SetDataFormat method or IDirectInputDevice8::SetActionMap method. If the data format has not been set, IDirectInputDevice8::Acquire returns DIERR_INVALIDPARAM.

Devices must be acquired before calling the IDirectInputDevice8::GetDeviceState or IDirectInputDevice8::GetDeviceData methods for that device.

Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice8::Acquire method twice, then calls the IDirectInputDevice8::Unacquire method once, the device is unacquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::BuildActionMap Method

Builds an action map for the device and retrieves information about it.

Syntax

HRESULT BuildActionMap(

    LPDIACTIONFORMAT lpdiaf,
    LPCTSTR lpszUserName,
    DWORD dwFlags
);

Parameters

lpdiaf
Address of a DIACTIONFORMAT structure that receives information about the action map.
lpszUserName
Pointer to a string that specifies the name of the user for whom mapping is requested. If NULL, the current user is assumed.
dwFlags
Flags to control the mapping. This can be one of the following values.
DIDBAM_DEFAULT
Overwrite all mappings except application-specified mappings; that is, mappings that have the DIA_APPMAPPED flag in the DIACTION structure.
DIDBAM_HWDEFAULTS
Overwrite all mappings, including application-specified mappings. This flag is similar to DIDBAM_INITIALIZE, but automatically overrides user-mapped actions with the defaults specified by the device driver or Microsoft® DirectInput®.
DIDBAM_INITIALIZE
Overwrite all mappings, including application-specified mappings.
DIDBAM_PRESERVE
Preserve current mappings assigned for this device or any other configured device.

Return Value

If the method succeeds, the return value is DI_OK, DI_NOEFFECT, or DI_WRITEPROTECT. See Remarks.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MAPFILEFAIL | An error has occurred reading either the vendor-supplied action-mapping file for the device or reading or writing the user configuration file for the device.

Remarks

The method returns DI_NOEFFECT if no mappings were created for the device. For example, a keyboard or mouse will not provide mappings for genre-specific actions.

If DIERR_INVALIDPARAM is returned, one or more of the mappings was not valid. The dwHow member of the DIACTION structure is set to DIAH_ERROR. The application can iterate through the action map to find and correct errors.

If DIEFF_MAPFILEFAIL is returned, an error has occurred either reading the vendor supplied file for the device or reading or writing the user configuration file for the device.

DI_WRITEPROTECT is returned if the mappings were not configurable. For example, the buttons on a voice controller cannot be reconfigured because each button causes a specific hardware action to occur. DI_WRITEPROTECT overrides other success codes, so a check of the return codes will not reveal if any actions have been mapped.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::SetActionMap, IDirectInputDevice8::SetDataFormat

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::CreateEffect Method

Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).

Syntax

HRESULT CreateEffect(

    REFGUID rguid,
    LPCDIEFFECT lpeff,
    LPDIRECTINPUTEFFECT *ppdeff,
    LPUNKNOWN punkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the GUID identifying the effect to be created. This can be a predefined effect GUID, or it can be a GUID obtained from IDirectInputDevice8::EnumEffects. The following standard effect GUIDs are defined:
  • GUID_ConstantForce
  • GUID_RampForce
  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown
  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction
  • GUID_CustomForce
lpeff
DIEFFECT structure that provides parameters for the created effect. This parameter is optional. If it is NULL, the effect object is created without parameters. The application must then call the IDirectInputEffect::SetParameters method to set the parameters of the effect before it can download the effect.
ppdeff
Address of a variable to receive a pointer to the IDirectInputEffect interface if successful.
punkOuter
Controlling unknown for Component Object Model (COM) aggregation. The value is NULL if the interface is not aggregated. Most callers pass NULL.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft® DirectInput®. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the return value is S_OK, the effect was created, and the parameters of the effect were updated, but the effect was not necessarily downloaded. For it to be downloaded, the device must be acquired in exclusive mode.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::EnumCreatedEffectObjects Method

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

Syntax

HRESULT EnumCreatedEffectObjects(

    LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD fl
);

Parameters

lpCallback
Address of an application-defined callback function. Microsoft® DirectInput® provides the prototype function DIEnumCreatedEffectObjectsCallback.
pvRef
Reference data (context) for callback.
fl
No flags are currently defined. This parameter must be 0.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The results are unpredictable if you create or destroy an effect while an enumeration is in progress. However, the callback function can safely release the effect passed to it.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::EnumEffects Method

Enumerates all the effects supported by the force-feedback system on the device. The enumerated globally unique identifiers (GUIDs) can represent predefined effects, as well as effects peculiar to the device manufacturer.

Syntax

HRESULT EnumEffects(

    LPDIENUMEFFECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwEffType
);

Parameters

lpCallback
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsCallback prototype.
pvRef
A 32-bit application-defined value to be passed to the callback function. This parameter can be any 32-bit type; it is declared as LPVOID for convenience.
dwEffType
Effect type filter. Use one of the DIEFT_* values to indicate the effect type to be enumerated, or DIEFT_ALL to enumerate all effect types. For a list of these values, see DIEFFECTINFO.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

An application can use the dwEffType member of the DIEFFECTINFO structure to obtain general information about the effect, such as its type and which envelope and condition parameters are supported by the effect.

To exploit an effect to its fullest, contact the device manufacturer to obtain information about the semantics of the effect and its effect-specific parameters.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::EnumEffectsInFile Method

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

Syntax

HRESULT EnumEffectsInFile(

    LPCSTR lpszFileName,
    LPENUMEFFECTSINFILECALLBACK pec,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
pec
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsInFileCallback prototype.
pvRef
Application-defined value to be passed to the callback function. This parameter can be any 32-bit type.
dwFlags
Can be DIFEF_DEFAULT ( = 0) or one or both of the following values:
DIFEF_INCLUDENONSTANDARD
Include effect types that are not defined by Microsoft® DirectInput®.
DIFEF_MODIFYIFNEEDED
Instruct DirectInput to modify the authored effect, if necessary, so that it plays on the current device. For example, by default, an effect authored for two axes does not play on a single-axis device. Setting this flag allows the effect to play on a single axis. The parameters are modified in the DIEFFECT structure pointed to by the lpDiEffect member of the DIFILEEFFECT structure passed to the callback.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

See Also

IDirectInputDevice8::WriteEffectToFile, Loading Effects from a File

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::EnumObjects Method

Enumerates the input and output objects available on a device.

Syntax

HRESULT EnumObjects(

    LPDIENUMDEVICEOBJECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

lpCallback
Address of a callback function that receives DirectInputDevice objects. Microsoft® DirectInput® provides a prototype of this function as DIEnumDeviceObjectsCallback.
pvRef
Reference data (context) for callback.
dwFlags
Flags that specify the types of object to be enumerated. Each of the following values restricts the enumeration to objects of the described type:
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALIAS
Controls identified by a Human Interface Device (HID) usage alias. This flag applies only to HID-compliant USB devices.
DIDFT_ALL
All objects.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
A HID link collection. HID link collections do not generate data of their own.
DIDFT_ENUMCOLLECTION(n)
An object that belongs to HID link collection number n.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which the wCollectionNumber member of the DIDEVICEOBJECTINSTANCE structure is 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_OUTPUT
An object that supports output. For details, see Remarks in IDirectInputDevice8::SendDeviceData.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it, and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.
DIDFT_VENDORDEFINED
An object of a type defined by the manufacturer.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags in the dwFlags parameter restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR | DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER | DIDFT_TGLBUTTON | DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Applications should not rely on this method to determine whether certain keyboard keys or indicator lights are present, as these objects might be enumerated even though they are not present. Although the basic set of available objects can be determined from the device subtype, there is no reliable way of determining whether extra objects such as the menu key are available.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::Escape Method

Sends a hardware-specific command to the force-feedback driver.

Syntax

HRESULT Escape(

    LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer actually used.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetCapabilities Method

Obtains the capabilities of the DirectInputDevice object.

Syntax

HRESULT GetCapabilities(

    LPDIDEVCAPS lpDIDevCaps
);

Parameters

lpDIDevCaps
Address of a DIDEVCAPS structure to be filled with the device capabilities. The dwSize member of this structure must be initialized before calling this method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft® DirectX® 3, it is also valid to pass a DIDEVCAPS_DX3 structure with the dwSize member initialized to sizeof(DIDEVCAPS_DX3).

The number of objects returned in the DIDEVCAPS structure is the maximum number of objects that could be enumerated. However, all of these objects are not necessarily returned during a call to IDirectInputDevice8::EnumObjects.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetDeviceData Method

Retrieves buffered data from the device.

Syntax

HRESULT GetDeviceData(

    DWORD cbObjectData,
    LPDIDEVICEOBJECTDATA rgdod,
    LPDWORD pdwInOut,
    DWORD dwFlags
);

Parameters

cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag.
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice8::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.

Return Value

If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED | The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Note If the method returns DI_BUFFEROVERFLOW, the data in the rgdod array has been truncated.

In the debug version of Microsoft® DirectInput®, if a call is made to IDirectInputDevice8::GetDeviceData and the device has been unacquired, then random bytes will be sent to the device data buffer. To make sure you are not using random device data, always check for the DIERR_UNACQUIRED return code.

Before device data can be obtained, you must set the data format and the buffer size by using the IDirectInputDevice8::SetDataFormat and IDirectInputDevice8::SetProperty methods, or by using the IDirectInputDevice8::SetActionMap method. You must also acquire the device by using the IDirectInputDevice8::Acquire method.

The maximum number of events that the buffer will hold is one less than the buffer size set with the IDirectInputDevice8::SetProperty method.

The following code example reads up to ten buffered data elements, removing them from the device buffer as they are read.

DIDEVICEOBJECTDATA rgdod[10];
DWORD dwItems = 10;
hres = idirectinputdevice9_GetDeviceData(
    sizeof(DIDEVICEOBJECTDATA),
    rgdod,
    &dwItems,
    0);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements read (could be zero).
    if (hres == DI_BUFFEROVERFLOW) {
    // Buffer had overflowed.
    }
}

Your application can flush the buffer and retrieve the number of flushed items by specifying NULL for the rgdod parameter and a pointer to a variable containing INFINITE for the pdwInOut parameter. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (SUCCEEDED(hres)) {
    // Buffer successfully flushed.
    // dwItems = Number of elements flushed.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer had overflowed.
    }
}

Your application can query for the number of elements in the device buffer by setting the rgdod parameter to NULL, setting pdwInOut to INFINITE and setting dwFlags to DIGDD_PEEK. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            DIGDD_PEEK);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements in buffer.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer overflow occurred; not all data
        //   was successfully captured.
    }
}

To query about whether a buffer overflow has occurred, set the rgdod parameter to NULL and the pdwInOut parameter to 0. The following code example illustrates how this can be done.

dwItems = 0;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (hres == DI_BUFFEROVERFLOW) {
    // Buffer overflow occurred.
}

See Also

IDirectInputDevice8::Poll, Polling and Event Notification

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetDeviceInfo Method

Obtains information about the device's identity.

Syntax

HRESULT GetDeviceInfo(

    LPDIDEVICEINSTANCE pdidi
);

Parameters

pdidi
Address of a DIDEVICEINSTANCE structure to be filled with information about the device's identity. An application must initialize the structure's dwSize member before calling this method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft® DirectX® 3, it is also valid to pass a DIDEVICEINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEINSTANCE_DX3).

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetDeviceState Method

Retrieves immediate data from the device.

Syntax

HRESULT GetDeviceState(

    DWORD cbData,
    LPVOID lpvData
);

Parameters

cbData
Size of the buffer in the lpvData parameter, in bytes.
lpvData
Address of a structure that receives the current state of the device. The format of the data is established by a prior call to the IDirectInputDevice8::SetDataFormat method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_PENDING | Data is not yet available.

Remarks

Before device data can be obtained, set the cooperative level by using the IDirectInputDevice8::SetCooperativeLevel method, then set the data format by using IDirectInputDevice8::SetDataFormat, and acquire the device by using the IDirectInputDevice8::Acquire method.

The five predefined data formats require corresponding device state structures according to the following table:

Data format | State structure
c_dfDIMouse | DIMOUSESTATE
c_dfDIMouse2 | DIMOUSESTATE2
c_dfDIKeyboard | array of 256 bytes
c_dfDIJoystick | DIJOYSTATE
c_dfDIJoystick2 | DIJOYSTATE2

For example, if you passed the c_dfDIMouse format to the IDirectInputDevice8::SetDataFormat method, you must pass a DIMOUSESTATE structure to the IDirectInputDevice8::GetDeviceState method.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification, Buffered and Immediate Data

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetEffectInfo Method

Obtains information about an effect.

Syntax

HRESULT GetEffectInfo(

    LPDIEFFECTINFO pdei,
    REFGUID rguid
);

Parameters

pdei
DIEFFECTINFO structure that receives information about the effect. The calling application must initialize the dwSize member of the structure before calling this method.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the effect for which information is being requested.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft® DirectInput®. This value is equal to the REGDB_E_CLASSNOTREG standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

Note If this method is called on an non-Force Feedback device, E_POINTER will be returned.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetForceFeedbackState Method

Retrieves the state of the device's force-feedback system.

Syntax

HRESULT GetForceFeedbackState(

    LPDWORD pdwOut
);

Parameters

pdwOut
Location for flags that describe the current state of the device's force-feedback system.

The value is a combination of the following constants.

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off; that is, the device cannot operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on; that is, the device can operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_STOPPED
No effects are playing, and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off; that is, the device cannot operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on; that is, the device can operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.

Applications should ignore any flags that are not currently defined.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

The DIGFFS_PAUSED and DIGFFS_STOPPED flags may not always be reported correctly because there is no mechanism for the drivers to report that they support these flags.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetImageInfo Method

Retrieves information about a device image for use in a configuration property sheet.

Syntax

HRESULT GetImageInfo(

    LPDIDEVICEIMAGEINFOHEADER lpdiDevImageInfoHeader
);

Parameters

lpdiDevImageInfoHeader
Address of a DIDEVICEIMAGEINFOHEADER structure that receives information about the device image.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MAPFILEFAIL | An error has occurred reading either the vendor-supplied action-mapping file for the device or reading or writing the user configuration file for the device.
DIERR_MOREDATA | Not all the requested information fitted into the buffer.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetObjectInfo Method

Retrieves information about a device object, such as a button or axis.

Syntax

HRESULT GetObjectInfo(

    LPDIDEVICEOBJECTINSTANCE pdidoi,
    DWORD dwObj,
    DWORD dwHow
);

Parameters

pdidoi
Address of a DIDEVICEOBJECTINSTANCE structure to be filled with information about the object. The structure's dwSize member must be initialized before this method is called.
dwObj
Value that identifies the object whose information is to be retrieved. The value set for this parameter depends on the value specified in the dwHow parameter.
dwHow
Value that specifies how the dwObj parameter should be interpreted. The dwHow value can be one of the following:
DIPH_BYOFFSET
The dwObj parameter is the offset into the current data format of the object whose information is being accessed.
DIPH_BYID
The dwObj parameter is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects method.
DIPH_BYUSAGE
The dwObj parameter contains the HID Usage Page and Usage values of the object, combined by the DIMAKEUSAGEDWORD macro.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft® DirectX® 3, it is also valid to pass a DIDEVICEOBJECTINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEOBJECTINSTANCE_DX3).

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::GetProperty Method

Retrieves information about the input device.

Syntax

HRESULT GetProperty(

    REFGUID rguidProp,
    LPDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be retrieved. This can be one of the predefined values or a pointer to a GUID that identifies the property. The following properties are predefined for an input device.
DIPROP_APPDATA
Retrieves the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Determines whether device objects are self centering. The value returned can be DIPROPAUTOCENTER_OFF or DIPROPAUTOCENTER_ON. See IDirectInputDevice8::SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL.
DIPROP_BUFFERSIZE
Retrieves the input buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. You can set this value to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set. However, this property always returns the buffer size set using the IDirectInputDevice8::SetProperty method, even if the buffer cannot be supported because it is too large.
DIPROP_CALIBRATION
Predefined property that allows the application to access the information that Microsoft® DirectInput® uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for a particular axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object ID or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the DirectInput Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE
For use by device drivers; not used by applications.
DIPROP_CPOINTS
Retrieves calibration points used for the adjustment of incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. This property always returns DI_OK even if the device does not support force feedback. See IDirectInputDevice8::SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE. The retrieved value is in the range from 0 through 100, indicating the percentage of device memory in use. The device must be acquired in exclusive mode. If it is not, the method will fail with a return value of DIERR_NOTEXCLUSIVEACQUIRED.
DIPROP_GETPORTDISPLAYNAME
Retrieves the human-readable display name of the port to which this device is connected. Not generally used by applications.
DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one; that is, all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20; that is, all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on. This is a read-only property.
DIPROP_GUIDANDPATH
Retrieves the class GUID and device interface (path) for the device. This property lets advanced applications perform operations on a HID that are not supported by DirectInput. For more information, see the DIPROPGUIDANDPATH structure.
DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_JOYSTICKID
Retrieves the instance number of a joystick. This property is not implemented for the mouse or keyboard.
DIPROP_KEYNAME
Retrieves the localized key name for a keyboard key, as a DIPROPSTRING. Using this property on devices other than a keyboard will return unexpected names.
DIPROP_LOGICALRANGE
Retrieves the range of the raw data returned for axes on a HID. Devices can return negative values.
DIPROP_PHYSICALRANGE
Retrieves the range of data for axes as suggested by the manufacturer of a HID. Values can be negative. Normally DirectInput returns values from 0 through 0×FFFF, but the range can be made to conform to the manufacturer's suggested range by using DIPROP_RANGE.
DIPROP_PRODUCTNAME
Retrieves the friendly product name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. For some devices, this is a read-only property.
DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
DIPROP_SCANCODE
Retrieves the scan code for a keyboard key, as a DIPROPDWORD. If successful, S_OK is returned. E_FAIL is returned if the property cannot resolve specialized keys on USB keyboards because they do not exist in scan code form. For all other failures, E_INVALIDARG is returned.
DIPROP_TYPENAME
Predefined property that retrieves the type name of a device. For most game controllers, this is the registry key name under REGSTR_PATH_JOYOEM from which static device settings can be retrieved, but predefined joystick types have special names consisting of a number sign (#) followed by a character dependent on the type. This value might not be available for all devices.
DIPROP_USERNAME
Retrieves the user name for a user currently assigned to a device, as a DIPROPSTRING. User names are set by calling IDirectInputDevice8::SetActionMap. If no user name is set, the method returns S_FALSE.
DIPROP_VIDPID
Read-only device property that retrieves the vendor identity (ID) and product ID of a HID device. This property is of type DIPROPDWORD and contains both values. These two WORD values are combined in the dwData member of the DIPROPDWORD structure. See Examples. This property applies to the entire device, rather than to any particular object, so the dwHow member of the DIPROPHEADER structure must be set to DIPH_DEVICE.
pdiph
Address of the DIPROPHEADER portion of a larger property-dependent structure that contains the DIPROPHEADER structure as a member. The following structures are used for properties:
  • DIPROPDWORD is used for properties represented by a single numerical value.
  • DIPROPGUIDANDPATH is used for DIPROP_GUIDANDPATH.
  • DIPROPRANGE is used for properties represented by a pair of numerical values. Currently, the only such property is DIPROP_RANGE.
  • DIPROPSTRING is used for string properties.

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

If rguidProp is set to DIPROP_APPDATA, the dwHow member of the DIPROPHEADER structure should only be set to DIPH_BYUSAGE when getting information about input controls, such as buttons or axes. Setting DIPH_BYUSAGE for other device objects such as PID or LED devices can lead to unpredictable results.

S_FALSE is always returned when IDirectInputDevice8::GetProperty is called with rguidProp set to DIPROP_GETPORTDISPLAYNAME, even if the method succeeds.

The scan codes reported in Microsoft DirectX® 8.1 are different from the ones reported in DirectX 8.0. In DirectX 8.0, the property actually reported the single byte DIK_* constant associated with the key, not the scan code. In DirectX 8.1 and DirectX 9.0, the property reports the make scan code as would be reported by a PS/2 keyboard. In some cases, scan codes are multiple bytes, in which case the scan code bytes are ordered with the first byte in the least significant byte of the DWORD retrieved by the property.

Examples

The following C example shows how to obtain the value of the DIPROP_BUFFERSIZE property.

DIPROPDWORD dipdw;  // DIPROPDWORD contains a DIPROPHEADER structure.
HRESULT hr;
dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj        = 0; // device property
dipdw.diph.dwHow        = DIPH_DEVICE;

hr = idirectinputdevice9_GetProperty(pdid, DIPROP_BUFFERSIZE, &dipdw.diph);
if (SUCCEEDED(hr)) {
    // The dipdw.dwData member contains the buffer size.
}

The following example shows how to extract the two WORD values from the dwData member of the DIPROPDWORD structure using the DIPROP_VIDPID property:

wVendorID  = LOWORD(DIPROPDWORD.dwData);
wProductID = HIWORD(DIPROPDWORD.dwData);

See Also

IDirectInputDevice8::SetProperty

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::Initialize Method

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputDevice object. Microsoft® DirectInput® uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, a Microsoft ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that may be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device with which the interface should be associated. The IDirectInput8::EnumDevices method can be used to determine which instance GUIDs are supported by the system.

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE. If the method returns S_FALSE, the device had already been initialized with the instance GUID passed in though rGUID.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_DEVICENOTREG | The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard Component Object Model (COM) return value.

Remarks

If this method fails, the underlying object should be considered to be in an indeterminate state and must be reinitialized before use.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::Poll Method

Retrieves data from polled objects on a Microsoft® DirectInput® device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

Syntax

HRESULT Poll(VOID);

Return Value

If the method succeeds, the return value is DI_OK, or DI_NOEFFECT if the device does not require polling.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Before a device data can be polled, the data format must be set by using the IDirectInputDevice8::SetDataFormat or IDirectInputDevice8::SetActionMap method, and the device must be acquired by using the IDirectInputDevice8::Acquire method.

See Also

Polling and Event Notification

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::RunControlPanel Method

Runs the Microsoft® DirectInput® control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

Syntax

HRESULT RunControlPanel(

    HWND hwndOwner,
    DWORD dwFlags
);

Parameters

hwndOwner
Parent window handle. If this parameter is NULL , no parent window is used.
dwFlags
Not currently used. Zero is the only valid value.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SendDeviceData Method

Sends data to a device that accepts output.

Note There are no devices that accept output from IDirectInputDevice8::SendDeviceData. See Remarks.

Syntax

HRESULT SendDeviceData(

    DWORD cbObjectData,
    LPCDIDEVICEOBJECTDATA rgdod,
    LPDWORD pdwInOut,
    DWORD fl
);

Parameters

cbObjectData
Size, in bytes, of a single DIDEVICEOBJECTDATA structure.
rgdod
Array of DIDEVICEOBJECTDATA structures containing the data to send to the device.
pdwInOut
On entry, the variable pointed to by this parameter contains the number of elements in the array pointed to by rgdod. On exit, it contains the number of elements sent to the device.
fl
Flags controlling the manner in which data is sent. This can be 0 or the following value.
DISDD_CONTINUE
The device data sent is overlaid on the previously sent device data.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_REPORTFULL | More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED | The operation could not be completed because the device is not plugged in.

Remarks

Applications should not use IDirectInputDevice8::SendDeviceData. Force Feedback is the recommended way to send data to a device. If you want to send other data to a device, such as changing LED or internal device states, the HID application programming interface (API) is the recommended way.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SendForceFeedbackCommand Method

Sends a command to the device's force-feedback system.

Syntax

HRESULT SendForceFeedbackCommand(

    DWORD dwFlags
);

Parameters

dwFlags
Single value indicating the desired change in state. The value can be one of the following.
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock-on effects so that they continue playing to their full duration when restarted.

While the device is paused, new effects cannot be started, and existing ones cannot be modified. Doing so can cause the subsequent DISFFC_CONTINUE command to fail to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be re-created if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted, rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects are reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost. This command is equivalent to calling the IDirectInputEffect::Stop method for each effect playing.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SetActionMap Method

Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.

Syntax

HRESULT SetActionMap(

    LPCDIACTIONFORMAT lpdiActionFormat,
    LPCTSTR lptszUserName,
    DWORD dwFlags
);

Parameters

lpdiActionFormat
Address of a DIACTIONFORMAT structure containing information about the action map to be applied.
lptszUserName
Unicode string that specifies the name of the user for which the action map is being set. A value of NULL specifies the user currently logged into the system.
dwFlags
DWORD value that specifies how the action map is applied. This can be one of the following values.
DIDSAM_DEFAULT
Set the action map for this user. If the map differs from the current map, the new settings are saved to disk.
DIDSAM_FORCESAVE
Always save the configuration to disk.
DIDSAM_NOUSER
Reset user ownership for this device in the default configuration property sheet. Resetting user ownership does not remove the current action map.

Return Value

If the method succeeds, the return value can be one of the following error values: DI_OK, DI_SETTINGSNOTSAVED, or DI_WRITEPROTECT.

If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED or DIERR_INVALIDPARAM.

DI_OK | The operation completed successfully. This value is equal to the S_OK standard Component Object Model (COM) return value.
DI_SETTINGSNOTSAVED | The action map was applied to the device, but the settings could not be saved.
DI_WRITEPROTECT | A SUCCESS code indicating that settings cannot be modified.
DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.

Remarks

This method provides the mechanism to change action-to-control mapping from the device defaults. An application must use this method to map its in-game actions to virtual controls.

The user name passed to this method binds a set of action mappings for a device to a specific user. Settings are automatically saved to disk when they differ from the currently applied map. Applications that accept input from multiple users should be very careful when applying action maps to the system mouse or keyboard, as the action maps for each user may conflict.

The method can be called only when the device is not acquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::BuildActionMap

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SetCooperativeLevel Method

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

Syntax

HRESULT SetCooperativeLevel(

    HWND hwnd,
    DWORD dwFlags
);

Parameters

hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a Microsoft® DirectInput® device.
dwFlags
Flags that describe the cooperative level associated with the device. The following flags are defined:
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device can be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device can obtain exclusive access to the device while it is acquired. However, nonexclusive access to the device is always permitted, even if another application has obtained exclusive access.

An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window.
DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires nonexclusive access. Access to the device does not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
Disable the Microsoft Windows® logo key. Setting this flag ensures that the user cannot inadvertently break out of the application. Note, however, that DISCL_NOWINKEY has no effect when the default action mapping user interface (UI) is displayed, and the Windows logo key will operate normally as long as that UI is present.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_HANDLE | The HWND parameter is not a valid top-level window that belongs to the process.

Remarks

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.

If the system mouse is acquired in exclusive mode, the pointer is removed from the screen until the device is unacquired. This applies only to a mouse created by passing GUID_SysMouse to IDirectInput8::CreateDevice.

Applications that select the background exclusive mode cooperative level are not guaranteed to retain access to the device if another application requests exclusive access. When a background exclusive mode application loses access, calls to DirectInput device methods will fail and return DIERR_NOTACQUIRED. The application can regain access to the device by manually unacquiring the device and reaquiring it.

Applications must call this method before acquiring the device by using the IDirectInputDevice8::Acquire method.

See Also

Cooperative Levels

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SetDataFormat Method

Sets the data format for the Microsoft® DirectInput® device.

Syntax

HRESULT SetDataFormat(

    LPCDIDATAFORMAT lpdf
);

Parameters

lpdf
Address of a structure that describes the format of the data that the DirectInputDevice should return. An application can define its own DIDATAFORMAT structure or use one of the following predefined global variables:
  • c_dfDIKeyboard
  • c_dfDIMouse
  • c_dfDIMouse2
  • c_dfDIJoystick
  • c_dfDIJoystick2

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The data format must be set before the device can be acquired by using the IDirectInputDevice8::Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

If the application is using action mapping, the data format is set instead by the call to IDirectInputDevice8::SetActionMap.

See Also

IDirectInputDevice8::GetDeviceState

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SetEventNotification Method

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

Syntax

HRESULT SetEventNotification(

    HANDLE hEvent
);

Parameters

hEvent
Handle to the event that is to be set when the device state changes. Microsoft® DirectInput® uses the Microsoft Win32® SetEvent function on the handle when the state of the device changes. If the hEvent parameter is NULL, notification is disabled.

The application can create the handle as either a manual-reset or autoreset event by using the Win32 CreateEvent function. If the event is created as an autoreset event, the operating system automatically resets the event when a wait has been satisfied. If the event is created as a manual-reset event, it is the application's responsibility to call the Win32 ResetEvent function to reset it. DirectInput does not call the Win32 ResetEvent function for event notification handles. Most applications create the event as an automatic-reset event.

Return Value

If the method succeeds, the return value is DI_OK or DI_POLLEDDEVICE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_HANDLEEXISTS | The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

Do not call the Win32 CloseHandle function on the event while it has been selected into a DirectInputDevice object. You must call this method with the hEvent parameter set to NULL before closing the event handle.

The event notification handle cannot be changed while the device is acquired. If the function is successful, the application can use the event handle like any other Win32 event handle.

Examples

The following code example checks whether the handle is currently set without blocking:

dwResult = WaitForSingleObject(hEvent, 0);
if (dwResult == WAIT_OBJECT_0) {
    // Event is set. If the event was created as
    // autoreset, it has also been reset.
}

The following code example illustrates blocking indefinitely until the event is set. This behavior is strongly discouraged because the thread does not respond to the system until the wait is satisfied. In particular, the thread does not respond to Microsoft Windows® messages.

dwResult = WaitForSingleObject(hEvent, INFINITE);
if (dwResult == WAIT_OBJECT_0) {
    // Event has been set. If the event was created
    // as autoreset, it has also been reset.
}

The following code example illustrates a typical application loop for a non-message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                        INFINITE, QS_ALLINPUT);
    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // Unexpected error.
        Panic();
        break;
    }
}

The following code example illustrates a typical message loop for a message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };
DWORD dwWait = 0;

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                                         dwWait, QS_ALLINPUT);
    dwWait = 0;

    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // No input or messages waiting.
        // Do a frame of the game.
        // If the game is idle, tell the next wait
        // to wait indefinitely for input or a message.
        if (!DoGame()) {
            dwWait = INFINITE;
        }
        break;
    }
}

See Also

Polling and Event Notification

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::SetProperty Method

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

Syntax

HRESULT SetProperty(

    REFGUID rguidProp,
    LPCDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be set. This can be one of the predefined values, or a pointer to a GUID that identifies the property. The following property values are predefined for an input device:
DIPROP_APPDATA
Sets the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Specifies whether device objects are self centering. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member can be one of the following values.

DIPROPAUTOCENTER_OFF: The device should not automatically center when the user releases the device. An application that uses force feedback should disable autocentering before playing effects.

DIPROPAUTOCENTER_ON: The device should automatically center when the user releases the device.

Not all devices support the autocenter property.

DIPROP_AXISMODE
Sets the axis mode. The value being set (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_BUFFERSIZE
Sets the input buffer size. The value being set must be specified in the dwData member of the associated DIPROPDWORD structure. See Remarks. This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_CALIBRATION
Predefined property that allows the application to access the information that Microsoft® DirectInput® uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for an axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object identifier (ID) or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the Microsoft DirectX® Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE
Enables the application to specify whether DirectInput should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The dwData member of the DIPROPDWORD structure can be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by applications of the control panel type. Note that raw data might include negative values.

Setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_CPOINTS
Sets calibration points used for the adjustment of incoming raw data. The values being set must be specified as CPOINT types in the cp array of the associated DIPROPCPOINTS structure. This setting applies to individual device objects, so the dwHow member of the associated DIPROPHEADER structure must be set to either DIPH_BYID or DIPH_BYOFFSET.
DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range. This setting can be applied to either the entire device or to a specific axis.
DIPROP_FFGAIN
Sets the gain for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a gain value that is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90 percent of their nominal magnitudes.

DirectInput always checks the gain value before setting the gain property. If the gain is outside of the range (less than zero or greater than 10,000), IDirectInputDevice8::SetProperty will return DIERR_INVALIDPARAM. Otherwise, if successful, it will return DI_OK, even if the device does not support force feedback.

Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences.

Unlike other properties, the gain can be set when the device is in an acquired state.

DIPROP_INSTANCENAME
This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_PRODUCTNAME
This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

Setting the product name is only useful for changing the user-defined name of an analog joystick on Microsoft Windows® 98,Windows 2000, and Windows Millennium Edition (Windows Me) computers. In other cases, attempting to set this property will still return DI_OK. However, the name is not stored in a location used by IDirectInputDevice8::GetProperty.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lMin and lMax members of the associated DIPROPRANGE structure.

For some devices, this is a read-only property.

You cannot set a reverse range; lMax must be greater than lMin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone). This setting can be applied to either the entire device or a specific axis.
pdiph
Address of the DIPROPHEADER structure contained within the type-specific property structure.

Return Value

If the method succeeds, the return value is DI_OK or DI_PROPNOEFFECT.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set.

See Also

IDirectInputDevice8::GetProperty

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::Unacquire Method

Releases access to the device.

Syntax

HRESULT Unacquire(VOID);

Return Value

The return value is DI_OK is the device was unacquired, or DI_NOEFFECT if the device was not in an acquired state.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputDevice8::WriteEffectToFile Method

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

Syntax

HRESULT WriteEffectToFile(

    LPCSTR lpszFileName,
    DWORD dwEntries,
    LPCDIFILEEFFECT rgDiFileEft,
    DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
dwEntries
Number of structures in the rgDiFileEft array.
rgDiFileEft
Array of DIFILEEFFECT structures.
dwFlags
Flags which control how the effect should be written. This can be DIFEF_DEFAULT (= 0) or the following value:
DIFEF_INCLUDENONSTANDARD
Includes effects that are not defined by Microsoft® DirectInput®. If this flag is not specified, only effects with globally unique identifiers (GUIDs) defined in Dinput.h, such as GUID_ConstantForce, are written.

Return Value

If the method succeeds, it returns DI_OK.

If it fails, the return value can be DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::EnumEffectsInFile

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect Interface

Applications use the methods of the IDirectInputEffect interface to manage effects of force-feedback devices.

IDirectInputEffect Members

Download

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

Escape

Sends a hardware-specific command to the driver.

GetEffectGuid

Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect object.

GetEffectStatus

Retrieves the status of an effect.

GetParameters

Retrieves information about an effect.

Initialize

Initializes a DirectInputEffect object.

SetParameters

Sets the characteristics of an effect.

Start

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

Stop

Stops playing an effect.

Unload

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

Remarks

The interface is obtained by using the IDirectInputDevice8::CreateEffect method.

The LPDIRECTINPUTEFFECT type is defined as a pointer to the IDirectInputEffect interface:

typedef struct IDirectInputEffect    *LPDIRECTINPUTEFFECT;

Interface Information

Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Download Method

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

Syntax

HRESULT Download(VOID);

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_EFFECTPLAYING | The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the method returns S_FALSE, the effect has already been downloaded to the device.

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for IDirectInputEffect::SetParameters.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Escape Method

Sends a hardware-specific command to the driver.

Syntax

HRESULT Escape(

    LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer used.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_DEVICEFULL | The device is full.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::GetEffectGuid Method

Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect object.

Syntax

HRESULT GetEffectGuid(

    LPGUID pguid
);

Parameters

pguid
GUID structure that is filled by the method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Additional information about the effect can be obtained by passing the GUID to IDirectInputDevice8::GetEffectInfo.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::GetEffectStatus Method

Retrieves the status of an effect.

Syntax

HRESULT GetEffectStatus(

    LPDWORD pdwFlags
);

Parameters

pdwFlags
Status flags for the effect. The value can be 0 or one or more of the following constants:
DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::GetParameters Method

Retrieves information about an effect.

Syntax

HRESULT GetParameters(

    LPDIEFFECT peff,
    DWORD dwFlags
);

Parameters

peff
Address of a DIEFFECT structure that receives effect information. The dwSize member must be filled in by the application before calling this method.
dwFlags
Flags that specify which parts of the effect information are to be retrieved. The value can be 0 or one or more of the following constants:
DIEP_ALLPARAMS
The union of all other DIEP_* flags, indicating that all members of the DIEFFECT structure are being requested.
DIEP_ALLPARAMS_DX5
The union of all other DIEP_* flags except the DIEP_STARTDELAY flag.
DIEP_AXES
The cAxes and rgdwAxes members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rgdwAxes member. If the buffer is too small, the method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.
DIEP_DIRECTION
The cAxes and rglDirection members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rglDirection member. If the buffer is too small, the IDirectInputEffect::GetParameters method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.

The dwFlags member must include at least one of the coordinate system flags (DIEFF_CARTESIAN, DIEFF_POLAR, or DIEFF_SPHERICAL). Microsoft® DirectInput® returns the direction of the effect in one of the coordinate systems you specified, converting between coordinate systems as necessary. On exit, exactly one of the coordinate system flags is set in the dwFlags member, indicating which coordinate system DirectInput used. In particular, passing all three coordinate system flags retrieves the coordinates in exactly the same format in which they were set.
DIEP_DURATION
The dwDuration member should receive data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that should receive data. If the effect does not have an envelope associated with it, the lpEnvelope member is set to NULL.
DIEP_GAIN
The dwGain member should receive data.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member should receive data.
DIEP_STARTDELAY
The dwStartDelay member should receive data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member should receive data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member should receive data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams member points to a buffer whose size is specified by the cbTypeSpecificParams member. On return, the buffer is filled in with the type-specific data associated with the effect, and the cbTypeSpecificParams member contains the number of bytes copied. If the buffer supplied by the application is too small to contain all the type-specific data, the method returns DIERR_MOREDATA, and the cbTypeSpecificParams member contains the required size of the buffer in bytes.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MOREDATA | Not all the requested information fitted into the buffer.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Common errors resulting in a DIERR_INVALIDPARAM error include not setting the dwSize member of the DIEFFECT structure, passing invalid flags, or not setting up the members in the DIEFFECT structure properly in preparation for receiving the effect information. For example, if information is to be retrieved in the dwTriggerButton member, the dwFlags member must be set to either DIEFF_OBJECTIDS or DIEFF_OBJECTOFFSETS so that DirectInput knows how to describe the button.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Initialize Method

Initializes a DirectInputEffect object.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputEffect object. Microsoft® DirectInput® uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Address of the globally unique identifier (GUID) identifying the effect with which the interface is associated. The IDirectInputDevice8::EnumEffects method can be used to determine which effect GUIDs are supported by the device.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be an indeterminate state and needs to be reinitialized before it can be subsequently used.

If this method succeeds, all effect parameters will be invalid. You must call IDirectInputEffect::SetParameters before an effect can be downloaded or started.

The IDirectInputDevice8::CreateEffect method automatically initializes the effect after creating it. Applications normally do not need to call the IDirectInputEffect::Initialize method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::SetParameters Method

Sets the characteristics of an effect.

Syntax

HRESULT SetParameters(

    LPCDIEFFECT peff,
    DWORD dwFlags
);

Parameters

peff
DIEFFECT structure that contains effect information. The dwSize member must be filled in by the application before calling this method, as well as any members specified by corresponding bits in the dwFlags parameter.
dwFlags
Flags that specify which portions of the effect information are to be set and how the downloading of the parameters should be handled. The value can be 0 or one or more of the following constants:
DIEP_AXES
The cAxes and rgdwAxes members contain data.
DIEP_DIRECTION
The cAxes and rglDirection members contain data. The dwFlags member specifies (with DIEFF_CARTESIAN or DIEFF_POLAR) the coordinate system in which the values should be interpreted.
DIEP_DURATION
The dwDuration member contains data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that contains data. To detach any existing envelope from the effect, pass this flag and set the lpEnvelope member to NULL.
DIEP_GAIN
The dwGain member contains data.
DIEP_NODOWNLOAD
Suppress the automatic IDirectInputEffect::Download that is normally performed after the parameters are updated. See Remarks.
DIEP_NORESTART
Suppress the stopping and restarting of the effect to change parameters. See Remarks.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member contains data.
DIEP_START
The effect is to be started (or restarted if it is currently playing) after the parameters are updated. By default, the play state of the effect is not altered.
DIEP_STARTDELAY
The dwStartDelay member contains data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member contains data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member contains data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams and cbTypeSpecificParams members of the DIEFFECT structure contain the address and size of type-specific data for the effect.

Return Value

If the method succeeds, the return value can be DI_DOWNLOADSKIPPED, DI_EFFECTRESTARTED, DI_OK, DI_TRUNCATED, or DI_TRUNCATEDANDRESTARTED. If the method fails, the return value can be DIERR_NOTINITIALIZED, DIERR_INCOMPLETEEFFECT, DIERR_INPUTLOST, DIERR_INVALIDPARAM, or DIERR_EFFECTPLAYING.

DI_DOWNLOADSKIPPED | The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.
DI_EFFECTRESTARTED | The effect was stopped, the parameters were updated, and the effect was restarted.
DI_OK | The operation completed successfully. This value is equal to the S_OK standard Component Object Model (COM) return value.
DI_TRUNCATED | The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.
DI_TRUNCATEDANDRESTARTED | Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_EFFECTPLAYING | The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.

Remarks

The dwDynamicParams member of the DIEFFECTINFO structure for the effect specifies which parameters can be dynamically updated while the effect is playing.

The IDirectInputEffect::SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, you can manually download the effect by invoking the IDirectInputEffect::Download method.

If the effect is playing while the parameters are changed, the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect then continues for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly, as if the direction had not changed.

In the same situation, if after two seconds the duration of the effect were changed to 1.5 seconds, the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned, and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the IDirectInputEffect::Start method had been called with the dwIterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling IDirectInputEffect::Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Start Method

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

Syntax

HRESULT Start(

    DWORD dwIterations,
    DWORD dwFlags
);

Parameters

dwIterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration.

To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass INFINITE. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the IDirectInputEffect::SetParameters method, and change the dwDuration member to INFINITE.
dwFlags
Flags that describe how the effect should be played by the device. The value can be 0 or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Stop Method

Stops playing an effect.

Syntax

HRESULT Stop(VOID);

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

© 2002 Microsoft Corporation. All rights reserved.


IDirectInputEffect::Unload Method

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

Syntax

HRESULT Unload(VOID);

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


Callback Functions

This section describes the seven functions that are prototype callback functions for use with various enumeration methods. Applications can declare one of these callback functions under any name and define it in any way, but the parameter and return types must be the same as in the prototype.

Functions

  • DIConfigureDevicesCallback
  • DIEnumCreatedEffectObjectsCallback
  • DIEnumDeviceObjectsCallback
  • DIEnumDevicesBySemanticsCallback
  • DIEnumDevicesCallback
  • DIEnumEffectsCallback
  • DIEnumEffectsInFileCallback

© 2002 Microsoft Corporation. All rights reserved.


DIConfigureDevicesCallback Function

Application-defined callback function that is called each time the property sheet image is refreshed. This function needs to be supplied only when the application is displaying the property sheet within its own window.

Syntax

BOOL CALLBACK DIConfigureDevicesCallback(

    IUnknown *lpDDSTarget,
    LPVOID pvRef
);

Parameters

lpDDSTarget
Pointer to the IUnknown interface of the surface in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure that was passed to IDirectInput8::ConfigureDevices.
pvRef
Application-defined value passed to IDirectInput8::ConfigureDevices as the pvRef parameter.

Return Value

Can return TRUE or FALSE. Microsoft® DirectInput® does not use the return value.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEnumCreatedEffectObjectsCallback Function

Application-defined callback function that receives DirectInputDevice effects as a result of a call to the IDirectInputDevice8::EnumCreatedEffectObjects method.

Syntax

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(

    LPDIRECTINPUTEFFECT peff,
    LPVOID pvRef
);

Parameters

peff
Address of an effect object that has been created.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumCreatedEffectObjects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEnumDeviceObjectsCallback Function

Application-defined callback function that receives DirectInputDevice objects as a result of a call to the IDirectInputDevice8::EnumObjects method.

Syntax

BOOL CALLBACK DIEnumDeviceObjectsCallback(

    LPCDIDEVICEOBJECTINSTANCE lpddoi,
    LPVOID pvRef
);

Parameters

lpddoi
DIDEVICEOBJECTINSTANCE structure that describes the object being enumerated.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumObjects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEnumDevicesBySemanticsCallback Function

Application-defined callback function that receives Microsoft® DirectInput® devices as a result of a call to the IDirectInput8::EnumDevicesBySemantics method.

Syntax

BOOL CALLBACK DIEnumDevicesBySemanticsCallback(

    LPCDIDEVICEINSTANCE lpddi,
    LPDIRECTINPUTDEVICE8 lpdid,
    DWORD dwFlags,
    DWORD dwRemaining,
    LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
lpdid
Pointer to the IDirectInputDevice8 interface for the device.
dwFlags
Flags that provide information about why the device is being enumerated. This can be a combination of action-mapping flags and one usage flag. At least one action-mapping flag is always present.

The DIEDBS_MAPPEDPRI1 and DIEDBS_MAPPEDPRI2 action-mapping flags and the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE usage flags are defined below.

DIEDBS_MAPPEDPRI1
The device is being enumerated because priority 1 actions can be mapped to the device.
DIEDBS_MAPPEDPRI2
The device is being enumerated because priority 2 actions can be mapped to the device.
DIEDBS_RECENTDEVICE
The device is being enumerated because the commands described by the action-mapping flags were recently used.
DIEDBS_NEWDEVICE
The device is being enumerated because the device was installed recently. Devices described by this flag have not been used with this game before.
dwRemaining
Number of devices, after this one, remaining to be enumerated.
pvRef
The application-defined value passed to IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

See Also

DIEnumDevicesCallback

© 2002 Microsoft Corporation. All rights reserved.


DIEnumDevicesCallback Function

Application-defined callback function that receives Microsoft® DirectInput® devices as a result of a call to the IDirectInput8::EnumDevices method.

Syntax

BOOL CALLBACK DIEnumDevicesCallback(

    LPCDIDEVICEINSTANCE lpddi,
    LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
pvRef
The application-defined value passed to IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

See Also

DIEnumDevicesBySemanticsCallback

© 2002 Microsoft Corporation. All rights reserved.


DIEnumEffectsCallback Function

Application-defined callback function used with the IDirectInputDevice8::EnumEffects method.

Syntax

BOOL CALLBACK DIEnumEffectsCallback(

    LPCDIEFFECTINFO pdei,
    LPVOID pvRef
);

Parameters

pdei
DIEFFECTINFO structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEnumEffectsInFileCallback Function

Application-defined callback function used with the IDirectInputDevice8::EnumEffectsInFile method.

Syntax

BOOL CALLBACK DIEnumEffectsInFileCallback(

    LPCDIFILEEFFECT lpDiFileEf,
    LPVOID pvRef
);

Parameters

lpDiFileEf
DIFILEEFFECT structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffectsInFile as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section is a reference for Microsoft® DirectInput® functions other than COM interface methods and callback functions.

The following function falls into this category:

Functions

  • DirectInput8Create
  • ShowJoyCPL

© 2002 Microsoft Corporation. All rights reserved.


DirectInput8Create Function

Creates a Microsoft® DirectInput® object and returns an IDirectInput8 or later interface.

Syntax

HRESULT WINAPI DirectInput8Create(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFIID riidltf,
    LPVOID *ppvOut,
    LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an Microsoft ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. If the application defines DIRECTINPUT_VERSION before including Dinput.h, the value must be greater than 0x0800. For earlier versions, use DirectInputCreateEx, which is in Dinput.lib.
riidltf
Unique identifier of the desired interface. This value is IID_IDirectInput8A or IID_IDirectInput8W. Passing the IID_IDirectInput8 define selects the ANSI or Unicode version of the interface, depending on whether UNICODE is defined during compilation.
ppvOut
Address of a pointer to a variable to receive the interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for Component Object Model (COM) aggregation, or NULL if the interface is not aggregated. Most callers pass NULL. If aggregation is requested, the object returned in ppvOut is a pointer to IUnknown, as required by COM aggregation.

Return Value

If the function succeeds, the return value is DI_OK.

If the function fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION | The application was written for an unsupported prerelease version of DirectInput.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_OLDDIRECTINPUTVERSION | The application requires a newer version of DirectInput.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

The DirectInput object created by this function is implemented in Dinput8.dll. Versions of interfaces earlier than Microsoft DirectX® 8.0 cannot be obtained in this implementation.

To create a DirectX 8.x interface with the DirectX 9.0 software development kit (SDK) without using CoCreateInstance World Wide Web link:

  1. Set "#define DIRECTINPUT_VERSION 0x0800" before the include statement for Dinput8.h.
  2. Call DirectInput8Create instead of DirectInputCreateEx.
  3. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 8.x interface with the DirectX 8.x SDK without using CoCreateInstance:

  1. Call DirectInput8Create instead of DirectInputCreateEx.
  2. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or DirectX 9.0 SDK without using CoCreateInstance:

  1. Set "#define DIRECTINPUT_VERSION 0x0700" before the include statement for dinput.h.
  2. Call DirectInputCreateEx instead of DirectInput8Create.
  3. Link to the Dinput.lib library instead of Dinput8.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or DirectX 9.0 SDK using CoCreateInstance:

  1. Call CoInitializeEx.
  2. Call CoCreateInstance using CLISID_DirectInput.
  3. Use IDirectInput7::Initialize to initialize the DirectInput object.

To create a DirectX 8.x or DirectX 9.0 interface from the DirectX 8.x or DirectX 9.0 SDK using CoCreateInstance:

  1. Call CoInitializeEx World Wide Web link.
  2. Call CoCreateInstance using CLISID_DirectInput8.
  3. Use IDirectInput8::Initialize to initialize the DirectInput object.

Calling the function with punkOuter = NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput8W, lplpDirectInput), then initializing it with IDirectInput8::Initialize.

Calling the function with punkOuter != NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

Function Information

Header | dinput.h
Import library | dinput8.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ShowJoyCPL Function

Invokes the joystick control panel directly, using the passed window handle as the parent of the dialog box.

Syntax

VOID WINAPI ShowJoyCPL(

    HWND hWnd
);

Parameters

hWnd
Window handle of the parent dialog box.

Return Value

None.

Remarks

It is recommended that applications use IDirectInputDevice8::RunControlPanel instead of ShowJoyCPL.

The following typedef is provided to allow declaration and casting of an appropriately typed variable.

typedef void (WINAPI* LPFNSHOWJOYCPL)( HWND hWnd );

Example

ShowJoyCPL can be called using the function pointer returned by GetProcAddress, where hCPL is an HMODULE returned by LoadLibrary.

HMODULE hCPL;
LPFNSHOWJOYCPL pShowJoyCPL;
.
.
.
hCPL = LoadLibrary(TEXT("joy.cpl"));
pShowJoyCPL  = (LPFNSHOWJOYCPL)GetProcAddress(hCPL, TEXT("ShowJoyCPL"));

pShowJoyCPL(NULL);  //Invoke Joystick Control Panel

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows XP SP1

© 2002 Microsoft Corporation. All rights reserved.


Macros

This section describes the macros used in Microsoft® DirectInput®.

Macros

  • DIDFT_GETINSTANCE
  • DIDFT_GETTYPE
  • DIDFT_MAKEINSTANCE
  • DIEFT_GETTYPE
  • DIMAKEUSAGEDWORD
  • DISEQUENCE_COMPARE
  • GET_DIDEVICE_SUBTYPE
  • GET_DIDEVICE_TYPE

Dinput.h also defines macros for C calls to all the methods of the IDirectInput8 and IDirectInputDevice8 interfaces. These macros eliminate the need for pointers to method tables. For example, the following is a C call to the IDirectInputDevice8::Release method.

lpdid->lpVtbl->Release(lpdid));

The equivalent macro call looks like this.

idirectinputdevice9_Release(lpdid);

All these macros take the same parameters as the method calls themselves.

© 2002 Microsoft Corporation. All rights reserved.


DIDFT_GETINSTANCE Macro

The DIDFT_GETINSTANCE macro extracts the object instance number code from a data format type.

Syntax

#define DIDFT_GETINSTANCE(n) LOWORD((n) >> 8)

Parameters

n
Microsoft® DirectInput® data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_MAKEINSTANCE, DIDFT_GETTYPE

© 2002 Microsoft Corporation. All rights reserved.


DIDFT_GETTYPE Macro

The DIDFT_GETTYPE macro extracts the object type code from a data format type.

Syntax

#define DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft® DirectInput® data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_GETINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


DIDFT_MAKEINSTANCE Macro

The DIDFT_MAKEINSTANCE macro creates an instance identifier of a device object for packing in the dwType member of the DIOBJECTDATAFORMAT structure.

Syntax

#define DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8)

Parameters

n
Instance of the object; for example, 1 for button 1 of a mouse.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_GETINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


DIEFT_GETTYPE Macro

The DIEFT_GETTYPE macro extracts the effect type code from an effect format type.

Syntax

#define DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft® DirectInput® effect format type. The possible values for this parameter are identical to those found in the dwEffType member of the DIEFFECTINFO structure.

Return Value

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIMAKEUSAGEDWORD Macro

The DIMAKEUSAGEDWORD macro combines the usage page and usage codes for a device object representing a Human Interface Device (HID), for passing to the IDirectInputDevice8::GetObjectInfo method.

Syntax

#define DIMAKEUSAGEDWORD(UsagePage, Usage) \
        ((DWORD)MAKELONG(Usage, UsagePage))

Parameters

UsagePage
Usage page of the device object.
Usage
Usage of the device object.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DISEQUENCE_COMPARE Macro

The DISEQUENCE_COMPARE macro compares two Microsoft® DirectInput® sequence numbers, compensating for wraparound.

Syntax

#define DISEQUENCE_COMPARE(dwSequence1, cmp, dwSequence2) \
                ((int)((dwSequence1) - (dwSequence2)) cmp 0)

Parameters

dwSequence1
First sequence number to compare.
cmp
One of the following comparison operators: ==, !=, <, >, <=, or >=.
dwSequence2
Second sequence number to compare.

Return Value

Returns a nonzero value if the result of the comparison specified by the cmp parameter is true, or zero otherwise.

Remarks

The following example checks whether the dwSequence1 parameter value precedes the dwSequence2 parameter value chronologically.

BOOL Sooner = (DISEQUENCE_COMPARE(dwSequence1, <, dwSequence2));

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


GET_DIDEVICE_SUBTYPE Macro

The GET_DIDEVICE_SUBTYPE macro extracts the device subtype code from a device type description code.

Syntax

#define GET_DIDEVICE_SUBTYPE(dwDevType)  HIBYTE(dwDevType)

Parameters

dwDevType
Microsoft® DirectInput® device type description code. The possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Remarks

The interpretation of the subtype code depends on the primary type.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

GET_DIDEVICE_TYPE, DIDEVICEINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


GET_DIDEVICE_TYPE Macro

The GET_DIDEVICE_TYPE macro extracts the device primary type code from a device type description code.

Syntax

#define GET_DIDEVICE_TYPE(dwDevType)  LOBYTE(dwDevType)

Parameters

dwDevType
Microsoft® DirectInput® device type description code. Possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

GET_DIDEVICE_SUBTYPE, DIDEVICEINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains information about the structures used with Microsoft® DirectInput®.

Structures

  • CPOINT
  • DIACTION
  • DIACTIONFORMAT
  • DICOLORSET
  • DICONDITION
  • DICONFIGUREDEVICESPARAMS
  • DICONSTANTFORCE
  • DICUSTOMFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEIMAGEINFO
  • DIDEVICEIMAGEINFOHEADER
  • DIDEVICEINSTANCE
  • DIDEVICEOBJECTDATA
  • DIDEVICEOBJECTINSTANCE
  • DIEFFECT
  • DIEFFECTINFO
  • DIEFFESCAPE
  • DIENVELOPE
  • DIFILEEFFECT
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODIC
  • DIPROPCPOINTS
  • DIPROPDWORD
  • DIPROPGUIDANDPATH
  • DIPROPHEADER
  • DIPROPPOINTER
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE

Note The memory for all Microsoft DirectX® structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DIDEVCAPS:
DIDEVCAPS didevcaps; // Can't use this yet

ZeroMemory(&didevcaps, sizeof(didevcaps));
didevcaps.dwSize = sizeof(didevcaps);

// Now the structure Can be used.

© 2002 Microsoft Corporation. All rights reserved.


CPOINT Structure

Describes a calibration point. An array of CPOINT structures is contained by a DIPROPCPOINTS structure.

Syntax

typedef struct _CPOINT {
    LONG lP;
    DWORD dwLog;
} CPOINT, *PCPOINT;

Members

lP
Raw data
dwLog
Scaling value to be associated with the lP number. The percentage of the maximum value multiplied by 10000.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

Using CPOINTs

© 2002 Microsoft Corporation. All rights reserved.


DIACTION Structure

Describes a mapping of one game action to one device semantic. An array of DIACTION structures is contained by a DIACTIONFORMAT structure.

Syntax

typedef struct _DIACTION {
    UINT_PTR    uAppData;
    DWORD       dwSemantic;
    DWORD       dwFlags;
    union {
        LPCTSTR lptszActionName;
        UINT    uResIdString;
    };
    GUID        guidInstance;
    DWORD       dwObjID;
    DWORD       dwHow;
} DIACTION, *LPDIACTION;

typedef const DIACTION *LPCDIACTION;

Members

uAppData
Address of an application-defined UINT value to be returned to the application by IDirectInputDevice8::GetDeviceData when the state of the control associated with the action changes. This value is returned in the uAppData member of the DIDEVICEOBJECTDATA structure. It is typically an identifier for the application-specific action associated with the device object, but can also be a function pointer.
dwSemantic
For a joystick, a predefined action mapping constant for this application genre representing a virtual control or a constant for a control not defined in the genre. For a keyboard, mouse, or Microsoft® DirectPlay® voice device, a constant that represents a particular device object. See Action Mapping Constants.
dwFlags
Flags used to request specific attributes or processing. Can be zero or one or more of the following values.
DIA_APPFIXED
The action cannot be remapped by Microsoft DirectInput®.
DIA_APPMAPPED
The dwObjID member is valid, and IDirectInputDevice8::BuildActionMap will not override the application-defined mapping.
DIA_APPNOMAP
This action is not to be mapped.
DIA_FORCEFEEDBACK
The action must be mapped to an actuator or trigger.
DIA_NORANGE
The default range is not to be set for this action. This flag can be set only for absolute axis actions.
lptszActionName
Application-defined name of the action. This string is displayed by the device property sheet when IDirectInput8::ConfigureDevices is called.
uResIdString
Resource identifier for the string for this action. The module instance for this resource is specified in the hInstString member of the DIACTIONFORMAT structure that contains this structure.
guidInstance
Device instance globally unique identifier (GUID) if a specific device is requested. Otherwise GUID_NULL.
dwObjID
Control identifier. Use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to retrieve the instance and type from this value.
dwHow
When the structure is returned by IDirectInputDevice8::BuildActionMap, this member receives a value to indicate the mapping mechanism used by DirectInput to configure the action. This memeber is ignored when the action map is passed to IDirectInputDevice8::SetActionMap. The following values are defined.
DIAH_APPREQUESTED
The mapping was configured by the application, which specified the device (guidInstance) and device object (dwObjID) when calling IDirectInputDevice8::BuildActionMap.
DIAH_DEFAULT
The mapping was determined by DirectInput in the absence of other mapping information.
DIAH_ERROR
An error occurred. The action cannot be matched to a control on the device. The action will be ignored when the action map is set.
DIAH_HWAPP
The mapping was specified by the hardware manufacturer for this game.
DIAH_HWDEFAULT
The mapping was specified by the hardware manufacturer for this genre.
DIAH_UNMAPPED
No suitable device object was found.
DIAH_USERCONFIG
The mapping was configured by the user.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping

© 2002 Microsoft Corporation. All rights reserved.


DIACTIONFORMAT Structure

Contains information about the calling application and acts as a container for an array of DIACTION structures that define action-to-control mappings for a genre.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwActionSize;
    DWORD dwDataSize;
    DWORD dwNumActions;
    LPDIACTION rgoAction;
    GUID guidActionMap;
    DWORD dwGenre;
    DWORD dwBufferSize;
    LONG lAxisMin;
    LONG lAxisMax;
    HINSTANCE hInstString;
    FILETIME ftTimeStamp;
    DWORD dwCRC;
    TCHAR tszActionMap[MAX_PATH];
} DIACTIONFORMAT;

Members

dwSize
DWORD value that specifies the size of the DIACTIONFORMAT structure, in bytes.
dwActionSize
DWORD value that specifies the size of the DIACTION structure, in bytes.
dwDataSize
DWORD value that specifies the size of the device data to be returned by the device for immediate device data, in bytes. This member should be dwNumActions multiplied by four.
dwNumActions
DWORD value that specifies the number of elements in the rgoAction array.
rgoAction
Address of an array of DIACTION structures, each of which describes how an action maps to a virtual control or device object, and how the mapping information should be displayed to the user.
guidActionMap
globally unique identifier (GUID) that identifies the action map. Device manufacturers can use this value to tune mappings for a specific title.
dwGenre
DWORD value that specifies the genre of the application. For possible values, see Action Mapping Constants.
dwBufferSize
DWORD value that specifies the number of input data packets in the buffer for each device to which this action map is to be applied. The buffer size must be set to a value greater than zero in order to retrieve data by using IDirectInputDevice8::GetDeviceData. Applications that set this member to the desired buffer size before calling IDirectInputDevice8::SetActionMap do not need to set the DIPROP_BUFFERSIZE property by using IDirectInputDevice8::SetProperty.
lAxisMin
Minimum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMin value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

lAxisMax
Maximum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMax value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

hInstString
Handle of the module containing string resources for action names, as specified in the uResIdString member of the DIACTION structure for each action. Can be zero if action names are specified in the lptszActionName member of the DIACTION structure for each action.
ftTimeStamp
FILETIME structure that receives the time at which this action map was last written to disk. See Remarks.
dwCRC
Cyclic redundancy check for this map. Used internally by Microsoft® DirectInput® to determine when a set of mappings should be saved to disk.
tszActionMap
Null-terminated string, of maximum length MAX_PATH, that specifies the friendly name for this action map. This string appears in the drop-down list box in the default property sheet.

Remarks

The ftTimeStamp member can contain special values that apply to new and unused devices. New devices have never been enumerated for this application and have never had an action map applied to them. Unused devices have been enumerated for the application before but have never had an action map applied. New devices always have DIAFTS_NEWDEVICELOW and DIAFTS_NEWDEVICEHIGH in the low and high DWORDs respectively of the FILETIME structure. Unused devices have DIAFTS_UNUSEDDEVICELOW and DIAFTS_UNUSEDDEVICEHIGH in these positions.

Applications should not use ftTimeStamp to check for new devices. Instead, they should look for the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE flags in the enumeration callback. For more information, see DIEnumDevicesBySemanticsCallback.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping

© 2002 Microsoft Corporation. All rights reserved.


DICOLORSET Structure

Describes a set of colors used to draw the device configuration user interface. It is part of the DICONFIGUREDEVICESPARAMS structure.

Syntax

typedef struct _DICOLORSET {
    DWORD    dwSize
    D3DCOLOR cTextFore;
    D3DCOLOR cTextHighlight;
    D3DCOLOR cCalloutLine;
    D3DCOLOR cCalloutHighlight;
    D3DCOLOR cBorder;
    D3DCOLOR cControlFill;
    D3DCOLOR cHighlightFill;
    D3DCOLOR cAreaFill;
} DICOLORSET, *LPDICOLORSET;

typedef const DICOLORSET *LPCDICOLORSET;

Members

dwSize
Size of this structure, in bytes.
cTextFore
Foreground text color.
cTextHighlight
Foreground color for highlighted text.
cCalloutLine
Color used to display callout lines.
cCalloutHighlight
Color used to display callout lines.
cBorder
Border color, used to display lines around controls such as tabs and buttons.
cControlFill
Fill color for controls such as tabs and buttons.
cHighlightFill
Fill color for highlighted controls.
cAreaFill
Fill color for areas outside controls such as tabs and buttons.

Remarks

Text background color is always transparent.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR

© 2002 Microsoft Corporation. All rights reserved.


DICONDITION Structure

Contains type-specific information for effects that are marked as DIEFT_CONDITION.

A pointer to an array of DICONDITION structures for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

Syntax

typedef struct DICONDITION {
    LONG	 lOffset;
    LONG	 lPositiveCoefficient;
    LONG	 lNegativeCoefficient;
    DWORD	 dwPositiveSaturation;
    DWORD	 dwNegativeSaturation;
    LONG	 lDeadBand;
} DICONDITION, *LPDICONDITION;

typedef const DICONDITION *LPCDICONDITION;

Members

lOffset
Offset for the condition, in the range from –10,000 through 10,000.
lPositiveCoefficient
Coefficient constant on the positive side of the offset, in the range from –10,000 through 10,000.
lNegativeCoefficient
Coefficient constant on the negative side of the offset, in the range from –10,000 through 10,000. If the device does not support separate positive and negative coefficients, the value of lNegativeCoefficient is ignored, and the value of lPositiveCoefficient is used as both the positive and negative coefficients.
dwPositiveSaturation

Maximum force output on the positive side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

dwNegativeSaturation

Maximum force output on the negative side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

If the device does not support separate positive and negative saturation, the value of dwNegativeSaturation is ignored, and the value of dwPositiveSaturation is used as both the positive and negative saturation.

lDeadBand
Region around lOffset in which the condition is not active, in the range from 0 through 10,000. In other words, the condition is not active between lOffset minus lDeadBand and lOffset plus lDeadBand.

Remarks

Different types of conditions interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero deadband is provided. If the metric is less than lOffset - lDeadBand, the resulting force is given by the following formula:

force = lNegativeCoefficient * ( q - ( lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, the resulting force is given by the following formula:

force = lPositiveCoefficient * ( q - ( lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.

If the number of DICONDITION structures in the array is equal to the number of axes for the effect, the first structure applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis spring condition with lOffset set to 0 in both DICONDITION structures would have the same effect as the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must not be rotated.

If there is a single DICONDITION structure for an effect with more than one axis, the direction along which the parameters of the DICONDITION structure are in effect is determined by the direction parameters passed in the rglDirection field of the DIEFFECT structure. For example, a friction condition rotated 45 degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would have no effect on joystick motion in the northwest-southeast direction.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DICONFIGUREDEVICESPARAMS Structure

Contains information for the device configuration property sheet. It is used by the IDirectInput8::ConfigureDevices method.

Syntax

typedef struct _DICONFIGUREDEVICESPARAMS {
    DWORD dwSize;
    DWORD dwcUsers;
    LPTSTR lptszUserNames;
    DWORD dwcFormats;
    LPDIACTIONFORMAT lprgFormats;
    HWND hwnd;
    DICOLORSET dics;
    IUnknown *lpUnkDDSTarget;
} DICONFIGUREDEVICESPARAMS, *LPDICONFIGUREDEVICESPARAMS;

Members

dwSize
Size of this structure, in bytes.
dwcUsers
Count of user names in the buffer at lptszUserNames. If lptszUserNames is NULL (to indicate that default user names should be used), the value in this member is ignored. If the dwcUsers value exceeds the number of entries actually in the buffer, the method fails, returning DIERR_INVALIDPARAM.
lptszUserNames
Pointer to a buffer containing a series of null-terminated name strings, the final element being designated by a double-null terminator. The lptszUserNames parameter can be set to NULL to instruct the use of default names. If the application passes more names than the dwcUsers count indicates, only the names within the count are used. If an application specifies names that are different from the names currently assigned to devices, ownership is revoked for all devices, a default name is created for the mismatched name, and the interface shows (No User) for all devices.
dwcFormats
Count of structures in the array at lprgFormats.
lprgFormats
Pointer to an array of DIACTIONFORMAT structures that contains action-mapping information for each genre used by the game. On input, this array contains action-to-control mappings and strings to display as callouts for each mapping. The configuration interface displays the genres in its drop-down list in the same order as in the array.
hwnd
Handle to the top-level window of the calling application. The member is needed only for applications that run in windowed mode and is otherwise ignored.
dics
DICOLORSET structure that describes the color scheme to apply to the configuration user interface. Passing a zero-initialized DICOLORSET structure causes the default color scheme to be used.
lpUnkDDSTarget
Pointer to the IUnknown interface for a Microsoft® DirectDraw® or Microsoft Direct3D® target surface object that will be filled to contain an image of the configuration user interface. The image represents the current state of the user interface at the time that the DIEnumDevicesBySemanticsCallback function is invoked. The target surface will retain any alpha information passed as part of the DICOLORSET structure above, and also any alpha information encoded into the device image by the hardware manufacturer. The target surface object referred to by the IUnknown interface must support either IDirect3DSurface8, IDirectDrawSurface7 or IDirectDrawSurface4. The IDirect3DSurface9 interface is not supported. For more information, see IDirectInput8::ConfigureDevices. Full-screen applications using DirectDraw must have target surfaces created using the DDSCAPS_SYSTEMEMORY flag.

Applications that are not using DirectDraw and applications that are using DirectDraw but are windowed rather than using the full screen may pass NULL in this parameter. This will cause Microsoft DirectInput® to use the Microsoft Windows® Windows Graphics Device Interface (GDI) functions to draw the configuration user interface image. Passing NULL when using IDirect3DSurface9 surfaces will fail. For more information, see Remarks in IDirectInput8::ConfigureDevices.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DICONSTANTFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_CONSTANTFORCE.

The structure describes a constant force effect.

A pointer to a single DICONSTANTFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DICONSTANTFORCE {
    LONG lMagnitude;
} DICONSTANTFORCE, *LPDICONSTANTFORCE;

typedef const DICONSTANTFORCE *LPCDICONSTANTFORCE;

Members

lMagnitude
The magnitude of the effect, in the range from –10,000 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DICUSTOMFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_CUSTOMFORCE.

The structure describes a custom or user-defined force.

A pointer to a DICUSTOMFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DICUSTOMFORCE {
    DWORD  cChannels;
    DWORD  dwSamplePeriod;
    DWORD  cSamples;
    LPLONG rglForceData;
} DICUSTOMFORCE, *LPDICUSTOMFORCE;

typedef const DICUSTOMFORCE *LPCDICUSTOMFORCE;

Members

cChannels
Number of channels (axes) affected by this force.

The first channel is applied to the first axis associated with the effect, the second to the second, and so on. If there are fewer channels than axes, nothing is associated with the extra axes.

If there is only a single channel, the effect is rotated in the direction specified by the rglDirection member of the DIEFFECT structure. If there is more than one channel, rotation is not allowed.

Not all devices support rotation of custom effects.

dwSamplePeriod
Sample period, in microseconds.
cSamples
Total number of samples in the rglForceData. It must be an integral multiple of the cChannels.
rglForceData
Pointer to an array of force values representing the custom force. If multiple channels are provided, the values are interleaved. For example, if cChannels is 3, the first element of the array belongs to the first channel, the second to the second, and the third to the third.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIDATAFORMAT Structure

Describes a device's data format. This structure is used with the IDirectInputDevice8::SetDataFormat method.

Syntax

typedef struct DIDATAFORMAT {
    DWORD dwSize;
    DWORD dwObjSize;
    DWORD dwFlags;
    DWORD dwDataSize;
    DWORD dwNumObjs;
    LPDIOBJECTDATAFORMAT rgodf;
} DIDATAFORMAT, *LPDIDATAFORMAT;

typedef const DIDATAFORMAT *LPCDIDATAFORMAT;

Members

dwSize
Size of this structure, in bytes.
dwObjSize
Size of the DIOBJECTDATAFORMAT structure, in bytes.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property, using the IDirectInputDevice8::SetProperty method. This cannot be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the IDirectInputDevice8::SetProperty method. This cannot be combined with the DIDF_ABSAXIS flag.
dwDataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
dwNumObjs
Number of objects in the rgodf array.
rgodf
Address to an array of DIOBJECTDATAFORMAT structures. Each structure describes how one object's data should be reported in the device data. Typical errors include placing two pieces of information in the same location and placing one piece of information in more than one location.

Remarks

Applications do not typically need to create a DIDATAFORMAT structure. An application can use one of the predefined global data format variables, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2.

Applications that need to create a DIDATAFORMAT structure must first call IDirectInputDevice8::EnumObjects to determine the available objects for the current device. This is because the IDirectInputDevice8::SetDataFormat method will return DIERR_INVALIDPARAM if an an object is described in the DIDATAFORMAT structure but does not exist on the current device.

The following code example sets a data format for a device that has an X-axis and a Y-axis:

// Suppose an application uses the following
// structure to read device data.

typedef struct MYDATA {
    LONG  lX;                   // X-axis goes here.
    LONG  lY;                   // Y-axis goes here.
    BYTE  bButtonA;             // One button goes here.
    BYTE  bButtonB;             // Another button goes here.
    BYTE  bPadding[2];          // Must be DWORD multiple in size.
} MYDATA;

// Then, it can use the following data format.

DIOBJECTDATAFORMAT rgodf[ ] = {
  { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonA),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonB),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
};
#define numObjects (sizeof(rgodf) / sizeof(rgodf[0]))

DIDATAFORMAT df = {
    sizeof(DIDATAFORMAT),       // Size of this structure
    sizeof(DIOBJECTDATAFORMAT), // Size of object data format
    DIDF_ABSAXIS,               // Absolute axis coordinates
    sizeof(MYDATA),             // Size of device data
    numObjects,                 // Number of objects
    rgodf,                      // And here they are
};

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIACTIONFORMAT

© 2002 Microsoft Corporation. All rights reserved.


DIDEVCAPS Structure

Describes a Microsoft® DirectInput® device's capabilities. This structure is used with the IDirectInputDevice8::GetCapabilities method.

Syntax

typedef struct DIDEVCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDevType;
    DWORD dwAxes;
    DWORD dwButtons;
    DWORD dwPOVs;
    DWORD dwFFSamplePeriod;
    DWORD dwFFMinTimeResolution;
    DWORD dwFirmwareRevision;
    DWORD dwHardwareRevision;
    DWORD dwFFDriverVersion;
} DIDEVCAPS, *LPDIDEVCAPS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized by the application before a call to the IDirectInputDevice8::GetCapabilities method.
dwFlags
Flags associated with the device. This value can be a combination of the following:
DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_ATTACHED
The device is physically attached.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface, such as a Human Interface Device (HID), or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade, the fade level and fade time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFFADE flag if fade is supported for that effect.

DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack, the attack level and attack time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFATTACK flag if attack is supported for that effect.

DIDC_HIDDEN
Fictitious device created by a device driver so that it can generate keyboard and mouse events. Such devices are not normally enumerated by IDirectInput8::EnumDevices or configured by IDirectInput8::ConfigureDevices.
DIDC_PHANTOM
Placeholder. Phantom devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data. HID devices can contain a mixture of polled and nonpolled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGCOEFFICIENTS flag if separate positive and negative coefficients are supported for that condition.

DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGSATURATION flag if separate positive and negative saturation are supported for that condition.

DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_SATURATION flag if saturation is supported for that condition.

DIDC_STARTDELAY
The force-feedback system supports the start delay parameter for at least one effect. If the device does not support start delays, the dwStartDelay member of the DIEFFECT structure is ignored.
dwDevType
Device type specifier. This member can contain values identical to those in the dwDevType member of the DIDEVICEINSTANCE structure.
dwAxes
Number of axes available on the device.
dwButtons
Number of buttons available on the device.
dwPOVs
Number of point-of-view controllers available on the device.
dwFFSamplePeriod
Minimum time between playback of consecutive raw force commands, in microseconds.
dwFFMinTimeResolution
Minimum time, in microseconds, that the device can resolve. The device rounds any times to the nearest supported increment. For example, if the value of dwFFMinTimeResolution is 1000, the device would round any times to the nearest millisecond.
dwFirmwareRevision
Firmware revision of the device.
dwHardwareRevision
Hardware revision of the device.
dwFFDriverVersion
Version number of the device driver.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions have larger numbers.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDEVICEINSTANCE

© 2002 Microsoft Corporation. All rights reserved.


DIDEVICEIMAGEINFO Structure

Carries information required to display a device image or an overlay image with a callout. This structure is passed to the IDirectInputDevice8::GetImageInfo method as an array within a DIDEVICEIMAGEINFOHEADER structure.

Syntax

typedef struct _DIDEVICEIMAGEINFO {
    TCHAR tszImagePath[MAX_PATH];
    DWORD dwFlags;
    DWORD dwViewID;
    RECT rcOverlay;
    DWORD dwObjID;
    DWORD dwcValidPts;
    POINT rgptCalloutLine[5];
    RECT rcCalloutRect;
    DWORD dwTextAlign;
} DIDEVICEIMAGEINFO, *LPDIDEVICEIMAGEINFO;

Members

tszImagePath
Fully qualified path to the file that contains an image of the device. The file format is given in dwFlags. If no image is available for the device, this member will be set to NULL. If so, the application is responsible for enumerating controls on the device and displaying a default listing of actions to device controls (similar to the method used by most applications before Microsoft® DirectX® 8.0).
dwFlags
Flag that describes the intended use of the image.
DIDIFT_CONFIGURATION
The file is used to display the current configuration of actions on the device. Overlay image coordinates are relative to the upper-left corner of the configuration image.
DIDIFT_OVERLAY
The file (if provided) is an overlay for a configuration image. The dwViewID, rcOverlay, dwObjID, rgptCalloutLine, rcCalloutRect, and dwTextAlign members are valid and contain data used to display the overlay and callout information for a single control on the device. If no file is provided (null path string), all other pertinent members are relevant except rcOverlay.
dwViewID
For device view images (DIDIFT_CONFIGURATION), this is the identifier (ID) of the device view. For device control overlays (DIDIFT_OVERLAY), this value refers to the device view (by ID) over which an image and callout information should be displayed.
rcOverlay
Rectangle, using coordinates relative to the top-left pixel of the device configuration image, in which the overlay image should be painted. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwObjID
Control identifier, as a combination of DIDFT_* flags and an instance value, to which an overlay image corresponds for this device. Applications use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to decode this value to its constituent parts. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwcValidPts
Number of points in the array at rgptCalloutLine.
rgptCalloutLine
Array of POINT structures that specify coordinates of the points describing a callout line. A callout line connects a device control to a caption for the game action. Each line can have from one to four segments. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
rcCalloutRect
RECT structure that describes the rectangle in which the game action string is displayed. If the string cannot fit within the rectangle, the application is responsible for handling clipping. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwTextAlign
DWORD value that specifies the alignment of the text in the rectangle described by the rcCalloutRect member. Must be one horizontal alignment flag combined with one vertical alignment flag. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
The following horizontal alignment flags are defined.
DIDAL_LEFTALIGNED
Text is aligned on the left border.
DIDAL_CENTERED
Text is horizontally centered.
DIDAL_RIGHTALIGNED
Text is aligned on the right border.
The following vertical alignment flags are defined.
DIDAL_MIDDLE
The text is vertically centered.
DIDAL_TOPALIGNED
The text is aligned on the top border.
DIDAL_BOTTOMALIGNED
The text is aligned on the bottom border.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIDEVICEIMAGEINFOHEADER Structure

Contains information about device images. Used in the IDirectInputDevice8::GetImageInfo method.

Syntax

typedef struct _DIDEVICEIMAGEINFOHEADER {
    DWORD dwSize;
    DWORD dwSizeImageInfo;
    DWORD dwcViews;
    DWORD dwcButtons;
    DWORD dwcAxes;
    DWORD dwcPOVs;
    DWORD dwBufferSize;
    DWORD dwBufferUsed;
    DIDEVICEIMAGEINFO *lprgImageInfoArray;
} DIDEVICEIMAGEINFOHEADER, *LPDIDEVICEIMAGEINFOHEADER;

Members

dwSize
DWORD value that specifies the size of this structure, in bytes. Must be initialized before the structure can be used.
dwSizeImageInfo
DWORD value that specifies the size of the DIDEVICEIMAGEINFO structure, in bytes. Must be initialized before this structure can be used.
dwcViews
DWORD variable that receives the number of views of this device.
dwcButtons
DWORD variable that receives the number of buttons on the device.
dwcAxes
DWORD variable that receives the number of axes on the device.
dwcPOVs
DWORD variable that receives the number of point-of-view controllers on the device.
dwBufferSize
DWORD value that specifies the size, in bytes, of the buffer at lprgImageInfoArray. When set to zero, the IDirectInputDevice8::GetImageInfo method ignores all other members and returns the minimum buffer size required to hold information for all images.
dwBufferUsed
DWORD value that receives the size, in bytes, of the memory used in the buffer at lprgImageInfoArray. When dwBufferSize is set to zero, the IDirectInputDevice8::GetImageInfo method sets this member to the minimum size needed to hold information for all images.
lprgImageInfoArray
Pointer to a buffer that receives an array of DIDEVICEIMAGEINFO structures describing all the device images and views, overlay images, and callout-string coordinates.

Remarks

The buffer at lprgImageInfoArray must be large enough to hold all required image information structures. Applications can query for the required size by calling the IDirectInputDevice8::GetImageInfo method with the dwBufferSize member set to zero. After the call, dwBufferUsed contains the amount of memory, in bytes, that was modified.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIDEVICEINSTANCE Structure

Describes an instance of a Microsoft® DirectInput® device. This structure is used with the IDirectInput8::EnumDevices, IDirectInput8::EnumDevicesBySemantics, and IDirectInputDevice8::GetDeviceInfo methods.

Syntax

typedef struct DIDEVICEINSTANCE {
    DWORD dwSize;
    GUID  guidInstance;
    GUID  guidProduct;
    DWORD dwDevType;
    TCHAR tszInstanceName[MAX_PATH];
    TCHAR tszProductName[MAX_PATH];
    GUID  guidFFDriver;
    WORD  wUsagePage;
    WORD  wUsage;
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

typedef const DIDEVICEINSTANCE  *LPCDIDEVICEINSTANCE;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
guidInstance
Unique identifier for the instance of the device. An application can save the instance globally unique identifier (GUID) into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.
guidProduct
Unique identifier for the product. This identifier is established by the manufacturer of the device.
dwDevType
Device type specifier. The least-significant byte of the device type description code specifies the device type. The next-significant byte specifies the device subtype. This value can also be combined with DIDEVTYPE_HID, which specifies a Human Interface Device (HID).
tszInstanceName
Friendly name for the instance. For example, "Joystick 1."
tszProductName
Friendly name for the product.
guidFFDriver
Unique identifier for the driver being used for force feedback. The driver's manufacturer establishes this identifier.
wUsagePage
If the device is a Human Interface Device (HID), this member contains the HID usage page code.
wUsage
If the device is a Human Interface Device (HID), this member contains the HID usage code.

Remarks

The following device types and subtypes are defined for use in the dwDevType member.

  • DI8DEVTYPE_1STPERSON

    First-person action game device. The following subtypes are defined.

    • DI8DEVTYPE1STPERSON_LIMITED

      Device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPE1STPERSON_SHOOTER

      Device designed for first-person shooter games.

    • DI8DEVTYPE1STPERSON_SIXDOF

      Device with six degrees of freedom; that is, three lateral axes and three rotational axes.

    • DI8DEVTYPE1STPERSON_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DEVICE

    Device that does not fall into another category.

  • DI8DEVTYPE_DEVICECTRL

    Input device used to control another type of device from within the context of the application. The following subtypes are defined.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION

      Control used to make communications selections.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION_HARDWIRED

      Device that must use its default configuration and cannot be remapped.

    • DI8DEVTYPEDEVICECTRL_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DRIVING

    Device for steering. The following subtypes are defined.

    • DI8DEVTYPEDRIVING_COMBINEDPEDALS

      Steering device that reports acceleration and brake pedal values from a single axis.

    • DI8DEVTYPEDRIVING_DUALPEDALS

      Steering device that reports acceleration and brake pedal values from separate axes.

    • DI8DEVTYPEDRIVING_HANDHELD

      Hand-held steering device.

    • DI8DEVTYPEDRIVING_LIMITED

      Steering device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEDRIVING_THREEPEDALS

      Steering device that reports acceleration, brake, and clutch pedal values from separate axes.

  • DI8DEVTYPE_FLIGHT

    Controller for flight simulation. The following subtypes are defined.

    • DI8DEVTYPEFLIGHT_LIMITED

      Flight controller that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEFLIGHT_RC

      Flight device based on a remote control for model aircraft.

    • DI8DEVTYPEFLIGHT_STICK

      Joystick.

    • DI8DEVTYPEFLIGHT_YOKE

      Yoke.

  • DI8DEVTYPE_GAMEPAD

    Gamepad. The following subtypes are defined.

    • DI8DEVTYPEGAMEPAD_LIMITED

      Gamepad that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_STANDARD

      Standard gamepad that provides the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_TILT

      Gamepad that can report x-axis and y-axis data based on the attitude of the controller.

  • DI8DEVTYPE_JOYSTICK

    Joystick. The following subtypes are defined.

    • DI8DEVTYPEJOYSTICK_LIMITED

      Joystick that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEJOYSTICK_STANDARD

      Standard joystick that provides the minimum number of device objects for action mapping.

  • DI8DEVTYPE_KEYBOARD

    Keyboard or keyboard-like device. The following subtypes are defined.

    • DI8DEVTYPEKEYBOARD_UNKNOWN

      Subtype could not be determined.

    • DI8DEVTYPEKEYBOARD_PCXT

      IBM PC/XT 83-key keyboard.

    • DI8DEVTYPEKEYBOARD_OLIVETTI

      Olivetti 102-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCAT

      IBM PC/AT 84-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCENH

      IBM PC Enhanced 101/102-key or Microsoft Natural® keyboard keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA1050

      Nokia 1050 keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA9140

      Nokia 9140 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98

      Japanese NEC PC98 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98LAPTOP

      Japanese NEC PC98 laptop keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98106

      Japanese NEC PC98 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPAN106

      Japanese 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPANAX

      Japanese AX keyboard.

    • DI8DEVTYPEKEYBOARD_J3100

      Japanese J3100 keyboard.

  • DI8DEVTYPE_MOUSE

    A mouse or mouse-like device (such as a trackball). The following subtypes are defined.

    • DI8DEVTYPEMOUSE_ABSOLUTE

      Mouse that returns absolute axis data.

    • DI8DEVTYPEMOUSE_FINGERSTICK

      Fingerstick.

    • DI8DEVTYPEMOUSE_TOUCHPAD

      Touchpad.

    • DI8DEVTYPEMOUSE_TRACKBALL

      Trackball.

    • DI8DEVTYPEMOUSE_TRADITIONAL

      Traditional mouse.

    • DI8DEVTYPEMOUSE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_REMOTE

    Remote-control device. The following subtype is defined.

    • DI8DEVTYPEREMOTE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_SCREENPOINTER

    Screen pointer. The following subtypes are defined.

    • DI8DEVTYPESCREENPTR_UNKNOWN

      Unknown subtype.

    • DI8DEVTYPESCREENPTR_LIGHTGUN

      Light gun.

    • DI8DEVTYPESCREENPTR_LIGHTPEN

      Light pen.

    • DI8DEVTYPESCREENPTR_TOUCH

      Touch screen.

  • DI8DEVTYPE_SUPPLEMENTAL

    Specialized device with functionality unsuitable for the main control of an application, such as pedals used with a wheel. The following subtypes are defined.

    • DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER

      Secondary handheld controller.

    • DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS

      Device whose primary function is to report acceleration and brake pedal values from a single axis.

    • DI8DEVTYPESUPPLEMENTAL_DUALPEDALS

      Device whose primary function is to report acceleration and brake pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_HANDTRACKER

      Device that tracks hand movement.

    • DI8DEVTYPESUPPLEMENTAL_HEADTRACKER

      Device that tracks head movement.

    • DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS

      Device with rudder pedals.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTER

      Device that reports gear selection from an axis.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE

      Device that reports gear selection from button states.

    • DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE

      Device whose primary function is to report at least two throttle values. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_THREEPEDALS

      Device whose primary function is to report acceleration, brake, and clutch pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_THROTTLE

      Device whose primary function is to report a single throttle value. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_UNKNOWN

      Unknown subtype.

Versions of DirectInput earlier than Microsoft DirectX® 8.0 have a somewhat different scheme of device types and subtypes. See the DIDEVTYPExxx defines in Dinput.h.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIDEVICEOBJECTDATA Structure

Contains buffered device information. This structure is used with the IDirectInputDevice8::GetDeviceData and the IDirectInputDevice8::SendDeviceData methods.

Syntax

typedef struct DIDEVICEOBJECTDATA {
    DWORD    dwOfs;
    DWORD    dwData;
    DWORD    dwTimeStamp;
    DWORD    dwSequence;
    UINT_PTR uAppData;
} DIDEVICEOBJECTDATA, *LPDIDEVICEOBJECTDATA;

typedef const DIDEVICEOBJECTDATA *LPCDIDEVICEOBJECTDATA;

Members

dwOfs
For IDirectInputDevice8::GetDeviceData, the offset into the current data format of the object whose data is being reported; that is, the location in which the dwData would have been stored if the data had been obtained by a call to the IDirectInputDevice8::GetDeviceState method. If the device is accessed as a mouse, keyboard, or joystick, the dwOfs member is one of the mouse device constants, keyboard device constants, or joystick device constants. If a custom data format has been set, it is an offset relative to the custom data format.

This member can be ignored if Action Mapping is being used. Instead, retrieve the action value from uAppData.

For IDirectInputDevice8::SendDeviceData, the instance identifier (ID) of the object to which the data is being sent, as obtained from the dwType member of a DIDEVICEOBJECTINSTANCE structure.

dwData
Data obtained from or sent to the device.

For axis input, if the device is in relative axis mode, the relative axis motion is reported. If the device is in absolute axis mode, the absolute axis coordinate is reported.

For button input, only the low byte of dwData is significant. The high bit of the low byte is set if the button was pressed; it is clear if the button was released.

dwTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days. See Remarks.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

dwSequence
Microsoft® DirectInput® sequence number for this event. All input events are assigned an increasing sequence number. This enables events from different devices to be sorted chronologically. Because this value can wrap around, care must be taken when comparing two sequence numbers. The DISEQUENCE_COMPARE macro can be used to perform this comparison safely.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

uAppData
Application-defined action value assigned to this object in the last call to IDirectInputDevice8::SetActionMap. This is the value in the uAppData member of the DIACTION structure associated with the object. Ignore this value if you are not using action mapping.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be zero.

Remarks

The system time returned in dwTimeStamp comes from the same clock used by the Microsoft Win32® GetTickCount or timeGetTime functions, but it produces potentially more precise values. For example, on Microsoft Windows® 95, the GetTickCount timer is updated only every 55 milliseconds, but the dwTimeStamp value is accurate to within 1 millisecond. Therefore, if you call GetTickCount and it returns n, and you then receive an event with a timestamp of n + n1, you cannot assume that the event took place exactly n1 milliseconds after the call to GetTickCount.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIDEVICEOBJECTINSTANCE Structure

Describes a device object instance. This structure is used with the IDirectInputDevice8::EnumObjects method to provide the DIEnumDeviceObjectsCallback callback function with information about a particular object associated with a device, such as an axis or button. It is also used with the IDirectInputDevice8::GetObjectInfo method to retrieve information about a device object.

Syntax

typedef struct DIDEVICEOBJECTINSTANCE {
    DWORD dwSize;
    GUID  guidType;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
    TCHAR tszName[MAX_PATH];
    DWORD dwFFMaxForce;
    DWORD dwFFForceResolution;
    WORD  wCollectionNumber;
    WORD  wDesignatorIndex;
    WORD  wUsagePage;
    WORD  wUsage;
    DWORD dwDimension;
    WORD  wExponent;
    WORD  wReportId;
} DIDEVICEOBJECTINSTANCE, *LPDIDEVICEOBJECTINSTANCE;

typedef const DIDEVICEOBJECTINSTANCE *LPCDIDEVICEOBJECTINSTANCE;

Members

dwSize
Size of the structure, in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. When the structure is passed to the IDirectInputDevice8::GetObjectInfo method, this member must be initialized to sizeof(DIDEVICEOBJECTINSTANCE).
guidType
Unique identifier that indicates the object type. This member is optional. If present, it can be one of the following values:
GUID_XAxis
The horizontal axis. For example, it can represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it can represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it can represent the rotation of a mouse wheel or the movement of a joystick throttle control.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A mouse button.
GUID_Key
A keyboard key.
GUID_POV
A point-of-view indicator.
GUID_Unknown
Unknown.
dwOfs
Offset in the native data format of the device. The native data format corresponds to the raw device data. The dwOfs member does not correspond to the device constant, such as DIJOFS_BUTTON0, for this object.
dwType
Device type that describes the object. It is a combination of DIDFT_* flags that describe the object type (axis, button, and so on) and contains the object instance number in the middle 16 bits. Use the DIDFT_GETINSTANCE macro to extract the object instance number. For the DIDFT_* flags, see IDirectInputDevice8::EnumObjects.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_GUIDISUSAGE
The pguid member of the DIOBJECTDATAFORMAT structure contains the desired usage page and usage in a packed DWORD. See DIMAKEUSAGEDWORD.
DIDOI_POLLED
The object does not return data until the IDirectInputDevice8::Poll method is called.
tszName
Name of the object; for example, "X-Axis" or "Right Shift."
dwFFMaxForce
The magnitude of the maximum force that can be created by the actuator associated with this object. Force is expressed in newtons and measured in relation to where the hand would be during normal operation of the device.
dwFFForceResolution
The force resolution of the actuator associated with this object. The returned value represents the number of gradations, or subdivisions, of the maximum force that can be expressed by the force-feedback system from 0 (no force) to maximum force.
wCollectionNumber
The Human Interface Device (HID) link collection to which the object belongs.
wDesignatorIndex
An index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library (Hidpi.h) to obtain additional information about the device object.
wUsagePage
The Human Interface Device (HID) usage page associated with the object, if known. HIDs always report a usage page. Non-HID devices can optionally report a usage page; if they do not, the value of this member is 0.
wUsage
The HID usage associated with the object, if known. HIDs always report a usage. Non-HIDs can optionally report a usage; if they do not, the value of this member is 0.
dwDimension
A Human Interface Device (HID) code for the dimensional units in which the object's value is reported, if known, or 0 if not known.
wExponent
The exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent might be needed to convert them to nonintegral types.
wReportId
Reserved.

Remarks

Warning The value in dwOfs is the offset within the raw data returned by the device, regardless of whether the data format has been set for the device.

Applications can use the wUsagePage and wUsage members to obtain additional information about how the object was designed to be used. For example, if wUsagePage has the value 0x02 (vehicle controls) and wUsage has the value 0xB9 (elevator trim), the object was designed to be the elevator trim control on a flight stick. A flight simulator application can use this information to provide more reasonable defaults for objects on the device. HID usage codes are determined by the USB standards committee.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEFFECT Structure

Used by the IDirectInputDevice8::CreateEffect method to initialize a new IDirectInputEffect object. It is also used by the IDirectInputEffect::SetParameters and IDirectInputEffect::GetParameters methods.

Syntax

typedef struct DIEFFECT {
    DWORD   dwSize;
    DWORD   dwFlags;
    DWORD   dwDuration;
    DWORD   dwSamplePeriod;
    DWORD   dwGain;
    DWORD   dwTriggerButton;
    DWORD   dwTriggerRepeatInterval;
    DWORD   cAxes;
    LPDWORD rgdwAxes;
    LPLONG  rglDirection;
    LPDIENVELOPE lpEnvelope;
    DWORD   cbTypeSpecificParams;
    LPVOID  lpvTypeSpecificParams;
    DWORD   dwStartDelay;
} DIEFFECT, *LPDIEFFECT;

typedef const DIEFFECT *LPCDIEFFECT;

Members

dwSize
Specifies the size, in bytes, of the structure. This member must be initialized before the structure is used.
dwFlags
Flags associated with the effect. This value can be a combination of one or more of the following values:
DIEFF_CARTESIAN
The values of rglDirection are to be interpreted as Cartesian coordinates.
DIEFF_OBJECTIDS
The values of dwTriggerButton and rgdwAxes are object identifiers as obtained by IDirectInputDevice8::EnumObjects.
DIEFF_OBJECTOFFSETS
The values of dwTriggerButton and rgdwAxes are data format offsets.
DIEFF_POLAR
The values of rglDirection are to be interpreted as polar coordinates.
DIEFF_SPHERICAL
The values of rglDirection are to be interpreted as spherical coordinates.
dwDuration
The total duration of the effect, in microseconds. If this value is INFINITE, the effect has infinite duration. If an envelope has been applied to the effect, the attack is applied, followed by an infinite sustain.
dwSamplePeriod
The period at which the device should play back the effect, in microseconds. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of playing back the effect at the specified rate, it chooses the supported rate that is closest to the requested value.

Setting a custom dwSamplePeriod can be used for special effects. For example, playing a sine wave at an artificially large sample period results in a rougher texture.

dwGain
The gain to be applied to the effect, in the range from 0 through 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
dwTriggerButton
The identifier or offset of the button to be used to trigger playback of the effect. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the value. If this member is set to DIEB_NOTRIGGER, no trigger button is associated with the effect.
dwTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to INFINITE suppresses repetition.

Support for trigger repeat for an effect is indicated by the presence of the DIEP_TRIGGERREPEATINTERVAL flag in the dwStaticParams member of the DIEFFECTINFO structure.

cAxes
Number of axes involved in the effect. This member must be filled in by the caller if changing or setting the axis list or the direction list.

The number of axes for an effect cannot be changed once it has been set.

rgdwAxes
Pointer to a DWORD array (of cAxes elements) containing identifiers or offsets identifying the axes to which the effect is to be applied. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the values in the array.

The list of axes associated with an effect cannot be changed once it has been set.

No more than 32 axes can be associated with a single effect.

rglDirection
Pointer to a LONG array (of cAxes elements) containing either Cartesian coordinates, polar coordinates, or spherical coordinates. The flags DIEFF_CARTESIAN, DIEFF_POLAR, and DIEFF_SPHERICAL determine the semantics of the values in the array.

If Cartesian, each value in rglDirection is associated with the corresponding axis in rgdwAxes.

If polar, the angle is measured in hundredths of degrees from the (0, –1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.

If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.

lpEnvelope
Optional pointer to a DIENVELOPE structure that describes the envelope to be used by this effect. Not all effect types use envelope. If no envelope is to be applied, the member should be set to NULL.
cbTypeSpecificParams
Number of bytes of additional type-specific parameters for the corresponding effect type.
lpvTypeSpecificParams
Pointer to type-specific parameters, or NULL if there are no type-specific parameters.

If the effect is of type DIEFT_CONDITION, this member contains a pointer to an array of DICONDITION structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the rglDirection array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the rglDirection array:

  • DIEFF_SPHERICAL: 0, 0, ...
  • DIEFF_POLAR: 9000, 0, ...
  • DIEFF_CARTESIAN: 1, 0, ...

If the effect is of type DIEFT_CUSTOMFORCE, this member contains a pointer to a DICUSTOMFORCE structure that defines the parameters for the custom force.

If the effect is of type DIEFT_PERIODIC, this member contains a pointer to a DIPERIODIC structure that defines the parameters for the effect.

If the effect is of type DIEFT_CONSTANTFORCE, this member contains a pointer to a DICONSTANTFORCE structure that defines the parameters for the constant force.

If the effect is of type DIEFT_RAMPFORCE, this member contains a pointer to a DIRAMPFORCE structure that defines the parameters for the ramp force.

dwStartDelay
Time (in microseconds) that the device should wait after an IDirectInputEffect::Start call before playing the effect. If this value is 0, effect playback begins immediately. This member is not present in versions prior to Microsoft® DirectX® 7.0.

Remarks

Note The rglDirection array must contain cAxes entries, even if polar or spherical coordinates are given. In these cases, the last element in the rglDirection array is reserved and must be 0.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEFFECTINFO Structure

Used by the IDirectInputDevice8::EnumEffects and IDirectInputDevice8::GetEffectInfo methods to return information about a particular effect supported by a device.

Syntax

typedef struct DIEFFECTINFO {
    DWORD dwSize;
    GUID  guid;
    DWORD dwEffType;
    DWORD dwStaticParams;
    DWORD dwDynamicParams;
    TCHAR tszName[MAX_PATH];
} DIEFFECTINFO, *LPDIEFFECTINFO;

typedef const DIEFFECTINFO  *LPCDIEFFECTINFO;

Members

dwSize
Size of the structure in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. This member must be initialized before the structure is passed to the IDirectInputDevice8::GetEffectInfo method.
guid
Identifier of the effect.
dwEffType
Zero or more of the following values:
DIEFT_ALL
Valid only for IDirectInputDevice8::EnumEffects. Enumerate all effects, regardless of type. This flag cannot be combined with any of the other flags.
DIEFT_CONDITION
The effect represents a condition. When creating or modifying a condition, the lpvTypeSpecificParams member of the DIEFFECT structure must point to an array of DICONDITION structures (one per axis), and the cbTypeSpecificParams member must be set to cAxis * sizeof(DICONDITION).

Not all devices support all the parameters of conditions. Check the effect capability flags to determine which capabilities are available.

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to conditions.

DIEFT_CONSTANTFORCE
The effect represents a constant-force effect. When creating or modifying a constant-force effect, the lpvTypeSpecificParams member of the DIEFFECT must point to a DICONSTANTFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICONSTANTFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to constant-force effects.

DIEFT_CUSTOMFORCE
The effect represents a custom-force effect. When creating or modifying a custom-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DICUSTOMFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICUSTOMFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to custom-force effects.

DIEFT_DEADBAND
The effect generator for this condition effect supports the lDeadBand parameter.
DIEFT_FFATTACK
The effect generator for this effect supports the attack envelope parameter. If the effect generator does not support attack, the attack level and attack time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_FFFADE
The effect generator for this effect supports the fade parameter. If the effect generator does not support fade, the fade level and fade time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_HARDWARE
The effect represents a hardware-specific effect. For additional information about using a hardware-specific effect, consult the hardware documentation.

The flag can be passed to the IDirectInputDevice8::EnumEffects method to restrict the enumeration to hardware-specific effects.

DIEFT_PERIODIC
The effect represents a periodic effect. When creating or modifying a periodic effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIPERIODICstructure, and the cbTypeSpecificParams member must be set to sizeof(DIPERIODIC).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to periodic effects.

DIEFT_POSNEGCOEFFICIENTS
The effect generator for this effect supports two coefficient values for conditions, one for the positive displacement of the axis and one for the negative displacement of the axis. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored, and the positive coefficient is used in both directions.
DIEFT_POSNEGSATURATION
The effect generator for this effect supports a maximum saturation for both positive and negative force output. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored, and the positive saturation is used in both directions.
DIEFT_RAMPFORCE
The effect represents a ramp-force effect. When creating or modifying a ramp-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIRAMPFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DIRAMPFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to ramp-force effects.

DIEFT_SATURATION
The effect generator for this effect supports the saturation of condition effects. If the effect generator does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.
DIEFT_STARTDELAY
The effect has a delay before it plays rather than beginning immediately. This can be used to offset effects so that they play in sequence.
dwStaticParams
Zero or more DIEP_* values describing the parameters supported by the effect. For example, if DIEP_ENVELOPE is set, the effect supports an envelope. For a list of possible values, see IDirectInputEffect::GetParameters.

It is not an error for an application to attempt to use effect parameters that are not supported by the device. The unsupported parameters are ignored.

This information is provided to enable the application to tailor its use of force feedback to the capabilities of the specific device.

dwDynamicParams
Zero or more DIEP_* values denoting parameters of the effect that can be modified while the effect is playing. For a list of possible values, see IDirectInputEffect::GetParameters.

If an application attempts to change a parameter while the effect is playing and the driver does not support modifying that effect dynamically, the driver is permitted to stop the effect, update the parameters, then restart it. For more information, see IDirectInputEffect::SetParameters.

tszName
Name of the effect; for example, "Sawtooth up" or "Constant force".

Remarks

Use the DIEFT_GETTYPE macro to extract the effect type from the dwEffType flags.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIEFFESCAPE Structure

Used by the IDirectInputDevice8::Escape and IDirectInputEffect::Escape methods to pass hardware-specific data directly to the device driver.

Syntax

typedef struct DIEFFESCAPE {
    DWORD dwSize;
    DWORD dwCommand;
    LPVOID lpvInBuffer;
    DWORD cbInBuffer;
    LPVOID lpvOutBuffer;
    DWORD cbOutBuffer;
} DIEFFESCAPE, *LPDIEFFESCAPE;

Members

dwSize
Size of the structure in bytes. This member must be initialized before the structure is used.
dwCommand
Driver-specific command number. Consult the driver documentation for a list of valid commands.
lpvInBuffer
Buffer containing the data required to perform the operation.
cbInBuffer
Size, in bytes, of the lpvInBuffer buffer.
lpvOutBuffer
Buffer in which the operation's output data is returned.
cbOutBuffer
On entry, the size in bytes of the lpvOutBuffer buffer. On exit, the number of bytes actually produced by the command.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is talking to the correct driver by comparing the guidFFDriver member in the DIDEVICEINSTANCE structure against the value the application is expecting.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIENVELOPE Structure

Used by the DIEFFECT structure to specify the optional envelope parameters for an effect. The sustain level for the envelope is represented by the dwMagnitude member of the DIPERIODIC structure and the lMagnitude member of the DICONSTANTFORCE structure. The sustain time is represented by dwDuration member of the DIEFFECT structure.

Syntax

typedef struct DIENVELOPE {
    DWORD dwSize;
    DWORD dwAttackLevel;
    DWORD dwAttackTime;
    DWORD dwFadeLevel;
    DWORD dwFadeTime;
} DIENVELOPE, *LPDIENVELOPE;

typedef const DIENVELOPE *LPCDIENVELOPE;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
dwAttackLevel
Amplitude for the start of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwAttackTime
The time, in microseconds, to reach the sustain level.
dwFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwFadeTime
The time, in microseconds, to reach the fade level.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIFILEEFFECT Structure

Describes data for a force-feedback effect stored in a file. It is used in conjunction with the IDirectInputDevice8::EnumEffectsInFile and IDirectInputDevice8::WriteEffectToFile methods.

Syntax

typedef struct DIFILEEFFECT {
    DWORD dwSize;
    GUID GuidEffect;
    LPCDIEFFECT lpDiEffect;
    CHAR szFriendlyName[MAX_PATH];
} DIFILEEFFECT, *LPDIFILEEFFECT;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
GuidEffect
Unique identifier of the effect type. This can be one of the standard globally unique identifiers (GUIDs) defined in Dinput.h, such as GUID_ConstantForce, or one created by the designer.
lpDiEffect
Pointer to a DIEFFECT structure containing information about the effect.
szFriendlyName
Name of the effect.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIJOYSTATE Structure

Describes the state of a joystick device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIJOYSTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[32];
} DIJOYSTATE, *LPDIJOYSTATE;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axes, formerly called the u-axis and v-axis, whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.

Remarks

You must prepare the device for joystick-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft® DirectX® 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIJOYSTATE2

© 2002 Microsoft Corporation. All rights reserved.


DIJOYSTATE2 Structure

Describes the state of a joystick device with extended capabilities. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[128];
    LONG lVX;
    LONG lVY;
    LONG lVZ;
    LONG lVRx;
    LONG lVRy;
    LONG lVRz;
    LONG rglVSlider[2];
    LONG lAX;
    LONG lAY;
    LONG lAZ;
    LONG lARx;
    LONG lARy;
    LONG lARz;
    LONG rglASlider[2];
    LONG lFX;
    LONG lFY;
    LONG lFZ;
    LONG lFRx;
    LONG lFRy;
    LONG lFRz;
    LONG rglFSlider[2];
} DIJOYSTATE2, *LPDIJOYSTATE2;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as–1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.
lVX
X-axis velocity.
lVY
Y-axis velocity.
lVZ
Z-axis velocity.
lVRx
X-axis angular velocity.
lVRy
Y-axis angular velocity.
lVRz
Z-axis angular velocity.
rglVSlider
Extra axis velocities.
lAX
X-axis acceleration.
lAY
Y-axis acceleration.
lAZ
Z-axis acceleration.
lARx
X-axis angular acceleration.
lARy
Y-axis angular acceleration.
lARz
Z-axis angular acceleration.
rglASlider
Extra axis accelerations.
lFX
X-axis force.
lFY
Y-axis force.
lFZ
Z-axis force.
lFRx
X-axis torque.
lFRy
Y-axis torque.
lFRz
Z-axis torque.
rglFSlider
Extra axis forces.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick2 global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft® DirectX® 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIJOYSTATE

© 2002 Microsoft Corporation. All rights reserved.


DIMOUSESTATE Structure

Describes the state of a mouse device that has up to four buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[4];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIMOUSESTATE2

© 2002 Microsoft Corporation. All rights reserved.


DIMOUSESTATE2 Structure

Describes the state of a mouse device that has up to eight buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIMOUSESTATE2 {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[8];
} DIMOUSESTATE2, *LPDIMOUSESTATE2;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse2 global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIMOUSESTATE

© 2002 Microsoft Corporation. All rights reserved.


DIOBJECTDATAFORMAT Structure

Describes a device object's data format for use with the IDirectInputDevice8::SetDataFormat method.

Syntax

typedef struct DIOBJECTDATAFORMAT {
    const GUID * pguid;
    DWORD        dwOfs;
    DWORD        dwType;
    DWORD        dwFlags;
} DIOBJECTDATAFORMAT, *LPDIOBJECTDATAFORMAT;

typedef const DIOBJECTDATAFORMAT *LPCDIOBJECTDATAFORMAT;

Members

pguid
Unique identifier for the axis, button, or other input source. When requesting a data format, making this member NULL indicates that any type of object is permissible.
dwOfs
Offset within the data packet where the data for the input source is stored. This value must be a multiple of 4 for DWORD size data, such as axes. It can be byte-aligned for buttons.
dwType
Device type that describes the object. It is a combination of the following flags describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits. When requesting a data format, the instance portion must be set to DIDFT_ANYINSTANCE to indicate that any instance is permissible, or to DIDFT_MAKEINSTANCE(n) to restrict the request to instance n. See the examples under Remarks.
DIDFT_ABSAXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute axis.
DIDFT_AXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute or relative axis.
DIDFT_BUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button or a toggle button.
DIDFT_FFACTUATOR
The object selected by the IDirectInputDevice8::SetDataFormat method must contain a force-feedback actuator; in other words, it must be possible to apply forces to the object.
DIDFT_FFEFFECTTRIGGER
The object selected by the IDirectInputDevice8::SetDataFormat method must be a valid force-feedback effect trigger.
DIDFT_POV
The object selected by the IDirectInputDevice8::SetDataFormat method must be a point-of-view controller.
DIDFT_PSHBUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button.
DIDFT_RELAXIS
The object selected by IDirectInputDevice8::SetDataFormat must be a relative axis.
DIDFT_TGLBUTTON
The object selected by IDirectInputDevice8::SetDataFormat must be a toggle button.
DIDFT_VENDORDEFINED
The object selected by IDirectInputDevice8::SetDataFormat must be of a type defined by the manufacturer.
dwFlags
Zero or more of the following values:
DIDOI_ASPECTACCEL
The object selected by IDirectInputDevice8::SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by IDirectInputDevice8::SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by IDirectInputDevice8::SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by IDirectInputDevice8::SetDataFormat must report velocity information.

Remarks

A data format is made up of several DIOBJECTDATAFORMAT structures, one for each object (axis, button, and so on). An array of these structures is contained in the DIDATAFORMAT structure that is passed to IDirectInputDevice8::SetDataFormat. An application typically does not need to create an array of DIOBJECTDATAFORMAT structures; rather, it can use one of the predefined data formats, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2, which have predefined settings for DIOBJECTDATAFORMAT.

The following object data format specifies that Microsoft® DirectInput® should choose the first available axis and report its value in the DWORD at offset 4 in the device data.

DIOBJECTDATAFORMAT dfAnyAxis = {
    0,                              // Wildcard
    4,                              // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that the x-axis of the device should be stored in the DWORD at offset 12 in the device data. If the device has more than one x-axis, the first available one should be selected.

DIOBJECTDATAFORMAT dfAnyXAxis = {
    &GUID_XAxis,                    // Must be an x-axis
    12,                             // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any x-axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that DirectInput should choose the first available button and report its value in the high bit of the byte at offset 16 in the device data.

DIOBJECTDATAFORMAT dfAnyButton = {
    0,                                // Wildcard
    16,                               // Offset
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, // Any button is okay.
    0,                                // Ignore aspect
};

The following object data format specifies that button 0 of the device should be reported as the high bit of the byte stored at offset 18 in the device data.

If the device does not have a button 0, the attempt to set this data format fails.

DIOBJECTDATAFORMAT dfButton0 = {
    0,                                    // Wildcard
    18,                                   // Offset
    DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0), // Button zero
    0,                                    // Ignore aspect
};

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPERIODIC Structure

Contains type-specific information for effects that are marked as DIEFT_PERIODIC.

The structure describes a periodic effect.

A pointer to a single DIPERIODIC structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DIPERIODIC {
    DWORD dwMagnitude;
    LONG  lOffset;
    DWORD dwPhase;
    DWORD dwPeriod;
} DIPERIODIC, *LPDIPERIODIC;

typedef const DIPERIODIC *LPCDIPERIODIC;

Members

dwMagnitude
Magnitude of the effect, in the range from 0 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.
lOffset
Offset of the effect. The range of forces generated by the effect is lOffset minus dwMagnitude to lOffset plus dwMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
dwPhase
Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999. See Remarks.
dwPeriod
Period of the effect, in microseconds.

Remarks

A device driver cannot provide support for all values in the dwPhase member. In this case, the value is rounded off to the nearest supported value.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPROPCPOINTS Structure

Sets calibration points for the current instance.

Syntax

typedef struct DIPROPCPOINTS {
    DIPROPHEADER diph;
    DWORD  dwCPointsNum;
    CPOINT cp[MAXCPOINTSNUM];
} DIPROPCPOINTS, *LPDIPROPCPOINTS;

typedef const DIPROPCPOINTS *LPCDIPROPCPOINTS;

Members

diph
DIPROPHEADER structure.
dwCPointsNum
Number of stored calibration points. No more than 8 calibration points may be used.
cp
Array of calibration points.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPCPOINTS)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

This property can be applied only to individual device objects, so DIPH_DEVICE cannot be used.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPROPDWORD Structure

Used to access DWORD properties.

Syntax

typedef struct DIPROPDWORD {
    DIPROPHEADER diph;
    DWORD        dwData;
} DIPROPDWORD, *LPDIPROPDWORD;

typedef const DIPROPDWORD *LPCDIPROPDWORD;

Members

diph
DIPROPHEADER structure.
dwData
Property-specific value being set or retrieved.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPDWORD)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty

© 2002 Microsoft Corporation. All rights reserved.


DIPROPGUIDANDPATH Structure

Used to access properties whose values represent a globally unique identifier (GUID) and a path.

Syntax

typedef struct DIPROPGUIDANDPATH {
    DIPROPHEADER diph;
    GUID         guidClass;
    WCHAR        wszPath[MAX_PATH];
} DIPROPGUIDANDPATH, *LPDIPROPGUIDANDPATH;

typedef const DIPROPGUIDANDPATH *LPCDIPROPGUIDANDPATH;

Members

diph
DIPROPHEADER structure.
guidClass
Class GUID for the object.
wszPath
Returned path for the object. This is a Unicode string.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPGUIDANDPATH).
dwHeaderSize | sizeof(DIPROPHEADER).
dwObj | For this structure, this member must be set to 0.
dwHow | Specifies how the dwObj member should be interpreted. For this structure, dwHow should be DIPH_DEVICE.

The DIPROP_GUIDANDPATH property associated with the DIPROPGUIDANDPATH structure enables advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft® DirectInput®.

The application calls the IDirectInputDevice8::GetProperty method with DIPROP_GUIDANDPATH as the rguidProp parameter. The class GUID of the device is returned in the guidClass member of the DIPROPGUIDANDPATH structure, and the device interface path is returned in the wszPath member. The application can then call the CreateFile function on this path to access the device directly.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPROPHEADER Structure

Serves as a header for all property structures.

Syntax

typedef struct DIPROPHEADER {
    DWORD    dwSize;
    DWORD    dwHeaderSize;
    DWORD    dwObj;
    DWORD    dwHow;
} DIPROPHEADER, *LPDIPROPHEADER;

typedef const DIPROPHEADER *LPCDIPROPHEADER;

Members

dwSize
Size of the enclosing structure. This member must be initialized before the structure is used.
dwHeaderSize
Size of the DIPROPHEADER structure.
dwObj
Object for which the property is to be accessed. The value set for this member depends on the value specified in the dwHow member.
dwHow
Value that specifies how the dwObj member should be interpreted. This value can be one of the following:
DIPH_DEVICE
The dwObj member must be 0.
DIPH_BYOFFSET
The dwObj member is the offset into the current data format of the object whose property is being accessed.
DIPH_BYUSAGE
The dwObj member is the HID usage page and usage values in packed form.
DIPH_BYID
The dwObj member is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects member.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPROPPOINTER Structure

Used in setting and retrieving data values of type UINT_PTR. This is typically a value associated with an application-specific action associated with a device object in an action map, but can also be a function pointer.

Syntax

typedef struct DIPROPPOINTER {
    DIPROPHEADER diph;
    UINT_PTR     uData;
} DIPROPPOINTER, *LPDIPROPPOINTER;

typedef const DIPROPPOINTER *LPCDIPROPPOINTER;

Members

diph
DIPROPHEADER structure.
uData
Application-defined value of type UINT_PTR, which represents the uAppData value (from an action map) that is associated with a device control.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPPOINTER)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIPROPRANGE Structure

Contains information about the range of an object within a device. This structure is used with the DIPROP_RANGE flag set in the IDirectInputDevice8::GetProperty and IDirectInputDevice8::SetProperty methods.

Syntax

typedef struct DIPROPRANGE {
    DIPROPHEADER diph;
    LONG         lMin;
    LONG         lMax;
} DIPROPRANGE, *LPDIPROPRANGE;

typedef const DIPROPRANGE *LPCDIPROPRANGE;

Members

diph
DIPROPHEADER structure.
lMin
Lower limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMIN when the IDirectInputDevice8::GetProperty method returns.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMAX when the IDirectInputDevice8::GetProperty method returns.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPRANGE)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.Identifier of the object whose property is being retrieved or set.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The range values for devices whose ranges are unrestricted wraparound.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty

© 2002 Microsoft Corporation. All rights reserved.


DIPROPSTRING Structure

Gets and retrieves properties as strings.

Syntax

typedef struct DIPROPSTRING {
    DIPROPHEADER diph;
    WCHAR        wsz[MAX_PATH];
} DIPROPSTRING, * LPDIPROPSTRING;;

typedef const DIPROPSTRING *LPCDIPROPSTRING;

Members

diph
DIPROPHEADER structure.
wsz
Unicode string that specifies or retrieves the property.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPSTRING)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The DIPROP_INSTANCENAME and DIPROP_PRODUCTNAME properties associated with the DIPROPSTRING structure enable advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft® DirectInput®.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIRAMPFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_RAMPFORCE. The structure describes a ramp force effect.

A pointer to a single DIRAMPFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DIRAMPFORCE {
    LONG lStart;
    LONG lEnd;
} DIRAMPFORCE, *LPDIRAMPFORCE;

typedef const DIRAMPFORCE *LPCDIRAMPFORCE;

Members

lStart
Magnitude at the start of the effect, in the range from –10,000 through 10,000.
lEnd
Magnitude at the end of the effect, in the range from –10,000 through 10,000.

Remarks

The dwDuration for a ramp force effect cannot be INFINITE.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Device Constants

This section is a reference for constants used to interpret data for keys, buttons, and axes.

Constants

  • DirectInput and Japanese Keyboards
  • Joystick Device Constants
  • Keyboard Device
  • Mouse Device

© 2002 Microsoft Corporation. All rights reserved.


DirectInput and Japanese Keyboards

This topic lists keys that are available on Japanese keyboards but not on standard U.S. keyboards, as well as keys that are available on U.S. keyboards but not on the various Japanese keyboards.

On Microsoft® Windows® 2000 and with some keyboards (such as the NEC PC-98) using other operating systems, the DIK_CAPSLOCK, DIK_KANJI, and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Japanese Keyboard | Additional keys | Missing keys
DOS/V 106, NEC PC-98 106 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU

© 2002 Microsoft Corporation. All rights reserved.


Joystick Device Constants

Joystick device constants represent offsets within a joystick device's data packet, the DIJOYSTATE structure. The data at a given offset is associated with a device object; that is, a button or axis. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The following macros return a constant indicating the offset of the data for a particular button or axis relative to the beginning of the DIJOYSTATE structure.

Constant | Device object
DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n) | Button
DIJOFS_POV(n) | Point-of-view indicator
DIJOFS_RX | X-axis rotation
DIJOFS_RY | Y-axis rotation
DIJOFS_RZ | Z-axis rotation (rudder)
DIJOFS_X | X-axis
DIJOFS_Y | Y-axis
DIJOFS_Z | Z-axis
DIJOFS_SLIDER(n) | Slider axis

© 2002 Microsoft Corporation. All rights reserved.


Keyboard Device Enumerated Type

Keyboard device constants, defined in Dinput.h, represent offsets within a keyboard device's data packet, a 256-byte array.

Syntax

typedef enum {
    DIK_0,
    DIK_1,
    DIK_2,
    DIK_3,
    DIK_4,
    DIK_5,
    DIK_6,
    DIK_7,
    DIK_8,
    DIK_9,
    DIK_A,
    DIK_ABNT_C1,
    DIK_ABNT_C2,
    DIK_ADD,
    DIK_APOSTROPHE,
    DIK_APPS,
    DIK_AT,
    DIK_AX,
    DIK_B,
    DIK_BACK,
    DIK_BACKSLASH,
    DIK_C,
    DIK_CALCULATOR,
    DIK_CAPITAL,
    DIK_COLON,
    DIK_COMMA,
    DIK_CONVERT,
    DIK_D,
    DIK_DECIMAL,
    DIK_DELETE,
    DIK_DIVIDE,
    DIK_DOWN,
    DIK_E,
    DIK_END,
    DIK_EQUALS,
    DIK_ESCAPE,
    DIK_F,
    DIK_F1,
    DIK_F2,
    DIK_F3,
    DIK_F4,
    DIK_F5,
    DIK_F6,
    DIK_F7,
    DIK_F8,
    DIK_F9,
    DIK_F10,
    DIK_F11,
    DIK_F12,
    DIK_F13,
    DIK_F14,
    DIK_F15,
    DIK_G,
    DIK_GRAVE,
    DIK_H,
    DIK_HOME,
    DIK_I,
    DIK_INSERT,
    DIK_J,
    DIK_K,
    DIK_KANA,
    DIK_KANJI,
    DIK_L,
    DIK_LBRACKET,
    DIK_LCONTROL,
    DIK_LEFT,
    DIK_LMENU,
    DIK_LSHIFT,
    DIK_LWIN,
    DIK_M,
    DIK_MAIL,
    DIK_MEDIASELECT,
    DIK_MEDIASTOP,
    DIK_MINUS,
    DIK_MULTIPLY,
    DIK_MUTE,
    DIK_MYCOMPUTER,
    DIK_N,
    DIK_NEXT,
    DIK_NEXTTRACK,
    DIK_NOCONVERT,
    DIK_NUMLOCK,
    DIK_NUMPAD0,
    DIK_NUMPAD1,
    DIK_NUMPAD2,
    DIK_NUMPAD3,
    DIK_NUMPAD4,
    DIK_NUMPAD5,
    DIK_NUMPAD6,
    DIK_NUMPAD7,
    DIK_NUMPAD8,
    DIK_NUMPAD9,
    DIK_NUMPADCOMMA,
    DIK_NUMPADENTER,
    DIK_NUMPADEQUALS,
    DIK_O,
    DIK_OEM_102,
    DIK_P,
    DIK_PAUSE,
    DIK_PERIOD,
    DIK_PLAYPAUSE,
    DIK_POWER,
    DIK_PREVTRACK,
    DIK_PRIOR,
    DIK_Q,
    DIK_R,
    DIK_RBRACKET,
    DIK_RCONTROL,
    DIK_RETURN,
    DIK_RIGHT,
    DIK_RMENU,
    DIK_RSHIFT,
    DIK_RWIN,
    DIK_S,
    DIK_SCROLL,
    DIK_SEMICOLON,
    DIK_SLASH,
    DIK_SLEEP,
    DIK_SPACE,
    DIK_STOP,
    DIK_SUBTRACT,
    DIK_SYSRQ,
    DIK_T,
    DIK_TAB,
    DIK_U,
    DIK_UNDERLINE,
    DIK_UNLABELED,
    DIK_UP,
    DIK_V,
    DIK_VOLUMEDOWN,
    DIK_VOLUMEUP,
    DIK_W,
    DIK_WAKE,
    DIK_WEBBACK,
    DIK_WEBFAVORITES,
    DIK_WEBFORWARD,
    DIK_WEBHOME,
    DIK_WEBREFRESH,
    DIK_WEBSEARCH,
    DIK_WEBSTOP,
    DIK_X,
    DIK_Y,
    DIK_YEN,
    DIK_Z
} Keyboard Device;

Constants

DIK_0

On main keyboard

DIK_1

On main keyboard

DIK_2

On main keyboard

DIK_3

On main keyboard

DIK_4

On main keyboard

DIK_5

On main keyboard

DIK_6

On main keyboard

DIK_7

On main keyboard

DIK_8

On main keyboard

DIK_9

On main keyboard

DIK_A

DIK_ABNT_C1

On numeric pad of Brazilian keyboards

DIK_ABNT_C2

On numeric pad of Brazilian keyboards

DIK_ADD

PLUS SIGN (+) on numeric keypad

DIK_APOSTROPHE

DIK_APPS

Application key

DIK_AT

On Japanese keyboard

DIK_AX

On Japanese keyboard

DIK_B

DIK_BACK

BACKSPACE

DIK_BACKSLASH

DIK_C

DIK_CALCULATOR

DIK_CAPITAL

CAPS LOCK

DIK_COLON

On Japanese keyboard

DIK_COMMA

DIK_CONVERT

On Japanese keyboard

DIK_D

DIK_DECIMAL

PERIOD (decimal point) on numeric keypad

DIK_DELETE

DIK_DIVIDE

Forward slash (/) on numeric keypad

DIK_DOWN

DOWN ARROW

DIK_E

DIK_END

DIK_EQUALS

On main keyboard

DIK_ESCAPE

DIK_F

DIK_F1

DIK_F2

DIK_F3

DIK_F4

DIK_F5

DIK_F6

DIK_F7

DIK_F8

DIK_F9

DIK_F10

DIK_F11

DIK_F12

DIK_F13

On NEC PC-98 Japanese keyboard

DIK_F14

On NEC PC-98 Japanese keyboard

DIK_F15

On NEC PC-98 Japanese keyboard

DIK_G

DIK_GRAVE

Grave accent (`)

DIK_H

DIK_HOME

DIK_I

DIK_INSERT

DIK_J

DIK_K

DIK_KANA

On Japanese keyboard

DIK_KANJI

On Japanese keyboard

DIK_L

DIK_LBRACKET

Left square bracket [

DIK_LCONTROL

Left CTRL

DIK_LEFT

LEFT ARROW

DIK_LMENU

Left ALT

DIK_LSHIFT

Left SHIFT

DIK_LWIN

Left Microsoft® Windows® logo key

DIK_M

DIK_MAIL

DIK_MEDIASELECT

Media Select key, which displays a selection of supported media players on the system

DIK_MEDIASTOP

DIK_MINUS

On main keyboard

DIK_MULTIPLY

Asterisk (*) on numeric keypad

DIK_MUTE

DIK_MYCOMPUTER

DIK_N

DIK_NEXT

PAGE DOWN

DIK_NEXTTRACK

Next track

DIK_NOCONVERT

On Japanese keyboard

DIK_NUMLOCK

DIK_NUMPAD0

DIK_NUMPAD1

DIK_NUMPAD2

DIK_NUMPAD3

DIK_NUMPAD4

DIK_NUMPAD5

DIK_NUMPAD6

DIK_NUMPAD7

DIK_NUMPAD8

DIK_NUMPAD9

DIK_NUMPADCOMMA

On numeric keypad of NEC PC-98 Japanese keyboard

DIK_NUMPADENTER

DIK_NUMPADEQUALS

On numeric keypad of NEC PC-98 Japanese keyboard

DIK_O

DIK_OEM_102

On British and German keyboards

DIK_P

DIK_PAUSE

DIK_PERIOD

On main keyboard

DIK_PLAYPAUSE

DIK_POWER

DIK_PREVTRACK

Previous track; circumflex on Japanese keyboard

DIK_PRIOR

PAGE UP

DIK_Q

DIK_R

DIK_RBRACKET

Right square bracket ]

DIK_RCONTROL

Right CTRL

DIK_RETURN

ENTER on main keyboard

DIK_RIGHT

RIGHT ARROW

DIK_RMENU

Right ALT

DIK_RSHIFT

Right SHIFT

DIK_RWIN

Right Windows logo key

DIK_S

DIK_SCROLL

SCROLL LOCK

DIK_SEMICOLON

DIK_SLASH

Forward slash (/) on main keyboard

DIK_SLEEP

DIK_SPACE

SPACEBAR

DIK_STOP

On NEC PC-98 Japanese keyboard

DIK_SUBTRACT

MINUS SIGN (-) on numeric keypad

DIK_SYSRQ

DIK_T

DIK_TAB

DIK_U

DIK_UNDERLINE

On NEC PC-98 Japanese keyboard

DIK_UNLABELED

On Japanese keyboard

DIK_UP

UP ARROW

DIK_V

DIK_VOLUMEDOWN

DIK_VOLUMEUP

DIK_W

DIK_WAKE

DIK_WEBBACK

DIK_WEBFAVORITES

Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list.

DIK_WEBFORWARD

DIK_WEBHOME

DIK_WEBREFRESH

DIK_WEBSEARCH

DIK_WEBSTOP

DIK_X

DIK_Y

DIK_YEN

On Japanese keyboard

DIK_Z

Remarks

The following alternate names are available:

Alternate name | Regular name | Note
DIK_BACKSPACE | DIK_BACK | BACKSPACE
DIK_CAPSLOCK | DIK_CAPITAL | CAPS LOCK
DIK_CIRCUMFLEX | DIK_PREVTRACK | On Japanese keyboard
DIK_DOWNARROW | DIK_DOWN | On arrow keypad
DIK_LALT | DIK_LMENU | Left ALT
DIK_LEFTARROW | DIK_LEFT | On arrow keypad
DIK_NUMPADMINUS | DIK__SUBTRACT | MINUS SIGN (-) on numeric keypad
DIK_NUMPADPERIOD | DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_NUMPADPLUS | DIK_ADD | PLUS SIGN (+) on numeric keypad
DIK_NUMPADSLASH | DIK__DIVIDE | Forward slash (/) on numeric keypad
DIK_NUMPADSTAR | DIK_MULTIPLY | Asterisk (*) on numeric keypad
DIK_PGDN | DIK_NEXT | On arrow keypad
DIK_PGUP | DIK_PRIOR | On arrow keypad
DIK_RALT | DIK_RMENU | Right ALT
DIK_RIGHTARROW | DIK_RIGHT | On arrow keypad
DIK_UPARROW | DIK_UP | On arrow keypad

For information about Japanese keyboards, see DirectInput and Japanese Keyboards.

The data at a given offset is associated with a keyboard key. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures, or as indices when accessing data within the array using array notation.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


Mouse Device Enumerated Type

Mouse device constants, defined in Dinput.h, represent offsets within a mouse device's data packet, the DIMOUSESTATE or DIMOUSESTATE2 structure.

Syntax

typedef enum {
    DIMOFS_BUTTON0,
    DIMOFS_BUTTON1,
    DIMOFS_BUTTON2,
    DIMOFS_BUTTON3,
    DIMOFS_BUTTON4,
    DIMOFS_BUTTON5,
    DIMOFS_BUTTON6,
    DIMOFS_BUTTON7,
    DIMOFS_X,
    DIMOFS_Y,
    DIMOFS_Z
} Mouse Device;

Constants

DIMOFS_BUTTON0

DIMOFS_BUTTON1

DIMOFS_BUTTON2

DIMOFS_BUTTON3

DIMOFS_BUTTON4

DIMOUSESTATE2 only

DIMOFS_BUTTON5

DIMOUSESTATE2 only

DIMOFS_BUTTON6

DIMOUSESTATE2 only

DIMOFS_BUTTON7

DIMOUSESTATE2 only

DIMOFS_X

DIMOFS_Y

DIMOFS_Z

Remarks

The data at a given offset is associated with a device object (button or axis). Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


Action Mapping Constants

This section is a reference to the constants defined in Dinput.h for application genres and controls mapped to actions within each genre.

The control constants, such as DIAXIS_FIGHTINGH_MOVE, are used in the dwSemantic member of the DIACTION structure to associate the control with an action in the application.

The constants for the genres, such as DIVIRTUAL_FIGHTING_HAND2HAND, are used in the dwGenre member of the DIACTIONFORMAT structure.

Action mapping constants are provided for application genres in the following categories.

  • Action Genres
  • Arcade Genres
  • CAD Genres
  • Control Genres
  • Driving Genres
  • Flight Genres
  • Sports Genres
  • Strategy Genres

The dwSemantic member of the DIACTION structure member can map the action to a particular device object rather than a virtual control. Device object constants are provided in the following categories.

Constants

  • Any-Control
  • DirectPlay Voice Mapping
  • Keyboard Mapping
  • Mouse Mapping

© 2002 Microsoft Corporation. All rights reserved.


Action Genres

The following genres contain controls for fighting and action games.

Constants

  • Hand-to-Hand
  • Shooting
  • Third-Person Action

© 2002 Microsoft Corporation. All rights reserved.


Hand-to-Hand

The DIVIRTUAL_FIGHTING_HAND2HAND genre contains controls for a first-person fighting game without guns.

Priority 1 Controls
DIAXIS_FIGHTINGH_LATERAL
DIAXIS_FIGHTINGH_MOVE
DIBUTTON_FIGHTINGH_BLOCK
DIBUTTON_FIGHTINGH_CROUCH
DIBUTTON_FIGHTINGH_JUMP
DIBUTTON_FIGHTINGH_KICK
DIBUTTON_FIGHTINGH_MENU
DIBUTTON_FIGHTINGH_PUNCH
DIBUTTON_FIGHTINGH_SPECIAL1
DIBUTTON_FIGHTINGH_SPECIAL2

Priority 2 Controls
DIAXIS_FIGHTINGH_ROTATE
DIBUTTON_FIGHTINGH_BACKWARD_LINK
DIBUTTON_FIGHTINGH_DEVICE
DIBUTTON_FIGHTINGH_DISPLAY
DIBUTTON_FIGHTINGH_DODGE
DIBUTTON_FIGHTINGH_FORWARD_LINK
DIBUTTON_FIGHTINGH_LEFT_LINK
DIBUTTON_FIGHTINGH_RIGHT_LINK
DIBUTTON_FIGHTINGH_PAUSE
DIBUTTON_FIGHTINGH_SELECT
DIHATSWITCH_FIGHTINGH_SLIDE

© 2002 Microsoft Corporation. All rights reserved.


Shooting

The DIVIRTUAL_FIGHTING_FPS genre contains controls for a first-person fighting game with guns.

Priority 1 Controls
DIAXIS_FPS_LOOKUPDOWN
DIAXIS_FPS_MOVE
DIAXIS_FPS_ROTATE
DIBUTTON_FPS_APPLY
DIBUTTON_FPS_CROUCH
DIBUTTON_FPS_FIRE
DIBUTTON_FPS_JUMP
DIBUTTON_FPS_MENU
DIBUTTON_FPS_SELECT
DIBUTTON_FPS_STRAFE
DIBUTTON_FPS_WEAPONS

Priority 2 Controls
DIAXIS_FPS_SIDESTEP
DIBUTTON_FPS_BACKWARD_LINK
DIBUTTON_FPS_DEVICE
DIBUTTON_FPS_DISPLAY
DIBUTTON_FPS_DODGE
DIBUTTON_FPS_FIRESECONDARY
DIBUTTON_FPS_FORWARD_LINK
DIBUTTON_FPS_GLANCE_DOWN_LINK
DIBUTTON_FPS_GLANCE_UP_LINK
DIBUTTON_FPS_GLANCEL
DIBUTTON_FPS_GLANCER
DIBUTTON_FPS_PAUSE
DIBUTTON_FPS_ROTATE_LEFT_LINK
DIBUTTON_FPS_ROTATE_RIGHT_LINK
DIHATSWITCH_FPS_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Third-Person Action

The DIVIRTUAL_FIGHTING_THIRDPERSON genre contains controls for a third-person action game.

Priority 1 Controls
DIAXIS_TPS_MOVE
DIAXIS_TPS_TURN
DIBUTTON_TPS_ACTION
DIBUTTON_TPS_JUMP
DIBUTTON_TPS_MENU
DIBUTTON_TPS_RUN
DIBUTTON_TPS_SELECT
DIBUTTON_TPS_USE

Priority 2 Controls
DIAXIS_TPS_STEP
DIBUTTON_TPS_BACKWARD_LINK
DIBUTTON_TPS_DEVICE
DIBUTTON_TPS_DODGE
DIBUTTON_TPS_FORWARD_LINK
DIBUTTON_TPS_GLANCE_DOWN_LINK
DIBUTTON_TPS_GLANCE_LEFT_LINK
DIBUTTON_TPS_GLANCE_RIGHT_LINK
DIBUTTON_TPS_GLANCE_UP_LINK
DIBUTTON_TPS_INVENTORY
DIBUTTON_TPS_PAUSE
DIBUTTON_TPS_STEPLEFT
DIBUTTON_TPS_STEPRIGHT
DIBUTTON_TPS_TURN_LEFT_LINK
DIBUTTON_TPS_TURN_RIGHT_LINK
DIBUTTON_TPS_VIEW
DIHATSWITCH_TPS_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Arcade Genres

The following genres contain controls for arcade-type games in which the object is to move a figure through a dangerous environment.

Constants

  • Platform
  • Side-to-Side

© 2002 Microsoft Corporation. All rights reserved.


Platform

The DIVIRTUAL_ARCADE_PLATFORM genre contains controls for an arcade-style game.

Priority 1 Controls
DIAXIS_ARCADEP_LATERAL
DIAXIS_ARCADEP_MOVE
DIBUTTON_ARCADEP_CROUCH
DIBUTTON_ARCADEP_FIRE
DIBUTTON_ARCADEP_JUMP
DIBUTTON_ARCADEP_MENU
DIBUTTON_ARCADEP_SELECT
DIBUTTON_ARCADEP_SPECIAL

Priority 2 Controls
DIBUTTON_ARCADEP_BACK_LINK
DIBUTTON_ARCADEP_DEVICE
DIBUTTON_ARCADEP_FIRESECONDARY
DIBUTTON_ARCADEP_FORWARD_LINK
DIBUTTON_ARCADEP_LEFT_LINK
DIBUTTON_ARCADEP_PAUSE
DIBUTTON_ARCADEP_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_DOWN_LINK
DIBUTTON_ARCADEP_VIEW_LEFT_LINK
DIBUTTON_ARCADEP_VIEW_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_UP_LINK
DIHATSWITCH_ARCADEP_VIEW

© 2002 Microsoft Corporation. All rights reserved.


Side-to-Side

The DIVIRTUAL_ARCADE_SIDE2SIDE genre contains controls for a two-dimensional arcade-style game.

Priority 1 Controls
DIAXIS_ARCADES_LATERAL
DIAXIS_ARCADES_MOVE
DIBUTTON_ARCADES_ATTACK
DIBUTTON_ARCADES_CARRY
DIBUTTON_ARCADES_MENU
DIBUTTON_ARCADES_SELECT
DIBUTTON_ARCADES_SPECIAL
DIBUTTON_ARCADES_THROW

Priority 2 Controls
DIBUTTON_ARCADES_BACK_LINK
DIBUTTON_ARCADES_DEVICE
DIBUTTON_ARCADES_FORWARD_LINK
DIBUTTON_ARCADES_LEFT_LINK
DIBUTTON_ARCADES_PAUSE
DIBUTTON_ARCADES_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_DOWN_LINK
DIBUTTON_ARCADES_VIEW_LEFT_LINK
DIBUTTON_ARCADES_VIEW_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_UP_LINK
DIHATSWITCH_ARCADES_VIEW

© 2002 Microsoft Corporation. All rights reserved.


CAD Genres

The following genres contain controls for computer-assisted drafting applications.

Constants

  • 2-D Object
  • 3-D Model
  • 3-D Navigation
  • 3-D Object

© 2002 Microsoft Corporation. All rights reserved.


2-D Object

The DIVIRTUAL_CAD_2DCONTROL genre contains controls to select and move objects in a two-dimensional drafting environment.

Priority 1 Controls
DIAXIS_2DCONTROL_LATERAL
DIAXIS_2DCONTROL_MOVE
DIAXIS_2DCONTROL_INOUT
DIBUTTON_2DCONTROL_MENU
DIBUTTON_2DCONTROL_SELECT
DIBUTTON_2DCONTROL_SPECIAL
DIBUTTON_2DCONTROL_SPECIAL1
DIBUTTON_2DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_2DCONTROL_ROTATEZ
DIBUTTON_2DCONTROL_DEVICE
DIBUTTON_2DCONTROL_DISPLAY
DIBUTTON_2DCONTROL_PAUSE
DIHATSWITCH_2DCONTROL_HATSWITCH

© 2002 Microsoft Corporation. All rights reserved.


3-D Model

The DIVIRTUAL_CAD_MODEL genre contains controls for modeling three-dimensional objects.

Priority 1 Controls
DIAXIS_CADM_LATERAL
DIAXIS_CADM_MOVE
DIAXIS_CADM_INOUT
DIBUTTON_CADM_MENU
DIBUTTON_CADM_SELECT
DIBUTTON_CADM_SPECIAL
DIBUTTON_CADM_SPECIAL1
DIBUTTON_CADM_SPECIAL2

Priority 2 Controls
DIAXIS_CADM_ROTATEX
DIAXIS_CADM_ROTATEY
DIAXIS_CADM_ROTATEZ
DIBUTTON_CADM_DEVICE
DIBUTTON_CADM_DISPLAY
DIBUTTON_CADM_PAUSE
DIHATSWITCH_CADM_HATSWITCH

© 2002 Microsoft Corporation. All rights reserved.


3-D Navigation

The DIVIRTUAL_CAD_FLYBY genre contains control for fly-through navigation of three-dimensional environments.

Priority 1 Controls
DIAXIS_CADF_LATERAL
DIAXIS_CADF_MOVE
DIAXIS_CADF_INOUT
DIBUTTON_CADF_MENU
DIBUTTON_CADF_SELECT
DIBUTTON_CADF_SPECIAL
DIBUTTON_CADF_SPECIAL1
DIBUTTON_CADF_SPECIAL2

Priority 2 Controls
DIAXIS_CADF_ROTATEX
DIAXIS_CADF_ROTATEY
DIAXIS_CADF_ROTATEZ
DIBUTTON_CADF_DEVICE
DIBUTTON_CADF_DISPLAY
DIBUTTON_CADF_PAUSE
DIHATSWITCH_CADF_HATSWITCH

© 2002 Microsoft Corporation. All rights reserved.


3-D Object

The DIVIRTUAL_CAD_3DCONTROL genre contains controls to select and move objects in a three-dimensional drafting environment.

Priority 1 Controls
DIAXIS_3DCONTROL_LATERAL
DIAXIS_3DCONTROL_MOVE
DIAXIS_3DCONTROL_INOUT
DIBUTTON_3DCONTROL_MENU
DIBUTTON_3DCONTROL_SELECT
DIBUTTON_3DCONTROL_SPECIAL
DIBUTTON_3DCONTROL_SPECIAL1
DIBUTTON_3DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_3DCONTROL_ROTATEX
DIAXIS_3DCONTROL_ROTATEY
DIAXIS_3DCONTROL_ROTATEZ
DIBUTTON_3DCONTROL_DEVICE
DIBUTTON_3DCONTROL_DISPLAY
DIBUTTON_3DCONTROL_PAUSE
DIHATSWITCH_3DCONTROL_HATSWITCH

© 2002 Microsoft Corporation. All rights reserved.


Control Genres

The following genres contain controls for use with browsers and remote-control devices.

Constants

  • Browser
  • Remote Control

© 2002 Microsoft Corporation. All rights reserved.


Browser

The DIVIRTUAL_BROWSER_CONTROL genre contains controls for a browser.

Priority 1 Controls
DIAXIS_BROWSER_LATERAL
DIAXIS_BROWSER_MOVE
DIAXIS_BROWSER_VIEW
DIBUTTON_BROWSER_MENU
DIBUTTON_BROWSER_REFRESH
DIBUTTON_BROWSER_SELECT

Priority 2 Controls
DIBUTTON_BROWSER_DEVICE
DIBUTTON_BROWSER_FAVORITES
DIBUTTON_BROWSER_HISTORY
DIBUTTON_BROWSER_HOME
DIBUTTON_BROWSER_NEXT
DIBUTTON_BROWSER_PAUSE
DIBUTTON_BROWSER_PREVIOUS
DIBUTTON_BROWSER_PRINT
DIBUTTON_BROWSER_SEARCH
DIBUTTON_BROWSER_STOP

© 2002 Microsoft Corporation. All rights reserved.


Remote Control

The DIVIRTUAL_REMOTE_CONTROL genre contains controls for remote-control devices used with equipment such as media players.

Priority 1 Controls
DIAXIS_REMOTE_SLIDER
DIBUTTON_REMOTE_CHANGE
DIBUTTON_REMOTE_CUE
DIBUTTON_REMOTE_MENU
DIBUTTON_REMOTE_MUTE
DIBUTTON_REMOTE_PLAY
DIBUTTON_REMOTE_RECORD
DIBUTTON_REMOTE_REVIEW
DIBUTTON_REMOTE_SELECT

Priority 2 Controls
DIAXIS_REMOTE_SLIDER2
DIBUTTON_REMOTE_ADJUST
DIBUTTON_REMOTE_CABLE
DIBUTTON_REMOTE_CD
DIBUTTON_REMOTE_DEVICE
DIBUTTON_REMOTE_DIGIT0
DIBUTTON_REMOTE_DIGIT1
DIBUTTON_REMOTE_DIGIT2
DIBUTTON_REMOTE_DIGIT3
DIBUTTON_REMOTE_DIGIT4
DIBUTTON_REMOTE_DIGIT5
DIBUTTON_REMOTE_DIGIT6
DIBUTTON_REMOTE_DIGIT7
DIBUTTON_REMOTE_DIGIT8
DIBUTTON_REMOTE_DIGIT9
DIBUTTON_REMOTE_DVD
DIBUTTON_REMOTE_PAUSE
DIBUTTON_REMOTE_TUNER
DIBUTTON_REMOTE_TV
DIBUTTON_REMOTE_VCR

© 2002 Microsoft Corporation. All rights reserved.


Driving Genres

The following genres are used in games where the players control vehicles in racing or combat.

Constants

  • Combat Racing
  • Mechanical Fighting
  • Racing
  • Tank

© 2002 Microsoft Corporation. All rights reserved.


Combat Racing

The DIVIRTUAL_DRIVING_COMBAT genre contains controls for a vehicle race game with combat.

Priority 1 Controls
DIAXIS_DRIVINGC_ACCELERATE
DIAXIS_DRIVINGC_BRAKE
DIAXIS_DRIVINGC_STEER
DIBUTTON_DRIVINGC_FIRE
DIBUTTON_DRIVINGC_MENU
DIBUTTON_DRIVINGC_TARGET
DIBUTTON_DRIVINGC_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGC_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGC_ACCELERATE_LINK
DIBUTTON_DRIVINGC_AIDS
DIBUTTON_DRIVINGC_BRAKE
DIBUTTON_DRIVINGC_DASHBOARD
DIBUTTON_DRIVINGC_DEVICE
DIBUTTON_DRIVINGC_FIRESECONDARY
DIBUTTON_DRIVINGC_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGC_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGC_PAUSE
DIBUTTON_DRIVINGC_SHIFTDOWN
DIBUTTON_DRIVINGC_SHIFTUP
DIBUTTON_DRIVINGC_STEER_LEFT_LINK
DIBUTTON_DRIVINGC_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGC_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Mechanical Fighting

The DIVIRTUAL_DRIVING_MECHA genre contains controls for a walking vehicle in a mechanized-warfare game.

Priority 1 Controls
DIAXIS_MECHA_ROTATE
DIAXIS_MECHA_STEER
DIAXIS_MECHA_THROTTLE
DIAXIS_MECHA_TORSO
DIBUTTON_MECHA_FIRE
DIBUTTON_MECHA_JUMP
DIBUTTON_MECHA_MENU
DIBUTTON_MECHA_REVERSE
DIBUTTON_MECHA_TARGET
DIBUTTON_MECHA_WEAPONS
DIBUTTON_MECHA_ZOOM

Priority 2 Controls
DIBUTTON_MECHA_BACK_LINK
DIBUTTON_MECHA_CENTER
DIBUTTON_MECHA_DEVICE
DIBUTTON_MECHA_FASTER_LINK
DIBUTTON_MECHA_FIRESECONDARY
DIBUTTON_MECHA_FORWARD_LINK
DIBUTTON_MECHA_LEFT_LINK
DIBUTTON_MECHA_PAUSE
DIBUTTON_MECHA_RIGHT_LINK
DIBUTTON_MECHA_ROTATE_LEFT_LINK
DIBUTTON_MECHA_ROTATE_RIGHT_LINK
DIBUTTON_MECHA_SLOWER_LINK
DIBUTTON_MECHA_VIEW
DIHATSWITCH_MECHA_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Racing

The DIVIRTUAL_DRIVING_RACE genre contains controls for an auto-racing game without combat.

Priority 1 Controls
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIAXIS_DRIVINGR_STEER
DIBUTTON_DRIVINGR_MENU
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_VIEW

Priority 2 Controls
DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGR_ACCELERATE_LINK
DIBUTTON_DRIVINGR_AIDS
DIBUTTON_DRIVINGR_BOOST
DIBUTTON_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_DASHBOARD
DIBUTTON_DRIVINGR_DEVICE
DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGR_MAP
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_PAUSE
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGR_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Tank

The DIVIRTUAL_DRIVING_TANK genre contains controls for a military tank simulation.

Priority 1 Controls
DIAXIS_DRIVINGT_ACCELERATE
DIAXIS_DRIVINGT_BARREL
DIAXIS_DRIVINGT_ROTATE
DIAXIS_DRIVINGT_STEER
DIBUTTON_DRIVINGT_FIRE
DIBUTTON_DRIVINGT_MENU
DIBUTTON_DRIVINGT_TARGET
DIBUTTON_DRIVINGT_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGT_ACCEL_AND_BRAKE
DIAXIS_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_ACCELERATE_LINK
DIBUTTON_DRIVINGT_BARREL_UP_LINK
DIBUTTON_DRIVINGT_BARREL_DOWN_LINK
DIBUTTON_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_DASHBOARD
DIBUTTON_DRIVINGT_DEVICE
DIBUTTON_DRIVINGT_FIRESECONDARY
DIBUTTON_DRIVINGT_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGT_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGT_PAUSE
DIBUTTON_DRIVINGT_ROTATE_LEFT_LINK
DIBUTTON_DRIVINGT_ROTATE_RIGHT_LINK
DIBUTTON_DRIVINGT_STEER_LEFT_LINK
DIBUTTON_DRIVINGT_STEER_RIGHT_LINK
DIBUTTON_DRIVINGT_VIEW
DIHATSWITCH_DRIVINGT_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Flight Genres

The following genres are used in games and simulations where the players control aircraft or spaceships.

Constants

  • Air Combat
  • Civilian Flight
  • Helicopter Combat
  • Space Combat

© 2002 Microsoft Corporation. All rights reserved.


Air Combat

The DIVIRTUAL_FLYING_MILITARY genre contains controls for a fixed-wing aerial combat simulation.

Priority 1 Controls
DIAXIS_FLYINGM_BANK
DIAXIS_FLYINGM_PITCH
DIAXIS_FLYINGM_THROTTLE
DIBUTTON_FLYINGM_FIRE
DIBUTTON_FLYINGM_MENU
DIBUTTON_FLYINGM_TARGET
DIBUTTON_FLYINGM_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGM_BRAKE
DIAXIS_FLYINGM_FLAPS
DIAXIS_FLYINGM_RUDDER
DIBUTTON_FLYINGM_BRAKE_LINK
DIBUTTON_FLYINGM_COUNTER
DIBUTTON_FLYINGM_DEVICE
DIBUTTON_FLYINGM_DISPLAY
DIBUTTON_FLYINGM_FASTER_LINK
DIBUTTON_FLYINGM_FIRESECONDARY
DIBUTTON_FLYINGM_FLAPSDOWN
DIBUTTON_FLYINGM_FLAPSUP
DIBUTTON_FLYINGM_GEAR
DIBUTTON_FLYINGM_GLANCE_DOWN_LINK
DIBUTTON_FLYINGM_GLANCE_LEFT_LINK
DIBUTTON_FLYINGM_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGM_GLANCE_UP_LINK
DIBUTTON_FLYINGM_PAUSE
DIBUTTON_FLYINGM_SLOWER_LINK
DIBUTTON_FLYINGM_VIEW
DIHATSWITCH_FLYINGM_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Civilian Flight

The DIVIRTUAL_FLYING_CIVILIAN genre contains controls for noncombat flight simulations.

Priority 1 Controls
DIAXIS_FLYINGC_BANK
DIAXIS_FLYINGC_PITCH
DIAXIS_FLYINGC_THROTTLE
DIBUTTON_FLYINGC_DISPLAY
DIBUTTON_FLYINGC_GEAR
DIBUTTON_FLYINGC_MENU
DIBUTTON_FLYINGC_VIEW

Priority 2 Controls
DIAXIS_FLYINGC_BRAKE
DIAXIS_FLYINGC_FLAPS
DIAXIS_FLYINGC_RUDDER
DIBUTTON_FLYINGC_BRAKE_LINK
DIBUTTON_FLYINGC_DEVICE
DIBUTTON_FLYINGC_FASTER_LINK
DIBUTTON_FLYINGC_FLAPSDOWN
DIBUTTON_FLYINGC_FLAPSUP
DIBUTTON_FLYINGC_GLANCE_DOWN_LINK
DIBUTTON_FLYINGC_GLANCE_LEFT_LINK
DIBUTTON_FLYINGC_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGC_GLANCE_UP_LINK
DIBUTTON_FLYINGC_PAUSE
DIBUTTON_FLYINGC_SLOWER_LINK
DIHATSWITCH_FLYINGC_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Helicopter Combat

The DIVIRTUAL_FLYING_HELICOPTER genre contains controls for a combat helicopter simulation.

Priority 1 Controls
DIAXIS_FLYINGH_BANK
DIAXIS_FLYINGH_COLLECTIVE
DIAXIS_FLYINGH_PITCH
DIBUTTON_FLYINGH_FIRE
DIBUTTON_FLYINGH_MENU
DIBUTTON_FLYINGH_TARGET
DIBUTTON_FLYINGH_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGH_THROTTLE
DIAXIS_FLYINGH_TORQUE
DIBUTTON_FLYINGH_COUNTER
DIBUTTON_FLYINGH_DEVICE
DIBUTTON_FLYINGH_FASTER_LINK
DIBUTTON_FLYINGH_FIRESECONDARY
DIBUTTON_FLYINGH_GEAR
DIBUTTON_FLYINGH_GLANCE_DOWN_LINK
DIBUTTON_FLYINGH_GLANCE_LEFT_LINK
DIBUTTON_FLYINGH_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGH_GLANCE_UP_LINK
DIBUTTON_FLYINGH_PAUSE
DIBUTTON_FLYINGH_SLOWER_LINK
DIBUTTON_FLYINGH_VIEW
DIHATSWITCH_FLYINGH_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Space Combat

The DIVIRTUAL_SPACESIM genre contains controls for a spaceship combat simulation.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL
DIAXIS_SPACESIM_MOVE
DIAXIS_SPACESIM_THROTTLE
DIBUTTON_SPACESIM_FIRE
DIBUTTON_SPACESIM_MENU
DIBUTTON_SPACESIM_TARGET
DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls
DIAXIS_SPACESIM_CLIMB
DIAXIS_SPACESIM_ROTATE
DIBUTTON_SPACESIM_BACKWARD_LINK
DIBUTTON_SPACESIM_DEVICE
DIBUTTON_SPACESIM_DISPLAY
DIBUTTON_SPACESIM_FASTER_LINK
DIBUTTON_SPACESIM_FIRESECONDARY
DIBUTTON_SPACESIM_FORWARD_LINK
DIBUTTON_SPACESIM_GEAR
DIBUTTON_SPACESIM_GLANCE_DOWN_LINK
DIBUTTON_SPACESIM_GLANCE_LEFT_LINK
DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK
DIBUTTON_SPACESIM_GLANCE_UP_LINK
DIBUTTON_SPACESIM_LEFT_LINK
DIBUTTON_SPACESIM_LOWER
DIBUTTON_SPACESIM_PAUSE
DIBUTTON_SPACESIM_RAISE
DIBUTTON_SPACESIM_RIGHT_LINK
DIBUTTON_SPACESIM_SLOWER_LINK
DIBUTTON_SPACESIM_TURN_LEFT_LINK
DIBUTTON_SPACESIM_TURN_RIGHT_LINK
DIBUTTON_SPACESIM_VIEW
DIHATSWITCH_SPACESIM_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Sports Genres

The following genres contain controls for sports games and simulations.

Constants

  • Baseball Batting
  • Baseball Fielding
  • Baseball Pitching
  • Basketball Defense
  • Basketball Offense
  • Fishing
  • Football Defense
  • Football Offense
  • Football Play
  • Football Quarterback
  • Golf
  • Hockey Defense
  • Hockey Goalie
  • Hockey Offense
  • Hunting
  • Mountain Biking
  • Racquet
  • Skiing
  • Soccer Defense
  • Soccer Offense

© 2002 Microsoft Corporation. All rights reserved.


Baseball Batting

The DIVIRTUAL_SPORTS_BASEBALL_BAT genre contains controls for a batter in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLB_LATERAL
DIAXIS_BASEBALLB_MOVE
DIBUTTON_BASEBALLB_BUNT
DIBUTTON_BASEBALLB_BURST
DIBUTTON_BASEBALLB_CONTACT
DIBUTTON_BASEBALLB_MENU
DIBUTTON_BASEBALLB_NORMAL
DIBUTTON_BASEBALLB_POWER
DIBUTTON_BASEBALLB_SELECT
DIBUTTON_BASEBALLB_SLIDE
DIBUTTON_BASEBALLB_STEAL

Priority 2 Controls
DIBUTTON_BASEBALLB_BOX
DIBUTTON_BASEBALLB_BACK_LINK
DIBUTTON_BASEBALLB_DEVICE
DIBUTTON_BASEBALLB_FORWARD_LINK
DIBUTTON_BASEBALLB_LEFT_LINK
DIBUTTON_BASEBALLB_NOSTEAL
DIBUTTON_BASEBALLB_PAUSE
DIBUTTON_BASEBALLB_RIGHT_LINK

© 2002 Microsoft Corporation. All rights reserved.


Baseball Fielding

The DIVIRTUAL_SPORTS_BASEBALL_FIELD genre contains controls for fielders in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLF_LATERAL
DIAXIS_BASEBALLF_MOVE
DIBUTTON_BASEBALLF_BURST
DIBUTTON_BASEBALLF_DIVE
DIBUTTON_BASEBALLF_JUMP
DIBUTTON_BASEBALLF_MENU
DIBUTTON_BASEBALLF_NEAREST
DIBUTTON_BASEBALLF_THROW1
DIBUTTON_BASEBALLF_THROW2

Priority 2 Controls
DIBUTTON_BASEBALLF_AIM_LEFT_LINK
DIBUTTON_BASEBALLF_AIM_RIGHT_LINK
DIBUTTON_BASEBALLF_BACK_LINK
DIBUTTON_BASEBALLF_DEVICE
DIBUTTON_BASEBALLF_FORWARD_LINK
DIBUTTON_BASEBALLF_PAUSE
DIBUTTON_BASEBALLF_SHIFTIN
DIBUTTON_BASEBALLF_SHIFTOUT

© 2002 Microsoft Corporation. All rights reserved.


Baseball Pitching

The DIVIRTUAL_SPORTS_BASEBALL_PITCH genre contains controls for a pitcher in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLP_LATERAL
DIAXIS_BASEBALLP_MOVE
DIBUTTON_BASEBALLP_BASE
DIBUTTON_BASEBALLP_FAKE
DIBUTTON_BASEBALLP_MENU
DIBUTTON_BASEBALLP_PITCH
DIBUTTON_BASEBALLP_SELECT
DIBUTTON_BASEBALLP_THROW

Priority 2 Controls
DIBUTTON_BASEBALLP_BACK_LINK
DIBUTTON_BASEBALLP_DEVICE
DIBUTTON_BASEBALLP_FORWARD_LINK
DIBUTTON_BASEBALLP_LEFT_LINK
DIBUTTON_BASEBALLP_LOOK
DIBUTTON_BASEBALLP_PAUSE
DIBUTTON_BASEBALLP_RIGHT_LINK
DIBUTTON_BASEBALLP_WALK

© 2002 Microsoft Corporation. All rights reserved.


Basketball Defense

The DIVIRTUAL_SPORTS_BASKETBALL_DEFENSE genre contains controls for defensive moves in a basketball game.

Priority 1 Controls
DIAXIS_BBALLD_LATERAL
DIAXIS_BBALLD_MOVE
DIBUTTON_BBALLD_BURST
DIBUTTON_BBALLD_FAKE
DIBUTTON_BBALLD_JUMP
DIBUTTON_BBALLD_MENU
DIBUTTON_BBALLD_PLAY
DIBUTTON_BBALLD_PLAYER
DIBUTTON_BBALLD_SPECIAL
DIBUTTON_BBALLD_STEAL

Priority 2 Controls
DIBUTTON_BBALLD_BACK_LINK
DIBUTTON_BBALLD_DEVICE
DIBUTTON_BBALLD_FORWARD_LINK
DIBUTTON_BBALLD_LEFT_LINK
DIBUTTON_BBALLD_PAUSE
DIBUTTON_BBALLD_RIGHT_LINK
DIBUTTON_BBALLD_SUBSTITUTE
DIBUTTON_BBALLD_TIMEOUT
DIHATSWITCH_BBALLD_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Basketball Offense

The DIVIRTUAL_SPORTS_BASKETBALL_OFFENSE genre contains controls for the player who has the ball in a basketball game.

Priority 1 Controls
DIAXIS_BBALLO_LATERAL
DIAXIS_BBALLO_MOVE
DIBUTTON_BBALLO_BURST
DIBUTTON_BBALLO_CALL
DIBUTTON_BBALLO_DUNK
DIBUTTON_BBALLO_FAKE
DIBUTTON_BBALLO_MENU
DIBUTTON_BBALLO_PASS
DIBUTTON_BBALLO_PLAYER
DIBUTTON_BBALLO_SHOOT
DIBUTTON_BBALLO_SPECIAL

Priority 2 Controls
DIBUTTON_BBALLO_BACK_LINK
DIBUTTON_BBALLO_DEVICE
DIBUTTON_BBALLO_FORWARD_LINK
DIBUTTON_BBALLO_JAB
DIBUTTON_BBALLO_LEFT_LINK
DIBUTTON_BBALLO_PAUSE
DIBUTTON_BBALLO_PLAY
DIBUTTON_BBALLO_POST
DIBUTTON_BBALLO_RIGHT_LINK
DIBUTTON_BBALLO_SCREEN
DIBUTTON_BBALLO_SUBSTITUTE
DIBUTTON_BBALLO_TIMEOUT
DIHATSWITCH_BBALLO_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Fishing

The DIVIRTUAL_SPORTS_FISHING genre contains controls for a sport-fishing simulation.

Priority 1 Controls
DIAXIS_FISHING_LATERAL
DIAXIS_FISHING_MOVE
DIBUTTON_FISHING_BAIT
DIBUTTON_FISHING_BINOCULAR
DIBUTTON_FISHING_CAST
DIBUTTON_FISHING_MAP
DIBUTTON_FISHING_MENU
DIBUTTON_FISHING_TYPE

Priority 2 Controls
DIAXIS_FISHING_ROTATE
DIBUTTON_FISHING_BACK_LINK
DIBUTTON_FISHING_CROUCH
DIBUTTON_FISHING_DEVICE
DIBUTTON_FISHING_DISPLAY
DIBUTTON_FISHING_FORWARD_LINK
DIBUTTON_FISHING_JUMP
DIBUTTON_FISHING_LEFT_LINK
DIBUTTON_FISHING_PAUSE
DIBUTTON_FISHING_RIGHT_LINK
DIBUTTON_FISHING_ROTATE_LEFT_LINK
DIBUTTON_FISHING_ROTATE_RIGHT_LINK
DIHATSWITCH_FISHING_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Football Defense

The DIVIRTUAL_SPORTS_FOOTBALL_DEFENSE genre contains controls for the defensive side in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLD_LATERAL
DIAXIS_FOOTBALLD_MOVE
DIBUTTON_FOOTBALLD_FAKE
DIBUTTON_FOOTBALLD_JUMP
DIBUTTON_FOOTBALLD_MENU
DIBUTTON_FOOTBALLD_PLAY
DIBUTTON_FOOTBALLD_SELECT
DIBUTTON_FOOTBALLD_SUPERTACKLE
DIBUTTON_FOOTBALLD_TACKLE

Priority 2 Controls
DIBUTTON_FOOTBALLD_AUDIBLE
DIBUTTON_FOOTBALLD_BACK_LINK
DIBUTTON_FOOTBALLD_BULLRUSH
DIBUTTON_FOOTBALLD_DEVICE
DIBUTTON_FOOTBALLD_FORWARD_LINK
DIBUTTON_FOOTBALLD_LEFT_LINK
DIBUTTON_FOOTBALLD_PAUSE
DIBUTTON_FOOTBALLD_RIGHT_LINK
DIBUTTON_FOOTBALLD_RIP
DIBUTTON_FOOTBALLD_SPIN
DIBUTTON_FOOTBALLD_SUBSTITUTE
DIBUTTON_FOOTBALLD_SWIM
DIBUTTON_FOOTBALLD_ZOOM

© 2002 Microsoft Corporation. All rights reserved.


Football Offense

The DIVIRTUAL_SPORTS_FOOTBALL_OFFENSE genre contains controls for the ball carrier in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLO_LATERAL
DIAXIS_FOOTBALLO_MOVE
DIBUTTON_FOOTBALLO_JUMP
DIBUTTON_FOOTBALLO_LEFTARM
DIBUTTON_FOOTBALLO_MENU
DIBUTTON_FOOTBALLO_RIGHTARM
DIBUTTON_FOOTBALLO_SPIN
DIBUTTON_FOOTBALLO_THROW

Priority 2 Controls
DIBUTTON_FOOTBALLO_BACK_LINK
DIBUTTON_FOOTBALLO_DEVICE
DIBUTTON_FOOTBALLO_DIVE
DIBUTTON_FOOTBALLO_FORWARD_LINK
DIBUTTON_FOOTBALLO_JUKE
DIBUTTON_FOOTBALLO_LEFT_LINK
DIBUTTON_FOOTBALLO_PAUSE
DIBUTTON_FOOTBALLO_RIGHT_LINK
DIBUTTON_FOOTBALLO_SHOULDER
DIBUTTON_FOOTBALLO_SUBSTITUTE
DIBUTTON_FOOTBALLO_TURBO
DIBUTTON_FOOTBALLO_ZOOM

© 2002 Microsoft Corporation. All rights reserved.


Football Play

The DIVIRTUAL_SPORTS_FOOTBALL_FIELD genre contains general controls for a North American football game.

Priority 1 Controls
DIBUTTON_FOOTBALLP_HELP
DIBUTTON_FOOTBALLP_MENU
DIBUTTON_FOOTBALLP_PLAY
DIBUTTON_FOOTBALLP_SELECT

Priority 2 Controls
DIBUTTON_FOOTBALLP_DEVICE
DIBUTTON_FOOTBALLP_PAUSE

© 2002 Microsoft Corporation. All rights reserved.


Football Quarterback

The DIVIRTUAL_SPORTS_FOOTBALL_QBCK genre contains controls for the quarterback in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLQ_LATERAL
DIAXIS_FOOTBALLQ_MOVE
DIBUTTON_FOOTBALLQ_FAKE
DIBUTTON_FOOTBALLQ_JUMP
DIBUTTON_FOOTBALLQ_MENU
DIBUTTON_FOOTBALLQ_PASS
DIBUTTON_FOOTBALLQ_SELECT
DIBUTTON_FOOTBALLQ_SLIDE
DIBUTTON_FOOTBALLQ_SNAP

Priority 2 Controls
DIBUTTON_FOOTBALLQ_AUDIBLE
DIBUTTON_FOOTBALLQ_BACK_LINK
DIBUTTON_FOOTBALLQ_DEVICE
DIBUTTON_FOOTBALLQ_FAKESNAP
DIBUTTON_FOOTBALLQ_FORWARD_LINK
DIBUTTON_FOOTBALLQ_LEFT_LINK
DIBUTTON_FOOTBALLQ_MOTION
DIBUTTON_FOOTBALLQ_PAUSE
DIBUTTON_FOOTBALLQ_RIGHT_LINK

© 2002 Microsoft Corporation. All rights reserved.


Golf

The DIVIRTUAL_SPORTS_GOLF genre contains controls for a golf game.

Priority 1 Controls
DIAXIS_GOLF_LATERAL
DIAXIS_GOLF_MOVE
DIBUTTON_GOLF_DOWN
DIBUTTON_GOLF_FLYBY
DIBUTTON_GOLF_MENU
DIBUTTON_GOLF_SELECT
DIBUTTON_GOLF_SWING
DIBUTTON_GOLF_TERRAIN
DIBUTTON_GOLF_UP

Priority 2 Controls
DIBUTTON_GOLF_BACK_LINK
DIBUTTON_GOLF_DEVICE
DIBUTTON_GOLF_FORWARD_LINK
DIBUTTON_GOLF_LEFT_LINK
DIBUTTON_GOLF_PAUSE
DIBUTTON_GOLF_RIGHT_LINK
DIBUTTON_GOLF_SUBSTITUTE
DIBUTTON_GOLF_TIMEOUT
DIBUTTON_GOLF_ZOOM
DIHATSWITCH_GOLF_SCROLL

© 2002 Microsoft Corporation. All rights reserved.


Hockey Defense

The DIVIRTUAL_SPORTS_HOCKEY_DEFENSE genre contains controls for defensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYD_LATERAL
DIAXIS_HOCKEYD_MOVE
DIBUTTON_HOCKEYD_BLOCK
DIBUTTON_HOCKEYD_BURST
DIBUTTON_HOCKEYD_FAKE
DIBUTTON_HOCKEYD_MENU
DIBUTTON_HOCKEYD_PLAYER
DIBUTTON_HOCKEYD_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYD_BACK_LINK
DIBUTTON_HOCKEYD_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYD_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYD_STRATEGY
DIBUTTON_HOCKEYD_SUBSTITUTE
DIBUTTON_HOCKEYD_TIMEOUT
DIBUTTON_HOCKEYD_ZOOM
DIHATSWITCH_HOCKEYD_SCROLL

© 2002 Microsoft Corporation. All rights reserved.


Hockey Goalie

The DIVIRTUAL_SPORTS_HOCKEY_GOALIE genre contains controls for a goalkeeper in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYG_LATERAL
DIAXIS_HOCKEYG_MOVE
DIBUTTON_HOCKEYG_BLOCK
DIBUTTON_HOCKEYG_MENU
DIBUTTON_HOCKEYG_PASS
DIBUTTON_HOCKEYG_POKE
DIBUTTON_HOCKEYG_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYG_BACK_LINK
DIBUTTON_HOCKEYG_DEVICE
DIBUTTON_HOCKEYG_FORWARD_LINK
DIBUTTON_HOCKEYG_LEFT_LINK
DIBUTTON_HOCKEYG_PAUSE
DIBUTTON_HOCKEYG_RIGHT_LINK
DIBUTTON_HOCKEYG_STRATEGY
DIBUTTON_HOCKEYG_SUBSTITUTE
DIBUTTON_HOCKEYG_TIMEOUT
DIBUTTON_HOCKEYG_ZOOM
DIHATSWITCH_HOCKEYG_SCROLL

© 2002 Microsoft Corporation. All rights reserved.


Hockey Offense

The DIVIRTUAL_SPORTS_HOCKEY_OFFENSE genre contains controls for offensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYO_LATERAL
DIAXIS_HOCKEYO_MOVE
DIBUTTON_HOCKEYO_BURST
DIBUTTON_HOCKEYO_FAKE
DIBUTTON_HOCKEYO_MENU
DIBUTTON_HOCKEYO_PASS
DIBUTTON_HOCKEYO_SHOOT
DIBUTTON_HOCKEYO_SPECIAL

Priority 2 Controls
DIBUTTON_HOCKEYO_BACK_LINK
DIBUTTON_HOCKEYO_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYO_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYO_STRATEGY
DIBUTTON_HOCKEYO_SUBSTITUTE
DIBUTTON_HOCKEYO_TIMEOUT
DIBUTTON_HOCKEYO_ZOOM
DIHATSWITCH_HOCKEYO_SCROLL

© 2002 Microsoft Corporation. All rights reserved.


Hunting

The DIVIRTUAL_SPORTS_HUNTING genre contains controls for a hunting simulation.

Priority 1 Controls
DIAXIS_HUNTING_LATERAL
DIAXIS_HUNTING_MOVE
DIBUTTON_HUNTING_AIM
DIBUTTON_HUNTING_BINOCULAR
DIBUTTON_HUNTING_CALL
DIBUTTON_HUNTING_FIRE
DIBUTTON_HUNTING_MAP
DIBUTTON_HUNTING_MENU
DIBUTTON_HUNTING_SPECIAL
DIBUTTON_HUNTING_WEAPON

Priority 2 Controls
DIAXIS_HUNTING_ROTATE
DIBUTTON_HUNTING_BACK_LINK
DIBUTTON_HUNTING_CROUCH
DIBUTTON_HUNTING_DEVICE
DIBUTTON_HUNTING_DISPLAY
DIBUTTON_HUNTING_FIRESECONDARY
DIBUTTON_HUNTING_FORWARD_LINK
DIBUTTON_HUNTING_JUMP
DIBUTTON_HUNTING_LEFT_LINK
DIBUTTON_HUNTING_PAUSE
DIBUTTON_HUNTING_RIGHT_LINK
DIBUTTON_HUNTING_ROTATE_LEFT_LINK
DIBUTTON_HUNTING_ROTATE_RIGHT_LINK
DIHATSWITCH_HUNTING_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Mountain Biking

The DIVIRTUAL_SPORTS_BIKING_MOUNTAIN contains controls for a mountain-bike game.

Priority 1 Controls
DIAXIS_BIKINGM_PEDAL
DIAXIS_BIKINGM_TURN
DIBUTTON_BIKINGM_CAMERA
DIBUTTON_BIKINGM_JUMP
DIBUTTON_BIKINGM_MENU
DIBUTTON_BIKINGM_SELECT
DIBUTTON_BIKINGM_SPECIAL1
DIBUTTON_BIKINGM_SPECIAL2

Priority 2 Controls
DIAXIS_BIKINGM_BRAKE
DIBUTTON_BIKINGM_BRAKE_BUTTON_LINK
DIBUTTON_BIKINGM_DEVICE
DIBUTTON_BIKINGM_FASTER_LINK
DIBUTTON_BIKINGM_LEFT_LINK
DIBUTTON_BIKINGM_PAUSE
DIBUTTON_BIKINGM_RIGHT_LINK
DIBUTTON_BIKINGM_SLOWER_LINK
DIBUTTON_BIKINGM_ZOOM
DIHATSWITCH_BIKINGM_SCROLL

© 2002 Microsoft Corporation. All rights reserved.


Racquet

The DIVIRTUAL_SPORTS_RACQUET genre includes racquet games such as tennis, table tennis, and squash.

Priority 1 Controls
DIAXIS_RACQUET_LATERAL
DIAXIS_RACQUET_MOVE
DIBUTTON_RACQUET_BACKSWING
DIBUTTON_RACQUET_MENU
DIBUTTON_RACQUET_SELECT
DIBUTTON_RACQUET_SMASH
DIBUTTON_RACQUET_SPECIAL
DIBUTTON_RACQUET_SWING

Priority 2 Controls
DIBUTTON_RACQUET_BACK_LINK
DIBUTTON_RACQUET_DEVICE
DIBUTTON_RACQUET_FORWARD_LINK
DIBUTTON_RACQUET_LEFT_LINK
DIBUTTON_RACQUET_PAUSE
DIBUTTON_RACQUET_RIGHT_LINK
DIBUTTON_RACQUET_SUBSTITUTE
DIBUTTON_RACQUET_TIMEOUT
DIHATSWITCH_RACQUET_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Skiing

The DIVIRTUAL_SPORTS_SKIING contains controls for skiing games as well as for similar sports simulations such as snowboarding and skateboarding.

Priority 1 Controls
DIAXIS_SKIING_SPEED
DIAXIS_SKIING_TURN
DIBUTTON_SKIING_CAMERA
DIBUTTON_SKIING_CROUCH
DIBUTTON_SKIING_JUMP
DIBUTTON_SKIING_MENU
DIBUTTON_SKIING_SELECT
DIBUTTON_SKIING_SPECIAL1
DIBUTTON_SKIING_SPECIAL2

Priority 2 Controls
DIBUTTON_SKIING_DEVICE
DIBUTTON_SKIING_FASTER_LINK
DIBUTTON_SKIING_LEFT_LINK
DIBUTTON_SKIING_PAUSE
DIBUTTON_SKIING_RIGHT_LINK
DIBUTTON_SKIING_SLOWER_LINK
DIBUTTON_SKIING_ZOOM
DIHATSWITCH_SKIING_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Soccer Defense

The DIVIRTUAL_SPORTS_SOCCER_DEFENSE contains controls for defensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERD_LATERAL
DIAXIS_SOCCERD_MOVE
DIBUTTON_SOCCERD_BLOCK
DIBUTTON_SOCCERD_FAKE
DIBUTTON_SOCCERD_MENU
DIBUTTON_SOCCERD_PLAYER
DIBUTTON_SOCCERD_SELECT
DIBUTTON_SOCCERD_SLIDE
DIBUTTON_SOCCERD_SPECIAL
DIBUTTON_SOCCERD_STEAL

Priority 2 Controls
DIBUTTON_SOCCERD_BACK_LINK
DIBUTTON_SOCCERD_CLEAR
DIBUTTON_SOCCERD_DEVICE
DIBUTTON_SOCCERD_FORWARD_LINK
DIBUTTON_SOCCERD_FOUL
DIBUTTON_SOCCERD_GOALIECHARGE
DIBUTTON_SOCCERD_HEAD
DIBUTTON_SOCCERD_LEFT_LINK
DIBUTTON_SOCCERD_PAUSE
DIBUTTON_SOCCERD_RIGHT_LINK
DIBUTTON_SOCCERD_SUBSTITUTE
DIHATSWITCH_SOCCERD_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Soccer Offense

The DIVIRTUAL_SPORTS_SOCCER_OFFENSE contains controls for offensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERO_BEND
DIAXIS_SOCCERO_LATERAL
DIAXIS_SOCCERO_MOVE
DIBUTTON_SOCCERO_FAKE
DIBUTTON_SOCCERO_MENU
DIBUTTON_SOCCERO_PASS
DIBUTTON_SOCCERO_PLAYER
DIBUTTON_SOCCERO_SELECT
DIBUTTON_SOCCERO_SHOOT
DIBUTTON_SOCCERO_SPECIAL1

Priority 2 Controls
DIBUTTON_SOCCERO_BACK_LINK
DIBUTTON_SOCCERO_CONTROL
DIBUTTON_SOCCERO_DEVICE
DIBUTTON_SOCCERO_FORWARD_LINK
DIBUTTON_SOCCERO_HEAD
DIBUTTON_SOCCERO_LEFT_LINK
DIBUTTON_SOCCERO_PASSTHRU
DIBUTTON_SOCCERO_PAUSE
DIBUTTON_SOCCERO_RIGHT_LINK
DIBUTTON_SOCCERO_SHOOTHIGH
DIBUTTON_SOCCERO_SHOOTLOW
DIBUTTON_SOCCERO_SPRINT
DIBUTTON_SOCCERO_SUBSTITUTE
DIHATSWITCH_SOCCERO_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Strategy Genres

The following genres contain controls for strategy, role-playing, and adventure games.

Constants

  • Role-Playing
  • Turn-Based

© 2002 Microsoft Corporation. All rights reserved.


Role-Playing

The DIVIRTUAL_STRATEGY_ROLEPLAYING genre contains controls for a role-playing or adventure game in which navigation, problem-solving, and fighting with weapons and magic are common activities.

Priority 1 Controls
DIAXIS_STRATEGYR_LATERAL
DIAXIS_STRATEGYR_MOVE
DIBUTTON_STRATEGYR_APPLY
DIBUTTON_STRATEGYR_ATTACK
DIBUTTON_STRATEGYR_CAST
DIBUTTON_STRATEGYR_CROUCH
DIBUTTON_STRATEGYR_GET
DIBUTTON_STRATEGYR_JUMP
DIBUTTON_STRATEGYR_MENU
DIBUTTON_STRATEGYR_SELECT

Priority 2 Controls
DIAXIS_STRATEGYR_ROTATE
DIBUTTON_STRATEGYR_BACK_LINK
DIBUTTON_STRATEGYR_DEVICE
DIBUTTON_STRATEGYR_DISPLAY
DIBUTTON_STRATEGYR_FORWARD_LINK
DIBUTTON_STRATEGYR_LEFT_LINK
DIBUTTON_STRATEGYR_MAP
DIBUTTON_STRATEGYR_PAUSE
DIBUTTON_STRATEGYR_RIGHT_LINK
DIBUTTON_STRATEGYR_ROTATE_LEFT_LINK
DIBUTTON_STRATEGYR_ROTATE_RIGHT_LINK
DIHATSWITCH_STRATEGYR_GLANCE

© 2002 Microsoft Corporation. All rights reserved.


Turn-Based

The DIVIRTUAL_STRATEGY_TURN genre contains controls for a turn-based strategy game.

Priority 1 Controls
DIAXIS_STRATEGYT_LATERAL
DIAXIS_STRATEGYT_MOVE
DIBUTTON_STRATEGYT_APPLY
DIBUTTON_STRATEGYT_INSTRUCT
DIBUTTON_STRATEGYT_MENU
DIBUTTON_STRATEGYT_SELECT
DIBUTTON_STRATEGYT_TEAM
DIBUTTON_STRATEGYT_TURN

Priority 2 Controls
DIBUTTON_STRATEGYT_BACK_LINK
DIBUTTON_STRATEGYT_DEVICE
DIBUTTON_STRATEGYT_DISPLAY
DIBUTTON_STRATEGYT_FORWARD_LINK
DIBUTTON_STRATEGYT_LEFT_LINK
DIBUTTON_STRATEGYT_MAP
DIBUTTON_STRATEGYT_PAUSE
DIBUTTON_STRATEGYT_RIGHT_LINK
DIBUTTON_STRATEGYT_ZOOM

© 2002 Microsoft Corporation. All rights reserved.


Any-Control Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to any matching control on the device.

Syntax

typedef enum {
    DIAXIS_ANY_1,
    DIAXIS_ANY_2,
    DIAXIS_ANY_3,
    DIAXIS_ANY_3,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_B_1,
    DIAXIS_ANY_B_2,
    DIAXIS_ANY_C_1,
    DIAXIS_ANY_C_2,
    DIAXIS_ANY_R_1,
    DIAXIS_ANY_R_2,
    DIAXIS_ANY_S_1,
    DIAXIS_ANY_S_2,
    DIAXIS_ANY_U_1,
    DIAXIS_ANY_U_2,
    DIAXIS_ANY_V_1,
    DIAXIS_ANY_V_2,
    DIAXIS_ANY_X_1,
    DIAXIS_ANY_X_2,
    DIAXIS_ANY_Y_1,
    DIAXIS_ANY_Y_2,
    DIAXIS_ANY_Z_1,
    DIAXIS_ANY_Z_2,
    DIBUTTON_ANY,
    DIPOV_ANY_1,
    DIPOV_ANY_2,
    DIPOV_ANY_3,
    DIPOV_ANY_4
} Any-Control;

Constants

DIAXIS_ANY_1

Any axis

DIAXIS_ANY_2

Any axis

DIAXIS_ANY_3

Any axis

DIAXIS_ANY_3

Any axis

DIAXIS_ANY_A_1

Any accelerator

DIAXIS_ANY_A_1

Any accelerator

DIAXIS_ANY_B_1

Any brake

DIAXIS_ANY_B_2

Any brake

DIAXIS_ANY_C_1

Any clutch

DIAXIS_ANY_C_2

Any clutch

DIAXIS_ANY_R_1

Any r-axis

DIAXIS_ANY_R_2

Any r-axis

DIAXIS_ANY_S_1

Any s-axis

DIAXIS_ANY_S_2

Any s-axis

DIAXIS_ANY_U_1

Any u-axis

DIAXIS_ANY_U_2

Any u-axis

DIAXIS_ANY_V_1

Any v-axis

DIAXIS_ANY_V_2

Any v-axis

DIAXIS_ANY_X_1

Any x-axis

DIAXIS_ANY_X_2

Any x-axis

DIAXIS_ANY_Y_1

Any y-axis

DIAXIS_ANY_Y_2

Any y-axis

DIAXIS_ANY_Z_1

Any z-axis

DIAXIS_ANY_Z_2

Any z-axis

DIBUTTON_ANY

Any button. This is a constant macro that takes a button number as its argument. For example, DIBUTTON_ANY(3).

DIPOV_ANY_1

Any point-of-view controller

DIPOV_ANY_2

Any point-of-view controller

DIPOV_ANY_3

Any point-of-view controller

DIPOV_ANY_4

Any point-of-view controller

Remarks

These constants can be used to map an application action to a virtual control that is not defined in a genre. Such actions are mapped after genre-specific actions. If the mapper has already mapped all matching controls to genre-specific actions, the any-control action is left unmapped.

Any-control actions are treated with equal priority. If a device has one x-axis and the action array specifies DIAXIS_ANY_1 and DIAXIS_ANY_X_1, the action mapped to the x-axis is the one that appears first in the action array.

DIBUTTON_ANY(x) can accept any value from 0 through 255. Do not use an index more than once. For instance, the following set of DIACTION structures would be invalid.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",},
{eB_VOLUP,   DIBUTTON_ANY(0), 0, "Volume Up",   },
{eB_VOLDOWN, DIBUTTON_ANY(0), 0, "Volume Down", },

The correct method uses different indexes, as shown below.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",}
{eB_VOLUP,   DIBUTTON_ANY(1), 0, "Volume Up",   }
{eB_VOLDOWN, DIBUTTON_ANY(2), 0, "Volume Down", }

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Voice Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a channel on Microsoft® DirectPlay® voice device.

Syntax

typedef enum {
    DIVOICE_CHANNEL1,
    DIVOICE_CHANNEL2,
    DIVOICE_CHANNEL3,
    DIVOICE_CHANNEL4,
    DIVOICE_CHANNEL5,
    DIVOICE_CHANNEL6,
    DIVOICE_CHANNEL7,
    DIVOICE_CHANNEL8,
    DIVOICE_ALL,
    DIVOICE_TEAM,
    DIVOICE_PLAYBACKMUTE,
    DIVOICE_RECORDMUTE,
    DIVOICE_TRANSMIT,
    DIVOICE_VOICECOMMAND
} DirectPlay Voice Mapping;

Constants

DIVOICE_CHANNEL1

DIVOICE_CHANNEL2

DIVOICE_CHANNEL3

DIVOICE_CHANNEL4

DIVOICE_CHANNEL5

DIVOICE_CHANNEL6

DIVOICE_CHANNEL7

DIVOICE_CHANNEL8

DIVOICE_ALL

DIVOICE_TEAM

DIVOICE_PLAYBACKMUTE

DIVOICE_RECORDMUTE

DIVOICE_TRANSMIT

DIVOICE_VOICECOMMAND

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


Keyboard Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical key.

Syntax

typedef enum {
    DIKEYBOARD_0,
    DIKEYBOARD_1,
    DIKEYBOARD_2,
    DIKEYBOARD_3,
    DIKEYBOARD_4,
    DIKEYBOARD_5,
    DIKEYBOARD_6,
    DIKEYBOARD_7,
    DIKEYBOARD_8,
    DIKEYBOARD_9,
    DIKEYBOARD_A,
    DIKEYBOARD_ABNT_C1,
    DIKEYBOARD_ABNT_C2,
    DIKEYBOARD_ADD,
    DIKEYBOARD_APOSTROPHE,
    DIKEYBOARD_APPS,
    DIKEYBOARD_AT,
    DIKEYBOARD_AX,
    DIKEYBOARD_B,
    DIKEYBOARD_BACK,
    DIKEYBOARD_BACKSLASH,
    DIKEYBOARD_C,
    DIKEYBOARD_CALCULATOR,
    DIKEYBOARD_CAPITAL,
    DIKEYBOARD_COLON,
    DIKEYBOARD_COMMA,
    DIKEYBOARD_CONVERT,
    DIKEYBOARD_D,
    DIKEYBOARD_DECIMAL,
    DIKEYBOARD_DELETE,
    DIKEYBOARD_DIVIDE,
    DIKEYBOARD_DOWN,
    DIKEYBOARD_E,
    DIKEYBOARD_END,
    DIKEYBOARD_EQUALS,
    DIKEYBOARD_ESCAPE,
    DIKEYBOARD_F,
    DIKEYBOARD_F1,
    DIKEYBOARD_F2,
    DIKEYBOARD_F3,
    DIKEYBOARD_F4,
    DIKEYBOARD_F5,
    DIKEYBOARD_F6,
    DIKEYBOARD_F7,
    DIKEYBOARD_F8,
    DIKEYBOARD_F9,
    DIKEYBOARD_F10,
    DIKEYBOARD_F11,
    DIKEYBOARD_F12,
    DIKEYBOARD_F13,
    DIKEYBOARD_F14,
    DIKEYBOARD_F15,
    DIKEYBOARD_G,
    DIKEYBOARD_GRAVE,
    DIKEYBOARD_H,
    DIKEYBOARD_HOME,
    DIKEYBOARD_I,
    DIKEYBOARD_INSERT,
    DIKEYBOARD_J,
    DIKEYBOARD_K,
    DIKEYBOARD_KANA,
    DIKEYBOARD_KANJI,
    DIKEYBOARD_L,
    DIKEYBOARD_LBRACKET,
    DIKEYBOARD_LCONTROL,
    DIKEYBOARD_LEFT,
    DIKEYBOARD_LMENU,
    DIKEYBOARD_LSHIFT,
    DIKEYBOARD_LWIN,
    DIKEYBOARD_M,
    DIKEYBOARD_MAIL,
    DIKEYBOARD_MEDIASELECT,
    DIKEYBOARD_MEDIASTOP,
    DIKEYBOARD_MINUS,
    DIKEYBOARD_MULTIPLY,
    DIKEYBOARD_MUTE,
    DIKEYBOARD_MYCOMPUTER,
    DIKEYBOARD_N,
    DIKEYBOARD_NEXT,
    DIKEYBOARD_NEXTTRACK,
    DIKEYBOARD_NOCONVERT,
    DIKEYBOARD_NUMLOCK,
    DIKEYBOARD_NUMPAD0,
    DIKEYBOARD_NUMPAD1,
    DIKEYBOARD_NUMPAD2,
    DIKEYBOARD_NUMPAD3,
    DIKEYBOARD_NUMPAD4,
    DIKEYBOARD_NUMPAD5,
    DIKEYBOARD_NUMPAD6,
    DIKEYBOARD_NUMPAD7,
    DIKEYBOARD_NUMPAD8,
    DIKEYBOARD_NUMPAD9,
    DIKEYBOARD_NUMPADCOMMA,
    DIKEYBOARD_NUMPADENTER,
    DIKEYBOARD_NUMPADEQUALS,
    DIKEYBOARD_O,
    DIKEYBOARD_OEM_102,
    DIKEYBOARD_P,
    DIKEYBOARD_PAUSE,
    DIKEYBOARD_PERIOD,
    DIKEYBOARD_PLAYPAUSE,
    DIKEYBOARD_POWER,
    DIKEYBOARD_PREVTRACK,
    DIKEYBOARD_PRIOR,
    DIKEYBOARD_Q,
    DIKEYBOARD_R,
    DIKEYBOARD_RBRACKET,
    DIKEYBOARD_RCONTROL,
    DIKEYBOARD_RETURN,
    DIKEYBOARD_RIGHT,
    DIKEYBOARD_RMENU,
    DIKEYBOARD_RSHIFT,
    DIKEYBOARD_RWIN,
    DIKEYBOARD_S,
    DIKEYBOARD_SCROLL,
    DIKEYBOARD_SEMICOLON,
    DIKEYBOARD_SLASH,
    DIKEYBOARD_SLEEP,
    DIKEYBOARD_SPACE,
    DIKEYBOARD_STOP,
    DIKEYBOARD_SUBTRACT,
    DIKEYBOARD_SYSRQ,
    DIKEYBOARD_T,
    DIKEYBOARD_TAB,
    DIKEYBOARD_U,
    DIKEYBOARD_UNDERLINE,
    DIKEYBOARD_UNLABELED,
    DIKEYBOARD_UP,
    DIKEYBOARD_V,
    DIKEYBOARD_VOLUMEDOWN,
    DIKEYBOARD_VOLUMEUP,
    DIKEYBOARD_W,
    DIKEYBOARD_WAKE,
    DIKEYBOARD_WEBBACK,
    DIKEYBOARD_WEBFAVORITES,
    DIKEYBOARD_WEBFORWARD,
    DIKEYBOARD_WEBHOME,
    DIKEYBOARD_WEBREFRESH,
    DIKEYBOARD_WEBSEARCH,
    DIKEYBOARD_WEBSTOP,
    DIKEYBOARD_X,
    DIKEYBOARD_Y,
    DIKEYBOARD_YEN,
    DIKEYBOARD_Z
} Keyboard Mapping;

Constants

DIKEYBOARD_0

On main keyboard

DIKEYBOARD_1

On main keyboard

DIKEYBOARD_2

On main keyboard

DIKEYBOARD_3

On main keyboard

DIKEYBOARD_4

On main keyboard

DIKEYBOARD_5

On main keyboard

DIKEYBOARD_6

On main keyboard

DIKEYBOARD_7

On main keyboard

DIKEYBOARD_8

On main keyboard

DIKEYBOARD_9

On main keyboard

DIKEYBOARD_A

DIKEYBOARD_ABNT_C1

On numeric pad of Brazilian keyboards

DIKEYBOARD_ABNT_C2

On numeric pad of Brazilian keyboards

DIKEYBOARD_ADD

PLUS SIGN (+) on numeric keypad

DIKEYBOARD_APOSTROPHE

DIKEYBOARD_APPS

Application key

DIKEYBOARD_AT

On Japanese keyboard

DIKEYBOARD_AX

On Japanese keyboard

DIKEYBOARD_B

DIKEYBOARD_BACK

BACKSPACE

DIKEYBOARD_BACKSLASH

DIKEYBOARD_C

DIKEYBOARD_CALCULATOR

DIKEYBOARD_CAPITAL

CAPS LOCK

DIKEYBOARD_COLON

On Japanese keyboard

DIKEYBOARD_COMMA

DIKEYBOARD_CONVERT

On Japanese keyboard

DIKEYBOARD_D

DIKEYBOARD_DECIMAL

PERIOD (decimal point) on numeric keypad

DIKEYBOARD_DELETE

DIKEYBOARD_DIVIDE

FORWARD SLASH (/) on numeric keypad

DIKEYBOARD_DOWN

DOWN ARROW

DIKEYBOARD_E

DIKEYBOARD_END

DIKEYBOARD_EQUALS

On main keyboard

DIKEYBOARD_ESCAPE

DIKEYBOARD_F

DIKEYBOARD_F1

DIKEYBOARD_F2

DIKEYBOARD_F3

DIKEYBOARD_F4

DIKEYBOARD_F5

DIKEYBOARD_F6

DIKEYBOARD_F7

DIKEYBOARD_F8

DIKEYBOARD_F9

DIKEYBOARD_F10

DIKEYBOARD_F11

DIKEYBOARD_F12

DIKEYBOARD_F13

On NEC PC-98 Japanese keyboard

DIKEYBOARD_F14

On NEC PC-98 Japanese keyboard

DIKEYBOARD_F15

On NEC PC-98 Japanese keyboard

DIKEYBOARD_G

DIKEYBOARD_GRAVE

GRAVE ACCENT (`)

DIKEYBOARD_H

DIKEYBOARD_HOME

DIKEYBOARD_I

DIKEYBOARD_INSERT

DIKEYBOARD_J

DIKEYBOARD_K

DIKEYBOARD_KANA

On Japanese keyboard

DIKEYBOARD_KANJI

On Japanese keyboard

DIKEYBOARD_L

DIKEYBOARD_LBRACKET

Left SQUARE BRACKET ([)

DIKEYBOARD_LCONTROL

Left CTRL

DIKEYBOARD_LEFT

LEFT ARROW

DIKEYBOARD_LMENU

Left ALT

DIKEYBOARD_LSHIFT

Left SHIFT

DIKEYBOARD_LWIN

Left Microsoft® Windows® logo key

DIKEYBOARD_M

DIKEYBOARD_MAIL

DIKEYBOARD_MEDIASELECT

MEDIA SELECT key, which displays a selection of supported media players on the system

DIKEYBOARD_MEDIASTOP

DIKEYBOARD_MINUS

On main keyboard

DIKEYBOARD_MULTIPLY

ASTERISK (*) on numeric keypad

DIKEYBOARD_MUTE

DIKEYBOARD_MYCOMPUTER

DIKEYBOARD_N

DIKEYBOARD_NEXT

PAGE DOWN

DIKEYBOARD_NEXTTRACK

NEXT TRACK

DIKEYBOARD_NOCONVERT

On Japanese keyboard

DIKEYBOARD_NUMLOCK

DIKEYBOARD_NUMPAD0

DIKEYBOARD_NUMPAD1

DIKEYBOARD_NUMPAD2

DIKEYBOARD_NUMPAD3

DIKEYBOARD_NUMPAD4

DIKEYBOARD_NUMPAD5

DIKEYBOARD_NUMPAD6

DIKEYBOARD_NUMPAD7

DIKEYBOARD_NUMPAD8

DIKEYBOARD_NUMPAD9

DIKEYBOARD_NUMPADCOMMA

On numeric keypad of NEC PC-98 Japanese keyboard

DIKEYBOARD_NUMPADENTER

DIKEYBOARD_NUMPADEQUALS

On numeric keypad of NEC PC-98 Japanese keyboard

DIKEYBOARD_O

DIKEYBOARD_OEM_102

On British and German keyboards

DIKEYBOARD_P

DIKEYBOARD_PAUSE

DIKEYBOARD_PERIOD

On main keyboard

DIKEYBOARD_PLAYPAUSE

DIKEYBOARD_POWER

DIKEYBOARD_PREVTRACK

PREVIOUS TRACK; CIRCUMFLEX (^) on Japanese keyboard

DIKEYBOARD_PRIOR

PAGE UP

DIKEYBOARD_Q

DIKEYBOARD_R

DIKEYBOARD_RBRACKET

Right SQUARE BRACKET (])

DIKEYBOARD_RCONTROL

Right CTRL

DIKEYBOARD_RETURN

ENTER on main keyboard

DIKEYBOARD_RIGHT

RIGHT ARROW

DIKEYBOARD_RMENU

Right ALT

DIKEYBOARD_RSHIFT

Right SHIFT

DIKEYBOARD_RWIN

Right Windows logo key

DIKEYBOARD_S

DIKEYBOARD_SCROLL

SCROLL LOCK

DIKEYBOARD_SEMICOLON

DIKEYBOARD_SLASH

FORWARD SLASH (/) on main keyboard

DIKEYBOARD_SLEEP

DIKEYBOARD_SPACE

SPACEBAR

DIKEYBOARD_STOP

On NEC PC-98 Japanese keyboard

DIKEYBOARD_SUBTRACT

MINUS SIGN (-) on numeric keypad

DIKEYBOARD_SYSRQ

DIKEYBOARD_T

DIKEYBOARD_TAB

DIKEYBOARD_U

DIKEYBOARD_UNDERLINE

On NEC PC-98 Japanese keyboard

DIKEYBOARD_UNLABELED

On Japanese keyboard

DIKEYBOARD_UP

UP ARROW

DIKEYBOARD_V

DIKEYBOARD_VOLUMEDOWN

DIKEYBOARD_VOLUMEUP

DIKEYBOARD_W

DIKEYBOARD_WAKE

DIKEYBOARD_WEBBACK

DIKEYBOARD_WEBFAVORITES

Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list

DIKEYBOARD_WEBFORWARD

DIKEYBOARD_WEBHOME

DIKEYBOARD_WEBREFRESH

DIKEYBOARD_WEBSEARCH

DIKEYBOARD_WEBSTOP

DIKEYBOARD_X

DIKEYBOARD_Y

DIKEYBOARD_YEN

On Japanese keyboard

DIKEYBOARD_Z

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


Mouse Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical axis or button on a mouse.

Syntax

typedef enum {
    DIMOUSE_BUTTON0,
    DIMOUSE_BUTTON1,
    DIMOUSE_BUTTON2,
    DIMOUSE_BUTTON3,
    DIMOUSE_BUTTON4,
    DIMOUSE_BUTTON5,
    DIMOUSE_BUTTON6,
    DIMOUSE_BUTTON7,
    DIMOUSE_WHEEL,
    DIMOUSE_XAXIS,
    DIMOUSE_YAXIS,
    DIMOUSE_XAXISAB,
    DIMOUSE_YAXISAB
} Mouse Mapping;

Constants

DIMOUSE_BUTTON0

DIMOUSE_BUTTON1

DIMOUSE_BUTTON2

DIMOUSE_BUTTON3

DIMOUSE_BUTTON4

DIMOUSE_BUTTON5

DIMOUSE_BUTTON6

DIMOUSE_BUTTON7

DIMOUSE_WHEEL

DIMOUSE_XAXIS

DIMOUSE_YAXIS

DIMOUSE_XAXISAB

DIMOUSE_YAXISAB

Remarks

DIMOUSE_XAXISAB and DIMOUSE_YAXISAB represent the x-axis and y-axis on a mouse that returns absolute rather than relative axis data.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


Return Values Enumerated Type

The list below contains the HRESULT values that can be returned by Microsoft® DirectInput® methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the error values each method or function can return, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

Syntax

typedef enum {
    DI_BUFFEROVERFLOW,
    DI_DOWNLOADSKIPPED,
    DI_EFFECTRESTARTED,
    DI_NOEFFECT,
    DI_NOTATTACHED,
    DI_OK,
    DI_POLLEDDEVICE,
    DI_PROPNOEFFECT,
    DI_SETTINGSNOTSAVED,
    DI_TRUNCATED,
    DI_TRUNCATEDANDRESTARTED,
    DI_WRITEPROTECT,
    DIERR_ACQUIRED,
    DIERR_ALREADYINITIALIZED,
    DIERR_BADDRIVERVER,
    DIERR_BETADIRECTINPUTVERSION,
    DIERR_DEVICEFULL,
    DIERR_DEVICENOTREG,
    DIERR_EFFECTPLAYING,
    DIERR_GENERIC,
    DIERR_HANDLEEXISTS,
    DIERR_HASEFFECTS,
    DIERR_INCOMPLETEEFFECT,
    DIERR_INPUTLOST,
    DIERR_INVALIDPARAM,
    DIERR_MAPFILEFAIL,
    DIERR_MOREDATA,
    DIERR_NOAGGREGATION,
    DIERR_NOINTERFACE,
    DIERR_NOTACQUIRED,
    DIERR_NOTBUFFERED,
    DIERR_NOTDOWNLOADED,
    DIERR_NOTEXCLUSIVEACQUIRED,
    DIERR_NOTFOUND,
    DIERR_NOTINITIALIZED,
    DIERR_OBJECTNOTFOUND,
    DIERR_OLDDIRECTINPUTVERSION,
    DIERR_OTHERAPPHASPRIO,
    DIERR_OUTOFMEMORY,
    DIERR_READONLY,
    DIERR_REPORTFULL,
    DIERR_UNPLUGGED,
    DIERR_UNSUPPORTED,
    E_HANDLE,
    E_PENDING,
    E_POINTER
} Return Values;

Constants

DI_BUFFEROVERFLOW

The device buffer overflowed and some input was lost. This value is equal to the S_FALSE standard COM return value.

DI_DOWNLOADSKIPPED

The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.

DI_EFFECTRESTARTED

The effect was stopped, the parameters were updated, and the effect was restarted.

DI_NOEFFECT

The operation had no effect. This value is equal to the S_FALSE standard Component Object Model (COM) return value.

DI_NOTATTACHED

The device exists but is not currently attached. This value is equal to the S_FALSE standard COM return value.

DI_OK

The operation completed successfully. This value is equal to the S_OK standard COM return value.

DI_POLLEDDEVICE

The device is a polled device. As a result, device buffering does not collect any data and event notifications is not signaled until the IDirectInputDevice8::Poll method is called.

DI_PROPNOEFFECT

The change in device properties had no effect. This value is equal to the S_FALSE standard COM return value.

DI_SETTINGSNOTSAVED

The action map was applied to the device, but the settings could not be saved.

DI_TRUNCATED

The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.

DI_TRUNCATEDANDRESTARTED

Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.

DI_WRITEPROTECT

A SUCCESS code indicating that settings cannot be modified.

DIERR_ACQUIRED

The operation cannot be performed while the device is acquired.

DIERR_ALREADYINITIALIZED

This object is already initialized

DIERR_BADDRIVERVER

The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.

DIERR_BETADIRECTINPUTVERSION

The application was written for an unsupported prerelease version of DirectInput.

DIERR_DEVICEFULL

The device is full.

DIERR_DEVICENOTREG

The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.

DIERR_EFFECTPLAYING

The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.

DIERR_GENERIC

An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.

DIERR_HANDLEEXISTS

The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.

DIERR_HASEFFECTS

The device cannot be reinitialized because effects are attached to it.

DIERR_INCOMPLETEEFFECT

The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.

DIERR_INPUTLOST

Access to the input device has been lost. It must be reacquired.

DIERR_INVALIDPARAM

An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.

DIERR_MAPFILEFAIL

An error has occurred either reading the vendor-supplied action-mapping file for the device or reading or writing the user configuration mapping file for the device.

DIERR_MOREDATA

Not all the requested information fit into the buffer.

DIERR_NOAGGREGATION

This object does not support aggregation.

DIERR_NOINTERFACE

The object does not support the specified interface. This value is equal to the E_NOINTERFACE standard COM return value.

DIERR_NOTACQUIRED

The operation cannot be performed unless the device is acquired.

DIERR_NOTBUFFERED

The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.

DIERR_NOTDOWNLOADED

The effect is not downloaded.

DIERR_NOTEXCLUSIVEACQUIRED

The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.

DIERR_NOTFOUND

The requested object does not exist.

DIERR_NOTINITIALIZED

This object has not been initialized.

DIERR_OBJECTNOTFOUND

The requested object does not exist.

DIERR_OLDDIRECTINPUTVERSION

The application requires a newer version of DirectInput.

DIERR_OTHERAPPHASPRIO

Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard DirectInput return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.

DIERR_OUTOFMEMORY

The DirectInput subsystem could not allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

DIERR_READONLY

The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.

DIERR_REPORTFULL

More information was requested to be sent than can be sent to the device.

DIERR_UNPLUGGED

The operation could not be completed because the device is not plugged in.

DIERR_UNSUPPORTED

The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

E_HANDLE

The HWND parameter is not a valid top-level window that belongs to the process.

E_PENDING

Data is not yet available.

E_POINTER

An invalid pointer, usually NULL, was passed as a parameter.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay

The Microsoft® DirectPlay® application programming interface (API) is the component of Microsoft DirectX® that enables you to write network applications such as multiplayer games. DirectPlay performs all of the hard work associated with connecting players, even those behind Network Address Translation (NAT) devices, and managing sessions. It allows you to create, find, and connect to multiplayer games. Once connected, DirectPlay enables you to send guaranteed or non-guaranteed messages to other players. A common framework for launching applications and in-game voice communications is also provided. In addition, DirectPlay provides support for Microsoft Windows® Powered Pocket PC 2002 and connectivity with DirectPlay 8.0 applications.

Information about DirectPlay is presented in the following sections.

Roadmap

What's New in DirectPlay. New features and functionality of this component in DirectX 9.0.

Basic Concepts in DirectPlay. An overview of what DirectPlay is and what it can do for your application, together with a first view of some key objects and the steps involved in creating a network application.

Peer-to-Peer Sessions. A guide to using the IDirectPlay8Peer interface for creating and managing peer-to-peer applications.

Client/Server Sessions. A guide to using the IDirectPlay8Client and IDirectPlay8Server interfaces for creating and managing client/server applications.

DirectPlay Lobby. A guide to using the IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication interfaces for setting up multiplayer games.

DirectPlay Voice. A guide to using the IDirectPlayVoiceClient and IDirectPlayVoiceServer interfaces for creating and managing voice sessions.

DirectPlay for Pocket PC 2002. Information about creating applications for the Pocket PC 2002.

Advanced Topics in DirectPlay. More advanced features of DirectPlay including addressing, NATs, callbacks, and multithreading.

DirectPlay C/C++ Tutorials. Step-by-step tutorials following sample code in the software development kit (SDK).

DirectPlay C++ Samples. A guide to the C/C++ sample applications in the SDK.

DirectPlay C/C++ Reference. Detailed information for the DirectPlay C++ API.

© 2002 Microsoft Corporation. All rights reserved.


What's New in DirectPlay

This section introduces new features for Microsoft® DirectPlay® 9.0.

New Features in DirectPlay

  • The DirectPlay application programming interfaces (APIs) are available for the Microsoft Windows® Powered Pocket PC 2002. See DirectPlay for Pocket PC 2002 for more information.
  • The DPN_MSGID_SEND_COMPLETE message structure has two new members that allow you to calculate the round-trip travel time of messages.
  • DirectPlay has a new service provider for network simulation. You can use the IDP8SimControl methods to test applications under a variety of network conditions.
  • DirectPlay has a new interface, IDirectPlay8ThreadPool, that allows you to manage threads in your application.
  • Applications can cancel all messages sent by a particular player using the DPNCANCEL_PLAYER_SENDS flag when calling IDirectPlay8Peer::CancelAsyncOperation, IDirectPlay8Server::CancelAsyncOperation, and IDirectPlay8Client::CancelAsyncOperation.
  • Players can receive their local player identifier (ID) in the DPN_MSGID_CONNECT_COMPLETE message.
  • Hosts can prevent DirectPlay from processing enumeration queries by setting the DPNSESSION_NOENUMS flag in the DPN_APPLICATION_DESC structure when calling IDirectPlay8Peer::Host and IDirectPlay8Server::Host.
  • Messages sent to a group with no players in it will now return DPNSUCCESS_NOPLAYERSINGROUP instead of DPNERR_GENERIC.
  • Packet signing is available for all DirectPlay traffic.
  • Applications can close immediately by setting the DPNCLOSE_IMMEDIATE flag when calling IDirectPlay8Peer::Close, IDirectPlay8Client::Close, and IDirectPlay8Server::Close.
  • DirectPlay 9.0 has improved defense against connection spoofing.
  • Use the DPNINITIALIZE_HINT_LANSESSION flag when calling IDirectPlay8Peer::Initialize, IDirectPlay8Client::Initialize, and IDirectPlay8Server::Initialize.
  • When resending packets, packet coalescence is available by setting the DPNSEND_COALESCE flag when calling IDirectPlay8Peer::SendTo, IDirectPlay8Client::Send, and IDirectPlay8Server::SendTo.
  • Applications can tune the DirectPlay protocol using the DPN_CAPS_EX structure used when calling IDirectPlay8Peer::GetCaps, IDirectPlay8Client::GetCaps, and IDirectPlay8Server::GetCaps or IDirectPlay8Peer::SetCaps, IDirectPlay8Client::SetCaps, and IDirectPlay8Server::SetCaps.
  • A group owner's context value has been added to the DPNMSG_CREATE_GROUP structure.
  • If the DPNSESSION_NODPNSVR flag is not set in the DPN_APPLICATION_DESC structure when calling IDirectPlay8Peer::Host or IDirectPlay8Server::Host and dpnsvr.exe does not start, the call to Host will fail and return DPNERR_DPNSVRNOTAVAILABLE.
  • Less reliable connections should now perform better with improved DirectPlay protocol behavior.
  • Network Address Translation (NAT) support has improved. This includes the new IDirectPlay8NATResolver interface, which allows you to create a NAT resolver application.
  • DirectPlay now supports Internet Protocol (IP) v6.

© 2002 Microsoft Corporation. All rights reserved.


Basic Concepts in DirectPlay

The Microsoft® DirectPlay® API provides developers with the tools to develop multiplayer applications such as games or chat clients. For simplicity, this documentation will refer to all such applications as "games". A multiplayer application has two basic characteristics:

  • Two or more individual users, each with a game client on their computer.
  • Network links that enable the users' computers to communicate with each other, perhaps through a centralized server.

DirectPlay provides a layer that largely isolates your application from the underlying network. For most purposes, your application can just use the DirectPlay API, and enable DirectPlay to handle the details of network communication. DirectPlay provides many features that simplify the process of implementing many aspects of a multiplayer application, including:

  • Creating and managing both peer-to-peer and client/server sessions
  • Managing users and groups within a session
  • Managing messaging between the members of a session over different network links and varying network conditions
  • Enabling applications to interact with lobbies
  • Enabling users to communicate with each other by voice

The following documentation provides a high-level overview of the capabilities of DirectPlay.

  • DirectPlay Network Communication
  • Communicating with DirectPlay Objects
  • Creating and Managing Sessions

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Network Communication

The primary function of Microsoft® DirectPlay® is to provide you with efficient and flexible messaging support that largely isolates your application from the underlying network hardware and software. If you need to send a status update, you can call the relevant DirectPlay application programming interface (API), regardless of what kind of network link is involved. DirectPlay network service providers support communication over Transmission Control Protocol/Internet Protocol (TCP/IP), Internetwork Packet Exchange (IPX), modem, and serial links.

Notes DirectPlay does not provide secure communications.

  • DirectPlay Transport Protocol
  • DirectPlay Addresses

DirectPlay Transport Protocol

The core of the DirectPlay networking capabilities is the DirectPlay protocol. This transport-layer protocol has been completely overhauled for DirectPlay 8, and is now used for all messaging. The DirectPlay protocol is focused on making it simple for you to send data from the sending application to the target application, without needing to worry about what happens in between. The protocol offers a number of features that are tailored to the needs of multiplayer games, including:

  • Reliable and unreliable delivery of messages. Reliable messages will be resent until the target application receives them. You can assign the delivery type on a message-by-message basis.
  • Sequential and non-sequential delivery of messages. Sequential messages will be passed to the target application in the order they were sent.
  • Message fragmentation and reassembly. If message size exceeds the capacity of a particular network, DirectPlay automatically fragments and reassembles the message.
  • Congestion control. DirectPlay automatically throttles your outgoing messages to a level that can be handled by the target. This feature prevents you from flooding the target with more messages than it can process.
  • Send prioritization. To ensure that the most important messages get sent first, DirectPlay enables you to designate messages as low, medium, or high priority. The high priority messages are sent to the front of the output queue, followed by medium and low priority messages.
  • Message timeouts. To prevent the outgoing message queue from being clogged with messages that have been superseded by more recent messages, DirectPlay enables you to assign a timeout value to all messages. When a message times out, it is removed from the outgoing message queue, regardless of whether it has been sent or not.

DirectPlay Addresses

In order to deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

DirectPlay addresses are in the form of URL strings. These strings consist of a scheme, scheme separator, and data string in the following general format.

x-directplay:/[data string]

The data string contains several elements that specify everything that is needed to enable communication to take place between sender and target, over a variety of different types of network link.

In use, the URL strings are embedded in a DirectPlay address object which is passed to or from DirectPlay API methods. You have the option of either manipulating the URL string directly, or using the methods exposed by the address object to handle each element of the data string separately.

© 2002 Microsoft Corporation. All rights reserved.


Communicating with DirectPlay Objects

Microsoft® DirectPlay® consists of a collection of Component Object Model (COM) objects. Each object exposes one or more interfaces that enable you to control various aspects of DirectPlay. For instance, the DirectPlay peer object (CLSID_DirectPlay8Peer) is used to manage peer-to-peer games.

You communicate with a DirectPlay object by calling the methods exposed by its interfaces. For instance, to send some data to another user in a peer-to-peer game, you would send a message by calling the IDirectPlay8Peer::SendTo method. DirectPlay then takes care of getting the message to its target.

DirectPlay communicates with your application through one or more callback functions. These functions are similar in principle to the familiar Window procedure. Your application implements the callback function and passes a pointer to the function to DirectPlay during initialization. When DirectPlay needs to communicate with your application, it calls the callback function and passes in two key items of information:

  • A message identifier (ID) that identifies the message type
  • A pointer to a block of data, typically a structure, that provides any needed details.

For instance, when the message sent in the above example arrives at its target, the target application's callback function will receive a message with a DPNMSGID_RECEIVE message ID, indicating that a message has arrived from another user. The accompanying structure contains the data.

Because much of DirectPlay messaging is multithreaded, it is critical that callback functions be properly implemented.

© 2002 Microsoft Corporation. All rights reserved.


Creating and Managing Sessions

A game session is an instance of a particular multiplayer game. A session has two or more users playing simultaneously, each with the same game client on his or her computer. A player is an entity in the game itself, and is defined by the particular game. Each user may have more than one player in a game. However, the game application must manage these players itself, using separate Microsoft® DirectPlay® interfaces or objects for each player.

The first step in creating a session is to collect a group of users. There are two basic approaches.

  • Many game sessions are arranged by a lobby application running on a remote computer. This approach is used by most Internet-based games.
  • It is also possible to arrange games by having the individual users' computers communicate with each other. This approach is typically limited such situations as a group of potential users that are all on the same LAN.

Once the session has been arranged, the game is launched and gameplay begins. As the session proceeds, players may be eliminated from the session, or new players added. The details are up to the individual game.

With a multiplayer game, each user's user interface (UI) can be synchronized with that of all other users in the session. Managing a multiplayer session thus requires a continual stream of messages to and from each user. For example, every time a player moves, a message must be sent to update that player's position on all the other game clients in the session. The core of DirectPlay is that part of the application programming interface (API) that supports efficient and flexible messaging between all the computers in a session.

There are two basic ways to structure the messaging topology of a session: peer-to-peer and client/server. Both topologies have their advantages and limitations, so you will need to evaluate which is most appropriate for your game.

This section includes the following topics.

  • Peer-to-Peer Topology
  • Client/Server Topology

© 2002 Microsoft Corporation. All rights reserved.


Peer-to-Peer Topology

A peer-to-peer game consists of the individual players' computers, connected by network links. Schematically, the topology of a four-player peer-to-peer game looks like:

Peer-to-peer game topology

Gameplay is handled by having each user's game client communicate directly with the other users' clients. For instance, when one user moves, the game client must send three update messages, one to each of the other users' computers.

A peer-to-peer game is normally arranged and launched through a lobby client application that resides on the user's computer. There are two basic ways the lobby client can arrange a session:

  • The lobby client communicates directly with other potential users' lobby clients. This approach can be used, for instance, to arrange a game among users on the same LAN subnet.
  • The lobby client acts as a link to lobby server application running on a remote computer. This is the way Internet-based games are normally arranged.

Once a session has been arranged and launched, most or all of the messaging will be user to user. If a lobby server is involved, it will only be handling such tasks as updating its list of session members when a player leaves the game, or enabling a new user to request entry to the session. Otherwise, the server stays in the background, and is typically not even aware of most of the messages that are being sent.

Because the server is either non-existent or at least not directly involved with the game play, one user is designated as the game host. They are responsible for handling logistical details such as bringing new players into an ongoing session.

Peer-to-peer games have the advantage of simplicity. All that is needed is a collection of players with game clients, and a way to organize a session. The primary drawback of the peer-to-peer topology is scalability. As the number of users increase, the number of messages needed to facilitate game play increases geometrically. The maximum number of users that can be accommodated depends on the game and the network bandwidth, but is typically no more than 20-30.

© 2002 Microsoft Corporation. All rights reserved.


Client/Server Topology

A client/server game consists of the individual players' computers (the "game clients") connected to a central server computer. The topology of a four-player client/server game is shown in the following graphic.

Client/Server game topology

Game play is handled by having each user's game client communicate with the server. The server is responsible for passing information about to the other users. For instance, when one user moves, the user's computer sends a message to the server. The server then sends messages to the other players to inform them of a change in game state. The server can have a number of responsibilities; it can:

  • Act as the session's messaging hub. Each computer needs to send messages only to the server. The server handles the logistics of synchronizing all the other users. This arrangement can substantially reduce message traffic, especially for large games.
  • Host the game. The server typically takes care of the tasks that must be handled by the session host in a peer-to-peer game.
  • Support many aspects of the game. The server often does much more than support game logistics. With many games, especially large ones, much of the processing that maintains the "game universe" takes place on the server. The game clients are primarily responsible for handling the user interface (UI).

A client/server game is typically arranged and launched through a lobby client application that resides on the user's computer. The lobby client acts as a link to a lobby server application, which usually runs on the same remote computer that is hosting the game. When the game has been launched, the game server application becomes the host and handles tasks such as admitting new users to the game.

There are a number of advantages to client/server games.

  • They are more efficient, especially for large-scale games. In particular, they scale much better than peer-to-peer games because additional players cause only a linear increase in the messaging traffic. The client/server topology is necessary for massively multiplayer games.
  • You are not limited by the processing power of your users' computers. You can locate much of the processing required to maintain a large complex "game universe" on a single powerful computer, and let the users' computers handle the UI.
  • You can control key aspects of your game at a central site. For instance, you can often update the game or fix bugs by modifying the server application, thereby avoiding the need to update large numbers of game clients.

Once you have developed and shipped a peer-to-peer game, you are essentially finished. The game clients are largely self-sufficient. However, with a client/server game, you have an ongoing responsibility to your users that goes beyond providing support services. You must also provide and maintain a game server computer and the associated software, along with the network links to handle all the messaging, for the lifetime of the application. In the case of massively multiplayer games, you may need to operate your servers for extended periods with few or no breaks in service, or risk angering users by disrupting their game play.

© 2002 Microsoft Corporation. All rights reserved.


Peer-to-Peer Sessions

A peer-to-peer session consists of a collection of users connected by a network. While a lobby server may be used to arrange and launch the game, the messaging needed to run the game is sent directly from one user's to another. Any communication with the lobby server is for such limited purposes as updating the list of participants.

With a peer-to-peer game, everything that is needed to run the game is part of the client software. With no server involved, all the processing needed to create and maintain the game universe must be handled by the client applications. This document discusses the basic principles of a lobbyable Microsoft® DirectPlay® peer-to-peer game. For a simple working example of a peer-to-peer application, see the SimplePeer application included with the software development kit (SDK).

  • Initiating a Peer-to-Peer Session
  • Using DirectPlay Enumerations
  • Selecting a Service Provider for a Peer-to-Peer Session
  • Selecting a Host for a Peer-to-Peer Session
  • Connecting to a Peer-to-Peer Session
  • Managing a Peer-to-Peer Session
  • Handling DirectPlay Messaging
  • Host Migration
  • Normal Peer-to-Peer Game Play
  • Leaving a Peer-to-Peer Session
  • Terminating a Peer-to-Peer Session

© 2002 Microsoft Corporation. All rights reserved.


Initiating a Peer-to-Peer Session

A peer-to-peer game can be launched directly by the user, or lobby-launched by a lobby client application that resides on the user's computer. This documentation will assume that the game is lobbyable, and can communicate with the lobby client.

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create and initialize a lobbied application object (CLSID_DirectPlay8LobbiedApplication). When you do so, you pass the object a pointer to your lobbied application message handler. This message handler receives messages directly from the lobbied application object, and indirectly from the lobby client and the lobby.

  • If the application was lobby-launched, the IDirectPlay8LobbiedApplication::Initialize method returns a connection handle to the lobby client and a DPL_MSGID_CONNECT message is sent to your lobbied application message handler. The pdplConnectionSettings member of the associated structure points to a DPL_CONNECTION_SETTINGS structure that contains connection information such as address objects for the members of the session.
  • If the application was not lobby launched, you will receive neither the connection handle, nor the message. However, if you call IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can later connect your running application to a session by sending your lobbied application message handler a DPL_MSGID_CONNECT message.

You should also create and initialize a peer object (CLSID_DirectPlay8Peer). This object will be your primary means of communicating with Microsoft® DirectPlay®, and the other users in the session. If you want to have multiple players in the session, you must create a separate instance of this object for each player.

© 2002 Microsoft Corporation. All rights reserved.


Using DirectPlay Enumerations

Enumeration is one of the ways that Microsoft® DirectPlay® provides information to applications. Enumerations are used to collect data associated with a number of similar elements. For instance, you can use an enumeration to obtain information about each player in a session. To perform an enumeration, an application queries DirectPlay for a particular type of information, and DirectPlay returns a data structure for each related element, typically as an array of structures.

Most applications will need to perform at least one and often several enumeration operations. Each DirectPlay interface supports a different set of enumerations. Thus the details will vary from application to application. The following is a list of available enumerations, along with the interfaces that support each type of enumeration.

  • Session hosts (IDirectPlay8Peer, IDirectPlay8Client)
  • Service providers (IDirectPlay8Peer, IDirectPlay8Client, IDirectPlay8Server)
  • Players (IDirectPlay8Peer, IDirectPlay8Server)
  • Groups (IDirectPlay8Peer, IDirectPlay8Server)
  • Group members (IDirectPlay8Peer, IDirectPlay8Server)
  • Local programs (IDirectPlay8LobbyClient)

For more information, see Implementing a DirectPlay Enumeration.

Enumeration is one of the ways that DirectPlay provides information to applications. Enumerations are used to collect data associated with a number of similar elements. For instance, you can use an enumeration to obtain information about each player in a session. To perform an enumeration, an application queries DirectPlay for a particular type of information, and DirectPlay returns a data type for each related element, typically as an array of types.

© 2002 Microsoft Corporation. All rights reserved.


Implementing a DirectPlay Enumeration

Most Microsoft® DirectPlay® enumerations follow a standard pattern: call the appropriate enumeration method, and examine the returned data array. The exception to this pattern is host enumerations, which are discussed separately.

Before you can call the method to obtain the data, you must allocate enough memory to contain the returned data block. However, you typically do not know, in advance, how large that array will be. Allocating a large enough block of memory to hold any conceivable array will work, but is inefficient. Instead DirectPlay is allows you query for the required array size, and then repeat the query to obtain the structure itself.

The following procedure outlines how to enumerate the members of a group in a peer-to-peer game. The same general procedure is followed by all other types of enumeration, except for host enumerations. Because enumerations are often used to obtain a snapshot of information that might be changing, you should perform enumerations in a loop until you are successful.

  1. Call IDirectPlay8Peer::EnumGroupMembers. This method returns an integer array in the prgdpnid parameter that contains the identifier (ID) of each player in the group. The pcdpnid parameter is used to indicate the number of elements in the array. Set the pcdpnid parameter to 0 to request the appropriate value. Set prgdpnid to NULL.
  2. When the method returns, pcdpnid will point to the number of elements that will be in the array.
  3. Allocate your array using the returned pcdpnid value, and assign the array to the prgdpnid parameter.
  4. Set pcdpnid to the value that was returned in the first method call.
  5. Call IDirectPlay8Peer::EnumGroupMembers again.
  6. When the method returns the second time, check the return value. If successful, the method will return S_OK, and the array will contain the player's IDs.
  7. If the method returns DPNERR_BUFFERTOOSMALL again, the number of players has increased since the previous method call. Return to step three and use the new pcdpnid value to increase the array size. Be careful not to leak memory.

In some cases, the method returns an array of structures. In that case, you follow the same procedure, but the value returned from the first method call gives you the size of the array in bytes, instead of the number of elements in the array. Refer to the individual method references for details.

For more information, see Enumerating Hosts.

© 2002 Microsoft Corporation. All rights reserved.


Enumerating Hosts

One way to arrange a session is to have session hosts advertise themselves as available. Peers or clients can look for a game to join by enumerating the available hosts, selecting one, and then join the game by sending a connection request. See Peer-to-Peer Sessions or Client/Server Sessions for a detailed discussion.

Unlike other enumerations, the information needed to respond to a request for available hosts is not stored on the local computer. Instead, a client or peer must broadcast a request, for instance on their local subnet, and wait for available hosts to respond. Hosts, on the other hand, must wait for these requests, and then respond appropriately. There are thus two slightly different procedures, depending on whether you are a potential session member, or a session host.

The following procedure illustrates how to enumerate the available hosts for a peer-to-peer session. The procedure for a client/server session is essentially the same. IDirectPlay8Peer::EnumHosts is the method that starts the enumeration. The key parameters to set are pApplicationDesc, pdpaddrDeviceinfo, and pdpaddrHost.

  1. Assign the globally unique identifier (GUID) of the game you are interested in playing to the guidApplication member of the DPN_APPLICATION_DESC structure and assign the structure pointer to the pApplicationDesc parameter.
  2. Create an address object for your device and assign its pointer to pdpaddrDeviceinfo. This object contains the information needed to make a network connection.
  3. To query a specific computer for available hosts, create a host address object for that computer and assign its pointer to pdpaddrHost. If you set this parameter to NULL, Microsoft® DirectPlay® will create an address object from the information contained in pdpaddrDeviceinfo. See DirectPlay Addressing for further discussion of address objects. If you are using an Internet Protocol (IP) or Internetwork Packet Exchange (IPX) service provider, the query will then normally be broadcast to your local subnet. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag, the service provider may display a dialog box to the user to request address information.
  4. Call IDirectPlay8Peer::EnumHosts.
  5. Your callback message handler will then receive a series of DPN_MSGID_ENUM_HOSTS_RESPONSE messages, one for each host that responds.

    Examine the information returned to your message handler, select a session, and ask to join it by calling IDirectPlay8Peer::Connect.

If you want to be the host of a session, advertise yourself as available, and wait for queries or connection requests. The following procedure applies to peer-to-peer hosts, but is essentially similar to the procedure for client/server hosts.

  1. Call IDirectPlay8Peer::SetPeerInfo to specify the static settings for your player.
  2. Specify the configuration of the game by assigning values the DPN_APPLICATION_DESC structure.
  3. Call IDirectPlay8Peer::Host to advertise yourself as a potential host. Set the pdnAppDesc parameter to the DPN_APPLICATION_DESC structure defined in the previous step.
  4. Wait for enumeration requests. They will take the form of a DPN_MSGID_ENUM_HOSTS_QUERY message sent to your callback message handler. If you want to respond to the enumeration request, fill in the DPN_APPLICATION_DESC and return S_OK. The peer will receive a DPN_MSGID_ENUM_HOSTS_RESPONSE message with the information.
  5. If the peer decides that they would like to join your session, you will receive a DPN_MSGID_INDICATE_CONNECT message.

See the Peer-to-Peer Sessions and Client/Server Sessions sections for further discussion of how to arrange and launch a game.

© 2002 Microsoft Corporation. All rights reserved.


Selecting a Service Provider for a Peer-to-Peer Session

The service provider is your network connection. Most games use either the Transmission Control Protocol/Internet Protocol (TCP/IP) or modem service provider, but Microsoft® DirectPlay® also provides support for serial and Internetwork Packet Exchange (IPX) connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS structure that accompanies the DPL_MSGID_CONNECT message. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the peer object's IDirectPlay8Peer::EnumServiceProviders method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.

© 2002 Microsoft Corporation. All rights reserved.


Selecting a Host for a Peer-to-Peer Session

Although most aspects of peer-to-peer games can be handled by the various users' communicating directly with each other, there are some tasks that must have a single owner. These tasks are handled by the game host. To join a session, you must know the address of the session's host. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive with the DPL_MSGID_CONNECT message include the host's address object. To find out who the session host is:

  • Check the dwFlags member of the DPL_CONNECTION_SETTINGS structure that is returned. If that member is set to DPLCONNECTSETTINGS_HOST, your system is the host.
  • If the DPLCONNECTSETTINGS_HOST flag is not set, then you can get the address of the host from the pdp8HostAddress member.

You can also create a session, perhaps on a local area network (LAN) subnet, by advertising yourself as a session host. To do so call IDirectPlay8Peer::SetPeerInfo to set the player's name and then call IDirectPlay8Peer::Host to advertise yourself as a potential host. You specify the configuration of the game by assigning values the DPN_APPLICATION_DESC structure that is passed through the pdnAppDesc parameter of IDirectPlay8Peer::Host.

To allow your user to examine the available sessions and hosts, you can enumerate the available hosts by calling IDirectPlay8Peer::EnumHosts. When the user has selected a session, you can request a connection.

© 2002 Microsoft Corporation. All rights reserved.


Connecting to a Peer-to-Peer Session

Unless you are the session host, you will need to connect your player to the session. To do so, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling IDirectPlay8LobbiedApplication::GetConnectionSettings. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's addresses, and a DPN_APPLICATION_DESC structure that describes the associated session.

To ask to join a session, call IDirectPlay8Peer::SetPeerInfo to set your player's name, and then call IDirectPlay8Peer::Connect with the selected host's address to connect to the session.

When a player attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session, return S_OK. Returning any other value rejects the request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response. If the host accepted the connection, the hResultCode member of the associated structure will be set to S_OK. If not, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION.

The host can define a player context value when it receives the DPN_MSGID_INDICATE_CONNECT message, however the player identifier (ID) will not yet be defined. The host can also wait to define a player context value until it receives a DPN_MSGID_CREATE_PLAYER message, which includes the player ID. Ordinary players to not receive a DPN_MSGID_INDICATE_CONNECT message.

Once the new player is connected, each member of the session, including the host, receives a DPN_MSGID_CREATE_PLAYER message announcing the new player. The structure associated with the message contains the player ID that you will use to send messages to that player. Peers that are not hosts must define the player context value when they handle this message. When a peer or host has returned from handling this message, that player context value is set for the session, and cannot be changed. See Using Player Context Values for more discussion of player context values.

© 2002 Microsoft Corporation. All rights reserved.


Managing a Peer-to-Peer Session

The session host is responsible for managing the session, including:

  • Managing the list of session members and their network addresses
  • Deciding whether a new user is allowed to join the session.
  • Notifying all members when a new user joins the session, and passing them the new user's address.
  • Providing new users with the current game state
  • Notifying all users when a user leaves the session

When players attempt to join a session, the host will receive a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session return S_OK. Returning any other value rejects the request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response.

The host can remove a player from the session by calling IDirectPlay8Peer::DestroyPeer. Other members of the session cannot call this method successfully. If you want to allow players to request that another player be removed from the session, you must send the request to the host with normal Microsoft® DirectPlay® messaging, and have the host handle the request.

© 2002 Microsoft Corporation. All rights reserved.


Handling DirectPlay Messaging

This set of documents provides information about how to handle Microsoft® DirectPlay® messaging. This particular document introduces general considerations for all DirectPlay messaging. Details for messaging with particular session types and roles can be found in the following documents.

  • Handling Standard Peer-to-Peer Messages
  • Peer-to-Peer Host Messages

General Messaging Considerations

The following general considerations apply to all DirectPlay messaging.

  • You will frequently receive a message following a method call. For instance, when you ask to join a host's session by calling IDirectPlay8Peer::Connect, you receive a DPN_MSGID_CONNECT_COMPLETE message that provides the result of your request. Two events thus follow your method call: The method returns and you receive a message. The order in which these events occur depend on whether you call the method synchronously or asynchronously, and may not be predictable.
  • By default, DirectPlay performs most operations asynchronously. To use synchronous operations, you typically need to set an xxx_SYNC flag in the method's dwFlags parameter. As long as an asynchronous method call does not fail for reasons such as parameter validation, it immediately returns DPNSUCCESS_PENDING. DirectPlay notifies you that the operation is complete by sending you a message such as DPN_MSGID_SEND_COMPLETE or DPN_MSGID_ASYNC_OP_COMPLETE. These messages can arrive before or after the method returns.
  • DirectPlay signals the end of most asynchronous operations by sending you a completion message, usually DPN_MSGID_ASYNC_OP_COMPLETE. Two exceptions to this rule occur: Send/SendTo, and Connect operations. The end of those operations is signaled by DPN_MSGID_SEND_COMPLETE and DPN_MSGID_CONNECT_COMPLETE, respectively. Synchronous operations do not return until the operation is complete. For that reason, most do not generate a completion message. The exception is synchronous connection operations that may generate a DPN_MSGID_CONNECT_COMPLETE message. See Handling Standard Peer-to-Peer Messages for further discussion.
  • You can force many asynchronous operations to terminate at any time by calling IDirectPlay8Peer::CancelAsyncOperation. Group operations cannot be terminated.
  • By default, DirectPlay serializes the messages associated with each player. As long as the DPNSEND_NONSEQUENTIAL flag is not set, you receive messages from a particular player in the order in which they are sent. This is true for messages sent to you directly, and to you as a member of a group. When a player sends a message to your group, the message appears to you as coming from the player, not from the group. You receive all messages from a particular player on one thread at a time, regardless of whether DPNSEND_NONSEQUENTIAL is set. You will not receive messages from a player before you have processed the corresponding DPN_MSGID_CREATE_PLAYER message, or after you have processed the corresponding DPN_MSGID_DESTROY_PLAYER message.
  • Group messages are also serialized. For instance, you will not receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message until you have processed DPN_MSGID_CREATE_GROUP. You will not receive any group-related messages after you have processed the corresponding DPN_MSGID_DESTROY_GROUP message.
  • Create and destroy messages are always paired. For instance, every DPN_MSGID_CREATE_GROUP message will be matched by a corresponding DPN_MSGID_DESTROY_GROUP message.
  • You should spend as little time in your message handler as possible. Executing a long blocking operation while handling a DirectPlay message may seriously impede network performance. For example, when you send data to another player in a peer-to-peer session by calling IDirectPlay8Peer::SendTo within your message handler, do so asynchronously. This allows you to return from the message handler as soon as the method returns. You can process the result of the operation when the DPN_MSGID_SEND_COMPLETE message arrives.

© 2002 Microsoft Corporation. All rights reserved.


Handling Standard Peer-to-Peer Messages

This document describes how to handle Microsoft® DirectPlay® messaging for a normal member of a peer-to-peer session. It does not discuss messages that are specific to a host. For a discussion of host-related messaging, see Peer-to-Peer Host Messages. For a discussion of general messaging issues, see Handling DirectPlay Messaging.

  • Startup Messages
  • Messaging During Normal Game Play
  • Session Termination Messages

Startup Messages

The host can set up a peer-to-peer session in two ways.

  • Arrange the session in advance. For example, you can use an online lobby to collect a group of players prior to starting the session. The player selected as host is responsible for calling IDirectPlay8Peer::Host to start the session. The lobby typically provides the host's address to the other players, and they use that address to connect directly to the session. Players usually need not do a host enumeration. See DirectPlay Lobby for details on how to handle lobbies.
  • Create a stand-alone session. When a player does a host enumeration, an enumeration query is sent to every host at the specified network location that matches the player's description of the type of session they want to join. If the host chooses to respond, the host passes the player the information the player needs to connect to the session. With a stand-alone session, there is no need for a lobby. The host calls IDirectPlay8Peer::Host and assembles the group of players by responding to enumeration queries and connection attempts.

This section describes the messages you may receive when selecting and joining a session.

  • DPN_MSGID_ENUM_HOSTS_RESPONSE

    If you need to locate a standalone session, call IDirectPlay8Peer::EnumHosts to enumerate the available hosts. You will receive a DPN_MSGID_ENUM_HOSTS_RESPONSE message for each host that responds to your enumeration request. You may receive multiple DPN_MSGID_ENUM_HOSTS_RESPONSE messages from the same host.

    By default, host enumeration is performed asynchronously. When an asynchronous enumeration terminates, for instance after the retry count is reached, you will be notified with a DPN_MSGID_ASYNC_OP_COMPLETE message. You will receive no further DPN_MSGID_ENUM_HOSTS_RESPONSE messages after DPN_MSGID_ASYNC_OP_COMPLETE arrives. You can cancel the operation at any time by calling IDirectPlay8Peer::CancelAsyncOperation. You can also cancel a host enumeration by calling IDirectPlay8Peer::Connect to connect to a session. The enumeration is halted as soon as the connect request completes successfully.

    Note You should call IDirectPlay8Peer::Connect outside of the DPN_MSGID_ENUM_HOSTS_RESPONSE message handler.
  • DPN_MSGID_CONNECT_COMPLETE

    Typically, the next step you will take is to attempt to join a session by calling IDirectPlay8Peer::Connect. You normally receive a DPN_MSGID_CONNECT_COMPLETE message with the host's response, even if the host rejects your connection request. You can receive this message for asynchronous and synchronous calls, but there are differences in detail.

    • Asynchronous calls: Once the connection attempt is underway, IDirectPlay8Peer::Connect normally returns DPNSUCCESS_PENDING. When you get this return value, you will always receive a DPN_MSGID_CONNECT_COMPLETE message containing the outcome of the connection attempt. However, the message might be indicated on a different thread before IDirectPlay8Peer::Connect returns. If the method returns DPNSUCCESS_PENDING, you also receive an asynchronous operation handle that you can use to cancel the operation by calling IDirectPlay8Peer::CancelAsyncOperation. This handle is valid only until you receive the DPN_MSGID_CONNECT_COMPLETE message. If IDirectPlay8Peer::Connect does not return DPNSUCCESS_PENDING, you will not receive a DPN_MSGID_CONNECT_COMPLETE message. Typically, this occurs when there is a problem with parameter validation, memory allocation, or addressing.
    • Synchronous calls: The method returns after the connection attempt is completed. You may receive a DPN_MSGID_CONNECT_COMPLETE message, as well as a return value. However, the message is guaranteed to arrive before the method returns. If your connection attempt is successful, you will receive a DPN_MSGID_CONNECT_COMPLETE, followed by a return value of DPN_OK. You may also receive a DPN_MSGID_CONNECT_COMPLETE message before other return values, such as DPNERR_HOSTREJECTEDCONNECTION. You will not receive DPN_MSGID_CONNECT_COMPLETE if the method call fails because of parameter validation, memory allocation, or addressing problems. You do not receive an asynchronous operation handle and cannot use IDirectPlay8Peer::CancelAsyncOperation to cancel a synchronous connection attempt.
  • DPN_MSGID_CREATE_PLAYER and DPN_MSGID_CREATE_GROUP

    If your connection attempt was successful, you will receive a DPN_MSGID_CREATE_PLAYER message for each player in the session at the time you joined. At a minimum, you will receive one message for the host and one for your player. If any groups have been created, you will receive a DPN_MSGID_CREATE_GROUP message for each group. You will also receive a series of DPN_MSGID_ADD_PLAYER_TO_GROUP messages for each group, one for each player in the group. All of these messages will arrive before DPN_MSGID_CONNECT_COMPLETE.

    You must define your player and group context values when you handle the associated creation messages. These context values can also be defined earlier, when IDirectPlay8Peer::Host, IDirectPlay8Peer::Connect, or IDirectPlay8Peer::CreateGroup methods are called. You can change those player or group context values when you handle DPN_MSGID_CREATE_PLAYER or DPN_MSGID_CREATE_GROUP respectively. However, once that handler returns, the corresponding context value cannot be changed again. See Using Player Context Values for further discussion.

Messaging During Normal Game Play

During a game, you might receive any of the following messages.

  • DPN_MSGID_CREATE_PLAYER and DPN_MSGID_DESTROY_PLAYER

    Players can typically enter or leave while the game is in progress. You receive a DPN_MSGID_CREATE_PLAYER when a player enters a game, and a DPN_MSGID_DESTROY_PLAYER message when that player leaves. You might receive DPN_MSGID_CREATE_PLAYER and DPN_MSGID_DESTROY_PLAYER messages simultaneously on different threads, but only for different players. You will not receive a DPN_MSGID_DESTROY_PLAYER message before your callback function has returned from receiving the corresponding DPN_MSGID_CREATE_PLAYER message. If you want to create a player context value, you must do so before you return from the DPN_MSGID_CREATE_PLAYER message handler.

  • DPN_MSGID_CREATE_GROUP and DPN_MSGID_DESTROY_GROUP

    Many games simplify messaging by allowing players to be grouped. When a group is created, you receive a DPN_MSGID_CREATE_GROUP message, regardless of whether your player is a member. If you want to create a group context value, you must do so before you return from the DPN_MSGID_CREATE_GROUP message handler. When a group is destroyed, you receive a DPN_MSGID_DESTROY_GROUP message. You will not receive a DPN_MSGID_DESTROY_GROUP message before your callback function has returned from processing the corresponding DPN_MSGID_CREATE_GROUP message.

  • DPN_MSGID_ADD_PLAYER_TO_GROUP and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP

    You receive DPN_MSGID_ADD_PLAYER_TO_GROUP messages for each group member after a group is created, and when a player is added to a group. You receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message when a player is removed from a group, and for all the remaining players in the group when the group is destroyed. You will not receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message before your callback function has returned from processing the corresponding DPN_MSGID_ADD_PLAYER_TO_GROUP message.

    You are guaranteed to receive every DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message for a group before you receive the DPN_MSGID_DESTROY_GROUP message. When a player is destroyed, you will receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message for every group in which that player is a member, before you receive the player's DPN_MSGID_DESTROY_PLAYER message.

  • DPN_MSGID_SEND_COMPLETE

    You send data to a player or group by calling IDirectPlay8Peer::SendTo. If you call this message asynchronously, the method will normally return DPNERR_PENDING. You receive a DPN_MSGID_SEND_COMPLETE message when the data is sent. The DPN_MSGID_SEND_COMPLETE message can arrive before or after the method returns.

    Receiving a DPN_MSGID_SEND_COMPLETE message does not necessarily mean that the target has received and processed the message. By default, if the network is overloaded, packets may be dropped. If you want to be certain that the message has arrived at the target, set the DPNSEND_GUARANTEED flag when you call IDirectPlay8Peer::SendTo. You will not receive a DPN_MSGID_SEND_COMPLETE message until DirectPlay has verified that the target has received the data. If you want to be certain that the message has also been processed by the target, set the DPNSEND_COMPLETEONPROCESS flag. If you set this flag, you will not receive a DPN_MSGID_SEND_COMPLETE message until the target's message handler has processed the message and returned.

    Note Setting the DPNSEND_GUARANTEED and DPNSEND_COMPLETEONPROCESS flags add overhead to the Send process. You may want to design your communication process to be able to tolerate some data loss in return for increased performance.
  • DPN_MSGID_RECEIVE

    When another player sends you data, it is delivered to your message handler with a DPN_MSGID_RECEIVE message. By default, the buffer containing the data is valid only until you return from the message handler. If you want to retain control over the data buffer after your message handler returns, have your message handler return DPNERR_PENDING. This return value will prevent DirectPlay from freeing or modifying the buffer. When you no longer need the buffer, you must return it to the control of DirectPlay by calling IDirectPlay8Peer::ReturnBuffer.

  • DPN_MSGID_PEER_INFO, DPN_MSGID_GROUP_INFO, and DPN_MSGID_APPLICATION_DESC

    Information structures are associated with the application, and with each player and group in the session. If this information changes during a session, you will receive the corresponding message. To obtain up-to-date information, you must call IDirectPlay8Peer::GetApplicationDesc, IDirectPlay8Peer::GetGroupInfo, or IDirectPlay8Peer::GetPeerInfo.

  • DPN_MSGID_HOST_MIGRATE

    A session must have a host. If the host set the DPNSESSION_MIGRATE_HOST flag when it created the session and then leaves the session without terminating it, DirectPlay chooses a new host. DirectPlay notifies the remaining players of the change by sending them a DPN_MSGID_HOST_MIGRATE message with the new host's identifier (ID).

Session Termination Messages

Sessions terminate for a variety of reasons. Typically, the session terminates when the host calls IDirectPlay8Peer::TerminateSession. If host migration is not permitted, the session terminates when the host calls IDirectPlay8Peer::Close or is involuntarily disconnected.

  • DPN_MSGID_TERMINATE_SESSION

    The DPN_MSGID_TERMINATE_SESSION message notifies you that the session is over. It is followed by a series of DPN_MSGID_DESTROY_PLAYER, DPN_MSGID_DESTROY_GROUP, and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP messages.

  • DPN_MSGID_DESTROY_PLAYER

    You will receive a DPN_MSGID_DESTROY_PLAYER message for each player in the session. If the host has intentionally terminated the session, this is considered normal behavior and the dwReason member of the associated structure is set to DPNDESTROYPLAYERREASON_NORMAL. The DPNDESTROYPLAYERREASON_SESSIONTERMINATED value is set only for unexpected disconnections from a session that does not allow host migration.

  • DPN_MSGID_DESTROY_GROUP and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP

    If any groups have been formed, you will receive DPN_MSGID_REMOVE_PLAYER_FROM_GROUP messages for each member of each group, and a DPN_MSGID_DESTROY_GROUP message for each group itself. The DPN_MSGID_REMOVE_PLAYER_FROM_GROUP messages will always arrive before the corresponding DPN_MSGID_DESTROY_PLAYER or DPN_MSGID_DESTROY_GROUP messages.

© 2002 Microsoft Corporation. All rights reserved.


Peer-to-Peer Host Messages

This document describes how to handle Microsoft® DirectPlay® messaging for the host of a peer-to-peer session. It discusses only those messages that are specific to a host. For a discussion of messaging for a normal peer, see Handling Standard Peer-to-Peer Messages. For a discussion of general messaging issues, see Handling DirectPlay Messaging.

  • Starting a Session
  • Host Migration and Session Termination

Starting a Session

You can set up a peer-to-peer session in two ways:

  • Arrange the session in advance. For example, you can use an online lobby to collect a group of players prior to starting the session. The player selected as host is responsible for calling IDirectPlay8Peer::Host to start the session. The lobby typically provides the host's address to the other players, and they use that address to connect directly to the session. Players usually need not do a host enumeration. For details on how to handle lobbies, see DirectPlay Lobby.
  • Create a stand-alone session. When a player does a host enumeration, an enumeration query is sent to every host at a specified network location, which matches the player's description of the type of session they want to join. If the host chooses to respond, the host passes the player the information needed to connect to the session. With a stand-alone session, there is no need for a lobby. The host calls IDirectPlay8Peer::Host and assembles the group of players by responding to enumeration queries and connection attempts.

In either case, you must start the session by calling IDirectPlay8Peer::Host. Once you start the session, you must be prepared to handle the following messages:

  • DPN_MSGID_ENUM_HOSTS_QUERY

    If you have started a stand-alone session, a potential player must be able find it before the player can connect. Players who are looking for a stand-alone session call IDirectPlay8Peer::EnumHosts to enumerate the available sessions. They indicate the type of session they are interested in by filling in the guidApplication member of the DPN_APPLICATION_DESC structure. They can also specify the network location they are interested in by adding the appropriate items to the host address object, which is passed to the pdpaddrHost parameter of IDirectPlay8Peer::EnumHosts. For more information about how to handle DirectPlay address objects, see DirectPlay Addressing.

    During enumeration, DirectPlay sends each available host a DPN_MSGID_ENUM_HOSTS_QUERY that includes the address of the player requesting the enumeration. If the player specified an application globally unique identifier (GUID), this message will go to only those hosts that have specified the same GUID. If the player does not specify an application GUID, DirectPlay will send DPN_MSGID_ENUM_HOSTS_QUERY to all available hosts at the specified network location.

    You can accept the enumeration request by having your handler return DPN_OK. DirectPlay will then pass information about the session, specifically your address and the DPN_APPLICATION_DESC structure, to the player. You can also provide some application-specific data to the player by assigning a data buffer to the DPNMSG_ENUM_HOSTS_QUERY structure's pvResponse member. When this buffer is no longer needed, DirectPlay notifies you that it is safe to free the buffer by sending you a DPN_MSGID_RETURN_BUFFER message.

    You can reject the enumeration request by having your message handler return a value other than DPN_OK. In that case, no information will be sent to the player. If you reject an enumeration request, there is no need for a response buffer, and you will not receive a DPN_MSGID_RETURN_BUFFER message.

    Note You can receive a DPN_MSGID_ENUM_HOSTS_QUERY message at any time while you are a host. If you are hosting an arranged session, or do not want to add any more players, you must still handle this message and reject the enumeration request.
  • DPN_MSGID_INDICATE_CONNECT

    Once a player has the address of a host, the player can attempt to connect to that session by calling IDirectPlay8Peer::Connect. The session host then receives a DPN_MSGID_INDICATE_CONNECT message with information about the player.

    To accept a player's connection request, have your DPN_MSGID_INDICATE_CONNECT message handler return DPN_OK. As with DPN_MSGID_ENUM_HOSTS_QUERY, you can also return a data buffer to the player by assigning it to the DPNMSG_INDICATE_CONNECT structure's pvReplyData member. When this buffer is no longer needed, DirectPlay sends you a DPN_MSGID_RETURN_BUFFER message to notify you that you can safely free the buffer.

    You can also create a local player context value for the player at this time. That value will be passed back to you later when you receive the a DPN_MSGID_CREATE_PLAYER message for the player. You have the option of changing the player context value when you handle that message. See Using Player Context Values for more information about player context values.

    You can reject a connection request by having your handler return any value other than DPN_OK. In that case, there is no need for a response buffer and you will not receive a DPN_MSGID_RETURN_BUFFER message. You can return a data buffer to the rejected player by assigning it to the DPNMSG_INDICATE_CONNECT structure's pvReplyData member. When this buffer is no longer needed, DirectPlay sends you a DPN_MSGID_RETURN_BUFFER message to notify you that you can safely free the buffer.

    You can also prevent connections by limiting the number of players in the session. When you call IDirectPlay8Peer::Host or IDirectPlay8Peer::SetApplicationDesc, set the dwMaxPlayers member of the DPN_APPLICATION_DESC structure to the maximum number of players you will allow in the session. When the number of players in the session reaches your specified maximum, you will receive no more DPN_MSGID_INDICATE_CONNECT messages. Instead, additional connection attempts will automatically fail, returning DPNERR_SESSIONFULL.

  • DPN_MSGID_CREATE_PLAYER

    After you have returned DPN_OK to accept a player's connection request, you will receive a corresponding DPN_MSGID_CREATE_PLAYER message. If you want to create a player context value or modify the value you created when you handled DPN_MSGID_INDICATE_CONNECT, you must do so when you handle DPN_MSGID_CREATE_PLAYER. Once your DPN_MSGID_CREATE_PLAYER message handler returns, DirectPlay permits no further changes to the player context value.

  • DPN_MSGID_INDICATED_CONNECT_ABORTED

    If a player drops the connection after the host has processed the DPN_MSGID_INDICATE_CONNECT message but before it has processed DPN_MSGID_CREATE_PLAYER, the host receives a DPN_MSGID_INDICATED_CONNECT_ABORTED message. If you receive this message, free any memory that you allocated while processing DPN_MSGID_INDICATE_CONNECT. If you process DPN_MSGID_CREATE_PLAYER before the player disconnects, you will receive a DPN_MSGID_DESTROY_PLAYER message. You can free the memory you have allocated when you process that message. If the player disconnects while you are processing DPN_MSGID_CREATE_PLAYER, you will receive a DPN_MSGID_DESTROY_PLAYER message after your message handler returns from processing DPN_MSGID_CREATE_PLAYER.

Host Migration and Session Termination

Every peer-to-peer session must have a host. However, the original host may leave the session either by calling IDirectPlay8Peer::Close or by being disconnected. This situation can be handled in one of two ways:

  • When host leaves the session, it terminates.
  • When the host leaves the session, a new host is chosen.

The original host specifies which of those two options is to be followed when it calls IDirectPlay8Peer::Host to start the session. If it enables "host migration" by setting the DPNSESSION_MIGRATE_HOST flag in the DPN_APPLICATION_DESC structure, a new host will be chosen when the current host leaves. However, even if host migration is enabled, the host can force the session to terminate by calling IDirectPlay8Peer::TerminateSession. If host migration is not enabled, the session terminates when the host leaves. The host will then receive the same messages as all other members of the session. See Handling Standard Peer-to-Peer Messages for details.

© 2002 Microsoft Corporation. All rights reserved.


Host Migration

While the host must be one of the initial members of the session, they may choose to leave before session is finished. When the host leaves the session, there are two possible outcomes:

  • The session terminates.
  • The host migrates, and another user becomes host.

Sessions may or may not permit host migration. To enable host migration, the session organizer must set the DPNSESSION_MIGRATE_HOST flag in the dwFlags member of the DPN_APPLICATION_DESC structure when they set up the game. If this flag is not set, the session terminates when the host leaves.

If the DPNSESSION_MIGRATE_HOST flag is set, the host can still force the session to terminate by calling IDirectPlay8Peer::TerminateSession.

If DPNSESSION_MIGRATE_HOST flag is set and the host leaves the session, Microsoft® DirectPlay® will select a new session host. All remaining session members will receive a DPN_MSGID_HOST_MIGRATE message that includes the identifier (ID) of the new host.

© 2002 Microsoft Corporation. All rights reserved.


Normal Peer-to-Peer Game Play

In Microsoft® DirectPlay®, a message is essentially a block of game-related data that you send to one or more members of the session. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data from one user to another. When the game is underway, each session member will normally send a constant stream of messages to all other members of the session for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same user interface (UI). However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

To send a message to another session member, call IDirectPlay8Peer::SendTo. That member will receive a DPN_MSGID_RECEIVE message with the data. To send a message to a specific player, set the dpnid parameter to the player identifier (ID) that you received with the associated DPN_MSGID_CREATE_PLAYER message. You can also send a message to every player in the session by setting dpnid to DPNID_ALL_PLAYERS_GROUP. You can also define groups of players, and use a single IDirectPlay8Peer::SendTo call to send a message to all members of a group.

Note You can also use the IDirectPlay8Peer::SetPeerInfo method to send information to other users. They will receive the information with a DPN_MSGID_PEER_INFO message. However, this way of transmitting information is not very efficient, and should not be used for normal messaging.

Using Groups

Many games allow players to be organized into groups. For instance, strategy games typically allow individual players to be organized into groups that can then be directed as a single entity. DirectPlay also allows the formation of groups of players. DirectPlay groups are essentially a way to simplify your messaging. When you have defined a group, you can send a message to every group member with a single call to IDirectPlay8Peer::SendTo. While DirectPlay groups normally correspond to the groups that are defined by the game, you are free to create a group for any reason.

To create a DirectPlay group, call IDirectPlay8Peer::CreateGroup All session members will then receive a DPN_MSGID_CREATE_GROUP message with the details. The message will include a group ID that is used to send messages to the group.

Once the group is created, you then add players by calling IDirectPlay8Peer::AddPlayerToGroup. Session members will then receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message with the IDs of the group and the player that was just added.

Once the group is established, you can send data to the group by calling IDirectPlay8Peer::SendTo, with the dpnid parameter set to the group ID. All group members will then receive a DPN_MSGID_RECEIVE message with the data.

To remove a player from a group, call IDirectPlay8Peer::RemovePlayerFromGroup. The session members will receive a DPN_MSGID_DESTROY_PLAYER message with the player's ID.

Finally, when you no longer need the group, you can destroy it by calling IDirectPlay8Peer::DestroyGroup All session members will then receive a DPN_MSGID_DESTROY_GROUP message with the group ID.

© 2002 Microsoft Corporation. All rights reserved.


Leaving a Peer-to-Peer Session

To leave a session, terminate the connection by calling IDirectPlay8Peer::Close. The session members will be notified with a DPN_MSGID_DESTROY_PLAYER message.

If you are the session host, leaving also terminates the session unless you configured the session to allow host migration. See Host Migration for details.

© 2002 Microsoft Corporation. All rights reserved.


Terminating a Peer-to-Peer Session

When the session is over, the host should terminate the session by calling IDirectPlay8Peer::TerminateSession. This method terminates the session even if host-migration is enabled. All session members will be notified by a DPN_MSGID_TERMINATE_SESSION message. You should then perform any necessary cleanup. To start another session, you must first call IDirectPlay8Peer::Close, and then IDirectPlay8Peer::Initialize.

If you registered your application as available for connection by calling IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can offer to connect you to a new session by sending your lobbied application message handler a DPL_MSGID_CONNECT message. You must have first called IDirectPlay8Peer::Close and IDirectPlay8Peer::Initialize.

© 2002 Microsoft Corporation. All rights reserved.


Client/Server Sessions

A client/server session consists of a collection of players, or clients, connected to a central server. As far as Microsoft® DirectPlay® is concerned, a client has no knowledge of any other clients, only the server. The messaging needed to run the game is between the individual clients and the server. DirectPlay does not provide direct client-to-client messaging, as it does for peer-to-peer sessions.

A client/server session requires two distinctly different applications.

  • The server application runs on a remote server. At a minimum, it serves as a central messaging hub and game host. The server must receive and handle all incoming messages from the clients, and send appropriate messages back out. Any transfer of data from one client to another must be handled by the server application.
  • A client application runs on each players' computer. The primary function of this application is to handle the UI, and keep the player's game state synchronized with the server.

There are certain aspects of the session that can be handled by only one of these applications. For instance, updating a player's video display can only be done by the client application. However, many aspects of the processing needed to maintain the game universe can, at least in principle, be done by either application. Writing an effective client/server game requires some careful consideration of how to divide the processing chores between the two applications.

This document describes the basic principles of client server games, and outlines how to implement client and server applications.

  • Initiating a Client/Server Session
  • Selecting a Service Provider for a Client
  • Selecting a Client/Server Host
  • Connecting to a Client/Server Session
  • Managing a Client/Server Session
  • Handling Client/Server Messages
  • Normal Client/Server Game Play
  • Leaving a Client/Server Session
  • Terminating a Client/Server Session

© 2002 Microsoft Corporation. All rights reserved.


Initiating a Client/Server Session

A client/server game can be launched through a lobby, or directly by the server application.

The Server Application

Client/server games are often arranged through lobbies. The most straightforward way to launch the server is to implement it as a lobbyable application. This approach provides a way to launch the server, and supports communication between server and lobby during the course of the session. See DirectPlay Lobby for further discussion.

A server can also be directly launched, and then advertise itself as available and wait for clients to connect. See Selecting a Client/Server Host for details.

Once the server application has been launched, it should initialize itself by calling IDirectPlay8Server::Initialize. As with other similar Microsoft® DirectPlay® methods, the primary purpose of initialization is to provide DirectPlay with a pointer to your callback message handler. You should also call IDirectPlay8Server::SetServerInfo to describe the current game. Clients cannot connect to a server until this method has been called.

The Client Application

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create and initialize a lobbied application object (CLSID_DirectPlay8LobbiedApplication ). When you do so, you pass the object a pointer to your lobbied application message handler. This message handler receives messages directly from the lobbied application object, and indirectly from the lobby client and the lobby.

  • If the application was lobby-launched, the IDirectPlay8LobbiedApplication::Initialize method returns a connection handle to the lobby client and a DPL_MSGID_CONNECT message is sent to your lobbied application message handler. The pdplConnectionSettings member of the associated structure points to a DPL_CONNECTION_SETTINGS structure that contains connection information such as an address object for the server.
  • If the application was not lobby launched, you will receive neither the connection handle, nor the message. However, if you call IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can later connect your running application to a session by sending your lobbied application message handler a DPL_MSGID_CONNECT message.

You should also create and initialize a client object (CLSID_DirectPlay8Client ). This object will be your primary means of communicating with DirectPlay and the server. If you want to have multiple players in the session, you must create a separate instance of this object for each player.

© 2002 Microsoft Corporation. All rights reserved.


Selecting a Service Provider for a Client

The service provider is your network connection. Most games use either the Transmission Control Protocol/Internet Protocol (TCP/IP) or modem service provider, but Microsoft® DirectPlay® also provides support for serial and Internetwork Packet Exchange (IPX) connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS structure that accompanies the DPL_MSGID_CONNECT message. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the client object's IDirectPlay8Client::EnumServiceProviders method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.

© 2002 Microsoft Corporation. All rights reserved.


Selecting a Client/Server Host

By definition, the server application hosts the session. To join a session, a client application must determine the host server's address. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive with the DPL_MSGID_CONNECT message include the host's address object. The pdp8HostAddress member of the associate structure points to an address object with the host's address.

Servers using an Internet Protocol (IP) or Internetwork Packet Exchange (IPX) service provider can also create a session perhaps on a local area network (LAN) subnet, by advertising themselves as session hosts. To create a session, call IDirectPlay8Server::SetServerInfo to specify the server settings. Then call IDirectPlay8Server::Host to advertise the server as a session host. You specify the configuration of the game by assigning values to the DPN_APPLICATION_DESC structure that is passed through the pdnAppDesc parameter of IDirectPlay8Server::Host.

To allow your user to view the available sessions and hosts, a client application can query for available hosts by calling IDirectPlay8Client::EnumHosts. When the user has selected a host, you can request a connection.

© 2002 Microsoft Corporation. All rights reserved.


Connecting to a Client/Server Session

All clients must explicitly join the session by connecting to the host, even if the session has been arranged through a lobby. A connection establishes the client as a member of the session, and provides the host with the information it needs to communicate with the client. The host has the option of accepting or rejecting a connection request.

The Server Application

When a client attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session, return S_OK. Returning any other value rejects the request. In either case, the client will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response. You can define a player context value at this time, or wait until you receive a DPN_MSGID_CREATE_PLAYER message. See Using Player Context Values for more discussion of player context values.

If the player is successfully added to the session, the server will receive a DPN_MSGID_CREATE_PLAYER message with the new player's identifier (ID) (DPNID). If you want to define a player context value, and have not yet done so, you must define it before your message handler returns from handling this message. Once it has done so, you cannot change the player context value.

The Client Application

To connect to a session, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling IDirectPlay8LobbiedApplication::GetConnectionSettings.

If you do not have the address of a session host and you are using either an Internet Protocol (IP) or Internetwork Packet Exchange (IPX) service provider, you can look for sessions by calling IDirectPlay8Client::EnumHosts and enumerating the available hosts. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's address, the device use to reach the host, and a DPN_APPLICATION_DESC structure that describes the associated session.

To ask to join a session, call IDirectPlay8Client::SetClientInfo to set your player's name, and then call IDirectPlay8Client::Connect with the selected host's address to connect to the session.

Your message handler will receive a DPN_MSGID_CONNECT_COMPLETE message with the host's response. If the host accepted the connection, the hResultCode member of the associated structure will be set to S_OK. If not, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION.

© 2002 Microsoft Corporation. All rights reserved.


Managing a Client/Server Session

As host, the server is responsible for managing the course of the session. The details will depend on how the application is designed, but a session host's duties include, at a minimum:

  • Managing the list of session members and their network addresses. Microsoft® DirectPlay® handles some of this task, but server applications typically need to manage more player data than is provided by DirectPlay.
  • Deciding whether a new user is allowed to join the session.
  • Providing new users with the current game state.

When a player attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session, return S_OK. Returning any other value rejects the connection request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response.

The host can remove a player from the session by calling IDirectPlay8Server::DestroyClient.

© 2002 Microsoft Corporation. All rights reserved.


Handling Client/Server Messages

This document describes how to handle Microsoft® DirectPlay® messaging for client/server sessions.

Messaging within client/server sessions is handled in much the same way as it is for peer-to-peer sessions (see Handling DirectPlay Messaging, Handling Standard Peer-to-Peer Messages, and Peer-to-Peer Host Messages). The primary differences are that within client/server sessions:

  • A client receives no messages that carry information about other players—and no group-related messages—because DirectPlay provides no way for a client to know about or to communicate with other clients.
  • DirectPlay provides no host-migration messaging because the server must be the host. A client/server session cannot be hosted by a client.

This document focuses on the issues specific to client/server sessions.

  • Client Startup Messages
  • Server Startup Messages
  • Client Messaging During Normal Game Play
  • Server Messaging During Normal Game Play
  • Client Session Termination Messages
  • Server Session Termination Messages

Client Startup Messages

To select and join a session, you must locate the server that is the session host, connect to the server, and handle the messaging used to set up the session. As with peer-to-peer sessions, the server hosting the session can either arrange the session in advance or create a stand-alone session.

To locate and connect to the server, you will need to handle some—or all—of the following messages. The process is essentially identical to that used for a peer-to-peer session. Refer to Handling Standard Peer-to-Peer Messages for details on how to handle individual messages.

  • DPN_MSGID_ENUM_HOSTS_RESPONSE

    To enumerate the available servers, call IDirectPlay8Client::EnumHosts, then handle DPN_MSGID_ENUM_HOSTS_RESPONSE messages from each server that responds to your enumeration request.

  • DPN_MSGID_CONNECT_COMPLETE

    After you have located the server and called IDirectPlay8Client::Connect to attempt to connect to the session, you will normally need to handle a DPN_MSGID_CONNECT_COMPLETE message, containing the server's response.

Server Startup Messages

Since the server is, by definition, the host of a client/server session, the startup procedure and messaging is virtually identical to a peer-to-peer host. As with peer-to-peer sessions, the host server can either arrange the session in advance, or create a stand-alone session. You will need to handle some or all of the following messages while starting up your session. Refer to Peer-to-Peer Host Messages for details on how to handle the individual messages.

  • DPN_MSGID_ENUM_HOSTS_QUERY

    If you are hosting a session, you will need to handle DPN_MSGID_ENUM_HOSTS_QUERY from potential players who are attempting to find a suitable host. Even if you are not hosting a session, you may still receive this message and must handle it.

  • DPN_MSGID_INDICATE_CONNECT

    You receive this message when a player attempts to connect to your session. Return DPN_OK to accept connection attempt and allow the player into the session. Return any other value to reject the connection attempt.

  • DPN_MSGID_CREATE_PLAYER

    You receive this message for each player that you accept into your session.

  • DPN_MSGID_INDICATED_CONNECT_ABORTED

    You receive this message if a client drops the connection after you have processed the DPN_MSGID_INDICATE_CONNECT message but before you have processed DPN_MSGID_CREATE_PLAYER.

Client Messaging During Normal Game Play

The messages that you can receive during normal game play are basically a subset of the messages that are used by normal members of a peer-to-peer session. You will not receive messages that carry information about other players, and no group-related messages. You also will not receive a host-migration message, because the host cannot migrate.

You must process the following messages. Refer to Handling Standard Peer-to-Peer Messages for details on how to handle individual messages.

  • DPN_MSGID_SEND_COMPLETE

    You can send messages to the server by calling IDirectPlay8Client::Send. As with peer-to-peer sessions, you receive a DPN_MSGID_SEND_COMPLETE message notifying you that the message has been sent.

  • DPN_MSGID_RECEIVE

    When the server sends you data, it is delivered to your message handler with a DPN_MSGID_RECEIVE message.

  • DPN_MSGID_APPLICATION_DESC, DPN_MSGID_SERVER_INFO

    Information structures are associated with the application and the server. If this information changes during a session, you will receive a corresponding message. To retrieve the updated application and server information structures, you must must call IDirectPlay8Client::GetApplicationDesc, IDirectPlay8Client::GetServerInfo.

Server Messaging During Normal Game Play

The server receives essentially the same messages as a peer-to-peer host during normal game play. You will need to process the following messages. Refer to Handling Standard Peer-to-Peer Messages for details on how to handle the individual messages.

  • DPN_MSGID_CREATE_PLAYER and DPN_MSGID_DESTROY_PLAYER

    You receive DPN_MSGID_CREATE_PLAYER when a player enters a game, and a DPN_MSGID_DESTROY_PLAYER message when that player leaves the game.

  • DPN_MSGID_CREATE_GROUP and DPN_MSGID_DESTROY_GROUP

    Groups are visible only to the server. You receive a DPN_MSGID_CREATE_GROUP message when you create a group, and DPN_MSGID_DESTROY_GROUP when you destroy the group.

  • DPN_MSGID_ADD_PLAYER_TO_GROUP and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP

    You receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message each time you add a player to a group, and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP each time you remove a player. When you destroy a group, you receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message for each group member.

  • DPN_MSGID_SEND_COMPLETE

    When you send messages to a client by calling IDirectPlay8Server::SendTo, you receive a DPN_MSGID_SEND_COMPLETE message to notify you that the message was sent.

  • DPN_MSGID_RECEIVE

    When a client sends you data, it is delivered to your message handler with a DPN_MSGID_RECEIVE message.

  • DPN_MSGID_APPLICATION_DESC, DPN_MSGID_CLIENT_INFO, DPN_MSGID_GROUP_INFO

    Information structures are associated with the application, the server, and your groups. If this information changes during a session, you will receive the corresponding message. To retrieve the updated application, client, and group information structures, you must must call IDirectPlay8Client::GetApplicationDesc, IDirectPlay8Server::GetClientInfo, and IDirectPlay8Server::GetGroupInfo.

Client Session Termination Messages

A client/server session normally ends when the server calls IDirectPlay8Server::Close. A session can also end if the server is disconnected. When the session ends, each client receives the following messages. Refer to Handling Standard Peer-to-Peer Messages for details on how to handle the individual messages.

  • DPN_MSGID_TERMINATE_SESSION

    This messages notifies you that the session is over.

Server Session Termination Messages

After you end the session, you will receive the following messages. Refer to Handling Standard Peer-to-Peer Messages.

  • DPN_MSGID_DESTROY_PLAYER

    You will receive a DPN_MSGID_DESTROY_PLAYER message for each player in your session.

  • DPN_MSGID_DESTROY_GROUP and DPN_MSGID_REMOVE_PLAYER_FROM_GROUP

    You will receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message for each player in each group, and a DPN_MSGID_DESTROY_GROUP message for each group.

© 2002 Microsoft Corporation. All rights reserved.


Normal Client/Server Game Play

In Microsoft® DirectPlay®, a message is essentially a block of game-related data that is sent from client to server or vice versa. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data. Once the game is underway, each client will normally send a constant stream of messages to the server, and vice versa, for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same user interface (UI). However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

The Server Application

To send a message to a client, call IDirectPlay8Server::SendTo. The client will receive a DPN_MSGID_RECEIVE message with the data.

The Client Application

To send a message to the server, call IDirectPlay8Client::Send. The server will receive a DPN_MSGID_RECEIVE message with the data.

Note DirectPlay does not provide a mechanism for clients to communicate with other clients, only with the server. Any client-client communication must be implemented by the server application.

Using Groups

Many games allow players to be organized into groups. For example, in a squad-based game, every player in the squad could be a member of a group. DirectPlay allows servers in a client/server game to create groups of players. While DirectPlay groups typically correspond to the groups that defined by the game, you are free to create a group for any reason. DirectPlay groups are essentially a way to simplify your messaging. When you have defined a group, you can send a message to every group member with a single IDirectPlay8Server::SendTo call.

To create a DirectPlay group, call IDirectPlay8Server::CreateGroup. Your message handler will then receive a DPN_MSGID_CREATE_GROUP message with the details. The message will include a group identifier (ID) that is used to send messages to the group. Once the group is created, you then add players by calling IDirectPlay8Server::AddPlayerToGroup.

Once the group is established, you can send data to the group by calling IDirectPlay8Server::SendTo, with the dpnid parameter set to the group ID. All group members will then receive a DPN_MSGID_RECEIVE message with the data.

To remove a player from a group, call IDirectPlay8Server::RemovePlayerFromGroup. Finally, when you no longer need the group, you can destroy it by calling IDirectPlay8Server::DestroyGroup.

© 2002 Microsoft Corporation. All rights reserved.


Leaving a Client/Server Session

A client can leave a session by calling IDirectPlay8Client::Close. The server is notified with a DPN_MSGID_DESTROY_PLAYER message.

© 2002 Microsoft Corporation. All rights reserved.


Terminating a Client/Server Session

To terminate a client/server session, the server calls IDirectPlay8Server::Close. There is no host migration in a client/server session, so this method terminates all connections and closes the session. The clients are notified of the session end by a DPN_MSGID_TERMINATE_SESSION message.

The server will then receive a DPN_MSGID_DESTROY_PLAYER message for each player, including itself. IDirectPlay8Server::Close is synchronous, and will not return until all the DPN_MSGID_DESTROY_PLAYER messages have been processed. When IDirectPlay8Server::Close has returned, you can safely shut down the server application.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Lobby

A lobby is an application with the primary purpose of helping users arrange multiplayer games. The lobby is usually an application that is hosted on a remote server. The user visits the lobby, typically through the Internet, and either sets up a game session or joins a session started by someone else. The lobby application then launches the group's individual game applications, and the game is underway.

Because many multiplayer games are arranged through lobbies, most games based on Microsoft® DirectPlay® must be able to interact with lobby applications. Conversely, because most lobbies will want to support DirectPlay-based games, the lobby application must be able to interact with the game application. This document discusses how to enable a Microsoft DirectX® game to interact with a lobby and vice versa.

Overviews

  • DirectPlay Lobby Architecture
  • DirectPlay Lobby Support
  • Implementing a Lobby Client
  • Implementing a Lobbyable Application
  • Lobby Clients
  • Lobby Servers
  • Lobbyable Applications

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Lobby Architecture

The process of arranging and managing a session of a multiplayer game based on Microsoft® DirectPlay® involves five separate components. The lobby server application is a third-party application that typically resides on a remote server and is accessed through the Internet. The remaining four components are installed on each player's computer.

  • Lobby client. The lobby client is a third-party application that communicates with the lobby server. It also communicates with the user's game application through the DirectPlay lobby client object.
  • Lobbyable game application. The lobbyable game application is a third-party application that uses the DirectPlay lobbied application object to communicate with the lobby client, and through the lobby client with the lobby server.
  • DirectPlay lobby client object.
  • DirectPlay lobbied application object.

The two DirectPlay objects act as links between the game application and the lobby client. They communicate with each other through private interfaces. The following graphic shows how these pieces are linked, and how they communicate.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Lobby Support

A lobby is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often also perform a variety of other functions, such as hosting chat rooms, posting news and information, and selling merchandise. While lobby servers are convenient and commonly used to arrange multiplayer games, they aren't required. Multiplayer games can also be arranged by direct communication between lobby clients.

There are normally three components that are needed to enable a game to interact with a lobby:

  • A lobby server
  • A lobby client
  • A lobbyable game.

Microsoft® DirectPlay® does not specify how you should implement a lobby server application. Instead, DirectPlay provides support for a lobby client. A lobby client is an application that is implemented by a lobby server vendor, and installed on each user's system. It serves as a link between the user and the lobby. While you could handle such communication directly, you would have to know the specific implementation details of every lobby that might launch your game.

The lobby client application handles the details of communicating with its associated lobby server, using whatever protocols are appropriate. The lobby client communicates with the user and their game applications through a DirectPlay interface. DirectPlay then passes messages to the application. The application can also use a DirectPlay interface to pass messages to the lobby client.

A lobby can launch virtually any application. However, the application must have some specific lobby-aware components to take full advantage of lobby-launching. In particular, a lobbyable application can communicate with the lobby client throughout the course of the session. If an application is registered as lobbyable, the lobby client also automatically receives updates for various changes in game status, such as host migration.

© 2002 Microsoft Corporation. All rights reserved.


Implementing a Lobby Client

A lobby client is an application that resides on a user's computer. It typically serves as a link between a game application on the user's computer and a lobby server on a remote computer. However, lobby clients can also function as stand-alone applications. For instance, they can be used to arrange a game session among the users of a particular local area network (LAN) subnet.

Lobby clients typically consist of three primary components that handle the following tasks:

  • Communicating with the outside world, either a lobby server or other lobby clients.
  • Communicating with the user, typically through a graphical user interface (GUI).
  • Communicating with Microsoft® DirectPlay®.

DirectPlay does not specify how the first two items should be implemented. Lobby client vendors should use whatever approach is suitable to their product. What DirectPlay provides is a standard application programming interface (API) that a lobby client can use to communicate with DirectPlay, and through DirectPlay with the user's lobbyable game applications.

This section discusses the essential details of lobby client implementation.

  • Initializing a Lobby Client
  • Launching a Lobbied Application
  • Implementing a Lobby Client Message Handler
  • Communicating with a Lobbied Application
  • Closing Down a Lobby Client

See the LobbyClient sample application for a fully implemented example of a simple lobby client.

© 2002 Microsoft Corporation. All rights reserved.


Initializing a Lobby Client

Lobby clients are launched either by a lobby server or directly, by a user. When a lobby client is launched, it must be initialized before it can launch an application. Initialization involves the following tasks.

  • Call CoCreateInstance to create a lobby client object (CLSID_DirectPlay8LobbyClient). Use the riid parameter to request an IDirectPlay8LobbyClient interface (IID_IDirectPlay8LobbyClient).
  • Call the lobby client's IDirectPlay8LobbyClient::Initialize method. Pass the method a pointer to your lobby client's callback message handler.
  • Use the IDirectPlay8LobbyClient::EnumLocalPrograms method to enumerate the lobbyable applications on the user's system.

The first two steps create the lobby client object, and set up a communication link between that object and your lobby client. The final step determines what lobbyable applications are available on the user's system. You need this information in order to launch the selected application.

The following code sample illustrates how to enumerate local applications. It is a simplified version of the EnumRegisteredApplications function in the LobbyClient sample found in the software development kit (SDK). Code related to error handling and to the dialog box has been deleted for clarity. See the LobbyClient sample in the SDK for the complete code.

HRESULT EnumRegisteredApplications()
{
    HRESULT hr;
    DWORD   dwSize     = 0;
    DWORD   dwPrograms = 0;
    DWORD   iProgram;
    BYTE*   pData   = NULL;

// g_pLobbyClient is a pointer to an IDirectPlay8LobbyClient interface
// Start with a NULL data buffer. The required buffer size is
// returned through dwSize.
  hr = g_pLobbyClient->EnumLocalPrograms( NULL, pData, &dwSize, &dwPrograms, 0 );
 if( dwSize == 0 )
  {
// No registered applications.
  }
// Set the data buffer to the appropriate size
  pData = new BYTE[dwSize];
  hr = g_pLobbyClient->EnumLocalPrograms( NULL, pData, &dwSize, &dwPrograms, 0 )

// Cast the returned data to the appropriate structure type
  DPL_APPLICATION_INFO* pAppInfo = (DPL_APPLICATION_INFO*) pData;

// Enumerate the names of the registered applications
  for( iProgram=0; iProgram<dwPrograms; iProgram++ )
  {
    TCHAR strAppName[MAX_PATH];
    DXUtil_ConvertWideStringToGeneric( strAppName, pAppInfo->pwszApplicationName, MAX_PATH );
  }
  SAFE_DELETE_ARRAY( pData );
  return S_OK;
}

© 2002 Microsoft Corporation. All rights reserved.


Launching a Lobbied Application

When the user has selected an application and your lobby client has verified that it has been registered on the user's system, you can launch the application. To do so, call IDirectPlay8LobbyClient::ConnectApplication. The first parameter is a DPL_CONNECT_INFO structure that contains a variety of information needed to launch the application, including the following:

  • The globally unique identifier (GUID) that identifies the application.
  • The connection settings, including the user's Microsoft® DirectPlay® address. See DirectPlay Addressing for a discussion of DirectPlay addresses.
  • Whether the application will be a host.

When you call IDirectPlay8LobbyClient::ConnectApplication, you can set a connection context value in the pvUserApplicationContext parameter. If you do not set the connection context value when you call IDirectPlay8LobbyClient::ConnectApplication, you can set the pvConnectionContext parameter when you handle the DPL_MSGID_CONNECT message. After this value has been set, the connection context value will be passed along in the pvConnectionContext parameter with any message you receive from that connection. This is a useful parameter to set if you are receiving messages from multiple connections and using a common lobby client message handler.

The IDirectPlay8LobbyClient::ConnectApplication method returns an application handle that is used to identify the application in all further communication. When the application has launched and the connection is successfully established, your message handler receives a DPL_MSGID_CONNECT message.

Note Your message handler may receive the DPL_MSGID_CONNECT before the IDirectPlay8LobbyClient::ConnectApplication method has confirmed the connection by returning a success code. Your message handler should be prepared to handle the message even if the method has not yet returned.

© 2002 Microsoft Corporation. All rights reserved.


Implementing a Lobby Client Message Handler

The message handler is a callback function that is used by the lobby client object to communicate with the lobby client. The lobby client message handler has three parameters that pass in the following information.

  • A message identifier (ID) that indicates the message type.
  • A pointer to a message data block. You must cast this parameter to the structure that is used by the particular message.
  • A pointer to an optional application-defined user-context data block.

The user context value is defined by the lobby client when it calls IDirectPlay8LobbyClient::Initialize. It can be used for such purposes as differentiating between messages that are sent from different objects. For more information about user-context values, see Using Player Context Values.

Your message handler must be able to handle the following five lobby client-specific messages.

  • DPL_MSGID_CONNECT
  • DPL_MSGID_CONNECTION_SETTINGS
  • DPL_MSGID_DISCONNECT
  • DPL_MSGID_RECEIVE
  • DPL_MSGID_SESSION_STATUS

Most of these messages are generated by the lobby client object in response to changes in the game status, or when the lobby client requests information. The exception is DPL_MSGID_RECEIVE. This message is used to pass data directly from the game application to the lobby client. See PFNDPNMESSAGEHANDLER for a complete description the message handler function.

Note Microsoft® DirectPlay® message handlers must be written to work properly in a multithreaded environment, or your application may not function well.

DPL_MSGID_CONNECT

This message is sent by the lobby client following the launch of a lobbyable application. The message indicates that the application has been successfully connected. The associated DPL_MSGID_CONNECT structure holds a variety of information, including:

  • A connection ID. Use this ID when your lobby client needs to send data to the application with IDirectPlay8LobbyClient::Send, or release the connection with IDirectPlay8LobbyClient::ReleaseApplication.
  • Lobby connection data.
  • An optional connection context value.

DPL_MSGID_CONNECTION_SETTINGS

This message is sent by DirectPlay whenever an associated lobbyable application calls its IDirectPlay8LobbiedApplication::SetConnectionSettings method to modify the session connections. The associated DPL_MSGID_CONNECTION_SETTINGS structure contains the updated connection information.

DPL_MSGID_DISCONNECT

This message is sent when the lobbyable application disconnects from the session by calling IDirectPlay8LobbiedApplication::Close. Your lobby client application should delete the connection from its list and free any data that is associated with the application.

DPL_MSGID_RECEIVE

This message enables an application to pass data to the lobby client. DirectPlay passes the data block from the application to the lobby client in a DPL_MSGID_RECEIVE structure. It is up to the lobby client to process the data.

DPL_MSGID_SESSION_STATUS

This message is sent by DirectPlay whenever one of the following six changes in the session's status occurs.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

The type of status change is indicated by the value of the dwStatus field in the associated DPL_MSGID_SESSION_STATUS structure.

For more information, see A Sample Lobby Client Message Handler.

© 2002 Microsoft Corporation. All rights reserved.


A Sample Lobby Client Message Handler

The following code is a simplified version of the message handler from the LobbyClient sample in the software development kit (SDK). Error handling code has been removed for clarity. See the sample for a complete version.

HRESULT WINAPI DirectPlayLobbyMessageHandler( PVOID pvUserContext,
                                              DWORD dwMessageId,
                                              PVOID pMsgBuffer )
{
  switch( dwMessageId )
  {
    case DPL_MSGID_DISCONNECT:
    {
      PDPL_MESSAGE_DISCONNECT pDisconnectMsg;
      pDisconnectMsg = (PDPL_MESSAGE_DISCONNECT)pMsgBuffer;

      // Free any data associated with the application and
      //   remove the connection from the list.
      break;
    }
    case DPL_MSGID_RECEIVE:
    {
      PDPL_MESSAGE_RECEIVE pReceiveMsg;
      pReceiveMsg = (PDPL_MESSAGE_RECEIVE)pMsgBuffer;

      // The lobby application sent data. Process the data and
      //   respond appropriately.
      break;
    }
    case DPL_MSGID_SESSION_STATUS:
    {
      PDPL_MESSAGE_SESSION_STATUS pStatusMsg;
      pStatusMsg = (PDPL_MESSAGE_SESSION_STATUS)pMsgBuffer;

      switch( pStatusMsg->dwStatus )
      {
        case DPLSESSION_CONNECTED:        // Session connected.
          break;
        case DPLSESSION_COULDNOTCONNECT:  // Session could not connect.
          break;
        case DPLSESSION_DISCONNECTED:     // Session disconnected.
          break;
        case DPLSESSION_TERMINATED:       // Session terminated.
          break;
        case DPLSESSION_HOSTMIGRATED:     // Host migrated.
          break;
        case DPLSESSION_HOSTMIGRATEDHERE: // Host migrated here.
          break;
      }
      case DPL_MSGID_CONNECTION_SETTINGS:
      {
        PDPL_MESSAGE_CONNECTION_SETTINGS pConnectionStatusMsg;
        pConnectionStatusMsg = (PDPL_MESSAGE_CONNECTION_SETTINGS)pMsgBuffer;
        // The application has changed the connection settings.
        break;
      }
  }
  return S_OK;
}

© 2002 Microsoft Corporation. All rights reserved.


Communicating with a Lobbied Application

Much of the lobby client's interaction with an associated application is indirect. The lobby client does something that affects the application, and Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the lobby client changes the connection settings, DirectPlay notifies the application and provides the new settings. However, the IDirectPlay8LobbyClient::Send method enables the lobby client to send a message directly to the application. DirectPlay passes the data to the application without modification. It is the responsibility of the application to process that data.

The lobbied application can also send data directly to the lobby client. The data is passed to the lobby client's message handler with a DPL_MSGID_RECEIVE message. DirectPlay passes the data to the lobby client without modification. It is up to the lobby client to process the data.

© 2002 Microsoft Corporation. All rights reserved.


Closing Down a Lobby Client

When you are ready to close the session, disconnect the application by calling IDirectPlay8LobbyClient::ReleaseApplication. The application receives a DPL_MSGID_DISCONNECT message.

After releasing the application, perform any cleanup that is necessary, and close the session by calling IDirectPlay8LobbyClient::Close. You should then free the lobby client object by calling IDirectPlay8LobbyClient::Release.

© 2002 Microsoft Corporation. All rights reserved.


Implementing a Lobbyable Application

A lobbyable application must be designed to work properly with a lobby client. While a lobby client can launch any application, only lobby-launched applications can receive messages from Microsoft® DirectPlay® and from the lobby client. To be lobby launched, an application must be appropriately registered, and it must be able to use a DirectPlay lobbied application object to communicate with DirectPlay and the lobby client.

This section discusses how to implement lobbyable applications.

  • Registering a Lobbyable Application
  • Handling Lobby Launching
  • Implementing a Lobbied Application Callback Message Handler
  • Communicating with a Lobby Client
  • Closing Down a Lobbied Application

© 2002 Microsoft Corporation. All rights reserved.


Registering a Lobbyable Application

A lobbyable application must be registered before it can be lobby launched. This registration needs to be done only once and is typically handled by the application's setup procedure. Do not attempt to modify the registry directly to register an application as lobbyable. Instead, do the following:

  • Call CoCreateInstance to create a lobbied application object (CLSID_DirectPlay8LobbiedApplication). Set the riid parameter to IID_IDirectPlay8LobbiedApplication to request an IDirectPlay8LobbiedApplication interface.
  • Call IDirectPlay8LobbiedApplication::RegisterProgram.This method takes the information and creates appropriate registry keys and values.

You must provide IDirectPlay8LobbiedApplication::RegisterProgram with a variety of information, including the following:

  • A GUID that is used to identify the application.
  • A friendly name for the application.
  • The location and name of the application's executable file.
  • The location and name of an optional launcher application.
  • Any command-line arguments that need to be passed to the executable file when it is launched.

Instead of launching the game application, Microsoft® DirectPlay® launches a launcher application. The launcher application then launches the game. Launcher applications can be used, for example, as an anti-piracy measure.

To unregister a registered program, call IDirectPlay8LobbiedApplication::UnRegisterProgram. This method removes the registry entries created by IDirectPlay8LobbiedApplication::RegisterProgram.

© 2002 Microsoft Corporation. All rights reserved.


Handling Lobby Launching

The first thing your lobbyable application should do when it is launched is to create and initialize a Microsoft® DirectPlay® lobbied application object. To do this, perform the following tasks.

  • Call CoCreateInstance to create a lobbied application object (CLSID_DirectPlay8LobbiedApplication). Set the riid parameter to IID_IDirectPlay8LobbiedApplication to request an IDirectPlay8LobbiedApplication interface.
  • Call IDirectPlay8LobbiedApplication::Initialize to initialize the lobbied application object. Pass the object a pointer to your lobbied application callback message handler.

Next, determine whether your application was lobby launched. If so, your application needs to set up a communication channel with DirectPlay so that you can effectively manage the session. Do the following to detect whether your application was lobby launched.

  • When the IDirectPlay8LobbiedApplication::Initialize method returns, examine the pdpnhConnection parameter. If this parameter is set to a valid connection handle, the game was lobby launched.
  • Examine the DPL_MSGID_CONNECT message you receive through your message handler. This message carries with it a variety of information, including the ID that you use to send messages to the lobby client.
Note Your message handler may receive the DPL_MSGID_CONNECT message before the IDirectPlay8LobbiedApplication::Initialize method returns. Your message handler should be prepared to handle the message appropriately.

If your application was not lobby launched, you can indicate that your application is available to lobby clients for connection by calling IDirectPlay8LobbiedApplication::SetAppAvailable. This method is typically called when the application has been launched by the user. However, it can also be used if the user has closed one session but the application is still running and available for another session. In either case, your message handler receives a DPL_MSGID_CONNECT message when the lobby client connects your application to a session.

The following sample code illustrates how to initialize a lobbied application, and how to detect whether an application was lobby launched. It is a simplified version of the InitDirectPlay function used by the SimplePeer application in the software development kit (SDK). Refer to that sample application for the complete code. In particular, error-handling code has been deleted for clarity. The g_bWasLobbyLaunched variable is a global variable that is set to TRUE if the application was lobby launched.

HRESULT InitDirectPlay()
{
  DPNHANDLE hLobbyLaunchedConnection = NULL;
  HRESULT hr;

  // Create IDirectPlay8LobbiedApplication
  hr = CoCreateInstance( CLSID_DirectPlay8LobbiedApplication, NULL,
                         CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8LobbiedApplication,
                         (LPVOID*) &g_pLobbiedApp );

  // Initialize IDirectPlay8LobbiedApplication
  hr = g_pLobbiedApp->Initialize( NULL,
                                  DirectPlayLobbyMessageHandler,
                                  &hLobbyLaunchedConnection,
                                  0 );
  //Check for a valid connection handle. If it is non-NULL
  //the application was lobby launched.
  g_bWasLobbyLaunched = ( hLobbyLaunchedConnection != NULL );

  return S_OK;
}

© 2002 Microsoft Corporation. All rights reserved.


Implementing a Lobbied Application Callback Message Handler

The message handler is a callback function that is used by the lobbied application object to communicate with a lobbied application. The lobbied application message handler has three parameters that pass in the following information.

  • A message identifier (ID) that indicates the message type.
  • A pointer to a message data block. You must cast this parameter to the structure that is used by the particular message.
  • A pointer to an optional application-defined user-context data block.

The user context value is defined by the lobby client when it calls IDirectPlay8LobbyClient::Initialize. It can be used for such purposes as differentiating between messages that are sent from different objects. For more information about user-context values, see Using Player Context Values.

Your message handler must to be able to handle the following four lobbied application-specific messages.

  • DPL_MSGID_CONNECT
  • DPL_MSGID_CONNECTION_SETTINGS
  • DPL_MSGID_DISCONNECT
  • DPL_MSGID_RECEIVE

Most of these messages are generated by the lobbied application object in response to changes in the connection, or when the lobbied application requests connection information. The exception is DPL_MSGID_RECEIVE. This message is used to pass data directly from the lobby client to the game application. See PFNDPNMESSAGEHANDLER for a complete description the message handler function.

Note Microsoft® DirectPlay® message handlers must be written to work properly in a multithreaded environment, or your application may not function well.

DPL_MSGID_CONNECT

This message is sent by the lobbied application object when the lobby client calls IDirectPlay8LobbyClient::ConnectApplication to connect an application to a session. The associated DPL_MSGID_CONNECT structure includes the following information.

  • A connection ID. Use this ID when your application needs to send data to the lobby client with IDirectPlay8LobbiedApplication::Send, or update the session status with IDirectPlay8LobbiedApplication::UpdateStatus.
  • Lobby connection data.
  • An optional connection context value. You can set the connection context value when you handle the DPL_MSGID_CONNECT message. If this value is set for a connection, it will be returned whenever you receive a message from that connection in the pvConnectionContext parameter. This is a useful value to set if your application has multiple connections and a common lobbied application message handler.

DPL_MSGID_CONNECTION_SETTINGS

DirectPlay sends this message whenever an associated lobby client calls its IDirectPlay8LobbyClient::SetConnectionSettings method to modify the session connections. The associated DPL_MSGID_CONNECTION_SETTINGS structure contains the updated connection information.

DPL_MSGID_DISCONNECT

This message is sent when the lobby client disconnects the application from the session by calling IDirectPlay8LobbyClient::ReleaseApplication. Your application should delete the connection from its list, and free any data that is associated with the session.

DPL_MSGID_RECEIVE

This message enables a lobby client to pass data to an application. DirectPlay passes the data block from the lobby client to the application in a DPL_MSGID_RECEIVE structure. It is up to the application to process the data.

For more information, see A Sample Lobbied Application Message Handler.

© 2002 Microsoft Corporation. All rights reserved.


A Sample Lobbied Application Message Handler

The following code is a simplified version of the message handler from the SimplePeer sample in the software development kit (SDK). Error handling code has been removed for clarity. See the sample for a complete version.

HRESULT WINAPI DirectPlayLobbyMessageHandler( PVOID pvUserContext,
                                              DWORD dwMessageId,
                                              PVOID pMsgBuffer )
{
  switch( dwMessageId )
  {
    case DPL_MSGID_CONNECT:
    {
      PDPL_MESSAGE_CONNECT pConnectMsg;
      pConnectMsg = (PDPL_MESSAGE_CONNECT)pMsgBuffer;

      // Connected. Start the session.
      break;
    }
    case DPL_MSGID_DISCONNECT:
    {
      PDPL_MESSAGE_DISCONNECT pDisconnectMsg;
      pDisconnectMsg = (PDPL_MESSAGE_DISCONNECT)pMsgBuffer;

      // Disconnected. Free any data associated with
      // the lobby client.
      break;
    }
    case DPL_MSGID_RECEIVE:
    {
      PDPL_MESSAGE_RECEIVE pReceiveMsg;
      pReceiveMsg = (PDPL_MESSAGE_RECEIVE)pMsgBuffer;

      // The lobby client sent data. Process the data and
      // respond appropriately.
      break;
    }

    case DPL_MSGID_CONNECTION_SETTINGS:
    {
      PDPL_MESSAGE_CONNECTION_SETTINGS pConnectionStatusMsg;
      pConnectionStatusMsg = (PDPL_MESSAGE_CONNECTION_SETTINGS)pMsgBuffer;

      // The lobby client has changed the connection settings.
      break;
    }
  }
  return S_OK;
}

© 2002 Microsoft Corporation. All rights reserved.


Communicating with a Lobby Client

Much of the lobbied application's interaction with an associated lobby client is indirect. The application does something that affects the lobby client, Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the application changes the connection settings, DirectPlay notifies the lobby client, and provides the new settings. However, there are two methods that provide information directly to the lobby client: IDirectPlay8LobbiedApplication::UpdateStatus and IDirectPlay8LobbiedApplication::Send.

You must notify the lobby client when any of the following changes in the game status take place.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

To notify the lobby client of one of these status changes, call IDirectPlay8LobbiedApplication::UpdateStatus, and set the dwStatus parameter to the appropriate value. The lobby client receives a DPL_MSGID_SESSION_STATUS message to notify it of the status change.

The IDirectPlay8LobbiedApplication::Send method enables the application to send a message directly to the lobby client. DirectPlay passes the data to the lobby client without modification. It is the responsibility of the lobby client to process that data.

The lobby client can also send data directly to the application. The data is passed to the lobby client's message handler with a DPL_MSGID_RECEIVE message. DirectPlay passes the data to the application without modification. The lobby client must process the data.

© 2002 Microsoft Corporation. All rights reserved.


Closing Down a Lobbied Application

To close a session, call IDirectPlay8LobbiedApplication::Close. The lobby client receives a DPL_MSGID_DISCONNECT message to notify it of the disconnection. If you want to keep the application running and connect to another session, indicate that your application is available by calling IDirectPlay8LobbiedApplication::SetAppAvailable. Otherwise, call IDirectPlay8LobbiedApplication::Release to free the lobbied application object, and shut the application down.

© 2002 Microsoft Corporation. All rights reserved.


Lobby Clients

A lobby client is an application that is implemented by the lobby server vendor and installed on each player's computer. It handles communication between the players and their game applications, and the lobby server. A common way to install a lobby client is to have the user download it from the lobby server's Web site as part of the sign-up procedure.

The following is a typical scenario.

  1. A new player goes to the Web site and signs up.
  2. As part of the sign-up procedure, the lobby client is downloaded to the client's computer.
  3. The player determines which to play and asks to join a session.
  4. The Web site launches the lobby client on the player's computer. A typical launch mechanism is a URL that points to the lobby client's executable file.
  5. The lobby client handles the mechanics of arranging the session, and then launches the user's game application.
  6. If the game is a lobbyable application, the lobby client enables the game application to communicate with the lobby server. This connection enables the lobby server to keep track of events such as players entering and leaving the game and host migration.

Lobby clients do not necessarily have to be linked to a remote server. In another scenario the user launches the lobby client directly. The lobby client then lists the available games and sessions, perhaps among the people connected to the user's local area network (LAN) subnet. When the user chooses a game and session, the lobby client launches the game.

This section discusses some the general features of a lobby client. For more information about communicating between a lobby client and its associated lobby server, see Communicating with a Lobbied Application.

For more information about implementation details, see Implementing a Lobby Client or the LobbyClient sample application included in the software development kit (SDK).

Communicating with a Lobby Client

Much of the lobbied application's interaction with an associated lobby client is indirect. The application does something that affects the lobby client, Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the application changes the connection settings, DirectPlay notifies the lobby client, and provides the new settings. However, there are two methods that provide information directly to the lobby client: IDirectPlay8LobbiedApplication::UpdateStatus and IDirectPlay8LobbiedApplication::Send.

You must notify the lobby client when any of the following changes in the game status take place.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

To notify the lobby client of one of these status changes, call IDirectPlay8LobbiedApplication::UpdateStatus, and set the dwStatus parameter to the appropriate value. The lobby client receives a DPL_MSGID_SESSION_STATUS message to notify it of the status change.

The IDirectPlay8LobbiedApplication::Send method enables the application to send a message directly to the lobby client. DirectPlay passes the data to the lobby client without modification. It is the responsibility of the lobby client to process that data.

The lobby client can also send data directly to the application. The data is passed to the lobby client's message handler with a DPL_MSGID_RECEIVE message. DirectPlay passes the data to the application without modification. The lobby client must process the data.

© 2002 Microsoft Corporation. All rights reserved.


Lobby Servers

The lobby server is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often perform a variety of other functions such as hosting chat rooms, posting news and information, and selling merchandise.

To manage multiplayer games, a lobby server typically handles a variety of tasks, including:

  • Managing the network addresses of the various game sessions and players.
  • Launching a session by launching the associated game applications on the players' computers.
  • Adding players to an ongoing session.
  • Connecting the various computers in a session to the correct network addresses.
  • Keeping track of changes in the session, such as players leaving the game or changes in the game's host.

The details of the lobby server application depend on what kind of services the vendor wants to offer. Microsoft® DirectPlay® does not specify how a lobby server should be implemented nor how it should communicate with its users' computers. However, lobby vendors must implement and distribute to their users a lobby client that is compatible with DirectPlay.

© 2002 Microsoft Corporation. All rights reserved.


Lobbyable Applications

Lobbyable applications are designed to work with a lobby client based on Microsoft® DirectPlay®. While a lobby client can use DirectPlay to launch any application, lobbyable applications have a number of advantages.

  • The lobby client receives automatic updates when game status changes.
  • The lobby client can use a standard application programming interface (API) to communicate with the application.
  • The application can use a standard API to communicate with the lobby client.

In short, DirectPlay virtually eliminates the need for game-specific or lobby client-specific communication code. You can use a standard API for everything with little or no modification for the particular game or lobby client.

For a discussion of implementation details, see Implementing a Lobbyable Application or software development kit (SDK) samples such as SimplePeer, or StagedPeer.

  • Launching a Lobbyable Application

Launching a Lobbyable Application

One of the first things a lobbyable application should do after it is launched is create a lobbied application object. Among other things, this object enables your application to determine whether it was lobby-launched. A lobbied application must also implement a message-handler callback function to receive messages from the lobby client. The basic procedure is:

  • Create a lobbied application object.
  • Initialize the object.
  • If the initialization method returns a valid connection handle, your application was lobby launched.
  • Examine the user context value that is returned by the initialization method. This value might contain game-specific information from the lobby client.
  • Examine the connection message received through the lobbied application message handler. This message carries with it a variety of information, including the identifier (ID) that you will use to send messages to the lobby client.

Once an application has been successfully lobby launched, DirectPlay can automatically send status updates to the lobby client when events such as host migration occur. To enable automatic status updates, call the RegisterLobby method of the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interface. You can also use the lobbied application interface to send messages to the lobby client.

Be aware that your message handler function might receive messages from the lobby client before the initialization method returns. In addition to the connection message, the callback function receives messages when the lobby client changes connection settings, or it breaks the connection. The lobby client can also send messages directly to your message handler that contain game-specific information.

Note It is possible to receive messages from more than one thread. To handle messaging properly, your lobbied application callback function should be re-entrant.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Voice

Microsoft® DirectPlay® Voice uses a DirectPlay session for media-independent network transport and player management. The DirectPlay Voice application programming interface (API) does not duplicate session control features from DirectPlay. A DirectPlay network transport session must also be created before DirectPlay Voice can transmit and receive voice communications. DirectPlay Voice can use either the IDirectPlay4 object or IDirectPlay8 object for network transport.

If DirectPlay Voice is being used in-process with a multiplayer game, the game will most likely also use the transport session to exchange its game-specific data. This makes it possible to optimize the use of network resources between the game and voice data.

It is also acceptable to create and use a transport session specifically for the voice session, as would be the case for a standalone voice conferencing application.

DirectPlay Voice is a full-voice communications API that is integrated with DirectPlay for network session management and network transport.

DirectPlay Voice is also integrated with DirectPlay Sound for voice recording and playback, and all DirectPlay Sound audio features are inherited including the ability to target voice data to different playback buffers and the use of special audio effects such as three-dimensional sound positioning.

Note DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Overviews

  • Audio Device Testing
  • Automatic Gain Control
  • Capture Focus
  • Configuring the Windows Sound Mixer
  • Creating a 3-D Voice Session
  • DirectPlay Voice Communication
  • DirectPlay Voice Topologies
  • Fast User Switching
  • Handling Voice Client Messages
  • Handling Voice Host Messages
  • Jitter Buffers
  • Sharing the Audio Capture Device
  • Transmission Control
  • Voice Codecs
  • Voice Host Migration
  • Working Set Guidelines

© 2002 Microsoft Corporation. All rights reserved.


Audio Device Testing

Microphone setup is supported by the Microsoft® DirectX® Voice Test Wizard. This wizard confirms that your system properly supports full duplex operation and ensures your microphone and playback settings are correct. You need to run the wizard only once for each combination of playback and capture device you select.

You can launch the Voice Test Wizard in two ways:

  • Launch the wizard from your program by creating a voice test object (CLSID_DirectPlayVoiceTest) and calling its IDirectPlayVoiceTest::CheckAudioSetup method.
  • In the Sound and Audio Devices Control Panel application for Microsoft Windows® Millennium Edition (Windows Me) or Windows XP, launch the wizard from the Voice tab.

Each time your application starts, you should test the configuration by calling IDirectPlayVoiceTest::CheckAudioSetup with the dwFlags parameter set to DVFLAGS_QUERYONLY. This enables you to quickly test whether the device configuration has changed since you last tested them. If your devices have not been tested, you should run IDirectPlayVoiceTest::CheckAudioSetup again to invoke the wizard. If you do not do so, IDirectPlayVoiceClient::Connect will return DVERR_RUNSETUP, and you will not be able to initialize Microsoft DirectPlay® Voice.

Many older computer systems still in use do not have a full duplex sound card. Without full duplex, a sound card can receive—but not send—voice communications. Because games typically hold the sound card in playback mode, DirectX prevents problems by not allowing dynamic switching between playback and capture. The Voice Test Wizard provides users with information about the duplexing abilities of their system.

© 2002 Microsoft Corporation. All rights reserved.


Automatic Gain Control

Microsoft® DirectPlay® Voice offers functionality to adjust the hardware input volume on the sound card automatically to provide the best recording input level possible. You can enable automatic gain control when you call IDirectPlayVoiceClient::Connect to connect to a voice session by setting the DVCLIENTCONFIG_AUTORECORDVOLUME flag in the dwFlags member of the DVCLIENTCONFIG structure. You can activate or deactivate automatic gain control during a session by calling IDirectPlayVoiceClient::SetClientConfig. Set the DVCLIENTCONFIG_AUTORECORDVOLUME flag to activate automatic gain control, and leave the flag unset to deactivate automatic gain control.

Most game applications should use automatic gain control because it requires a negligible amount of game resources and prevents the need for an in-game volume recording control. Users are not required to set the level themselves, yet they experience the highest quality of voice transmission and reception possible.

© 2002 Microsoft Corporation. All rights reserved.


Capture Focus

The concept of capturing focus is integral to creating lobbyable game applications and lobby applications with Microsoft® DirectPlay® Voice support. If your game application does not properly implement focus capture, it is possible that voice communication will not function if your game was launched from a lobby application.

To illustrate this point, consider two players who meet in a lobby application that has DirectPlay Voice support. The two players agree to launch the game. After the game is launched, the lobby application loses focus on each player's computer, and each copy of the game application gains focus. If the game application does not properly gain focus from the lobby application, it is possible that the lobby application can still have focus while the game application is running.

For example, this will occur if the first player's lobby application retains focus while the game session is running while the second player's game session gains focus from the lobby application. From the second player's perspective, the first player's voice session has fallen back to half-duplex. The second player can hear the first player, but the first player cannot hear the second player. From the first player's perspective, the voice session has ended because the second player does not seem to be speaking. Also, the first player does not know that the second player can hear him or her.

Note that this behavior is by design. Consider the same scenario as above, but when the first player attempts to start the game session from the lobby application, there is a problem and the session fails to start. If the second player's session starts successfully, that player can hear the voice of the first player and the first player can inform the second player that their game session failed. Both players might then drop back to the lobby and attempt to start the session once again.

To handle capture focus properly, your game application must set the hwndAppWindow parameter in the DVSOUNDDEVICECONFIG structure to the window handle that will have focus when the game is running. The DirectPlay Voice session can then be created through a call to IDirectPlayVoiceClient::Connect. The game application must then handle the DVMSGID_LOSTFOCUS and DVMSGID_GAINFOCUS messages.

See Sharing the Audio Capture Device for more information.

© 2002 Microsoft Corporation. All rights reserved.


Configuring the Windows Sound Mixer

The Microsoft® Windows® audio mixer must be correctly set up for Microsoft DirectPlay® Voice to function properly. This article describes how to set up the sound mixer to support a DirectPlay Voice session.

  • Selecting a DirectPlay Voice Device
  • Configuring the Windows Sound Mixer for Playback
  • Configuring the Windows Sound Mixer for Recording
  • Microphone Boost
  • Autoconfiguration

Selecting a DirectPlay Voice Device

On Windows XP and Windows Millennium Edition (Windows Me) systems, the Sound and Audio Devices Control Panel application has a Voice tab. You can use this tab to select playback and recording devices for DirectPlay Voice. If you have multiple sound cards on your system, you can select a different sound card for DirectPlay Voice transmissions than the sound card you use for normal audio.

Configuring the Windows Sound Mixer for Playback

To set up your sound system for DirectPlay Voice playback, you might have to configure the Windows audio playback mixer. You can launch the playback mixer in several ways, including:

  • Double-click the speaker icon in the status area of the taskbar.
  • Launch the Voice Test wizard and click the Volume button below the Playback box on the microphone or speaker test pages.
  • Launch the Sound and Audio Devices Control Panel application, select the Audio Devices tab, and click the playback section's Volume button.

The following screen shot shows the Windows 2000 playback mixer.

Windows audio playback mixer

To configure the playback mixer

  1. From the Options menu, choose Properties.
  2. In the Properties dialog box that appears, click Playback.
  3. At the bottom of the dialog box, make sure all available output lines are selected, as shown.
  4. Click OK to display the playback mixer again.
The following screen shot shows the mixer's Properties dialog box.

Audio mixer properties

The microphone has separate playback and recording lines. You must disable microphone playback line or your microphone input will be routed to your speakers and DirectPlay Voice will not be able to record your input.

To disable the microphone playback line

  1. Click OK on the Properties dialog box to display the playback mixer again.
  2. Make sure that the microphone section's Mute check box is selected.
  3. If the microphone section has a check box labeled Select, clear the check box.

Configuring the Windows Sound Mixer for Recording

You may also need to manually configure the recording mixer. There are three ways to launch the recording mixer.

  • Launch the Sound and Audio Devices Control Panel application, select the Audio Devices tab, and click the playback section's Volume button.
  • Launch the Voice Test Wizard and click the Volume button below the Recording box on either the microphone or speaker test pages.
  • Launch the playback mixer, choose the Properties command on the Options menu, select the Recording radio button, and click OK.

To configure the recording settings

  1. From the Options menu, choose Properties.
  2. Select Recording. The check boxes at the bottom of the dialog box will show all the available audio input sources for your selected devices.
  3. Make sure that all sources are selected, and click OK. The recording mixer will then display a volume control for the microphone and all other selected sources.
  4. Make sure that the microphone's Select check box is selected, and all other Select boxes are clear. In particular, do not select CD Audio. If CD Audio is selected and your user is listening to a CD while playing the game, DirectPlay Voice will transmit the output from the CD.
The following screen shot shows the Windows 2000 recording mixer.

Microphone Boost

Many sound cards have an option called "Microphone Boost" or "Mic Boost." This feature boosts the input volume so that weak input devices can produce stronger input. If you determine that the input level from a system is too low for your voice session, you can enable microphone boost.

To enable microphone boost

  1. Display the recording mixer, as described in the previous section.
  2. Enable the Advanced buttons on the mixer by choosing the Advanced command from the Options menu.
  3. Click the microphone line's Advanced button to display the microphone's Advanced Controls dialog box.
  4. Select the Microphone Boost check box.
If microphone boost makes your input too loud, you can use the same procedure to disable microphone boost. If your sound card does not support microphone boost, one or more of the following will be true.

  • The Advanced command on the recording mixer's Options menu will be unavailable.
  • The Advanced button in the recording mixer's microphone section will be unavailable.
  • The Microphone Boost check box on the Advanced Control dialog box will be unavailable.

Autoconfiguration

If you set the DVSOUNDCONFIG_AUTOSELECT flag in the dwFlags member of the DVSOUNDDEVICECONFIG structure, DirectPlay Voice will attempt to configure the recording portion of the audio mixer for you. However, the attempt might fail. For example, DirectPlay Voice always chooses microphone 0 as the input source. If your user's system has more than one microphone, autoselection works only if the user has the microphone connected to the microphone 0 input. To use another microphone channel, the user must configure the mixer manually.

Note To ensure that your application works on all systems, you should allow your users to disable autoselection if necessary and configure the mixer manually.

© 2002 Microsoft Corporation. All rights reserved.


Creating a 3-D Voice Session

You can add extra realism to a Microsoft® DirectPlay® Voice session by making the sound three-dimensional. Your players can then use audio cues to perceive the positions and movement of the other players. The basis for a 3-D voice session is the 3-D capabilities of Microsoft DirectSound®. This document discusses how to manage your voice buffers to create a 3-D voice session. For complete details about how to use the DirectSound 3-D application programming interface (API), see 3-D Sound.

Managing 3-D Voice Buffers

When you receive a voice transmission, it is streamed into a DirectSound buffer. By default, everything is streamed into the main buffer. To implement 3-D sound, you must have a separate buffer for each distinct source. You can then use the DirectSound 3-D API to manage the buffers to create 3-D sound.

You can specify separate 3-D buffers for individual players and for groups of players. To specify a 3-D buffer for a particular player or group, call IDirectPlayVoiceClient::Create3DSoundBuffer and pass the method either the player or group DVID. All transmissions from that player or group will then go into the specified 3-D buffer.

DirectPlay Voice 3-D buffers have the following characteristics.

  • If you do not specify a 3-D buffer for a player or group, those transmissions will be streamed into the main buffer.
  • If you specify a 3-D buffer for a player or group, those transmissions will not be streamed into the main buffer.
  • You can retrieve the 3-D buffer for the main buffer by calling IDirectPlayVoiceClient::Create3DSoundBuffer with DVID_REMAINING as the DVID.
  • A player's transmission can be streamed into multiple buffers that can be managed separately. For instance, if a player has a 3-D buffer and is also a member of a group with a 3-D buffer, the player's transmissions will be streamed into both buffers. For example, you might have the group's transmissions coming from a radio on a table. If the player runs by shouting, you can hear the player through the radio, with a fixed position, as well as from a moving sound source as the player runs by.
  • You can mute the main buffer by calling IDirectPlayVoiceClient::SetClientConfig and setting the DVCLIENTCONFIG_MUTEGLOBAL flag in the DVCLIENTCONFIG structure. If the main buffer is muted, your player will hear only those voice streams that have a 3-D buffer.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Voice Communication

The current trend toward team-based multiplayer games makes player-to-player communication an essential part of gameplay. Historically this has been confined to text-based communication, where players type out the messages to their teammates. Although suitable for slower, turn-based games, text-based communication is at best an inconvenience for real-time games. Not only does it put slow typists at a disadvantage during gameplay but also it is a significant break in the reality that games attempt to create for the player. An obvious solution to the problem is the use of speech as a means for communication. It requires no training and increases the immersion of the game itself.

The windows platform provides all the tools required to provide real-time voice conferencing to video game developers, but it requires a significant amount of effort on the part of the game developer. This, combined with the cost and difficulty of obtaining the rights to compression technology capable of handling extremely low bandwidth situations, has prevented the wide-spread use of voice in games.

Microsoft® DirectPlay® provides the game developer with a robust real-time voice conferencing system that requires a minimal amount of effort to use.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Voice Topologies

Microsoft® DirectPlay® Voice sessions require a DirectPlay network session to transport voice communication. Once the network session has been created, a DirectPlay Voice object can be created to use one of three topologies.

  • Forwarding Server Voice Topology
  • Mixing Server Sessions
  • Peer-to-Peer Voice Topology

The choice of topology is dependent on several factors, and these factors are discussed in the individual DirectPlay Voice topology topics. Note that not all voice topologies can be transported over all types of DirectPlay networking sessions.

© 2002 Microsoft Corporation. All rights reserved.


Forwarding Server Voice Topology

In a Microsoft® DirectPlay® voice session using a forwarding server topology, one computer in the session acts as a forwarding server. Each client in the voice session streams voice data to the forwarding server, which then forwards the voice data to all other clients in the session. Each client receives all incoming audio streams forwarded from the forwarding server. Each client's computer then mixes the incoming streams and plays them back.

The outgoing bandwidth requirement on each client in a voice session using a forwarding server topology is constant because there is only one outgoing voice audio stream. The incoming bandwidth and processor requirements are identical to the requirements of a voice session using a peer-to-peer topology, but they vary depending on the number of incoming voice audio streams.

The server has much higher bandwidth requirements than the individual clients in a forwarding server DirectPlay voice session. However, the processor requirements are not high because no compression or decompression of voice data occurs on the server. This reduced load on the computer's processor also means that an individual client's computer with a high bandwidth connection can host the forwarding server without adversely affecting the performance of the individual client's computer or the performance of a game server and/or client program running on the same computer.

Note that in a voice session using a peer-to-peer topology, the outgoing bandwidth requirements on the individual clients are usually much higher than the incoming bandwidth requirements. Therefore, reducing the outgoing bandwidth requirement to a single stream of audio can result in a significant reduction in total bandwidth usage. For example, if a client is taking part in an eight-person voice session in which all clients can hear one another, the client has seven outgoing voice streams each time voice data is captured and transmitted on his or her computer. However, it is rare that all clients talk at once, so there are most likely fewer than two or three incoming voice streams at any one time.

© 2002 Microsoft Corporation. All rights reserved.


Mixing Server Sessions

In mixing server sessions, one computer in the session acts as a mixing server. Each client streams its voice data to the mixing server. The mixing server examines the targets of each voice stream, performs decompression, mixing, and recompression as appropriate to generate a mixed stream of audio data for each client. Each client receives this single stream of premixed audio data and plays it back.

Diagram of a mixing server voice session

The outgoing bandwidth, incoming bandwidth, and CPU requirement on the client in a mixing server session is easily predictable because each client has only one outgoing stream of audio to compress and send, and one incoming stream of audio to decompress and play back.

The mixing server has much higher bandwidth and CPU requirements than do the clients. Typically, the mixing server is either a completely dedicated computer, or it shares a computer with a dedicated game server.

Mixing server voice sessions do not support 3-D spatialization of the voice data through the IDirectPlayVoiceClient::Create3DSoundBuffer method.

You can run mixing server voice sessions using either a peer-to-peer or a client/server transport session.

© 2002 Microsoft Corporation. All rights reserved.


Peer-to-Peer Voice Topology

In a Microsoft® DirectPlay® Voice session using a peer-to-peer topology, each voice-session client streams its voice audio data directly to every other voice-session client. Each client receives all individual incoming voice audio streams, mixes the received streams, and plays the resulting mixed signal on the client's computer.

Diagram of a peer-to-peer voice session

The advantage of using a peer-to-peer topology is that no computer in the voice session requires high bandwidth or processor power. However, the bandwidth and processor usage on each client's computer varies according to the number of incoming and outgoing audio streams. The number of outgoing voice audio streams is equal to the number of targets participating in the voice session, unless the network provider is capable of true multicasting, as noted below. The number of incoming voice audio streams depends on how many other voice-session clients are targeting the client in question and also on how many of the other clients are speaking.

As a game design consideration, it is not useful for a voice-session client to be the target of more than about six to eight other clients. If all six to eight clients are speaking at once, the conversation can become confusing, and communication between clients can be difficult.

If the DirectPlay network session supports true multicasting, the number of outgoing voice audio streams can be reduced considerably. If all clients are part of a multicast network and the target of the voice stream is a DirectPlay group, there is only one outgoing stream.

A DirectPlay voice session using a peer-to-peer voice topology supports 3-D spatialization of the voice data using the IDirectPlayVoiceClient::Create3DSoundBuffer method.

It is important to note that a voice session using a peer-to-peer voice topology cannot be used if the network transport is a client/server session.

© 2002 Microsoft Corporation. All rights reserved.


Fast User Switching

Unlike previous versions of Microsoft® Windows®, Windows XP allows multiple users to log on simultaneously. Each user account has its own running applications and settings. The current user does not need to log off in order to switch to a new user. The fast user switching feature of Windows XP basically disconnects the current user account and brings the newly connected user account to the foreground. The disconnected user's applications and desktop settings remain loaded and running in the background.

While fast user switching offers a new level of convenience for users, it must be handled properly. Applications that use shared resources need to ensure they don't interfere with the currently connected application. Microsoft DirectPlay® Voice applications use shared resources and have the potential to cause problems when users switch. In particular, voice transmissions from the disconnected DirectPlay Voice application could still be audible, interfering with the current user's applications. To prevent such problems, DirectPlay Voice automatically mutes voice transmissions when a user's account is disconnected and unmutes transmissions when the account is connected again. This feature relieves your DirectPlay Voice application of the need to detect and handle a user switch.

© 2002 Microsoft Corporation. All rights reserved.


Handling Voice Client Messages

This document describes how to handle messaging for a client of a Microsoft® DirectPlay® Voice session. For a discussion of host-related messaging, see Handling Voice Host Messages. For a discussion of general messaging issues, see Handling DirectPlay Messaging.

  • General Voice Messaging Considerations
  • Startup Messages
  • Messaging During Normal Game Play
  • Session Termination Messages

General Voice Messaging Considerations

Many of the messages used by DirectPlay Voice are similar to those used by the DirectPlay core application programming interface (API). However, be aware that similar core and voice messages sometimes differ in their usage.

For example, when you connect to either a core or voice session, DirectPlay returns a completion message with the results of your connection attempt. With a core session, you may get a DPN_MSGID_CONNECT_COMPLETE completion message under some circumstances, even when you connect synchronously. With DirectPlay Voice however, you will never get a completion message if you attempt to connect synchronously to a voice session. You get a DVMSGID_CONNECTRESULT completion message only if you connect to a voice session asynchronously.

One notable difference between core and voice message handling is that your core message handler receives every core message. With DirectPlay Voice, you have the option of specifying a list of messages that you want to receive by calling IDirectPlayVoiceClient::SetNotifyMask. You will receive only those messages that are on the notification list that you pass to this method through the pdwMessageMask parameter. This list must contain at least one message. You cannot use IDirectPlayVoiceClient::SetNotifyMask to disable all DirectPlay Voice messages.

Note DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Startup Messages

DirectPlay Voice is an optional addition to a regular DirectPlay session. It enables voice communication between the session members. Before you can become a client of a voice session, you must have created the appropriate DirectPlay object and be connected to a regular peer-to-peer or client/server session. See Peer-to-Peer Sessions or Client/Server Sessions for details.

Every voice session must have a host. If you are in a peer-to-peer session, one of the members must be selected as the voice session host. The voice host need not be the same member as the one that is hosting the core session. If you are in a client/server session, the server must host the voice session as well as the core session. When a session host has been determined, the host must start the voice session by creating a voice server object and calling IDirectPlayVoiceServer::StartSession. Once the session has been started, clients can connect.

This section outlines the messages that a voice client receives when joining a session.

  • DVMSGID_CONNECTRESULT

    Once the session is set up, clients must call IDirectPlayVoiceClient::Connect to connect to the voice session. If you call this method asynchronously and it returns DV_PENDING, you will receive a DVMSGID_CONNECTRESULT message with the result of the connection attempt. This message can arrive before or after IDirectPlayVoiceClient::Connect returns DV_PENDING. If you call the method synchronously, you will not receive a DVMSGID_CONNECTRESULT message. The result of a synchronous connection attempt is indicated by the method's return value.

  • DVMSGID_CREATEVOICEPLAYER

    Voice clients receive this message only if they are a member of a peer-to-peer voice session. After you are connected and have processed DVMSGID_CONNECTRESULT, you will receive a DVMSGID_CREATEVOICEPLAYER message for yourself and each member of the voice session. The structure that accompanies this message contains the DVID value that you will use to identify the player during the session. The dwFlags member of this structure contains two flags that describe the player. If the player is the local player, the DVPLAYERCAPS_LOCAL flag will be set. If the player is half-duplex, the DVPLAYERCAPS_HALFDUPLEX flag will be set.

    If you want to create a voice session player context value for the player, you must do so when you handle this message. For more information about player context values, see Using Player Context Values. You will receive no messages associated with a player until you have processed the corresponding DVMSGID_CREATEVOICEPLAYER message.

Messaging During Normal Game Play

Once you have successfully connected, there are a number of messages that you might receive during the course of a voice session. The list of possible messages depends on whether you are in a peer-to-peer or client/server voice session. As a general rule, voice clients in a client/server voice session do not receive any messages that are associated with a particular player.

Common Voice Messages

The following messages can be received by clients of both types of voice sessions.

  • DVMSGID_GAINFOCUS and DVMSGID_LOSTFOCUS

    These messages let you know whether you have capture focus and are capturing audio. When you gain capture focus and audio capture starts, you receive a DVMSGID_GAINFOCUS message. When you lose capture focus and audio capture stops, you receive a DVMSGID_LOSTFOCUS message. Both messages are simple notifications and do not have an associated structure. For more information about capture focus, see Capture Focus and Implementing a Callback Function in DirectPlay and DirectPlay Voice.

    Note Gaining or losing capture focus does not necessarily indicate the beginning or end of transmission. The beginning or end of transmission is indicated by the DVMSGID_RECORDSTART and DVMSGID_RECORDSTOP messages.
  • DVMSGID_RECORDSTART and DVMSGID_RECORDSTOP

    These messages notify you when the local player is transmitting. You receive a DVMSGID_RECORDSTART message when transmission starts and a DVMSGID_RECORDSTOP when transmission stops. The structure that accompanies these messages contains the voice player context value for the local player. What causes transmission to start and stop depends on whether you are using push-to-talk or voice activation transmission control and whether your application has gained or lost audio capture focus.

    The simplest case is when audio capture focus does not change. In that case, voice activated transmission starts when the user's voice exceeds the activation threshold. It stops when the voice drops below the activation threshold. With push-to-talk transmission, the user starts and stops transmission manually, typically by pushing and releasing a button.

    Even if the player has exceeded the voice activation threshold or pushed push-to-talk, the application must have capture focus in order to transmit. If the player is talking but the application does not have audio capture focus, transmission begins only when the application gains audio capture focus. You will receive a DVMSGID_GAINFOCUS message followed by a DVMSGID_RECORDSTART message at that time. If you lose audio capture focus while the player is still talking, transmission immediately stops and you receive a DVMSGID_LOSTFOCUS message followed by a DVMSGID_RECORDSTOP message. If you get audio capture focus back and the player is still talking, transmission will start again.

    You normally receive a DVMSGID_RECORDSTOP message when transmission stops, regardless of the reason. However, if you disconnect from the voice session while you are transmitting, you are not guaranteed to receive a DVMSGID_RECORDSTOP message.

    For details about capture focus, see Capture Focus. For details about transmission control, see Transmission Control.

  • DVMSGID_INPUTLEVEL and DVMSGID_OUTPUTLEVEL

    The DVMSGID_INPUTLEVEL message gives you the current audio input level from your player's microphone. The DVMSGID_OUTPUTLEVEL message gives you the current audio output level from your player's speakers or headphones. These messages are sent at a regular time interval. They start after you have processed a DVMSGID_RECORDSTART message and stop after you process the corresponding DVMSGID_RECORDSTOP message. To specify the rate at which the messages are sent, set dwNotifyPeriod member of the DVCLIENTCONFIG structure to an appropriate time interval. To suppress these messages, set dwNotifyPeriod to 0.

Peer-to-Peer Messages

The following messages can be received only by clients of peer-to-peer voice sessions.

  • DVMSGID_CREATEVOICEPLAYER and DVMSGID_DELETEVOICEPLAYER

    You receive a DVMSGID_CREATEVOICEPLAYER message each time a player is added to the voice session. You should handle this message in the same way as the player creation messages that you received when you connected to the session. When a player leaves the voice session, you receive a DVMSGID_DELETEVOICEPLAYER message. You will receive a DVMSGID_DELETEVOICEPLAYER message for every DVMSGID_CREATEVOICEPLAYER message. When you have processed a DVMSGID_DELETEVOICEPLAYER message, you will receive no further messages for that player.

  • DVMSGID_SETTARGETS

    The DVMSGID_SETTARGETS message is sent when the list of voice targets changes. It is generated any time a voice client calls IDirectPlayVoiceClient::SetTransmitTargets or a voice host calls IDirectPlayVoiceServer::SetTransmitTargets.

  • DVMSGID_PLAYERVOICESTART and DVMSGID_PLAYERVOICESTOP

    The DVMSGID_PLAYERVOICESTART message is sent when you start to receive a transmission from a player. If level notification is enabled, you will start receiving DVMSGID_PLAYEROUTPUTLEVEL messages. The DVMSGID_PLAYERVOICESTOP messages sent when that player's transmission stops. When you have processed this messages, the DVMSGID_PLAYEROUTPUTLEVEL messages stop. If audio capture focus changes, these messages are handled in essentially the same way as for DVMSGID_RECORDSTART and DVMSGID_RECORDSTOP. You will not receive these messages for a player until you have processed the corresponding DVMSGID_CREATEVOICEPLAYER message.

  • DVMSGID_PLAYEROUTPUTLEVEL

    The DVMSGID_PLAYEROUTPUTLEVEL gives you the current audio output level on your player's speakers or headphones for a particular player's transmission. These messages are sent at a regular time interval. They start after you have processed a DVMSGID_RECORDSTART message and stop after you process the corresponding DVMSGID_RECORDSTOP message. To specify the rate at which the messages are sent, set dwNotifyPeriod member of the DVCLIENTCONFIG structure to an appropriate time interval. To suppress these messages, set dwNotifyPeriod to 0.

  • DVMSGID_LOCALHOSTSETUP

    When the voice host migrates, the DVMSGID_LOCALHOSTSETUP message is sent to the new voice host. This message allows the new voice host to set the callback function and context value that will be used when creating the new voice server object. When your application returns from handling this message, you will receive a DVMSGID_HOSTMIGRATED message.

  • DVMSGID_HOSTMIGRATED

    When the host migrates, a DVMSGID_HOSTMIGRATED message is sent to all remaining members of the voice session. The associated structure contains the DVID of the new voice host. When the host migrates, DirectPlay Voice automatically creates a new voice server object. If your application is the new voice host, the DVMSGID_HOSTMIGRATED message's structure will also contain a pointer to the voice server's IDirectPlayVoiceServer interface. If you want to use this interface, you must call the interface's AddRef method to increment the interface's reference count. If you have called AddRef on IDirectPlayVoiceServer, be sure to call Release when you are finished with the interface.

Session Termination Messages

  • DVMSGID_DISCONNECTRESULT

    Disconnect from a voice session by calling IDirectPlayVoiceClient::Disconnect. If you call this method asynchronously and it returns DV_PENDING, you will receive a DVMSGID_DISCONNECTRESULT to notify you of the outcome. This message can arrive before or after IDirectPlayVoiceClient::Disconnect returns. The DVMSGID_DISCONNECTRESULT message is not sent if you call IDirectPlayVoiceClient::Disconnect synchronously. The result of a synchronous disconnection attempt is indicated by the method's return value.

    For peer-to-peer voice sessions, the client will receive a DVMSGID_DELETEVOICEPLAYER for every remaining player in the session—before the client receives DVMSGID_DISCONNECTRESULT.

  • DVMSGID_SESSIONLOST

    If the session terminates unexpectedly because of an unrecoverable error, clients will receive a DVMSGID_SESSIONLOST message. The reason for the failure is specified in the hrResult member of the associated structure.

    For peer-to-peer voice sessions, the client will receive a DVMSGID_DELETEVOICEPLAYER for every remaining player in the session—before the client receives DVMSGID_SESSIONLOST.

  • DVMSGID_DELETEVOICEPLAYER

    For peer-to-peer sessions, you will receive a DVMSGID_DELETEVOICEPLAYER for every player remaining in the voice session when you are disconnected, regardless of whether you call IDirectPlayVoiceClient::Disconnect or the session is lost. This ensures that each DVMSGID_CREATEVOICEPLAYER that you receive has a corresponding DVMSGID_DELETEVOICEPLAYER message. You will receive all DVMSGID_DELETEVOICEPLAYER messages before the disconnect is completed.

© 2002 Microsoft Corporation. All rights reserved.


Handling Voice Host Messages

Every Microsoft® DirectPlay® Voice session must have a host that is responsible for starting, managing, and terminating the session. A voice host must create a voice server object (CLSID_DirectPlayVoiceServer) and manage the voice session through that object's IDirectPlayVoiceServer interface. Like a voice client, a voice host must have a message handler and will receive messages during a session. A voice host message handler can receive any of the following three messages.

  • DVMSGID_CREATEVOICEPLAYER
  • DVMSGID_DELETEVOICEPLAYER
  • DVMSGID_SESSIONLOST

Unlike core DirectPlay messaging, none of these messages are unique to a voice session host. Depending on the type of session, these messages may also be received by voice client message handlers. This document gives a brief description of how a voice session host handles messaging. For specific details on how to handle these messages, see Handling Voice Client Messages. For a discussion of general messaging issues, see Handling DirectPlay Messaging.

Messaging During Normal Game Play

A client/server voice host will normally receive the following messages after the voice session starts.

  • DVMSGID_CREATEVOICEPLAYER

    You will receive a DVMSGID_CREATEVOICEPLAYER message every time a player joins your voice session.

  • DVMSGID_DELETEVOICEPLAYER

    You will receive a DVMSGID_DELETEVOICEPLAYER message every time a player leaves your voice session.

Session Termination Messages

A client/server voice host may receive one or more of the following messages when the voice session terminates.

  • DVMSGID_SESSIONLOST

    You will receive a DVMSGID_SESSIONLOST message if the underlying core session is disconnected. For example, the core session will be disconnected when the underlying DirectPlay peer or server transport object is closed, or when your host is disconnected from the network.

  • DVMSGID_DELETEVOICEPLAYER

    You will receive one DVMSGID_DELETEVOICEPLAYER message for each client remaining in the session when the voice session is terminated.

© 2002 Microsoft Corporation. All rights reserved.


Jitter Buffers

Microsoft® DirectPlay® Voice features a jitter buffer, an adaptive buffering algorithm that provides optimal voice quality with the least amount of latency.

On busy networks, individual packets of voice data information might arrive in a different sequence from that in which they were encoded on the host computer. Because voice data is sequential in nature, these incoming packets must be queued for a time so that delayed packets have an opportunity to arrive and be played back in order.

If the jitter buffer is set to maximize the quality of voice communication, it takes longer for the required number of voice packets to arrive and be queued for play. The result is voice latency, and the effect is that voice communication is not heard in real time. Instead, the voice data might be heard anywhere from a fraction of a second to several seconds after it was recorded. This can introduce problems during cooperative game play because events can occur in the game but players will not be able to communicate information based on those events in real time. For example, if a player in a first-person shooter is about to be attacked from behind and a teammate attempts to warn the player, the voice communication might not be heard until after the player has been attacked.

If the jitter buffer is set to a reduce latency, the number of packets required to fill the queue is reduced. However, it is possible that not all sequential packets will arrive in time and, as a result, voice data will be missing from the buffer when it is played. The voice communication will be heard much closer to the actual time it was recorded. However, it will have a "broken-up" quality.

The DirectPlay jitter buffer uses two methods to determine how to provide the best quality of voice communication with the least amount of latency. First, network conditions are monitored to determine the amount of lag or network congestion. The size of the jitter buffer, or queue, is then dynamically sized to keep latency as low as possible while providing the least amount of voice break up.

The default behavior of DirectPlay Voice jitter buffer is to automatically adjust to network conditions. You can manually adjust how closely the algorithm tracks network conditions using the dwBufferAggressiveness and dwBufferQuality members of the DVCLIENTCONFIG structure. The higher the level of "aggressiveness," the more closely the algorithm monitors network conditions. In general, the higher the quality value, the higher the quality of the voice, but the higher the latency as well. The lower the quality value, the lower the latency but the lower the quality of the voice. You can set these two members when you call IDirectPlayVoiceClient::Connect to connect to a session, and at any time during the session by calling IDirectPlayVoiceClient::SetClientConfig.

It is important to choose an appropriate level of aggressiveness for network conditions when your game application is running because selecting a high level of aggressiveness during times of steady network performance can cause the algorithm to misinterpret a transitory problem and overcompensate for a problem that might not exist.

© 2002 Microsoft Corporation. All rights reserved.


Sharing the Audio Capture Device

The most recent versions of Microsoft® Windows®, Windows Millennium Edition (Windows Me), and Windows XP allow the audio capture device to be shared between different processes. However, in Windows 95, Windows 98, and Windows 2000 operating systems, the audio capture device is a shared resource and can be opened by only one process at a time. To use audio capture on these operating systems, your application must be designed to effectively handle resource ownership and coordination issues. This document discusses how multiple Microsoft DirectPlay® Voice applications can share the same audio capture device on any Windows operating system.

Coordinating Shared Resources

Resource ownership becomes a problem when a physical resource such the audio capture device is a shared resource. If one application owns the shared audio capture device, other applications cannot open it. In the past, this limitation rarely posed problems because few applications used audio capture. However, the increasing popularity of technologies such as voice recognition means that applications can no longer assume that they can have exclusive ownership of the audio capture device. For instance, a lobby operator might want to implement a voice chat feature to help clients set up game sessions. However, if the lobby client application owns the audio capture device, the game application will not be able to use audio capture and its voice features will be effectively disabled.

Resource coordination is the process by which two or more applications manage ownership of a shared resource. For example, if two voice communication applications are running, the foreground application is typically the only application that needs the audio capture device. When focus changes, ownership of the audio capture device needs to shift to the new foreground application. For instance, after a group of players have finished using a lobby's voice chat feature to set up their session, they will launch their game applications. At that point, the game application moves to the foreground and acquires ownership of the audio capture device for game-related voice features.

DirectPlay Voice handles the problem of sharing the audio capture device through a feature called capture focus. Capture focus operates on a per-device basis, and allows multiple DirectPlay Voice applications to share a single audio capture device regardless of which version of Windows is installed on the system. As long as capture focus is enabled, any number of DirectPlay Voice application instances can have the same audio capture device open. Capture focus also provides a way for DirectPlay Voice applications to coordinate their use of the audio capture device. Capture focus is not available to applications that are not using DirectPlay Voice.

Using Capture Focus

DirectPlay Voice automatically coordinates the use of the audio capture device for all DirectPlay Voice applications that have enabled capture focus. If multiple DirectPlay Voice applications are running with capture focus enabled, focus is normally coordinated in the following way.

  • The application whose window is in the foreground has capture focus and can capture audio.
  • An application retains capture focus until another DirectPlay Voice application that has enabled capture focus gains the foreground.
  • None of the other applications can capture audio until they acquire capture focus.

The shift in capture focus normally occurs after the shift in window focus. Typically, your application will acquire capture focus one to two seconds after your window gains the foreground.

Capture focus is enabled by default. To disable capture focus, you must set the DVSOUNDCONFIG_NOFOCUS flag in the dwFlags member of the DVSOUNDDEVICECONFIG structure when you call IDirectPlayVoiceClient::Connect to connect to a voice session.

Note Use of the DVSOUNDCONFIG_NOFOCUS flag is not recommended. If you set this flag and an instance of your application successfully opens the audio capture device, no other DirectPlay Voice applications will be able to use that device.

To specify which window you want DirectPlay Voice to use for focus determination, assign its window handle to the hwndApp member of the DVSOUNDDEVICECONFIG structure when you connect to the voice session. You should use the window handle of your application's top-level window for focus determination. Do not use the desktop window. Doing so may lead to inconsistent determination of focus.

When capture focus shifts, DirectPlay sends a DVMSGID_LOSTFOCUS message to the application that has lost focus. Once an application receives this message, audio capture stops until the application regains focus. DirectPlay sends a DVMSGID_GAINFOCUS message to the application that has gained focus. This message indicates that the application has started capturing audio. It will continue to do so until it loses focus to another application.

Note This document describes how to share capture focus between different processes. However, it is possible to share capture focus among multiple instances within a single process if each instance has a unique window handle.

Strict Mode

By default, your application loses capture focus only if another capture focus-enabled DirectPlay Voice application gains the foreground. Your application can retain capture focus even if it is no longer the foreground application. It must only be higher in the z-order than any other capture focus-enabled application. If you want your application to have capture focus only when it is the foreground application, specify strict mode. In strict mode, a DirectPlay Voice application must be active and at the top of the z-order in order to have capture focus. If it loses that status to any other application, audio capture will cease. To specify strict mode, set the DVSOUNDCONFIG_STRICTFOCUS flag in the dwFlags member of the DVSOUNDDEVICECONFIG when you connect to the voice session.

Muting Capture Focus

You can give up capture focus programmatically by muting audio capture. To mute audio capture, call IDirectPlayVoiceClient::SetClientConfig, and set the DVCLIENTCONFIG_RECORDMUTE flag in the dwFlags member of the DVCLIENTCONFIG structure. When you mute audio capture, your application loses capture focus and the last application that had capture focus gains it again. If no other application has capture focus enabled, DirectPlay stops audio capture. You can unmute audio capture and attempt to regain capture focus by calling IDirectPlayVoiceClient::SetClientConfig without the DVCLIENTCONFIG_RECORDMUTE flag. However, this action does not necessarily return capture focus to your application.

  • If yours is the only capture focus-enabled application, you will immediately regain capture focus.
  • If your application is higher in the z-order than any other capture focus-enabled application, you will immediately regain capture focus even if you are not the foreground application. In particular, when you mute audio capture, capture focus often passes an application application below yours in the z-order. If that order does not change, you will regain capture focus when you unmute audio capture.
  • If capture focus has passed to another capture focus-enabled application that is higher than yours in the z-order, you do not immediately regain capture focus. Your application must become the foreground application in order to regain capture focus.
  • If you are in strict mode, you will regain capture focus only if your application is at the top of the z-order. Your application must become the foreground application in order to regain capture focus.

© 2002 Microsoft Corporation. All rights reserved.


Transmission Control

To keep the performance requirements of Microsoft® DirectPlay® Voice low, voice data should be transmitted only when the user is speaking. There are three ways to control voice data transmission.

  • Push-to-Talk
  • Manual Voice Activation
  • Automatic Voice Activation

You select which transmission control method to use when you call IDirectPlayVoiceClient::Connect to connect to a voice session. To specify the type of transmission control you want to use, set the appropriate flag in the DVCLIENTCONFIG structure's dwFlags member. You can change the method during the session by calling IDirectPlayVoiceClient::SetClientConfig and changing the flag setting.

Push to Talk

Push-to-talk transmission control is analogous to pushing the Talk button on a two-way radio. It adds reality to certain game genres such as first-person shooters. Push-to-talk requires users to actively select when they want to transmit voice data. There is no danger that anything besides voice data will activate transmission. In addition, requiring users to actively select when they want to speak reduces the number of users speaking at once.

Push-to-talk transmission control requires more design and development than voice activation. In particular, you must have some way of detecting when the user has chosen to start transmitting, typically by pushing a controller button or a key on the keyboard. When you detect that the user wants to start talking, you must start transmission by calling IDirectPlayVoiceClient::SetTransmitTargets, and provide an array of target identifiers (IDs) that will receive the transmission. When you detect that the user is finished, stop transmission by calling IDirectPlayVoiceClient::SetTransmitTargets again, with the target array set to NULL and the number of targets set to 0.

Push-to-talk is the default transmission control method. It is enabled unless you explicitly select voice activation by setting the DVCLIENTCONFIG_AUTOVOICEACTIVATED or DVCLIENTCONFIG_MANUALVOICEACTIVATED flag in the DVCLIENTCONFIG structure.

Voice Activation

With voice activated transmission control, the microphone input is constantly analyzed to determine if the user is speaking. When the input exceeds a threshold level, voice activation is triggered, and the user begins transmitting. Ideally, transmission starts when the user starts speaking, and stops when the user finishes.

Voice activation is simpler for the user than push-to-talk, because the user must only speak into the microphone. It is also more easily coded because you do not need to detect when the user wants to start or stop transmitting. You specify voice activation when you connect, and transmission control is handled by the system from that point on. However, one drawback of voice activation is that it can result in unwanted transmissions. In addition to speech, transmission can be triggered by sounds such as the user breathing directly on the microphone, high levels of ambient sound in a noisy environment, or a set of external speakers playing the game's audio background. Low-quality microphones can increase the probability of unwanted transmission.

Voice activation can be either automatic or manual. To specify one of these modes, set the DVCLIENTCONFIG_AUTOVOICEACTIVATED or DVCLIENTCONFIG_MANUALVOICEACTIVATED flag, respectively, when you connect to the voice session.

Automatic voice activation is the preferred transmission control method for most applications. In this mode, the threshold for transmission is determined automatically by the system. The threshold level is adaptive, adjusting itself automatically to the input signal.

With manual voice activation, you must explicitly set a threshold when you connect to the voice session by assigning a value to the dwThreshhold member of DVCLIENTCONFIG. The system will not change this value for you. If conditions change, and the threshold value is no longer adequate, you must call IDirectPlayVoiceClient::SetClientConfig and specify a new value for dwThreshhold.

© 2002 Microsoft Corporation. All rights reserved.


Voice Codecs

The compression/decompression (codec) algorithms provided with Microsoft® DirectPlay® are optimized for low-bandwidth voice compression and decompression. These codecs all operate on 8 kHz, 16-bit mono-format based data. However, DirectPlay Voice handles all the details of converting voice data to and from this intermediate format. Third-party codecs are not supported, and you cannot write proprietary codecs for use with DirectPlay Voice.

It is important to note that as the bandwidth requirements drop, the audio quality of the voice data also drops. The following table lists the supported codecs, the bandwidth in kilobits per second (Kbps), and the compression globally unique identifier (GUID) used to select them. The compression GUIDs are defined in Dvoice.h.

Codec | Bandwidth | GUID
Voxware VR12 | variable (1.2 Kbps, avg.) | DPVCTGUID_VR12
Voxware SC03 | 3.2 Kbps | DPVCTGUID_SC03
Voxware SC06 | 6.4 Kbps | DPVCTGUID_SC06
TrueSpeech | 8 Kbps | DPVCTGUID_TRUESPEECH
Global System for Mobile Communications (GSM) | 13 Kbps | DPVCTGUID_GSM
Microsoft Adaptive Delta Pulse Code Modulation (MS-ADPCM) | 32 Kbps | DPVCTGUID_ADPCM
Pulse Code Modulation (PCM) | 64 Kbps | DPVCTGUID_NONE

The first three codecs provide a high level of compression and have approximately the same resource demands. On a 500 MHz Pentium III class computer, these codecs use approximately 1.5 percent of the CPU capacity. The VR12 codec sounds tinny and robotic, but the SC03 and SC06 codecs provide reasonable fidelity. The PCM codec provides the highest sound quality and is essentially uncompressed 8 kHz 16-bit mono-format audio data.

Note The GSM, ADPCM, and PCM codecs are included with the Microsoft Windows® installation but might not have been installed by the user. You might need to prompt the user to install them. You can determine which codecs are available on a system by calling IDirectPlayVoiceServer::GetCompressionTypes. If a codec is not listed, the corresponding ACM codec is not installed.

Selecting a Codec

As with all other game setup parameters, the host controls which codec is used for the voice session. All members of the voice session must use the same codec. Remember that in a peer-to-peer voice session, the voice-session host does not necessarily have to be the same as the game-data host. The host selects the codec when it calls IDirectPlayVoiceServer::StartSession. Set the guidCT member of the DVSESSIONDESC structure to the compression GUID of the codec that you want to use. A client can retrieve this structure by calling IDirectPlayVoiceClient::GetSessionDesc.

The same codec might not be ideal for the entire duration of a game. For instance, you might want to use one codec for the lobby chat feature that players use to set up the game, and another to handle voice communication after the game is launched. You cannot dynamically change codecs during a voice session. To switch to another codec, you must terminate the current voice session and create a new voice session with the new codec. However, you can stop and restart a voice session without terminating the underlying DirectPlay core session.

As with any form of network communication, it is important to analyze the cost of the voice communication to ensure that adequate bandwidth is available to support communication of the game data and voice data. Analyzing the voice bandwidth consumption is straightforward: Estimate the number of simultaneous voice streams that you anticipate and multiply that number by the sum of the bandwidth required by the codec and the protocol overhead. CPU consumption is another factor to consider when choosing a codec. As with network bandwidth, CPU resource consumption is additive, per stream.

© 2002 Microsoft Corporation. All rights reserved.


Voice Host Migration

In a peer-to-peer Microsoft® DirectPlay® network session, one client of the networking session acts as host. If that host exits the session or stops responding for any reason, another client in the session is elected as host.

In a DirectPlay voice session, a similar process of host migration occurs in peer-to-peer voice sessions, except that the voice host migrates independently of the DirectPlay network session. The voice host migrates when the server calls IDirectPlayVoiceServer::StopSession or if the voice host stops responding.

When the voice host migrates, the new host's voice client message handler receives a DVMSGID_LOCALHOSTSETUP message. The primary purpose of this message is to allow the new host to provide DirectPlay with a pointer to the callback message handler that will receive voice server messages. To specify your callback message handler, set the value of the pMessageHandler member of the DVMSGID_LOCALHOSTSETUP structure to point to your voice server message handler before you return from the client message handler. The new host can also specify a voice server context value by setting the value of the pvContext member of the structure.

Each client in the voice session receives a DVMSGID_HOSTMIGRATED message with the DVID of the new host. The client that is chosen as the new host also receives a valid IDirectPlayVoiceServer pointer, which the client can use to call the voice server methods. The new host does not receive DVMSGID_HOSTMIGRATED until after it has processed DVMSGID_LOCALHOSTSETUP.

© 2002 Microsoft Corporation. All rights reserved.


Working Set Guidelines

Determining the best configuration of transport topology, voice topology, transmission control, and codec depends on the type or genre of game you are creating, the number of players that will participate in a single game session, and the type of connection that will be targeted.

It's important to note that the number of players participating in the voice session is not necessarily the number of players actually participating in the game session. For example, if your game is a first-person shooter, voice communication can be represented in the game as a radio or communicator that is offered as a time-limited powerup. Also, the radio metaphor can be used to limit communication to radios in either vehicles or stationary command stations.

A second example to consider is an online bridge game, which involves four players at one time. Because this is a small working set, it is appropriate to choose a peer-to-peer voice topology transported over a peer-to-peer network topology. This small working set also allows for the use of voice activation as the mode of transmission control. The peer-to-peer voice topology is easily implemented and does not require any player to act as a server. If all four players use the Voxware SC6 codec, the maximum resulting bandwidth is 4.2 Kbps per speech stream, including the codec protocol overhead. Further assuming that game data requires negligible bandwidth, the outgoing maximum bandwidth requirement for an individual speaker is three independent streams to the other three players, or 12.6 Kbps. The incoming stream to any client ranges from 0 if no other players are talking, to 12.6 Kbps if all three other players speak simultaneously. The CPU requirement is 8 percent for encoding and 0 to 12 percent for decoding. This results in a worst-case requirement of 25.2 Kbps. Therefore each player must have a minimum of a 14,400-baud modem.

Another example is a squad combat game that can involve up to 32 players split between 2 teams. Assume that the game data requires a 28,800 baud modem. In this example, there is a larger number of players and it is appropriate to choose a forwarding server voice topology. Again, if all players use the Voxware SC6 codec, the bandwidth requirements are the same as the bridge game above: 4.2 Kbps. In this example, note that there is 4.2 Kbps outgoing when speaking, and a maximum of 12.6 Kbps incoming from the squad. The maximum CPU requirement is 8 percent of a Pentium 200 for encode and 12 percent receiving. Therefore, each player requires 28.8 Kbps for game data, and the greater incoming bandwidth of 12.6 Kbps requires a minimum 41,400 baud rate from each player's modem.

The worst-case scenario for the forwarding server itself is if all 32 players talk at once, requiring 134.4 Kbps. The server CPU use is minimal because the server is not encoding or decoding the streams. It is merely redirecting them. More typically, there might be 16 players talking simultaneously for 67.2 Kbps.

To illustrate the difference between choosing a mixing server voice topology and a forwarding server voice topology, consider the same 32-player squad combat game discussed above. If a mixing server voice topology is used, each client requires 4.2 Kbps to send and 4.2 Kbps to receive. The worst-case bandwidth requirements drop to 8.4 Kbps and 12 percent of the Pentium processor running at 200 MHz. This reduces the modem requirement to a 33,600 Kbps baud rate for the client.

For the server, the CPU burden changes. The server is now decoding and re-encoding all incoming streams and is also mixing the streams as required. The CPU burden mix the stream is relatively low and is considered negligible. The worst case is the decoding and encoding of 32 simultaneous streams. This results in a requirement of at least a Pentium II processor running at 400 MHz for the voice service alone.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay for Pocket PC 2002

Beginning with Microsoft® DirectX® 8.1, the Microsoft DirectPlay® application programming interfaces (APIs) are available for the Microsoft Windows® Powered Pocket PC 2002. The implementation of the APIs is the same on all platforms, with the following exceptions for Pocket PC 2002.

  • The DirectPlay Voice APIs are not available.
  • Only the IPv.4 service provider and Bluetooth Service Provider are available. The IPv.4 service will function over the wireless 802.1x network. Currently, serial, modem, and Internetwork Packet Exchange (IPX) are not available.
  • Because pop-up windows are not available on the Pocket PC 2002, the DPNHOST_OKTOQUERYFORADDRESSING, DPNCONNECT_OKTOQUERYFORADDRESSING, and DPNENUMHOSTS_OKTOQUERYFORADDRESSING flags cannot be used.

© 2002 Microsoft Corporation. All rights reserved.


Bluetooth Service Provider

The Bluetooth wireless technology service provider is a low-cost, low-power wireless technology designed to simplify setting up network connections between devices. This topic describes how to use Bluetooth with the Microsoft® Windows® Powered Pocket PC 2002.

Note The Bluetooth service provider in Microsoft DirectPlay® is only supported with the Pocket PC 2002. It is not available for the desktop version. Applications wishing to operate between the desktop and the Pocket PC 2002 should use the DirectPlay Internet Protocol (IP) service provider.

Native Bluetooth support in DirectPlay is designed for hosting sessions where all players in the session are also using the Bluetooth service provider. In this scenario, all players must be located within Bluetooth radio range of each other to participate. DirectPlay does not support using a mixture of service providers within a single session. Note that Bluetooth can also be used as an access technology for other network types. For example, a player might obtain IP connectivity using a Bluetooth Network Access Point. In this case the Bluetooth device is essentially invisible to DirectPlay, and an application should use the IP service provider instead.

The Bluetooth service provider for DirectPlay provides feature parity with the IP service provider. All session types are supported—client, server, and peer—together with the full set of features from each. However, some minor variations in setting up addresses and enumerations with Bluetooth are described here.

Addressing

Applications should always check to see if the Bluetooth service provider is available before attempting to use it or offering it as an option to the user. Use the IDirectPlay8Peer::EnumServiceProviders or IDirectPlay8Client::EnumServiceProviders or IDirectPlay8Server::EnumServiceProviders method to see if Bluetooth is available.

If the Bluetooth service provider is found, applications should set Bluetooth as the service provider for the address object by calling IDirectPlay8Address::SetSP as illustrated in the following example.

IDirectPlay8Address*	pAddress;
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &pAddress);
.
.
.
pAddress->SetSP(&CLSID_DP8SP_BLUETOOTH);

When creating IDirectPlay8Address objects, applications need to specify the address of the host device with the Host Name address component. Each host name should be specified as a string using hex format as shown in the following example.

WCHAR * wszDeviceAddress=L" 50c20003c418";
pAddress->AddComponent(DPNA_KEY_HOSTNAME, wszDeviceAddress,
(wcslen(wszDeviceAddress)+1)*sizeof(WCHAR), DPNA_DATATYPE_STRING );

Address objects supplied to the application from DirectPlay as the result of an enumeration operation may be enhanced by adding the name information component. This specifies the name of the Pocket PC 2002 device the address represents and provides a more user friendly string to present rather than the Bluetooth device address. Therefore, applications should test for the presence of the DPNA_KEY_NAMEINFO field when displaying the result of enumerations and present it to the user if possible. Note that this field is purely an informative one and is not used by DirectPlay in anyway. Applications creating their own address objects rather than obtaining them using enumerations should always use the DPNA_KEY_HOSTNAME field to specify the address of a remote device. Connecting to a device using purely the DPNA_KEY_NAMEINFO component is not supported.

Enumeration

When enumerating Bluetooth devices, DirectPlay first attempts to discover all the Bluetooth devices in the area. Each device found is contacted one at a time and sent an enumeration request. This process is hidden from the application but the initial device discovery process can take 10 or more seconds to complete. Therefore, a call to IDirectPlay8Peer::EnumHosts or IDirectPlay8Client::EnumHosts will generate no responses initially and then a rapid sequence of responses after about 10 seconds.

Because of the time it takes to enumerate and because Bluetooth addresses are fixed for each device, it is recommended that applications provide a mechanism to store the last few addresses to which a player connected. This allows a user to pick from a list of recent connections rather than needing to type in a hexadecimal address each time or wait for the enumeration to complete.

A call to EnumHosts works slightly differently with the Bluetooth service provider. The following parameters are different.

  • dwEnumCount is unused.
  • dwRetryInterval determines the period in milliseconds that DirectPlay waits for a response from a single device before moving onto the next device.
  • dwTimeout determines the total period allowed for the enumeration operation.

Note Setting dwTimeout to less than 15 seconds is pointless, given the minimum discovery period outlined above. The recommended approach is to set this value to Infinity, and wait for the user to either cancel the enumeration or select a session.

Attempting to connect to or host a session automatically cancels any running enumeration. When connecting causes the enumeration cancellation, the result code for the enumeration supplied in the DPN_MSGID_ASYNC_OP_COMPLETE message will be DPNERR_CONNECTING. When hosting causes the enumeration cancellation, the result code will be DPNERR_HOSTING.

Session Limitations

Due to the limits of the Bluetooth specification, the maximum number of devices supported in a peer-to-peer session is eight. For a client/server session, up to seven clients can connect to a single server.

Host migration can take several seconds in Bluetooth, and during this period no data transmission occurs between devices. Therefore, if the host player drops from the game, any messages sent by the remaining players will be queued during the time it takes to reestablish the network connectivity.

Bluetooth is essentially a client/server architecture. Although DirectPlay hides this and offers a peer-to-peer mode with host migration, all data still has to be routed through the host in this scenario. Applications should consider this when making assumptions about latency and available bandwidth.

© 2002 Microsoft Corporation. All rights reserved.


Advanced Topics in DirectPlay

This section of the Microsoft® DirectPlay® documentation is designed to show you how to use the DirectPlay application programming interface (API) to implement important aspects of multiplayer applications.

Overviews

  • DirectPlay Addressing
  • DirectPlay Callback Functions and Multithreading Issues
  • DirectPlay Protocol
  • DP8Sim Utility
  • Monitoring DirectPlay Network Traffic with Netmon
  • Network Address Translation, Firewalls, and Proxies
  • Optimizing Network Usage
  • Packet Signing
  • Testing Network Performance
  • Using Player Context Values
  • Using the DirectPlay DPNSVR Application

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Addressing

To deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer to either the computer on which your application is running (device address), or a computer with which your application needs to communicate (host address).

Microsoft® DirectPlay® represents addresses in the form of a URL string. That address string is then encapsulated in a DirectPlay address object that is passed as a parameter in or out of methods such as IDirectPlay8Peer::Connect.

This section describes three ways of handling DirectPlay addresses.

  • DirectPlay Service Providers discusses what service providers are, and which ones are available with DirectPlay.
  • Understanding Ports discusses what ports are, and how to use them.
  • Internet Protocol Version 6 discusses how to use IPv6 with DirectPlay.
  • DirectPlay URLs discusses how to construct the address string directly.
  • Handling Addresses discusses how to pass address objects in the Host, EnumHosts, or Connect methods.
  • DirectPlay Address Objects discusses how to manipulate the address string using the methods exposed by the address object's IDirectPlay8Address interface.
  • Data Value Summary contains a table listing all the possible data values associated with DirectPlay addresses and shows which values are required for each service provider.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Service Providers

Microsoft® DirectPlay® provides your application with a virtual network connection that enables you to communicate with other computers in the same way, regardless of type of network involved. To provide this level of abstraction, network connections are made through a service provider. When you have selected a service provider, your application uses the appropriate DirectPlay methods to communicate with other computers in a session. The service provider handles the details of communicating over the selected network hardware.

DirectPlay includes service providers for four types of network connections: Transmission Control Protocol/Internet Protocol (TCP/IP), Internetwork Packet Exchange (IPX), modem, and serial. See DirectPlay Address Objects for a discussion of how to select a service provider.

Note DirectPlay uses the telephony application programming interface (API) (TAPI) to handle modem communication. The use of this API means that the code that is used to answer the phone must be in the message loop's thread.

© 2002 Microsoft Corporation. All rights reserved.


Understanding Ports

This topic explains how to select a game port. Ports are an important part of addressing for Internet Protocol (IP) and Internetwork Packet Exchange (IPX) service providers. In cases where each computer has a unique IP address, the port specifies the application running on the computer. Microsoft® Windows® allows only one application per port. So if a user were playing a networked game, sending e-mail, and downloading files at the same time, each application would be bound to a different port. Each message received would have a port number in its address so that it could be passed to the correct application.

In cases where computers are behind a Network Address Translation (NAT) device and sharing a single public IP address, the port not only specifies the application but also the computer on which the application is running. So, if three computers sharing the same IP address were running the same application, each application would be bound to a different port, allowing messages to be delivered to the correct computer and application.

Also, if you specify a port, you don't need to use DPNSVR, which makes NAT device administration easier for users. Your application should choose a default port but allow users to override that port in case it is already in use. For more information about configuring game ports when players are behind NAT devices, see Network Address Translation, Firewalls, and Proxies.

Note Ports are not used for serial or modem service providers.

Setting a Port

Set a port by calling the IDirectPlay8Address::AddComponent method. In the following example, port 12345 is selected.

IDirectPlay8Address* pAddress;
DWORD dwPort;
...
dwPort = 12345;
hr = pAddress->AddComponent(DPNA_KEY_PORT, &dwPort, sizeof(dwPort),DPNA_DATATYPE_DWORD);

The port is specified as a DWORD, although the port number is limited to 65535 (2 bytes) and is used in host byte order. When selecting a port, do not choose a reserved port.

Reserved Ports

All ports under 1024 are reserved.

Also, Microsoft DirectPlay® has reserved the following ports.

Port | Reserved for
1900 | Universal Plug and Play - Simple Service Discovery Protocol
2302-2400 | DirectPlay device address default
2234 | Internet sharing and firewall support for Windows Millennium Edition (Windows Me) and Windows XP
6073 | DirectPlay enumerations using DPNSVR
47624 | Deprecated DirectPlay enumeration

The Internet Assigned Numbers Authority World Wide Web link maintains a list of registered User Datagram Protocol (UDP) ports that you should avoid using.

© 2002 Microsoft Corporation. All rights reserved.


Internet Protocol Version 6

The Internet Protocol (IP) is the foundation upon which all Internet traffic is based. The current version, Internet Protocol version 4 (IPv4), has remained unchanged for over two decades. While this is a testament to its original design, no one ever envisioned the unprecedented growth the Internet has seen. The demand for unique addresses used to route traffic through this network has grown so large that many are predicting the supply will be exhausted in a few short years. Technologies such as Network Address Translation (NAT) have only marginally extended the IPv4 lifetime at the cost of end-to-end connectivity for many applications such as games. Internet Protocol version 6 (IPv6) is the next generation networking protocol designed to address this and many other concerns.

The Microsoft® DirectPlay® Transmission Control Protocol/Internet Protocol (TCP/IP) service provider supports both IPv4 and IPv6 transparently. This ensures that the application you write today will automatically take advantage of the IPv6 features as its adoption becomes more widespread. The only behavior required of your application is that it should treat the value of the DPNA_KEY_HOSTNAME address component returned by DirectPlay as a string. Your application should not expect it to be in an IPv4 address, formatted using decimal dotted notation. The DPNA_KEY_HOSTNAME component can be an IPv4 address, an IPv6 address, or a Domain Name System (DNS) hostname string. You should simply display DPNA_KEY_HOSTNAME as a string without parsing. Alternatively, use match-making services or friendly player names to hide the address complexity from the user altogether.

For more information about creating TCP/IP protocol DirectPlay addresses, see Creating TCP/IP Address Objects. For more information about match-making services, see DirectPlay Lobby.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay URLs

Microsoft® DirectPlay® represents addresses as URLs. In general, URLs are strings that consist of three basic components in the following order: scheme, scheme separator, and data string.

All DirectPlay addresses use "x-directplay" as the scheme, and ":/" (a colon followed by a forward slash ) as the scheme separator. Using ":/" as a separator implies that the data that follows is opaque. In other words, the data string does not conform to any Internet standard and should be passed to the receiving application without modification. All DirectPlay URLs thus have the following general form.

x-directplay:/[data string]
Note Do not use "://" (a colon followed by two forward slashes) as a scheme separator. That separator implies that the data that follows conforms to an Internet standard and can be interpreted as such. To prevent confusion, DirectPlay flags any URL containing "://" as invalid.

This section discusses the following topics.

  • Data Strings
  • Sample URLs

© 2002 Microsoft Corporation. All rights reserved.


Data Strings

The data string holds address information. The first part of a data string consists of a series of keyname= value elements separated by semicolons (;). You can include optional user data by putting a number sign (#) after the last value, followed by an application-defined string.

The key name is a lowercase string that identifies the data and implicitly indicates what type of data is contained in the value. For instance, the "provider" key name indicates that the value contains a Microsoft® DirectPlay® service provider globally unique identifier (GUID), in the form of a GUID string. The following characters are reserved and should not be used in value strings.

Ampersand (&) | Forward slash (/)
At sign (@) | Number sign (#)
Colon (:) | Question mark (?)
Equal sign (=) | Semicolon (;)

The first element in the data string must be the provider. Other elements can follow in any order. A generic URL looks something like this.

x-directplay:/provider=Provider_GUID;[keyname1=value1];[keyname2=value2][...]#[user defined string]

The Provider_GUID should be of the form

{EBFE7BA0-628D-11D2-AE0F-006097B01411}

but using the escape characters for the invalid characters as shown in the following example.

%7BEBFE7BA0-628D-11D2-AE0F-006097B01411%7D

© 2002 Microsoft Corporation. All rights reserved.


Sample URLs

The following sample URLs illustrate what a Microsoft® DirectPlay® URL might look like for the four standard service providers. Each GUID expression should start with %7B and end with %7D, which are the escape characters for { and }.

Local IP Address

x-directplay:/provider=%7BEBFE7BA0-628D-11D2-AE0F-006097B01411%7D;device=IP ADAPTER GUID;port=0000230034#IPUserData

Local IPX Address

x-directplay:/provider=%7B53934290-628D-11D2-AE0F-006097B01411%7D;device=IPX ADAPTER GUID;port=00230#IPXUserData

Local Serial Address

x-directplay:/provider=%7B743B5D60-628D-11D2-AE0F-006097B01411%7D;device=COM PORT GUID;baud=57600;stopbits=1;parity=NONE;flowcontrol=RTSDTR#SerialUserData

Remote Modem Address

x-directplay:/provider=%7B6D4A3650-628D-11D2-AE0F-006097B01411%7D;device=MODEM DEVICE GUID;phonenumber=555-1212#ModemUserData

© 2002 Microsoft Corporation. All rights reserved.


Handling Addresses

If you call the Host, EnumHosts, or Connect methods exposed by the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server you must pass address objects as parameters. If Microsoft® DirectPlay® does not have sufficient address information, the method that you called will fail, and it will return DPNERR_ADDRESSING. However, it is not necessary to have all the information in the address object at the time you call the method.

All address objects must have the service provider globally unique identifier (GUID) set. However, it is possible to omit other data values.

  • You can omit the device if the service provider supports all adapters.
  • You can omit the port number for Internet Protocol (IP) and Internetwork Packet Exchange (IPX) service providers for the Host, EnumHosts, and Connect methods. DirectPlay will assign a port number. This number may vary.
  • If you set the OKTOQUERYFORADDRESSING flag, the service provider can display a dialog box asking the user for the information needed to complete the address. If the user does not supply sufficient information, the method will fail. If the OKTOQUERYFORADDRESSING flag is not set, no dialog box will be displayed. If the address you pass to the method is insufficient, the method will fail. In the last two cases, the error value that is returned will be DPNERR_ADDRESSING.

There are two important issues for IP and IPX service providers that you need to be aware of. Failing to handle them properly may cause your application to fail.

  • If you set the NOBROADCASTFALLBACK flag when you call an enumeration method, you must supply a hostname. If you do not do so, the method will fail and return DPNERR_ADDRESSING.
  • If you do not specify a port, do not assume that DirectPlay will always choose the same port number. The only way to be certain of the port number is to specify it in your address. If you do not specify a port number, you must retrieve the actual value later, after the command is in progress.
Note Application developers who choose to override the default DirectPlay 8 dialog for Transmission Control Protocol/Internet Protocol (TCP/IP) are strongly urged to implement a solution that allows the user to override the port used for a connection or enumeration. One possible solution is to enable users to follow the host name with a colon and then the port, as implemented by the default DirectPlay 8 TCP/IP protocol dialog, for example: host.domain.com:8090. Another possible solution is to add a field to the user interface (UI) that enables the user to enter a port.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Address Objects

Microsoft® DirectPlay® does not handle URL strings directly. Instead, the string must be encapsulated in a DirectPlay address object (CLSID_DirectPlay8Address). This object exposes the IDirectPlay8Address interface that enables you to insert URL information into, or extract it from, the address object.

To create DirectPlay address, you must call CoCreateInstance to create a DirectPlay address object. You can then define the address in one of two ways:

  • Create the URL string directly. Then use either IDirectPlay8Address::BuildFromURLA or IDirectPlay8Address::BuildFromURLW to insert the complete string.
  • Use IDirectPlay8Address methods to insert the various pieces of data that make up the string directly into the object. For details see:
    • Creating TCP/IP Address Objects
    • Creating Modem Address Objects
    • Creating IPX Address Objects
    • Creating Serial Address Objects

When you receive an address object, you have a similar pair of options.

  • Extract the entire URL string with either IDirectPlay8Address::GetURLA or IDirectPlay8Address::GetURLW. Then parse the string and extract the needed information
  • Use other IDirectPlay8Address methods to extract the particular data you are interested in from the address object.

© 2002 Microsoft Corporation. All rights reserved.


Creating TCP/IP Address Objects

This topic discusses how to create typical Address objects using the IDirectPlay8Address methods for Transmission Control Protocol/Internet Protocol (TCP/IP) service providers.

The first step in creating an address object is to call CoCreateInstance to create an IDirectPlay8Address object. The parameters include the class identifier of an address object (CLSID_DirectPlay8Address), the identifier of the interface (IID_IDirectPlay8Address), and the address of a pointer to an IDirectPlay8Address interface. The following example illustrates how to create an address object.

IDirectPlay8Address*  g_pDeviceAddress;
.
.
.
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &g_pDeviceAddress );

For more information about using CoCreateInstance, see Creating a COM Object.

After creating the address object, you must set the service provider component, at a minimum. To do that, call IDirectPlay8Address::SetSP. The following example illustrates how to set the service provider to the Microsoft® DirectPlay® TCP/IP protocol service provider.

hr = g_pDeviceAddress->SetSP(&CLSID_DP8SP_TCPIP );

The EnumHosts, Connect, and Host methods each have an OKTOQUERYFORADDRESSING flag (DPNENUMHOSTS_OKTOQUERYFORADDRESSING, DPNCONNECT_OKTOQUERYFORADDRESSING, and DPNHOST_OKTOQUERYFORADDRESSING) that allow DirectPlay to prompt the user for any missing information in the address beyond the service provider component. However, for most applications you will want to override these standard dialogs to improve the user experience. The following sections describe the common and required components used for the TCP/IP protocol service providers.

Device Addresses

If you are creating a device address for the local player and using TCP/IP protocol as your service provider, you may also want to set the device port. For a list of other data values you may set, see Data Value Summary.

The following example illustrates how to set the port for a device address using the IDirectPlay8Address::AddComponent method.

DWORD dwPort;
// Set dwPort to the port number for the device address.

hr = g_pDeviceAddress->AddComponent( DPNA_KEY_PORT,           //pwszName
                                   &dwPort, sizeof(dwPort),   //lpvData, dwDataSize
                                   DPNA_DATATYPE_DWORD );     //dwDataType

If you set the port for the player hosting the session, it is recommended that you also set the DPNSESSION_NODPNSVR flag in the DPN_APPLICATION_DESC structure passed in the Host method. However, if you disable DPNSVR, you should do one of the following:

  • Specify the host port in the pdpaddrHost parameter when you call EnumHosts.
  • Specify the host port in the pHostAddr parameter when you call Connect.

Host Addresses

If you are creating a host address and using TCP/IP protocol as your service provider, you may need to set the host name address component. For a list of other data values you may set, see Data Value Summary. If you did not use EnumHosts to find a session and do not pass the DPNCONNECT_OKTOQUERYFORADDRESSING flag to Connect, the host name must be specified for the host address.

The following example illustrates how to set the host name for a host address using the IDirectPlay8Address::AddComponent method.

size_t cb;
WCHAR wstrIP[MAX_PATH];
// Set wstrIP to the host IP address
hr = StringCbLengthW(wstrIP, MAX_PATH, &cb);

hr = g_pHostAddress->AddComponent(DPNA_KEY_HOSTNAME,        //pwszName
                                  wstrIP,                   //lpvData
                                  cb,                       //dwDataSize in bytes
                                  DPNA_DATATYPE_STRING );   //dwDataType

In this example, wstrIP contains the Internet Protocol (IP) address or name of the session host in dotted notation, that is, the string "123.123.123.123" or "DirectPlayMaze.rte.microsoft.com".

Similarly, you may need to set the port for the host address. If you set the port component of the device address for the player calling Host, it is recommended that you set the port component of the host address passed in EnumHosts or Connect. If you did not use EnumHosts to find a session's host address and do not pass the DPNCONNECT_OKTOQUERYFORADDRESSING flag, the port must be specified for the host address in order to connect to the session.

The following example illustrates how to set the port for a host address using the IDirectPlay8Address::AddComponent method.

DWORD dwPort;
//Set dwPort to the port number of the host address

hr = g_pHostAddress->AddComponent( DPNA_KEY_PORT,           //pwszName
                                 &dwPort, sizeof(dwPort),   //lpvData, dwDataSize
                                 DPNA_DATATYPE_DWORD );     //dwDataType

After you have created the address objects, you connect to the session by passing the device address in the pDeviceInfo parameter and the host address in the pHostAddr parameter in the Connect method.

© 2002 Microsoft Corporation. All rights reserved.


Creating Modem Address Objects

This topic discusses how to create typical address objects using the IDirectPlay8Address methods for modem service providers.

The first step in creating an address object is to call CoCreateInstance to create an IDirectPlay8Address object. The parameters include the class identifier of an address object (CLSID_DirectPlay8Address), the identifier of the interface (IID_IDirectPlay8Address), and the address of a pointer to an IDirectPlay8Address interface. The following example illustrates how to create an address object.

IDirectPlay8Address*   g_pDeviceAddress;
.
.
.
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &g_pDeviceAddress );

For more information about using CoCreateInstance, see Creating a COM Object.

After creating the address object, you must set the service provider component, at a minimum. To do that, call IDirectPlay8Address::SetSP. The following example illustrates how to set the service provider to the Microsoft® DirectPlay® modem service provider.

hr = g_pDeviceAddress->SetSP(&CLSID_DP8SP_MODEM );

The EnumHosts, Connect, and Host methods each have an OKTOQUERYFORADDRESSING flag (DPNENUMHOSTS_OKTOQUERYFORADDRESSING, DPNCONNECT_OKTOQUERYFORADDRESSING, and DPNHOST_OKTOQUERYFORADDRESSING) that allow DirectPlay to prompt the user for any missing information in the address beyond the service provider component. However, for most applications you will want to override these standard dialogs to improve the user experience. The following sections describe the common and required components used for the modem service providers.

Device Addresses

If you are creating a device address for the local player and using the modem service provider, you may need to set the device. For a list of other data values you may set, see Data Value Summary. If you do not pass the respective OKTOQUERYFORADDRESSING flag to EnumHosts, Connect, or Host, the device must be specified for the device address.

Use the EnumServiceProviders method to obtain a list of available devices. The following example illustrates how to retrieve a list of available modem devices by calling the EnumServiceProviders method with the pguidServiceProvider parameter set to CLSID_DP8SP_MODEM.

DWORD dwSize;
DWORD dwItems;
PDPN_SERVICE_PROVIDER_INFO pSPInfoBuffer;

hr = g_pDP->EnumServiceProviders(&CLSID_DP8SP_MODEM,        //pguidServiceProvider
                                 NULL, pSPInfoBuffer,       //pguidApplication, pSPInfoBuffer
                                 &dwSize, &dwItems, 0 );    //pcbEnumData, pcReturned, dwFlags

The pSPInfoBuffer parameter is the address of the buffer where DirectPlay places the service provider device information if the call is successful. Typically EnumServiceProviders is called twice, once to retrieve the buffer size required, and again to actually fill in the buffer.

After enumerating the available devices, select a modem device by using the IDirectPlay8Address::AddComponent method as is shown below.

GUID pGuid;
//  Set pGuid to the GUID of the modem device.

hr = g_pDeviceAddress->AddComponent( DPNA_KEY_DEVICE,        //pwszName
                                    pGuid, sizeof(GUID),     //lpvData, dwDataSize
                                    DPNA_DATATYPE_GUID);     //dwDataType

In this example, pGuid is the address of the globally unique identifier (GUID) that represents the selected modem device.

Host Addresses

If you are creating a host address and using the modem service provider, you may need to set the phone number. For a list of other data values you may set, see Data Value Summary. If you do not pass the respective OKTOQUERYFORADDRESSING flag to EnumHosts or Connect, the phone number must be specified for the host address.

The following example illustrates how to set the phone number for a host address using the IDirectPlay8Address::AddComponent method.

size_t cb;
WCHAR wstrPhone[MAX_PATH];
//  Set wstrPhone to the phone number of the host address
hr = StringCbLengthW(wstrPhone, MAX_PATH, &cb);

hr = pHostAddress->AddComponent( DPNA_KEY_PHONENUMBER,                 //pwszName
                                 wstrPhone,                            //lpvData
                                 cb,                                   //dwDataSize in bytes
                                 DPNA_DATATYPE_STRING );               //dwDataType

In this example, wstrPhone contains the phone number of the host to which you will connect.

After you have created the address objects, you connect to the session by passing the device address in the pDeviceInfo parameter and the host address in the pHostAddr parameter in the Connect method.

© 2002 Microsoft Corporation. All rights reserved.


Creating IPX Address Objects

This topic discusses how to create typical address objects using the IDirectPlay8Address methods for Internetwork Packet Exchange (IPX) service providers.

The first step in creating an address object is to call CoCreateInstance to create an IDirectPlay8Address object. The parameters include the class identifier of an address object (CLSID_DirectPlay8Address), the identifier of the interface (IID_IDirectPlay8Address) and the address of a pointer to an IDirectPlay8Address interface. The following example illustrates how to create an address object.

IDirectPlay8Address*   g_pDeviceAddress;
.
.
.
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &g_pDeviceAddress);

For more information about using CoCreateInstance, see Creating a COM Object.

After creating the address object, you must set the service provider component, at a minimum. To do that, call IDirectPlay8Address::SetSP. The following example illustrates how to set the service provider to the Microsoft® DirectPlay® IPX service provider.

 hr = g_pDeviceAddress->SetSP(&CLSID_DP8SP_IPX );

The EnumHosts, Connect, and Host methods each have an OKTOQUERYFORADDRESSING flag (DPNENUMHOSTS_OKTOQUERYFORADDRESSING, DPNCONNECT_OKTOQUERYFORADDRESSING, and DPNHOST_OKTOQUERYFORADDRESSING) that allow DirectPlay to prompt the user for any missing information in the address beyond the service provider component. However, for most applications you will want to override these standard dialogs to improve the user experience. The following sections describe the common and required components used for the IPX service providers.

Device Addresses

If you are creating a device address for the local player and using IPX as your service provider, you may also want to set the device port. For a list of other data values you may set, see Data Value Summary.

The following example illustrates how to set the port for a device address using the IDirectPlay8Address::AddComponent method.

DWORD dwPort;
// Set dwPort to the port number for the device address.

hr = g_pDeviceAddress->AddComponent( DPNA_KEY_PORT,           //pwszName
                                   &dwPort, sizeof(dwPort),   //lpvData, dwDataSize
                                   DPNA_DATATYPE_DWORD );     //dwDataType

If you set the port for the player hosting the session, it is recommended that you also set the DPNSESSION_NODPNSVR flag in the DPN_APPLICATION_DESC structure passed in the Host method. However, if you disable DPNSVR, you should do one of the following:

  • Specify the host port in the pdpaddrHost parameter when you call EnumHosts.
  • Specify the host port in the pHostAddr parameter when you call Connect.

Host Addresses

If you are creating a host address and using IPX as your service provider, you may need to set the host name address component. For a list of other data values you may set, see Data Value Summary. If you did not use EnumHosts to find a session, the host name must be specified for the host address.

The following example illustrates how to set the host name for a host address using the IDirectPlay8Address::AddComponent method.

size_t cb;
WCHAR wstrIPX[MAX_PATH];
// Set wstrIPX to the host IPX address
hr = StringCbLengthW(wstrIPX, MAX_PATH, &cb);

hr = g_pHostAddress->AddComponent(DPNA_KEY_HOSTNAME,        //pwszName
                                  pwszHost,                 //lpvData
                                  cb,                       //dwDataSize in bytes
                                  DPNA_DATATYPE_STRING );   //dwDataType

In this example, pwszHost contains the IPX network and node number of the session host. If you were to use (hexadecimal) network 2702 and node 00-02-B3-10-87-64, the host name string would be "00002702,0002B3108764".

Similarly, you may need to set the port for the host address. If you set the port for the device address of the player who is hosting, it is recommended that you set the port for the host address passed in EnumHosts or Connect. If you did not use EnumHosts to find a session's host address, the port must be specified for the host address in order to connect to the session.

The following example illustrates how to set the port for a host address using the IDirectPlay8Address::AddComponent method.

DWORD dwPort;
//Set dwPort to the port number of the host address

hr = g_pHostAddress->AddComponent( DPNA_KEY_PORT,           //pwszName
                                 &dwPort, sizeof(dwPort),   //lpvData, dwDataSize
                                 DPNA_DATATYPE_DWORD );     //dwDataType

After you have created the address objects, you connect to the session by passing the device address in the pDeviceInfo parameter and the host address in the pHostAddr parameter in the Connect method.

© 2002 Microsoft Corporation. All rights reserved.


Creating Serial Address Objects

This topic discusses how to create typical address objects using the IDirectPlay8Address methods for serial service providers.

The first step in creating an address object is to call CoCreateInstance to create an IDirectPlay8Address object. The parameters include the class identifier of an address object (CLSID_DirectPlay8Address), the identifier of the interface (IID_IDirectPlay8Address), and the address of a pointer to an IDirectPlay8Address interface. The following example illustrates how to create an address object.

IDirectPlay8Address*  g_pDeviceAddress;
.
.
.
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &g_pDeviceAddress );

For more information about using CoCreateInstance, see Creating a COM Object.

After creating the address object, you must set the service provider component, at a minimum. To do that, call IDirectPlay8Address::SetSP. The following example illustrates how to set the service provider to the Microsoft® DirectPlay® serial service provider.

hr = g_pDeviceAddress->SetSP(&CLSID_DP8SP_SERIAL );

The EnumHosts, Connect, and Host methods each have an OKTOQUERYFORADDRESSING flag (DPNENUMHOSTS_OKTOQUERYFORADDRESSING, DPNCONNECT_OKTOQUERYFORADDRESSING, and DPNHOST_OKTOQUERYFORADDRESSING) that allow DirectPlay to prompt the user for any missing information in the address beyond the service provider component. However, for most applications you will want to override these standard dialogs to improve the user experience. The following sections describe the common and required components used for the serial service providers.

Device Addresses

If you are creating a device address for the local player and using the serial service provider, you need to set the following components.

  • baud
  • stop bits
  • parity
  • flow control
  • device (depends on your setup)

For a list of other data values you may set, see Data Value Summary.

Baud

The following example illustrates how to set the baud rate using the IDirectPlay8Address::AddComponent method.

DWORD dwBaudRate;
//  Set dwBaudRate

hr = g_pHostAddress->AddComponent( DPNA_KEY_BAUD,                   //pwszName
                                 &dwBaudRate, sizeof(dwBaudRate),   //lpvData, dwDataSize
                                 DPNA_DATATYPE_DWORD );             //dwDataType

In this example, the dwBaudRate variable can contain any of the DPNA_BAUD_RATE constants defined in dpaddr.h.

Stop bits

The following example illustrates how to set the stop bits using the IDirectPlay8Address::AddComponent method.

size_t cb;
hr = StringCbLengthW(DPNA_STOP_BITS_ONE, MAX_PATH, &cb);

hr = g_pHostAddress->AddComponent( DPNA_KEY_STOPBITS,                  //pwszName
                                 DPNA_STOP_BITS_ONE,                   //lpvData
                                 cb,                                   //dwDataSize, in bytes
                                 DPNA_DATATYPE_STRING );               //dwDataType

In this example, the stop bits setting is 1, as indicated by the use of the DPNA_STOP_BITS_ONE constant defined in dpaddr.h.

Parity

The following example illustrates how to set the parity using the IDirectPlay8Address::AddComponent method.

size_t cb;
hr = StringCbLengh(DPNA_PARITY_NONE, MAX_PATH, &cb);

hr = g_pHostAddress->AddComponent(DPNA_KEY_PARITY,                   //pwszName
                                 DPNA_PARITY_NONE,                   //lpvData
                                 cb,                                 //dwDataSize, in bytes
                                 DPNA_DATATYPE_STRING );             //dwDataType

In this example, the parity setting is none, as indicated by the use of the DPNA_PARITY_NONE constant defined in dpaddr.h.

Flow Control

The following example illustrates how to set the flow control using the IDirectPlay8Address::AddComponent method.

size_t cb;
hr = StringCbLengh(DPNA_FLOW_CONTROL_RTSDTR, MAX_PATH, &cb);

hr = g_pHostAddress->AddComponent(DPNA_KEY_FLOWCONTROL,                    //pwszName
                                 DPNA_FLOW_CONTROL_RTSDTR,                 //lpvData
                                 cb,                                       //dwDataSize, in bytes
                                 DPNA_DATATYPE_STRING );                   //dwDataType

In this example, the flow control is set to RTS/DTR, as indicated by the use of the DPNA_FLOW_CONTROL_RTSDTR constant defined in dpaddr.h.

Device

You may need to set the device if you do not pass the respective OKTOQUERYFORADDRESSING flag to EnumHosts, Connect, or Host.

Use the EnumServiceProviders method to obtain a list of available devices. The following example illustrates how to retrieve a list of available serial devices by calling the EnumServiceProviders method with the pguidServiceProvider parameter set to CLSID_DP8SP_SERIAL.

DWORD dwSize;
DWORD dwItems;
PDPN_SERVICE_PROVIDER_INFO pSPInfoBuffer;

hr = g_pDP->EnumServiceProviders(&CLSID_DP8SP_SERIAL,       //pguidServiceProvider
                                 NULL, pSPInfoBuffer,       //pguidApplication, pSPInfoBuffer
                                 &dwSize, &dwItems, 0 );    //pcbEnumData, pcReturned, dwFlags

The pSPInfoBuffer parameter is the address of the buffer where DirectPlay places the service provider device information if the call is successful. Typically EnumServiceProviders is called twice, once to retrieve the buffer size required, and again to actually fill in the buffer.

After enumerating the available devices, select a serial device by using the IDirectPlay8Address::AddComponent method as is shown below.

GUID pGuid;
//  Set pGuid

hr = g_pDeviceAddress->AddComponent( DPNA_KEY_DEVICE,        //pwszName
                                    pGuid, sizeof(GUID),     //lpvData, dwDataSize
                                    DPNA_DATATYPE_GUID);     //dwDataType

In this example, pGuid is the address of the globally unique identifier (GUID) that represents the selected serial device.

Host Addresses

Serial host addresses do not need to contain any additional information beyond the serial provider component.

© 2002 Microsoft Corporation. All rights reserved.


Data Value Summary

The following two tables outline the standard data values and indicate which values are used by each type of service provider for both host and device addresses. For more information about how to create address objects, see DirectPlay Address Objects.

Host Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required |
Device | Not used | Optional | Required | Required
Flow Control | Not used | Not used | Required |
Host Name | Required | Required | Optional | Optional
Parity | Not used | Not used | Required |
Phone Number | Not used | Not used | Not used | Required
Port | Required | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required |

Device Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required | Not used
Flow Control | Not used | Not used | Required | Not used
Host Name | Optional | Optional | Optional | Optional
Device | Optional | Required | Required | Required
Parity | Not used | Not used | Required | Not used
Phone Number | Not used | Not used | Not used | Not used
Port | Optional | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required | Not used

© 2002 Microsoft Corporation. All rights reserved.


Data Values

The values that need to be included in the data string depend on the particular service provider. Modem providers, for instance, need a telephone number in their address, whereas local area network (LAN) providers might need a port number. This section provides a detailed description of the standard data values. It also includes a key name that can be used in place of the literal string. These names are defined in Dpaddr.h. For more information about using these values, see DirectPlay Address Objects.

  • Application Instance
  • Baud
  • Device
  • Flow Control
  • Host Name
  • Parity
  • Phone Number
  • Port
  • Program
  • Provider
  • Stop Bits

Application Instance

An optional globally unique identifier (GUID) that identifies an application instance. This value is used when specifying the game that is to be connected to.

Key Name: DPNA_KEY_APPLICATION_INSTANCE

Key String: "applicationinstance"

Data Type: GUID

Providers: All

Valid Values: Any valid application instance GUID.

Baud

The baud rate.

Key Name: DPNA_KEY_BAUD

Key String: "baud"

Data Type: DWORD

Providers: Modem and serial

Valid Values: Any valid baud rate. You can set this value to the appropriate integer, or you can use one of the following predefined values from Dpaddr.h.

DPNA_BAUD_RATE_9600
DPNA_BAUD_RATE_14400
DPNA_BAUD_RATE_19200
DPNA_BAUD_RATE_38400
DPNA_BAUD_RATE_56000
DPNA_BAUD_RATE_57600
DPNA_BAUD_RATE_115200

Device

A GUID that identifies the device on the local computer that will be used. If the service provider supports all adapters, you do not need to specify a device.

Key Name: DPNA_KEY_DEVICE

Key String: "device"

Data Type: GUID

Providers: All, but for device addresses only, not host addresses

Valid Values: Any valid device GUID.

Flow Control

The type of flow control to be used.

Key Name: DPNA_KEY_FLOWCONTROL

Key String: "flowcontrol"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_FLOW_CONTROL_NONE | DPNA_FLOW_CONTROL_DTR
DPNA_FLOW_CONTROL_XONXOFF | DPNA_FLOW_CONTROL_RTSDTR
DPNA_FLOW_CONTROL_RTS |

Host Name

The name of a remote host computer.

Key Name: DPNA_KEY_HOSTNAME

Key String: "hostname"

Data Type: String

Providers: All, but for host addresses only, not device addresses

Valid Values: A fully-qualified host name, or a dotted address.

Parity

The parity of the connection.

Key Name: DPNA_KEY_PARITY

Key String: "parity"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_PARITY_NONE | DPNA_PARITY_MARK
DPNA_PARITY_EVEN | DPNA_PARITY_SPACE
DPNA_PARITY_ODD |

Phone Number

A phone number.

Key Name: DPNA_KEY_PHONENUMBER

Key String: "phonenumber"

Data Type: String

Providers: Modem

Valid Values: Any valid phone number.

Port

An optional port number. For more information, see Understanding Ports.

Key Name: DPNA_KEY_PORT

Key String: "port"

Data Type: DWORD

Providers: Internet Protocol (IP) and Internetwork Packet Exchange (IPX)

Valid Values: Any 16-bit integer. Only the lower 16 bits of the value are valid. If you do not specify a port, Microsoft® DirectPlay® will choose one for you.

Program

An optional application GUID.

Key Name: DPNA_KEY_PROGRAM

Key String: "program"

Data Type: GUID

Providers: All

Valid Values: Any valid application GUID.

Provider

A GUID that identifies the DirectPlay service provider that will be used. For more information, see DirectPlay Service Providers.

Key Name: DPNA_KEY_PROVIDER

Key String: "provider"

Data Type: GUID

Providers: All

Valid Values: Any valid service provider GUID.

Stop Bits

The number of stop bits.

Key Name: DPNA_KEY_STOPBITS

Key String: "stopbits"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_STOP_BITS_ONE | DPNA_STOP_BITS_TWO
DPNA_STOP_BITS_ONE_FIVE |

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Callback Functions and Multithreading Issues

Microsoft® DirectPlay® and DirectPlay Voice both require you to implement and register several callback functions to handle the events fired by DirectPlay. DirectPlay is multithreaded and will fire multiple events concurrently. It is possible that your application will receive multiple overlapping callbacks.

DirectPlay maintains a thread pool to service callback indications, and your callback is invoked on a thread from the pool of threads maintained by DirectPlay. The size of this thread pool is configurable on a per process basis in Microsoft Windows® 2000 and Windows XP. Also, DirectPlay will use I/O completion ports when running on Windows 2000 and Windows XP. I/O completion ports is an advanced topic beyond the scope of this document, and it is recommended that you look in the Microsoft Developer Network documents or in one of the Microsoft Win32® multithreading references currently available.

In order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization. This is known as making your callback re-entrant or threadsafe.

The Windows family of operating systems currently offers three methods of synchronizing data in multithreaded environments:

  • Mutex objects (mutually exclusive synchronization objects).
  • Semaphore objects (flag variables used to indicate to potential users that a shared file or other resource is in use).
  • Critical section objects (also provide mutually exclusive synchronization but used only by the threads of a single process).

The DirectPlay voice samples that ship with the Microsoft DirectX® 9.0 software development kit (SDK) demonstrate synchronization using Critical Section Objects. If you want to implement a Mutex or Semaphore Object, these topics are discussed in the Microsoft Platform Software Development Kit (SDK) as well as in many reference books. Implementing any of these synchronization methods requires an expert knowledge level in these areas due to the level of complexity and difficulty in debugging should any issues arise.

The DirectPlay threading model is optimized for maximum efficiency and there are no thread context switches during "indication" messages, including receive messages.

See Implementing a Callback Function in DirectPlay and DirectPlay Voice for more information.

DirectPlay Networking Callbacks

DirectPlay networking callback functions are of type PFNDPNMESSAGEHANDLER. Depending on the type of networking session, you register the address of your callback function with IDirectPlay8Peer::Initialize, IDirectPlay8Client::Initialize, or IDirectPlay8Server::Initialize.

Synchronization Issues

You must employ one of the three thread synchronization objects in order to maintain the integrity of your game data during processing in a DirectPlay callback.

To understand how your game data could be corrupted, consider that your callback inserts a packet of game data into a structure. Because the callback is reentrant, another thread can enter the callback before the first callback has completed. It is possible that this second thread could also attempt to access the structure at the same location in memory and change the data. Therefore, the data placed in the structure by the first thread is overwritten by the data placed in the structure by the second thread. Please note that this is an oversimplified example of multithreading and there are many other implications to not properly synchronizing multiple threads.

See Implementing a DirectPlay Networking Callback Using Critical Section Objects for an example of how to synchronize data in a DirectPlay networking session.

Worker Threads

You have the option of creating your own "worker threads". A worker thread is another multithreaded application defined callback that is created to process game data independently of the DirectPlay callbacks. The most common way of accomplishing this is to buffer data received during a DirectPlay networking callback thread. Then, a new thread is created and a message is sent to your worker thread callback to notify it to process the buffered data.

Multithreading Performance Issues and Asynchronous Operations

It is important to carefully consider how much time is spent processing messages in DirectPlay callbacks. If you process a lot of data within the DirectPlay callbacks and you employ a data locking mechanism to synchronize threads, you will run into blocking problems as other threads wait to enter the callback.

If you choose to implement a worker thread and offset the processing of game data to another callback, you run the risk of adding a lot of overhead processing time as the CPU switches context between the threads you create and the threads created by DirectPlay. This should be done only if the game data requires a large amount of processing time, and the data is not critical to the real time operation of the game. For example, it is not recommended to process player location data in a worker thread because this data is critical to positioning players in real time within the game.

You can also return DPNSUCCESS_PENDING from the callback, create a pointer to the data buffer, and make that pointer available the worker thread. When the worker thread is finished processing the game data, it calls the ReturnBuffer method of either IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server, depending on the topology used.

Holding Locks Across API Calls

In general, you should avoid holding shared resource locks across application programming interface (API) calls. This is because it can be hard to envision all the possible interactions with other threads. In the following code, the sending thread is incorrectly holding the pObj->csSomeLock critical section while calling IDirectPlay8Peer::SendTo synchronously.

typedef struct _MYOBJECT{
    CRITICAL_SECTION    csSomeLock;
    DWORD               dwFlags;
    .
    .
    .
} MYOBJECT, *PMYOBJECT;

IDirectPlay8Peer    *pDP8Peer;
PMYOBJECT           pObj;
.
.
.
EnterCriticalSection(&pObj->csSomeLock);
pDP8Peer->SendTo(DPNID_ALL_PLAYERS_GROUP,
                 &dpnBuffer, 1, 0,
                 NULL, NULL, DPNSEND_SYNC);
LeaveCriticalSection(&pObj->csSomeLock);

The local player will receive a copy of the message with a call to the application's message handler on a different thread because the DPNSEND_NOLOOPBACK flag was not used. If the message handler tried to acquire pObj->csSomeLock in response to this message, it would deadlock, because the sending thread cannot return from IDirectPlay8Peer::SendTo (and thus cannot drop the lock) until the message handler returns, but the message handler can't return until the sending thread drops the lock. Instead, use a flag or indexing system so that you can release the lock while you make the API call.

typedef struct _MYOBJECT{
    CRITICAL_SECTION    csSomeLock;
    DWORD               dwFlags;
    .
    .
    .
} MYOBJECT, *PMYOBJECT;

IDirectPlay8Peer     *pDP8Peer;
PMYOBJECT            pObj;
.
.
.
EnterCriticalSection(&pObj->csSomeLock);
pObj->dwFlags |= FLAGS_SENDING;
LeaveCriticalSection(&pObj->csSomeLock);

pDP8Peer->SendTo(DPNID_ALL_PLAYERS_GROUP,
                 &dpnBuffer, 1, 0,
                 NULL, NULL, DPNSEND_SYNC);

EnterCriticalSection(&pObj->csSomeLock);
pObj->dwFlags &= ~FLAGS_SENDING;
LeaveCriticalSection(&pObj->csSomeLock);

© 2002 Microsoft Corporation. All rights reserved.


Implementing a Callback Function in DirectPlay and DirectPlay Voice

Microsoft® DirectPlay® and DirectPlay Voice both require you to implement and register several callback functions to handle the events fired by DirectPlay. DirectPlay is multithreaded and will fire multiple events concurrently. Therefore, in order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization. This is known as making your callback re-entrant or threadsafe.

Callback Function Structure

The structure of the callback follows standard Microsoft Win32® application programming interface (API) programming guidelines.

HRESULT WINAPI Callback(
  PVOID pvUserContext,
  DWORD dwMessageType,
  PVOID pMessage );

pvUserContext is the a context value you supply when you register the callback function with DirectPlay. If you pass this value to DirectPlay when you register your callback, the context value will be returned when DirectPlay invokes your callback.

dwMessageType is one of the identifier (ID) values passed to your callback by DirectPlay.

pMessage will contain the message passed by DirectPlay.

Registering Your Callback

DirectPlay networking callback functions are of type PFNDPNMESSAGEHANDLER. Depending on the type of networking session, you register the address of your callback function with IDirectPlay8Peer::Initialize, IDirectPlay8Client::Initialize, or IDirectPlay8Server::Initialize. If you are registering a DirectPlay voice callback function, register the address of your callback with IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize, depending on the type of DirectPlay voice session you want to create.

The following code snippet demonstrates how to register a callback function with the IDirectPlay8Peer interface.

HRESULT WINAPI Callback(PVOID, DWORD, PVOID);

IDirectPlay8Peer* pdp8Peer;

// Get the server interface
hr = CoCreateInstance( CLSID_DirectPlay8Peer, ...)
...

// Register the callback
hr = pdp8Peer->Initialize(NULL, Callback, 0);

© 2002 Microsoft Corporation. All rights reserved.


Implementing a DirectPlay Networking Callback Using Critical Section Objects

Microsoft® DirectPlay® networking and voice callback are multithreaded. Therefore, in order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization.

Currently, there are three methods of synchronizing mulithreaded callback data.

  • Mutex Objects
  • Semaphore Objects
  • Critical Section Objects

The DirectPlay voice samples that ship with the Microsoft DirectX® SDK demonstrate synchronization using Critical Section Objects, and the following topics will also demonstrate how Critical Section Objects are used. If you want to implement a Mutex or Semaphore Object, these topics are discussed in the Microsoft Platform Software Development Kit (SDK) as well as in many reference books. Implementing any of these synchronization methods requires an expert knowledge level in these areas due of the level of complexity and difficulty in debugging should any issues arise.

CRITICAL_SECTION g_csPlayerContext;
InitializeCriticalSectionAndSpinCount(&g_csPlayerContext, 0);

Next, implement the DirectPlay message callback handler.

HRESULT WINAPI DirectPlayMessageHandler( PVOID pvUserContext,
                                         DWORD dwMessageId,
                                         PVOID pMsgBuffer )
{
    switch( dwMessageId )
    {
        case DPN_MSGID_CREATE_PLAYER:
        {
             EnterCriticalSection( &g_csPlayerContext );
             //callback is now locked
             //perform operation on player data
             LeaveCriticalSection( &g_csPlayerContext );
        }
    }
}

Finally, during application exit, ensure that you call the DeleteCriticalSection function to free the memory associated with your critical section object.

DeleteCriticalSection( &g_csPlayerContext );

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay Protocol

Multiplayer games require efficient and flexible network messaging services for optimal performance. The Microsoft® DirectPlay® protocol is a transport-layer messaging protocol that is used for all DirectPlay messaging. It provides your application with the messaging support it needs to make everything run smoothly. The DirectPlay protocol includes the following messaging support.

  • Reliable and unreliable delivery of messages
  • Sequential and non-sequential delivery of messages
  • Message fragmentation and reassembly
  • Congestion control
  • Send prioritization
  • Message timeouts
Note Before DirectPlay 8.1, the DirectPlay protocol was optional, and had to be specified explicitly. Since DirectPlay 8.1, this protocol is used for all DirectPlay messaging.

This document provides a general description of how the Microsoft DirectX® protocol works, and how you can use it in your application.

  • Basic Message Handling
  • Message Categories
  • Congestion Control
  • Send Prioritization
  • Packet Signing
  • Monitoring Messaging Statistics
  • Monitoring the Pending Message Queues
  • Using the DirectX Protocol in an Application

© 2002 Microsoft Corporation. All rights reserved.


Basic Message Handling

A message, as the term is used in this document, is a block of data that needs to be sent to another computer. A network protocol creates a packet by adding some bits to the data block that hold information such as the target's network address. This packet is the basic unit of network data. When the target receives the packet, the target's network protocol removes the extra bits and passes the data block to the receiving application.

Although similar in usage, the terms message and packet are not strictly interchangeable. This document uses the term message to refer to the unit of information that is passed to and received from the Microsoft® DirectPlay® application programming interface (API). Packet refers to the unit of information handled by the network. DirectPlay handles packets internally. With rare exceptions, DirectPlay applications need to deal only with messages.

The primary reason for the distinction between message and packet is that networks generally limit the maximum size of the packets they handle. This size is referred to as a Maximum Transmission Unit (MTU). If a message is small, it is sent in a single packet and the two terms are effectively synonymous. However, large messages might need to be fragmented into two or more packets and then be reassembled by the receiver. The DirectPlay protocol automatically handles fragmentation and reassembly of messages as needed. As far as your application is concerned, you send a message, and the target receives it.

Note DirectPlay delivers messages of any size. However, the more packets that are required for a single message, the greater the odds that one or more packets will be lost and have to be retransmitted. Messages that are large enough to require fragmentation and reassembly thus typically have more network latency than single-packet messages. If you need to keep network latency to a minimum, avoid sending large messages, especially on lossy networks. You can determine the maximum size that your connection can accommodate in a single packet by calling the GetSPCaps method exposed by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces.

© 2002 Microsoft Corporation. All rights reserved.


Message Categories

The Microsoft® DirectPlay® protocol is designed to handle the following two basic types of network messaging.

  • Reliable versus unreliable messaging determines whether messages are guaranteed to be delivered to the target application.
  • Non-sequential versus sequential messaging determines whether messages are received by the target application in the same order they are sent.

Games use messaging for a variety of purposes, each with different demands. To support this range of messaging needs, the DirectPlay protocol enables you to designate a message as belonging to one of four categories:

  • Reliable and sequential
  • Unreliable and sequential
  • Reliable and non-sequential
  • Unreliable and non-sequential

The DirectPlay protocol enables you to optimize your messaging strategy by assigning categories on a message-by-message basis.

Reliable and Unreliable Messaging

Messages are sometimes lost in transit. Reliable messaging provides a guarantee that the target will receive every message. This type of messaging is required when data loss cannot be tolerated. Most reliable messaging schemes require the target to acknowledge receipt of each message. If the sender does not receive an acknowledgment within a specified timeout period, it resends the message. This process typically continues until the sender receives an acknowledgment, confirming that the message has arrived.

The DirectPlay protocol imposes a limit on the number of resend attempts. If no acknowledgment is received after a reasonable number of attempts, DirectPlay assumes that the connection has been lost, and closes it.

Unreliable messaging is the simplest form of network communication. It might be faster than reliable messaging because there is no guarantee that the message will be delivered to the target. The sender transmits the message. If the target does not receive the message, the sender will not transmit the message again, and the packet is lost.

Unreliable messaging is used primarily when speed or bandwidth is more important than an occasional lost message. For example, high-bandwidth streaming media applications often use unreliable messaging. They cannot afford to take up bandwidth with acknowledgments and retransmissions, nor can they wait for a lost message to be retransmitted. An occasional lost message normally has only a minor impact on quality, so it can be ignored.

Sequential and Non-Sequential Messaging

Messages leave the sender in a particular sequence. However, there is no guarantee that messages will arrive at the target's computer in the same order that they are sent. For example, if a message is lost and must be retransmitted, that message will typically arrive later than messages that followed it in the original sequence.

Sequential messaging uses sequencing information embedded in the message to ensure that the messages are presented to the target application in the correct order. This type of messaging is required when the target application must receive messages in the correct order. Out-of-order messages are buffered until the missing messages arrive.

Non-sequential messaging presents the received messages to the target as soon as they arrive at the target computer, regardless of the order in which they were sent. Because there is no need to wait for a missing packet, applications often use non-sequential messaging when speed is more important than an occasional out-of-order message. The out-of-order message is ignored.

Choosing the Best Message Category

Choosing the best category for messages is a core issue for multiplayer game developers. While DirectPlay provides the tools to manage your messaging, the choice of a message category ultimately depends on the semantic content of the message and the nature of the game.

The following are general guidelines for choosing the best message category.

  • Use non-guaranteed messaging whenever the content permits. For example, your game might send frequent player-location updates. Each update is independent, and it supersedes any previous updates. If an update is lost, the next update is sufficient to maintain the player's game state. A lost and retransmitted message might arrive later than the subsequent update message.
  • Use guaranteed messaging when data loss cannot be tolerated. For example, a text-based chat feature depends on every character being delivered to its target.
  • Use sequential messaging when the order of the messages is important. For example, streaming media typically uses sequential-unreliable messaging. An occasional dropped message can be tolerated, but an out-of-order message would cause problems.

© 2002 Microsoft Corporation. All rights reserved.


Congestion Control

In an ideal world, your game can send messages as often as it needs to. They arrive at the target immediately and are processed instantaneously. If all of the computers in your game have ample processing power and are connected by a lightly used high-bandwidth network link, you might approach this ideal situation. You can then send messages as often as you like. However, a number of factors can create congestion and cause messaging to work more slowly than this ideal:

  • Network latency. Even under ideal conditions, messages take a finite time to traverse the network from sender to target, especially over the Internet. There might be further delays for acknowledgments, retransmission of lost packets, or reassembly of out-of-order packets.
  • Network bandwidth. The network bandwidth controls the rate at which a message can be sent or received by a computer. Network links have a wide range of bandwidths, and even high-bandwidth networks might be slowed by high traffic levels. If one or more of your players has a low-bandwidth connection, they will be able to send and receive messages only at a limited rate.
  • Processing speed. Even if network bandwidth is high and latency low, the target application still needs some time to process a received message. If one or more of the players in a session is using a relatively slow computer, the rate at which they can process received messages might be below the rate at which messages can be sent.

Message Throttling

If there is no control over the rate at which messages are sent, a target can be flooded by more messages than it can handle. To prevent this situation, the Microsoft® DirectPlay® protocol throttles the rate at which messages are sent. The net effect of throttling is that the rate at which messages are sent is controlled by the rate at which the target can handle them.

Throttling is implemented with a sliding window mechanism. The sliding window is basically a queue with a limited number of slots that holds messages that have been sent but not yet received. All outgoing messages are placed in this queue, regardless of their category. Once the sent-message queue is full, it accepts no more outgoing messages until one of the messages in the queue has been received.

For optimal performance, the size of the sliding window must be matched to current network conditions. The DirectPlay protocol automatically monitors such factors as the number of messages and the total number of bytes in the sent-message queue. This information is then used to dynamically adjust the size of the sliding window to optimize messaging for the current network conditions.

Connection Checking

If there is no activity on a link, the DirectPlay protocol periodically tests the connection by sending an empty reliable packet. If no acknowledgment is received from the target after a reasonable number of attempts, DirectPlay concludes that the link has been disconnected.

© 2002 Microsoft Corporation. All rights reserved.


Send Prioritization

Messages often vary widely in importance. Some are time-critical and must be delivered as quickly as possible. Others can be delayed if necessary or, possibly, not sent at all. One issue with congestion control algorithms is that an application might create messages faster than they can be sent. Unsent messages must then be held in a queue until an outgoing slot opens up. If all unsent messages are held in a single pending-message queue, high priority messages might be blocked while waiting for lower priority messages to be sent first.

The Microsoft® DirectPlay® protocol solves this problem by having three pending message queues: low, medium, and high priority. When a slot opens up in the sent-message queue, the protocol selects the next message to be sent as follows:

  1. Send the oldest message in the high-priority queue.
  2. If there are no messages in the high-priority queue, send the oldest message in the medium-priority queue.
  3. If there are no messages in the medium-priority queue, send the oldest message in the low-priority queue.

This priority mechanism enables you to get your time-critical messages out as quickly as possible, even when less important messages have already been submitted.

Note All DirectPlay Voice messages are sent with medium priority and a timeout value of 1.5 seconds. Any messages that should not be preempted by voice traffic should be sent with high priority.

Send Timeouts

One of the consequences of throttling is that messages might spend a relatively long time in a pending-message queue, especially if they are low priority. Some messages might stay long enough to have been superseded by subsequent messages. These messages are no longer relevant. For example, your application might periodically send player-location update messages. Each update is independent of the others and supersedes any previous updates. If you have two player-location updates in the pending message queue, only the most recent one needs to be sent.

The DirectPlay protocol enables you to handle the problem of outdated messages by adding an optional timeout value to the message. If the message is still in a pending-message queue when the timeout expires, the message will be canceled.

Disconnection

When an application sends a disconnect message, the message is placed at the end of the low-priority pending-message queue, and the protocol stops accepting outgoing messages. This practice guarantees that all pending messages are sent before the link is disconnected. The disconnect message is sent as a reliable sequential message to guarantee that it arrives, but not before all other messages in the queue have been delivered.

© 2002 Microsoft Corporation. All rights reserved.


Packet Signing

Microsoft® DirectPlay® provides packet signing to prevent malicious users from sending spoofed Internet Protocol (IP) packets that corrupt the link between peers or between clients and a server. Packet signing is performed by attaching a "signature" to each packet before sending. This signature is 8 bytes. Any packet received without the correct signature is silently ignored by DirectPlay.

Packet signing does not encrypt the data that is sent over the link, nor does it provide a form of authentication. It should be used to prevent third parties from inserting invalid data into a DirectPlay game session. Some other mechanism needs to be used if you want the application to authenticate the users connecting to the game.

Packet signing is set when the session is started by the host. The host determines the type of signing by setting either the DPNSESSION_FAST_SIGNED or DPNSESSION_FULL_SIGNED flag in the DPN_APPLICATION_DESC structure when calling IDirectPlay8Peer::Host or IDirectPlay8Server::Host. Players connecting to the session can set either flag when calling IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect, but they will use whichever type of signing the host has selected. Once connected, clients can determine which type of signing the session is using by calling IDirectPlay8Peer::GetApplicationDesc or IDirectPlay8Client::GetApplicationDesc. The dwFlags member of the DPN_APPLICATION_DESC structure will contain one of the signing flags.

Note All players must be using Microsoft DirectX® 9.0 or later in order to use packet signing in a session.

Fast Signing

Fast signing creates the lowest overhead on your game. All it does is add the same 8-byte value to each packet. Fast signing is recommended for all DirectPlay sessions created. However, it is vulnerable to a malicious attack if a third-party user has access to the packets being exchanged and can determine the 8-byte value.

Full Signing

Full signing adds computational overhead to your game. Each packet sent and received has to be hashed over in order to compute its signature. Full signing uses the Secure Hash Algorithm version 1.0. Once the session has been established, access to the packets does not enable a third-party user to compromise the link. However, if a third-party user reads the initial connection sequence between two computers, that user may be able to compromise the link.

© 2002 Microsoft Corporation. All rights reserved.


Monitoring Messaging Statistics

While the Microsoft® DirectPlay® protocol handles many aspects of messaging automatically, your application should still monitor messaging behavior. For example, if you are consistently sending messages faster than they can be delivered, you might need to modify your messaging scheme.

Because network conditions change continuously, your application should periodically check the behavior of the network and adjust its messaging scheme accordingly. To do so, call the GetConnectionInfo method that is exposed by every DirectPlay interface that supports messaging. GetConnectionInfo returns a structure that contains a wide variety of statistical information that you can use to refine your messaging scheme, including the following:

  • Round trip latency
  • Throughput
  • Packets sent
  • Packets received
  • Packets resent
  • Packets dropped
  • Messages transmitted at different priority levels
Note The messaging statistics are obtained by monitoring the actual network traffic. If you call GetConnectionInfo immediately after you initialize the connection, there will have been little time to collect data and the statistics might be misleading.

© 2002 Microsoft Corporation. All rights reserved.


Monitoring the Pending Message Queues

You should monitor your pending message queues to ensure that they do not become too large. The IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces all expose a GetSendQueueInfo method that can be used to check the number of messages and the number of bytes currently in the queue. By default, the method returns the total for all three queues, but you can also obtain values for each of the three priority levels.

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectX Protocol in an Application

This section covers how you can use the features of the Microsoft® DirectPlay® protocol in your application.

You can use five DirectPlay interfaces to send messages.

  • IDirectPlay8Peer
  • IDirectPlay8Client
  • IDirectPlay8Server
  • IDirectPlay8LobbyClient
  • IDirectPlay8LobbiedApplication

Depending on which interface your application is using to send messages, you send a message by calling a method named either Send, or SendTo. While the usage of these five methods is similar, they vary in detail. Refer to the appropriate reference pages for further discussion.

The Send/Sendto method's parameters might allow you to control many of the DirectPlay protocol's features. For example, the dwFlags field of IDirectPlay8Peer::SendTo allows you to specify:

  • The message's priority level.
  • Whether the message is reliable or unreliable.
  • Whether the message is sequential or non-sequential.

Refer to the appropriate method reference for further details.

When your application receives a message, your callback function will receive a DPN_MSGID_RECEIVE message. The associated structure contains a pointer to the data block, along with information such as the source of the message.

© 2002 Microsoft Corporation. All rights reserved.


DP8Sim Utility

The DP8Sim utility is an executable that uses the methods of IDP8SimControl to allow you to test your application under a variety of network conditions. Alternatively, you can use the DP8Sim service provider and IDP8SimControl interface to create your own test environment. For more information, see Testing Network Performance.

Note DP8Sim is implemented on top of the existing DirectPlay8 TCP/IP Service Provider. The settings are also applied on top of the existing network characteristics. Therefore, it is intended to be used on a high-speed local area network (LAN) where normal latency and packet loss are negligible.

Path

Executable: (SDK root)\bin\dp8simui.exe

DLL: (SDK root)\bin\dp8sim.dll

User's Guide

The configuration utility, Dp8simui.exe, is the user interface for controlling Dp8sim.dll. Both files must reside in the same directory. When you start the configuration utility, it will automatically register the Dp8sim.dll Component Object Model (COM) objects. You can also manually register the dynamic-link library (DLL) by typing the following command at your Microsoft® MS-DOS® prompt.

regsvr32.exe dp8sim.dll

After the Dp8sim.dll is registered, the DP8Sim service provider will be available. Select the "DirectPlay8 TCP/IP Service Provider (Network Simulator)" service provider from the service providers returned by the IDirectPlay8Peer::EnumServiceProviders, IDirectPlay8Client::EnumServiceProviders, and IDirectPlay8Server::EnumServiceProviders methods. Note that Microsoft DirectPlay® sessions cannot use the network simulator if the DirectPlay interface was created before running the simulator.

Once the simulator is running, you can control various network options. There are also predefined network settings that may be useful.

The options for sending (receiving) are:

  • Bandwidth (bytes/second). The total available outbound (inbound) bandwidth for all players in bytes per second. All packets have their latency increased in proportion to their size according to this value. If the application sends (receives) more than this amount, later packets are queued behind earlier ones. Use 0 (zero) for unlimited bandwidth, up to the real underlying network bandwidth.
  • Drop percentage (0 to 100 percent). The random frequency as a percentage for an individual outbound (inbound) packet to be dropped. Each packet stands the same chance of being dropped, regardless of other packets. Note that this does not necessarily model the behavior of all networks. Packet loss on the Internet, for example, tends to be erratic, with packet loss high at some times and low at others. A value of 1 means that an average of 1 out of every 100 packets is dropped. A value of 100 means every packet is dropped. Use 0 if you do not want to drop any packets other than loss due to the real underlying network.
  • Minimum latency (milliseconds). The minimum delay in milliseconds for outbound (inbound) packets. The actual delay for an individual packet is chosen randomly between this minimum value and the maximum latency value. Note that the delay is applied on top of any delay imposed by bandwidth limitations. Use 0 if you do not want to have a lower bound for artificial latency beyond the real underlying network.
  • Maximum latency (milliseconds). The maximum delay in milliseconds for outbound (inbound) packets. The actual delay for an individual packet is chosen randomly between the minimum latency value and this maximum value. If this value is lower than the minimum latency value, it is automatically set to equal the minimum value. Note that the delay is applied on top of any delay imposed by bandwidth limitations. Use 0 if you do not want to have an upper bound for artificial latency beyond the real underlying network.
Note These options apply for in-game data only. Host enumerations and responses are not subject to the simulation.

To make modifications, use the Apply and Revert buttons. Click Apply to change the settings and Revert to restore the previous settings. To save you settings, click the Save As button. You will be prompted to give a name for your settings.

At the bottom of the configuration utility window, the send and receive statistics for all affected DirectPlay interfaces are displayed. The Refresh button updates the statistics and Clear resets the statistics to 0.

To unregister Dp8sim.dll, type the following at the MS-DOS command prompt.

regsvr32.exe /u dp8sim.dll
Note The DP8Sim utility provided with Microsoft DirectX® 8.1 will not work with applications using the DirectX 9.0 DLLs.

For more information about network performance, see Optimizing Network Usage.

© 2002 Microsoft Corporation. All rights reserved.


Monitoring DirectPlay Network Traffic with Netmon

During game development, you might find it useful to monitor Microsoft® DirectPlay® network traffic, especially when trying to understand bugs. The Network Monitor is a standard utility for analyzing network traffic. DirectPlay includes a set of parsers, that allow you to use the Network Monitor to analyze four components of DirectPlay messaging: the service provider layer, the transport layer, the session layer, and the voice layer.

How Network Monitor Works With DirectPlay

The DirectPlay protocol stack has three basic layers.

  • The voice and session layers share the top level of the stack. Normal messaging passes through the session layer, and voice-related messaging passes through the voice layer.
  • The transport layer is the middle of the stack. Both voice and session traffic passes through this layer, which is responsible for such tasks as fragmentation and reassembly of messages and retransmission of lost packets.
  • The service provider layer is at the bottom of the stack. All messaging is handled by this layer, which is responsible for communicating with the network. For example, for Transmission Control Protocol/Internet Protocol (TCP/IP) networking, the service provider uses the Windows Sockets (Winsock) application programming interface (API) to communicate with the network stack. The Network Monitor can only parse network traffic that is carried on an Internet Protocol (IP) or Internetwork Packet Exchange (IPX) service provider.

By installing the DirectPlay parsers, you can use the Network Monitor to analyze the network traffic as it passes through any of these four layers. You can see all DirectPlay traffic by selecting the service provider parser. However, by selecting one of the higher-level parsers, you can filter out traffic that might not be of interest.

With the transport layer parser, you see all voice and session traffic, but not low-level traffic such as connection handshaking. Be aware that the transport layer breaks messages that are longer than the network's Maximum Transmission Unit (MTU) into one or more fragments.

The session and voice layer parsers enable you to analyze session and voice-related traffic separately. Both of these parsers are can detect fragmentation, and notify the user, but cannot parse fragmented packets.

Configuring Network Monitor for DirectPlay

If you have a Microsoft Windows® 2000 Server system, Network Monitor is already installed. For Windows 2000 Professional, you must purchase a copy of Systems Management Server (SMS). For a general discussion of how to use Network Monitor, see About Network Monitor 2.0.

To configure the Network Monitor to handle DirectPlay traffic:

  1. Copy Dp8parse.dll from (SDK root)\bin\DXUtils to the appropriate folder. The Network Monitor root folder is normally installed in the \Winnt\System32 folder. If you have installed SMS, the root folder will be called NetMonFull. For Windows 2000 Server, the root folder will be called NetMon. Depending on which version of the Network Monitor you are using, copy the parser dynamic-link library (DLL) to either the ...\NetMonFull\Parsers, or ...\NetMon\parsers folder.
  2. Start the Network Monitor.
  3. Set the adapter to capture from (Capture, Networks, Local Computer). Be sure to choose the adapter with the "Dial-up Connection" property set to FALSE.

You are now ready to start capturing traffic.

Capturing DirectPlay Network Traffic

To start the capture process, click Start Capture on the Network Monitor toolbar to open the capture view. Initially, you will see all the traffic that is passing through your adapter. You can filter that raw traffic stream to focus on only those packets that are of interest. By installing the DirectPlay parsers, you essentially add four DirectPlay-oriented filters to Network Monitor that enable you to filter everything but DirectPlay traffic from your capture view.

To select a filter:

  1. Click the Edit Display Filter button on the Network Monitor toolbar.
  2. Double-click Protocol == Any.
  3. Click Disable All.
  4. Under Disabled Protocols, double-click DPLAYSESSION, DPLAYSP, DPLAYTRANSPORT, and DPLAYVOICE.

Click OK twice to return to the capture view, and you are ready to start viewing DirectPlay traffic.

You can also apply a filter to the capture process itself, rather than to the capture view. This allows you, for instance, to capture only IP packets with specified source and destination ports. For details, see the Network Monitor documentation.

Tips for Using Network Monitor with DirectPlay

Here are a few tips to using the Network Monitor with DirectPlay.

  • By default, the Network Monitor captures only 1 MB of the most recent traffic. You will probably want to increase this value to at least 10 to 20 MB.
  • The Network Monitor doesn't stream to the hard drive, so all you can see is what is in the capture buffer. To stream captured traffic to a hard drive, you need to implement your own capturer. For details, see MSDN®.
  • By default, DirectPlay parsing uses the [2302,2400]U{6073} port/socket range to filter IP and IPX packets. To parse ports other than the default DirectPlay ports, create two new DWORD values under the HKEY_CURRENT_USER\Software\Microsoft\DirectPlay\Parsers key, as shown in the following example.
    MinUserPort = x

MaxUserPort = y

    The x- and y-data values define the range to parse in addition to the default DirectPlay ports. They can be the same value if you only need one custom port.

  • DirectPlay parsers support both signed and unsigned traffic. By default, the parsers assume that packets are unsigned. To enable monitoring of signed packets, set the DWORD value under the HKEY_CURRENT_USER\Software\Microsoft\DirectPlay\Parsers key, as shown in the following example.
    AssumeSigned = 1
  • Because the DirectPlay and Realtime Transport Protocols (RTPs) are both layered on top of the User Datagram Protocol (UDP), their parsers might conflict. You should disable the RTP parser when analyzing DirectPlay traffic, and vice versa.

© 2002 Microsoft Corporation. All rights reserved.


Network Address Translation, Firewalls, and Proxies

Network Address Translation (NAT) is a mechanism with which one network can be connected to another. This is commonly used to connect a private home or office network to the Internet. The gateway between these two networks modifies packets sent from the private network to computers on the Internet so that they appear to have been sent by the gateway. When packets are sent back from the Internet to the gateway, the gateway forwards the packet on to the associated private computer.

The two main reasons these NAT gateways are used are as follows:

  • Improved security and access control. NAT devices provide a central point through which all traffic from the unmanaged Internet must flow to reach the presumably secure home network. The NAT software frequently has capabilities to filter out any packets that are potentially harmful, as described below.
  • Increased address space. The explosion in popularity of the Internet means an incredible demand for addresses. Internet Protocol version 4 (IPv4), the underlying protocol for today's Internet, is rapidly running out of available unique addresses. NAT devices allow the private computers to "share" a single Internet Protocol (IP) address. Each computer does actually have its own IP address, but that address is only valid within the home network. Any computer outside the home network uses the NAT device's public address to communicate with those inside the home network.

Firewalls are devices or software that inspect incoming or outgoing packets, and reject those that are not allowed by the firewall administrator. Most of them drop incoming packets that did not have a previous outgoing packet to the same port for security reasons. In this respect they behave like NAT devices, which can't forward packets without knowing their intended target. Many NAT devices also implement firewall capabilities.

Proxies relay requests to the external network on behalf of computers on the internal network. They can cache some requests like World Wide Web traffic for improved response time. They also typically work in conjunction with proxy client software installed on the internal computers for increased access control. Because external computers only see the proxy's external address, proxies can be thought of as performing NAT for the internal computers.

Unfortunately, all of these mechanisms are often at odds with providing a seamless network gaming experience. For example, having both a private address as well as a shared public address can make it hard to send packets to the appropriate destination. Sometimes the user is forced to enable forwarding for a particular port in order to play online. But until the next version of the Internet Protocol (IPv6) becomes widely deployed, issues like address sharing will only grow more common.

Microsoft® DirectPlay® provides many features such as Universal Plug and Play support that take the hard work out of supporting NAT. This section includes the following topics.

  • Quick NAT Compatibility Guidelines. Quick guidelines that all game developers should consider to maximize NAT compatibility.
  • Topology Specific NAT Issues. Breakdown of the issues affecting each topology architecture.
  • Using the IDirectPlay8NATResolver Interface. Help implementing IDirectPlay8NATResolver servers.
  • Notes Regarding Firewalls and Proxies. A few notes about how NATs affect firewalls and proxies.
  • NAT Troubleshooting Techniques for Developers and End Users. Troubleshooting techniques for developers and end users.

© 2002 Microsoft Corporation. All rights reserved.


Quick NAT Compatibility Guidelines

Following these guidelines will help you maximize your application's compatibility with Network Address Translation (NAT) devices, proxies, and firewalls.

  • Keep host enumerations active while connecting.

    Ending a call to EnumHosts before calling IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect on the same interface might close a virtual connection that was established with some NAT devices. This could prevent the call to Connect from succeeding. Instead, specify INFINITE for the dwEnumCount parameter when calling EnumHosts and let Microsoft® DirectPlay® stop the enumeration for you when the call to Connect completes successfully.

  • Avoid relying on DPNSVR.

    DPNSVR can simplify discovering multiple hosts on a single computer or a migrated host, but packets sent to the DPNSVR port can seem like separate connections to many NAT devices. They might not be forwarded in the same way as packets sent directly to the game's port. If you use DPNSVR, you should enumerate both the DPNSVR port and the game port when possible. See Using the DirectPlay DPNSVR Application for more information.

  • Use default ports but allow user to override if necessary.

    You should let DirectPlay select the local device port to use by default. The addresses returned by IDirectPlay8Peer::GetLocalHostAddresses and IDirectPlay8Server::GetLocalHostAddresses can be used to identify the port actually selected for hosts. Your game can then use external means, such as DirectPlay Lobby match-making, as a way to get the host's addresses to clients. However, applications should still provide the option for users to select a particular port. Some NAT scenarios require the end user to manually set up port-forwarding and they will appreciate the greater flexibility. See Understanding Ports for more information.

  • Use the client/server topology.

    Every player in the peer-to-peer topology must be able to communicate directly with every other player. This increases the chances that any particular player is prevented from joining a session successfully because of one or more NAT devices. Use the IDirectPlay8Client and IDirectPlay8Server interfaces to be sure that as long as the client can reach the host, it can join the session.

  • Avoid hosting behind NAT devices that are not Universal Plug and Play (UPnP) compatible when possible.

    Almost all NAT issues involve accepting inbound connections through a NAT. IDirectPlay8Peer or IDirectPlay8Server hosts require inbound connections by definition, and are therefore most susceptible. Hosting only on the open Internet or behind devices that support UPnP simplifies the NAT limitations presented to the user.

  • Use match-making services to hide address complexity from user.

    When NAT devices are involved, a player might have multiple addresses even though the computer only has a single physical network interface. Most users will not know which address is correct for a given situation. Your application should use match-making services to pass a combined address returned by IDirectPlay8Peer::GetLocalHostAddresses or IDirectPlay8Server::GetLocalHostAddresses to the client application for a better user experience. You can also use match-making to facilitate advanced NAT traversal techniques. See DirectPlay Lobby Support for more information on match-making.

These guidelines and example implementations are described in more detail for each topology.

© 2002 Microsoft Corporation. All rights reserved.


Topology Specific NAT Issues

Each topology has different Network Address Translation (NAT) requirements, as does each role within the topology. This section has been into organized into the following categories.

  • NAT Issues for Peer Hosts
  • NAT Issues for Peer_Clients
  • NAT Issues for Servers
  • NAT Issues for Clients

© 2002 Microsoft Corporation. All rights reserved.


NAT Issues for Peer Hosts

Hosting with the IDirectPlay8Peer interface has many special Network Address Translation (NAT) considerations, which are described in the following pages.

  • Basic NAT Issues for Peer Hosts
  • Advanced NAT Techniques for Peer Hosts
  • Peer Host NAT Compatibility Reference

© 2002 Microsoft Corporation. All rights reserved.


Basic NAT Issues for Peer Hosts

The best Network Address Translation (NAT) compatibility for hosting with the IDirectPlay8Peer interface is when the NAT device supports the use of Universal Plug and Play (UPnP) by Microsoft® DirectPlay®. Peer hosts should avoid relying on DPNSVR and use a particular set of ports to improve support for NAT devices without UPnP compatibility.

DPNSVR

The DPNSVR helper application is launched when IDirectPlay8Peer::Host is called with a DPN_APPLICATION_DESC structure that does not have the DPNSESSION_NODPNSVR flag set. The DPNSVR process listens for enumeration queries on a "well known" port, which is the same port that is assumed when the DPNA_KEY_PORT component is not specified in the IDirectPlay8Address host object passed to IDirectPlay8Peer::EnumHosts.

When DPNSVR receives an enumeration query, it is forwarded to all DPNSVR-enabled hosts on the local computer. Each host application then replies to the enumerator directly from its own port. However, some clients' NAT devices expect these replies to come from the port to which the client originally sent, and might drop this enumeration response. Therefore if your application uses DPNSVR to help with session discovery, it should also attempt to enumerate the game port directly. This requires that the client knows the game's addresses in advance. See Client Issues for more information on handling peer clients.

Determining the Host's Addresses

A host can determine the addresses on which it is listening by using the IDirectPlay8Peer::GetLocalHostAddresses method.

IDirectPlay8Address *pDP8AddressHost = NULL;
DWORD dwNumAddresses = 1;

hr = pDP8Peer->GetLocalHostAddresses(&pDP8AddressHost, &dwNumAddresses, DPNGETLOCALHOSTADDRESSES_COMBINED);

Specifying the DPNGETLOCALHOSTADDRESSES_COMBINED flag with the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider returns a single address object that allows IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect to attempt all of the host's addresses simultaneously. This address can be converted into a string for easy transmission through a match-making service by using the IDirectPlay8Address::GetURLA method as shown in the following example.

char *szHostAddress = NULL;
DWORD dwNumHostAddressChars = 0;

hr = pDP8AddressHost->GetURLA(NULL, &dwNumHostAddressChars);

szHostAddress = LocalAlloc(LPTR, dwNumHostAddressChars * sizeof(char));

hr = pDP8AddressHost->GetURLA(szHostAddress, &dwNumHostAddressChars);

Once received, the client converts the string back into an object using IDirectPlay8Address::BuildFromURLA. See Client Issues for more information on handling peer clients.

Using a Particular Port

Applications should generally let DirectPlay select a port when hosting. However, there are some NAT scenarios where the user might want to change the port on which the game is hosting. Also, if your application does not pass addresses using DirectPlay Lobby or other match-making service, it should have a default game port to use for direct discovery. This can be added to a device address using the DPNA_KEY_PORT component as shown in the following example.

DWORD dwUserSelectedPort; // value retrieved from user input

if (dwUserSelectedPort != 0)
{
    // User specified a port value; use it.
    hr = pDP8AddressDevice->AddComponent(DPNA_KEY_PORT, &dwUserSelectedPort, sizeof(dwUserSelectedPort), DPNA_DATATYPE_DWORD);
}
else
{
    // Let DirectPlay select; don't add port component.
}

This address object is then passed to IDirectPlay8Peer::Host as a device address on which to host.

Automatic UPnP Port Forwarding

When the host has the Windows Internet Connection Firewall enabled or is behind a UPnP NAT device, DirectPlay will attempt to enable port forwarding for your application automatically. This asks the device to accept all packets received from the Internet on a particular port and forward them to a particular address and port inside the private network.

If DirectPlay selected the local port for the host, then it will select an unused external port for the NAT device to forward. The actual public port number chosen will vary, and might not be the same as the local port.

If the DPNA_KEY_PORT component was set in the device address specified to IDirectPlay8Peer::Host, then DirectPlay will ask the NAT device to forward the same external port number. If that public port number is in use then the call to IDirectPlay8Peer::Host will fail with DPNERR_INVALIDDEVICEADDRESS. This can happen when another instance of the application is already hosting behind the same NAT.

You should design your application and match-making so that they do not require the same port to be used both locally and on the NAT device. You can then allow DirectPlay to try alternate external ports when the matching port is not available by using the DPNA_KEY_TRAVERSALMODE device address component as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_PORTRECOMMENDED;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

Disabling Automatic Traversal

Some users know that the hosting application is not behind a UPnP NAT device and the Windows Internet Connection Firewall is not enabled. Others might want to manually control any mappings made for the host. You can decrease the time required by IDirectPlay8Peer::Host and prevent automated traversal by setting the DPNA_KEY_TRAVERSALMODE component to DPNA_TRAVERSALMODE_NONE as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_NONE;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

© 2002 Microsoft Corporation. All rights reserved.


Advanced NAT Techniques for Peer Hosts

Microsoft® DirectPlay® cannot provide 100 percent connectivity for hosts behind Network Address Translation (NAT) devices that do not support Universal Plug and Play (UPnP). However, your application might be able to improve support for some of these cases using more elaborate methods. The techniques described here require additional development effort, as well as external server resources.

NAT Resolver

NAT devices create an implicit port mapping when an internal computer sends a packet to an external computer. Some NAT devices allow any external computer to use this port mapping to send to the internal computer, instead of only forwarding replies sent by the original external target. These are sometimes referred to as "loose NATs." DirectPlay can take advantage of this behavior using the IDirectPlay8NATResolver interface and address components to allow hosting behind these devices.

You must start by implementing an IDirectPlay8NATResolver server that will be accessible from the Internet. Then your game application can add the DPNA_KEY_NAT_RESOLVER component to the device address passed to IDirectPlay8Peer::Host. The component data is a string containing the Internet Protocol (IP) address and port for the NAT resolver to use, separated by a colon. For example, the following code specifies to use a server located on port 5678 at the address 123.123.123.123.

WCHAR * wszNATResolver = L"123.123.123.123:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

You can also specify a hostname instead of a numerical IP address, as shown in the following example.

WCHAR * wszNATResolver = L"resolver.mydomain.com:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

For robustness, you might want to have more than one resolving servers to try. You can specify multiple addresses separated by commas as shown in the following example.

WCHAR * wszNATResolvers = L"123.123.123.123:5678,backupresolver.mydomain.com:6789";
DWORD dwNATResolverSize = (wcslen(wszNATResolvers) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolvers,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

Each resolver is tried simultaneously for speed, and the first response is used. If no server responds, the IDirectPlay8Peer::Host call still succeeds.

Because hosting these resolving servers requires resources, you might want to prevent arbitrary players from using the resolver. This can be achieved with the DPNA_KEY_NAT_RESOLVER_USER_STRING address component. This value is passed directly to the resolver for verification in the DPN_MSGID_NAT_RESOLVER_QUERY message, and it can choose to respond or ignore as appropriate. The following example shows how to do this.

WCHAR * wszPassword = L"MyPassword";
DWORD dwPasswordSize = (wcslen(wszPassword) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER_USER_STRING,
                        wszPassword,
                        dwPasswordSize,
                        DPNA_DATATYPE_STRING);

Note The user string is passed in clear text over the network, so if the text could contain sensitive information, you should encrypt it in some fashion.

The host's NAT device generates a port mapping for the NAT resolver query. If the NAT resolver elects to respond to the query, DirectPlay will send the mapping's public address back to the querying host. The host will then have it included in the addresses returned by the IDirectPlay8Peer::GetLocalHostAddresses method.

External peer clients use the mapping address when connecting to the internal host. However the NAT device will expire the mapping if it is inactive, which will prevent the clients from using it. The actual expiration timeout varies by NAT device. Generally, the external peer clients are expected to begin connecting within 30 seconds of the IDirectPlay8Peer::Host call completing.

An example usage of NAT resolver address components can be found in the NATPeer sample.

Enumerating Clients to Create Implicit NAT Mappings

An expanded technique can sometimes be used to host behind so-called "strict NATs" that only allow the target of an outbound packet to send packets in to the private network. If the strict NAT device uses the same external port number for sending to different external addresses, even though they are using different implicit mappings, the host might be able to use the IDirectPlay8Peer::EnumHosts method to generate mappings for external peer clients that want to join.

The host must know that the external peer client intends join, as well as the address that the client will use when connecting. This is determined through match-making or similar means. The client's address is then passed as the pdpaddrHost parameter for IDirectPlay8Peer::EnumHosts by the host itself. See Enumerating Hosts for more information.

The joining peers do not need to send an enumeration response and will not even receive a query notification message callback. The NAT device will merely create a mapping for the outbound enumeration packet from the host that allows the client's inbound enumeration or connect requests to be forwarded to the internal host. The host's reverse IDirectPlay8Peer::EnumHosts operation should remain active until the peer client successfully joins or stops attempting to join so that the NAT mapping remains active.

Because the address of the external peer clients must be determined beforehand, the clients also must not be behind NAT devices that select different port numbers for different external targets.

© 2002 Microsoft Corporation. All rights reserved.


Peer Host NAT Compatibility Reference

The following section outlines peer host Network Address Translation (NAT) compatibility for applications that follow the guidelines recommended in previous sections.

Windows 98 Second Edition Internet Connection Sharing

The following table shows the default support for hosts using Microsoft® Windows® 98 Second Edition Internet Connection Sharing (ICS).

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Not without manual port forwarding
Host on ICS computer | Yes | Yes | Not without manual port forwarding or by discovering game via broadcast

Windows 98 Second Edition ICS supports joining a host on or behind the ICS computer from the Internet only with manual port forwarding.

The Advanced NAT Techniques for Peer Hosts section describes methods that might be used to allow external clients to join the host without manual port forwarding in some scenarios.

Windows 2000 Internet Connection Sharing

The following table shows the default support for hosts using Windows 2000 ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Not without manual port forwarding
Host on ICS computer | Yes | Yes | Yes

Windows 2000 ICS supports joining a host on the ICS computer from the Internet. Joining a host behind the ICS computer requires manual port forwarding.

The Advanced NAT Techniques for Peer Hosts section describes methods that can be used to allow external clients to join the host without manual port forwarding in some scenarios.

Windows Millennium Edition Internet Connection Sharing

The following table shows the default support for hosts using Windows Millennium Edition (Windows Me) ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Yes
Host on ICS computer | Yes | Yes | Yes

Hosting behind or on a Windows Me ICS computer is fully supported using Microsoft DirectPlay®'s automatic traversal.

Windows XP Internet Connection Sharing

The following table shows the default support for hosts using Windows XP ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Yes
Host on ICS computer | Yes | Yes | Yes

Hosting behind or on a Windows XP ICS computer is fully supported using DirectPlay's automatic traversal.

Third-Party NAT Device with Universal Plug and Play

Hosting behind a third-party NAT device that is compatible with DirectPlay's automatic traversal using Universal Plug and Play (UPnP) is supported. Refer to the NAT device's documentation for UPnP compatibility information.

Third-Party NAT Device without Universal Plug and Play

Clients can join a host behind a third-party NAT device without Universal Plug and Play support if the clients are behind the same device. External clients cannot join by default unless port forwarding is manually configured. Refer to the NAT device's documentation for information on enabling port forwarding.

The Advanced NAT Techniques for Peer Hosts section describes methods that can be used to allow external clients to join the host without manual port forwarding in some scenarios.

© 2002 Microsoft Corporation. All rights reserved.


NAT Issues for Peer Clients

Clients using the IDirectPlay8Peer interface have many special Network Address Translation (NAT) considerations, which are described in the following pages.

  • Basic NAT Issues for Peer Clients
  • Advanced NAT Techniques for Peer Clients
  • Peer Client NAT Compatibility Reference

© 2002 Microsoft Corporation. All rights reserved.


Basic NAT Issues for Peer Clients

The best Network Address Translation (NAT) compatibility for joining a session with the IDirectPlay8Peer interface is when the NAT device supports Microsoft® DirectPlay®'s use of Universal Plug and Play (UPnP). Peer clients should keep enumerations active and avoid relying on DPNSVR to improve support for NAT devices without UPnP compatibility.

Keeping EnumHosts Active While Connecting

Most NAT devices create virtual connections each time an internal client starts sending packets to a new external address and port, such as a new IDirectPlay8Peer::EnumHosts operation. These virtual connections will sometimes be destroyed as soon as the IDirectPlay8Peer::EnumHosts operation completes. If your client application enumerates hosts before connecting, you should neither cancel the IDirectPlay8Peer::EnumHosts operation nor allow it to time out so that the call to IDirectPlay8Peer::Connect can reuse the virtual connection. This requirement can be met by specifying INFINITE for the dwEnumCount parameter as shown in the following example.
hr = pDP8Peer->EnumHosts(&dpnad,
                         pDP8AddressHost,
                         pDP8AddressDevice,
                         NULL,
                         0,
                         INFINITE,
                         0,
                         0,
                         NULL,
                         &dpnhEnumHosts,
                         0);

DirectPlay will automatically cancel all outstanding IDirectPlay8Peer::EnumHosts operations for you when the connect operation completes successfully. If the connect fails, the enumerations will continue running. You can then cancel them using the IDirectPlay8Peer::CancelAsyncOperation method.

To ensure that the connect operation uses the same virtual connection as the enumeration, the host and device address objects specified to IDirectPlay8Peer::Connect should be the same as those included in the corresponding DPN_MSGID_ENUM_HOSTS_RESPONSE message. For examples of how to add a reference or duplicate these addresses, see the DirectPlay C++ Samples.

DPNSVR

The application sends enumeration queries to the DPNSVR port when the DPNA_KEY_PORT component is not specified in the IDirectPlay8Address host object passed to IDirectPlay8Peer::EnumHosts. However the hosts reply from their respective game ports. Some NAT devices expect replies to come from the port to which the client originally sent, and might therefore drop the enumeration response. If your application uses DPNSVR to help with session discovery, it should also attempt to enumerate the game port directly.

Enumerating the Host's Game Port Directly

The host can retrieve its addresses using IDirectPlay8Peer::GetLocalHostAddresses and pass it in string format to the client using IDirectPlay8Address::GetURLA through a match-making service. The client can then convert the string back into an address using the IDirectPlay8Address::BuildFromURLA method as shown in the following example.

IDirectPlay8Address *pDP8AddressHost = NULL;

hr = CoCreateInstance(CLSID_DirectPlay8Address, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, NULL, (PVOID*) (&pDP8AddressHost));

hr = pDP8AddressHost->BuildFromURLA(szHostAddress);

This address object can then be passed to IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect.

Enumerating or Connecting From a Particular Port

Applications should almost always let DirectPlay choose the local port or ports when enumerating or connecting. However, the local ports selected by DirectPlay to connect to the original host are the same ones used to listen for new players once the host migrates. If your application uses host migration but does not pass updated addresses for the new host by a DirectPlay Lobby or other match-making service, you might want to allow the user to select a local port. This can be added to a device address using the DPNA_KEY_PORT component as shown in the following example.

DWORD dwUserSelectedPort; // value retrieved from user input

if (dwUserSelectedPort != 0)
{
    // User specified a port value; use it.
    hr = pDP8AddressDevice->AddComponent(DPNA_KEY_PORT, &dwUserSelectedPort, sizeof(dwUserSelectedPort), DPNA_DATATYPE_DWORD);
}
else
{
    // Let DirectPlay select; don't add port component.
}

This address object is then passed to IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect for the device address parameter.

Automatic UPnP Port Forwarding

When the client has Microsoft Windows® Internet Connection Firewall enabled or is behind a UPnP NAT device, DirectPlay will attempt to enable port forwarding for your application automatically. This asks the device to accept all packets received from the Internet on a particular port and forward them to a particular address and port inside the private network.

If DirectPlay selected the local port for the client, then it will select an unused external port for the NAT device to forward. The actual public port number chosen will vary, and might not be the same as the local port.

If the DPNA_KEY_PORT component was set in the device address specified to IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect, then DirectPlay will ask the NAT device to forward the same external port number. If that public port number is in use then the call to IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect will fail with DPNERR_INVALIDDEVICEADDRESS. This might happen when another instance of the application behind the same NAT is already connected. You should design your application and match-making so that they do not require the same port to be used both locally and on the NAT device. You can then allow DirectPlay to try alternate external ports when the matching port is not available by using the DPNA_KEY_TRAVERSALMODE device address component. This is shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_PORTRECOMMENDED;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

Disabling Automatic Traversal

Some users know that the client is not behind a UPnP NAT device and Windows Internet Connection Firewall is not enabled. Others might want to manually control any mappings made for the client. You can decrease the time required by IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect and prevent automated traversal by setting the DPNA_KEY_TRAVERSALMODE component to DPNA_TRAVERSALMODE_NONE as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_NONE;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

© 2002 Microsoft Corporation. All rights reserved.


Advanced NAT Techniques for Peer Clients

Microsoft® DirectPlay® cannot provide 100 percent connectivity for peer clients behind Network Address Translation (NAT) devices that do not support Universal Plug and Play (UPnP). However, your application might be able to improve support for some of these cases using more elaborate methods. The techniques described here require additional development effort as well as external server resources.

NAT Resolver

NAT devices create an implicit port mapping when an internal computer sends a packet to an external computer. Some NAT devices allow any external computer to use this port mapping to send to the internal computer, instead of only forwarding replies sent by the original external target. These are sometimes referred to as "loose NATs." DirectPlay automatically takes advantage of this behavior when the peer host is outside of the NAT. Your application can use the IDirectPlay8NATResolver interface and address components to also allow peer clients behind a loose NAT to join a session hosted behind the same NAT device with external peer clients already connected to the same session.

You must start by implementing an IDirectPlay8NATResolver server that will be accessible from the Internet. Then your game application can add the DPNA_KEY_NAT_RESOLVER component to the device address passed to IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect. The component data is a string containing the Internet Protocol (IP) address and port for the NAT resolver to use, separated by a colon. For example, the following code specifies to use a server located on port 5678 at the address 123.123.123.123.

WCHAR * wszNATResolver = L"123.123.123.123:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

You can also specify a hostname instead of a numerical IP address as shown in the following example.

WCHAR * wszNATResolver = L"resolver.mydomain.com:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

For robustness, you might want to have more than one resolving servers to try. You can specify multiple addresses separated by commas as shown in the following example.

WCHAR * wszNATResolvers = L"123.123.123.123:5678,backupresolver.mydomain.com:6789";
DWORD dwNATResolverSize = (wcslen(wszNATResolvers) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolvers,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

Each resolver is tried simultaneously for speed, and the first response is used. If no server responds, the IDirectPlay8Peer::EnumHosts or IDirectPlay8Peer::Connect call still succeeds.

Because hosting these resolving servers requires resources, you might want to prevent arbitrary players from using the resolver. This can be achieved with the DPNA_KEY_NAT_RESOLVER_USER_STRING address component. This value is passed directly to the resolver for verification in the DPN_MSGID_NAT_RESOLVER_QUERY message, and it can choose to respond or ignore as appropriate. The following example shows how to do this.

WCHAR * wszPassword = L"MyPassword";
DWORD dwPasswordSize = (wcslen(wszPassword) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER_USER_STRING,
                        wszPassword,
                        dwPasswordSize,
                        DPNA_DATATYPE_STRING);

Note The user string is passed in clear text over the network, so if the text could contain sensitive information, you should encrypt it in some fashion.

The peer client's NAT device generates a port mapping for the NAT resolver query. If the NAT resolver elects to respond to the query, DirectPlay will send the mapping's public address back to the querying peer client. The address will then be reported to the host when connecting to the session so external peer clients can contact this joining internal client.

An example usage of NAT resolver address components can be found in the NATPeer sample.

© 2002 Microsoft Corporation. All rights reserved.


Peer Client NAT Compatibility Reference

The following section outlines peer client Network Address Translation (NAT) compatibility for applications that follow the guidelines recommended in previous sections.

Windows 98 Second Edition Internet Connection Sharing

Any number of peer clients behind or on the same Microsoft® Windows® 98 Second Edition Internet Connection Sharing (ICS) system is supported. Peer clients behind different Windows 98 Second Edition ICS computers are not supported.

A player behind or on the Windows 98 Second Edition ICS computer that receives a DPN_MSGID_HOST_MIGRATE message indicating that the host has migrated to the local player becomes a peer host. See the Windows 98 Second Edition Internet Connection Sharing section in the Peer Host NAT Compatibility Reference topic.

Windows 2000 Internet Connection Sharing

Any number of peer clients behind or on the same Windows 2000 ICS system is supported. Peer clients behind different Windows 2000 ICS computers are not supported.

A player behind or on the Windows 2000 ICS computer that receives a DPN_MSGID_HOST_MIGRATE message indicating that the host has migrated to the local player becomes an peer host. See the Windows 2000 Internet Connection Sharing section in the Peer Host NAT Compatibility Reference topic.

Windows Millennium Edition Internet Connection Sharing

Any number of peer clients behind or on the same or different Windows Millennium Edition (Windows Me) ICS computers is fully supported using Microsoft DirectPlay®'s automatic traversal.

Windows XP Internet Connection Sharing

Any number of peer clients behind or on the same or different Windows XP ICS computers is fully supported using DirectPlay's automatic traversal.

Third-Party NAT Device with Universal Plug and Play

Any number of peer clients behind the same or different third-party NAT devices that are compatible with DirectPlay's automatic traversal using Universal Plug and Play (UPnP) is supported. Refer to the NAT device's documentation for UPnP compatibility information.

Third-Party NAT Device without Universal Plug and Play

Any number of peer clients behind the same NAT device without UPnP is supported. Peer clients behind different NAT devices without UPnP are not supported but might work, depending on the device implementation.

The Advanced NAT Techniques for Peer Clients describes methods that can be used to allow clients to join sessions in some scenarios that do not work using default settings.

A player behind a third-party NAT device that receives a DPN_MSGID_HOST_MIGRATE message indicating that the host has migrated to the local player becomes an peer host. See the Third-Party NAT Device Without Universal Plug-and-Play section in the Peer Host NAT Compatibility Reference topic.

© 2002 Microsoft Corporation. All rights reserved.


NAT Issues for Servers

The IDirectPlay8Server interface has some special Network Address Translation (NAT) considerations, which are described in the following pages.

  • Basic NAT Issues for Servers
  • Advanced NAT Techniques for Servers
  • Server NAT Compatibility Reference

© 2002 Microsoft Corporation. All rights reserved.


Basic NAT Issues for Servers

The best Network Address Translation (NAT) compatibility for hosting with the IDirectPlay8Server interface is when the NAT device supports the use of Universal Plug and Play (UPnP) by Microsoft® DirectPlay®. Servers should avoid relying on DPNSVR and use a particular set of ports to improve support for NAT devices without UPnP compatibility.

DPNSVR

The DPNSVR helper application is launched when IDirectPlay8Server::Host is called with a DPN_APPLICATION_DESC structure that does not have the DPNSESSION_NODPNSVR flag set. The DPNSVR process listens for enumeration queries on a "well known" port, which is the same port that is assumed when the DPNA_KEY_PORT component is not specified in the IDirectPlay8Address host object passed to IDirectPlay8Client::EnumHosts.

When DPNSVR receives an enumeration query it is forwarded to all DPNSVR-enabled hosts on the local computer. Each host application then replies to the enumerator directly from its own port. However, some clients' NAT devices expect these replies to come from the port to which the client originally sent, and might drop this enumeration response. Therefore if your application uses DPNSVR to help with session discovery, it should also attempt to enumerate the game port directly. This requires that the client knows the game's addresses in advance. See Client Issues for More Information on Handling Peer Clients.

Determining the Host's Addresses

A host can determine the addresses on which it is listening by using the IDirectPlay8Server::GetLocalHostAddresses method.

IDirectPlay8Address *pDP8AddressHost = NULL;
DWORD dwNumAddresses = 1;

hr = pDP8Server->GetLocalHostAddresses(&pDP8AddressHost, &dwNumAddresses, DPNGETLOCALHOSTADDRESSES_COMBINED);

Specifying the DPNGETLOCALHOSTADDRESSES_COMBINED flag with the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider returns a single address object that allows IDirectPlay8Client::EnumHosts or IDirectPlay8Client::Connect to attempt all of the host's addresses simultaneously. This address can be converted into a string for easy transmission through a match-making service by using the IDirectPlay8Address::GetURLA method as shown in the following example.

char *szHostAddress = NULL;
DWORD dwNumHostAddressChars = 0;

hr = pDP8AddressHost->GetURLA(NULL, &dwNumHostAddressChars);

szHostAddress = LocalAlloc(LPTR, dwNumHostAddressChars * sizeof(char));

hr = pDP8AddressHost->GetURLA(szHostAddress, &dwNumHostAddressChars);

Once received, the client converts the string back into an object using IDirectPlay8Address::BuildFromURLA. See Client Issues for more information on handling peer clients.

Using a Particular Port

Applications should generally let DirectPlay select a port when hosting. However, there are some NAT scenarios where the user might want to change the port on which the game is hosting. Also, if your application does not pass addresses using DirectPlay Lobby or other match-making service, it should have a default game port to use for direct discovery. This can be added to a device address using the DPNA_KEY_PORT component as shown in the following example.

DWORD dwUserSelectedPort; // value retrieved from user input

if (dwUserSelectedPort != 0)
{
    // User specified a port value; use it.
    hr = pDP8AddressDevice->AddComponent(DPNA_KEY_PORT, &dwUserSelectedPort, sizeof(dwUserSelectedPort), DPNA_DATATYPE_DWORD);
}
else
{
    // Let DirectPlay select; don't add port component.
}

This address object is then passed to IDirectPlay8Server::Host as a device address on which to host.

Automatic UPnP Port Forwarding

When the host has the Microsoft Windows® Internet Connection Firewall enabled or is behind a UPnP NAT device, DirectPlay will attempt to enable port forwarding for your application automatically. This asks the device to accept all packets received from the Internet on a particular port and forward them to a particular address and port inside the private network.

If DirectPlay selected the local port for the host, then it will select an unused external port for the NAT device to forward. The actual public port number chosen will vary, and might not be the same as the local port.

If the DPNA_KEY_PORT component was set in the device address specified to IDirectPlay8Server::Host, DirectPlay will ask the NAT device to forward the same external port number. If that public port number is in use then the call to IDirectPlay8Server::Host will fail with DPNERR_INVALIDDEVICEADDRESS. This can happen when another instance of the application is already hosting behind the same NAT.

You should design your application and match-making so that they do not require the same port to be used both locally and on the NAT device. You can then allow DirectPlay to try alternate external ports when the matching port is not available by using the DPNA_KEY_TRAVERSALMODE device address component as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_PORTRECOMMENDED;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

Disabling Automatic Traversal

Some users know that the hosting application is not behind a UPnP NAT device and the Windows Internet Connection Firewall is not enabled. Others might want to manually control any mappings made for the host. You can decrease the time required by IDirectPlay8Server::Host and prevent automated traversal by setting the DPNA_KEY_TRAVERSALMODE component to DPNA_TRAVERSALMODE_NONE as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_NONE;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

© 2002 Microsoft Corporation. All rights reserved.


Advanced NAT Techniques for Servers

Microsoft® DirectPlay® cannot provide 100 percent connectivity for hosts behind Network Address Translation (NAT) devices that do not support Universal Plug and Play (UPnP). However, your application might be able to improve support for some of these cases using more elaborate methods. The techniques described here require additional development effort as well as external server resources.

NAT Resolver

NAT devices create an implicit port mapping when an internal computer sends a packet to an external computer. Some NAT devices allow any external computer to use this port mapping to send to the internal computer, instead of only forwarding replies sent by the original external target. These are sometimes referred to as "loose NATs." DirectPlay can take advantage of this behavior using the IDirectPlay8NATResolver interface and address components to allow hosting behind these devices.

You must start by implementing an IDirectPlay8NATResolver server that will be accessible from the Internet. Then your game application can add the DPNA_KEY_NAT_RESOLVER component to the device address passed to IDirectPlay8Server::Host. The component data is a string containing the Internet Protocol (IP) address and port for the NAT resolver to use, separated by a colon. For example, the following code specifies to use a server located on port 5678 at the address 123.123.123.123.

WCHAR * wszNATResolver = L"123.123.123.123:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

You can also specify a hostname instead of a numerical IP address as shown in the following example.

WCHAR * wszNATResolver = L"resolver.mydomain.com:5678";
DWORD dwNATResolverSize = (wcslen(wszNATResolver) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolver,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

For robustness, you might want to have more than one resolving servers to try. You can specify multiple addresses separated by commas as shown in the following example.

WCHAR * wszNATResolvers = L"123.123.123.123:5678,backupresolver.mydomain.com:6789";
DWORD dwNATResolverSize = (wcslen(wszNATResolvers) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER,
                        wszNATResolvers,
                        dwNATResolverSize,
                        DPNA_DATATYPE_STRING);

Each resolver is tried simultaneously for speed, and the first response is used. If no server responds, the IDirectPlay8Server::Host call still succeeds.

Because hosting these resolving servers requires resources, you might want to prevent arbitrary players from using the resolver. This can be achieved with the DPNA_KEY_NAT_RESOLVER_USER_STRING address component. This value is passed directly to the resolver for verification in the DPN_MSGID_NAT_RESOLVER_QUERY message, and it can choose to respond or ignore as appropriate. The following example shows how to do this.

WCHAR * wszPassword = L"MyPassword";
DWORD dwPasswordSize = (wcslen(wszPassword) + 1) * sizeof(WCHAR);

hr = pDP8DeviceAddress->AddComponent(DPNA_KEY_NAT_RESOLVER_USER_STRING,
                        wszPassword,
                        dwPasswordSize,
                        DPNA_DATATYPE_STRING);

Note The user string is passed in clear text over the network, so if the text could contain sensitive information, you should encrypt it in some fashion.

The host's NAT device generates a port mapping for the NAT resolver query. If the NAT resolver elects to respond to the query, DirectPlay will send the mapping's public address back to the querying host. The host will then have it included in the addresses returned by the IDirectPlay8Server::GetLocalHostAddresses method.

External clients use the mapping address when connecting to the internal host. However the NAT device will expire the mapping if it is inactive, which will prevent external clients from using it. The actual expiration timeout varies by NAT device. Generally, the external clients are expected to begin connecting within 30 seconds of the IDirectPlay8Server::Host call completing.

An example usage of NAT resolver address components can be found in the NATPeer sample.

© 2002 Microsoft Corporation. All rights reserved.


Server NAT Compatibility Reference

The following section outlines server Network Address Translation (NAT) compatibility for applications that follow the guidelines recommended in previous sections.

Windows 98 Second Edition Internet Connection Sharing

The following table shows the default support for hosts using Microsoft® Windows® 98 Second Edition Internet Connection Sharing (ICS).

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Not without manual port forwarding
Host on ICS computer | Yes | Yes | Not without manual port forwarding or by discovering game via broadcast

Windows 98 Second Edition ICS supports joining a host on or behind the ICS computer from the Internet only with manual port forwarding.

The Advanced NAT Techniques for Peer Hosts section describes methods that can be used to allow external clients to join the host without manual port forwarding in some scenarios.

Windows 2000 Internet Connection Sharing

The following table shows the default support for hosts using Windows 2000 ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Not without manual port forwarding
Host on ICS computer | Yes | Yes | Yes

Windows 2000 ICS supports joining a host on the ICS computer from the Internet. Joining a host behind the ICS computer requires manual port forwarding.

Windows Millennium Edition Internet Connection Sharing

The following table shows the default support for hosts using Windows Millennium Edition (Windows Me) ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Yes
Host on ICS computer | Yes | Yes | Yes

Hosting behind or on a Windows Me ICS computer is fully supported using DirectPlay's automatic traversal.

Windows XP Internet Connection Sharing

The following table shows the default support for hosts using Windows XP ICS.

 | Join from behind ICS computer | Join from ICS computer | Join from external network
Host behind ICS computer | Yes | Yes | Yes
Host on ICS computer | Yes | Yes | Yes

Hosting behind or on a Windows XP ICS computer is fully supported using Microsoft DirectPlay®'s automatic traversal.

Third-Party NAT Device with Universal Plug and Play

Hosting behind a third-party NAT device that is compatible with DirectPlay's automatic traversal using Universal Plug and Play (UPnP) is supported. Refer to the NAT device's documentation for UPnP compatibility information.

Third-Party NAT Device without Universal Plug and Play

Clients can join a host behind a third-party NAT device without Universal Plug and Play support if the clients are behind the same device. External clients cannot join by default unless port forwarding is manually configured. Refer to the NAT device's documentation for information on enabling port forwarding.

The Advanced NAT Techniques for Servers section describes methods that can be used to allow external clients to join the host without manual port forwarding in some scenarios.

© 2002 Microsoft Corporation. All rights reserved.


NAT Issues for Clients

Clients using the IDirectPlay8Client interface have some limited Network Address Translation (NAT) considerations, which are described in the following pages.

  • Basic NAT Issues for Clients
  • Client NAT Compatibility Reference

© 2002 Microsoft Corporation. All rights reserved.


Basic NAT Issues for Clients

The IDirectPlay8Client interface has very few Network Address Translation (NAT) concerns and works in almost all scenarios. Clients should however keep enumerations active and avoid relying on DPNSVR to ensure NAT compatibility.

Keeping EnumHosts Active While Connecting

Most NAT devices create virtual connections each time an internal client starts sending packets to a new external address and port, such as a new IDirectPlay8Client::EnumHosts operation. These virtual connections will sometimes be destroyed as soon as the IDirectPlay8Client::EnumHosts operation completes. If your client application enumerates hosts before connecting, you should neither cancel the IDirectPlay8Client::EnumHosts operation nor allow it to time out so that the call to IDirectPlay8Client::Connect can reuse the virtual connection. This requirement can be met by specifying INFINITE for the dwEnumCount parameter as shown in the following example.
hr = pDP8Client->EnumHosts(&dpnad,
                           pDP8AddressHost,
                           pDP8AddressDevice,
                           NULL,
                           0,
                           INFINITE,
                           0,
                           0,
                           NULL,
                           &dpnhEnumHosts,
                           0);

Microsoft® DirectPlay® will automatically cancel all outstanding IDirectPlay8Client::EnumHosts operations for you when the connect operation completes successfully. If the connect fails, the enumerations will continue running. You can then cancel them using the IDirectPlay8Client::CancelAsyncOperation method.

To ensure that the connect operation uses the same virtual connection as the enumeration, the host and device address objects specified to IDirectPlay8Client::Connect should be the same as those included in the corresponding DPN_MSGID_ENUM_HOSTS_RESPONSE message. For examples of how to add a reference or duplicate these addresses, see the DirectPlay C++ Samples.

DPNSVR

The application sends enumeration queries to the DPNSVR port when the DPNA_KEY_PORT component is not specified in the IDirectPlay8Address host object passed to IDirectPlay8Client::EnumHosts. However the hosts reply from their respective game ports. Some NAT devices expect replies to come from the port to which the client originally sent, and might therefore drop the enumeration response. If your application uses DPNSVR to help with session discovery, it should also attempt to enumerate the game port directly.

Enumerating the Host's Game Port Directly

The host can retrieve its addresses using IDirectPlay8Server::GetLocalHostAddresses and pass it in string format to the client using IDirectPlay8Address::GetURLA through a match-making service. The client can then convert the string back into an address using the IDirectPlay8Address::BuildFromURLA method as shown in the following example.

IDirectPlay8Address *pDP8AddressHost = NULL;

hr = CoCreateInstance(CLSID_DirectPlay8Address, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, NULL, (PVOID*) (&pDP8AddressHost));

hr = pDP8AddressHost->BuildFromURLA(szHostAddress);

This address object can then be passed to IDirectPlay8Client::EnumHosts or IDirectPlay8Client::Connect.

Enumerating or Connecting from a Particular Port

Applications should almost always let DirectPlay choose the local port or ports when enumerating or connecting. However, you might want to allow the user to select a local port. This can be added to a device address using the DPNA_KEY_PORT component as shown in the following example.

DWORD dwUserSelectedPort; // value retrieved from user input

if (dwUserSelectedPort != 0)
{
    // User specified a port value; use it.
    hr = pDP8AddressDevice->AddComponent(DPNA_KEY_PORT, &dwUserSelectedPort, sizeof(dwUserSelectedPort), DPNA_DATATYPE_DWORD);
}
else
{
    // Let DirectPlay select; don't add port component.
}

This address object is then passed to IDirectPlay8Client::EnumHosts or IDirectPlay8Client::Connect for the device address parameter.

Disabling Automatic Traversal

When the client has Microsoft Windows® Internet Connection Firewall enabled or is behind a Universal Plug and Play (UPnP) NAT device, DirectPlay will attempt to enable port forwarding for your application automatically. This asks the device to accept all packets received from the Internet on a particular port and forward them to a particular address and port inside the private network. In many cases, this is unnecessary, particularly when the server is known to be on the open Internet. You can decrease the time required by IDirectPlay8Client::EnumHosts or IDirectPlay8Client::Connect and prevent automated traversal by setting the DPNA_KEY_TRAVERSALMODE component to DPNA_TRAVERSALMODE_NONE as shown in the following example.

DWORD dwTraversalMode = DPNA_TRAVERSALMODE_NONE;

hr = pDP8AddressDevice->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD);

© 2002 Microsoft Corporation. All rights reserved.


Client NAT Compatibility Reference

When following the guidelines listed in the previous sections, the IDirectPlay8Client interface supports all Network Address Translation (NAT) device types.

© 2002 Microsoft Corporation. All rights reserved.


Using the IDirectPlay8NATResolver Interface

The IDirectPlay8NATResolver interface can be used in conjunction with the DPNA_KEY_NAT_RESOLVER and DPNA_KEY_NAT_RESOLVER_USER_STRING address components to improve automated Network Address Translation (NAT) support in some cases. This section describes how to implement a NAT resolver application that is deployed on the Internet. Hosts and clients use this server to identify their public address as described in Advanced NAT Techniques for Peer Hosts, Advanced NAT Techniques for Peer Clients, and Advanced NAT Techniques for Servers.

Creating an IDirectPlay8NATResolver Interface

To prepare the NAT resolver you must first create the interface object and call IDirectPlay8NATResolver::Initialize to specify a callback function. This is shown in the following example.
hr = CoCreateInstance(CLSID_DirectPlay8NATResolver,
                      NULL,
                      CLSCTX_INPROC_SERVER,
                      IID_IDirectPlay8NATResolver,
                      (LPVOID*) &g_pDPNATResolver);

.
.
.
hr = g_pDPNATResolver->Initialize(NULL, DirectPlayMessageHandler, 0);

The IDirectPlay8ThreadPool interface can be used to control threading for the IDirectPlay8NATResolver interface. If you choose to use IDirectPlay8ThreadPool, that interface should be initialized and configured first.

Starting a NAT Resolver

Once the IDirectPlay8NATResolver interface has been initialized, you should call IDirectPlay8NATResolver::Start to begin listening for NAT resolver queries. The device addresses passed to IDirectPlay8NATResolver::Start are similar to those passed to IDirectPlay8Peer::Host or IDirectPlay8Server::Host, except that they must only be for the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider, and IPv6 device globally unique identifiers (GUIDs) are not accepted. You can leave the device GUID unspecified and listen using all devices. You might also choose to not specify an address object at all, and Microsoft® DirectPlay® will automatically select a port for listening on all TCP/IP protocol devices. The following example shows how to optionally start listening on a particular port specified by the user.
if (g_dwPort > 0)
{
    hr = pDP8AddrLocal->AddComponent(DPNA_KEY_PORT,
                                     &g_dwPort,
                                     sizeof(DWORD),
                                     DPNA_DATATYPE_DWORD);
}

hr = g_pDPNATResolver->Start(&pDP8AddrLocal, 1, 0);

Handling queries

The IDirectPlay8NATResolver interface only generates one callback to the application's message handler, DPN_MSGID_NAT_RESOLVER_QUERY. The message contains the address of the query sender and the device on which it was received. The application can allow DirectPlay to respond to the query by returning DPN_OK from its message handler, or ignore it by returning a failure code. This is shown in the following example.

case DPN_MSGID_NAT_RESOLVER_QUERY:
{
    DPNMSG_NAT_RESOLVER_QUERY *pMsgNATResolverQuery = (DPNMSG_NAT_RESOLVER_QUERY*) pMsgBuffer;
    .
    .
    .

    if (bIgnoreQuery)
    {
        // Return failure to ignore the query.
        return DPNERR_GENERIC;
    }

    // Return OK so that DirectPlay will reply.
    .
    .
    .
}

The DPNMSG_NAT_RESOLVER_QUERY structure also contains a pointer to the user string, or NULL if the string was not specified. This string is the same as the DPNA_NAT_RESOLVER_USER_STRING component included in the querying application's device address specified to IDirectPlay8Peer::Host, IDirectPlay8Peer::EnumHosts, IDirectPlay8Peer::Connect, IDirectPlay8Server::Host, IDirectPlay8Client::EnumHosts, or IDirectPlay8Client::Connect. The user string is sent in clear text, so you should encrypt the string if it contains sensitive data.

See NATResolver for an example usage of this interface.

© 2002 Microsoft Corporation. All rights reserved.


Notes Regarding Firewalls and Proxies

Following the guidelines outlined for maximizing Network Address Translation (NAT) support will maximize your application's firewall and proxy support as well. A few issues specific to firewalls and proxies are described here.

Windows Internet Connection Firewall

Microsoft® DirectPlay® works with the Internet Connection Firewall capabilities of Microsoft Windows® XP. When your application begins hosting, enumerating, or connecting, the appropriate ports will automatically open and when your application shuts down, these ports will automatically close. However, the user launching the application must be a member of the administrator group for the computer so that DirectPlay has the security permissions to open the ports. If the user is not an administrator, then only IDirectPlay8Client and IDirectPlay8Peer clients are supported.

You can disable the automatic Internet Connection Firewall traversal using the DPNA_KEY_TRAVERSALMODE device address component described in Basic NAT Issues for Peer Hosts, Basic NAT Issues for Peer Clients, Basic NAT Issues for Servers, and Basic NAT Issues for Clients.

Third-Party Firewall Solutions

DirectPlay cannot automatically configure third-party firewalls. However, IDirectPlay8Client and IDirectPlay8Peer clients are generally supported without user intervention, unless the application relies on DPNSVR. See Basic NAT Issues for Peer Clients or Basic NAT Issues for Clients for more information on avoiding DPNSVR.

The user should consult the product's documentation for information on how to allow hosts to traverse a particular third-party firewall.

Microsoft Internet Security and Acceleration Server

DirectPlay works with Microsoft Internet Security and Acceleration (ISA) Server. Clients that have the ISA Firewall Client software installed should not cancel the enumeration before connecting and should pass the address objects from the DPN_MSGID_ENUM_HOSTS_RESPONSE callback as described in Basic NAT Issues for Peer Clients and Basic NAT Issues for Clients. If the enumeration is cancelled, the ISA Server can close the virtual connection established by the enumeration and the call to IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect will fail.

DPNSVR should also be avoided as described in Basic NAT Issues for Peer Hosts, Basic NAT Issues for Peer Clients, Basic NAT Issues for Servers, and Basic NAT Issues for Clients.

Hosts behind an ISA Server must manually configure the proxy to redirect traffic received externally to the internal host. Refer to the ISA Server documentation for information on defining server publishing and protocol rules.

Third-Party Proxies

Applications should follow the guidelines described in Basic NAT Issues for Peer Hosts, Basic NAT Issues for Peer Clients, Basic NAT Issues for Servers, and Basic NAT Issues for Clients.

IDirectPlay8Client and IDirectPlay8Peer clients are generally supported, however the user should refer to the product's documentation for possible restrictions.

Hosts behind a third-party proxy must manually configure the proxy to redirect traffic received externally to the internal host. The user should refer to the product's documentation for directions on how to enable port forwarding.

© 2002 Microsoft Corporation. All rights reserved.


NAT Troubleshooting Techniques for Developers and End Users

This topic contains techniques to help developers and end users who are trying to troubleshoot Network Address Translation (NAT) problems.

  • Verify simple connectivity by attempting to access the World Wide Web.
  • Use the Ping system utility to verify that packets can be sent to and from the computer's Internet Protocol (IP) gateway. Also use Ping to test the host or player that cannot join. Note that some firewalls might disallow the Internet Control Message Protocol echo packets used by Ping even though the two computers can communicate.
  • Third-party NAT device owners should download and install the latest firmware revision available from the manufacturer.
  • Microsoft® Windows® XP Internet Connection Sharing users should ensure that the Allow other network users to control or disable the shared Internet connection box in the shared connection's properties Advanced tab is set.
  • Running a CPU-intensive application such as a game on the Windows Internet Connection Sharing computer can impact NAT performance. Clients behind the Internet Connection Sharing computer might experience higher latency and packet loss when the computer is heavily loaded.
  • Many NAT devices have a Demilitarized Zone option that forwards all packets to a particular computer. This can be used to ensure connectivity for that computer if all other traversal mechanisms fail.
  • When the IDirectPlay8Peer::Connect method completes with the DPNERR_PLAYERNOTREACHABLE error code, this means that the host was contacted, but one or more peers already in the session could not communicate with the joining player. Having the players join the session in a different order can prevent this, but it might mean some of the players are behind NAT devices that are not compatible.

© 2002 Microsoft Corporation. All rights reserved.


Optimizing Network Usage

Providing the best gaming experience normally means sending updates and other information as rapidly as possible without flooding the target with more messages than it can handle. The Microsoft® DirectPlay® protocol combined with asynchronous messaging enables you to dynamically optimize your messaging strategy to provide your users with the best possible game experience.

The bulk of your messaging will use the IDirectPlay8Peer::SendTo, IDirectPlay8Client::Send, or IDirectPlay8Server::SendTo methods. These methods normally work asynchronously for all message categories. They return immediately, and your message handler receives a DPN_MSGID_SEND_COMPLETE message when the message is actually sent. You can choose to send messages synchronously by setting the DPNSEND_SYNC flag. If you do so, the method will block until the message is actually sent.

The DirectPlay protocol's throttling mechanism guarantees that the client will not receive messages faster than they can be handled. However, the throttling protocol does not control how frequently you submit messages to the outgoing queue. You can easily end up with a large backlog of messages in your unsent message queues. You can avoid this situation by sending messages as infrequently as possible, but then you might unnecessarily degrade the user's experience. An optimal messaging strategy sends messages as fast as possible without exceeding the target's ability to handle them.

The following are tips for optimizing your messaging strategy.

  • Send most if not all of your messages asynchronously. If you send a message synchronously, the method will block until the throttling mechanism allows the message to be sent.
  • Monitor the pending message queues and the network statistics. If there are few or no messages in the queue, you can increase your transmission rate. If the queues are large or growing rapidly, decrease your transmission rate and perhaps cancel some messages. See the discussion of send timeouts in Send Prioritization for more information.
  • Analyze the pending message queues on a player-by-player basis. Some players might be able to receive messages at a much higher rate than others. The bulk statistics might be misleading. Consider using directed sends rather than group sends.
  • Choose the appropriate category for each message. Reserve the categories with the highest overhead for the most important messages.
  • Prioritize your messages, so that the most important are assured of being sent promptly and not delayed by relatively unimportant messages.
  • Do not let the pending message queues grow too large. In addition to delaying the transmission of your messages, a large number of pending messages might consume significant memory resources.
  • Use the timeout feature of the Send and SendTo methods to automatically clear outdated messages from the pending message queue.
  • Minimize the amount of data per message. It is usually better to send frequent small messages than a smaller number of large messages.
  • Do not loop tightly when checking the pending message queue. Doing so wastes CPU cycles. Instead, use a sleep period based on how long it typically takes the queue to get down to the level that it will be ready for another send.

© 2002 Microsoft Corporation. All rights reserved.


Testing Network Performance

Microsoft® DirectPlay® offers the DP8Sim service provider that allows you to test your DirectPlay application in a variety of network conditions, such as high latency and packet loss. The network simulator is not a replacement for testing in the real deployment environment, but it can help you predict how your application will perform.

DirectPlay also offers the DP8Sim Utility if you don't want to create your own testing environment. The main advantage of using the IDP8SimControl interface and the DP8Sim service provider in your application is that it allows you to integrate the network settings into your application's debugging user interface (UI), command line, or scripting tools instead of having to manually change the settings through the DP8Sim Utility.

Note The network simulator is implemented on top of the existing DirectPlay8 TCP/IP Service Provider. The settings are also applied on top of the existing network characteristics. Therefore, it is intended to be used on a high-speed local area network (LAN) where normal latency and packet loss are negligible.

Using the DP8Sim service provider

You can switch between the standard Transmission Control Protocol/Internet Protocol (TCP/IP) service provider to the DP8Sim service provider to run network simulation tests on your application. To set the network simulator as your service provider, you have three choices.

  • Enumerate all service providers and then select the "DirectPlay8 TCP/IP Service Provider (Network Simulator)."
  • Explicitly set the service provider globally unique identifier (GUID) with IDirectPlay8Address::SetSP.
  • Call IDirectPlay8Peer::EnumServiceProviders, IDirectPlay8Server::EnumServiceProviders, or IDirectPlay8Client::EnumServiceProviders with the pguidServiceProvider set to CLSID_NETWORKSIMULATOR_DP8SP_TCPIP.
Note The DP8Sim service providers enumerated will have the DPNSPINFO_NETWORKSIMULATORDEVICE flag set in the dwFlags member of the DPN_SERVICE_PROVIDER_INFO structure.

The following example shows how to explicitly set the service provider to the network simulator.

IDirectPlay8Address*  g_pDeviceAddress;
.
.
.
hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlay8Address,
                       (LPVOID*) &g_pDeviceAddress );

hr = g_pDeviceAddress->SetSP(&CLSID_NETWORKSIMULATOR_DP8SP_TCPIP );

When using the DP8Sim service provider, DirectPlay will set the DPNSPCAPS_NETWORKSIMULATOR in DPN_SP_CAPS.

© 2002 Microsoft Corporation. All rights reserved.


Using Player Context Values

Most applications will want to associate some data with each player. However, when you receive a message that is associated to a player, you need some way to access that data quickly. Player context values are designed to provide you with an efficient way to access your player data.

Note Only the IDirectPlay8Peer and IDirectPlay8Server interfaces use player context values. They are not needed for the IDirectPlay8Client interface because clients use this interface to communicate only with the server, not other clients.

Defining a Player Context Value

To user player context values, you need to have a block of data on your system for each player, typically in the form of a structure. A player context value is normally an index into an array of pointers to the various players' data blocks. When you receive a message from a player, there is no need for time-consuming operations such as searching for the player's identifier (ID) in a table. The index contained in the player context value allows you to quickly obtain the necessary pointer.

You define a player context value when you handle the DPN_MSGID_CREATE_PLAYER message that notifies you that a player has been added to the game. Host's can also define a player context value when they handle the DPN_MSGID_INDICATE_CONNECT message. That player context value will be set in the subsequent DPN_MSGID_CREATE_PLAYER message. When the host processes that message, it has the option of changing the player context value. To create a player context value:

  • Allocate a structure to hold the player's data.
  • Add the structure pointer to your player data array.
  • Assign the index of that pointer to the pvPlayerContext member of the message's DPN_MSGID_CREATE_PLAYER structure.

Microsoft® DirectPlay® does not specify how you should obtain the data to populate the structure. Each game is responsible for handling that issue in its own way.

Note The only place you can define a player context value is in a DPN_MSGID_CREATE_PLAYER or DPN_MSGID_INDICATE_CONNECT message handler. When the DPN_MSGID_CREATE_PLAYER message handler returns, the player context value is set. For each subsequent message associated with that player, the player context value will be the same value that was set by the DPN_MSGID_CREATE_PLAYER message handler. You can modify the contents of the associated data structure, but you cannot change the player context value itself.

Managing Player Context Data

While player context values are fairly straightforward to handle, there are a couple of issues that you need to be careful with.

The player context value provides you with a quick way to obtain a valid memory address that will presumably be accessed each time a message arrives. However, you must be careful that different parts of your application do not access the data at the same time. DirectPlay serializes messages associated with a particular player, which guarantees that you will never be handling two messages from the same player at the same time. As long as you only access the data structure from your callback message handler, you can safely access the structure. However, most applications will need to access player data outside the message handler.

If your application accesses the data outside the callback message handler, you must prevent concurrent access by providing some sort of global mechanism to lock the structure. Even if your application does not require such locking in the early stages of development, you should assume that locking will eventually be required, and build it in from the beginning. If your player context values that are indexes into an array, you should also make sure that you read and update that array safely.

Don't deallocate a player's data structure prematurely. When a player leaves the game, you will normally want to deallocate their data structure and free the associated memory. However, be careful about deallocating the structure as soon as you receive a DPN_MSGID_DESTROY_PLAYER message. If your application accesses that structure outside the callback message handler, that data may still be in use when the message arrives. If you deallocate the structure as soon as the message arrives, you may cause other parts of your application to fail.

To avoid prematurely deallocating the structure, you should not only provide an application-level locking mechanism, you should also implement some sort of reference counting. Increment this reference count when you create the structure, and every time you use it. Decrement the reference count every time you have finished with the structure, including in your DPN_MSGID_DESTROY_PLAYER message handler. As long as the reference count is nonzero, some part of your application is accessing the structure. Do not deallocate the structure until the reference count drops to zero.

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectPlay DPNSVR Application

Microsoft® Windows® allows one process per Internet Protocol (IP) or Internetwork Packet Exchange (IPX) port. Windows does not allow multiple processes to share a single port. To act as a communication host, each application must use a separate port. This restriction creates several issues, especially when doing such tasks as enumerating running games.

  • Avoiding port conflicts. You must choose a port that does not conflict with other applications.
  • Managing multiple communications hosts on a single system. Each instance of a host must use a different port. Client applications then have to determine which port a particular host is using.
  • Avoiding ports that are already in use. If your preferred port is in use, your application must be able to use another port.

The DPNSVR application addresses these issues by acting as a forwarding service for enumeration requests. When an application begins hosting, it informs DPNSVR on which port it is running. DPNSVR listens on a well-known port and forwards any enumeration requests to all Microsoft DirectPlay® hosts on the system. Responses to enumeration requests contain the port number to which the host is actually connected.

The following diagram illustrates how DPNSVR, on a computer with two active host applications, handles an enumeration query from a remote client.

Diagram of how DPNSVR handles an enumeration query

DPNSVR offers developers the following advantages.

  • You can write generic enumeration routines that enumerate all the games running on a particular system.
  • You can use DirectPlay to select the host's port. Client applications can use the services of DPNSVR to enumerate the running games on a well-known port, and the responses will contain the port number to which the host is actually connected.
  • You need not allow for the situation where your application does not get the port it requests.
  • You need not be concerned about conflicts with other applications on the system

While most applications will want to use the services of DPNSVR, there are some circumstances where you may want to disable it. Two examples are:

  • You know what port you want to use, and only one instance of your application will be running on the computer.
  • You want to restrict the ability of players to enumerate your session. If you disable DPNSVR, only those players who know which port your host is connected to will be able to enumerate your host.

How to Use DPNSVR

To determine whether DPNSVR is supported by your service provider, call the GetSPCaps methods supported by the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interface. If the service provider supports DPNSVR, the DPNSPCAPS_SUPPORTSDPNSRV flag will be set in the dwFlags member of the returned DPN_SP_CAPS structure. Only IP, IPX, and the network simulator service providers currently support DPNSVR.

Note If you host a DPNSVR session with the network simulator service provider, you cannot host a DPNSVR session with the IP service provider and vice versa. All DPNSVR sessions must be with either the IP or the network simulator service provider. This does not affect your ability to host IPX session or sessions without DPNSVR.

Using DPNSVR requires no special effort, because it is selected by default. If you do not want enumeration requests forwarded to your host, you must explicitly disable DPNSVR by setting the DPNSESSION_NODPNSVR flag in the dwFlags member of the DPN_APPLICATION_DESC structure. Some additional characteristics of DPNSVR are:

  • DPNSVR does not have a window but it does appear in the user's task list.
  • If no applications are using DPNSVR, it shuts down after 30 seconds of inactivity. DPNSVR is automatically started up when an application begins hosting.
  • You can shut down DPNSVR by running DPNSVR /kill from the command line and it will shut down immediately. However, if you have any host applications open when you shut down DPNSVR, they will no longer be able to receive enumerations on the DPNSVR port.
Note Applications can always enumerate your host if they know the port on which it is running, even if the DPNSESSION_NODPNSVR flag is set.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay C/C++ Tutorials

This section contains tutorials that provide step-by-step instructions for implementing basic Microsoft® DirectPlay® functionality in a C or C++ application. Each tutorial builds on the previous tutorials and it is recommended that you complete the tutorials in the order in which they are listed. The first eight tutorials use the IDirectPlay8Peer interface methods. Tutorial 9 uses the IDirectPlay8Client and IDirectPlay8Server interface methods.

Tutorials

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
  • Tutorial 4: Connecting to a Session
  • Tutorial 5: Sending Messages to Other Peers
  • Tutorial 6: Handling Host Migration
  • Tutorial 7: Creating a Lobbyable Application
  • Tutorial 8: Direct Play Voice
  • Tutorial 9: Creating a DirectPlay Client/Server Session
  • Tutorial 10: DirectPlay Thread Pool

Note These tutorials are written using C++ style function calls. For instructions on writing Microsoft DirectX® function calls in a C environment, see Using C to Access COM Objects.
For other examples, see DirectPlay C++ Samples.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers

This series of tutorials demonstrate how to implement a simple peer-to-peer multiplayer game using Microsoft® DirectPlay®. This tutorial outlines the initial steps: creating a DirectPlay object and enumerating the available network service providers. Subsequent tutorials build on this foundation to take you through the key steps needed to construct a simple peer-to-peer console application. Much of the information in these tutorials can also be applied to client/server applications. The complete sample code for this tutorial is included with the Microsoft DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut01_EnumSP.

For a general discussion of peer-to-peer applications, see Peer-to-Peer Sessions.

  • User's Guide
  • Creating a DirectPlay Peer Object
  • Enumerating Service Providers
  • Terminating a DirectPlay Application
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and the application displays the service providers found on your computer. To end the tutorial, click Exit.

Creating a DirectPlay Peer Object

One of the first things a peer-to-peer application must do is create and initialize a DirectPlay peer object (CLSID_DirectPlay8Peer). To create a DirectPlay peer object, call CoCreateInstance, and request a pointer to an IDirectPlay8Peer interface. All of your subsequent interaction with DirectPlay and your fellow players will be through this interface.

Once you have created the peer object, you must initialize it by calling the IDirectPlay8Peer::Initialize method. This method takes three parameters:

  • A player context value
  • A pointer to your callback message handling function
  • A flag

The message handler is a key part of a DirectPlay application. You communicate with DirectPlay by calling methods on a DirectPlay interface. DirectPlay in turn communicates with your application by sending messages to your message handler, much like Microsoft Windows® sends messages to a window procedure. See DirectPlay Callback Functions and Multithreading Issues for details on how to implement a message handler.

The player context value is an application defined value that is returned each time a message is sent to your message handler. See Using Player Context Values for a discussion of how to handle player context values.

There is only one flag value that can be set, DPNINITIALIZE_DISABLEPARAMVAL. Setting this flag disables parameter validation for all DirectPlay methods. While setting this flag improves your application's performance, you should only do so with an application that has been thoroughly tested.

The following excerpt from the tutorial sample illustrates how to create and initialize a DirectPlay peer object.

#include <dplay8.h>
.
.
.
// Create the IDirectPlay8Peer Object
   hr = CoCreateInstance( CLSID_DirectPlay8Peer, NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDirectPlay8Peer,
                          (LPVOID*) &g_pDP );

// Initialize DirectPlay
   hr = g_pDP->Initialize(NULL, DirectPlayMessageHandler, 0 );

Enumerating Service Providers

DirectPlay is an application programming interface (API) that allows game players to easily connect with each other and exchange messages, regardless of the underlying transport protocol. It enables you to use one or more service providers when hosting, connecting to, or enumerating sessions. To determine which service providers are available on your system, DirectPlay allows your application to enumerate your system's valid installed service providers as well as their adapters.

To enumerate your service providers, call IDirectPlay8Peer::EnumServiceProviders. This method fills an application-supplied buffer with information about the valid service providers on your system. As you do not know the minimum size of the buffer prior to calling this method, you should call it twice. The first time, specify a zero-length buffer and the method returns the required size. Use this size value in your second method call and DirectPlay fills the buffer with valid data. See Using DirectPlay Enumerations for further information about DirectPlay enumeration.

The following excerpt from the tutorial sample illustrates how to enumerate available service providers.

    DPN_SERVICE_PROVIDER_INFO*  pdnSPInfo       = NULL;
    DPN_SERVICE_PROVIDER_INFO*  pdnSPInfoEnum   = NULL;
    DWORD                       dwItems         = 0;
    DWORD                       dwSize          = 0;
    DWORD                       i;

    // Determine the required buffer size
    hr = g_pDP->EnumServiceProviders(NULL, NULL, NULL, &dwSize, &dwItems, 0);

     pdnSPInfo = (DPN_SERVICE_PROVIDER_INFO*) new BYTE[dwSize];

    //Fill the buffer with service provider information
    hr = g_pDP->EnumServiceProviders(NULL, NULL, pdnSPInfo, &dwSize, &dwItems, 0 );

    // Print the provider descriptions
    pdnSPInfoEnum = pdnSPInfo;
    for (i = 0; i < dwItems; i++)
    {
        DXUtil_ConvertWideStringToGenericCch( strBuf, pdnSPInfoEnum->pwszName, 256 );
        SendMessage( GetDlgItem( g_hDlg, IDC_PROVIDERS ),
                     LB_ADDSTRING, 0, (LPARAM) strBuf );

        pdnSPInfoEnum++;
    }

Terminating a DirectPlay Application

If a DirectPlay peer object was successfully initialized by calling IDirectPlay8Peer::Initialize, it should be closed by calling IDirectPlay8Peer::Close. You should then release all active objects before terminating the application. A DirectPlay object can be reused once it has been closed, provided that it is re-initialized by calling IDirectPlay8Peer::Initialize.

The following excerpt from the tutorial sample illustrates how to close and release DirectPlay objects.

hr = g_pDP->Close(0);

g_pDP->Release();
g_pDP = NULL;

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 2: Hosting a Session

This tutorial extends Tutorial 1, and discusses how to create an address object and advertise your application as a session host. Refer to Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers for the initial steps in this tutorial. The complete sample code for this tutorial is included with the Microsoft® DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut02_Host.

  • User's Guide
  • Creating an Address Object
  • Hosting a Session
  • Terminating the Application
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens which contains information about the session status, which initially will be "Not connected to a session". To begin hosting a session, click the Start Hosting button. Once you are hosting a session, the session status will change to "Hosting a Session." To stop hosting, click Exit.

Creating an Address Object

The first step in hosting a session is to create a Microsoft DirectPlay® address object (CLSID_DirectPlay8Address) that contains the address of of the device that you host the session on. At a minimum, each address object must contain a service provider. The simplest way to specify a service provider is to call the address object's IDirectPlay8Address::SetSP method. You can optionally specify a particular adapter. If no adapter is specified, and it is allowed, DirectPlay attempts to host the session on all adapters associated with the given service provider. See DirectPlay Addressing for further information about DirectPlay addressing.

The following excerpt from the tutorial sample illustrates how to create an address object for a Transmission Control Protocol/Internet Protocol (TCP/IP) protocol service provider.

IDirectPlay8Address*  g_pDeviceAddress = NULL;
.
.
.
    // Create our IDirectPlay8Address Device Address
       hr = CoCreateInstance( CLSID_DirectPlay8Address, NULL,
                                       CLSCTX_INPROC_SERVER,
                                       IID_IDirectPlay8Address,
                                       (LPVOID*) &g_pDeviceAddress );
    // Set the SP for our Device Address
    hr = g_pDeviceAddress->SetSP(&CLSID_DP8SP_TCPIP );

Hosting a Session

Once you have created the address object, you must then create a description of your application. To do so, assign appropriate values to the members of a DPN_APPLICATION_DESC structure. The information that you can provide includes:

  • The application's globally unique identifier (GUID)
  • The maximum number of players (optional)
  • The session name (optional)
  • A session password (optional)
  • Application-specific data (optional)

The application GUID uniquely identifies an application, not a particular session. Different applications should not have the same GUID. If you specify a maximum player count of 0, there is no limit on the number of players that can join the session.

To begin hosting a session, call IDirectPlay8Peer::Host. The following excerpt from the tutorial sample illustrates how host a session with an unlimited number of players.

    DPN_APPLICATION_DESC    dpAppDesc;
.
.
.
    // Set up the application description.
    ZeroMemory(&dpAppDesc, sizeof(DPN_APPLICATION_DESC));
    dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC);
    dpAppDesc.guidApplication = g_guidApp;

    // You are now ready to host the application.
    hr = g_pDP->Host( &dpAppDesc,          // AppDesc
                      &g_pDeviceAddress, 1,// Device Address
                      NULL, NULL,          // Reserved
                      NULL,                // Player Context
                      0 );                 // dwFlags

Hosting a DirectPlay session causes a host player to be created with the player name and data specified when you called the IDirectPlay8Peer::SetPeerInfo method. When the player is created, you are notified through your DirectPlay message handler.

Terminating the Application

If a DirectPlay peer object was successfully initialized, you should first close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 3: Enumerating Hosted Sessions

Before your application can join a peer-to-peer session, you need the address of the session host. In some cases, lobby-launched applications might give you the host address. With Microsoft® DirectPlay®, you can use that address to connect to the session. There is no need to enumerate the available hosted sessions. However, if you do not have the address of a session host, you must obtain it by enumerating the available hosted sessions. This tutorial extends Tutorial 2, and discusses how to enumerate available hosts. The complete sample code for this tutorial is included with the Microsoft DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut03_EnumHosts.

  • User's Guide
  • Initiating Host Enumeration
  • Handling Host Responses
  • Terminating the Application

Refer to the preceding tutorials for a discussion of the initial steps in the process:

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and you can choose to either begin hosting a session or enumerate existing sessions.

To host, click the Host... button and the Host New Session window opens. Enter a session name and click OK. the session status will change to 'Hosting Session "YourSessionName".'

To enumerate existing sessions, enter an Internet Protocol (IP) address in the Search Address box and click Search. The application prints all the sessions found at the address in the Detected Sessions box. The Search button will turn grey while the search is taking place. If the address does not exist, a message box opens containing the error. If no session is found at the address, the Detected Sessions box will have a message that says "No hosts found."

You can run this sample twice—once to host a session and once to enumerate sessions. When enumerating, enter your computer's IP address.

To end the sample, click Exit.

Initiating Host Enumeration

To enumerate hosts, you must basically advertise a description of the type of session that you are interested in, your target address, and the device you perform the enumeration on. You then wait for any available hosts to respond.

You describe your application by assigning values to a DPN_APPLICATION_DESC structure, as discussed in Tutorial 2. Tutorial 2 also describes how to create an address object to contain your address.

To start the host enumeration, pass the DPN_APPLICATION_DESC structure and your address object to IDirectPlay8Peer::EnumHosts. You can specify a host address if you want to direct your enumeration query to a particular address. Otherwise, host enumeration queries are broadcast to every address in your Transmission Control Protocol/Internet Protocol (TCP/IP) subnet.

The following excerpt from the tutorial sample illustrates how to start enumerating the available hosts at a specified address.

    ZeroMemory(&dpAppDesc, sizeof(DPN_APPLICATION_DESC));
    dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC);
    dpAppDesc.guidApplication = g_guidApp;

    hr = g_pDP->EnumHosts( &dpAppDesc,          // pApplicationDesc
                           g_pHostAddress,      // Host Address
                           g_pDeviceAddress,    // Device Address
                           NULL, 0,             // pvUserEnumData, size
                           4,                   // dwEnumCount
                           0,                   // dwRetryInterval
                           0,                   // dwTimeOut
                           NULL,                // pvUserContext
                           NULL,                // pAsyncHandle
                           DPNENUMHOSTS_SYNC ); // dwFlags

Handling Host Responses

A host receives your query in the form of a DPN_MSGID_ENUM_HOSTS_QUERY message sent to the message handler. The associated structure includes the information that you passed to IDirectPlay8Peer::EnumHosts. After examining this information, the host can respond to your query by returning DPN_OK, or reject the query by returning a different value.

When a host responds affirmatively, your application's message handler receives a DPN_MSGID_ENUM_HOSTS_RESPONSE message. The structure associated with the message contains information describing the session.

The following excerpt from the tutorial sample illustrates how to process a DPN_MSGID_ENUM_HOSTS_RESPONSE message. Essentially, the message handler places the associated structure in a list, to be examined after the enumeration is finished. Refer to the tutorial sample for details.

HRESULT WINAPI DirectPlayMessageHandler( PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer )
{
.
.
.
  switch( dwMessageId )
    {
        case DPN_MSGID_ENUM_HOSTS_RESPONSE:
        {
            PDPNMSG_ENUM_HOSTS_RESPONSE     pEnumHostsResponseMsg;
            const DPN_APPLICATION_DESC*     pAppDesc;
            HOST_NODE*                      pHostNode = NULL;
            WCHAR*                          pwszSession = NULL;

            pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE) pMsgBuffer;
            pAppDesc = pEnumHostsResponseMsg->pApplicationDescription;
            .
            .
            .
            // Copy the Host Address
             pEnumHostsResponseMsg->pAddressSender->Duplicate(&pHostNode->pHostAddress);

             pHostNode->pAppDesc = new DPN_APPLICATION_DESC;

             ZeroMemory(pHostNode->pAppDesc, sizeof(DPN_APPLICATION_DESC));
             memcpy(pHostNode->pAppDesc, pAppDesc, sizeof(DPN_APPLICATION_DESC));

When enumeration is finished, the IDirectPlay8Peer::EnumHosts method returns, and your application can decide which session to join.

Terminating the Application

If a DirectPlay peer object was successfully initialized you should first close the object by calling IDirectPlay8Peer::Close. Then release all active objects and terminate the application. See Tutorial 1 for further discussion.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 4: Connecting to a Session

If you have found a session, you can then connect to it. This tutorial extends Tutorial 3 and discusses how to connect to a session. The complete sample code for this tutorial is included with the Microsoft® DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut04_Connect.

  • User's Guide
  • Connecting to a Session
  • Terminating the Application

Refer to the preceding tutorials for a discussion of the initial steps in the process:

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and you can choose to either begin hosting a session or connect to an existing session.

To host, click the Host... button and the Host New Session window opens. Enter a session name and click OK. the session status will change to 'Hosting Session "YourSessionName".'

To connect to an existing session, enter an Internet Protocol (IP) address in the Search Address box and click Search. The application prints all the sessions found at the address in the Detected Sessions box. The Search button will turn grey while the search is taking place. Select one of the Detected Sessions and click Connect.

You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address.

To end the sample, click Exit.

Connecting to a Session

Once you have selected a host, you can connect to the session. To do so, you will need:

  • A DPN_APPLICATION_DESC structure. The structure should include the application's globally unique identifier (GUID) and a password if one is required for joining the session.
  • The host address that you received when you enumerated the available hosts.
  • An address object with your device address. See Creating an Address Object for a discussion of how to create an address object.

To connect to a session, call IDirectPlay8Peer::Connect. The host receives a DPN_MSGID_INDICATE_CONNECT message with your information. The host might reject the connection at this point by returning a value other than DPN_OK. In that case, if IDirectPlay8Peer::Connect is called synchronously, as it is in the tutorial, the method returns an error value. If the connection is accepted, your Microsoft DirectPlay® message handler receives a DPN_MSGID_CONNECT_COMPLETE message. You also receive a DPN_MSGID_CREATE_PLAYER messages for yourself and each player already in the session.

The following excerpt from the tutorial sample illustrates how to connect to a selected session.

    DPN_APPLICATION_DESC        dpnAppDesc;
    IDirectPlay8Address*        pHostAddress = NULL;
.
.
.
    ZeroMemory(&dpnAppDesc, sizeof(DPN_APPLICATION_DESC));
    dpnAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC);
    dpnAppDesc.guidApplication = g_guidApp;
.
.
.
    hr = g_pDP->Connect(&dpnAppDesc,    // Application Description
                        pHostAddress,       // Host Address
                        g_pDeviceAddress,
                        NULL,
                        NULL,
                        NULL, 0,
                        NULL,
                        NULL,
                        NULL,
                        DPNCONNECT_SYNC);

        if( FAILED( hr))
            //Failed Connecting to Host
    }

Terminating the Application

If a DirectPlay peer object was successfully initialized, you should first close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 5: Sending Messages to Other Peers

Once you have connected to a session, you can begin game play by sending messages to the other peers in the session for whom you have received a DPN_MSGID_CREATE_PLAYER message. This tutorial extends Tutorial 4 and discusses how to send messages. The complete sample code for this tutorial is included with the Microsoft® DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut05_Send.

  • User's Guide
  • Sending a Message
  • Receiving a Message
  • Terminating the Application

Refer to the preceding tutorials for a discussion of the initial steps in the process:

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
  • Tutorial 4: Connecting to a Session
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and you have the choice to either Host or Connect.

If you choose Host:

  1. A window will open and you should enter a session name, then click OK. Your session status will change to 'Hosting Session "YourSessionName".'
  2. You can now choose to send a message or disconnect. If you choose to send a message, enter a text string and click Send. If you choose to disconnect, click Disconnect and the session ends.
  3. Click Exit to end the sample

If you choose Connect:

  1. The Connect to Session window will open and you should enter an Internet Protocol (IP) address and click Search. If any sessions are found at that address, they will be listed in the Detected Sessions box. Select a session and click Connect. If the address does not exist, a message box opens with an error message.
  2. Once connected, your session status will change to 'Connected to Session "YourSessionName".' You can now choose to send a message or disconnect. If you choose to send a message, enter a text string and click Send. If you choose to disconnect, click Disconnect.
  3. Click Exit to end the sample.

You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address. Once connected, you can send messages between the host and the client application.

Sending a Message

Once the session is initiated, the peers manage the progress of the game by sending a stream of messages to each other. The content of the message is up to the application but typically includes such information as game state updates or player-to-player communication. Sending a message is straightforward. Select the player you want to send the message to, package your data in a buffer, and pass the data to the target player by calling IDirectPlay8Peer::SendTo. You also have the option of using a single IDirectPlay8Peer::SendTo call to broadcast a message to all players.

The following excerpt from the tutorial sample illustrates how to send a message to every player in the session.

    DPN_BUFFER_DESC dpnBuffer;
    WCHAR           wszData[256];

    dpnBuffer.pBufferData = (BYTE*) wszData;
    dpnBuffer.dwBufferSize = 2 * (wcslen(wszData) + 1);

    hr = g_pDP->SendTo( DPNID_ALL_PLAYERS_GROUP, // dpnid
                                    &dpnBuffer,  // pBufferDesc
                                    1,           // cBufferDesc
                                    0,           // dwTimeOut
                                    NULL,        // pvAsyncContext
                                    NULL,        // pvAsyncHandle
                                    DPNSEND_SYNC |
                                    DPNSEND_NOLOOPBACK );    // dwFlags

Receiving a Message

When another player sends you a message, your Microsoft DirectPlay® message handler receives a DPN_MSGID_RECEIVE message containing the data buffer.

The following excerpt from the tutorial sample illustrates a simple message handler for received messages.

//In the receiving player's message handler:

HRESULT WINAPI DirectPlayMessageHandler(void *pvUserContext, DWORD dwMessageId, void *pMsgBuffer)
{
switch( dwMessageId )
{
case DPN_MSGID_RECEIVE:
{
     case DPN_MSGID_RECEIVE:
        {
            PDPNMSG_RECEIVE     pMsg;

            pMsg = (PDPNMSG_RECEIVE) pMsgBuffer;
            //process message
             .
             .
             .
            break;
        }

}
}
return(DPN_OK);
}

Terminating the Application

If a DirectPlay peer object was successfully initialized, you should first close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 6: Handling Host Migration

A peer-to-peer session must have a host. This tutorial extends Tutorial 5 and discusses how to handle the situation that occurs when the host leaves the session. The complete sample code for this tutorial is included with the Microsoft® DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut02_HostMigration.

  • Users Guide
  • Host Migration
  • Terminating the Application

Refer to the preceding tutorials for a discussion of the initial steps in the process:

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
  • Tutorial 4: Connecting to a Session
  • Tutorial 5: Sending Messages to Other Peers
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

Users Guide

When you run this tutorial sample, a window opens and you have the choice to either Host or Connect.

If you choose Host:

  1. A window will open and you should enter a session name. Select the Migrate Host box to allow host migration to take place in this session. Then click OK. Your session status will change to 'Hosting Session "YourSessionName".'
  2. You can now choose to send a message or disconnect. If you choose to send a message, enter a text string and click Send. If you choose to disconnect, click Disconnect and the session ends.
  3. Click Exit to end the sample

If you choose Connect:

  1. The Connect to Session window will open and you should enter an Internet Protocol (IP) address and click Search. If any sessions are found at that address, they will be listed in the Detected Sessions box. Select a session and click Connect. If the address does not exist, a message box opens with an error message.
  2. Once connected, your session status will change to 'Connected to Session "YourSessionName".' You can now choose to send a message or disconnect. If you choose to send a message, enter a text string and click Send. If you choose to disconnect, click Disconnect.
  3. Click Exit to end the sample.

You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address. Once connected, you can send messages between the host and the client application. To test host migration, close the host application. The client application's session status will change to 'Hosting Session "YourSessionName".'.

Host Migration

In a peer-to-peer game, there is nothing to prevent the session host from leaving before the game is finished. This situation typically occurs when the player decides to leave the game but might also result from a network problem that disconnects the player. Because a game must have a host, there are two possible ways to deal with this problem: stop the game, or choose a new host. The process of choosing a new host in the middle of a game is referred to as "host migration."

When a session host initially advertises a session, it must choose whether to allow host migration. If host migration is not allowed, the game terminates when the host leaves. To enable host migration in a session, the original session host must set the DPNSESSION_MIGRATE_HOST flag in the dwFlag member of the DPN_APPLICATION_DESC structure that is passed to the IDirectPlay8Peer::Host. See Tutorial 2: Hosting a Session for more discussion of how to host a session.

If host migration is enabled, the host can still force the session to terminate by calling the IDirectPlay8Peer::TerminateSession method. Otherwise, Microsoft DirectPlay® selects a new session host. When the host migrates, each remaining member's DirectPlay message handler receives a DPN_MSGID_HOST_MIGRATE message. The associated structure includes the identifier of the new host, which may be any remaining player in the session including you.

The following excerpt from the tutorial sample illustrates how to handle DPN_MSGID_HOST_MIGRATE.

HRESULT WINAPI DirectPlayMessageHandler(void *pvUserContext, DWORD dwMessageId, void *pMsgBuffer)
{
switch( dwMessageId )
{
.
.
.
  case DPN_MSGID_HOST_MIGRATE:
        {
            PDPNMSG_HOST_MIGRATE    pHostMigrateMsg;

            pHostMigrateMsg = (PDPNMSG_HOST_MIGRATE) pMsgBuffer;

            // See if you are the new host.
            if( pHostMigrateMsg->dpnidNewHost == g_dpnidLocalPlayer)
                //You are the New Host;
            else
                //The new host is pHostMigrateMsg->dpnidNewHost

            break;
       }
}
}

Terminating the Application

If a DirectPlay peer object was successfully initialized, you should first close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 7: Creating a Lobbyable Application

A lobby is an application whose primary purpose is to enable players to meet and arrange games. It involves two separate application:

  • A lobby server application. This application is implemented by the lobby operator and resides on a remote computer.
  • A lobby client application. This application is implemented by the lobby operator and runs on client systems. It allows the lobby server to communicate with client systems.

In order for a game application to take full advantage of lobby launching, it must be able to communicate with the lobby client application. This tutorial extends Tutorial 6 and discusses how to use Microsoft® DirectPlay® to make a peer-to-peer application "lobbyable". Much of this information also applies to client/server applications. For further information about DirectPlay lobby support, see DirectPlay Lobby. The complete sample code for this tutorial is included with the Microsoft DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut07_LobbyLaunch.

  • Users Guide
  • Detecting a Lobby Launch
  • Handling the DPL_MSGID_CONNECT Message
  • Obtaining Connection Settings
  • Starting the Session
  • Terminating a Lobbied Session
  • Registering an Application as Lobbyable

Refer to the preceding tutorials for a discussion of the initial steps in the process:

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 4: Connecting to a Session
  • Tutorial 5: Sending Messages to Other Peers
  • Tutorial 6: Handling Host Migration

The error handling code for the examples in this document have been deleted for clarity. See the tutorial sample for a complete version of the code.

Users Guide

This sample has the same user interface (UI) as Tutorial 6: Handling Host Migration. See the Users Guide in Tutorial 6: Handling Host Migration for how to use this sample.

Detecting a Lobby Launch

Once your application is launched, you must determine whether you were launched by a lobby, or by some other means. To detect a lobby launch, you must first create a DirectPlay lobbied application object (CLSID_DirectPlay8LobbiedApplication).

Once the lobbied application object has been created, you must initialize it by calling IDirectPlay8LobbiedApplication::Initialize. This call takes four parameters:

  • A context value. This value is included with each message that the lobbied application object sends to your message handler.
  • A pointer to your lobbied application message handling function. This is a standard DirectPlay message handler, which processes messages from the lobbied application object.
  • A pointer to a lobby handle.
  • A flag field.

There is only one flag value that can be set, DPNINITIALIZE_DISABLEPARAMVAL. Setting this flag disables parameter validation for methods on this instance of the DirectPlay lobbied application object. While setting this flag improves your application's performance, you should only do so with an application that has been thoroughly tested.

After the call to IDirectPlay8LobbiedApplication::Initialize returns, examine the lobby handle. If your application was lobby-launched, the variable is set to a valid lobby handle. If your application was not lobby-launched, the lobby handle is set to NULL.

The following excerpt from the tutorial sample illustrates how to detect a lobby launch.

#include <dplay8.h>
#include <dplobby8.h>

BOOL  g_bLobbyLaunched = FALSE;   // TRUE if lobby launched.

IDirectPlay8lobbiedApplication * g_pLobbyApp = NULL;
.
.
.
hr = CoCreateInstance(CLSID_DirectPlay8LobbiedApplication, NULL,
                      CLSCTX_INPROC_SERVER,
                      IID_IDirectPlay8LobbiedApplication,
                      (LPVOID*) &g_pLobbyApp );
.
.
.
// Initialize the lobbied application object.
hr = g_pLobbyApp->Initialize(NULL, LobbyAppMessageHandler, &g_hLobbyHandle, 0);

// Determine whether the application was lobby-launched.
if( g_hLobbyHandle != NULL )
    {
        // Attempt to host or connect to a session based on the
        //   settings received from the lobby client.

    }
else
        // The application was not lobby-launched.

Handling the DPL_MSGID_CONNECT Message

If you were lobby launched, your lobbied application message handler receives a DPL_MSGID_CONNECT message following your call to IDirectPlay8LobbiedApplication::Initialize. This message carries with it a variety of information, including the identifier (ID) that you use to send messages to the lobby client. When you process this message, you should call IDirectPlay8Peer::RegisterLobby. Doing so allows applications to automatically propagate game status to the lobby client application.

The following excerpt from the tutorial sample illustrates how to handle DPL_MSGID_CONNECT.

HRESULT WINAPI LobbyAppMessageHandler(PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer)
{
.
.
.
    switch (dwMessageId)
    {
    .
    .
    .
        case DPL_MSGID_CONNECT:
        {
            PDPL_MESSAGE_CONNECT pConnectMsg;
            DPNHANDLE	            g_hLobbyClient;
            IDirectPlay8Peer*       g_pDP;

            pConnectMsg = (PDPL_MESSAGE_CONNECT)pMsgBuffer;
            PDPL_CONNECTION_SETTINGS pSettings = pConnectMsg->pdplConnectionSettings;
            g_hLobbyClient = pConnectMsg->hConnectId;

            // Register with the lobby.
            hr = g_pDP->RegisterLobby( g_hLobbyClient, g_pLobbiedApp, DPNLOBBY_REGISTER );

            // Check for connection settings.
            if( pSettings == NULL )
               {
                // There are no connection settings from the lobby.
               }
            else
                {
                 // You have connection settings.
                }
Note Your message handler might receive the DPL_MSGID_CONNECT message before the IDirectPlay8LobbiedApplication::Initialize method returns. Your message handler should be prepared to handle the message appropriately.

Obtaining Connection Settings

If your application was lobby-launched, the lobby client has the option of providing you with connection settings. To determine whether you have been given connection settings, examine the DPL_CONNECTION_SETTINGS structure that accompanies the message. If no connection settings are specified, you must query the user. See Tutorial 1 for details.

The DPL_CONNECTION_SETTINGS structure also provides you with a variety of other information that you will need to begin the session, including:

  • A flag indicating whether you are to be the session host.
  • A DPN_APPLICATION_DESC structure with a description of the session.
  • The address of the host, unless you have been selected as host.

Starting the Session

Once you have selected your service provider, start the session much like you would a non-lobbied peer-to-peer session. You should first create a DirectPlay peer object, and call IDirectPlay8Peer::SetPeerInfo to establish your player's name. You should make this method call synchronous by setting the DPNOP_SYNC flag. Otherwise, there is a risk that the method might not return before you attempt to connect to the session.

If the lobby has selected you as host, you need to start hosting the session by calling IDirectPlay8Peer::Host. The other players typically receive your address through their lobby clients and send you connection requests. If you are not the host, get the address of the session host from the DPL_CONNECTION_SETTINGS structure and call the IDirectPlay8Peer::Connect method to connect to the session.

From this point on, the session proceeds much like a non-lobbied session. See the preceding tutorials for further details.

Terminating a Lobbied Session

You should next call IDirectPlay8LobbiedApplication::Close to close the connection to the lobbied application object. If a DirectPlay peer object was successfully initialized you should close the object by calling IDirectPlay8Peer::Close; then release all active objects and terminate the application. See Tutorial 1 for further discussion.

Registering an Application as Lobbyable

An application must be registered before it can be properly lobby launched. You only need to register the application once, typically during your installation procedure. Registration provides DirectPlay with a variety of information about your application, including:

  • The application's unique globally unique identifier (GUID)
  • The application's name
  • The name and path of the application's executable file
  • The name and path of a launcher application (optional)

To register your application, you must create a DirectPlay lobbied application object and call IDirectPlay8LobbiedApplication::RegisterProgram. Do not attempt to manually enter application information in the registry. Failure to use IDirectPlay8LobbiedApplication::RegisterProgram might make your application nonportable and incompatible with later versions of DirectPlay.

The following excerpt from the tutorial sample illustrates how to register a lobbyable application.

    DPL_PROGRAM_DESC	dplDesc;

    ZeroMemory(&dplDesc, sizeof(DPL_PROGRAM_DESC));
    dplDesc.dwSize = sizeof(DPL_PROGRAM_DESC);
    dplDesc.guidApplication = g_guidApp;    // The application GUID
    dplDesc.pwszApplicationName = L"MyApplicationName";
    dplDesc.pwszExecutableFilename = L"MyApp.exe";
    dplDesc.pwszExecutablePath = L"C:\...\MyAppFolder";

    hr = g_pLobbyApp->RegisterProgram(&dplDesc, 0);

When you uninstall a registered lobbyable application, you should unregister it. Your uninstall procedure should create a DirectPlay lobbied application object, and unregister the application by calling the IDirectPlay8LobbiedApplication::UnRegisterProgram method.

The following excerpt from the tutorial sample illustrates how to unregister a lobbyable application.

HRESULT UnRegister()
{
    HRESULT		hr = S_OK;
    hr = g_pLobbyApp->UnRegisterProgram(&g_guidApp, 0);
    return hr;
}

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 8: Direct Play Voice

Microsoft® DirectPlay® Voice is a full-voice communications application programming interface (API) that uses DirectPlay for network session management and network transport. This tutorial extends the preceding tutorials to describe how to add voice communications to a peer-to-peer network application. Much of this information also applies to client/server applications. For further discussion of DirectPlay Voice, see DirectPlay Voice. The complete sample code for this tutorial is included with the Microsoft DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut08_Voice.

  • User's Guide
  • Preparing for a DirectPlay Voice Session
  • Creating a Voice Session Host
  • Starting a Voice Session
  • Testing the Voice Setup
  • Creating a DirectPlay Voice Client Object
  • Connecting to a DirectPlay Voice Client Session
  • Setting the Transmission Targets List
  • Terminating a Voice Session

Refer to the preceding tutorials for a discussion of the initial steps in the process.

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
  • Tutorial 4: Connecting to a Session
  • Tutorial 5: Sending Messages to Other Peers
  • Tutorial 6: Handling Host Migration
  • Tutorial 7: Creating a Lobbyable Application
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and you have the choice to either Host or Connect.

If you choose Host:

  1. A window will open and you should enter a session name. Select the Migrate Host box to allow host migration to take place in this session. Then click OK. If you have not used your sound hardware before, DirectPlay may run the Sound Hardware Test Wizard before you can start a session. Once you are hosting, the session status will change to 'Hosting Session "YourSessionName".'
  2. You can now choose to send a message, disconnect, or speak to other players. If you choose to send a message, enter a text string and click Send. To speak to other players, start talking into your microphone, voice recording starts automatically. If you choose to disconnect, click Disconnect and the session ends.
  3. Click Exit to end the sample

If you choose Connect:

  1. The Connect to Session window will open and you should enter an Internet Protocol (IP) address and click Search. If any sessions are found at that address, they will be listed in the Detected Sessions box. Select a session and click Connect. If the address does not exist, a message box opens with an error message.
  2. Once connected, your session status will change to 'Connected to Session "YourSessionName".' You can now choose to send a message, disconnect, or speak to other players. If you choose to send a message, enter a text string and click Send. To speak to other players, start talking into your microphone, voice recording starts automatically. If you choose to disconnect, click Disconnect.
  3. Click Exit to end the sample.

You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address. Once you start a session and have at least two players connected (the host and a client), the voice recording starts automatically. Speak into a microphone and your voice will play out on the speakers.

Preparing for a DirectPlay Voice Session

Before you can start up a DirectPlay Voice session, you must have a valid DirectPlay object connected to or hosting a session. For full details on creating, connecting and hosting DirectPlay objects, see previous tutorials.

Creating a Voice Session Host

To enable voice communications, one peer in the session must become the Voice session host. To become the host, you must create a Voice server object and obtain a pointer to its IDirectPlayVoiceServer interface. You use this interface to perform host-specific tasks during the Voice session. You must then call IDirectPlayVoiceServer::Initialize to initialize the object. As with most DirectPlay objects, the primary purpose of initialization is to provide DirectPlay with a pointer to your Voice server callback message handler.

Note The Voice server host can be a different peer than the session host.

The following excerpt from the tutorial sample illustrates how to create and initialize a Voice server object.

IDirectPlayVoiceServer*  g_pVoiceServer = NULL;
.
.
.
// Create the Voice server object.
   hr = CoCreateInstance(CLSID_DirectPlayVoiceServer, NULL,
                         CLSCTX_INPROC_SERVER,
                         IID_IDirectPlayVoiceServer,
                         (LPVOID*) &g_pVoiceServer );

// Initialize the object.
   hr = g_pVoiceServer->Initialize(g_pDP,
                                   DirectVoiceServerMessageHandler,
                                   NULL, 0, 0 ) ;

Starting a Voice Session

Before any clients can connect to a Voice session, the Voice session host must start the session by calling IDirectPlayVoiceServer::StartSession. Once the session has been started, Voice clients can connect to the Voice session.

The DVSESSIONDESC structure that you pass to this method contains the information DirectPlay needs to start the session. In particular, you must specify which of several DirectPlay Voice topologies you want to use. This tutorial uses the peer-to-peer topology. For further information about this subject, see DirectPlay Voice Topologies.

The following excerpt from the tutorial sample illustrates how to start a peer-to-peer session using the default CODEC.

IDirectPlayVoiceServer* 	g_pVoiceServer = NULL;
.
.
.
ZeroMemory(&dvSessionDesc, sizeof(DVSESSIONDESC));
dvSessionDesc.dwSize = sizeof(DVSESSIONDESC);
dvSessionDesc.dwSessionType = DVSESSIONTYPE_PEER;
dvSessionDesc.dwBufferQuality = DVBUFFERQUALITY_DEFAULT;
dvSessionDesc.guidCT = DPVCTGUID_DEFAULT;
dvSessionDesc.dwBufferAggressiveness = DVBUFFERAGGRESSIVENESS_DEFAULT;

hr = g_pVoiceServer->StartSession(&dvSessionDesc, 0 );

Testing the Voice Setup

Before connecting a Voice client to a Voice session, you must test the audio configuration. To do so, you must to create an IDirectPlayVoiceTest object and call IDirectPlayVoiceTest::CheckAudioSetup. Call the method first with the DVFLAGS_QUERYONLY set to determine whether the test has already been run.

If the test has not been run, the method returns DVERR_RUNSETUP. You should then call the function again without the DVFLAGS_QUERYONLY flag, and DirectPlay will launch the Sound Hardware Test Wizard. If the method returns a success code, you can continue. Otherwise, you must first handle the error condition. After testing is complete, release the IDirectPlayVoiceTest object. When the audio configuration has been tested, your client can connect to the Voice session.

The following excerpt from the tutorial sample illustrates how to test voice setup.

IDirectPlayVoiceTest*   pVoiceTest = NULL;
.
.
.
// Create the IDirectPlayVoiceTest Object.
   hr = CoCreateInstance(CLSID_DirectPlayVoiceTest, NULL,
                                  CLSCTX_INPROC_SERVER,
                                  IID_IDirectPlayVoiceTest,
                                 (LPVOID*) &pVoiceTest );

guidPlayback = DSDEVID_DefaultVoicePlayback;
guidCapture = DSDEVID_DefaultVoiceCapture;
hr = pVoiceTest->CheckAudioSetup(&guidPlayback,
                                 &guidCapture,
                                 NULL, DVFLAGS_QUERYONLY);
if( hr == DVERR_RUNSETUP)
    {
    // The test has not been run yet.
     hr = pVoiceTest->CheckAudioSetup(&guidPlayback,
                                      &guidCapture,
                                      g_hDlg, DVFLAGS_ALLOWBACK );
    }
else if( FAILED( hr))
    {
    /* Handle Errors */
    }
else
    {
    // The test has been passed, proceed.
    }
.
.
.

Creating a DirectPlay Voice Client Object

All clients that want to participate in the voice session must connect to the session, including the host. The first step in connecting to a voice session is to create and initialize a voice client object (CLSID_DirectPlayVoiceClient).

Once you have created the object, initialize it by calling IDirectPlayVoiceClient::Initialize. Pass this method a pointer to your voice callback message handler. This message handler receives voice-related messages from DirectPlay Voice during the voice session. You must also pass the method a pointer to an IDirectPlay8Peer interface. The DirectPlay object that exposes this interface must be either connected to or hosting a session before you call IDirectPlayVoiceClient::Initialize.

The following excerpt from the tutorial sample illustrates how to create and initialize a voice client object.

// Create the IDirectPlayVoiceClient object.
IDirectPlayVoiceClient* 	g_pVoiceClient = NULL;
.
.
.
hr = CoCreateInstance(CLSID_DirectPlayVoiceClient, NULL,
                                  CLSCTX_INPROC_SERVER,
                                  IID_IDirectPlayVoiceClient,
                                  (LPVOID*) &g_pVoiceClient );
// Initialize the object.
hr = g_pVoiceClient->Initialize(g_pDP,
                                DirectVoiceClientMessageHandler,
                                NULL, 0, 0 );

Connecting to a DirectPlay Voice Client Session

Once the IDirectPlayVoiceClient object is created and initialized, you can connect your client to the voice session by calling IDirectPlayVoiceClient::Connect. You need to pass two structures to this method: DVSOUNDDEVICECONFIG and DVCLIENTCONFIG. The structure contains information about the sound device configuration. The structure is used to configure run-time parameters. When you have initialized the structures, connect to the voice session by passing the structures to IDirectPlayVoiceClient::Connect.

The following excerpt from the tutorial sample illustrates how to initialize a structure. In this example, the default voice capture device and default voice playback device are used for audio capture and playback. Additionally, this example enables automatic microphone selection.

ZeroMemory(&dvSoundDeviceConfig, sizeof(DVSOUNDDEVICECONFIG));
dvSoundDeviceConfig.dwSize = sizeof(DVSOUNDDEVICECONFIG);
dvSoundDeviceConfig.dwFlags = DVSOUNDCONFIG_AUTOSELECT;
dvSoundDeviceConfig.guidPlaybackDevice = DSDEVID_DefaultVoicePlayback;
dvSoundDeviceConfig.lpdsPlaybackDevice = NULL;
dvSoundDeviceConfig.guidCaptureDevice = DSDEVID_DefaultVoiceCapture;
dvSoundDeviceConfig.lpdsCaptureDevice = NULL;
dvSoundDeviceConfig.hwndAppWindow = g_hDlg;
dvSoundDeviceConfig.lpdsMainBuffer = NULL;
dvSoundDeviceConfig.dwMainBufferFlags = 0;
dvSoundDeviceConfig.dwMainBufferPriority = 0;

The following excerpt from the tutorial sample illustrates how to initialize a structure. In this example the system is configured for automatic voice activation and automatic gain control.

dvClientConfig.dwSize = sizeof(DVCLIENTCONFIG);
dvClientConfig.dwFlags = DVCLIENTCONFIG_AUTOVOICEACTIVATED | DVCLIENTCONFIG_AUTORECORDVOLUME;
dvClientConfig.lRecordVolume = DVRECORDVOLUME_LAST;
dvClientConfig.lPlaybackVolume = DVPLAYBACKVOLUME_DEFAULT;
dvClientConfig.dwThreshold = DVTHRESHOLD_UNUSED;
dvClientConfig.dwBufferQuality = DVBUFFERQUALITY_DEFAULT;
dvClientConfig.dwBufferAggressiveness = DVBUFFERAGGRESSIVENESS_DEFAULT;
dvClientConfig.dwNotifyPeriod = 0;

Setting the Transmission Targets List

Before transmitting audio to other voice session clients you must first create a transmission targets list that specifies who should receive audio transmissions. You can send audio to any combination of individual players and/or groups of players. Sending to a group allows you to reach multiple players with a single send. Each player or group is identified by a DVID value, which corresponds to equivalent DirectPlay 8 DPNID value. The transmission targets list may contain up to 64 players and/or groups. If no targets are specified, no audio data is transmitted.

If voice activation is enabled, voice transmission begins when the voice activation module detects speech activity. If voice activation is disabled voice transmission begins when valid set of targets is specified.

The following excerpt from the tutorial sample illustrates how to set a client's transmission targets to all players in the voice session.

DVID dvid = DVID_ALLPLAYERS;
hr = g_pVoiceClient->SetTransmitTargets(&dvid, 1, 0 );

Terminating a Voice Session

Once the session is over, clients, including the host, must shut down their voice client objects. To do so, the client must disconnect from the DirectPlay Voice session by calling IDirectPlayVoiceClient::Disconnect. They can then release the voice client object.

A voice session host terminates a voice session by calling . The session host must then release the DirectPlay Voice server object.

The following excerpt from the tutorial sample illustrates how to terminate a voice session and shut down the voice server and client objects.

// Shut down the voice client object.
hr = g_pVoiceClient->Disconnect( 0 );
g_pVoiceClient->Release();

// Terminate the voice session.
hr = g_pVoiceServer->StopSession( 0 );
g_pVoiceServer->Release();

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 9: Creating a DirectPlay Client/Server Session

This tutorial shows you how to create a simple client/server session. Client/server sessions are often used for creating large-scale multiplayer games. One advantage for using a client/server game rather than a peer-to-peer game is that the majority of the processing can be done on a separate computer—the server—and therefore you do not need to rely on the power of the client's computer. For more information about client/server sessions, see Client/Server Topology and Client/Server Sessions.

Before beginning this tutorial, you should complete Tutorials 1 through 4, which describe how to create a peer-to-peer session. The steps for creating a client/server session are very similar. Rather than passing information directly from peer to peer however, a client/server session requires clients to pass information to each other indirectly, through the server. No automatic method exists for the server to pass information from one client to another. If you want this feature available to your users, you need to implement it in the server application.

The Microsoft® DirectX® software development kit (SDK) includes the complete sample code for this tutorial. The sample code can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut09_ClientServer.

This article contains the following sections.

  • User's Guide
  • Setting Up the Server
  • Setting Up a Client
  • Server Messages
  • Client Messages
  • Terminating a Client/Server Session
Note The error handling code for the examples in this article is removed for clarity. For a complete version of the code, see the tutorial sample.

User's Guide

To play this tutorial sample, first run the server application. To host, click the Host... button and the Host New Session window opens. Enter a session name and click OK. the session status will change to 'Hosting Session "YourSessionName".'

Once the server is hosting, you can run the client application. Click Connect... and the Connect to Session window will open. Enter an Internet Protocol (IP) address in the Search Address box and click Search. The application prints all the sessions found at the address in the Detected Sessions box. The Search button will turn grey while the search is taking place. Select one of the Detected Sessions and click Connect. Once connected, your session status will change to 'Connected to Session "YourSessionName".'

The server and the clients can choose to send a message or disconnect. If sending a message, enter a text string and click Send. If disconnecting, click Disconnect. Click Exit to end the sample.

Setting Up the Server

The server application is where the main part of the game's processing will most likely be done. The server is responsible for updating clients about the game state, for example when a player joins or leaves the session. The following topics in this section describe the tasks needed to set up a server application. Each task is described in detail below.

  1. Create a DirectPlay Server Object
  2. Create the Server Address Object
  3. Begin Hosting

Create a DirectPlay Server Object

Creating a Microsoft DirectPlay® server object is similar to Creating a DirectPlay Peer Object. The only difference is that when you call CoCreateInstance, you pass the class identifier of a server object (CLSID_DirectPlay8Server), the identifier of the interface (IID_IDirectPlay8Server), and the address of a pointer to an IDirectPlay8Server interface, instead of the equivalent peer parameters. After you've created the DirectPlay server object, you can initialize it by calling the IDirectPlay8Server::Initialize method.

The following excerpt from the tutorial sample illustrates how to create and initialize a DirectPlay server object.

    IDirectPlay8Server		*g_pDPServer = NULL;
    .
    .
    .
    // Create the IDirectPlay8Server object.
    hr = CoCreateInstance(CLSID_DirectPlay8Server, NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDirectPlay8Server,
                          (LPVOID*) &g_pDPServer);

    // Initialize DirectPlay.
    hr = g_pDPServer->Initialize(NULL, DirectPlayMessageHandlerServer, 0);

In the initialization, you pass the pointer to a Implementing a Callback Function in DirectPlay and DirectPlay Voice, DirectPlayMessageHandlerServer, which handles messages received by the server.

Create the Server Address Object

To host a session, you must specify the address of the host device. Do this by creating an IDirectPlay8Address object and calling the IDirectPlay8Address::SetSP method. This step is identical to the step Creating an Address Object in Tutorial 2: Hosting a Session.

Begin Hosting

To begin hosting a DirectPlay server session, call the IDirectPlay8Server::Host method. This method takes the following parameters.

  • pdnAppDesc: A pointer to a DPN_APPLICATION_DESC
  • prgpDeviceInfo: A pointer to an array of IDirectPlay8Address objects
  • cDeviceInfo: The number of objects in the array of IDirectPlay8Address objects
  • pdpSecurity and pdpCredentials: Reserved parameters that must be set to NULL
  • pvPlayerContext: A pointer to the player context value which may be set to NULL
  • dwFlags: An optional flag

For more information about the parameters, see IDirectPlay8Server::Host.

The following excerpt from the tutorial sample illustrates how to begin hosting a DirectPlay server session.

    WCHAR                   strHost[128] = {0};
    DPN_APPLICATION_DESC    dpAppDesc;

    // Get the session name from dialog
    if( IDOK != DialogBox( g_hInst, MAKEINTRESOURCE(IDD_HOST), g_hDlg, HostDlgProc ) )
        return S_OK;

    DXUtil_ConvertGenericStringToWideCch( strHost, g_strSession, 128 );

    // Set up the Application Description.
    ZeroMemory(&dpAppDesc, sizeof(DPN_APPLICATION_DESC));
    dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC);
    dpAppDesc.dwFlags = DPNSESSION_CLIENT_SERVER;   // Flag describing the app
    dpAppDesc.guidApplication = g_guidApp;          // GUID for the app
    dpAppDesc.pwszSessionName = strHost;         // Session name

    // Host the application.
        hr = g_pDPServer->Host(&dpAppDesc,       // pdnAppDesc
                          &g_pDeviceAddress, 1,  // prgpDeviceInfo, cDeviceInfo
                          NULL, NULL,            // pdpSecurity, pdpCredentials
                          NULL,                  // pvPlayerContext
                          0);                    // dwFlags

Setting Up a Client

The client application is responsible for handling the user interface (UI) and processing messages from the server. The following topics in this section describe the tasks needed to create a DirectPlay client application. Each task is described in detail below.

  1. Create a DirectPlay Client Object
  2. Create the Client Address Object
  3. Create the Server Address Object
  4. Enumerate the Hosts
  5. Connect to a Host

Create a DirectPlay Client Object

Setting up a client object is similar to Creating a DirectPlay Peer Object. The only difference between setting up a client object and a peer object is that when you call CoCreateInstance, instead of passing the equivalent peer parameters, you pass the class identifier of a client object (CLSID_DirectPlay8Client), the identifier of the interface (IID_IDirectPlay8Client), and the address of a pointer to an IDirectPlay8Client interface. After you create the DirectPlay client object, you can initialize it by calling IDirectPlay8Client::Initialize.

The following excerpt from the tutorial sample illustrates how to create and initialize a DirectPlay client object.

    // Create the IDirectPlay8Client object.
    hr = CoCreateInstance(CLSID_DirectPlay8Client, NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDirectPlay8Client,
                          (LPVOID*) &g_pDPClient);

    // Initialize IDirectPlay8Client object.
    hr = g_pDPClient->Initialize(NULL, DirectPlayMessageHandlerClient, 0);

In the initialization, you pass the pointer to a callback function, DirectPlayMessageHandlerClient, which handles messages the client receives. In this sample, the pvUserContext parameter is set to NULL. However, if you use the same message handler function for multiple interfaces, you should specify a value for pvUserContext. For more information, see Using Player Context Values.

Create the Client Device Address Object

For the client to connect to the server, you must specify the client's device address. Do this by creating an IDirectPlay8Address object and calling the IDirectPlay8Address::SetSP method. This step is identical to the step Creating an Address Object in Tutorial 2: Hosting a Session.

Create the Server Address Object

For the client to connect to the server, you must also create an IDirectPlay8Address object for the address of the server. This step is identical to the step Creating an Address Object in Tutorial 2: Hosting a Session.

Enumerate Hosts

If you don't know the address of the server to which you want to connect, you can enumerate all of the available servers. Follow the steps in Tutorial 3: Enumerating Hosted Sessions and replace all instances of the pointer to an IDirectPlay8Peer interface with the pointer to an IDirectPlay8Client interface.

Connect to a Server

To connect to a DirectPlay client/server session, follow the same process you use to connect to a peer-to-peer session except that the IDirectPlay8Client::Connect method does not take the pvPlayerContext parameter. Therefore, the call to IDirectPlay8Client::Connect is as follows:

        hr = g_pDPClient->Connect(&dpnAppDesc,       // pdnAppDesc
                                  pHostAddress,      // pHostAddr
                                  g_pDeviceAddress,  // pDeviceInfo
                                  NULL,              // pdnSecurity
                                  NULL,              // pdnCredentials
                                  NULL, 0,           // pvUserConnectData, Size
                                  NULL,              // pvAsyncContext
                                  NULL,              // pvAsyncHandle
                                  DPNCONNECT_SYNC);  // dwFlags

For more information, see Tutorial 4: Connecting to a Session.

Server Messages

After the server is hosting and a client is connected, the client and server can send messages to each other. If more than one client is connected, the server can send messages to a single player, a group of players, or all the players.

Sending Messages from the Server to Clients

The server can send a message to clients using the IDirectPlay8Server::SendTo method. The following excerpt from the client/server tutorial sample illustrates how to call the IDirectPlay8Server::SendTo method.

            hr = g_pDPServer->SendTo(DPNID_ALL_PLAYERS_GROUP, // dpnid
                                    &dpnBuffer,               // pBufferDesc
                                    1,                        // cBufferDesc
                                    0,                        // dwTimeOut
                                    NULL,                     // pvAsyncContext
                                    NULL,                     // pvAsyncHandle
                                    DPNSEND_SYNC |            // dwFlags
                                    DPNSEND_NOLOOPBACK);

Setting the dpnid parameter to DPNID_ALL_PLAYERS_GROUP sends the message to all players connected to the session. To specify a specific player or group, set dpnid to the specific player ID or group ID. The dpnBuffer is a pointer to the DPN_BUFFER_DESC structure that contains the data to send. For a description of the message flags and the other parameters, see IDirectPlay8Server::SendTo.

Receiving Messages from Clients

Messages received from the clients are processed by the DirectPlayMessageHandlerServer function. The message handler function will typically take the following form.

HRESULT WINAPI DirectPlayMessageHandlerServer(PVOID pvUserContext, DWORD dwMessageId, PVOID pMsgBuffer)
{
    switch (dwMessageId)
    {
        case DPN_MSGID_RECEIVE:
        {
            PDPNMSG_RECEIVE     pMsg;
            pMsg = (PDPNMSG_RECEIVE) pMsgBuffer;
             //process data
            break;
        }
       .
       .
       .
       //Other cases
    }

    return hr;
}

When a message is received, DirectPlay generates a DPN_MSGID_RECEIVE message. The DirectPlayMessageHandlerServer function tells your application what to do with the data it received. In this example, the text in the message data buffer displays on the player's screen.

For other messages that you might want to include, see Handling Client/Server Messages.

Client Messages

A client can send messages to and receive messages from only the server. If a client wants to send a message to another client, the message must first be sent to the server. The server application can implement a method to forward the message to other clients.

Sending Messages to the Server

A client can send a message to the server using the IDirectPlay8Client::Send method. The following example from the client/server tutorial sample illustrates how to call the IDirectPlay8Client::Send method.

             hr = g_pDPClient->Send(&dpnBuffer,             // pBufferDesc
                                    1,                      // cBufferDesc
                                    0,                      // dwTimeOut
                                    NULL,                   // pvAsyncContext
                                    NULL,                   // pvAsyncHandle
                                    DPNSEND_SYNC|
                                    DPNSEND_NOLOOPBACK);    // dwFlags

The pBufferDesc parameter is a pointer to a DPN_BUFFER_DESC structure that tells the application what data to send. The dwTimeOut parameter is set to 0, which means that the message waits in the queue until it is either sent or the connection ends. You can set dwTimeOut to a value so that the message is not sent unless it is sent within the specified number of milliseconds. For a description of the message flags and the other parameters, see IDirectPlay8Client::Send.

Receiving Messages from the Server

Messages received from the server are processed by the DirectPlayMessageHandlerClient function. The client message handler function takes the same form as the DirectPlayMessageHandlerServer function. For more information, see the example of a message handler function in the Receiving Messages from Clients section of Server Messages.

Terminating a Client/Server Session

If a DirectPlay client or server object was successfully initialized, you should close the object by calling IDirectPlay8Client::Close or IDirectPlay8Server::Close, and then release all active objects and terminate the application. For further discussion on closing and releasing DirectPlay objects, see Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers. When a client closes the session, the server receives the DPN_MSGID_DESTROY_PLAYER message but the game will continue if other players are connected. When the server closes the session, the clients receive the DPN_MSGID_TERMINATE_SESSION message and the session ends. For more information about handling these messages, see Handling Client/Server Messages.

© 2002 Microsoft Corporation. All rights reserved.


Tutorial 10: DirectPlay Thread Pool

This tutorial shows how to use the IDirectPlay8ThreadPool interface and avoid multithreading by taking advantage of the IDirectPlay8ThreadPool::DoWork method.

Some Microsoft® DirectPlay® games choose to use DirectPlay's internal worker threads to send and receive messages. These games must implement synchronization mechanisms to avoid data corruption and deadlocking.

Because multithreading is a complex issue, DirectPlay has implemented the IDirectPlay8ThreadPool interface to help users managed their threads. One advantage to using the IDirectPlay8ThreadPool interface is that you can use the IDirectPlay8ThreadPool::SetThreadCount method to disable all of DirectPlay's internal threads. All you need to do is call the IDirectPlay8ThreadPool::DoWork method regularly in your game loop and DirectPlay will perform networking tasks only during the time specified and only on the calling thread.

This tutorial uses a peer-to-peer, lobbied application, so you should review the following tutorials before beginning this one.

  • Tutorial 1: Creating a DirectPlay Object and Enumerating Service Providers
  • Tutorial 2: Hosting a Session
  • Tutorial 3: Enumerating Hosted Sessions
  • Tutorial 4: Connecting to a Session
  • Tutorial 5: Sending Messages to Other Peers
  • Tutorial 6: Handling Host Migration
  • Tutorial 7: Creating a Lobbyable Application

The complete sample code for this tutorial is included with the Microsoft DirectX® software development kit (SDK) and can be found at (SDK root)\Samples\C++\DirectPlay\Tutorials\Tut10_ThreadPool.

This article contains the following sections.

  • User's Guide
  • Creating a DirectPlay ThreadPool Object
  • Setting the Thread Count
  • Working in DoWork Mode
  • Terminating the Application
Note The error handling code for the examples in this document has been deleted for clarity. See the tutorial sample for a complete version of the code.

User's Guide

When you run this tutorial sample, a window opens and you have the choice to either Host or Connect.

If you choose Host:

  1. A window will open and you should enter a session name. Select the Migrate Host box to allow host migration to take place in this session. Then click OK. Your session status will change to 'Hosting Session "YourSessionName".'
  2. You can now draw pictures in Shared Canvas. Select a color by clicking on one of the color boxes and then hold the mouse down while you move it inside the canvas window to draw. To disconnect, click Disconnect and the session ends.
  3. Click Exit to end the sample

If you choose Connect:

  1. The Connect to Session window will open and you should enter an Internet Protocol (IP) address and click Search. If any sessions are found at that address, they will be listed in the Detected Sessions box. Select a session and click Connect. If the address does not exist, a message box opens with an error message.
  2. Once connected, your session status will change to 'Connected to Session "YourSessionName". You can now draw pictures in Shared Canvas. Select a color by clicking on one of the color boxes and then hold the mouse down while you move it inside the canvas window to draw. To disconnect, click Disconnect.
  3. Click Exit to end the sample.

You can run this sample twice—once to host a session and once to connect. When connecting, enter your computer's IP address. Once connected, you can draw pictures on the canvas shared between the host and the client application. To test host migration, close the host application. The client application's session status will change to 'Hosting Session "YourSessionName".'.

Creating a DirectPlay ThreadPool Object

The first step in using the DirectPlay thread pool is to create and initialize an IDirectPlay8ThreadPool object. The IDirectPlay8ThreadPool object must be initialized before any other DirectPlay object or DirectPlay will create its own IDirectPlay8ThreadPool object when IDirectPlay8Peer is initialized. There can be only one IDirectPlay8ThreadPool object per process so if DirectPlay has created its own IDirectPlay8ThreadPool object then a subsequent call to IDirectPlay8ThreadPool::Initialize will return DPNERR_ALREADYINITIALIZED.

To create an IDirectPlay8ThreadPool object, call CoCreateInstance World Wide Web link passing the class identifier (CLSID_DirectPlay8ThreadPool), the identifier of the interface (IID_IDirectPlay8ThreadPool), and the address of a pointer to an IDirectPlay8ThreadPool object. The following snippet from the tutorial sample shows how to create and initialize an IDirectPlay8ThreadPool object.

IDirectPlay8ThreadPool* g_pThreadPool;
.
.
.
// Create the IDirectPlay8ThreadPool interface
   hr = CoCreateInstance( CLSID_DirectPlay8ThreadPool, NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDirectPlay8ThreadPool,
                          (LPVOID*) &g_pThreadPool );

// Initialize ThreadPool
   hr = g_pThreadPool->Initialize(NULL, DirectPlayMessageHandler, 0 );

Setting the Thread Count

After initializing your DirectPlay objects, you should you call IDirectPlay8ThreadPool::SetThreadCount and set the thread count to zero. It is recommended that you do this before making any networking calls.

The following snippet from the tutorial sample shows how to set the thread count to zero.

// Turn off worker DirectPlay worker threads because you'll be using the
//   DoWork method to synchronously handle network messages.
hr = g_pThreadPool->SetThreadCount( (DWORD) -1, 0, 0 );
// dwProcessorNum, dwNumThreads, dwFlags

The dwProcessorNum parameter is set to -1 to change the thread count for all processors.

Working in DoWork Mode

After you set the thread count to zero, you must call IDirectPlay8ThreadPool::DoWork to perform any DirectPlay tasks. When you call IDirectPlay8ThreadPool::DoWork, you specify the amount of time that the application should spend on DirectPlay tasks. DirectPlay will handle starting and closing threads to perform various tasks such as receiving messages. If DirectPlay finishes all the networking tasks before the specified time, the method will return early. If there are any tasks left when the time runs out, IDirectPlay8ThreadPool::DoWork will return DPNSUCCESS_PENDING.

The correct way to use IDirectPlay8ThreadPool::DoWork is to call it within the game loop. IDirectPlay8ThreadPool::DoWork will block the application until it returns, so you should limit the time your program spends on DirectPlay tasks.

The following snippet from the tutorial sample shows how to use IDirectPlay8ThreadPool::DoWork.

// Handle incoming network data
// Here you're setting the allowed timeslice at 100 milliseconds.
// The program will block while DoWork handles network communication
//   so you don't need to worry about thread synchronization issues as
//   you have on earlier tutorials.
g_pThreadPool->DoWork( 100, 0 );  // dwAllowedTimeSlice, dwFlags

Terminating the Application

If an IDirectPlay8ThreadPool object was successfully initialized, you should call IDirectPlay8ThreadPool::Close before terminating the application. You should call IDirectPlay8ThreadPool::Close after terminating other DirectPlay objects. Before IDirectPlay8ThreadPool::Close returns, all existing DirectPlay threads will terminate and you will receive a DPN_MSGID_DESTROY_THREAD message for each thread.

The following snippet from the tutorial sample shows how to use IDirectPlay8ThreadPool::Close.

if( g_pThreadPool )
       g_pThreadPool->Close(0);

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay C++ Samples

The following sample applications demonstrate the use and capabilities of the Microsoft® DirectPlay® application programming interface for the C++ programming language. Refer to the Readme.txt file in each sample folder for details. All sample folders can be found under the SDK root directory, typically C:\mssdk.

Samples

  • AddressOverride
  • ChatPeer
  • DataRelay
  • LobbyClient
  • Maze
  • NATPeer
  • NATResolver
  • SimpleClientServer
  • SimplePeer
  • StagedPeer
  • Throttle
  • VoiceClientServer
  • VoiceConnect
  • VoiceGroup
  • VoicePosition

© 2002 Microsoft Corporation. All rights reserved.


AddressOverride

AddressOverride demonstrates how to programmatically provide an address to Microsoft® DirectPlay® in order to host or connect to another session on the network. The alternative is to have DirectPlay display a standard dialog box to ask the user the connection settings. Most games will set addresses directly so that they can provide their own user interface.

Path

Source: (SDK root)\Samples\C++\DirectPlay\AddressOverride

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

The AddressOverride sample displays a dialog box that allows you to select address parameters. To use the dialog box:

  1. Enter the player's name and session.
  2. If you want to be a session host, select the Host Session check box.
  3. Choose a service provider from the Service Provider list.
  4. Choose an adapter from the Adapter list.
  5. The remaining steps depend on which service provider you choose.
    • If you choose the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider:
      • To join a session, select a particular host by entering its Internet Protocol (IP) address and port in the associated edit boxes. You can also have DirectPlay search the local network for available hosts by leaving the IP address and Port boxes blank.
      • To host a session, you can specify a port. If you leave the Port box blank, DirectPlay will select a port for you.
    • If you choose the model service provider, enter the phone number.
    • If you choose the Internetwork Packet Exchange (IPX) service provider, enter the port.
    • If you choose the serial service provider, the sample will launch the default DirectPlay dialog box that queries the user for serial settings.

Once you have finished filling in the Address Override dialog box, click OK to start or join a game. This game is similar to SimplePeer. See the SimplePeer user's guide for more details.

Programming Notes

The AddressOverride sample is very similar to the SimplePeer sample. See the Programming Notes section of the SimplePeer sample for details. AddressOverride differs by programmatically specifying an address, rather than having DirectPlay display the default address selection dialog box.

The following list outlines how the AddressOverride sample works. When the OK button is pressed, the sample:

  1. Determines whether the user wants to host or join a session from the Host Session check box.
  2. Determines the service provider from the Service Provider list, and selects the appropriate globally unique identifier (GUID).
  3. Creates an IDirectPlay8Address object called pDeviceAddress.
  4. Calls that object's IDirectPlay8Address::SetSP method to specify the service provider.
  5. If the user is hosting a session, creates an IDirectPlay8Address object called pHostAddress. It then calls that object's IDirectPlay8Address::SetSP method to specify the service provider.
  6. If an adapter was specified, the sample calls the pDeviceAddress object's IDirectPlay8Address::SetDevice to specify the adapter.

The sample then calls IDirectPlay8Address::AddComponent to complete the initialization of the address objects. The details depend on which service provider was selected, and whether the user is joining or hosting a session.

  • If the TCP/IP service provider was selected and:
    • The user is hosting a session, the user can specify the port.
      • If a port was specified, set the pwszName parameter to DPNA_KEY_PORT and call the pDeviceAddress object's IDirectPlay8Address::AddComponent to add the user's port to the address.
    • The user is joining a session, the user can specify the host IP address and the port.
      • If a host IP address was specified, set the pwszName parameter to DPNA_KEY_HOSTNAME and call the pHostAddress object's IDirectPlay8Address::AddComponent to add the host's IP address to the address object.
      • If a port was specified, set the pwszName parameter to DPNA_KEY_PORT and call the pHostAddress object's IDirectPlay8Address::AddComponent method to add the host's port to the address.
  • If the IPX service provider was selected and:
    • The user is hosting a session, the user must specify a port. Set the pwszName parameter to DPNA_KEY_PORT and call the pDeviceAddress object's IDirectPlay8Address::AddComponent method to add the users port to the address.
    • The user is joining a session, the user must specify a port. Set the pwszName parameter to DPNA_KEY_PORT and call the pHostAddress object's IDirectPlay8Address::AddComponent method to add the users port to the address.
  • If the modem service provider was selected and the user is joining a session, the user must specify a phone number. Set the pwszName parameter to DPNA_KEY_PHONENUMBER and call the pHostAddress object's IDirectPlay8Address::AddComponent method to add the phone number to the address.

Use the device and host address objects to connect to the session, much like the SimplePeer sample.

© 2002 Microsoft Corporation. All rights reserved.


ChatPeer

The ChatPeer sample is similar in form to SimplePeer. When a player hosts or connects to a session, the players can chat with each other by passing text strings.

Path

Source: (SDK root)\Samples\C++\DirectPlay\ChatPeer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Enter the player's name and choose a connection type. You can choose "Wait for Lobby Connection" or choose a service provider. Use the Multiplayer Games dialog box to either search for an active game to join or to start a new game. When you join or start a game, you can begin immediately. Other players can join the game at any time. If host migration is on, the host player can also leave at any time, because Microsoft® DirectPlay® will automatically migrate the host session to another player.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

The ChatPeer sample is very similar in form to the SimplePeer sample. The ChatPeer differs by letting clients send text string to all players connected to the session. For detailed programming notes, see the Programming Notes section of the SimplePeer sample.

When Send is pressed, the SendChatMessage function does the following:

  1. Retrieves the text string from the dialog box.
  2. Fills an application-defined structure, GAMEMSG_CHAT. This structure has a message type identifier (ID) as the first BYTE. This lets the application figure out what type of application message was received. However, ChatPeer uses only one application-defined message. See StagedPeer for a more complex example of this process.
  3. Fills out a DPN_BUFFER_DESC structure using the GAMEMSG_CHAT buffer.
  4. Calls IDirectPlay8Peer::SendTo with the DPN_BUFFER_DESC. It passes the DPNID_ALL_PLAYERS_GROUP flag, so this message goes to everyone.

© 2002 Microsoft Corporation. All rights reserved.


DataRelay

The DataRelay sample is similar to SimplePeer but differs by sending a packet of data with options specified in the dialog box's user interface (UI).

Path

Source: (SDK root)\Samples\C++\DirectPlay\DataRelay

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Host or connect to a session in the same manner as explained in SimplePeer. When the main dialog box appears, select the target, size, rate, and timeout values. Then click Push to Send. This will send a packet of data to the target—at the rate specified—with the specified size. Using the Connection Info drop-down menu, specify a target on which you would like to periodically gather connection information.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have Microsoft® DirectPlay® perform a search for the address, select the use DPNSVR check box.

Programming Notes

The DataRelay sample is very similar in form to the SimplePeer sample. For detailed programming notes, see the Programming Notes section of the SimplePeer sample.

When the Push to Send button is clicked, a timer is created that goes off every number of milliseconds, as indicated by the UI.

When the timer goes off, the callback function calls the SendNetworkData function to do the following tasks.

  1. Create an application-defined structure.
  2. Create a GAMEMSG_DATA_NODE, which is handed off to the application worker thread. That thread processes the node and then updates the UI to show that a packet was sent.
  3. A DPN_BUFFER_DESC structure is filled out, passing in a pointer to the application-defined structure created above.
  4. The IDirectPlay8Peer::SendTo method is called, passing in the DPN_BUFFER_DESC structure.
  5. The event g_hDPDataAvailEvent is set, telling the worker thread that there is data ready to be processed.

On receipt of the g_hDPDataAvailEvent event, the ProcessNetDataProc function calls the ProcessData function, which does the following:

  1. Enters the critical section, g_csDataList.
  2. Runs through the linked list, processing each node.
  3. Calls IDirectPlay8Peer::ReturnBuffer so that DirectPlay can free buffer space that it passed in DPN_MSGID_RECEIVE.

The DirectPlayMessageHandler function handles different kinds of messages, such as DPN_MSGID_RECEIVE and DPN_MSGID_SEND_COMPLETE.

© 2002 Microsoft Corporation. All rights reserved.


LobbyClient

LobbyClient is a simple lobby client application. It displays all registered Microsoft® DirectPlay® applications on the local system. It enables the user to launch one or more of these applications using a chosen service provider. A launched lobbied application can be told to either join or host a game.

Path

Source: (SDK root)\Samples\C++\DirectPlay\LobbyClient

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

The LobbyClient sample displays a dialog box that allows you to choose launch parameters before starting the application by clicking Launch App. The Active Connections list will display the handle to all current lobbied applications. Clicking Send Message will send a lobby message to the lobbied application. This is done mainly for demonstration purposes. In a more complex lobby client, you might want to use this functionality in a more meaningful way by passing a message to which the lobbied application responds.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

The InitDirectPlay function does the following:

  1. Initializes Component Object Model (COM) with CoInitialize.
  2. Creates an IDirectPlay8Peer object with CoCreateInstance.
  3. Calls IDirectPlay8Peer::Initialize to tell the interface about our message handler.
  4. Creates an IDirectPlay8LobbyClient object with CoCreateInstance.
  5. Calls IDirectPlay8LobbyClient::Initialize to tell the interface about our lobby message handler.

The OnInitDialog function does the following:

  1. Enumerates the registered lobbied applications and display them in the list box. See EnumRegisteredApplications.
  2. Enumerates the DirectPlay service providers and display them in the list box. See EnumServiceProviders.
  3. Whenever a new service provider is selected (and upon initialization), enumerates the service provider's adapters. See EnumAdapters.

When Launch App is clicked, the LaunchApp function does the following:

  1. Fills out a DPL_CONNECT_INFO structure. This is complex because it contains the host and device addresses as well as the DPN_APPLICATION_DESC. See LaunchApp and AllocAndInitConnectSettings.
  2. Calls IDirectPlay8LobbyClient::ConnectApplication passing in the DPL_CONNECT_INFO structure.
  3. Frees the DPL_CONNECT_INFO structure. This is complex because this structure has a number of DirectPlay addresses. See FreeConnectSettings.

The DirectPlayLobbyMessageHandler function can handle the following messages.

DPL_MSGID_DISCONNECT | The lobbied application was disconnected. The pDisconnectMsg–>hDisconnectId parameter will contain the handle of the lobbied application that was disconnected and the pDisconnectMsg–>hrReason parameter will contain the reason. This sample pops up a message box.
DPL_MSGID_RECEIVE | The lobbied application sent the client data. This sample does not respond to any message.
DPL_MSGID_SESSION_STATUS | A lobbied application has changed its status. The pStatusMsg–>hSender parameter will be one of several predefined status codes. This sample updates the user interface (UI), showing that the lobby status has been updated. However, more complex lobby clients might take action.
DPL_MSGID_CONNECTION_SETTINGS | A lobbied application has changed its connection settings. This lobby client takes no action. However, more complex clients might take action.

When Send Message is clicked, the SendMsgToApp function calls IDirectPlay8LobbyClient::Send. The hConnection parameter is set to the handle of the receiving lobbied application and the pBuffer parameter is set to the message buffer.

When Disconnect is clicked, the DisconnectFromApp function calls IDirectPlay8LobbyClient::ReleaseApplication. The hApplication parameter is set to the handle of the lobbied application from which to disconnect.

© 2002 Microsoft Corporation. All rights reserved.


Maze

The maze sample is a Microsoft® DirectPlay® client/server application. There are two different client applications—a console-based version and a Microsoft Direct3D® client. The Direct3D client can optionally be run as screen saver by copying Mazeclient.exe to your \winnt\system32\ folder and renaming it Mazeclient.scr. Doing so will make it a screen saver that can be detected by the display control panel application.

Path

Path: (SDK root)\Samples\C++\DirectPlay\Maze

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

There are three executable maze samples—MazeClient, MazeConsoleClient, and MazeServer. MazeClient is a self-contained executable file but MazeServer and MazeConsoleClient must be run together. Instructions for running each sample are described below.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

MazeClient

You can run MazeClient in three ways:

  • Start MazeClient from the Bin folder by double-clicking the MazeClient icon. This runs the sample in settings mode. When you click the icon, a dialog box appears. Choose the setting you want and click Launch. This starts the maze sample. To quit the sample, press any key or click the mouse.

  • To run MazeClient in test mode, at the command prompt type:

    mazeclient.exe /t

    In test mode, you can search and join a server game or you can choose to not connect to a server. There are few simple commands you can type when running mazeclient in test mode:

    • a will turn autopilot on or off, but when moving about. There is no collision detection code, so you can go through walls.
    • r will turn reflections on or off.

  • To run MazeClient in screen saver mode, at the command prompt type the following:

    mazeclient.exe /s

    This mode will autoconnect to a server using the settings from settings mode. If a server is not found, it will run without connecting to a server. It will also exit upon mouse or keyboard input.

MazeConsoleClient

Start MazeConsoleClient by double-clicking the MazeConsoleClient icon in the Bin folder or by typing at the command prompt:

MazeConsoleClient.exe

MazeConsoleClient should automatically search for a session on the local network. If it does not, at the command prompt type:

setup

When asked if you want to connect to a local server, type:

Yes

If you are already running MazeServer, MazeConsoleClient will automatically connect and start. To search for a session at a specific Internet Protocol (IP) address, type it at the command prompt, for example,

MazeConsoleClient 255.255.255.255

If a server is not found or the session is lost, it will exit automatically. Press CTRL+C to close the session.

MazeServer

Start MazeServer by double-clicking the MazeServer icon in the Bin folder or typing at the command prompt:

mazeserver.exe

MazeServer will automatically create a host session that clients can join. MazeServer.exe takes an optional command prompt parameter to set the size of the maze. For example, to set the maze to 16 wide and 128 high, type:

mazeserver.exe /size 16 128

The width and height are restricted to these numbers: 16, 32, 64, or 128.

Once started, the server will display a simple command prompt to control the server. Here is the list of commands.

help | Lists simple commands you can use.
stop | Shuts down the server.
stats | Displays how many players are connected.
sr or serverreliable | Set what percentage of the packets going from the server to the client have the DPNSEND_GUARANTEED flag.
cr or clientreliable | Set what percentage of the packets going from every client to the server have the DPNSEND_GUARANTEED flag.
cu or clientupdate | Set how many milliseconds pass between updates from each client.
ct or clienttimeout | Sets the timeout value of packets sent by the clients.
st or servertimeout | Sets the timeout value of packets sent by the server.
ci or connectioninfo | Displays information about the connection from the server to a client. For example, ci 00300003.
loglevel | Set how much extra information it provides about what is happening behind the scenes.

© 2002 Microsoft Corporation. All rights reserved.


NatPeer

The NATPeer sample allows the user behind a Network Address Translation (NAT) device to specify the address and optional password of an IDirectPlay8NATResolver server to be used for address resolution during calls to Host, EnumHosts, and Connect. For more information about NATs, see Network Address Translation, Firewalls, and Proxies.

Path

Source: (SDK root)\Samples\C++\DirectPlay\NatPeer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

When you start the program, a dialog box is displayed where you can specify connection information, including an option to enable NAT address resolution. If NAT address resolution is enabled, the Server Address and Password are used by Microsoft® DirectPlay® for resolving the external addresses of players behind NATs which are not Universal Plug and Play (UPnP) compatible. If the user chooses not to be the session host, a second dialog is displayed that allows users to find and connect to active sessions.

Once in a session, the game play is similar to SimplePeer.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

If the NAT address resolution option is checked, the Server Address and Password fields are added as components of the local device address under the DPNA_KEY_NAT_RESOLVER and DPNA_KEY_NAT_RESOLVER_USER_STRING keys.

You can also specify multiple comma-delimited servers in the DPNA_KEY_NAT_RESOLVER component. Each server is tried simultaneously for speed, and the first response is used. If no server responds, the Host, Connect, or EnumHosts call still succeeds, but only local and UPnP connectivity information is used.

Because hosting these resolving servers require resources, you might want to prevent arbitrary players from using the server. This can be achieved with the DPNA_KEY_NAT_RESOLVER_USER_STRING address component. This value is passed directly to the resolving server for verification. The server can choose to respond as appropriate. Note that the user string is passed in clear text over the network, so if the text could contain sensitive information, you should encrypt it before sending.

For an implementation of an IDirectPlay8NATResolver server and more information about NAT address resolution, check the NATResolver sample included with the software development kit (SDK).

© 2002 Microsoft Corporation. All rights reserved.


NATResolver

The NATResolver sample shows how the IDirectPlay8NATResolver interface can be used to implement address resolution for players behind Network Address Translation (NAT) devices. This interface acts as a simple server, which accepts queries and reflects the perceived address back to the caller.

Path

Source: (SDK root)\Samples\C++\DirectPlay\NATResolver

Executable: (SDK root)\Samples\C++\DirectPlay\NATResolver

User's Guide

When the sample starts, an IDirectPlay8NATResolver object is created that waits for queries. The sample always listens on all available IPv4 devices for incoming queries. If Require password is checked, queries are first screened for the plain text password before allowing Microsoft® DirectPlay® to return the resolved address.

The dialog displays the list of addresses currently in use, as well as the number of incoming queries and outgoing responses.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

DirectPlay handles most of the address resolution work, interrupting only to check that incoming queries are from authorized clients. The IDirectPlay8NATResolver::Initialize method sets up the message callback for client authorization, and the IDirectPlay8NATResolver::Start method starts the server on the requested device.

DirectPlay informs your program about client queries with DPN_MSGID_NAT_RESOLVER_QUERY messages, which contain the client address and given password. A successful return value from this callback instructs DirectPlay to handle the address resolution. A failed return value cancels the resolution but continues executing the associated DirectPlay call. Using the password allows you to deny access to your resolution server for clients who are not part of your game.

© 2002 Microsoft Corporation. All rights reserved.


SimpleClientServer

The SimpleClientServer sample is a simple client/server application. It is similar in form to SimplePeer but uses the client/server interfaces. When the user presses Wave to other players, the game passes a single Microsoft® DirectPlay® message to all connected players.

Path

Path: (SDK root)\Samples\C++\DirectPlay\SimpleClientServer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

To run the game, do the following:

  1. Start the SimpleServer by double-clicking the SimpleServer icon in the Bin folder.
  2. Change the port if desired, and click Start Server.
  3. Start the SimpleClient by double-clicking the SimpleClient icon in the Bin folder.
  4. Enter the player's name.
  5. Type the Internet Protocol (IP) address, or leave it blank to search the local network.
  6. Click Start Search.
  7. Click Join when a session appears.

The game begins immediately after it has been created. Other players can join the game at any time.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

© 2002 Microsoft Corporation. All rights reserved.


SimplePeer

The SimplePeer sample illustrates how to implement a simple peer-to-peer application. After joining or creating a session, the game begins immediately. Other players can join the session at any time.

Path

Source: (SDK root)\Samples\C++\DirectPlay\SimplePeer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Enter the player's name and choose a connection type. You can choose Wait for lobby connection or choose a service provider. Use the Multiplayer Games dialog box to search for an active game to join or to start a new game. After the game has been joined or created, the game begins immediately. Other players can join the game at any time. If Host Migration is on, the host player can leave at any time because Microsoft® DirectPlay® will automatically migrate the host session to another player.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

The InitDirectPlay function does the following:

  1. Initializes the Component Object Model (COM) with CoInitialize.
  2. Creates an IDirectPlay8Peer object with CoCreateInstance.
  3. Creates an IDirectPlay8LobbiedApplication object with CoCreateInstance.
  4. Calls IDirectPlay8Peer::Initialize and passes its message handler.
  5. Calls IDirectPlay8LobbiedApplication::Initialize and passes its message handler.
  6. Checks the return value of the IDirectPlay8LobbiedApplication::Initialize method. If it is successful, the application is launched by a lobby client.

If the application is lobby launched, the connection settings can be obtained from the lobby client by the ConnectUsingLobbySetting function of the CNetConnectWizard. The CNetConnectWizard class is a helper class. It uses dialog boxes to query the user for information. The ConnectUsingLobbySettings function does the following:

  1. Calls IDirectPlay8LobbiedApplication::GetConnectionSettings to get the connection setting from the client.
  2. Checks the dwFlags member of the DPL_CONNECTION_SETTINGS structure for the DPLCONNECTIONSETTINGS_HOST flag to see if it should host.
  3. Calls IDirectPlay8Peer::SetPeerInfo.
  4. Calls IDirectPlay8Peer::Host if hosting, otherwise IDirectPlay8Peer::Connect.
  5. Releases the objects in DPL_CONNECTION_SETTINGS.

If the connection setting from the lobby client is not provided, the application calls the DoConnectWizard function of the CNetConnectWizard. DoConnectWizard does the following:

  1. Calls IDirectPlay8Peer::EnumServiceProviders to enumerate service providers.
  2. Calls the ConnectionDlgOnOk function, which displays a dialog box where the user can either choose a service provider or choose to use a lobby connection. If Wait for lobby connection is chosen, the function calls IDirectPlay8LobbiedApplication::SetAppAvailable to tell the lobby client that the application is available for connection. If a service provider is selected, the function creates a DirectPlay host and device address objects by calling CoCreateInstance. Then it calls IDirectPlay8Address::SetSP to pass service provider's globally unique identifier (GUID) into the two DirectPlay address objects.
  3. Calls IDirectPlay8Peer::EnumHosts to enumerate all the games in progress on that service provider.
  4. Processes the DPN_MSGID_ENUM_HOSTS_RESPONSE that arrives in the callback function.

The wizard displays the list of the current sessions and allows users to choose a game from the list or create a new one. If Join is clicked, the SessionDlgJoinGame function calls IDirectPlay8Peer::SetPeerInfo to set the player name and IDirectPlay8Peer::Connect to connect to a game. If Create is clicked, the SessionDlgCreateGame function calls IDirectPlay8Peer::SetPeerInfo to set the player's name and IDirectPlay8Peer::Host to begin hosting a game. A DPN_APPLICATION_DESC structure filled with information such as the game name, max player, and the application GUID is passed in the call to Connect.

Once connected, if Wave to other players is clicked, the WaveToAllPlayers function calls IDirectPlay8Peer::SendTo with the dpnid parameter set to DPNID_ALL_PLAYERS_GROUP and the pBufferDesc parameter pointing to a DWORD containing GAME_MSGID_WAVE.

When you click Exit, all the interfaces are cleaned up.

© 2002 Microsoft Corporation. All rights reserved.


StagedPeer

The StagedPeer sample connects players together with dialog boxes that allow players to chat and to start a new game at the same time. The host can start the game when all the players have joined and everyone is ready. The host player can also reject players or close player slots. The game is identical to the SimplePeer game.

When the game starts, players can press the Wave to other players button, which sends a simple Microsoft® DirectPlay® message to all other players.

Path

Path: (SDK root)\Samples\C++\DirectPlay\StagedPeer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

Programming Notes

The StagedPeer sample is similar in form to the SimplePeer sample. StagedPeer differs only by displaying a multiplayer stage using a dialog box. See Netstage.cpp and Netstage.h for details. For more information, see the Programming Notes section of the SimplePeer sample.

© 2002 Microsoft Corporation. All rights reserved.


Throttle

The Throttle sample demonstrates how to monitor the send queue and scale the rate of network communications.

Path

Source: (SDK root)\Samples\C++\DirectPlay\Throttle

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Start the Throttle Server by double-clicking on the ThrottleServer.exe in the Bin folder. Wait for a moment while it connects to the network. When the server is ready to accept connection, the dialog user interface (UI) will appear. While the server is running, you can adjust the Server Load slider to simulate the processing load on the server. The higher the load setting, the slower the server will handle incoming messages.

After the server is running, launch the Throttle Client by double-clicking on the ThrottleClient.exe in the bin folder. The client will prompt for the host name or Internet Protocol (IP) address where the server is running. The port number is fixed. When the client is connected to the server, the server will indicate the added connection and show the amount of received data.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have Microsoft® DirectPlay® perform a search for the address, select the use DPNSVR check box.

You can adjust the Send Interval slider on the Client window to set the delay between successive calls to IDirectPlay8Client::Send. With the default settings, the server's receive buffer will quickly fill to capacity, and outgoing messages will fill the client's send queue. When the Regulate Outgoing Rate box is checked, the program will attempt to scale the number of outgoing messages to keep the queue size below the Max Queue Size set by the slider.

Note Adjustments to any of the client or server controls causes a corresponding change in the queue size and wait as reported in the Outgoing Data group box. Multiple clients can be connected simultaneously to model a typical multiplayer session.

Programming Notes

To understand why you might need to throttle outgoing data in your application, you need to understand the DirectPlay architecture and DirectPlay Service Providers.

DPN_SP_CAPS contains a list of capabilities and settings for service providers. This sample focuses on dwNumThreads, dwBuffersPerThread, and dwSystemBufferSize. During most Transmission Control Protocol/Internet Protocol (TCP/IP) sessions, DirectPlay immediately delivers messages to the receiver's system queue. The threads take messages from the system buffer and store them in their own message buffers until they can be received by the message handler.

When the thread buffers fill up and the system buffer fills up, DirectPlay won't allow any further messages to be delivered. Any messages destined for that target are then stored in the local send queue until enough space frees up on the remote computer.

You can adjust these parameters to suit your application, but increases in buffer size usually translate to increases in game lag. Therefore, it's best to leave these values for the service provider to decide and concentrate instead on Optimizing Network Usage.

Usually, the send queue is needed only for temporary spikes in network traffic. However, if a player continues to send messages faster than the target can receive them, the send queue will continue to grow. If no precautions are taken, any outgoing messages will take several seconds, possibly minutes, to make their way through all the queues. This will effectively end the game.

One easy way to combat this is to place a timeout value on outgoing messages. You can give critical messages a higher timeout value and a different priority. In extreme circumstances, you can still run into a problem where messages consistently time out before reaching the target. For the most flexibility, you should also monitor the send queue and adjust the rate of outgoing data accordingly.

This sample takes the simple approach of blocking a portion of outgoing data, based on the current send queue size. Because the application is responsible for blocking the data, it would be possible to store a running total of blocked data and send an averaged block of data the next time space allows. That way, critical data is never lost and minor update data can be screened or combined to ease the output rate.

© 2002 Microsoft Corporation. All rights reserved.


VoiceClientServer

The VoiceClientServer sample is a simple Microsoft® DirectPlay® voice-based client/server application.

Path

Source: (SDK root)\Samples\C++\DirectPlay\VoiceClientServer

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Refer to the User's Guide section of the SimpleClientServer sample for basic information about running client/server samples.

In addition to what SimpleClientServer does, the VoiceClientServer allows you to select the voice codec you want to use and to select either a forwarding server or a mixing server. For more information about these server types, see the Microsoft DirectX® documents.

The VoiceClient allows any client to alter the playback or capture settings by clicking Setup once the chat session has begun.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

© 2002 Microsoft Corporation. All rights reserved.


VoiceConnect

The VoiceConnect sample shows how to network with other players to start a Microsoft® DirectPlay® Voice chat session. After joining or creating a session, the players can use a microphone to talk to one other. Other players can join the session at any time.

Path

Source: (SDK root)\Samples\C++\DirectPlay\VoiceConnect

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

For information about how to connect, refer to the User's Guide section of the SimplePeer sample. After connecting, the host is presented with a dialog box asking which voice codec to use. Typical voice applications automatically select a voice codec, or present this to the user in some other fashion. Once the chat session begins, any client can alter the playback or capture settings by clicking Setup.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

Programming Notes

The VoiceConnect sample is very similar in form to the SimplePeer sample. The VoiceConnect differs by letting clients use DirectPlay Voice to talk to each other using a computer microphone. For detailed programming notes, see the Programming Notes section of the SimplePeer sample.

To create the voice functionality, the application must first initialize DirectPlay voice. This sample does this by calling CNetVoice::Init when the main dialog is initialized. CNetVoice::Init performs the following tasks.

  • Calls the VoiceSessionTestAudioSetup function to test the audio setup with DirectPlay Voice. VoiceSessionTestAudioSetup does the following:

    1. Creates an IDirectPlayVoiceTest object with CoCreateInstance.
    2. Calls IDirectPlayVoiceTest::CheckAudioSetup with the DVFLAGS_QUERYONLY flag set. This will return DVERR_RUNSETUP if the setup wizard needs to be run. To run the setup wizard, call IDirectPlayVoiceTest::CheckAudioSetup again without the DVFLAGS_QUERYONLY flag. If it returns successfully, then the VoiceConnect sample continues, otherwise the sample ends.
    3. Releases the IDirectPlayVoiceTest object.

  • Calls the VoiceSessionCreate function to create the audio setup with DirectPlay Voice if the player is hosting. VoiceSessionCreate does the following:
    1. Creates an IDirectPlayVoiceServer with CoCreateInstance.
    2. Calls IDirectPlayVoiceServer::Initialize to register the voice server message handler. The DirectPlay interface is also passed here.
    3. Fills out a DVSESSIONDESC structure with the session type and the desired voice codec.
    4. Calls IDirectPlayVoiceServer::StartSession passing in the DVSESSIONDESC structure.
  • If the player is either hosting or joining, the application calls the VoiceSessionConnect function, which uses the following steps to connect to the session.
    1. Create an IDirectPlayVoiceClient with CoCreateInstance.
    2. Call IDirectPlayVoiceClient::Initialize to register the voice client message handler. The DirectPlay interface is also passed here.
    3. Fill out a DVSOUNDDEVICECONFIG structure with the globally unique identifiers (GUIDs) for the Microsoft DirectShow® playback and capture devices.
    4. Fill out a DVCLIENTCONFIG structure. In this sample, this structure is filled out when with a dialog box. More complex applications might want to do this a different way. See the VoiceConfigDlgProc function in VoiceConnect.cpp.
    5. Call IDirectPlayVoiceClient::Connect passing the DVSOUNDDEVICECONFIG and DVCLIENTCONFIG structures.
    6. Call IDirectPlayVoiceClient::SetTransmitTargets to the desired default target. This sample sets the target value to DVID_ALLPLAYERS, which targets all players.
    7. Call IDirectPlayVoiceClient::GetSoundDeviceConfig. Check for the DVSOUNDCONFIG_HALFDUPLEX flag in the dwflags member of the DVSOUNDDEVICECONFIG structure returned to figure out if this client is in half-duplex mode. In half-duplex mode, the client cannot talk but can listen.

DirectPlayVoiceClientMessageHandler handles different DirectPlay messages such as:

  • DVMSGID_CREATEVOICEPLAYER
  • DVMSGID_DELETEVOICEPLAYER
  • DVMSGID_HOSTMIGRATED
  • DVMSGID_GAINFOCUS and DVMSGID_LOSTFOCUS
  • DVMSGID_RECORDSTART
  • DVMSGID_RECORDSTOP
  • DVMSGID_PLAYERVOICESTART
  • DVMSGID_PLAYERVOICESTOP

When Exit is clicked, the application needs to clean up DirectPlay Voice by calling CNetVoice::Free, which does the following:

  1. Disconnects the player from the voice session. The VoiceSessionDisconnect function calls IDirectPlayVoiceClient::Disconnect and releases the IDirectPlayVoiceClient object.
  2. Destroys the voice session if this player is the host. The VoiceSessionDestroy function calls IDirectPlayVoiceServer::StopSession and releases the IDirectPlayVoiceServer object

© 2002 Microsoft Corporation. All rights reserved.


VoiceGroup

The VoiceGroup sample shows how use Microsoft® DirectPlay® Voice to enable users to talk to a specific group of players.

Path

Source: (SDK root)\Samples\C++\DirectPlay\VoiceGroup

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Refer to the User's Guide section of the VoiceConnect sample for basic information about starting up the voice samples.

With VoiceGroup, you can click Cycle Group Assignment to change the local player's group assignment to 1, 2, 3, 4, or 5, or to unassigned. You can also click Cycle Target Assignment to change the local player's voice target assignment to 1, 2, 3, 4, or 5—to talk with only one of those groups, or to Everyone—to talk with everyone in the session.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

© 2002 Microsoft Corporation. All rights reserved.


VoicePosition

VoicePosition is similar in form to VoiceConnect. VoicePosition shows how use 3-D positioning with Microsoft® DirectPlay® Voice. It uses a simple 2-D grid to represent a playing field. Players can move around the playing field to hear the effects of 3-D spatial positioning.

Path

Source: (SDK root)\Samples\C++\DirectPlay\VoicePosition

Executable: (SDK root)\Samples\C++\DirectPlay\Bin

User's Guide

Refer to the User's Guide section of the VoiceConnect sample for basic information about starting up the voice samples.

With VoicePosition, you can click anywhere on the 2-D grid to move your local player on the playing field. The player always faces up, so players to the left of your player will sound off from the left speaker.

Note If you choose the Internetwork Packet Exchange (IPX) service provider and want to have DirectPlay perform a search for the address, select the use DPNSVR check box.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay C/C++ Reference

Reference material for the Microsoft® DirectPlay® C/C++ application programming interface is divided into the following categories.

  • Interfaces
  • Functions
  • Callback Functions
  • System Messages
  • Structures
  • Return Values

© 2002 Microsoft Corporation. All rights reserved.


Interfaces

This section contains references for methods of the Microsoft® DirectPlay® interfaces.

Interfaces

  • IDirectPlay8Address
  • IDirectPlay8AddressIP
  • IDirectPlay8Client
  • IDirectPlay8LobbiedApplication
  • IDirectPlay8LobbyClient
  • IDirectPlay8NATResolver
  • IDirectPlay8Peer
  • IDirectPlay8Server
  • IDirectPlay8ThreadPool
  • IDirectPlayNATHelp
  • IDirectPlayVoiceClient
  • IDirectPlayVoiceServer
  • IDirectPlayVoiceTest
  • IDP8SimControl

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address Interface

The IDirectPlay8Address interface contains generic addressing methods used to create and manipulate addresses for Microsoft® DirectPlay®. This interface is one of the interfaces available through the CLSID_DirectPlay8Address Component Object Model (COM) object. To create an object that supports this interface, use the CoCreateInstanceEx method for the CLSID CLSID_DirectPlay8Address that specifies the IID_IDirectPlay8Address interface.

IDirectPlay8Address Members

AddComponent

Adds a component to the address. If the component is part of the address, it is replaced by the new value in this call.

Values are specified in native formats when making this call. Therefore, the lpvData parameter should be a recast pointer to a variable that holds the data in the native format. For example, if the component is a globally unique identifier (GUID), the lpvData parameter should be a recast pointer to a GUID.

This method validates that the predefined component types are the right format.

BuildFromDPADDRESS

Sets the current object's internal address to be the DirectPlay 8 equivalent of the specified DirectPlay 4 address. The purpose of this method is to allow lobby developers to launch games with the new DirectPlay interface using the old lobby code.

This method enumerates the address components in the specified address and adds the corresponding element to the DirectPlay 8 address.

BuildFromURLA

Sets the object equal to the specified DirectPlay URL string. It erases the contents of the object.

BuildFromURLW

Sets the object equal to the specified DirectPlay URL string. It erases the contents of the object.

Clear

Resets the address object to an empty address.

Duplicate

Creates a DirectPlay Address object that duplicates the address in this object.

GetComponentByIndex

Retrieves information about the component at the specified index. Values for the component are retrieved in their native format. If the component key is not found, the method returns DPNERR_DOESNOTEXIST.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

GetComponentByName

Retrieves information about the component at the specified key. Values for the component are retrieved in their native format. If the component key is not found, DPNERR_DOESNOTEXIST is returned.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

GetDevice

Retrieves the local device GUID in the address object. If no device is specified, this method returns DPNERR_DOESNOTEXIST.

GetNumComponents

Retrieves the number of components in the address.

GetSP

Retrieves the service provider GUID in the address object. If no service provider is specified, this method returns DPNERR_DOESNOTEXIST.

GetURLA Retrieves the DirectPlay address URL string represented by this object (ANSI version).
GetURLW

Retrieves the DirectPlay address URL string represented by this object.

GetUserData

Retrieves the user data in the address object. If no user data exists in this address object, this method returns DPNERR_DOESNOTEXIST.

IsEqual

Compares two addresses to see if they are equal.

SetDevice

Sets the local device GUID in the address object. If a local device is specified for this address, it is overwritten by this call.

SetEqual

Sets the contents of the object it is called on to match the contents of the address object passed to the method.

SetSP

Sets the service provider GUID in the address object. If a service provider is specified for this address, it is overwritten by this call.

SetUserData

Sets the user data in the address object. If there is user data in this address, it is overwritten by this call.

Remarks

In order to deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

DirectPlay represents addresses as URLs. These URLs are then encapsulated in the address object so that they can be passed to or from the DirectPlay API. In general, address URLs are strings that consist of three basic components in the following order: scheme, scheme separator, and data string.

All DirectPlay addresses use "x-directplay" as the scheme, and ":/" as the scheme separator. Using ":/" as a separator implies that the data that follows is opaque. In other words, the data string does not conform to any Internet standard, and should just be passed on to the receiving application without modification. All DirectPlay URLs thus have the following general form:

x-directplay:/[data string]

There are two basic approaches to handling address objects:

  • Handle the data string directly, using normal string manipulation techniques.
  • Use the methods exposed by IDirectPlay8Address to obtain or modify the individual elements of the data string.

For more information about DirectPlay addresses, see DirectPlay Addressing.

Interface Information

Inherits from | IUnknown
Header | dpaddr.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::AddComponent Method

Adds a component to the address. If the component is part of the address, it is replaced by the new value in this call.

Values are specified in native formats when making this call. Therefore, the lpvData parameter should be a recast pointer to a variable that holds the data in the native format. For example, if the component is a globally unique identifier (GUID), the lpvData parameter should be a recast pointer to a GUID.

This method validates that the predefined component types are the right format.

Syntax

HRESULT AddComponent(

    const WCHAR *const pwszName,
    const void *const lpvData,
    const DWORD dwDataSize,
    const DWORD dwDataType
);

Parameters

pwszName
[in] NULL-terminated Unicode string that contains the key for the component. You can set this to a valid string or use one of the following predefined values.
DPNA_KEY_APPLICATION_INSTANCE
DPNA_KEY_BAUD
DPNA_KEY_DEVICE
DPNA_KEY_FLOWCONTROL
DPNA_KEY_HOSTNAME
DPNA_KEY_NAMEINFO
DPNA_KEY_NAT_RESOLVER
DPNA_KEY_NAT_RESOLVER_USER_STRING
DPNA_KEY_PARITY
DPNA_KEY_PHONENUMBER
DPNA_KEY_PORT
DPNA_KEY_PROCESSOR
DPNA_KEY_PROGRAM
DPNA_KEY_PROVIDER
DPNA_KEY_SCOPE
DPNA_KEY_STOPBITS
DPNA_KEY_TRAVERSALMODE
lpvData
[in] Pointer to a buffer that contains the value associated with the specified key. Data should be specified in its native format.
dwDataSize
[in] Size, in bytes, of the data in the buffer located at lpvData. The size depends on the data type. If the size is not specified correctly, the method returns DPNERR_INVALIDPARAM.
DWORD
Size = sizeof( DWORD )
GUID
Size = sizeof( GUID )
String
Size = size of the string in bytes, including the terminating NULL character.
dwDataType
[in] Data type of the value associated with this key. The data type can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_STRING_ANSI
Data is a NULL-terminated ANSI string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a GUID.
DPNA_DATATYPE_BINARY
Data is in raw binary format.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

For a discussion of various address components and their keys, see Data Values.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::BuildFromDPADDRESS Method

Sets the current object's internal address to be the Microsoft® DirectPlay® 8 equivalent of the specified DirectPlay 4 address. The purpose of this method is to allow lobby developers to launch games with the new DirectPlay interface using the old lobby code.

This method enumerates the address components in the specified address and adds the corresponding element to the DirectPlay 8 address.

Syntax

HRESULT BuildFromDPADDRESS(

    LPVOID pvAddress,
    DWORD dwDataSize
);

Parameters

pvAddress
[in] Pointer to a DirectPlay 4 address that will be converted to the DirectPlay 8 address format.
dwDataSize
[in] Size of data contained in the pvAddress parameter.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDADDRESSFORMAT | The address format is invalid.
DPNERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

Remarks

This method builds a DirectPlay 8 address from a DirectPlay 4 address. This method will clear the current address of all elements before building the new address.

This method has the following limitations.

  • The method cannot map the DPAID_Modem address element because DirectPlay 4 used modem names, while DirectPlay 8 uses globally unique identifiers (GUIDs) to identify modems.
  • Elements of the DirectPlay 4 address that are not part of the predefined DirectPlay 4 address elements will result in an error and a return value of DPNERR_INVALIDADDRESSFORMAT. See DirectPlay 4 documentation on DirectPlay addresses for a complete list of the DirectPlay 4 address elements.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::BuildFromURLA Method

Sets the object equal to the specified Microsoft® DirectPlay® URL string. It erases the contents of the object.

Syntax

HRESULT BuildFromURLA(

    CHAR *pszSourceURL
);

Parameters

pszSourceURL
[in] Pointer to a NULL-terminated ANSI string that contains a properly formatted DirectPlay address.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_INVALIDURL | Specified string is not a valid DirectPlayURL.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

The Dpaddr.h header file defines a number of standard strings that you can use to construct your URL instead using a literal string. All of the string names have the form DPNA_xxx. For example, DPNA_HEADER can be used in place of L"x-directplay:/" for the URL header.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::BuildFromURLW Method

Sets the object equal to the specified Microsoft® DirectPlay® URL string. It erases the contents of the object.

Syntax

HRESULT BuildFromURLW(

    WCHAR *pwszSourceURL
);

Parameters

pwszSourceURL
[in] Pointer to a NULL-terminated Unicode string that contains a properly formatted DirectPlay address.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_INVALIDURL | Specified string is not a valid DirectPlayURL.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

The Dpaddr.h header file defines a number of standard strings that you can use to construct your URL instead using a literal string. All of the string names have the form DPNA_xxx. For example, DPNA_HEADER can be used in place of L"x-directplay:/" for the URL header.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::Clear Method

Resets the address object to an empty address.

Syntax

HRESULT Clear(VOID);

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_NOTALLOWED This function is not allowed on this object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::Duplicate Method

Creates a Microsoft® DirectPlay® Address object that duplicates the address in this object.

Syntax

HRESULT Duplicate(

    PDIRECTPLAY8ADDRESS *ppdpaNewAddress
);

Parameters

ppdpaNewAddress
[out] Address of a pointer to receive the IDirectPlay8Address pointer for the duplicate object. DirectPlay increments the reference count for this interface. You must release the interface when you no longer need it.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_GENERIC An undefined error condition occurred.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetComponentByIndex Method

Retrieves information about the component at the specified index. Values for the component are retrieved in their native format. If the component key is not found, the method returns DPNERR_DOESNOTEXIST.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

Syntax

HRESULT GetComponentByIndex(

    const DWORD dwComponentID,
    WCHAR *pwszName,
    PDWORD pdwNameLen,
    void *pvBuffer,
    PDWORD pdwBufferSize,
    PDWORD pdwDataType
);

Parameters

dwComponentID
[in] Index of the component to retrieve. This value is zero-based and should be in the range of [0..GetNumComponents()-1].
pwszName
[out] Buffer to retrieve the name of the component on a successful call. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwNameLen. The method returns DPNERR_BUFFERTOOSMAL in this case.
pdwNameLen
[in, out] On input, a pointer to a DWORD that contains the size of the buffer, in characters including the terminating NULL character, pointed to by pwszName. On output, a pointer to a DWORD that contains the number of characters written to the buffer, including the terminating NULL character, on success and on failure, the number of characters required, including the terminating NULL character, to store this value.
pvBuffer
[out] Buffer to retrieve the data stored in the value of the component. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwBufferSize. The method returns DPNERR_BUFFERTOOSMALL in this case.
pdwBufferSize
[in, out] On input, a pointer to a DWORD containing the size of the buffer, in bytes, pointed to by pvBuffer. On output, a pointer to a DWORD that contains the number of bytes written to the buffer on success and on failure, the number of bytes required to store the data.
pdwDataType
[out] DWORD pointed to by this parameter that is set to the type of data that is stored in this component. This can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a globally unique identifier (GUID).
DPNA_DATATYPE_BINARY
Data is raw binary.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetComponentByName Method

Retrieves information about the component at the specified key. Values for the component are retrieved in their native format. If the component key is not found, DPNERR_DOESNOTEXIST is returned.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

Syntax

HRESULT GetComponentByName(

    const WCHAR *const pwszName,
    void *pvBuffer,
    PDWORD pdwBufferSize,
    PDWORD pdwDataType
);

Parameters

pwszName
[in] String specifying the name of the component you want to retrieve.
pvBuffer
[out] Buffer to retrieve the data stored in the value of the component. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwBufferSize. The method returns DPNERR_BUFFERTOOSMALL in this case.
pdwBufferSize
[in, out] On input, a pointer to a DWORD that contains the size of the buffer, in bytes, pointed to by pvBuffer. On output, a pointer to a DWORD that contains the number of bytes written to the buffer on success and on failure, the number of bytes required to store the data.
pdwDataType
[out] DWORD pointed to by this parameter that is set to the type of data that is stored in this component. This can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a globally unique identifier (GUID).
DPNA_DATATYPE_BINARY
Data is raw binary.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetDevice Method

Retrieves the local device globally unique identifier (GUID) in the address object. If no device is specified, this method returns DPNERR_DOESNOTEXIST.

Syntax

HRESULT GetDevice(

    GUID *pguidDevice
);

Parameters

pguidDevice
[out] Pointer to a GUID to receive the device in the address object.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetNumComponents Method

Retrieves the number of components in the address.

Syntax

HRESULT GetNumComponents(

    PDWORD pdwNumComponents
);

Parameters

pdwNumComponents
[out] Pointer to a DWORD to receive the number of components in this address object.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPOINTER Pointer specified as a parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetSP Method

Retrieves the service provider globally unique identifier (GUID) in the address object. If no service provider is specified, this method returns DPNERR_DOESNOTEXIST.

Syntax

HRESULT GetSP(

    GUID *pguidSP
);

Parameters

pguidSP
[out] Pointer to a GUID to receive the service provider in the address object.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetURLA Method

Retrieves the Microsoft® DirectPlay® address URL string represented by this object (ANSI version).

Syntax

HRESULT GetURLA(

    CHAR *pszURL,
    PDWORD pdwNumChars
);

Parameters

pszURL
[out] Address of a pointer to receive the URL represented by this object. This parameter can be NULL if pdwNumChars points to a DWORD containing 0.
pdwNumChars
[in, out] Pointer to a DWORD that contains the number of characters the specified buffer can hold, including the terminating NULL character. On success this value contains the number of characters written to the specified buffer, including the terminating NULL character. On failure this value contains the number of characters, including the terminating NULL character, required to hold the URL and the method returns DPNERR_BUFFERTOOSMALL.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_GENERIC | An undefined error condition occurred.
DPNERR_INVALIDURL | Specified string is not a valid DirectPlayURL.
DPNERR_OUTOFMEMORY | There is insufficient memory to perform the requested operation.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetURLW Method

Retrieves the Microsoft® DirectPlay® address URL string represented by this object.

Syntax

HRESULT GetURLW(

    WCHAR *pwszURL,
    PDWORD pdwNumChars
);

Parameters

pwszURL
[out] Address of a pointer to receive the URL represented by this object. This parameter can be NULL if pdwNumChars points to a DWORD containing 0.
pdwNumChars
[in, out] Pointer to a DWORD that contains the number of characters the specified buffer can hold, including the terminating NULL character. On success this value contains the number of characters written to the specified buffer, including the terminating NULL character. On failure this value contains the number of characters, including the terminating NULL character, required to hold the URL and the method returns DPNERR_BUFFERTOOSMALL.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_GENERIC | An undefined error condition occurred.
DPNERR_INVALIDURL | Specified string is not a valid DirectPlayURL.
DPNERR_OUTOFMEMORY | There is insufficient memory to perform the requested operation.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::GetUserData Method

Retrieves the user data in the address object. If no user data exists in this address object, this method returns DPNERR_DOESNOTEXIST.

Syntax

HRESULT GetUserData(

    void *pvUserData,
    PDWORD pdwBufferSize
);

Parameters

pvUserData
[out] Pointer to a buffer to receive the user data from this address. To retrieve the required size, set this parameter to NULL and the DWORD in pdwBufferSizeto 0.
pdwBufferSize
[in, out] Size in bytes of the buffer pointed to by pvUserData. If pvUserData is NULL, this parameter must point to a DWORD containing 0. On output, the contained DWORD is set to the number of bytes written to the buffer. On failure, this contains the number of bytes required to retrieve the user data and the method returns DPNERR_BUFFERTOOSMALL.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::IsEqual Method

Compares two addresses to see if they are equal.

Syntax

HRESULT IsEqual(

    PDIRECTPLAY8ADDRESS pdpaAddress
);

Parameters

pdpaAddress
[in] Address to compare to the address contained within the object.

Return Value

If the addresses are equal DPNSUCCESS_EQUAL is returned. If the addresses are not equal DPNSUCCESS_NOTEQUAL is returned.

If the method fails, one of the following error values may be returned.

DPNERR_INVALIDADDRESSFORMAT | The address format is invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

Remarks

This method checks the contents of the address specified by the pdpaAddress parameter and compares it to the address contained within the object this method was called on. This method does not affect the contents of either address.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::SetDevice Method

Sets the local device globally unique identifier (GUID) in the address object. If a local device is specified for this address, it is overwritten by this call.

Syntax

HRESULT SetDevice(

    const GUID *const pguidDevice
);

Parameters

pguidDevice
[in] Pointer to a GUID of the local device.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::SetEqual Method

Sets the contents of the object it is called on to match the contents of the address object passed to the method.

Syntax

HRESULT SetEqual(

    PDIRECTPLAY8ADDRESS pdpaAddress
);

Parameters

pdpaAddress
[in] Pointer to a IDirectPlay8Address object that this object will be set to.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDADDRESSFORMAT | The address format is invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::SetSP Method

Sets the service provider globally unique identifier (GUID) in the address object. If a service provider is specified for this address, it is overwritten by this call.

Syntax

HRESULT SetSP(

    const GUID *const pguidSP
);

Parameters

pguidSP
[in] Pointer to the service provider GUID. This can be one of the following predefined values.
CLSID_DP8SP_TCPIP
Internet Protocol (IP) service provider
CLSID_NETWORKSIMULATOR_DP8SP_TCPIP
Network simulator IP service providers
CLSID_DP8SP_SERIAL
Serial service provider
CLSID_DP8SP_MODEM
Modem service provider
CLSID_DP8SP_IPX
IPX service provider
CLSID_DP8SP_BLUETOOTH
Bluetooth Service Provider

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Address::SetUserData Method

Sets the user data in the address object. If there is user data in this address, it is overwritten by this call.

Syntax

HRESULT SetUserData(

    const void *const pvUserData,
    const DWORD dwDataSize
);

Parameters

pvUserData
[in] Pointer to a buffer that contains the data to place in the user data section of the address. Set to NULL to clear the user data.
dwDataSize
[in] Size, in bytes, of the data in pvUserData. If pvUserData is NULL, this must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP Interface

The IDirectPlay8AddressIP interface is available through the CLSID_DirectPlay8Address Component Object Model (COM) object. This interface is used for Internet Protocol (IP) provider-specific addressing services.

IDirectPlay8AddressIP Members

BuildAddress

Builds a remote Microsoft® DirectPlay® IP address from a host name and a port.

BuildFromSockAddr Builds a remote DirectPlay IP address from a valid SOCKADDR structure.
BuildLocalAddress

Builds a local DirectPlay IP address from a device and port.

GetAddress

Retrieves the remote address information from a remote DirectPlay IP address.

GetLocalAddress

Retrieves the local address information from a DirectPlay IP address.

GetSockAddress

Retrieves a list of SOCKADDR structures describing the addresses represented by this object.

Interface Information

Inherits from | IUnknown
Header | dpaddr.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::BuildAddress Method

Builds a remote Microsoft® DirectPlay® Internet Protocol (IP) address from a host name and a port.

Syntax

HRESULT BuildAddress(

    const WCHAR *const wszAddress,
    const USHORT usPort
);

Parameters

wszAddress
[in] Remote host address can be a dotted Internet address—for example, 127.0.0.1—or a valid host name—for example, example.microsoft.com.
usPort
[in] Port on the remote host to which to connect.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_HOSTNAME = specified host name
  • DPNA_KEY_PORT = specified port
All addressing information contained in the object before the call is erased.

Note The DPNSVR is a DirectPlay feature that allows multiple processes to share a single port for enumeration. Do not use the DPNA_DPNSVR_PORT flag when constructing a device address, or when making a connection. This flag should only be used for enumerations. If you do not add a port element to the enumeration address, the port represented by the flag will be automatically added to that address. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::BuildFromSockAddr Method

Builds a remote Microsoft® DirectPlay® Internet Protocol (IP) address from a valid SOCKADDR structure.

Syntax

HRESULT BuildFromSockAddr(

    const SOCKADDR *const pSockAddr
);

Parameters

pSockAddr
[in] Valid User Datagram Protocol (UDP) address specified in SOCKADDR form.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

The SOCKADDR structure must specify an IP address. If the address is not in the correct format, DPNERR_INVALIDPARAM is returned.

The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_HOSTNAME = specified host name
  • DPNA_KEY_PORT = specified port
All addressing information contained in the object before the call is erased.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::BuildLocalAddress Method

Builds a local Microsoft® DirectPlay® Internet Protocol (IP) address from a device and port.

Syntax

HRESULT BuildLocalAddress(

    const GUID *const pguidAdapter,
    const USHORT usPort
);

Parameters

pguidAdapter
[in] Local device identifier to host on.
usPort
[in] Port on the local device to host on. This value can be set to 0 to allow DirectPlay to automatically select the port.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_DEVICE= specified device
  • DPNA_KEY_PORT = specified port
All addressing information contained in the object before the call is erased.

Note The DPNSVR is a DirectPlay feature that allows multiple processes to share a single port for enumeration. Do not use the DPNA_DPNSVR_PORT flag when constructing a device address, or when making a connection. This flag should only be used for enumerations. If you do not add a port element to the enumeration address, the port represented by the flag will be automatically added to that address. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::GetAddress Method

Retrieves the remote address information from a remote Microsoft® DirectPlay® Internet Protocol (IP) address.

Syntax

HRESULT GetAddress(

    WCHAR *wszAddress,
    PDWORD pdwAddressLength,
    USHORT *psPort
);

Parameters

wszAddress
[out] Pointer to a buffer to receive the host name. This parameter can be NULL to retrieve the required size.
pdwAddressLength
[in, out] Size, in characters, of the buffer specified in wszAddress, including the terminating NULL character. On success, this parameter contains the number of characters, including the terminating NULL character, written to the specified buffer. On failure, this parameter contains the number of characters, including the terminating NULL character, required to retrieve the host name.
psPort
[out] Pointer to a USHORT to contain the port specified in this local address.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

Remarks

To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_HOSTNAME
  • DPNA_KEY_PORT = specified port

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::GetLocalAddress Method

Retrieves the local address information from a Microsoft® DirectPlay® Internet Protocol (IP) address.

Syntax

HRESULT GetLocalAddress(

    GUID *pguidAdapter,
    USHORT *pusPort
);

Parameters

pguidAdapter
[out] Pointer to a globally unique identifier (GUID) to retrieve the GUID of the local device specified in this address.
pusPort
[out] Pointer to a USHORT to contain the port specified in this local address.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

Remarks

To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_DEVICE
  • DPNA_KEY_PORT

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8AddressIP::GetSockAddress Method

Retrieves a list of SOCKADDR structures describing the addresses represented by this object.

Syntax

HRESULT GetSockAddress(

    SOCKADDR *psockAddress,
    PDWORD pdwAddressBufferSize
);

Parameters

psockAddress
[out] Pointer to buffer to retrieve the array of SOCKADDR structures. There is one SOCKADDR structure for each address the host resolves to.
pdwAddressBufferSize
[in, out] Size, in bytes, of the buffer specified in psockAddress. On success, this parameter contains the number of bytes written to the specified buffer. On failure, this parameter contains the number of bytes required to retrieve the array of SOCKADDR structures. You can divide the value of this parameter by the size of the SOCKADDR structure to determine the number of items present in the returned array.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.

Remarks

If the host name specified in the object requires a Domain Name System (DNS) lookup, it is performed. Therefore, this method may block while the DNS is queried. It is also possible for a host name to resolve to multiple addresses.

To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_HOSTNAME
  • DPNA_KEY_PORT = specified port

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client Interface

Applications use the methods of the IDirectPlay8Client interface to create and manage client applications for client/server sessions.

IDirectPlay8Client Members

CancelAsyncOperation

Cancels asynchronous requests.

Close

Closes the open connection to a session and uninitializes the IDirectPlay8Client object. This method must be called on any object that is successfully initialized with a call to the IDirectPlay8Client::Initialize method.

Connect

Establishes the connection to the server.

EnumHosts

Enumerates applications that host Microsoft® DirectPlay® games.

EnumServiceProviders

Enumerates the registered service providers available to the application.

GetApplicationDesc

Retrieves the full application description for the connected application.

GetCaps

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

GetConnectionInfo

Retrieves statistical information about the connection between the local client and the server.

GetSendQueueInfo

Used by the application to monitor the size of the send queue. DirectPlay does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate that messages are sent.

GetServerAddress

Retrieves the address of the server for the session.

GetServerInfo

Retrieves the data set for the server set by the call to the IDirectPlay8Server::SetServerInfo method.

GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Initialize

Registers an entry point in the client's code that receives the messages from the IDirectPlay8Client interface and from the server. This method must be called before calling any other methods of this interface.

RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, DirectPlay assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

Send

Transmits data to the server. The message can be sent synchronously or asynchronously.

SetCaps

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

SetClientInfo

Sets the static settings of a client with an application. Call this method before connecting to relay basic player information to the application. When the client successfully connects with the application, the server can retrieve information obtained through this method by calling the IDirectPlay8Server::GetClientInfo method.

SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

Interface Information

Inherits from | IUnknown
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::CancelAsyncOperation Method

Cancels asynchronous requests.

Syntax

HRESULT CancelAsyncOperation(

    const DPNHANDLE hAsyncHandle,
    const DWORD dwFlags
);

Parameters

hAsyncHandle
[in] Handle of the asynchronous operation to stop. You receive this handle when you call one of several methods that support asynchronous operations. This value can be set to NULL to stop all requests or a particular type of asynchronous request. If a particular handle is specified, the dwFlags parameter must be 0. If one of the DPNCANCEL_PLAYER_SENDS flags is specified in the dwFlags parameter, hAsyncHandle must be 0 to cancel all pending calls to the server.
dwFlags
[in] Flag that specifies which asynchronous request to canceled. You can set one of the following flags.
DPNCANCEL_ENUM
Cancel all asynchronous IDirectPlay8Client::EnumHosts requests. A single IDirectPlay8Client::EnumHosts request can be canceled by specifying the handle returned from the IDirectPlay8Client::EnumHosts method.
DPNCANCEL_CONNECT
Cancel an asynchronous IDirectPlay8Client::Connect request.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Client::Send request.
DPNCANCEL_PLAYER_SENDS
Cancel all asynchronous IDirectPlay8Client::Send requests.
DPNCANCEL_PLAYER_SENDS_PRIORITY_LOW
Cancel low-priority asynchronous IDirectPlay8Client::Send requests.
DPNCANCEL_PLAYER_SENDS_PRIORITY_NORMAL
Cancel normal-priority asynchronous IDirectPlay8Client::Send requests.
DPNCANCEL_PLAYER_SENDS_PRIORITY_HIGH
Cancel high-priority asynchronous IDirectPlay8Client::Send requests.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous requests.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL | The operation could not be canceled.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNSUCCESS_PENDING | An asynchronous operation has reached the point where it is successfully queued.

Remarks

Many methods of the IDirectPlay8Client interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can be run asynchronously return a hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

You can use this method to cancel an asynchronous operation for the IDirectPlay8Client::Connect, IDirectPlay8Client::Send, and IDirectPlay8Client::EnumHosts methods. Microsoft® DirectPlay® does not support cancellation of other asynchronous operations.

You can cancel a send by providing the handle returned from IDirectPlay8Client::Send method. A DPN_MSGID_SEND_COMPLETE system message is still posted to the applications message handler for each asynchronous send that is sent without the DPNSEND_NOCOMPLETE flag set. Sends that are canceled by this method return DPNERR_USERCANCEL in their hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS, DPNCANCEL_CONNECT, DPNCANCEL_SEND, or DPNCANCEL_ENUM flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::Close Method

Closes the open connection to a session and uninitializes the IDirectPlay8Client object. This method must be called on any object that is successfully initialized with a call to the IDirectPlay8Client::Initialize method.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] The following flag can be specified.
DPNCLOSE_IMMEDIATE
Close immediately. Do not wait for outstanding calls to complete.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED The requested object has not been initialized.

Remarks

Calling IDirectPlay8Client::Close will cancel all outstanding operations, including guaranteed messages that are in the queue waiting to be sent. Messages that have already been sent as guaranteed will continue to be retried until acknowledgement of their delivery has been received. To make sure all messages are sent, wait for all outstanding IDirectPlay8Client::Send calls to complete before calling IDirectPlay8Client::Close.

If you do not want the application to wait, the application should call IDirectPlay8Client::CancelAsyncOperation to cancel all outstanding sends prior to calling IDirectPlay8Client::Close or doing a final release call on the IDirectPlay8Client interface. Failing to do so causes unpredictable results.

Calling IDirectPlay8Client::Close will invalidate any DPN_CAPS, DPN_CAPS_EX, and DPN_SP_CAPS associated with the IDirectPlay8Client object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::Connect Method

Establishes the connection to the server.

Syntax

HRESULT Connect(

    const DPN_APPLICATION_DESC *const pdnAppDesc,
    IDirectPlay8Address *const pHostAddr,
    IDirectPlay8Address *const pDeviceInfo,
    const DPN_SECURITY_DESC *const pdnSecurity,
    const DPN_SECURITY_CREDENTIALS *const pdnCredentials,
    const void *const pvUserConnectData,
    const DWORD dwUserConnectDataSize,
    void *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdnAppDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application. Only some of the members of this structure are used by this method. The only member of this structure that you must set is the guidApplication member. You can also set guidInstance, pwszPassword, dwFlags, and dwSize.
pHostAddr
[in] Pointer to an IDirectPlay8Address interface that specifies the addressing information to use to connect to the computer that is hosting. The user can be queried for any missing address information if you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in the dwFlags parameter.
pDeviceInfo
[in] Pointer to an IDirectPlay8Address object that specifies what network adapter (for example, network interface card, modem, and so on) to use to connect to the server. Some service providers allow this parameter to be NULL or be an address object containing only the service provider component. In this case, they will use the most appropriate device to reach the designated host. If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for any missing address information.
pdnSecurity
[in] Reserved. Must be NULL.
pdnCredentials
[in] Reserved. Must be NULL.
pvUserConnectData
[in] Pointer to application-specific data provided to the host or server to further validate the connection. Microsoft® DirectPlay® will make a copy of this data when the method is called and therefore you can modify or destroy this data once the connection is complete. This data is sent to the DPN_MSGID_INDICATE_CONNECT message in the pvUserConnectData member. This parameter is optional and you can pass NULL to bypass the connection validation provided by the user code.
dwUserConnectDataSize
[in] Variable of type DWORD that specifies the size of the data contained in pvUserConnectData.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_CONNECT_COMPLETE system message. This parameter is optional and can be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNCONNECT_SYNC flag in dwFlags.
dwFlags
[in] Flag that describes the connection mode. You can set the following flag.
DPNCONNECT_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay dialog box, which queries the user for more information if not enough information is passed in this method.
DPNCONNECT_SYNC
Process the connection request synchronously. Setting this flag does not generate a DPN_MSGID_CONNECT_COMPLETE system message.

Return Value

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK will be returned if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_HOSTREJECTEDCONNECTION | The connection request was rejected. Check the ReplyData member of the DPN_MSGID_CONNECT_COMPLETE type for details.
DPNERR_INVALIDAPPLICATION | The globally unique identifier (GUID) supplied for the application is invalid.
DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHOSTADDRESS | The specified remote address is invalid.
DPNERR_INVALIDINSTANCE | The GUID for the application instance is invalid.
DPNERR_INVALIDINTERFACE | The interface parameter is invalid. This value will be returned in a connect request if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.
DPNERR_INVALIDPASSWORD | An invalid password was supplied when attempting to join a session that requires a password.
DPNERR_NOCONNECTION | No communication link was established.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.
DPNERR_SESSIONFULL | The request to connect to the host or server failed because the maximum number of players allotted for the session has been reached.
DPNERR_ALREADYCONNECTED | The object is already connected to the session.

Remarks

It is not required to enumerate hosts before calling IDirectPlay8Client::Connect if you know the appropriate host and device information.

If you do call the IDirectPlay8Client::EnumHosts method and you want to ensure better Network Address Translation (NAT) and proxy support when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider or to prevent redialing with the modem service provider, keep the enumeration active when calling the IDirectPlay8Client::Connect method. To prevent the enumeration from completing, set the dwEnumCount parameter to INFINITE and do not use the IDirectPlay8Client::CancelAsyncOperation to terminate the enumeration before the connect operation has completed. You should also pass the pAddressSender and pAddressDevice address objects in the DPNMSG_ENUM_HOSTS_RESPONSE message without modification into the pHostAddr and pDeviceInfo parameters of the IDirectPlay8Client::Connect method. To pass the address objects to IDirectPlay8Client::Connect outside of the callback function, use IDirectPlay8Address::Duplicate or IDirectPlay8Address::AddRef to prevent the object from being destroyed and store the pointers using thread-safe code. DirectPlay will automatically cancel the enumeration when the connect completes with DPN_OK or when IDirectPlay8Client::Close is called.

Before this method is called, you can obtain an application description by calling IDirectPlay8Client::EnumHosts. When you call IDirectPlay8Client::EnumHosts, DPN_MSGID_ENUM_HOSTS_RESPONSE messages are sent to your message handler with the IDirectPlay8Address objects and the DPN_APPLICATION_DESC structure for each host found. This information can be passed without modification to the IDirectPlay8Client::Connect method.

After a connection is established, the communication channel on the interface is open and the application should expect messages to arrive immediately. No messages can be sent by means of the IDirectPlay8Client::Send method until the connection has completed.

Although multiple enumerations can be run concurrently, and can be run across the duration of a connection, only one connection is allowed per interface. To establish a connection to more than one application, you must create another interface.

When this method is called, a DPN_MSGID_INDICATE_CONNECT message is posted to the server's message handler. On retrieval of this message, the host can pass back connection reply data to the IDirectPlay8Client::Connect method. Connection reply data can send a message indicating that the host does not approve the connection. The calling application can then handle this reply appropriately.

If IDirectPlay8Client::Connect is called synchronously, the following outcomes are possible.

  • Connection Successful. The application will receive a DPN_MSGID_CONNECT_COMPLETE message containing the success code and the IDirectPlay8Client::Connect method will return with DPN_OK.
  • Connection fails because the server rejects the connection. The application will receive a DPN_MSGID_CONNECT_COMPLETE message containing the DPNERR_HOSTREJECTEDCONNECTION failure code. The IDirectPlay8Client::Connect method will also return with the error code DPNERR_HOSTREJECTEDCONNECTION. The DPN_MSGID_CONNECT_COMPLETE message provides an opportunity for the client application to inspect any data the server returns with the rejection.
  • Connection fails for any other reason. The application will not receive a DPN_MSGID_CONNECT_COMPLETE message, and the IDirectPlay8Client::Connect method will return with the appropriate error code.

If IDirectPlay8Client::Connect is called asynchronously, the method returns immediately with DPNSUCCESS_PENDING. A DPN_MSGID_CONNECT_COMPLETE message will follow after the connection completes, containing the result of the connection. The only time the method does not return DPNSUCCESS_PENDING is when validation of the supplied parameters fails, in which case the appropriate error code is returned.

When the connection request completes, all outstanding enumerations are canceled with the return of DPNERR_USERCANCEL.

The hResultCode on the completion will indicate S_OK if the Connect() attempt was successful, or an error otherwise. If the Host player returned anything other than S_OK from the DPN_MSGID_INDICATE_CONNECT message, the likely error code in the completion will be DPNERR_HOSTREJECTEDCONNECTION.

When the connection completes, a DPN_MSGID_CONNECT_COMPLETE message is sent to the application's message handler. All outstanding enumerations are canceled with the return of DPNERR_USERCANCEL.

To close the connection established with this method, call the IDirectPlay8Client::Close method.

Data Value Summary specifies the required addressing information for each service provider.

Note If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::EnumHosts Method

Enumerates applications that host Microsoft® DirectPlay® games.

Syntax

HRESULT EnumHosts(

    PDPN_APPLICATION_DESC const pApplicationDesc,
    IDirectPlay8Address *const pdpaddrHost,
    IDirectPlay8Address *const pdpaddrDeviceInfo,
    PVOID const pvUserEnumData,
    const DWORD dwUserEnumDataSize,
    const DWORD dwEnumCount,
    const DWORD dwRetryInterval,
    const DWORD dwTimeOut,
    PVOID const pvUserContext,
    HANDLE *const pAsyncHandle,
    const DWORD dwFlags
);

Parameters

pApplicationDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that specifies which application hosts to enumerate. You must set the pApplicationDesc.dwSize member to the appropriate value. To reduce the number of responses, set pApplicationDesc.guidApplication to the globally unique identifier (GUID) of the application to be found. If this member is not set, the search will include all applications.
pdpaddrHost
[in] Pointer to an IDirectPlay8Address object that specifies the address of the computer that is hosting the application. Some service providers allow this parameter to be NULL or be an address object containing only the service provider component. In this case, DirectPlay will get the information by using a broadcast mechanism or from the pdpaddrDeviceInfo parameter. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for any missing address information.
pdpaddrDeviceInfo
[in] Pointer to an IDirectPlay8Address object that specifies the service provider and local device settings to use when enumerating. The user can be queried for any missing address information if you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in the dwFlags parameter.
pvUserEnumData
[in] Pointer to a block of data that is sent in the enumeration request to the host. The size of the data is limited depending on the network type. Call IDirectPlay8Client::GetSPCaps to obtain the exact value.
dwUserEnumDataSize
[in] Variable of type DWORD that specifies the size of the data pointed at in the pvUserEnumData parameter.
dwEnumCount
[in] Value specifying how many times the enumeration data will be sent. Set this parameter to zero to use the default value. You can obtain the default value for dwEnumCount by calling IDirectPlay8Client::GetSPCaps. If dwEnumCount is set to INFINITE, the enumeration will continue until canceled.
dwRetryInterval
[in] Value specifying how many milliseconds between enumeration retries. Set this parameter to zero to use the default value. You can obtain the default value for dwRetryInterval by calling IDirectPlay8Client::GetSPCaps.
dwTimeOut
[in] Variable of type DWORD that specifies the number of milliseconds that DirectPlay will wait for replies after the last enumeration is sent. Set this parameter to zero to use the default value. You can obtain the default value for dwTimeOut by calling IDirectPlay8Client::GetSPCaps. If INFINITE is specified, the enumeration continues until it is canceled.
pvUserContext
[in] Context that is provided in the client's message handler when it is called with responses to the enumeration. This can be useful to differentiate replies from concurrent enumerations.
pAsyncHandle
[out] A DPNHANDLE. When the method returns, pAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNENUMHOSTS_SYNC flag in dwFlags.
dwFlags
[in] The following flags can be set.
DPNENUMHOSTS_SYNC
Causes the method to process synchronously.
DPNENUMHOSTS_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay dialog box, which queries the user for more information if not enough information is passed in this method.
DPNENUMHOSTS_NOBROADCASTFALLBACK
If the service provider supports broadcasting, setting this flag will disable the broadcast capabilities. Check to see if broadcasting is supported by examining the DPN_SP_CAPS structure before setting this flag.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHOSTADDRESS | The specified remote address is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_ENUMQUERYTOOLARGE | The query data specified is too large.
DPNERR_USERCANCEL | The user canceled the operation.

Remarks

When an application is found that meets the enumeration criteria, the application's message handler is called with a DPN_MSGID_ENUM_HOSTS_RESPONSE system message. The message contains a DPN_APPLICATION_DESC structure describing the applications found and IDirectPlay8Address objects identifying the location of the hosts.

When an application is found that meets the enumeration criteria, the application's message handler is called with a DPN_MSGID_ENUM_HOSTS_RESPONSE system message. The message contains a DPN_APPLICATION_DESC structure describing the applications found and IDirectPlay8Address objects identifying the location of the hosts.

To ensure better Network Address Translation (NAT) and proxy support when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider or to prevent redialing with the modem service provider, keep the enumeration active when calling the IDirectPlay8Client::Connect method. To prevent the enumeration from completing, set the dwEnumCount parameter to INFINITE and do not use the IDirectPlay8Client::CancelAsyncOperation to terminate the enumeration before the connect operation has completed. You should also pass the pAddressSender and pAddressDevice address objects in the DPNMSG_ENUM_HOSTS_RESPONSE message without modification into the pHostAddr and pDeviceInfo parameters of the IDirectPlay8Client::Connect method. To pass the address objects to IDirectPlay8Client::Connect outside of the callback function, use IDirectPlay8Address::Duplicate or IDirectPlay8Address::AddRef to prevent the object from being destroyed and store the pointers using thread-safe code.

Any number of enumerations can be run concurrently. The pvUserContext value is provided in the message handler to help differentiate replies to different enumerations.

Because of the variation in the number of ways enumeration can happen, it is not recommended that an application attempt to specify dwEnumCount, dwRetryInterval, or dwTimeOut unless the application has some specific media knowledge. The only exception is if you want to have the enumeration continue until explicitly cancelled, then set dwEnumCount to INFINITE.

The default enumeration count and timeout values will cause IDirectPlay8Client::EnumHosts to complete within a reasonable amount of time. These values are set by the service provider, and can be obtained by calling IDirectPlay8Client::GetSPCaps. Asynchronous enumerations can be stopped at any time by calling IDirectPlay8Client::CancelAsyncOperation and either passing the handle returned in the pAsyncHandle parameter or setting the DPNCANCEL_ENUM flag in the dwFlags parameter. An enumeration can also be stopped by returning anything other than S_OK from the message handler when processing a DPN_MSGID_ENUM_HOSTS_RESPONSE message.

You might receive multiple DPN_MSGID_ENUM_HOSTS_RESPONSE messages from the same host during one enumeration session. The guidInstance member of the associated DPN_APPLICATION_DESC structure can be used to correlate these duplicate responses.

If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Data Value Summary specifies the required addressing information for each service provider.

DPNERR_USERCANCEL will be returned if the enumeration is canceled by calling the IDirectPlay8Client::CancelAsyncOperation method or if DPN_OK is not returned when processing a DPN_MSGID_ENUM_HOSTS_RESPONSE message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::EnumServiceProviders Method

Enumerates the registered service providers available to the application.

Syntax

HRESULT EnumServiceProviders(

    const GUID *const pguidServiceProvider,
    const GUID *const pguidApplication,
    DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
    PDWORD const pcbEnumData,
    PDWORD const pcReturned,
    const DWORD dwFlags
);

Parameters

pguidServiceProvider
[in] Pointer to a variable of type GUID that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers. Otherwise, set pguidServiceProvider to one of the following predefined values.
CLSID_DP8SP_TCPIP
Internet Protocol (IP) service providers
CLSID_NETWORKSIMULATOR_DP8SP_TCPIP
DP8Sim service providers
CLSID_DP8SP_SERIAL
Serial service providers
CLSID_DP8SP_MODEM
Modem service providers
CLSID_DP8SP_IPX
IPX service providers
pguidApplication
[in] Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected to the application are enumerated. You can also pass NULL to enumerate the registered service providers for the system.
pSPInfoBuffer
[out] Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
[out] Pointer to DWORD, which is filled with the size of the pSPInfoBuffer array if the buffer is too small.
pcReturned
[out] Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pSPInfoBuffer array.
dwFlags
[in] The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system, including those that are not available to the application or do not have devices installed.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can be obtained by passing a pointer to a service provider globally unique identifier (GUID) in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose among different modems for dialing out and select specific modems for hosting.

If the pEnumDatabuffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the cbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call the method again with the appropriate-sized buffer.

Normally, this method will return only those service providers that can be used by the application. For example, if the Internetwork Packet Exchange (IPX) networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetApplicationDesc Method

Retrieves the full application description for the connected application.

Syntax

HRESULT GetApplicationDesc(

    DPN_APPLICATION_DESC *const pAppDescBuffer,
    DWORD *const pcbDataSize,
    const DWORD dwFlags
);

Parameters

pAppDescBuffer
[out] Pointer to a DPN_APPLICATION_DESC structure where the application description data is written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
[in, out] Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.

Remarks

Call this method initially by passing NULL in the pAppDescBuffer parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

The returned DPN_APPLICATION_DESC structure will have the guidInstance, guidApplication, and pwszSessionName members set. It will not contain information about other clients that are connected to the session. That information, if available, can be obtained only from the server application. In particular, the dwCurrentPlayers member will always be set to 0.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetCaps Method

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT GetCaps(

    DPN_CAPS *const pdpnCaps,
    const DWORD dwFlags
);

Parameters

pdpnCaps
[out] Pointer to a DPN_CAPS or DPN_CAPS_EX structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Client::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used, based on the size of the structure referenced by pdpnCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetConnectionInfo Method

Retrieves statistical information about the connection between the local client and the server.

Syntax

HRESULT GetConnectionInfo(

    DPN_CONNECTION_INFO *const pdnConnectInfo,
    const DWORD dwFlags
);

Parameters

pdnConnectInfo
[out] Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. You must set the dwSize member of this structure to an appropriate value.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method can be called only after a successful IDirectPlay8Client::Connect call has completed.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetSendQueueInfo Method

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate that messages are sent.

Syntax

HRESULT GetSendQueueInfo(

    DWORD *const pdwNumMsgs,
    DWORD *const pdwNumBytes,
    const DWORD dwFlags
);

Parameters

pdwNumMsgs
[out] Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and may be set to NULL.
pdwNumBytes
[out] Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and may be set to NULL.
dwFlags
[in] You may specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

Remarks

You cannot set both pdwNumMsgsand pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetServerAddress Method

Retrieves the address of the server for the session.

Syntax

HRESULT GetServerAddress(

    IDirectPlay8Address **const ppAddress,
    const DWORD dwFlags
);

Parameters

ppAddress
[out] Address of a pointer to an IDirectPlay8Address object that specifies the address of the server. You must release this object when you no longer need it.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetServerInfo Method

Retrieves the data set for the server set by the call to the IDirectPlay8Server::SetServerInfo method.

Syntax

HRESULT GetServerInfo(

    DPN_PLAYER_INFO *const pdpnPlayerInfo,
    DWORD *const pdwSize,
    const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
[out] Pointer to a DPN_PLAYER_INFO structure to be filled with the server's information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to the size of a DPN_PLAYER_INFO structure.
pdwSize
[out] Pointer to a variable of type DWORD that contains the size of the data returned in the pdpnPlayerInfo parameter. If this value is too small, the method returns DPNERR_BUFFERTOOSMALL, and this parameter is set to the required size of the buffer.
dwFlags
[in] Reserved. Must be set to 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method after the client receives a DPN_MSGID_SERVER_INFO message, indicating that the server has updated its information.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for your structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Server::SetServerInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Server::SendTo method because of the high cost of using the IDirectPlay8Server::SetServerInfo method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::GetSPCaps Method

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT GetSPCaps(

    const GUID *const pguidSP,
    DPN_SP_CAPS *const pdpnSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) specifying the service provider you want to get information about.
pdpnSPCaps
[out] Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member to the size of a DPN_SP_CAPS structure.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method retrieves information about the specified service provider. A successful call to IDirectPlay8Client::Initialize must be made before this method can be called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::Initialize Method

Registers an entry point in the client's code that receives the messages from the IDirectPlay8Client interface and from the server. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    PVOID const pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value in calls to the message handler. Providing a user-context value can be useful to differentiate messages coming from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the server, and receives indications of session changes from the IDirectPlay8Client interface.
dwFlags
[in] You can specify the following flags.
DPNINITIALIZE_DISABLEPARAMVAL
Disable parameter validation for the current object.
DPNINITIALIZE_HINT_LANSESSION
Opens a larger send window for games running on a local area network (LAN).
DPNINITIALIZE_DISABLELINKTUNING
Disable any attempts by Microsoft® DirectPlay® to tune the rate it sends at to the observed network conditions. Messages will be pushed out onto the network at the first available opportunity.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

This is the first method you should call after using CoCreateInstance to obtain the IDirectPlay8Client interface.

Specify the DPNINITIALIZE_HINT_LANSESSION flag for sessions where all players will be on the same LAN.

Applications might want to specify the DPNINITIALIZE_DISABLELINKTUNING flag when they send at a fixed rate and do not alter the rate based on the network conditions. With this flag specified, DirectPlay will always assume the network has the capacity to carry all the application data and will therefore not attempt to tune its send rate to the network bandwidth. Specifying this flag and then sending at a rate that exceeds the capacity of the network will lead to unpredictable network behavior such as higher latency and increased packet drop rates. Applications that monitor the send queues and dynamically adjust their send rate to make best use of the available bandwidth should not specify this flag.

If the DPNINITIALIZE_DISABLELINKTUNING flag is specified, DirectPlay features such as message prioritization, coalescence, and timeout are not useful because messages always go directly to the network and are not queued.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::RegisterLobby Method

Allows launched applications to automatically propagate game status to the lobby.

Syntax

HRESULT RegisterLobby(

    const DPNHANDLE dpnHandle,
    IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
    const DWORD dwFlags
);

Parameters

dpnHandle
[in] Connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
[in] Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
[in] One of the following flags:
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::ReturnBuffer Method

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

Syntax

HRESULT ReturnBuffer(

    const DPNHANDLE hBufferHandle,
    const DWORD dwFlags
);

Parameters

hBufferHandle
[in] Variable of type DPNHANDLE that specifies the buffer handle to the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::Send Method

Transmits data to the server. The message can be sent synchronously or asynchronously.

Syntax

HRESULT Send(

    const DPN_BUFFER_DESC *const pBufferDesc,
    const DWORD cBufferDesc,
    const DWORD dwTimeOut,
    void *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pBufferDesc
[in] Pointer to a DPN_BUFFER_DESC structure that describes the data to send.
cBufferDesc
[in] Number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can be up to eight buffers in this version of Microsoft® DirectPlay®.
dwTimeOut
[in] Number of milliseconds to wait for the message to send. If the message has not been sent by the dwTimeOut value, it is deleted from the send queue. If you set this parameter to 0, the message remains in the send queue until it is sent or until the link is dropped.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message.
phAsyncHandle
[in, out] A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
[in] Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the IDirectPlay8Client::Send request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This can be a more efficient method of sending data to the server. However, it is less robust because modifying or deleting the data before receiving the DPN_MSGID_SEND_COMPLETE message can cause erroneous data to be sent. This flag cannot be combined with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Does not send DPN_MSGID_SEND_COMPLETE to the message handler. This flag cannot be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Send DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process might become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Send the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NOLOOPBACK
Suppress the DPN_MSGID_RECEIVE system message to your message handler if you are sending to yourself.
DPNSEND_NONSEQUENTIAL
If the flag is not set, messages are delivered to the target application in the order that they are sent, which can necessitate buffering out of sequence messages until the missing messages arrive. Messages are delivered to the target application in the order that they are received.
DPNSEND_COALESCE
Allows DirectPlay to combine packets when sending.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_TIMEDOUT | The operation could not complete because it has timed out.

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the server's message handler. The data buffer is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message, set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. See Basic Networking for a discussion of send priorities.

When the IDirectPlay8Client::Send request is completed, a DPN_MSGID_SEND_COMPLETE system message is posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associate structure. You can suppress the send completion by setting the DPN_NOCOMPLETE flag in dwFlags.

If a player joins a game and needs to send multiple messages immediately, the player should first send a message with the DPNSEND_COMPLETEONPROCESS flag set. When the DPN_MSGID_SEND_COMPLETE message is returned, the application can begin sending messages. If the player does not do this, some of the messages might need to be queued on the receiver and, if too much data arrives, the queue can grow faster than the receiver can handle the messages. This might result in lost data. After a player is established in the game, however, throttling in DirectPlay will control the data flow by using message timeouts or the GetSendQueueInfo method. For more information, see Optimizing Network Usage.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It might still be in a queue. If you want to be certain that the message has been processed by the target, set the DPN_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message and returned.

If the DPNSEND_COALESCE flag is set in dwFlags, DirectPlay will try to coalesce up to 32 packets waiting in the queue into the outgoing frame. DirectPlay does not guarantee coalescence, even if the DPNSEND_COALESCE flag is set. Packets will only be coalesced if there is more than one message in the queue and the player receiving is running Microsoft DirectX® 9.0 or later. All voice packets can be coalesced. Both guaranteed and non-guaranteed packets will be coalesced into the same frame. If the frame is dropped before it reaches its destination, only the guaranteed parts of the frame will be resent and no other data will be coalesced into the frame.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message can be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource can become invalid at any time after the method has been called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::SetCaps Method

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT SetCaps(

    const DPN_CAPS *const pdpCaps,
    const DWORD dwFlags
);

Parameters

pdpCaps
[in] Pointer to a DPN_CAPS or DPN_CAPS_EX structure used to set the information about the current interface.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Client::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used based on the size of the structure referenced by pdpCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::SetClientInfo Method

Sets the static settings of a client with an application. Call this method before connecting to relay basic player information to the application. When the client successfully connects with the application, the server can retrieve information obtained through this method by calling the IDirectPlay8Server::GetClientInfo method.

Syntax

HRESULT SetClientInfo(

    const DPN_PLAYER_INFO *const pdpnPlayerInfo,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
[in] Pointer to a DPN_PLAYER_INFO structure that contains the client information to set.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[in, out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETCLIENTINFO_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK can return if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_NOCONNECTION | No communication link was established.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

This method can be called at any time during the session.

The DPN_PLAYER_INFO structure's dwPlayerFlags member must be set to zero.

Transmission of nonstatic information should be handled with the IDirectPlay8Client::Send method because of the high cost of using the IDirectPlay8Client::SetClientInfo method.

You can modify the client information with this method after connecting to the application. Calling this method after connection generates a DPN_MSGID_CLIENT_INFO system message to all players, informing them that data has been updated.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Client::SetSPCaps Method

Sets the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT SetSPCaps(

    const GUID *const pguidSP,
    const DPN_SP_CAPS *const pdpnSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) that specifies the service provider to set information about.
pdpnSPCaps
[in] Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method sets parameters for the specified service provider. A successful call to IDirectPlay8Client::Initialize must be made before this method can be called. Currently, only the dwSystemBufferSize member can be set by this call. The dwNumThreads member is for legacy support. Microsoft DirectX® 9.0 applications should use the IDirectPlay8ThreadPool::SetThreadCount method to set the number of threads. The other members of the DPN_SP_CAPS structure are get-only or ignored.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication Interface

The IDirectPlay8LobbiedApplication interface is used by an application that supports lobbying. This interface allows the application to register with the system so that it can be lobby launched. Additionally, it also lets the application get the connection information necessary to launch a game without querying the user. Lastly, this interface allows the lobbied application to send messages and notifications to the lobby client that launched the application.

IDirectPlay8LobbiedApplication Members

Close

Deletes the lobbied application.

GetConnectionSettings

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are done with the structure.

Initialize

Registers a message handler function that receives notifications about changes in the state of the lobby client and receives messages from the lobby client.

RegisterProgram

Registers a lobby-aware application with Microsoft® DirectPlay®. Applications must be registered to enable lobby launching.

Send

Sends a message from the lobbied application to the lobby client.

SetAppAvailable

Makes an application available or unavailable for a lobby client to connect to. This method is typically called if a lobbied application is independently launched, that is, not launched by a lobby client. Additionally, this method should be called if a game has ended and the lobbied application needs to be available to connect to a lobby client at the start of another game.

SetConnectionSettings

Sets the connection settings to be associated with the specified connection. Calling this method generates a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

UnRegisterProgram

Unregisters a lobby-aware application that was registered through the IDirectPlay8LobbiedApplication::RegisterProgram method.

UpdateStatus

Updates the status of a connected lobby client.

Interface Information

Inherits from | IUnknown
Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::Close Method

Deletes the lobbied application.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_OUTOFMEMORY | There is insufficient memory to perform the requested operation.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::GetConnectionSettings Method

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are done with the structure.

Syntax

HRESULT GetConnectionSettings(

    const DPNHANDLE hLobbyClient,
    DPL_CONNECTION_SETTINGS *const pdplSessionInfo,
    DWORD *pdwInfoSize,
    const DWORD dwFlags
);

Parameters

hLobbyClient
[in] Handle to the connection for which to retrieve the settings.
pdplSessionInfo
[out] Pointer to a DPL_CONNECTION_SETTINGS structure to receive the connection settings for the specified connection.
pdwInfoSize
[in, out] Pointer to a DWORD containing the size, in bytes, of the buffer specified in the pdplSessionInfo structure. If the buffer is not large enough to hold the connection settings, DPNERR_BUFFERTOOSMALL is returned and this value will be set to the required buffer size. On success, this value will contain the number of bytes written to the specified buffer.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::Initialize Method

Registers a message handler function that receives notifications about changes in the state of the lobby client and receives messages from the lobby client.

Syntax

HRESULT Initialize(

    const PVOID pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    DPNHANDLE *const pdpnhConnection,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the IDirectPlay8LobbyClient interface and indications of session changes from the IDirectPlay8LobbiedApplication interface.
pdpnhConnection
[out] Value used to detect if your application was lobby launched. If your application was lobby launched, this parameter will be set to the connection handle to the lobby client. If your process was not lobby launched, this parameter is set to NULL.
dwFlags
[in] The following flag can be specified.
DPLINITIALIZE_DISABLEPARAMVAL
Disables parameter validation.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_ALREADYINITIALIZED | The object has already been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8LobbiedApplication interface.

This method automatically establishes a connection to the lobby client if you were lobby launched. If you call IDirectPlay8LobbiedApplication::Initialize and you were lobby launched and the lobbied application interface is unable to contact the lobby client process, IDirectPlay8LobbiedApplication::Initialize will time out after four seconds. In this case, IDirectPlay8LobbiedApplication::Initialize will return DPNERR_TIMEDOUT but will still succeed.

Note Only one instance of IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication is allowed to be running for each process.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::RegisterProgram Method

Registers a lobby-aware application with Microsoft® DirectPlay®. Applications must be registered to enable lobby launching.

Syntax

HRESULT RegisterProgram(

    PDPL_PROGRAM_DESC pdplProgramDesc,
    const DWORD dwFlags
);

Parameters

pdplProgramDesc
[in] Pointer to the DPL_PROGRAM_DESC structure that describes the lobby-aware application to register.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

The application needs to register only once. It should be unregistered with a call to the IDirectPlay8LobbiedApplication::UnRegisterProgram method when it is uninstalled.

IDirectPlay8LobbiedApplication::RegisterProgram must be used. You cannot manually enter application information in the registry. Failure to use this interface might make your application nonportable and incompatible with later versions of DirectPlay.

If your application is running on Microsoft Windows® Powered Pocket PC 2002, do not set the pwszExecutablePath member of the DPL_PROGRAM_DESC structure to NULL unless your application's executable is located in the Windows directory (\Windows). If it is not in that directory, set pwszExecutablePath to the correct path.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::Send Method

Sends a message from the lobbied application to the lobby client.

Syntax

HRESULT Send(

    const DPNHANDLE hConnection,
    BYTE *const pBuffer,
    const DWORD pBufferSize,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Variable of type DPNHANDLE that specifies the lobby client that the message is sent to. You may also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
The message you have specified will be sent to all lobby clients to which you are connected.
pBuffer
[in] Pointer to a variable of type BYTE that contains the message buffer.
pBufferSize
[in] Variable of type DWORD that specifies the size of the message buffer in the pBuffer parameter, in bytes. This parameter must be at least 1 byte and no more than 64 KB.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_SENDTOOLARGE | The buffer was too large.

Remarks

If the buffer size is larger than 64 KB, the method returns DPNERR_SENDTOOLARGE. If the buffer size is set to 0, the method returns DPNERR_INVALIDPARAM.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::SetAppAvailable Method

Makes an application available or unavailable for a lobby client to connect to. This method is typically called if a lobbied application is independently launched, that is, not launched by a lobby client. Additionally, this method should be called if a game has ended and the lobbied application needs to be available to connect to a lobby client at the start of another game.

Syntax

HRESULT SetAppAvailable(

    const BOOL fAvailable,
    const DWORD dwFlags
);

Parameters

fAvailable
[in] Boolean value that sets the availability of the application. Set this value to TRUE to indicate that your application is available, or to FALSE to indicate that it is not available.
dwFlags
[in] The following flag can be set for this method.
DPLAVAILABLE_ALLOWMULTIPLECONNECT
The default behavior for this method is to automatically mark the interface as Unavailable when the first connection is established. By specifying this flag, the interface is not automatically marked unavailable after the first connection is established, thereby allowing multiple connections.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::SetConnectionSettings Method

Sets the connection settings to be associated with the specified connection. Calling this method generates a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

Syntax

HRESULT SetConnectionSettings(

    const DPNHANDLE hConnection,
    const DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Handle to the connection to set the settings for. You may also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
The connection settings will be updated for all the lobby clients to which you are connected.
pdplConnectSettings
[in] Pointer to a DPL_CONNECTION_SETTINGS structure containing the settings associated with the specified connection.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::UnRegisterProgram Method

Unregisters a lobby-aware application that was registered through the IDirectPlay8LobbiedApplication::RegisterProgram method.

Syntax

HRESULT UnRegisterProgram(

    GUID *pguidApplication,
    const DWORD dwFlags
);

Parameters

pguidApplication
[in] Pointer to the globally unique identifier (GUID) of the application to unregister.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbiedApplication::UpdateStatus Method

Updates the status of a connected lobby client.

Syntax

HRESULT UpdateStatus(

    const DPNHANDLE hConnection,
    const DWORD dwStatus,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Variable of type DPNHANDLE that specifies the lobby client. You may also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
The status update will be sent to all lobby clients to which you are connected.
dwStatus
[in] Variable of type DWORD that is filled with one of the following values that indicate the status between the lobby client and the lobbied application.
DPLSESSION_CONNECTED
The lobby client and lobbied application are currently connected.
DPLSESSION_COULDNOTCONNECT
The lobby client was not able to connect to the lobbied application.
DPLSESSION_DISCONNECTED
The lobby client and lobbied application are currently disconnected.
DPLSESSION_TERMINATED
The connection between the lobby client and lobbied application has been terminated.
DPLSESSION_HOSTMIGRATED
The peer object associated with the connection is involved in a session where a host migration takes place and the local client is not the new host.
DPLSESSION_HOSTMIGRATEDHERE
The peer object associated with the connection is involved in a session where a host migration takes place and the local client becomes the new host.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient Interface

Applications use methods of the IDirectPlay8LobbyClient interface to enumerate and launch lobby-enabled games on a local computer, and communicate with the games when they are running. The lobby client must register a message-handler routine to process messages from the lobby and the lobbied game application.

IDirectPlay8LobbyClient Members

Close

Deletes the lobby client.

ConnectApplication

Connects a lobby-enabled application to the session specified in the DPL_CONNECT_INFO structure. If the application is not running, this method can be used to launch the application.

When the connection is successfully established, the lobbied application generates a DPL_MSGID_CONNECT system message to the message handler.

EnumLocalPrograms

Enumerates the lobbied applications that are registered on the system.

GetConnectionSettings

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are finished with the structure.

Initialize

Registers an entry point in the lobby client's code that receives notifications on changes of state for any launched applications. The message handler also receives messages from the lobbied application. This method must be called before calling any other methods of this interface.

ReleaseApplication

Releases a lobbied application and closes the connection between the lobby client and the application. This method should be called whenever a lobby client has finished its session with an application.

Send

Sends a message to a lobbied application that was launched by this lobby client or was connected by this lobby client.

This method sends a DPL_MSGID_RECEIVE system message to the target's message handler.

SetConnectionSettings

Sets the connection settings to be associated with the specified connection. Calling this method will generate a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

Interface Information

Inherits from | IUnknown
Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::Close Method

Deletes the lobby client.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED The requested object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::ConnectApplication Method

Connects a lobby-enabled application to the session specified in the DPL_CONNECT_INFO structure. If the application is not running, this method can be used to launch the application.

When the connection is successfully established, the lobbied application generates a DPL_MSGID_CONNECT system message to the message handler.

Syntax

HRESULT ConnectApplication(

    DPL_CONNECT_INFO *const pdplConnectionInfo,
    const PVOID pvUserApplicationContext,
    DPNHANDLE *const phApplication,
    const DWORD dwTimeOut,
    const DWORD dwFlags
);

Parameters

pdplConnectionInfo
[in] Pointer to a DPL_CONNECT_INFO structure, which describes the connection parameters, including the globally unique identifier (GUID) of the application to connect to.
pvUserApplicationContext
[in] Pointer to a context value defined for the lobby client that is passed in calls to the lobby client's message handler.
phApplication
[out] Pointer to a DPNHANDLE that specifies the application connect handle that is set if this method succeeds. This handle is used for further communication with the application. Additionally, this handle is used in the phApplication parameter in the IDirectPlay8LobbyClient::ReleaseApplication method.
dwTimeOut
[in] Variable of type DWORD that specifies the number of milliseconds to wait for the connection to process.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_CANTLAUNCHAPPLICATION | The lobby cannot launch the specified application.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_TIMEDOUT | The operation could not complete because it has timed out.
DPNERR_NOCONNECTION | No communication link was established.
DPNERR_DOESNOTEXIST | Requested element is not part of the address.

Remarks

When this method returns DPNERR_NOCONNECTION, the reason is usually that the application described in the pdplConnectionInfo parameter has not called IDirectPlay8LobbiedApplication::SetAppAvailable.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::EnumLocalPrograms Method

Enumerates the lobbied applications that are registered on the system.

Syntax

HRESULT EnumLocalPrograms(

    GUID *const pGuidApplication,
    BYTE *const pEnumData,
    DWORD *const pdwEnumData,
    DWORD *const pdwItems,
    const DWORD dwFlags
);

Parameters

pGuidApplication
[in] Pointer to a variable of type globally unique identifier (GUID) that specifies the lobbied application to enumerate. This parameter is optional, and passing NULL enumerates all available lobbied applications.
pEnumData
[out] Pointer to a variable of type BYTE, which is filled with a description of the lobbied application.
pdwEnumData
[in] Pointer to variable of type DWORD that specifies the number of bytes contained in the pEnumData buffer. If the buffer in pEnumData is too small, this method returns DPNERR_BUFFERTOOSMALL and sets this parameter to the size of the required buffer.
pdwItems
[out] Pointer to a variable of type DWORD that contains the number of DPL_APPLICATION_INFO structures in the pEnumData buffer. This parameter is filled only if the method succeeds.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_DOESNOTEXIST | Requested element is not part of the address.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

This method is generally called twice—once to obtain the size of the required buffer, and then with the correct buffer size.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::GetConnectionSettings Method

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are finished with the structure.

Syntax

HRESULT GetConnectionSettings(

    const DPNHANDLE hConnection,
    DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
    DWORD *pdwDataSize,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Handle to the connection for which to retrieve the settings.
pdplConnectSettings
[out] Pointer to a buffer to receive the connection settings for the specified connection.
pdwDataSize
[in, out] Pointer to a DWORD containing the size, in bytes, of the buffer specified in the pdplConnectSettings structure. If the buffer is not large enough to hold the connection settings, DPNERR_BUFFERTOOSMALL is returned and this value is set to the required buffer size. On success, this value contains the number of bytes written to the specified buffer.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::Initialize Method

Registers an entry point in the lobby client's code that receives notifications on changes of state for any launched applications. The message handler also receives messages from the lobbied application. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    const PVOID pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value provided in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the IDirectPlay8LobbyClient interface and indications of session changes from the IDirectPlay8LobbiedApplication interface.
dwFlags
[in] The following flag can be specified.
DPLINITIALIZE_DISABLEPARAMVAL
Disables parameter validation.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_ALREADYINITIALIZED | The object has already been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

Call this is method first after using CoCreateInstance to obtain the IDirectPlay8LobbyClient interface.

Note Only one instance of IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication is allowed to be running for each process.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::ReleaseApplication Method

Releases a lobbied application and closes the connection between the lobby client and the application. This method should be called whenever a lobby client has finished its session with an application.

Syntax

HRESULT ReleaseApplication(

    const DPNHANDLE hApplication,
    const DWORD dwFlags
);

Parameters

hApplication
[in] The DPNHANDLE of the lobbied application to release. This value is set in the phApplication parameter of the IDirectPlay8LobbyClient::ConnectApplication method. You can also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
All application connections will be released.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::Send Method

Sends a message to a lobbied application that was launched by this lobby client or was connected by this lobby client.

This method sends a DPL_MSGID_RECEIVE system message to the target's message handler.

Syntax

HRESULT Send(

    const DPNHANDLE hConnection,
    BYTE *const pBuffer,
    const DWORD pBufferSize,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Variable of type DPNHANDLE that specifies the target for the message transmission. You may also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
The message you have specified will be sent to all lobbied applications that are connected to your lobby client application.
pBuffer
[in] Pointer to an array of bytes that contains the message.
pBufferSize
[in] Variable of type DWORD that specifies the size of the message buffer in the pBuffer parameter, in bytes. This parameter must be at least 1 byte and no more than 64 KB.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_SENDTOOLARGE | The buffer was too large.

Remarks

If the buffer size is larger than 64 KB, the method returns DPNERR_SENDTOOLARGE. If the buffer size is set to 0, the method returns DPNERR_INVALIDPARAM.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8LobbyClient::SetConnectionSettings Method

Sets the connection settings to be associated with the specified connection. Calling this method will generate a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

Syntax

HRESULT SetConnectionSettings(

    const DPNHANDLE hConnection,
    const DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
    const DWORD dwFlags
);

Parameters

hConnection
[in] Handle to the connection to set the settings for. You may also specify the following flag.
DPLHANDLE_ALLCONNECTIONS
The connection settings will be updated for all the lobbied applications you are connected to.
pdplConnectSettings
[in] Pointer to a DPL_CONNECTION_SETTINGS structure containing the settings associated with the specified connection.
dwFlags
[in] Reserved, must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver Interface

Applications use the methods of the IDirectPlay8NATResolver interface to improve connectivity for players behind Network Address Translation (NAT) devices that are not Universal Plug and Play (UPnP).

Note This interface is only for players using the IPv4 service provider.

IDirectPlay8NATResolver Members

Close

Closes the IDirectPlay8NATResolver interface.

EnumDevices

Enumerates the list of available devices on which the NAT Resolver can be started.

GetAddresses

Retrieves the list of IDirectPlay8Address objects on which the NAT Resolver has been started.

Initialize

Initializes the IDirectPlay8NATResolver interface. This method must be called before calling any other methods of this interface.

Start

Launches the NAT Resolver server using the specified device addresses.

Interface Information

Inherits from | IUnknown
Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver::Close Method

Closes the IDirectPlay8NATResolver interface.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Set to NULL.

Return Value

Returns DPN_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver::EnumDevices Method

Enumerates the list of available devices on which the Network Address Translation (NAT) Resolver can be started.

Syntax

HRESULT EnumDevices(

    DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
    PDWORD const pdwBufferSize,
    PDWORD const pdwNumDevices,
    const DWORD dwFlags
);

Parameters

pSPInfoBuffer
[out] Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pdwBufferSize
[out] Pointer to DWORD, which is filled with the size of the pSPInfoBuffer buffer.
pdwNumDevices
Pointer to DWORD which is filled with the number of DPN_SERVICE_PROVIDER_INFO structures returned in pSPInfoBuffer.
dwFlags
[in] Reserved. Set to NULL.

Return Value

Returns DPN_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

If the value at pdwBufferSize indicates the buffer is too small to hold the list of devices, the size required is placed in pdwBufferSize and DPNERR_BUFFERTOOSMALL is returned. Otherwise the size written is placed in pdwBufferSize

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver::GetAddresses Method

Retrieves the list of IDirectPlay8Address objects on which the Network Address Translation (NAT) Resolver has been started.

Syntax

HRESULT GetAddresses(

    IDirectPlay8Address **const ppAddresses,
    DWORD *const pdwNumAddresses,
    const DWORD dwFlags
);

Parameters

ppAddresses
[out] Receives an array of IDirectPlay8Address address objects.
pdwNumAddresses
[in] Number of address objects returned in the ppAddresses.
dwFlags
[in] Reserved. Set to NULL.

Return Value

Returns DPN_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

IDirectPlay8Address::Release must be called on each of the address interface pointers returned by IDirectPlay8NATResolver::GetAddresses when you are finished with the objects.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver::Initialize Method

Initializes the IDirectPlay8NATResolver interface. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    const PVOID pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value in calls to the message handler. A user-provided context value can be used to differentiate messages coming from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that is used to receive all messages.
dwFlags
[in] The following flag can be set.
DPNINITIALIZE_DISABLEPARAMVAL
Passing this flag will disable parameter validation for the current object.

Return Value

Returns DPN_OK if successful, or one of the following error values.

DPNERR_ALREADYINITIALIZED | The object has already been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8NATResolver::Start Method

Launches the Network Address Translation (NAT) Resolver server using the specified device addresses.

Syntax

HRESULT Start(

    IDirectPlay8Address **const ppDevices,
    const DWORD dwNumDevices,
    const DWORD dwFlags
);

Parameters

ppDevices
[in] An array of IDirectPlay8Address device address objects. Set to NULL to use all Internet Protocol (IP) devices. See Remarks.
dwNumDevices
[in] Number of device addresses in the ppDevices array.
dwFlags
[in] Reserved. Set to NULL.

Return Value

Returns DPN_OK if successful, or one of the following error values.

DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

The ppDevices parameter must contain address objects which have called IDirectPlay8Address::SetSP with the pGuidSP parameter set to CLSID_DP8SP_TCPIP. If IDirectPlay8Address::SetDevice has not been called to set the device globally unique identifier (GUID), all adapters will be used. Only eight addresses can be specified simultaneously.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer Interface

Applications use the methods of the IDirectPlay8Peer interface to create a peer-to-peer Microsoft® DirectPlay® session.

IDirectPlay8Peer Members

AddPlayerToGroup

Adds a peer to a group.

When this method is called, all peers connected to the application receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message.

CancelAsyncOperation

Cancels asynchronous requests. For instance, several methods of the IDirectPlay8Peer interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

Close

Closes the open connection to a session and uninitializes the IDirectPlay8Peer object. This method must be called on any object successfully initialized with IDirectPlay8Peer::Initialize.

Connect

Establishes the connection to all the peers in a peer-to-peer session. Once a connection is established, the communication channel on the interface is open and the application should expect messages to arrive immediately. No messages can be sent by way of the IDirectPlay8Peer::SendTo method until the connection has completed.

CreateGroup

Creates a group in the current session. A group is a logical collection of players.

DestroyGroup

Deletes a group created by the IDirectPlay8Peer::CreateGroup method. This method can be called by any peer in the session.

DestroyPeer

Deletes a peer from the session.

EnumGroupMembers

Retrieves a list of all players in a group.

EnumHosts

Enumerates applications that host DirectPlay games.

EnumPlayersAndGroups

Retrieves a list of all the player and/or group identifiers for the session.

EnumServiceProviders

Enumerates all the registered service providers available to the application.

GetApplicationDesc

Retrieves the full application description for the connected application.

GetCaps

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

GetConnectionInfo

Retrieves statistical information about the connection between the local application and the specified remote player.

GetGroupContext

Retrieves the group context value for the specified group.

GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received indicating that the group data has been modified.

GetLocalHostAddresses

Retrieves the local addresses being used to host the session.

GetPeerAddress

Retrieves the address for the specified remote player in the session.

GetPeerInfo

Retrieves peer information set for the specified peer.

GetPlayerContext

Retrieves the player context value for the specified peer.

GetSendQueueInfo

Used by the application to monitor the size of the send queue.

GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Host

Creates a new peer-to-peer session, hosted by the local computer.

Initialize

Registers an entry point in the peer's code that receives all the messages from the IDirectPlay8Peer interface and from remote peers. This method must be called before calling any other methods of this interface.

RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

RemovePlayerFromGroup

Removes a peer from a group.

When this method is called all peers connected to the application receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message.

ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, DirectPlay assumes that ownership of the buffer is transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

SendTo

Transmits data to another peer or group within the session by sending a message to the appropriate message handlers. The message can be sent synchronously or asynchronously.

SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

SetCaps

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

Calling this method generates a DPN_MSGID_GROUP_INFO message, which is sent to all the peers connected to the application.

SetPeerInfo

Sets the static settings of the local peer. Call this method before connecting to relay basic player information with the application. When the peer successfully connects with the application, information set through this method can be retrieved by other players by calling the IDirectPlay8Peer::GetPeerInfo method.

SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

TerminateSession

Terminates the current DirectPlay session.

Interface Information

Inherits from | IUnknown
Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::AddPlayerToGroup Method

Adds a peer to a group.

When this method is called, all peers connected to the application receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message.

Syntax

HRESULT AddPlayerToGroup(

    const DPNID idGroup,
    const DPNID idClient,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] Variable of type DPNID that specifies the identifier of the group to add the peer to.
idClient
[in] Variable of type DPNID that specifies the identifier of the peer that is added to the group.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNADDPLAYERTOGROUP_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method runs asynchronously and usually returns DPNSUCCESS_PENDING. It may also return one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_PLAYERALREADYINGROUP | The player ID is already included in the group.

Remarks

Any peer can add itself or another peer to an existing group. Once the peer is successfully added to the group, all messages sent to the group are also sent to the peer.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::CancelAsyncOperation Method

Cancels asynchronous requests. For instance, several methods of the IDirectPlay8Peer interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

Syntax

HRESULT CancelAsyncOperation(

    const DPNHANDLE hAsyncHandle,
    const DWORD dwFlags
);

Parameters

hAsyncHandle
[in] Handle of the asynchronous operation to stop. You receive this handle when you call one of several methods that support asynchronous operations. This value can be set to NULL to stop all operations or a particular type of asynchronous request. If a particular handle is specified, the dwFlags parameter must be 0. If one of the DPNCANCEL_PLAYER_SENDS flags is specified in the dwFlags parameter, hAsyncHandle must be set to a player's DPNID.
dwFlags
[in] Flag that specifies which asynchronous request is to be canceled. One of the following flags can be set.
DPNCANCEL_ENUM
Cancel all asynchronous IDirectPlay8Peer::EnumHosts requests. A single IDirectPlay8Peer::EnumHosts request can be canceled by specifying the handle returned from the IDirectPlay8Peer::EnumHosts method.
DPNCANCEL_CONNECT
Cancel an asynchronous IDirectPlay8Peer::Connect request.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Peer::SendTo request.
DPNCANCEL_PLAYER_SENDS
Cancel all asynchronous IDirectPlay8Peer::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_LOW
Cancel low-priority asynchronous IDirectPlay8Peer::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_NORMAL
Cancel normal-priority asynchronous IDirectPlay8Peer::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_HIGH
Cancel high-priority asynchronous IDirectPlay8Peer::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous IDirectPlay8Peer::Connect, IDirectPlay8Peer::SendTo, and IDirectPlay8Peer::EnumHosts operations.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL | The operation could not be canceled.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.

Remarks

You can use this method to cancel an asynchronous operation for the IDirectPlay8Peer::Connect, IDirectPlay8Peer::SendTo, and IDirectPlay8Peer::EnumHosts methods. Microsoft® DirectPlay® does not support cancellation of other asynchronous operations.

You can cancel a send request by providing the handle returned from the IDirectPlay8Peer::SendTo method. A DPN_MSGID_SEND_COMPLETE, or DPN_MSGID_CONNECT_COMPLETE system message is still posted to the application's message handler for each asynchronous send request that is sent without the DPNSEND_NOCOMPLETE flag set. Send requests that are canceled by this method return DPNERR_USERCANCEL in the hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS, DPNCANCEL_CONNECT, DPNCANCEL_SEND, or DPNCANCEL_ENUM flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

If you set one of the DPNCANCEL_PLAYER_SENDS flags in dwFlags, you must specify a player's DPNID in hAsyncHandle. This will cancel all pending IDirectPlay8Peer::SendTo requests where the DPNID specified in the dpnid parameter matches the value set in the hAsyncHandle parameter.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::Close Method

Closes the open connection to a session and uninitializes the IDirectPlay8Peer object. This method must be called on any object successfully initialized with IDirectPlay8Peer::Initialize.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] The following flag can be specified.
DPNCLOSE_IMMEDIATE
Close immediately. Do not wait for outstanding calls to complete.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED The requested object has not been initialized.

Remarks

This method will cancel any operations still outstanding, including guaranteed messages that are in the queue waiting to be sent. Messages that have already been sent as guaranteed will continue to be retried until acknowledgement of their delivery has been received. To make sure all messages are sent, wait for all outstanding IDirectPlay8Peer::SendTo calls to complete before calling IDirectPlay8Peer::Close.

If this method is called by the host player and host migration has been enabled, the host will migrate and the session will continue for other players. If host migration is not enabled, the session will terminate. If the host player wants to terminate the session without host migration, IDirectPlay8Peer::TerminateSession should be called before calling IDirectPlay8Peer::Close. See Host Migration for more information.

To start a new session or connect to another session after calling IDirectPlay8Peer::Close, you must first call IDirectPlay8Peer::Initialize on the IDirectPlay8Peer object before calling IDirectPlay8Peer::Host or IDirectPlay8Peer::Connect.

Calling IDirectPlay8Peer::Close will invalidate any DPN_CAPS, DPN_CAPS_EX, and DPN_SP_CAPS associated with the IDirectPlay8Peer object.

See Also

Leaving a Peer-to-Peer Session, Terminating a Peer-to-Peer Session

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::Connect Method

Establishes the connection to all the peers in a peer-to-peer session. Once a connection is established, the communication channel on the interface is open and the application should expect messages to arrive immediately. No messages can be sent by way of the IDirectPlay8Peer::SendTo method until the connection has completed.

Syntax

HRESULT Connect(

    const DPN_APPLICATION_DESC *const pdnAppDesc,
    IDirectPlay8Address *const pHostAddr,
    IDirectPlay8Address *const pDeviceInfo,
    const DPN_SECURITY_DESC *const pdnSecurity,
    const DPN_SECURITY_CREDENTIALS *const pdnCredentials,
    const void *const pvUserConnectData,
    const DWORD dwUserConnectDataSize,
    void *const pvPlayerContext,
    void *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdnAppDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application. Only some of the members of this structure are used by this method. The only members that you must set are dwSize and guidApplication. You can also set guidInstance, pwszPassword, and dwFlags.
pHostAddr
[in] Pointer to an IDirectPlay8Address interface that specifies the addressing information to use to connect to the computer that is hosting. The user can be queried for any missing address information if you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in the dwFlags parameter.
pDeviceInfo
[in] Pointer to an IDirectPlay8Address interface that specifies the network adapter (for example, network interface card, modem, and so on) to use to connect to the server. Some service providers allow this parameter to be NULL or be an address object containing only the service provider component. In this case, they will use the most appropriate device to reach the designated host. If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for any missing address information.
pdnSecurity
[in] Reserved. Must be NULL.
pdnCredentials
[in] Reserved. Must be NULL.
pvUserConnectData
[in] Pointer to application-specific data provided to the host or server to further validate the connection. Microsoft® DirectPlay® will make a copy of this data when the method is called and therefore you can modify or destroy this data once the connection is complete. This data is sent to the DPN_MSGID_INDICATE_CONNECT message in the pvUserConnectData member. This parameter is optional and can be set to NULL if no additional connection validation is provided by the user code.
dwUserConnectDataSize
[in] Variable of type DWORD that specifies the size of the data contained in the pvUserConnectData parameter.
pvPlayerContext
[in] Pointer to the context value of the local player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional and can be set to NULL.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_CONNECT_COMPLETE system message. This parameter is optional and can be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNCONNECT_SYNC flag in dwFlags.
dwFlags
[in] Flag that describes the connection mode. You can set the following flags.
DPNCONNECT_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay dialog box, which queries the user for more information if not enough information is passed in this method.
DPNCONNECT_SYNC
Process the connection request synchronously. Your message handler still receives a DPN_MSGID_CONNECT_COMPLETE message, so that you can process any connection reply data from the host. You will receive this message before IDirectPlay8Peer::Connect returns.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method runs asynchronously and normally returns DPNSUCCESS_PENDING. It might also return one of the following error values.

DPNERR_HOSTREJECTEDCONNECTION | The connection request was rejected. Check the ReplyData member of the DPN_MSGID_CONNECT_COMPLETE type for details.
DPNERR_INVALIDAPPLICATION | The globally unique identifier (GUID) supplied for the application is invalid.
DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHOSTADDRESS | The specified remote address is invalid.
DPNERR_INVALIDINSTANCE | The GUID for the application instance is invalid.
DPNERR_INVALIDINTERFACE | The interface parameter is invalid. This value will be returned in a connect request if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.
DPNERR_INVALIDPASSWORD | An invalid password was supplied when attempting to join a session that requires a password.
DPNERR_NOCONNECTION | No communication link was established.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.
DPNERR_SESSIONFULL | The request to connect to the host or server failed because the maximum number of players allotted for the session has been reached.

Remarks

Before this method is called, you can obtain application descriptions and the addresses of the associated hosts by calling IDirectPlay8Peer::EnumHosts. When you call IDirectPlay8Peer::EnumHosts, DPN_MSGID_ENUM_HOSTS_RESPONSE messages are sent to your message handler with the IDirectPlay8Address objects and the DPN_APPLICATION_DESC structure for each host found. This information can be passed without modification to the IDirectPlay8Peer::Connect method.

It is not required to enumerate hosts before calling IDirectPlay8Peer::Connect if you know the appropriate host and device information.

If you do call the IDirectPlay8Peer::EnumHosts method and you want to ensure better Network Address Translation (NAT) and proxy support when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider or to prevent redialing with the modem service provider, keep the enumeration active when calling the IDirectPlay8Peer::Connect method. To prevent the enumeration from completing, set the dwEnumCount parameter to INFINITE and do not use the IDirectPlay8Peer::CancelAsyncOperation to terminate the enumeration before the connect operation has completed. You should also pass the pAddressSender and pAddressDevice address objects in the DPNMSG_ENUM_HOSTS_RESPONSE message without modification into the pHostAddr and pDeviceInfo parameters of the IDirectPlay8Peer::Connect method. To pass the address objects to IDirectPlay8Peer::Connect outside of the callback function, use IDirectPlay8Address::Duplicate or IDirectPlay8Address::AddRef to prevent the object from being destroyed and store the pointers using thread-safe code. DirectPlay will automatically cancel the enumeration when the connect completes with DPN_OK or when IDirectPlay8Peer::Close is called.

Although multiple enumerations can be run concurrently and can be run across the duration of a connection, only one connection is allowed per interface. To establish a connection to more than one application, you must create another interface.

When this method is called, a DPN_MSGID_INDICATE_CONNECT message is posted to the host's message handler. When the host handles this message, it can specify connection reply data that the player will receive with the DPN_MSGID_CONNECT_COMPLETE message. If the host accepts the connection, the connection reply data might contain custom startup information. If the connection was rejected, the connection reply data might contain an explanation of the rejection.

If IDirectPlay8Client::Connect is called synchronously, the following outcomes are possible.

  • Connection Successful. The application will receive a DPN_MSGID_CONNECT_COMPLETE message containing the success code and the IDirectPlay8Client::Connect method will return with DPN_OK.
  • Connection fails because the host rejects the connection. The application will receive a DPN_MSGID_CONNECT_COMPLETE message containing the DPNERR_HOSTREJECTEDCONNECTION failure code. The IDirectPlay8Client::Connect method will also return with the error code DPNERR_HOSTREJECTEDCONNECTION. The DPN_MSGID_CONNECT_COMPLETE message provides an opportunity for the client application to inspect any data the host returns with the rejection.
  • Connection fails for any other reason. The application will not receive a DPN_MSGID_CONNECT_COMPLETE message, and the IDirectPlay8Client::Connect method will return with the appropriate error code.

If IDirectPlay8Client::Connect is called asynchronously, the method returns immediately with DPNSUCCESS_PENDING. A DPN_MSGID_CONNECT_COMPLETE message will follow after the connection completes, containing the result of the connection. The only time the method does not return DPNSUCCESS_PENDING is when validation of the supplied parameters fails, in which case the appropriate error code is returned.

When the connection request completes, all outstanding enumerations are canceled with the return of DPNERR_USERCANCEL.

You must call IDirectPlay8Peer::Close to end the connection to the host.

Data Value Summary specifies the required addressing information for each service provider.

Note If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::CreateGroup Method

Creates a group in the current session. A group is a logical collection of players.

Syntax

HRESULT CreateGroup(

    const DPN_GROUP_INFO *const pdpnGroupInfo,
    VOID *const pvGroupContext,
    VOID *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdpnGroupInfo
[in] Pointer to a DPN_GROUP_INFO structure that contains the group description.
pvGroupContext
[in] Pointer to the group's context value. This value is preset when the local application's message handler receives the associated DPN_MSGID_CREATE_GROUP message. This parameter is optional and may be set to NULL.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNCREATEGROUP_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return the following error value.

DPNERR_INVALIDFLAGS The flags passed to this method are invalid.

Remarks

DirectPlay does not maintain hierarchical groups because these can easily be implemented with flat groups and expeditious use of the group data.

All peers receive a DPN_MSGID_CREATE_GROUP message when this method is called.

Note Multicasting is not supported for this release.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::DestroyGroup Method

Deletes a group created by the IDirectPlay8Peer::CreateGroup method. This method can be called by any peer in the session.

Syntax

HRESULT DestroyGroup(

    const DPNID idGroup,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] Variable of type DPNID that should be set to the identifier of the group to be deleted.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNDESTROYGROUP_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::DestroyPeer Method

Deletes a peer from the session.

Syntax

HRESULT DestroyPeer(

    const DPNID dpnidClient,
    void *const pDestroyInfo,
    const DWORD dwDestroyInfoSize,
    const DWORD dwFlags
);

Parameters

dpnidClient
[in] Variable of type DPNID that specifies the identifier of the peer to delete.
pDestroyInfo
[in] Pointer to a value that describes additional delete data information.
dwDestroyInfoSize
[in] Variable of type DWORD that specifies the size of the data contained in the pDestroyInfo parameter.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.

Remarks

A player can only be deleted by the session host. The deleted player will be notified through a DPN_MSGID_TERMINATE_SESSION message. The structure associated with the message will contain the data passed through the pDestroyInfo parameter. If any other session member calls this method, it will fail, and return DPNERR_NOTHOST.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::EnumGroupMembers Method

Retrieves a list of all players in a group.

Syntax

HRESULT EnumGroupMembers(

    const DPNID dpnid,
    DPNID *const prgdpnid,
    DWORD *const pcdpnid,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the group that contains the players to enumerate.
prgdpnid
[out] Pointer to an array that will contain the identifiers of the group's players.
pcdpnid
[in] Pointer to a variable of type DWORD that specifies the number of identifiers that can be contained in the buffer pointed to by dpnid. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

Remarks

Because player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::EnumHosts Method

Enumerates applications that host Microsoft® DirectPlay® games.

Syntax

HRESULT EnumHosts(

    PDPN_APPLICATION_DESC const pApplicationDesc,
    IDirectPlay8Address *const pdpaddrHost,
    IDirectPlay8Address *const pdpaddrDeviceInfo,
    PVOID const pvUserEnumData,
    const DWORD dwUserEnumDataSize,
    const DWORD dwEnumCount,
    const DWORD dwRetryInterval,
    const DWORD dwTimeOut,
    PVOID const pvUserContext,
    HANDLE *const pAsyncHandle,
    const DWORD dwFlags
);

Parameters

pApplicationDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that specifies which application hosts to enumerate. You must set the pApplicationDesc.dwSize member to the appropriate value. To reduce the number of responses, set pApplicationDesc.guidApplication to the globally unique identifier (GUID) of the application to be found. If this member is not set, the search will include all applications.
pdpaddrHost
[in] Pointer to an IDirectPlay8Address object that specifies the address of the computer that is hosting the application. Some service providers allow this parameter to be NULL or be an address object containing only the service provider component. In this case, DirectPlay will get the information by using a broadcast mechanism or from the pdpaddrDeviceInfo parameter. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for any missing address information.
pdpaddrDeviceInfo
[in] Pointer to an IDirectPlay8Address object that specifies the service provider and local device settings to use when enumerating. The user can be queried for any missing address information if you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in the dwFlags parameter.
pvUserEnumData
[in] Pointer to a block of data that is sent in the enumeration request to the host. The size of the data is limited depending on the network type. Call IDirectPlay8Peer::GetSPCaps to obtain the exact value.
dwUserEnumDataSize
[in] Variable of type DWORD that specifies the size of the data pointed at in the pvUserEnumData parameter.
dwEnumCount
[in] Value specifying how many times that the enumeration data will be sent. Set this parameter to zero to use the default value. You can obtain the default value for dwEnumCount by calling IDirectPlay8Peer::GetSPCaps. If dwEnumCount is set to INFINITE, the enumeration will continue until canceled.
dwRetryInterval
[in] Value specifying how many milliseconds between enumeration retries. Set this parameter to zero to use the default value. You can obtain the default value for dwRetryInterval by calling IDirectPlay8Peer::GetSPCaps.
dwTimeOut
[in] Variable of type DWORD that specifies the number of milliseconds that DirectPlay will wait for replies after the last enumeration is sent. Set this parameter to zero to use the default value. You can obtain the default value for dwTimeOut by calling IDirectPlay8Peer::GetSPCaps. If INFINITE is specified, the enumeration continues until it is canceled.
pvUserContext
[in] Context that is provided in the peer's message handler when it is called with responses to the enumeration. This can be useful to differentiate replies from concurrent enumerations.
pAsyncHandle
[out] A DPNHANDLE. When the method returns, pAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNENUMHOSTS_SYNC flag in dwFlags.
dwFlags
[in] The following flags can be set.
DPNENUMHOSTS_SYNC
Causes the method to process synchronously.
DPNENUMHOSTS_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay dialog box, which queries the user for more information if not enough information is passed in this method.
DPNENUMHOSTS_NOBROADCASTFALLBACK
If the service provider supports broadcasting, setting this flag will disable the broadcast capabilities. Check to see if broadcasting is supported by examining the DPN_SP_CAPS structure before setting this flag.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHOSTADDRESS | The specified remote address is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_ENUMQUERYTOOLARGE | The query data specified is too large.
DPNERR_USERCANCEL | The user canceled the operation.

Remarks

When an application is found that meets the enumeration criteria, the application's message handler is called with a DPN_MSGID_ENUM_HOSTS_RESPONSE system message. The message contains a DPN_APPLICATION_DESC structure describing the applications found and IDirectPlay8Address objects identifying the location of the hosts.

To ensure better Network Address Translation (NAT) and proxy support when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider or to prevent redialing with the modem service provider, keep the enumeration active when calling the IDirectPlay8Peer::Connect method. To prevent the enumeration from completing, set the dwEnumCount parameter to INFINITE and do not use the IDirectPlay8Peer::CancelAsyncOperation to terminate the enumeration before the connect operation has completed. You should also pass the pAddressSender and pAddressDevice address objects in the DPNMSG_ENUM_HOSTS_RESPONSE message without modification into the pHostAddr and pDeviceInfo parameters of the IDirectPlay8Peer::Connect method. To pass the address objects to IDirectPlay8Peer::Connect outside of the callback function, use IDirectPlay8Address::Duplicate or IDirectPlay8Address::AddRef to prevent the object from being destroyed and store the pointers using thread-safe code.

Any number of enumerations can be run concurrently. The pvUserContext value is provided in the message handler to help differentiate replies to different enumerations.

Because of the variation in the number of ways enumeration can happen, an application should not attempt to specify dwEnumCount, dwRetryInterval, or dwTimeOut unless the application has some specific media knowledge. The only exception is if you want to have the enumeration continue until explicitly cancelled, then set dwEnumCount to INFINITE.

The default enumeration count and timeout values will cause IDirectPlay8Peer::EnumHosts to complete within a reasonable amount of time. These values are set by the service provider, and can be obtained by calling IDirectPlay8Peer::GetSPCaps. Asynchronous enumerations can be stopped at any time by calling IDirectPlay8Peer::CancelAsyncOperation and either passing the handle returned in the pAsyncHandle parameter or setting the DPNCANCEL_ENUM flag in the dwFlags parameter. An enumeration can also be stopped by returning anything other than S_OK from the message handler when processing a DPN_MSGID_ENUM_HOSTS_RESPONSE message.

You might receive multiple DPN_MSGID_ENUM_HOSTS_RESPONSE messages from the same host during one enumeration session. The guidInstance member of the associated DPN_APPLICATION_DESC structure can be used to correlate these duplicate responses.

If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box or your application will lock.

Data Value Summary specifies the required addressing information for each service provider.

DPNERR_USERCANCEL will be returned if the enumeration is canceled by calling the IDirectPlay8Peer::CancelAsyncOperation method or if DPN_OK is not returned when processing a DPN_MSGID_ENUM_HOSTS_RESPONSE message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::EnumPlayersAndGroups Method

Retrieves a list of all the player and/or group identifiers for the session.

Syntax

HRESULT EnumPlayersAndGroups(

    DPNID *const prgdpnid,
    DWORD *const pcdpnid,
    const DWORD dwFlags
);

Parameters

prgdpnid
[out] Pointer to an array that will be filled with the session's group and/or player identifiers.
pcdpnid
[in] Pointer to a variable of type DWORD that specifies the number of identifiers that can be contained in the buffer pointed to by prgdpnid. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
[in] Flag that describes enumeration behavior. You can set one or both of the following flags.
DPNENUM_PLAYERS
Return a list of player identifiers.
DPNENUM_GROUPS
Return a list of group identifiers.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

Remarks

Because group and player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::EnumServiceProviders Method

Enumerates all the registered service providers available to the application.

Syntax

HRESULT EnumServiceProviders(

    const GUID *const pguidServiceProvider,
    const GUID *const pguidApplication,
    const DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
    DWORD *const pcbEnumData,
    DWORD *const pcReturned,
    const DWORD dwFlags
);

Parameters

pguidServiceProvider
[in] Pointer to a variable of type globally unique identifier (GUID) that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers. Otherwise, set pguidServiceProvider to one of the following predefined values.
CLSID_DP8SP_TCPIP
Internet Protocol (IP) service providers
CLSID_NETWORKSIMULATOR_DP8SP_TCPIP
DP8Sim service providers
CLSID_DP8SP_SERIAL
Serial service providers
CLSID_DP8SP_MODEM
Modem service providers
CLSID_DP8SP_IPX
IPX service providers
pguidApplication
[in] Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected by the application are enumerated. You can also pass NULL to enumerate all the registered service providers for the system.
pSPInfoBuffer
[out] Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
[out] Pointer to DWORD that is filled with the size of the pSPInfoBuffer buffer if the buffer is too small.
pcReturned
[out] Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pcbEnumData array.
dwFlags
[in] The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system, including those that are not available to the application or do not have devices installed.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can then be obtained by passing a pointer to a service provider GUID in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose different modems for dialing out and specific modems for hosting.

If the pcbEnumData buffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the pcbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call it again with the appropriate-sized buffer.

Typically, this method will return only those service providers that can be used by the application. For example, if the Internetwork Packet Exchange (IPX) networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetApplicationDesc Method

Retrieves the full application description for the connected application.

Syntax

HRESULT GetApplicationDesc(

    DPN_APPLICATION_DESC *const pAppDescBuffer,
    DWORD *const pcbDataSize,
    const DWORD dwFlags
);

Parameters

pAppDescBuffer
[out] Pointer to a DPN_APPLICATION_DESC structure where the application description data is to be written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
[in, out] Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.

Remarks

Call this method initially by passing NULL in the pAppDescBuffer parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

The returned DPN_APPLICATION_DESC structure will have the guidInstance, guidApplication, and pwszSessionName members set. It will not contain information about other clients that are connected to the session. That information, if available, can be obtained only from the server application. In particular, the dwCurrentPlayers member will always be set to 0.

To avoid accidentally overwriting the application description, applications should call IDirectPlay8Peer::GetApplicationDesc and fill in the DPN_APPLICATION_DESC structure before calling IDirectPlay8Peer::SetApplicationDesc.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetCaps Method

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT GetCaps(

    DPN_CAPS *const pdpnCaps,
    const DWORD dwFlags
);

Parameters

pdpnCaps
[out] Pointer to a DPN_CAPS or DPN_CAPS_EX structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Peer::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used based on the size of the structure referenced by pdpnCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetConnectionInfo Method

Retrieves statistical information about the connection between the local application and the specified remote player.

Syntax

HRESULT GetConnectionInfo(

    const DPNID dpnidEndPoint,
    DPN_CONNECTION_INFO *const pdnConnectInfo,
    const DWORD dwFlags
);

Parameters

dpnidEndPoint
[in] The DPNID of the remote player whose connection information will be retrieved.
pdnConnectInfo
[out] Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. The dwSize member of this structure must be set to the size of a DPN_CONNECTION_INFO structure.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.

Remarks

This method can be called only after a successful IDirectPlay8Peer::Host or IDirectPlay8Peer::Connect call has completed.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetGroupContext Method

Retrieves the group context value for the specified group.

Syntax

HRESULT GetGroupContext(

    const DPNID dpnid,
    PVOID *const ppvGroupContext,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group to retrieve context data for.
ppvGroupContext
[out] Pointer to the context value of the group.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTREADY | The object is not ready for use.

Remarks

Group context values are set by pointing the pvGroupContext member of the DPN_MSGID_CREATE_GROUP system message to the context value data.

This method returns DPNERR_NOTREADY when it is called before a DPN_MSGID_CREATE_PLAYER message is received by Microsoft® DirectPlay® for the player specified in dpnid. Call IDirectPlay8Peer::GetPlayerContext again allowing task switching so that the thread carrying the message can return.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetGroupInfo Method

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received indicating that the group data has been modified.

Syntax

HRESULT GetGroupInfo(

    const DPNID dpnid,
    DPN_GROUP_INFO *const pdpnGroupInfo,
    DWORD *const pdwSize,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group whose data block will be retrieved.
pdpnGroupInfo
[out] Pointer to a DPN_GROUP_INFO structure that describes the group data. If pdwSize is not set to NULL, you must set pdpnGroupInfo.dwSize to the size of a DPN_GROUP_INFO structure.
pdwSize
[out] Pointer to a variable of type DWORD that returns the size of the data in the pdpnGroupInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
[in] Reserved. Set to 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

Remarks

Microsoft® DirectPlay® returns the DPN_GROUP_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for your structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_GROUP_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetGroupInfo, to notify DirectPlay which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetGroupInfo method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetLocalHostAddresses Method

Retrieves the local addresses being used to host the session.

Syntax

HRESULT GetLocalHostAddresses(

    IDirectPlay8Address **const prgpAddress,
    DWORD *const pcAddress,
    const DWORD dwFlags
);

Parameters

prgpAddress
[out] Pointer to an array of IDirectPlay8Address objects that specify the local host addresses. You must release these objects when you no longer need them, or you will create memory leaks.
pcAddress
[in, out] Maximum number of address objects that can be returned in the array pointed to by prgpAddress. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
[in] The following flag can be specified when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider. This method will return DPNERR_UNSUPPORTED if this flag is used with any other service provider.
DPNGETLOCALHOSTADDRESSES_COMBINED
Return all listening addresses combined into one IDirectPlay8Address object.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_UNSUPPORTED | The function or feature is not available in this implementation or on this service provider.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.

Remarks

The most robust way to use this method is to call it first with pcAddress set to 0. When the method returns, pcAddress will point to the correct value, and you can use that value to call the method a second time to retrieve the information.

If the caller is not the session host, the method returns DPNERR_NOTHOST. Use IDirectPlay8Peer::GetPeerAddress to retrieve the address of a remote player.

If DPNGETLOCALHOSTADDRESSES_COMBINED is specified, the address object returned will contain all listening host addresses. For example, the host might have multiple addresses if it is behind a Network Address Translation (NAT) device or if it has multiple network cards. In this case, players can connect to the host faster if they can try all of the addresses simultaneously. The application must provide its own mechanism for passing the combined address object to the connecting players. One way to do this is by using IDirectPlay8Address::GetURLA or IDirectPlay8Address::GetURLW and IDirectPlay8Address::BuildFromURLA or IDirectPlay8Address::BuildFromURLW to create a string to pass using a Web page or lobby mechanism.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetPeerAddress Method

Retrieves the address for the specified remote player in the session.

Syntax

HRESULT GetPeerAddress(

    const DPNID dpnid,
    IDirectPlay8Address **const pAddress,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID specifying the identification of the player.
pAddress
[out] Address of a pointer to an IDirectPlay8Address object that specifies the address of the peer. You must release this object when you no longer need it.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method cannot be used to retrieve the address of the local player. If the player calls this method on his or her own identifier (ID), it returns a DPNERR_INVALIDPLAYER error message.

Use IDirectPlay8Peer::GetLocalHostAddresses to retrieve addresses that can be used to connect to the session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetPeerInfo Method

Retrieves peer information set for the specified peer.

Syntax

HRESULT GetPeerInfo(

    const DPNID dpnid,
    DPN_PLAYER_INFO *const pdpnPlayerInfo,
    DWORD *const pdwSize,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the peer whose information will be retrieved.
pdpnPlayerInfo
[out] Pointer to a DPN_PLAYER_INFO structure to fill with peer information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to the size of a DPN_PLAYER_INFO structure.
pdwSize
[in, out] Pointer to a variable of type DWORD that contains the size of the peer data returned in the pdpnPlayerInfo parameter. If the buffer is too small this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.
dwFlags
[in] Reserved. Set to 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_CONNECTING | The method is in the process of connecting to the network.

Remarks

Call this method after the peer receives a DPN_MSGID_PEER_INFO message from the application, which indicates a peer has updated their information.

Calling IDirectPlay8Peer::GetPeerInfo before the host has returned from IDirectPlay8Peer::Host will cause this method to fail with DPNERR_CONNECTING. If this happens, try calling IDirectPlay8Peer::GetPeerInfo again.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetPeerInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetPeerInfo method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetPlayerContext Method

Retrieves the player context value for the specified peer.

Syntax

HRESULT GetPlayerContext(

    const DPNID dpnid,
    PVOID *const ppvPlayerContext,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the player to get context data for.
ppvPlayerContext
[out] Pointer to the context data of the peer.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_NOTREADY | The object is not ready for use.

Remarks

Player context values are set by pointing the pvPlayerContext member of the DPN_MSGID_CREATE_PLAYER system message to the context value data.

This method returns DPNERR_NOTREADY when it is called before a DPN_MSGID_CREATE_PLAYER message is received by Microsoft® DirectPlay® for the player specified in dpnid. Call IDirectPlay8Peer::GetPlayerContext again allowing task switching so that the thread carrying the message can return.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetSendQueueInfo Method

Used by the application to monitor the size of the send queue.

Syntax

HRESULT GetSendQueueInfo(

    const DPNID dpnid,
    DWORD *const pdwNumMsgs,
    DWORD *const pdwNumBytes,
    const DWORD dwFlags
);

Parameters

dpnid
[in] DPNID of the player to get send queue information for.
pdwNumMsgs
[out] Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and can be set to NULL.
pdwNumBytes
[out] Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and can be set to NULL.
dwFlags
[in] You can specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

Remarks

Microsoft® DirectPlay® will not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should slow the rate that messages are sent.

You cannot set both pdwNumMsgs and pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::GetSPCaps Method

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT GetSPCaps(

    const GUID *const pguidSP,
    DPN_SP_CAPS *const pdpnSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) specifying the service provider you want to get information about.
pdpnSPCaps
[out] Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member of the structure.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method retrieves information about the specified service provider. A successful call to IDirectPlay8Peer::Initialize must be made before this method can be called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::Host Method

Creates a new peer-to-peer session, hosted by the local computer.

Syntax

HRESULT Host(

    const DPN_APPLICATION_DESC *const pdnAppDesc,
    IDirectPlay8Address **const prgpDeviceInfo,
    const DWORD cDeviceInfo,
    const DPN_SECURITY_DESC *const pdpSecurity,
    const DPN_SECURITY_CREDENTIALS *const pdpCredentials,
    VOID *const pvPlayerContext,
    const DWORD dwFlags
);

Parameters

pdnAppDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application.
prgpDeviceInfo
[in] Pointer to an array of IDirectPlay8Address objects containing the device addresses that should be used to host the application. You must release these objects when you no longer need them.
cDeviceInfo
[in] Variable of type DWORD that specifies the number of device address objects in the array pointed to by prgpDeviceInfo.
pdpSecurity
[in] Reserved. Must be NULL.
pdpCredentials
[in] Reserved. Must be NULL.
pvPlayerContext
[in] Pointer to the context value of the local player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional and may be set to NULL.
dwFlags
[in] The following flag can be specified.
DPNHOST_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_DATATOOLARGE | The application data is too large for the service provider's Maximum Transmission Unit.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDDEVICEADDRESS | The address for the local computer or adapter is invalid.
DPNERR_DPNSVRNOTAVAILABLE | Port 6073 is already in use.

Remarks

Do not set the guidInstance member of the DPN_APPLICATION_DESC structure when calling IDirectPlay8Peer::Host because DirectPlay will ignore any value passed in and determine its own globally unique identifier (GUID). The only way to retrieve the guidInstance is by calling IDirectPlay8Peer::GetApplicationDesc.

If you set the DPNHOST_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Data Value Summary specifies the required addressing information for each service provider.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::Initialize Method

Registers an entry point in the peer's code that receives all the messages from the IDirectPlay8Peer interface and from remote peers. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    PVOID const pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value in calls to the message handler. A user-provided context value can be used to differentiate messages coming from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that is used to receive all messages from remote peers and indications of session changes from the IDirectPlay8Peer interface.
dwFlags
[in] You can specify the following flags.
DPNINITIALIZE_DISABLEPARAMVAL
Passing this flag will disable parameter validation for the current object.
DPNINITIALIZE_HINT_LANSESSION
Opens a larger send window for games running on a local area network (LAN).
DPNINITIALIZE_DISABLELINKTUNING
Disable any attempts by Microsoft® DirectPlay® to tune the rate it sends at to the observed network conditions. Messages will be pushed out onto the network at the first available opportunity.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8Peer interface.

Specify the DPNINITIALIZE_HINT_LANSESSION flag for sessions where all players will be on the same LAN.

Applications might want to specify the DPNINITIALIZE_DISABLELINKTUNING flag when they send at a fixed rate and do not alter the rate based on the network conditions. With this flag specified, DirectPlay will always assume the network has the capacity to carry all the application data and will therefore not attempt to tune its send rate to the network bandwidth. Specifying this flag and then sending at a rate that exceeds the capacity of the network will lead to unpredictable network behavior such as higher latency and increased packet drop rates. Applications that monitor the send queues and dynamically adjust their send rate to make best use of the available bandwidth should not specify this flag.

If the DPNINITIALIZE_DISABLELINKTUNING flag is specified, DirectPlay features such as message prioritization, coalescence, and timeout are not useful because messages always go directly to the network and are not queued.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::RegisterLobby Method

Allows launched applications to automatically propagate game status to the lobby.

Syntax

HRESULT RegisterLobby(

    const DPNHANDLE dpnHandle,
    IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
    const DWORD dwFlags
);

Parameters

dpnHandle
[in] The connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
[in] Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
[in] One of the following flags:
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::RemovePlayerFromGroup Method

Removes a peer from a group.

When this method is called all peers connected to the application receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message.

Syntax

HRESULT RemovePlayerFromGroup(

    const DPNID idGroup,
    const DPNID idClient,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] Variable of type DPNID that specifies the identifier of the group that the peer will be removed from.
idClient
[in] Variable of type DPNID that specifies the identifier of the peer that will be removed from the group.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNREMOVEPLAYERFROMGROUP_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_PLAYERNOTINGROUP | The player ID is not included in the group.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::ReturnBuffer Method

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes that ownership of the buffer is transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

Syntax

HRESULT ReturnBuffer(

    const DPNHANDLE hBufferHandle,
    const DWORD dwFlags
);

Parameters

hBufferHandle
[in] Variable of type DPNHANDLE that specifies the buffer handle to the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SendTo Method

Transmits data to another peer or group within the session by sending a message to the appropriate message handlers. The message can be sent synchronously or asynchronously.

Syntax

HRESULT SendTo(

    const DPNID dpnid,
    const DPN_BUFFER_DESC *const pBufferDesc,
    const DWORD cBufferDesc,
    const DWORD dwTimeOut,
    void *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Identifier of the peer or group that receives data. Set this parameter to DPNID_ALL_PLAYERS_GROUP to send a message to all players in the session.
pBufferDesc
[in] Pointer to a DPN_BUFFER_DESC structure that contains the data to be sent.
cBufferDesc
[in] Number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can be up to eight buffers in this version of Microsoft® DirectPlay®.
dwTimeOut
[in] Number of milliseconds to wait for the message to send. If the message has not been sent by the dwTimeOut value, it is deleted from the send queue. If you set this parameter to 0, the message remains in the send queue until it is sent or until the link is dropped.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message. This parameter is optional and can be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
[in] Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the IDirectPlay8Peer::SendTo request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This can be a more efficient method of sending data. However, it is less robust because modifying or deleting the data before receiving the DPN_MSGID_SEND_COMPLETE message can cause erroneous data to be sent. This flag cannot be combined with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Does not send the DPN_MSGID_SEND_COMPLETE to the message handler. This flag cannot be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag the pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Sends the DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process might become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Sends the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NONSEQUENTIAL
If this flag is set, the target application will receive the messages in the order that they arrive at the user's computer. If this flag is not set, messages are delivered sequentially, and will be received by the target application in the order that they were sent. Doing so might require buffering incoming messages until missing messages arrive.
DPNSEND_NOLOOPBACK
Suppresses the DPN_MSGID_RECEIVE system message to your message handler when you are sending to a group that includes the local player. For example, this flag is useful if you are broadcasting to the entire session.
DPNSEND_COALESCE
Allows DirectPlay to combine packets when sending.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_CONNECTIONLOST | The service provider connection was reset while data was being sent.
DPNERR_GENERIC | An undefined error condition occurred.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_TIMEDOUT | The operation could not complete because it has timed out.

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the receiver's message handler. The data buffer is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message, set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. See Basic Networking for a discussion of send priorities.

When the IDirectPlay8Peer::SendTo request is completed, a DPN_MSGID_SEND_COMPLETE system message is normally posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associated structure. You can suppress send completions by setting the DPNSEND_NOCOMPLETE flag in dwFlags.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It might still be in a queue. If you want to be certain that the message has been processed by the target, set the DPNSEND_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message and returned.

If the DPNSEND_COALESCE flag is set in dwFlags, DirectPlay will try to coalesce up to 32 packets waiting in the queue into the outgoing frame. DirectPlay does not guarantee coalescence, even if the DPNSEND_COALESCE flag is set. Packets will only be coalesced if there is more than one message in the queue and the player receiving is running Microsoft DirectX® 9.0 or later. All voice packets can be coalesced. Both guaranteed and non-guaranteed packets will be coalesced into the same frame. If the frame is dropped before it reaches its destination, only the guaranteed parts of the frame will be resent and no other data will be coalesced into the frame.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message can be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource can become invalid at any time after the method has been called.

This method returns a DPNERR_GENERIC error value if the send computer is host with no other player connected and DPNSEND_SYNC and DPNSEND_NOLOOPBACK flags are set.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SetApplicationDesc Method

Changes the settings for the application that is being hosted. Only some settings can be changed.

Syntax

HRESULT SetApplicationDesc(

    const DPN_APPLICATION_DESC *const pad,
    const DWORD dwFlags
);

Parameters

pad
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application settings to modify.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_DATATOOLARGE | The application data is too large for the service provider's Maximum Transmission Unit.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC structure.

  • dwMaxPlayers
  • pwszSessionName
  • pwszPassword
  • pvApplicationReservedData
  • dwApplicationReservedDataSize

When IDirectPlay8Peer::SetApplicationDesc is called, Microsoft® DirectPlay® makes a copy of the data pad points to. You do not need to save the DPN_APPLICATION_DESC structure once IDirectPlay8Peer::SetApplicationDesc returns.

You cannot set the dwMaxPlayers member to a smaller value than the current number of players in the session.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

To avoid accidentally overwriting the application description, applications should call IDirectPlay8Peer::GetApplicationDesc and fill in the DPN_APPLICATION_DESC structure before calling IDirectPlay8Peer::SetApplicationDesc.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SetCaps Method

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT SetCaps(

    const DPN_CAPS *const pdpCaps,
    const DWORD dwFlags
);

Parameters

pdpCaps
[in] Pointer to a DPN_CAPS or DPN_CAPS_EX structure used to set the information about the current interface.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Peer::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used based on the size of the structure referenced by pdpCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SetGroupInfo Method

Sets a block of data associated with a group, including the name of the group.

Calling this method generates a DPN_MSGID_GROUP_INFO message, which is sent to all the peers connected to the application.

Syntax

HRESULT SetGroupInfo(

    const DPNID dpnid,
    DPN_GROUP_INFO *const pdpnGroupInfo,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group whose data block will be modified.
pdpnGroupInfo
[in] Pointer to a DPN_GROUP_INFO structure that describes the group data to set. To change the values of the pwszName or pvData members, you must set the corresponding DPNINFO_NAME or DPNINFO_DATA flags in the dwInfoFlags member.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method:
DPNSETGROUPINFO_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

Remarks

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetGroupInfo method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SetPeerInfo Method

Sets the static settings of the local peer. Call this method before connecting to relay basic player information with the application. When the peer successfully connects with the application, information set through this method can be retrieved by other players by calling the IDirectPlay8Peer::GetPeerInfo method.

Syntax

HRESULT SetPeerInfo(

    const DPN_PLAYER_INFO *const pdpnPlayerInfo,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
[in] Pointer to a DPN_PLAYER_INFO structure that contains the peer information to set.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETPEERINFO_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.

Remarks

This method can be called at any time during the session.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetPeerInfo method.

The DPN_PLAYER_INFO structure's dwPlayerFlags member must be set to zero.

You can modify the peer information with this method after connecting to the application. Calling this method after connection generates a DPN_MSGID_PEER_INFO system message to all players, informing them that data has been updated. The dwPlayerFlags method in the DPN_PLAYER_INFO structure must be set to 0 when making this call.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::SetSPCaps Method

Sets the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT SetSPCaps(

    const GUID *const pguidSP,
    const DPN_SP_CAPS *const pdpSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) that specifies the service provider to set information about.
pdpSPCaps
[in] Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Peer::Initialize must be made before this method can be called. Currently, only the dwSystemBufferSize member can be set by this call. The dwNumThreads member is for legacy support. Microsoft DirectX® 9.0 applications should use the IDirectPlay8ThreadPool::SetThreadCount method to set the number of threads. The other members of the DPN_SP_CAPS structure are get-only or ignored.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Peer::TerminateSession Method

Terminates the current Microsoft® DirectPlay® session.

Syntax

HRESULT TerminateSession(

    void *const pvTerminateData,
    const DWORD dwTerminateDataSize,
    const DWORD dwFlags
);

Parameters

pvTerminateData
[in] Pointer to termination data. This data is also sent in the pvTerminateData member of the DPN_MSGID_TERMINATE_SESSION system message.
dwTerminateDataSize
[in] Size of data contained in the pvTerminateData parameter.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or an error value otherwise.

Remarks

This method may be called only by the host player.

This method terminates the session even if host migration is enabled. To close the host player's connection to the session and allow host migration to take place, call IDirectPlay8Peer::Close instead.

When this method is called, the DPN_MSGID_TERMINATE_SESSION will be sent to the message handler of each player in the session.

Players should call IDirectPlay8Peer::Close after receiving the DPN_MSGID_TERMINATE_SESSION message to uninitialize the IDirectPlay8Peer object.

See Also

Host Migration, Leaving a Peer-to-Peer Session, Terminating a Peer-to-Peer Session

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server Interface

Applications use the methods of the IDirectPlay8Server interface to create and manage the server for a Microsoft® DirectPlay® client/server transport session.

IDirectPlay8Server Members

AddPlayerToGroup Adds a client to a group. After the client is successfully added to the group, all messages sent to the group are sent to the client.
CancelAsyncOperation

Cancels asynchronous requests. Many methods of the IDirectPlay8Server interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can be run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

Close

Closes the open connection to a session and uninitializes the IDirectPlay8Server object.

CreateGroup

Creates a group in the current session. When this method is called, the server's message handler receives a DPN_MSGID_CREATE_GROUP message.

DestroyClient

Deletes a client from the session.

DestroyGroup

Deletes a group created by the IDirectPlay8Server::CreateGroup method.

EnumGroupMembers

Retrieves a list of all players in a group.

EnumPlayersAndGroups

Retrieves a list of all the player and/or group identifiers for the application.

EnumServiceProviders

Enumerates the registered service providers available to the application.

GetApplicationDesc

Retrieves the full application description for the connected application.

GetCaps

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

GetClientAddress

Retrieves the address for the specified player in the session.

GetClientInfo

Retrieves the client information set for the specified client.

GetConnectionInfo

Retrieves statistical information about the connection between the local server and the specified remote client.

GetGroupContext

Retrieves the group context value for a group.

GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received, indicating that the group data has been modified.

GetLocalHostAddresses

Retrieves the local addresses being used to host the session.

GetPlayerContext

Retrieves the player context value for a client.

GetSendQueueInfo

Used by the application to monitor the size of the send queue. DirectPlay does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should slow the rate that messages are sent.

GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Host

Creates a new client/server session, hosted by the local computer.

Initialize

Registers an entry point in the server's code that receives the messages from the IDirectPlay8Server interface and from remote clients. This method must be called before calling any other methods of this interface.

RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

RemovePlayerFromGroup

Removes a client from a group.

ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, DirectPlay assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

SendTo

Transmits data to a client or group within the session. The message can be sent synchronously or asynchronously.

SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

SetCaps

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

SetServerInfo

Sets the static settings of a server with an application. After clients successfully connect to the server, they can retrieve the information set by this method by calling theIDirectPlay8Client::GetServerInfo method.

SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

Interface Information

Inherits from | IUnknown
Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::AddPlayerToGroup Method

Adds a client to a group. After the client is successfully added to the group, all messages sent to the group are sent to the client.

Syntax

HRESULT AddPlayerToGroup(

    const DPNID idGroup,
    const DPNID idClient,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] Variable of type DPNID that specifies the identifier of the group to add the client to.
idClient
[in] Variable of type DPNID that specifies the identifier of the client to add to the group.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and can be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNADDPLAYERTOGROUP_SYNC
Causes this method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_PLAYERALREADYINGROUP | The player ID is already included in the group.

Remarks

The server can add itself or a client to an existing group. After a player is successfully added to a group, all messages sent to the group will be received by the player.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::CancelAsyncOperation Method

Cancels asynchronous requests. Many methods of the IDirectPlay8Server interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can be run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

Syntax

HRESULT CancelAsyncOperation(

    const DPNHANDLE hAsyncHandle,
    const DWORD dwFlags
);

Parameters

hAsyncHandle
[in] Handle of the asynchronous operation to stop. This value can be NULL to stop all requests or a particular type of asynchronous request. If a specific handle is specified, the dwFlags parameter must be 0. You will receive this handle when you call one of several methods that support asynchronous operations. If one of the DPNCANCEL_PLAYER_SENDS flags is specified in the dwFlags parameter, hAsyncHandle must be set to a player's DPNID.
dwFlags
[in] Flag that specifies which asynchronous request to cancel. You can set one of the following flags.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Server::SendTo request.
DPNCANCEL_PLAYER_SENDS
Cancel all asynchronous IDirectPlay8Server::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_LOW
Cancel low-priority asynchronous IDirectPlay8Server::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_NORMAL
Cancel normal-priority asynchronous IDirectPlay8Server::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_PLAYER_SENDS_PRIORITY_HIGH
Cancel high-priority asynchronous IDirectPlay8Server::SendTo requests for the player specified in the hAsyncHandle parameter.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous requests.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL | The operation could not be canceled.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNSUCCESS_PENDING | An asynchronous operation has reached the point where it is successfully queued.

Remarks

You can use this method to cancel an asynchronous operation for the IDirectPlay8Server::SendTo method. Microsoft® DirectPlay® does not support cancellation of other asynchronous operations.

You can cancel a IDirectPlay8Server::SendTo request by providing the handle returned from IDirectPlay8Server::SendTo method. A DPN_MSGID_SEND_COMPLETE system message is still posted to the applications message handler for each asynchronous IDirectPlay8Server::SendTo request that is sent without the DPNSEND_NOCOMPLETE flag set. Send requests that are canceled by this method return DPNERR_USERCANCEL in their hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS or DPNCANCEL_SEND flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

If you set one of the DPNCANCEL_PLAYER_SENDS flags in dwFlags, you must specify a player's DPNID in hAsyncHandle. This will cancel all pending IDirectPlay8Server::SendTo requests where the DPNID specified in the dpnid parameter matches the value set in the hAsyncHandle parameter.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::Close Method

Closes the open connection to a session and uninitializes the IDirectPlay8Server object.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] The following flag can be specified.
DPNCLOSE_IMMEDIATE
Close immediately. Do not wait for outstanding calls to complete.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED The requested object has not been initialized.

Remarks

This method must be called on any object successfully initialized with IDirectPlay8Server::Initialize.

This method is a counterpart to IDirectPlay8Server::Host. It closes all active network connections hosted by the server. This method is synchronous, and will not return until the server has processed all DPN_MSGID_DESTROY_PLAYER messages. This feature guarantees that when IDirectPlay8Server::Close returns, you can safely shut down the server application.

Calling IDirectPlay8Server::Close will cancel all outstanding operations, including guaranteed messages that are in the queue waiting to be sent. Messages that have already been sent as guaranteed will continue to be retried until acknowledgement of their delivery has been received. To make sure all messages are sent, wait for all outstanding IDirectPlay8Server::SendTo calls to complete before calling IDirectPlay8Server::Close.

Calling IDirectPlay8Server::Close will invalidate any DPN_CAPS, DPN_CAPS_EX, and DPN_SP_CAPS associated with the IDirectPlay8Server object.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::CreateGroup Method

Creates a group in the current session. When this method is called, the server's message handler receives a DPN_MSGID_CREATE_GROUP message.

Syntax

HRESULT CreateGroup(

    const DPN_GROUP_INFO const *const pdpnGroupInfo,
    VOID *const pvGroupContext,
    VOID *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdpnGroupInfo
[in] Pointer to a DPN_GROUP_INFO structure that contains the group description.
pvGroupContext
[in] Pointer to the context value for the group. This value is preset when the local application's message handler processes the DPN_MSGID_CREATE_GROUP message. This parameter is optional and may be set to NULL.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNCREATEGROUP_SYNC
Causes this method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or the following error value.

DPNERR_INVALIDFLAGS The flags passed to this method are invalid.

Remarks

DirectPlay does not maintain hierarchical groups because these can easily be implemented with flat groups and expeditious use of the group data.

Note Multicasting is not supported for this release.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::DestroyClient Method

Deletes a client from the session.

Syntax

HRESULT DestroyClient(

    const DPNID dpnidClient,
    const VOID *const pDestroyInfo,
    const DWORD dwDestroyInfoSize,
    const DWORD dwFlags
);

Parameters

dpnidClient
[in] Variable of type DPNID that specifies the identifier of the client to delete.
pDestroyInfo
[in] Pointer that describes additional delete data information.
dwDestroyInfoSize
[in] Variable of type DWORD that specifies the size of the data in the pDestroyInfo parameter.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_NOTHOST | The client attempted to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tried to set the application description.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::DestroyGroup Method

Deletes a group created by the IDirectPlay8Server::CreateGroup method.

Syntax

HRESULT DestroyGroup(

    const DPNID idGroup,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] DPNID of the group to delete.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNDESTROYGROUP_SYNC
Causes the method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::EnumGroupMembers Method

Retrieves a list of all players in a group.

Syntax

HRESULT EnumGroupMembers(

    const DPNID dpnid,
    DPNID *const prgdpnid,
    DWORD *const pcdpnid,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the group that contains the players to enumerate.
prgdpnid
[out] Pointer to an array that contains the identifiers of the group's players.
pcdpnid
[in, out] Pointer to a variable of type DWORD that contains the number of player identifiers in the prgdpnid parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter is set to the number of entries that are required.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::EnumPlayersAndGroups Method

Retrieves a list of all the player and/or group identifiers for the application.

Syntax

HRESULT EnumPlayersAndGroups(

    DPNID *const prgdpnid,
    DWORD *const pcdpnid,
    const DWORD dwFlags
);

Parameters

prgdpnid
[out] Pointer to an array that will be filled with the session's group and/or player identifiers.
pcdpnid
[in, out] Pointer to a variable of type DWORD that specifies the number of identifiers in the prgdpnid parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
[in] Flag that describes enumeration behavior. You can set one or both of the following flags.
DPNENUM_PLAYERS
Return a list of player identifiers.
DPNENUM_GROUPS
Return a list of group identifiers.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.

Remarks

Because group and player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::EnumServiceProviders Method

Enumerates the registered service providers available to the application.

Syntax

HRESULT EnumServiceProviders(

    const GUID *const pguidServiceProvider,
    const GUID *const pguidApplication,
    DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
    PDWORD const pcbEnumData,
    PDWORD const pcReturned,
    const DWORD dwFlags
);

Parameters

pguidServiceProvider
[in] Pointer to a variable of type globally unique identifier (GUID) that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers. Otherwise, set pguidServiceProvider to one of the following predefined values.
CLSID_DP8SP_TCPIP
Internet Protocol (IP) service providers
CLSID_NETWORKSIMULATOR_DP8SP_TCPIP
DP8Sim service providers
CLSID_DP8SP_SERIAL
Serial service providers
CLSID_DP8SP_MODEM
Modem service providers
CLSID_DP8SP_IPX
IPX service providers
pguidApplication
[in] Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected to the application are enumerated. You can also pass NULL to enumerate the registered service providers for the system.
pSPInfoBuffer
[out] Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
[out] Pointer to DWORD, which is filled with the size of the pSPInfoBuffer buffer if the buffer is too small.
pcReturned
[out] Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pcbEnumData array.
dwFlags
[in] The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system including those that are not available to the application or do not have devices installed.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can be obtained by passing a pointer to a specific service provider GUID in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose between different modems for dialing out and select specific modems for hosting.

If the pcbEnumData buffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the pcbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call the method again with the appropriate sized buffer.

Normally, this method will return only those service providers that can be used by the application. For example, if the Internetwork Packet Exchange (IPX) networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetApplicationDesc Method

Retrieves the full application description for the connected application.

Syntax

HRESULT GetApplicationDesc(

    DPN_APPLICATION_DESC *const pAppDescBuffer,
    DWORD *const pcbDataSize,
    const DWORD dwFlags
);

Parameters

pAppDescBuffer
[out] Pointer to a DPN_APPLICATION_DESC structure where the application description data is to be written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
[in, out] Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.

Remarks

Call this method initially by passing NULL in the pcbDataSize parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

To avoid accidentally overwriting the application description, applications should call IDirectPlay8Server::GetApplicationDesc and fill in the DPN_APPLICATION_DESC structure before calling IDirectPlay8Server::SetApplicationDesc.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetCaps Method

Retrieves the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT GetCaps(

    DPNCAPS *const pdpnCaps,
    const DWORD dwFlags
);

Parameters

pdpnCaps
[out] Pointer to a DPN_CAPS or DPN_CAPS_EX structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Server::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used, based on the size of the structure referenced by pdpnCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetClientAddress Method

Retrieves the address for the specified player in the session.

Syntax

HRESULT GetClientAddress(

    const DPNID dpnid,
    IDirectPlay8Address **const pAddress,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID specifying the identification of the player.
pAddress
[out] Address of a pointer to an IDirectPlay8Address object that specifies the address of the client. You must release this object when you no longer need it.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

Use the IDirectPlay8Server::GetLocalHostAddresses method to retrieve addresses that can be used to connect to the session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetClientInfo Method

Retrieves the client information set for the specified client.

Syntax

HRESULT GetClientInfo(

    const DPNID dpnid,
    DPN_PLAYER_INFO *const pdpnPlayerInfo,
    DWORD *const pdwSize,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the client to retrieve the information for.
pdpnPlayerInfo
[out] Pointer to a DPN_PLAYER_INFO structure that is filled with client information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to an appropriate value.
pdwSize
[in, out] Pointer to a variable of type DWORD that contains the size of the client data returned in the pdpnPlayerInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.
dwFlags
[in] Flags describing the information returned for the client. Currently, both of the following flags are returned.
DPNINFO_NAME
The DPN_PLAYER_INFO structure contains the name set for the client.
DPNINFO_DATA
The DPN_PLAYER_INFO structure contains the data set for the client.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.

Remarks

Call this method after the server receives a DPN_MSGID_CLIENT_INFO message from the application. This message indicates that a client has updated its information.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Client::SetClientInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Client::Send method because of the high cost of using the IDirectPlay8Peer::SetPeerInfo method.

The player sets the information by calling IDirectPlay8Client::SetClientInfo.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetConnectionInfo Method

Retrieves statistical information about the connection between the local server and the specified remote client.

Syntax

HRESULT GetConnectionInfo(

    const DPNID dpnidEndPoint,
    DPN_CONNECTION_INFO *const pdnConnectInfo,
    const DWORD dwFlags
);

Parameters

dpnidEndPoint
[in] DPNID of the player whose connection information will be retrieved.
pdnConnectInfo
[out] Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. The dwSize member of this structure must be set to the size of a DPN_CONNECTION_INFO structure.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method can be called only after a successful IDirectPlay8Server::Host call has completed.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetGroupContext Method

Retrieves the group context value for a group.

Syntax

HRESULT GetGroupContext(

    const DPNID dpnid,
    PVOID *const ppvGroupContext,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group to get context data for.
ppvGroupContext
[out] Pointer to the context value of the group.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTREADY | The object is not ready for use.

Remarks

Group context values are set by pointing the pvGroupContext member of the DPN_MSGID_CREATE_GROUP system message to the context value data.

This method returns DPNERR_NOTREADY when it is called before a DPN_MSGID_CREATE_GROUP message is received by Microsoft® DirectPlay® for the group specified in dpnid. Call IDirectPlay8Server::GetGroupContext again allowing task switching so that the thread carrying the message can return.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetGroupInfo Method

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received, indicating that the group data has been modified.

Syntax

HRESULT GetGroupInfo(

    const DPNID dpnid,
    DPN_GROUP_INFO *const pdpnGroupInfo,
    DWORD *const pdwSize,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group whose data block will be retrieved.
pdpnGroupInfo
[out] Pointer to a DPN_GROUP_INFO structure that describes the group data. If pdwSize is not set to NULL, you must set pdpnGroupInfo.dwSize to the size of a DPN_GROUP_INFO structure.
pdwSize
[in, out] Pointer to a variable of type DWORD that returns the size of the data in the pdpnGroupInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
[in] Flags describing the information returned for the group. Currently, both of the following flags are returned.
DPNINFO_NAME
The DPN_PLAYER_INFO structure contains the name set for the client.
DPNINFO_DATA
The DPN_PLAYER_INFO structure contains the data set for the client.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

Remarks

Microsoft® DirectPlay® returns the DPN_GROUP_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetLocalHostAddresses Method

Retrieves the local addresses being used to host the session.

Syntax

HRESULT GetLocalHostAddresses(

    IDirectPlay8Address **const prgpAddress,
    DWORD *const pcAddress,
    const DWORD dwFlags
);

Parameters

prgpAddress
[out] Address of a pointer to an array of IDirectPlay8Address objects that specify the local host addresses. You must release these objects when you no longer need them or you will create memory leaks.
pcAddress
[in, out] Maximum number of address objects that can be contained in the array pointed to by prgpAddress. If the buffer is too small, the method returns DPNERR_BUFFERTOOSMALL, and pcAddress will be set to the required value.
dwFlags
[in] The following flag can be specified when using the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider. This method will return DPNERR_UNSUPPORTED if this flag is used with any other service provider.
DPNGETLOCALHOSTADDRESSES_COMBINED
Return all listening addresses combined into one IDirectPlay8Address object.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_UNSUPPORTED | The function or feature is not available in this implementation or on this service provider.

Remarks

The most robust way to use this method is to first call it with pcAddress set to 0. When the method returns, pcAddress will point to the required value. You can use that value when you call the method for a second time to retrieve the information.

If DPNGETLOCALHOSTADDRESSES_COMBINED is specified, the address object returned will contain all listening server addresses. For example, the server might have multiple addresses if it is behind a Network Address Translation (NAT) device or if it has multiple network cards. In this case, players can connect to the server faster if they can try all of the addresses simultaneously. The application must provide its own mechanism for passing the combined address object to the connecting players. One way to do this is by using IDirectPlay8Address::GetURLA or IDirectPlay8Address::GetURLW and IDirectPlay8Address::BuildFromURLA or IDirectPlay8Address::BuildFromURLW to create a string to pass using a Web page or lobby mechanism.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetPlayerContext Method

Retrieves the player context value for a client.

Syntax

HRESULT GetPlayerContext(

    const DPNID dpnid,
    PVOID *const ppvPlayerContext,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the player to get context data for.
ppvPlayerContext
[out] Pointer to the context data of the client.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_NOTREADY | The object is not ready for use.

Remarks

Player context values are set by pointing the pvPlayerContext member of the DPN_MSGID_CREATE_PLAYER system message to the context value data.

This method returns DPNERR_NOTREADY when it is called before a DPN_MSGID_CREATE_PLAYER message is received by Microsoft® DirectPlay® for the player specified in dpnid. Call IDirectPlay8Server::GetPlayerContext again allowing task switching so that the thread carrying the message can return.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetSendQueueInfo Method

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should slow the rate that messages are sent.

Syntax

HRESULT GetSendQueueInfo(

    const DPNID dpnid,
    DWORD *const pdwNumMsgs,
    DWORD *const pdwNumBytes,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the player to get the send-queue information for.
pdwNumMsgs
[out] Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and may be set to NULL.
pdwNumBytes
[out] Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and may be set to NULL.
dwFlags
[in] You may specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

Remarks

You cannot set both pdwNumMsgs and pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::GetSPCaps Method

Retrieves the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT GetSPCaps(

    const GUID *const pguidSP,
    DPN_SP_CAPS *const pdpnSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) specifying the service provider you want to get information about.
pdpnSPCaps
[out] Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member of this structure to an appropriate value.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method retrieves information about the specified service provider. A successful call to IDirectPlay8Server::Initialize must be made before this method can be called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::Host Method

Creates a new client/server session, hosted by the local computer.

Syntax

HRESULT Host(

    const DPN_APPLICATION_DESC *const pdnAppDesc,
    IDirectPlay8Address **const prgpDeviceInfo,
    const DWORD cDeviceInfo,
    const DPN_SECURITY_DESC *const pdpSecurity,
    const DPN_SECURITY_CREDENTIALS *const pdpCredentials,
    VOID *const pvPlayerContext,
    const DWORD dwFlags
);

Parameters

pdnAppDesc
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application.
prgpDeviceInfo
[in] Pointer to an array of IDirectPlay8Address objects containing device addresses that should be used to host the application.
cDeviceInfo
[in] Variable of type DWORD that specifies the number of device address objects in the array pointed to by prgpDeviceInfo.
pdpSecurity
[in] Reserved. Must be set to NULL.
pdpCredentials
[in] Reserved. Must be set to NULL.
pvPlayerContext
[in] Pointer to the context value of the player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional, and may be set to NULL.
dwFlags
[in] The following flag can be specified.
DPNHOST_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_DATATOOLARGE | The application data is too large for the service provider's Maximum Transmission Unit.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_DPNSVRNOTAVAILABLE | Port 6073 is already in use.

Remarks

Do not set the guidInstance member of the DPN_APPLICATION_DESC structure when calling IDirectPlay8Server::Host because DirectPlay will ignore any value passed in and determine its own globally unique identifier (GUID). The only way to retrieve the guidInstance is by calling IDirectPlay8Server::GetApplicationDesc.

If you set the DPNHOST_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider might attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Data Value Summary specifies the required addressing information for each service provider.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::Initialize Method

Registers an entry point in the server's code that receives the messages from the IDirectPlay8Server interface and from remote clients. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    PVOID const pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] Pointer to the user-provided context value in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from remote clients and indications of session changes from the IDirectPlay8Server interface.
dwFlags
[in] You can specify the following flags.
DPNINITIALIZE_DISABLEPARAMVAL
Passing this flag will disable parameter validation for the current object.
DPNINITIALIZE_HINT_LANSESSION
Opens a larger send window for games running on a local area network (LAN).
DPNINITIALIZE_DISABLELINKTUNING
Disable any attempts by Microsoft® DirectPlay® to tune the rate it sends at to the observed network conditions. Messages will be pushed out onto the network at the first available opportunity.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8Server interface.

Applications might want to specify the DPNINITIALIZE_DISABLELINKTUNING flag when they send at a fixed rate and do not alter the rate based on the network conditions. With this flag specified, DirectPlay will always assume the network has the capacity to carry all the application data and will therefore not attempt to tune its send rate to the network bandwidth. Specifying this flag and then sending at a rate that exceeds the capacity of the network will lead to unpredictable network behavior such as higher latency and increased packet drop rates. Applications that monitor the send queues and dynamically adjust their send rate to make best use of the available bandwidth should not specify this flag.

If the DPNINITIALIZE_DISABLELINKTUNING flag is specified, DirectPlay features such as message prioritization, coalescence, and timeout are not useful because messages always go directly to the network and are not queued.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::RegisterLobby Method

Allows launched applications to automatically propagate game status to the lobby.

Syntax

HRESULT RegisterLobby(

    const DPNHANDLE dpnHandle,
    IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
    const DWORD dwFlags
);

Parameters

dpnHandle
[in] Connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
[in] Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
[in] One of the following flags.
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Value

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::RemovePlayerFromGroup Method

Removes a client from a group.

Syntax

HRESULT RemovePlayerFromGroup(

    const DPNID idGroup,
    const DPNID idClient,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

idGroup
[in] Variable of type DPNID that specifies the identifier of the group to remove the client from.
idClient
[in] Variable of type DPNID that specifies the identifier of the client to remove from the group.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNREMOVEPLAYERFROMGROUP_SYNC
Causes this method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_PLAYERNOTINGROUP | The player ID is not included in the group.

Remarks

When this method is called, the server's message handler receives a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::ReturnBuffer Method

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

Syntax

HRESULT ReturnBuffer(

    const DPNHANDLE hBufferHandle,
    const DWORD dwFlags
);

Parameters

hBufferHandle
[in] Variable of type DPNHANDLE that specifies the buffer handle to the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE | The handle specified is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SendTo Method

Transmits data to a client or group within the session. The message can be sent synchronously or asynchronously.

Syntax

HRESULT SendTo(

    const DPNID dpnid,
    const DPN_BUFFER_DESC *const pBufferDesc,
    const DWORD cBufferDesc,
    const DWORD dwTimeOut,
    void *const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Identifier of the client or group to receive data. Set this parameter to DPNID_ALL_PLAYERS_GROUP to send a message to all players in the session.
pBufferDesc
[in] Pointer to a DPN_BUFFER_DESC structure that describes the data to send.
cBufferDesc
[in] Number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can be up to eight buffers in this version of Microsoft® DirectPlay®.
dwTimeOut
[in] Number of milliseconds to wait for the message to send. If the message has not been sent by the dwTimeOut value, it is deleted from the send queue. If you set this parameter to 0, the message remains in the send queue until it is sent or until the link is dropped.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Server::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
[in] Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the IDirectPlay8Server::SendTo request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This can be a more efficient method of sending data. However, it is less robust because modifying or deleting the data before receiving the DPN_MSGID_SEND_COMPLETE message can cause erroneous data to be sent. This flag cannot be used with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Do not send the DPN_MSGID_SEND_COMPLETE structure to the message handler. This flag cannot be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Send the DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process might become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Send the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NOLOOPBACK
Suppress the DPN_MSGID_RECEIVE system message to your message handler when you are sending to a group that includes the local player. For example, this flag is useful if you are broadcasting to the entire session.
DPNSEND_NONSEQUENTIAL
If this flag is set, the target application will receive the messages in the order that they arrive at the user's computer. If this flag is not set, messages are delivered sequentially, and will be received by the target application in the order that they were sent. Doing so might require buffering incoming messages until missing messages arrive.
DPNSEND_COALESCE
Allows DirectPlay to combine packets when sending.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_CONNECTIONLOST | The service provider connection was reset while data was being sent.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPLAYER | The player ID is not recognized as a valid player ID for this game session.
DPNERR_TIMEDOUT | The operation could not complete because it has timed out.

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the receiver's message handler. The data is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. For a discussion of send priorities, see Basic Networking.

When the IDirectPlay8Server::SendTo request is completed, a DPN_MSGID_SEND_COMPLETE system message is posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associated structure. You can suppress the send completion by setting the DPNSEND_NOCOMPLETE flag in dwFlags.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It might still be in a queue. If you want to be certain that the message has been processed by the target, set the DPNSEND_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message and returned.

If the DPNSEND_COALESCE flag is set in dwFlags, DirectPlay will try to coalesce up to 32 packets waiting in the queue into the outgoing frame. DirectPlay does not guarantee coalescence, even if the DPNSEND_COALESCE flag is set. Packets will only be coalesced if there is more than one message in the queue and the player receiving is running Microsoft DirectX® 9.0 or later. All voice packets can be coalesced. Both guaranteed and non-guaranteed packets will be coalesced into the same frame. If the frame is dropped before it reaches its destination, only the guaranteed parts of the frame will be resent and no other data will be coalesced into the frame.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message can be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource can become invalid at any time after the method has been called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SetApplicationDesc Method

Changes the settings for the application that is being hosted. Only some settings can be changed.

Syntax

HRESULT SetApplicationDesc(

    const DPN_APPLICATION_DESC *const pad,
    const DWORD dwFlags
);

Parameters

pad
[in] Pointer to a DPN_APPLICATION_DESC structure that describes the application settings to modify.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_DATATOOLARGE | The application data is too large for the service provider's Maximum Transmission Unit.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC structure.

  • dwMaxPlayers
  • pwszSessionName
  • pwszPassword
  • pvApplicationReservedData
  • dwApplicationReservedDataSize

When IDirectPlay8Server::SetApplicationDesc is called, Microsoft® DirectPlay® makes a copy of the data pad points to. You do not need to save the DPN_APPLICATION_DESC structure once IDirectPlay8Server::SetApplicationDesc returns.

You cannot set the dwMaxPlayers member to a smaller value than the current number of players in the session.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

To avoid accidentally overwriting the application description, applications should call IDirectPlay8Server::GetApplicationDesc and fill in the DPN_APPLICATION_DESC structure before calling IDirectPlay8Server::SetApplicationDesc.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SetCaps Method

Sets the DPN_CAPS or DPN_CAPS_EX structure for the current interface.

Syntax

HRESULT SetCaps(

    const DPNCAPS *const pdpCaps,
    const DWORD dwFlags
);

Parameters

pdpCaps
[in] Pointer to a DPN_CAPS or DPN_CAPS_EX structure used to set the information about the current interface.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

A successful call to IDirectPlay8Server::Initialize must be made before this method can be called.

DirectPlay will determine whether DPN_CAPS or DPN_CAPS_EX is being used, based on the size of the structure referenced by pdpCaps.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SetGroupInfo Method

Sets a block of data associated with a group, including the name of the group.

Syntax

HRESULT SetGroupInfo(

    const DPNID dpnid,
    DPN_GROUP_INFO *const pdpnGroupInfo,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

dpnid
[in] Variable of type DPNID that specifies the identifier of the group whose data block will be modified.
pdpnGroupInfo
[in] Pointer to a DPN_GROUP_INFO structure that describes the group data to set. To change the values of the pwszName or pvData members of this structure, you must set the corresponding DPNINFO_NAME OR DPNINFO_DATA flag in the dwInfoFlags member.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETGROUPINFO_SYNC
Causes this method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDGROUP | The group ID is not recognized as a valid group ID for this game session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SetServerInfo Method

Sets the static settings of a server with an application. After clients successfully connect to the server, they can retrieve the information set by this method by calling theIDirectPlay8Client::GetServerInfo method.

Syntax

HRESULT SetServerInfo(

    const DPN_PLAYER_INFO *const pdpnPlayerInfo,
    PVOID const pvAsyncContext,
    DPNHANDLE *const phAsyncHandle,
    const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
[in] Pointer to a DPN_PLAYER_INFO structure that contains the server information to set.
pvAsyncContext
[in] Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
[out] A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® does not permit cancellation of this operation, so the value cannot be used.
dwFlags
[in] Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETSERVERINFO_SYNC
Causes this method to process synchronously.

Return Value

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK can return if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOCONNECTION | No communication link was established.

Remarks

This method may be called before calling IDirectPlay8Server::Host, and at any time during the session.

The DPN_PLAYER_INFO structure's dwPlayerFlags member must be set to zero.

Handle transmission of nonstatic information with the IDirectPlay8Server::SendTo method because of the high cost of using the IDirectPlay8Server::SetServerInfo method.

You can modify the server information with this method after clients have connected to the application. Calling this method after connection generates a DPN_MSGID_SERVER_INFO system message to all players, informing them that data has been updated.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8Server::SetSPCaps Method

Sets the DPN_SP_CAPS structure for the specified service provider.

Syntax

HRESULT SetSPCaps(

    const GUID *const pguidSP,
    const DPN_SP_CAPS *const pdpnSPCaps,
    const DWORD dwFlags
);

Parameters

pguidSP
[in] Pointer to a globally unique identifier (GUID) specifying the service provider you want to set information about.
pdpnSPCaps
[in] Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPOINTER | Pointer specified as a parameter is invalid.
DPNERR_UNINITIALIZED | The requested object has not been initialized.

Remarks

This method sets parameters for the specified service provider. A successful call to IDirectPlay8Server::Initialize must be made before this method can be called. Currently, only the dwSystemBufferSize member can be set by this call. The dwNumThreads member is for legacy support. Microsoft DirectX® 9.0 applications should use the IDirectPlay8ThreadPool::SetThreadCount method to set the number of threads. The other members of the DPN_SP_CAPS structure are get-only or ignored.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool Interface

Applications use the methods of the IDirectPlay8ThreadPool interface to manage threads in a Microsoft® DirectPlay® application.

IDirectPlay8ThreadPool Members

Close | Closes the IDirectPlay8ThreadPool object.
DoWork | Performs work that is currently scheduled.
GetThreadCount | Retrieves the number of threads for the specified processor or all processors.
Initialize | Initializes the thread pool interface for the process.
SetThreadCount | Changes the number of threads for a specified processor or all processors.

Remarks

The serial and modem service providers do not support the IDirectPlay8ThreadPool interface. Therefore, if you use these service providers, you must handle multithreaded callbacks from threads that did not generate a DPN_MSGID_CREATE_THREAD message when created.

DirectPlay Voice uses a different set of threads to perform audio capture, playback, and message notification. If you use the IDirectPlayVoiceClient or IDirectPlayVoiceServer interface, you must handle multithreaded callbacks from threads that did not generate a DPN_MSGID_CREATE_THREAD message when created.

Interface Information

Inherits from | IUnknown
Header | dplay8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool::Close Method

Closes the IDirectPlay8ThreadPool object.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPN_OK if successful. Otherwise, returns one of the following errors.

DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

Any threads that exist will send a DPN_MSGID_DESTROY_THREAD message before this method will return.

DPNERR_NOTALLOWED is returned if this method is called when there is an outstanding call to IDirectPlay8ThreadPool::DoWork or if this method is called from an IDirectPlay8ThreadPool thread.

Always close the IDirectPlay8ThreadPool interface after closing all of the other Microsoft® DirectPlay® objects used by the process. Closing an IDirectPlay8ThreadPool interface that was in a IDirectPlay8ThreadPool::DoWork call before closing an IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interface can cause the IDirectPlay8ThreadPool interface to appear to hang.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool::DoWork Method

Performs work that is currently scheduled.

Syntax

HRESULT DoWork(

    const DWORD dwAllowedTimeSlice,
    const DWORD dwFlags
);

Parameters

dwAllowedTimeSlice
[in] Specifies the time allowed for the work to complete. Set to INFINITE to allow all immediately available items to be run.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPN_OK if no additional work is immediately available. If dwAllowedTimeSlice is not set to INFINITE and the time specified has expired, leaving outstanding work items, DPNSUCCESS_PENDING will be returned. Otherwise, returns one of the following errors.

DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_NOTREADY | The object is not ready for use.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

This method allows Microsoft® DirectPlay® to operate without any threads of its own. It is expected that this method will be called at regular intervals so that time critical operations can be performed with reasonable accuracy.

The dwAllowedTimeSlice parameter must be between 0 and 60,000 milliseconds (1 minute) or it can be set to INFINITE. If it is set to 0, at most the first work item will be performed.

This method cannot be called unless the thread count has been set to 0. It will return DPNERR_NOTREADY if there are threads currently active.

If an attempt is made to call this method by more than one thread simultaneously, recursively, or within a DirectPlay callback, DPNERR_NOTALLOWED is returned.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool::GetThreadCount Method

Retrieves the number of threads for the specified processor or all processors.

Syntax

HRESULT GetThreadCount(

    const DWORD dwProcessorNum,
    DWORD *const pdwNumThreads,
    const DWORD dwFlags
);

Parameters

dwProcessorNum
[in] Specifies the processor number. Set to -1 to retrieve the thread count for all processors.
pdwNumThreads
[out] Receives the current number of threads for the processor specified in dwProcessorNum.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPN_OK if successful. Otherwise, returns one of the following errors.

DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool::Initialize Method

Initializes the thread pool interface for the process.

Syntax

HRESULT Initialize(

    PVOID const pvUserContext,
    const PFNDPNMESSAGEHANDLER pfn,
    const DWORD dwFlags
);

Parameters

pvUserContext
[in] User context for all message callbacks.
pfn
[in] Pointer to a PFNDPNMESSAGEHANDLER function to handle thread pool messages.
dwFlags
[in] The following flag can be specified.
DPNINITIALIZE_DISABLEPARAMVAL
Disables parameter validation.

Return Value

Returns DPN_OK if successful. Otherwise, returns one of the following errors.

DPNERR_ALREADYINITIALIZED | The object has already been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

Only one IDirectPlay8ThreadPool object is allowed in a process. DPNERR_ALREADYINITALIZED is returned if IDirectPlay8ThreadPool::Initialize is called on a second IDirectPlay8ThreadPool object.

If a Microsoft® DirectPlay® object has already created threads, the IDirectPlay8ThreadPool object cannot be initialized. If the IDirectPlay8ThreadPool object has not been initialized, DPNERR_NOTALLOWED will be returned.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlay8ThreadPool::SetThreadCount Method

Changes the number of threads for a specified processor or all processors.

Syntax

HRESULT SetThreadCount(

    const DWORD dwProcessorNum,
    const DWORD dwNumThreads,
    const DWORD dwFlags
);

Parameters

dwProcessorNum
[in] Specifies the processor number. Set to -1 to change the total thread count for all processors.
dwNumThreads
[in] Specifies the new thread count.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPN_OK if successful. Otherwise, returns one of the following errors.

DPNERR_UNINITIALIZED | The requested object has not been initialized.
DPNERR_INVALIDFLAGS | The flags passed to this method are invalid.
DPNERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DPNERR_NOTALLOWED | This function is not allowed on this object.

Remarks

If the value in the dwNumThreads parameter is larger than the current thread count, the new threads will be started, generating a DPN_MSGID_CREATE_THREAD message for each new thread before this method returns.

If the value in the dwNumThreads parameter is smaller than the current thread count, the excess threads will be shut down, generating a DPN_MSGID_DESTROY_THREAD message for each closed thread before this method returns.

If the thread count is set to 0, Microsoft® DirectPlay® will not create any threads in the application. Therefore, to make anything happen in the application, you'll need to call IDirectPlay8ThreadPool::DoWork regularly.

DirectPlay performs tasks differently when the thread count set to 0 than when you are using DirectPlay threads. Therefore, it is recommended that you do not switch between zero thread count mode and multithread count mode once a session has been created.

DPNERR_NOTALLOWED is returned if this method is called when there is an outstanding call to IDirectPlay8ThreadPool::DoWork on a thread. In this case, the thread count will not change.

DPNERR_NOTALLOWED is returned if dwNumThreads parameter is smaller than the current thread count and this method is called from an IDirectPlay8ThreadPool thread. In this case, the thread count will not change.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp Interface

Applications use the methods of the IDirectPlayNATHelp interface to simplify traversal through the Internet Connection Sharing features available in Microsoft® Windows® Millennium Edition (Windows Me) and Windows XP.

IDirectPlayNATHelp Members

Close

Closes and unregisters this application with any Internet gateway servers. This method must be called on any object successfully initialized with IDirectPlayNATHelp.

GetCaps

Retrieves the capabilities of the Internet gateway server(s) and information about leased ports.

GetRegisteredAddresses

Returns the current public address mappings for the specified registered port group.

Initialize

Initializes an IDirectPlayNATHelp object. This method must be called before using any other functions.

QueryAddress

Determine a private alias for a given public address.

RegisterPorts

Asks for public realm port(s) that are aliases for the local port(s) on this private realm node.

SetAlertEvent

Specifies an event that will be set when maintenance needs to be performed.

Interface Information

Inherits from | IUnknown
Header | dpnathlp.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::Close Method

Closes and unregisters this application with any Internet gateway servers. This method must be called on any object successfully initialized with IDirectPlayNATHelp.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::GetCaps Method

Retrieves the capabilities of the Internet gateway server(s) and information about leased ports.

Syntax

HRESULT GetCaps(

    PPDPNHCAPS *const pdpnhcaps,
    const DWORD dwFlags
);

Parameters

pdpnhcaps
[in] Pointer to a DPNHCAPS structure to be filled with Network Address Translation (NAT) helper's capabilities. The dwSize member of the structure must be set.
dwFlags
[in] May be the following value.
DPNHGETCAPS_UPDATESERVERSTATUS
Automatically extend expiring leases and detect changes in the server status.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_INVALIDPOINTER | An invalid pointer was specified.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.

Remarks

This method should be called periodically with the DPNHGETCATS_UPDATESERVERSTATUS flag set to automatically extend port leases that are about to expire. The DPNHGETCATS_UPDATESERVERSTATUS flag also causes detection of changes in the status of the servers since the last call to IDirectPlayNATHelp::GetCaps. If a new server becomes available, an existing server becomes unavailable, or a server's public address changes in a way that affects an existing registered port mapping, then DPNHSUCCESS_ADDRESSESCHANGED is returned instead of DPNH_OK.

If DPNHSUCCESS_ADDRESSESCHANGED is returned, the user should call IDirectPlayNATHelp::GetRegisteredAddresses to update port binding information.

When the DPNHGETCATS_UPDATESERVERSTATUS flag is set, this method may stall while attempts are made to communicate with the server.

This method must be called with the DPNHGETCATS_UPDATESERVERSTATUS flag set at least once before calling IDirectPlayNATHelp::GetRegisteredAddresses or IDirectPlayNATHelp::QueryAddress.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::GetRegisteredAddresses Method

Returns the current public address mappings for the specified registered port group.

Syntax

HRESULT GetRegisteredAddresses(

    const DPNHANDLE hRegisteredPorts,
    SOCKADDR *const paPublicAddresses,
    DWORD *const pdwPublicAddressSize,
    DWORD *const pdwAddressTypeFlags,
    DWORD *const pdwLeaseTimeRemaining,
    const DWORD dwFlags
);

Parameters

hRegisteredPorts
[in] Handle to a specific binding returned by IDirectPlayNATHelp::RegisterPorts.
paPublicAddresses
[out] Buffer to receive assigned public realm addresses. Set to NULL if not desired.
pdwPublicAddressSize
[in, out] Pointer to a size of paPublicAddresses buffer on input. On output, receives the size written to paPublicAddresses or the size required if the buffer is too small. Can be NULL only if paPublicAddresses is NULL.
pdwAddressTypeFlags
[out] Receives flags describing the address types returned. Set to NULL if not desired. The following values can be returned.
DPNHANDLEADDRESSTYPE_TCP
The mappings are for TCP ports instead of User Datagram Protocol (UDP) ports.
DPNHANDLEADDRESSTYPE_FIXEDPORTS
The mappings are for ports which are the same on the Internet gateway.
DPNHANDLEADDRESSTYPE_SHAREDPORTS
The mappings are for shared UDP fixed ports.
DPNHANDLEADDRESSTYPE_LOCALFIREWALL
The addresses are opened on a local firewall.
DPNHANDLEADDRESSTYPE_GATEWAY
The addresses are registered with an Internet gateway.
DPNHANDLEADDRESSTYPE_GATEWAYISLOCAL
The Internet gateway is local.
pdwLeaseTimeRemaining
[out] Receives time remaining in the port lease in milliseconds. Set to NULL if not desired. Call IDirectPlayNATHelp::GetCaps to automatically extend leases.
dwFlags
[in] Can be the following value.
DPNHGETREGISTEREDADDRESSES_LOCALFIREWALLREMAPONLY
Retrieve the public address for the local firewall only, even if mapped on remote Internet gateway.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_NOMAPPING | The server does not have valid public interfaces.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.
DPNHERR_SERVERUNAVAILABLE | No servers are currently present.
DPNHERR_UPDATESERVERSTATUS | IDirectPlayNATHelp::GetCaps has not been called with the DPNHGETCAPS_UPDATESERVERSTATUS flag set.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::Initialize Method

Initializes an IDirectPlayNATHelp object. This method must be called before using any other functions.

Syntax

HRESULT Initialize(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Can be one of the following values.
DPNHINITIALIZE_DISABLEGATEWAYSUPPORT
Do not attempt to traverse the Internet gateway.
DPNHINITIALIZE_DISABLELOCALFIREWALLSUPPORT
Do not attempt to traverse a local firewall.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_ALREADYINITIALIZED | This object has already been initialized.
DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.

Remarks

This method does not attempt to contact any Internet gateway servers.

Call IDirectPlayNATHelp::GetCaps with the DPNHGETCAPS_UPDATESERVERSTATUS flag set to search for a server.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::QueryAddress Method

Determine a private alias for a given public address.

Syntax

HRESULT QueryAddress(

    const SOCKADDR *const pSourceAddress,
    const SOCKADDR *const pQueryAddress,
    SOCKADDR *const pResponseAddress,
    const int iAddressSize,
    const DWORD dwFlags
);

Parameters

pSourceAddress
[in] Address for the network interface that is using the desired address. This can be set to INADDR_ANY in which case the best server will be used.
pQueryAddress
[in] Address to look up. Do not set this value to INADDR_ANY or INADDR_BROADCAST.
pResponseAddress
[out] Receives the private alias to the public address specified.
iAddressSize
[in] Size of the SOCKADDR structure used for the pSourceAddress, pQueryAddress, and pResponseAddress buffers.
dwFlags
[in] Set to 0 to query for a User Datagram Protocol (UDP) port. Otherwise, set to one of the following values.
DPNHQUERYADRESS_TCP
Query for a TCP port.
DPNHQUERYADRESS_CACHEFOUND
Cache the address if a mapping is found.
DPNHQUERYADRESS_CACHENOTFOUND
Cache the address if a mapping is not found.
DPNHQUERYADRESS_CHECKFORPRIVATEBUTUNMAPPED
Determine if an address is private when no specific mapping is found.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_INVALIDPOINTER | An invalid pointer was specified.
DPNHERR_NOMAPPING | The server does not have valid public interfaces.
DPNHERR_NOMAPPINGBUTPRIVATE | The server indicated that no mapping was found, but it is a private address.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.
DPNHERR_SERVERUNAVAILABLE | No servers are currently present.
DPNHERR_UPDATESERVERSTATUS | IDirectPlayNATHelp::GetCaps has not been called with the DPNHGETCAPS_UPDATESERVERSTATUS flag set.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::RegisterPorts Method

Asks for public realm port(s) that are aliases for the local port(s) on this private realm node.

Syntax

HRESULT RegisterPorts(

    const SOCKADDR *const aLocalAddress,
    const DWORD dwAddressesSize,
    const DWORD dwNumAddresses,
    const DWORD dwLeaseTime,
    DPNHANDLE *const phRegisteredPorts,
    const DWORD dwFlags
);

Parameters

aLocalAddress
[in] Array of local address and port tuples for which remote ports are selected.
dwAddressesSize
[in] Size of entire local addresses array.
dwNumAddresses
[in] Number of SOCKADDR structures in local addresses array.
dwLeaseTime
[in] Requested time to lease the ports, in milliseconds. If IDirectPlayNATHelp::GetCaps is called before this time expires, the lease will automatically be renewed.
phRegisteredPorts
[in] Place to store an identifier for this binding which can be used to query or release the binding.
dwFlags
[in] Set to 0 for User Datagram Protocol (UDP) ports or one of the following values.
DPNHREGISTERPORTS_TCP
TCP ports.
DPNHREGISTERPORTS_FIXEDPORTS
Asks the server to use the same port on the public interface.
DPNHREGISTERPORTS_SHAREDPORTS
Allow the UDP fixed port to be shared.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_PORTALREADYREGISTERED | At least one of the ports has already been registered in a different address array or order.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayNATHelp::SetAlertEvent Method

Specifies an event that will be set when maintenance needs to be performed.

Syntax

HRESULT SetAlertEvent(

    const HANDLE hEvent,
    const DWORD dwFlags
);

Parameters

hEvent
[in] Handle to the event to signal when IDirectPlayNATHelp::GetCaps is to be called.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DPNH_OK if successful, or one of the following error values.

DPNHERR_GENERIC | An error occurred while closing.
DPNHERR_INVALIDFLAGS | Invalid flags were specified.
DPNHERR_INVALIDOBJECT | The interface object is invalid.
DPNHERR_INVALIDPARAM | An invalid parameter was specified.
DPNHERR_NOTINITIALIZED | The object has not been initialized.
DPNHERR_OUTOFMEMORY | There is not enough memory to perform this operation.
DPNHERR_REENTRANT | The interface has been re-entered on the same thread.

Remarks

Call IDirectPlayNATHelp::GetCaps using the DPNHGETCAPS_UPDATESERVERSTATUS flag when the event is signalled.

This method is used in addition to the regular polling by IDirectPlayNATHelp::GetCaps. It allows the polling to be less frequent.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient Interface

Applications use the methods of the IDirectPlayVoiceClient interface to manage clients in a voice session.

IDirectPlayVoiceClient Members

Connect

Connects the client to a Microsoft® DirectPlay® Voice session.

Create3DSoundBuffer

Retrieves a 3-D sound buffer for a player or group. You can use the methods of the 3-D sound buffer object to change the virtual 3-D position of incoming voice transmissions from the specified group or player.

Delete3DSoundBuffer

Returns exclusive control of the 3-D sound buffer object to the DirectPlay voice client object.

Disconnect

Disconnects the DirectPlay Voice client from the existing DirectPlay Voice session.

GetCaps

Retrieves the DirectPlay Voice capabilities.

GetClientConfig

Retrieves the client configuration.

GetCompressionTypes

Retrieves the available compression types on the system.

GetSessionDesc

Retrieves the session properties.

GetSoundDeviceConfig

Retrieves the sound device configuration of the session.

GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream from this client.

Initialize

Initializes the DirectPlayVoiceClient object by associating it with a DirectPlay object. Additionally, this method registers a message handler with the DirectPlayVoiceClient object.

SetClientConfig

Sets the client configuration.

SetNotifyMask

Specifies which messages are sent to the message handler.

SetTransmitTargets

Specifies which players and/or groups receive audio transmissions from the local client.

Interface Information

Inherits from | IUnknown
Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::Connect Method

Connects the client to a Microsoft® DirectPlay® Voice session.

Syntax

HRESULT Connect(

    PDVSOUNDDEVICECONFIG pSoundDeviceConfig,
    PDVCLIENTCONFIG pdvClientConfig,
    DWORD dwFlags
);

Parameters

pSoundDeviceConfig
[in] Pointer to a DVSOUNDDEVICECONFIG structure that describes the sound device configuration.
pdvClientConfig
[in] Pointer to a DVCLIENTCONFIG structure that describes the general configuration of the client.
dwFlags
[in] Flag. You can specify the following flag.
DVFLAGS_SYNC
The method does not return until the operation is completed.

Return Value

If the method is processed synchronously and is successful, it returns DV_OK. By default, this method is run asynchronously and returns DV_PENDING. On error, this method will return one of the following values.

DVERR_ALREADYPENDING | An asynchronous call of this type is already pending.
DVERR_COMPRESSIONNOTSUPPORTED | The specified compression type is not supported on the local computer.
DVERR_INCOMPATIBLEVERSION | The client connected to a voice session that is incompatible with the host.
DVERR_INVALIDDEVICE | The specified device is invalid.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_OUTOFMEMORY | There is insufficient memory to perform the requested operation.
DVERR_RUNSETUP | The specified audio configuration has not been tested. Call the IDirectPlayVoiceTest::CheckAudioSetup method.
DVERR_SENDERROR | An error occurred while sending data.
DVERR_SOUNDINITFAILURE | A failure was encountered initializing the sound card.
DVERR_TIMEOUT | The operation could not be performed in the specified time.
DVERR_TRANSPORTNOPLAYER | The specified transport is connected/hosting but no local player exists.
DVERR_TRANSPORTNOSESSION | The specified transport is valid but is not connected/hosting.
DVERR_CONNECTED | The DirectPlay Voice object is connected.
DVERR_NOVOICESESSION | The session specified is not a voice session.

Remarks

If you call this method asynchronously and it returns DVERR_PENDING, you will receive a DVMSGID_CONNECTRESULT message with the result of the connection attempt. This message can arrive before or after the method returns DVERR_PENDING. If you call this method asynchronously, you will not receive a DVMSGID_CONNECTRESULT message.

You must test the sound devices selected for playback and capture by invoking the setup wizard before connecting the client to the DirectPlay Voice session. On application startup, check the audio configuration by using IDirectPlayVoiceTest::CheckAudioSetup. If this method returns DVERR_RUNSETUP, the sound configuration specified has not been tested. The setup wizard needs to be run only once for any configuration.

If you specify a buffer that is not the right format, the method will return DVERR_INVALIDBUFFER.

If the buffer or a portion of the buffer is locked when DirectPlay Voice attempts to write to it, the method will return DVERR_INVALIDBUFFER, and DirectPlay Voice will disconnect from the session. You will also receive a DVMSGID_SESSIONLOST message. The hResult member of the associated structure will be set to DVERR_LOCKEDBUFFER. Subsequent method calls will return a DVERR_NOTCONNECTED error code.

If full duplex operation is not supported, DirectPlay Voice falls back to half duplex (listen only) mode. To determine if you are in half-duplex mode, call IDirectPlayVoiceClient::GetSoundDeviceConfig after you have completed the connection. If you are in half-duplex mode, the DVSOUNDDEVICECONFIG structure's dwFlags member will have the DVSOUNDCONFIG_HALFDUPLEX flag set.

Regardless of how the interfaces are obtained, the DirectPlayVoiceClient object maintains a reference, through a call to AddRef, to the IDirectSound and IDirectSoundCapture interfaces it uses until IDirectPlayVoiceClient::Disconnect is called. When IDirectPlayVoiceClient::Disconnect is called, the DirectPlayVoiceClient object calls Release on both interfaces.

Any calls to IDirectPlayVoiceClient::Connect while a connection is pending return DVERR_ALREADYPENDING. Additionally, only one connection can be pending at a time.

A transport session must be started on the specified DirectPlay object before calling this method. A successful call to IDirectPlayVoiceClient::Initialize must be made before calling the Connect method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::Create3DSoundBuffer Method

Retrieves a 3-D sound buffer for a player or group. You can use the methods of the 3-D sound buffer object to change the virtual 3-D position of incoming voice transmissions from the specified group or player.

Syntax

HRESULT Create3DSoundBuffer(

    DVID dvID,
    LPDIRECTSOUNDBUFFER lpdsSourceBuffer,
    DWORD dwPriority,
    DWORD dwFlags,
    LPDIRECTSOUND3DBUFFER *lpUserBuffer
);

Parameters

dvID
[in] Variable of type DVID that specifies the identification of the player or group that the user wants to reserve a buffer for. You can also specify DVID_REMAINING to create a 3-D user buffer for all players or groups that do not have a user buffer. If DVID_REMAINING is specified, the lpdsSourceBuffer parameter must be set to NULL and the dwPriority and dwFlags parameters must be set to 0.
lpdsSourceBuffer
[in] Pointer to an IDirectSoundBuffer interface, which is used to create the Microsoft® DirectPlay® Voice main buffer. This can be either NULL or a user-created Microsoft DirectSound® buffer. If this member is set to NULL, then DirectPlay Voice creates a buffer for you.
dwPriority
[in] Direct pass-through. This value is passed in the dwPriority parameter when the call to IDirectSoundBuffer::Play is made. For more information, see IDirectSoundBuffer8::Play. This parameter must be 0 if lpdsSourceBuffer is NULL.
dwFlags
[in] Direct pass-through. This value is passed to the dwFlagsparameter when the call to IDirectSoundBuffer::Play is made. For more information, see IDirectSoundBuffer8::Play. This parameter must be 0 if lpdsSourceBuffer is NULL.
lpUserBuffer
[out] Pointer to memory where the reserved buffer is placed.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYBUFFERED | There is already a user buffer for the specified ID.
DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTALLOWED | The object does not have the permission to perform this operation.
DVERR_NOTCONNECTED | The DirectPlay Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_OUTOFMEMORY | There is insufficient memory to perform the requested operation.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

If the DirectPlay voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.

Although you can access all the member functions of the 3-D sound buffer object, because the DirectPlay voice client uses the buffer to stream incoming audio, do not use the Lock, UnLock, or Play methods of the DirectSound3DBuffer object.

If the user specifies a buffer, DirectPlay uses that buffer for the player's or group's buffer. User-created buffers have the following restrictions.

  • The buffer must be 22 kilohertz, 16-bit, Mono format.
  • The buffer must be at least 1 second in length.
  • The buffer must have been created with the DSBCAPS_GETCURRENTPOSITION2 and DSBCAPS_CTRL3D flags.
  • The buffer must not be a primary buffer.
  • The buffer must not be playing when it is passed to DirectPlay.

If the buffer is not the right format, the method will return DVERR_INVALIDBUFFER.

The buffer must not be locked when you pass it to DirectPlay. When the buffer for the individual user is no longer required or when a player leaves the voice session, it is important to call IDirectPlayVoiceClient::Delete3DSoundBuffer to free up resources.

If the buffer or a portion of the buffer is locked when DirectPlay Voice attempts to write to it, the method will return DVERR_INVALIDBUFFER. If you lock the buffer after the method has returned, you will receive a DVMSGID_SESSIONLOST message. The hResult member of the associated structure will be set to DVERR_LOCKEDBUFFER. Subsequent method calls will return a DVERR_NOTCONNECTED error code.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::Delete3DSoundBuffer Method

Returns exclusive control of the 3-D sound buffer object to the Microsoft® DirectPlay® voice client object.

Syntax

HRESULT Delete3DSoundBuffer(

    DVID dvID,
    LPDIRECTSOUND3DBUFFER *lpUserBuffer
);

Parameters

dvID
[in] DVID of the player or group that the user wants to delete a buffer for.
lpUserBuffer
[in] Pointer to the user buffer to delete. This must be a user buffer obtained through the IDirectPlayVoiceClient::Create3DSoundBuffer method.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYBUFFERED | There is already a user buffer for the specified ID.
DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTALLOWED | The object does not have the permission to perform this operation.
DVERR_NOTBUFFERED | There is no user buffer for the specified ID.
DVERR_NOTCONNECTED | The DirectPlay Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

If the DirectPlay Voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::Disconnect Method

Disconnects the Microsoft® DirectPlay® Voice client from the existing DirectPlay Voice session.

Syntax

HRESULT Disconnect(

    DWORD dwFlags
);

Parameters

dwFlags
[in] Flag. You can specify the following flag.
DVFLAGS_SYNC
Do not return until the operation is completed.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING | An asynchronous call of this type is already pending.
DVERR_CONNECTABORTING | The connection is being disconnected.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_NOTCONNECTED | The DirectPlay Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_PENDING | Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued.
DVERR_SESSIONLOST | The transport has lost the connection to the session.
DVERR_TIMEOUT | The operation could not be performed in the specified time.

Remarks

On calling this method, all recording and playback is stopped. If a connection is being processed, it is canceled by this call.

Unless the DVFLAGS_SYNC is specified, calling this method immediately returns a DVERR_PENDING error value and proceeds to process the disconnection request in the background. The status of the disconnection is not known until the DirectPlay Voice client generates a DVMSGID_DISCONNECTRESULT message that contains the disconnection result. Only one disconnection can be pending at a time. If you call IDirectPlayVoiceClient::Disconnect while a disconnect is pending, DirectPlay will return a DVERR_ALREADYPENDING error value.

If this method is called synchronously by setting the DVFLAGS_SYNC flag, the method does not return until the IDirectPlayVoiceClient::Disconnect method completes. The result of the disconnection is the return value from this method. No DVMSGID_DISCONNECTRESULT message is generated.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetCaps Method

Retrieves the Microsoft® DirectPlay® Voice capabilities.

Syntax

HRESULT GetCaps(

    PDVCAPS pCaps
);

Parameters

pCaps
[out] Pointer to the DVCAPS structure that contains the capabilities of the DirectPlayVoiceClient object.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetClientConfig Method

Retrieves the client configuration.

Syntax

HRESULT GetClientConfig(

    PDVCLIENTCONFIG pClientConfig
);

Parameters

pClientConfig
[out] Pointer to a DVCLIENTCONFIG structure that contains the configuration of the local client.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

Before calling this method, you must set the DVCLIENTCONFIG structure's dwSize member.

You can call this method only after a connection is successfully established with a DirectPlay Voice session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetCompressionTypes Method

Retrieves the available compression types on the system.

Syntax

HRESULT GetCompressionTypes(

    PVOID pData,
    PDWORD pdwDataSize,
    PDWORD pdwNumElements,
    DWORD dwFlags
);

Parameters

pData
[out] Pointer to buffer that receives an array of DVCOMPRESSIONINFO structures, one structure for every compression type supported through this object.
pdwDataSize
[in] Pointer to a DWORD that contains the size of the buffer, in bytes, passed in the pData parameter.
pdwNumElements
[out] Pointer to a DWORD where the method writes the number of elements returned in the array of DVCOMPRESSIONINFO structures. This contains the number of structures only if the buffer specified in the pData is large enough to hold the information.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.

Remarks

If the buffer passed is not large enough to store the list of compression types, the method returns DVERR_BUFFERTOOSMALL and the pdwDataSize parameter is set to the minimum required size.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetSessionDesc Method

Retrieves the session properties.

Syntax

HRESULT GetSessionDesc(

    PDVSESSIONDESC pvSessionDesc
);

Parameters

pvSessionDesc
[out] Pointer to a DVSESSIONDESC structure to receive the session description.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

Before calling this method, make sure to set the DVSESSIONDESC structure's dwSize member.

This method may be called only after a connection is successfully established with a DirectPlay Voice session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetSoundDeviceConfig Method

Retrieves the sound device configuration of the session.

Syntax

HRESULT GetSoundDeviceConfig(

    PDVSOUNDDEVICECONFIG pSoundDeviceConfig,
    PDWORD pdwSize
);

Parameters

pSoundDeviceConfig
[out] Pointer to a DVSOUNDDEVICECONFIG structure that is filled with the configuration of the sound device.
pdwSize
[in, out] Pointer to a DWORD that specifies the size of the buffer in pSoundDeviceConfig parameter. If the buffer is too small, the method returns DVERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

You can call this method only after a connection is successfully established with a DirectPlay Voice session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::GetTransmitTargets Method

Retrieves the transmit targets, if any, of the voice stream from this client.

Syntax

HRESULT GetTransmitTargets(

    PDVID pdvIDTargets,
    PDWORD pdwNumTargets,
    DWORD dwFlags
);

Parameters

pdvIDTargets
[out] Member to fill with an array of DVIDs that specify the targets that were set by the IDirectPlayVoiceClient::SetTransmitTargets or IDirectPlayVoiceServer::SetTransmitTargets method. You can retrieve the number of targets by specifying NULL for this parameter.
pdwNumTargets
[in, out] Number of DVIDs in the pdvIDTargets array. If the call is successful, when the method return, this parameter will be set to the number of elements in the pdvIDTargets array. If the array is too small, the method returns DVERR_BUFFERTOOSMALL, and pdwNumTargets will be set to the required number of elements. If pdvIDTargets is NULL, this must be 0.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTALLOWED | The object does not have the permission to perform this operation.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

Remarks

The value returned in the pdvIDTargets parameter can be player or group DVIDs or the DVID_ALLPLAYERS constant.

If the buffer specified in pdvIDTargets is not large enough to store the list of targets, this method returns DVERR_BUFFERTOOSMALL and pdwNumTargets is set to the required number of elements.

If there is no target specified, pdwNumTargets is set to 0 and the return value is DV_OK.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::Initialize Method

Initializes the DirectPlayVoiceClient object by associating it with a Microsoft® DirectPlay® object. Additionally, this method registers a message handler with the DirectPlayVoiceClient object.

Syntax

HRESULT Initialize(

    LPUNKNOWN pVoid,
    PDVMESSAGEHANDLER pMessageHandler,
    PVOID pUserContext,
    PDWORD pdwMessageMask,
    DWORD dwMessageMaskElements
);

Parameters

pVoid
[in] Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceClient object should use.
pMessageHandler
[in] User-defined callback function that is called when there is a DirectPlayVoiceClient message to be processed. Threads within the DirectPlayVoiceClient object call the callback function, so it will not be called in the context of your process's main thread.
pUserContext
[in] Pointer to an application-defined structure that is passed to the callback function each time the function is called.
pdwMessageMask
[in] Array of DWORD values that contains the message identifiers that you want DirectPlay Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface, but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
[in] DWORD value specifying the number of elements in the pdwMessageMask parameter. If pdwMessageMask is NULL, this must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYINITIALIZED | The object has already been initialized.
DVERR_GENERIC | An undefined error condition occurred.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOCALLBACK | This operation cannot be performed because no callback function was specified.
DVERR_TRANSPORTNOTINIT | The specified transport is not yet initialized.

Remarks

This method must be called successfully before IDirectPlayVoiceClient::Connect method is called.

You can call IDirectPlayVoiceClient::SetNotifyMask to change the notify mask during the course of the voice session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::SetClientConfig Method

Sets the client configuration.

Syntax

HRESULT SetClientConfig(

    PDVCLIENTCONFIG pClientConfig
);

Parameters

pClientConfig
[in] Pointer to a DVCLIENTCONFIG structure that contains the configuration description to set.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

You can call this method only after a connection is successfully established with a DirectPlay Voice session.

Calling this method sets all the parameters in the DVCLIENTCONFIG structure. Therefore, to leave a setting unmodified, you must retrieve the current configuration with IDirectPlayVoiceClient::GetClientConfig. Then modify the parameters to change and call IDirectPlayVoiceClient::SetClientConfig.

If the session is running in half duplex mode, the members of the DVCLIENTCONFIG structure related to recording are ignored.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::SetNotifyMask Method

Specifies which messages are sent to the message handler.

Syntax

HRESULT SetNotifyMask(

    PDWORD pdwMessageMask,
    DWORD dwMessageMaskElements
);

Parameters

pdwMessageMask
[in] Pointer to an array of DWORD values containing the message identifiers that you want Microsoft® DirectPlay® Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface, but is for the client interface. To enable all messages, set this value to NULL.
dwMessageMaskElements
[in] DWORD value specifying the number of elements in the pdwMessageMask parameter. If pdwMessageMask is NULL, this parameter must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOCALLBACK | This operation cannot be performed because no callback function was specified.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceClient::SetTransmitTargets Method

Specifies which players and/or groups receive audio transmissions from the local client.

Syntax

HRESULT SetTransmitTargets(

    PDVID pdvIDTargets,
    DWORD dwNumTargets,
    DWORD dwFlags
);

Parameters

pdvIDTargets
[in] Pointer to an array of DVIDs that specify your targets. To target all players in the session, use a single element array, with the value of that element set to DVID_ALLPLAYERS. To target no players, set this parameter to NULL.
dwNumTargets
[in] Number of DVIDs in the array. This value cannot exceed 64. If pdvIDTargets is NULL, this parameter must be set to 0.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_INVALIDTARGET | The specified target is not a valid player ID or group ID for this voice session.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

Remarks

The number of individual targets that you can transmit to is limited to 64. If you exceed this value, the method will fail, and return DVERR_NOTALLOWED. However, you can transmit to more than 64 players. To do this, form the players into groups, and then use the groups as your target.

The pdvIDTargets parameter specifies an array of player and/or group DVIDs. There must be no duplicate targets in this parameter, and all entries must be valid DVIDs. If a target contains a player as its individual DVID and through a group that the target belongs to, Microsoft® DirectPlay® Voice ensures duplicate speech packets are not sent to the player.

If the session was created with the DVSESSION_SERVERCONTROLTARGET flag, only the server can set the targets for this local client. A call to this method returns DVERR_NOTALLOWED.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer Interface

Applications use the methods of the IDirectPlayVoiceServer interface to manage the host of the voice session.

IDirectPlayVoiceServer Members

GetCaps

Retrieves the capabilities of the Microsoft® DirectPlay® Voice server for this system.

GetCompressionTypes

Retrieves available compression types for the system.

GetSessionDesc

Retrieves the DirectPlay Voice session settings.

GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream for a player in a session.

Initialize

Initializes the DirectPlayVoiceServer object by associating it with a DirectPlay object. Additionally, this method registers a message handler with this interface.

SetNotifyMask

Specifies which messages are sent to the message handler.

SetSessionDesc

Sets the session settings.

SetTransmitTargets

Controls the transmission of audio from the client to the specified members of the session.

StartSession

Starts an initialized DirectPlay Voice session within a running DirectPlay transport session. This method must be successfully called before the clients can complete a connection to the voice session.

StopSession

Stops the DirectPlay Voice session.

Interface Information

Inherits from | IUnknown
Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::GetCaps Method

Retrieves the capabilities of the Microsoft® DirectPlay® Voice server for this system.

Syntax

HRESULT GetCaps(

    PDVCAPS pDVCaps
);

Parameters

pDVCaps
[out] Pointer to the DVCAPS structure that contains the capabilities of the DirectPlayVoiceServer object.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::GetCompressionTypes Method

Retrieves available compression types for the system.

Syntax

HRESULT GetCompressionTypes(

    PVOID pData,
    PDWORD pdwDataSize,
    PDWORD pdwNumElements,
    DWORD dwFlags
);

Parameters

pData
[out] Pointer to the buffer that receives an array of DVCOMPRESSIONINFO structures that describe the compression types supported by this object.
pdwDataSize
[in] Pointer to a DWORD value that contains the size of the buffer, in bytes, passed in the pData parameter.
pdwNumElements
[out] Pointer to a DWORD value where the method writes the number of elements returned in the array of DVCOMPRESSIONINFO structures.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.

Remarks

If the buffer is not large enough to store the list of compression types, the method returns DVERR_BUFFERTOOSMALL and the pdwDataSize parameter is set to the minimum required size.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::GetSessionDesc Method

Retrieves the Microsoft® DirectPlay® Voice session settings.

Syntax

HRESULT GetSessionDesc(

    PDVSESSIONDESC pvSessionDesc
);

Parameters

pvSessionDesc
[out] Pointer to a DVSESSIONDESC structure to receive the session description.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTHOSTING | The object is not the host of the session.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

Before calling this method, make sure to set the DVSESSIONDESC structure's dwSize member.

A successful call to IDirectPlayVoiceServer::StartSession must be made before this method can be called.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::GetTransmitTargets Method

Retrieves the transmit targets, if any, of the voice stream for a player in a session.

Syntax

HRESULT GetTransmitTargets(

    DVID dvSource,
    PDVID pdvIDTargets,
    PDWORD pdwNumTargets,
    DWORD dwFlags
);

Parameters

dvSource
[in] DVID of the user or group whose target is returned.
pdvIDTargets
[out] Array of DVIDs that will contain the current targets of the player or group that were set by the IDirectPlayVoiceServer::SetTransmitTargets method. You can retrieve the number of targets by specifying NULL for this parameter.
pdwNumTargets
[in, out] Number of DVIDs in the pdvIDTargets array. If the call is successful, when the method return, this parameter will be set to the number of elements in the pdvIDTargets array. If the array is too small, the method returns DVERR_BUFFERTOOSMALL, and pdwNumTargets will be set to the required number of elements. If pdvIDTargets is NULL, this must be 0.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL | The supplied buffer is not large enough to contain the requested data.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTALLOWED | The object does not have the permission to perform this operation.
DVERR_NOTCONNECTED | The Microsoft® DirectPlay® Voice object is not connected.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

Remarks

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::Initialize Method

Initializes the DirectPlayVoiceServer object by associating it with a Microsoft® DirectPlay® object. Additionally, this method registers a message handler with this interface.

Syntax

HRESULT Initialize(

    LPUNKNOWN lpVoid,
    PDVMESSAGEHANDLER pMessageHandler,
    PVOID pUserContext,
    LPDWORD lpdwMessageMask,
    DWORD dwMessageMaskElements
);

Parameters

lpVoid
[in] Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceServer object should use.
pMessageHandler
[in] User-defined callback function that is called when there is a DirectPlayVoiceClient message to process. A thread within the DirectPlayVoiceClient object calls the callback function, so it is not called in the context of your process's main thread.
pUserContext
[in] Pointer to an application-defined structure that is passed to the callback function each time the method is called.
lpdwMessageMask
[in] Array of DWORD values that contain the message identifiers that you want DirectPlay Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
[in] DWORD value that specifies the number of elements in the lpdwMessageMask parameter. If lpdwMessageMask is NULL, this must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYINITIALIZED | The object has already been initialized.
DVERR_GENERIC | An undefined error condition occurred.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOCALLBACK | This operation cannot be performed because no callback function was specified.
DVERR_TRANSPORTNOTINIT | The specified transport is not yet initialized.

Remarks

You can call IDirectPlayVoiceServer::SetNotifyMask to change the notify mask during the course of the voice session.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::SetNotifyMask Method

Specifies which messages are sent to the message handler.

Syntax

HRESULT SetNotifyMask(

    PDWORD pdwMessageMask,
    DWORD dwMessageMaskElements
);

Parameters

pdwMessageMask
[in] Pointer to an array of DWORD values that contain the message identifiers that you want Microsoft® DirectPlay® Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
[in] DWORD value that specifies the number of elements in the pdwMessageMask parameter. If pdwMessageMask is NULL, this must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOCALLBACK | This operation cannot be performed because no callback function was specified.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::SetSessionDesc Method

Sets the session settings.

Syntax

HRESULT SetSessionDesc(

    PDVSESSIONDESC pSessionDesc
);

Parameters

pSessionDesc
[in] Pointer to a DVSESSIONDESC structure that contains the session description.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT | The Microsoft® DirectPlay® object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTHOSTING | The object is not the host of the session.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

After the DirectPlay voice session has started, only some of the session properties of the DVSESSIONDESC structure can be changed. For more information, see DVSESSIONDESC.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::SetTransmitTargets Method

Controls the transmission of audio from the client to the specified members of the session.

Syntax

HRESULT SetTransmitTargets(

    DVID dvSource,
    PDVID pdvIDTargets,
    DWORD dwNumTargets,
    DWORD dwFlags
);

Parameters

dvSource
[in] DVID of the user whose targets are set.
pdvIDTargets
[in] Pointer to an array of DVIDs that specify your targets. To target all players in the session, use a single element array with the value of that element set to DVID_ALLPLAYERS. To target no players, set this parameter to NULL.
dwNumTargets
[in] Number of DVIDs in the array. This value cannot exceed 64. If pdvIDTargets is NULL, this must be 0.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_INVALIDTARGET | The specified target is not a valid player ID or group ID for this voice session.
DVERR_NOTALLOWED | The object does not have the permission to perform this operation.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.

Remarks

The number of individual targets that you can transmit to is limited to 64. If you exceed this value, the method will fail, and return DVERR_NOTALLOWED. However, you can transmit to more than 64 players. To do so, form the players into groups, and then use the group as your target.

There must be no duplicate targets in this parameter, and all entries must be valid DVIDs. If a target contains a player as its individual DVID and through a group that the target belongs to, Microsoft® DirectPlay® Voice ensures duplicate speech packets are not sent to the player.

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::StartSession Method

Starts an initialized Microsoft® DirectPlay® Voice session within a running DirectPlay transport session. This method must be successfully called before the clients can complete a connection to the voice session.

Syntax

HRESULT StartSession(

    PDVSESSIONDESC pSessionDesc,
    DWORD dwFlags
);

Parameters

pSessionDesc
[in] Pointer to a DVSESSIONDESC structure that contains the session description.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING | An asynchronous call of this type is already pending.
DVERR_HOSTING | The object is the host of the session.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPOINTER | The pointer specified is invalid.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_COMPRESSIONNOTSUPPORTED | The specified compression type is not supported on the local computer.

Remarks

The IDirectPlayVoiceServer::Initialize method must be called before this method is called. The voice session can be hosted on any client in the session if the voice session is peer-to-peer. If the voice session is not peer-to-peer, it must be hosted on the transport client, which is the host of a active transport session.

The DVSESSIONDESC structure contains the type of voice session to start. The type of voice session can have a dramatic effect on the CPU and bandwidth usage for both the client and the server. To use the default compression type, set the DVSESSIONDESC structure's guidCT member to DPVCTGUID_DEFAULT.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceServer::StopSession Method

Stops the Microsoft® DirectPlay® Voice session.

Syntax

HRESULT StopSession(

    DWORD dwFlags
);

Parameters

dwFlags
[in] Flag. The following flag can be set.
DVFLAGS_NOHOSTMIGRATE
The host will not migrate regardless of session and transport settings. Use this flag when you want to shut down the voice session completely.

Return Value

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING | An asynchronous call of this type is already pending.
DVERR_INVALIDFLAGS | The flags passed to this method are invalid.
DVERR_INVALIDOBJECT | The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_NOTHOSTING | The object is not the host of the session.
DVERR_NOTINITIALIZED | The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_SESSIONLOST | The transport has lost the connection to the session.

Remarks

This method returns DVERR_ALREADYPENDING if it is called while another thread is processing a IDirectPlayVoiceServer::StopSession request.

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceTest Interface

Applications use the IDirectPlayVoiceTest::CheckAudioSetup method of the IDirectPlayVoiceTest interface to test the Microsoft® DirectPlay® Voice audio configuration.

IDirectPlayVoiceTest Members

CheckAudioSetup

Runs the Audio Setup Wizard on the specified devices. This wizard runs a series of tests on the devices to determine if they are capable of full duplex audio and to ensure that the microphone is plugged in and working correctly on the capture device.

Interface Information

Inherits from | IUnknown
Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


IDirectPlayVoiceTest::CheckAudioSetup Method

Runs the Audio Setup Wizard on the specified devices. This wizard runs a series of tests on the devices to determine if they are capable of full duplex audio and to ensure that the microphone is plugged in and working correctly on the capture device.

Syntax

HRESULT CheckAudioSetup(

    const GUID *pguidPlaybackDevice,
    const GUID *pguidCaptureDevice,
    HWND hwndParent,
    DWORD dwFlags
);

Parameters

pguidPlaybackDevice
[in] Pointer to the globally unique identifier (GUID) that identifies the playback device to test. If NULL is passed for this parameter, Microsoft® DirectPlay® Voice tests the system default playback device defined by Microsoft DirectSound®. You can also pass one of the DirectSound default GUIDs:
DSDEVID_DefaultPlayback
The system default playback device.
DSDEVID_DefaultVoicePlayback
The default voice playback device.
pguidCaptureDevice
[in] Pointer to the GUID that identifies the capture device to test. If NULL is passed for this parameter, DirectPlay Voice tests the system default capture device defined by DirectSound. You can also pass one of the DirectSound default GUIDs:
DSDEVID_DefaultCapture
The default system capture device. You can also specify this device by passing a NULL pointer in the device GUID parameter.
DSDEVID_DefaultVoiceCapture
The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.
hwndParent
[in] The test wizard invoked by this method is modal. If the calling application has a window that should be the parent window of the wizard, it should pass a handle to that window in this parameter. If the calling application does not have a window, it can pass NULL. If the DVFLAGS_QUERYONLY flag is specified, this parameter is not used and the application can pass NULL.
dwFlags
[in] Flags. The following flags can be set.
DVFLAGS_QUERYONLY
Audio setup is not run. Instead, the method checks the registry to see if the devices have been tested. If the devices have not been tested, the method returns DVERR_RUNSETUP. If the devices have been tested, the method returns DV_FULLDUPLEX if the devices support full duplex audio, or DV_HALFDUPLEX if the devices do not support full duplex audio.
DVFLAGS_ALLOWBACK
Passing this flag enables the Back button on the wizard's Welcome page. If the user clicks the Back button on the Welcome page, the wizard exits, and IDirectPlayVoiceTest::CheckAudioSetup returns DVERR_USERBACK.

Return Value

Returns DV_OK, DV_FULLDUPLEX, DV_HALFDUPLEX if successful, or one of the following error values.

DVERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DVERR_RUNSETUP | The specified audio configuration has not been tested. Call the IDirectPlayVoiceTest::CheckAudioSetup method.
DVERR_INVALIDDEVICE | The specified device is invalid.

Remarks

This method contains user interface (UI) elements and displays dialog boxes. If the DVFLAGS_QUERYONLY flag is specified, the tests are not actually run and no UI is raised. Instead, the registry is checked to determine the results of a previous test of these devices.

If the user cancels the wizard, the IDirectPlayVoiceTest::CheckAudioSetup call returns DVERR_USERCANCEL. The calling application can then handle the situation appropriately. For example, in DirectPlay Voice part of the gaming options control panel application, if the user clicks Cancel, the dialog box displays a message indicating that voice cannot be used because the wizard has been canceled.

This method might return DVERR_INVALIDDEVICE if the device specified does not exist. Also, if you specify the default device and this method still returns this error, then there are no sound devices on the system.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl Interface

Applications use methods of the IDP8SimControl interface to create a DP8Sim session and test applications under a variety of network conditions.

IDP8SimControl Members

ClearAllStatistics

Clears all of the current DP8Sim statistics.

Close

Closes the open connection to a session. This method must be called on any object successfully initialized with IDP8SimControl::Initialize.

GetAllParameters

Retrieves all of the current DP8Sim settings.

GetAllStatistics

Retrieves all of the current DP8Sim statistics.

Initialize

Initializes the IDP8SimControl interface. This method must be called before calling any other methods of this interface.

SetAllParameters

Modifies all of the current DP8Sim settings.

Interface Information

Inherits from | IUnknown
Header | dp8sim.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::ClearAllStatistics Method

Clears all of the current DP8Sim statistics.

Syntax

HRESULT ClearAllStatistics(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_NOTINITIALIZED | The DP8Sim control object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::Close Method

Closes the open connection to a session. This method must be called on any object successfully initialized with IDP8SimControl::Initialize.

Syntax

HRESULT Close(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_NOTINITIALIZED | The DP8Sim control object has not been initialized.

Remarks

This method will cancel any operations still outstanding.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::GetAllParameters Method

Retrieves all of the current DP8Sim settings.

Syntax

HRESULT GetAllParameters(

    DP8SIM_PARAMETERS *const pdp8spSend,
    DP8SIM_PARAMETERS *const pdp8spReceive,
    const DWORD dwFlags
);

Parameters

pdp8spSend
[out] Pointer to a DP8SIM_PARAMETERS structure to be filled with the current send parameters.
pdp8spReceive
[out] Pointer to a DP8SIM_PARAMETERS structure to be filled with the current receive parameters.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DP8SIMERR_INVALIDPOINTER | A pointer specified as a parameter is invalid.
DP8SIMERR_NOTINITIALIZED | The DP8Sim control object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::GetAllStatistics Method

Retrieves all of the current DP8Sim statistics.

Syntax

HRESULT GetAllStatistics(

    DP8SIM_STATISTICS *const pdp8ssSend,
    DP8SIM_STATISTICS *const pdp8ssReceive,
    const DWORD dwFlags
);

Parameters

pdp8ssSend
[out] Pointer to a DP8SIM_STATISTICS structure to be filled with the current send statistics.
pdp8ssReceive
[out] Pointer to a DP8SIM_STATISTICS structure to be filled with the current receive statistics.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DP8SIMERR_INVALIDPOINTER | A pointer specified as a parameter is invalid.
DP8SIMERR_NOTINITIALIZED | The DP8Sim control object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::Initialize Method

Initializes the IDP8SimControl interface. This method must be called before calling any other methods of this interface.

Syntax

HRESULT Initialize(

    const DWORD dwFlags
);

Parameters

dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_ALREADYINITIALIZED | The DP8Sim control object has already been initialized.
DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_MISMATCHEDVERSION | A different version of DP8Sim is already in use on this system.

Remarks

Call this method first after using CoCreateInstance to obtain the IDP8SimControl interface.

© 2002 Microsoft Corporation. All rights reserved.


IDP8SimControl::SetAllParameters Method

Modifies all of the current DP8Sim settings.

Syntax

HRESULT SetAllParameters(

    const DP8SIM_PARAMETERS *const pdp8spSend,
    const DP8SIM_PARAMETERS *const pdp8spReceive,
    const DWORD dwFlags
);

Parameters

pdp8spSend
[out] Pointer to a DP8SIM_PARAMETERS structure containing the send parameters to set.
pdp8spReceive
[out] Pointer to a DP8SIM_PARAMETERS structure containing the receive parameters to set.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns DP8SIM_OK if successful, or one of the following error values.

DP8SIMERR_INVALIDFLAGS | The flags passed to this method are invalid.
DP8SIMERR_INVALIDOBJECT | The DP8Sim control object specified is invalid.
DP8SIMERR_INVALIDPARAM | One or more of the parameters passed to the method are invalid.
DP8SIMERR_INVALIDPOINTER | A pointer specified as a parameter is invalid.
DP8SIMERR_NOTINITIALIZED | The DP8Sim control object has not been initialized.

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section contains functions that are used to create Microsoft® DirectPlay® interface objects.

Functions

  • DirectPlay8AddressCreate
  • DirectPlay8Create
  • DirectPlay8LobbyCreate
  • DirectPlayVoiceCreate

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay8AddressCreate Function

Not currently supported.

Users should instead use CoCreateInstance to create the object.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay8Create Function

Not currently supported.

Users should instead use CoCreateInstance to create the object.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlay8LobbyCreate Function

Not currently supported.

Users should instead use CoCreateInstance to create the object.

© 2002 Microsoft Corporation. All rights reserved.


DirectPlayVoiceCreate Function

Not currently supported.

Users should instead use CoCreateInstance to create the object.

© 2002 Microsoft Corporation. All rights reserved.


Callback Functions

This section contains Microsoft® DirectPlay® prototype callback functions that are used in Peer-to-Peer, Client/Server, Lobbied, and Voice sessions.

Functions

  • PDVMESSAGEHANDLER
  • PFNDPNMESSAGEHANDLER

© 2002 Microsoft Corporation. All rights reserved.


PDVMESSAGEHANDLER Prototype

PDVMESSAGEHANDLER is an application-defined callback function used by the IDirectPlayVoiceClient and IDirectPlayVoiceServer interfaces to send messages to the user.

Syntax

typedef HRESULT (CALLBACK *PDVMESSAGEHANDLER)(

    LPVOID pvUserContext,
    DWORD dwMessageType,
    LPVOID lpMessage
);

Parameters

pvUserContext
Pointer to the application-defined structure that will be passed to this callback function. This is defined in the lpUserContext parameter of the IDirectPlayVoiceServer::Initialize and IDirectPlayVoiceClient::Initialize methods.
dwMessageType
One of the following message types.
DVMSGID_CONNECTRESULT
DVMSGID_CREATEVOICEPLAYER
DVMSGID_DELETEVOICEPLAYER
DVMSGID_DISCONNECTRESULT
DVMSGID_GAINFOCUS
DVMSGID_HOSTMIGRATED
DVMSGID_INPUTLEVEL
DVMSGID_LOCALHOSTSETUP
DVMSGID_LOSTFOCUS
DVMSGID_OUTPUTLEVEL
DVMSGID_PLAYEROUTPUTLEVEL
DVMSGID_PLAYERVOICESTART
DVMSGID_PLAYERVOICESTOP
DVMSGID_RECORDSTART
DVMSGID_RECORDSTOP
DVMSGID_SESSIONLOST
DVMSGID_SETTARGETS
lpMessage
Structure containing message information.

Return Value

See the documentation for the individual messages for appropriate return values. Unless otherwise noted, this function should return DV_OK.

Remarks

When implementing this callback function, you must first view the message type returned in the dwMessageType parameter and then cast the message structure (lpMessage) to that type to obtain message information. Some messages don't have a defined structure because they have no parameters. For these messages, the lpMessage parameter is NULL.

Note This function may be called on multiple different threads at the same time. It must thus be threadsafe and reentrant.

All message structures have the same name as the corresponding message types except the prefix is DVMSG_ instead of DVMSGID_. For example, the structure for DVMSGID_RECORDSTART is DVMSG_RECORDSTART.

The structure sent to the message handler is valid only for the duration of the call. Therefore, if you want to use any of the information passed into the function after the handler function has returned you must make a copy of the data.

Callback messages from the same player are serialized. Once you receive a message from a player, you will not receive another until you have handled the first message, and the callback function has returned.

Only messages that are specified in the message mask through a call to the IDirectPlayVoiceClient::Initialize, IDirectPlayVoiceServer::Initialize, IDirectPlayVoiceClient::SetNotifyMask and IDirectPlayVoiceServer::SetNotifyMask methods are sent to this callback function.

The DVMSGID_GAINFOCUS and DVMSGID_LOSTFOCUS message structures have not been implemented in this release of Microsoft® DirectPlay®.

Prototype Information

Header | dvoice.h
Import library | None
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


PFNDPNMESSAGEHANDLER Prototype

PFNDPNMESSAGEHANDLER is an application-defined callback function used by the IDirectPlay8Peer, IDirectPlay8Client, IDirectPlay8Server, IDirectPlay8LobbyClient, and IDirectPlay8LobbiedApplication interfaces to process messages.

Syntax

typedef HRESULT (CALLBACK *PFNDPNMESSAGEHANDLER)(

    PVOID pvUserContext,
    DWORD dwMessageType,
    PVOID pMessage
);

Parameters

pvUserContext
Pointer to the application-defined structure that will be passed to this callback function. This is defined in the pvUserContext parameter of the Initialize method.
dwMessageType
One of the following DPN_ message types that are generated by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces. Each interface uses a different subset of the available DPN_ messages. Refer to the interface documentation for details. Additionally, if the application supports Microsoft® DirectPlay® lobby functionality, this parameter can specify one of the following DPL_ message types that are generated by the IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication interfaces. Each lobby interface uses a different subset of the available DPL_ messages. Refer to the interface documentation for details.
DPN_MSGID_ADD_PLAYER_TO_GROUP
DPN_MSGID_ASYNC_OP_COMPLETE
DPN_MSGID_CLIENT_INFO
DPN_MSGID_CONNECT_COMPLETE
DPN_MSGID_CREATE_GROUP
DPN_MSGID_CREATE_PLAYER
DPN_MSGID_DESTROY_GROUP
DPN_MSGID_DESTROY_PLAYER
DPN_MSGID_ENUM_HOSTS_QUERY
DPN_MSGID_ENUM_HOSTS_RESPONSE
DPN_MSGID_GROUP_INFO
DPN_MSGID_HOST_MIGRATE
DPN_MSGID_INDICATE_CONNECT
DPN_MSGID_INDICATED_CONNECT_ABORTED
DPN_MSGID_PEER_INFO
DPN_MSGID_RECEIVE
DPN_MSGID_REMOVE_PLAYER_FROM_GROUP
DPN_MSGID_RETURN_BUFFER
DPN_MSGID_SEND_COMPLETE
DPN_MSGID_SERVER_INFO
DPN_MSGID_TERMINATE_SESSION
DPL_MSGID_CONNECT
DPL_MSGID_CONNECTION_SETTINGS
DPL_MSGID_DISCONNECT
DPL_MSGID_RECEIVE
DPL_MSGID_SESSION_STATUS
pMessage
Structure containing message information.

Return Value

See the documentation for the individual messages for appropriate return values. Unless otherwise noted, this function should return S_OK.

Remarks

This function must be threadsafe because it might be called reentrantly through multiple threads.

Callback messages from the same player are serialized. Once you receive a message from a player, you will not receive another until you have handled the first message, and the callback function has returned.

The message structures have the same name as the message type except the "DPN_MSGID" is replaces with "DPNMSG". For example, the DPN_MSGID_TERMINATE_SESSION message type uses the DPNMSG_TERMINATE_SESSION message structure to convey the actual message information.

When implementing this callback function, first view the message type returned in the dwMessageType parameter and then cast the message structure (pMessage) to that type to obtain message information. Some messages don't have a defined structure because they have no parameters. For these messages, the pMessage parameter is NULL.

Prototype Information

Header | dplay8.h
Import library | None
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


System Messages

This section contains Microsoft® DirectPlay® messages that are received by a DirectPlay callback message handler. DirectPlay uses these messages to convey information from the system to a DirectPlay application.

  • DirectPlay Core Messages
  • DirectPlay Lobby Messages
  • DirectPlay Voice Messages

DirectPlay Core Messages

The following messages can be processed by the DirectPlay core callback message handlers.

Messages

  • DPN_MSGID_ADD_PLAYER_TO_GROUP
  • DPN_MSGID_APPLICATION_DESC
  • DPN_MSGID_ASYNC_OP_COMPLETE
  • DPN_MSGID_CLIENT_INFO
  • DPN_MSGID_CONNECT_COMPLETE
  • DPN_MSGID_CREATE_GROUP
  • DPN_MSGID_CREATE_PLAYER
  • DPN_MSGID_CREATE_SENDER_CONTEXT
  • DPN_MSGID_CREATE_THREAD
  • DPN_MSGID_DESTROY_GROUP
  • DPN_MSGID_DESTROY_PLAYER
  • DPN_MSGID_DESTROY_THREAD
  • DPN_MSGID_ENUM_HOSTS_QUERY
  • DPN_MSGID_ENUM_HOSTS_RESPONSE
  • DPN_MSGID_GROUP_INFO
  • DPN_MSGID_HOST_MIGRATE
  • DPN_MSGID_INDICATE_CONNECT
  • DPN_MSGID_INDICATED_CONNECT_ABORTED
  • DPN_MSGID_NAT_RESOLVER_QUERY
  • DPN_MSGID_PEER_INFO
  • DPN_MSGID_RECEIVE
  • DPN_MSGID_REMOVE_PLAYER_FROM_GROUP
  • DPN_MSGID_RETURN_BUFFER
  • DPN_MSGID_SEND_COMPLETE
  • DPN_MSGID_SERVER_INFO
  • DPN_MSGID_TERMINATE_SESSION

DirectPlay Lobby Messages

The following messages are handled by lobby client and lobbied application callback message handlers.

Lobby Messages

  • DPL_MSGID_CONNECT
  • DPL_MSGID_CONNECTION_SETTINGS
  • DPL_MSGID_DISCONNECT
  • DPL_MSGID_RECEIVE
  • DPL_MSGID_SESSION_STATUS

DirectPlay Voice Messages

The following messages are handled by DirectPlay voice callback message handlers.

Voice Messages

  • DVMSGID_CONNECTRESULT
  • DVMSGID_CREATEVOICEPLAYER
  • DVMSGID_DELETEVOICEPLAYER
  • DVMSGID_DISCONNECTRESULT
  • DVMSGID_GAINFOCUS
  • DVMSGID_HOSTMIGRATED
  • DVMSGID_INPUTLEVEL
  • DVMSGID_LOCALHOSTSETUP
  • DVMSGID_LOSTFOCUS
  • DVMSGID_OUTPUTLEVEL
  • DVMSGID_PLAYEROUTPUTLEVEL
  • DVMSGID_PLAYERVOICESTART
  • DVMSGID_PLAYERVOICESTOP
  • DVMSGID_RECORDSTART
  • DVMSGID_RECORDSTOP
  • DVMSGID_SESSIONLOST
  • DVMSGID_SETTARGETS

© 2002 Microsoft Corporation. All rights reserved.


DPL_MSGID_CONNECT Message

Microsoft® DirectPlay® generates a DPL_MSGID_CONNECT message when a lobby client connects to the lobbied application through the IDirectPlay8LobbyClient::ConnectApplication method.

The DPL_MESSAGE_CONNECT structure is passed with the DPL_MSGID_CONNECT message.

Syntax

typedef struct _DPL_MESSAGE_CONNECT {
    DWORD dwSize;
    DPNHANDLE hConnectId;
    PDPL_CONNECTION_SETTINGS pdplConnectionSettings;
    PVOID pvLobbyConnectData;
    DWORD dwLobbyConnectDataSize;
    PVOID pvConnectionContext;
}  DPL_MESSAGE_CONNECT, *PDPL_MESSAGE_CONNECT;

Members

dwSize
Size of the DPL_MESSAGE_CONNECT message structure. The application must set this member before it uses the structure.
hConnectId
Handle used to identify the connection. This handle is used in subsequent calls to IDirectPlay8LobbyClient::Send and IDirectPlay8LobbyClient::ReleaseApplication.
pdplConnectionSettings
Pointer to a DPL_CONNECTION_SETTINGS structure with connection information.
pvLobbyConnectData
Pointer to lobby connection data.
dwLobbyConnectDataSize
Variable of type DWORD specifying the size of the data contained in the pvLobbyConnectData member.
pvConnectionContext
Context value associated with this connection. For lobbied applications, set this parameter when this message is received in your message handler to associate the context value with the connection. This may be set to NULL to disable context values.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_MSGID_CONNECTION_SETTINGS Message

The DPL_MSGID_CONNECTION_SETTINGS message is sent from the lobby client to the lobby application when IDirectPlay8LobbyClient::SetConnectionSettings is called. It is also sent from the lobby application to the lobby client when IDirectPlay8LobbiedApplication::SetConnectionSettings is called.

The DPL_MESSAGE_CONNECTION_SETTINGS structure is passed with the DPL_MSGID_CONNECTION_SETTINGS message.

Syntax

typedef struct _DPL_MESSAGE_CONNECTION_SETTINGS {
    DWORD dwSize;
    DPNHANDLE hSender;
    PDPL_CONNECTION_SETTINGS pdplConnectionSettings;
    PVOID pvConnectionContext;
}  DPL_MESSAGE_CONNECTION_SETTINGS, *PDPL_MESSAGE_CONNECTION_SETTINGS;

Members

dwSize
Contains the size of the DPL_MESSAGE_CONNECTION_SETTINGS structure. It should be set to sizeof( DPL_MESSAGE_CONNECTION_SETTINGS ).
hSender
Contains the handle to the connection that sent this message.
pdplConnectionSettings
Contains a pointer to a DPL_CONNECTION_SETTINGS structure describing the connection settings for the specified connection.
pvConnectionContext
Pointer to a context value that has been set for the connection.

Remarks

Return from the message callback function with DPN_OK.

The contents of the message are valid only for the duration of the message callback. Therefore, if you want to use the data contained in the message, you must make a copy before returning. In addition, if you want to use the addressing objects you must call AddRef on each address to ensure you retain a reference.

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between the lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and, in your IDirectPlay8LobbiedApplication interface, pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_MSGID_DISCONNECT Message

Microsoft® DirectPlay® generates a DPL_MSGID_DISCONNECT message when a lobby client disconnects from a lobbied application through the IDirectPlay8LobbyClient::ReleaseApplication method.

The DPL_MESSAGE_DISCONNECT structure contains information for the DPL_MSGID_DISCONNECT system message.

Syntax

typedef struct _DPL_MESSAGE_DISCONNECT {
    DWORD dwSize;
    DPNHANDLE hDisconnectId;
    HRESULT hrReason;
    PVOID pvConnectionContext;
}  DPL_MESSAGE_DISCONNECT, *PDPL_MESSAGE_DISCONNECT;

Members

dwSize
Size of the DPL_MESSAGE_DISCONNECT message structure. The application must set this member before it uses the structure.
hDisconnectId
Handle specifying the disconnection identifier (ID).
hrReason
Reason for the disconnection.
DPN_OK
It was a standard disconnection.
DPNERR_CONNECTIONLOST
This will be set if the process running the client or application exited abnormally.
pvConnectionContext
Context value that has been set for the connection.

Remarks

Return from the message callback function with DPN_OK.

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and, in your IDirectPlay8LobbiedApplication interface, pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_MSGID_RECEIVE Message

Microsoft® DirectPlay® generates the DPL_MSGID_RECEIVE message when the target receives a message sent by the IDirectPlay8LobbyClient::Send or IDirectPlay8LobbiedApplication::Send method.

The DPL_MESSAGE_RECEIVE structure contains information for the DPL_MSGID_RECEIVE system message.

Syntax

typedef struct _DPL_MESSAGE_RECEIVE {
    DWORD dwSize;
    DPNHANDLE hSender;
    BYTE *pBuffer;
    DWORD dwBufferSize;
    PVOID pvConnectionContext;
}  DPL_MESSAGE_RECEIVE, *PDPL_MESSAGE_RECEIVE;

Members

dwSize
Size of the DPL_MESSAGE_RECEIVE message structure. The application must set this member before it uses the structure.
hSender
Handle of the client that sent the message.
pBuffer
Pointer to message data.
dwBufferSize
Size of the message data contained in the pBuffer.
pvConnectionContext
Context value that has been set for the connection.

Remarks

Return from the message callback function with DPN_OK.

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between the lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A, and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value, and in your IDirectPlay8LobbiedApplication interface, pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_MSGID_SESSION_STATUS Message

Microsoft® DirectPlay® generates the DPL_MSGID_SESSION_STATUS message when the session has been updated with a call to the IDirectPlay8LobbiedApplication::UpdateStatus method.

The DPL_MESSAGE_SESSION_STATUS structure contains the information for the DPL_MSGID_SESSION_STATUS system message.

Syntax

typedef struct _DPL_MESSAGE_SESSION_STATUS {
    DWORD dwSize;
    DPNHANDLE hSender;
    DWORD dwStatus;
    PVOID pvConnectionContext;
}  DPL_MESSAGE_SESSION_STATUS, *PDPL_MESSAGE_SESSION_STATUS;

Members

dwSize
Size of the DPL_MESSAGE_SESSION_STATUS message structure. The application must set this member before it uses the structure.
hSender
The handle of the application that sent the status update message.
dwStatus
Updated status of the session. This member can be set to one of the following values.
DPLSESSION_CONNECTED
The lobbied application is currently connected to a session.
DPLSESSION_COULDNOTCONNECT
The lobbied application could not connect to the session.
DPLSESSION_DISCONNECTED
The lobbied application is currently disconnected from the session.
DPLSESSION_TERMINATED
The connection between session host and the lobbied application has been terminated.
DPLSESSION_HOSTMIGRATED
The host of a peer-to-peer session has migrated. The local client is not the new host.
DPLSESSION_HOSTMIGRATEDHERE
The host of a peer-to-peer session has migrated. The local client is the new host.
pvConnectionContext
Context value that has been set for the connection.

Remarks

Return from the message callback function with DPN_OK.

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and in your IDirectPlay8LobbiedApplication interface pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_ADD_PLAYER_TO_GROUP Message

Microsoft® DirectPlay® generates the DPN_MSGID_ADD_PLAYER_TO_GROUP message when a player has been added to a group in a peer-to-peer or client/server session.

The DPNMSG_ADD_PLAYER_TO_GROUP structure contains information for the DPN_MSGID_ADD_PLAYER_TO_GROUP system message.

Syntax

typedef struct _DPNMSG_ADD_PLAYER_TO_GROUP {
    DWORD dwSize;
    DPNID dpnidGroup;
    PVOID pvGroupContext;
    DPNID dpnidPlayer;
    PVOID pvPlayerContext;
}  DPNMSG_ADD_PLAYER_TO_GROUP, *PDPNMSG_ADD_PLAYER_TO_GROUP;

Members

dwSize
Size of this structure.
dpnidGroup
DPNID of the group to add the player.
pvGroupContext
Group context value.
dpnidPlayer
DPNID of the player added to the group.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_APPLICATION_DESC Message

This message indicates that the application description has been changed. There is no accompanying structure.

Remarks

Return from the message callback function with DPN_OK.

To determine the new application description, call the GetApplicationDesc method exposed by IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interfaces.

Message Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_ASYNC_OP_COMPLETE Message

Microsoft® DirectPlay® generates the DPN_MSGID_ASYNC_OP_COMPLETE message when an asynchronous request has completed.

The DPNMSG_ASYNC_OP_COMPLETE structure contains information for the DPN_MSGID_ASYNC_OP_COMPLETE system message.

Syntax

typedef struct _DPNMSG_ASYNC_OP_COMPLETE {
    DWORD dwSize;
    DPNHANDLE hAsyncOp;
    PVOID pvUserContext;
    HRESULT hResultCode;
}  DPNMSG_ASYNC_OP_COMPLETE, *PDPNMSG_ASYNC_OP_COMPLETE;

Members

dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
Supplied user context.
hResultCode
HRESULT indicating the result of the asynchronous operation.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CLIENT_INFO Message

Microsoft® DirectPlay® generates the DPN_MSGID_CLIENT_INFO message when client data is modified during a client/server session.

The DPNMSG_CLIENT_INFO structure contains information for the DPN_MSGID_CLIENT_INFO system message.

Syntax

typedef struct _DPNMSG_CLIENT_INFO {
    DWORD dwSize;
    DPNID dpnidClient;
    PVOID pvPlayerContext;
}  DPNMSG_CLIENT_INFO, *PDPNMSG_CLIENT_INFO;

Members

dwSize
Size of this structure.
dpnidClient
DPNID of the client for client information.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CONNECT_COMPLETE Message

Microsoft® DirectPlay® generates the DPN_MSGID_CONNECT_COMPLETE message when the connection attempt has been completed in a peer-to-peer or client/server session.

The DPNMSG_CONNECT_COMPLETE structure contains information for the DPN_MSGID_CONNECT_COMPLETE system message.

Syntax

typedef struct _DPNMSG_CONNECT_COMPLETE {
    DWORD dwSize;
    DPNHANDLE hAsyncOp;
    PVOID pvUserContext;
    HRESULT hResultCode;
    PVOID pvApplicationReplyData;
    DWORD dwApplicationReplyDataSize;
    DPNID dpnidLocal;
}  DPNMSG_CONNECT_COMPLETE, *PDPNMSG_CONNECT_COMPLETE;

Members

dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
User context supplied when the IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect methods are called.
hResultCode
HRESULT describing the result of the connection attempt. See the Return Values section in the IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect method for more information. Additionally, DPNERR_PLAYERNOTREACHABLE will be returned if a player has tried to join a peer-to-peer session where at least one other existing player in the session cannot connect to the joining player.
pvApplicationReplyData
Connection reply data returned from the host or server.
dwApplicationReplyDataSize
Size of the data, in bytes, of the pvApplicationReplyData member.
dpnidLocal
Specifies the DPNID of the local player.

Remarks

Return from the message callback function with DPN_OK.

This message is generated whether or not the connection was successful.

Message Information

Header | dplay8.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CREATE_GROUP Message

Microsoft® DirectPlay® generates the DPN_MSGID_CREATE_GROUP message when a group is created.

The DPNMSG_CREATE_GROUP structure contains information for the DPN_MSGID_CREATE_GROUP system message.

Syntax

typedef struct _DPNMSG_CREATE_GROUP {
    DWORD dwSize;
    DPNID dpnidGroup;
    DPNID dpnidOwner;
    PVOID pvGroupContext;
    PVOID pvOwnerContext;
}  DPNMSG_CREATE_GROUP, *PDPNMSG_CREATE_GROUP;

Members

dwSize
Size of this structure.
dpnidGroup
DPNID of the of the created group.
dpnidOwner
DPNID of the of the group's owner. This value is only set for groups that have the DPNGROUP_AUTODESTRUCT flag set in the dwGroupFlags member of the DPN_GROUP_INFO structure.
pvGroupContext
Group context value.
pvOwnerContext
Owner context value.

Remarks

Return from the message callback function with DPN_OK.

The only method of setting the group context value is through this system message. Once set, group context values cannot be changed.

Message Information

Header | dplay8.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CREATE_PLAYER Message

Microsoft® DirectPlay® generates the DPN_MSGID_CREATE_PLAYER message when a player is added to a peer-to-peer or client/server session.

The DPNMSG_CREATE_PLAYER structure contains information for the DPN_MSGID_CREATE_PLAYER system message.

Syntax

typedef struct _DPNMSG_CREATE_PLAYER {
    DWORD dwSize;
    DPNID dpnidPlayer;
    PVOID pvPlayerContext;
}  DPNMSG_CREATE_PLAYER, *PDPNMSG_CREATE_PLAYER;

Members

dwSize
Size of this structure.
dpnidPlayer
DPNID of the player that was added to the session.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

The only method of setting the player context value is through this message. You can either set the player context value directly, through this message, or indirectly through DPN_MSGID_INDICATE_CONNECT. Once a player context value has been set, it cannot be changed.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CREATE_SENDER_CONTEXT Message

Microsoft® DirectPlay® generates a DPN_MSGID_CREATE_SENDER_CONTEXT message when another player is recognized by the local player.

Syntax

typedef struct _DPNMSG_CREATE_SENDER_CONTEXT {
    DWORD dwSize;
    PVOID pvSenderContext;
}  DPNMSG_CREATE_SENDER_CONTEXT, *PDPNMSG_CREATE_SENDER_CONTEXT;

Members

dwSize
Size of this structure.
pvSenderContext
Sender context value.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_CREATE_THREAD Message

Microsoft® DirectPlay® generates the DPN_MSGID_CREATE_THREAD message when a new thread is created.

The DPNMSG_CREATE_THREAD structure contains information for the DPN_MSGID_CREATE_THREAD system message.

Syntax

typedef struct _DPNMSG_CREATE_THREAD {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwProcessorNum;
    PVOID pvUserContext;
}  DPNMSG_CREATE_THREAD, *PDPNMSG_CREATE_THREAD;

Members

dwSize
Size of this structure.
dwFlags
Reserved. Must be 0.
dwProcessorNum
Specifies the processor index to which this thread is bound.
pvUserContext
Thread context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_DESTROY_GROUP Message

Microsoft® DirectPlay® generates the DPN_MSGID_DESTROY_GROUP message when a group is destroyed from a peer-to-peer or client/server session.

The DPNMSG_DESTROY_GROUP structure contains information for the DPN_MSGID_DESTROY_GROUP system message.

Syntax

typedef struct _DPNMSG_DESTROY_GROUP {
    DWORD dwSize;
    DPNID dpnidGroup;
    PVOID pvGroupContext;
    DWORD dwReason;
}  DPNMSG_DESTROY_GROUP, *PDPNMSG_DESTROY_GROUP;

Members

dwSize
Size of this structure.
dpnidGroup
DPNID of the group deleted from the session.
pvGroupContext
Group context value.
dwReason
The following flag can be set to indicate why the player was destroyed.
DPNDESTROYGROUPREASON_SESSIONTERMINATED
The group is being destroyed because the session was terminated.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_DESTROY_PLAYER Message

Microsoft® DirectPlay® generates the DPN_MSGID_DESTROY_PLAYER message when a player leaves a peer-to-peer or client/server session.

The DPNMSG_DESTROY_PLAYER structure contains information for the DPN_MSGID_DESTROY_PLAYER system message.

Syntax

typedef struct _DPNMSG_DESTROY_PLAYER {
    DWORD dwSize;
    DPNID dpnidPlayer;
    PVOID pvPlayerContext;
    DWORD dwReason;
}  DPNMSG_DESTROY_PLAYER, *PDPNMSG_DESTROY_PLAYER;

Members

dwSize
Size of this structure.
dpnidPlayer
DPNID of the player deleted from the session.
pvPlayerContext
Player context value.
dwReason
One of the following flags indicating why the player was destroyed.
DPNDESTROYPLAYERREASON_NORMAL
The player is being deleted for normal reasons.
DPNDESTROYPLAYERREASON_CONNECTIONLOST
The player is being deleted because the connection was lost.
DPNDESTROYPLAYERREASON_SESSIONTERMINATED
The player is being deleted because the session was terminated.
DPNDESTROYPLAYERREASON_HOSTDESTROYEDPLAYER
The player is being deleted because the host called IDirectPlay8Peer::DestroyPeer.

Remarks

Return from the message callback function with DPN_OK.

In client/server mode, this message is received only by the server. In peer-to-peer mode, all players receive this message.

When the server closes a session, it receives a DPN_MSGID_DESTROY_PLAYER message for all connected players. Because the server knows that it is disconnecting, this is normal behavior, and the dwReason member of the associated structure is set to DPNDESTROYPLAYERREASON_NORMAL. The DPNDESTROYPLAYERREASON_SESSIONTERMINATED value is only set for unexpected disconnections.

You might receive DPN_MSGID_CREATE_PLAYER and DPN_MSGID_DESTROY_PLAYER messages on different threads. However, you will not receive a DPN_MSGID_DESTROY_PLAYER message before your callback function has returned from receiving a DPN_MSGID_CREATE_PLAYER message.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_DESTROY_THREAD Message

Microsoft® DirectPlay® generates the DPN_MSGID_DESTROY_THREAD message when a thread is shut down.

The DPNMSG_DESTROY_THREAD structure contains information for the DPN_MSGID_DESTROY_THREAD system message.

Syntax

typedef struct _DPNMSG_DESTROY_THREAD {
    DWORD dwSize;
    DWORD dwProcessorNum;
    PVOID pvUserContext;
}  DPNMSG_DESTROY_THREAD, *PDPNMSG_DESTROY_THREAD;

Members

dwSize
Size of this structure.
dwProcessorNum
Specifies the processor index to which this thread is bound.
pvUserContext
Thread context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_ENUM_HOSTS_QUERY Message

Microsoft® DirectPlay® sends the DPN_MSGID_ENUM_HOSTS_QUERY message to the host's message handler when a peer or client is enumerating the available hosts.

The DPNMSG_ENUM_HOSTS_QUERY structure contains information for the DPN_MSGID_ENUM_HOSTS_QUERY system message.

Syntax

typedef struct _DPNMSG_ENUM_HOSTS_QUERY {
    DWORD dwSize;
    IDirectPlay8Address *pAddressSender;
    IDirectPlay8Address *pAddressDevice;
    PVOID pvReceivedData;
    DWORD dwReceivedDataSize;
    DWORD dwMaxResponseDataSize;
    PVOID pvResponseData;
    DWORD dwResponseDataSize;
    PVOID pvResponseContext;
}  DPNMSG_ENUM_HOSTS_QUERY, *PDPNMSG_ENUM_HOSTS_QUERY;

Members

dwSize
Size of this structure.
pAddressSender
Pointer an IDirectPlay8Address interface specifying the address of the sender. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer an IDirectPlay8Address interface specifying the address of the device. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pvReceivedData
Pointer to the data received from the enumeration.
dwReceivedDataSize
Size of the data pointed to in the pvReceivedData member.
dwMaxResponseDataSize
Maximum allowed size for the enumeration response.
pvResponseData
Pointer to the response data from the enumeration. This data must be valid beyond the scope of the callback message handler. It cannot be stack-based. You will receive a DPN_MSGID_RETURN_BUFFER message when DirectPlay is finished with this buffer.
dwResponseDataSize
Size of the data pointed to in the pvResponseData member.
pvResponseContext
Pointer to a response context value. This value will be passed to the host's message handler with the DPN_MSGID_RETURN_BUFFER message as the pvUserContext member of the associated structure.

Remarks

Return from the message callback function with DPN_OK.

When you respond normally to this query, DirectPlay will send you a DPN_MSGID_RETURN_BUFFER message once the buffer is no longer needed. You can then safely free the buffer.

You can reject the query by returning a value that is not equal to DPN_OK. However, when you reject a query, DirectPlay does not send a reply, does not need a reply buffer, and does not generate a DPN_MSGID_RETURN_BUFFER message.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_ENUM_HOSTS_RESPONSE Message

Microsoft® DirectPlay® sends the DPN_MSGID_ENUM_HOSTS_RESPONSE message to a peer or client's message handler to convey the host's response to an enumeration request.

The DPNMSG_ENUM_HOSTS_RESPONSE structure contains information for the DPN_MSGID_ENUM_HOSTS_RESPONSE system message.

Syntax

typedef struct _DPNMSG_ENUM_HOSTS_RESPONSE {
    DWORD dwSize;
    IDirectPlay8Address *pAddressSender;
    IDirectPlay8Address *pAddressDevice;
    const DPN_APPLICATION_DESC *pApplicationDescription;
    PVOID pvResponseData;
    DWORD dwResponseDataSize;
    PVOID pvUserContext;
    DWORD dwRoundTripLatencyMS;
}  DPNMSG_ENUM_HOSTS_RESPONSE, *PDPNMSG_ENUM_HOSTS_RESPONSE;

Members

dwSize
Size of this structure.
pAddressSender
Pointer to an IDirectPlay8Address interface specifying the address of the host responding to the enumeration. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer an IDirectPlay8Address interface specifying the address of the device. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pApplicationDescription
Pointer to a DPN_APPLICATION_DESC structure containing the application description.
pvResponseData
Pointer to the response data from the enumeration.
dwResponseDataSize
Size of the data pointed to in the pvResponseData member.
pvUserContext
Pointer to the user context value. This value is the same as the user context value passed to IDirectPlay8Peer::EnumHosts or IDirectPlay8Client::EnumHosts.
dwRoundTripLatencyMS
Latency measured in milliseconds.

Remarks

Return from the message callback function with DPN_OK.

Because there is no buffer to fill, this message does not generate a DPN_MSGID_RETURN_BUFFER message.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_GROUP_INFO Message

Microsoft® DirectPlay® generates the DPN_MSGID_GROUP_INFO message when group data is modified during a peer-to-peer or client/server session.

The DPNMSG_GROUP_INFO structure contains information for the DPN_MSGID_GROUP_INFO system message.

Syntax

typedef struct _DPNMSG_GROUP_INFO {
    DWORD dwSize;
    DPNID dpnidGroup;
    PVOID pvGroupContext;
}  DPNMSG_GROUP_INFO, *PDPNMSG_GROUP_INFO;

Members

dwSize
Size of this structure.
dpnidGroup
DPNID of the group for group information.
pvGroupContext
Group context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_HOST_MIGRATE Message

Microsoft® DirectPlay® generates the DPN_MSGID_HOST_MIGRATE message if the DPNSESSION_MIGRATE_HOST flag is set in the DPN_APPLICATION_DESC structure and the host has migrated.

The DPNMSG_HOST_MIGRATE structure contains information for the DPN_MSGID_HOST_MIGRATE system message.

Syntax

typedef struct _DPNMSG_HOST_MIGRATE {
    DWORD dwSize;
    DPNID dpnidNewHost;
    PVOID pvPlayerContext;
}  DPNMSG_HOST_MIGRATE, *PDPNMSG_HOST_MIGRATE;

Members

dwSize
Size of this structure.
dpnidNewHost
DPNID of the player that is now hosting the session.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_INDICATED_CONNECT_ABORTED Message

Microsoft® DirectPlay® generates the DPN_MSGID_INDICATED_CONNECT_ABORTED message if a player's connection drops after it was indicated on the host, but prior to being added to the session though DPN_MSGID_CREATE_PLAYER.

The DPNMSG_INDICATED_CONNECT_ABORTED structure contains information for the DPN_MSGID_INDICATED_CONNECT_ABORTED system message.

Syntax

typedef struct _DPNMSG_INDICATED_CONNECT_ABORTED {
    DWORD dwSize;
    PVOID pvPlayerContext;
}  DPNMSG_INDICATED_CONNECT_ABORTED, *PDPNMSG_INDICATED_CONNECT_ABORTED;

Members

dwSize
Size of this structure.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_INDICATE_CONNECT Message

Microsoft® DirectPlay® generates the DPN_MSGID_INDICATE_CONNECT message when a player attempts to connect to a peer-to-peer or client/server session.

The DPNMSG_INDICATE_CONNECT structure contains information for the DPN_MSGID_INDICATE_CONNECT system message.

Syntax

typedef struct _DPNMSG_INDICATE_CONNECT {
    DWORD dwSize;
    PVOID pvUserConnectData;
    DWORD dwUserConnectDataSize;
    PVOID pvReplyData;
    DWORD dwReplyDataSize;
    PVOID pvReplyContext;
    PVOID pvPlayerContext;
    IDirectPlay8Address *pAddressPlayer;
    IDirectPlay8Address *pAddressDevice;
}  DPNMSG_INDICATE_CONNECT, *PDPNMSG_INDICATE_CONNECT;

Members

dwSize
Size of this structure.
pvUserConnectData
Data of the connecting player.
dwUserConnectDataSize
Size of the data, in bytes, contained in the pvUserConnectData member.
pvReplyData
Connection reply data. This data must be valid beyond the scope of the callback message handler. You will receive a DPN_MSGID_RETURN_BUFFER message when DirectPlay is finished with this buffer.
dwReplyDataSize
Size of the data, in bytes, contained in the pvReplyData member.
pvReplyContext
Buffer context for pvReplyData. This value will be passed to the host's message handler with the DPN_MSGID_RETURN_BUFFER message as the pvUserContext member of the associated structure.
pvPlayerContext
Player context preset.
pAddressPlayer
Pointer to an IDirectPlay8Address interface for the connecting player. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer to an IDirectPlay8Address interface for the device receiving the connect attempt. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.

Remarks

Return DPN_OK to allow the player to join the session. Any other return value will reject the requested connection.

The hResultCode member of the structure associated with the DPN_MSGID_CONNECT_COMPLETE message that is sent to the player requesting a connection will be set to S_OK if the connection was successful. If the connection is rejected, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION, not the value you return from this message.

When an DPN_MSGID_INDICATE_CONNECT notification arrives on the host player's message handler, setting pvPlayerContext before returning the thread will preset the player context value on the respective DPN_MSGID_CREATE_PLAYER notification. This feature allows you to pass a player context value to DPN_MSGID_CREATE_PLAYER.

If you set a player context value, that value is not frozen until the subsequent DPN_MSGID_CREATE_PLAYER message has been processed. You thus have the option of modifying this player context value when you process DPN_MSGID_CREATE_PLAYER.

If a client drops the connection after the server has processed the DPN_MSGID_INDICATE_CONNECT message but before it has processed DPN_MSGID_CREATE_PLAYER, the server will receive a DPN_MSGID_INDICATED_CONNECT_ABORTED message. If you receive this message, free any memory that you allocated while processing DPN_MSGID_INDICATE_CONNECT. When DPN_MSGID_CREATE_PLAYER has been processed, this memory should be freed when you process DPN_MSGID_DESTROY_PLAYER.

If you specify a value for pvUserConnectData, you will subsequently be sent a DPN_MSGID_RETURN_BUFFER message to notify you that you can safely free the buffer.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_NAT_RESOLVER_QUERY Message

Microsoft® DirectPlay® generates the DPN_MSGID_NAT_RESOLVER_QUERY message when a player using the Network Address Translation (NAT) Resolver calls Host, EnumHosts, or Connect.

The DPNMSG_NAT_RESOLVER_QUERY structure contains information for the DPN_MSGID_NAT_RESOLVER_QUERY system message.

Syntax

typedef struct _DPNMSG_NAT_RESOLVER_QUERY {
    DWORD dwSize;
    IDirectPlay8Address pAddressSender;
    IDirectPlay8Address pAddressDevice;
    WCHAR pwszUserString;
}  DPNMSG_NAT_RESOLVER_QUERY, *PDPNMSG_NAT_RESOLVER_QUERY;

Members

dwSize
Size of this structure.
pAddressSender
Address of the client that sent the query.
pAddressDevice
Address of the device that received the query.
pwszUserString
User specified string or NULL if no string was specified.

Remarks

Return from the message callback function with DPN_OK

A player will be using the NAT Resolver if they have called IDirectPlay8Address::AddComponent with the pwszName parameter set to DPNA_KEY_NAT_RESOLVER on the device address.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_PEER_INFO Message

Microsoft® DirectPlay® generates the DPN_MSGID_PEER_INFO message when peer data is modified during a peer-to-peer session.

The DPNMSG_PEER_INFO structure contains information for the DPN_MSGID_PEER_INFO system message.

Syntax

typedef struct _DPNMSG_PEER_INFO {
    DWORD dwSize;
    DPNID dpnidPeer;
    PVOID pvPlayerContext;
}  DPNMSG_PEER_INFO, *PDPNMSG_PEER_INFO;

Members

dwSize
Size of this structure.
dpnidPeer
DPNID of the peer for peer information.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_RECEIVE Message

Microsoft® DirectPlay® generates the DPN_MSGID_RECEIVE message when a message has been processed by the receiver.

The DPNMSG_RECEIVE structure contains information for the DPN_MSGID_RECEIVE system message.

Syntax

typedef struct _DPNMSG_RECEIVE {
    DWORD dwSize;
    DPNID dpnidSender;
    PVOID pvPlayerContext;
    PBYTE pReceiveData;
    DWORD dwReceiveDataSize;
    DPNHANDLE hBufferHandle;
    DWORD dwReceiveFlags;
}  DPNMSG_RECEIVE, *PDPNMSG_RECEIVE;

Members

dwSize
Size of this structure.
dpnidSender
DPNID of the player that sent the message.
pvPlayerContext
Player context value of the player that sent the message.
pReceiveData
Pointer to the message data buffer. This buffer is normally only valid while the DPN_MSGID_RECEIVE message is being processed by the callback message handler.
dwReceiveDataSize
Size of the data, in bytes, of the pReceiveData member.
hBufferHandle
Buffer handle to the pReceiveData member. If you have returned DPNSUCCESS_PENDING , pass this value to the appropriate ReturnBuffer method to notify DirectPlay to free the buffer.
dwReceiveFlags
The following flags can be specified to describe how messages are received.
DPNRECEIVE_GUARANTEED
The message received was sent guaranteed.
DPNRECEIVE_COALESCED
The message received was coalesced for sending.

Remarks

Return from the message callback function with DPN_OK.

Because you should not spend large amounts of time processing messages, you should copy this data, and process the message. Alternatively, you can return DPNSUCCESS_PENDING from the callback message handler. Doing so transfers ownership of the buffer to the application. If you return DPNSUCCESS_PENDING, you must call IDirectPlay8Peer::ReturnBuffer, IDirectPlay8Client::ReturnBuffer, or IDirectPlay8Server::ReturnBuffer when you are finished with the buffer. Pass the method the value you receive in the hBufferHandle member to identify the buffer. If you fail to call ReturnBuffer, you will create a memory leak.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_REMOVE_PLAYER_FROM_GROUP Message

Microsoft® DirectPlay® generates the DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message when a player has been deleted from a group in a peer-to-peer or client/server session.

The DPNMSG_REMOVE_PLAYER_FROM_GROUP structure contains information for the DPN_MSGID_REMOVE_PLAYER_FROM_GROUP system message.

Syntax

typedef struct _DPNMSG_REMOVE_PLAYER_FROM_GROUP {
    DWORD dwSize;
    DPNID dpnidGroup;
    PVOID pvGroupContext;
    DPNID dpnidPlayer;
    PVOID pvPlayerContext;
}  DPNMSG_REMOVE_PLAYER_FROM_GROUP, *PDPNMSG_REMOVE_PLAYER_FROM_GROUP;

Members

dwSize
Size of this structure.
dpnidGroup
DPNID of the group that the player was deleted from.
pvGroupContext
Group context value.
dpnidPlayer
DPNID of the player deleted from the group.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_RETURN_BUFFER Message

Microsoft® DirectPlay® generates the DPN_MSGID_RETURN_BUFFER message when DirectPlay is done with a user buffer.

The DPNMSG_RETURN_BUFFER structure contains information for the DPN_MSGID_RETURN_BUFFER message.

Syntax

typedef struct _DPNMSG_RETURN_BUFFER {
    DWORD dwSize;
    HRESULT hResultCode;
    PVOID pvBuffer;
    PVOID pvUserContext;
}  DPNMSG_RETURN_BUFFER, *PDPNMSG_RETURN_BUFFER;

Members

dwSize
Size of this structure.
hResultCode
Return value of the operation. This will be set to DPNERR_ENUMRESPONSETOOLARGE if the response to a DPN_MSGID_ENUM_HOSTS_QUERY message is too large.
pvBuffer
Pointer to the buffer being returned.
pvUserContext
Context value associated with the buffer.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_SEND_COMPLETE Message

Microsoft® DirectPlay® generates the DPN_MSGID_SEND_COMPLETE message when an asynchronous send message request has completed.

The DPNMSG_SEND_COMPLETE structure contains information for the DPN_MSGID_SEND_COMPLETE system message.

Syntax

typedef struct _DPNMSG_SEND_COMPLETE {
    DWORD dwSize;
    DPNHANDLE hAsyncOp;
    PVOID pvUserContext;
    HRESULT hResultCode;
    DWORD dwSendTime;
    DWORD dwFirstFrameRTT;
    DWORD dwFirstRetryCount;
    DWORD dwSendCompleteFlags;
    const DPN_BUFFER_DESC pBuffers;
    DWORD dwNumBuffers;
}  DPNMSG_SEND_COMPLETE, *PDPNMSG_SEND_COMPLETE;

Members

dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
User context supplied in the IDirectPlay8Client::Send, IDirectPlay8Peer::SendTo and IDirectPlay8Server::SendTo methods.
hResultCode
HRESULT indicating the result of the send message request.
dwSendTime
Total time, in milliseconds, between send call and completion.
dwFirstFrameRTT
The measured round-trip time for this message, if it is available. It will only be available for reliable messages that arrive on the first try and therefore do not need to be retransmitted. For all other messages this field is set to -1. For large messages that span multiple frames, this value will reflect the measured round-trip time for the first frame sent.
dwFirstRetryCount
For reliable messages, this gives the number of times DirectPlay had to retransmit the message before it was successfully delivered. For unreliable messages, this field is always set to -1.
dwSendCompleteFlags
Specify the following flags that describe how the message was sent.
DPNSENDCOMPLETE_GUARANTEED
The message was sent guaranteed.
DPNSENDCOMPLETE_COALESCED
The message was coalesced for sending.
pBuffers
Pointer to array of DPN_BUFFER_DESC structures sent.
dwNumBuffers
Number of DPN_BUFFER_DESC structures in the pBuffers array.

Remarks

Return from the message callback function with DPN_OK.

If the DPNSEND_NOCOPY flag was specified when IDirectPlay8Peer::SendTo, IDirectPlay8Client::Send, or IDirectPlay8Server::SendTo was called, the pBuffers and dwNumBuffers members refer to an array that contains the same buffer pointers and sizes that were passed when the send call was made. If the DPNSEND_NOCOPY flag was not specified, pBuffers is set to NULL and dwNumBuffers is set to 0.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_SERVER_INFO Message

Microsoft® DirectPlay® generates the DPN_MSGID_SERVER_INFO message when server data is modified during a client/server session.

The DPNMSG_SERVER_INFO structure contains information for the DPN_MSGID_SERVER_INFO system message.

Syntax

typedef struct _DPNMSG_SERVER_INFO {
    DWORD dwSize;
    DPNID dpnidServer;
    PVOID pvPlayerContext;
}  DPNMSG_SERVER_INFO, *PDPNMSG_SERVER_INFO;

Members

dwSize
Size of this structure.
dpnidServer
DPNID of the server for server information.
pvPlayerContext
Player context value.

Remarks

Return from the message callback function with DPN_OK.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_MSGID_TERMINATE_SESSION Message

Microsoft® DirectPlay® generates the DPN_MSGID_TERMINATE_SESSION message when a session is terminated by the host.

The DPNMSG_TERMINATE_SESSION structure contains information for the DPN_MSGID_TERMINATE_SESSION system message.

Syntax

typedef struct _DPNMSG_TERMINATE_SESSION {
    DWORD dwSize;
    HRESULT hResultCode;
    PVOID pvTerminateData;
    DWORD dwTerminateDataSize;
}  DPNMSG_TERMINATE_SESSION, *PDPNMSG_TERMINATE_SESSION;

Members

dwSize
Size of this structure.
hResultCode
Specifies how the session was terminated. This member is set to DPNERR_HOSTTERMINATEDSESSION if the session was peer-to-peer, and the host called IDirectPlay8Peer::TerminateSession. If the session was ended by the host calling IDirectPlay8Peer::Close, or if the host stops responding, hResultCode is set to DPNERR_CONNECTIONLOST.
pvTerminateData
Termination data. If hResultCode is set to DPNERR_HOSTTERMINATEDSESSION, pvTerminateData points to the data block that the host passed through the pvTerminateData parameter of IDirectPlay8Peer::TerminateSession.
dwTerminateDataSize
Size of the data block pointed to by pvTerminateData. This member will be zero if pvTerminateData is set to NULL.

Remarks

Return from the message callback function with DPN_OK.

In a peer-peer game that permits host-migration, if the current host calls IDirectPlay8Peer::Close or stops responding, the session does not terminate. Instead, the host migrates and all nonhost players receive a DPN_MSGID_DESTROY_PLAYER message for the host's players, and a DPN_MSGID_HOST_MIGRATE message for the new host. To prevent host migration, the host must shut down the session by calling IDirectPlay8Peer::TerminateSession. When the host terminates a session this way, all players receive a DPN_MSGID_TERMINATE_SESSION message with hResultCode set to DPNERR_HOSTTERMINATEDSESSION. The session will terminate, generating DPN_MSGID_DESTROY_PLAYER messages for every player.

In a peer-peer game that does not permit host-migration, the session is terminated if the host calls IDirectPlay8Peer::Close, or stops responding. In that case, DPN_MSGID_TERMINATE_SESSION is sent to all players with hResultCode set to DPNERR_CONNECTIONLOST. The session will terminate, generating DPN_MSGID_DESTROY_PLAYER messages for every player.

In a client/server game, the session is also terminated if the host calls IDirectPlay8Server::Close or stops responding. In that case, DPN_MSGID_TERMINATE_SESSION is sent to all connected clients with hResultCode set to DPNERR_CONNECTIONLOST. The DPN_MSGID_DESTROY_PLAYER message not sent to clients. If the server disconnected by calling IDirectPlay8Server::Close, it will receive DPN_MSGID_DESTROY_PLAYER messages for all players, including its own. Otherwise, the server will only receive DPN_MSGID_DESTROY_PLAYER for the clients' players.

Note The DPN_MSGID_TERMINATE_SESSION message typically arrives before any DPN_MSGID_DESTROY_PLAYER messages. However, the order of arrival is not guaranteed.

Message Information

Header | dplay8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_CONNECTRESULT Message

Microsoft® DirectPlay® Voice generates the DVMSGID_CONNECTRESULT message when the connect request generated through a call to the IDirectPlayVoiceClient::Connect method has completed.

The DVMSG_CONNECTRESULT structure contains information for the DVMSGID_CONNECTRESULT message.

Syntax

typedef struct {
    DWORD dwSize;
    HRESULT hrResult;
}  DVMSG_CONNECTRESULT *LPDVMSG_CONNECTRESULT, *PDVMSG_CONNECTRESULT;

Members

dwSize
Size of the DVMSG_CONNECTRESULT message structure.
hrResult
HRESULT that specifies the outcome of the connection attempt.

Remarks

Return from the message callback function with DV_OK.

This message is sent only if the IDirectPlayVoiceClient::Connect method is called asynchronously.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_CREATEVOICEPLAYER Message

Microsoft® DirectPlay® Voice generates the DVMSGID_CREATEVOICEPLAYER message when a new player joins the voice session.

The DVMSG_CREATEVOICEPLAYER structure contains information for the DVMSGID_CREATEVOICEPLAYER message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidPlayer;
    DWORD dwFlags;
    PVOID pvPlayerContext;
}  DVMSG_CREATEVOICEPLAYER *LPDVMSG_CREATEVOICEPLAYER, *PDVMSG_CREATEVOICEPLAYER;

Members

dwSize
Size of the this message structure.
dvidPlayer
DVID of the player who connected.
dwFlags
Flag specifying information about the player:
DVPLAYERCAPS_HALFDUPLEX
The specified player is running in half duplex mode. The player will only be able to receive voice, not transmit it.
DVPLAYERCAPS_LOCAL
The player is the local player.
pvPlayerContext
Player context value for the player in the voice session. This value is set through this parameter when this message is received.

Remarks

Return from the message callback function with DV_OK.

Upon connecting to a voice session, clients receive one of these messages for each player in the voice session. These messages are sent only to clients in peer-to-peer voice sessions.

The host receives these messages when players join the voice session.

Players do not join the voice session until they have called IDirectPlayVoiceClient::Connect. Therefore, it is possible for a player to be in the transport session but not part of the voice session.

DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_DELETEVOICEPLAYER Message

For clients, Microsoft® DirectPlay® Voice generates the DVMSGID_DELETEVOICEPLAYER message when a player quits the voice session. This message is available only to clients in peer-to-peer voice sessions.

For the host, DirectPlay Voice generates the DVMSGID_DELETEVOICEPLAYER message when a player quits the voice session.

The DVMSG_DELETEVOICEPLAYER structure contains information for the DVMSGID_DELETEVOICEPLAYER system message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidPlayer;
    PVOID pvPlayerContext;
}  DVMSG_DELETEVOICEPLAYER *LPDVMSG_DELETEVOICEPLAYER, *PDVMSG_DELETEVOICEPLAYER;

Members

dwSize
Size of the DVMSG_DELETEVOICEPLAYER message structure.
dvidPlayer
DVID of player who disconnected.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER structure.

Remarks

Return from the message callback function with DV_OK.

Players do not leave the voice session until they have called IDirectPlayVoiceClient::Disconnect or they have disconnected from the transport session. Therefore, a client might be part of the transport session but not part of the voice session.

DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_DISCONNECTRESULT Message

Microsoft® DirectPlay® Voice generates the DVMSGID_DISCONNECTRESULT message when the disconnect request generated through a call to the IDirectPlayVoiceClient::Disconnect method has completed.

The DVMSG_DISCONNECTRESULT structure contains information for the DVMSGID_DISCONNECTRESULT system message.

Syntax

typedef struct {
    DWORD dwSize;
    HRESULT hrResult;
}  DVMSG_DISCONNECTRESULT *LPDVMSG_DISCONNECTRESULT, *PDVMSG_DISCONNECTRESULT;

Members

dwSize
Size of the DVMSG_DISCONNECTRESULT message structure.
hrResult
Result of the disconnect request.

Remarks

Return from the message callback function with DV_OK.

This message is sent only if the IDirectPlayVoiceClient::Disconnect method is called asynchronously

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_GAINFOCUS Message

This message is sent to notify you that you have begun capturing audio. There is no data associated with this message.

Remarks

Return from the message callback function with DV_OK.

This message is sent when an application that has lost capture focus recovers it. Refer to the Microsoft® DirectSound® documentation for more information about capturing audio.

Message Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_HOSTMIGRATED Message

Microsoft® DirectPlay® Voice generates the DVMSGID_HOSTMIGRATED message when the voice host has migrated.

The DVMSG_HOSTMIGRATED structure contains information for the DVMSGID_HOSTMIGRATED system message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidNewHostID;
    LPDIRECTPLAYVOICESERVER pdvServerInterface;
}  DVMSG_HOSTMIGRATED *LPDVMSG_HOSTMIGRATED, *PDVMSG_HOSTMIGRATED;

Members

dwSize
Size of the DVMSG_HOSTMIGRATED message structure.
dvidNewHostID
DVID of the new host.
pdvServerInterface
If the local client has become the new voice session host, this member will point to a newly created IDirectPlayVoiceServer object that can be used by the local client for providing host services. If the local client is not the new host, this member will be NULL. If this parameter points to an IDirectPlayVoiceServer interface, you must call IDirectPlayVoiceServer::AddRef to increment the interface's reference count. Call IDirectPlayVoiceServer::Release when you no longer need the interface.

Remarks

Return from the message callback function with DV_OK.

DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_INPUTLEVEL Message

Microsoft® DirectPlay® Voice generates the DVMSGID_INPUTLEVEL message periodically to notify the user of the input level from the microphone.

The DVMSG_INPUTLEVEL structure contains information for the DVMSGID_INPUTLEVEL system message.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    LONG lRecordVolume;
    PVOID pvLocalPlayerContext;
}  DVMSG_INPUTLEVEL *LPDVMSG_INPUTLEVEL, *PDVMSG_INPUTLEVEL;

Members

dwSize
Size of the DVMSG_INPUTLEVEL message structure.
dwPeakLevel
Integer value representing peak level across the current frame, which corresponds to approximately 1/10 second of audio stream. The current frame typically lags 50-200 ms behind real-time. This value can range from 0 through 99, with 0 being completely silent and 99 being the highest possible input level.
lRecordVolume
Current recording volume for the client. The value can range from -10,000 to 0. This member is available even when automatic gain control is active.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER structure.

Remarks

Return from the message callback function with DV_OK.

The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent. In addition, if the client is running in half duplex mode, this message is not available.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_LOCALHOSTSETUP Message

The DVMSGID_LOCALHOSTSETUP message is sent when the local client is selected as the new voice host during host migration.

The DVMSG_LOCALHOSTSETUP structure contains information for the DVMSGID_LOCALHOSTSETUP system message.

Syntax

typedef struct {
    DWORD dwSize;
    PVOID pvContext;
    PDVMESSAGEHANDLER pMessageHandler;
}  DVMSG_LOCALHOSTSETUP *LPDVMSG_LOCALHOSTSETUP, *PDVMSG_LOCALHOSTSETUP;

Members

dwSize
Size of the DVMSG_LOCALHOSTSETUP message structure.
pvContext
Pointer to the context value you want to set for the new server.
pMessageHandler
Pointer to the callback function to be used for the new server.

Remarks

Return from the message callback function with DV_OK.

The message is sent before the DVMSGID_HOSTMIGRATED message and gives you the chance to set the callback function and context value that will be used when creating the new host object. If you do not set either of the values, then the new server interface will have no callback function. When the application returns from handling this message, it will receive the DVMSGID_HOSTMIGRATED message.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_LOSTFOCUS Message

The DVMSGID_LOSTFOCUS message is sent to notify you that you have stopped capturing audio. There is no data associated with this message.

Remarks

Return from the message callback function with DV_OK.

This message is sent when an application that has capture focus loses it to another application. Refer to the Microsoft® DirectSound® documentation for more information about capturing audio.

Message Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_OUTPUTLEVEL Message

Microsoft® DirectPlay® Voice generates the DVMSGID_OUTPUTLEVEL message periodically to notify the user of the output level of playback.

The DVMSG_OUTPUTLEVEL structure contains information for the DVMSGID_OUTPUTLEVEL system message.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    LONG lOutputVolume;
    PVOID pvLocalPlayerContext;
}  DVMSG_OUTPUTLEVEL *LPDVMSG_OUTPUTLEVEL, *PDVMSG_OUTPUTLEVEL;

Members

dwSize
Size of the DVMSG_OUTPUTLEVEL message structure.
dwPeakLevel
Integer representing the current output level of playback. This value must be in the range from 0 through 99. 0 indicates complete silence and 99 indicates the highest possible output level.
lOutputVolume
Current playback volume for the client.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_PLAYEROUTPUTLEVEL Message

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYEROUTPUTLEVEL message periodically to notify the user of the output level of an individual player's voice stream.

The DVMSG_PLAYEROUTPUTLEVEL structure contains information for the DVMSGID_PLAYEROUTPUTLEVEL system message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidSourcePlayerID;
    DWORD dwPeakLevel;
    PVOID pvPlayerContext;
}  DVMSG_PLAYEROUTPUTLEVEL *LPDVMSG_PLAYEROUTPUTLEVEL, *PDVMSG_PLAYEROUTPUTLEVEL;

Members

dwSize
Size of the DVMSG_PLAYEROUTPUTLEVEL message structure.
dvidSourcePlayerID
DVID of the player whose voice is being played back.
dwPeakLevel
Integer representing the current output level of the player's voice stream. This value must be in the range from 0 through 99, with 0 being completely silent and 99 being the highest possible output level.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

This message is generated while voice is being played back for an individual player. If multiple player voices are being played, one message for each player speaking will be sent each notification period.

The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_PLAYERVOICESTART Message

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYERVOICESTART message when an incoming audio stream begins playing back.

The DVMSG_PLAYERVOICESTART structure contains information for the DVMSGID_PLAYERVOICESTART system message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidSourcePlayerID;
    PVOID pvPlayerContext;
}  DVMSG_PLAYERVOICESTART *LPDVMSG_PLAYERVOICESTART, *PDVMSG_PLAYERVOICESTART;

Members

dwSize
Size of the DVMSG_PLAYERVOICESTART message structure.
dvidSourcePlayerID
DVID of the player where the voice transmission originated.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_PLAYERVOICESTOP Message

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYERVOICESTOP message when an incoming audio stream stops.

The DVMSG_PLAYERVOICESTOP structure contains information for the DVMSGID_PLAYERVOICESTOP system message.

Syntax

typedef struct {
    DWORD dwSize;
    DVID dvidSourcePlayerID;
    PVOID pvPlayerContext;
}  DVMSG_PLAYERVOICESTOP *LPDVMSG_PLAYERVOICESTOP, *PDVMSG_PLAYERVOICESTOP;

Members

dwSize
Size of the DVMSG_PLAYERVOICESTOP message structure.
dvidSourcePlayerID
DVID of the player where the voice transmission originated.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_RECORDSTART Message

Microsoft® DirectPlay® Voice generates the DVMSGID_RECORDSTART message when audio input on the local client begins.

The DVMSG_RECORDSTART structure contains information for the DVMSGID_RECORDSTART system message.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    PVOID pvLocalPlayerContext;
}  DVMSG_RECORDSTART *LPDVMSG_RECORDSTART, *PDVMSG_RECORDSTART;

Members

dwSize
Size of the DVMSG_RECORDSTART message structure.
dwPeakLevel
Voice activation level that caused the transmission to begin. In push-to-talk mode, this value is 0.
pvLocalPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

This message can be sent, for instance, when the voice activation sensitivity level is exceeded or when a valid target is specified in push-to-talk mode.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_RECORDSTOP Message

Microsoft® DirectPlay® Voice generates the DVMSGID_RECORDSTOP message when audio input on the local client stops.

The DVMSG_RECORDSTOP structure contains information for the DVMSGID_RECORDSTOP system message.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    PVOID pvLocalPlayerContext;
}  DVMSG_RECORDSTOP *LPDVMSG_RECORDSTOP, *PDVMSG_RECORDSTOP;

Members

dwSize
Size of the DVMSG_RECORDSTOP message structure.
dwPeakLevel
Voice activation level that caused the transmission to stop. In push-to-talk mode, this value is 0.
pvLocalPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSGID_CREATEVOICEPLAYER message structure.

Remarks

Return from the message callback function with DV_OK.

This message can be generated when the voice activation sensitivity level is not being reached or when a target is deselected in push-to-talk mode.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_SESSIONLOST Message

Microsoft® DirectPlay® Voice generates the DVMSGID_SESSIONLOST message when the voice session terminates.

The DVMSG_SESSIONLOST structure contains information for the DVMSGID_SESSIONLOST system message.

Syntax

typedef struct {
    DWORD dwSize;
    HRESULT hrResult;
}  DVMSG_SESSIONLOST *LPDVMSG_SESSIONLOST, *PDVMSG_SESSIONLOST;

Members

dwSize
Size of the DVMSG_SESSIONLOST message structure.
hrResult
HRESULT value indicating why the session was terminated.

Remarks

Return from the message callback function with DV_OK.

DirectPlay and DirectPlay Voice sessions are separate entities. While there are guarantees about message order for each interface, there are no guarantees about message order between interfaces.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVMSGID_SETTARGETS Message

Microsoft® DirectPlay® Voice generates the DVMSGID_SETTARGETS message when the IDirectPlayVoiceClient::SetTransmitTargets or IDirectPlayVoiceServer::SetTransmitTargets methods are called.

The DVMSG_SETTARGETS structure contains information for the DVMSGID_SETTARGETS system message.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwNumTargets;
    PDVID pdvidTargets;
}  DVMSG_SETTARGETS *LPDVMSG_SETTARGETS, *PDVMSG_SETTARGETS;

Members

dwSize
Size of the DVMSG_SETTARGETS message structure.
dwNumTargets
Number of DVIDs contained in the pdvidTargets member.
pdvidTargets
Array of DVIDs specifying the set targets. This can also be set to NULL if there are no targets.

Remarks

Return from the message callback function with DV_OK.

Message Information

Header | dvoice.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains Microsoft® DirectPlay® structures.

Structures

  • DP8SIM_PARAMETERS
  • DP8SIM_STATISTICS
  • DPL_APPLICATION_INFO
  • DPL_CONNECT_INFO
  • DPL_CONNECTION_SETTINGS
  • DPL_PROGRAM_DESC
  • DPN_APPLICATION_DESC
  • DPN_BUFFER_DESC
  • DPN_CAPS
  • DPN_CAPS_EX
  • DPN_CONNECTION_INFO
  • DPN_GROUP_INFO
  • DPN_PLAYER_INFO
  • DPN_SECURITY_CREDENTIALS
  • DPN_SECURITY_DESC
  • DPN_SERVICE_PROVIDER_INFO
  • DPN_SP_CAPS
  • DPNHCAPS
  • DVCAPS
  • DVCLIENTCONFIG
  • DVCOMPRESSIONINFO
  • DVSESSIONDESC
  • DVSOUNDDEVICECONFIG

© 2002 Microsoft Corporation. All rights reserved.


DP8SIM_PARAMETERS Structure

Used to set and retrieve DP8Sim settings.

Syntax

typedef struct _DP8SIM_PARAMTERS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwPacketHeaderSize;
    DWORD dwBandwidthBPS;
    FLOAT fPcketLossPercent;
    DWORD dwMinLatencyMS;
    DWORD dwMaxLatencyMS;
} DP8SIM_PARAMETERS, *PDP8SIM_PARAMETERS;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Unused. Must be zero.
dwPacketHeaderSize
Fixed transport packet header size for packet size calculations, or 0 to calculate based on Microsoft® DirectPlay® headers and payload only. The following values are defined for convenience.
DP8SIMPACKETHEADERSIZE_IP
Represents the standard Internet Protocol (IP) header size, 20 bytes.
DP8SIMPACKETHEADERSIZE_UDP
Represents the standard User Datagram Protocol (UDP) header size, 8 bytes.
DP8SIMPACKETHEADERSIZE_IP_UDP
Represents the standard IP and UDP header size, 28 bytes. This is the recommended value.
dwBandwidthBPS
Bandwidth limit in bytes per second. Set to 0 for no limit.
fPcketLossPercent
Percentage of packets to drop. Can be a value between 0.0 and 100.0.
dwMinLatencyMS
Minimum artificial latency, in milliseconds. This value is in addition to any latency cause by bandwidth settings.
dwMaxLatencyMS
Maximum artificial latency, in milliseconds. This value is in addition to any latency cause by bandwidth settings.

Structure Information

Header | dp8sim.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DP8SIM_STATISTICS Structure

Used to set and retrieve DP8Sim statistics.

Syntax

typedef struct _DP8SIM_STATISTICS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwTransmittedPackets;
    DWORD dwTransmittedBytes;
    DWORD dwDroppedPackets;
    DWORD dwDroppedBytes;
    DWORD dwTotalDelayMS;
} DP8SIM_STATISTICS, *PDP8SIM_STATISTICS;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Reserved. Must be zero.
dwTransmittedPackets
Number of packets sent or received.
dwTransmittedBytes
Number of bytes sent or received.
dwDroppedPackets
Number of packets intentionally dropped.
dwDroppedBytes
Number of bytes intentionally dropped.
dwTotalDelayMS
Total number of milliseconds delay added due to bandwidth limitations or random latency settings.

Structure Information

Header | dp8sim.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_APPLICATION_INFO Structure

Used in the pEnumData parameter of the IDirectPlay8LobbyClient::EnumLocalPrograms method to describe the lobbied application.

Syntax

typedef struct _DPL_APPLICATION_INFO {
    GUID guidApplication;
    PWSTR pwszApplicationName;
    DWORD dwNumRunning;
    DWORD dwNumWaiting;
    DWORD dwFlags;
} DPL_APPLICATION_INFO, *PDPL_APPLICATION_INFO;

Members

guidApplication
Variable of type GUID specifying the lobbied application.
pwszApplicationName
Pointer to a variable of type WSTR containing the name of the lobbied application.
dwNumRunning
Number of instances of the application.
dwNumWaiting
Number of clients waiting to connect to the lobbied application.
dwFlags
Reserved. Must be 0.

Structure Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_CONNECT_INFO Structure

Used to specify connection information for a lobby client when connecting to the lobby application in the IDirectPlay8LobbyClient::ConnectApplication method.

Syntax

typedef struct _DPL_CONNECT_INFO {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidApplication;
    PDPL_CONNECTION_SETTINGS pdplConnectionSettings;
    PVOID pvLobbyConnectData;
    DWORD dwLobbyConnectDataSize;
} DPL_CONNECT_INFO, *PDPL_CONNECT_INFO;

Members

dwSize
Size of the DPL_CONNECT_INFO structure. The application must set this member before it uses the structure.
dwFlags
One of the following flags, which determine connection behavior.
DPLCONNECT_LAUNCHNEW
Launches a new instance of the application.
DPLCONNECT_LAUNCHNOTFOUND
Launches a new instance of the application only if there is currently no application running that can supply launch settings.
guidApplication
Variable of type globally unique identifier (GUID) specifying the application.
pdplConnectionSettings
Contains the connection settings you want to associate with the connection when it is established.
pvLobbyConnectData
Pointer to connection data passed to the lobbied application.
dwLobbyConnectDataSize
Variable of type DWORD specifying the size of the data buffer in the pvLobbyConnectData member.

Structure Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_CONNECTION_SETTINGS Structure

Used to specify the settings you want to associate with a connection. These settings contain all the information required to create, initialize and connect/host a Microsoft® DirectPlay® object.

Syntax

typedef struct _DPL_CONNECTION_SETTINGS {
    DWORD dwSize;
    DWORD dwFlags;
    DPN_APPLICATION_DESC dpnAppDesc;
    IDirectPlay8Address *pdp8HostAddress;
    IDirectPlay8Address *ppdp8DeviceAddresses;
    DWORD cNumDeviceAddresses;
    PWSTR pwszPlayerName;
} DPL_CONNECTION_SETTINGS, *PDPL_CONNECTION_SETTINGS;

Members

dwSize
Size of the DPL_CONNECTION_SETTINGS structure. The application must set this to sizeof( DPL_CONNECTION_SETTINGS ) before using this structure.
dwFlags
The following flag can be specified.
DPLCONNECTSETTINGS_HOST
The application should host the session.
dpnAppDesc
Pointer to the application description that should be passed to the Connect or Host call when DirectPlay initialized.
pdp8HostAddress
If DPLCONNECTSETTINGS_HOST is not specified, this is the address of the session the client should connect to. If DPLCONNECTSETTINGS_HOST is specified, this member must be NULL.
ppdp8DeviceAddresses
This structure contains an array of pointers to device addresses. If DPLCONNECTSETTINGS_HOST is specified, this member will contain the addresses the host should listen on. If DPLCONNECTSETTINGS_HOST is not specified, this member will contain the address of the devices the client should use when connecting.
cNumDeviceAddresses
Number of addresses specified in the ppdp8DeviceAddresses member.
pwszPlayerName
Can be used to pass the player name you want the DirectPlay object to use when launching. This member can be NULL.

Structure Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPL_PROGRAM_DESC Structure

Describes a Microsoft® DirectPlay® lobby-aware application.

Syntax

typedef struct _DPL_PROGRAM_DESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidApplication;
    PWSTR pwszApplicationName;
    PWSTR pwszCommandLine;
    PWSTR pwszCurrentDirectory;
    PWSTR pwszDescription;
    PWSTR pwszExecutableFilename;
    PWSTR pwszExecutablePath;
    PWSTR pwszLauncherFilename;
    PWSTR pwszLauncherPath;
} DPL_PROGRAM_DESC, *PDPL_PROGRAM_DESC;

Members

dwSize
Size of the DPL_PROGRAM_DESC structure. The application must set this member before it uses the structure.
dwFlags
Reserved. Must be 0.
guidApplication
Variable of type GUID specifying the application.
pwszApplicationName
Pointer to the application name.
pwszCommandLine
Pointer to the command-line arguments.
pwszCurrentDirectory
Pointer to the directory that should be set as the application's working directory..
pwszDescription
Pointer to the application description.
pwszExecutableFilename
Pointer to the file name of the application executable.
pwszExecutablePath
Pointer to the path of the application executable.
pwszLauncherFilename
Pointer to the file name of the launcher executable.
pwszLauncherPath
Pointer to the path of the launcher executable.

Structure Information

Header | dplobby8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_APPLICATION_DESC Structure

Describes the settings for a Microsoft® DirectPlay® application.

Syntax

typedef struct _DPN_APPLICATION_DESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidInstance;
    GUID guidApplication;
    DWORD dwMaxPlayers;
    DWORD dwCurrentPlayers;
    WCHAR *pwszSessionName;
    WCHAR *pwszPassword;
    PVOID pvReservedData;
    DWORD dwReservedDataSize;
    PVOID pvApplicationReservedData;
    DWORD dwApplicationReservedDataSize;
} DPN_APPLICATION_DESC, *PDPN_APPLICATION_DESC;

Members

dwSize
Size of the DPN_APPLICATION_DESC structure. The application must set this member before it uses the structure.
dwFlags
One of the following flags describing application behavior.
DPNSESSION_CLIENT_SERVER
This type of session is client/server. This flag cannot be combined with DPNSESSION_MIGRATE_HOST.
DPNSESSION_MIGRATE_HOST
Used in peer-to-peer sessions, enables host migration. This flag cannot be combined with DPNSESSION_CLIENT_SERVER.
DPNSESSION_NODPNSVR
Do not forward enumerations to your host from DPNSVR. See Using the DirectPlay DPNSVR Application for details.
DPNSESSION_REQUIREPASSWORD
The session is password protected. If this flag is set, pwszPassword must be set to a valid string.
DPNSESSION_NOENUMS
Do not allow DirectPlay to start enumeration queries.
DPNSESSION_FAST_SIGNED
Add an 8 byte value to each packet. The packet must contain this value before a receiver accepts it.
DPNSESSION_FULL_SIGNED
Add a rolling 8 byte SHA1 hash value based on the contents of the packet. The packet must have the correct SHA1 signature before it is accepted.
guidInstance
Globally unique identifier (GUID) that is generated by DirectPlay at startup . This member is an [out] parameter when calling IDirectPlay8Peer::GetApplicationDesc, IDirectPlay8Client::GetApplicationDesc, or IDirectPlay8Server::GetApplicationDesc. It is an optional [in] parameter when calling the IDirectPlay8Peer::Connect and IDirectPlay8Client::Connect methods. It must be set to GUID_NULL when you call the IDirectPlay8Peer::SetApplicationDesc or IDirectPlay8Server::SetApplicationDesc methods. You cannot obtain this GUID by calling the IDirectPlay8Server::Host or IDirectPlay8Peer::Host methods. You must obtain the GUID by calling a GetApplicationDesc method.
guidApplication
Application GUID.
dwMaxPlayers
Variable of type DWORD, specifying the maximum number of players allowed in the session. Set this member to 0 to specify an unlimited number of players.
dwCurrentPlayers
Variable of type DWORD specifying the number of players currently connected to the session. This member is is set only by the IDirectPlay8Peer::GetApplicationDesc, IDirectPlay8Client::GetApplicationDesc, and IDirectPlay8Server::GetApplicationDesc methods.
pwszSessionName
Pointer to a variable of type WCHAR specifying the name of the session. This member is set by the host or server only for informational purposes. A client cannot use this name to connect to a host or server.
pwszPassword
Pointer to a variable of type WCHAR specifying the Unicode password that is required to connect to the session. This must be NULL if the DPNSESSION_REQUIREPASSWORD is not set in the dwFlags member.
pvReservedData
Pointer to DirectPlay reserved data. An application should never modify this value.
dwReservedDataSize
Variable of type DWORD specifying the size of data contained in the pvReservedData member. An application should never modify this value.
pvApplicationReservedData
Pointer to application-specific reserved data. This value is optional and may be set to NULL.
dwApplicationReservedDataSize
Variable of type DWORD specifying the size of the data in the pvApplicationReservedData member. This value is optional and may be set to 0.

Remarks

Multiple instances of the application can run simultaneously in a session. If multiple instances are running, each will have a unique DPN_APPLICATION_DESC structure associated with it. "Application" refers to a specific instance of an application.

The dwMaxPlayers, pvApplicationReservedData, dwApplicationReservedDataSize, pwszPassword, and pwszSessionName members can be set when calling the IDirectPlay8Peer::Host, IDirectPlay8Server::Host, IDirectPlay8Peer::SetApplicationDesc, or IDirectPlay8Server::SetApplicationDesc methods.

Setting either the DPNSESSION_FAST_SIGNED or the DPNSESSION_FULL_SIGNED flag prevents players using Microsoft DirectX® 8.1 or earlier versions from being able to connect to the session. These flags cannot be used together.

security note Security Alert When connecting to a password-protected session, the data in the pwszPassword member is transmitted in clear text to the host.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_BUFFER_DESC Structure

Used by Microsoft® DirectPlay® for generic buffer information.

Syntax

typedef struct _BUFFERDESC {
    DWORD dwBufferSize;
    BYTE *pBufferData;
} DPN_BUFFER_DESC, BUFFERDESC;

Members

dwBufferSize
Variable of type DWORD that specifies the size of the data buffer in the pBufferData member.
pBufferData
Pointer to a variable of type BYTE that contains the buffer data.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_CAPS Structure

Used when setting and retrieving general parameters for Microsoft® DirectPlay®.

Syntax

typedef struct _DPN_CAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwConnectTimeout;
    DWORD dwConnectRetries;
    DWORD dwTimeoutUntilKeepAlive;
} DPN_CAPS, *PDPN_CAPS;

Members

dwSize
This value must be set to the size of the structure.
dwFlags
Reserved, this must be 0.
dwConnectTimeout
Number of milliseconds DirectPlay should wait before it retries a connection request.
dwConnectRetries
Number of connection retries DirectPlay should make during the connection process.
dwTimeoutUntilKeepAlive
Number of milliseconds DirectPlay waits since the last time it received a packet from an endpoint, before it sends a keep alive message. The actual delay can vary from the specified value to as much as twice the specified value.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_CAPS_EX Structure

Used when setting and retrieving parameters to tune the Microsoft® DirectPlay® protocol.

Syntax

typedef struct _DPN_CAPS_EX {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwConnectTimeout;
    DWORD dwConnectRetries;
    DWORD dwTimeoutUntilKeepAlive;
    DWORD dwMaxRecvMsgSize;
    DWORD dwNumSendRetries;
    DWORD dwMaxSendRetryInterval;
    DWORD dwDropThresholdRate;
    DWORD dwThrottleRate;
    DWORD dwNumHardDisconnectSends;
    DWORD dwMaxHardDisconnectPeriod;
} DPN_CAPS_EX, *PDPN_CAPS_EX;

Members

dwSize
Value, which must be set to the size of the structure.
dwFlags
Reserved; this must be 0.
dwConnectTimeout
Number of milliseconds DirectPlay should wait before it retries a connection request.
dwConnectRetries
Number of connection retries DirectPlay should make during the connection process.
dwTimeoutUntilKeepAlive
Number of milliseconds DirectPlay waits since the last time it received a packet from an endpoint, before it sends a keep-alive message. The actual delay can vary from the specified value to as much as twice the specified value.
dwMaxRecvMsgSize
Maximum size of received messages, in bytes.
dwNumSendRetries
Maximum number of times applications can try to send a message before the connection is considered dead.
dwMaxSendRetryInterval
Maximum number of milliseconds between attempts to resend messages.
dwDropThresholdRate
Percentage of dropped packets allowed before Message Throttling is applied.
dwThrottleRate
Percentage to reduce the send queue when applying message throttling.
dwNumHardDisconnectSends
Number of hard disconnect frames to send when the DPNCLOSE_IMMEDIATE flag is specified.
dwMaxHardDisconnectPeriod
Maximum time, in milliseconds, between each hard disconnect frame sent.

Remarks

When using the DPN_CAPS_EX structure with IDirectPlay8Peer or IDirectPlay8Client objects, the dwMaxRecvMsgSize member is ignored. Callback functions for IDirectPlay8Peer and IDirectPlay8Client will receive messages of any size, even those larger than dwMaxRecvMsgSize.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_CONNECTION_INFO Structure

Used to retrieve statistics for the connection between you and a remote computer that you are connected to.

Syntax

typedef struct _DPN_CONNECTION_INFO {
    DWORD dwSize;
    DWORD dwRoundTripLatencyMS;
    DWORD dwThroughputBPS;
    DWORD dwPeakThroughputBPS;
    DWORD dwBytesSentGuaranteed;
    DWORD dwPacketsSentGuaranteed;
    DWORD dwBytesSentNonGuaranteed;
    DWORD dwPacketsSentNonGuaranteed;
    DWORD dwBytesRetried;
    DWORD dwPacketsRetried;
    DWORD dwBytesDropped;
    DWORD dwPacketsDropped;
    DWORD dwMessagesTransmittedHighPriority;
    DWORD dwMessagesTimedOutHighPriority;
    DWORD dwMessagesTransmittedNormalPriority;
    DWORD dwMessagesTimedOutNormalPriority;
    DWORD dwMessagesTransmittedLowPriority;
    DWORD dwMessagesTimedOutLowPriority;
    DWORD dwBytesReceivedGuaranteed;
    DWORD dwPacketsReceivedGuaranteed;
    DWORD dwBytesReceivedNonGuaranteed;
    DWORD dwPacketsReceivedNonGuaranteed;
    DWORD dwMessagesReceived;
} DPN_CONNECTION_INFO, *PDPN_CONNECTION_INFO;

Members

dwSize
Size of the structure.
dwRoundTripLatencyMS
Approximate time, in milliseconds (ms), it takes a packet to reach the remote computer and be returned to the local computer. This number will change throughout the session as link conditions change.
dwThroughputBPS
Approximate throughput, in bytes per second (Bps), for the link. This number will change throughout the session as link conditions change. This value is approximate, and you may want to calculate your own value for greater accuracy.
dwPeakThroughputBPS
Peak throughput, in bytes per second (Bps) for the link. This number will change throughout the session as link conditions change. This value is approximate, and you may want to calculate your own value for greater accuracy.
dwBytesSentGuaranteed
Amount, in bytes, of guaranteed messages that have been sent.
dwPacketsSentGuaranteed
Number of packets of guaranteed messages that have been sent.
dwBytesSentNonGuaranteed
Amount, in bytes, of nonguaranteed messages that have been sent.
dwPacketsSentNonGuaranteed
Number of packets of nonguaranteed messages that have been sent.
dwBytesRetried
Amount, in bytes, of messages that have been retried.
dwPacketsRetried
Amount of packets that have been retried.
dwBytesDropped
Amount, in bytes, of messages that have been dropped.
dwPacketsDropped
Number of packets that have been dropped.
dwMessagesTransmittedHighPriority
Number of high-priority messages that have been transmitted.
dwMessagesTimedOutHighPriority
Number of high-priority messages that have timed out.
dwMessagesTransmittedNormalPriority
Number of normal-priority messages that have been transmitted.
dwMessagesTimedOutNormalPriority
Number of normal-priority messages that have timed out.
dwMessagesTransmittedLowPriority
Number of low-priority messages that have been transmitted.
dwMessagesTimedOutLowPriority
Number of low priority messages that have timed out.
dwBytesReceivedGuaranteed
Amount, in bytes, of guaranteed messages that have been received.
dwPacketsReceivedGuaranteed
Number of packets of guaranteed messages that have been received.
dwBytesReceivedNonGuaranteed
Amount, in bytes, of nonguaranteed messages that have been received.
dwPacketsReceivedNonGuaranteed
Number of packets of nonguaranteed messages that have been received.
dwMessagesReceived
Number of messages that have been received.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_GROUP_INFO Structure

Describes static group information.

Syntax

typedef struct _DPN_GROUP_INFO {
    DWORD dwSize;
    DWORD dwInfoFlags;
    PWSTR pwszName;
    PVOID pvData;
    DWORD dwDataSize;
    DWORD dwGroupFlags;
} DPN_GROUP_INFO, *PDPN_GROUP_INFO;

Members

dwSize
Variable of type DWORD describing the size of this structure.
dwInfoFlags
Variable of type DWORD containing flags that specify the type of information contained in this structure. When the IDirectPlay8Peer::GetGroupInfo or IDirectPlay8Server::GetGroupInfo method returns, the dwInfoFlags member of the DPN_GROUP_INFO will always have both flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetGroupInfo, to notify Microsoft® DirectPlay® of which values have changed.
DPNINFO_NAME
The pwszName member contains valid data.
DPNINFO_DATA
The pvData member contains valid data.
pwszName
Pointer to a variable of type PWSTR specifying the Unicode name of the group.
pvData
Pointer to the data describing the group.
dwDataSize
Variable of type DWORD that specifies the size of the data contained in the pvData member.
dwGroupFlags
Variable of type DWORD that can be set to the following description flag.
DPNGROUP_AUTODESTRUCT
Causes the group to be automatically destroyed when the group creator leaves the group.

Remarks

When using this structure in the IDirectPlay8Peer::GetGroupInfo and IDirectPlay8Server::GetGroupInfo methods, dwInfoFlags must be set to 0.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_PLAYER_INFO Structure

Describes static player information.

Syntax

typedef struct _DPN_PLAYER_INFO {
    DWORD dwSize;
    DWORD dwInfoFlags;
    PWSTR pwszName;
    PVOID pvData;
    DWORD dwDataSize;
    DWORD dwPlayerFlags;
} DPN_PLAYER_INFO, *PDPN_PLAYER_INFO;

Members

dwSize
Variable of type DWORD describing the size of this structure.
dwInfoFlags
Variable of type DWORD containing flags that specify the type of information contained in this structure. When the IDirectPlay8Peer::GetPeerInfo or IDirectPlay8Server::GetClientInfo method returns, the dwInfoFlags member of the DPN_PLAYER_INFO will always have both flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetPeerInfo, to notify Microsoft® DirectPlay® which values have changed.
DPNINFO_NAME
The pwszName member contains valid data.
DPNINFO_DATA
The pvData member contains valid data.
pwszName
Pointer to a variable of type PWSTR specifying the Unicode name of the player.
pvData
Pointer to the data describing the player.
dwDataSize
Variable of type DWORD that specifies the size of the data contained in the pvData member.
dwPlayerFlags
Variable of type DWORD that may contain one of the following flags.
DPNPLAYER_LOCAL
This information is for the local player.
DPNPLAYER_HOST
This player is the host for the application.

Remarks

When using this structure in the IDirectPlay8Peer::GetPeerInfo and IDirectPlay8Server::GetClientInfo methods, dwInfoFlags must be set to 0.

When using this structure in the IDirectPlay8Client::SetClientInfo, IDirectPlay8Peer::SetPeerInfo, or IDirectPlay8Server::SetServerInfo methods, dwPlayerFlags should be set to zero.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_SECURITY_CREDENTIALS Structure

Not currently implemented.

© 2002 Microsoft Corporation. All rights reserved.


DPN_SECURITY_DESC Structure

Not currently implemented.

© 2002 Microsoft Corporation. All rights reserved.


DPN_SERVICE_PROVIDER_INFO Structure

Used when enumerating information for a specific service provider.

Syntax

typedef struct _DPN_SERVICE_PROVIDER_INFO {
    DWORD dwFlags;
    GUID guid;
    WCHAR *pwszName;
    PVOID pvReserved;
    DWORD dwReserved;
} DPN_SERVICE_PROVIDER_INFO, *PDPN_SERVICE_PROVIDER_INFO;

Members

dwFlags
Describes the service provider.
DPNSPINFO_NETWORKSIMULATORDEVICE
Device is available to the DP8Sim service provider.
guid
GUID for the service provider.
pwszName
Name of the service provider.
pvReserved
Reserved. Must be 0.
dwReserved
Reserved. Must be 0.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPN_SP_CAPS Structure

Used to set and retrieve parameters for service providers.

Syntax

typedef struct _DPN_SP_CAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwNumThreads;
    DWORD dwDefaultEnumCount;
    DWORD dwDefaultEnumRetryInterval;
    DWORD dwDefaultEnumTimeout;
    DWORD dwMaxEnumPayloadSize;
    DWORD dwBuffersPerThread;
    DWORD dwSystemBufferSize;
} DPN_SP_CAPS, *PDPN_SP_CAPS;

Members

dwSize
Value must be set to the size of the structure.
dwFlags
Can be a combination of the following flags.
DPNSPCAPS_SUPPORTSDPNSRV
DPNSVR.EXE will provide port sharing for the given SP. Currently this flag is available on Internet Protocol (IP) and Internetwork Packet Exchange (IPX) only. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.
DPNSPCAPS_SUPPORTSBROADCAST
On IP and IPX applications, the service provider has the ability to broadcast to find games if not enough addressing information is passed.
DPNSPCAPS_SUPPORTSALLADAPTERS
The service provider will use all devices on the system. There is no need to specify a device element.
DPNSPCAPS_SUPPORTSTHREADPOOL
The service provider will support the thread pool.
DPNSPCAPS_NETWORKSIMULATOR
Specifies the DP8Sim service provider.
dwNumThreads
Number of threads the service provider will use for servicing network requests. The default value for this is based on an algorithm that takes into account the number of processors on the system. Most applications will not need to modify this value.

After a service provider is active in your process, you can only increase this value. Decreasing the value will have no effect. The setting is process wide, which means it will affect your current Microsoft® DirectPlay® object and any other DirectPlay objects in your process.

You can specify a lower value than the default if you call the SetSPCaps method before you call an EnumHosts, Connect, or Host method.

dwDefaultEnumCount
Default enumeration count.
dwDefaultEnumRetryInterval
Default retry interval, in milliseconds.
dwDefaultEnumTimeout
Default enumeration timeout value, in milliseconds.
dwMaxEnumPayloadSize
Maximum size of the payload information that can be sent in the pvResponseData member of the structures that accompany the DPN_MSGID_ENUM_HOSTS_QUERY and DPN_MSGID_ENUM_HOSTS_RESPONSE messages.
dwBuffersPerThread
The number of outstanding receive buffers allocated for each DirectPlay thread. If you increase the number of receive buffers, DirectPlay can pull more data out of the operating system buffers. However, you can also increase latency if data is arriving faster than your application can process it.
dwSystemBufferSize
The size of the operating system buffer. This buffer holds data from the communications device when your application cannot process data as fast as it arrives. The purpose of this buffer is to prevent data loss if you receive a sudden burst of data, or if the receive threads are momentarily stalled. Increasing dwSystemBufferSize can increase latency if your application cannot process the received data fast enough. You can eliminate the operating system buffer by setting dwSystemBufferSize to 0. However, if you do so, you run the risk of losing data if you cannot process the received data as fast as it arrives.

Remarks

The dwBuffersPerThread and dwSystemBufferSize members are used only by IP and IPX service providers. The default values for these members are set by the service provider. To determine the default value, call the appropriate GetSPCaps method. Most applications should use the default values for these two members. They are intended primarily for use by developers writing server applications for massively-multiplayer games.

Structure Information

Header | dplay8.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DPNHCAPS Structure

Used to set and retrieve parameters for service providers.

Syntax

typedef struct _DPNHCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwNumRegisteredPorts;
    DWORD dwMinLeaseTimeRemaining;
    DWORD dwRecommendedGetCapsInterval;
} DPNHCAPS, *PDPNHCAPS;

Members

dwSize
Size of this structure. Must be filled prior to calling IDirectPlayNATHelp::GetCaps.
dwFlags
Flags indicating capabilities of the Internet gateway server. Possible values are:
DPNHCAPSFLAGS_LOCALFIREWALLPRESENT
At least one network connection has a local firewall present.
DPNHCAPSFLAGS_GATEWAYPRESENT
At least one network connection has an Internet gateway present.
DPNHCAPSFLAGS_GATEWAYISLOCAL
A detected Internet gateway is local.
DPNHCAPSFLAGS_PUBLICADDRESSAVAILABLE
At least one server has a valid public address for registered mappings.
DPNHCAPSFLAGS_NOTALLSUPPORTACTIVENOTIFY
At least one available server does not support an active notification mechanism and must be polled.
dwNumRegisteredPorts
Number of ports currently registered, including multiple ports registered at the same time.
dwMinLeaseTimeRemaining
Time remaining on the lease that will expire first, in milliseconds.
dwRecommendedGetCapsInterval
Recommended time between calls to IDirectPlayNATHelp::GetCaps, in milliseconds.

Structure Information

Header | dpnathlp.h
Minimum operating systems | Windows 98, Pocket PC 2002

© 2002 Microsoft Corporation. All rights reserved.


DVCAPS Structure

Describes the capabilities of the Microsoft® DirectPlay® VoiceClient object.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
} DVCAPS, *LPDVCAPS, *PDVCAPS;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Reserved. Must be 0.

Structure Information

Header | dvoice8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVCLIENTCONFIG Structure

Controls the run-time parameters for the client.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    LONG lRecordVolume;
    LONG lPlaybackVolume;
    DWORD dwThreshold;
    DWORD dwBufferQuality;
    DWORD dwBufferAggressiveness;
    DWORD dwNotifyPeriod;
} DVCLIENTCONFIG, *LPDVCLIENTCONFIG, *PDVCLIENTCONFIG;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Combination of the following flags. Possible values include the following:
DVCLIENTCONFIG_AUTORECORDVOLUME | Activates automatic gain control. With automatic gain control, Microsoft® DirectPlay® Voice adjusts the hardware input volume on your sound card automatically to get the best input level possible. You can determine the current input volume by looking at the lRecordVolume member of this structure after calling IDirectPlayVoiceClient::GetClientConfig, or by looking at the lRecordVolume member of the structure that accompanies a DVMSGID_INPUTLEVEL message.
DVCLIENTCONFIG_ECHOSUPPRESSION | Activates the echo suppression mode. This mode reduces echo introduced by configurations with external speakers and extremely sensitive microphones. While remote players' voices are being played back on the local speaker, the microphone is automatically muted. If the local player is transmitting, the playback of remote player voices is buffered until local input stops. After local input stops, playback resumes.
DVCLIENTCONFIG_MUTEGLOBAL | Mutes playback of the main sound buffer. Only sound buffers created through calls to IDirectPlayVoiceClient::Create3DSoundBuffer will be heard.
DVCLIENTCONFIG_PLAYBACKMUTE | Mutes playback of all DirectPlay Voice output and stops playback. This also stops decompression of incoming packets so CPU usage is reduced. Packets are effectively discarded while this flag is specified.
DVCLIENTCONFIG_RECORDMUTE | Mutes input from the microphone and stops recording. This also stops compression so CPU usage is reduced.
In addition to the preceding flags, the method of transmission is controlled by setting only one of the following flags or by not specifying either flag. Possible values include the following:
DVCLIENTCONFIG_AUTOVOICEACTIVATED | Places the transmission control system into automatic voice activation mode. In this mode, the sensitivity of voice activation is determined automatically by the system. The input level is adaptive, adjusting itself automatically to the input signal. For most applications this should be the setting used. This flag is mutually exclusive with the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag.
DVCLIENTCONFIG_MANUALVOICEACTIVATED | Places the transmission control system into manual voice activation mode. In this mode, transmission of voice begins when the input level passes the level specified by the dwThreshold member. When input levels drop below the specified level, transmission stops. This flag is mutually exclusive with the DVCLIENTCONFIG_AUTOVOICEACTIVATED flag.
If you do not specify either DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED, the system will operate in push-to-talk mode. In push-to-talk mode, as long as there is a valid target specified the input from the microphone will be transmitted. Voice transmission stops when a NULL target is set or the current target leaves the session or is destroyed.
lRecordVolume

LONG value that specifies what the volume of the recording should be set to. See the IDirectSoundBuffer8::SetVolume method for valid values.

If automatic gain control is enabled, this value can be set to DVRECORDVOLUME_LAST, which tells the system to use the current volume as determined by the automatic gain control algorithm. If a value other than DVRECORDVOLUME_LAST is specified in combination with automatic gain control, this value will be used to restart the algorithm at the specified value.

On return from a call to IDirectPlayVoiceClient::GetClientConfig, this value will contain the current recording volume. When adjusting the recording volume, DirectPlay Voice will adjust the volume for the microphone (if a microphone volume is present for the card) and the master recording volume (if one is present on the card). If neither a microphone volume nor a master record volume is present, DirectPlay Voice will be unable to adjust the recording volume.

lPlaybackVolume
Value indicating what the playback volume should be set to. Adjusting this volume adjusts both the main buffer and all 3-D sound buffers. See the IDirectSoundBuffer8::SetVolume method for valid values. You can specify DVPLAYBACKVOLUME_DEFAULT to use a default value that is appropriate for most situations (full volume).
dwThreshold
Input level used to trigger voice transmission if the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag is specified in the dwFlags member. When the flag is specified, this value can be set to anywhere in the range of DVTHRESHOLD_MIN to DVTHRESHOLD_MAX. Additionally, DVTHRESHOLD_DEFAULT can be set to use a default value. If DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED is not specified in the dwFlags member. When the flag is specified, this value can be set to anywhere in the range member of this structure (indicating push-to-talk mode) this value must be set to DVTHRESHOLD_UNUSED.
dwBufferQuality
Buffer quality setting for the adaptive buffering algorithm. For most applications, this should be set to DVBUFFERQUALITY_DEFAULT. It can be set to anything in the range of DVBUFFERQUALITY_MIN to DVBUFFERQUALITY_MAX. In general, the higher the value, the higher the quality of the voice but the higher the latency. The lower the value, the lower the latency but the lower the quality.
dwBufferAggressiveness
Buffer aggressiveness setting for the adaptive buffer algorithm. For most applications, this can be set to DVBUFFERAGGRESSIVENESS_DEFAULT. It can also be set to anything in the range of DVBUFFERAGGRESSIVENESS_MIN and DVBUFFERAGGRESSIVENESS_MAX. In general, the higher the value, the quicker the adaptive buffering adjusts to changing conditions. The lower the value, the slower the adaptive buffering adjusts to changing conditions.
dwNotifyPeriod
Value indicating how often you want to receive DVMSGID_OUTPUTLEVEL and DVMSGID_INPUTLEVEL (if session is full duplex) messages. If this value is set to 0, these messages are disabled. The value specifies the number of milliseconds between these messages. DVNOTIFYPERIOD_MINPERIOD specifies the minimum period between messages that is allowed.

Remarks

This structure is first used in the call to IDirectPlayVoiceClient::Connect, where it sets the initial state of these parameters. The structure can be retrieved after a connection has been made by calling IDirectPlayVoiceClient::GetClientConfig, and set using IDirectPlayVoiceClient::SetClientConfig.

Structure Information

Header | dvoice8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVCOMPRESSIONINFO Structure

Describes the attributes of a specific Microsoft® DirectPlay® Voice compression type.

Syntax

typedef struct {
    DWORD dwSize;
    GUID guidType;
    LPWSTR lpszName;
    LPWSTR lpszDescription;
    DWORD dwFlags;
    DWORD dwMaxBitsPerSecond;
} DVCOMPRESSIONINFO, *LPDVCOMPRESSIONINFO, *PDVCOMPRESSIONINFO;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
guidType
GUID used to identify this compression type by DirectPlay Voice.
lpszName
Pointer to a name describing the codec.
lpszDescription
Pointer to a longer name of the codec.
dwFlags
Reserved; must be 0.
dwMaxBitsPerSecond
Maximum number of bits per second claimed by the codec.

Structure Information

Header | dvoice8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVSESSIONDESC Structure

Describes the desired or current session settings for the Microsoft® DirectPlay® Voice server. This structure is used by the voice session host to configure the session, and by the session host and clients to retrieve information about the current session.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwSessionType;
    GUID guidCT;
    DWORD dwBufferQuality;
    DWORD dwBufferAggressiveness;
} DVSESSIONDESC, *LPDVSESSIONDESC, *PDVSESSIONDESC;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Combination of the following flags.
DVSESSION_NOHOSTMIGRATION
The voice host will not migrate regardless of the transport settings. If this flag is not specified, the voice host will migrate if the transport supports it.
DVSESSION_SERVERCONTROLTARGET
The clients are unable to control the target of their speech. Only the server player can control the target of their speech. If the server does not specify this flag, only the clients can control the target of their speech. This flag can be specified only in multicast and mixing sessions.
dwSessionType
The type of DirectPlay Voice session to run. The DVSESSIONTYPE_PEER flag is not available in client/server sessions; all other flags are valid for all session types. This member can be one of the following values.
DVSESSIONTYPE_PEER
Voice messages will be sent directly between players.
DVSESSIONTYPE_MIXING
Voice session will use a mixing server. In this mode of operation, all voice messages are sent to the server, which mixes them and then forwards a single, premixed stream to each client. This reduces the bandwidth and CPU usage on clients significantly at the cost of increased bandwidth and CPU usage on the server.
DVSESSIONTYPE_FOWARDING
Voice messages will be routed through the session host. This will save bandwidth on the clients at the expense of bandwidth usage on the server. This option is only useful if the session host has a high-speed connection.
guidCT
GUID specifying the compression type of the session. To select the default compression codec, set this member to DPVCTGUID_DEFAULT.
dwBufferQuality
The buffer quality setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERQUALITY_DEFAULT.

Allowable values are between DVBUFFERQUALITY_MIN and DVBUFFERQUALITY_MAX. Additionally, this member can be set to the following value.

DVBUFFERQUALITY_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Sounds and Multimedia in Control Panel.
dwBufferAggressiveness
Buffer aggressiveness setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERAGGRESSIVENESS_DEFAULT.

Allowable values are between DVBUFFERAGGRESSIVENESS _MIN and DVBUFFERAGGRESSIVENESS _MAX. Additionally, this member can be set to the following value.

DVBUFFERAGGRESSIVENESS_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Control Panel.

Remarks

The dwFlags, dwSessionType, and guidCT members can only be set when the host starts the voice session. The host can change the buffer settings at any time.

Structure Information

Header | dvoice8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DVSOUNDDEVICECONFIG Structure

Used to set and retrieve information about the sound device configuration and cannot be changed once a connection has been made. After a connection is made, you can retrieve the current sound device configuration by calling IDirectPlayVoiceClient::GetSoundDeviceConfig.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidPlaybackDevice;
    LPDIRECTSOUND lpdsPlaybackDevice;
    GUID guidCaptureDevice;
    LPDIRECTSOUNDCAPTURE lpdsCaptureDevice;
    HWND hwndAppWindow;
    LPDIRECTSOUNDBUFFER lpdsMainBuffer;
    DWORD dwMainBufferFlags;
    DWORD dwMainBufferPriority;
} DVSOUNDDEVICECONFIG, *LPDVSOUNDDEVICECONFIG, *PDVSOUNDDEVICECONFIG;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
A combination of the following flags.
DVSOUNDCONFIG_AUTOSELECT
Tells Microsoft® DirectPlay® Voice to attempt to automatically select (or un-mute) the microphone line in the mixer for the specified recording device.
DVSOUNDCONFIG_HALFDUPLEX
Tells DirectPlay Voice to initialize itself in half-duplex mode. In half-duplex mode no recording takes place. If the initialization of the sound system fails in full-duplex mode, this flag will be set by the system.
DVSOUNDCONFIG_NORMALMODE
Tells DirectPlay Voice to use Microsoft DirectSound® Normal Mode when initializing the DirectSound object. If this flag is not specified, the DirectSound object is initialized with DirectSound Priority Mode. See documentation for IDirectSound8::SetCooperativeLevel for more information. If a valid DirectSound object is specified in the lpdsPlaybackDevice member, this flag is ignored.
DVSOUNDCONFIG_SETCONVERSIONQUALITY
Enables better quality audio at the expense of higher CPU usage.
DVSOUNDCONFIG_NORECVOLAVAILABLE
Set by DirectPlay Voice if there are no volume controls available on the recording device you specified. You cannot set this flag.
DVSOUNDCONFIG_NOFOCUS
The voice application will never go out of focus. In other words, the application will never release the sound capture device. Use of this flag is not recommended.
DVSOUNDCONFIG_STRICTFOCUS
The voice application will lose focus whenever its window is not the foreground window.
guidPlaybackDevice

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains the actual device globally unique identifier (GUID) used for playback.

When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the GUID of the device used for playback. This must be specified even if the lpdsPlaybackDevice member is used. You can also specify the following default GUIDs provided by DirectSound.
DSDEVID_DefaultPlayback
The system default playback device.
DSDEVID_DefaultVoicePlayback
The default voice playback device.
lpdsPlaybackDevice
When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the DirectSound object you want DirectPlay Voice to use for playback. The GUID specified in guidPlaybackDevice must match the one used to create the device specified by this parameter. If you used NULL when specifying the device when you created your DirectSound object, pass DSDEVID_DefaultPlayback for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains a pointer to the DirectSound object being used by DirectPlay Voice. This will either be a pointer to the object specified when Connect was called or a pointer to a newly created and initialized DirectSound object. If you want to use this DirectSound object, you must store the pointer and increment the reference count by calling AddRef on the DirectSound interface.

guidCaptureDevice
When this structure is used in IDirectPlayVoiceClient::Connect method, this member specifies the GUID of the device used for capture. This must be specified even if the lpdsCaptureDevice member is used. If you used NULL when specifying the device when you created your DirectSoundCapture object, pass DSDEVID_DefaultCapture for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member will contain the actual device GUID used for capture.

lpdsCaptureDevice
When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the DirectSound object you want DirectPlay Voice to use for capture. The GUID specified in guidCaptureDevice must match the one used to create the device specified by this parameter. If you want to have DirectPlay Voice create the DirectSoundCapture object for you, specify NULL for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains a pointer to the DirectSoundCapture object being used by DirectPlay Voice. This will either be a pointer to the object specified when Connect was called or a pointer to a newly created and initialized DirectSoundCapture object. If you want to use this DirectSoundCapture object, you must store the pointer and increment the reference count by calling AddRef on the IDirectSoundCapture8 interface. If the DirectPlay Voice object is operating in half duplex mode, this member will be NULL.

hwndAppWindow
Must be set to the handle of the window that will be used to determine focus for sound playback. See IDirectSound8::SetCooperativeLevel for information about DirectSound focus. If you do not have a window to use for focus, use GetDesktopWindow to use the desktop window.
lpdsMainBuffer
Pointer to an IDirectSoundBuffer8 interface, which is used to create the DirectPlay Voice main buffer. This can be either NULL or a user-created DirectSound buffer. If this member is set to NULL, DirectPlay Voice will create a buffer for the main voice buffer. If users specify a buffer here, DirectPlay Voice will use their buffer for the main voice buffer. User-created buffers have the following restrictions.
  • The buffer must be 22 kilohertz, 16-bit, Mono format.
  • The buffer must be at least 1 second in length.
  • The buffer must have been created with the DSBCAPS_GETCURRENTPOSITION2 and DSBCAPS_CTRL3D flags.
  • The buffer must not be a primary buffer.
  • The buffer must not be playing when it is passed to the DirectPlay Voice software.
  • The buffer must not be locked when it is passed to the DirectPlay Voice software.
dwMainBufferFlags
Passed directly to the dwFlags parameter of the IDirectSoundBuffer8::Play method when Play is called for the main buffer. The DSBPLAY_LOOPING flag is automatically added to this field. See the documentation on IDirectSoundBuffer8::Play for details. This parameter must be 0 if the lpdsMainBuffer member of this structure is NULL.
dwMainBufferPriority
Passed directly to the dwPriority parameter of the IDirectSoundBuffer8::Play method when Play is called on the main buffer. See documentation for IDirectSoundBuffer8::Play for more information. This member must be set to 0 if lpdsMainBufferDesc is NULL.

Remarks

Note Applications should set the DVSOUNDCONFIG_NOFOCUS or DVSOUNDCONFIG_STRICTFOCUS flags only when strictly necessary. Instead, you should normally use the default behavior that results when neither flag is set.

Structure Information

Header | dvoice8.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Return Values Enumerated Type

Errors are represented by negative values and cannot be combined.

Many of the Microsoft® DirectPlay® samples include a GetDirectPlayErrStr function that converts HRESULT values to string names for the DirectPlay errors. You can copy this code into your own applications for diagnostic traces or error reports.

Syntax

typedef enum {
    DPNSUCCESS_PENDING,
    DPN_OK,
    DPNERR_ABORTED,
    DPNERR_ADDRESSING,
    DPNERR_ALREADYCONNECTED,
    DPNERR_ALREADYCLOSING,
    DPNERR_ALREADYDISCONNECTING,
    DPNERR_ALREADYINITIALIZED,
    DPNERR_BUFFERTOOSMALL,
    DPNERR_CANNOTCANCEL,
    DPNERR_CANTCREATEGROUP,
    DPNERR_CANTCREATEPLAYER,
    DPNERR_CANTLAUNCHAPPLICATION,
    DPNERR_CONNECTING,
    DPNERR_CONNECTIONLOST,
    DPNERR_DATATOOLARGE,
    DPNERR_DOESNOTEXIST,
    DPNERR_DPNSVRNOTAVAILABLE,
    DPNERR_ENUMQUERYTOOLARGE,
    DPNERR_ENUMRESPONSETOOLARGE,
    DPNERR_EXCEPTION,
    DPNERR_GENERIC,
    DPNERR_GROUPNOTEMPTY,
    DPNERR_HOSTREJECTEDCONNECTION,
    DPNERR_HOSTTERMINATEDSESSION,
    DPNERR_INCOMPLETEADDRESS,
    DPNERR_INVALIDADDRESSFORMAT,
    DPNERR_INVALIDAPPLICATION,
    DPNERR_INVALIDCOMMAND,
    DPNERR_INVALIDDEVICEADDRESS,
    DPNERR_INVALIDFLAGS,
    DPNERR_INVALIDGROUP,
    DPNERR_INVALIDHANDLE,
    DPNERR_INVALIDHOSTADDRESS,
    DPNERR_INVALIDINSTANCE,
    DPNERR_INVALIDINTERFACE,
    DPNERR_INVALIDOBJECT,
    DPNERR_INVALIDPARAM,
    DPNERR_INVALIDPASSWORD,
    DPNERR_INVALIDPLAYER,
    DPNERR_INVALIDPOINTER,
    DPNERR_INVALIDPRIORITY,
    DPNERR_INVALIDSTRING,
    DPNERR_INVALIDURL,
    DPNERR_INVALIDVERSION,
    DPNERR_NOCAPS,
    DPNERR_NOCONNECTION,
    DPNERR_NOHOSTPLAYER,
    DPNERR_NOINTERFACE,
    DPNERR_NORESPONSE,
    DPNERR_NOTALLOWED,
    DPNERR_NOTHOST,
    DPNERR_NOTREADY,
    DPNERR_OUTOFMEMORY,
    DPNERR_PENDING,
    DPNERR_PLAYERALREADYINGROUP,
    DPNERR_PLAYERNOTINGROUP,
    DPNERR_PLAYERLOST,
    DPNERR_PLAYERNOTREACHABLE,
    DPNERR_SESSIONFULL,
    DPNERR_TIMEDOUT,
    DPNERR_UNINITIALIZED,
    DPNERR_UNSUPPORTED,
    DPNERR_USERCANCEL,
    DV_OK,
    DV_FULLDUPLEX,
    DV_HALFDUPLEX,
    DV_PENDING,
    DVERR_BUFFERTOOSMALL,
    DVERR_EXCEPTION,
    DVERR_GENERIC,
    DVERR_INVALIDFLAGS,
    DVERR_INVALIDOBJECT,
    DVERR_INVALIDPARAM,
    DVERR_INVALIDPLAYER,
    DVERR_INVALIDGROUP,
    DVERR_INVALIDHANDLE,
    DVERR_OUTOFMEMORY,
    DVERR_PENDING,
    DVERR_NOTSUPPORTED,
    DVERR_NOINTERFACE,
    DVERR_SESSIONLOST,
    DVERR_NOVOICESESSION,
    DVERR_CONNECTIONLOST,
    DVERR_NOTINITIALIZED,
    DVERR_CONNECTED,
    DVERR_NOTCONNECTED,
    DVERR_CONNECTABORTING,
    DVERR_NOTALLOWED,
    DVERR_INVALIDTARGET,
    DVERR_TRANSPORTNOTHOST,
    DVERR_COMPRESSIONNOTSUPPORTED,
    DVERR_ALREADYPENDING,
    DVERR_ALREADYINITIALIZED,
    DVERR_SOUNDINITFAILURE,
    DVERR_TIMEOUT,
    DVERR_CONNECTABORTED,
    DVERR_NO3DSOUND,
    DVERR_ALREADYBUFFERED,
    DVERR_NOTBUFFERED,
    DVERR_HOSTING,
    DVERR_NOTHOSTING,
    DVERR_INVALIDDEVICE,
    DVERR_RECORDSYSTEMERROR,
    DVERR_PLAYBACKSYSTEMERROR,
    DVERR_SENDERROR,
    DVERR_USERCANCEL,
    DVERR_UNKNOWN,
    DVERR_RUNSETUP,
    DVERR_INCOMPATIBLEVERSION,
    DVERR_INITIALIZED,
    DVERR_INVALIDPOINTER,
    DVERR_NOTRANSPORT,
    DVERR_NOCALLBACK,
    DVERR_TRANSPORTNOTINIT,
    DVERR_TRANSPORTNOSESSION,
    DVERR_TRANSPORTNOPLAYER,
    DP8SIM_OK,
    DP8SIMERR_ALREADYINITIALIZED,
    DP8SIMERR_INVALIDFLAGS,
    DP8SIMERR_INVALIDOBJECT,
    DP8SIMERR_MISMATCHEDVERSION,
    DP8SIMERR_NOTINITIALIZED,
    DP8SIMERR_INVALIDPARAM,
    DP8SIMERR_INVALIDPOINTER
} Return Values;

Constants

DPNSUCCESS_PENDING

An asynchronous operation has reached the point where it is successfully queued.

DPN_OK

The operation completed successfully. This value is equal to the S_OK standard Component Object Model (COM) return value.

DPNERR_ABORTED

The operation was canceled before it could be completed.

DPNERR_ADDRESSING

The address specified is invalid.

DPNERR_ALREADYCONNECTED

The object is already connected to the session.

DPNERR_ALREADYCLOSING

An attempt to call the Close method on a session has been made more than once.

DPNERR_ALREADYDISCONNECTING

The client is already disconnecting from the session.

DPNERR_ALREADYINITIALIZED

The object has already been initialized.

DPNERR_BUFFERTOOSMALL

The supplied buffer is not large enough to contain the requested data.

DPNERR_CANNOTCANCEL

The operation could not be canceled.

DPNERR_CANTCREATEGROUP

A new group cannot be created.

DPNERR_CANTCREATEPLAYER

A new player cannot be created.

DPNERR_CANTLAUNCHAPPLICATION

The lobby cannot launch the specified application.

DPNERR_CONNECTING

The method is in the process of connecting to the network.

DPNERR_CONNECTIONLOST

The service provider connection was reset while data was being sent.

DPNERR_DATATOOLARGE

The application data is too large for the service provider's Maximum Transmission Unit.

DPNERR_DOESNOTEXIST

Requested element is not part of the address or the requested application globally unique identifier (GUID) is not registered.

DPNERR_DPNSVRNOTAVAILABLE

Port 6073 is already in use.

DPNERR_ENUMQUERYTOOLARGE

The query data specified is too large.

DPNERR_ENUMRESPONSETOOLARGE

The response to an enumeration query is too large.

DPNERR_EXCEPTION

An exception occurred when processing the request.

DPNERR_GENERIC

An undefined error condition occurred.

DPNERR_GROUPNOTEMPTY

The specified group is not empty.

DPNERR_HOSTREJECTEDCONNECTION

The DPN_MSGID_INDICATE_CONNECT system message returned something other than S_OK in response to a connect request.

DPNERR_HOSTTERMINATEDSESSION

The host in a peer session (with host migration enabled) terminated the session.

DPNERR_INCOMPLETEADDRESS

The address specified is not complete.

DPNERR_INVALIDADDRESSFORMAT

The address format is invalid.

DPNERR_INVALIDAPPLICATION

The GUID supplied for the application is invalid.

DPNERR_INVALIDCOMMAND

The command specified is invalid.

DPNERR_INVALIDDEVICEADDRESS

The address for the local computer or adapter is invalid.

DPNERR_INVALIDFLAGS

The flags passed to this method are invalid.

DPNERR_INVALIDGROUP

The group identifier (ID) is not recognized as a valid group ID for this game session.

DPNERR_INVALIDHANDLE

The handle specified is invalid.

DPNERR_INVALIDHOSTADDRESS

The specified remote address is invalid.

DPNERR_INVALIDINSTANCE

The GUID for the application instance is invalid.

DPNERR_INVALIDINTERFACE

The interface parameter is invalid. This value will be returned in a connect request if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.

DPNERR_INVALIDOBJECT

The DirectPlay object pointer is invalid.

DPNERR_INVALIDPARAM

One or more of the parameters passed to the method are invalid.

DPNERR_INVALIDPASSWORD

An invalid password was supplied when attempting to join a session that requires a password.

DPNERR_INVALIDPLAYER

The player ID is not recognized as a valid player ID for this game session.

DPNERR_INVALIDPOINTER

The pointer specified as a parameter is invalid.

DPNERR_INVALIDPRIORITY

The specified priority is not within the range of allowed priorities, which is inclusively from 0 through 65535.

DPNERR_INVALIDSTRING

String specified as a parameter is invalid.

DPNERR_INVALIDURL

Specified string is not a valid DirectPlay URL.

DPNERR_INVALIDVERSION

There was an attempt to connect to an invalid version of DirectPlay.

DPNERR_NOCAPS

The communication link that DirectPlay is attempting to use is not capable of this function.

DPNERR_NOCONNECTION

No communication link was established.

DPNERR_NOHOSTPLAYER

There is currently no player acting as the host of the session.

DPNERR_NOINTERFACE

The interface is not supported.

DPNERR_NORESPONSE

There was no response from the specified target.

DPNERR_NOTALLOWED

This function is not allowed on this object.

DPNERR_NOTHOST

An attempt by the client to connect to a nonhost computer. Additionally, this error value can be returned by a nonhost that tries to set the application description.

DPNERR_NOTREADY

The object is not ready for use.

DPNERR_OUTOFMEMORY

There is insufficient memory to perform the requested operation.

DPNERR_PENDING

Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued. SUCCEEDED(DPNERR_PENDING) will return TRUE. This error value has been superseded by DPNERR_SUCCESS, which should be used by all new applications. DPNERR_PENDING is only included for backward compatibility.

DPNERR_PLAYERALREADYINGROUP

The player ID is already included in the group.

DPNERR_PLAYERNOTINGROUP

The player ID is not included in the group.

DPNERR_PLAYERLOST

A player has lost the connection to the session.

DPNERR_PLAYERNOTREACHABLE

A player has tried to join a peer-peer session where at least one other existing player in the session cannot connect to the joining player.

DPNERR_SESSIONFULL

The request to connect to the host or server failed because the maximum number of players allotted for the session has been reached.

DPNERR_TIMEDOUT

The operation could not complete because it has timed out.

DPNERR_UNINITIALIZED

The requested object has not been initialized.

DPNERR_UNSUPPORTED

The function or feature is not available in this implementation or on this service provider.

DPNERR_USERCANCEL

The user canceled the operation.

DV_OK

The request completed successfully.

DV_FULLDUPLEX

The sound card is capable of full-duplex operation.

DV_HALFDUPLEX

The sound card can only be run in half-duplex mode.

DV_PENDING

An asynchronous operation has reached the point where it is successfully queued.

DVERR_BUFFERTOOSMALL

The supplied buffer is not large enough to contain the requested data.

DVERR_EXCEPTION

An exception occurred when processing the request.

DVERR_GENERIC

An undefined error condition occurred.

DVERR_INVALIDFLAGS

The flags passed to this method are invalid.

DVERR_INVALIDOBJECT

The DirectPlay object pointer is invalid.

DVERR_INVALIDPARAM

One or more of the parameters passed to the method are invalid.

DVERR_INVALIDPLAYER

The player ID is not recognized as a valid player ID for this game session.

DVERR_INVALIDGROUP

The group ID is not recognized as a valid group ID for this game session.

DVERR_INVALIDHANDLE

The handle specified is invalid.

DVERR_OUTOFMEMORY

There is insufficient memory to perform the requested operation.

DVERR_PENDING

Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued. This error value has been deprecated. It has been replaced by DV_PENDING.

DVERR_NOTSUPPORTED

The operation is not supported.

DVERR_NOINTERFACE

The specified interface is not supported. Could indicate using the wrong version of DirectPlay.

DVERR_SESSIONLOST

The transport has lost the connection to the session.

DVERR_NOVOICESESSION

The session specified is not a voice session.

DVERR_CONNECTIONLOST

The connection to the voice session has been lost.

DVERR_NOTINITIALIZED

The IDirectPlayVoiceClient::Initialize IDirectPlayVoiceClient8::Initialize or IDirectPlayVoiceServer::Initialize IDirectPlayVoiceServer8::Initialize method must be called before calling this method.

DVERR_CONNECTED

The DirectPlay Voice object is connected.

DVERR_NOTCONNECTED

The DirectPlay Voice object is not connected.

DVERR_CONNECTABORTING

The connection is being disconnected.

DVERR_NOTALLOWED

The object does not have the permission to perform this operation.

DVERR_INVALIDTARGET

The specified target is not a valid player ID or group ID for this voice session.

DVERR_TRANSPORTNOTHOST

The object is not the host of the voice session.

DVERR_COMPRESSIONNOTSUPPORTED

The specified compression type is not supported on the local computer.

DVERR_ALREADYPENDING

An asynchronous call of this type is already pending.

DVERR_ALREADYINITIALIZED

The object has already been initialized.

DVERR_SOUNDINITFAILURE

A failure was encountered initializing the sound card.

DVERR_TIMEOUT

The operation could not be performed in the specified time.

DVERR_CONNECTABORTED

The connect operation was canceled before it could be completed.

DVERR_NO3DSOUND

The local computer does not support 3-D sound.

DVERR_ALREADYBUFFERED

There is already a user buffer for the specified ID.

DVERR_NOTBUFFERED

There is no user buffer for the specified ID.

DVERR_HOSTING

The object is the host of the session.

DVERR_NOTHOSTING

The object is not the host of the session.

DVERR_INVALIDDEVICE

The specified device is invalid.

DVERR_RECORDSYSTEMERROR

An error in the recording system occurred.

DVERR_PLAYBACKSYSTEMERROR

An error in the playback system occurred.

DVERR_SENDERROR

An error occurred while sending data.

DVERR_USERCANCEL

The user canceled the operation.

DVERR_UNKNOWN

An unknown error occurred.

DVERR_RUNSETUP

The specified audio configuration has not been tested. Call the IDirectPlayVoiceTest::CheckAudioSetup method.

DVERR_INCOMPATIBLEVERSION

The client connected to a voice session that is incompatible with the host.

DVERR_INITIALIZED

The Initialize method failed because the object has already been initialized.

DVERR_INVALIDPOINTER

The pointer specified is invalid.

DVERR_NOTRANSPORT

The specified object is not a valid transport.

DVERR_NOCALLBACK

This operation cannot be performed because no callback function was specified.

DVERR_TRANSPORTNOTINIT

The specified transport is not yet initialized.

DVERR_TRANSPORTNOSESSION

The specified transport is valid but is not connected/hosting.

DVERR_TRANSPORTNOPLAYER

The specified transport is connected/hosting but no local player exists.

DP8SIM_OK

The DP8Sim control object was successfully initialized.

DP8SIMERR_ALREADYINITIALIZED

The DP8Sim control object has already been initialized.

DP8SIMERR_INVALIDFLAGS

The flags passed to this method are invalid.

DP8SIMERR_INVALIDOBJECT

The DP8Sim control object specified is invalid.

DP8SIMERR_MISMATCHEDVERSION

A different version of DP8Sim is already in use on this system.

DP8SIMERR_NOTINITIALIZED

The DP8Sim control object has not been initialized.

DP8SIMERR_INVALIDPARAM

One or more of the parameters passed to the method are invalid.

DP8SIMERR_INVALIDPOINTER

A pointer specified as a parameter is invalid.

Remarks

The following table lists the interfaces to which the error codes listed apply.

Interface
IDirectPlay8Address
IDirectPlay8AddressIP
IDirectPlay8Client
IDirectPlay8LobbiedApplication
IDirectPlay8LobbyClient
IDirectPlay8Peer
IDirectPlay8Server
IDirectPlayVoiceClient
IDirectPlayVoiceServer
IDirectPlayVoiceTest
IDP8SimControl

For a list of the error codes each method can return, see the individual method descriptions.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP

© 2002 Microsoft Corporation. All rights reserved.


DirectSetup

This section provides information about the DirectSetup component of the Microsoft® DirectX® application programming interface (API) in the Microsoft Platform Software Development Kit (SDK) or the stand-alone DirectX software development kit (SDK).

This section includes the following topics:

  • DirectSetup Essentials
  • DXSetup.exe
  • DirectSetup Reference
  • Dinstall Sample

About DirectSetup

DirectSetup is a simple API that provides one-call installation of the DirectX components. This is more than a convenience; DirectX is a complex product and installing it is an involved task. You should not attempt to install DirectX manually.

DirectSetup includes several API functions and structures. It also includes a prototype DirectXSetupCallbackFunction that can be defined by an application to customize the user interface during the installation process. The DirectX SDK includes a sample application that demonstrates the use of this callback function.

If you don't want to create your own custom installation, you can use the DXSetup.exe standard installation provided with the SDK.

© 2002 Microsoft Corporation. All rights reserved.


DirectSetup Essentials

This section contains general information about the Microsoft DirectSetup component. The following topics are discussed.

  • Setup Overview for DirectSetup
  • Preparing the Setup Folder
  • Customizing Setup
  • Testing the Setup Program
  • Enabling AutoPlay

© 2002 Microsoft Corporation. All rights reserved.


Setup Overview for DirectSetup

Applications and games that depend on Microsoft® DirectX® use the DirectXSetup function to install the necessary system components into an existing Microsoft Windows® installation. The function optionally updates the display and audio drivers for optimal support of DirectX. Typically, you would call DirectXSetup from the program that you are using to install your own application files.

Warning The DirectXSetup function overwrites system components from previous versions of DirectX. For example, if you install DirectX 8.0 on a system that already has DirectX 7.0 components, all DirectX 7.0 components are overwritten. Because all DirectX components comply with Component Object Model (COM) backward-compatibility rules, software written for DirectX 7.0 continues to function properly.

The DirectXSetup function can tell when DirectX components, display drivers, and audio drivers need to be upgraded. It can also distinguish whether these components can be upgraded without adversely affecting the Windows operating system. This is said to be a safe upgrade. The upgrade is safe for the operating system, not necessarily for the applications running on the computer. Some hardware-dependent applications can be negatively affected by an upgrade that is safe for Windows.

By default, the DirectXSetup function performs only safe upgrades. If the upgrade of a device driver might adversely affect the operation of Windows, the upgrade is not performed.

During the setup process, DirectSetup creates a backup copy of the system components and drivers that are replaced. These can be restored if problems occur.

When display or audio drivers are upgraded, the DirectXSetup function uses a database created by the system to manage the process. The database contains information about existing drivers that are provided by Microsoft, the manufacturers of the hardware, or the vendors of the hardware. This database describes the upgrade status of each driver, based on testing done at Microsoft and other sites.

Check the value returned by DirectXSetup. If it is DSETUPERR_SUCCESS_RESTART, notify the user that changes do not take effect without a restart, and offer the choice of restarting immediately. For an example of how to do this, see Dinstall.c in the Dinstall Sample.

© 2002 Microsoft Corporation. All rights reserved.


Preparing the Setup Folder

The DirectXSetup function takes a parameter, lpszRootPath, that points to the root directory of the installation. It can be NULL to indicate that the root path is the current directory—that is, the directory where your setup program resides.

The root directory must contain Dsetup.dll and Dsetup32.dll. It must also have a folder named "DirectX" (this name is not case sensitive), containing all the redistributable files and drivers. To create the proper structure on your application setup disk, copy the redistributable code from one of the following locations into the root path of your setup program.

  • Installed by the software development kit (SDK) at (SDK root)\Redist\DirectX9
  • On the Microsoft® DirectX® 9.0 CD at (CD root)\Redist\DirectX9
  • SDK download at (Extracted location)\Redist\DirectX9
  • A separate download at http://msdn.microsoft.com/downloads World Wide Web link

These files must be included in any distribution of DirectX 9.0 as explained by the "DirectX Redist.txt" file found at (CD root)\License\DirectX Redist.txt.

© 2002 Microsoft Corporation. All rights reserved.


Customizing Setup

Microsoft DirectSetup enables you to define a callback function for customizing the Microsoft® DirectX® setup process. In the DirectSetup documentation, this callback function is referred to as DirectXSetupCallbackFunction, but you can give it any name.

If a callback function is not provided by the setup program, the DirectXSetup function displays status and error information in a dialog box and obtains user input by calling the Microsoft Win32® MessageBox function. If a callback is provided, the information that would have been used to create the status dialog or message box is instead passed to the callback. The callback function is called once for each DirectX component and device driver that can be installed or upgraded.

You can use the callback function to do the following:

  • Employ a custom interface. Your setup program might display messages in ways other than by using MessageBox or standard Microsoft® Windows® dialog boxes. The callback function enables you to integrate messages for the DirectX component of your installation into your own interface.
  • Update a progress indicator.
  • Suppress the display of status and error messages. Designers of programs for novice users might want to suppress error messages and let the setup program handle errors and make upgrade choices silently. This approach requires a greater development effort for the setup program, but it might be appropriate for the target audience.

For help customizing your setup, see Creating a DirectSetup Callback Function.

© 2002 Microsoft Corporation. All rights reserved.


Creating a DirectSetup Callback Function

To customize the setup process, first create a callback function that conforms to the DirectXSetupCallbackFunction prototype, as in the following declaration.

DWORD WINAPI DirectXSetupCallbackFunction(
        DWORD dwReason,
        DWORD dwMsgType,
        LPSTR szMessage,
        LPSTR szName,
        void *pInfo);

In this example, adapted from the Dinstall Sample sample application, the name of the function is the same as that of the prototype, but this is optional. The parameter names differ slightly from those in the prototype declared in the Dsetup.h header file and are used throughout the following discussion.

  • Parameters
  • Return Value
  • Setting the Callback Function

Parameters

The dwReason parameter indicates why the callback function has been called. The possible values are listed and explained in the reference for DirectXSetupCallbackFunction.

The dwMsgType parameter receives flags equivalent to those that DirectSetup would, by default, pass to MessageBox, such as those controlling which buttons and icons are displayed. Of special interest are the button flags, which you use to determine what return values are expected. If this value is 0, the event never requires user input, and DirectSetup normally displays a status message.

The szMessage parameter receives the same text that DirectSetup would otherwise pass to the status dialog box or to MessageBox.

When a driver is a candidate for upgrading, its name is passed in the szName parameter, and pInfo points to information about how the upgrade is to be handled—for example, whether DirectSetup recommends that the old driver be kept or upgraded.

The way your callback function interprets the parameters is entirely up to you. Typically, you would choose which messages to display (based on dwReason) and when to present the user with alternatives, and you would modify the interface accordingly.

Return Value

The value returned by your callback function must conform to the following rules.

  • When dwMsgType is 0, the return value must be IDOK. In this case, there are no choices to be made by the user. Your application, of course, can display a status message, even though no input is required.
  • If dwMsgType is nonzero, the return value must be the same as would have been returned by MessageBox, given the equivalent choice by the user.

To determine the appropriate return value in the second case, test dwMsgType for the buttons that would normally have been put in a message box. The following example, from the GetReply function in Dinstall, shows how this is done.

/* The global g_wReply identifies the custom dialog button
   that has been selected by the user. */

switch (dwMsgType & 0x0000000F)
{
   / * There would normally have been an OK and a Cancel button.
       IDBUT1 is equivalent to the OK button. If the user did not
       choose that, it was a Cancel. */
    case MB_OKCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDOK : IDCANCEL;
        break;
    / * And so on with the other button combinations. */
    case MB_OK:
        wDefaultButton = IDOK;
        break;
    case MB_RETRYCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDRETRY : IDCANCEL;
        break;
    case MB_ABORTRETRYIGNORE:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDABORT;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDRETRY;
        else
            wDefaultButton = IDIGNORE;
        break;
    case MB_YESNOCANCEL:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDYES;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDNO;
        else
            wDefaultButton = IDCANCEL;
        break;
    case MB_YESNO:
        wDefaultButton = (g_wReply == IDBUT1) ? IDYES : IDNO;
        break;
    default:
        wDefaultButton = IDOK;
}

This routine translates button clicks from the custom interface into the equivalent button identifiers in the standard dialog box that DirectSetup would otherwise create. The wDefaultButton variable is set to the identifier of the equivalent standard dialog box button, and this value is ultimately returned from the callback function.

Setting the Callback Function

Before calling DirectXSetup, notify DirectSetup that you want to use a callback by calling the DirectXSetupSetCallback function, passing a pointer to the callback as a parameter. The following example shows how this is done.

DirectXSetupSetCallback(
        (DSETUP_CALLBACK) DirectXSetupCallbackFunction);

© 2002 Microsoft Corporation. All rights reserved.


Testing the Setup Program

To test the DirectSetup component of your setup program, compile a version in which the DSETUP_TESTINSTALL flag is passed to the DirectXSetup function. Set up the installation directory, as described in Preparing the Setup Folder.

When you run your setup program, DirectSetup goes through the motions of installing Microsoft® DirectX®, including calls to your callback function if you have provided one, without actually installing any components.

© 2002 Microsoft Corporation. All rights reserved.


Enabling AutoPlay

If you are building an AutoPlay compact disc title, copy the Autorun.inf file in the root directory of the Microsoft® DirectX® software development kit (SDK) compact disc to the root of your application directory. This text file contains the following information.

[autorun]
OPEN=SETUP.EXE

If your application's setup program is called Setup.exe, you do not have to make any changes to this file; otherwise, edit this file to contain the name of your setup program.

© 2002 Microsoft Corporation. All rights reserved.


DXSetup.exe

DXSetup.exe is a standard installer that independent software vendors (ISVs) can use to install the Microsoft® DirectX® 9.0 redistributable runtime. It provides an easy way for developers to install the DirectX 9.0 runtime without having to write a custom installer. The standard installer is included in the (SDK root)\Redist\DirectX9 folder.

DXSetup.exe uses the DirectSetup application programming interface (API) for version checking, setting up install type, displaying the end-user license agreement (EULA), installing DirectX, progress reporting, and message handling. DXSetup.exe displays all user interface (UI) components during the DirectX 9.0 installation. These include the click-through-EULA, progress meter, and message handling.

Developers who need to install the Managed DirectX component and are using the standard installer must perform the following steps.

  1. Before calling DXSetup.exe, verify the Microsoft .NET Framework is installed.
  2. Call DXSetup.exe with the /InstallManagedDX command line attribute.

The following is an example of how to use the standard installer for Managed DirectX.

DXSetup.exe /InstallManagedDX

DXSetup.exe Supports the Microsoft Windows® 98, Windows 98 Second Edition, Windows Millennium Edition (Windows Me), Windows 2000, and Windows XP operating systems.

DXSetup.exe supports the following languages:

  • Chinese (Simplified)
  • Chinese (Traditional)
  • Czech
  • Dutch
  • English (American)
  • French
  • German
  • Italian
  • Japanese
  • Korean
  • Polish
  • Portuguese (Brazil)
  • Russian
  • Spanish
  • Swedish

© 2002 Microsoft Corporation. All rights reserved.


DirectSetup Reference

This section contains reference information for the Microsoft DirectSetup application programming interface (API) elements. Reference material is divided into the following categories.

  • Functions
  • Structures
  • Enumerations
  • Return Values

© 2002 Microsoft Corporation. All rights reserved.


Functions

This section contains information about the following global functions used with Microsoft DirectSetup.

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetEULA
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXSetupShowEULA
  • DirectXUnRegisterApplication

© 2002 Microsoft Corporation. All rights reserved.


DirectXRegisterApplication Function

Registers an application as one designed to work with IDirectPlayLobby3.

Syntax

int DirectXRegisterApplication(

    HWND hWnd,
    LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
Handle of the parent window. If this parameter is set to NULL, the desktop is the parent window.
lpDXRegApp
Address of the DIRECTXREGISTERAPP structure that contains the registry entries that are required for the application to function properly with DirectPlayLobby.

Return Value

If this function succeeds, it returns TRUE.

If it fails, it returns FALSE. Call the GetLastError function to get extended error information.

Remarks

The DirectXRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These files are not installed on the system but they are included in the software development kit (SDK).

DirectXRegisterApplication corresponds to the old IDirectPlayLobby3::RegisterApplication method. It is recommended that you use the IDirectPlay8LobbiedApplication::RegisterProgram method instead.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXUnRegisterApplication

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetup Function

Installs one or more Microsoft® DirectX® components.

Syntax

int DirectXSetup(

    HWND hWnd,
    LPSTR lpszRootPath,
    DWORD dwFlags
);

Parameters

hWnd
Handle of the parent window for the setup dialog boxes.
lpszRootPath
Address of a string that contains the root path of the DirectX component files. This string must specify a full path to the directory that contains the files Dsetup.dll and Dsetup32.dll, as well as the DirectX redistributable files. If this value is NULL, the current working directory is used.
dwFlags
One or more flags indicating which control the DirectSetup configuration.
DSETUP_DIRECTX
Installs DirectX run-time components, as well as DirectX-compatible display and audio drivers.
DSETUP_MANAGEDDX
Installs the Managed DirectX component. This requires that the Microsoft .NET Framework is installed.
DSETUP_TESTINSTALL
Performs a test installation. Does not install new components.

Return Value

If it fails, it returns an error value. For a list of possible return values, see Return Values. If this function succeeds, it returns one of the following success codes:

DSETUPERR_SUCCESS | Success.
DSETUPERR_SUCCESS_RESTART | Success, but the user must restart the system for the changes to take effect.

Remarks

Before using the DirectXSetup function in your setup program, you should first ensure that the system has enough available disk space. The maximum space that you need to set up DirectX 9.0 is 20 MB for Microsoft Windows® 98 and Windows Millennium Edition (Windows Me) systems, and 25 MB for Windows 2000 and Windows XP.

The following flags can be specified for the dwFlags parameter but are ignored by DirectX 9.0.
DSETUP_D3D | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAW | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAWDRV | Not used in DirectX 8.1.
DSETUP_DINPUT | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DIRECTXSETUP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAY | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAYSP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUND | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUNDDRV | Not used in DirectX 8.1.
DSETUP_DXCORE | Installs DirectX run-time components. Does not install DirectX-compatible display and audio drivers.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetupCallbackFunction Function

A placeholder name for an optional callback function supplied by the setup program. If present, it is called once for each step in the setup process.

Syntax

DWORD DirectXSetupCallbackFunction(

    DWORD Reason,
    DWORD MsgType,
    char *szMessage,
    char *szName,
    void *pInfo
);

Parameters

Reason
Reason for the callback. It can be one of the following values:
DSETUP_CB_MSG_BEGIN_INSTALL
DirectXSetup is about to begin installing Microsoft® DirectX® components. The system will be checked for the DirectX version, operating system, system language, and disk space requirements.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_INTERNAL_ERROR
An internal error has occurred. Setup of the DirectX component or device driver has failed.
DSETUP_CB_MSG_NOMESSAGE
No message to be displayed. The callback function should return.
DSETUP_CB_MSG_PROGRESS
Reporting the progress of the runtime installation, which includes initializing, extracting, copying, and finalizing DirectSetup files.
DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT
DirectSetup has detected that one or more DirectX components are disabled.
MsgType
Flags that control the display of a message box. These flags can be passed as the uType parameter to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information but should not wait for input from the user.
szMessage
Pointer to a localized character string containing error or status messages that can be displayed in a dialog box created with the MessageBox function.
szName
NULL and can be ignored.
pInfo
Pointer to the address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_PROGRESS, the setup program supplies the current state of installation. In this case, pInfo points to a DSETUP_CB_PROGRESS structure containing information about the phase of the installation.

Return Value

The return value should be the same as the value that would be returned by the MessageBox function, with one exception. If this function returns 0, the DirectXSetup function performs the default action for upgrade of the DirectX component or driver.

Remarks

The name of DirectXSetupCallbackFunction is supplied by the setup program. The DirectXSetupSetCallback function is used to pass the address of the callback function to DirectSetup.

If MsgType is 0, the setup program can display status information but it should not wait for user input. In this case, the function returns IDOK.

If Reason is DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT, direct the user to the DirectX Diagnostic Tool for more information about enabling DirectX components. It is typical for components such as Microsoft Direct3D® to be disabled on Microsoft Windows® servers.

Function Information

Header | dsetup.h
Import library | None
Minimum operating systems | Windows 98

See Also

DirectXSetupSetCallback, Customizing Setup

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetupGetEULA Function

Gets the Microsoft® DirectX® end-user license agreement (EULA) text for a specific language.

Syntax

int WINAPI DirectXSetupGetEULA(

    LPTSTR lpszEULA,
    UINT cchEULA,
    WORD LangID
);

Parameters

lpszEULA
[in] Points to a buffer that receives the EULA string. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
cchEULA
[out] Specifies the size of the buffer pointed to by the lpszEULA parameter. If this value is zero, the function returns the required buffer size and makes no use of the lpszEULA buffer. If the compiler settings specify Unicode, the size is in Unicode characters, otherwise the size will be in ANSI characters.
LangID
[in] Determines in which language the DirectX EULA is returned. Specify 0 for the system default language. Or specify one of the following values.
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED)
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL)
MAKELANGID(LANG_CZECH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_DUTCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_FRENCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_GERMAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ITALIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_JAPANESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_KOREAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_POLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_PORTUGUESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_RUSSIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SPANISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SWEDISH, SUBLANG_NEUTRAL)

Return Value

If the function succeeds, and cchEULA is nonzero, the return value is the number of EULA characters (Unicode or ANSI) written to the buffer pointed to by lpszEULA. If the function succeeds, and cchEULA is zero, the return value is the required size, in ANSI or Unicode characters, for a buffer that can receive the EULA string.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to DirectXSetupGetEULAW. Otherwise, the function call resolves to DirectXSetupGetEULAA because ANSI strings are being used.

If a LangID is passed that is not supported, the function will fail and return 0. In this case, the GetLastError return value will be ERROR_INVALID_PARAMETER. ERROR_INVALID_PARAMETER is also returned for the following reasons.

  • cchEULA is not large enough to receive the EULA.
  • cchEULA is nonzero and lpszEULA is NULL.
  • lpszEULA is an invalid pointer.

The setup application must display the EULA with in accordance with the DirectX software development kit (SDK) EULA.

The EULA must be displayed and accepted before continuing with DirectSetup.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetupGetVersion Function

Retrieves the version number of the Microsoft® DirectX® components that are currently installed.

Syntax

INT DirectXSetupGetVersion(

    DWORD *pdwVersion,
    DWORD *pdwRevision
);

Parameters

pdwVersion
Pointer to the address of a variable to receive the version number. This parameter can be NULL if the version number is not wanted.
pdwRevision
Pointer to the address of a variable to receive the revision number. This parameter can be NULL if the revision number is not wanted.

Return Value

If the function succeeds, it returns nonzero.

If it fails, it returns 0.

Remarks

The DirectXSetupGetVersion function can be used to retrieve the version and revision numbers before or after the DirectXSetup function is called. If it is called before DirectXSetup is invoked, it gives the version and revision numbers of the DirectX components that are currently installed. If it is called after DirectXSetup is called, but before the computer is restarted, it gives the version and revision numbers of the DirectX components that take effect after the computer is restarted.

The version number in the pdwVersion parameter is composed of the major version number and the minor version number. The major version number is in the 16 most significant bits of the DWORD when this function returns. The minor version number is in the 16 least significant bits of the DWORD when this function returns. The version numbers can be interpreted as follows:

DirectX version | Value pointed to by pdwVersion
DirectX 5.0 | 0x00040005
DirectX 6.0 | 0x00040006
DirectX 7.0 | 0x00040007
DirectX 8.x | 0x00040008
DirectX 9.0 | 0x00040009

DirectX 9.0 supports only operating systems and DirectX versions later than Microsoft Windows® 98 and DirectX 5.0. This method will not return a value less than 0x00040005 for pdwVersion.

The version number in the pdwRevision parameter is composed of the release number and the build number. The release number is in the 16 most significant bits of the DWORD when this function returns. The build number is in the 16 least significant bits of the DWORD when this function returns.

All DirectX 8.x releases have the same pdwVersion value. The pdwRevision parameter differentiates them. DirectX 8.x versions do not install on Windows XP. Windows XP shipped with DirectX 8.1 and the DirectX 8.1a and DirectX 8.1b updates were included in Windows XP Service Pack 1. The following table lists the pdwRevision values for DirectX 8.x.
DirectX release | pdwRevision | Notes
DirectX 8.0
DirectX 8.1 | 0x0001032A | 4.08.01.0810. Windows XP version
DirectX 8.1 | 0x00010371 | 4.08.01.0881. This is the DirectX 8.1 version for the down level operating systems. 0371 is the hex version for 0881 decimal revision value
DirectX 8.1a | 0x00010385 | 4.08.01.0901. This release includes an update to Microsoft Direct3D® (d3d8.dll).
DirectX 8.1b | 0x00010385 | 4.08.01.0901. This update includes a fix to Microsoft DirectShow® on Windows 2000 (quartz.dll)
DirectX 8.2 | 0x00020386 | 4.08.02.0134. This version includes Microsoft DirectPlay® updates for both Windows XP and downlevel operating systems.

Note There is no way to tell the difference between DirectX 8.1a and DirectX 8.1b with the pdwVersion and pdwRevision values. DirectX 8.1a updates only D3d8.dll. DirectX 8.1b includes the changes in DirectX 8.1a as well as updates to other files. Use GetFileVersionInfo to get version information for the following files.

On Windows 2000:

Quartz.dll | 6.03.01.0885
Stream.sys | 5.01.2600.0885
Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 5.01.2600.0901
D3d8d.dll | 5.01.2600.0901

On Windows 95 or later:

Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 4.08.01.0901
D3d8d.dll | 4.08.01.0901

The following sample code fragment demonstrates how the information returned by DirectXSetupGetVersion can be extracted and used.

DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
    printf("DirectX version is %d.%d.%d.%d\n",
           HIWORD(dwVersion), LOWORD(dwVersion),
           HIWORD(dwRevision), LOWORD(dwRevision));
}

Version and revision numbers can be concatenated into a 64-bit quantity for comparison. The version number is in the 32 most significant bits and the revision number is in the 32 least significant bits.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXSetup

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetupSetCallback Function

Sets a pointer to a callback function that is periodically called by DirectXSetup. The callback function can be used for setup progress notification and to implement a custom user interface for an application's setup program. For more information, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

Syntax

INT DirectXSetupSetCallback(

    DSETUP_CALLBACK Callback
);

Parameters

Callback
Address of a callback function.

Return Value

Currently returns 0.

Remarks

To set a callback function, DirectXSetupSetCallback must be called before DirectXSetup is called.

The name of the callback function passed to DirectXSetupSetCallback is supplied by the setup program. However, it must match the prototype given in DirectXSetupCallbackFunction.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXSetupCallbackFunction, DirectXSetup

© 2002 Microsoft Corporation. All rights reserved.


DirectXSetupShowEULA Function

Displays the Microsoft® DirectX® end-user license agreement (EULA) in the system's localized language.

Syntax

int WINAPI DirectXSetupShowEULA(

    HWND hWndParent
);

Parameters

hWndParent
Handle of the parent window for the EULA dialog boxes.

Return Value

IDYES is returned if the user accepts the EULA and the application can continue with DirectSetup. Otherwise, IDNO is returned and the application must cancel DirectSetup.

Remarks

Both the EULA and dialog box displaying the EULA are localized to the system language.

If hWndParent equals NULL then DirectSetup uses the desktop as the parent window.

DirectXSetupShowEULA should be called before proceeding with DirectSetup.

Even if the local language for the system is changed to another language, using, for example, a multilingual user interface package, this application programming interface (API) displays the DirectX user interface (UI) in the system language. To display the EULA for local languages other than the system language, use DirectXSetupGetEULA.

IDNO is returned if the user rejects the EULA or an internal setup error occurs.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DirectXUnRegisterApplication Function

Deletes the registration of an application designed to work with IDirectPlayLobby3.

Syntax

int DirectXUnRegisterApplication(

    HWND hWnd,
    LPGUID lpGUID
);

Parameters

hWnd
Handle of the parent window. Set this to NULL if the desktop is the parent window.
lpGUID
Address of a globally unique identifier (GUID) that represents the Microsoft® DirectPlay® application to be unregistered.

Return Value

If the function succeeds, the return value is TRUE. This means that the registration is successfully deleted.

If the function fails, the return value is FALSE.

Remarks

The DirectXUnRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These two files are not installed on the system but they are included in the software development kit (SDK).

DirectXUnRegisterApplication corresponds to the old IDirectPlayLobby3::UnregisterApplication method. It is recommended that you use the IDirectPlay8LobbiedApplication::UnRegisterProgram method instead.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXRegisterApplication

© 2002 Microsoft Corporation. All rights reserved.


Structures

This section contains information about the following structures used with Microsoft DirectSetup.

  • DIRECTXREGISTERAPP
  • DIRECTXREGISTERAPP2
  • DSETUP_CB_PROGRESS
Note The memory for all Microsoft® DirectX® structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use.

© 2002 Microsoft Corporation. All rights reserved.


DIRECTXREGISTERAPP Structure

Contains the registry entries needed for applications designed to work with IDirectPlayLobby3.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *PDIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved.
lpszApplicationName
Name of the application.
lpGUID
globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DIRECTXREGISTERAPP2 Structure

Contains the registry entries needed for applications designed to work with IDirectPlayLobby3.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
    LPSTR lpszLauncherName;
} DIRECTXREGISTERAPP2, *PDIRECTXREGISTERAPP2, *LPDIRECTXREGISTERAPP2;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved.
lpszApplicationName
Name of the application.
lpGUID
The globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.
lpszLauncherName
Name of the executable to be launched from the lobby.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


DSETUP_CB_PROGRESS Structure

Passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_PROGRESS. Callback functions can use it to get status information on the upgrade that is about to be done.

Syntax

typedef struct _DSETUP_CB_PROGRESS {
    DWORD dwPhase;
    DWORD dwInPhaseMaximum;
    DWORD dwInPhaseProgress;
    DWORD dwOverallMaximum;
    DWORD dwOverallProgress;
} DSETUP_CB_PROGRESS;

Members

dwPhase
Flag indicating the phase of the install progress. Can be any of the DSETUP_CB_PROGRESS_PHASE flags.
dwInPhaseMaximum
This is the maximum number of files that will need to be extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phase. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwInPhaseProgress
This is the current number of files that have been extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phase. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwOverallMaximum
This is the total number of files for both the DSETUP_EXTRACTING and DSETUP_COPYING phase that need to be performed. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwOverallProgress
This is the current number of files that have been extract or copied in relation to the dwOverallMaximum value. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98

See Also

DirectXSetupCallbackFunction

© 2002 Microsoft Corporation. All rights reserved.


Enumerations

This section contains information on the following enumerations used with Microsoft® DirectSetup:

Enumerations

  • DSETUP_CB_PROGRESS_PHASE

© 2002 Microsoft Corporation. All rights reserved.


DSETUP_CB_PROGRESS_PHASE Enumerated Type

Specifies the progress phase of a DirectSetup install.

Syntax

typedef enum _DSETUP_CB_PROGRESS_PHASE {
    DSETUP_INITIALIZING,
    DSETUP_EXTRACTING,
    DSETUP_COPYING,
    DSETUP_FINALIZING
} DSETUP_CB_PROGRESS_PHASE;

Constants

DSETUP_INITIALIZING

Initializing DirectSetup. Initialization includes version checking, an operating system check, and locale and disk space calculations.

DSETUP_EXTRACTING

Extracting files from the cabinet (.cab) files.

DSETUP_COPYING

Copying files onto the user's computer.

DSETUP_FINALIZING

Finalizing DirectSetup. This includes updating the registry and removing temporary files.

Enumerated Type Information

Header | dsetup.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Return Values Enumerated Type

The DirectXSetup function can return the following values. It can also return a standard Component Object Model (COM) error.

Syntax

typedef enum {
    DSETUPERR_SUCCESS,
    DSETUPERR_SUCCESS_RESTART,
    DSETUPERR_BADWINDOWSVERSION,
    DSETUPERR_CANTFINDDIR,
    DSETUPERR_CANTFINDINF,
    DSETUPERR_INTERNAL,
    DSETUPERR_NOTADMIN,
    DSETUPERR_NOCOPY,
    DSETUPERR_OUTOFDISKSPACE,
    DSETUPERR_SOURCEFILENOTFOUND,
    DSETUPERR_UNSUPPORTEDPROCESSOR,
    DSETUPERR_MISSINGCAB_MANAGEDDX,
    DSETUPERR_NODOTNETFRAMEWORKINSTALLED
} Return Values;

Constants

DSETUPERR_SUCCESS

Setup was successful, and no restart is required.

DSETUPERR_SUCCESS_RESTART

Setup was successful, and a restart is required.

DSETUPERR_BADWINDOWSVERSION

Microsoft® DirectX® does not support the Microsoft Windows® version on the system.

DSETUPERR_CANTFINDDIR

The setup program could not find the working directory.

DSETUPERR_CANTFINDINF

A required .inf file could not be found.

DSETUPERR_INTERNAL

An internal error occurred.

DSETUPERR_NOTADMIN

The current user does not have administrative privileges. On Windows 2000 systems, the user may need administrative privileges for some setup operations.

DSETUPERR_NOCOPY

A file's version could not be verified or was incorrect.

DSETUPERR_OUTOFDISKSPACE

The setup program ran out of disk space during installation.

DSETUPERR_SOURCEFILENOTFOUND

One of the required source files could not be found.

DSETUPERR_UNSUPPORTEDPROCESSOR

The processor type is unsupported. DirectX 9.0 supports only Pentium or K6-compatible or higher processors.

DSETUPERR_MISSINGCAB_MANAGEDDX

ManagedDX.CAB is missing from the DirectX package.

DSETUPERR_NODOTNETFRAMEWORKINSTALLED

The Microsoft .NET Framework is not installed and is required for Managed DirectX.

Enumerated Type Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Dinstall Sample

Description

Dinstall is an example of how to use Microsoft DirectSetup functions to install the Microsoft® DirectX® subsystem. It shows how to use a callback function to present messages and get user input through a custom interface, in this case a simple modeless dialog box.

Path

Source: (SDK root)\Samples\C++\Misc\DXInstall

User's Guide

  1. Copy the entire contents of the \Redist\DirectX8 folder from the DirectX software development kit (SDK) CD into the same folder as Dinstall.exe.
  2. In your development environment, set the working directory to this folder as well. (In Microsoft Visual C++®, this setting is on the Debug page of the Project Settings dialog box.)
  3. Run the program and, on the File menu, click Start Install. DirectSetup performs a simulated installation of DirectX (see Programming Notes below) and advises you of its progress in a modeless dialog box. You can use the Options menu to change the level of messages shown. However, if you are performing only a simulated installation, you will never see problem or update messages.
  4. On the File menu, click GET Version. The program shows the version and revision number of DirectX currently installed on the system.

Programming Notes

By default, the program passes DSETUP_TESTINSTALL to the DirectXSetup function. This means that no files are copied and the registry is not modified. To perform a real installation, delete this flag from the call.

Dinstall employs a callback function to monitor the progress of installation and intercept messages. Depending on the user's preferred warning level, as tracked in g_fStatus, messages may be ignored or presented to the user in a modeless dialog box. If user input is required, the appropriate buttons are displayed and the GetReply function monitors the message queue until one of the buttons is pressed.

Although DirectX samples include Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

© 2002 Microsoft Corporation. All rights reserved.


DirectMusic

This section provides information about using Microsoft® DirectMusic® to capture and play sounds in applications written in C and C++.

Information is presented in the following sections:

  • What's New in DirectMusic. A guide to new features of DirectMusic in Microsoft DirectX® 9.0.
  • Introduction to DirectMusic. An overview of DirectMusic: its capabilities, basic concepts, and architecture, together with an introduction to dynamic soundtracks. This section focuses on principles rather than on the practical side of programming for DirectMusic.
  • Getting Started with DirectMusic. Information on setting up and debugging DirectMusic projects, and an overview of the programming steps involved in setting up a DirectMusic performance and playing a sound.
  • Using DirectMusic. A guide to using the DirectMusic application programming interface (API). You'll probably want to familiarize yourself with the table of contents for this section, and then refer to parts of it as you need specific information. It should be used in conjunction with the reference section.
  • Advanced Topics in DirectMusic. Information of interest mostly for developing specialized applications or applications that need highly optimized performance.
  • Related Software. Information about software distributed with the DirectX SDK that can be used in conjunction with DirectMusic.
  • DirectMusic C++ Samples. A guide to the sample applications in the SDK, to point you to the sample code you need. As well as showing how to implement basic functionality, each sample demonstrates one or more particular features of DirectMusic.
  • DirectMusic C++ Tutorials. Step-by-step guides to implementing basic DirectMusic functionality.
  • DirectMusic C/C++ Reference. Detailed information about all the API elements declared in the DirectMusic header files.


What's New in DirectMusic

The DirectMusic application programming interface (API) has not been significantly revised for DirectX 9.0. However, many performance enhancements have been made. The most significant of these is a new low-latency DirectSound sink, which enables DirectMusic to attain much quicker response when using audiopaths that play through the software synthesizer. This enhancement is of particular interest to sound designers and composers who want to take advantage of the rich DirectMusic feature set but who also require low latency for quick interactive response. For more information, see Reducing Latency.

Several new features have been added to content created in DirectMusic Producer. For example, streamed waves in wave tracks can now be looped for the easier creation of ambient sounds, and looping can be done in clock time so that looping waves are not affected by tempo changes. For more information, see What's New in This Release in the DirectMusic Producer Help.

A large library of DirectMusic styles has been added to the SDK, along with an application for auditioning them.

In addition, two new tools have been made available in the \bin\DXUtils\AppWizard folder of the SDK installation:

  • DMToolWizard.awx is a wizard for creating DirectMusic tools.
  • AEDMOWiz.awx is a wizard for creating effect DMOs.

See Also

  • Related Software.


Introduction to DirectMusic

This section provides a quick overview of the capabilities of DirectMusic and what you need to do to get started with the API. Information is presented in the following sections:

  • The Power of DirectMusic
  • Elements of a DirectMusic Application
  • Overview of Audio Data Flow
  • Introduction to Dynamic Musical Soundtracks


The Power of DirectMusic

DirectMusic does much more than simply play sounds. It provides a complete system for implementing a dynamic soundtrack that takes advantage of hardware acceleration, Downloadable Sounds (DLS), DirectX Media Objects (DMOs), and advanced 3-D positioning effects.

By using the DirectMusic interfaces in your application, you can do the following:

  • Load and play sounds from files or resources in MIDI, WAV, or DirectMusic Producer run-time format.
  • Play from multiple sources simultaneously.
  • Schedule the timing of musical events with high precision.
  • Send tempo changes, patch changes, and other MIDI events programmatically.
  • Use Downloadable Sounds. By using DLS, an application can be sure that message-based music sounds the same on all computers. An application can also play an unlimited variety of instruments and even produce unique sounds for individual notes and velocities.
  • Locate sounds in a 3-D environment.
  • Easily apply pitch changes, reverberation, and other effects.
  • Use more than 16 MIDI channels. DirectMusic makes it possible for any number of voices to be played simultaneously, up to the limits of the synthesizer.
  • Play segments on different audiopaths, so that effects or spatialization can be applied individually to each sound.
  • Capture MIDI data, or stream ("thru") it from one port to another.

If you use source files from DirectMusic Producer, you can do much more:

  • Control many more aspects of playback at run time; for example, by choosing a different set of musical variations or altering the chord progression.
  • Play music that varies subtly each time it repeats.
  • Play waveforms with variations.
  • Map performance channels to audiopaths, so that different parts within the same segment can have different effects.
  • Compose wholly new pieces of music at run time, not generated algorithmically but based on elements supplied by a human composer.
  • Dynamically compose transitions between existing pieces of music.
  • Cue transitions, motifs, and sound effects to occur at specified rhythmic points in the performance.

These capabilities are the ones most often used by mainstream applications. DirectMusic is designed to be used easily for the basic tasks, but it also allows low-level access to those who need it. It is also extensible. Specialized applications can implement new objects at virtually every stage on the audiopath, such as the following:

  • 5Loaders to parse data in new or proprietary formats.
  • Tracks containing any kind of sequenced data.
  • Tools to process messages; for example, to intercept notes and apply transpositions, or to display lyrics embedded in a segment file.
  • Custom sequencer.
  • Custom synthesizer.
  • Effects filters.

DirectMusic delivers full functionality on Microsoft Windows® 98 and Microsoft Windows 2000. Support for hardware synthesizers is available only on Windows 98 Second Edition, Windows 2000, and later operating systems. The default Microsoft software synthesizer is always available.

Although DirectMusic loads and plays WAV files, applications that need highly optimized performance or low-level control over sound buffers can still use the DirectSound API. For a comparison of the two APIs, see DirectSound and DirectMusic.


Elements of a DirectMusic Application

This section is an introduction to some of the key concepts and code objects of DirectMusic. Although some interfaces are introduced, this section does not get into the details of using the API. For practical information on writing DirectMusic applications, see Using DirectMusic or the specific topics listed under See Also at the end of each topic.

The following topics are discussed:

  • Loader
  • Segments and Segment States
  • Performance
  • Messages
  • Performance Channels
  • Downloadable Sounds
  • Instruments and Downloading
  • Audiopaths and Buffers
  • Audio Scripts


Loader

The loader, represented by the IDirectMusicLoader8 interface, is an object that gets other objects. It is generally one of the first objects created in a DirectMusic application. The loader is used to load all audio content, including DirectMusic segment files, DLS collections, MIDI files, and WAV files. It can also load data stored in resources or application memory.

Any object that encapsulates data from a file or resource supports the IDirectMusicObject8 interface. The loader gets this interface and then uses it to initiate the process of streaming the data into an object in your application. Data objects parse themselves through their implementations of IPersistStream, and the entire loading process is carried out automatically. All you need to do is pass a description of the object to the loader, along with a request for the desired interface, such as IDirectMusicSegment8.

See Also

  • Loading Audio Data


Segments and Segment States

Segments are objects encapsulating sequenced sound data. The data might be a MIDI sequence, a waveform, a collection of information originating in a segment file from DirectMusic Producer, or a piece of music composed at run time from different components. In general, a segment is a piece of music or other sound that is played as a unit.

A segment can be played as a primary segment or secondary segment. Only one primary segment can be played at a time. Secondary segments are typically short musical motifs or sound effects played over the primary segment.

Segments originating as MIDI or WAV files sound the same each time they are played, unless the application performs some special processing on them. A segment authored in DirectMusic Producer, on the other hand, can contain different musical patterns and other information that allows variation each time the segment is played.

Segments can combine different kinds of data such as waveforms, patterns, chord changes, band changes, and tempo changes. Each type of data is encapsulated in a track object. Applications written in C++ can access individual tracks, but most do not need to. Segments can also contain information about the audiopath on which they should be played, including special effects.

DirectMusic Producer segments can also contain references to other loadable musical components. For example, it is possible to obtain a band object from a segment authored with that band.

Each time a segment is played, a segment state object is created. The application can use this object to get information about the state of playback and the audiopath for that instance of the playing segment.

See Also

  • Using Segments


Performance

The performance object manages the flow of data from the source to the synthesizer. Typically an application has only a single performance.

The performance handles timing, the mapping of data channels to audiopaths, the routing of messages, tool management, notifications, and other important tasks.

See Also

  • Creating the Performance


Messages

Audio data flows through the performance in the form of messages. Performance messages are similar to MIDI messages but contain more information and a greater variety of information. A message could contain information about a musical note, a waveform, or a controller change. It might even contain text for a display of lyrics.

Most applications don't deal directly with messages, which are generated by tracks when a segment is playing. However, it is possible for an application to insert messages into the performance. It is also possible to intercept messages by using plug-in components called tools.

Messages are also used for notifications. Applications can request that an event be signaled whenever certain points in the performance are reached—for example, on every beat of the music. Information about the event is contained in a performance message.

See Also

  • Notification and Event Handling
  • Using DirectMusic Messages


Performance Channels

Every playing sound consists of one or more parts. A part might be a MIDI channel, a part in a DirectMusic Producer segment, or a waveform. Often a part corresponds to a single musical instrument.

A performance channel is the route between a part and an audiopath. Every message that contains information about a part also specifies the part's performance channel, so that it can be routed correctly.

Performance channels are similar to MIDI channels, but whereas traditional MIDI playback is limited to 16 channels, the number of performance channels is virtually unlimited.

Note The array of performance channels in the DirectMusic API is zero-based, but in DirectMusic Producer it is one-based. Performance channel 1 in DirectMusic Producer is performance channel 0 in the API.

See Also

  • Using Bands


Downloadable Sounds

In the past, most computer audio has been produced in one of two fundamentally different ways, each with its advantages and disadvantages:

  • Waveforms are reproduced from digital samples, typically stored in a file or, in the case of Red Book audio, on a standard CD track. Digital samples can reproduce any sound, and the output is very similar on all sound cards. However, they require large amounts of storage and resources for streaming.
  • Musical instrument sounds are synthesized, usually in hardware, in response to messages, typically from a MIDI file. MIDI files are compact and require few streaming resources, but the output is limited to the number of instruments available in the General MIDI set and in the synthesizer, and may sound very different on different systems.

One way to combine the advantages of digital sampling with the compactness and flexibility of MIDI is wave-table synthesis, which is the synthesis of instrument sounds from digital samples. These samples are obtained from recordings of real instruments and stored on the hardware. The samples are looped and modulated to produce sounds of any length at different pitches and volumes.

Wave-table synthesis produces more realistic timbres than algorithmic FM synthesis but is still limited to a fixed set of instruments. Also, a particular instrument might sound different on different pieces of hardware, depending on the manufacturer's implementation of that instrument.

The Downloadable Sounds (DLS) standard, published by the MIDI Manufacturers Association, is a way of enabling wave-table synthesis to be based on samples provided at run time rather than hard-wired into the system. The data describing an instrument is downloaded to the synthesizer, and then the instrument can be played like any other MIDI instrument. Because DLS data can be distributed as part of an application, developers can be sure that their soundtracks will be delivered uniformly on all systems. Moreover, developers are not limited in their choice of instruments.

A DLS instrument is created from one or more digital samples, typically representing single pitches, which are then modulated by the synthesizer to create other pitches. Multiple samples are used to make the instrument sound realistic over a wide range of pitches. When a DLS instrument is downloaded, each sample is assigned to a certain range of pitches, called a region.

DLS Level 2 allows every note to occupy its own region. Moreover, the timbre for each region can be made up of multiple samples, called layers, and different layers can be triggered depending on the velocity of the note. A single instrument can thus be used to produce thousands of different sounds.

In addition, samples can be given an articulation, which defines characteristics that make the sound more like that produced by a real instrument. Articulation includes envelopes, or shapes, for the volume and pitch of the sound and a low-frequency oscillator (LFO) to provide vibrato and tremolo.

Samples can be loopable or single-shot. A loopable sample plays repeatedly for the duration of the note. A single-shot sample plays only once.

DLS data is stored in instrument collections. Individual instruments are assigned patch numbers and respond to MIDI messages just like traditional MIDI instruments. However, a DLS instrument does not have to belong to the General MIDI set. Any sound, even a fragment of speech or a fully composed measure of music, can be associated with a DLS instrument.

For more information on DLS collections and how instruments are created, see the documentation for DirectMusic Producer. To learn more about the DLS standard, consult the document "Downloadable Sounds Level 2," available from the MIDI Manufacturers Association.

By default, DirectMusic uses the Microsoft software synthesizer, which supports DLS Level 2.

Note The DLS Level 1 synthesizer used with the DirectX 7 interfaces contains reverberation capabilities, which are on by default. The Waves TrueVerb reverberation technology is licensed to Microsoft Corporation as the SimpleVerb implementation.

The DLS Level 2 synthesizer used with later interfaces does not contain built-in reverberation capabilities. Reverberation is instead implemented as a DirectX Media Object. Waves MaxxVerb is licensed to Microsoft Corporation for this purpose.

See Also

  • Using Bands


Instruments and Downloading

To play an instrument, the synthesizer needs information about how the instrument should sound. This information, consisting of waveform samples and articulation data, is stored in DLS collections. Instrument data is made available to the synthesizer by being downloaded.

By default, the Microsoft software synthesizer takes its DLS data from the Roland GM/GS collection. The default collection contains DLS data for the 128 instruments defined by the General MIDI standard. Custom collections can include instruments of any kind. The waveform samples for an instrument do not have to be based on a musical instrument but can be any recorded sound such as a sound effect, a fragment of speech, or even a fully formed measure of music.

Most applications do not need to access collections directly, as the necessary data is either contained in the default collection or referenced by a band object associated with a segment. A band is a set of instruments and settings mapped to performance channels. Several techniques are available for ensuring that band instruments are downloaded before use.

Note The Roland GM/GS Sound Set cannot be modified, due to legal restrictions.

WAV files and resources also have to be downloaded to the synthesizer before they can be played.

A band is a collection of performance channel settings that determine how parts in a sound file are played. For each channel, a band includes an instrument assignment as well as settings for volume, pan, and transposition. Every part in a performance is mapped to a performance channel, and each part plays with the instrument settings applied to its channel by the band.

Although a band can be thought of as a set of instruments, it is not the same as a DLS collection. A DLS collection is a set of instruments that can be downloaded to the synthesizer and thus made available to any application. The instruments themselves contain no information about assignment to performance channels, volume, pan, or transposition. This data must be supplied by bands for the channels used by a performance.

Note When bands are downloaded to the synthesizer, it is really the DLS instruments referenced by the band that are being downloaded.

Bands can be saved as separate files or included in styles or segments.

See Also

  • Using Bands


Audiopaths and Buffers

Each DirectMusic segment plays on an audiopath that controls the flow of sounds from the performance to the synthesizer, then through DirectSound buffers where effects can be applied, and finally into the primary buffer, where the final output is mixed.

Note The buffers referred to here are used for streaming and processing PCM data after it has left the synthesizer, and these buffers support the IDirectSoundBuffer8 interface. Another kind of buffer, represented by the IDirectMusicBuffer8 interface, is used for sequencing message data to the synthesizer. Most applications do not need access to the second kind of buffer, which is managed by the DirectMusic performance.

Applications can create standard audiopaths and then play segments on them. For example, an application could create one audiopath for playing MIDI files to a buffer with musical reverb and another for playing WAV files to a buffer with 3-D control.

More sophisticated audiopath configurations can be authored into a segment in DirectMusic Producer. For example, a nonstandard configuration might direct parts in a segment through different DirectSound buffers to apply different effects to them.

An audiopath can be seen as a chain of objects through which data is streamed. An application can gain access to any of these objects. For example, you might retrieve a buffer object to set 3-D properties of a sound source, or an effect DMO to change the parameters of the effect.

See Also

  • Using Audiopaths


Audio Scripts

An audio script is a file containing variables and routines that can be accessed from within an application. Scripts can be written using any Microsoft ActiveX® Scripting language, but DirectMusic Producer also enables scripting in a special language called AudioVBScript. The advantage of using AudioVBScript is that it requires a very small run-time library, which is one of the DirectMusic system components. AudioVBScript is a subset of Microsoft Visual Basic® Scripting Edition.

Note Audio scripts are not designed to be used on Web pages.

Scripts implement some of the key DirectMusic objects and can perform basic functions such as the following:

  • Creating audiopaths
  • Setting audiopath volumes
  • Setting global parameters for the performance
  • Loading, playing, and stopping segments
  • Downloading bands

DirectMusic scripts make it easier for application developers and sound designers to coordinate their efforts. Scripts give sound designers greater and more immediate control over the soundtrack. The basic functionality of loading and playing sounds is performed by the script. The application contains generalized code that calls into the script.

The following scenario is one in which scripting might be helpful. It supposes that the sound effects for a game are stored as individual WAV files. The game uses these sounds for events such as weapons firing and monsters grunting.

Using conventional programming techniques, the developers load the individual sounds by file name and play them as secondary segments at appropriate times in the game. But now the sound designers want to make some changes. They decide, for example, that the boss monster should have a different grunt than normal monsters. The sound designers create the necessary files and hand them off to the developers, who implement the changes in code. Considerable time may pass before the sound designers are able to get a newly compiled version of the game and test it.

Imagine the same scenario using an audio script. Rather than hard-coding the actual sounds into the application, the developers might write code like the following to play a grunt. Assume that that szGrunter has been set to a string constant such as "Player", "Boss", or "NormalMonster", and that pdmScript is an interface to the script object:

pdmScript->SetVariableVariant("Grunter", szGrunter, NULL);
pdmScript->CallRoutine("PlayGrunt", NULL);

This fragment of code sets the value of the Grunter variable in the script and calls the PlayGrunt script routine. The script author, who is probably a member of the sound design team, decides what the routine does. For example, the routine might test the value of Grunter before deciding what sound to play.

To change the response to the game situation, all that is required is an alteration in the text of the script, and the new routine can be tested immediately in the existing application.

The scripting API is documented in the DirectMusic Producer Help file.

See Also

  • Using Audio Scripts


Overview of Audio Data Flow

Typically, a DirectMusic application obtains sounds from one or more of the following sources:

  • MIDI files
  • WAV files
  • Segment files authored in DirectMusic Producer or a similar application
  • Component files authored in an application such as DirectMusic Producer and turned into a complete composition at run time by the DirectMusic composer object

Note Any of these data sources can be stored in the application as a resource rather than in a separate file.

Data from these sources is encapsulated in segment objects. Each segment object represents data from a single source. At any moment in a performance, one primary segment and any number of secondary segments can be playing. Source files can be mixed; for example, a secondary segment based on a WAV file can be played along with a primary segment based on an authored segment file.

A segment comprises one or more tracks, each containing timed data of a particular kind; for example, notes or tempo changes. Most tracks generate time-stamped messages when the segment is played by the performance. Other kinds of tracks supply data only when queried by the performance.

The performance first dispatches the messages to any application-defined tools. A tool can modify a message and pass it on, delete it, or send a new message. Tools are arranged in linear sets called toolgraphs. A message might pass through any or all of the following toolgraphs, in the order given:

  • Segment toolgraph. Processes messages from a single segment.
  • Audiopath toolgraph. Processes messages on a single audiopath.
  • Performance toolgraph. Processes all messages in the performance.

Finally, the messages are delivered to the output tool, which converts the data to MIDI format before passing it to the synthesizer. Channel-specific MIDI messages are directed to the appropriate channel group on the synthesizer. The synthesizer creates waveforms and streams them to a device called a sink, which manages the distribution of data through buses to DirectSound buffers.

There are three kinds of DirectSound buffers:

  • Sink-in buffers are DirectSound secondary buffers into which the sink streams data. These buffers enable the application to control pan, volume, 3-D location, and other properties. They can also pass their data through effects modules to add effects such as reverberation and echo. The resulting waveform is passed either directly to the primary buffer or to one or more mix-in buffers.
  • Mix-in buffers receive data from other buffers, apply effects, and mix the resulting waveforms. These buffers can be used to apply global effects. An effect achieved by directing data to a mix-in buffer is called a send. Mix-in buffers can be created only by using audiopath configurations authored in DirectMusic Producer.
  • The primary buffer performs the final mixing on all data and passes it to the rendering device.

Note Applications are not responsible for managing secondary buffers that are part of a DirectMusic performance. Although an application can obtain a buffer object for the purpose of adding effects and changing properties, it cannot lock the buffer, write to it, start it, or stop it by using the IDirectSoundBuffer8 interface.

The following diagram is a simplified view of the flow of data from files to the speakers. A single segment is shown, though multiple segments can play at the same time. The segment gets its data from only one of the four possible sources shown: a WAV file, a MIDI file, a segment file authored in DirectMusic Producer, or component files combined by the composer object. In all cases, data can come from a resource rather than a file.

For a closer look at the flow of messages through the performance, see Using DirectMusic Messages.

For information on how to implement the process shown in the illustration, see Loading Audio Data and Playing Sounds.


Introduction to Dynamic Musical Soundtracks

If you want to take full advantage of DirectMusic, you won't play just MIDI and WAV files. You'll take elements authored in DirectMusic Producer and use them to create performances that can be varied or manipulated in countless ways.

Note Throughout this documentation, the human composer of musical elements is referred to as the author, to avoid confusion with the composer object of DirectMusic. Similarly, musical elements are said to be authored rather than composed.

The following brief introduction to the elements of a dynamic soundtrack is meant to give the application developer an understanding of the material being used in the performance. For a more detailed view, see the Help for DirectMusic Producer. For information on how to incorporate these elements in an application, see Using Compositional Elements.

The following topics are covered:

  • Styles
  • Chordmaps
  • Style-based Segments
  • Templates
  • How Music Varies During Playback
  • Music Values and MIDI Notes


Styles

A style is a collection of musical patterns that can be used to create a dynamic score. It also contains a time signature and a tempo, and can contain one or more bands.

A pattern is a musical figure, one or more measures long, consisting of a basic sequence of notes for each instrument, or part. These notes are not defined as fixed pitches; they are described according to the role they play in the chord structure. The notes are mapped to MIDI values when they are played, after the current key, chord, and play mode have been taken into account.

A motif is a special type of pattern designed to be played dynamically over the basic score. Motifs are always played explicitly by the application. Motifs are often used in interactive applications to mark an event.

Each pattern can have up to 32 variations. At run time, variations are chosen by the style playback mechanism. However, the author can specify that a variation must never be chosen when a certain chord is being played.

The author also assigns a groove range to the pattern, specifying the groove levels at which the pattern can be played.

Any pattern (other than a motif) can be designated as an embellishment. There are four standard embellishment types: intro, fill, break, and end. In addition, DirectMusic Producer enables authors to establish up to 100 custom embellishment types. A pattern can be assigned to one or more of these types. When a style-based segment is played and a certain type of embellishment is specified at some point in the segment, only patterns of that type are candidates for playback.

See Also

  • DirectMusic Style Library
  • Style-based Segments


Chordmaps

Much modern music, especially music in the popular, rock, folk, and jazz idioms, is based on the concept of chord progression. All the notes played within a given span of time are associated with a certain chord, and the music moves harmoniously from one chord to another.

The notes within a pattern authored for DirectMusic are derived from or intended to harmonize with a single chord. At run time, however, the pattern is transposed according to the chord progression; that is, each time the underlying chord changes, DirectMusic modulates the pitch of the notes accordingly.

A chordmap is a collection of chords that provides multiple potential chord progressions to a musical piece. Chord progressions are generated from a chordmap and inserted into the chord track of a segment, either at design time or at run time.

By using chordmaps, the author of the music can create multiple segments from a common set of chords. Chordmaps can also be used by the application at run time to create new segments or to build new chord progressions in existing segments.

Certain important chords in a chordmap are designated as signposts. These are chords that must be played at certain points. The music is always moving from one signpost to the next. Between the signposts, however, the chord progression can follow various routes from one chord to another, as mapped out by the author.

A chord in the chordmap can actually consist of several different chords, referred to as subchords. In order to achieve polytonality by playing different inversions of the same chord, the author can assign different parts to different subchords. Each subchord is valid for one or more levels, and these are matched up with levels assigned to parts in the style.

See Also

  • Using Chordmaps


Style-based Segments

A style-based segment is a largely prebuilt piece of music that the author constructs from the following elements:

  • Style. A style consists of general information about the music (such as time signature and tempo), as well as patterns.
  • Chord progression. This might be derived automatically by the authoring tool from a chordmap (by choosing a path through the chord chart), or entered manually by the author.
  • Command track. This track, known as the groove track in DirectMusic Producer, is a series of commands for selecting appropriate patterns at set times. A characteristic of the patterns in styles is that they can be designated as embellishments (intro, fill, break, and end) and can also be assigned a certain groove range by the author. The command track of the segment might instruct the style playback engine to select an intro pattern and play it for the first measure, then play only patterns with a groove level of 25 for the next four measures, then play a break, and so on.
  • Band. The author can assign instruments and performance channels to all the parts in the various patterns.

See Also

  • Chordmaps
  • Styles


Templates

A template is a segment that contains a signpost track and, optionally, a command track. The signpost track can be used to create a new chord progression, either for the segment that contains the track or for another segment that does not have a signpost track. The command track supplies groove levels and embellishments. You can use templates at run time to compose new material.

The signpost track contains a sequence of signpost markers, which mark the beginning and end of regions in which variations in the chord progression are possible. Each signpost marker is designated as valid for a particular group of signpost chords in a chordmap. The author of the content is responsible for assigning signpost markers and signpost chords to the appropriate groups.

DirectMusic composes a segment by applying the signpost track to a particular style and chordmap. Each time the composer encounters a pair of signpost markers along the time line in the template, it searches the chordmap for a pair of signpost chords that belong to that group. If it finds a pair and the interval between them fits into the time available, it follows the chord progression between those two signpost chords, as defined in the chordmap. If it is unable to find a path that works, or if there is no end signpost marker, the engine plays any chord from the group of the beginning signpost marker.

For information on composing segments from templates in an application, see Using Templates.


How Music Varies During Playback

As DirectMusic plays a style-based segment, changes are made to the basic harmony and rhythm so that the performance does not sound static. Changes are partly scripted and partly random.

  • Choice of pattern. A typical style contains multiple patterns, which are selected in response to commands from the command track. For example, if the command track calls for a break embellishment to be played, the style playback engine selects a break pattern that is compatible with the current groove level. (The author specifies which groove levels are appropriate for each pattern.) If there is more than one suitable pattern, one is chosen according to rules embedded in the segment by the author. The choice might be completely or partly random, or patterns might be selected in a certain sequence.
  • Variations within a pattern. Any part within a pattern can have multiple variations. Variations can play in an order specified by the author; otherwise the style playback engine makes a random choice of variations on each repetition of the pattern.
  • Groove level. The groove level of the segment determines which of the patterns in the style can be selected for playback. The current level is set by the command track, which is normally authored into a segment. The groove level of a segment can also be changed programmatically, and a modifier can be applied to all segments by setting the master groove level for the performance.
  • Transposition. As the segment plays, changes are made to the underlying chord according to the progression in the chord track. The notes in the current pattern are automatically transposed to harmonize with the new chord.
  • Variations in timing. The playback engine can introduce small random changes in the start and stop times of individual notes. The degree of randomness is set by the author of the content.
  • Band. The choice of instruments and instrument settings (volume, pan, and transposition) can be changed as the segment is playing, either by the band track within an authored segment or dynamically by the application.

In many cases, applications exert control over the music by playing different segments rather than by manipulating existing segments. For example, to have the music reflect a change in the intensity of a game, you can simply change to a new segment authored for that intensity level. You can achieve a similar effect with a single style-based segment by having the author create patterns with different groove ranges, and then changing the groove level in response to game events.


Music Values and MIDI Notes

Notes in a pattern in a DirectMusic style or pattern track are not notes with a fixed MIDI value. Rather, they are music values that become MIDI notes only when they are transposed to the current chord according to the current play mode and subchord level.

A music value is a representation of the note's intended role. For example, a music value can specify that a note is intended to be played as the second position in the chord, up one in the scale. When that music value is applied to a particular chord, it is converted to the appropriate MIDI note—the one in the second position in the chord, up one in the scale.

The play mode determines how to interpret the note against the chord. For example, if the mode is DMUS_PLAYMODE_NORMALCHORD, the note is interpreted against the intervals of the chord and scale, based on the root of the chord. If the mode is DMUS_PLAYMODE_FIXEDTOKEY, the note is interpreted as a linear value.

To allow for complex harmonies with multiple parallel chord progressions, DirectMusic chords can be made up of multiple subchords. The subchord level is a value in the range from 0 through 31 that determines which subchords of a chord can be used in establishing the music value. Each subchord is valid for one or more levels, as defined by the author of the music. DirectMusic Producer supports up to four subchords per chord.

When a segment is played, each note is encapsulated in a message structure that specifies the original music value and the final MIDI note along with the play mode and subchord level that were used in transposition. Most applications don't deal directly with note messages, but tools can intercept them and alter the notes. For example, a tool could intercept a note that was transposed in a certain play mode, change the play mode, and calculate a new MIDI value before passing on the message.

See Also

  • DMUS_NOTE_PMSG
  • DMUS_PLAYMODE_FLAGS
  • DMUS_CHORD_PARAM
  • DMUS_CHORD_KEY
  • DMUS_SUBCHORD
  • IDirectMusicPerformance8::MIDIToMusic
  • IDirectMusicPerformance8::MusicToMIDI
  • DirectMusic Tools


Getting Started with DirectMusic

This section gives information on setting up and debugging DirectMusic projects, as well as a brief overview of the programming steps required to set up a performance and play sounds.

More information on getting started is included in the following topics:

  • Building DirectMusic Projects
  • Debugging DirectMusic Projects
  • First Steps in DirectMusic Programming


Building DirectMusic Projects

Projects need to include the Dmusici.h header file, which contains declarations for the DirectMusic performance layer. Including this file will bring in three other essential headers:

  • Dmusicc.h: declarations for the core layer of DirectMusic.
  • Dmerr.h: DirectMusic return values.
  • Dsound.h: the DirectSound API.

The following additional headers are not needed by most applications:

  • Dmusicf.h: file structures and definitions. This header is needed only by applications such as music-authoring tools that work directly with files and don't rely solely on the loaders built into DirectMusic.
  • Dmusics.h: declarations for the IDirectMusicSynth and IDirectMusicSynthSink interfaces, which are used for creating synthesizers and synthesizer sinks.
  • Dmusbuff.h: declaration of the DMUS_EVENTHEADER structure, used only by applications that are directly sequencing events to the synthesizer.
  • Dmksctrl.h: declarations for the IKsControl interface used for port property sets. You do not need this file if you have included Ksproxy.h and Ks.h.
  • Dmplugin.h: declarations for the IDirectMusicTool8 and IDirectMusicTrack8 interfaces, which are implemented by add-ons for advanced applications that need specialized message-processing tools and track types. Most applications do not use this part of the DirectMusic API.

You must also ensure that your application has access to the GUIDs used by DirectMusic. Define INITGUID before all other preprocessor directives, or link to Dxguid.lib.

DirectMusic uses the multithreading capabilities of the Windows 32-bit operating system. Multithreading allows DirectX to generate, process, and synthesize music in the background while your application is accomplishing other tasks. You should develop your project with multithreading in mind. If nothing else, be sure to link with the appropriate libraries.


Debugging DirectMusic Projects

The DirectMusic dynamic-link libraries (DLLs) installed with the debug version of the DirectX software development kit (SDK) generate information in the debug output window as the application is running. These DLLs are available if you installed the debug version of the DirectX SDK. They can be dynamically selected through the DirectX property sheet in Control Panel by choosing Use Debug Version of DirectMusic.

You can control the volume of information that goes to your debug output window by changing values in Win.ini. The output for each DirectMusic DLL can be set separately, as in the following example:

[Debug]
DMBAND=1
DMCOMPOS=1
DMIME=1
DMLOADER=0
DMUSIC=1
DMSTYLE=3
DMSYNTH=5

Each value can be in the range from 0 through 5, where 0 produces no debugging information and 5 the most detailed information. For most purposes it is unnecessary to set the level higher than 2; output at higher levels does not pertain to errors or warnings but is purely informational.

If there is no entry in Win.ini, the debug output is at level 0. You can focus on problems in a particular DLL by setting lower values for the other components.

You can also set the debug level within the range from 0 to 5 by using the Debug Output Level sliders on the DirectMusic page of the DirectX property sheet in Control Panel. The slider sets the same value for all DLLs.


First Steps in DirectMusic Programming

This topic gives an overview of the basic steps required for setting up a DirectMusic performance and playing a file. For details, see Using DirectMusic. For sample code, see Tutorial 1: Playing Audio Files.

To produce a sound, an application needs to do the following:

  1. Initialize COM. There are no helper functions for creating DirectMusic objects. To initialize COM, you must call CoInitializeEx.
  2. Create and initialize the performance. Most applications have a single performance object. Create the performance by calling CoCreateInstance, obtaining the IDirectMusicPerformance8 interface. Then call IDirectMusicPerformance8::InitAudio. This method can set up a default audiopath.
  3. Create the loader. Using CoCreateInstance, create a loader object and obtain an IDirectMusicLoader8 interface. You need to do this only once, and normally you should keep the same loader object for the life of the application.
  4. Load a segment. Call IDirectMusicLoader8::SetSearchDirectory so the loader can find the data files. Then call IDirectMusicLoader8::GetObject to load a segment from a file or resource and obtain its IDirectMusicSegment8 interface.
  5. Download the band. Download DLS instrument data to the synthesizer so that notes can be synthesized. WAV files must also be downloaded. The simplest way to download all instruments and waves is by calling IDirectMusicSegment8::Download.
  6. Play the segment. Pass the segment pointer to IDirectMusicPerformance8::PlaySegmentEx.


Using DirectMusic

This section is a guide to using the Microsoft® DirectMusic® application programming interface (API) in application development.

Information is presented in the following topics:

  • Loading Audio Data
  • Playing Sounds
  • Performance Parameters
  • Using Audiopaths
  • Using 3-D Sound in DirectMusic
  • Using Effects in DirectMusic
  • Buffer Chains
  • Using Compositional Elements
  • Using Audio Scripts
  • Capturing MIDI

For a more general overview, see the following topics:

  • Elements of a DirectMusic Application
  • First Steps in DirectMusic Programming
  • Overview of Audio Data Flow

For information on advanced features used mainly by specialized applications, see Advanced Topics in DirectMusic.


Loading Audio Data

Many DirectMusic objects have to be loaded from a file or resource before they can be incorporated into a performance. The IDirectMusicLoader8 interface is used to manage the enumeration and loading of such objects, as well as to cache them so that they are not loaded more than once.

Note Do not load data from untrusted sources. Loading DirectMusic data files causes objects to be constructed, with the possibility that excessive demand on resources will lead to degradation of performance or system failure.

An application should have only one instance of the loader in existence at a time. You should create a single global loader object and not free it until there is no more loading to be done. This strategy ensures that objects are found and cached efficiently.

When objects are loaded from a memory location or a stream, the application should not touch the data until the loader is released. Because of caching and other internal mechanisms, the loader might try to access the data at a later time. To load new data, always allocate a new buffer or create a new stream.

The DirectMusic implementation of IStream streams the data from the source. The parsing of the data is handled by the various objects themselves through their implementations of IPersistStream. As long as you are dealing only with standard DirectMusic data, you don't have to use these interfaces directly.

Loading of objects referenced by other objects is handled transparently. For example, suppose a segment being loaded from a DirectMusic Producer file contains a reference to a WAV sound in another file. When the segment's implementation of IPersistStream::Load finds the reference, it obtains the IDirectMusicGetLoader8 interface from the stream object. Using this interface, it obtains a pointer to the loader object. Then it calls IDirectMusicLoader8::GetObject to load the WAV sound.

More information on using the loader is contained in the following topics:

  • Setting the Loader's Search Directory
  • Scanning a Directory for Objects
  • Enumerating Objects
  • Loading an Object from a File
  • Loading an Object from a Resource or Memory Address
  • Containers
  • Getting Object Descriptors
  • Cache Management
  • Garbage Collection
  • Setting Objects

See Also

  • Custom Loading


Setting the Loader's Search Directory

By default, the loader looks for objects in the current directory unless a full path is specified in the wszFileName member of the DMUS_OBJECTDESC structure describing the object being sought. By using the IDirectMusicLoader8::SetSearchDirectory method, you can set a different default path for the IDirectMusicLoader8::GetObject and IDirectMusicLoader8::EnumObject methods. This default path can apply to all objects, or only to objects of a certain class.

The behavior of IDirectMusicLoader8::LoadObjectFromFile is somewhat different. See the Remarks for that method.

The following example function sets the search path for style files:

HRESULT mySetLoaderPath (IDirectMusicLoader8 *pILoader)
{
  return pILoader->SetSearchDirectory(
      CLSID_DirectMusicStyle,
      L"c:\\mymusic\\rock",
      FALSE);
}

After calling this function, the application can load a style by file name, without including the full path.


Scanning a Directory for Objects

The IDirectMusicLoader8::ScanDirectory method scans the current search directory for objects of a specified class. You can further narrow the search by providing a subclass and a file extension other than "*".

The method compiles a list of all matching files and uses the IDirectMusicObject8::ParseDescriptor method to extract the GUID and the name of the object. These identifiers are retained in an internal database so that the application can subsequently load objects by GUID or name rather than by file name. See Loading an Object from a File.

Note If you are working with DirectMusic Producer content, it is always a good idea to call ScanDirectory before loading any objects. Even though you may be loading objects explicitly by file name, those objects might contain references to other objects not identified by file name, and the loader will not be able to find these referenced objects if ScanDirectory has not been called on every directory in which the objects might reside.

If you include a pointer to a string in the pwszScanFileName parameter of the ScanDirectory method, the results of the scan are cached in a file by that name, to speed up subsequent scans. When a cache file is available, the method updates object information only for files whose time stamps or sizes have changed.

Note In the current version of DirectMusic, ScanDirectory does not use the cache file. However, implementing a cache file does no harm.

For an example, see Enumerating Objects.


Enumerating Objects

Use the IDirectMusicLoader8::EnumObject method to iterate through all objects of a specified class, or of all classes, that have previously been listed in the internal database through a call to IDirectMusicLoader8::ScanDirectory or calls to IDirectMusicLoader8::GetObject. A description of each object found is returned in a DMUS_OBJECTDESC structure.

Note To be sure of finding all objects, call ScanDirectory first. EnumObject works by checking the internal database of objects, not by parsing disk files.

The following example enumerates all listed style objects in the current search directory. The loop continues until there are no more objects of that class to enumerate.

void ListStyles(IDirectMusicLoader *pILoader)
{
  if (pILoader)
  {
    HRESULT hr = pILoader->SetSearchDirectory(
        CLSID_DirectMusicStyle,
        L"c:\\mymusic",
        TRUE);
    if (SUCCEEDED(hr))
    {
      hr = pILoader->ScanDirectory(
          CLSID_DirectMusicStyle,
          L"sty",*
          L"stylecache");
      if (hr == S_OK)  // Only if files were found.
      {
        DWORD dwIndex;
        DMUS_OBJECTDESC objDesc;
        objDesc.dwSize = sizeof(DMUS_OBJECTDESC);
        for (dwIndex = 0; ;dwIndex++)
        {
          if (S_OK ==(pILoader->EnumObject(
              CLSID_DirectMusicStyle,
              dwIndex, &objDesc)))
          {
             // Do something with information from objDesc.
            .
            .
            .
          }
          else break;
        }
      }
    }
  }
}

Notice that the example does not use the SUCCEEDED macro to test the result of the method call, because EnumObject returns a success code, S_FALSE, for an index number that is not valid.


Loading an Object from a File

To load an object, first obtain the IDirectMusicLoader8 interface, as in the following example:

IDirectMusicLoader8* g_pLoader;

CoInitializeEx(NULL, 0);
HRESULT hr = CoCreateInstance(
    CLSID_DirectMusicLoader,
    NULL,
    CLSCTX_INPROC,
    IID_IDirectMusicLoader8,
    (void**)&g_pLoader);

if (FAILED(hr))
{
  ErrorExit(hr);  // Add error-handling code.
}

You can then load an object from a file by using either IDirectMusicLoader8::LoadObjectFromFile or IDirectMusicLoader8::GetObject. The first of these methods is more convenient because it does not require you to describe the object by filling out a DMUS_OBJECTDESC structure.

The following example code loads four segments from a directory previously set by IDirectMusicLoader8::SetSearchDirectory:

IDirectMusicSegment8 * g_pSegments[4];

static WCHAR  wszNames[4][MAX_PATH] = {
    L"AudioPath1.sgt",
    L"AudioPath2.sgt",
    L"AudioPath3.wav",
    L"AudioPath4.sgt"
};

for (DWORD dwIndex = 0; dwIndex < 4; dwIndex++)
{
  hr = g_pLoader->LoadObjectFromFile(
      CLSID_DirectMusicSegment,
      IID_IDirectMusicSegment8,
      wszNames[dwIndex],
      (void**) &g_pSegments[dwIndex]);
  if (FAILED(hr))
  {
    ErrorExit(hr);  // Add error-handling code.
  }
}

The following example function uses IDirectMusicLoader8::GetObject to load a style object from a file. The first parameter receives a pointer to the style.

HRESULT LoadStyle(IDirectMusicStyle8 **ppStyle, IDirectMusicLoader8 *pLoader)
{
  if (pLoader)
  {
    DMUS_OBJECTDESC objDesc;

    // Start by initializing objDesc with the file name and
    // class GUID for the style object.

    wcsncpy(objDesc.wszFileName, L"c:\\mymusic\\polka.sty",
        sizeof(objDesc.wszName) - 1);
    objDesc.wszFileName[sizeof(objDesc.wszFileName) - 1] = 0;
    objDesc.guidClass = CLSID_DirectMusicStyle;
    objDesc.dwSize = sizeof (DMUS_OBJECTDESC);
    objDesc.dwValidData = DMUS_OBJ_CLASS |
        DMUS_OBJ_FILENAME |
        DMUS_OBJ_FULLPATH;

    return pLoader->GetObject(&objDesc, IID_IDirectMusicStyle8,
        (void **) ppStyle);
  }
  else return E_INVALIDARG;
}

The example identifies the file by a full path name and indicates this by setting the DMUS_OBJ_FULLPATH flag.

To identify the particular file object being sought, fill in at least one of wszName, guidObject, or wszFileName in the DMUS_OBJECTDESC structure, and set the corresponding flag or flags in the dwValidData member. If you identify the file by wszName or guidObject, but not by wszFileName, you must first call the IDirectMusicLoader8::ScanDirectory method to make the GUIDs and names in the current directory available. For more information, see Scanning a Directory for Objects.

See Also

  • Loading an Object from a Resource or Memory Address.


Loading an Object from a Resource or Memory Address

Objects stored as resources or at some other location in memory are loaded in much the same way as file objects. See Loading an Object from a File.

With memory objects, however, the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure are irrelevant. Instead, you must obtain a pointer to the block of memory occupied by the object, and its size, and put these in the pbMemData and llMemLength members respectively. You must also set the DMUS_OBJ_MEMORY flag in the dwFlags member.

After IDirectMusicLoader8::GetObject has been called on an object in memory, the address and size of the memory buffer are privately cached by the loader. If you then release the buffer, a subsequent memory allocation might use the same address, and when another object is loaded from that address, the cached memory size will be used, possibly resulting in an incorrect number of bytes being loaded. To prevent this from happening, after loading the first object call IDirectMusicLoader8::SetObject with the same DMUS_OBJECTDESC descriptor, but with NULL in pbMemData. For this to work, the object descriptor must contain a name or GUID when passed to both GetObject and SetObject.

Note It is usually best not to release or change the contents of memory from which an object has been loaded, because it is difficult to be sure that the loader will not need to access the data again. In most cases, you should not release or reuse memory until after the loader is released. Also, do not load objects from data passed on the stack.

The following function loads a MIDI file from a resource into a segment:

HRESULT LoadMidi(HMODULE hMod, WORD ResourceID,
                 IDirectMusicLoader8* pLoader, IDirectMusicSegment8** ppSeg)
{
  HRESULT      hr;
  DMUS_OBJECTDESC  objDesc;

  HRSRC hFound = FindResource(hMod, MAKEINTRESOURCE(ResourceID), RT_RCDATA);
  HGLOBAL hRes = LoadResource(hMod, hFound);
  if (NULL == hRes) return E_FAIL;

  objDesc.dwSize = sizeof(DMUS_OBJECTDESC);
  objDesc.guidClass = CLSID_DirectMusicSegment;
  objDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
  objDesc.pbMemData = (BYTE *) LockResource(hRes);
  objDesc.llMemLength = SizeofResource(hMod, hFound);

  if (pLoader && ppSeg)
  {
    hr = pLoader->GetObject(
        &objDesc, IID_IDirectMusicSegment8,
        (void**) ppSeg);
    return hr;
  }
  else return E_INVALIDARG;
}

Objects referenced by other objects must be loaded first. For example, if you load a segment that contains a reference to a style, the style must already be loaded in order for the segment to play correctly. Alternatively, you can call IDirectMusicLoader8::SetObject on the style so that the segment can find it.

See Also

  • Cache Management


Containers

Containers are objects representing files that contain various objects. A container file might hold all the data necessary for a performance, including segments, styles, and DLS collections. Container files are typically created in DirectMusic Producer. Containers can also exist within segment and script files.

You load a container like any other object, using IDirectMusicLoader8::GetObject. This method makes all objects in the container known to the loader, so that you can then use GetObject to retrieve them by name or GUID.

After you have obtained the IDirectMusicContainer8 interface, you can enumerate the objects in the container by using IDirectMusicContainer8::EnumObject.

The following example function loads a container, retrieves a segment from it by name, and returns an IDirectMusicSegment interface. For purposes of demonstration, the container object is created and released within the function; in practice, this should be done only once during the life of the application, to prevent duplication of objects.

HRESULT LoadSegmentFromContainer (
    IDirectMusicLoader8* pLoader,
    WCHAR* wszFileName,
    WCHAR* wszSegmentName,
    IDirectMusicSegment** ppSeg)

{
  DMUS_OBJECTDESC objDesc;
  IDirectMusicContainer8* pContainer = NULL;

// Load the container.

  HRESULT hr = pLoader->LoadObjectFromFile(
      CLSID_DirectMusicContainer,
      IID_IDirectMusicContainer8,
      wszFileName,
      (void**)&pContainer);
  if (FAILED(hr)) return hr;

// Describe the segment.

  ZeroMemory(&objDesc, sizeof(objDesc));
  objDesc.dwSize = sizeof(objDesc);
  objDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_NAME;
  objDesc.guidClass = CLSID_DirectMusicSegment;
  wcsncpy (objDesc.wszName, wszSegmentName,
      sizeof(objDesc.wszName) - 1);
  objDesc.wszName[sizeof(objDesc.wszName) - 1] = 0;

// Load the segment.

  hr = pLoader->GetObject(&objDesc, IID_IDirectMusicSegment,
      (void**) ppSeg);

// Release the container from the cache and destroy the object.

  if (pContainer)
  {
    IDirectMusicObject *pObject = NULL;
    pContainer->QueryInterface(IID_IDirectMusicObject,
        (void **)&pObject);
    if (pObject)
    {
      pLoader->ReleaseObject(pObject);
      pObject->Release();
    }
    pContainer->Release();
  }
  return hr;
}


Getting Object Descriptors

After you have loaded an object, you can use its IDirectMusicObject8 interface to retrieve information about it in a DMUS_OBJECTDESC structure.

The following example function uses the IDirectMusicObject8::GetDescriptor method to obtain information about the name of a style:

void GetStyleName(IDirectMusicStyle8* pStyle)
{
  IDirectMusicObject8 *pIObject;
  DMUS_OBJECTDESC objDesc;

  if (SUCCEEDED(pStyle->QueryInterface(IID_IDirectMusicObject8,
      (void **) &pIObject)))
  {
    if (SUCCEEDED(pIObject->GetDescriptor(&objDesc)))
    {
      if (objDesc.dwValidData & DMUS_OBJ_NAME)
      {
        // Do something with objDesc.wszName,
        // which now contains the name of the style.
      }
    }
    pIObject->Release();
  }
}


Cache Management

When an object is cached, the same instance of the object is always returned by the IDirectMusicLoader8::GetObject method.

The cache stores a pointer to the object. The memory for the object itself is managed by COM, and is not released until the reference count reaches zero. It is important to remember that clearing an object from the cache is not the same as releasing your application's COM reference to it.

Caching is used extensively in the file-loading process to resolve links to objects. For example, two segments could reference the same style. When the first segment loads, it calls the loader to get the style. The loader creates a style object, loads the data from disk, caches a pointer to the style object, and returns this pointer to the segment. If caching is enabled, when the second segment loads, it asks for the style, and the loader immediately returns the same pointer. Now both segments point to the same style. If caching is disabled, the second segment's request for the style causes a duplicate style object to be loaded from the file, at a cost in time and memory.

Here's another example. A band object relies on the loader to keep the General MIDI DLS collection cached. Every time a band has to download a GM instrument, it gets the collection from the loader. If caching for CLSID_DirectMusicCollection is disabled, every patch change in a MIDI file causes a separate copy of the entire GM collection to be created. This is obviously undesirable.

By default, caching is enabled for all object classes. You can disable caching for an object class, or for all objects, by using the IDirectMusicLoader8::EnableCache method. This method can also be used to re-enable caching for any or all object classes.

If you want to clear the cache without disabling future caching, use the IDirectMusicLoader8::ClearCache method. It's not necessary to call this method before terminating your application, because the cache is automatically cleared when the loader is released. ClearCache is only useful if the application soundtrack is changing completely, with all new instruments and source files.

Note Regardless of whether caching is enabled, the loader keeps a private cache of object descriptors. When you load an object from a stream, a reference to the IStream is cached with the descriptor, and if that object is subsequently reloaded, it will be loaded from the same stream. When you load an object from a memory location, the address and buffer size are cached, and if the address is subsequently reused for another object, the incorrect number of bytes might be loaded. To ensure that the private cache of object descriptors is cleared, you can do one of the following:

  • If caching is enabled, call ClearCache.
  • If caching is not enabled, either destroy the loader and create a new one, or call IDirectMusicLoader8::SetSearchDirectory with the fClear parameter set to TRUE.

To cache a single object when general caching is disabled, pass it to the IDirectMusicLoader8::CacheObject method.

You can remove an object from the cache, ensuring that it will be loaded again on the next call to GetObject, by using the IDirectMusicLoader8::ReleaseObject or IDirectMusicLoader8::ReleaseObjectByUnknown method. It is a good idea to call one of these methods before calling Release on an object, especially a segment. If you don't, a reference to the object remains in the cache, so the object continues to exist. As well as taking up memory, the object might retain certain state information. In the case of a segment, any instance that you load later will be taken from the cache, and the start point and loop points will be the same as they were when the previous instance was destroyed.

See Also

  • Garbage Collection
  • Loading an Object from a Resource or Memory Address.


Garbage Collection

Caching of loaded objects can lead to wasted memory when an application loads many objects, particularly objects that reference other objects.

When automatic caching is enabled, as it is by default, every object loaded by IDirectMusicLoader8::GetObject is cached, including objects that are loaded by reference. For example, if you call GetObject on a segment, and that segment contains a reference to a script, the script is loaded and cached as well.

When you call IDirectMusicLoader8::ReleaseObject or IDirectMusicLoader8::ReleaseObjectByUnknown, however, only the primary object that was loaded by GetObject is removed from the cache. Referenced objects are not released, even if they are not being used by other objects.

In order to clean up objects that are not in use, call IDirectMusicLoader8::CollectGarbage. This method releases all objects from the cache except objects directly loaded by GetObject and objects referenced by them. Objects only referenced by other objects that no longer exist are released. CollectGarbage clears an object from the cache by releasing the loader's COM reference to the object. If the object's reference count drops to zero as a result, the object destroys itself, thus making its memory available again.

In summary, to ensure that loaded objects do not remain in memory when no longer needed, you must do the following:

  • Call ReleaseObject or ReleaseObjectByUnknown on any object for which GetObject has been called.
  • Call CollectGarbage to release the loader's reference to any objects that were loaded indirectly.
  • Call Release on any pointers held by your application.

A complication arises when objects have circular references to one another. Suppose the script track of a segment contains a reference to a script object, and this script object contains a reference to the segment. You load the segment directly by calling GetObject, and the script is loaded indirectly. Then you release the segment from the cache by using ReleaseObject, and call Release on your application's reference to it. The segment continues to exist because there is still one COM reference to it, which is held by the script object. The script is now garbage, because it is not referenced by any other object in the cache. Without taking special measures, however, CollectGarbage could only release the loader's reference to the script; therefore its reference count would not drop to zero. The segment and script would continue to be referenced by one another, and although both were removed from the cache, they would both continue to exist in memory.

To avoid this problem, CollectGarbage calls an internal method on an object that forces the object to release its references to other objects. In the example above, it causes the script to release its reference to the segment. The segment's reference count drops to zero, and in the course of destroying itself, the segment releases its reference to the script, thus allowing the script to destroy itself when the loader releases its reference.

There is one more complication, however. Suppose the application has obtained an interface to the script that the loader knows nothing about, and the application neglects to call Release on this pointer. The script continues to exist, but it might not be able to behave as it should, because it no longer has a reference to the segment. Calling a method on the script could lead to a fatal error. To prevent this, CollectGarbage ensures that all methods of the script object return DMUS_S_GARBAGE_COLLECTED.

This scenario does not affect most applications. However, you should be aware that calling a method on an object that has been cleared from the cache by CollectGarbage might not yield the desired result.

In the following example function, assume that the loaded script contains a reference to a segment. After calling a routine in the script, the function removes the script object from the cache and then calls CollectGarbage, which releases the referenced segment. If the segment contains a circular reference to the script, this is released so that the script can be destroyed, in turn releasing the final reference to the segment and allowing the segment to be destroyed.

void CallWhistle(IDirectMusicLoader8* pLoader, IDirectMusicPerformance8* pPerformance)
{
  IDirectMusicScript8 *pScript;
  WCHAR wszScript[MAX_PATH] = L"soundfx.spt";

  pLoader->LoadObjectFromFile(CLSID_DirectMusicScript,
                              IID_IDirectMusicScript8,
                              wszScript, (void**)&pScript);
  pScript->Init(pPerformance, NULL);
  pScript->CallRoutine(L"Whistle", NULL);

  pLoader->ReleaseObjectByUnknown(pScript);
  pLoader->CollectGarbage();
  pScript->Release();
}

See Also

  • Cache Management


Setting Objects

Sometimes it is desirable to tell the loader where to get an object, without actually loading that object, so that the loader can retrieve it if the object is later referenced by other objects as they are being loaded. You might also want to give an object a new attribute so that the loader can find it by that attribute.

The IDirectMusicLoader8::SetObject method takes as a parameter a DMUS_OBJECTDESC structure that contains two key pieces of information:

  • A pointer to the data. This can be either a file path or a pointer to a block of memory. See Loading an Object from a File and Loading an Object from a Resource or Memory Address.
  • An identifier for the object when it is referenced later. This could be a GUID or a name. Later, the call to IDirectMusicLoader8::GetObject will find the stored object by using the same name or GUID. Note that you cannot change a GUID or name that already exists in the object.

On return, the DMUS_OBJECTDESC structure may contain additional information about the object gathered by the loader.

The following function assigns a name to an unnamed object (such as a MIDI file) in a resource:

HRESULT SetObjectFromResource(const GUID* guid, int ID,
    char* type, WCHAR* name, IDirectMusicLoader8* pLoader,
    HINSTANCE hInstance)
{
  HRSRC hResource = NULL;
  HGLOBAL hData = NULL;
  hResource = FindResource(hInstance, MAKEINTRESOURCE(ID), type);
  if (hResource != NULL)
  {
    hData = LoadResource(hInstance, hResource);
    if (hData != NULL)
    {
      DMUS_OBJECTDESC objDesc;
      if(pLoader && (hResource != NULL) && (hData != NULL))
      {
        ZeroMemory(&objDesc,sizeof(objDesc));
        objDesc.pbMemData = (BYTE*) LockResource(hData);
        objDesc.llMemLength = SizeofResource(hInstance, hResource);
        objDesc.guidClass = (*guid);
        objDesc.dwSize = sizeof(objDesc);
        objDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
        if (name)
        {
          wcsncpy(objDesc.wszName, name, sizeof(objDesc.wszName) - 1);
          objDesc.wszName[sizeof(objDesc.wszName) - 1] = 0;
          objDesc.dwValidData |= DMUS_OBJ_NAME;
        }
        return pLoader->SetObject(&objDesc);
      }
    }
  }
  return E_FAIL;
}

The example function could be used to assign a name to a MIDI file stored as a resource of type "MIDI", as in the following function call:

SetObjectFromResource(CLSID_DirectMusicSegment, 101,
    "MIDI", "canyon", g_pLoader, g_hInstance);

The object can now be loaded at any time by name.


Playing Sounds

This section describes basic techniques for playing sounds and coordinating the different elements of a performance.

The following topics are discussed:

  • Creating the Performance
  • Using Segments
  • Changing the Pitch of Waveforms
  • Using Bands
  • Timing
  • Notification and Event Handling
  • Troubleshooting Playback


Creating the Performance

The performance object is the overall manager of playback. Among the tasks it performs are the following:

  • Managing ports and audiopaths
  • Mapping channels to audiopaths
  • Playing and stopping segments
  • Dispatching messages
  • Managing tools and timing

Most applications have a single performance object, but it is possible to have more than one performance with different parameters, such as master tempo or volume.

The following example function creates a performance and returns a pointer to the IDirectMusicPerformance8 interface:

HRESULT GetPerformance(IDirectMusicPerformance8** ppPerf)
{
  return CoCreateInstance(CLSID_DirectMusicPerformance,
                NULL, CLSCTX_INPROC, IID_IDirectMusicPerformance8,
               (void**)ppPerf);
}

After the performance is created, it must be initialized. If your application is using audiopaths, you must call the IDirectMusicPerformance8::InitAudio method. Applications using the earlier channel-to-port mapping model must call IDirectMusicPerformance8::Init instead.

An important part of initialization is the creation of a DirectMusic object. You can pass an existing IDirectMusic8 interface pointer to IDirectMusicPerformance8::InitAudio, but in most cases it is more convenient to have InitAudio create the DirectMusic object. You can also choose whether to retrieve a pointer to the IDirectMusic8 interface, depending on how much control you need over ports and the master clock. Most applications don't need access to the methods of IDirectMusic8 and can pass NULL as the ppDirectMusic parameter of InitAudio.

InitAudio can also take an existing DirectSound device object. DirectSound manages the sound data after it leaves the synthesizer. In most cases you can let InitAudio create this object. You don't need an interface to it unless you intend to use DirectSound for other purposes such as playing waveforms directly into DirectSound secondary buffers rather than through the DirectMusic performance.

By passing a DMUS_AUDIOPARAMS structure to InitAudio, the application can request synthesizer capabilities or set a synthesizer other than the default one. Most applications don't have to do this.

The following example function initializes the performance without retrieving pointers to the DirectMusic and DirectSound objects. It creates a standard default audiopath with 16 performance channels and all available features on the port. The hWnd parameter is the application window handle.

BOOLEAN Init(IDirectMusicPerformance8* pPerf, HWND hWnd)
{
  if (FAILED(pPerf->InitAudio(NULL, NULL, hWnd,
      DMUS_APATH_SHARED_STEREOPLUSREVERB, 16,
      DMUS_AUDIOF_ALL, NULL)))
  {
    return FALSE;
  }
  else return TRUE;
}


Using Segments

Segments are the basic units of playable data in the DirectMusic performance. A segment is represented by an IDirectMusicSegment8 interface.

Each segment consists of one or more tracks, each represented by an IDirectMusicTrack8 interface. Tracks contain most of the data for the segment, whether that data consists of note events, band changes, tempo changes, or other timed events. Applications generally don't need to use this interface, because the tracks are managed through the segment object.

This section provides more information on segments in the following topics:

  • Creating Segment Objects
  • Playing Segments
  • Segment States
  • Pausing Segments
  • Control Segments
  • Self-Controlling Segments
  • MIDI-Based Segments
  • WAV-Based Segments


Creating Segment Objects

You can create a segment object in any of the following ways:

  • Load a file or resource object that supports the IDirectMusicSegment8 interface. Most segments are created this way.
  • Get a motif from a style by using the IDirectMusicStyle8::GetMotif method.
  • Use methods of the IDirectMusicComposer8 interface to create a composition or transition at run time.
  • Make a copy of an existing segment by using the IDirectMusicSegment8::Clone method.
  • Use the IDirectMusicBand8::CreateSegment method. This method creates a special type of secondary segment that is used only for making band changes.
  • Use the IDirectMusicPatternTrack8::CreateSegment method to create a segment from a pattern track object. Most applications don't do this, because pattern track objects usually come from existing segments.
  • Construct a segment from existing tracks. To do this, create a segment object by calling CoCreateInstance, and then add tracks by calling IDirectMusicSegment8::InsertTrack. This technique is not used by most applications.

See Also

  • DirectMusic Tracks
  • Loading Audio Data
  • Making Band Changes Programmatically
  • Using Compositional Elements
  • Using Templates
  • Using Transitions


Playing Segments

Segments can perform different roles in the performance. There must always be a primary segment, which provides the main content of the soundtrack and normally serves as the control segment, setting global parameters such as tempo. Secondary segments play along with the primary segment and might provide sound effects or short musical themes. A special type of secondary segment is the motif, which is always obtained from a DirectMusic style object.

In addition, three kinds of segments have special roles:

  • Transition segment. A short musical transition created at run time by the DirectMusic composer object and normally played as a primary segment leading from one segment to another, or from a segment to silence.
  • Band segment. A set of instruments and instrument settings for the various channels in the performance. The application can play a band segment as a secondary segment to execute changes in the band performing the music.
  • Template segment. A guide to chord progressions, groove levels, and embellishments, used in conjunction with a style and chordmap to compose music at run time.

The playback of segments is controlled by the performance object and begins with a call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

Only one primary segment at a time can be played. When you cue a primary segment for playback, you can specify that it is to be played after the currently playing segment is finished, or you can use it to replace the current primary segment.

Secondary segments, on the other hand, play over the current primary segment, and any number of secondary segments can be playing simultaneously.

Secondary segments do not normally alter the performance of the primary segment. For example, a secondary segment can be based on a different style without affecting the style of the primary segment. However, a secondary segment can be designated as the control segment, in which case it takes over certain tasks normally handled by the primary segment.

See Also

  • Segment Timing
  • Making Band Changes Programmatically
  • Using Templates
  • Using Transitions


Segment States

When you play a segment, parameters for that instance of the playing segment (such as the audiopath, start point, and number of repetitions) are stored in an object called a segment state, represented by an IDirectMusicSegmentState8 interface.

When different instances of a segment are being played on different audiopaths, you can use the segment state to retrieve a 3-D sound buffer or an effect, and make changes that apply only to that instance. For example, you might use the same engine sound for different cars in a race game, playing the sound for each car on its own audiopath. You can use either IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath to retrieve an IDirectSound3DBuffer8 interface from each audiopath, allowing you to set the 3-D parameters for each car individually.

See Also

  • Retrieving Objects from an Audiopath


Pausing Segments

To pause a segment, you must ascertain the current play position before stopping the segment. The following example function returns the current play position in music time.

MUSIC_TIME GetTimeOffset(const MUSIC_TIME mtNow,           // From GetTime
                         const MUSIC_TIME mtStartTime,     // From GetStartTime
                         const MUSIC_TIME mtStartPoint,    // From GetStartPoint
                         const MUSIC_TIME mtLoopStart,     // From GetLoopPoints
                         const MUSIC_TIME mtLoopEnd,       // From GetLoopPoints
                         const MUSIC_TIME mtLength,        // From GetLength
                         const DWORD dwLoopRepeats)        // From GetRepeats
{
    // Convert mtNow from absolute time to an offset
    // from when the segment started playing.

    LONGLONG llOffset = mtNow - (mtStartTime - mtStartPoint);

    // If mtLoopEnd is not zero, set llLoopEnd to mtLoopEnd;
    // otherwise use the segment length.

    LONGLONG llLoopEnd = mtLoopEnd ? mtLoopEnd : mtLength;

    LONGLONG llLoopStart = mtLoopStart;

    // Adjust offset to take looping into account.

    if ((dwLoopRepeats != 0) &&  (llLoopStart < llLoopEnd) &&  (llLoopEnd > mtStartPoint))
    {
        if ((dwLoopRepeats != DMUS_SEG_REPEAT_INFINITE)
          &&  (llOffset > (llLoopStart + (llLoopEnd - llLoopStart) *(signed)dwLoopRepeats)))
        {
            llOffset -= (llLoopEnd - llLoopStart) * dwLoopRepeats;
        }
        else if (llOffset > llLoopStart)
        {
            llOffset = llLoopStart + (llOffset - llLoopStart) % (llLoopEnd - llLoopStart);
        }
    }

    llOffset = min(llOffset, LONG_MAX);  // LONG_MAX is defined in Limits.h.
    return long(llOffset);
}

To restart the segment at the correct position, pass the return value of the sample function to IDirectMusicSegment8::SetStartPoint before calling IDirectMusicPerformance8::PlaySegmentEx.

Note The mtLength parameter of the example function will normally be 1 for segments loaded from WAV files. In this case, before calling SetStartPoint you must use IDirectMusicSegment8::SetLength to set the length of the segment to at least 1 tick more than the current offset. For more information, see IDirectMusicSegment8::SetStartPoint.


Control Segments

The control segment is the source of any data that is shared across tracks by parameter calls.

The following tracks give their data to the performance not by sending messages, as most other tracks do, but by responding to parameter calls.

  • Chord
  • Command
  • Mute
  • Tempo
  • Time signature

The chord track, for example, answers parameter calls from the style track. To determine the MIDI value for a note before sending that note, the style track must determine the current chord. It does so by calling IDirectMusicPerformance8::GetParam, and this call is relayed to the chord track in the control segment.

To function as a control segment, a segment must have at least one controlling track. The chord, command, mute, and tempo tracks are controlling tracks.

The control segment does not affect any aspect of playback that is controlled by messages. The time signature comes from the control segment only when there is no time signature track, as is normally the case in segments not based on MIDI files.

By default, the primary segment is the control segment. However, a secondary segment can be designated the control segment by passing the DMUS_SEGF_CONTROL flag to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

When a secondary segment is the control segment, the primary segment continues to function as a fallback source of control data. For example, if a secondary control segment does not contain a tempo track, but the primary segment does, the tempo comes from the primary segment.

See Also

  • DMUS_SEGF_FLAGS
  • Self-Controlling Segments
  • Track Configuration


Self-Controlling Segments

A self-controlling segment ignores any control information from the control segment that duplicates control information in the self-controlling segment. For example, if the segment has a command track, it can use its own commands (such as groove levels) rather than the commands in the control segment.

Segments can define for each track where it gets its controlling information, as follows:

  • From tracks in the control segment. This is the default behavior.
  • From tracks in the primary segment, regardless of whether it is the control segment.
  • From tracks in the same segment.

Configuring a segment as self-controlling is usually done by the author. However, applications can configure individual tracks within segments by setting or clearing the following flags, using the IDirectMusicSegment8::SetTrackConfig or IDirectMusicSegmentState8::SetTrackConfig method:

Flag | Effect
DMUS_TRACKCONFIG_OVERRIDE_ALL | The track should get parameters from this segment before control and primary segment tracks.
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY | The track should get parameters from this segment before primary segment tracks.
DMUS_TRACKCONFIG_FALLBACK | The track should get parameters from this segment if the primary and control segments do not return the needed information.

The following example code, where pSegment is an IDirectMusicSegment8 interface pointer, instructs the style track to get all its parameters from other tracks in the same segment, ensuring that chords, groove levels, and mute commands do not come from the control segment.

HRESULT hr = pSegment ->SetTrackConfig(CLSID_DirectMusicStyleTrack,
    -1, DMUS_SEG_ALLTRACKS, DMUS_TRACKCONFIG_OVERRIDE_ALL, 0);

See Also

  • Control Segments
  • Track Configuration.


MIDI-Based Segments

A MIDI-based segment can be created at run time by loading a standard MIDI (.mid) file. In addition, MIDI-based segment (.sgt) files can be created in DirectMusic Producer, often by importing MIDI files to which the author might add tempo, key, and band changes, as well as loop points. Unlike a style-based segment, a MIDI-based segment has no patterns and no command track. Instead, it has a sequence track that contains MIDI notes and other commands.


WAV-Based Segments

DirectMusic can load and play WAV files, but greater flexibility is provided by DirectMusic Producer segments containing wave tracks. A segment can contain any number of wave tracks, and a wave track can contain multiple waveforms.

WAV-based DirectMusic Producer segments can be used to create sound effects and ambient audio that do not sound repetitive. Each part in a wave track can have up to 32 variations, and every waveform in the part is assigned to one or more of these variations. Each time the track plays, one of the variations is selected for each part, and only the waveforms assigned to that variation are heard. Because different parts can play different variations, a two-part wave track could play in up to 1024 different ways. For an example of the use of waveform variations, see the Audio Scripts Sample.

Waveform variations are authored into segments. Applications do not control the selection of variations.

Another advantage of WAV-based segments over WAV files is that the waveforms can be in compressed format. The DirectMusic loader can load compressed waveform audio files in any format supported by the audio compression manager (ACM).

Segments loaded from WAV files are played just like any other segment. They pass through the performance as DMUS_WAVE_PMSG messages and are always played on channel 0 of the audiopath. Although waveforms are not synthesized in the same sense as musical notes, they do pass through the synthesizer and can be manipulated by MIDI controllers.

Waveforms are analogous to band instruments and must be downloaded to the synthesizer before being played. Waveforms are downloaded when the segment's bands are downloaded.

Waveforms can be either static or streaming. Static waveforms are loaded into synthesizer memory all at once. Streaming waveforms are loaded piece by piece as they play. Waveforms saved as DirectMusic Producer files are designated as static or streaming by the author, who also sets the readahead time; that is, the maximum amount of data that is copied into memory at one time. Waveforms from standard WAV files are streamed if longer than 5000 milliseconds, with a readahead of 500 milliseconds.


Playing WAV Sounds in Music Time

Because a WAV sound has no tempo, the loader cannot calculate the music-time length of a segment loaded from a WAV file or resource, and it always sets the length to 1 tick. In consequence, you cannot cue another segment to play immediately after a WAV segment by using the DMUS_SEGF_QUEUE flag. A further limitation is that you must play the WAV segment from the beginning, because IDirectMusicSegment8::SetStartPoint fails with any parameter greater than the known music-time length of the segment.

To overcome these limitations, you must set the length of the segment to a music-time value equivalent to the clock-time length of the sound. The length of the sound can be calculated from the WAV chunk headers; the DirectX SDK includes sample code to do this. The following sample function sets the length of a WAV segment whose length is known:

HRESULT SetWAVLength(IDirectMusicSegment8* pSeg,
        DWORD tempo,        // In beats per minute.
        float wavLength)    // In seconds.
{
  if (pSeg)
  {
    MUSIC_TIME mt;
    mt = (wavLength * DMUS_PPQ * tempo) / 60;
    return pSeg->SetLength(mt);
  }
  else return E_POINTER;
}

See Also

  • Calculating the Duration of a WAV Sound
  • Clock Time and Music Time
  • IDirectMusicSegment8::SetLength


Changing the Pitch of Waveforms

Several techniques can be used to change the pitch of a waveform programmatically.

If you are playing the waveform as a segment, you can obtain the DirectSound buffer through which it is playing and use the IDirectSoundBuffer8::SetFrequency method to change the pitch. Because a pitch change affects all sounds playing through a buffer, you should play the sound on its own audiopath, or its own mix group within an audiopath. Different buffers within a mix group cannot have different frequencies. (For information on mix groups, see the Help for DirectMusic Producer.)

This technique does not work well with looping segments. Because the performance does not take into account the actual time it takes for the sound to finish playing in the buffer, looping continues to happen at intervals based on the normal length of the sound. When the pitch is lower than the original pitch of the sound, the whole sound does not play before it loops; when the pitch is higher than the original, intervals of silence occur between loops. If the entire sound is looping, you can adjust the intervals by using IDirectMusicSegment8::SetLength before playing the segment; however, calling this method while the segment is playing will have unpredictable results.

Another technique is to set a MIDI pitch bend on the performance channel on which the sound is playing. To do so, send a DMUS_MIDI_PMSG message, specifying 0xE0 as the status byte. The lower seven bits of the two data bytes are combined as a 14-bit value, where 0x2000 specifies no pitch bend, lower values represent a lower pitch, and higher values represent a higher pitch. For more information, see the MIDI specification.

Perhaps the most effective way to control the pitch is to play the waveform as a DLS instrument created in DirectMusic Producer. You can use the same WAV sound as the sample for all regions (note ranges), or assign different sounds to different regions for more realistic effects. You can also create articulations such as volume envelopes to make the sound start and stop in a more natural way. To play the sound at different pitches in your application, start and stop different notes by sending DMUS_NOTE_PMSG messages.

See Also

  • Changing the Tempo
  • Retrieving Objects from an Audiopath
  • Using DirectMusic Messages


Using Bands

A band is a collection of settings for performance channels. Every part in a segment or style plays on a single performance channel, and the most recently applied band determines how sound is synthesized on that channel.

Bands can contain the following information for each channel:

  • Instrument, identified by a MIDI patch number and bank select. This setting does not affect WAV parts playing on the channel.
  • DLS collection from which to load the instrument. By default, the DLS collection is the standard General MIDI collection.
  • Volume.
  • Pan.
  • Transposition. If this value is not zero, music notes on the channel are automatically transposed for the instrument.

A band does not necessarily contain settings for every performance channel in use, and it does not have to contain every possible setting for channels it does affect. Settings not explicitly changed by a band remain as they were before the band was played. For example, if the application plays a band that does not contain any settings for channel 1, any parts on that channel continue playing on the last instrument assigned to it, and with the same volume, pan, and transposition settings. The band could change a single setting, such as the volume, without affecting any of the other settings currently in effect.

Segments and styles always contain at least one band, called the default band. Styles can contain additional bands. When you load a segment or style, the default band and any other bands are automatically loaded as well. However, you must still download the DLS data for the instruments in any band that you intend to use.

You can retrieve a pointer to the default band by using the IDirectMusicStyle8::GetDefaultBand method.

Other bands might be authored into the style, and can be found and retrieved by using the IDirectMusicStyle8::EnumBand and IDirectMusicStyle8::GetBand methods. Bands can also be obtained from other style files or from band files. When you have obtained an IDirectMusicBand8 interface, you have access to that band and can substitute it for the default band.

See Also

  • Downloading and Unloading Bands
  • Making Band Changes Programmatically
  • Ensuring Timely Band Changes
  • Playing a MIDI File with Custom Instruments


Downloading and Unloading Bands

Before a band can be used, the instruments it references must be downloaded to the performance. This step maps the instruments to performance channels and downloads the DLS data to the synthesizer.

By default, the application is responsible for downloading any band it uses. However, you can turn on automatic downloading of bands.

Downloading a band makes the band available to the performance but does not perform any program changes. Program changes take place in response to messages generated by the segment's band track, which is typically authored into a segment file. For information on how to make program changes at run time, see Making Band Changes Programmatically.

Information about how to implement downloading and unloading of bands is contained in the following topics:

  • Automatically Downloading Bands
  • Manually Downloading Bands
  • Patch Collisions
  • Unloading Bands


Automatically Downloading Bands

When automatic downloading is on, the instruments in the band are downloaded when the segment containing the band is cued. The instruments are automatically unloaded when the segment is stopped, unless another segment using the same instruments is cued to play immediately or is currently playing.

Automatic downloading should be used only when the timing of segment starts is not critical. Repeated loading and unloading of instruments is time-consuming and can cause serious degradation of performance in complex audio environments.

Automatic unloading, which is part of the automatic downloading mechanism, can also lead to undesired results. For example, suppose you play a short secondary segment that changes the instrument on a channel. The instrument is automatically downloaded when the secondary segment starts, replacing the existing instrument. When the secondary segment ends, the instrument is automatically unloaded, with the result that there is no instrument on that channel, and the channel plays silence.

You can turn on automatic downloading of bands in one of the following ways:

  • Call the IDirectMusicPerformance8::SetGlobalParam method for the GUID_PerfAutoDownload parameter.
  • Enable automatic downloading for a single segment by calling the IDirectMusicSegment8::SetParam method for the GUID_Enable_Auto_Download parameter.

In the following example function, the global parameter for the performance is set to enable automatic downloading of bands in all segments:

HRESULT TurnOnDownload(IDirectMusicPerformance8* pPerf)
{
  BOOL fAuto = TRUE;

  HRESULT hr = pPerf->SetGlobalParam(
    GUID_PerfAutoDownload, &fAuto, sizeof(BOOL));
  return hr;
}

See Also

  • Setting and Retrieving Global Parameters
  • Setting and Retrieving Track Parameters
  • Unloading Bands


Manually Downloading Bands

You can manually download a band in one of the following ways:

  • Call IDirectMusicSegment8::Download to download the bands and waveforms in a segment to either an audiopath or a performance.
  • Obtain an IDirectMusicBand8 interface from a loaded object, and call the IDirectMusicBand8::Download method.
  • Call the IDirectMusicSegment8::SetParam method with the GUID_Download or GUID_DownloadToAudioPath parameter to download the band in the segment's first band track. You can also use IDirectMusicPerformance8::SetParam to set this parameter on the primary segment, or IDirectMusicTrack8::SetParamEx to set it directly on a band track. For more information, see Setting and Retrieving Track Parameters.

If your application creates audiopaths that use more than one port, you must download bands to the individual audiopaths, not to the performance. However, most applications use only a single port, and in this case it is safe to download all instrument data to either an audiopath or the performance. When a band is downloaded to an audiopath, the instrument data is downloaded to the port on that audiopath and is then available to any audiopath using the same port.

There is no danger in downloading the same instrument multiple times. If an instrument appears in one band multiple times or if it appears in multiple bands that are all opened and downloaded at the same time, only one copy of the instrument is sent to the synthesizer.

The following example function loads a band from a file and downloads it to the performance:

HRESULT DownloadBand(
  IDirectMusicLoader8 *pLoader,
  IDirectMusicPerformance8 *pPerf,
  WCHAR *pwszFile)
{
  IDirectMusicBand8* pBand;
  HRESULT hr;

  hr = pLoader->LoadObjectFromFile(CLSID_DirectMusicBand, IID_IDirectMusicBand8,
                                   pwszFile, (void **)&pBand);
  if (SUCCEEDED(hr))
  {
    hr = pBand->Download(pPerf);
  }
  return hr;
}


Patch Collisions

When bands from different segments are downloaded to the same port, instruments in band can overwrite data from a previously downloaded band.

For example, suppose segment A uses a band that assigns a piano to patch number 1, and segment B uses a band that assigns a banjo to the same patch. The application calls IDirectMusicSegment8::Download first for segment A and then for segment B. Even though the bands might be downloaded to different audiopaths, the instrument data is downloaded to the same synthesizer, so any note on a performance channel mapped to patch number 1 will be played by the banjo.

This potential for patch collisions must be taken into account when the content is authored. Different segments should not use different instruments with the same patch number.


Unloading Bands

Bands take up memory and should be unloaded when they are no longer in use. If you have enabled automatic downloading of bands, the bands associated with a segment are unloaded automatically when the segment stops. Otherwise, you can manually unload a band in one of the following ways:

  • Call the IDirectMusicSegment8::Unload or IDirectMusicBand8::Unload method for instruments downloaded by the corresponding Download method.
  • Call the IDirectMusicSegment8::SetParam method for the GUID_Unload or GUID_UnloadFromAudioPath parameter to unload the band in the segment's band track. You can also use IDirectMusicPerformance8::SetParam to set this parameter on the primary segment, or IDirectMusicTrack8::SetParamEx to set it directly on a band track.

The IDirectMusicPerformance8::CloseDown method also unloads any remaining downloaded instruments.

See Also

  • Setting and Retrieving Track Parameters


Making Band Changes Programmatically

In most cases, the band track in a loaded segment performs all necessary program changes. However, you can also do so manually if you have a band object. You must create a secondary segment by using IDirectMusicBand8::CreateSegment, and then play that segment by calling IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx. Typically, you would use DMUS_SEGF_MEASURE or DMUS_SEGF_GRID in the dwFlags parameter to ensure that the band change takes effect on an appropriate boundary.

The following example function creates a segment from a band and plays it on the next measure boundary. It is presumed that the instruments have already been downloaded or that automatic downloading has been enabled.

HRESULT PlayBand(
  IDirectMusicBand8 *pBand,
  IDirectMusicPerformance8 *pPerf,
  REFERENCE_TIME rfTime)
{
  IDirectMusicSegment *pSegment;

  HRESULT hr = pBand->CreateSegment(&pSegment);
  if (SUCCEEDED(hr))
  {
    hr = pPerf->PlaySegment(pSegment, DMUS_SEGF_MEASURE | DMUS_SEGF_SECONDARY,
                            rfTime, NULL);
    pSegment->Release();
  }
  return hr;
}

See Also

  • Patch Collisions


Ensuring Timely Band Changes

A consideration in playing band segments is the randomness in the timing of notes played by a style track. For instance, a note that is on measure 1, beat 1 might actually play somewhat earlier than the beat boundary. If you make a band change at the beat boundary, the note might play with the incorrect instrument.

To prevent this problem, an application should cue the band segment early. Suppose, for example, that you have a style-based segment pStyleSeg and a band segment pBandSeg. You want to play both the style segment and the band segment on the next measure boundary of the performance pPerf. You know that the style contains notes that could go out up to 30 ticks earlier, in music time, than the start time of the segment. The following example code ensures that the band segment is played 31 ticks before the style segment, so that all instruments are in place before any note is played:

HRESULT CueSegmentAfterBand(IDirectMusicPerformance8* pPerf,
                            IDirectMusicSegment8* pBandSeg,
                            IDirectMusicSegment8* pStyleSeg)
{
  REFERENCE_TIME rtResolved;
  MUSIC_TIME mtResolved;
  HRESULT hr;

  hr = pPerf->GetResolvedTime(0, &rtResolved, DMUS_TIME_RESOLVE_MEASURE);
  if (SUCCEEDED(hr))
  {
    hr = pPerf->ReferenceToMusicTime(rtResolved, &mtResolved);
   if (SUCCEEDED(hr))
   {
      mtResolved -= 31;
      hr = pPerf->PlaySegment(pBandSeg, 0, mtResolved, NULL);
      if (SUCCEEDED(hr))
      {
        pPerf->PlaySegment(pStyleSeg, DMUS_TIME_RESOLVE_MEASURE, 0, NULL);
      }
    }
  }
  return hr;
}

Note If there is no randomness in the notes played by a segment (for example, one loaded from a MIDI file), you don't need to worry about the timeliness of a band segment played at the same time. By default, all band segments start 1 tick early.


Playing a MIDI File with Custom Instruments

By default, when you play a MIDI file the instruments used are those in the Roland GM/GS Sound Set, contained in the Gm.dls file. However, you can use instruments from any DLS collection when playing a MIDI file.

First, load the collection and retrieve a pointer to the IDirectMusicCollection8 interface.

The following example function loads a collection by file name:

HRESULT LoadCollectionByName(
    IDirectMusicLoader8 *pILoader,
    char *pszFileName,
    IDirectMusicCollection8 **ppICollection)
{
  HRESULT hr;
  DMUS_OBJECTDESC objDesc;

  mbstowcs(objDesc.wszFileName,pszFileName,DMUS_MAX_FILENAME);
  objDesc.dwSize = sizeof(DMUS_OBJECTDESC);
  objDesc.guidClass = CLSID_DirectMusicCollection;
  objDesc.dwValidData = DMUS_OBJ_CLASS
      | DMUS_OBJ_FILENAME
      | DMUS_OBJ_FULLPATH;

  hr = pILoader->GetObject(&objDesc,
    IID_IDirectMusicCollection8,
    (void **) ppICollection);
  return hr;
}

Next, you must associate the DLS data with the segment by calling IDirectMusicSegment8::SetParam, as shown in the following example:

HRESULT ConnectCollection(IDirectMusicSegment8* pSegment,
                          IDirectMusicCollection8* pCollection)
{
  HRESULT hr = pSegment->SetParam(GUID_ConnectToDLSCollection,
      0xFFFFFFFF, DMUS_SEG_ALLTRACKS, 0, (void*)pCollection);
  return hr;
}

Finally, download the instruments in the collection to the performance or audiopath by calling IDirectMusicSegment8::Download.

When a custom collection is attached to a MIDI segment, the connection to the GM collection is not broken. For example, suppose you load a collection containing a single instrument that has a patch number of 12 and connect this to the segment. MIDI channels with any patch number other than 12 continue to be played by the appropriate instruments in the GM collection.

See Also

  • Using Instrument Collections.


Timing

This section is an overview of various timing issues in DirectMusic. The following topics are discussed:

  • Master Clock
  • Clock Time and Music Time
  • Changing the Tempo
  • Prepare Time
  • Latency and Bumper Time
  • Reducing Latency
  • Segment Timing


Master Clock

To guarantee accurate timing with an acceptably low latency, DirectMusic incorporates a master clock in kernel mode. This clock is based on a hardware timer. DirectMusic automatically selects the system clock as the master clock, but an application can select a different one, such as the wave-out crystal on a sound card.

The master clock is a high-resolution timer that is shared by all processes, devices, and applications that are using DirectMusic. The clock is used to synchronize all audio playback in the system. It is a standard IReferenceClock interface. The IReferenceClock::GetTime method returns the current time as a 64-bit integer (defined as the REFERENCE_TIME type) in increments of 100 nanoseconds.

To obtain an interface to the master clock, call the IDirectMusic8::GetMasterClock method.

You can choose a different master clock for your application, but only if there are no other DirectMusic applications running. First, you get descriptions of all devices that can serve as the master clock by using the IDirectMusic8::EnumMasterClock method. After you have obtained the GUID of the device that you want to use as the master clock, pass it to the IDirectMusic8::SetMasterClock method.


Clock Time and Music Time

In DirectX for C++, the time returned by the master clock is a 64-bit value defined as type REFERENCE_TIME. Reference time is measured in units of approximately 100 nanoseconds, so the clock ticks about 10 million times each second. The value returned by the IReferenceClock::GetTime method is relative to an arbitrary start time.

Music time is a 32-bit value defined as type MUSIC_TIME. It is not an absolute measure of time but is relative to the tempo. The clock is started when the performance is initialized and ticks DMUS_PPQ times for each quarter-note. DMUS_PPQ is defined as 768.

When a performance is initialized, it starts keeping an internal clock. You can retrieve the current performance time in both reference time and music time by using the IDirectMusicPerformance8::GetTime method.

The IDirectMusicPerformance8::AdjustTime method can be used to make small changes to the performance time. Most applications don't need to do this, but it can be useful when synchronizing to another source.

To convert between the two kinds of time in a performance, you can use the IDirectMusicPerformance8::MusicToReferenceTime and IDirectMusicPerformance8::ReferenceToMusicTime methods. These methods convert between time offsets within the performance, taking into account all tempo changes that have taken place since the performance started.

When a segment is cued to play by a call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx and the start time is given in reference time, DirectMusic must convert the start time to music time. If no primary segment is currently playing, the conversion is made immediately, based on the current tempo. Otherwise, if another segment is playing, the start time of the cued segment is not converted to music time until the start time has been reached.

If the tempo is changed before the segment starts playing, the actual start time can be affected, or the segment might not start on the desired boundary. In the first case, in which the conversion to music time is done immediately, the start time (in reference time) is advanced if the tempo speeds up and delayed if the tempo slows down. In the second case, in which conversion is made at start time, a change in tempo can mean that the segment does not start at correct resolution boundaries. For example, if the segment is supposed to start on a measure boundary (as indicated in the dwFlags parameter of PlaySegment or PlaySegmentEx), the actual start time (in reference time) is calculated when the segment is cued. However, if the tempo then changes, a measure boundary might not fall at that time.

When a primary segment is played with the DMUS_SEGF_QUEUE flag (see DMUS_SEGF_FLAGS), the i64StartTime parameter is ignored, and the segment is cued to play after any primary segments whose start times have already been converted. If a previously cued segment is still stamped in reference time, that segment will play at its designated time, perhaps interrupting another segment.

For example, suppose you have three segments, each 10 seconds in length. You cue segment A to play 5 seconds from now. Because no primary segment is currently playing, the start time is immediately converted to music time. At 6 seconds, you cue segment B to play at 20 seconds. In this case, because music is already playing and the tempo might change, the conversion to music time is not made immediately. Then you cue segment C with the DMUS_SEGF_QUEUE flag so that it starts immediately after segment A finishes, at 15 seconds. At 20 seconds, segment B starts playing and interrupts segment C.

See Also

  • Playing WAV Sounds in Music Time


Changing the Tempo

The tempo of a performance dictates the conversion between the two types of time used in DirectMusic, which in turn controls the resolution of events to musical boundaries. (See Clock Time and Music Time.) The tempo track of the control segment usually manages the tempo, but it is also possible for an application to set the tempo dynamically.

There are two ways to change the tempo: by sending a message and by setting a track parameter on the control segment.

The following example function sends a message to change the tempo, after disabling the tempo track so that it does not override the new tempo.

HRESULT ChangeTempoByMessage(IDirectMusicPerformance8* pPerformance,
                    IDirectMusicSegment8* pSegment,
                    double dblNewTempo)
{
   DMUS_TEMPO_PMSG* pTempoMsg;
   HRESULT hr;

   if (SUCCEEDED(hr = pSegment->SetParam(GUID_DisableTempo,
          0xFFFF, 0, 0, NULL)))
   {
    if (SUCCEEDED(hr = pPerformance->AllocPMsg(
        sizeof(DMUS_TEMPO_PMSG), (DMUS_PMSG**)&pTempoMsg)))
    {
      // Cue the tempo event.
      ZeroMemory(pTempoMsg, sizeof(DMUS_TEMPO_PMSG));
      pTempoMsg->dwSize = sizeof(DMUS_TEMPO_PMSG);
      pTempoMsg->dblTempo = dblNewTempo;
      pTempoMsg->dwFlags = DMUS_PMSGF_REFTIME;
      pTempoMsg->dwType = DMUS_PMSGT_TEMPO;
      pPerformance->SendPMsg((DMUS_PMSG*)pTempoMsg);
    }
  }
  return hr;
}

If the performance has more than one audiopath, the message should be stamped for delivery to the correct audiopath. For more information, see Application-Created Messages.

The following example shows how to change the tempo parameter.

HRESULT ChangeTempoParameter(IDirectMusicSegment8* pSegment, double dblNewTempo)
{
  DMUS_TEMPO_PARAM Tempo;
  Tempo.dblTempo = dblNewTempo;
  HRESULT hr = pSegment->SetParam(GUID_TempoParam, 0xFFFF, 0, 0, &Tempo);
  return hr;
}

Note DMUS_TEMPO_PARAM is declared in Dmusicf.h, which is not automatically included when you include Dmusici.h.

You can also change the master tempo, which adjusts the tempo set by any control segment.

See Also

  • Setting and Retrieving Global Parameters
  • Setting and Retrieving Track Parameters


Prepare Time

As a segment is played, the performance makes repeated calls to the segment's tracks, causing them to generate messages for a specified time range, which is a fraction of a second. These messages are then placed in the queue behind those that were generated in previous calls. By default, about a second's worth of messages are in the queue at any time.

Each time it calls on a track to play messages, the performance calculates the end time for that call by adding the prepare time to the current time. For example, if the current time is 10,000 milliseconds (or the equivalent in reference time units) and the prepare time is the default 1000 milliseconds, the end time is at 11,000. The result is that all new messages that are to be played up to time 11,000 must be prepared and placed in the queue.

Most applications don't need to change the default prepare time, and the process just described is not visible to the application. However, it is helpful to understand the concept of prepare time because of the DMUS_SEGF_AFTERPREPARETIME flag, which the application can pass to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

If you set a start time of "now" for the segment without specifying DMUS_SEGF_AFTERPREPARETIME, the performance invalidates any messages currently in the queue. Any tracks that are still valid at this point (for example, tracks of secondary segments, which continue to play) then have to resend their messages, taking into account any changes made to the environment by the new segment. This causes extra processing and might also lead to undesired results.

You can use the DMUS_SEGF_AFTERPREPARETIME flag to specify that the segment isn't to start playing until all messages currently in the queue have been processed and passed to the port buffer. If messages up to time 10,000 are in the queue and the current time is 9,000, a segment cued to play immediately, but flagged DMUS_SEGF_AFTERPREPARETIME, starts playing just after the 10,000 mark.

See Also

  • IDirectMusicPerformance8::GetPrepareTime
  • IDirectMusicPerformance8::SetPrepareTime
  • Latency and Bumper Time
  • Segment Timing.


Latency and Bumper Time

Latency is the delay between the time at which the port receives a message and the time at which it has synthesized enough of a waveform to play. The IDirectMusicPerformance8::GetLatencyTime method retrieves the current time plus the latency for the performance as a whole. The latency is based on the largest value returned by any port's latency clock.

The bumper is an extra amount of time allotted for code to run between the time that an event is put into the port buffer and the time that the port starts to process it. By default, the bumper length is 50 milliseconds.

The following example shows how latency time and bumper time are combined. Suppose an event is cued to play at 10,000 milliseconds. The latency of the port is known to be 100 ms, and the bumper length is at its default value of 50 ms. The performance therefore places the message into the port buffer at 9,850 ms.

Any tools that alter the time of messages must take latency and bumper time into account. If a tool stamps a message with a time that is already past the latency time, the note or other event will not play at the correct time.

After a message has been placed in the port buffer, it no longer belongs to the performance and cannot be stopped from playing by using the IDirectMusicPerformance8::Invalidate method or by stopping the segment. The first message that can be invalidated has a time stamp equal to or greater than the current time plus the latency time and the bumper time. This value can be retrieved by using the IDirectMusicPerformance8::GetQueueTime method.

The following diagram, not to scale, illustrates the relationship of the times and durations retrieved by various methods. The current time is at the left, and the last time for which messages have been prepared is at the right. Remember that prepare time is only an approximation of the total timespan of messages in the queue at any moment.

See Also

  • Reducing Latency
  • IDirectMusicPerformance8::GetBumperLength.
  • IDirectMusicPerformance8::SetBumperLength


Reducing Latency

The latency in DirectMusic consists of two major components, system-dependent latency and latency padding.

System-dependent latency is calculated dynamically by approximating the minimum amount of write-ahead data required for the given system configuration. This behavior is automatic and not controllable by the application. The absolute minimum system-dependent latency is 4 milliseconds.

Latency padding ranges from 0 to 100 milliseconds, and is configurable by the application. This value is added to the system-dependent latency and may be used to mitigate glitching problems. To ensure maximum compatibility with older systems, latency padding is set to 55 milliseconds by default. Most applications do not need to increase the latency padding.

Decreasing the latency padding allows applications to take advantage of the low-latency capabilities of modern hardware. However, doing so comes at the risk of glitching on some systems. Only applications that truly need the lowest latency possible should reduce the latency padding value.

Changing the latency padding value is accomplished by setting the GUID_DMUS_PROP_WriteLatency property on the port. The following example code demonstrates the use of this property.

HRESULT SetLatency (IDirectMusicPort8 *pDMPort, DWORD dwLatency)
{
    IKsControl* pKSControl;
    HRESULT hr;

    // Query for IKsControl. All ports that support properties provide this interface.
    hr = pDMPort->QueryInterface(IID_IKsControl, (void**)&pKSControl);
    if (SUCCEEDED(hr)) {
        KSPROPERTY KSProperty;
        ULONG      ulDummy;
        ZeroMemory(&KSProperty, sizeof(KSProperty));
        KSProperty.Set   = GUID_DMUS_PROP_WriteLatency;
        KSProperty.Flags = KSPROPERTY_TYPE_SET;
        hr = pKSControl->KsProperty(&KSProperty, sizeof(KSProperty),
                (LPVOID)&dwLatency, sizeof(dwLatency), &ulDummy);
        pKSControl->Release();
    }
    return hr;
}

To attain the absolute minimum latency, applications must also reduce the wakeup interval of the DirectMusic realtime thread. This is achieved by setting the GUID_DMUS_PROP_WritePeriod property on the port.

See Also

  • KSPROPERTY
  • Property Sets for DirectMusic Ports


Segment Timing

When you cue a segment to play, you have a great deal of control over when the segment starts, what point in the segment is heard first, how the segment is aligned rhythmically with currently playing music, and whether any part of the segment plays more than once.

The following terms are used throughout this section to clarify the relationship between times within segments and times within the performance.

Start point

The first point in the segment that can be a segment start time. By default this value is 0, indicating the beginning of the segment. However, it can be changed by the application.

Segment start time

The point in a segment where it begins producing sounds. This time is usually the same as the start point, but can be later than the start point if the start point is deliberately aligned to a play time that is in the past.

Play time

The point in the performance where a segment's start point is cued. In the DirectMusic API, this time is sometimes called start time.

Resolved time

A specified time (such as the play time) adjusted to a specified boundary. For example, the resolved time could be the time of the next beat after the specified time.

Start marker

A marker indicating a valid segment start time in a segment. The marker can be an enter switch point in the marker track, or a variation switch point in a pattern.

Play marker

A marker in the marker track of a control segment indicating where another segment's start point can be cued.

Note Start markers and play markers are placed in a segment in DirectMusic Producer and cannot be changed by the application. They can, however, be retrieved by using the GUID_Valid_Start_Time and GUID_Play_Marker parameters.

Segments normally play from the beginning. You can make a segment start from another point by using the IDirectMusicSegment8::SetStartPoint method. The new start point remains valid until changed.

The play time is determined by two parameters of the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx methods:

  • The i64StartTime parameter sets the earliest time at which the segment can start playing. If i64StartTime is 0, this time is as soon as possible. The actual time at which the segment can start depends on the type of segment. If it is a primary segment or a secondary control segment, the earliest play time is at queue (or flush) time. If it is a noncontrol secondary segment, the earliest play time is at latency time. For more information on queue time and latency time, see Latency and Bumper Time.
  • The dwFlags parameter specifies how soon after the earliest possible play time the segment will actually start playing. Usually, you will want to wait for an appropriate point in the rhythm before introducing a new primary segment, transition, or motif. You control the delay by setting one or more flags from the DMUS_SEGF_FLAGS enumeration.

Repeating and Looping

If a repeat count is set by using IDirectMusicSegment8::SetRepeats, the entire segment repeats that number of times, unless a loop has been defined by a call to IDirectMusicSegment8::SetLoopPoints, in which case only the part of the segment between the loop points repeats.

Aligning a Segment to a Past Time

Rather than forcing the segment start time to the next grid, beat, or measure in the control segment, you might want the segment to start playing sooner, yet still match the rhythm of the current segment. You can make the segment do so by cuing its start point to a rhythmic boundary that has already passed. The rhythm in the cued segment is thus aligned with that in the current segment, and the new segment can start playing immediately.

To cue the segment in the past, use the DMUS_SEGF_ALIGN flag. Add one of DMUS_SEGF_GRID, DMUS_SEGF_BEAT, DMUS_SEGF_SEGMENTEND, or DMUS_SEGF_MEASURE to cue the start point of the segment at the appropriate rhythmic boundary. Alternatively, you can use DMUS_SEGF_MARKER to align the start point to the most recently played play marker in the control segment.

Note Combining DMUS_SEGF_ALIGN with DMUS_SEGF_SEGMENTEND causes the beginning of the cued segment to be aligned with the beginning of the current segment.

Of course, when the start point is in the past, the segment start time has to be adjusted to fall in the present or the future. The performance uses the following rules to determine the segment start time. In all cases, "next" means "next possible"—that is, within the part of the segment that does not fall in the past.

  • If a start marker appears in the cued segment before the next resolution boundary of the specified type, the segment start time falls at that point.
  • If there is no valid start marker, the segment start time is at the next start resolution boundary of the cued segment, as specified by one of the following flags:
    Flag | Effect
    DMUS_SEGF_VALID_START_BEAT | Puts the segment start time on the next beat.
    DMUS_SEGF_VALID_START_GRID | Puts the segment start time on the next grid.
    DMUS_SEGF_VALID_START_MEASURE | Puts the segment start time on the next bar line.
    DMUS_SEGF_VALID_START_TICK | Puts the segment start time at the earliest possible point.

  • If there is no valid start marker and no start resolution flag is supplied, the segment start time is at the next play resolution boundary as specified by the DMUS_SEGF_GRID, DMUS_SEGF_BEAT, or DMUS_SEGF_MEASURE flag. If none of these flags is present, the segment start time is immediate.

Play markers and start markers allow greater flexibility in the cuing of segments, especially motifs. Suppose a motif is designed to sound best when it starts playing at the beginning of a measure in the primary segment. If the motif is cued with the DMUS_SEGF_MEASURE flag, there might be a significant delay before the next measure boundary is reached and the motif plays. But if the DMUS_SEGF_ALIGN flag is added, the motif can start playing sooner without violating the rhythm. Adding the DMUS_SEGF_MARKER flag ensures that the motif plays at an appropriate boundary within the control segment, rather than on just any measure, beat, or grid.

For information on how tempo changes can affect segment start times, see Clock Time and Music Time.

The following diagram shows how the timing is determined for a segment cued with the DMUS_SEGF_MEASURE, DMUS_SEGF_ALIGN, and DMUS_SEGF_VALID_START_BEAT flags. The solid vertical lines are measure boundaries, and the dotted lines are beat boundaries. The start point of the segment is aligned with the previous measure boundary in the current primary segment. The segment start time falls at the first beat in the cued segment after the unresolved play time.

Logical Time and Actual Time

Some events have both a logical time and an actual time. The actual time is when the event will take place, and the logical time represents the musical position where it belongs.

For example, a segment might contain a program change that belongs to the start of a beat. The logical time is the start of the beat. However, you want to make sure the program change takes place before the note on the beat is played, so you assign it a physical time that's a little earlier.

If the segment loops to the logical time (the start of that same beat), the program change will still go out.


Notification and Event Handling

From time to time, your application may need to respond to a performance event. For example, you might need to know when the end of a segment has been reached, or you might want to synchronize graphics with the beat of the music. You get the desired information by asking DirectMusic to notify you when a certain type of event occurs.

Note Performance notifications should not be confused with DirectSound buffer notifications, which are not used by DirectMusic applications.

To specify what types of events you want to be notified of, call the IDirectMusicPerformance8::AddNotificationType method once for each desired type of event.

The following example function causes DirectMusic to set segment-related events. The specific type of event, such as a segment start or a segment end, is derived later from the notification message.

HRESULT SetSegmentNotification(IDirectMusicPerformance8* pPerformance)
{
  GUID guid = GUID_NOTIFICATION_SEGMENT;

  return pPerformance->AddNotificationType(guid);
}

You can also add notification types for a particular segment by using the IDirectMusicSegment8::AddNotificationType method. You could do this, for example, to receive notification of when a particular segment stops playing. You cannot use this method to request GUID_NOTIFICATION_PERFORMANCE types, because these must come from the performance object.

Note Most applications do not call the IDirectMusicTrack8::AddNotificationType method directly.

Information about notifications is sent in DMUS_NOTIFICATION_PMSG message structures. You can poll for any pending notification messages within the Windows message loop by calling the IDirectMusicPerformance8::GetNotificationPMsg method, or you can have DirectMusic signal an event object in a separate thread when a message is pending.

If you want to be alerted of pending DirectMusic notification messages by a Windows event object, you must first obtain an event handle by calling the CreateEvent function. Typically, you would create an autoreset event with a call such as the following:

HANDLE g_hNotify = CreateEvent(NULL, FALSE, FALSE, NULL);

After creating the event, assign the handle to the performance by passing it to the IDirectMusicPerformance8::SetNotificationHandle method. You can use the second parameter of this method to specify how long DirectMusic should hold onto the event if it is not retrieved. A value of 0 in this parameter indicates that the default time of 2 seconds is to be used.

In the following example, g_pPerf is a valid pointer to the IDirectMusicPerformance8 interface:

HRESULT hr = g_pPerf->SetNotificationHandle(g_hNotify, 0);

The following example function executes repeatedly in its own thread, checking for signaled events and retrieving notification messages:

void WaitForEvent(LPVOID lpv, HANDLE hNotify, IDirectMusicPerformance8* pPerformance)
{
  DWORD dwResult;
  DMUS_NOTIFICATION_PMSG* pPmsg;

  while (TRUE)
  {
    dwResult = WaitForSingleObject(hNotify, 100);
    while (S_OK == pPerformance->GetNotificationPMsg(&pPmsg))
    {
      // Check notification type and do something in response.
      // Then free the message.
      pPerformance->FreePMsg((DMUS_PMSG*)pPmsg);
    }
  }
}

More than one message might be waiting when an event is signaled or when you call GetNotificationPMsg in the message loop. To be sure of catching all notifications, call GetNotificationPMsg repeatedly until it returns S_FALSE.

Multiple messages with the same time stamp are not queued in any particular order.

It is the application's responsibility to free any messages it retrieves, by calling the IDirectMusicPerformance8::FreePMsg method.


Troubleshooting Playback

The following are common causes for sounds not playing correctly:

  • Instruments have not been downloaded. You must download all instruments and waveforms used by segments, even the default Gm.dls instrument collection. To ensure that all instruments and waveforms are downloaded, you can turn on automatic downloading; however, this is not recommended. A better way is to download each segment when it is loaded, by using IDirectMusicSegment8::Download. For more information, see Downloading and Unloading Bands.

    There is one case in which automatic downloading might be required: when a segment trigger track cues other segments that use different instruments or waveforms. Because your application doesn't obtain an interface to the triggered segments, it cannot download them manually.

  • The loader cannot find needed files. Make sure the loader is searching in the correct folder by calling IDirectMusicLoader8::SetSearchDirectory.
  • The loader cannot find objects that are used by other objects. Content authored in DirectMusic Producer can contain references to content in other files. For example, a script track in a segment might contain calls to play other segments. If the loader cannot find the referenced segments, it cannot play them. To ensure that the loader can identify and load all referenced objects, call IDirectMusicLoader8::ScanDirectory. For more information, see Scanning a Directory for Objects.


Performance Parameters

DirectMusic lets you control many aspects of track behavior by changing parameters during playback, using one of the following SetParam methods:

  • IDirectMusicPerformance8::SetParam sets data on a specific track within the current control segment of the performance. The control segment is normally the primary segment, but a secondary segment can be designated as the control segment when it is played. See Control Segments.
  • IDirectMusicSegment8::SetParam sets data on a specific track within the segment.
  • IDirectMusicTrack8::SetParam and IDirectMusicTrack8::SetParamEx set data on the track represented by the interface. Applications do not normally have interfaces to individual tracks.

The IDirectMusicPerformance8::SetGlobalParam method enables you to set values that apply across the entire performance.

The equivalent GetParam and GetGlobalParam methods retrieve current values for a track or the performance.

To have the music respond immediately to a changed parameter, an application can flush messages from the queue by using the IDirectMusicPerformance8::Invalidate method. This method causes all tracks to resend messages from the specified point forward.

See Also

  • Setting and Retrieving Track Parameters
  • Disabling and Enabling Track Parameters
  • Setting and Retrieving Global Parameters


Setting and Retrieving Track Parameters

The following methods are used for setting and retrieving track parameters:

  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx

When calling one of these methods on the performance or segment, you can identify the track by setting the dwGroupBits and dwIndex parameters. Usually, however, you can let DirectMusic find the appropriate track for you. For more information, see Identifying the Track.

The track parameter that is being set or retrieved is identified by a GUID in the rguidType parameter of the method. Each parameter that requires data is associated with a particular data type, and pParam must point to a variable or structure of this type. In some cases, part of the data structure must be initialized even when retrieving the parameter. For some parameters, you must also specify the time within the track at which the change is to take effect or for which the parameter is to be retrieved.

For reference information on the data associated with the standard parameter types, see Standard Track Parameters.

Some parameter changes might not appear to take effect immediately. For example, changing the groove level does not make a difference until the current pattern is about to finish playing and the next pattern is chosen. If you want the change to take effect sooner, you can force the current pattern to be discarded by calling the IDirectMusicPerformance8::Invalidate method.

To determine whether a particular parameter is supported by a track, use the IDirectMusicTrack8::IsParamSupported method and check for an S_OK result.


Identifying the Track

When you set or retrieve a parameter by using IDirectMusicTrack8::SetParamEx or IDirectMusicTrack8::GetParamEx, the parameter is associated with the track on which the method is called. However, when you call IDirectMusicPerformance8::SetParam, IDirectMusicPerformance8::GetParam, IDirectMusicSegment8::SetParam, or IDirectMusicSegment8::GetParam, DirectMusic needs to find the appropriate track.

Normally, you can let DirectMusic determine which track contains the desired parameter. To do this, set dwGroupBits to 0xFFFFFFFF and dwIndex to DMUS_SEG_ANYTRACK or DMUS_SEG_ALLTRACKS. For example, the following call to IDirectMusicSegment8::SetParam turns off the tempo track so that looping a segment does not reset the tempo:

HRESULT hr = pIDMSegment->SetParam(GUID_DisableTempo, 0xFFFFFFFF,
    DMUS_SEG_ALLTRACKS, 0, NULL);

There are times, however, when you need to specify a track. Typically, this would be the case when a segment contains multiple tracks of the same type. To set or retrieve the parameter on the desired track, you must identify it by group and index value.

Every track belongs to one or more groups, each group being represented by a bit in the dwGroupBits parameter of one of the methods under discussion. The track is assigned to a group or groups when it is inserted in the performance. In the case of segments loaded from a file, track groups are assigned by the author of the segment.

A track is identified by a zero-based index value within each of the groups it belongs to. The index value is determined by the order in which the tracks were inserted.

Suppose a segment contains the tracks shown in the following table.

Track | Group bits
A | 0x1
B | 0x2
C | 0x1
D | 0x3

Group 1 contains tracks A, C, and D, and group 2 contains tracks B and D. If you call GetParam with a value of 1 in dwGroupBits and a value of 0 in dwIndex, the parameter is retrieved from track A, which is the first track in group 1. If dwIndex is 1, the parameter is retrieved from track C, the second track in the group. Track D belongs to two groups, 1 and 2, so it can be identified as either dwGroupBits = 1 and dwIndex =2, or dwGroupBits = 2 and dwIndex = 1.

If you set more than one bit in dwGroupBits, the parameter is retrieved from the nth track containing any of those bits, where n is the value in dwIndex.

See Also

  • IDirectMusicSegment8::InsertTrack


Disabling and Enabling Track Parameters

By setting the GUID_DisableTempo and GUID_DisableTimeSig parameters on a track, you can disable the setting of tempo and time signature by a control segment. You might want to do this, for example, when you have set the tempo dynamically and don't want the primary segment to send tempo messages.

To re-enable the parameter, call one of the set-parameter methods with GUID_EnableTempo or GUID_EnableTimeSig as the rguidType parameter. You can also set these parameters to force a segment to send tempo messages even though it isn't the control segment, or to cause a secondary segment to send time signature messages.

It is also possible to disable and enable any track parameter by setting the configuration flags on the track. For more information, see Track Configuration.

See Also

  • Control Segments
  • IDirectMusicTrack8::IsParamSupported
  • Setting and Retrieving Track Parameters.


Setting and Retrieving Global Parameters

By using the IDirectMusicPerformance8::SetGlobalParam and IDirectMusicPerformance8::GetGlobalParam methods, you can set and retrieve parameters that affect the entire performance rather than a single track.

The parameter to be set or retrieved is identified by a GUID in the rguidType parameter of the method. Each parameter is associated with a particular data type, whose size is given in the dwSize parameter. The predefined GUIDs and their data types are shown in the following table.

Parameter type GUID (rguidType) | Data (*pParam) | Description
GUID_PerfAutoDownload | BOOL | This parameter controls whether instruments are automatically downloaded when a segment is played. By default, it is off. See Downloading and Unloading Bands.
GUID_PerfMasterGrooveLevel | char | The master groove level is a value that is always added to the groove level established by the command track. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.
GUID_PerfMasterTempo | float | The master tempo is a scaling factor applied to the tempo by the final output tool. By default, it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it. This value can be set in the range from DMUS_MASTERTEMPO_MIN through DMUS_MASTERTEMPO_MAX.
GUID_PerfMasterVolume | long | The master volume is an amplification or attenuation factor, in hundredths of a decibel, applied to the default volume of the entire performance and any other performances using the same synthesizer. The range of permitted values is determined by the port. For the default software synthesizer, the allowed range is +20db to -200dB, but the useful range is +10db to -100db. Hardware MIDI ports do not support changing master volume. Setting this parameter is equivalent to calling IKsControl::KsProperty for the GUID_DMUS_PROP_Volume property set on every port in the performance.

Applications can also use custom types of global parameters. To create a new type, establish a GUID and a data type for it.

Note All parameters have to be set before they can be retrieved. When a parameter is set, the performance allocates memory for the data in a linked list of items that are identified by GUID. If SetGlobalParam has never been called on the parameter, it does not appear in this linked list, and GetGlobalParam fails.


Using Audiopaths

A DirectMusic performance typically contains one or more audiopaths, which manage the flow of sound data through various objects. An audiopath might include the performance itself, a segment, toolgraphs, the synthesizer, DirectSound buffers, effects DMOs, and the primary DirectSound buffer where the final mixing is done.

If your application does nothing more complicated than playing 2-D sound effects or MIDI files, you can set up a standard default audiopath and play everything on it. But to take advantage of the full power of DirectMusic you may want to use multiple audiopaths and exercise more control over them.

Audiopaths use only the Microsoft software synthesizer. If you want your application to use another port or ports, you must initialize the performance by using IDirectMusicPerformance8::Init. For more information, see Using DirectMusic Ports.

This section is a guide to creating audiopaths, playing segments on them, and accessing objects within them. The following topics are covered:

  • Creating Audiopaths
  • Default Audiopath
  • Standard Audiopaths
  • Playing Sounds on Audiopaths
  • Retrieving Objects from an Audiopath


Creating Audiopaths

Applications can set up audiopaths in the following ways:

  • Create one or more standard audiopaths by using IDirectMusicPerformance8::CreateStandardAudioPath. See Standard Audiopaths.
  • Create a default standard audiopath for the performance in the call to IDirectMusicPerformance8::InitAudio. See Default Audiopath.
  • Have DirectMusic create an audiopath from the segment's audiopath configuration when the segment is played. Audiopaths created in this way are temporary and not visible to the application.
  • Obtain an audiopath configuration from a file authored in DirectMusic Producer and pass the configuration object to IDirectMusicPerformance8::CreateAudioPath.

An audiopath configuration object can be loaded just like any other object, by using IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile. A configuration embedded in a segment can be retrieved by using IDirectMusicSegment8::GetAudioPathConfig.

The audiopath configuration object does not have a unique interface or methods, and your application cannot change the configuration in any way. All you can do with the object is pass it, by its IUnknown interface, to IDirectMusicPerformance8::CreateAudioPath. For example code, see Playing Sounds on Audiopaths.

Audiopath configurations are the only means of creating nonstandard audiopaths. For instance, if different performance channels are to be routed to different buffers, this mapping must be specified in the audiopath configuration of a segment.


Default Audiopath

The default audiopath is the one used when a segment is played by using IDirectMusicPerformance8::PlaySegment, or when no audiopath is specified in a call to IDirectMusicPerformance8::PlaySegmentEx.

You can create an audiopath and make it the default by specifying a standard type in the dwDefaultPathType parameter of IDirectMusicPerformance8::InitAudio.

Any existing audiopath can be made the default audiopath by passing it to IDirectMusicPerformance8::SetDefaultAudioPath. Retrieve the default audiopath by using IDirectMusicPerformance8::GetDefaultAudioPath.


Standard Audiopaths

If your application does not play exclusively on audiopaths created from audiopath configuration objects, you must create one or more standard audiopaths.

Standard audiopaths are identified by the values passed in the dwType parameter of IDirectMusicPerformance8::CreateStandardAudioPath or in the dwDefaultPathType parameter of IDirectMusicPerformance8::InitAudio.

The audiopaths defined by DirectMusic manage the flow of synthesizer output through combinations of standard buffers, some of which have effect DMOs attached to them. The following table shows the standard audiopaths and which standard buffers they contain. Shared buffers can be used by more than one audiopath.

Audiopath type | Standard buffers | Buffer shared?
DMUS_APATH_DYNAMIC_3D | 3-D Dry | No
DMUS_APATH_DYNAMIC_MONO | Mono | No
DMUS_APATH_DYNAMIC_STEREO | Stereo | No
DMUS_APATH_SHARED_STEREOPLUSREVERB | Music Reverb | Yes Yes

Characteristics of the standard buffers are shown in the following table, where the Capabilities column lists values returned in the dwFlags member of the DSBCAPS structure passed to IDirectSoundBuffer8::GetCaps. The last column shows interfaces that can be obtained from the buffer object. In addition, applications can add effects to buffers by using IDirectSoundBuffer8::SetFX, making other interfaces available. For more information on obtaining interfaces, see Retrieving Objects from an Audiopath.

Standard buffer | Description | Capabilities | Interfaces
3-D Dry | Mono 3-D buffer | DSBCAPS_CTRL3D DSBCAPS_CTRLFREQUENCY DSBCAPS_CTRLFX DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS DSBCAPS_MUTE3DATMAXDISTANCE | IDirectSound3DBuffer8 IDirectSoundBuffer8 IDirectSound3DBuffer8
Mono | Mono buffer with no effects | DSBCAPS_CTRLFREQUENCY DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | IDirectSoundBuffer8
Music | Stereo buffer used with Reverb | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | IDirectSoundBuffer8
Reverb | Stereo buffer with music reverberation effect | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | IDirectSoundFXWavesReverb8 IDirectSoundBuffer8
Stereo | Stereo buffer with no effects | DSBCAPS_CTRLFREQUENCY, DSBCAPS_CTRLFX, DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | IDirectSoundBuffer8

More information about the standard audiopaths is available in the following topics:

  • DMUS_APATH_DYNAMIC_3D
  • DMUS_APATH_DYNAMIC_MONO
  • DMUS_APATH_DYNAMIC_STEREO
  • DMUS_APATH_SHARED_STEREOPLUSREVERB


DMUS_APATH_DYNAMIC_3D

This standard audiopath sets up a nonshared buffer of type 3-D Dry.

Applications can obtain an interface to the 3-D Dry buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.

The buffer uses the DS3DALG_NO_VIRTUALIZATION algorithm for 3-D effects, and this property cannot be changed by the application. Other algorithms can be applied to custom buffers in audiopaths that have been authored in DirectMusic Producer. For information on 3-D algorithms, see DSBUFFERDESC.

See Also

  • Standard Audiopaths


DMUS_APATH_DYNAMIC_MONO

This standard audiopath sets up a nonshared buffer of type Mono that has no 3-D parameters or special effects.

Applications can obtain an interface to the buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.

See Also

  • Standard Audiopaths


DMUS_APATH_DYNAMIC_STEREO

This standard audiopath sets up a nonshared buffer of type Stereo. This audiopath is intended for sound effects on stereo buffers. No reverberation is available.

Applications can obtain an interface to the buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.

See Also

  • Standard Audiopaths


DMUS_APATH_SHARED_STEREOPLUSREVERB

This standard audiopath sets up buffers of type Reverb and Stereo.

The Stereo buffer is shared among multiple audiopaths. It is a sink-in buffer, meaning that it accepts data directly from the synthesizer, not from other buffers.

Applications can obtain an interface to the Stereo buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.

The Reverb buffer is also a shared sink-in buffer. Unlike the Stereo buffer, it accepts a mono input from the synthesizer and converts the data to stereo format.

Applications can obtain an interface to the Reverb buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 1.

The following example function retrieves an IDirectSoundFXWavesReverb8 interface to the DMO in the Reverb buffer on a default DMUS_APATH_SHARED_STEREOPLUSREVERB audiopath:

HRESULT GetDMO(IDirectMusicPerformance8* pPerf,IDirectSoundFXWavesReverb8** ppEffectDMO)
{
  IDirectMusicAudioPath8 * pAudioPath;
  HRESULT hr;

  hr = pPerf->GetDefaultAudioPath(&pAudioPath);
  if (SUCCEEDED(hr))
  {
    HRESULT hr = pAudioPath->GetObjectInPath(DMUS_PCHANNEL_ALL,
      DMUS_PATH_BUFFER_DMO, 1,
      GUID_All_Objects, 0, IID_IDirectSoundFXWavesReverb8,
      (LPVOID*) ppEffectDMO);
  }
  return hr;
}

See Also

  • Standard Audiopaths


Playing Sounds on Audiopaths

If your application has created a default audiopath in the call to IDirectMusicPerformance8::InitAudio, you can play a segment on this path by using IDirectMusicPerformance8::PlaySegment. You can also play a segment on the default path by passing NULL in the pAudioPath parameter of IDirectMusicPerformance8::PlaySegmentEx.

If there is no default audiopath, or if you want to play a segment on another path, you must use PlaySegmentEx rather than PlaySegment. You can specify the audiopath in two ways:

  • Supply a pointer in the pAudioPath parameter. Usually this is the IDirectMusicAudioPath8 interface pointer you received when the audiopath was created.
  • Include DMUS_SEGF_USE_AUDIOPATH in dwFlags. This flag causes the segment to create an audiopath from a configuration embedded in the segment object.

Note An audiopath created in response to the DMUS_SEGF_USE_AUDIOPATH flag is released as soon as the segment has stopped playing. If the audiopath contains an effect such as reverberation, the effect is cut short prematurely. To prevent this from happening, the application should create the audiopath manually and release it only after a suitable delay.

Bands are not downloaded for segments played with the DMUS_SEGF_USE_AUDIOPATH flag unless automatic downloading is enabled. For more information, see Automatically Downloading Bands.

The following example function plays a segment on an embedded audiopath configuration if one is available, or on the default audiopath otherwise:

HRESULT PlayOnEmbedded(IDirectMusicPerformance8* pPerf, IDirectMusicSegment8 *pSeg)
{
  IDirectMusicAudioPath8 * pPath =  NULL;
  IUnknown *pConfig;
  HRESULT hr;

  if (pSeg)
  {
    if (SUCCEEDED(hr = pSeg->GetAudioPathConfig(&pConfig)))
    {
      hr = pPerf->CreateAudioPath(pConfig, TRUE, &pPath);
      pConfig->Release();
    }
    hr = pPerf->PlaySegmentEx(pSeg, NULL, NULL, 0, 0, NULL, NULL, pPath);
    if (pPath)
    {
      pPath->Release();
      pPath = NULL;
    }
  }
  return hr;
}

If you have an interface to the audiopath, you can change the volume by using IDirectMusicAudioPath8::SetVolume. Unlike the global parameter GUID_PerfMasterVolume, which affects all sounds playing on the synthesizer, this method sets the volume only on the performance channels playing on this audiopath.


Retrieving Objects from an Audiopath

It is often necessary to retrieve an interface to a particular object within the audiopath. Common reasons to do so include the following:

  • To manipulate the 3-D properties of sounds by obtaining an IDirectSound3DBuffer8 interface.
  • To set global 3-D sound properties by obtaining an IDirectSound3DListener8 interface from the primary buffer.
  • To set effects on a secondary buffer by obtaining the IDirectSoundBuffer8 interface.
  • To set effect parameters by obtaining an interface to a DMO such as IDirectSoundFXI3DL2Reverb8.

Objects can be retrieved from an audiopath by calling IDirectMusicSegmentState8::GetObjectInPath on the segment state that is playing on the audiopath. You can also call IDirectMusicAudioPath8::GetObjectInPath on the audiopath object itself. The following table gives information about the parameters to these two methods.

dwStage | guidObject | dwPChannel used? | dwIndex used? | iidInterface (typical)
DMUS_PATH_AUDIOPATH (*) | Ignored | No | No | IID_IDirectMusicAudioPath8
DMUS_PATH_AUDIOPATH_GRAPH | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_AUDIOPATH_TOOL | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_BUFFER | Ignored | Yes | No, identify by dwBuffer | IID_IDirectSoundBuffer8
DMUS_PATH_BUFFER_DMO | DMO class ID, such as GUID_DSFX_STANDARD_GARGLE, or GUID_All_Objects to enumerate | Yes | Yes; index of DMO within buffer | GUID for standard DMO interface, such as IID_IDirectSoundFXGargle(**)
DMUS_PATH_MIXIN_BUFFER | Ignored | No | No, identify by dwBuffer | IID_IDirectSoundBuffer8
DMUS_PATH_MIXIN_BUFFER_DMO | DMO class ID, such as GUID_DSFX_STANDARD_I3DL2REVERB, or GUID_All_Objects to enumerate | No | Yes; index of DMO within buffer | GUID for standard DMO interface, such as IID_IDirectSoundFXI3DL2Reverb(**)
DMUS_PATH_PERFORMANCE | Ignored | No | No | IID_IDirectMusicPerformance8
DMUS_PATH_PERFORMANCE_GRAPH | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_PERFORMANCE_TOOL | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_PORT | Port class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicPort
DMUS_PATH_PRIMARY_BUFFER | Ignored | No | No | IID_IDirectSound3DListener8
DMUS_PATH_SEGMENT (*) | Ignored | No | No | IID_IDirectMusicSegment8
DMUS_PATH_SEGMENT_GRAPH (*) | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_SEGMENT_TOOL (*) | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_SEGMENT_TRACK (*) | Track class ID or GUID_All_Objects to enumerate | No | Yes | IID_IDirectMusicTrack8

Notes (*) Objects in this stage cannot be retrieved by IDirectMusicAudioPath8::GetObjectInPath.

(**) The standard DMOs provided with DirectX also support the IMediaObject, IMediaObjectInPlace, and IMediaParams interfaces.

For more information on the values for dwIndex when retrieving standard buffers, see Standard Audiopaths.

The following example function retrieves a segment from the segment state that was created when the segment was played:

HRESULT GetSegmentFromState(IDirectMusicSegmentState* pSegState, IDirectMusicSegment8** ppSeg)
{
  IDirectMusicSegmentState8* pSegState8;
  HRESULT hr;

  if (SUCCEEDED(hr = pSegState->QueryInterface(IID_IDirectMusicSegmentState8,
                (void**) &pSegState8)))
  {
    hr = SUCCEEDED(pSegState8->GetObjectInPath(0, DMUS_PATH_SEGMENT, 0,
                  GUID_NULL, 0, IID_IDirectMusicSegment, (void**) ppSeg));
    pSegState8->Release();
  }
  return hr;
}

If you already have an interface to an effects buffer, it is also possible to retrieve a DMO interface by using IDirectSoundBuffer8::GetObjectInPath.

You can retrieve an IDirectSoundBuffer8 interface for any buffer in the audiopath, but some methods are not valid. For more information, see IDirectSoundBuffer8 Interface.


Using 3-D Sound in DirectMusic

Using the DirectSound API, you can locate DirectMusic sounds in space and can apply Doppler shift to moving sounds.

3-D effects are applied to individual DirectSound buffers. Because you can direct different sounds along different audiopaths, each with its own buffer, it's easy to apply different parameters to different sounds.

To apply 3-D effects to a buffer, you must obtain an IDirectSound3DBuffer8 interface to a buffer that has 3-D capabilities, such as one in the DMUS_APATH_DYNAMIC_3D standard audiopath. You can also create a suitable audiopath from a configuration object that specifies 3-D parameters for a buffer.

The following example code creates a standard audiopath and retrieves an IDirectSound3DBuffer8 interface. Assume that g_pPerformance is a valid IDirectMusicPerformance8 pointer.

HRESULT                  hr;
IDirectMusicAudioPath8*  g_p3DAudioPath;
IDirectSound3DBuffer8*   g_pDS3DBuffer;

if (SUCCEEDED(hr = g_pPerformance->CreateStandardAudioPath(
    DMUS_APATH_DYNAMIC_3D, 64, TRUE, &g_p3DAudioPath)))
{
  hr = g_p3DAudioPath->GetObjectInPath(
      DMUS_PCHANNEL_ALL, DMUS_PATH_BUFFER, 0,
      GUID_NULL, 0, IID_IDirectSound3DBuffer8,
      (LPVOID*) &g_pDS3DBuffer);
}
if (FAILED(hr))
{
  ErrorExit(hr);  // Add error-handling code.
}

To adjust global 3-D parameters and manipulate the position and orientation of the listener, you must obtain an IDirectSound3DListener8 interface from the primary buffer in any audiopath by using IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath, setting the dwStage parameter to DMUS_PATH_PRIMARY_BUFFER. The following example function retrieves the listener from an audiopath:

HRESULT GetListener(IDirectMusicAudioPath8* pPath, IDirectSound3DListener8** ppListener)
{
  HRESULT hr = E_INVALIDARG;

  if (NULL != pPath)
  {
    hr = pPath->GetObjectInPath(0, DMUS_PATH_PRIMARY_BUFFER, 0,
                                GUID_NULL, 0, IID_IDirectSound3DListener8,
                                (LPVOID*) ppListener);
  }
  return hr;
}}

See Also

  • Retrieving Objects from an Audiopath
  • Standard Audiopaths.
  • 3-D Sound


Using Effects in DirectMusic

DirectX provides support for effects processing of sounds by DirectX Media Objects (DMOs). A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system.

All the standard DMOs except Waves reverberation can process 8-bit or 16-bit PCM data with one or two channels at any sample rate supported by DirectSound. Waves reverberation does not support 8-bit samples.

Effects are attached to DirectSound buffers in audiopaths. To add, remove, or modify effects at run time, an application must obtain an interface to the buffer and use the DirectSound API. For more information, see Using Effects.

If you are playing segments authored in DirectMusic Producer with audiopath configurations, any effects are set up when you create the audiopath from the configuration object. A standard audiopath might also contain effects. However, in some cases you may prefer to implement an effect on a custom audiopath at run time or add an effect to a standard audiopath. For example, you might want to add an effect to a standard audiopath so that you can apply the effect to standard WAV or MIDI files.

To apply an effect to an audiopath, you must first obtain an IDirectSoundBuffer8 interface to a buffer on the path. Then set one or more effects on that buffer by using IDirectSoundBuffer8::SetFX.

To learn how to obtain a buffer interface, see Retrieving Objects from an Audiopath. For information on how to identify standard audiopath buffers in the call to GetObjectInPath, see the audiopath types under Standard Audiopaths.

The following example code sets a standard audiopath, retrieves a buffer from the path, and sets an echo effect on the buffer:

HRESULT SetEchoEffect(IDirectMusicPerformance8 *pPerformance,
    IDirectMusicAudioPath* p3DAudioPath,
    IDirectSoundBuffer8* pDSBuffer)
{
  HRESULT       hr;

  // Create a standard audiopath with a source and
  // environment reverb buffers. Don't activate the path;
  // SetFX fails if the buffer is running.

  if( FAILED(hr = pPerformance->CreateStandardAudioPath(
      DMUS_APATH_DYNAMIC_3D, 64, FALSE, &p3DAudioPath)))
    return hr;

  // Get the buffer in the audiopath.

  if( FAILED(hr = p3DAudioPath->GetObjectInPath(DMUS_PCHANNEL_ALL,
      DMUS_PATH_BUFFER, 0, GUID_NULL, 0, IID_IDirectSoundBuffer8,
      (LPVOID*) &pDSBuffer)))
    return hr;

  // Describe the effect.

  DSEFFECTDESC dsEffect;
  dsEffect.dwSize = sizeof(DSEFFECTDESC);
  dsEffect.dwFlags = 0;
  dsEffect.guidDSFXClass = GUID_DSFX_STANDARD_ECHO;
  dsEffect.dwReserved1 = 0;
  dsEffect.dwReserved2 = 0;

  DWORD dwResults;

  // Set the effect.
  if (FAILED(hr = pDSBuffer->SetFX(1, &dsEffect, &dwResults)))
  {
    p3DAudioPath->Activate(TRUE);
    return hr;
  }
  // You can check the value of dwResults here to ascertain
  // whether the effect was allocated, and how.

  // Activate the path.

  p3DAudioPath->Activate(TRUE);
  return hr;
}


Buffer Chains

A sound does not necessarily go through only a single secondary sound buffer. It is possible for buffers in an audiopath to send data to other secondary buffers. The advantage in doing so is that sounds from multiple buffers can be directed to a shared buffer where common 3-D parameters or special effects can be applied. Shared buffers can also be more efficient.

Buffer chains are set up automatically when an audiopath is created from an audiopath configuration embedded in a DirectMusic Producer file. For more information, see Using Audiopaths.

Buffer chains cannot be created by using the DirectSound API.


Using Compositional Elements

This section is a guide to using musical components in a DirectMusic application to create a soundtrack that is, to some extent, composed as it plays. It is presumed that you have a basic understanding of elements such as chordmaps and styles. If not, you should first read Introduction to Dynamic Musical Soundtracks.

It is possible to incorporate files from DirectMusic Producer into applications without working with individual compositional elements. Many applications use only fully authored segments. However, using individual components gives greater control over the performance at run time.

The following topics are discussed in this section:

  • Music Files for Composition
  • Overview of Programming for Composition
  • Using Styles
  • Using Motifs
  • Using Chordmaps
  • Using Templates
  • Using Transitions


Music Files for Composition

When programming for DirectMusic composition, you will use a variety of files created in DirectMusic Producer or a similar application. You load these elements into the application as COM objects and obtain interfaces to them.

The following table summarizes the types of file objects you will encounter. Any of these objects can also be obtained from a container file or from a resource.

The class GUID is the value that you put in the guidClass member of the DMUS_OBJECTDESC structure when loading the object.

Element | Class GUID | Interface | File extension
Band | CLSID_DirectMusicBand | IDirectMusicBand8 | .bnd
Chordmap | CLSID_DirectMusicChordMap | IDirectMusicChordMap8 | .cdm
DLS collection | CLSID_DirectMusicCollection | IDirectMusicCollection8 | .dls
Segment | CLSID_DirectMusicSegment | IDirectMusicSegment8 | .sgt
Style | CLSID_DirectMusicStyle | IDirectMusicStyle8 | .sty

Note Bands can be authored as part of a style, in which case they are automatically loaded when the style is loaded. Similarly, styles and bands can be authored into a segment, in which case you don't need separate files for those elements.

Files can also contain references to other files. If a style contains a reference to a band file, the band is automatically loaded when the style is, provided the loader can find the band file.

See Also

  • Loading Audio Data


Overview of Programming for Composition

When you implement music composed at run time, you will use previously authored objects as building blocks. In consultation with the author or other content provider, you can choose to get the musical data in the form of small building blocks that offer you the greatest possible flexibility and variation at run time, or you can use larger prefabricated elements that define the form of the music more fully.

Using the largest building blocks, you load highly structured segments based on styles, MIDI files, or waveforms that contain everything the performance requires to play the sound. All you have to do is load the segment and query for the IDirectMusicSegment8 interface. Pass this interface pointer to the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx method. The style playback engine selects pattern variations from the style and plays them according to a fixed chord progression—or, in the case of a MIDI-based segment, simply plays the MIDI sequence. Band changes are usually contained in the segment as well.

If you want to use smaller building blocks, you obtain the following elements:

  • Chordmaps, which are used to build chord progressions.
  • Styles, which define a basic melody and rhythm with variations, motifs, and embellishments.
  • Template segments, which are structural plans that control various aspects of playback, including the length of the segment, whether it loops, where groove level changes and embellishment patterns are to be placed, and what types of chords in the chordmap are to serve as signposts.

You can construct a segment by combining any chordmap, style, and template, using the IDirectMusicComposer8::ComposeSegmentFromTemplate method.

To have even more flexibility in music composition at run time, you can create segments based on predefined shapes rather than templates, using the IDirectMusicComposer8::ComposeSegmentFromShape method. The shape is used in creating the command and signpost tracks, which control the choice of embellishment patterns, the chord progression, and the frequency of chord changes.

When playing segments, you can also control the band used to play the parts. Bands are typically included in styles and templates, but they can also be supplied as separate files. To make band changes dynamically, create a secondary segment containing only the band, using the IDirectMusicBand8::CreateSegment method, and play this segment when it is time to assign instruments and instrument settings to the primary segment.

DirectMusic provides many options for creating transitions between segments. When you cue one segment to play after another, or to replace a currently playing segment, you have very precise control over the timing, and can synchronize the transition with the rhythm. In addition, you can have the DirectMusic composer object create a transitional measure.


Using Styles

The DirectMusic style object represents a collection of musical patterns, usually including embellishments and motifs, with a time signature, tempo, and band. It defines the basic rhythm and the notes to be played in each instrument part. For a conceptual overview, see Styles.

To obtain a style from a segment, use the IDirectMusicSegment8::GetParam method, as in the following example function, where the dwStyleIndex parameter specifies the index of the style within the segment:

HRESULT GetStyle(IDirectMusicSegment8* pSegment, DWORD dwStyleIndex,
                 IDirectMusicStyle8** ppStyle)
{
  return pSegment->GetParam(GUID_IDirectMusicStyle, 0xFFFFFFFF,
                            dwStyleIndex, 0, NULL, (LPVOID*)ppStyle);
}

A style by itself does not contain enough information to create a segment of music at run time. For this you need two other components: a chordmap, which is a scheme of possible chord progressions, and a command track to set the groove level and embellishments as the music plays. The command track can come from a template or be generated at run time from a shape. The chordmap generally comes from a chordmap file or resource.

To create a segment with a command track based on a template, call the IDirectMusicComposer8::ComposeSegmentFromTemplate method.

To create a segment based on a shape, call the IDirectMusicComposer8::ComposeSegmentFromShape method. You supply pointers to a style and a chordmap. You also supply a rate of harmonic motion, which controls the frequency of chord changes, and a shape constant, which determines the progression of groove levels and embellishments.

See Also

  • Using Templates


Using Motifs

A motif is a special kind of pattern in a style. A motif is intended to be played over the basic style pattern, typically in response to an interactive event. Unlike other patterns, motifs are always selected and played explicitly by the application. Although a motif can be as complex as any other pattern, even containing variations and multiple instrument parts, usually it is a short, simple musical figure that sounds good against a variety of background patterns. It might also be a sound effect played by a custom DLS instrument or instruments.

All the motifs authored into a style become available to you as soon as you have loaded that style. To get a particular motif ready for playback, call the IDirectMusicStyle8::GetMotif method, passing in the following parameters:

  • The name of the motif. You might know this from the documentation for the style, or you can obtain it from an index value by using the IDirectMusicStyle8::EnumMotif method.
  • A pointer to receive the IDirectMusicSegment8 interface to the segment object to be created by the method.

The following example function obtains and plays the motif whose name is passed in as pwszMotifName:

HRESULT PlayMotif(IDirectMusicPerformance8* pPerf,
   IDirectMusicStyle8* pStyle,
   WCHAR* pwszMotifName)
{
  IDirectMusicSegment* pSeg;
  HRESULT hr;

  if ((pPerf == NULL) || (pStyle == NULL))
  {
     return E_INVALIDARG;
  }

  // Get the motif segment from the style. Check for S_OK
  // specifically, because GetMotif() returns S_FALSE if it
  // does not find the motif.

  hr = pStyle->GetMotif(pwszMotifName, &pSeg);

  if (S_OK == hr)
  {
    hr = pPerf->PlaySegment(pSeg,DMUS_SEGF_BEAT | DMUS_SEGF_SECONDARY,
                            0, NULL);
    pSeg->Release();
  }
  return hr;
}

Note that pSeg is played as a secondary segment, because a motif is normally played over a primary segment. You cannot play a motif as a primary segment, because it does not have a chord track or band track. If you do want to play a motif against silence, create a primary segment from a style that has only blank patterns, and keep that segment playing while you play the motif.


Using Chordmaps

A chordmap object represents a collection of chords that provides the foundation of the harmonic structure and the mood of the music. A chordmap contains several pathways with many interconnected chords, providing many possibilities for the composition engine to choose from in determining the chord progression in a piece of music. For a conceptual overview, see Chordmaps.

For authored segments, applications don't normally need to concern themselves with chordmaps. The chordmap is used at the authoring stage to create a fixed chord progression. However, chordmaps can be used to compose segments at run time and to alter the chord progression of existing segments.

If a chordmap reference has been authored into a style, you can retrieve a pointer to its IDirectMusicChordMap8 interface by passing its name (assigned by the author) to the IDirectMusicStyle8::GetChordMap method. You can also use the IDirectMusicStyle8::EnumChordMap method to search for a particular chordmap, or the IDirectMusicStyle8::GetDefaultChordMap method to obtain a pointer to the default chordmap for the style.

Note DirectMusic Producer does not support authoring chordmap references into style files.

You set the chordmap for a composition when you create a segment by using either IDirectMusicComposer8::ComposeSegmentFromTemplate or IDirectMusicComposer8::ComposeSegmentFromShape.

After a segment has been created, you can change its chordmap by calling the IDirectMusicComposer8::ChangeChordMap method. This has the effect of changing the mood of the music without altering its basic rhythm and melody.

Every chordmap has an underlying scale, consisting of 24 tones. You can determine the tones of the scale by using the IDirectMusicChordMap8::GetScale method. The lower 24 bits of the variable pointed to by the pdwScale parameter of this method are set or cleared depending on whether the corresponding tone is part of the scale. The upper 8 bits give the root of the scale as an integer in the range from 0 through 23 (low C to middle B).

See Also

  • Using Styles


Using Templates

A template is a segment that can be used in composing a playable segment of music at run time. The template sets the length of the segment and any loop points. It can provide the command track, which controls changes in the groove level and the choice of embellishment patterns. It also prescribes how the chordmap is used in composing the segment, by specifying from which signpost group each new chord must come. For a conceptual overview, see Templates.

There are two ways to obtain a template:

  • Load it from a segment file or resource, and request the IDirectMusicSegment8 interface.
  • Create it from a shape, using the IDirectMusicComposer8::ComposeTemplateFromShape method. You choose the length, the overall shape, whether intro and end embellishment patterns are to be played, and how long the ending is to be. You get back a pointer to the IDirectMusicSegment interface from which you can obtain IDirectMusicSegment8.

After you have obtained a template segment object, you can pass it to the IDirectMusicComposer8::ComposeSegmentFromTemplate method, along with pointers to a style and a chordmap. You also supply a rate of harmonic motion, which sets the frequency of chord changes. The ComposeSegmentFromTemplate method creates a segment and returns a pointer to its IDirectMusicSegment interface.

See Also

  • Loading Audio Data


Using Transitions

To avoid a sudden and perhaps discordant break when stopping one segment and beginning another, or when bringing the music to a close, you can have the composer object create an intermediate or closing segment that provides an appropriate transition.

You have your choice of three techniques for composing transitional segments:

  • The IDirectMusicPerformance8::PlaySegmentEx method allows you to specify a segment in the pTransition parameter. This segment is used as a template for a newly composed transition. The transition is played at i64StartTime, and then the segment specified by pSource is played.
  • The IDirectMusicComposer8::AutoTransition method, given a pointer to the performance, creates a transition from the currently playing segment to a second segment of your choice, and then automatically cues the transitional segment and the second segment for playback, returning an IDirectMusicSegmentState interface for both. The transition begins playing immediately or on the next boundary, as specified in the dwFlags parameter. Optionally, the second segment can be NULL so that the transition is to silence.
  • The IDirectMusicComposer8::ComposeTransition method composes a transition from any point in one segment to the beginning of a second segment, or to silence, and returns an IDirectMusicSegment interface so that the application can play the transition.

The AutoTransition and ComposeTransition methods both take a chordmap, a command, and a set of flags as parameters:

  • The chordmap is used to create a chord track that defines the chord progression in the segment.
  • The command is one of the DMUS_COMMANDT_TYPES enumeration. It determines which type of pattern—either an ordinary groove pattern or one of the embellishments—is called for in the command track of the transitional segment. When the segment plays, an appropriate pattern is selected from the style.
  • The flags are from the DMUS_COMPOSEF_FLAGS enumeration and further define the transition, principally its timing. The DMUS_COMPOSEF_MODULATE flag can be used to cause the transition to move smoothly from one tonality to another; it cannot be used when there is no second segment, because there can be no modulation to silence.

Transitions created by AutoTransition and ComposeTransition are normally a single measure in length. However, they can be longer if the DMUS_COMPOSEF_LONG flag is included and the embellishment in the style is more than one measure long. They also contain at least two measures if they are of type DMUS_COMMANDT_ENDANDINTRO.

DirectMusic also provides many options for controlling the timing of transitions from one segment to another. For more information, see the following topics:

  • Segment Timing
  • DMUS_SEGF_FLAGS


Track Composition

Most tracks in a segment are fixed and generate the same data each time the segment is played. However, tracks can generate their data dynamically each time they start playing or each time they loop, provided they implement the IDirectMusicTrack8::Compose method and are configured for composition.

One standard track, the signpost track, supports composition. The signpost track composes a new chord track from a chordmap.

Normally the track configuration is set by the author, but the application can turn track composition behaviors on and off by passing one or more of the following flags to IDirectMusicSegment8::SetTrackConfig or IDirectMusicSegmentState8::SetTrackConfig.

Flag | Effect
DMUS_TRACKCONFIG_COMPOSING | The track is composed by the IDirectMusicSegment8::Compose method.
DMUS_TRACKCONFIG_LOOP_COMPOSE | The track is automatically composed each time the segment loops.
DMUS_TRACKCONFIG_PLAY_COMPOSE | The track is automatically composed each time the segment starts.

Automatic composition can take place only when the segment contains a track in which to put the composed content. When the signpost track is composed, it requires a chord track for the new chords. You can ensure that the necessary tracks exist by calling IDirectMusicSegment8::Compose before playing the segment.

If you choose to do all composition manually, the only configuration flag to set is DMUS_TRACKCONFIG_COMPOSING. Provided neither of the other two flags is set, the tracks will be composed only when you call Compose.


Using Audio Scripts

Scripts are collections of variables and routines authored in DirectMusic Producer. Although they consist mainly of text, scripts also contain a few binary parameters. For a conceptual overview, see Audio Scripts.

Load a script by using the IDirectMusicLoader8::GetObject method. Obtain the IDirectMusicScript8 interface, then call IDirectMusicScript8::Init to associate the script with a performance.

The following example function loads and initializes a script.

HRESULT LoadScript(IDirectMusicPerformance8 * pPerf,
                                IDirectMusicLoader8* pLoader,
                                WCHAR* wstrFileName,
                                IDirectMusicScript8** ppScript)
{
  DMUS_SCRIPT_ERRORINFO errInfo;
  HRESULT hr;

  if ((NULL == pPerf) || (NULL == pLoader))
  {
    return E_INVALIDARG;
  }
  if (SUCCEEDED(hr = pLoader->LoadObjectFromFile(
    CLSID_DirectMusicScript, IID_IDirectMusicScript8,
    wstrFileName, (LPVOID*) ppScript)))
  {
    if (FAILED(hr = (*ppScript)->Init(pPerf, &errInfo)))
    {
      (*ppScript)->Release();
    }
  }
  return hr;
}

Apart from Init, the methods of IDirectMusicScript8 have three main purposes:

  • Set and retrieve the value of variables declared in the script. Because script routines do not accept parameters, variables are the only way for the script and the application to exchange information.
  • Call routines. A routine must finish executing before the application thread can continue.
  • Enumerate routines and variables. These methods are of interest chiefly to script-editing applications.

All the methods of IDirectMusicScript8, except the enumeration methods, retrieve error information in a DMUS_SCRIPT_ERRORINFO structure. An error can occur if a variable is not found or code within a routine fails to execute.

Scripts can also be used without being directly loaded or called by the application. A segment authored in DirectMusic Producer can contain a script track that triggers calls to routines in one or more scripts.


Capturing MIDI

To capture MIDI messages from a device such as a keyboard, create a port for the capture device and use its IDirectMusicPort8::SetReadNotificationHandle method to cause an event to be signaled whenever messages are available to be read. In response to the event, call the IDirectMusicPort8::Read method repeatedly to place pending events into a buffer, until S_FALSE is returned. Each time Read is called, as many events are put into the buffer as are available, or as fit into the buffer. If at least one event was put into the buffer, S_OK is returned.

To retrieve events from the buffer, call the IDirectMusicBuffer8::GetNextEvent method. Each call retrieves a single event, until no more are available, at which point S_FALSE is returned.

The following code fragment illustrates this process. Assume that hEvent was created with CreateEvent and given to the capture port pPort by a call to SetReadNotificationHandle. Assume also that pBuffer was initialized by IDirectMusic8::CreateMusicBuffer.

REFERENCE_TIME rt;
DWORD    dwGroup;
DWORD    cb;
BYTE    *pb;

DWORD dw = WaitForMultipleObjects(1, hEvent, FALSE, INFINITE);
for (;;)
{
  hr = pPort->Read(pBuffer);
  if (hr == S_FALSE)
  {
    break;  // No more messages to read into the buffer.
  }
  pBuffer->ResetReadPtr();
  for (;;)
  {
    hr = pBuffer->GetNextEvent(&rt, &dwGroup, &cb, &pb);
    if (hr == S_OK)
    {
      // pb points to the data structure for the message, and
      // you can do anything that you want with it.
      // pb[0] is the status byte.
      // pb[1] and pb[2] are the data bytes.
    }
    else if (hr == S_FALSE)
    {
      break;  // No more messages in the buffer.
    }
  }  // Done with the buffer.
}  // Done reading pending events.

If you don't want to intercept messages, but simply want to send them from one port to another, you can use the IDirectMusicThru8 interface. See IDirectMusicThru8::ThruChannel for details.


Advanced Topics in DirectMusic

This section contains information needed for specialized applications that need functionality beyond that covered under Using DirectMusic.

Information is presented in the following topics:

  • DirectMusic Tracks
  • Using DirectMusic Messages
  • Using DirectMusic Ports
  • Custom Loading
  • Using Instrument Collections
  • Low-Level DLS
  • DirectMusic Tools
  • Property Sets for DirectMusic Ports


DirectMusic Tracks

Tracks are the components of a segment that contain its sequenced data, including information about notes, underlying chords, tempo, patch and band changes, and everything else that the performance needs to know to play the sounds.

Each track is represented by an IDirectMusicTrack8 interface. The methods of this interface are called by the performance, and most applications don't need to use them directly. This interface is chiefly of interest for plug-in components that implement their own track types.

When an application calls IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx, DirectMusic calls the IDirectMusicTrack8::Play or IDirectMusicTrack8::PlayEx method on the segment's tracks. Most tracks respond by immediately generating time-stamped messages containing data that is valid for the part of the segment that is being played. These messages are placed in a queue. See Message Creation and Delivery for more information about what happens after that.

A few tracks do not actively generate messages other than notifications in response to IDirectMusicTrack8::Play or IDirectMusicTrack8::PlayEx, but instead do most of their work by responding to requests for information that come from the performance or other tracks. The most important of these are the chord, mute, and command tracks. The tempo track sends messages but also responds to parameter requests.

More information is contained in the following topics:

  • Standard Track Types
  • Track Configuration


Standard Track Types

The following list describes the standard track types implemented by Microsoft DirectMusic. The class identifiers, such as CLSID_DirectMusicBandTrack, are used to identify track types in calls to various methods.

Track type | Class GUID | Purpose
Band | CLSID_DirectMusicBandTrack | Downloads DLS data to the performance. Sends messages of type DMUS_PATCH_PMSG, DMUS_TRANSPOSE_PMSG, DMUS_CHANNEL_PRIORITY_PMSG, and DMUS_MIDI_PMSG (for volume and pan). Used in segments based on MIDI files and styles.
Chord | CLSID_DirectMusicChordTrack | Used to convert music values in patterns to MIDI values. Sends messages of type DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_CHORD notifications).
Chordmap | CLSID_DirectMusicChordMapTrack | Used in template segments to compose chord tracks.
Command | CLSID_DirectMusicCommandTrack | Used in template segments to compose chord tracks, and in style segments to determine which patterns are played. Sends messages of type DMUS_NOTIFICATION_PMSG for GUID_NOTIFICATION_COMMAND notifications.
Lyrics | CLSID_DirectMusicLyricsTrack | Used to synchronize words with music. Generates messages of type DMUS_LYRIC_PMSG.
Marker | CLSID_DirectMusicMarkerTrack | Used for flow control. The marker track can hold valid start times for the segment, and play times at which new segments can be cued. For more information, see Segment Timing.
Motif | CLSID_DirectMusicMotifTrack | Used to play motifs to accompany other segments. Sends messages of type DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
Mute | CLSID_DirectMusicMuteTrack | Enables performance channels to be remapped or muted. Used with either style-based or MIDI-based segments.
Parameter control | CLSID_DirectMusicParamControlTrack | Controls the settings on tools, effects, and any other objects that support the IMediaParams interface.
Pattern | CLSID_DirectMusicPatternTrack | Contains a single musical pattern. The pattern track is similar to a sequence track, but contains music values rather than fixed notes. This track makes it possible to audition a pattern against different chords, and is used mostly by music-authoring applications. It might also be used to play an accompaniment. It is represented by its own interface, IDirectMusicPatternTrack8.
Script | CLSID_DirectMusicScriptTrack | Calls routines in an audio script.
Segment trigger | CLSID_DirectMusicSegmentTriggerTrack | Triggers the playback of segments. This track enables the author of a file to cue a segment from within a segment, rather than leaving this up to the application developer.
Sequence | CLSID_DirectMusicSeqTrack | Sends sequence messages of type DMUS_NOTE_PMSG and DMUS_MIDI_PMSG. Used in segments based on MIDI files. Also sends messages of type DMUS_CURVE_PMSG for segments saved in the .sgt format.
Signpost | CLSID_DirectMusicSignPostTrack | Used in template segments to compose chord tracks.
Style | CLSID_DirectMusicStyleTrack | Fundamental track for segments based on styles. Sends messages of type DMUS_TIMESIG_PMSG, DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
SysEx | CLSID_DirectMusicSysExTrack | Sends system exclusive messages of type DMUS_SYSEX_PMSG. Used in segments based on MIDI files.
Tempo | CLSID_DirectMusicTempoTrack | Controls the tempo of the performance.
Time Signature | CLSID_DirectMusicTimeSigTrack | Sends messages of type DMUS_TIMESIG_PMSG as well as GUID_NOTIFICATION_MEASUREANDBEAT notifications. The time signature track exists in imported MIDI files and authored segments specifically created with one. In most cases, the style track implements the time signature track's functionality, so it is not necessary for a segment that contains a style track to contain a time signature track as well. The Time Signature track supports the IDirectMusicTrack interface, but not IDirectMusicTrack8.
Wave | CLSID_DirectMusicWaveTrack | Sends messages of type DMUS_WAVE_PMSG to play time-stamped wave sounds.


Track Configuration

Using the IDirectMusicSegment8::SetTrackConfig and IDirectMusicSegmentState8::SetTrackConfig methods, an application can modify the behavior of any track in a segment. Configuration options include the following:

  • Enable or disable playback.
  • Enable or disable parameter calls on a track in a control segment.
  • Enable or disable notifications.
  • Override notifications in a primary segment with notifications from a secondary control segment.
  • Enable or disable track composition.
  • Control the start point of track data used in composing transitions.

For a list of the track configuration flags and a table of the flags valid on standard tracks, see IDirectMusicSegmentState8::SetTrackConfig.

Two of the configuration flags, DMUS_TRACKCONFIG_CONTROL_PLAY and DMUS_TRACKCONFIG_CONTROL_NOTIFICATION, extend the powers of secondary control segments. Normally, a secondary control segment manages only parameters that are obtained by the performance through calls to IDirectMusicTrack8::GetParam. Like any segment, the control segment can also make changes to the performance by sending messages. For example, it might change the volume of the performance. Such changes might appear to be overriding parameters in the primary segment, but they differ from true control changes in two ways:

  • They are valid only until a similar change is made by another segment. Control segment parameters cannot be overridden by other segments.
  • As long as they are not overridden, they remain valid even after the sending segment has finished playing. Control segment parameters are valid only until another segment becomes the control segment.

When the DMUS_TRACKCONFIG_CONTROL_PLAY or DMUS_TRACKCONFIG_CONTROL_NOTIFICATION flag is set on a track, the equivalent track on the primary segment is disabled. It is enabled again when the controlling segment stops.

The SetTrackConfig method is available on the IDirectMusicSegmentState8 interface as well as on IDirectMusicSegment8. The parameters are identical, but the effect differs as follows:

  • If you change a flag on a segment, subsequent instances of playing segment states inherit the changed flags. However, segment states that are already playing do not change their behavior.
  • If you change a flag on a segment state, the behavior changes only for that segment state. To ensure that the behavior changes immediately rather than after prepare time, you can call IDirectMusicPerformance8::Invalidate.

The following example code disables a chord progression track in the segment addressed by pSegment. Chord progressions are broadcast as control segment parameters, so the track is disabled by turning off the DMUS_TRACKCONFIG_CONTROL_ENABLED flag.

HRESULT hr = pSegment->SetTrackConfig(CLSID_DirectMusicChordTrack,
    -1, DMUS_SEG_ALLTRACKS, 0, DMUS_TRACKCONFIG_CONTROL_ENABLED);

The next example does the opposite, enabling all chord tracks to play:

hr = pSegment->SetTrackConfig(CLSID_DirectMusicChordTrack,
    -1, DMUS_SEG_ALLTRACKS, DMUS_TRACKCONFIG_CONTROL_ENABLED, 0);

See Also

  • Track Composition
  • Control Segments
  • Self-Controlling Segments


Using DirectMusic Messages

Data passes through the DirectMusic performance and to the synthesizer in the form of messages. For the most part, messages are created and processed behind the scenes, and your application might never have to work directly with them. However, a basic knowledge of messages can help you understand how DirectMusic works, and a more thorough understanding will enable you to use messages for greater control over the performance.

DirectMusic uses two different kinds of messages:

  • Performance messages. All sequenced data passes through the performance engine in this form. These messages contain detailed information about timing and routing of the data.
  • Standard MIDI messages. These can be read from a MIDI file or device and either passed directly (thrued) to another device or converted to performance message format when played by the performance.

Applications don't deal directly with MIDI messages. When a segment is played, all its data is in the form of performance messages and stays that way until it reaches the final output tool, which converts it to MIDI message format before sequencing it to the synthesizer. However, some performance messages contain information similar to that in standard MIDI messages. To help you understand such messages, this section describes some aspects of the MIDI message format.

Note The DMUS_MIDI_PMSG structure contains data equivalent to that in any standard MIDI message. However, it is used in performance messages.

Most performance messages are sent by a segment's tracks as the segment is playing. Applications can also send messages to do things like setting a MIDI controller, playing a single note, or changing the tempo.

Once a message has been sent, the application cannot retrieve or alter it except by implementing a tool. For example, a segment authored in DirectMusic Producer might contain a lyrics track that generates DMUS_LYRIC_PMSG messages. The only way an application can display the lyrics is by implementing a tool designed for that purpose. For more information, see DirectMusic Tools.

Notifications are an exception to the rule that messages can be intercepted only by tools. The IDirectMusicPerformance8::GetNotificationPMsg method enables the application to retrieve DMUS_NOTIFICATION_PMSG messages.

The following topics discuss messages and how they are routed:

  • Channels
  • Message Creation and Delivery
  • Application-Created Messages
  • Performance Message Types
  • Curves
  • MIDI Messages

See Also

  • Overview of Audio Data Flow
  • Notification and Event Handling


Channels

A channel is a destination for messages that are specific to one or more parts. A part might contain notes for a single instrument, or it might contain one or more waveforms.

Under the MIDI 1.0 standard, there are 16 MIDI channels, meaning that no more than 16 instruments can be playing at one time. To make more channels available to applications, DirectMusic creates channel groups. Up to 65,536 channel groups can exist at one time, each containing 16 channels, for a total of over one million channels. A port can be assigned any number of channel groups, up to its capability to support them. MIDI hardware ports have only a single channel group.

System-exclusive messages address all 16 channels within a channel group, but not other channel groups.

Every part in a DirectMusic performance plays on a performance channel, sometimes called a PChannel. The performance channel represents a particular MIDI channel in a particular group on a particular port. When a band is selected by a performance, each instrument in that band is mapped to a performance channel, so the part on that channel will play on that instrument.

When audiopaths are being used, identical performance channels on different audiopaths are mapped to different output channels.

Channel Priority

The number of notes that can be played simultaneously is limited by the number of voices available on the port. A voice is a set of resources dedicated to the synthesis of a single note or waveform being played on a channel. In the event that more notes are playing than there are available voices, one or more notes must be suppressed by the synthesizer. The choice is determined by the priority of the voice currently playing the note, which is based on the priority of the channel. By default, channels are ranked according to their index value, except that channel 10, the MIDI percussion channel, is ranked highest.

Applications and synthesizers can set their own channel priorities.

See Also

  • DMUS_CHANNEL_PRIORITY_PMSG
  • IDirectMusicPort8::GetChannelPriority


Message Creation and Delivery

When a segment is played, most of its tracks generate messages containing data about events that are scheduled to take place during playback. For more information, see DirectMusic Tracks.

A few tracks send more than one kind of message. For example, a style track sends note messages and time signature messages. In such cases, an application can disable certain kinds of messages in the track. For more information, see Disabling and Enabling Track Parameters.

The performance engine determines when each message is to be processed in clock time. In the case of channel messages, the performance also determines which performance channel gets the message. This information, along with other data—including the message type, its source track, and pointers to the first toolgraph and tool that are to receive it—is stored in the message structure.

Certain messages, such as tempo and time signature changes, are immediately processed and freed by the performance. Other messages, such as notes and patch changes, are placed in a queue and processed in order of time stamp.

Note There is no guarantee that messages with the same time stamp will be processed in any particular order.

Time signature messages are purely informational. The time signature is built into the segment and cannot be changed.

Messages are first sent to any tools in the segment toolgraph, then to the audiopath toolgraph, and finally to the performance toolgraph. Audiopath toolgraphs are optional components of audiopath configurations in DirectMusic Producer files. The application doesn't need to do anything to implement an audiopath toolgraph after creating the audiopath.

The first tool in a toolgraph processes the message and then, if it wants to pass it on, has the toolgraph stamp the message with a pointer to the next tool. The toolgraph also flags the message with a delivery type that determines when the message is delivered to the next tool. This flag is based on what delivery type the tool is expecting, as follows:

  • If the message is flagged as DMUS_PMSGF_TOOL_IMMEDIATE, it is delivered to the next tool immediately.
  • If it is flagged as DMUS_PMSGF_TOOL_QUEUE, the message is delivered just before the time at which it is supposed to play, taking latency into account. (See Latency and Bumper Time.)
  • If it is flagged as DMUS_PMSGF_TOOL_ATTIME, it is delivered at exactly the time at which it is to be processed. Notification messages are given this flag, because there is little or no latency involved in processing a notification.

The current tool can change the delivery type after the toolgraph has finished stamping and flagging the message.

Finally, the message arrives at the DirectMusic output tool, which converts all the data it receives into standard MIDI messages and delivers these to the synthesizer through the port buffer.

See Also

  • Overview of Audio Data Flow
  • DirectMusic Tools


Application-Created Messages

Most messages are generated by tracks, but applications can place messages in the queue directly. You might do this, for example, to change the tempo or to play a sound effect as a note on a DLS instrument.

When a performance has multiple audiopaths, DirectMusic may not be able to route application-created messages correctly, because a new message contains no information about what audiopath it belongs to. Even a channel-specific message might belong to a performance channel that is mapped to different audiopaths in different segments.

To ensure that a message is sent to a particular audiopath, first obtain the toolgraph for a segment or audiopath by calling IDirectMusicSegmentState8::GetObjectInPath or IDirectMusicAudioPath8::GetObjectInPath, retrieving the IDirectMusicGraph8 interface from the DMUS_PATH_AUDIOPATH_GRAPH or DMUS_PATH_SEGMENT_GRAPH stage in the audiopath. Then pass the message to IDirectMusicGraph8::StampPMsg.

See Also

  • IDirectMusicPerformance8::SendPMsg


Performance Message Types

Messages are stored in various structures derived from DMUS_PMSG. Because the C programming language does not support inheritance, the members of DMUS_PMSG are included in the declaration for each message type as the DMUS_PMSG_PART macro. These members contain data common to all messages, including the type of the message, time stamps, the performance channel to which the message is directed, and what toolgraph and tool are next in line to process the message. The other members contain data unique to the message type.

The following standard message structures are defined.

Structure | Content
DMUS_PMSG | Simple message with no additional parameters.
DMUS_CHANNEL_PRIORITY_PMSG | Channel priority change. See Channels.
DMUS_CURVE_PMSG | Curve.
DMUS_LYRIC_PMSG | Text.
DMUS_MIDI_PMSG | Any MIDI message that does not have a unique message type—for example, a control change.
DMUS_NOTE_PMSG | Music note. MIDI note-on and note-off messages are combined in this structure, which specifies the duration of the note.
DMUS_NOTIFICATION_PMSG | Notification. See Notification and Event Handling.
DMUS_PATCH_PMSG | MIDI patch change.
DMUS_SYSEX_PMSG | MIDI system exclusive message.
DMUS_TEMPO_PMSG | Tempo change.
DMUS_TIMESIG_PMSG | Time signature change.
DMUS_TRANSPOSE_PMSG | Transposition.
DMUS_WAVE_PMSG | Waveform playback.


Curves

A curve is a series of MIDI controller changes bringing about a smooth transition from one value to another—for example, volume fade-out or fade-in.

You can execute a curve by sending a single performance message of type DMUS_CURVE_PMSG. This structure enables you to set the start and end values, the duration of the curve, and the shape of the curve. Optionally, you can also set a reset value, which is the value to which the controller will return in case of an invalidation.

The wMeasure, nOffset, bBeat, bGrid, and mtOriginalStart members of the message structure are for information only, and do not affect the timing of the message. They are set in messages sent by DirectMusic Producer segments, and can be used by tools. Applications can normally set these members to 0.

The wMergeIndex member is used to determine whether changes are cumulative or overriding. Two curve messages with different merge indexes are cumulative; otherwise, each message in turn overrides settings made by a previous message.

The bCCData member contains the MIDI controller number for controller changes, and is otherwise ignored. For information on controller numbers, see the MIDI specification.

The following example function causes the volume to fade from its current value to zero over five seconds. If an invalidation occurs during that period, which might happen if another segment replaces the currently playing segment, full volume is restored.

HRESULT SendCurveMsg(IDirectMusicPerformance8* pPerf)
{
  DMUS_CURVE_PMSG *pCurveMsg;
  HRESULT hr;

  if (NULL == pPerf) return E_INVALIDARG;
  hr = pPerf->AllocPMsg(sizeof(DMUS_CURVE_PMSG),
      (DMUS_PMSG**) &pCurveMsg);
  if (SUCCEEDED(hr))
  {
    ZeroMemory(pCurveMsg, sizeof(DMUS_CURVE_PMSG));
    pCurveMsg->dwSize = sizeof(DMUS_CURVE_PMSG);
    pCurveMsg->rtTime = 0;
    pCurveMsg->dwFlags = DMUS_PMSGF_DX8 | DMUS_PMSGF_REFTIME
                         | DMUS_PMSGF_LOCKTOREFTIME;
    pCurveMsg->dwPChannel = DMUS_PCHANNEL_BROADCAST_PERFORMANCE;
    pCurveMsg->dwType = DMUS_PMSGT_CURVE;
    pCurveMsg->dwGroupID = 0xFFFFFFF;
    pCurveMsg->mtDuration = 5000;
    pCurveMsg->nEndValue = 0;
    pCurveMsg->bCurveShape = DMUS_CURVES_LINEAR;
    pCurveMsg->bCCData = 7;
    pCurveMsg->bFlags = DMUS_CURVE_RESET | DMUS_CURVE_START_FROM_CURRENT;
    pCurveMsg->bType = DMUS_CURVET_CCCURVE ;
    pCurveMsg->mtResetDuration = 0;
    pCurveMsg->nResetValue = 127;
    hr = pPerf->SendPMsg((DMUS_PMSG*) pCurveMsg);
  }
  return hr;
}

Note A simpler way to implement volume fading is by using IDirectMusicAudioPath8::SetVolume. This method always uses the linear shape for the curve.


MIDI Messages

Most applications don't deal directly with MIDI messages. However, an application can send a MIDI command as a performance message—for example, to make a control change.

MIDI messages consist of a status byte and usually one or two data bytes. System exclusive MIDI messages are of variable length.

The status byte indicates the type of message and, in some cases, the channel that is to receive the message. When several events of the same kind are in sequence in the file, the status byte can be omitted. Data bytes are recognizable because the high bit is always clear, whereas in status bytes it is always set.

The timing of MIDI events is controlled by a number before each message, indicating how many ticks separate this event from the last. The actual duration of a tick depends on the time format in the file header.

Note There is no guarantee that MIDI messages will be processed in the same order in which they occur in the source data. DirectMusic messages are delivered in order of time stamp, and two MIDI messages with identical times might not be delivered in the expected order. Care must be taken, in authoring MIDI content, to leave an interval between events if they must take place sequentially. For example, don't place a program change at the same time as a note that depends on the program change.

MIDI messages are divided into two main categories:

  • MIDI Channel Messages
  • MIDI System Messages


MIDI Channel Messages

A channel message is addressed to a particular MIDI channel, which corresponds to a part in the music.

A channel message can be either a mode message or a voice message.

A mode message specifies how the channel is to respond to subsequent voice messages. For example, a mode message might instruct the channel to remain silent, ignoring all note-on messages.

A voice message instructs the channel to begin or stop playing a note or to modify notes in some way. Most channel messages are voice messages.

The following table describes types of voice messages.

Voice message | Command
Note-on | Play a note.
Note-off | Stop playing the note.
Control change | Modify the tone with data from a pedal, lever, or other device; also used for miscellaneous controls such as volume and bank select.
Program (patch) change | Select an instrument for the channel by assigning a patch number.
Aftertouch | Modify an individual note, or all notes on the channel, according to the aftertouch of a key.
Pitch bend change | Modify the pitch of all notes played on the channel.

Keep in mind that these descriptions apply to standard MIDI messages, not MIDI data that has been converted to performance message format. For example, two MIDI messages to start and stop a note are combined by DirectMusic into a single performance message that specifies the duration of the note. Performance messages also contain additional information about timing and routing.

The following topics contain more information about MIDI channel messages and how they are implemented in DirectMusic:

  • MIDI Notes
  • Program Changes
  • Bank Selection
  • DirectMusic Patch Numbers


MIDI Notes

The data bytes of a note-on message represent the pitch and velocity. In most cases, a pitch value of 0 represents C below subcontra C (called C0 in MIDI notation), 12 represents subcontra C (or C1), 60 is middle C (or C5), and so on. For drum kits, the data byte instead represents a particular drum sound. For example, as long as the General MIDI (GM) percussion key map is being adhered to, a value of 60 represents a high bongo sound. Channel 10 is reserved for drum kits.

For information on how DirectMusic converts to and from MIDI notes, see Music Values and MIDI Notes.


Program Changes

Program changes and patch numbers are a key concept in MIDI playback and in DirectMusic. A program change assigns a particular instrument (also called a program or timbre) to a channel so that the notes sent to that channel are played with the appropriate sound. Instruments are identified by patch numbers. If the GM instrument set is loaded, a program change specifying patch number 1 always causes the channel to play its notes as an acoustic grand piano. The actual sound produced at the speakers depends on how the instrument is synthesized.


Bank Selection

Because a single data byte is used to select the patch number in a program change, and only seven bits in each data byte of a MIDI message are significant, a program change can select from a maximum of 128 instruments. To provide a greater choice, the MIDI specification allows for the use of up to 16,384 instrument banks, each containing up to 128 instruments.

To select an instrument from a different bank, the MIDI sequencer must first send a control change message called bank select. The two data bytes of this message are referred to as the most significant byte (MSB) and least significant byte (LSB), and they are combined to identify a bank. Once the bank has been selected, each subsequent program change selects an instrument from that bank.


DirectMusic Patch Numbers

In DirectMusic, the instrument patch number is not the seven-bit MIDI patch number but a 32-bit value that packs the MIDI patch number together with the MSB and LSB of the bank select and a one-bit flag for a drum kit. This extended patch number is returned by the IDirectMusicCollection8::EnumInstrument, IDirectMusicCollection8::GetInstrument, and IDirectMusicInstrument8::GetPatch methods. It can be changed for an instrument by using the IDirectMusicInstrument8::SetPatch method.

The organization of DirectMusic patch values is shown in the following table.

Bits | Purpose
0-7 | MIDI patch number (bit 7 is always 0)
8-15 | LSB bank select (bit 15 is always 0)
16-23 | MSB bank select (bit 23 is always 0)
24-30 | Unused
31 | Flag for drum kit


MIDI System Messages

System messages are not exclusive to any channel. There are three kinds, as shown in the following table.

Message type | Purpose
System common | Miscellaneous commands and data
System exclusive | Equipment-specific commands and data
System real-time | Synchronization of clock-based MIDI equipment

Unlike other MIDI messages, system exclusive messages can contain any number of data bytes. After transmitting the data, the sequencer sends a system common message called an EOX, which signals the end of the system exclusive message.

In DirectMusic, the DMUS_SYSEX_PMSG structure contains the length of the data and a pointer to an array of data bytes.


Using DirectMusic Ports

This section covers access to DirectMusic ports, which is usually required only by applications that do not use audiopaths. A port is a device that sends or receives data. It can correspond to a hardware device, a software synthesizer, or a software filter.

Each port in a DirectMusic application is represented by an IDirectMusicPort8 interface. Methods of this interface are used to retrieve information about the device, manage the memory on the device, download and unload DLS instruments, read incoming data, and cue playback buffers.

If your application initializes the performance by using IDirectMusicPerformance8::InitAudio, as is recommended, the audiopath manages ports and the mapping of performance channels to ports. You can obtain an interface to a port in the audiopath by using the IDirectMusicPerformance8::PChannelInfo method.

Every performance must have at least one port. If you want to use a port other than the default port, or to set special parameters for the default port, first set up a DMUS_PORTPARAMS8 structure. You don't have to fill in all members, but you must let DirectMusic know which members have valid information by putting the appropriate flags in the dwValidParams member. Then pass the structure to the IDirectMusic8::CreatePort method.

The following example function demonstrates how an object might be created for the default port, setting five channel groups on the port.

HRESULT CreateTypicalPort(IDirectMusic8* pDM)
{
  IDirectMusicPort8*  pPort;
  DMUS_PORTPARAMS  dmos;

  if (NULL == pDM) return E_INVALIDARG;
  ZeroMemory(&dmos, sizeof(DMUS_PORTPARAMS));
  dmos.dwSize = sizeof(DMUS_PORTPARAMS);
  dmos.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
  dmos.dwChannelGroups = 5;
  return pDM->CreatePort(GUID_NULL, &dmos, &pPort, NULL);
}

After creating a port, you must activate it by calling IDirectMusic8::Activate or IDirectMusicPort8::Activate and then attach it to the performance by using the IDirectMusicPerformance8::AddPort method.

When you add a port to a performance, assign a block of performance channels to it by calling the IDirectMusicPerformance8::AssignPChannelBlock method. The only time this isn't necessary is when you add the default port by passing NULL to IDirectMusicPerformance8::AddPort. In that case, PChannels 0 through 15 are assigned to the MIDI channels in the first group on the port.

You can map PChannels differently, add more PChannels, or assign PChannels to a different port by using the IDirectMusicPerformance8::AssignPChannelBlock and IDirectMusicPerformance8::AssignPChannel methods.

More information about ports is contained in the following topics:

  • Default Port
  • Property Sets for DirectMusic Ports


Default Port

Under versions of Windows 98 prior to Windows 98 Second Edition, and always when hardware that supports DLS is not available, the Microsoft software synthesizer is the default port. Under other versions of Windows, a hardware synthesizer could be the default port.

If you want your application to use the default port, you don't have to call the IDirectMusic8::CreatePort method before adding the port to the performance. Instead, you can pass NULL to IDirectMusicPerformance8::AddPort.

You can obtain the default port by a call to IDirectMusic8::GetDefaultPort, and then check its capabilities by using the IDirectMusicPort8::GetCaps method. If the port does not meet the needs of your application, use the IDirectMusic8::EnumPort method to find the Microsoft software synthesizer or another port.


Custom Loading

It might happen that an application needs to manage object loading itself—for example, because all objects are stored in a special compressed content file. The application can create its own loader in the form of an object that supports the IDirectMusicLoader8 interface, with at least the GetObject method implemented. This implementation of the loader must also create its own stream object that has both the IStream and the IDirectMusicGetLoader8 interfaces.

When GetObject receives a request to load an object from a file or resource, it creates a stream and passes the IStream pointer to the object's IPersistStream::Load method. When it receives a request to load an object from an existing stream created by the application to manage reading from a custom file, it creates a copy of the IStream with the same seek pointer and passes this copy to Load.

The stream object's implementation of IDirectMusicGetLoader8::GetLoader is used by loadable objects to retrieve a pointer to the loader that created the IStream. Objects need this pointer in order to call GetObject recursively when they find references to other objects. For example, a segment object might contain references to WAV files, which must be loaded along with the segment.

To support container objects, the loader must also implement the IDirectMusicLoader8::SetObject method. The implementation retains all information in the supplied DMUS_OBJECTDESC structure, copying the stream pointer if necessary. It then creates the object and calls IDirectMusicObject8::ParseDescriptor to obtain the rest of the object's descriptive information. However, the loader should not actually load the object until GetObject is called. If only containers with embedded objects need to be handled, only the case where DMUS_OBJ_STREAM is set needs to be implemented.

For more information, see Custom Loading in DirectMusic at msdn.microsoft.com.


Using Instrument Collections

In most applications, DLS instrument data is associated with bands and is downloaded to the synthesizer when the band is downloaded. For more information, see Using Bands.

For specialized DirectMusic applications that do their own DLS management, two steps must be taken: loading the instrument collection and downloading instrument data to a port.

These steps are covered in the following sections:

  • Loading and Downloading Collections
  • Working with Instruments


Loading and Downloading Collections

Collections are loaded like other objects. To load the standard Roland GM/GS set, pass GUID_DefaultGMCollection to the loader in the guidObject member of the DMUS_OBJECTDESC structure. If you intend to use the loader to access this object more than once, make sure that caching is enabled (as it is by default) so that you don't create another copy of the GM collection each time you request it.

The following example function illustrates how to load a collection identified by its GUID:

HRESULT myGetGMCollection(
    IDirectMusicLoader8 *pLoader,
    IDirectMusicCollection8 **ppCollection)
{
  HRESULT hr;
  DMUS_OBJECTDESC desc;

  if ((NULL == pLoader) || (NULL == ppCollection)) return E_INVALIDARG;
  desc.dwSize = sizeof(DMUS_OBJECTDESC);
  desc.guidClass = CLSID_DirectMusicCollection;
  desc.guidObject = GUID_DefaultGMCollection;
  desc.dwValidData = (DMUS_OBJ_CLASS | DMUS_OBJ_OBJECT);
  hr = pLoader->GetObject(&desc, IID_IDirectMusicCollection8,
          (void **) ppCollection);
  return hr;
}

When you have obtained a pointer to the IDirectMusicCollection8 interface, you have access to all the instruments in the collection. At this point, though, none of them have been downloaded to a port.

To download an entire collection at once, you must associate the collection with a segment and then call the IDirectMusicSegment8::Download method. For an example, see Playing a MIDI File with Custom Instruments.

These steps are necessary only when you want to use a collection other than the default one. Normally, when you call IDirectMusicSegment8::Download, the instruments downloaded to the port are from the default collection authored into the segment, or from the General MIDI set if the segment does not reference a collection. When you download a band, all DLS data needed by the instruments in that band is downloaded.

See Also

  • Loading Audio Data
  • Using Bands


Working with Instruments

When a collection object is created and loaded from a collection file or resource, it is not bound to any specific port. You can download different instruments to different ports or download a single instrument to multiple ports.

You can retrieve the patch number and name of all the available instruments by using the IDirectMusicCollection8::EnumInstrument method.

The following example function enumerates all instruments in a collection:

void ListInstruments(IDirectMusicCollection8 *pCollection)
{
  HRESULT hr = S_OK;
  DWORD dwPatch;
  WCHAR wszName[MAX_PATH];
  DWORD dwIndex;

  for (dwIndex = 0; hr == S_OK; dwIndex++)
  {
    hr = pCollection->EnumInstrument(
      dwIndex, &dwPatch, wszName, MAX_PATH);
    if (hr == S_OK)
    {
      // Do something with name of patch in wszName.
    }
  }
}

Obtain a pointer to a specific instrument by passing its patch number to the IDirectMusicCollection8::GetInstrument method.

After obtaining an instrument, you can change its patch number by using the IDirectMusicInstrument8::SetPatch method.

To download a single instrument to a port, pass an IDirectMusicInstrument8 interface pointer to the IDirectMusicPort8::DownloadInstrument or IDirectMusicPerformance8::DownloadInstrument method. This call makes the DLS data available on the port; it does not associate the instrument with any particular performance or audiopath.

To save memory, only waveforms and articulation required for given ranges of notes are downloaded. For example, for a bassoon you might specify that only data for the note range from low C through middle B is to be downloaded. Data for regions falling entirely outside that range is not downloaded.

The following code example, given a collection, a patch number, a port, and a range of notes, retrieves the instrument from the collection and downloads it. It sets up an array of one DMUS_NOTERANGE structure and passes this to the IDirectMusicPort8::DownloadInstrument method. Typically, only a single range of notes is specified, but it is possible to specify multiple ranges. If you pass NULL instead of an array, the data for all regions is downloaded.

HRESULT DownloadCollection(
    IDirectMusicCollection8 *pCollection,
    IDirectMusicPort8 *pPort,
    IDirectMusicDownloadedInstrument8 **ppDLInstrument,
    DWORD dwPatch,
    DWORD dwLowNote,
    DWORD dwHighNote)
 {
  HRESULT hr;
  if ((NULL == pCollection) || (NULL == pPort) || (NULL == ppDLInstrument))
  {
    return E_INVALIDARG;
  }
  IDirectMusicInstrument8* pInstrument;
  hr = pCollection->GetInstrument(dwPatch, &pInstrument);
  if (SUCCEEDED(hr))
  {
    DMUS_NOTERANGE NoteRange[1];
    NoteRange[0].dwLowNote = dwLowNote;
    NoteRange[0].dwHighNote = dwHighNote;
    hr = pPort->DownloadInstrument(pInstrument, ppDLInstrument, NoteRange, 1);
    pInstrument->Release();
  }
  return hr;
}

The DownloadInstrument method returns a pointer to the IDirectMusicDownloadedInstrument8 interface. This pointer has just one purpose: to identify the instrument in a subsequent call to the IDirectMusicPort8::UnloadInstrument method, which unloads the instance of the instrument on a particular port.

The following function downloads an instrument and then unloads it, which is not useful except to illustrate how the IDirectMusicDownloadedInstrument8 pointer can be used:

HRESULT DownloadAndUnload(
    IDirectMusicInstrument8* pInstrument,
    IDirectMusicPort8 *pPort)
{
  HRESULT hr;
  IDirectMusicDownloadedInstrument* pDLInstrument;

  if ((NULL == pInstrument) || (NULL == pPort)) return E_INVALIDARG;
  hr = pPort->DownloadInstrument(pInstrument, &pDLInstrument, NULL, 0);
  if (SUCCEEDED(hr))
  {
    hr = pPort->UnloadInstrument(pDLInstrument);
    pDLInstrument->Release();
  }
  return hr;
}


Low-Level DLS

If you are writing an application that edits DLS collections or creates instruments from waveform samples at run time, you must be able to download instrument data to the synthesizer without encapsulating it in a DirectMusic instrument object.

Working with DLS data requires knowledge of the DLS specification and file structure. For detailed information on these topics, contact the MIDI Manufacturers Association.

To download raw instrument data, first get a pointer to the IDirectMusicPortDownload8 interface, as shown in the following code example, where it is assumed that pIPort is a valid pointer to an IDirectMusicPort8 interface:

IDirectMusicPortDownload **ppIDownloadPort;

HRESULT hr = pIPort->QueryInterface(IID_IDirectMusicPortDownload8,
    (void **) ppIDownloadPort);

If the HRESULT is not S_OK, the port does not support DLS downloading.

Next, identify the buffers that must be prepared and downloaded. To send an instrument to the synthesizer, you will create the following buffers:

  • One instrument buffer, which represents the entire instrument definition with all the regions and articulations.
  • One or more waveform buffers, which describe each waveform that the instrument references for its regions.

Each buffer must be tagged with a unique identifier. Identifiers are used to resolve linkages between buffers, in particular the links between regions and waveforms. Tally the number of buffers that you need to download, and call IDirectMusicPortDownload8::GetDLId to allocate a range of identifiers. For example, if you are downloading an instrument with three waveforms, you must download four buffers in all, so request a set of four identifiers.

For each buffer, calculate the size needed, then call IDirectMusicPortDownload8::AllocateBuffer to allocate it. This method returns an IDirectMusicDownload8 interface representing the buffer. Call IDirectMusicDownload8::GetBuffer to access the memory.

Note There are two methods called GetBuffer:

  • IDirectMusicPortDownload8::GetBuffer returns an IDirectMusicDownload interface pointer for a buffer object whose download identifier is known.
  • IDirectMusicDownload::GetBuffer returns a pointer to the memory in the buffer.

Now write the data into the buffers. Each buffer starts with a DMUS_DOWNLOADINFO structure, which defines the size and functionality of the download. This structure must be prepared as follows:

  • Set the dwDLType member to either DMUS_DOWNLOADINFO_INSTRUMENT2 for an instrument or DMUS_DOWNLOADINFO_WAVE for a waveform.
  • Set the dwDLId member to one of the unique identifiers that you obtained by using IDirectMusicPortDownload::GetDLId.
  • Set the dwNumOffsetTableEntries member to the number of entries in the DMUS_OFFSETTABLE structure.
  • Set the cbSize member to the size of the download chunk, including DMUS_DOWNLOADINFO and DMUS_OFFSETTABLE.

The DMUS_DOWNLOADINFO structure is always followed by a DMUS_OFFSETTABLE structure. This offset table is used to manage all links within the data. Whenever a structure in the data refers to another structure, it addresses it with an integer index instead of a pointer. For every structure within the data that can be referenced, there is a unique index. The DMUS_OFFSETTABLE translates this integer index into a byte offset into the data.

The instrument or WAV data follows the DMUS_OFFSETTABLE. If the download is an instrument, the data starts with the DMUS_INSTRUMENT structure. Otherwise, it starts with the DMUS_WAVE structure.

The instrument data that follows the DMUS_INSTRUMENT structure is organized in the following structures:

  • DMUS_ARTICPARAMS
  • DMUS_ARTICULATION
  • DMUS_ARTICULATION2
  • DMUS_COPYRIGHT
  • DMUS_EXTENSIONCHUNK
  • DMUS_INSTRUMENT
  • DMUS_NOTERANGE
  • DMUS_REGION

The WAV data pointed to by the DMUS_WAVE structure is organized in a DMUS_WAVEDATA structure.

When the buffers are all ready, download them by using IDirectMusicPortDownload8::Download. Download the waveform buffers first so that they are in place and can be referenced when the instrument is downloaded.

Once the buffers have been downloaded, the synthesizer is ready to play the instrument. The memory in the buffer is no longer accessible.

Later, when done playing the instrument, unload the buffers and release them. First unload the instrument buffer, then all the waveform buffers. To unload, pass the IDirectMusicDownload8 pointers to IDirectMusicPortDownload8::Unload. Then release each buffer with a call to IDirectMusicDownload8::Release.

To update an instrument that has already been downloaded, you cannot write over the previously downloaded buffer. Instead, replace the instrument, but not the waveforms. To do this, call IDirectMusicPortDownload8::AllocateBuffer to allocate a new IDirectMusicDownload8 interface with a buffer of the correct size. Be sure to generate a new identifier for the buffer with a call to IDirectMusicPortDownload8::GetDLId. Write the new articulation information into the buffer; then download it. Then unload the previously downloaded buffer with a call to IDirectMusicPortDownload8::Unload.

To update a waveform buffer, take one extra step. Create both a new waveform buffer and an updated instrument buffer that references it. Download the new waveform, then the new instrument. Then unload the old instrument and the old waveform.

More information is contained in the following topic:

  • Creating DLS Instruments Programmatically


Creating DLS Instruments Programmatically

The following example code shows how to create a DLS instrument from a WAV file and make it available to the performance.

The entry point for the example is the PlayDLSFromWAV function, which creates and downloads the instrument and plays two notes on it by sending performance messages. This function uses two classes defined in the DirectX sample framework. The pWaveFile parameter is an instance of CWaveFile representing a WAV file that has already been opened. An instance of CMusicManager is used to create and initialize the performance. For more information on these classes, see CWaveFile Sample Class and CMusicManager Sample Class.

// Declare data structures for download.

#pragma pack(2)
struct INSTRUMENT_DOWNLOAD
{
    DMUS_DOWNLOADINFO   dlInfo;
    ULONG               ulOffsetTable[4];
    DMUS_INSTRUMENT     dmInstrument;
    DMUS_REGION         dmRegion;
    DMUS_ARTICULATION   dmArticulation;
    DMUS_ARTICPARAMS    dmArticParams;
};

struct WAVE_DOWNLOAD
{
    DMUS_DOWNLOADINFO   dlInfo;
    ULONG               ulOffsetTable[2];
    DMUS_WAVE           dmWave;
    DMUS_WAVEDATA       dmWaveData;
};

#pragma pack()

// Define some values for instrument parameters.

#define FIVE_HERTZ (0xFCACAE9C)
#define ZERO_SECONDS (0x80000000)
#define ONE_MILLISECOND (0xD1490F12)
#define ONE_HUNDRED_PERCENT (0x03E80000)

void InitializeInstDownload(INSTRUMENT_DOWNLOAD *pInstDownload, DWORD dwDLId, DWORD dwPatch, DWORD dwDLIdWave)
{
    ZeroMemory(pInstDownload, sizeof(INSTRUMENT_DOWNLOAD));
    pInstDownload->dlInfo.dwDLType = DMUS_DOWNLOADINFO_INSTRUMENT;
    pInstDownload->dlInfo.cbSize = sizeof(INSTRUMENT_DOWNLOAD);
    pInstDownload->dlInfo.dwDLId = dwDLId;
    pInstDownload->dlInfo.dwNumOffsetTableEntries = 4;
    pInstDownload->ulOffsetTable[0] = offsetof(INSTRUMENT_DOWNLOAD,dmInstrument);
    pInstDownload->ulOffsetTable[1] = offsetof(INSTRUMENT_DOWNLOAD,dmRegion);
    pInstDownload->ulOffsetTable[2] = offsetof(INSTRUMENT_DOWNLOAD,dmArticulation);
    pInstDownload->ulOffsetTable[3] = offsetof(INSTRUMENT_DOWNLOAD,dmArticParams);

    pInstDownload->dmInstrument.ulFirstRegionIdx = 1;
    pInstDownload->dmInstrument.ulGlobalArtIdx = 2;
    pInstDownload->dmInstrument.ulPatch = dwPatch;

    pInstDownload->dmRegion.RangeKey.usHigh = 127;
    pInstDownload->dmRegion.RangeVelocity.usHigh = 127;
    pInstDownload->dmRegion.fusOptions = F_RGN_OPTION_SELFNONEXCLUSIVE;
    pInstDownload->dmRegion.WaveLink.ulChannel = 1;
    pInstDownload->dmRegion.WaveLink.ulTableIndex = dwDLIdWave;
    pInstDownload->dmRegion.WaveLink.usPhaseGroup = 0;
    pInstDownload->dmRegion.WSMP.cbSize = sizeof(WSMPL);
    pInstDownload->dmRegion.WSMP.fulOptions = F_WSMP_NO_TRUNCATION;
    pInstDownload->dmRegion.WSMP.usUnityNote = 60; // Middle C
    pInstDownload->dmRegion.WLOOP[0].cbSize = sizeof(WLOOP);
    pInstDownload->dmRegion.WLOOP[0].ulType = WLOOP_TYPE_FORWARD;

    pInstDownload->dmArticulation.ulArt1Idx = 3;

    pInstDownload->dmArticParams.LFO.tcDelay = ZERO_SECONDS;
    pInstDownload->dmArticParams.LFO.pcFrequency = FIVE_HERTZ;
    pInstDownload->dmArticParams.PitchEG.tcAttack = ZERO_SECONDS;
    pInstDownload->dmArticParams.PitchEG.tcDecay = ZERO_SECONDS;
    pInstDownload->dmArticParams.PitchEG.ptSustain = ONE_HUNDRED_PERCENT;
    pInstDownload->dmArticParams.PitchEG.tcRelease = ONE_MILLISECOND;

    pInstDownload->dmArticParams.VolEG.tcAttack = ZERO_SECONDS;
    pInstDownload->dmArticParams.VolEG.tcDecay = ZERO_SECONDS;
    pInstDownload->dmArticParams.VolEG.ptSustain = ONE_HUNDRED_PERCENT;
    pInstDownload->dmArticParams.VolEG.tcRelease = ONE_MILLISECOND;
}

void InitializeWaveDownload(WAVE_DOWNLOAD *pWaveDownload, DWORD dwDLId, WAVEFORMATEX *pwfex, DWORD dwWaveSize, DWORD dwOverallSize)
{
    ZeroMemory(pWaveDownload,sizeof(WAVE_DOWNLOAD));
    pWaveDownload->dlInfo.dwDLType = DMUS_DOWNLOADINFO_WAVE;
    pWaveDownload->dlInfo.cbSize = dwOverallSize;
    pWaveDownload->dlInfo.dwDLId = dwDLId;
    pWaveDownload->dlInfo.dwNumOffsetTableEntries = 2;

    pWaveDownload->ulOffsetTable[0] = offsetof(WAVE_DOWNLOAD,dmWave);
    pWaveDownload->ulOffsetTable[1] = offsetof(WAVE_DOWNLOAD,dmWaveData);

    pWaveDownload->dmWave.ulWaveDataIdx = 1;

    memcpy(&pWaveDownload->dmWave.WaveformatEx, pwfex, sizeof(WAVEFORMATEX));

    pWaveDownload->dmWaveData.cbSize = dwWaveSize;
}

void PlayDLSFromWAV(HWND hWndMain, CWaveFile *pWaveFile)
{
    const DWORD dwPatch = 0x00123456;

    // Create and initialize performance.

    CMusicManager musicManager;
    IDirectMusicPerformance8* pPerf;
    HRESULT hr = musicManager.Initialize(hWndMain);
    pPerf = musicManager.GetPerformance();

    // Get interfaces to the port.

    IDirectMusicPort* pIDirectMusicPort = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pPerf->PChannelInfo(0, &pIDirectMusicPort, NULL, NULL);
    }

    IDirectMusicPortDownload8* pIDirectMusicPortDownload8 = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicPort->QueryInterface(IID_IDirectMusicPortDownload8, (void **)&pIDirectMusicPortDownload8);
    }

    // Reserve two download IDs, and retrieve the first.

    DWORD dwDLId = 0;
    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicPortDownload8->GetDLId(&dwDLId, 2);
    }

    // Allocate a buffer for the instrument data (regions, articulations, and so on.)

    IDirectMusicDownload8* pIDirectMusicDownloadArticulation = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicPortDownload8->AllocateBuffer( sizeof(INSTRUMENT_DOWNLOAD), &pIDirectMusicDownloadArticulation);
    }

    // Allocate a buffer for the WAV data.

    IDirectMusicDownload8* pIDirectMusicDownloadWave = NULL;
    DWORD dwAppend = 0;
    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicPortDownload8->GetAppend(&dwAppend);
        if (SUCCEEDED(hr))
        {
            hr = pIDirectMusicPortDownload8->AllocateBuffer(sizeof(WAVE_DOWNLOAD) +
                    dwAppend * pWaveFile->GetFormat()->nBlockAlign + pWaveFile->GetSize(),
                    &pIDirectMusicDownloadWave);
        }
    }

    // Read format data from the WAV file into the buffer, and download it to the port.

    void *pvData = NULL;
    DWORD dwSize = 0;
    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicDownloadWave->GetBuffer( &pvData, &dwSize );
        if (SUCCEEDED(hr))
        {
            InitializeWaveDownload((WAVE_DOWNLOAD*)pvData, dwDLId, pWaveFile->GetFormat(),
                    pWaveFile->GetSize(), dwSize);

            DWORD dwRead = 0;
            hr = pWaveFile->Read(((WAVE_DOWNLOAD*)pvData)->dmWaveData.byData,
                    pWaveFile->GetSize(), &dwRead);
            if (SUCCEEDED(hr) && pWaveFile->GetSize() == dwRead)
            {
                hr = pIDirectMusicPortDownload8->Download(pIDirectMusicDownloadWave);
                if (hr == DMUS_E_NOTMONO)
                {
                  MessageBox(hWndMain, "WAV must be mono.", "Error", 0);
                }
            }
        }
    }

    // Put instrument data into the buffer and download to the port.

    if (SUCCEEDED(hr))
    {
        hr = pIDirectMusicDownloadArticulation->GetBuffer( &pvData, &dwSize );
        if (SUCCEEDED(hr))
        {
            InitializeInstDownload((INSTRUMENT_DOWNLOAD *)pvData, dwDLId + 1, dwPatch, dwDLId);
            hr = pIDirectMusicPortDownload8->Download(pIDirectMusicDownloadArticulation);
        }
    }

    // Get the performance toolgraph so messages can be stamped.

    IDirectMusicGraph* pIDirectMusicGraph = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pPerf->QueryInterface(IID_IDirectMusicGraph, (void **)&pIDirectMusicGraph);
    }

    // Create and send a message to put the instrument on channel 0.

    DMUS_PATCH_PMSG *pDMUS_PATCH_PMSG = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pPerf->AllocPMsg( sizeof(DMUS_PATCH_PMSG), (DMUS_PMSG **)&pDMUS_PATCH_PMSG);
    }
    if (SUCCEEDED(hr))
    {
        pDMUS_PATCH_PMSG->dwType = DMUS_PMSGT_PATCH;
        pDMUS_PATCH_PMSG->dwPChannel = 0;
        pDMUS_PATCH_PMSG->dwFlags = DMUS_PMSGF_REFTIME ;
        pDMUS_PATCH_PMSG->byInstrument = dwPatch & 0x7F;
        pDMUS_PATCH_PMSG->byLSB = (dwPatch & 0x7f00) >> 8;
        pDMUS_PATCH_PMSG->byMSB = (dwPatch & 0x7f0000) >> 16;
        hr = pIDirectMusicGraph->StampPMsg((DMUS_PMSG *)pDMUS_PATCH_PMSG);
    }
    if (SUCCEEDED(hr))
    {
        hr = pPerf->SendPMsg((DMUS_PMSG *)pDMUS_PATCH_PMSG);
        if (FAILED(hr))
        {
            pPerf->FreePMsg((DMUS_PMSG *)pDMUS_PATCH_PMSG);
        }
    }

    // The instrument is now available to be played. The following code
    // plays two "notes" at different pitches and durations.

    DMUS_NOTE_PMSG *pDMUS_NOTE_PMSG = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pPerf->AllocPMsg( sizeof(DMUS_NOTE_PMSG), (DMUS_PMSG **)&pDMUS_NOTE_PMSG);
    }
    if (SUCCEEDED(hr))
    {
        pDMUS_NOTE_PMSG->dwType = DMUS_PMSGT_NOTE;
        pDMUS_NOTE_PMSG->dwPChannel = 0;
        pDMUS_NOTE_PMSG->dwFlags = DMUS_PMSGF_REFTIME;
        pDMUS_NOTE_PMSG->bFlags = DMUS_NOTEF_NOTEON;
        pDMUS_NOTE_PMSG->bVelocity = 127;
        pDMUS_NOTE_PMSG->bMidiValue = 60;
        pDMUS_NOTE_PMSG->mtDuration = DMUS_PPQ * 4; // Whole note
        hr = pIDirectMusicGraph->StampPMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG);
    }
    if (SUCCEEDED(hr))
    {
        hr = pPerf->SendPMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG);
        if (FAILED(hr))
        {
            pPerf->FreePMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG);
        }
    }

    Sleep(1000);

    DMUS_NOTE_PMSG *pDMUS_NOTE_PMSG2 = NULL;
    if (SUCCEEDED(hr))
    {
        hr = pPerf->AllocPMsg( sizeof(DMUS_NOTE_PMSG), (DMUS_PMSG **)&pDMUS_NOTE_PMSG2);
    }
    if (SUCCEEDED(hr))
    {
        pDMUS_NOTE_PMSG2->dwType = DMUS_PMSGT_NOTE;
        pDMUS_NOTE_PMSG2->dwPChannel = 0;
        pDMUS_NOTE_PMSG2->dwFlags = DMUS_PMSGF_REFTIME;
        pDMUS_NOTE_PMSG2->bFlags = DMUS_NOTEF_NOTEON;
        pDMUS_NOTE_PMSG2->bMidiValue = 70;
        pDMUS_NOTE_PMSG2->bVelocity = 127;
        pDMUS_NOTE_PMSG2->mtDuration = DMUS_PPQ * 2; // Half note
        hr = pIDirectMusicGraph->StampPMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG2);
    }
    if (SUCCEEDED(hr))
    {
        hr = pPerf->SendPMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG2);
        if (FAILED(hr))
        {
            pPerf->FreePMsg((DMUS_PMSG *)pDMUS_NOTE_PMSG2);
        }
    }

    // Allow time for second note to play before music manager goes out of scope
    // and shuts down performance.

    Sleep(4000);

    // Clean up. SAFE_RELEASE is defined in dmutil.h.

    SAFE_RELEASE(pIDirectMusicPort);
    SAFE_RELEASE(pIDirectMusicPortDownload8);
    SAFE_RELEASE(pIDirectMusicDownloadArticulation);
    SAFE_RELEASE(pIDirectMusicDownloadWave);
    SAFE_RELEASE(pIDirectMusicGraph);

}


DirectMusic Tools

A DirectMusic tool is an object that intercepts messages and handles them in some way. The tool might alter the message and then pass it on to the next tool, or free the message, or send a new message based on information in the old one.

DirectMusic has an output tool that is normally the last to receive messages. This tool converts performance messages to standard MIDI messages and streams them to the synthesizer. Other tools are implemented by the application or obtained from libraries.

The following topics provide more information on tools:

  • Creating a Tool
  • Implementing a Tool in the Client Application

See Also

  • Overview of Audio Data Flow


Creating a Tool

A tool object can reside in a DLL or in the client application. The object implements the methods of IDirectMusicTool or IDirectMusicTool8. The purpose of each method is summarized in the following table.

Method | Description
Init | Performs any needed initialization of the object. This method is called when the application adds the tool to a graph by calling IDirectMusicGraph8::InsertTool. It should always return S_OK.
GetMsgDeliveryType | Specifies when the performance should deliver messages to the tool by calling its ProcessPMsg method. Most tools can specify DMUS_PMSGF_TOOL_IMMEDIATE.
GetMediaTypes | Returns an array of message types that the tool processes. This method is called by the DirectMusic performance to determine which messages to pass to the ProcessPMsg method.
GetMediaTypeArraySize | Specifies the number of message types in the array.
ProcessPMsg | Processes each message. This method is called by the performance each time a message that matches the requested types is available. After processing, the method either requeues or deletes the message.
Flush | Specifies the behavior of the tool when it receives a message sent as a result of an invalidation. This can happen, for example, when a note or curve is in progress and the segment stops unexpectedly. Most tools can simply requeue the message.

When the performance engine is playing a segment, it enables each tool in the segment toolgraph, and then each tool in the performance toolgraph, to process each message. When a tool processes a message, it should obtain the IDirectMusicGraph8 pointer from the pGraph member of the DMUS_PMSG structure and then call the IDirectMusicGraph8::StampPMsg method to stamp the message with a pointer to the next tool, if any, that is to receive it.

The following sample code from the tool's implementation of IDirectMusicTool8::ProcessPMsg stamps the message (pPMsg) for the next tool, or frees the message if this is not possible.

if ((NULL == pPMsg->pGraph ) || (FAILED(pPMsg->pGraph->StampPMsg(pPMsg))))
{
    hr = DMUS_S_FREE;
}

It's important to stamp the message before reaching any code paths that might cause the method to return. If the message is not stamped for the next tool when it is handed back to the queue, it will be sent back to this tool, possibly resulting in an endless loop. On the other hand, be aware that StampPMsg can change the value in the dwPChannel member of the message structure. If your tool uses this value, save it before stamping the message.

Tools process messages in a high-priority thread. Do not call time-consuming functions, such as those involving graphics or file input/output, from within a tool's IDirectMusicTool8::ProcessPMsg method. If a tool needs to trigger an action, it should do so by signaling a different thread, perhaps the application's main thread.

When implementing the methods of IDirectMusicTool8, take care not to create circular references to parent objects. Circular references come about when one object creates another and the child keeps an additional reference to the parent. For example, suppose a tool creates a new reference to the toolgraph passed into its IDirectMusicTool8::Init method. If the tool fails to release this reference, there is a problem when the segment attempts to release the toolgraph. Because the tool still has a reference to the toolgraph, the toolgraph is not fully released; and because the toolgraph has a reference to the tool, the tool cannot be released either.

See Also

  • Music Tool Sample
  • DirectMusic Tool Wizard


Implementing a Tool in the Client Application

All tools other than the output tool are collected in toolgraphs. Even if your application is using only a single tool, you must create a toolgraph to contain it. Then add this toolgraph to a segment or the performance. Toolgraphs provide a convenient mechanism for directing messages from one tool to another.

Note Do not use or distribute tools from non-trusted sources. Tools can contain unsafe code.

The following sample code is from a client that uses a tool in a DLL. First, the client creates an object from a known class identifier and a known interface identifier. It then obtains the IDirectMusicTool8 interface, creates a graph, and inserts the tool in the graph. It is assumed that the ILyricsReader interface, together with the CLSID and IID, is declared in an included tool header.

HRESULT SetupLyricsTool(IDirectMusicPerformance8* pPerf)
{
  ILyricsReader* pLyricsReader;
  IDirectMusicTool* pTool;
  IDirectMusicGraph* pGraph;
  HRESULT hr;

  if (SUCCEEDED(hr = CoCreateInstance(CLSID_LyricsReader, NULL,
                CLSCTX_INPROC_SERVER, IID_ILyricsReader,
               (void **) &pLyricsReader)))
  {
    if (SUCCEEDED(hr = pLyricsReader->QueryInterface(IID_IDirectMusicTool8,
      (void**)&pTool)))
    {
      if ( SUCCEEDED(hr = CoCreateInstance( CLSID_DirectMusicGraph, NULL,
          CLSCTX_INPROC, IID_IDirectMusicGraph, (void**)&pGraph)))
      {
        if (SUCCEEDED(pGraph->InsertTool(pTool, NULL, 0, 0 )))
        {
          hr = pPerf->SetGraph(pGraph);
        }
        pGraph->Release();
      }
    }
  }
  return hr;
}

The tool will now process messages from all segments in the performance. To restrict the application of the tool to a particular segment, use IDirectMusicSegment8::SetGraph instead.


Property Sets for DirectMusic Ports

Through property sets, DirectMusic is able to support extended services offered by synthesizers.

Hardware vendors define new capabilities as properties and publish the specification for these properties. A GUID identifies a property set, and a ULONG identifies a particular property within the set. Individual properties may also have associated parameters. The meaning of the parameters is defined along with the properties.

Use the IKsControl::KsProperty method to find out whether a property is available and then to set and retrieve values for that property. You can obtain the IKsControl interface for a port by calling the IDirectMusicPort8::QueryInterface method, passing IID_IKsControl as the interface identifier.

A property set is represented by a GUID, and each item within the set is represented by a zero-based index. The meaning of the indexed items for a GUID never changes. For a list of the property sets supported by DirectMusic, see KSPROPERTY.

All property sets predefined by DirectMusic have only one item, usually at index 0. However, the full definition of kernel-streaming (KS) properties is supported, and vendors are free to create property sets with any number of items and instances, and data of any size.

Routing of the property item request to the port varies depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation over the Win32® handle-based multimedia calls (the midiOut and midiIn functions).

The following code example uses the IKsControl::KsProperty method to determine if the port supports General MIDI in hardware:

#include <dmksctrl.h>

BOOL IsGMSupported(IDirectMusicPort8 *pPort)
{
  HRESULT   hr;
  IKsControl  *pControl;
  KSPROPERTY  ksp;
  DWORD   dwFlags;
  ULONG   cb;
  BOOL    fIsSupported;

  hr = pPort->QueryInterface(IID_IKsControl, (void**)&pControl);
  if (FAILED(hr))
  {
    // Port does not support properties; assume no GM support.
    return FALSE;
  }
  ksp.Set = GUID_DMUS_PROP_GM_Hardware;
  ksp.Id  = 0;
  ksp.Flags = KSPROPERTY_TYPE_BASICSUPPORT;
  hr = pControl->KsProperty(&ksp, sizeof(ksp),
    &dwFlags, sizeof(dwFlags), &cb);
  fIsSupported = FALSE;
  if ((SUCCEEDED(hr)) || (cb >= sizeof(dwFlags)))
  {
    // Set is supported.
    fIsSupported = (BOOL)(dwFlags & KSPROPERTY_TYPE_GET);
  }
  pControl->Release();
  return fIsSupported;
}


Related Software

This section contains brief descriptions of software distributed with the DirectX SDK that can be used in the development of DirectMusic applications. The following software is described:

  • DirectMusic Producer
  • DirectMusic Style Library
  • DirectMusic Tool Wizard
  • Audio Effect DMO Wizard


DirectMusic Producer

Microsoft DirectMusic Producer is a powerful authoring application included with the DirectX SDK. Its enables composers and sound designers to create most elements of a dynamic soundtrack, including the following:

  • Audiopath configurations
  • Bands
  • Chordmaps
  • Downloadable Sounds collections
  • Scripts
  • Toolgraphs
  • Styles and style-based segments
  • MIDI-based segments
  • Waveform-based segments

For more information, see the DirectMusic Producer Help.


DirectMusic Style Library

The DirectX SDK includes many sample DirectMusic styles and an application, StylePlayer, that enables you to audition these styles with different chordmaps, bands, shapes, and motifs.

The style library and StylePlayer are found in the Essentials folder on the DirectX CD. To use them, copy the DirectMusic Style Library folder to your hard disk.

For more information, see the StylePlayer.txt file.


DirectMusic Tool Wizard

The DirectMusic Tool Wizard simplifies the task of creating a custom tool that can be inserted in DirectMusic Producer or in a DirectMusic application to intercept and process performance messages.

Microsoft Visual C++® 6.0 is required to run the wizard. Select New from the File menu, and then select DirectMusic Tool Wizard from the Projects tab of the New dialog box.

The wizard creates a ready-to-compile project containing C++ code that handles the basic COM component creation and DLL registration as well as the entry point for the DLL. In addition, the wizard generates the tool's implementation class with basic services already in place. After the project is created, you must add code that implements the tool's functionality.

For more information, see the Help for the wizard.


Audio Effect DMO Wizard

The Audio Effect DMO Wizard simplifies the task of creating a DirectX Media Object (DMO) that implements an audio effect. The audio effect DMO can be used in Microsoft DirectSound® applications, Microsoft DirectShow® applications, or in other custom application scenarios.

Microsoft Visual C++® 6.0 is required to run the wizard. Select New from the File menu, and then select Audio Effect DMO Wizard from the Projects tab of the New dialog box.

The wizard creates a Visual Studio® project and several C++ code and header files, which implement the framework for the DMO. After the project is created, you must add code that implements the audio effect.

For more information, see the Help for the wizard.


DirectMusic C++ Samples

The sample applications described in this section demonstrate the use and capabilities of the Microsoft® DirectMusic® application programming interface (API) in Microsoft® DirectX® for C++.

The following samples are found on the Start menu under Programs/Microsoft DirectX 9.0 SDK/C++ Samples/DirectMusic Samples.

  • 3D Audio Sample
  • Audio Path Sample
  • Audio Scripts Sample
  • AudioFX Sample
  • Cross Fade Sample
  • Music Tool Sample
  • Play Audio Sample
  • Play Motif Sample
  • Play Multi Sample

The source code is in the following folder, where SDK root is the installation folder for the DirectX SDK, such as C:\DXSDK:

(SDK root)\samples\C++\DirectMusic

In addition to these samples, the source files for tutorial applications are contained in the following folder:

(SDK root)\samples\C++\DirectMusic\Tutorials

For more information, see DirectMusic C++ Tutorials.

The samples other than the tutorials use common source files that implement functions and classes for basic DirectMusic and DirectSound functionality and for general tasks such as finding digital media files. For more information, see DirectMusic Sample Framework.


DirectMusic Sample Framework

The core functionality for the DirectMusic samples is in a common set of classes, declared in Dmutil.h and implemented in Dmutil.cpp. In addition, some of the samples make use of the DirectSound classes declared in Dsutil.h and implemented in Dsutil.cpp.

These files are found in the following folders:

(SDK root)\samples\C++\Common\Include
(SDK root)\samples\C++\Common\Src

To use the sample framework, your project must link to Dxerr9.lib and Winmm.lib

The framework classes provide basic functionality for the samples, and you can use them as a starting-point for your own applications. However, they are not intended to be a full-featured wrapper for the DirectMusic API.

The following classes are used in the samples:

Class | Description
CMusicManager Sample Class | Contains methods for loading and creating objects, creating the performance, and managing memory.
CMusicScript Sample Class | Represents a script, and contains methods for getting and setting variables and calling routines.
C3DMusicSegment Sample Class | Represents a segment playing on a 3-D audiopath. Inherits from CMusicSegment.
CMusicSegment Sample Class | Represents a segment, and contains methods for downloading and unloading instruments, playing and stopping the segment, and retrieving a style from the segment.

See Also

  • DirectMusic C++ Samples
  • DirectSound Sample Framework


CMusicManager Sample Class

The CMusicManager sample class contains methods for loading and creating objects, creating the performance, and managing memory.

class CMusicManager
{
protected:
    BOOL                      m_bCleanupCOM;
    IDirectMusicLoader8*      m_pLoader;
    IDirectMusicPerformance8* m_pPerformance;
    IDirectSound3DListener*   m_pDSListener;
    DS3DLISTENER              m_dsListenerParams;

public:
    CMusicManager();
    ~CMusicManager();

    inline IDirectMusicLoader8*  GetLoader()
        { return m_pLoader; }
    inline IDirectMusicPerformance8* GetPerformance()
        { return m_pPerformance; }
    inline IDirectSound3DListener*   GetListener()
        { return m_pDSListener; }
    IDirectMusicAudioPath8* GetDefaultAudioPath();
    HRESULT Initialize(HWND hWnd, DWORD dwPChannels = 128,
        DWORD dwDefaultPathType = DMUS_APATH_DYNAMIC_STEREO,
        LPDIRECTSOUND pDS = NULL);
    HRESULT SetSearchDirectory(const TCHAR* strMediaPath);
    VOID    CollectGarbage();
    VOID    StopAll();
    HRESULT CreateSegmentFromFile(CMusicSegment** ppSegment,
        TCHAR* strFileName, BOOL bDownloadNow = TRUE,
        BOOL bIsMidiFile = FALSE);
    HRESULT Create3DSegmentFromFile(C3DMusicSegment** ppSegment,
        TCHAR* strFileName, BOOL bDownloadNow = TRUE,
        BOOL bIsMidiFile = FALSE, IDirectMusicAudioPath8* p3DAudioPath = NULL);
    HRESULT CreateScriptFromFile(CMusicScript** ppScript,
        TCHAR* strFileName);
    HRESULT CreateChordMapFromFile(IDirectMusicChordMap8** ppChordMap,
        TCHAR* strFileName);
    HRESULT CreateStyleFromFile(IDirectMusicStyle8** ppStyle,
        TCHAR* strFileName);
    HRESULT GetMotifFromStyle(IDirectMusicSegment8** ppMotif,
        TCHAR* strStyle, TCHAR* wstrMotif);
    HRESULT CreateSegmentFromResource(CMusicSegment** ppSegment,
        TCHAR* strResource, TCHAR* strResourceType,
        BOOL bDownloadNow = TRUE, BOOL bIsMidiFile = FALSE);
    VOID Set3DParameters(FLOAT fDistanceFactor, FLOAT fDopplerFactor, FLOAT fRolloffFactor);
};

Constructor

The constructor initializes COM and the private data members.

Public Methods

The class contains the following methods, in alphabetical order.

Method | Description
CollectGarbage | Calls the IDirectMusicLoader8::CollectGarbage method, after ensuring that the loader still exists.
Create3DSegmentFromFile | Loads an object from a file and encapsulates it in a C3DMusicSegment object. If instructed to do so, sets the standard MIDI file parameter and downloads instruments.
CreateChordMapFromFile | Loads a chordmap from a file and returns the IDirectMusicChordMap8 interface.
CreateScriptFromFile | Loads a script from a file and encapsulates it in a CMusicScript object.
CreateSegmentFromFile | Loads an object from a file and encapsulates it in a CMusicSegment object. If instructed to do so, sets the standard MIDI file parameter and downloads instruments.
CreateSegmentFromResource | Loads an object from memory and encapsulates it in a CMusicSegment object. If instructed to do so, sets the standard MIDI file parameter and downloads instruments.
CreateStyleFromFile | Loads a style from a file and returns the IDirectMusicStyle8 interface.
GetDefaultAudioPath | Returns a pointer to the IDirectMusicAudioPath8 interface for the default audiopath created in the Initialize method.
GetListener | Returns a pointer to the IDirectSound3DListener8 interface.
GetLoader | Returns a pointer to the IDirectMusicLoader8 interface obtained in the Initialize method.
GetMotifFromStyle | Loads a motif from a style file and returns the IDirectMusicSegment8 interface.
GetPerformance | Returns a pointer to the IDirectMusicPerformance8 interface obtained in the Initialize method.
Initialize | Creates the loader and the performance, and initializes the performance with the supplied parameters. Note that in most cases pDs can be NULL.
Set3DParameters | Sets the distance factor, Doppler factor, and rolloff factor.
SetSearchDirectory | Sets the search directory for all types of objects.
StopAll | Stops all playing segments by calling IDirectMusicPerformance8::Stop, after ensuring that the performance still exists.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dmutil.cpp.

See Also

  • DirectMusic Sample Framework


CMusicScript Sample Class

The CMusicScript sample class represents a script, and contains methods for getting and setting variables and calling routines.

class CMusicScript
{
protected:
    IDirectMusicScript8*      m_pScript;
    IDirectMusicLoader8*      m_pLoader;
    IDirectMusicPerformance8* m_pPerformance;

public:
    CMusicScript(IDirectMusicPerformance8* pPerformance,
                  IDirectMusicLoader8* pLoader,
                  IDirectMusicScript8* pScript);
    virtual ~CMusicScript();

    inline  IDirectMusicScript8* GetScript() { return m_pScript; }
    HRESULT CallRoutine(TCHAR* strRoutine);
    HRESULT SetVariableNumber(TCHAR* strVariable, LONG lValue);
    HRESULT GetVariableNumber(TCHAR* strVariable, LONG* plValue);
    HRESULT SetVariableObject(TCHAR* strVariable, IUnknown *punkValue);
    HRESULT GetVariableObject(TCHAR* strVariable, REFIID riid,
        LPVOID FAR *ppv);
};

Constructor

The constructor stores pointers to the loader, performance, and script objects.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
CallRoutine | Calls IDirectMusicScript8::CallRoutine, after doing any necessary string type conversion.
GetScript | Returns the IDirectMusicScript8 interface pointer.
GetVariableNumber | Calls IDirectMusicScript8::GetVariableNumber, after doing any necessary string type conversion.
GetVariableObject | Calls IDirectMusicScript8::GetVariableObject, after doing any necessary string type conversion.
SetVariableNumber | Calls IDirectMusicScript8::SetVariableNumber, after doing any necessary string type conversion.
SetVariableObject | Calls IDirectMusicScript8::SetVariableObject, after doing any necessary string type conversion.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dmutil.cpp.

See Also

  • DirectMusic Sample Framework


C3DMusicSegment Sample Class

The C3DMusicSegment sample class represents a segment playing on a 3-D audiopath.

class C3DMusicSegment : public CMusicSegment
{
protected:
    IDirectMusicAudioPath8* m_p3DAudioPath;
    IDirectSound3DBuffer*   m_pDS3DBuffer;
    DS3DBUFFER              m_dsBufferParams;
    BOOL                    m_bDeferSettings;
    BOOL                    m_bCleanupAudioPath;

public:
    C3DMusicSegment(IDirectMusicPerformance8* pPerformance,
                   IDirectMusicLoader8* pLoader,
                   IDirectMusicSegment8* pSegment,
                   IDirectMusicAudioPath8* pAudioPath);
    virtual ~C3DMusicSegment();

    HRESULT Init();
    IDirectMusicAudioPath8* GetAudioPath() { return m_p3DAudioPath; }
    HRESULT Play(DWORD dwFlags = DMUS_SEGF_SECONDARY,
            IDirectMusicAudioPath8* pAudioPath = NULL);
    VOID Set3DParameters(FLOAT fMinDistance, FLOAT fMaxDistance);
    VOID SetObjectProperties(D3DVECTOR* pvPosition, D3DVECTOR* pvVelocity);
};

Constructor

The constructor stores pointers to the performance, loader, segment, and audiopath objects.

Public Methods

In addition to the methods inherited from CMusicSegment, the class contains the following public methods, in alphabetical order.

Method | Description
GetAudioPath | Returns a pointer to the IDirectMusicAudioPath8 interface in the m_p3DAudioPath member.
Init | Creates a 3-D audiopath if one is not already associated with the segment, and retrieves the 3-D buffer in the m_pDS3DBuffer member.
Play | Plays the segment, using the specified flags and audiopath. If no audiopath is specified, the audiopath in the m_p3DAudioPath member is used.
Set3DParameters | Sets the minimum and maximum distances for the 3-D buffer.
SetObjectProperties | Sets the position and velocity of the 3-D buffer.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dmutil.cpp.

See Also

  • DirectMusic Sample Framework


CMusicSegment Sample Class

The CMusicSegment sample class represents a segment, and contains methods for downloading and unloading instruments, playing and stopping the segment, and retrieving a style from the segment.

class CMusicSegment
{
protected:
    IDirectMusicSegment8*     m_pSegment;
    IDirectMusicLoader8*      m_pLoader;
    IDirectMusicPerformance8* m_pPerformance;
    IDirectMusicAudioPath8*   m_pEmbeddedAudioPath;
    BOOL                      m_bDownloaded;

public:
    CMusicSegment(IDirectMusicPerformance8* pPerformance,
                  IDirectMusicLoader8* pLoader,
                  IDirectMusicSegment8* pSegment);
    virtual ~CMusicSegment();

    inline  IDirectMusicSegment8* GetSegment() { return m_pSegment; }
    HRESULT GetStyle(IDirectMusicStyle8** ppStyle,
        DWORD dwStyleIndex = 0);
    HRESULT SetRepeats(DWORD dwRepeats);
    HRESULT Play(DWORD dwFlags = DMUS_SEGF_SECONDARY,
        IDirectMusicAudioPath8* pAudioPath = NULL);
    HRESULT Stop(DWORD dwFlags = 0);
    HRESULT Download( IDirectMusicAudioPath8* pAudioPath = NULL );
    HRESULT Unload(IDirectMusicAudioPath8* pAudioPath = NULL);
    BOOL    IsPlaying();
};

Constructor

The constructor stores pointers to the performance, loader, and segment objects. It also attempts to create an audiopath from an audiopath configuration embedded in the segment.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Download | Downloads the segment's instruments to the supplied audiopath. If no audiopath is supplied, this method downloads to the embedded audiopath if there is one, or to the performance otherwise.
GetSegment | Retrieves the IDirectMusicSegment8 interface pointer.
GetStyle | Retrieves a style in the segment, if the segment has a style track.
IsPlaying | Returns a Boolean variable that specifies whether the segment is playing. This method calls IDirectMusicPerformance8::IsPlaying.
Play | Plays the segment, using the specified flags and audiopath. If no audiopath is specified, this method plays on the embedded audiopath if there is one, or on the default audiopath otherwise. The method fails if the instruments have not been downloaded.
SetRepeats | Calls IDirectMusicSegment8::SetRepeats.
Unload | Unloads instruments from the specified audiopath. If no audiopath is specified, this method unloads from the embedded audiopath if there is one, or from the performance otherwise.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dmutil.cpp.

See Also

  • DirectMusic Sample Framework


3D Audio Sample

The 3D Audio sample application shows how to create a 3-D audiopath in a DirectMusic performance, how to obtain an interface to a 3-D buffer and listener in that path, and how to modify the parameters of the buffer and listener.

Path

Source: (SDK root)\Samples\C++\DirectMusic\3DAudio

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Click Open File and load a WAV, MIDI, or DirectMusic segment file. Play the segment. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

The 3D Audio sample is very similar in form to the Play Audio Sample.

See Also

  • DirectMusic C++ Samples
  • 3-D Sound
  • Retrieving Objects from an Audiopath


Audio Path Sample

The Audio Path sample demonstrates how different sounds can be played on an audiopath, and how the parameters of all sounds are affected by changes made on the audiopath.

Path

Source: (SDK root)\Samples\C++\DirectMusic\AudioPath

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Click Lullaby, Snore, and Mumble to play different sounds. Adjust the 3-D position of the sounds by using the sliders. Click Rude Awakening to play a different sound and stop all other sounds.

Programming Notes

This sample is very similar in form to the Play Audio Sample. The Audio Path sample differs by showing some of the various uses of an audiopath.

On WM_INITDIALOG, the OnInitDialog function does the following:

  1. Calls IDirectMusicPerformance8::CreateStandardAudioPath, passing in DMUS_APATH_DYNAMIC_3D to create a 3-D audiopath. The created IDirectMusicAudioPath8 interface is pointed to by g_p3DAudiopath.
  2. Uses the CMusicManager framework class to create CMusicSegment objects from a list of files.
  3. Gets the IDirectSound3DListener8 interface from the audiopath.
  4. Calls IDirectSound3DListener8::SetRolloffFactor to change the rate at which the amplitude of sounds diminishes over distance.

When the 3-D position slider is changed, the SetPosition function does the following:

  1. Calls IDirectMusicAudioPath8::GetObjectInPath to retrieve the IDirectSound3DBuffer8 interface.
  2. Calls IDirectSound3DBuffer8::SetPosition to set the position of the buffer.
  3. Releases the buffer.

When a segment is played, the PlaySegment function does one of the following:

  • If the Lullaby button was clicked, the segment is played on the audiopath as the primary segment.
  • If Snore or Mumble was clicked, a secondary segment is played.
  • If Rude Awakening was clicked, all sounds on the audiopath are stopped because the audiopath is passed to IDirectMusicPerformance8::PlaySegmentEx as the pFrom parameter. The alarm sound is then played as a new primary segment.

See Also

  • DirectMusic C++ Samples
  • Using Audiopaths


Audio Scripts Sample

The Audio Scripts sample demonstrates how an application and a DirectMusic script work together. The script reads and writes to variables in the application, and the application calls routines in the script that play segments.

The sample also demonstrates how waveforms can be played as variations in a segment.

Path

Source: (SDK root)\Samples\C++\DirectMusic\AudioScripts

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Select ScriptDemoBasic.spt from the Script File list box. Play a segment by clicking Routine 1. Click Routine 2 to play an ending and to stop playback. Play the segment again and click Routine 3 several times. Note how Variable 1 reflects the number of times the button has been clicked, and how the music changes in response to each click.

Select ScriptDemoBaseball.spt from the Script File list box. Click Routine 1 to play various calls from a vendor. Click Routine 2 to play various musical motifs. Change the score by entering different values in the Variable 1 and Variable 2 text boxes. Click Routine 3 to hear the score.

See Also

  • DirectMusic C++ Samples
  • Using Audio Scripts


AudioFX Sample

The AudioFX sample shows how to use DMOs on DirectMusic audiopaths to add effects to sounds, and how to set effect parameters.

Path

Source: (SDK root)\Samples\C++\DirectMusic\AudioFX

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

A default sound file is loaded when the application is run. You can load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. In the CSoundFXManager::Initialize method, it retrieves an IDirectSoundBuffer8 interface from the audiopath. This interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

  • DirectMusic C++ Samples
  • Using Effects


Cross Fade Sample

The Cross Fade sample shows how to fade out one segment while fading in another.

Path

Source: (SDK root)\Samples\C++\DirectMusic\CrossFade

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Click Play to play Segment 1. Click Crossfade to fade out Segment 1 and fade in Segment 2. Click Crossfade again to fade out Segment 2 and fade in Segment 1. You can load different segments by using the Browse buttons.

Programming Notes

The fade is achieved by playing the two segments on different audiopaths, whose volumes can be controlled separately by sending DMUS_CURVE_PMSG messages. The IDirectMusicAudioPath8::SetVolume method could be used instead, but it does not give any control over scheduling the curve. By using a curve message, the sample can put the starting point of the fade slightly in the future and make sure fading of both audiopaths happens at exactly the same time.

See Also

  • DirectMusic C++ Samples
  • Curves
  • Using Audiopaths


Music Tool Sample

The Music Tool sample demonstrates how to implement a DirectMusic tool that intercepts messages.

Path

Source: (SDK root)\Samples\C++\DirectMusic\MusicTool

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Play the default segment, or choose another WAV, MIDI, or DirectMusic segment file by clicking Open File. Select a tool from the drop-down list. The Echo Tool adds an echo to the sound. The Measure Tool causes the square to the right of the drop-down list to flash green on every beat, and red on every measure boundary.

Programming Notes

The tools are implemented in Echotool.cpp and Meastool.cpp. The Echo Tool works by copying messages and sending the copies to a different channel group. The Measure Tool responds to notifications of type GUID_NOTIFICATION_MEASUREANDBEAT. Notifications don't have to be intercepted by tools; they can also be retrieved by using IDirectMusicPerformance8::GetNotificationPMsg, as in the Play Audio Sample.

See Also

  • DirectMusic C++ Samples
  • DirectMusic Tools
  • Notification and Event Handling


Play Audio Sample

The Play Audio sample shows how to load a segment and play it on an audiopath, how to use DirectMusic notifications, and how to change global performance parameters.

Path

Source: (SDK root)\Samples\C++\DirectMusic\PlayAudio

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Play the default segment, or load another WAV, MIDI, or DirectMusic segment file by clicking Open File. Adjust the tempo and volume by using the sliders. The tempo cannot be adjusted for WAV files.

Programming Notes

The OnInitDialog function does the following:

  1. Creates an event, g_hDMusicMessageEvent. This will be used by DirectMusic to signal the application whenever a DirectMusic notification comes in.
  2. Creates an object of class CMusicManager called g_pMusicManager.
  3. Initializes the CMusicManager object. This does the following:
    • Creates IDirectMusicLoader8 by using CoCreateInstance.
    • Creates IDirectMusicPerformance8 by using CoCreateInstance.
    • Calls IDirectMusicPerformance8::InitAudio to initialize the performance and create a standard audiopath.
  4. Calls IDirectMusicPerformance8::AddNotificationType,requesting notifications of type GUID_NOTIFICATION_SEGMENT. DirectMusic will notify the application of all segment events so it can ascertain when the segment has ended.
  5. Calls IDirectMusicPerformance8::SetNotificationHandle, passing in the event whose handle is in g_hDMusicMessageEvent. This tells DirectMusic to signal this event when a notification is available.

The WinMain function performs the following tasks:

  1. Creates the window by using CreateDialog.
  2. In the messasge loop, calls MsgWaitForMultipleObjects, passing in g_hDMusicMessageEvent. This will tell us when g_hDMusicMessageEvent is signaled. DirectMusic signals this event whenever a DirectMusic notification has come in.
  3. If WAIT_OBJECT_0 is returned, calls ProcessDirectMusicMessages.
  4. If WAIT_OBJECT_0 + 1 is returned, Windows messages are available. The function does standard message processing by using PeekMessage.

When Open File is clicked, the OnOpenSoundFile function performs the following tasks:

  1. Gets the file name.
  2. Releases any previously created segment.
  3. Calls CMusicManager::CollectGarbage in Dmutil.cpp. This calls IDirectMusicLoader8::CollectGarbage, which ensures that unused objects are released. See Garbage Collection.
  4. Calls CMusicManager::SetSearchDirectory. This calls IDirectMusicLoader8::SetSearchDirectory, passing in GUID_DirectMusicAllTypes and a directory. This tells DirectMusic where to look for files referenced by segments.
  5. Calls CMusicManager::CreateSegmentFromFile to create a CMusicSegment called g_pMusicSegment. This entails the following steps:
    • Call IDirectMusicLoader8::LoadObjectFromFile to load the IDirectMusicSegment8 into pSegment.
    • Create a CMusicSegment, passing in pSegment.
    • If the file is a pure MIDI file, call IDirectMusicSegment8::SetParam, passing in GUID_StandardMIDIFile. This ensures that the file is played correctly.
    • Call IDirectMusicSegment8::Download, which downloads the segment's bands to the synthesizer. Some applications might want to wait before downloading, because the more instruments are downloaded, the more memory is required.

When Play is clicked, the OnPlayAudio function does the following:

  1. If the sound is to be looped, calls CMusicSegment::SetRepeats, passing in DMUS_SEG_REPEAT_INFINITE. Otherwise repeats are set to zero.
  2. Call CMusicSegment::Play, which calls IDirectMusicPerformance8::PlaySegmentEx.

When a notification is signaled, the ProcessDirectMusicMessages function looks for a message indicating that a segment has stopped. It performs the following tasks:

  1. Calls IDirectMusicPerformance8::GetNotificationPMsg in a loop to process each available message. The loop tests for S_OK, because S_FALSE is returned when no more messages are available.
  2. If the dwNotificationOption of the DMUS_NOTIFICATION_PMSG structure is DMUS_NOTIFICATION_SEGEND, calls QueryInterface on the punkUser member to obtain the IDirectMusicSegmentState8 interface of the segment instance that ended. The segment itself is obtained by using IDirectMusicSegmentState8::GetSegment. This method returns IDirectMusicSegment, and QueryInterface must be used to obtain IDirectMusicSegment8. The application then compares this pointer to the global primary segment pointer, to ensure that it was indeed the primary segment that stopped. Segments authored in DirectMusic Producer can trigger other segments, so we can't be sure that only the primary segment was playing.
  3. Cleans up all the interfaces.

See Also

  • DirectMusic C++ Samples


Play Motif Sample

The Play Motif sample demonstrates how a motif played as a secondary segment can be aligned to the rhythm of the primary segment in various ways.

Path

Source: (SDK root)\Samples\C++\DirectMusic\PlayMotif

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Play the default segment, or load another DirectMusic segment based on a style that contains motifs. Select one of the patterns in the list box and one of the Align Option buttons, and then click Play Motif. Note how the motif does not begin playing until an appropriate boundary in the primary segment has been reached.

Programming Notes

The Play Motif sample is very similar in form to the Play Audio Sample.

When loading the file, Play Motif performs the same steps as Play Audio, with the following additions in the LoadSegmentFile function:

  1. Loops through styles in the segment, searching it for motifs. It calls the CMusicSegment::GetStyle method in the sample framework, which in turn calls IDirectMusicSegment8::GetParam, passing GUID_IDirectMusicStyle and an incrementing index to get each of the styles in turn. The method fails when there are no more styles.
  2. For each style, calls IDirectMusicStyle8::EnumMotif, passing an incrementing motif index. This call retrieves the motif name at that index. When the call returns S_FALSE, there are no more motifs in the style.
  3. Passes the motif name to IDirectMusicStyle8::GetMotif to get an IDirectMusicSegment8 interface pointer to the motif, and stores this as data associated with the item in the list box.

When Play Motif is clicked, the OnPlayMotif function performs the following tasks:

  1. Retrieves the desired alignment option from the interface.
  2. Gets the selected motif from the listbox, along with its MOTIF_NODE item data. The MOTIF_NODE structure keeps a count of the number of plays currently occurring, as well as a pointer to the IDirectMusicSegment interface of the motif.
  3. Calls IDirectMusicPerformance8::PlaySegment, passing the motif's IDirectMusicSegment and flags, including DMUS_SEGF_SECONDARY and any alignment option.

DirectMusic notifications are handled much as in Play Audio, but this application also takes note of any motif starting or stopping, and updates the play count in the MOTIF_NODE structure. If the play count is greater than zero, then it updates the user interface to show that the motif is playing.

See Also

  • DirectMusic C++ Samples
  • Using Motifs


Play Multi Sample

The Play Multi sample shows how to play multiple segments simultaneously, one as a primary segment and the others as secondary segments.

Path

Source: (SDK root)\Samples\C++\DirectMusic\PlayMulti

Executable: (SDK root)\Samples\C++\DirectMusic\Bin

User's Guide

Use the default segments, or choose others by using the Browse buttons. The primary segment should be style-based so that it contains the rhythmic information necessary for proper cuing of the secondary segments.

Play the primary segment. Select a play boundary for a secondary segment and play it. Notice that the secondary segment begins playing on the specified boundary.

Select Controlling Segment to make a secondary segment the control segment. This will have an effect only if the secondary segment has a mute track, command track, tempo track, or chord track. Try loading a secondary segment that has a different tempo than the primary segment and playing it as the control segment. The tempo of the primary segment changes to match that of the secondary segment.

Programming Notes

The flags for IDirectMusicPerformance8::PlaySegmentEx are set in the OnPlay function and passed to the CMusicSegment::Play method in the sample framework.

See Also

  • DirectMusic C++ Samples
  • Control Segments
  • Using Segments


DirectMusic C++ Tutorials

This section contains the following tutorials showing how to implement Microsoft® DirectMusic® and Microsoft® DirectSound® in a C++ application:

  • Tutorial 1: Playing Audio Files
  • Tutorial 2: Using Audiopath Objects

Other, more specialized uses of DirectMusic are demonstrated in the sample applications provided with the SDK. For a description of these samples, see DirectMusic C++ Samples.

Note For the sake of simplicity, the tutorial applications perform minimal error checking when calling DirectX methods. Except for methods that always succeed, your code should always check the result of method calls and handle failure appropriately.


Tutorial 1: Playing Audio Files

This tutorial is a step-by-step guide to the most basic tasks in DirectMusic: initializing a DirectMusic performance and playing an audio file. The tutorial is presented in the following steps:

  • Step 1: Initialize
  • Step 2: Load a File
  • Step 3: Play the File
  • Step 4: Close Down

The complete sample code for the tutorial is available in the following folder:

C:\DXSDK\Samples\C++\DirectMusic\Tutorials\Tutorial1

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "Dxsdk" in the path.


Step 1: Initialize

The following instructions are needed for any application that uses the DirectMusic API. Including Dmusici.h also causes the other necessary header files for DirectMusic and DirectSound to be included.

#define INITGUID
#include <dmusici.h>

The tutorial uses three interface pointers, which are declared as follows:

IDirectMusicLoader8*  g_pLoader           = NULL;
IDirectMusicPerformance8* g_pPerformance  = NULL;
IDirectMusicSegment8*   g_pSegment        = NULL;

All the code in this simple application is included in the WinMain function. The application has no main window, so it can proceed straight to the creation of COM and two objects: the loader and the performance:.

INT APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrevInst,
  LPSTR pCmdLine, INT nCmdShow )
{
  CoInitialize(NULL);

  CoCreateInstance(CLSID_DirectMusicLoader, NULL,
       CLSCTX_INPROC, IID_IDirectMusicLoader8,
       (void**)&g_pLoader);

  CoCreateInstance(CLSID_DirectMusicPerformance, NULL,
       CLSCTX_INPROC, IID_IDirectMusicPerformance8,
       (void**)&g_pPerformance );

The next step is to initialize the performance and the synthesizer. The IDirectMusicPerformance8::InitAudio method performs the following tasks:

  • Creates a DirectMusic and a DirectSound object. In most cases you don't need an interface to those objects, and you can pass NULL in the first two parameters.
  • Associates an application window with the DirectSound object. Normally the handle of the main application window is passed as the third parameter, but the tutorial application doesn't have a window, so it passes NULL instead.
  • Sets up a default audiopath of a standard type. The tutorial requests a path of type DMUS_APATH_SHARED_STEREOPLUSREVERB, which is suitable for music.
  • Allocates a number of performance channels to the audiopath. WAV files require only a single performance channel, and MIDI files require up to 16. Segments created in DirectMusic Producer might need more. No harm is done by asking for extra channels.
  • Specifies capabilities and resources of the synthesizer. This can be done in one of two ways: by setting flags or by supplying a DMUS_AUDIOPARAMS structure with more detailed information. Most applications set the DMUS_AUDIOF_ALL flag and let DirectMusic create the synthesizer with default parameters.

In the tutorial, the call to InitAudio is very simple:

  g_pPerformance->InitAudio(
    NULL,              // IDirectMusic interface not needed.
    NULL,              // IDirectSound interface not needed.
    NULL,              // Window handle.
    DMUS_APATH_SHARED_STEREOPLUSREVERB,  // Default audiopath type.
    64,                // Number of performance channels.
    DMUS_AUDIOF_ALL,   // Features on synthesizer.
    NULL               // Audio parameters; use defaults.
  );

Next: Step 2: Load a File


Step 2: Load a File

The DirectMusic performance and synthesizer are now ready to process sound data. To get the data, the loader needs to know where to find it. Although a full path can be provided each time a file is loaded, it is more convenient to establish a default directory. Do this by using the IDirectMusicLoader8::SetSearchDirectory method.

In the sample code, the path to the default Windows media directory is given. You can change the value of wstrSearchPath to get files from a different folder.

The following code is from the WinMain function in the tutorial sample:

  // Find the Windows media directory.

  CHAR strPath[512];
  if( GetWindowsDirectory( strPath, MAX_PATH+1 ) == 0 )
        return 0;
  strcat( strPath, "\\media" );

 // Convert to Unicode.

  WCHAR wstrSearchPath[MAX_PATH + 1];
  MultiByteToWideChar( CP_ACP, 0, strPath, -1,
         wstrSearchPath, MAX_PATH );
  wstrSearchPath[MAX_PATH] = 0;

  // Set the search directory.

  g_pLoader->SetSearchDirectory(
    GUID_DirectMusicAllTypes, // Types of files sought.
    wstrSearchPath,           // Where to look.
    FALSE                     // Don't clear object data.
  );

In the call to SetSearchDirectory, the fClear parameter is set to FALSE because there is no danger of accidentally reloading objects from the wrong directory. This is likely to happen only if the application is loading identically named objects from different folders.

Now that the loader knows where to look for the file, it can load it as a segment:

  WCHAR wstrFileName[MAX_PATH] = L"ding.wav";

  if (FAILED(g_pLoader->LoadObjectFromFile(
    CLSID_DirectMusicSegment, // Class identifier.
    IID_IDirectMusicSegment8, // ID of desired interface.
    wstrFileName,             // Filename.
    (LPVOID*) &g_pSegment     // Pointer that receives interface.
  )))
  {
    MessageBox( NULL, "Media not found, sample will now quit.",
          "DirectMusic Tutorial", MB_OK );
    g_pPerformance->CloseDown();
    g_pLoader->Release();
    g_pPerformance->Release();
    CoUninitialize();
    return 0;
  }

Next: Step 3: Play the File


Step 3: Play the File

The WAV file loaded in the previous step is now available to the performance through its IDirectMusicSegment8 interface.

Before a segment can be played, its band must be downloaded to the synthesizer. As long as you don't unload the band, this step has to be taken only once for each segment that uses a unique band.

The following code from the WinMain function in the sample downloads the band to the performance. Alternatively, it could be downloaded to an audiopath. As long as only a single synthesizer is in use, it doesn't matter which destination object you choose:

  g_pSegment->Download( g_pPerformance );

To play the file, pass the segment interface to IDirectMusicPerformance8::PlaySegmentEx. This method offers many options for playback, but to play a segment immediately on the default audiopath, all the parameters except the first can be NULL or 0:

  g_pPerformance->PlaySegmentEx(
      g_pSegment,  // Segment to play.
      NULL,        // Not used.
      NULL,        // For transitions.
      0,           // Flags.
      0,           // Start time; 0 is immediate.
      NULL,        // Pointer that receives segment state.
      NULL,        // Object to stop.
      NULL         // Audiopath, if not default.
  );
  MessageBox( NULL, "Click OK to Exit.", "Play Audio", MB_OK );

Next: Step 4: Close Down


Step 4: Close Down

To exit an audio application cleanly, you must perform four main steps:

  1. Stop any playing segments by calling IDirectMusicPerformance8::Stop.
  2. Close down the performance. The IDirectMusicPerformance8::CloseDown method performs miscellaneous cleanup tasks and releases internal references to objects.
  3. Release all interfaces.
  4. Close COM.

The following code from the WinMain function in the tutorial sample is called when the dialog box is closed.

  g_pPerformance->Stop(
      NULL, // Stop all segments.
      NULL, // Stop all segment states.
      0,    // Do it immediately.
      0     // Flags.
  );

  g_pPerformance->CloseDown();

  g_pLoader->Release();
  g_pPerformance->Release();
  g_pSegment->Release();

  CoUninitialize();

  return 0;  // Return value for WinMain.
}      // End of WinMain.


Tutorial 2: Using Audiopath Objects

This tutorial is a guide to setting up a DirectMusic performance and retrieving an object—in this case, a 3-D buffer—from an audiopath so that sound parameters can be changed. The tutorial is presented in the following steps:

  • Step 1: Create the Audiopath
  • Step 2: Retrieve the Buffer
  • Step 3: Change Buffer Parameters

The complete sample code for the tutorial is available in the following folder:

C:\DXSDK\Samples\C++\DirectMusic\Tutorials\Tutorial2

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "Dxsdk" in the path.

It is assumed that you have already learned the basic steps of creating the performance and loader objects, and loading and playing a file. These steps are covered in Tutorial 1: Playing Audio Files.


Step 1: Create the Audiopath

The simplest way to create an audiopath is by passing a flag to IDirectMusicPerformance8::InitAudio. The tutorial sample passes the DMUS_APATH_DYNAMIC_STEREO flag, causing InitAudio to set up a default audiopath that supports stereo sounds:

g_pPerformance->InitAudio(
    NULL,        // IDirectMusic interface not needed.
    NULL,        // IDirectSound interface not needed.
    NULL,        // Window handle.
    DMUS_APATH_DYNAMIC_STEREO, // Default audiopath type.
    64,          // Number of performance channels.
    DMUS_AUDIOF_ALL,     // Features on synthesizer.
    NULL         // Audio parameters; use defaults.
);

The default audiopath is suitable for sounds that do not have to be located in space, such as background music or narration. However, if an application implements 3-D sound effects, it will play each sound source on its own audiopath, so that 3-D parameters can be set individually.

The sample creates one such audiopath as follows:

IDirectMusicAudioPath8* p3DAudioPath = NULL;
g_pPerformance->CreateStandardAudioPath(
    DMUS_APATH_DYNAMIC_3D,  // Path type.
    64,                     // Number of performance channels.
    TRUE,                   // Activate now.
    &p3DAudioPath           // Pointer that receives audiopath.
);

A segment can now be played on this audiopath as follows:

g_pPerformance->PlaySegmentEx(
    g_pSegment,  // Segment to play.
    NULL,        // Not used.
    NULL,        // For transitions.
    0,           // Flags.
    0,           // Start time; 0 is immediate.
    NULL,        // Pointer that receives segment state.
    NULL,        // Object to stop.
    p3DAudioPath // Audiopath.
);

Next: Step 2: Retrieve the Buffer


Step 2: Retrieve the Buffer

By using the IDirectMusicAudioPath8::GetObjectInPath method, you can retrieve interfaces to objects that form part of the path. In the case of the DMUS_APATH_DYNAMIC_3D standard audiopath type, such objects could include the secondary buffer itself, the primary buffer, the DirectSound listener, or any DMOs set on buffers after the audiopath was created. The tutorial sample obtains the IDirectSound3DBuffer8 interface to the buffer:

IDirectSound3DBuffer8* pDSB = NULL;

p3DAudioPath->GetObjectInPath(
    DMUS_PCHANNEL_ALL,  // Performance channel.
    DMUS_PATH_BUFFER,   // Stage in the path.
    0,                  // Index of buffer in chain.
    GUID_NULL,          // Class of object.
    0,                  // Index of object in buffer; ignored.
    IID_IDirectSound3DBuffer, // GUID of desired interface.
    (LPVOID*) &pDSB     // Pointer that receives interface.
);

The parameters to IDirectMusicAudioPath8::GetObjectInPath can be a little tricky to set up properly. For information on which parameters are relevant for objects at different stages in the path, see Retrieving Objects from an Audiopath.

In this case, you are retrieving a secondary buffer that is used by all performance channels on this audiopath. Set the dwPChannel parameter to DMUS_PCHANNEL_ALL.

Because the buffer you want is the first and in this case the only buffer in the chain, you pass 0 as dwBuffer. The DMUS_PATH_BUFFER stage contains only buffer objects, and not the DMOs attached to those buffers; therefore dwIndex is ignored.

Next: Step 3: Change Buffer Parameters


Step 3: Change Buffer Parameters

Now that you have the IDirectSound3DBuffer8 interface, you can use it to move the sound in space. The tutorial sample application does so when the user closes a series of message boxes. For example, the following code immediately moves the sound to the left:

pDSB->SetPosition( -0.1f, 0.0f, 0.0f, DS3D_IMMEDIATE );

The first three parameters specify the new position of the sound source in relation to the default listener. The default listener is at coordinates (0.0, 0.0, 0.0), facing toward the positive z-axis, with the top of the head toward the positive y-axis. Distance units are meters by default. Because the x-axis is positive from left to right, the new position of the sound is 10 centimeters directly to the left of the listener. For more information, see Coordinates of 3-D Space and Spatial Parameters of the Listener.

The last parameter of the IDirectSound3DBuffer8::SetPosition method specifies whether the change is to be made immediately or deferred until all changes are committed. For more information, see Deferred Settings.


DirectMusic C/C++ Reference

This section contains reference information for the API elements of Microsoft® DirectMusic®. Reference material is divided into the following categories.

  • DirectMusic Interfaces
  • DirectMusic Messages
  • DirectMusic Structures
  • DLS Structures
  • DirectMusic File Format
  • DirectMusic File Structures
  • Standard Track Parameters
  • DirectMusic Enumerated Types
  • DirectMusic Return Values


DirectMusic Interfaces

This section contains references for DirectMusic COM interfaces.

Interfaces in the current version (other than IKsControl and IReferenceClock) are either declared or defined with names ending in 8. To be sure of using the latest version of an interface, always include this suffix when declaring the interface pointer.

Interfaces retrieved by methods are always the base version. Where a newer version exists, you must call QueryInterface to obtain it, as in the following example, where lpdmBand is an IDirectMusicBand8 interface pointer:

IDirectMusicSegment * lpdmseg;
IDirectMusicSegment8 * lpdmseg8;

HRESULT hr = lpdmBand->CreateSegment(&lpdmseg);
if (SUCCEEDED(hr))
{
  hr = lpdmseg->QueryInterface(IID_IDirectMusicSegment8,
    (LPVOID*)&lpdmseg8);
}

Where there is no new version of an interface, the interface name with the suffix 8 is only a define. For example, IDirectMusicGraph8 is equivalent in all respects to IDirectMusicGraph. In such cases it is not necessary to query for a new interface, but doing so does no harm and can make your code easier to maintain for future versions of DirectX.

For information on which methods are supported by earlier versions of an interface, see the declaration of the interface in the appropriate header file.

When a method takes an interface pointer as an in parameter, you can pass in the newer version even where the method is declared as accepting the older version. For example, a pointer to either IDirectMusicSegment or IDirectMusicSegment8 can be passed to IDirectMusicPerformance8::PlaySegmentEx.

This documentation contains full reference topics only for the latest versions of interfaces. Where a define exists, such as IDirectMusicGraph8, the interface is documented under that name.

Interface | Description
IDirectMusic8 | Provides methods for managing buffers, ports, and the master clock.
IDirectMusicAudioPath8 | Manages the stages of data flow from the performance to the final mixer.
IDirectMusicBand8 | Represents a DirectMusic band object.
IDirectMusicBuffer8 | Represents a buffer containing time-stamped data (typically in the form of MIDI messages) being sequenced to a port.
IDirectMusicChordMap8 | Represents a chordmap.
IDirectMusicCollection8 | Manages an instance of a DLS file.
IDirectMusicComposer8 | Enables access to the composition engine.
IDirectMusicContainer8 | Provides access to objects in a container, which is a collection of objects used by a segment or performance.
IDirectMusicDownload8 | Represents a contiguous memory chunk used for downloading to a DLS synthesizer port.
IDirectMusicDownloadedInstrument8 | Used to identify an instrument that has been downloaded to the synthesizer by using the IDirectMusicPort8::DownloadInstrument or the IDirectMusicPerformance8::DownloadInstrument method.
IDirectMusicGetLoader8 | Used by an object parsing a stream when the object needs to load another object referenced by the stream.
IDirectMusicGraph8 | Manages the loading and message flow of tools.
IDirectMusicInstrument8 | Represents an individual instrument from a DLS collection.
IDirectMusicLoader8 | Used for finding, enumerating, caching, and loading objects.
IDirectMusicObject8 | Used by an object parsing a stream when the object needs to load another object referenced by the stream.
IDirectMusicPatternTrack8 | Represents a track that contains a single pattern.
IDirectMusicPerformance8 | Manages playback.
IDirectMusicPort8 | Represents a device that sends or receives sound data.
IDirectMusicPortDownload8 | Enables an application to communicate directly with a port that supports DLS downloading and to download memory chunks directly to the port.
IDirectMusicScript8 | Represents a script containing variables that can be set and retrieved by the application, and routines that can be called by the application.
IDirectMusicSegment8 | Represents a segment, which is a playable unit of data made up of multiple tracks.
IDirectMusicSegmentState8 | Represents a playing instance of a segment.
IDirectMusicStyle8 | Represents a style object, which encapsulates a collection of patterns, motifs, and bands used in run-time composition of musical segments.
IDirectMusicSynth | Implemented by synthesizers.
IDirectMusicSynthSink | Implemented by synthesizer sinks.
IDirectMusicThru8 | Supports thruing of MIDI messages from a capture port to another port.
IDirectMusicTool8 | Represents a tool object that processes messages.
IDirectMusicTrack8 | Represents a track object, which can store any kind of data for a segment.
IKsControl | Used to get, set, or query the support of properties, events, and methods.
IReferenceClock | Represents a system reference clock.


IDirectMusic8 Interface

The IDirectMusic8 interface provides methods for managing buffers, ports, and the master clock. There should not be more than one instance of this interface per application.

IDirectMusic8 supersedes IDirectMusic and adds a new method, SetExternalMasterClock.

There is no helper function to create this interface. Applications use the COM CoCreateInstance function, the IDirectMusicPerformance8::Init method, or the IDirectMusicPerformance8::InitAudio method to create a DirectMusic object.

In addition to the methods inherited from IUnknown, the IDirectMusic8 interface exposes the following methods.

Ports

Method | Description
Activate | Activates or deactivates all ports created from this interface.
CreatePort | Creates an object for a DirectMusic port.
EnumPort | Enumerates and retrieves the capabilities of the DirectMusic ports connected to the system.
GetDefaultPort | Retrieves the GUID of the default output port.

Timing

Method | Description
EnumMasterClock | Enumerates the clocks that DirectMusic can use as the master clock.
GetMasterClock | Retrieves the GUID and a pointer to the interface for the current master clock.
SetExternalMasterClock | Sets the DirectMusic master clock to an existing clock object.
SetMasterClock | Sets the DirectMusic master clock to a clock identified by a call to EnumMasterClock.

Miscellaneous

Method | Description
CreateMusicBuffer | Creates an object to hold messages being sequenced to the port.
SetDirectSound | Connects DirectMusic to a DirectSound device object for output from the synthesizer.

The LPDIRECTMUSIC8 type is defined as a pointer to the IDirectMusic8 interface:

typedef IDirectMusic8 *LPDIRECTMUSIC8;

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces


IDirectMusic8::Activate

The Activate method activates or deactivates all ports created from this interface.

Syntax

HRESULT Activate(
  BOOL fEnable
);

Parameters

fEnable

Switch to activate (TRUE) or deactivate (FALSE) all port objects created in this instance of DirectMusic.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Remarks

Applications should call Activate(FALSE) when they lose input focus if they do not need to play sounds in the background. This allows another application that has the input focus to have access to the ports. When the application has input focus again, it should call Activate(TRUE) to enable all its allocated ports.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusicPort8::Activate


IDirectMusic8::CreateMusicBuffer

The CreateMusicBuffer method creates a DirectMusicBuffer object to hold messages being sequenced to the port. Most applications do not need to call this method directly, because buffer management is handled by the performance when a port is added.

Syntax

HRESULT CreateMusicBuffer(
  LPDMUS_BUFFERDESC pBufferDesc,
  LPDIRECTMUSICBUFFER*..ppBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pBufferDesc

Address of the DMUS_BUFFERDESC structure that contains the description of the buffer to be created. The application must initialize the dwSize member of this structure before passing the pointer.

ppBuffer

Address of a variable that receives an IDirectMusicBuffer8 interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Because aggregation is not currently supported, this value must be set to NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
CLASS_E_NOAGGREGATION
E_INVALIDARG
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface


IDirectMusic8::CreatePort

The CreatePort method creates an object for a DirectMusic port.

Syntax

HRESULT CreatePort(
  REFCLSID rclsidPort,
  LPDMUS_PORTPARAMS pPortParams,
  LPDIRECTMUSICPORT*  ppPort,
  LPUNKNOWN pUnkOuter
);

Parameters

rclsidPort

Reference to (C++) or address of (C) the GUID that identifies the port for which the IDirectMusicPort8 interface is to be created. The GUID is retrieved through the IDirectMusic8::EnumPort method. If it is GUID_NULL, the returned port is the default port. For more information, see Default Port.

pPortParams

Address of a DMUS_PORTPARAMS8 structure that contains parameters for the port. The dwSize member of this structure must be initialized to sizeof(DMUS_PORTPARAMS8) before the method is called.

ppPort

Address of a variable that receives an IDirectMusicPort interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Because aggregation is not currently supported, this value must be NULL.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if a requested parameter is not available.

If it fails, the method can return one of error values in the following table.

Return code
CLASS_E_NOAGGREGATION
DMUS_E_DSOUND_NOT_SET
E_INVALIDARG
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

By default, the port is inactive when it is created. It must be activated by a call to IDirectMusic8::Activate or IDirectMusicPort8::Activate.

If not all parameters could be obtained, the DMUS_PORTPARAMS8 structure is changed as follows to match the available parameters of the port.

On entry, the dwValidParams member of the structure indicates which members in the structure are valid. If the flag is not set for a member of the structure, a default value is set for that parameter when the port is created.

On return, the flags in dwValidParams show which port parameters were set. If a particular parameter was not requested but was set to the default, that flag is added to those passed in.

If the port supports a specified parameter but the given value for the parameter is out of range, the parameter value in *pPortParams is changed. In this case, the flag in dwValidParams remains set, but S_FALSE is returned to indicate that the value has been changed.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • Using DirectMusic Ports


IDirectMusic8::EnumMasterClock

The EnumMasterClock method enumerates the clocks that DirectMusic can use as the master clock. Each time it is called, this method retrieves information about a single clock.

Syntax

HRESULT EnumMasterClock(
  DWORD dwIndex,
  LPDMUS_CLOCKINFO lpClockInfo
);

Parameters

dwIndex

Index of the clock for which the description is to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.

lpClockInfo

Address of a DMUS_CLOCKINFO8 structure that receives the description of the clock. The application must initialize the dwSize member of this structure before passing the pointer.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no clock with that index number.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a clock. Rebooting or adding and removing hardware can cause the index number of a clock to change.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusic8::GetMasterClock
  • IDirectMusic8::SetMasterClock
  • Master Clock


IDirectMusic8::EnumPort

The EnumPort method enumerates and retrieves the capabilities of the DirectMusic ports connected to the system. Each time it is called, this method retrieves information about a single port.

Syntax

HRESULT EnumPort(
  DWORD dwIndex,
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

dwIndex

Index of the port for which the capabilities are to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.

pPortCaps

Address of the DMUS_PORTCAPS structure that receives the capabilities of the port. The dwSize member of this structure must be initialized before the pointer is passed.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no port with that index value.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a port. Restarting the system or adding or removing ports could cause the index number of a port to change.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • Using DirectMusic Ports


IDirectMusic8::GetDefaultPort

The GetDefaultPort method retrieves the GUID of the default output port. This is the port to be created if GUID_NULL is passed to IDirectMusic8::CreatePort.

Syntax

HRESULT GetDefaultPort(
  LPGUID pguidPort
);

Parameters

pguidPort

Address of a variable that receives the default port GUID.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

  • Default Port
  • IDirectMusic8 Interface


IDirectMusic8::GetMasterClock

The GetMasterClock method retrieves the GUID and a pointer to the IReferenceClock interface for the clock that is currently set as the DirectMusic master clock.

Syntax

HRESULT GetMasterClock(
  LPGUID  pguidClock,
  IReferenceClock**  ppReferenceClock
);

Parameters

pguidClock

Address of a variable that receives the GUID of the master clock. The application can pass NULL if this value is not desired.

ppReferenceClock

Address of a variable that receives the IReferenceClock interface pointer for this clock. The application can pass NULL if this value is not desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_NOINTERFACE
E_POINTER

Remarks

The IReferenceClock interface pointer must be released after the application has finished using the interface.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusic8::SetMasterClock
  • Master Clock


IDirectMusic8::SetDirectSound

The SetDirectSound method connects DirectMusic to a DirectSound device object for output from the synthesizer.

This method is not used by most applications. The DirectSound device object is normally created and connected to the performance by IDirectMusicPerformance8::InitAudio.

Syntax

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

pDirectSound

Address of the IDirectSound8 interface to use for output. If this parameter is NULL, the method creates a DirectSound device object and sets the DSSCL_PRIORITY cooperative level. (See Remarks.) If this parameter contains an IDirectSound pointer, the caller is responsible for setting the cooperative level.

hWnd

Window handle to the DirectSound device object created by this call. If this value is NULL, the current foreground window is set as the focus window. (See Remarks.)

If pDirectSound is a valid interface, this parameter is ignored. It is the caller's responsibility to supply a valid window handle in the call to IDirectSound8::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_DSOUND_ALREADY_SET.

Remarks

The specified DirectSound device object is the one used for rendering audio on all ports. This default can be overridden on a particular port by using the IDirectMusicPort8::SetDirectSound method.

Whenever the IDirectMusic8::SetDirectSound method is called, any existing DirectSound device object is released.

When pDirectSound is NULL, a new DirectSound device object is not created until a port that uses DirectSound is activated, and the DirectSound device object is automatically released when the last port using it is deactivated.

If you created the DirectSound device object yourself, you can release it by calling this method with NULL in the pDirectSound parameter after deactivating all ports. (It is an error to call SetDirectSound on an active port.)

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window is in the foreground during initialization. In general, the top-level application window handle should be passed to DirectMusic and DirectSound.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusicPerformance8::Init


IDirectMusic8::SetExternalMasterClock

The SetExternalMasterClock method sets the DirectMusic master clock to an existing clock object. There is only one master clock for all DirectMusic applications.

Syntax

HRESULT SetExternalMasterClock(
  IReferenceClock *pClock
);

Parameters

pClock

IReferenceClock interface pointer that specifies the clock.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_PORTS_OPEN.

Remarks

If another running application is also using DirectMusic, it is not possible to change the master clock until that application is shut down.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusic8::EnumMasterClock
  • IDirectMusic8::GetMasterClock
  • IDirectMusic8::SetMasterClock
  • Master Clock


IDirectMusic8::SetMasterClock

The SetMasterClock method sets the DirectMusic master clock to a clock identified by a GUID obtained by using the IDirectMusic8::EnumMasterClock method. There is only one master clock for all DirectMusic applications.

Syntax

HRESULT SetMasterClock(
  REFGUID rguidClock
);

Parameters

rguidClock

Reference to (C++) or address of (C) the GUID that identifies the clock to set as the master clock for DirectMusic. This parameter must be a GUID returned by the IDirectMusic8::EnumMasterClock method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_PORTS_OPEN.

Remarks

If another running application is also using DirectMusic, it is not possible to change the master clock until that application is shut down.

Most applications do not need to call SetMasterClock. It should not be called unless there is a need to synchronize tightly with a hardware timer other than the system clock.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8 Interface
  • IDirectMusic8::EnumMasterClock
  • IDirectMusic8::GetMasterClock
  • IDirectMusic8::SetExternalMasterClock
  • Master Clock


IDirectMusicAudioPath8 Interface

The IDirectMusicAudioPath8 interface manages the stages of data flow from the performance to the final mixer. An audiopath can be created from an audiopath configuration object by using the IDirectMusicPerformance8::CreateAudioPath method. A standard audiopath can be created by using IDirectMusicPerformance8::CreateStandardAudioPath. A standard default path can also be created by IDirectMusicPerformance8::InitAudio and then retrieved by using IDirectMusicPerformance8::GetDefaultAudioPath.

The IDirectMusicAudioPath8 interface can be passed to IDirectMusicPerformance8::PlaySegmentEx to play the segment on that audiopath.

IDirectMusicAudioPath8 is a type definition for IDirectMusicAudioPath. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicAudioPath8 interface exposes the following methods.

Method | Description
Activate | Activates or deactivates the audiopath.
ConvertPChannel | Translates between a performance channel in a segment and the equivalent channel allocated in the performance for the audiopath.
GetObjectInPath | Retrieves an interface for an object in the audiopath.
SetVolume | Sets the audio volume on the audiopath.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Using Audiopaths


IDirectMusicAudioPath8::Activate

The Activate method activates or deactivates the audiopath.

Syntax

HRESULT Activate(
  BOOL fActivate
);

Parameters

fActivate

Boolean that specifies whether to activate (TRUE) or deactivate (FALSE) the audiopath.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the audiopath is already in the requested state.

Remarks

The behavior of this method is different from that of IDirectMusicPort8::Activate. When a port is deactivated, it no longer produces sound, but the performance can continue playing segments. When an audiopath is deactivated, all playback stops and any attempt to play a segment will fail.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicAudioPath8 Interface


IDirectMusicAudioPath8::ConvertPChannel

The ConvertPChannel method translates between a performance channel in a segment and the equivalent channel allocated in the performance for the audiopath. This method is not typically needed by applications, but can be used by components such as tracks.

Syntax

HRESULT ConvertPChannel(
  DWORD dwPChannelIn,
  DWORD *pdwPChannelOut
);

Parameters

dwPChannelIn

Value that specifies the performance channel to convert.

pdwPChannelOut

Address of a DWORD variable that receives the virtual performance channel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicAudioPath8 Interface


IDirectMusicAudioPath8::GetObjectInPath

The GetObjectInPath method retrieves an interface for an object in the audiopath.

Syntax

RESULT GetObjectInPath(
  DWORD dwPChannel,
  DWORD dwStage,
  DWORD dwBuffer,
  REFGUID guidObject,
  DWORD dwIndex,
  REFGUID iidInterface,
  void ** ppObject
);

Parameters

dwPChannel

Performance channel to search, or DMUS_PCHANNEL_ALL to search all channels. The first channel is numbered 0. (See Remarks.)

dwStage

Stage in the audiopath. Can be one of the values in the following table.

Value | Description
DMUS_PATH_AUDIOPATH_GRAPH | Get the audiopath toolgraph. One is created if none exists.
DMUS_PATH_AUDIOPATH_TOOL | Get a tool from the audiopath toolgraph.
DMUS_PATH_BUFFER | Get a DirectSound buffer.
DMUS_PATH_BUFFER_DMO | Get a DMO in a buffer. For information on DMO interfaces, see IDirectSoundBuffer8::GetObjectInPath.
DMUS_PATH_MIXIN_BUFFER | Get a global mix-in buffer.
DMUS_PATH_MIXIN_BUFFER_DMO | Get a DMO in a global mix-in buffer.
DMUS_PATH_PERFORMANCE | Get the performance.
DMUS_PATH_PERFORMANCE_GRAPH | Get the performance toolgraph. One is created if none exists.
DMUS_PATH_PERFORMANCE_TOOL | Get a tool from the performance toolgraph.
DMUS_PATH_PORT | Get the synthesizer.
DMUS_PATH_PRIMARY_BUFFER | Get the primary buffer.

dwBuffer

Index of the buffer (if dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER), or index of the buffer in which the DMO resides (if dwStage is DMUS_PATH_BUFFER_DMO or DMUS_PATH_MIXIN_BUFFER_DMO).

guidObject

Class identifier of the object, or GUID_All_Objects to search for an object of any class. This parameter is ignored if only a single class of object can exist at the stage specified by dwStage, and can be set to GUID_NULL.

dwIndex

Index of the object within a list of matching objects. Set to 0 to find the first matching object. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, this parameter is ignored, and the buffer index is specified by dwBuffer.

iidInterface

Identifier of the desired interface, such as IID_IDirectMusicTool.

ppObject

Address of a variable that receives a pointer to the requested interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_INVALIDARG
E_OUTOFMEMORY
E_NOINTERFACE
E_POINTER

Remarks

The value in dwPChannel must be 0 for any stage that is not channel-specific. Objects in the following stages are channel-specific and can be retrieved by setting a channel number or DMUS_PCHANNEL_ALL in dwPChannel:

DMUS_PATH_AUDIOPATH_TOOL
DMUS_PATH_BUFFER
DMUS_PATH_BUFFER_DMO
DMUS_PATH_PERFORMANCE_TOOL
DMUS_PATH_PORT

The precedence of the parameters in filtering out unwanted objects is as follows:

  1. dwStage.
  2. guidObject. If this value is not GUID_All_Objects, only objects whose class identifier equals guidObject are searched. However, this parameter is ignored for stages where only a single class of object can exist, such as DMUS_PATH_AUDIOPATH_GRAPH.
  3. dwPChannel. If the stage is channel-specific and this value is not DMUS_PCHANNEL_ALL, only objects on the channel are searched.
  4. dwBuffer. This is used only if dwStage is DMUS_PATH_BUFFER, DMUS_PATH_MIXIN_BUFFER, DMUS_PATH_BUFFER_DMO, or DMUS_PATH_MIXIN_BUFFER_DMO.
  5. dwIndex.

If a matching object is found but the interface specified by iidInterface cannot be obtained, the method fails.

The following example function shows how to enumerate the buffers in an audiopath:

void DumpAudioPathBuffers(
    IDirectMusicAudioPath *pDirectMusicAudioPath)
{
  DWORD dwBuffer = 0;
  IDirectSoundBuffer *pDirectSoundBuffer;

  while (S_OK == pDirectMusicAudioPath->GetObjectInPath(
      DMUS_PCHANNEL_ALL, DMUS_PATH_BUFFER, dwBuffer,
      GUID_NULL, 0, IID_IDirectSoundBuffer,
      (void**) &pDirectSoundBuffer))
  {
    // Do something with pDirectSoundBuffer.
    // . . .
    dwBuffer++;
    pDirectSoundBuffer->Release();
  }
}

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicAudioPath8 Interface
  • IDirectMusicSegmentState8::GetObjectInPath
  • Retrieving Objects from an Audiopath


IDirectMusicAudioPath8::SetVolume

The SetVolume method sets the audio volume on the audiopath. The volume can be faded in or out.

Syntax

HRESULT SetVolume(
  long lVolume,
  DWORD dwDuration
);

Parameters

lVolume

Value that specifies the attenuation, in hundredths of a decibel. This value must be in the range from -9600 to 0. Zero is full volume.

dwDuration

Value that specifies the time, in milliseconds, over which the volume change takes place. A value of 0 ensures maximum efficiency.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_INVALIDARG

Remarks

This method works by sending a volume curve message. Any volume events occurring later, such as a band change, override the volume set by this method. IDirectMusicAudioPath8::SetVolume is useful mainly for adjusting currently playing sounds; for example, to fade out before stopping a segment. If you want to make a global change that affects all playback, use one of the following techniques:

  • Obtain the buffer object from the audiopath and use IDirectSoundBuffer8::SetVolume.
  • Obtain the port object from the audiopath and use IKsControl::KsProperty to change the GUID_DMUS_PROP_Volume property set.
  • Set the master volume for the performance. See Setting and Retrieving Global Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Cross Fade Sample
  • Curves
  • IDirectMusicAudioPath8 Interface
  • Playing Sounds on Audiopaths


IDirectMusicBand8 Interface

The IDirectMusicBand8 interface represents a DirectMusic band object. A band is used to set the instrument choices and mixer settings for a set of performance channels. For an overview, see Using Bands. Bands can be stored directly in their own files or embedded in a style's band list or a segment's band track.

IDirectMusicBand8 is a define for IDirectMusicBand. The two interface names are interchangeable.

The DirectMusicBand object also supports the IPersistStream and IDirectMusicObject8 interfaces for loading its data.

In addition to the methods inherited from IUnknown, the IDirectMusicBand8 interface exposes the following methods.

Method | Description
CreateSegment | Creates a segment object that can be played to dynamically perform the volume, pan, transposition, and patch change commands in the band.
Download | Downloads the DLS data for instruments in the band to a performance object.
Unload | Unloads the DLS data for instruments in the band previously downloaded.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Using Bands


IDirectMusicBand8::CreateSegment

The CreateSegment method creates a segment object that can be played to dynamically perform the volume, pan, transposition, and patch change commands in the band.

Syntax

HRESULT CreateSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment

Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicBand8 Interface
  • Making Band Changes Programmatically


IDirectMusicBand8::Download

The Download method downloads the DLS data for instruments in the band to a performance object.

Syntax

HRESULT Download(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance

Performance to which instruments are to be downloaded. The performance manages the mapping of performance channels to DirectMusic ports.

Return Values

If the method succeeds, the return value is S_OK, or DMUS_S_PARTIALDOWNLOAD. (See Remarks.)

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

The method downloads each instrument in the band by calling the IDirectMusicPerformance8::DownloadInstrument method. DownloadInstrument, in turn, uses the performance channel of the instrument to find the appropriate port, and then calls the IDirectMusicPort8::DownloadInstrument method on that port.

After a band has been downloaded, the instruments in the band can be selected, either individually with program-change MIDI messages, or all at once by playing a band segment created through a call to the IDirectMusicBand8::CreateSegment method.

Because a downloaded band uses synthesizer resources, it should be unloaded when no longer needed by using the IDirectMusicBand8::Unload method.

This method may return S_OK even though the port does not support DLS.

If the download completely fails, DMUS_E_NOT_INIT is returned. This usually means that the performance was not properly connected to an initialized port. Because this is a complete failure, there is no need to call IDirectMusicBand8::Unload later.

If the download partially succeeds, DMUS_S_PARTIALDOWNLOAD is returned. This means that some of the instruments successfully downloaded and others did not. This usually occurs because of programming error in setting up the performance and port. The best way to find the problem is to set debug traces to 1 for Dmime.dll, Dmband.dll, and Dmsynth.dll. See Debugging DirectMusic Projects.

The following are some common causes of a partial download:

  • The band has instruments on performance channels that have not been set up on the performance (by using IDirectMusicPerformance8::AssignPChannelBlock).
  • The band has instruments on performance channels that are on channel groups not allocated on the port.
  • The band has instruments in a DLS format incompatible with the synthesizer they are being downloaded to.

Requirements

Header: Declared in dmusici.h.

See Also

  • Downloading and Unloading Bands
  • IDirectMusicBand8 Interface
  • IDirectMusicBand8::Unload


IDirectMusicBand8::Unload

The Unload method unloads the DLS data for instruments in the band previously downloaded by IDirectMusicBand8::Download.

Syntax

HRESULT Unload(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance

Performance from which to unload instruments.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
DMUS_E_NOT_FOUND

Requirements

Header: Declared in dmusici.h.

See Also

  • Downloading and Unloading Bands
  • IDirectMusicBand8 Interface
  • IDirectMusicPort8::UnloadInstrument


IDirectMusicBuffer8 Interface

The IDirectMusicBuffer8 interface represents a buffer containing time-stamped data (typically in the form of MIDI messages) being sequenced to a port. The buffer contains a small amount of data, typically less than 200 milliseconds. Unless your application is doing its own sequencing, you do not need to use the methods of this interface.

IDirectMusicBuffer8 is a type definition for IDirectMusicBuffer. The two interface names are interchangeable.

Buffer objects are completely independent of port objects until the buffer is passed to the port by a call to the IDirectMusicPort8::PlayBuffer or the IDirectMusicPort8::Read method. The application is then free to reuse the buffer.

In addition to the methods inherited from IUnknown, the IDirectMusicBuffer8 interface exposes the following methods.

Method | Description
Flush | Discards all data in the buffer.
GetBufferFormat | Retrieves the GUID that represents the buffer format.
GetMaxBytes | Retrieves the number of bytes that can be stored in the buffer.
GetNextEvent | Returns information about the next message in the buffer and advances the read pointer.
GetRawBufferPtr | Returns a pointer to the underlying buffer data structure.
GetStartTime | Retrieves the start time of the data in the buffer, relative to the master clock.
GetUsedBytes | Retrieves the number of bytes of data in the buffer.
PackStructured | Inserts fixed-length data (typically a MIDI channel message), along with timing and routing information, into the buffer.
PackUnstructured | Inserts unstructured data (typically a MIDI system-exclusive message), along with timing and routing information, into the buffer
ResetReadPtr | Sets the read pointer to the start of the data in the buffer.
SetStartTime | Sets the start time of the data in the buffer, relative to the master clock.
SetUsedBytes | Sets the number of bytes of data in the buffer.
TotalTime | Returns the total time spanned by the data in the buffer.

The LPDIRECTMUSICBUFFER8 type is defined as a pointer to the IDirectMusicBuffer8 interface:

typedef IDirectMusicBuffer8 *LPDIRECTMUSICBUFFER8;

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • IDirectMusic8::CreateMusicBuffer


IDirectMusicBuffer8::Flush

The Flush method discards all data in the buffer.

Syntax

HRESULT Flush();

Parameters

None.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface


IDirectMusicBuffer8::GetBufferFormat

The GetBufferFormat method retrieves the GUID that represents the buffer format.

Syntax

HRESULT GetBufferFormat(
  LPGUID pGuidFormat
);

Parameters

pGuidFormat

Address of a variable that receives the GUID of the buffer format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If the format was not specified when the buffer was created, KSDATAFORMAT_SUBTYPE_DIRECTMUSIC is returned in *pGuidFormat.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DMUS_EVENTHEADER
  • IDirectMusic8::CreateMusicBuffer
  • IDirectMusicBuffer8 Interface


IDirectMusicBuffer8::GetMaxBytes

The GetMaxBytes method retrieves the number of bytes that can be stored in the buffer.

Syntax

HRESULT GetMaxBytes(
  LPDWORD pcb
);

Parameters

pcb

Address of a variable that receives the maximum number of bytes that the buffer can hold.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface


IDirectMusicBuffer8::GetNextEvent

The GetNextEvent method returns information about the next message in the buffer and advances the read pointer.

Syntax

HRESULT GetNextEvent(
  LPREFERENCE_TIME prt,
  LPDWORD pdwChannelGroup,
  LPDWORD pdwLength,
  LPBYTE* ppData
);

Parameters

prt

Address of a variable that receives the time of the message.

pdwChannelGroup

Address of a variable that receives the channel group of the message.

pdwLength

Address of a variable that receives the length, in bytes, of the message.

ppData

Address of a variable that receives a pointer to the message data.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there are no messages in the buffer.

If it fails, the method can return E_POINTER.

Remarks

Any of the passed pointers can be NULL if the item is not needed.

The pointer returned in ppData is valid only for the lifetime of the buffer object.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::ResetReadPtr


IDirectMusicBuffer8::GetRawBufferPtr

The GetRawBufferPtr method returns a pointer to the underlying buffer data structure.

Syntax

HRESULT GetRawBufferPtr(
  LPBYTE* ppData
);

Parameters

ppData

Address of a variable that receives a pointer to the buffer's data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

This method returns a pointer to the raw data of the buffer. The format of the data depends on the implementation. The lifetime of the data is the same as the lifetime of the buffer object; therefore, the returned pointer should not be held after the next call to the IDirectMusicBuffer8::Release method.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface


IDirectMusicBuffer8::GetStartTime

The GetStartTime method retrieves the start time of the data in the buffer, relative to the master clock.

Syntax

HRESULT GetStartTime(
  LPREFERENCE_TIME prt
);

Parameters

prt

Address of a variable that receives the start time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_BUFFER_EMPTY
E_POINTER

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::SetStartTime
  • IDirectMusicBuffer8::TotalTime


IDirectMusicBuffer8::GetUsedBytes

The GetUsedBytes method retrieves the number of bytes of data in the buffer.

Syntax

HRESULT GetUsedBytes(
  LPDWORD pcb
);

Parameters

pcb

Address of a variable that receives the number of used bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::SetUsedBytes


IDirectMusicBuffer8::PackStructured

The PackStructured method inserts fixed-length data (typically a MIDI channel message), along with timing and routing information, into the buffer.

Syntax

HRESULT PackStructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD dwChannelMessage
);

Parameters

rt

Absolute time of the message. (See Remarks.)

dwChannelGroup

Channel group to which the data belongs.

dwChannelMessage

Data (MIDI message) to pack.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_INVALID_EVENT
E_OUTOFMEMORY

Remarks

At least 32 bytes (the size of DMUS_EVENTHEADER plus dwChannelMessage) must be free in the buffer.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort8::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::PackUnstructured


IDirectMusicBuffer8::PackUnstructured

The PackUnstructured method inserts unstructured data (typically a MIDI system-exclusive message), along with timing and routing information, into the buffer.

Syntax

HRESULT PackUnstructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD cb,
  LPBYTE lpb
);

Parameters

rt

Absolute time of the message.

dwChannelGroup

Channel group to which the message belongs.

cb

Size of the data, in bytes.

lpb

Address of a buffer containing the data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_OUTOFMEMORY
E_POINTER

Remarks

This method can be used to send any kind of data to the port.

At least 28 bytes (the size of DMUS_EVENTHEADER) plus the size of the data, padded to a multiple of 4 bytes, must be free in the buffer. The buffer space required can be obtained by using the DMUS_EVENT_SIZE(cb) macro, where cb is the size of the data.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort8::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::PackStructured


IDirectMusicBuffer8::ResetReadPtr

The ResetReadPtr method sets the read pointer to the start of the data in the buffer.

Syntax

HRESULT ResetReadPtr()

Parameters

None.

Return Values

The method always returns S_OK.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::GetNextEvent


IDirectMusicBuffer8::SetStartTime

The SetStartTime method sets the start time of the data in the buffer, relative to the master clock.

Syntax

HRESULT SetStartTime(
  REFERENCE_TIME rt
);

Parameters

rt

New start time for the buffer.

Return Values

The method always returns S_OK.

Remarks

Events already in the buffer are time-stamped relative to the start time and play at the same offset from the new start time.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::GetStartTime


IDirectMusicBuffer8::SetUsedBytes

The SetUsedBytes method sets the number of bytes of data in the buffer.

Syntax

HRESULT SetUsedBytes(
  DWORD cb
);

Parameters

cb

Number of valid data bytes in the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_BUFFER_FULL.

Remarks

This method allows an application to repack a buffer manually. Normally, this should be done only if the data format in the buffer is different from the default format provided by DirectMusic.

The method fails if the specified number of bytes exceeds the maximum buffer size, as returned by the IDirectMusicBuffer8::GetMaxBytes method.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::GetUsedBytes


IDirectMusicBuffer8::TotalTime

The TotalTime method retrieves the total time spanned by the data in the buffer.

Syntax

HRESULT TotalTime(
  LPREFERENCE_TIME prtTime
);

Parameters

prtTime

Address of a variable that receives the total time spanned by the buffer, in units of 100 nanoseconds.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicBuffer8 Interface
  • IDirectMusicBuffer8::GetStartTime


IDirectMusicChordMap8 Interface

The IDirectMusicChordMap8 interface represents a chordmap. Chordmaps provide the composer (represented by the IDirectMusicComposer8 interface) with the information needed to create chord progressions for segments composed at run time. Chordmaps can also be used to change the chords in an existing segment.

The DirectMusicChordMap object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

IDirectMusicChordMap8 is a type definition for IDirectMusicChordMap. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicChordMap8 interface exposes the following method.

Method | Description
GetScale | Retrieves the scale associated with the chordmap.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Using Chordmaps


IDirectMusicChordMap8::GetScale

The GetScale method retrieves the scale associated with the chordmap.

Syntax

HRESULT GetScale(
  DWORD* pdwScale
);

Parameters

pdwScale

Address of a variable that receives the scale value.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Remarks

The scale is defined by the bits in a DWORD, split into a scale pattern in the lower 24 bits and a root in the upper 8 bits. For the scale pattern, the low bit (0x0001) is the lowest note in the scale, the next higher (0x0002) is a semitone higher, and so on for two octaves. The upper 8 bits give the root of the scale as an integer between 0 and 23 (low C to middle B).

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicChordMap8 Interface
  • Using Chordmaps


IDirectMusicCollection8 Interface

The IDirectMusicCollection8 interface manages an instance of a DLS file. The collection provides methods to access instruments and download them to the synthesizer by means of the IDirectMusicPort8 interface.

IDirectMusicCollection8 is a type definition for IDirectMusicCollection. The two interface names are interchangeable.

The DirectMusicCollection object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

In addition to the methods inherited from IUnknown, the IDirectMusicCollection8 interface exposes the following methods.

Method | Description
EnumInstrument | Retrieves the patch and name of an instrument by its index in the collection.
GetInstrument | Retrieves an instrument by its patch number.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • Using Instrument Collections


IDirectMusicCollection8::EnumInstrument

The EnumInstrument method retrieves the patch number and name of an instrument by its index in the collection.

Syntax

HRESULT EnumInstrument(
  DWORD dwIndex,
  DWORD* pdwPatch,
  LPWSTR pwszName,
  DWORD dwNameLen
);

Parameters

dwIndex

Index of the instrument in the collection.

pdwPatch

Address of a variable that receives the patch number.

pwszName

Address of a buffer that receives the instrument name. Can be NULL if the name is not wanted.

dwNameLen

Number of WCHAR elements in the instrument name buffer.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no instrument with that index number.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

To enumerate all instruments in a collection, start with a dwIndex of 0 and increment until EnumInstrument returns S_FALSE.

The patch number returned in pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. For more information, see MIDI Channel Messages.

Although the ordering of the enumeration is consistent within one instance of a DLS collection, it has no relationship to the ordering of instruments in the file, their patch numbers, or their names.

For an example of instrument enumeration, see Working with Instruments.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicCollection8 Interface
  • Using Instrument Collections


IDirectMusicCollection8::GetInstrument

The GetInstrument method retrieves an instrument by its patch number.

Syntax

HRESULT GetInstrument(
  DWORD dwPatch,
  IDirectMusicInstrument** ppInstrument
);

Parameters

dwPatch

Instrument patch number.

ppInstrument

Address of a variable that receives a pointer to the IDirectMusicInstrument8 interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_INVALIDPATCH
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

The patch number passed in dwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. MSB is shifted left 16 bits, and LSB is shifted left 8 bits. In addition, the high bit is set (0x80000000) if the instrument is specifically a drum kit intended to be played on MIDI channel 10.

For an example of how this method is used, see Working with Instruments.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicCollection8 Interface
  • MIDI Channel Messages
  • Using Instrument Collections


IDirectMusicComposer8 Interface

The IDirectMusicComposer8 interface enables access to the composition engine. In addition to building new segments from templates and chordmaps, the composer can generate transitions between different segments. It can also apply a chordmap to an existing segment, thus altering the chord progression and the mood of the music.

IDirectMusicComposer8 is a define for IDirectMusicComposer. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicComposer8 interface exposes the following methods.

Method | Description
AutoTransition | Composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.
ChangeChordMap | Modifies the chords and scale pattern of an existing segment to reflect a new chordmap.
ComposeSegmentFromShape | Creates an original segment from a style and a chordmap, based on a predefined shape.
ComposeSegmentFromTemplate | Creates an original segment from a style, a chordmap, and a template.
ComposeTemplateFromShape | Creates a new template segment, based on a predefined shape.
ComposeTransition | Composes a transition from a measure inside one segment to another.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Using Compositional Elements


IDirectMusicComposer8::AutoTransition

The AutoTransition method composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.

Syntax

HRESULT AutoTransition(
  IDirectMusicPerformance* pPerformance,
  IDirectMusicSegment* pToSeg,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg,
  IDirectMusicSegmentState** ppToSegState,
  IDirectMusicSegmentState** ppTransSegState
);

Parameters

pPerformance

Performance in which to make the transition.

pToSeg

Segment to which the transition should smoothly flow. (See Remarks.)

wCommand

Embellishment to use when composing the transition. This can be one of the values of the DMUS_COMMANDT_TYPES enumeration, or a value defined in DirectMusic Producer as a custom embellishment. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to the current primary segment and an introduction to pToSeg.

dwFlags

Composition options. See DMUS_COMPOSEF_FLAGS.

pChordMap

Pointer to the IDirectMusicChordMap8 interface of the chordmap to be used when composing the transition.

ppTransSeg

Address of a variable that receives a pointer to the created segment. This value can be NULL, in which case the pointer is not returned.

ppToSegState

Address of a variable that receives a pointer to the segment state created by the performance (pPerformance) for the segment following the transition (pToSeg). (See Remarks.)

ppTransSegState

Address of a variable that receives a pointer to the segment state created by the performance (pPerformance) for the created segment (ppTransSeg). (See Remarks.)

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
E_INVALIDARG
E_POINTER

Remarks

The value in pToSeg can be NULL as long as dwFlags does not include DMUS_COMPOSEF_MODULATE. If pToSeg is NULL or does not contain a style track (as would be the case if it is based on a MIDI file), introductory embellishments are not valid. If the currently playing segment is NULL or does not contain a style track, then fill, break, end, and groove embellishments are not valid. If no style track is available either in the currently playing segment or in the one represented by pToSeg, all embellishments are invalid, and no transition occurs. In that case, both ppTransSeg and ppTransSegState return NULL, but the method succeeds and cues the segment represented by pToSeg, if that pointer is not NULL.

The value in pChordMap can be NULL. If it is, the composition engine attempts to obtain a chordmap from a chordmap track, first from pToSeg, and then from the performance's primary segment. If neither of these segments contains a chordmap track, the chord occurring at the current time in the primary segment is used as the chord in the transition.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • IDirectMusicComposer8::ComposeTransition
  • Using Transitions


IDirectMusicComposer8::ChangeChordMap

The ChangeChordMap method modifies the chords and scale pattern of an existing segment to reflect a new chordmap.

Syntax

HRESULT ChangeChordMap(
  IDirectMusicSegment* pSegment,
  BOOL fTrackScale,
  IDirectMusicChordMap* pChordMap
);

Parameters

pSegment

Pointer to the IDirectMusicSegment8 interface of the segment in which to change the chordmap. This segment must contain a chordmap track and a style.

fTrackScale

If TRUE, the method transposes all the chords to be relative to the root of the new chordmap's scale, rather than leaving their roots as they were.

pChordMap

Pointer to the IDirectMusicChordMap8 interface of the new chordmap for the segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method can be called while the segment is playing.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • Using Chordmaps


IDirectMusicComposer8::ComposeSegmentFromShape

The ComposeSegmentFromShape method creates an original segment from a style and a chordmap, based on a predefined shape. The shape represents the way chords and embellishments occur over time across the segment.

Syntax

HRESULT ComposeSegmentFromShape(
  IDirectMusicStyle* pStyle,
  WORD wNumMeasures,
  WORD wShape,
  WORD wActivity,
  BOOL fIntro,
  BOOL fEnd,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle

Style from which to compose the segment.

wNumMeasures

Length, in measures, of the segment to be composed.

wShape

Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.

wActivity

Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.

fIntro

TRUE if an introduction is to be composed for the segment.

fEnd

TRUE if an ending is to be composed for the segment.

pChordMap

Pointer to the IDirectMusicChordMap8 interface of the chordmap from which to create the segment.

ppSegment

Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • IDirectMusicComposer8::ComposeSegmentFromTemplate
  • IDirectMusicComposer8::ComposeTemplateFromShape
  • Using Compositional Elements


IDirectMusicComposer8::ComposeSegmentFromTemplate

The ComposeSegmentFromTemplate method creates an original segment from a style, a chordmap, and a template.

Syntax

HRESULT ComposeSegmentFromTemplate(
  IDirectMusicStyle* pStyle,
  IDirectMusicSegment* pTemplate,
  WORD wActivity,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle

IDirectMusicStyle8 interface pointer that specifies the style from which to create the segment.

pTemplate

IDirectMusicSegment8 interface pointer that specifies the template from which to create the segment.

wActivity

Rate of harmonic motion. Valid values are 0 through 3. Lower values mean more chord changes.

pChordMap

IDirectMusicChordMap8 interface pointer that specifies the chordmap from which to create the segment.

ppSegment

Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

If pStyle is not NULL, it is used in composing the segment; if it is NULL, a style is retrieved from the template specified in pTempSeg. Similarly, if pChordMap is not NULL, it is used in composing the segment; if it is NULL, a chordmap is retrieved from the template.

If pStyle is NULL and there is no style track in the template, or pChordMap is NULL and there is no chordmap track, the method returns E_INVALIDARG.

The length of the segment is equal to the length of the template passed in.

The default start point and loop points of the created segment are 0, regardless of the values in the template segment.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • IDirectMusicComposer8::ComposeSegmentFromShape
  • IDirectMusicComposer8::ComposeTemplateFromShape
  • Using Templates


IDirectMusicComposer8::ComposeTemplateFromShape

The ComposeTemplateFromShape method creates a new template segment, based on a predefined shape.

Syntax

HRESULT ComposeTemplateFromShape(
  WORD wNumMeasures,
  WORD wShape,
  BOOL fIntro,
  BOOL fEnd,
  WORD wEndLength,
  IDirectMusicSegment** ppTemplate
);

Parameters

wNumMeasures

Length, in measures, of the segment to be composed. This value must be greater than 0.

wShape

Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.

fIntro

TRUE if an introduction is to be composed for the segment.

fEnd

TRUE if an ending is to be composed for the segment.

wEndLength

Length in measures of the ending, if one is to be composed. If fEnd is TRUE, this value must be greater than 0 and equal to or less than the number of measures available (that is, not used in the introduction). (See Remarks.)

ppTemplate

Address of a variable that receives a pointer to the created template segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value of wEndLength should not be greater than the length of the longest ending available in any style likely to be associated with this template through the IDirectMusicComposer8::ComposeSegmentFromTemplate method. The ending starts playing at wEndLength measures before the end of the segment. If the ending is less than wEndLength measures long, the music then reverts to patterns from the basic groove level.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • IDirectMusicComposer8::ComposeSegmentFromTemplate
  • Using Templates


IDirectMusicComposer8::ComposeTransition

The ComposeTransition method composes a transition from a measure inside one segment to another segment.

Syntax

HRESULT ComposeTransition(
  IDirectMusicSegment* pFromSeg,
  IDirectMusicSegment* pToSeg,
  MUSIC_TIME mtTime,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg
);

Parameters

pFromSeg

Segment from which to compose the transition.

pToSeg

Segment to which the transition should smoothly flow. Can be NULL if dwFlags does not include DMUS_COMPOSEF_MODULATE.

mtTime

Time in pFromSeg from which to compose the transition.

wCommand

Embellishment to use when composing the transition. This can be one of the DMUS_COMMANDT_TYPES enumeration, or a value defined in DirectMusic Producer as a custom embellishment. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to pFromSeg and an introduction to pToSeg.

dwFlags

Composition options. This parameter can contain one or more values from the DMUS_COMPOSEF_FLAGS enumerated type.

pChordMap

Pointer to the IDirectMusicChordMap8 interface of the chordmap to be used when composing the transition. (See Remarks.)

ppTransSeg

Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value in pChordMap can be NULL. If it is, an attempt is made to obtain a chordmap from a chordmap track, first from pToSeg, and then from pFromSeg. If neither of these segments contains a chordmap track, the chord occurring at mtTime in pFromSeg is used as the chord in the transition.

The composer looks for a tempo, first in pFromSeg, and then in pToSeg. If neither of those segments contains a tempo track, the tempo for the transition segment is taken from the style.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicComposer8 Interface
  • IDirectMusicComposer8::AutoTransition
  • Using Transitions


IDirectMusicContainer8 Interface

The IDirectMusicContainer8 interface provides access to objects in a container, which is a collection of objects used by a segment or performance. The interface can be obtained when a container is loaded by a call to IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile.

When a container object is loaded, it makes all its objects available to the loader. When the container is released, all objects it refers to are released from the loader. However, any objects still in use when the container is released are not freed until explicitly released. If they are keeping a stream open, as DLS collections and streaming waveforms do, the stream also stays open. As a result, the container file stays locked, just as an individual WAV or DLS file would.

A container can be embedded in a segment. The container is placed in the file before the segment's tracks, so it can be read and its objects installed in the loader before the tracks are loaded. When the tracks are loaded, the loader is able to supply links to referenced objects in the container.

IDirectMusicContainer8 is a type definition for IDirectMusicContainer. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicContainer8 interface exposes the following method.

Method | Description
EnumObject | Retrieves information about an object in the container.

Requirements

Header: Declared in dmusici.h.

See Also

  • Containers
  • DirectMusic Interfaces


IDirectMusicContainer8::EnumObject

The EnumObject method retrieves information about an object in the container.

Syntax

HRESULT EnumObject(
  REFGUID rguidClass,
  DWORD dwIndex,
  LPDMUS_OBJECTDESC pDesc,
  WCHAR* pwszAlias
);

Parameters

rguidClass

Reference to (C++) or address of (C) the unique identifier of the object class, or GUID_DirectMusicAllTypes to obtain an object of any type. For a list of standard loadable classes, see IDirectMusicLoader8.

dwIndex

Index of the object among objects of class rguidClass in the container.

pDesc

Pointer to a DMUS_OBJECTDESC structure that receives a description of the object. This parameter can be NULL if no description is wanted. (See Remarks.)

pwszAlias

Address of a string buffer of size MAX_PATH that receives the object's alias, if it has one. (An alias is a special name used by a script to refer to the object.) This parameter can be NULL if no alias is wanted.

Return Values

If the method succeeds, one of the following success codes is returned.

Return code | Description
S_OK | The object was enumerated.
S_FALSE | There is no object with an index of dwIndex.
DMUS_S_STRING_TRUNCATED | The alias is longer than MAX_PATH.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, it can return E_POINTER.

Remarks

You must initialize the dwSize member of the DMUS_OBJECTDESC structure before passing it to the method. Other members are ignored. You cannot reduce the scope of the enumeration by, for example, specifying a value in the wszName member. The description returned by the method can be used to retrieve the object by calling IDirectMusicLoader8::GetObject. For sample code, see Containers.

Requirements

Header: Declared in dmusici.h.

See Also

  • Containers
  • IDirectMusicContainer8 Interface


IDirectMusicDownload8 Interface

The IDirectMusicDownload8 interface represents a contiguous memory chunk used for downloading to a DLS synthesizer port.

IDirectMusicDownload8 is a type definition for IDirectMusicDownload. The two interface names are interchangeable.

The IDirectMusicDownload8 interface and its contained memory chunk are created by the IDirectMusicPortDownload8::AllocateBuffer method. The memory can then be accessed by using the single method of this interface.

This interface is used only by applications that need to access DLS buffers directly rather than letting the performance, band, and segment objects download instrument data. For an overview, see Low-Level DLS.

In addition to the methods inherited from IUnknown, the IDirectMusicDownload8 interface exposes the following method.

Method | Description
GetBuffer | Retrieves a pointer to a buffer containing data to be downloaded.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • Low-Level DLS


IDirectMusicDownload8::GetBuffer

The GetBuffer method retrieves a pointer to a buffer containing data to be downloaded.

Syntax

HRESULT GetBuffer(
  void** ppvBuffer,
  DWORD* pdwSize
);

Parameters

ppvBuffer

Address of a variable that receives a pointer to the data buffer.

pdwSize

Address of a variable that receives the size of the returned buffer, in bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_BUFFERNOTAVAILABLE
E_POINTER

Remarks

The method returns DMUS_E_BUFFERNOTAVAILABLE if the buffer has already been downloaded.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicDownload8 Interface
  • Low-Level DLS


IDirectMusicDownloadedInstrument8 Interface

The IDirectMusicDownloadedInstrument8 interface is used to identify an instrument that has been downloaded to the synthesizer by using the IDirectMusicPort8::DownloadInstrument or the IDirectMusicPerformance8::DownloadInstrument method. The interface pointer is then used to unload the instrument through a call to IDirectMusicPort8::UnloadInstrument. After the instrument has been unloaded, the interface pointer must be released by the application. For an example, see Working with Instruments.

IDirectMusicDownloadedInstrument8 is a type definition for IDirectMusicDownloadedInstrument. The two interface names are interchangeable.

The IDirectMusicDownloadedInstrument8 interface has no methods other than those inherited from IUnknown.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • Low-Level DLS


IDirectMusicGetLoader8 Interface

The IDirectMusicGetLoader8 interface is used by an object parsing a stream when the object needs to load another object referenced by the stream. If a stream supports the loader, it must provide an IDirectMusicGetLoader8 interface.

For an example of how to obtain the IDirectMusicGetLoader8 interface from the stream, see IDirectMusicGetLoader8::GetLoader.

IDirectMusicGetLoader8 is a type definition for IDirectMusicGetLoader. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicGetLoader8 interface exposes the following method.

Method | Description
GetLoader | Retrieves a pointer to the loader object that created the stream.

Requirements

Header: Declared in dmusici.h.

See Also

See Also

  • Custom Loading
  • IDirectMusicLoader8 Interface
  • Loading Audio Data


IDirectMusicGetLoader8::GetLoader

The GetLoader method retrieves a pointer to the loader object that created the stream.

Syntax

HRESULT GetLoader8(
  IDirectMusicLoader ** ppLoader
);

Parameters

ppLoader

Address of a variable that receives the IDirectMusicLoader interface pointer. Use QueryInterface to obtain IDirectMusicLoader8. The reference count of the interface is incremented.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_NOINTERFACE.

Remarks

The following example function finds a reference to an object that needs to be accessed by the loader:

HRESULT GetReferencedObject(
  DMUS_OBJECTDESC *pDesc,          // Description of object.
  IStream *pIStream,               // Stream being parsed.
  IDirectMusicObject **ppIObject)  // Object to be accessed.
{
  IDirectMusicGetLoader *pIGetLoader;
  IDirectMusicLoader *pILoader;
  ppIObject = NULL;
  HRESULT hr = pIStream->QueryInterface(
     IID_IDirectMusicGetLoader,
     (void **) &pIGetLoader);
  if (SUCCEEDED(hr))
  {
    hr = pIGetLoader->GetLoader(&pILoader);
    if (SUCCEEDED(hr))
    {
    hr = pILoader->GetObject(pDesc, IID_IDirectMusicLoader,
      (void**) ppIObject);
    pILoader->Release();
    }
    pIGetLoader->Release();
  }
  return hr;
}

Requirements

Header: Declared in dmusici.h.

See Also

  • Custom Loading
  • IDirectMusicGetLoader8 Interface


IDirectMusicGraph8 Interface

The IDirectMusicGraph8 interface manages the loading and message flow of tools.

Graphs can occur in two places: performances and segments. The graph of tools in a performance is global in nature; it processes messages from all segments. A graph in a segment exists only for playback of that segment.

IDirectMusicGraph8 is a type definition for IDirectMusicGraph. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicGraph8 interface exposes the following methods.

Method | Description
GetTool | Retrieves a tool by index.
InsertTool | Inserts a tool in the graph.
RemoveTool | Removes a tool from the graph.
StampPMsg | Stamps a message with a pointer to the next tool that is to receive it.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • DirectMusic Tools


IDirectMusicGraph8::GetTool

The GetTool method retrieves a tool by index.

Syntax

HRESULT GetTool(
  DWORD dwIndex,
  IDirectMusicTool** ppTool
);

Parameters

dwIndex

Zero-based index of the requested tool in the graph.

ppTool

Address of a variable that receives a pointer to the tool.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

The application is responsible for releasing the retrieved tool.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicGraph8 Interface


IDirectMusicGraph8::InsertTool

The InsertTool method inserts a tool in the graph.

Note Do not use or distribute tools from untrusted sources. Tools can contain unsafe code.

Syntax

HRESULT InsertTool(
  IDirectMusicTool * pTool,
  DWORD * pdwPChannels,
  DWORD cPChannels,
  LONG lIndex
);

Parameters

pTool

Tool to insert.

pdwPChannels

Address of an array of performance channels on which the tool accepts messages. If the tool accepts messages on all channels, pass NULL.

cPChannels

Count of how many channels are pointed to by pdwPChannels. Ignored if pdwPChannels is NULL.

lIndex

Position at which to place the tool. This is a zero-based index from the start of the current tool list or, if it is negative, from the end of the list. If lIndex is out of range, the tool is placed at the beginning or end of the list. To place a tool at the end of the list, use a value that is larger than the number of tools in the current tool list.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_ALREADY_EXISTS
E_OUTOFMEMORY
E_POINTER

Remarks

The reference count of the tool is incremented.

This method calls IDirectMusicTool8::Init.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicGraph8 Interface


IDirectMusicGraph8::RemoveTool

The RemoveTool method removes a tool from the graph.

Syntax

HRESULT RemoveTool(
  IDirectMusicTool * pTool
);

Parameters

pTool

Tool to remove.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

The graph's reference to the tool object is released.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicGraph8 Interface


IDirectMusicGraph8::StampPMsg

The StampPMsg method stamps a message with a pointer to the next tool that is to receive it. After processing a message, a tool must call this method.

Syntax

HRESULT StampPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG

Address of a structure that contains the message to stamp. This structure is of a type derived from DMUS_PMSG.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_LAST_TOOL. (See Remarks.)

If it fails, the method can return E_POINTER.

Remarks

On entry, the pTool member of the DMUS_PMSG part of the message structure points to the current tool. StampPMsg uses this member to find the next tool in the graph. A value of NULL represents the first tool in the graph.

The object pointed to by the pGraph member represents the graph that contains the tool. This is stamped inside StampPMsg, along with the tool itself, and can change while the message travels from the segment state to the performance because there can be multiple toolgraphs.

The value of dwType equals the media type of the message, and is also used to find the next tool. The media types supported are those returned by the IDirectMusicTool8::GetMediaTypes method.

This method calls Release on the current IDirectMusicTool8 pointed to by pTool, replaces it with the next tool in the graph and calls AddRef on the new tool. It also flags the message with the correct delivery type, according to what type the next tool returns in its IDirectMusicTool8::GetMsgDeliveryType method. This flag determines when the message is delivered to the next tool.

Tools should not call StampPMsg until all other tasks have been performed. When audiopaths are in use, StampPMsg can have the effect of changing the value in the dwPChannel member of the message structure. A tool that uses this value cannot rely on it if StampPMsg has already been called

The implementations of this method in the segment state and performance objects always return S_OK on success. The implementation in the graph returns DMUS_S_LAST_TOOL if there is no tool other than the output tool waiting to receive the message.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicGraph8 Interface


IDirectMusicInstrument8 Interface

The IDirectMusicInstrument8 interface represents an individual instrument from a DLS collection.

IDirectMusicInstrument8 is a type definition for IDirectMusicInstrument. The two interface names are interchangeable.

To create an instrument object, first create a collection object, and then call the IDirectMusicCollection8::GetInstrument method. GetInstrument creates an instrument object and returns its IDirectMusicInstrument8 interface pointer.

To download the instrument, pass its interface pointer to the IDirectMusicPort8::DownloadInstrument or IDirectMusicPerformance8::DownloadInstrument method. If the method succeeds, it returns a pointer to an IDirectMusicDownloadedInstrument8 interface, which is used only to unload the instrument.

The methods of IDirectMusicInstrument8 operate only on an instrument that has not been downloaded. Any instances of the instrument that have been downloaded to a port are not affected by the IDirectMusicInstrument8::SetPatch method.

In addition to the methods inherited from IUnknown, the IDirectMusicInstrument8 interface exposes the following methods.

Method | Description
GetPatch | Retrieves the patch number for the instrument.
SetPatch | Sets the patch number for the instrument.

The LPDIRECTMUSICINTRUMENT8 type is defined as a pointer to this interface:

typedef IDirectMusicInstrument8 *LPDIRECTMUSICINSTRUMENT8;

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • Working with Instruments


IDirectMusicInstrument8::GetPatch

The GetPatch method retrieves the patch number for the instrument. The patch number is an address composed of the MSB and LSB bank select and the MIDI patch (program change) number. An optional flag bit indicates that the instrument is a drum, rather than a melodic instrument.

Syntax

HRESULT GetPatch(
  DWORD* pdwPatch
);

Parameters

pdwPatch

Address of a variable that receives the patch number.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_POINTER

Remarks

The patch number returned at pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. In addition, the high bit is set if the instrument is a drum kit.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicInstrument8 Interface
  • MIDI Channel Messages
  • Working with Instruments


IDirectMusicInstrument8::SetPatch

The SetPatch method sets the patch number for the instrument. Although each instrument in a DLS collection has a predefined patch number, the patch number can be reassigned after the IDirectMusicCollection8::GetInstrument method has been used to retrieve the instrument from the collection. For more information on DirectMusic patch numbers, see IDirectMusicInstrument8::GetPatch.

Syntax

HRESULT SetPatch(
  DWORD dwPatch
);

Parameters

dwPatch

Patch number to assign.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
DMUS_E_INVALIDPATCH

Remarks

The following code example gets an instrument from a collection, remaps its MSB bank select to a different bank, and then downloads the instrument:

HRESULT RemappedDownload(
    IDirectMusicCollection8 *pCollection,
    IDirectMusicPort8 *pPort,
    IDirectMusicDownloadedInstrument8 **ppDLInstrument,
    BYTE bMSB,
    DWORD dwPatch)

{
  HRESULT hr;
  IDirectMusicInstrument8* pInstrument;
  hr = pCollection->GetInstrument(dwPatch, &pInstrument);
  if (SUCCEEDED(hr))
  {
    dwPatch &= 0xFF00FFFF;
    dwPatch |= bMSB << 16;
    pInstrument->SetPatch(dwPatch);
    hr = pPort->DownloadInstrument(pInstrument,
                                   ppDLInstrument, NULL, 0);
    pInstrument->Release();
  }
  return hr;
}

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicInstrument8 Interface
  • MIDI Channel Messages
  • Working with Instruments


IDirectMusicLoader8 Interface

The IDirectMusicLoader8 interface is used for finding, enumerating, caching, and loading objects. For an overview, see Loading Audio Data.

This interface supersedes IDirectMusicLoader and adds support for garbage collection.

In addition to the methods inherited from IUnknown, the IDirectMusicLoader8 interface exposes the following methods.

Method | Description
CacheObject | Stores a reference to an object for later use, so that the object is not loaded more than once.
ClearCache | Removes all saved references to a specified object type.
CollectGarbage | Removes from the cache objects that are no longer in use.
EnableCache | Enables or disables automatic caching of all objects loaded.
EnumObject | Enumerates all available objects of the specified type.
GetObject | Retrieves an object from a file or resource.
LoadObjectFromFile | Retrieves an object from a file.
ReleaseObjectByUnknown | Releases the loader's reference to an object.
ReleaseObject | Releases the loader's reference to an object.
ScanDirectory | Searches a directory or disk for all files of a specified class type and file name extension.
SetObject | Enables the loader to find an object when it is later referenced by another object that is being loaded, and adds attributes to an object so that it can be identified by those attributes.
SetSearchDirectory | Sets a search path for finding object files.

The LPDMUS_LOADER type is defined as a pointer to the IDirectMusicLoader interface:

typedef IDirectMusicLoader __RPC_FAR *LPDMUS_LOADER;

The following table lists the standard types of loadable objects, together with their class identifiers (the rguidClass parameter of various methods that deal with objects) and the usual file name extension.

Object type | Class | Extension
Audiopath | CLSID_DirectMusicAudioPathConfig | aud
Band | CLSID_DirectMusicBand | bnd
Container | CLSID_DirectMusicContainer | con
DLS collection | CLSID_DirectMusicCollection | dls
Chordmap | CLSID_DirectMusicChordMap | cdm
Segment | CLSID_DirectMusicSegment | sgt
Script | CLSID_DirectMusicScript | spt
Style | CLSID_DirectMusicStyle | sty
Template | CLSID_DirectMusicSegment | tpl
Toolgraph | CLSID_DirectMusicGraph | tgr
Wave | CLSID_DirectSoundWave | wav

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Loading Audio Data


IDirectMusicLoader8::CacheObject

The CacheObject method stores a reference to an object for later use, so that the object is not loaded more than once.

Syntax

HRESULT CacheObject(
  IDirectMusicObject * pObject
);

Parameters

pObject

Address of the IDirectMusicObject interface of the object to cache. Use QueryInterface to obtain IDirectMusicObject8.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object is already cached.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
DMUS_E_LOADER_OBJECTNOTFOUND

Requirements

Header: Declared in dmusici.h.

See Also

  • Cache Management
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::ClearCache
  • IDirectMusicLoader8::EnableCache
  • IDirectMusicLoader8::ReleaseObject


IDirectMusicLoader8::ClearCache

The ClearCache method removes all saved references to a specified object type.

Syntax

HRESULT ClearCache(
  REFGUID rguidClass
);

Parameters

rguidClass

Reference to (C++) or address of (C) the identifier of the class of objects to clear, or GUID_DirectMusicAllTypes to clear all types. For a list of standard loadable classes, see IDirectMusicLoader8.

Return Values

The method returns S_OK.

Remarks

This method clears all objects that are currently being held, but does not turn off caching. Use the IDirectMusicLoader8::EnableCache method to turn off automatic caching.

To clear a single object from the cache, call the IDirectMusicLoader8::ReleaseObject method.

Requirements

Header: Declared in dmusici.h.

See Also

  • Cache Management
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::CacheObject


IDirectMusicLoader8::CollectGarbage

The CollectGarbage method removes from the cache objects that are no longer in use.

Syntax

CollectGarbage();

Parameters

None.

Return Values

None.

Remarks

When an application calls IDirectMusicLoader8::ReleaseObject, the object is removed from the cache, and any objects it references become candidates for removal. IDirectMusicLoader8::CollectGarbage finds cached objects that are no longer being used by other objects, removes them from the cache, and releases them from memory.

Requirements

Header: Declared in dmusici.h.

See Also

  • Garbage Collection
  • IDirectMusicLoader8 Interface


IDirectMusicLoader8::EnableCache

The EnableCache method enables or disables automatic caching of all objects it loads. By default, caching is enabled for all classes.

Syntax

HRESULT EnableCache(
  REFGUID rguidClass,
  BOOL fEnable
);

Parameters

rguidClass

Reference to (C++) or address of (C) the identifier of the class of objects to cache or stop caching, or GUID_DirectMusicAllTypes for all types. For a list of standard loadable classes, see IDirectMusicLoader8.

fEnable

TRUE to enable caching; FALSE to clear and disable.

Return Values

The method returns S_OK if the cache state is changed, or S_FALSE if the cache is already in the desired state.

Remarks

When you disable caching for a class, all objects of that class that have already been cached are released.

To clear the cache without disabling caching, call the IDirectMusicLoader8::ClearCache method.

The following code example disables caching only for segment objects so that they do not stay in memory after the application releases them. Other objects that should be shared, such as styles, chordmaps, and DLS collections, continue to be cached. The first call to EnableCache would normally be unnecessary, because caching is enabled for all objects by default.

void PrepareLoader(IDirectMusicLoader8 *pILoader)
{
  pILoader->EnableCache(GUID_DirectMusicAllTypes, TRUE);
  pILoader->EnableCache(CLSID_DirectMusicSegment, FALSE);
}

Requirements

Header: Declared in dmusici.h.

See Also

  • Cache Management
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::CacheObject
  • IDirectMusicLoader8::ClearCache


IDirectMusicLoader8::EnumObject

The EnumObject method enumerates an available object of the requested type. Objects are available if they have been loaded or if IDirectMusicLoader8::ScanDirectory has been called on the search directory.

Syntax

HRESULT EnumObject(
  REFGUID rguidClass,
  DWORD dwIndex,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

rguidClass

Reference to (C++) or address of (C) the identifier for the class of objects to view. For a list of standard loadable classes, see IDirectMusicLoader8.

dwIndex

Zero-based index into the list of matching objects.

pDesc

Address of a DMUS_OBJECTDESC structure to be filled with data about the object.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if dwIndex is past the end of the list.

Requirements

Header: Declared in dmusici.h.

See Also

  • Enumerating Objects
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::ScanDirectory


IDirectMusicLoader8::GetObject

The GetObject method retrieves an object from a file or resource and returns the specified interface.

Syntax

HRESULT GetObject(
  LPDMUS_OBJECTDESC pDesc,
  REFIID riid,
  LPVOID FAR * ppv
);

Parameters

pDesc

Address of a DMUS_OBJECTDESC structure describing the object.

riid

Unique identifier of the interface. See DirectMusic Interface GUIDs.

ppv

Address of a variable that receives a pointer to the desired interface of the object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALLOAD.

DMUS_S_PARTIALLOAD is returned if any referenced object cannot be found, such as a style referenced in a segment. The loader might fail to find the style if it is referenced by name but IDirectMusicLoader8::ScanDirectory has not been called for styles. DMUS_S_PARTIALLOAD might also mean that the default instrument collection file, Gm.dls, is not available.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_LOADER_NOCLASSID
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

For file objects, it is simpler to use the IDirectMusicLoader8::LoadObjectFromFile method.

DirectMusic does not support loading from URLs. If the dwValidData member of the DMUS_OBJECTDESC structure contains DMUS_OBJ_URL, the method returns DMUS_E_LOADER_FORMATNOTSUPPORTED.

The method does not require that all valid members of the DMUS_OBJECTDESC structure match before retrieving an object. The dwValidData flags are evaluated in the following order:

  1. DMUS_OBJ_OBJECT
  2. DMUS_OBJ_STREAM
  3. DMUS_OBJ_MEMORY
  4. DMUS_OBJ_FILENAME and DMUS_OBJ_FULLPATH
  5. DMUS_OBJ_NAME and DMUS_OBJ_CATEGORY
  6. DMUS_OBJ_NAME
  7. DMUS_OBJ_FILENAME

In other words, the highest priority goes to a unique GUID, followed by a stream pointer, followed by a resource, followed by the full file path name, followed by an internal name plus category, followed by an internal name, followed by a local file name.

Do not load data from untrusted sources. Loading DirectMusic data files causes objects to be constructed, with the possibility that excessive demand on resources will lead to degradation of performance or system failure.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::LoadObjectFromFile
  • IDirectMusicLoader8::ReleaseObject
  • IDirectMusicLoader8::ScanDirectory
  • Loading Audio Data


IDirectMusicLoader8::LoadObjectFromFile

The LoadObjectFromFile method retrieves an object from a file and returns the specified interface. This method can be used instead of IDirectMusicLoader8::GetObject when the object is in a file.

Syntax

HRESULT LoadObjectFromFile(
  REFGUID rguidClassID,
  REFIID iidInterfaceID,
  WCHAR *pwzFilePath,
  void ** ppObject
);

Parameters

rguidClassID

Unique identifier for the class of object. For a list of standard loadable classes, see IDirectMusicLoader8.

iidInterfaceID

Unique identifier of the interface. See DirectMusic Interface GUIDs.

pwzFilePath

Name of the file that contains the object. The path can be fully qualified or relative to the search directory. (See Remarks.)

ppObject

Address of a variable that receives a pointer to the desired interface of the object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALLOAD.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_LOADER_NOCLASSID
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

Do not load data from untrusted sources. Loading DirectMusic data files causes objects to be constructed, with the possibility that excessive demand on resources will lead to degradation of performance or system failure.

When pwzFilePath is an unqualified file name or a relative path, the loader searches first in the current directory, then in the Windows search path, and finally in the directory set by the last call to IDirectMusicLoader8::SetSearchDirectory.

DMUS_S_PARTIALLOAD is returned if any referenced object cannot be found, such as a style referenced in a segment. The loader might fail to find the style if it is referenced by name but IDirectMusicLoader8::ScanDirectory has not been called for styles. DMUS_S_PARTIALLOAD might also mean that the default instrument collection file, Gm.dls, is not available.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::GetObject
  • IDirectMusicLoader8::SetSearchDirectory
  • Loading an Object from a File


IDirectMusicLoader8::ReleaseObject

The ReleaseObject method releases the loader's reference to an object.

Syntax

HRESULT ReleaseObject(
  IDirectMusicObject * pObject
);

Parameters

pObject

IDirectMusicObject8 interface pointer of the object to release.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object has already been released or cannot be found in the cache.

If it fails, the method can return E_POINTER.

Remarks

ReleaseObject is the reciprocal of IDirectMusicLoader8::CacheObject.

Objects can be cached explicitly by using the CacheObject method, or automatically by using the IDirectMusicLoader8::EnableCache method.

To tell the loader to flush all objects of a particular type, call the IDirectMusicLoader8::ClearCache method.

Requirements

Header: Declared in dmusici.h.

See Also

  • Cache Management
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::GetObject
  • IDirectMusicLoader8::ReleaseObjectByUnknown


IDirectMusicLoader8::ReleaseObjectByUnknown

The ReleaseObjectByUnknown method releases the loader's reference to an object. This method is similar to IDirectMusicLoader8::ReleaseObject and is suitable for releasing objects for which the IDirectMusicObject8 interface is not readily available.

Syntax

HRESULT ReleaseObject(
  IUnknown * pObject
);

Parameters

pObject

Address of the IUnknown interface pointer of the object to release.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object has already been released or cannot be found in the cache.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • Cache Management
  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::GetObject


IDirectMusicLoader8::ScanDirectory

The ScanDirectory method searches a directory or disk for all files of a specified class type and file name extension. For each file found, it calls the IDirectMusicObject8::ParseDescriptor method to extract the GUID and name of the object. This information is stored in an internal database. After a directory has been scanned, all files of the requested type become available for enumeration through the IDirectMusicLoader8::EnumObject method; in addition, an object can be retrieved by using IDirectMusicLoader8::GetObject, even without a file name.

Syntax

HRESULT ScanDirectory(
  REFGUID rguidClass,
  WCHAR* pwzFileExtension,
  WCHAR* pwzScanFileName
);

Parameters

rguidClass

Reference to (C++) or address of (C) the identifier of the class of objects. For a list of standard loadable classes, see IDirectMusicLoader8.

pwzFileExtension

File name extension for the type of file to look for. Use L"*" to look in files with any or no extension. (See Remarks.)

pwzScanFileName

Name of a file to use for cached file information. This file is created by the first call to ScanDirectory and used by subsequent calls. Pass NULL if a cache file is not wanted.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if no files were found.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_FAIL
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

The IDirectMusicLoader8::SetSearchDirectory method must be called first to set the location to search.

The scanned information can be stored in a cache file defined by pwzScanFileName. After it has been stored, subsequent calls to ScanDirectory are much quicker because only files that have changed are scanned (the cache file stores the file size and date for each object, so it can tell if a file has changed).

GUID_DirectMusicAllTypes is not a valid value for rguidClass.

If the file type has more than one possible extension, call ScanDirectory once for each file name extension.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicLoader8 Interface
  • Scanning a Directory for Objects


IDirectMusicLoader8::SetObject

The SetObject method enables the loader to find an object when it is later referenced by another object that is being loaded, and adds attributes to an object so that it can be identified by those attributes.

Syntax

HRESULT SetObject(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc

Address of a DMUS_OBJECTDESC structure describing the object. On entry, this structure contains any information the application has about the object. On return, it can contain additional information.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_LOADER_NOCLASSID
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

This method can be used to set attributes that are not currently valid for an object. For example, you can supply a value in the wszName member of the DMUS_OBJECTDESC structure to assign an internal name to an unnamed object, such as a segment based on a MIDI file. However, the method cannot be used to change existing attributes. Most authored segments, for example, already have names, and these cannot be changed by the application.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::GetObject
  • Setting Objects


IDirectMusicLoader8::SetSearchDirectory

The SetSearchDirectory method sets a search path for finding object files. The search path can be set for one object file type or for all files.

Syntax

HRESULT SetSearchDirectory(
  REFGUID rguidClass,
  WCHAR* pwszPath,
  BOOL fClear
);

Parameters

rguidClass

Reference to (C++) or address of (C) the identifier of the class of objects that the call pertains to. GUID_DirectMusicAllTypes specifies all objects. For a list of standard loadable classes, see IDirectMusicLoader8.

pwszPath

File path for directory. Must be a valid directory and must be less than MAX_PATH in length. The path, if not fully qualified, is relative to the current directory when IDirectMusicLoader8::ScanDirectory is called.

fClear

If TRUE, clears all information about objects before setting the directory. This prevents the loader from accessing objects in a previous directory when those objects have the same name. However, objects are not removed from the cache.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the search directory is already set to pwszPath.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_LOADER_BADPATH
E_OUTOFMEMORY
E_POINTER

Remarks

After a search path is set, the loader does not need a full path every time it is given an object to load by file name. This enables objects that refer to other objects to find them by file name without knowing the full path.

When this method has been called, the loader expects the wszFileName member of the DMUS_OBJECTDESC structure to contain only a file name or a path relative to the search directory, unless the DMUS_OBJ_FULLPATH flag is set in the dwValidData member.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicLoader8 Interface
  • IDirectMusicLoader8::ScanDirectory
  • Setting the Loader's Search Directory


IDirectMusicObject8 Interface

The IDirectMusicObject8 interface is a generic object interface. All DirectMusic objects that can be loaded from a file or resource support the IDirectMusicObject8 interface so that they can work with the DirectMusic loader. New types of objects must implement this interface.

Most applications do not use the methods of this interface directly. However, IDirectMusicObject8::GetDescriptor can be used to query an object for information, including its name, GUID, file path, and version.

The IDirectMusicObject8 interface is usually obtained by calling another interface's QueryInterface method. It cannot be obtained by using CoCreateInstance. The interface is also returned by IDirectMusicContainer8::EnumObject.

IDirectMusicObject8 is a define for IDirectMusicObject. The two interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectMusicObject8 interface exposes the following methods.

Method | Description
GetDescriptor | Retrieves the object's internal description.
ParseDescriptor | Given a file stream, scans the file for data that it can store in the DMUS_OBJECTDESC structure.
SetDescriptor | Sets some or all members of the object's internal description.

The LPDMUS_OBJECT type is defined as a pointer to the IDirectMusicObject interface:

typedef IDirectMusicObject __RPC_FAR *LPDMUS_OBJECT;

Requirements

Header: Declared in dmusici.h.

See Also

  • Custom Loading
  • DirectMusic Interfaces
  • Loading Audio Data


IDirectMusicObject8::GetDescriptor

The GetDescriptor method retrieves the object's internal description.

Syntax

HRESULT GetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc

Address of a DMUS_OBJECTDESC structure to be filled with data about the object. Depending on the implementation of the object and how it was loaded from a file, some or all of the standard parameters are filled by GetDescriptor. Check the flags in the dwValidData member to ascertain which other members are valid.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • Getting Object Descriptors
  • IDirectMusicObject8 Interface
  • IDirectMusicObject8::SetDescriptor


IDirectMusicObject8::ParseDescriptor

Given a file stream, the ParseDescriptor method scans the file for data that it can store in the DMUS_OBJECTDESC structure. All members that are supplied are marked with the appropriate flags in dwValidData.

This method is primarily used by the loader when scanning a directory for objects, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

Syntax

HRESULT ParseDescriptor(
  LPSTREAM pStream,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pStream

Stream source for the file.

pDesc

Address of a DMUS_OBJECTDESC structure that receives data about the file.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_CHUNKNOTFOUND
DMUS_E_INVALID_BAND
DMUS_E_INVALIDFILE
DMUS_E_NOTADLSCOL
E_FAIL
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicObject8 Interface
  • IDirectMusicObject8::SetDescriptor


IDirectMusicObject8::SetDescriptor

The SetDescriptor method sets some or all members of the object's internal description.

This method is primarily used by the loader when creating an object, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

Syntax

HRESULT SetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc

Address of a DMUS_OBJECTDESC structure that receives data about the object. Data is copied to all members that are enabled in the dwValidData member.

Return Values

If the method succeeds, one of the values in the following table is returned.

Return code | Description
S_OK | The descriptor was set.
S_FALSE | See Remarks.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If it fails, the method can return one of the error values in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

Applications do not normally call this method on standard objects. Although it is possible to change the object descriptor returned by IDirectMusicObject8::GetDescriptor, the new description cannot successfully be passed to the IDirectMusicLoader8::GetObject method. For example, you could change the name of an object, but GetObject will still find the object only under its original name, because it relies on the object's own implementation of SetDescriptor.

Members that are not copied keep their previous values. For example, an object might already have its name and GUID stored internally. A call to its SetDescriptor method with a new name and file path (and DMUS_OBJ_NAME | DMUS_OBJ_FILENAME in the dwValidData member) would replace the name, supply a file name, and leave the GUID as it is.

If the object is unable to set one or more members, it sets the members that it does support, clears the flags in dwValidData that it does not support, and returns S_FALSE. An application-defined object should support at least DMUS_OBJ_NAME and DMUS_OBJ_OBJECT.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicObject8 Interface
  • IDirectMusicObject8::GetDescriptor
  • IDirectMusicObject8::ParseDescriptor


IDirectMusicPatternTrack8 Interface

The IDirectMusicPatternTrack8 interface represents a track that contains a single pattern. A pattern track is similar to a sequence track, but because it contains music values rather than fixed notes, it responds to chord changes.

You can obtain this interface by passing IID_IDirectMusicPatternTrack to the IDirectMusicTrack8::QueryInterface method of the track.

In addition to the methods inherited from IUnknown, the IDirectMusicPatternTrack8 interface exposes the following methods.

Method | Description
CreateSegment | Creates a segment containing the pattern track.
SetPatternByName | Sets the pattern to be played by the track.
SetVariation | Sets the variations to be played by a part in the track.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces


IDirectMusicPatternTrack8::CreateSegment

The CreateSegment method creates a segment containing the pattern track.

Syntax

HRESULT CreateSegment(
  IDirectMusicStyle* pStyle,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle

Style to use in creating the segment.

ppSegment

Address of a variable that receives an IDirectMusicSegment interface pointer for the created segment. Use QueryInterface to obtain IDirectMusicSegment8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_OUTOFMEMORY

Remarks

A pattern track is usually obtained from a segment object loaded from a file or resource, in which case the application already has the IDirectMusicSegment interface. This method is used for creating a segment when the pattern track object has been created by using CoCreateInstance.

This method does not assign a pattern to the track. The style in pStyle provides only the tempo, time signature, and band. To assign a pattern, use IDirectMusicPatternTrack8::SetPatternByName.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPatternTrack8 Interface


IDirectMusicPatternTrack8::SetPatternByName

The SetPatternByName method sets the pattern to be played by the track. The pattern comes from a style.

Syntax

HRESULT SetPatternByName(
  IDirectMusicSegmentState* pSegState,
  WCHAR* wszName,
  IDirectMusicStyle* pStyle,
  DWORD dwPatternType,
  DWORD* pdwLength
);

Parameters

pSegState

Address of the IDirectMusicSegmentState8 interface representing the playing instance of the segment that contains the track.

wszName

Name of the pattern to set. The name can be obtained by using IDirectMusicStyle8::EnumPattern.

pStyle

Address of the IDirectMusicStyle or IDirectMusicStyle8 interface of the style containing the pattern.

dwPatternType

One of the DMUS_STYLET_TYPES enumerations that specifies the type of pattern.

pdwLength

Address of a variable that receives the length of the pattern, in music time ticks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPatternTrack8 Interface


IDirectMusicPatternTrack8::SetVariation

The SetVariation method sets the variations to be played by a part in the track.

Syntax

HRESULT SetVariation(
  IDirectMusicSegmentState* pSegState,
  DWORD dwVariationFlags,
  DWORD dwPart
);

Parameters

pSegState

Address of the IDirectMusicSegmentState8 interface representing the playing instance of the segment that contains the track.

dwVariationFlags

Bitmask where a bit is set for each variation that is to be played.

dwPart

Identifier for the part containing the variations. This is the number assigned to the part in the authoring application, and is equivalent to the performance channel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_POINTER

Remarks

Variations can be set for only one part at a time. Each time this method is called, it overrides previous calls.

The following example code plays variations 16 and 32 on performance channel 1.

// pPattern is an IDirectMusicPatternTrack8 pointer.
// pSegmentState is an IDirectMusicSegmentState8 pointer.

#define VARIATION(v)  (1 << ((v) - 1))

HRESULT hr = pPattern->SetVariation(
    pSegmentState, VARIATION(32) | VARIATION(16), 1);

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPatternTrack8 Interface


IDirectMusicPerformance8 Interface

The IDirectMusicPerformance8 interface is the overall manager of playback. It is used for adding and removing ports, mapping performance channels to ports, playing segments, dispatching messages and routing them through tools, requesting and receiving event notification, and setting and retrieving various parameters. It also has several methods for getting information about timing and for converting time and music values from one system to another.

If an application needs two complete sets of music playing at the same time, it can do so by creating more than one performance. Separate performances have separate tempos, whereas all segments within one performance must play at the same tempo.

IDirectMusicPerformance8 supersedes the IDirectMusicPerformance interface and adds new methods.

In addition to the methods inherited from IUnknown, the IDirectMusicPerformance8 interface exposes the following methods, arranged by category.

Audiopaths

Method | Description
CreateAudioPath | Creates an audiopath from a configuration object.
CreateStandardAudioPath | Creates an audiopath with a standard configuration.
GetDefaultAudioPath | Retrieves the default audiopath.
SetDefaultAudioPath | Sets and activates the default audiopath for the performance.

Messages

Method | Description
AllocPMsg | Allocates memory for a performance message.
ClonePMsg | Makes a copy of a performance message.
FreePMsg | Frees memory allocated for a performance message.
SendPMsg | Sends a performance message.

MIDI conversion

Method | Description
MIDIToMusic | Converts a MIDI note value to a DirectMusic music value, using a supplied chord, subchord level, and play mode.
MusicToMIDI | Converts a DirectMusic music value to a MIDI note value.

Notifications

Method | Description
AddNotificationType | Adds a notification type to the performance.
GetNotificationPMsg | Retrieves a pending notification message.
RemoveNotificationType | Removes a previously added notification type from the performance.
SetNotificationHandle | Sets the event handle for notifications.

Parameters

Method | Description
GetGlobalParam | Retrieves global values from the performance.
GetParam | Retrieves data from a track.
GetParamEx | Retrieves data from a track, with support for self-controlling segments.
SetGlobalParam | Sets global values for the performance.
SetParam | Sets data on a track in the control segment.

Performance channels

Method | Description
AssignPChannel | Assigns a single performance channel to the performance and maps it to a port, group, and MIDI channel.
AssignPChannelBlock | Assigns a block of 16 performance channels to the performance and maps them to a port and a channel group.
PChannelInfo | Retrieves the port, group, and MIDI channel for a given performance channel.

Playback

Method | Description
GetSegmentState | Retrieves the currently playing primary segment state or the primary segment state that is playing at a given time.
IsPlaying | Ascertains whether a specified segment or segment state is currently being heard from the speakers.
PlaySegment | Begins playback of a segment.
PlaySegmentEx | Begins playback of a segment, with options for transition and audiopath.
Stop | Stops playback of a segment or segment state.
StopEx | Stops playback of a segment, segment state, or audiopath.

Ports

Method | Description
AddPort | Assigns a port to the performance.
RemovePort | Removes a port from the performance.

Timing

Method | Description
AdjustTime | Adjusts the internal performance time forward or backward.
GetBumperLength | Retrieves the interval between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.
GetLatencyTime | Retrieves the latency time, which is the performance time being heard from the speakers plus the time required to queue and render messages.
GetPrepareTime | Retrieves the interval between the time when messages are sent by tracks and the time when the sound is heard.
GetQueueTime | Retrieves the earliest time in the queue at which messages can be flushed.
GetResolvedTime | Resolves a given time to a given boundary.
GetTime | Retrieves the current time of the performance.
MusicToReferenceTime | Converts a performance time in MUSIC_TIME format to performance time in REFERENCE_TIME format.
ReferenceToMusicTime | Converts a performance time in REFERENCE_TIME format to a performance time in MUSIC_TIME format.
RhythmToTime | Converts rhythm time to music time.
SetBumperLength | Sets the interval between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.
SetPrepareTime | Sets the interval between the time when messages are sent by tracks and the time when the sound is heard.
TimeToRhythm | Converts music time to rhythm time.

Toolgraphs

Method | Description
GetGraph | Retrieves the toolgraph of a performance.
SetGraph | Replaces the performance's toolgraph.

Miscellaneous

Method | Description
CloseDown | Closes down the performance object.
DownloadInstrument | Downloads DLS instrument data to a port.
InitAudio | Initializes the performance and optionally sets up a default audiopath.
Invalidate | Flushes all queued messages from the supplied time forward and causes all tracks of all segments to resend their data from the given time forward.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces


IDirectMusicPerformance8::AddNotificationType

The AddNotificationType method adds a notification type to the performance. All segments and tracks are automatically updated with the new notification by an internal call to their AddNotificationType methods.

Syntax

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::RemoveNotificationType
  • IDirectMusicSegment8::AddNotificationType
  • IDirectMusicTrack8::AddNotificationType
  • Notification and Event Handling


IDirectMusicPerformance8::AddPort

The AddPort method assigns a port to the performance. This method is valid only for performances that do not use audiopaths. Such performances are initialized by using IDirectMusicPerformance8::Init.

Syntax

HRESULT AddPort(
  IDirectMusicPort* pPort
);

Parameters

pPort

IDirectMusicPort8 interface pointer of the port to add. If NULL, the default port is added. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_CANNOT_OPEN_PORT
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

When the default port is specified by passing NULL in pPort, it is assigned one channel group. If no performance channels have been set up for any other port, channels 0 through 15 are assigned to MIDI channels 0 through 15.

If pPort is not NULL, it must be a port created by the same DirectMusic object that was passed to, or created by, IDirectMusicPerformance8::Init. The port must be activated by a call to IDirectMusicPort8::Activate, and a block of channels must be assigned by a call to IDirectMusicPerformance8::AssignPChannelBlock.

This method creates a reference to IDirectMusicPort8 that is released by IDirectMusicPerformance8::RemovePort or IDirectMusicPerformance8::CloseDown. However, if NULL is passed to AddPort, the port cannot be removed by RemovePort, because the application has no reference to pass to RemovePort.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::RemovePort
  • Default Port


IDirectMusicPerformance8::AdjustTime

The AdjustTime method adjusts the internal performance time forward or backward. This is mostly used to compensate for drift when synchronizing to another source.

Syntax

HRESULT AdjustTime(
  REFERENCE_TIME rtAmount
);

Parameters

rtAmount

Amount of time to add. This can be a value in the range from -10,000,000 to 10,000,000 (–1 second to +1 second).

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_INVALIDARG.

Remarks

The adjusted time is used internally by DirectMusic. It is not reflected in the time retrieved by the IDirectMusicPerformance8::GetTime method.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetTime
  • Timing


IDirectMusicPerformance8::AllocPMsg

The AllocPMsg method allocates memory for a performance message.

Syntax

HRESULT AllocPMsg(
  ULONG cb,
  DMUS_PMSG** ppPMSG
);

Parameters

cb

Size of the message structure. This structure is of a type derived from DMUS_PMSG.

ppPMSG

Address of a variable that receives the pointer to the allocated message structure.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The dwSize member of the message structure is set to the value of cb. Other members are not necessarily initialized to zero, because of internal caching.

After the message is sent by IDirectMusicPerformance8::SendPMsg, the application no longer owns the memory and is not responsible for freeing the message. However, a tool can free a message within its IDirectMusicTool8::Flush or its IDirectMusicTool8::ProcessPMsg method. Applications are also responsible for freeing notification messages.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::FreePMsg
  • IDirectMusicPerformance8::SendPMsg
  • DirectMusic Messages


IDirectMusicPerformance8::AssignPChannel

The AssignPChannel method assigns a single performance channel to the performance and maps it to a port, group, and MIDI channel.

This method is not used by applications that route their data through audiopaths.

Syntax

HRESULT AssignPChannel(
  DWORD dwPChannel,
  IDirectMusicPort* pPort,
  DWORD dwGroup,
  DWORD dwMChannel
);

Parameters

dwPChannel

Performance channel to assign.

pPort

Pointer to the IDirectMusicPort8 interface of the port to which the channel is assigned.

dwGroup

Channel group on the port.

dwMChannel

Channel in the group. Must be in the range from 0 through 15.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE (see Remarks).

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

The method returns S_FALSE if dwGroup is out of the range of the port. The channel has been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if dwMChannel is out of range or the port has not been added to the performance through a call to the IDirectMusicPerformance8::AddPort method.

Requirements

Header: Declared in dmusici.h.

See Also

  • Channels
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AssignPChannelBlock
  • IDirectMusicPerformance8::PChannelInfo


IDirectMusicPerformance8::AssignPChannelBlock

The AssignPChannelBlock method assigns a block of 16 performance channels to the performance and maps them to a port and a channel group. This method is valid only for performances that do not use audiopaths; that is, performances initialized by using IDirectMusicPerformance8::Init.

Syntax

HRESULT AssignPChannelBlock(
  DWORD dwBlockNum,
  IDirectMusicPort* pPort,
  DWORD dwGroup
);

Parameters

dwBlockNum

Block number, in which 0 represents channels 0 through 15, 1 represents channels 16 through 31, and so on.

pPort

IDirectMusicPort8 interface pointer of the port to which the channels are assigned.

dwGroup

Channel group on the port. Must be 1 or greater.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

This method must be called when a port has been added to a performance, except when the default port has been added by passing NULL to IDirectMusicPerformance8::AddPort.

The method returns S_FALSE if dwGroup is out of the range of the port. The channels have been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if the port has not been added to the performance through a call to the IDirectMusicPerformance8::AddPort method.

Requirements

Header: Declared in dmusici.h.

See Also

  • Channels
  • Default Port
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AssignPChannel
  • IDirectMusicPerformance8::PChannelInfo


IDirectMusicPerformance8::ClonePMsg

The ClonePMsg method makes a copy of a performance message.

Syntax

HRESULT ClonePMsg(
  DMUS_PMSG* pSourcePMSG,
  DMUS_PMSG** ppCopyPMSG
);

Parameters

pSourcePMSG

Message to copy.

ppCopyPMSG

Address of a variable that receives a pointer to the copied message.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::CloseDown

The CloseDown method closes down the performance object. An application that created the performance object and called IDirectMusicPerformance8::Init or IDirectMusicPerformance8::InitAudio on it must call CloseDown before the performance is released.

Syntax

HRESULT CloseDown();

Parameters

This method returns no parameters.

Return Values

The method returns S_OK.

Remarks

Failure to call CloseDown can cause memory leaks or program failures.

CloseDown handles the release of the IDirectMusic8 interface if this reference was created by IDirectMusicPerformance8::Init or IDirectMusicPerformance8::InitAudio. If the application explicitly created the DirectMusic object, the application is responsible for releasing the reference.

If the DirectSound device object was created in the call to Init or InitAudio but no reference was returned to the application, CloseDown also releases the DirectSound device and all DirectSound buffers. If your application has obtained any interfaces to DirectSound buffers, it should release them before calling Closedown.

If the application created the DirectSound device object explicitly, or obtained a reference form Init or InitAudio, it is responsible for releasing the DirectSound device.

The method releases any downloaded instruments that have not been unloaded.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::CreateAudioPath

The CreateAudioPath method creates an audiopath from a configuration object.

Syntax

HRESULT CreateAudioPath(
  IUnknown *pSourceConfig,
  BOOL fActivate,
  IDirectMusicAudioPath **ppNewPath
);

Parameters

pSourceConfig

Address of an interface that represents the audiopath configuration. See Remarks.

fActivate

Boolean value that specifies whether to activate the path on creation.

ppNewPath

Address of a variable that receives an IDirectMusicAudioPath8 interface pointer for the audiopath.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT
DSERR_BUFFERLOST
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

The object addressed by pSourceConfig can be obtained from a segment by using the IDirectMusicSegment8::GetAudioPathConfig method or can be loaded directly from a file.

The method fails with DSERR_BUFFERLOST if any application has initialized DirectSound with the write-primary cooperative level.

If the audiopath configuration specifies a sound device that is not available, the method returns E_NOINTERFACE.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::CreateStandardAudioPath
  • Creating Audiopaths


IDirectMusicPerformance8::CreateStandardAudioPath

The CreateStandardAudioPath method creates an audiopath with a standard configuration.

Syntax

HRESULT  CreateStandardAudioPath(
  DWORD dwType,
  DWORD dwPChannelCount,
  BOOL  fActivate,
  IDirectMusicAudioPath **ppNewPath
);

Parameters

dwType

Type of the path. The following values are defined.

Value | Description
DMUS_APATH_DYNAMIC_3D | One bus to a 3-D buffer. Does not send to environmental reverb.
DMUS_APATH_DYNAMIC_MONO | One bus to a mono buffer.
DMUS_APATH_DYNAMIC_STEREO | Two buses to a stereo buffer.
DMUS_APATH_SHARED_STEREOPLUSREVERB | Ordinary music setup with stereo outs and reverb.

dwPChannelCount

Number of performance channels in the path.

fActivate

Boolean value that specifies whether to activate the path on creation.

ppNewPath

Address of a variable that receives an IDirectMusicAudioPath interface pointer for the audiopath. See IDirectMusicAudioPath8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT
DSERR_BUFFERLOST
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The method fails with DSERR_BUFFERLOST if any application has initialized DirectSound with the write-primary cooperative level.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::CreateAudioPath
  • Standard Audiopaths


IDirectMusicPerformance8::DownloadInstrument

The DownloadInstrument method downloads DLS instrument data to a port.

Syntax

HRESULT DownloadInstrument(
  IDirectMusicInstrument* pInst,
  DWORD dwPChannel,
  IDirectMusicDownloadedInstrument** ppDownInst,
  DMUS_NOTERANGE* pNoteRanges,
  DWORD dwNumNoteRanges,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

pInst

Pointer to the IDirectMusicInstrument8 interface of the instrument to download.

dwPChannel

Performance channel to which the instrument is assigned.

ppDownInst

Address of a variable that receives an IDirectMusicDownloadedInstrument8 pointer to the downloaded instrument.

pNoteRanges

Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.

dwNumNoteRanges

Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions are downloaded.

ppPort

Address of a variable that receives a pointer to the port to which the instrument was downloaded.

pdwGroup

Address of a variable that receives the channel group to which the instrument was assigned.

pdwMChannel

Address of a variable that receives the MIDI channel to which the instrument was assigned.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

Most applications do not need to use this method, because instrument downloading is normally handled by bands.

The method returns E_INVALIDARG if the performance channel is not assigned to a port.

To prevent loss of resources, unload the instrument by using the IDirectMusicPort8::UnloadInstrument method when the instrument is no longer needed.

Requirements

Header: Declared in dmusici.h.

See Also

  • Downloading and Unloading Bands
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPort8::DownloadInstrument
  • IDirectMusicPort8::UnloadInstrument
  • Working with Instruments


IDirectMusicPerformance8::FreePMsg

The FreePMsg method frees memory allocated for a performance message.

Syntax

HRESULT FreePMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG

Pointer to the message to free. This message must have been allocated using the IDirectMusicPerformance8::AllocPMsg method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_CANNOT_FREE
E_POINTER

Remarks

Most messages are released automatically by the performance after they have been processed, and IDirectMusicPerformance8::FreePMsg must not be called on a message that has been sent by using IDirectMusicPerformance8::SendPMsg. However, IDirectMusicPerformance8::FreePMsg can be used within IDirectMusicTool8::ProcessPMsg or IDirectMusicTool8::Flush to free a message that is no longer needed. It must also be used to free notification messages.

The method returns DMUS_E_CANNOT_FREE in the following cases:

  • If pPMSG is not a message allocated by AllocPMsg.
  • If it is in the performance queue because IDirectMusicPerformance8::SendPMsg was called on it. However, applications cannot assume that FreePMsg will return DMUS_E_CANNOT_FREE for all sent messages, because SendPMsg is not synchronous.
  • If it has already been freed.

If there is a value in the pTool, pGraph, or punkUser members (see DMUS_PMSG), each referenced object is released.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Messages
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AllocPMsg


IDirectMusicPerformance8::GetBumperLength

The GetBumperLength method retrieves the interval between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.

Syntax

HRESULT GetBumperLength(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds

Address of a variable to receive the buffer length.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 50 milliseconds.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::SetBumperLength
  • Latency and Bumper Time


IDirectMusicPerformance8::GetDefaultAudioPath

The GetDefaultAudioPath method retrieves the default audiopath set by IDirectMusicPerformance8::InitAudio or IDirectMusicPerformance8::SetDefaultAudioPath.

Syntax

HRESULT GetDefaultAudioPath(
  IDirectMusicAudioPath**  ppAudioPath
);

Parameters

ppAudioPath

Address of a variable that receives the IDirectMusicAudioPath8 interface pointer of the default audiopath.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • Default Audiopath
  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::GetGlobalParam

The GetGlobalParam method retrieves a global parameter that has been set by IDirectMusicPerformance8::SetGlobalParam.

Syntax

HRESULT GetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data.

pParam

Pointer to the allocated memory that receives a copy of the data. This must be the correct size, which is constant for each type of data. This parameter contains information that was passed in to the IDirectMusicPerformance8::SetGlobalParam method.

dwSize

Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

Do not assume that any parameter has a default value that can be retrieved by using GetGlobalParam. If SetGlobalParam has never been called for rguidType, the parameter might not be in the list of global data being handled by this performance, and GetGlobalParam might return E_INVALIDARG.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetGlobalParam
  • Performance Parameters


IDirectMusicPerformance8::GetGraph

The GetGraph method retrieves the toolgraph of a performance.

Syntax

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph

Address of a variable that receives a pointer to the toolgraph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

The reference count of the graph is incremented.

The performance object implements IDirectMusicGraph directly This interface is used primarily to call the IDirectMusicGraph8::StampPMsg method directly on the performance. This has nothing to do with a graph object that might be embedded in the performance. If you want to access an embedded object, you are accessing a different IDirectMusicGraph interface because it is an interface on the embedded graph object, not the performance itself. To obtain an interface to an embedded audiopath, use the IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath method.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::SendPMsg
  • IDirectMusicPerformance8::SetGraph
  • IDirectMusicSegment8::GetGraph


IDirectMusicPerformance8::GetLatencyTime

The GetLatencyTime method retrieves the latency time, which is the performance time being heard from the speakers plus the time required to queue and render messages.

Syntax

HRESULT GetLatencyTime(
  REFERENCE_TIME*  prtTime
);

Parameters

prtTime

Address of a variable that receives the current latency time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Latency and Bumper Time


IDirectMusicPerformance8::GetNotificationPMsg

The GetNotificationPMsg method retrieves a pending notification message.

Syntax

HRESULT GetNotificationPMsg(
  DMUS_NOTIFICATION_PMSG**  ppNotificationPMsg
);

Parameters

ppNotificationPMsg

Address of a variable that receives a pointer to a DMUS_NOTIFICATION_PMSG structure. The application retrieving this message is responsible for calling IDirectMusicPerformance8::FreePMsg on it.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there are no more notification events to return.

If it fails, the method can return E_POINTER.

Remarks

For most notifications, the segment state that generated the notification can be retrieved from the punkUser member of the message structure, and the segment can be retrieved by using IDirectMusicSegmentState8::GetSegment.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Notification and Event Handling


IDirectMusicPerformance8::GetParam

The GetParam method retrieves data from a track inside the control segment.

Syntax

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to retrieve. See Standard Track Parameters.

dwGroupBits

Group of the track from which to retrieve the data (see Remarks). Set this value to 0xFFFFFFFF for all groups.

dwIndex

Index of the track in the group from which to retrieve the data, or DMUS_SEG_ANYTRACK to find the first track that contains the parameter.

mtTime

Time from which to retrieve the data, in performance time.

pmtNext

Address of a variable that receives the time (relative to mtTime) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.

pParam

Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_GET_UNSUPPORTED
DMUS_E_NO_MASTER_CLOCK
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played.

The data returned in *pParam can become invalid before the time returned in *pmtNext if another control segment is cued.

Each track belongs to one or more groups, and each group is represented by a bit in dwGroupBits. For more information, see IDirectMusicSegment8::InsertTrack and Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

  • Control Segments
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetParamEx
  • IDirectMusicPerformance8::GetTime
  • IDirectMusicPerformance8::SetGlobalParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • Performance Parameters


IDirectMusicPerformance8::GetParamEx

The GetParamEx method retrieves data from a track. This method is similar to IDirectMusicPerformance8::GetParam but adds support for self-controlling segments. It is used chiefly by tools.

Syntax

HRESULT GetParamEx(
  REFGUID rguidType,
  DWORD dwTrackID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.

dwTrackID

Unique identifier of a track within the segment state from which the parameter is to be obtained. Every performance message that originates from a track carries an identifier of the track instance that generated the message. This identifier is kept in the dwVirtualTrackID member of the DMUS_PMSG part of the message structure. When this value is passed to GetParamEx, the method is able to determine whether the track is self-controlling, in which case it gets its data from another track in the same segment rather than from one in the control segment.

dwGroupBits

Group that the track is in (see Remarks). Set this value to 0xFFFFFFFF for all groups.

dwIndex

Index of the track in the group.

mtTime

Time from which to obtain the data, in performance time.

pmtNext

Address of a variable that receives the time (relative to mtTime) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.

pParam

Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_GET_UNSUPPORTED
DMUS_E_NO_MASTER_CLOCK
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Each track belongs to one or more groups, and each group is represented by a bit in dwGroupBits. For more information, see IDirectMusicSegment8::InsertTrack and Identifying the Track.

The data returned in *pParam can become invalid before the time returned in *pmtNext if another control segment is cued.

Requirements

Header: Declared in dmusici.h.

See Also

  • Control Segments
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetTime
  • IDirectMusicPerformance8::SetGlobalParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • Performance Parameters
  • Self-Controlling Segments


IDirectMusicPerformance8::GetPrepareTime

The GetPrepareTime method retrieves the interval between the time when messages are sent by tracks and the time when the sound is heard. This interval allows sufficient time for the message to be processed by tools.

Syntax

HRESULT GetPrepareTime(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds

Address of a variable that receives the amount of prepare time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 1000 milliseconds.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::SetPrepareTime
  • Prepare Time


IDirectMusicPerformance8::GetQueueTime

The GetQueueTime method retrieves the current flush time, which is the earliest time in the queue at which messages can be flushed. Messages that have time stamps earlier than this time have already been sent to the port and cannot be invalidated.

Syntax

HRESULT GetQueueTime(
  REFERENCE_TIME * prtTime
);

Parameters

prtTime

Address of a variable that receives the current flush time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::Invalidate
  • Latency and Bumper Time


IDirectMusicPerformance8::GetResolvedTime

The GetResolvedTime method resolves a given time to a given boundary.

Syntax

HRESULT GetResolvedTime(
  REFERENCE_TIME rtTime,
  REFERENCE_TIME* prtResolved,
  DWORD dwTimeResolveFlags
);

Parameters

rtTime

Time to resolve. If this is less than the current time, the current time is used.

prtResolved

Address of a variable that receives the resolved time.

dwTimeResolveFlags

One or more DMUS_TIME_RESOLVE_FLAGS describing the resolution desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Segment Timing


IDirectMusicPerformance8::GetSegmentState

The GetSegmentState method retrieves the currently playing primary segment state or the primary segment state that is playing at a given time.

Syntax

HRESULT GetSegmentState(
  IDirectMusicSegmentState ** ppSegmentState,
  MUSIC_TIME mtTime
);

Parameters

ppSegmentState

Address of a variable that receives a pointer to the segment state. The caller is responsible for calling Release on this pointer.

mtTime

Time for which the segment state is to be retrieved.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

To get the currently playing segment state, pass the time returned by the IDirectMusicPerformance8::GetTime method. Because of latency, the currently playing segment state is not necessarily the one being heard.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Segment States


IDirectMusicPerformance8::GetTime

The GetTime method retrieves the current time of the performance. Events cued at this time are now being performed.

Syntax

HRESULT GetTime(
  REFERENCE_TIME* prtNow,
  MUSIC_TIME* pmtNow
);

Parameters

prtNow

Address of a variable that receives the current time in REFERENCE_TIME format. Can be NULL.

pmtNow

Address of a variable that receives the current time in MUSIC_TIME format. Can be NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Timing


IDirectMusicPerformance8::Init

The Init method associates the performance with a DirectMusic object and a DirectSound device object. If the application is not using audiopaths, this method must be called before the performance can play.

For applications that use audiopaths, this method has been superseded by IDirectMusicPerformance8::InitAudio.

Syntax

HRESULT Init(
  IDirectMusic** ppDirectMusic,
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

ppDirectMusic

Address of a variable that specifies or receives an interface pointer to a DirectMusic object.

If the variable pointed to by ppDirectMusic contains a valid IDirectMusic or IDirectMusic8 interface pointer, the existing object is assigned to the performance. The reference count of the interface is incremented. Ports passed to the IDirectMusicPerformance8::AddPort method must be created from this DirectMusic object.

If the variable pointed to by ppDirectMusic contains NULL, a DirectMusic object is created and an IDirectMusic interface pointer is returned. Use QueryInterface to obtain IDirectMusic8.

If ppDirectMusic is NULL, a DirectMusic object is created and used internally by the performance.

See Remarks.

pDirectSound

IDirectSound8 interface pointer to use by default for waveform output. If this value is NULL, DirectMusic creates a DirectSound device object. There should, however, be only one DirectSound device object per process. If your application uses DirectSound separately, it should pass in that interface here, or to IDirectMusic8::SetDirectSound if the application creates the DirectMusic object explicitly.

hWnd

Window handle to be used for the creation of DirectSound. This parameter can be NULL, in which case the foreground window is used. See Remarks.

This parameter is ignored if pDirectSound is not NULL, in which case the application is responsible for setting the window handle in a call to IDirectSound8::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_ALREADY_INITED
E_OUTOFMEMORY
E_POINTER

Remarks

This method can be called only once. It cannot be used to retrieve an existing IDirectMusic8 interface.

A DirectMusic object can be associated with the performance in any of the following ways:

  • The application creates its own DirectMusic object and gives it to the performance by passing the address of the IDirectMusic8 pointer in ppDirectMusic. In this case, the pDirectSound and hWnd parameters are ignored because the application is responsible for calling IDirectMusic8::SetDirectSound.
  • The application allows the performance to create the DirectMusic object and needs a pointer to that object. In this case, *ppDirectMusic is NULL on entry, and contains the IDirectMusic pointer on exit.
  • The application allows the performance to initialize itself and does not need a DirectMusic object pointer. In this case, ppDirectMusic is NULL.

The performance must be terminated by using the IDirectMusicPerformance8::CloseDown method before being released.

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. It is best to pass the top-level application window handle.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::InitAudio

The InitAudio method initializes the performance and optionally sets up a default audiopath. This method must be called before the performance can play using audiopaths.

This method should be used in most cases instead of IDirectMusicPerformance8::Init.

Syntax

HRESULT InitAudio(
  IDirectMusic** ppDirectMusic,
  IDirectSound** ppDirectSound,
  HWND hWnd,
  DWORD dwDefaultPathType,
  DWORD dwPChannelCount,
  DWORD dwFlags,
  DMUS_AUDIOPARAMS *pParams
);

Parameters

ppDirectMusic

Address of a variable that specifies or receives an interface pointer to a DirectMusic object.

If the variable pointed to by ppDirectMusic contains a valid IDirectMusic or IDirectMusic8 interface pointer, the existing object is assigned to the performance. The reference count of the interface is incremented.

If the variable pointed to by ppDirectMusic contains NULL, a DirectMusic object is created and the IDirectMusic interface pointer is returned. Use QueryInterface to obtain IDirectMusic8.

If ppDirectMusic is NULL, a DirectMusic object is created and used internally by the performance.

See Remarks.

ppDirectSound

Address of a variable that specifies or receives an IDirectSound interface pointer for a DirectSound device object to use by default for waveform output. If this parameter contains a NULL pointer, DirectMusic creates a private DirectSound device object. If the variable pointed to contains NULL, DirectMusic creates a DirectSound device object and returns the interface pointer. See Remarks.

hWnd

Window handle to use for the creation of DirectSound. This parameter can be NULL, in which case the foreground window is used. See Remarks.

This parameter is ignored if an IDirectSound interface pointer is passed to the method in ppDirectSound. In that case the application is responsible for setting the window handle by using IDirectSound8::SetCooperativeLevel.

dwDefaultPathType

Value that specifies the default audiopath type. Can be zero if no default path type is wanted. For a list of defined values, see IDirectMusicPerformance8::CreateStandardAudioPath.

dwPChannelCount

Value that specifies the number of performance channels to allocate to the path, if dwDefaultPathType is not zero.

dwFlags

Flags that specify requested features. If pParams is not NULL, this value is ignored and the requested features are specified in the dwFeatures member of the DMUS_AUDIOPARAMS structure. The values listed in the following table are defined for use in this parameter.

Value | Description
DMUS_AUDIOF_3D | 3-D buffers.
DMUS_AUDIOF_ALL | All features.
DMUS_AUDIOF_BUFFERS | Multiple buffers.
DMUS_AUDIOF_DMOS | Additional DMOs.
DMUS_AUDIOF_ENVIRON | Environmental modeling.
DMUS_AUDIOF_EAX | EAX effects.
DMUS_AUDIOF_STREAMING | Support for streaming waveforms.

pParams

Address of a DMUS_AUDIOPARAMS structure that specifies parameters for the synthesizer and receives information about what parameters were set. Can be NULL if the default parameters are wanted.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_ALREADY_INITED
DSERR_BUFFERLOST
DSERR_PRIOLEVELNEEDED
DSERR_UNINITIALIZED
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

This method can be called only once. It cannot be used to retrieve an existing IDirectMusic8 interface.

A DirectMusic object can be associated with the performance in the following ways.

  • The application allows the performance to create the DirectMusic object and needs a pointer to that object. In this case, *ppDirectMusic is NULL on entry and contains the IDirectMusic pointer on exit.
  • The application allows the performance to initialize itself and does not need a DirectMusic object pointer. In this case, ppDirectMusic is NULL.
  • The application creates its own DirectMusic object and gives it to the performance by passing the address of the IDirectMusic8 pointer in ppDirectMusic. Most applications do not use this technique.

If you specify an interface pointer in ppDirectSound, it must be an interface to an object of class CLSID_DirectSound8. Objects of this class support both IDirectSound and IDirectSound8, but the IDirectSound interface must be passed. For information on how to create an object of this class, see the Remarks for IDirectSound8. The DirectSound device object must be fully initialized before being passed to InitAudio. If the object was created by using CoCreateInstance, call IDirectSound8::Initialize. Set the cooperative level to DSSCL_PRIORITY by using IDirectSound8::SetCooperativeLevel.

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. It is best to pass the top-level application window handle.

The parameters set in dwFlags and pParams apply to the default audiopath and any audiopaths created subsequently.

The method fails with DSERR_BUFFERLOST if a value other than zero is passed in dwDefaultPathType and any application has initialized DirectSound with the write-primary cooperative level.

The performance must be terminated by using the IDirectMusicPerformance8::CloseDown method before being released.

Requirements

Header: Declared in dmusici.h.

See Also

  • Creating the Performance
  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::Invalidate

The Invalidate method flushes all queued messages from the specified time forward and causes all tracks of all segments to resend their data.

Syntax

HRESULT Invalidate(
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

mtTime

Time from which to invalidate, adjusted by dwFlags. Setting this value to 0 causes immediate invalidation.

dwFlags

Flag that aligns mtTime to the next measure, beat, or grid. This value can be 0 or one of the following members of the DMUS_SEGF_FLAGS enumeration:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_NO_MASTER_CLOCK.

Remarks

If mtTime is so long ago that it is impossible to invalidate that time, the earliest possible time is used.

Notes that have already been sent to the port are normally cut off by invalidation; that is, any pending note-off message is immediately sent. However, this behavior can be overridden by using one of the DMUS_NOTEF_FLAGS flags in the message structure.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Latency and Bumper Time
  • Prepare Time
  • Segment Timing


IDirectMusicPerformance8::IsPlaying

The IsPlaying method ascertains whether a specified segment or segment state is currently being heard from the speakers.

Syntax

HRESULT IsPlaying(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegState
);

Parameters

pSegment

Segment to check. If NULL, check only pSegState.

pSegState

Segment state to check. If NULL, check only pSegment.

Return Values

If the method succeeds and the requested segment or segment state is playing, the return value is S_OK. If neither is playing or only one was requested and it is not playing, the return value is S_FALSE.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

The method returns S_OK only if the segment or segment state is actually playing at the speakers. Because of latency, this method might return S_FALSE even though IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx has just been called on the segment. Similarly, the method returns S_OK as long as the segment is being heard, even though all messages might already have been dispatched.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface


IDirectMusicPerformance8::MIDIToMusic

The MIDIToMusic method converts a MIDI note value to a DirectMusic music value, using a supplied chord, subchord level, and play mode.

Syntax

HRESULT MIDIToMusic(
  BYTE bMIDIValue,
  DMUS_CHORD_KEY* pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  WORD *pwMusicValue
);

Parameters

bMIDIValue

MIDI note value to convert, in the range from 0 through 127.

pChord

Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to DMUS_MAXSUBCHORD parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.

bPlayMode

Play mode determining how the music value is derived from the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.

bChordLevel

Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.

pwMusicValue

Address of a variable that receives the music value. For information on this value, see DMUS_NOTE_PMSG.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

Return code
S_OK
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails, *pwMusicValue is not changed.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been adjusted up or down one or more octaves to be in the proper MIDI range of from 0 through 127. This can occur when using play modes DMUS_PLAYMODE_FIXEDTOCHORD and DMUS_PLAYMODE_FIXEDTOKEY, both of which return MIDI values in *pwMusicValue.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::MusicToMIDI
  • Music Values and MIDI Notes


IDirectMusicPerformance8::MusicToMIDI

The MusicToMIDI method converts a DirectMusic music value to a MIDI note value.

Syntax

HRESULT MusicToMIDI(
  WORD wMusicValue,
  DMUS_CHORD_KEY*  pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  BYTE*  pbMIDIValue
);

Parameters

wMusicValue

Music value to convert. For information on music values, see DMUS_NOTE_PMSG.

pChord

Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to DMUS_MAXSUBCHORD parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.

bPlayMode

Play mode determining how the music value is related to the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.

bChordLevel

Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.

pbMIDIValue

Address of a variable that receives the MIDI value, in the range from 0 through 127.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

Return code
S_OK
DMUS_S_OVER_CHORD
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails or returns DMUS_S_OVER_CHORD, *pwMIDIValue is not changed.

The method returns DMUS_S_OVER_CHORD if no note has been calculated because the music value has the note at a position higher than the top note of the chord. This applies only to DMUS_PLAYMODE_NORMALCHORD play mode. The caller should not do anything with the note, which is not meant to be played against this chord.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been adjusted up or down one or more octaves to be in the proper MIDI range of 0 through 127. This can occur when using any play mode except DMUS_PLAYMODE_FIXED.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::MIDIToMusic
  • Music Values and MIDI Notes


IDirectMusicPerformance8::MusicToReferenceTime

The MusicToReferenceTime method converts a performance time in MUSIC_TIME format to performance time in REFERENCE_TIME format.

Syntax

HRESULT MusicToReferenceTime(
  MUSIC_TIME mtTime,
  REFERENCE_TIME* prtTime
);

Parameters

mtTime

Time in MUSIC_TIME format to convert.

prtTime

Address of a variable that receives the converted time in REFERENCE_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

Because reference time has a greater precision than music time, a time that has been converted from reference time to music time, and then back again, probably does not have its original value.

This method converts a time offset from the start of the performance, not a duration. Because the ratio between music time and reference time units depends on the tempo, DirectMusic takes into account all tempo changes since the start of the performance when calculating prtTime. If a master tempo has been set for the performance, it is taken into account as well.

Requirements

Header: Declared in dmusici.h.

See Also

  • Clock Time and Music Time
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::ReferenceToMusicTime


IDirectMusicPerformance8::PChannelInfo

The PChannelInfo method retrieves the port, group, and MIDI channel for a given performance channel.

Syntax

HRESULT PChannelInfo(
  DWORD dwPChannel,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

dwPChannel

Performance channel for which information is desired.

ppPort

Address of a variable that receives an IDirectMusicPort8 pointer. This value can be NULL if the pointer is not wanted. If a non-NULL pointer is returned, the reference count is incremented, and it is the responsibility of the application to call Release on the pointer. See Remarks.

pdwGroup

Address of a variable that receives the group on the port. Can be NULL if this value is not wanted.

pdwMChannel

Address of a variable that receives the MIDI channel on the group. Can be NULL if this value is not wanted.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

A NULL pointer is returned in *ppPort if the port has been removed by a call to IDirectMusicPerformance8::RemovePort, but the method succeeds.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AssignPChannel
  • IDirectMusicPerformance8::AssignPChannelBlock


IDirectMusicPerformance8::PlaySegment

The PlaySegment method begins playback of a segment.

Syntax

HRESULT PlaySegment(
  IDirectMusicSegment* pSegment,
  DWORD dwFlags,
  __int64 i64StartTime,
  IDirectMusicSegmentState** ppSegmentState
);

Parameters

pSegment

Segment to play.

dwFlags

Flags that modify the method's behavior. See DMUS_SEGF_FLAGS.

i64StartTime

Performance time at which to begin playing the segment, adjusted to any resolution boundary specified in dwFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of 0 causes the segment to start playing as soon as possible.

ppSegmentState

Address of a variable that receives a pointer to the segment state for this instance of the playing segment. This field can be NULL. If it is non-NULL, the segment state pointer is returned, and the application must call Release on it.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_OUTOFMEMORY
E_POINTER
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST

Remarks

Do not play segments from untrusted sources. Improperly written segments can make excessive demands on system resources, resulting in degradation of performance or system failure.

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in dwFlags are relative to the current primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time and Music Time.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::PlaySegmentEx
  • Playing Segments


IDirectMusicPerformance8::PlaySegmentEx

The PlaySegmentEx method begins playback of a segment. The method offers greater functionality than IDirectMusicPerformance8::PlaySegment.

Syntax

HRESULT PlaySegmentEx(
  IUnknown* pSource,
  WCHAR *pwzSegmentName,
  IUnknown* pTransition,
  DWORD dwFlags,
  __int64 i64StartTime,
  IDirectMusicSegmentState** ppSegmentState,
  IUnknown* pFrom,
  IUnknown* pAudioPath
);

Parameters

pSource

Address of the IUnknown interface of the object to play.

pwzSegmentName

Reserved. Set to NULL.

pTransition

IUnknown interface pointer of a template segment to use in composing a transition to this segment. Can be NULL. See Remarks.

dwFlags

Flags that modify the method's behavior. See DMUS_SEGF_FLAGS.

i64StartTime

Performance time at which to begin playing the segment, adjusted to any resolution boundary specified in dwFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of zero causes the segment to start playing as soon as possible.

ppSegmentState

Address of a variable that receives an IDirectMusicSegmentState interface pointer for this instance of the playing segment. Use QueryInterface to obtain IDirectMusicSegmentState8. The reference count of the interface is incremented. This parameter can be NULL if no segment state pointer is wanted.

pFrom

IUnknown interface pointer of a segment state or audiopath to stop when the new segment begins playing. If it is an audiopath, all segment states playing on that audiopath are stopped. This value can be NULL. See Remarks.

pAudioPath

IUnknown interface pointer of an object that represents the audiopath on which to play, or NULL to play on the default path.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_AUDIOPATH_INACTIVE
DMUS_E_AUDIOPATH_NOPORT
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST
E_OUTOFMEMORY
E_POINTER

Remarks

Do not play segments from untrusted sources. Improperly written segments can make excessive demands on system resources, resulting in degradation of performance or system failure.

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in dwFlags are relative to the primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time and Music Time.

If DMUS_SEGF_AUTOTRANSITION is specified in dwFlags and a segment is already playing at i64StartTime and is being interrupted, the method composes a transition between the two segments and plays it before playing pSource. The transition is based on a template provided at pTransition.

The method can be used to play on a performance that does not use audiopaths; that is, one initialized by using IDirectMusicPerformance8::Init. In this case the pAudioPath parameter must be NULL.

When the segment is being cued as a secondary segment, the pFrom parameter can be used to specify the segment state of another secondary segment against which to cue the new segment, as in the following example function.

HRESULT CueOneAfterAnother(IDirectMusicSegment8* pSegmentA,
        IDirectMusicSegmentState8* pSegmentStateB,
        IDirectMusicPerformance8* pPerf)
{
  HRESULT hr = pPerf->PlaySegmentEx(
    pSegmentA,
    NULL, NULL,
    DMUS_SEGF_QUEUE | DMUS_SEGF_SECONDARY,
    0, NULL,
    pSegmentStateB,
    NULL);
  return hr;
}

In the example, pSegmentStateB plays to the end before stopping because the DMUS_SEGF_QUEUE flag has been set. If you set a different flag such as DMUS_SEGF_MEASURE, pSegmentStateB stops as soon as the boundary is reached and the new secondary segment begins playing.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Playing Segments


IDirectMusicPerformance8::ReferenceToMusicTime

The ReferenceToMusicTime method converts a performance time in REFERENCE_TIME format to a performance time in MUSIC_TIME format.

Syntax

HRESULT ReferenceToMusicTime(
  REFERENCE_TIME rtTime,
  MUSIC_TIME* pmtTime
);

Parameters

rtTime

Time in REFERENCE_TIME format.

pmtTime

Address of a variable that receives the converted time in MUSIC_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

Because music time is less precise than reference time, rounding occurs.

This method converts a time offset from the start of the performance, not a duration. Because the ratio between music time and reference time units depends on the tempo, DirectMusic takes into account all tempo changes since the start of the performance when calculating prtTime. If a master tempo has been set for the performance, it is taken into account as well.

Requirements

Header: Declared in dmusici.h.

See Also

  • Clock Time and Music Time
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::MusicToReferenceTime


IDirectMusicPerformance8::RemoveNotificationType

The RemoveNotificationType method removes a previously added notification type from the performance. All segments and tracks are updated by a call to their RemoveNotificationType methods.

Syntax

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) If this value is GUID_NULL, all notifications are removed.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return E_POINTER.

Remarks

S_FALSE is returned when rguidNotificationType is not an active notification.

If a notification was added to a segment that has stopped playing, the performance cannot remove the notification type from that segment because it no longer has a reference to the segment.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AddNotificationType
  • IDirectMusicSegment8::RemoveNotificationType
  • IDirectMusicTrack8::RemoveNotificationType
  • Notification and Event Handling


IDirectMusicPerformance8::RemovePort

The RemovePort method removes a port from the performance. Any performance channels that map to this port are invalidated, and messages on those channels are not performed.

Syntax

HRESULT RemovePort(
  IDirectMusicPort* pPort
);

Parameters

pPort

Port to remove.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Remarks

A port added by passing NULL to IDirectMusicPerformance8::AddPort cannot be removed by passing NULL to RemovePort.

This method should not be called by applications that use audiopaths.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::AddPort


IDirectMusicPerformance8::RhythmToTime

The RhythmToTime method converts rhythm time to music time.

Syntax

HRESULT RhythmToTime(
  WORD wMeasure,
  BYTE bBeat,
  BYTE bGrid,
  short nOffset,
  DMUS_TIMESIGNATURE *pTimeSig,
  MUSIC_TIME *pmtTime
);

Parameters

wMeasure

Measure of the time to convert.

bBeat

Beat of the time to convert.

bGrid

Grid of the time to convert.

nOffset

Offset from the grid, in music-time ticks, of the time to convert.

pTimeSig

Address of a DMUS_TIMESIGNATURE structure containing information about the time signature.

pmtTime

Address of a variable that receives the music time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method calculates a duration from the supplied measure, beat, grid, and offset, and adds the value in the mtTime member of the DMUS_TIMESIGNATURE structure.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::TimeToRhythm


IDirectMusicPerformance8::SendPMsg

The SendPMsg method sends a performance message. This method is called by tracks when they are played. It can also be called by an application or tool to insert data into a performance.

Syntax

HRESULT SendPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG

Message allocated by IDirectMusicPerformance8::AllocPMsg. This structure is of a type derived from DMUS_PMSG.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
E_INVALIDARG
E_POINTER

Remarks

The dwFlags member (see DMUS_PMSG) must contain either DMUS_PMSGF_MUSICTIME or DMUS_PMSGF_REFTIME, depending on whether the time stamp is in rtTime or mtTime. The dwFlags member should also contain the appropriate delivery type—DMUS_PMSGF_TOOL_QUEUE, DMUS_PMSGF_TOOL_ATTIME, or DMUS_PMSGF_TOOL_IMMEDIATE—depending on the type of message. If none is selected, DMUS_PMSGF_TOOL_IMMEDIATE is used by default.

If the time of the message is set to 0 and the dwFlags member contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.

In most cases, the IDirectMusicGraph8::StampPMsg method should be called on the message before SendPMsg is called. If the message is not stamped, it is not delivered to any tools implemented by the application, and might not play on the correct performance channel. If you want the message to pass only through the performance toolgraph, obtain the IDirectMusicGraph8 interface by calling IDirectMusicPerformance8::QueryInterface. Otherwise, obtain it by calling IDirectMusicSegmentState8::QueryInterface. Do not attempt to obtain the interface by calling IDirectMusicPerformance8::GetGraph or IDirectMusicSegment8::GetGraph; these methods return a pointer to the graph object, rather than to the implementation of the IDirectMusicGraph8 interface on the performance or segment.

If you are using audiopaths, it is generally best not to send a message directly to the performance, because the performance channels may have been remapped, and messages sent to a particular channel may not be played. Instead, obtain the IDirectMusicGraph8 interface from IDirectMusicAudioPath8. The audiopath then manages the remapping of the performance channel.

Normally, the performance frees the message after it has been processed. For more information, see the Remarks for IDirectMusicPerformance8::FreePMsg.

The following example function shows how to allocate and send a system exclusive message to the performance graph.

HRESULT SendSysexMessage(IDirectMusicPerformance8* pPerformance,
    MUSIC_TIME mtTime, DWORD pbSysExData[], DWORD dwSysExLength)
{
  IDirectMusicGraph* pGraph;
  HRESULT hr;

  if (SUCCEEDED(hr = pPerformance->QueryInterface(IID_IDirectMusicGraph,
                                                  (void**)&pGraph)))
  {
    DMUS_SYSEX_PMSG* pSysEx;
    if (SUCCEEDED(hr = pPerformance->AllocPMsg(
                    sizeof(DMUS_SYSEX_PMSG) + dwSysExLength,
                    (DMUS_PMSG**)&pSysEx)))
    {
      ZeroMemory(pSysEx, sizeof(DMUS_NOTE_PMSG));
      pSysEx->dwSize = sizeof(DMUS_SYSEX_PMSG);
      pSysEx->dwLen = dwSysExLength;
      pSysEx->mtTime = mtTime;
      pSysEx->dwFlags = DMUS_PMSGF_MUSICTIME;
      pSysEx->dwType = DMUS_PMSGT_SYSEX;
      memcpy(pSysEx->abData, pbSysExData, dwSysExLength);
      pGraph->StampPMsg((DMUS_PMSG*)pSysEx);
      if (FAILED(hr = pPerformance->SendPMsg((DMUS_PMSG*)pSysEx)))
      {
        pPerformance->FreePMsg( (DMUS_PMSG*)pSysEx );
      }
    }
    pGraph->Release();
  }
  return hr;
}

The next example function sends a note message associated with the track identified by dwTrackID. The virtual track ID should be 0 if the message is not being generated from a DirectMusicTrack object.

HRESULT CreateNotePMsg(IDirectMusicPerformance8* pPerformance,
    MUSIC_TIME mtTime, DWORD dwTrackID)
{
  // Allocate a Note PMessage.
  DMUS_NOTE_PMSG* pNote = NULL;
  HRESULT hr = pPerformance->AllocPMsg( sizeof(DMUS_NOTE_PMSG),
      (DMUS_PMSG**) &pNote);
  if (FAILED(hr)) return hr;

  pNote->dwSize = sizeof(DMUS_NOTE_PMSG); // Size of a Note Pmessage.
  pNote->rtTime = 0;                      // Ignored.
  pNote->mtTime = mtTime;                 // When to play the note.
  pNote->dwFlags = DMUS_PMSGF_MUSICTIME;  // Use the mtTime field.
  pNote->dwPChannel = 5;                  // Play on PChannel 5.
  pNote->dwVirtualTrackID = dwTrackID;    // Track ID from parameter.

  // The following two fields should be set to NULL when a
  // message is initially sent. They will be updated in
  // IDirectMusicGraph::StampPMsg.
  pNote->pTool = NULL;
  pNote->pGraph = NULL;
  pNote->dwType = DMUS_PMSGT_NOTE;
  pNote->dwVoiceID = 0;           // Always 0.
  pNote->dwGroupID = 0xFFFFFFFF;  // All track groups.
  pNote->punkUser = NULL;         // Always NULL.

  // Get the current time signature from the performance
  // to compute measure and beat information.
  DMUS_TIMESIGNATURE TimeSig;
  MUSIC_TIME mtNext;
  hr = pPerformance->GetParam(GUID_TimeSignature, 0xFFFFFFFF,
    0, mtTime, &mtNext, &TimeSig);
  if (FAILED(hr)) return hr;

  // Recompute TimeSig.mtTime to have the value expected
  // by pPerformance->TimeToRhythm.
  TimeSig.mtTime += mtTime;

  // Get the current chord from the performance
  // to create a note value.
  DMUS_CHORD_KEY Chord;
  hr = pPerformance->GetParam(GUID_ChordParam, 0xFFFFFFFF, 0,
      mtTime, &mtNext, &Chord);
  if (FAILED(hr)) return hr;

  // Create a note with octave 5, chord tone 2 (fifth), scale
  // offset 1 (=> sixth), and no accidentals.
  WORD wMusicValue = 0x5210;

  // Use DMUS_PLAYMODE_PEDALPOINT as your play mode
  // in pPerformance->MusicToMIDI.
  BYTE bPlayModeFlags = DMUS_PLAYMODE_PEDALPOINT;

  // Fill in the fields specific to DMUS_NOTE_PMSG.
  pNote->wMusicValue = wMusicValue;
  hr = pPerformance->MusicToMIDI(
      wMusicValue,
      &Chord,
      bPlayModeFlags,
      0,
      &(pNote->bMidiValue));
  if (FAILED(hr)) return hr;

  hr = pPerformance->TimeToRhythm(
      TimeSig.mtTime,
      &TimeSig,
      &(pNote->wMeasure),
      &(pNote->bBeat),
      &(pNote->bGrid),
      &(pNote->nOffset));
  if (FAILED(hr)) return hr;

  pNote->mtDuration = DMUS_PPQ;      // Quarter note duration.
  pNote->bVelocity = 120;            // MIDI velocity (0 to 127).
  pNote->bFlags = DMUS_NOTEF_NOTEON; // Always set to this value.
  pNote->bTimeRange = 250;           // Randomize start time a lot.
  pNote->bDurRange = 5;              // Randomize duration a little.
  pNote->bVelRange = 0;              // Don't randomize velocity.
  pNote->bPlayModeFlags = bPlayModeFlags;
  pNote->bSubChordLevel = 0;         // Note uses subchord level 0.
  pNote->cTranspose = 0;             // No transposition.

  // Stamp the message with the performance graph.
  IDirectMusicGraph* pGraph;
  hr = pPerformance->QueryInterface(IID_IDirectMusicGraph,
      (void**)&pGraph);
  if (FAILED(hr)) return hr;

  pGraph->StampPMsg((DMUS_PMSG*)pNote);
  pGraph->Release();

  // Finally, send the message.
  hr = pPerformance->SendPMsg((DMUS_PMSG*)pNote);
  if (FAILED(hr))
  {
    pPerformance->FreePMsg((DMUS_PMSG*)pNote);
    return hr;
  }
  return S_OK;
}

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Messages
  • DirectMusic Tools
  • IDirectMusicPerformance8 Interface
  • IDirectMusicTool8::ProcessPMsg
  • Messages


IDirectMusicPerformance8::SetBumperLength

The SetBumperLength method sets the interval between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.

Syntax

HRESULT SetBumperLength(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds

Buffer length, in milliseconds. The default value is 50.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetBumperLength
  • IDirectMusicPerformance8::SetPrepareTime
  • Latency and Bumper Time


IDirectMusicPerformance8::SetDefaultAudioPath

The SetDefaultAudioPath method sets and activates the default audiopath for the performance.

Syntax

HRESULT SetDefaultAudioPath(
  IDirectMusicAudioPath *pAudioPath
);

Parameters

pAudioPath

Pointer to the IDirectMusicAudioPath8 interface of the default audiopath, or NULL to remove the current default audiopath.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_AUDIOPATH_NOPORT
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT
E_INVALIDARG
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • Default Audiopath
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetDefaultAudioPath
  • IDirectMusicPerformance8::InitAudio


IDirectMusicPerformance8::SetGlobalParam

The SetGlobalParam method sets global values for the performance.

Syntax

HRESULT SetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data.

pParam

Address of data to be copied and stored by the performance.

dwSize

Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_POINTER
E_OUTOFMEMORY

Remarks

The dwSize parameter is needed because the performance does not know about all types of data. New types can be created as needed.

For the parameters defined by DirectMusic and their associated data types, see Setting and Retrieving Global Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetGlobalParam
  • IDirectMusicPerformance8::SetParam
  • Performance Parameters


IDirectMusicPerformance8::SetGraph

The SetGraph method replaces the performance's toolgraph.

Syntax

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph

Toolgraph to set. Can be set to NULL to clear the graph from the performance.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current toolgraph are deleted.

Because the graph's reference count is incremented by this method, it is safe to release the original reference.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Tools
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetGraph
  • IDirectMusicPerformance8::SendPMsg
  • IDirectMusicSegment8::SetGraph


IDirectMusicPerformance8::SetNotificationHandle

The SetNotificationHandle method sets the event handle for notifications.

Syntax

HRESULT SetNotificationHandle(
  HANDLE hNotification,
  REFERENCE_TIME rtMinimum
);

Parameters

hNotification

Event handle created by CreateEvent, or 0 to clear out an existing handle.

rtMinimum

Minimum time that the performance should hold onto old notify events before discarding them. The value 0 means to use the default minimum time of 20,000,000 reference time units, which is 2 seconds, or the previous value if this method has been called previously. If the application has not called GetNotificationPMsg by this time, the event is discarded to free the memory.

Return Values

The method returns S_OK.

Remarks

When the event is signaled, the application should call the IDirectMusicPerformance8::GetNotificationPMsg method to retrieve the notification event.

It is the application's responsibility to call the Win32 CloseHandle function on the notification handle when it is no longer needed.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • Notification and Event Handling


IDirectMusicPerformance8::SetParam

The SetParam method sets data on a track in the control segment.

Syntax

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.

dwGroupBits

Group that the desired track is in.

dwIndex

Index of the track in the group identified by dwGroupBits in which data is to be set, or DMUS_SEG_ALLTRACKS to set the parameter on all tracks in the group that contain the parameter.

mtTime

Time at which to set the data. Unlike IDirectMusicSegment8::SetParam, this time is in performance time. The start time of the segment is subtracted from this time, and the result is passed to IDirectMusicSegment8::SetParam.

pParam

Address of a structure containing the data. This structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as the control segment when it is played.

For an explanation of dwGroupBits and dwIndex, see Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

  • Control Segments
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::GetTime
  • IDirectMusicPerformance8::SetGlobalParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::SetParamEx
  • Performance Parameters


IDirectMusicPerformance8::SetPrepareTime

The SetPrepareTime method sets the interval between the time when messages are sent by tracks and the time when the sound is heard. This interval allows sufficient time for the message to be processed by tools.

Syntax

HRESULT SetPrepareTime(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds

Amount of prepare time, in milliseconds. The default value is 1000.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::GetPrepareTime
  • IDirectMusicPerformance8::SetBumperLength
  • Prepare Time


IDirectMusicPerformance8::Stop

The Stop method stops playback of a segment or segment state.

This method has been superseded by IDirectMusicPerformance8::StopEx, which can stop playback of a segment, segment state, or audiopath.

Syntax

HRESULT Stop(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegmentState,
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

pSegment

Segment to stop playing. All segment states based on this segment are stopped at mtTime. See Remarks.

pSegmentState

Segment state to stop playing. See Remarks.

mtTime

Time at which to stop the segment, segment state, or both. If the time is in the past or if 0 is passed in this parameter, the specified segment and segment states stop playing immediately.

dwFlags

Flag that indicates when the stop should occur. Boundaries are in relation to the current primary segment. For a list of values, see IDirectMusicPerformance8::StopEx.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If pSegment and pSegmentState are both NULL, all music stops, and all currently cued segments are released. If either pSegment or pSegmentState is not NULL, only the requested segment states are removed from the performance. If both are non-NULL and DMUS_SEGF_DEFAULT is used, the default resolution from the pSegment is used.

If you set all parameters to NULL or 0, everything stops immediately, and controller reset messages and note-off messages are sent to all mapped performance channels.

Requirements

Header: Declared in dmusici.h.

See Also

  • DMUS_SEGF_FLAGS
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::PlaySegmentEx
  • IDirectMusicPerformance8::PlaySegment
  • IDirectMusicPerformance8::StopEx


IDirectMusicPerformance8::StopEx

The StopEx method stops playback of a segment, segment state, or audiopath.

Syntax

HRESULT StopEx(
  IUnknown *pObjectToStop,
  __int64 i64StopTime,
  DWORD dwFlags
);

Parameters

pObjectToStop

Pointer to the IUnknown interface of the segment, segment state, or audiopath to stop.

i64StopTime

Time at which to stop. If the time is in the past or if 0 is passed in this parameter, the object stops playing immediately.

dwFlags

Flags that adjust the time when the stop should occur. Boundaries are in relation to the current primary segment. Can be 0 or one of the following values. DMUS_SEGF_REFTIME can be combined with one other flag.

Value | Description
DMUS_SEGF_AUTOTRANSITION | Not implemented.
DMUS_SEGF_BEAT | Stop on the next beat boundary at or after i64StopTime.
DMUS_SEGF_DEFAULT | Stop on the default boundary, as set by the IDirectMusicSegment8::SetDefaultResolution method.
DMUS_SEGF_GRID | Stop on the next grid boundary at or after i64StopTime.
DMUS_SEGF_MEASURE | Stop on the next measure boundary at or after i64StopTime.
DMUS_SEGF_REFTIME | The value in i64StopTime is in reference time.
DMUS_SEGF_SEGMENTEND | Stop at the end of the primary segment.
DMUS_SEGF_MARKER | Stop at the next marker.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Stopping a segment stops all instances that are playing. Stopping an audiopath stops all segments playing on that audiopath.

Requirements

Header: Declared in dmusici.h.

See Also

  • DMUS_SEGF_FLAGS
  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::PlaySegmentEx
  • IDirectMusicPerformance8::Stop


IDirectMusicPerformance8::TimeToRhythm

The TimeToRhythm method converts music time to rhythm time.

Syntax

HRESULT TimeToRhythm(
  MUSIC_TIME mtTime,
  DMUS_TIMESIGNATURE *pTimeSig,
  WORD *pwMeasure,
  BYTE *pbBeat,
  BYTE *pbGrid,
  short *pnOffset
);

Parameters

mtTime

Time to convert.

pTimeSig

Address of a DMUS_TIMESIGNATURE structure that contains information about the time signature.

pwMeasure

Address of a variable that receives the measure in which the time falls.

pbBeat

Address of a variable that receives the beat at which the time falls.

pbGrid

Address of a variable that receives the grid at which the time falls.

pnOffset

Address of a variable that receives the offset from the grid (in music-time ticks) at which the time falls.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8 Interface
  • IDirectMusicPerformance8::RhythmToTime


IDirectMusicPort8 Interface

The IDirectMusicPort8 interface represents a device that sends or receives sound data. Examples are the input port of an MPU-401, the output port of an MPU-401, the Microsoft software synthesizer, and an IHV-provided filter. A physical device such as an MPU-401 might provide multiple ports. A single port, however, cannot both capture and render data.

IDirectMusicPort8 is a define for IDirectMusicPort. The two interface names are interchangeable.

The interface is typically obtained by using the IDirectMusic8::CreatePort method.

For an overview, see Using DirectMusic Ports.

In addition to the methods inherited from IUnknown, the IDirectMusicPort8 interface exposes the following methods, arranged by category.

Buffers

Method | Description
PlayBuffer | Cues a buffer for playback by the port.
Read | Fills a buffer with incoming MIDI data.
SetReadNotificationHandle | Specifies an event that is to be set when MIDI messages are available to be read with the Read method.

Devices

Method | Description
Activate | Activates or deactivates the port.
DeviceIoControl | Calls the Win32 DeviceIoControl function on the underlying file handle implementing the port.
SetDirectSound | Overrides the default DirectSound device object or buffer, or both, to which a port's waveform data is streamed.

DLS data

Method | Description
Compact | Instructs the port to compact DLS or wave-table memory, thus making the largest possible contiguous chunk of memory available for new instruments to be downloaded.
DownloadInstrument | Downloads an instrument to the DLS device.
UnloadInstrument | Unloads a previously downloaded DLS instrument.

Information retrieval

Method | Description
GetCaps | Retrieves the port's capabilities.
GetFormat | Retrieves information about the WAV format specified in the DMUS_PORTPARAMS8 structure passed to IDirectMusic8::CreatePort, and the recommended size of the buffer to use for waveform output.
GetLatencyClock | Retrieves a pointer to the port's latency clock.
GetRunningStats | Retrieves information about the state of the synthesizer.

MIDI Channels

Method | Description
GetChannelPriority | Retrieves the priority of a MIDI channel.
GetNumChannelGroups | Retrieves the number of channel groups on the port.
SetChannelPriority | Sets the priority of a MIDI channel.
SetNumChannelGroups | Changes the number of channel groups that the application needs on the port.

The LPDIRECTMUSICPORT8 type is defined as a pointer to the IDirectMusicPort8 interface.

typedef IDirectMusicPort8 *LPDIRECTMUSICPORT8;

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces


IDirectMusicPort8::Activate

The Activate method activates or deactivates the port.

Syntax

HRESULT Activate(
  BOOL fActive
);

Parameters

fActive

Switch to activate (TRUE) or deactivate (FALSE) the port.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • IDirectMusic8::Activate
  • Using DirectMusic Ports


IDirectMusicPort8::Compact

The Compact method instructs the port to compact DLS or wave-table memory, thus making the largest possible contiguous chunk of memory available for new instruments to be downloaded.

Syntax

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

This method affects only DLS devices that need to manage their own DLS wavetable memory. On ports that do not manage their own memory (such as software synthesizers or hardware synthesizers that use host system memory), the method returns E_NOTIMPL.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface


IDirectMusicPort8::DeviceIoControl

The DeviceIoControl method calls the Win32 DeviceIoControl function on the underlying file handle implementing the port.

Syntax

HRESULT DeviceIoControl(
  DWORD        dwIoControlCode,
  LPVOID       lpInBuffer,
  DWORD        nInBufferSize,
  LPVOID       lpOutBuffer,
  DWORD        nOutBufferSize,
  LPDWORD      lpBytesReturned,
  LPOVERLAPPED lpOverlapped
);

Parameters

dwIoControlCode

Control code of the operation to perform.

lpInBuffer

Buffer that contains input data.

nInBufferSize

Size of input buffer.

lpOutBuffer

Buffer that receives output data.

nOutBufferSize

Size of the output buffer.

lpBytesReturned

Address of a variable that receives the output byte count.

lpOverlapped

Address of an OVERLAPPED structure for asynchronous operation. OVERLAPPED is defined in Winbase.h.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_NOTIMPL

Remarks

This method is supported only on ports implemented by a Windows Driver Model (WDM) filter graph. In the case of a WDM filter graph, the file handle used is the topmost pin in the graph.

DirectMusic can refuse to perform defined kernel streaming operations on a pin that might collide with operations that it is performing on the filter graph. User-defined operations, however, are never blocked.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface


IDirectMusicPort8::DownloadInstrument

The DownloadInstrument method downloads an instrument to the DLS device. Downloading an instrument means handing the data that makes up the instrument to the DLS device. This includes articulation data and all waveforms needed by the instrument. To conserve resources, only waveforms and articulation required for a range are downloaded. The method returns an IDirectMusicDownloadedInstrument8 interface pointer, which is later used to unload the instrument.

Syntax

HRESULT DownloadInstrument(
  IDirectMusicInstrument* pInstrument,
  IDirectMusicDownloadedInstrument** ppDownloadedInstrument,
  DMUS_NOTERANGE* pNoteRanges,
  DWORD dwNumNoteRanges;
);

Parameters

pInstrument

Pointer to the IDirectMusicInstrument8 interface of the instrument whose data is downloaded.

ppDownloadedInstrument

Address of a variable that receives a pointer to the IDirectMusicDownloadedInstrument8 interface.

pNoteRanges

Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.

dwNumNoteRanges

Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions and waveform data for the instrument are downloaded.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_OUTOFMEMORY
E_NOTIMPL

Remarks

To prevent memory loss, the instrument must be unloaded by calling both IDirectMusicPort8::UnloadInstrument and IDirectMusicDownloadedInstrument8::Release when it is no longer needed.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::Compact
  • Working with Instruments


IDirectMusicPort8::GetCaps

The GetCaps method retrieves the port's capabilities.

Syntax

HRESULT GetCaps(
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

pPortCaps

Address of a DMUS_PORTCAPS structure that receives the capabilities of the port. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface


IDirectMusicPort8::GetChannelPriority

The GetChannelPriority method retrieves the priority of a MIDI channel. For an overview, see Channels.

Syntax

HRESULT GetChannelPriority(
  DWORD dwChannelGroup,
  DWORD dwChannel,
  LPDWORD pdwPriority
);

Parameters

dwChannelGroup

Group that the channel is in.

dwChannel

Index of the channel on the group.

pdwPriority

Address of a variable that receives the priority ranking. See Remarks.

Return Values

The return value is S_OK.

Remarks

The following values, defined in Dmusicc.h, each represent a range of priorities. They are listed here in descending order of priority.

Value
DAUD_CRITICAL_VOICE_PRIORITY
DAUD_HIGH_VOICE_PRIORITY
DAUD_STANDARD_VOICE_PRIORITY
DAUD_LOW_VOICE_PRIORITY
DAUD_PERSIST_VOICE_PRIORITY

The following values express the default ranking of the channels within a range, according to the DLS standard. They are listed here in descending order. Channel 10, the percussion channel, has the highest priority.

Value
DAUD_CHAN10_VOICE_PRIORITY_OFFSET
DAUD_CHAN1_VOICE_PRIORITY_OFFSET
DAUD_CHAN2_VOICE_PRIORITY_OFFSET
DAUD_CHAN3_VOICE_PRIORITY_OFFSET
DAUD_CHAN4_VOICE_PRIORITY_OFFSET
DAUD_CHAN5_VOICE_PRIORITY_OFFSET
DAUD_CHAN6_VOICE_PRIORITY_OFFSET
DAUD_CHAN7_VOICE_PRIORITY_OFFSET
DAUD_CHAN8_VOICE_PRIORITY_OFFSET
DAUD_CHAN9_VOICE_PRIORITY_OFFSET
DAUD_CHAN11_VOICE_PRIORITY_OFFSET
DAUD_CHAN12_VOICE_PRIORITY_OFFSET
DAUD_CHAN13_VOICE_PRIORITY_OFFSET
DAUD_CHAN14_VOICE_PRIORITY_OFFSET
DAUD_CHAN15_VOICE_PRIORITY_OFFSET
DAUD_CHAN16_VOICE_PRIORITY_OFFSET

The priority of a channel is represented by a range plus an offset. For example, DAUD_HIGH_VOICE_PRIORITY combined with DAUD_CHAN10_VOICE_PRIORITY_OFFSET represents the highest priority within the high range. Combined range and offset values for the standard range are defined for convenience in Dmusicc.h as DAUD_CHAN1_DEF_VOICE_PRIORITY, .DAUD_CHAN2_DEF_VOICE_PRIORITY, and so on.

Channels that have the same priority value have equal priority, regardless of which channel group they belong to.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::SetChannelPriority


IDirectMusicPort8::GetFormat

The GetFormat method retrieves information about the WAV format specified in the DMUS_PORTPARAMS8 structure passed to IDirectMusic8::CreatePort, and the recommended size of the buffer to use for waveform output. The information can be used to create a compatible DirectSound buffer for the port.

Syntax

HRESULT GetFormat(
  LPWAVEFORMATEX pWaveFormatEx,
  LPDWORD pdwWaveFormatExSize
  LPDWORD pdwBufferSize
);

Parameters

pWaveFormatEx

Address of the WAVEFORMATEX structure that receives information about the format. This value can be NULL. See Remarks.

pdwWaveFormatExSize

Address of a variable that specifies or receives the size of the structure. See Remarks.

pdwBufferSize

Address of a variable that receives the recommended size of the DirectSound buffer.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return E_POINTER.

Remarks

The WAVEFORMATEX structure can have a variable length that depends on the details of the format. Before retrieving the format description, the application should query the synthesizer object for the size of the format by calling this method and specifying NULL for the pWaveFormatEx parameter. The size of the structure is returned in the variable pointed to by pdwWaveFormatExSize. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

If pWaveFormatEx is not NULL, DirectMusic writes, at most, pdwWaveFormatExSize bytes to the structure.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::SetDirectSound


IDirectMusicPort8::GetLatencyClock

The GetLatencyClock method retrieves an IReferenceClock interface pointer to the port's latency clock. The latency clock specifies the nearest time in the future at which a message can be played on time. The latency clock is based on the DirectMusic master clock, which is set by using the IDirectMusic8::SetMasterClock method.

Syntax

HRESULT GetLatencyClock(
  IReferenceClock** ppClock
);

Parameters

ppClock

Address of a variable that receives the latency clock's IReferenceClock interface pointer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

In accordance with COM rules, GetLatencyClock increments the reference count of the returned interface. Therefore, the application must call Release on the IReferenceClock interface at some point.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • Latency and Bumper Time


IDirectMusicPort8::GetNumChannelGroups

The GetNumChannelGroups method retrieves the number of channel groups on the port.

Syntax

HRESULT GetNumChannelGroups(
  LPDWORD pdwChannelGroups
);

Parameters

pdwChannelGroups

Address of a variable that receives the number of channel groups.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Header: Declared in dmusicc.h.

See Also

  • Channels
  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::SetNumChannelGroups


IDirectMusicPort8::GetRunningStats

The GetRunningStats method retrieves information about the state of the synthesizer.

Syntax

HRESULT GetRunningStats(
  LPDMUS_SYNTHSTATS pStats
);

Parameters

pStats

Address of a DMUS_SYNTHSTATS8 structure that receives running statistics of the synthesizer. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

Some hardware synthesizers might continue to report running statistics even though the port has been deactivated.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface


IDirectMusicPort8::PlayBuffer

The PlayBuffer method cues a buffer for playback by the port.

Syntax

HRESULT PlayBuffer(
  LPDIRECTMUSICBUFFER pBuffer
);

Parameters

pBuffer

Address of an IDirectMusicBuffer8 interface pointer of the buffer to be added to the port's playback queue.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

The buffer is in use by the system only for the duration of this method and can be reused after the method returns.

If no start time has been set by using the IDirectMusicBuffer8::SetStartTime method, the start time is the time of the earliest event in the buffer, as set by the IDirectMusicBuffer8::PackStructured or the IDirectMusicBuffer8::PackUnstructured method.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusic8::CreateMusicBuffer
  • IDirectMusicBuffer8 Interface
  • IDirectMusicPort8 Interface


IDirectMusicPort8::Read

The Read method fills a buffer with incoming MIDI data. The method should be called with new buffer objects until no more data is available to be read.

Syntax

HRESULT Read(
  LPDIRECTMUSICBUFFER pBuffer
);

Parameters

pBuffer

Address of the IDirectMusicBuffer8 interface pointer of the buffer object to be filled with the incoming MIDI data.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no more data to read.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.

See Also

  • Capturing MIDI
  • IDirectMusicPort8 Interface


IDirectMusicPort8::SetChannelPriority

The SetChannelPriority method sets the priority of a MIDI channel. For an overview, see Channels.

Syntax

HRESULT SetChannelPriority(
  DWORD  dwChannelGroup,
  DWORD  dwChannel,
  DWORD  dwPriority
);

Parameters

dwChannelGroup

Group that the channel is in. This value must be 1 or greater.

dwChannel

Index of the channel on the group.

dwPriority

The priority ranking. See Remarks for IDirectMusicPort8::GetChannelPriority.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.

See Also

  • DMUS_CHANNEL_PRIORITY_PMSG
  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::GetChannelPriority


IDirectMusicPort8::SetDirectSound

The SetDirectSound method overrides the default DirectSound device object or buffer, or both, to which a port's waveform data is streamed. This method is also used to disconnect the port from DirectSound.

Syntax

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  LPDIRECTSOUNDBUFFER pDirectSoundBuffer
);

Parameters

pDirectSound

Address of the IDirectSound8 interface of the DirectSound device object to which the port is to be connected, or NULL to disconnect and release the existing DirectSound device object.

pDirectSoundBuffer

Address of the IDirectSoundBuffer8 interface to connect the port to. This value can be NULL, and must be NULL if pDirectSound is NULL. This parameter is not used if the port is the Microsoft software synthesizer in DirectX 8.0 or later.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_NOBUFFERCONTROL. See Remarks.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_ALREADY_ACTIVATED
E_INVALIDARG

Remarks

If a valid pointer is passed in pDirectSoundBuffer, the method returns DMUS_S_NOBUFFERCONTROL if control changes in the buffer such as pan and volume do not affect DirectMusic playback. This affects only Windows Driver Model (WDM) ports.

When the port is activated, the primary DirectSound buffer is upgraded, if necessary, to support the sample rate and channel information for this port (specified in the DMUS_PORTPARAMS8 structure passed to IDirectMusic8::CreatePort).

The buffer pointed to by pDirectSoundBuffer must be a secondary streaming buffer with a format that matches the sample rate and channel information for this port. If this parameter is NULL, an appropriate IDirectSoundBuffer instance is created internally.

Neither the IDirectSound nor the IDirectSoundBuffer can be changed after the port has been activated.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::Activate
  • IDirectMusicPort8::GetFormat


IDirectMusicPort8::SetNumChannelGroups

The SetNumChannelGroups method changes the number of channel groups that the application needs on the port.

Syntax

HRESULT SetNumChannelGroups(
  DWORD dwChannelGroups
);

Parameters

dwChannelGroups

Number of channel groups on this port that the application wants to allocate.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Header: Declared in dmusicc.h.

See Also

  • Channels
  • IDirectMusicPort8 Interface
  • IDirectMusicPort8::GetNumChannelGroups


IDirectMusicPort8::SetReadNotificationHandle

The SetReadNotificationHandle method specifies an event that is to be set when MIDI messages are available to be read with the IDirectMusicPort8::Read method. The event is signaled whenever new data is available. To turn off event notification, call SetReadNotificationHandle with a NULL value for the hEvent parameter.

Syntax

HRESULT SetReadNotificationHandle(
  HANDLE hEvent
);

Parameters

hEvent

Event handle obtained from a call to the Win32 CreateEvent function. It is the application's responsibility to close this handle after the port has been released.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_DMUSIC_RELEASED
E_NOTIMPL

Remarks

A return value of E_NOTIMPL can mean the port is not an input port.

Requirements

Header: Declared in dmusicc.h.

See Also

  • Capturing MIDI
  • IDirectMusicPort8 Interface


IDirectMusicPort8::UnloadInstrument

The UnloadInstrument method unloads a previously downloaded DLS instrument.

Syntax

HRESULT UnloadInstrument(
  IDirectMusicDownloadedInstrument *pDownloadedInstrument
);

Parameters

pDownloadedInstrument

Address of an IDirectMusicDownloadedInstrument8 interface, obtained when the instrument was downloaded by calling the IDirectMusicPort8::DownloadInstrument method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_DOWNLOADED_TO_PORT
E_POINTER
E_NOTIMPL

Remarks

This method must be called to free memory allocated by IDirectMusicPort8::DownloadInstrument.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPort8 Interface
  • Working with Instruments


IDirectMusicPortDownload8 Interface

The IDirectMusicPortDownload8 interface enables an application to communicate directly with a port that supports DLS downloading and to download memory chunks directly to the port. The interface is used primarily by authoring applications that edit DLS instruments directly.

To obtain the IDirectMusicPortDownload8 interface, call the IDirectMusicPort8::QueryInterface method, passing in IID_IDirectMusicPortDownload8 as the interface GUID. If the port does not support DLS downloading, this call might fail.

In addition to the methods inherited from IUnknown, the IDirectMusicPortDownload8 interface exposes the following methods.

Buffers

Method | Description
AllocateBuffer | Creates a buffer for downloading DLS data to the port.
GetAppend | Retrieves the amount of memory that the port needs to be appended to the end of a download buffer.
GetBuffer | Retrieves the pointer of a buffer whose unique identifier is known.
GetDLId | Obtains sequential identifiers for one or more download buffers.

Data

Method | Description
Download | Downloads a waveform or instrument definition to the port.
Unload | Unloads a buffer that was previously downloaded.

The LPDIRECTMUSICPORTDOWNLOAD8 type is defined as a pointer to this interface.

typedef IDirectMusicPortDownload8 *LPDIRECTMUSICPORTDOWNLOAD8;

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Interfaces
  • Low-Level DLS


IDirectMusicPortDownload8::AllocateBuffer

The AllocateBuffer method allocates a chunk of memory for downloading DLS data to the port and returns an IDirectMusicDownload8 interface pointer that allows access to this buffer.

Syntax

HRESULT AllocateBuffer(
  DWORD dwSize,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwSize

Requested size of buffer.

ppIDMDownload

Address of a variable that receives the IDirectMusicDownload8 interface pointer.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG
E_OUTOFMEMORY

Remarks

After a buffer has been allocated, its size cannot change.

The buffer is freed when the IDirectMusicDownload8 interface is released.

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPortDownload8 Interface
  • IDirectMusicPortDownload8::GetBuffer
  • Low-Level DLS


IDirectMusicPortDownload8::Download

The Download method downloads a waveform or instrument definition to the port. The memory must first be allocated by using the IDirectMusicPortDownload8::AllocateBuffer method.

Syntax

HRESULT Download(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload

Address of the IDirectMusicDownload8 interface for the buffer.

Return Values

Return values are determined by the implementation of the port.

If the method succeeds, it returns S_OK.

If the method fails, it can return one of the error values shown in the following table.

Return code
E_POINTER
E_FAIL
DMUS_E_ALREADY_DOWNLOADED
DMUS_E_BADARTICULATION
DMUS_E_BADINSTRUMENT
DMUS_E_BADOFFSETTABLE
DMUS_E_BADWAVE
DMUS_E_BADWAVELINK
DMUS_E_BUFFERNOTSET
DMUS_E_NOARTICULATION
DMUS_E_NOTMONO
DMUS_E_NOTPCM
DMUS_E_UNKNOWNDOWNLOAD

Remarks

For more information on how to prepare the data to be downloaded, see Low-Level DLS.

After the memory has been downloaded, you cannot do anything more with it. To update the download, you must create a new buffer and assign it a new download ID obtained by using the IDirectMusicPortDownload8::GetDLId method, and then send it down.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DMUS_DOWNLOADINFO
  • DMUS_OFFSETTABLE
  • IDirectMusicPortDownload8 Interface
  • IDirectMusicPortDownload8::Unload


IDirectMusicPortDownload8::GetAppend

The GetAppend method retrieves the amount of memory that the port needs to be appended to the end of a download buffer. This extra memory can be used by the port to interpolate across a loop boundary.

Syntax

HRESULT GetAppend(
  DWORD* pdwAppend
);

Parameters

pdwAppend

Address of a variable that receives the number of appended samples for which memory is required. The amount of memory can be calculated from the WAV format.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPortDownload8 Interface


IDirectMusicPortDownload8::GetBuffer

The GetBuffer method retrieves the IDirectMusicDownload8 interface pointer of a buffer whose unique identifier is known.

Syntax

HRESULT GetBuffer(
  DWORD dwDLId,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwDLId

Download identifier of the buffer. See DMUS_DOWNLOADINFO.

ppIDMDownload

Address of a variable that receives the IDirectMusicDownload8 interface pointer for the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
DMUS_E_INVALID_DOWNLOADID
DMUS_E_NOT_DOWNLOADED_TO_PORT

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPortDownload8 Interface
  • IDirectMusicDownload8::GetBuffer
  • IDirectMusicPortDownload8::GetDLId
  • Low-Level DLS


IDirectMusicPortDownload8::GetDLId

The GetDLId method obtains sequential identifiers for one or more download buffers.

Every memory chunk downloaded to the synthesizer must have a unique identifier placed in its DMUS_DOWNLOADINFO structure. The GetDLId method guarantees that no two downloads have the same identifier.

Syntax

HRESULT GetDLId(
  DWORD* pdwStartDLId,
  DWORD dwCount
);

Parameters

pdwStartDLId

Address of a variable that receives the first identifier.

dwCount

Number of identifiers to reserve. You might plan to download a whole series of chunks at once. Instead of calling GetDLId for each chunk, set dwCount to the number of chunks. GetDLId returns the first ID of the set, and the additional identifiers are automatically reserved up through *pdwStartDLId plus dwCount. A subsequent call to GetDLId would skip past the reserved values.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPortDownload8 Interface
  • IDirectMusicPortDownload8::GetBuffer
  • Low-Level DLS


IDirectMusicPortDownload8::Unload

The Unload method unloads a buffer that was previously downloaded by using IDirectMusicPortDownload8::Download.

Syntax

HRESULT Unload(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload

Address of the IDirectMusicDownload8 interface for the buffer.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following values:

Return code
E_NOINTERFACE
DMUS_E_SYNTHNOTCONFIGURED

Requirements

Header: Declared in dmusicc.h.

See Also

  • IDirectMusicPortDownload8 Interface


IDirectMusicScript8 Interface

The IDirectMusicScript8 interface represents a script containing variables that can be set and retrieved by the application, and routines that can be called by the application.

Typically the interface is obtained by using IDirectMusicLoader8::GetObject to load a script file. The application then calls IDirectMusicScript8::Init to associate the script with the DirectMusicPerformance object that performs the actual playback.

In addition to the methods inherited from IUnknown, the IDirectMusic8 interface exposes the following methods.

Method | Description
CallRoutine | Executes a routine in the script.
EnumRoutine | Retrieves the name of a routine in a script.
EnumVariable | Retrieves the name of a variable in a script.
GetVariableNumber | Retrieves a 32-bit signed value from a variable declared in the script.
GetVariableObject | Retrieves an object pointer from a variable declared in the script, or retrieves an object embedded or referenced in the script file.
GetVariableVariant | Retrieves a variant value from a variable declared in the script.
Init | Associates the script with the performance that will play the sounds.
SetVariableNumber | Assigns a 32-bit signed value to a variable declared in the script.
SetVariableObject | Assigns an object interface pointer to a variable declared in the script.
SetVariableVariant | Assigns a variant value to a variable declared in the script.

Requirements

Header: Declared in dmusici.h.

See Also

See Also

  • DirectMusic Interfaces
  • Using Audio Scripts


IDirectMusicScript8::CallRoutine

The CallRoutine method executes a routine in the script.

Syntax

HRESULT CallRoutine(
  WCHAR *pwszRoutineName,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszRoutineName

Name of the routine.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this parameter to NULL if you do not want error information.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If the method fails, return values can include those in the following table.

Return code
DMUS_E_AUDIOVBSCRIPT_OPERATIONFAILURE
DMUS_E_AUDIOVBSCRIPT_RUNTIMEERROR
DMUS_E_AUDIOVBSCRIPT_SYNTAXERROR
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_ERROR_IN_SCRIPT
DMUS_E_SCRIPT_ROUTINE_NOT_FOUND
E_POINTER

Remarks

Control does not return to the application until the routine finishes running.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • Using Audio Scripts


IDirectMusicScript8::EnumRoutine

The EnumRoutine method retrieves the name of a routine in a script. This method might be used by authoring applications that need to enumerate all routines in a script.

Syntax

HRESULT EnumRoutine(
  DWORD dwIndex,
  WCHAR *pwszName
);

Parameters

dwIndex

Zero-based index of the routine.

pwszName

Pointer to a string buffer that receives the name of the routine. Must contain at least MAX_PATH elements.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The routine was enumerated.
S_FALSE | There is no routine with the supplied index value.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.
DMUS_S_STRING_TRUNCATED | The name is longer than MAX_PATH.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::EnumVariable
  • Using Audio Scripts


IDirectMusicScript8::EnumVariable

The EnumVariable method retrieves the name of a variable in a script. This method might be used by authoring applications that need to enumerate all variables in a script.

Syntax

HRESULT EnumVariable(
  DWORD dwIndex,
  WCHAR *pwszName
);

Parameters

dwIndex

Zero-based index of the variable.

pwszName

Address of a string buffer that receives the name of the variable. Must contain at least MAX_PATH elements.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The routine was enumerated.
S_FALSE | There is no routine with the supplied index value.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.
DMUS_S_STRING_TRUNCATED | The name is longer than MAX_PATH.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::EnumRoutine
  • Using Audio Scripts


IDirectMusicScript8::GetVariableNumber

The GetVariableNumber method retrieves a 32-bit signed value from a variable declared in the script.

Syntax

HRESULT GetVariableNumber(
  WCHAR *pwszVariableName,
  LONG *plValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName

Name of the script variable.

plValue

Address of a variable that receives the value.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DISP_E_TYPEMISMATCH (See Winerror.h.)
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::SetVariableNumber
  • Using Audio Scripts


IDirectMusicScript8::GetVariableObject

The GetVariableObject method retrieves an object pointer from a variable declared in the script, or retrieves an object embedded or referenced in the script file.

Syntax

HRESULT GetVariableObject(
  WCHAR* pwszVariableName,
  REFIID riid,
  LPVOID FAR* ppv,
  DMUS_SCRIPT_ERRORINFO* pErrInfo
);

Parameters

pwszVariableName

Name of the script variable or of the object referenced or embedded in the script.

riid

Unique identifier of the interface. See DirectMusic Interface GUIDs.

ppv

Address of a variable that receives a pointer to the desired interface of the object.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_NOINTERFACE
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::SetVariableObject
  • Using Audio Scripts


IDirectMusicScript8::GetVariableVariant

The GetVariableVariant method retrieves a variant value from a variable declared in the script.

Syntax

HRESULT GetVariableVariant(
  WCHAR *pwszVariableName,
  VARIANT *pvarValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName

Name of the script variable.

pvarValue

Address of a variable that receives the value.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::SetVariableVariant
  • Using Audio Scripts


IDirectMusicScript8::Init

The Init method associates the script with the performance that will play the sounds.

Syntax

HRESULT Init(
  IDirectMusicPerformance* pPerformance,
  DMUS_SCRIPT_ERRORINFO* pErrInfo
);

Parameters

pPerformance

Address of the IDirectMusicPerformance8 interface of the performance object.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Requirements

Header: Declared in dmusici.h.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The script was initialized.
S_FALSE | The script has already been attached to a different performance.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_ERROR_IN_SCRIPT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER
E_NOINTERFACE

See Also

  • IDirectMusicScript8 Interface
  • Using Audio Scripts


IDirectMusicScript8::SetVariableNumber

The SetVariableNumber method assigns a 32-bit signed value to a variable declared in the script.

Syntax

HRESULT SetVariableNumber(
  WCHAR *pwszVariableName,
  LONG lValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName

Name of the script variable.

lValue

Value to assign to the variable.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::GetVariableNumber
  • Using Audio Scripts


IDirectMusicScript8::SetVariableObject

The SetVariableObject method assigns an object interface pointer to a variable declared in the script.

Syntax

HRESULT SetVariableObject(
  WCHAR* pwszVariableName,
  IUnknown* punkValue,
  DMUS_SCRIPT_ERRORINFO* pErrInfo
);

Parameters

pwszVariableName

Name of the script variable.

punkValue

Interface pointer to assign to the variable. This can be an interface of one of the DirectMusic objects supported by the script engine, such as IDirectMusicSegment8, or an interface of any other object that implements the IDispatch interface.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::GetVariableObject
  • Using Audio Scripts


IDirectMusicScript8::SetVariableVariant

The SetVariableVariant method assigns a variant value to a variable declared in the script.

Syntax

HRESULT SetVariableVariant(
  WCHAR* pwszVariableName,
  VARIANT varValue,
  BOOL fSetRef,
  DMUS_SCRIPT_ERRORINFO* pErrInfo
);

Parameters

pwszVariableName

Name of the script variable.

varValue

Value to assign to the variable.

fSetRef

TRUE if the variable is to be set by reference, FALSE if by value. Only objects can be set by reference. This flag should always be TRUE for DirectMusic objects and FALSE for other variants.

pErrInfo

Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

Return code | Description
S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

Return code
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_NOT_A_REFERENCE
DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicScript8 Interface
  • IDirectMusicScript8::GetVariableObject
  • Using Audio Scripts


IDirectMusicSegment8 Interface

The IDirectMusicSegment8 interface represents a segment, which is a playable unit of data made up of multiple tracks.

The segment object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

IDirectMusicSegment8 supersedes the IDirectMusicSegment interface and introduces new methods.

In addition to the methods inherited from IUnknown, the IDirectMusicSegment8 interface exposes the following methods, arranged by category.

Instrument data

Method | Description
Download | Downloads band data to a performance or audiopath.
Unload | Unloads instrument data from a performance or audiopath.

Notification

Method | Description
AddNotificationType | Adds a type of event for which notifications are required.
RemoveNotificationType | Removes a a type of event for which notifications are required.

Timing and looping

Method | Description
GetDefaultResolution | Retrieves the default resolution of the segment. This is the value used to determine how times such as the segment start time are adjusted for synchronization with the rhythm.
GetLength | Retrieves the length of the segment.
GetLoopPoints | Retrieves the start and end loop points.
GetRepeats | Retrieves the number of times the looping portion of the segment is set to repeat.
GetStartPoint | Retrieves the point within the segment at which it starts playing.
SetDefaultResolution | Sets the default resolution of the segment.
SetLength | Sets the length, in music time, of the segment.
SetLoopPoints | Sets the start and end points of the part of the segment that repeats.
SetRepeats | Sets the number of times the looping portion of the segment is to repeat.
SetStartPoint | Sets the point within the segment at which it starts playing.

Toolgraphs

Method | Description
GetGraph | Retrieves the segment's toolgraph.
SetGraph | Assigns a toolgraph to the segment.

Track parameters

Method | Description
GetParam | Retrieves data from a track inside this segment.
SetParam | Sets data on a track inside this segment.

Tracks

Method | Description
GetTrack | Searches the list of tracks for the one with the specified type, group, and index, and retrieves an interface to the track.
GetTrackGroup | Retrieves the group bits set on a track inside the segment.
InsertTrack | Inserts the specified track into the segment's list of tracks.
RemoveTrack | Removes a track from the segment's track list.
SetTrackConfig | Sets the onfiguration of a track for miscellaneous behaviors.

Miscellaneous

Method | Description
Clone | Copies all or part of the segment.
Compose | Composes all tracks flagged as DMUS_TRACKCONFIG_COMPOSING and places the composed tracks in this segment or in a copy of this segment.
GetAudioPathConfig | Retrieves an object that represents an audiopath configuration embedded in the segment.
InitPlay | Initializes the play state.
SetPChannelsUsed | Sets the performance channels that this segment uses.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Using Segments


IDirectMusicSegment8::AddNotificationType

The AddNotificationType method adds a type of event for which notifications are required. This method is called by the IDirectMusicPerformance8::AddNotificationType method, allowing the segment to generate notifications. The segment calls each track's IDirectMusicTrack8::AddNotificationType method.

Syntax

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, it returns S_OK, or S_FALSE if the type was already added.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_OUTOFMEMORY

Remarks

Segments cannot generate notifications of type GUID_NOTIFICATION_PERFORMANCE. To get notifications of this type, you must call IDirectMusicPerformance8::AddNotificationType.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • Notification and Event Handling


IDirectMusicSegment8::Clone

The Clone method copies all or part of the segment.

Syntax

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicSegment** ppSegment
);

Parameters

mtStart

Start of the part to copy. If this value is less than 0 or greater than the length of the segment, the segment is copied from the beginning.

mtEnd

End time of the part to copy. If this value is past the end of the segment, or 0, or less than mtStart, the segment is copied to the end.

ppSegment

Address of a variable that receives a pointer to the IDirectMusicSegment interface of the created segment. Use QueryInterface to obtain IDirectMusicSegment8. It is the caller's responsibility to call Release when finished with the segment.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if some tracks failed to copy.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_OUTOFMEMORY
E_POINTER

Remarks

Properties of the original segment, including start and loop points, number of repeats, and any toolgraph and default audiopath, are copied.

For style-based segments, if mtStart is greater than 0, it should be on a measure boundary.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface


IDirectMusicSegment8::Compose

The Compose method composes all tracks flagged as DMUS_TRACKCONFIG_COMPOSING and places the composed tracks in this segment or in a copy of this segment.

Syntax

HRESULT Compose(
  MUSIC_TIME mtTime,
  IDirectMusicSegment* pFromSegment,
  IDirectMusicSegment* pToSegment,
  IDirectMusicSegment** ppComposedSegment
);

Parameters

mtTime

Value of type MUSIC_TIME that specifies the time in pFromSegment at which to compose a transition. Set to 0 if pFromSegment is NULL.

pFromSegment

Pointer to an IDirectMusicSegment8 interface that specifies the segment leading to a transition. This value is NULL if the calling segment is not a transition.

pToSegment

Pointer to the IDirectMusicSegment8 interface that specifies the segment following a transition. This value is NULL if the calling segment is not a transition or if the transition is an ending.

ppComposedSegment

Address of a variable that receives the IDirectMusicSegment8 interface pointer of the composed segment, or NULL if the calling segment is to be recomposed.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

If the pointer parameters are all NULL, the segment calls IDirectMusicTrack8::Compose on all its tracks. Any composing tracks search for other tracks necessary for composition; if a needed track is not found, DMUS_E_NOT_FOUND is returned.

If ppComposedSegment is not NULL, the method creates a copy of the original segment that contains the recomposed tracks. If either pFromSegment or pToSegment is not NULL, the calling segment is assumed to be a transition and might include tracks that contain only headers referring to one of the bracketing segments.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetTrackConfig
  • IDirectMusicTrack8::Compose
  • Track Composition


IDirectMusicSegment8::Download

The Download method downloads band data to a performance or audiopath.

Syntax

HRESULT Download(
  IUnknown* pAudioPath
);

Parameters

pAudioPath

Pointer to the IUnknown interface of the performance or audiopath that receives the data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method may return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

All bands and waveform data in the segment are downloaded.

Always call IDirectMusicSegment8::Unload before releasing the segment.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • Using Bands


IDirectMusicSegment8::GetAudioPathConfig

The GetAudioPathConfig method retrieves an object that represents an audiopath configuration embedded in the segment. The object can be passed to IDirectMusicPerformance8::CreateAudioPath.

Syntax

HRESULT GetAudioPathConfig(
  IUnknown** ppAudioPathConfig
);

Parameters

ppAudioPathConfig

Address of a variable that receives a pointer to the IUnknown interface of the audiopath configuration object.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method may return one of the error values shown in the following table.

Return code
DMUS_E_NO_AUDIOPATH_CONFIG
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • Creating Audiopaths


IDirectMusicSegment8::GetDefaultResolution

The GetDefaultResolution method retrieves the default resolution of the segment. This is the value used to determine how times such as the segment start time are adjusted for synchronization with the rhythm.

Syntax

HRESULT GetDefaultResolution(
  DWORD* pdwResolution
);

Parameters

pdwResolution

Address of a variable that receives the default resolution. This value can be 0 or one of the members of the DMUS_SEGF_FLAGS enumeration shown in the following table.

Value | Description
DMUS_SEGF_MEASURE | Resolve times to next measure.
DMUS_SEGF_BEAT | Resolve times to next beat.
DMUS_SEGF_GRID | Resolve times to next grid.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetDefaultResolution
  • Segment Timing


IDirectMusicSegment8::GetGraph

The GetGraph method retrieves the segment's toolgraph.

Syntax

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph

Address of a variable that receives a pointer to the toolgraph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

If there is no graph in the segment, the method returns DMUS_E_NOT_FOUND.

The reference count of the toolgraph is incremented.

The segment object implements IDirectMusicGraph directly This interface is used primarily to call the IDirectMusicGraph8::StampPMsg method directly on the segment. This has nothing to do with a graph object that might be embedded in the segment. If you want to access an embedded object, you are accessing a different IDirectMusicGraph interface because it is an interface on the embedded graph object, not the segment itself. To obtain an interface to an embedded audiopath, use the IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath method.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetGraph
  • DirectMusic Tools


IDirectMusicSegment8::GetLength

The GetLength method retrieves the length of the segment.

Syntax

HRESULT GetLength(
  MUSIC_TIME* pmtLength
);

Parameters

pmtLength

Address of a variable that receives the segment's length in music time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method always returns 1 in *pmtLength for segments created from WAV files.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetLength


IDirectMusicSegment8::GetLoopPoints

The GetLoopPoints method retrieves the start and end points of the part of the segment that repeats the number of times set by the IDirectMusicSegment8::SetRepeats method.

Syntax

HRESULT GetLoopPoints(
  MUSIC_TIME* pmtStart,
  MUSIC_TIME* pmtEnd
);

Parameters

pmtStart

Address of a variable that receives the start point of the loop.

pmtEnd

Address of a variable that receives the end point of the loop. A value of 0 indicates that the entire segment loops.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetLoopPoints
  • Segment Timing


IDirectMusicSegment8::GetParam

The GetParam method retrieves data from a track inside this segment.

Syntax

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.

dwGroupBits

Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see Identifying the Track.

dwIndex

Index of the track in the group identified by dwGroupBits from which to obtain the data, or DMUS_SEG_ANYTRACK to find the first track that contains the parameter.

mtTime

Time from which to obtain the data.

pmtNext

Address of a variable that receives the segment time (relative to mtTime) until which the data is valid. If this returns a value of 0, it means either that the data is always valid, or that it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.

pParam

Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_GET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

The data can become invalid before the time returned in *pmtNext if another control segment is cued. For more information, see Control Segments.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • Performance Parameters


IDirectMusicSegment8::GetRepeats

The GetRepeats method retrieves the number of times the looping portion of the segment is set to repeat.

Syntax

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats

Address of a variable that receives the number of times that the looping portion of the segment is set to repeat.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetRepeats


IDirectMusicSegment8::GetStartPoint

The GetStartPoint method retrieves the point within the segment at which it starts playing.

Syntax

HRESULT GetStartPoint(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart

Address of a variable that receives the time within the segment at which it starts playing.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::SetStartPoint
  • Segment Timing


IDirectMusicSegment8::GetTrack

The GetTrack method searches the list of tracks for the one with the specified type, group, and index, and retrieves an interface to the track object.

Syntax

HRESULT GetTrack(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  IDirectMusicTrack** ppTrack
);

Parameters

rguidType

Reference to (C++) or address of (C) the class identifier of the track to find. A value of GUID_NULL retrieves any track. For track identifiers, see Standard Track Types.

dwGroupBits

Track groups in which to scan for the track. A value of 0 is invalid. Each bit in dwGroupBits corresponds to a track group. To scan all tracks, regardless of groups, set this parameter to 0xFFFFFFFF.

dwIndex

Zero-based index into the list of tracks of type rguidType and in group dwGroupBits to return. If multiple groups are selected in dwGroupBits, this index indicates the nth track of type rguidType encountered in the union of the groups selected. See Remarks.

ppTrack

Address of a variable that receives a pointer to the track. The variable is set to NULL if the track is not found.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_FAIL
E_POINTER

Remarks

To enumerate all tracks, use GUID_NULL for the rguidType and 0xFFFFFFFF for dwGroupBits. Call GetTrack starting with 0 for dwIndex, incrementing dwIndex until the method no longer returns a success code.

Tracks in segments created by DirectMusic Producer are not necessarily in the same order as they were in that application. Do not rely on dwIndex alone to find a particular track.

For more information on track groups, see Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::InsertTrack
  • DirectMusic Tracks


IDirectMusicSegment8::GetTrackGroup

The GetTrackGroup method retrieves the group bits set on a track inside the segment.

Syntax

HRESULT GetTrackGroup(
  IDirectMusicTrack* pTrack,
  DWORD* pdwGroupBits
);

Parameters

pTrack

Track for which to find the group bits.

pdwGroupBits

Address of a variable that receives the groups. Each bit in the DWORD corresponds to a track group.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_INVALIDARG

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::InsertTrack
  • Identifying the Track


IDirectMusicSegment8::InitPlay

The InitPlay method initializes the play state. This method was for internal use and is not implemented in versions later than DirectX 7.0.

Syntax

HRESULT InitPlay(
  IDirectMusicSegmentState** ppSegState,
  IDirectMusicPerformance* pPerformance,
  DWORD dwFlags
);

Parameters

ppSegState

Address of a variable that receives a pointer to the IDirectMusicSegmentState8 interface that is created in response to this method call and is used to hold state data. It is returned with a reference count of 1, so a call to its Release method fully releases it.

pPerformance

Address of the IDirectMusicPerformance8 interface. This is needed by the segment and segment state to call methods on the performance object.

dwFlags

DMUS_SEGF_FLAGS that modify the track's behavior.

Return Values

In DirectX 8.0 and later, the method returns E_NOTIMPL.

In earlier versions, if the method succeeds, the return value is S_OK. If it fails, it can return one of the error values shown in the following table.

Return code
E_POINTER
E_OUTOFMEMORY

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface


IDirectMusicSegment8::InsertTrack

The InsertTrack method inserts the specified track into the segment's list of tracks.

Syntax

HRESULT InsertTrack(
  IDirectMusicTrack* pTrack,
  DWORD dwGroupBits
);

Parameters

pTrack

Track to add to the segment.

dwGroupBits

Group or groups into which to insert the track. This value cannot be 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

Tracks are put in groups to link them correctly. For example, a segment might contain two style tracks and two mute tracks. Each style track would be put in a different group, along with its associated mute track. For more information on track groups, see Identifying the Track.

If the segment is currently playing, the new track is not included in playback because the segment state was not initialized with the new track.

This method initializes the track. However, if the track data is subsequently changed, the application must initialize it again by calling IDirectMusicTrack8::Init.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetTrackGroup
  • IDirectMusicSegment8::RemoveTrack


IDirectMusicSegment8::RemoveNotificationType

The RemoveNotificationType method removes a type of data for which notifications are required. This method is called by the IDirectMusicPerformance8::RemoveNotificationType method, allowing the segment to remove notifications. The segment calls each track's IDirectMusicTrack8::RemoveNotificationType method.

Syntax

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) Setting this value to GUID_NULL causes all notifications to be removed.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the notification type was not previously set.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • Notification and Event Handling


IDirectMusicSegment8::RemoveTrack

The RemoveTrack method removes a track from the segment's track list.

Syntax

HRESULT RemoveTrack(
  IDirectMusicTrack* pTrack
);

Parameters

pTrack

Track to remove from the segment's track list.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the specified track is not in the track list.

If the method fails, the return value can be E_POINTER.

Remarks

The track is released when removed.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::InsertTrack


IDirectMusicSegment8::SetDefaultResolution

The SetDefaultResolution method sets the default resolution of the segment. This is the value used to determine how times such as the segment start time are adjusted for synchronization with the rhythm.

Syntax

HRESULT SetDefaultResolution(
  DWORD dwResolution
);

Parameters

dwResolution

Default resolution. This value can be 0 or one of the members of the DMUS_SEGF_FLAGS enumeration shown in the following table.

Value | Description
DMUS_SEGF_MEASURE | Resolve times to next measure.
DMUS_SEGF_BEAT | Resolve times to next beat.
DMUS_SEGF_GRID | Resolve times to next grid.

Return Values

The method returns S_OK.

Remarks

This method is used primarily by secondary segments to specify whether they are synchronized to the measure, beat, or grid of the primary segment by default.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetDefaultResolution
  • Segment Timing


IDirectMusicSegment8::SetGraph

The SetGraph method assigns a toolgraph to the segment.

Syntax

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph

Toolgraph pointer. Can be set to NULL to clear the segment graph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current toolgraph are deleted.

The graph's reference count is incremented, so it is safe to release the original reference.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicPerformance8::SetGraph
  • DirectMusic Tools


IDirectMusicSegment8::SetLength

The SetLength method sets the length, in music time, of the segment. This method is usually called by the loader, which retrieves the segment length from the file and passes it to the segment object.

Syntax

HRESULT SetLength(
  MUSIC_TIME mtLength
);

Parameters

mtLength

Desired length. Must be greater than 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
DMUS_E_OUT_OF_RANGE

Remarks

The length does not affect the time for which the segment plays, but it is used to determine when the segment ends for purposes of synchronization; for example, when another segment is cued with the DMUS_SEGF_QUEUE flag.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetLength


IDirectMusicSegment8::SetLoopPoints

The SetLoopPoints method sets the start and end points of the part of the segment that repeats the number of times set by the IDirectMusicSegment8::SetRepeats method.

Syntax

HRESULT SetLoopPoints(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd
);

Parameters

mtStart

Point at which to begin the loop.

mtEnd

Point at which to end the loop. A value of 0 loops the entire segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

When the segment is played, it plays from the segment start time until mtEnd, then loops to mtStart, plays the looped portion the number of times set by IDirectMusicSegment8::SetRepeats, and then plays to the end.

The default values are set to loop the entire segment from beginning to end.

The method fails if mtStart is greater than or equal to the length of the segment, or if mtEnd is greater than the length of the segment. If mtEnd is 0, mtStart must be 0 as well.

This method does not affect any currently playing segment states created from this segment.

The loop points of a cached segment persist even if the segment is released, and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader8::ReleaseObject on it before releasing it.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetLoopPoints
  • Segment Timing


IDirectMusicSegment8::SetParam

The SetParam method sets data on a track inside this segment.

Syntax

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the type of data to set. See Standard Track Parameters.

dwGroupBits

Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see Identifying the Track.

dwIndex

Index of the track in the group identified by dwGroupBits in which to set the data, or DMUS_SEG_ALLTRACKS to set the parameter on all tracks in the group that contain the parameter.

mtTime

Time at which to set the data.

pParam

Address of a structure containing the data, or NULL if no data is required for this parameter. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicTrack8::SetParamEx
  • Performance Parameters


IDirectMusicSegment8::SetPChannelsUsed

The SetPChannelsUsed method sets the performance channels that this segment uses. This method is usually called by a track in the IDirectMusicTrack8::Init method to inform the segment of which channels the track uses.

Syntax

HRESULT SetPChannelsUsed(
  DWORD dwNumPChannels,
  DWORD* paPChannels
);

Parameters

dwNumPChannels

Number of performance channels to set. This must be equal to the number of members in the array pointed to by paPChannels.

paPChannels

Address of an array of performance channel identifiers.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

This method enables the performance to ascertain which ports are being used by the segment so that it can determine the actual latency, rather than providing for the worst case.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • Channels
  • Latency and Bumper Time


IDirectMusicSegment8::SetRepeats

The SetRepeats method sets the number of times the looping portion of the segment is to repeat.

Syntax

HRESULT SetRepeats(
  DWORD dwRepeats
);

Parameters

dwRepeats

Number of times that the looping portion of the segment is to repeat, or DMUS_SEG_REPEAT_INFINITE to repeat until explicitly stopped. A value of 0 specifies a single play with no repeats.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetRepeats
  • IDirectMusicSegment8::SetLoopPoints
  • Segment Timing


IDirectMusicSegment8::SetStartPoint

The SetStartPoint method sets the point within the segment at which it starts playing.

Syntax

HRESULT SetStartPoint(
  MUSIC_TIME mtStart
);

Parameters

mtStart

Point within the segment at which it is to start playing. Must be greater than or equal to 0 and less than the length of the segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

The start point is the first point in the segment that can possibly be heard. However, the actual first point heard may be later, if the start point of the segment is aligned to a past time. For more information, see Segment Timing.

By default, the start point is 0, meaning that the segment starts from the beginning.

If the segment does not already have a length, IDirectMusicSegment8::SetLength must be called before SetStartPoint can be called. SetLength is normally called by the loader. However, when a WAV file is loaded, the length is always set to 1, because a WAV file is played in clock time and has no inherent music-time length. If you want to set the start point for a WAV file to some value other than 0, you must first call SetLength, setting the length to some value greater than the desired start point. The length you set does not have to be the actual length of the sound unless you intend to cue another segment after it. When the segment is played, the conversion of the start point to clock-time units is based on a tempo of 120. Alternatively, you can use DirectMusic Producer to create a segment file that has a wave track; in this case, the loader will set the correct music-time length based on the tempo of the segment.

The method does not affect any currently playing segment states created from this segment.

The start point of a cached segment persists even if the segment is released and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader8::ReleaseObject on it before releasing it.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::GetStartPoint
  • IDirectMusicSegment8::SetLength
  • IDirectMusicSegment8::SetLoopPoints
  • IDirectMusicSegmentState8::GetStartPoint
  • Segment Timing


IDirectMusicSegment8::SetTrackConfig

The SetTrackConfig method sets the configuration of a track for miscellaneous behaviors.

Syntax

HRESULT SetTrackConfig(
  REFGUID rguidTrackClassID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  DWORD dwFlagsOn,
  DWORD dwFlagsOff
);

Parameters

rguidTrackClassID

Reference to (C++) or address of (C) the identifier of the track class. For a list of values, see Standard Track Types.

dwGroupBits

Groups to which the track belongs.

dwIndex

Index of the track within the group, or DMUS_SEG_ALLTRACKS to set the configuration of all tracks in the group.

dwFlagsOn

Configuration flags to set. See Remarks.

dwFlagsOff

Configuration flags to clear. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TRACK_NOT_FOUND
E_INVALIDARG

Remarks

If you change a flag on a segment, subsequent instances of segment states inherit the change. However, segment states that are already playing do not change their behavior.

The following flags are defined:

Value | Description
DMUS_TRACKCONFIG_COMPOSING | Use this track to compose other tracks.
DMUS_TRACKCONFIG_CONTROL_ENABLED | Enable IDirectMusicTrack8::GetParamEx.
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION | When played in a control segment, override notification of primary segment tracks.
DMUS_TRACKCONFIG_CONTROL_PLAY | When played in a control segment, override playback of primary segment tracks.
DMUS_TRACKCONFIG_DEFAULT | The combination of DMUS_TRACKCONFIG_CONTROL_ENABLED | DMUS_TRACKCONFIG_PLAY_ENABLED | DMUS_TRACKCONFIG_NOTIFICATION_ENABLED.
DMUS_TRACKCONFIG_FALLBACK | The track tries to get parameters from this segment if the primary and control segments don't return the requested information.
DMUS_TRACKCONFIG_LOOP_COMPOSE | Regenerate data each time the track repeats.
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED | Enable notifications.
DMUS_TRACKCONFIG_OVERRIDE_ALL | The track tries to get parameters from this segment before the control and primary segment.
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY | The track tries to get parameters from this segment before the primary segment.
DMUS_TRACKCONFIG_PLAY_CLOCKTIME | Play in clock time, not music time.
DMUS_TRACKCONFIG_PLAY_COMPOSE | Regenerate data each time the track starts playing.
DMUS_TRACKCONFIG_PLAY_ENABLED | Enable track to send messages.
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT | In composing transitions, get track information from the current place in the first segment.
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART | In composing transitions, get track information from the start of the first segment.
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART | In composing transitions, get track information from the start of the second segment.

The following table shows which track configuration flags are valid for standard tracks.

Track | Valid flags
Band | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Chord | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Chordmap | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Command | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Lyrics | DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Marker | DMUS_TRACKCONFIG_CONTROL_ENABLED
Melody formulation (Not implemented for this release) | DMUS_TRACKCONFIG_COMPOSING DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_LOOP_COMPOSE DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_PLAY_COMPOSE DMUS_TRACKCONFIG_PLAY_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Motif | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_FALLBACK DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_OVERRIDE_ALL DMUS_TRACKCONFIG_OVERRIDE_PRIMARY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Mute | DMUS_TRACKCONFIG_CONTROL_ENABLED
Parameter control | DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Pattern | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_FALLBACK DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_OVERRIDE_ALL DMUS_TRACKCONFIG_OVERRIDE_PRIMARY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Script | DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Segment Trigger | DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Sequence | DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_FALLBACK DMUS_TRACKCONFIG_OVERRIDE_ALL DMUS_TRACKCONFIG_OVERRIDE_PRIMARY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Signpost | DMUS_TRACKCONFIG_COMPOSING DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_LOOP_COMPOSE DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_PLAY_COMPOSE DMUS_TRACKCONFIG_PLAY_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Style | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_FALLBACK DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_OVERRIDE_ALL DMUS_TRACKCONFIG_OVERRIDE_PRIMARY DMUS_TRACKCONFIG_PLAY_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Sysex | DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED
Tempo | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
Time signature | DMUS_TRACKCONFIG_CONTROL_ENABLED DMUS_TRACKCONFIG_CONTROL_NOTIFICATION DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_NOTIFICATION_ENABLED DMUS_TRACKCONFIG_PLAY_ENABLED
Wave | DMUS_TRACKCONFIG_CONTROL_PLAY DMUS_TRACKCONFIG_FALLBACK DMUS_TRACKCONFIG_OVERRIDE_ALL DMUS_TRACKCONFIG_OVERRIDE_PRIMARY DMUS_TRACKCONFIG_PLAY_CLOCKTIME DMUS_TRACKCONFIG_PLAY_ENABLED

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegmentState8::SetTrackConfig
  • Self-Controlling Segments
  • Track Configuration


IDirectMusicSegment8::Unload

The Unload method unloads instrument data from a performance or audiopath.

Syntax

HRESULT Unload(
  IUnknown *pAudioPath
);

Parameters

pAudioPath

Pointer to the IUnknown interface of the performance or audiopath from which to unload the instrument data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

The method succeeds even if no data was previously downloaded.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicSegment8::Download
  • Downloading and Unloading Bands


IDirectMusicSegmentState8 Interface

The IDirectMusicSegmentState8 interface represents a playing instance of a segment. When the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx method is called, the performance creates a segment state object that tracks the state of the playing segment. This object be passed toIDirectMusicPerformance8::StopEx.

IDirectMusicSegmentState8 supersedes IDirectMusicSegmentState and adds new methods.

In addition to the methods inherited from IUnknown, the IDirectMusicSegmentState8 interface exposes the following methods.

Method | Description
GetObjectInPath | Retrieves an interface for an object in the audiopath on which this segment state is playing.
GetRepeats | Retrieves the number of times that the looping portion of the segment is set to repeat.
GetSeek | Retrieves the seek pointer in the segment state.
GetSegment | Retrieves a pointer to the segment that owns this segment state.
GetStartPoint | Retrieves the time within the segment at which it started playing.
GetStartTime | Retrieves the performance time at which the segment started playing.
SetTrackConfig | Sets the configuration of a track in the parent segment.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces


IDirectMusicSegmentState8::GetObjectInPath

The GetObjectInPath method retrieves an interface for an object in the audiopath on which this segment state is playing.

Syntax

HRESULT GetObjectInPath(
  DWORD dwPChannel,
  DWORD dwStage,
  DWORD dwBuffer,
  REFGUID guidObject,
  DWORD dwIndex,
  REFGUID iidInterface,
  Void** ppObject
);

Parameters

dwPChannel

Performance channel to search, or DMUS_PCHANNEL_ALL to search all channels. The first channel is numbered 0. See Remarks.

dwStage

Stage in the path. Can be one of the values listed in the following table.

Value | Description
DMUS_PATH_AUDIOPATH | The audiopath on which the segment state is playing.
DMUS_PATH_AUDIOPATH_GRAPH | The audiopath toolgraph. One is created if none exists.
DMUS_PATH_AUDIOPATH_TOOL | A tool from the audiopath toolgraph.
DMUS_PATH_BUFFER | A DirectSound buffer.
DMUS_PATH_BUFFER_DMO | A DMO in the buffer. For information on DMO interfaces, see IDirectSoundBuffer8::GetObjectInPath.
DMUS_PATH_MIXIN_BUFFER | A global mix-in buffer.
DMUS_PATH_MIXIN_BUFFER_DMO | A DMO in a global mix-in buffer.
DMUS_PATH_PERFORMANCE | The performance.
DMUS_PATH_PERFORMANCE_GRAPH | The performance toolgraph. One is created if none exists.
DMUS_PATH_PERFORMANCE_TOOL | A tool in the performance graph.
DMUS_PATH_PORT | The synthesizer.
DMUS_PATH_PRIMARY_BUFFER | The primary buffer.
DMUS_PATH_SEGMENT | The segment that owns this segment state.
DMUS_PATH_SEGMENT_GRAPH | The segment toolgraph. One is created if none exists. See Remarks.
DMUS_PATH_SEGMENT_TOOL | A tool from the segment graph. See Remarks.
DMUS_PATH_SEGMENT_TRACK | A track from the segment. See Remarks.

dwBuffer

If dwStage is DMUS_PATH_BUFFER_DMO or DMUS_PATH_MIXIN_BUFFER_DMO, the index of the buffer in which that DMO resides. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, the index of the buffer. Otherwise must be 0.

guidObject

Class identifier of the objector GUID_All_Objects to search for an object of any class. This parameter is ignored if only a single class of object can exist at the stage specified by dwStage, and can be set to GUID_NULL.

dwIndex

Index of the object in the list of matching objects. Set to 0 to find the first matching object. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, this parameter is ignored, and the buffer index is specified by dwBuffer.

iidInterface

Identifier of the desired interface, such as IID_IDirectMusicGraph.

ppObject

Address of a variable that receives a pointer to the requested interface.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_INVALIDARG
E_NOINTERFACE
E_OUTOFMEMORY

Remarks

The value in dwPChannel must be 0 for any stage that is not channel-specific. Objects in the following stages are channel-specific and can be retrieved by setting a channel number or DMUS_PCHANNEL_ALL in dwPChannel:

Value
DMUS_PATH_AUDIOPATH_TOOL
DMUS_PATH_BUFFER
DMUS_PATH_BUFFER_DMO
DMUS_PATH_PERFORMANCE_TOOL
DMUS_PATH_PORT
DMUS_PATH_SEGMENT_TOOL

The precedence of the parameters in filtering out unwanted objects is as follows:

  1. dwStage.
  2. guidObject. If this value is not GUID_All_Objects, only objects whose class identifier equals guidObject are searched. However, this parameter is ignored when only a single class of object can exist at the specified stage.
  3. dwPChannel. If the stage is channel-specific and this value is not DMUS_PCHANNEL_ALL, only objects on the channel are searched.
  4. dwBuffer. This is used only if dwStage is DMUS_PATH_BUFFER, DMUS_PATH_MIXIN_BUFFER, DMUS_PATH_BUFFER_DMO, or DMUS_PATH_MIXIN_BUFFER_DMO.
  5. dwIndex. Note that tracks in segments created by DirectMusic Producer are not necessarily in the same order as they were in that application. Do not rely on dwIndex alone to find a particular track at stage DMUS_PATH_SEGMENT_TRACK.

If a matching object is found but the interface specified by iidInterface cannot be obtained, the method fails.

The object returned when DMUS_PATH_SEGMENT_GRAPH or DMUS_PATH_SEGMENT_TOOL is specified in dwStage might not be the same one returned for a different segment state based on the same segment. When a segment is played, its toolgraph is copied and any tools that support the IDirectMusicTool8::Clone method are also cloned.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • IDirectMusicAudioPath8::GetObjectInPath
  • Retrieving Objects from an Audiopath


IDirectMusicSegmentState8::GetRepeats

The GetRepeats method retrieves the number of times that the looping portion of the segment is set to repeat.

Syntax

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats

Address of a variable that receives the repeat count. A value of 0 indicates that the segment is to play through only once, with no portion repeated.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • IDirectMusicSegment8::SetRepeats


IDirectMusicSegmentState8::GetSeek

The GetSeek method retrieves the seek pointer in the segment state. This is the value that is passed in the mtStart parameter of IDirectMusicTrack8::Play the next time that method is called. It does not take into account looping and repeating; if the entire segment state repeats to the beginning, the seek pointer is reset to 0.

Syntax

HRESULT GetSeek(
  MUSIC_TIME* pmtSeek
);

Parameters

pmtSeek

Address of a variable that receives the seek pointer.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Remarks

This method is not an accurate way of determining the current play position, because it seeks beyond the prepare time. For a better way to determine the current play position, see Pausing Segments.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • Prepare Time


IDirectMusicSegmentState8::GetSegment

The GetSegment method retrieves a pointer to the segment that generated this segment state.

Syntax

HRESULT GetSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment

Address of a variable that receives a pointer to the IDirectMusicSegment interface. Use QueryInterface to obtain IDirectMusicSegment8 interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
E_POINTER

Remarks

The pointer returned in ppSegment must be released by the application.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface


IDirectMusicSegmentState8::GetStartPoint

The GetStartPoint method retrieves the time within the segment at which it started playing.

Syntax

HRESULT GetStartPoint(
  MUSIC_TIME * pmtStart
);

Parameters

pmtStart

Address of a variable that receives the music-time offset from the start of the segment at which play will begin or began.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The start point is the first point in the segment that can possibly be heard. However, the actual first point heard may be later, if the start point of the segment is aligned to a past time. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • IDirectMusicSegment8::SetStartPoint
  • IDirectMusicSegmentState8::GetStartTime
  • Segment Timing


IDirectMusicSegmentState8::GetStartTime

The GetStartTime method retrieves the performance time at which the segment started playing.

Syntax

HRESULT GetStartTime(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart

Address of a variable that receives the music-time offset stored in this segment state.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The time retrieved by this method is the resolved play time within the performance where the segment start time was cued. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • IDirectMusicSegment8::GetStartPoint
  • IDirectMusicSegment8::SetStartPoint
  • IDirectMusicSegmentState8::GetStartPoint


IDirectMusicSegmentState8::SetTrackConfig

The SetTrackConfig method sets the configuration of a track in the parent segment.

Syntax

HRESULT SetTrackConfig(
  REFGUID rguidTrackClassID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  DWORD dwFlagsOn,
  DWORD dwFlagsOff
);

Parameters

rguidTrackClassID

Reference to (C++) or address of (C) the identifier of the track class. For a list of values, see Standard Track Types.

dwGroupBits

Groups to which the track belongs.

dwIndex

Index of the track within the group, or DMUS_SEG_ALLTRACKS to set the configuration of all tracks in the group.

dwFlagsOn

Configuration flags to set. For a list of values, see IDirectMusicSegment8::SetTrackConfig.

dwFlagsOff

Configuration flags to clear.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TRACK_NOT_FOUND
E_INVALIDARG

Remarks

Any change in configuration takes effect after prepare time. If you want the change to take effect immediately, call IDirectMusicPerformance8::Invalidate.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegmentState8 Interface
  • IDirectMusicSegment8::SetTrackConfig
  • Self-Controlling Segments
  • Track Configuration


IDirectMusicStyle8 Interface

The IDirectMusicStyle8 interface represents a collection of patterns, motifs, and bands used in run-time composition of musical segments. For an overview, see Using Styles.

Style objects also support the IDirectMusicObject8 and IPersistStream interfaces for loading their data.

IDirectMusicStyle8 supersedes the IDirectMusicStyle interface and provides a new method, EnumPattern.

In addition to the methods inherited from IUnknown, the IDirectMusicStyle8 interface exposes the following methods, arranged by category.

Data retrieval

Method | Description
GetBand | Retrieves a band specified by name.
GetChordMap | Retrieves a chordmap specified by name.
GetDefaultBand | Retrieves the style's default band.
GetDefaultChordMap | Retrieves the style's default chordmap.
GetEmbellishmentLength | Finds the shortest and longest lengths for patterns of the specified embellishment type and groove level.
GetMotif | Creates a segment containing a motif specified by name.
GetTempo | Retrieves the recommended tempo of the style.
GetTimeSignature | Retrieves the style's time signature.

Enumeration

Method | Description
EnumBand | Retrieves the name of the band with a specified index value.
EnumChordMap | Retrieves the name of the chordmap with a specified index value.
EnumMotif | Retrieves the name of a motif with a specified index value.
EnumPattern | Retrieves the name of a pattern with a specified index value and type.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces


IDirectMusicStyle8::EnumBand

The EnumBand method retrieves the name of the band with a specified index value.

Syntax

HRESULT EnumBand(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex

Zero-based index into the style's band list.

pwszName

Address of a buffer that receives the band name. This should be of size MAX_PATH.

Return Values

If the method succeeds, it returns S_OK, S_FALSE if there is no band with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • Using Bands


IDirectMusicStyle8::EnumChordMap

The EnumChordMap method retrieves the name of the chordmap with a specified index value.

Syntax

HRESULT EnumChordMap(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex

Zero-based index of the chordmap in the style's chordmap list.

pwszName

Address of a buffer that receives the chordmap name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no chordmap with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Remarks

DirectMusic Producer does not support embedding chordmap references in style files.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface


IDirectMusicStyle8::EnumMotif

The EnumMotif method retrieves the name of a motif with a specified index value.

Syntax

HRESULT EnumMotif(
  DWORD dwIndex,
  WCHAR* pwszName
);

Parameters

dwIndex

Zero-based index into the style's motif list.

pwszName

Address of a buffer that receives the motif name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no motif with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the motif name is greater than MAX_PATH.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • IDirectMusicStyle8::GetMotif
  • Using Motifs


IDirectMusicStyle8::EnumPattern

The EnumPattern method retrieves the name of a pattern with a specified index value and type. The name can be passed to the IDirectMusicPatternTrack8::SetPatternByName method.

Syntax

HRESULT EnumPattern(
  DWORD dwIndex,
  DWORD dwPatternType,
  WCHAR* pwszName
);

Parameters

dwIndex

Zero-based index into the style's pattern list.

dwPatternType

One of the DMUS_STYLET_TYPES enumeration that specifies the type of pattern.

pwszName

Address of a buffer that receives the pattern name. The buffer should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no pattern with the given index value and type, or DMUS_S_STRING_TRUNCATED if the length of the motif name is greater than MAX_PATH.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface


IDirectMusicStyle8::GetBand

The GetBand method retrieves a band specified by name.

Syntax

HRESULT GetBand(
  WCHAR* pwszName,
  IDirectMusicBand** ppBand
);

Parameters

pwszName

Name of the band to retrieve. This name is created by the author of the style.

ppBand

Address of a variable that receives the IDirectMusicBand8 interface.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if there is no band with that name.

If the method fails, the return value can be E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • IDirectMusicStyle8::GetDefaultBand
  • Using Bands


IDirectMusicStyle8::GetChordMap

The GetChordMap method retrieves a chordmap specified by name.

Syntax

HRESULT GetChordMap(
  WCHAR* pwszName,
  IDirectMusicChordMap** ppChordMap
);

Parameters

pwszName

Name of the chordmap to retrieve. This name is created by the author of the style.

ppChordMap

Address of a variable that receives a pointer to the IDirectMusicChordMap8 interface.

Return Values

If the method succeeds, the return value is S_OK if a chordmap is returned, or S_FALSE if there is no chordmap by that name.

If ppChordMap is not a valid pointer, the method returns E_POINTER.

Remarks

DirectMusic Producer does not support embedding chordmap references in style files.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • IDirectMusicStyle8::GetDefaultChordMap
  • Using Chordmaps


IDirectMusicStyle8::GetDefaultBand

The GetDefaultBand method retrieves the style's default band.

Syntax

HRESULT GetDefaultBand(
  IDirectMusicBand ** ppBand
);

Parameters

ppBand

Address of a variable that receives the IDirectMusicBand8 interface pointer for the default band.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if the style does not have a default band.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • IDirectMusicStyle8::GetBand
  • Using Bands


IDirectMusicStyle8::GetDefaultChordMap

The GetDefaultChordMap method retrieves the style's default chordmap.

Syntax

HRESULT GetDefaultChordMap(
  IDirectMusicChordMap** ppChordMap
);

Parameters

ppChordMap

Address of a variable that receives a pointer to the IDirectMusicChordMap8 interface.

Return Values

If the method succeeds, the return value is S_OK if a chordmap is returned, or S_FALSE if the style does not have a default chordmap.

If it fails, the method can return E_POINTER.

Remarks

DirectMusic Producer does not support embedding chordmap references in style files.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface
  • IDirectMusicStyle8::GetChordMap
  • Using Chordmaps


IDirectMusicStyle8::GetEmbellishmentLength

The GetEmbellishmentLength method finds the shortest and longest lengths for patterns of the specified embellishment type and groove level.

Syntax

HRESULT GetEmbellishmentLength(
  DWORD dwType,
  DWORD dwLevel,
  DWORD* pdwMin,
  DWORD* pdwMax
);

Parameters

dwType

Embellishment type. This can be one of the DMUS_COMMANDT_TYPES enumeration, or a value defined in DirectMusic Producer as a custom embellishment.

dwLevel

Groove level, in the range from 1 through 100. Ignored if dwType is not DMUS_COMMANDT_GROOVE.

pdwMin

Address of a variable that receives the length, in measures, of the shortest pattern of the specified type and groove level.

pdwMax

Address of a variable that receives the length, in measures, of the longest pattern of the specified type and groove level.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

If there are no patterns of the specified type and groove level, the method returns S_FALSE.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface


IDirectMusicStyle8::GetMotif

The GetMotif method creates a segment containing a motif specified by name.

Syntax

HRESULT GetMotif(
  WCHAR* pwszName,
  IDirectMusicSegment** ppSegment
);

Parameters

pwszName

Name of the motif.

ppSegment

Address of a variable that receives a pointer to a segment containing the named motif.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

The method searches the style's list of motifs for one whose name matches pwszName. If one is found, a segment is created containing a motif track. The track references the style as its associated style and the motif as its pattern.

If there is no motif with the name, the method returns S_FALSE.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8 Interface
  • IDirectMusicStyle8 Interface
  • Using Motifs


IDirectMusicStyle8::GetTempo

The GetTempo method retrieves the recommended tempo of the style.

Syntax

HRESULT GetTempo(
  double* pTempo
);

Parameters

pTempo

Address of a variable that receives the recommended tempo of the style.

Return Values

If the method succeeds, the return value is S_OK.

If pTempo is not a valid pointer, the method returns E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface


IDirectMusicStyle8::GetTimeSignature

The GetTimeSignature method retrieves the time signature of the style.

Syntax

HRESULT GetTimeSignature(
  DMUS_TIMESIGNATURE* pTimeSig
);

Parameters

pTimeSig

Address of a DMUS_TIMESIGNATURE structure that receives data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicStyle8 Interface


IDirectMusicSynth Interface

The IDirectMusicSynth interface is implemented by synthesizers. Applications do not use this interface but communicate with the port by using IDirectMusicPort8.

For more information, see the following topic on mdsn.microsoft.com:

  • DirectMusic User Mode Synth and Synth Sink Interfaces

Requirements

Header: Declared in dmusics.h.

See Also

  • DirectMusic Interfaces


IDirectMusicSynthSink Interface

The IDirectMusicSynthSink interface is implemented by a synthesizer sink, which pull data from a synthesizer. Applications do not use this interface.

A custom sink for the default DirectX 7.0 synthesizer (created by calling IDirectMusicPerformance8::Init) must implement this interface. Such a sink will not work with the default synthesizer for DirectX 8.0 and later (created by calling IDirectMusicPerformance8::InitAudio). To capture output from the later version of the synthesizer, you must implement a DMO on the primary buffer.

For more information, see the following topic on mdsn.microsoft.com:

  • DirectMusic User Mode Synth and Synth Sink Interfaces

Requirements

Header: Declared in dmusics.h.

See Also

  • DirectMusic Interfaces


IDirectMusicThru8 Interface

The IDirectMusicThru8 interface supports thruing of MIDI messages from a capture port to another port. It is obtained by calling QueryInterface on the IDirectMusicPort8 interface for the capture port. For an example, see the Remarks for IDirectMusicThru8::ThruChannel.

IDirectMusicThru8 is a type definition for IDirectMusicThru. The two interface names can be used interchangeably.

In addition to the methods inherited from IUnknown, the IDirectMusicThru8 interface exposes the following methods.

Method | Description
ThruChannel | Establishes or breaks a thruing connection between a channel on a capture port and a channel on another port.

The LPDIRECTMUSICTHRU8 type is defined as a pointer to this interface.

typedef IDirectMusicThru8 *LPDIRECTMUSICTHRU8;

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Interfaces
  • Capturing MIDI


IDirectMusicThru8::ThruChannel

The ThruChannel method establishes or breaks a thruing connection between a channel on a capture port and a channel on another port.

Syntax

HRESULT ThruChannel(
  DWORD dwSourceChannelGroup,
  DWORD dwSourceChannel,
  DWORD dwDestinationChannelGroup,
  DWORD dwDestinationChannel,
  LPDIRECTMUSICPORT pDestinationPort
);

Parameters

dwSourceChannelGroup

Channel group on the capture port. This value is always 1.

dwSourceChannel

Source channel.

dwDestinationChannelGroup

Channel group on the destination port.

dwDestinationChannel

Destination channel.

pDestinationPort

Address of the IDirectMusicPort8 interface for the destination channel. Set this value to NULL to break an existing thruing connection.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_NOTIMPL
E_INVALIDARG
DMUS_E_PORT_NOT_RENDER

Remarks

System-exclusive messages are not transmitted to the destination port.

Thruing to the Microsoft software synthesizer or other synthesizers that do not have a constant latency is not recommended. Thruing is done as soon as possible upon reception of the incoming MIDI events. Because of the comparatively high latency of the software synthesizer (compared with a hardware port) and the fact that it renders blocks of audio data at the same time, each event is delayed by a small, essentially random amount of time before it plays. This random offset shows up as jitter in the playback of the data. Latency of other devices (such as an MPU-401 port) is small enough that jitter does not occur.

If an application needs to thru to the software synthesizer, it should add a small offset to the incoming note event time stamps to compensate for the rendering latency of the synthesizer.

The following code example obtains the IDirectMusicThru8 interface and establishes a thru connection between all channels on group 1 of the capture port and the equivalent channels on a destination port.

HRESULT SetupOneToOneThru(
    IDirectMusicPort8 *pCapturePort,
    IDirectMusicPort8 *pRenderPort)
{
  HRESULT hr;
  IDirectMusicThru8 *pThru;

  hr = pCapturePort->QueryInterface(IID_IDirectMusicThru8,
      (void**)&pThru);
  if (FAILED(hr)) return hr;
  for (DWORD dwChannel = 0; dwChannel < 16; dwChannel++)
  {
    hr = pThru->ThruChannel(1, dwChannel,
        1, dwChannel, (IDirectMusicPort*)pRenderPort);
    if (FAILED(hr)) break;
  }
  pThru->Release();
  return hr;
}

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicThru8 Interface


IDirectMusicTool8 Interface

The IDirectMusicTool8 interface represents a tool object that processes messages.

Methods of this interface are implemented by tools and are generally called by the performance. The application only needs to insert the tool in the message path by using IDirectMusicGraph8::InsertTool.

IDirectMusicTool8 supersedes the IDirectMusicTool interface and adds a new method.

In addition to the methods inherited from IUnknown, the IDirectMusicTool8 interface exposes the following methods.

Method | Description
Clone | Creates a new instance of the tool.
Flush | Flushes messages from the queue when the performance stops.
GetMediaTypeArraySize | Retrieves the size of the array that must be passed in to the IDirectMusicTool8::GetMediaTypes method.
GetMediaTypes | Retrieves a list of the types of messages that this tool supports.
GetMsgDeliveryType | Retrieves the tool's delivery type, which determines when messages are to be delivered to the tool.
Init | Initializes the tool.
ProcessPMsg | Performs the main task of the tool.

Requirements

Header: Declared in dmplugin.h.

See Also

  • DirectMusic Interfaces
  • DirectMusic Tools
  • Message Creation and Delivery


IDirectMusicTool8::Clone

The Clone method creates a new instance of the tool.

Syntax

HRESULT Clone(
  IDirectMusicTool** ppTool
);

Parameters

ppTool

Address of a variable that receives a pointer to the IDirectMusicTool interface of the new instance of the tool. Use QueryInterface to obtain IDirectMusicTool8.

Return Values

Return values are determined by the implementation. If it succeeds, the method should return S_OK. If it fails, the return value might be E_POINTER or E_OUTOFMEMORY.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface


IDirectMusicTool8::Flush

The Flush method flushes messages from the queue when the performance stops. The tool can use the method to do whatever is necessary to flush the message. For instance, the output tool uses this method to ensure that any pending note-off messages are processed immediately.

Syntax

HRESULT Flush(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG,
  REFERENCE_TIME rtTime
);

Parameters

pPerf

Address of the IDirectMusicPerformance8 interface.

pPMSG

Message to flush.

rtTime

Time at which to flush.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

Return code
DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

The message will have DMUS_PMSGF_TOOL_FLUSH set in its dwFlags member. See DMUS_PMSG.

If the method returns DMUS_S_REQUEUE, the message is placed back in the queue. The tool can put a new time stamp and parameters on the message, or change the delivery type.

If the return value is DMUS_S_FREE, the message is freed by the performance.

If the return value is S_OK, the message is not freed by the performance. The tool might be holding onto the message for some reason, or the tool might already have freed the message.

Be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface


IDirectMusicTool8::GetMediaTypeArraySize

The GetMediaTypeArraySize method retrieves the size of the array that must be passed in to the IDirectMusicTool8::GetMediaTypes method. A return value of 0 indicates that the tool handles all types, and it is unnecessary to call GetMediaTypes.

Syntax

HRESULT GetMediaTypeArraySize(
  DWORD* pdwNumElements
);

Parameters

pdwNumElements

Address of a variable that receives the number of media types. If 0 is returned in this field, all types are supported.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface


IDirectMusicTool8::GetMediaTypes

The GetMediaTypes method retrieves a list of the types of messages that this tool supports.

Syntax

HRESULT GetMediaTypes(
  DWORD** padwMediaTypes,
  DWORD dwNumElements
);

Parameters

padwMediaTypes

Address of an array of DWORDs. The method fills this array with the media types supported by this tool. For media types, see DMUS_PMSGT_TYPES.

dwNumElements

Number of elements in the padwMediaTypes array. This value is equal to the number returned by the IDirectMusicTool8::GetMediaTypeArraySize method. If dwNumElements is less than this number, the method cannot return all the message types that are supported. If it is greater than this number, the extra elements in the array should be set to 0.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK, or S_FALSE if the method could not fill in all values because dwNumElements was too small. If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

If the method returns E_NOTIMPL, the tool processes all media types.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface


IDirectMusicTool8::GetMsgDeliveryType

The GetMsgDeliveryType method retrieves the tool's delivery type, which determines when messages are to be delivered to the tool.

Syntax

HRESULT GetMsgDeliveryType(
  DWORD* pdwDeliveryType
);

Parameters

pdwDeliveryType

Address of a variable that receives the delivery type. The returned value must be DMUS_PMSGF_TOOL_IMMEDIATE, DMUS_PMSGF_TOOL_QUEUE, or DMUS_PMSGF_TOOL_ATTIME. An unrecognized value in *pdwDeliveryType is treated as DMUS_PMSGF_TOOL_IMMEDIATE by the graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Remarks

For an overview of the delivery mechanism, see Message Creation and Delivery.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface


IDirectMusicTool8::Init

The Init method initializes the tool. This method is called when the tool is inserted into the graph, giving the tool an opportunity to perform any necessary initialization.

Syntax

HRESULT Init(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph

Calling graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_NOTIMPL

Remarks

Because a tool can be inserted into more than one graph, this method must be able to deal gracefully with multiple calls.

Be sure not to create a circular reference to the graph represented by pGraph. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicGraph8::InsertTool
  • IDirectMusicTool8 Interface


IDirectMusicTool8::ProcessPMsg

The ProcessPMsg method performs the main task of the tool. It is called from inside the performance's real-time thread for all messages that match the types specified by IDirectMusicTool8::GetMediaTypes.

Syntax

HRESULT ProcessPMsg(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG
);

Parameters

pPerf

Performance that is generating messages.

pPMSG

Message to process.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

Return code
DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

If the method returns DMUS_S_REQUEUE, the message is placed back in the queue. The tool can put a new time stamp and parameters on the message, or change the delivery type.

If the return value is DMUS_S_FREE, the message is freed by the performance.

If the return value is S_OK, the message is not freed by the performance. The tool might be holding onto the message for some reason, or the tool might already have freed the message.

Tools should not perform time-consuming activities because doing so can severely affect overall performance. Also be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTool8 Interface
  • IDirectMusicPerformance8::SendPMsg
  • Message Creation and Delivery
  • Messages


IDirectMusicTrack8 Interface

The IDirectMusicTrack8 interface represents a track object, which can store any kind of data for a segment.

The methods of this interface are typically not called directly by applications. However, if you want to install your own data playback mechanism in DirectMusic, you must create a track object to represent it. The track object must also support the IPersistStream interface for loading its data.

IDirectMusicTrack8 supersedes the IDirectMusicTrack interface and adds new methods.

Note When implementing methods of the IDirectMusicTrack8 interface, be sure not to hold onto references to objects passed in. For example, if IDirectMusicTrack8::Init adds a reference to the IDirectMusicSegment interface that it receives as a parameter, ensure that this reference is released.

In addition to the methods inherited from IUnknown, the IDirectMusicTrack8 interface exposes the following methods, arranged by category.

Notification

Method | Description
AddNotificationType | Adds a type of event for which notifications are required.
RemoveNotificationType | Removes a type of event for which notifications are required.

Parameters

Method | Description
GetParam | Retrieves data from a track, in music time.
GetParamEx | Retrieves data from a track, in either music time or reference time.
IsParamSupported | Ascertains whether the track supports a given data type.
SetParam | Sets data on a track, in music time.
SetParamEx | Sets data on a track, in either clock or music time.

Playback

Method | Description
EndPlay | Called when the object that originally called IDirectMusicTrack8::InitPlay is destroyed.
InitPlay | Called when a track is ready to start playing.
Play | Called when the object that originally called IDirectMusicTrack8::InitPlay is destroyed.
PlayEx | Causes the track to play in clock time.

Miscellaneous

Method | Description
Clone | Makes a copy of the track.
Compose | Recomposes the track based on data from a segment.
Init | Initializes the track.
Join | Appends one track to another.

Requirements

Header: Declared in dmplugin.h.

See Also

  • DirectMusic Interfaces
  • DirectMusic Tracks
  • Setting and Retrieving Track Parameters


IDirectMusicTrack8::AddNotificationType

The AddNotificationType method adds a type of event for which notifications are required. It is similar to, and called by, the IDirectMusicSegment8::AddNotificationType method.

Syntax

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_NOTIMPL

Remarks

If the track does not support notifications, the method returns E_NOTIMPL. A motif or style track returns DMUS_E_NOT_INIT if it has not been initialized.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::RemoveNotificationType
  • Notification and Event Handling


IDirectMusicTrack8::Clone

The Clone method makes a copy of the track.

Syntax

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicTrack** ppTrack
 );

Parameters

mtStart

Start of the part to copy. It should be 0 or greater and less than the length of the track.

mtEnd

End of the part to copy. It should be greater than mtStart and less than the length of the track.

ppTrack

Address of a variable that receives a pointer to the created track, if successful.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

It is the caller's responsibility to call Release when finished with the track.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface


IDirectMusicTrack8::Compose

The Compose method recomposes the track based on data from a segment. DirectMusic implements this method on the signpost track to compose a chord track.

Syntax

HRESULT Compose(
  IUnknown* pContext,
  DWORD dwTrackGroup,
  IDirectMusicTrack** ppResultTrack
 );

Parameters

pContext

IUnknown interface pointer of the object to use in the composition. This is usually the segment that owns this track.

dwTrackGroup

DWORD value that specifies group bits for the track. For more information on group bits, see Identifying the Track.

ppResultTrack

Address of a variable that receives the IDirectMusicTrack interface of the composed track. Use QueryInterface to obtain IDirectMusicTrack8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_INVALIDARG
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicSegment8::Compose


IDirectMusicTrack8::EndPlay

The EndPlay method called when the object that originally called IDirectMusicTrack8::InitPlay is destroyed.

Syntax

HRESULT EndPlay(
  void * pStateData
);

Parameters

pStateData

Pointer to state data returned from IDirectMusicTrack8::InitPlay. This data should be freed in the EndPlay method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface


IDirectMusicTrack8::GetParam

The GetParam method retrieves data from a track, in music time.

Syntax

HRESULT GetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.

mtTime

Time, in track time, from which to obtain the data.

pmtNext

Address of a variable that receives the track time (relative to the current time) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL.

pParam

Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
DMUS_E_TYPE_DISABLED
DMUS_E_GET_UNSUPPORTED
E_POINTER

Remarks

The IDirectMusicTrack8::GetParamEx method can be used for greater functionality.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicTrack8::IsParamSupported
  • IDirectMusicTrack8::SetParam
  • Performance Parameters


IDirectMusicTrack8::GetParamEx

The GetParamEx method retrieves data from a track, in either music time or reference time.

Syntax

HRESULT GetParamEx(
  REFGUID rguidType,
  REFERENCE_TIME rtTime,
  REFERENCE_TIME* prtNext,
  void * pParam
  void * pStateData,
  DWORD dwFlags
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.

rtTime

Time from which to obtain the data. Unless DMUS_TRACK_PARAMF_CLOCK is set in dwFlags, this value is in music time.

prtNext

Address of a variable that receives the time until which the data is valid. If this returns a value of 0, either the data is always valid, or it is unknown when it might become invalid. If this information is not needed, prtNext can be set to NULL.

pParam

Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

pStateData

Address of a buffer containing state data for the track instance. This value is obtained from IDirectMusicTrack8::InitPlay.

dwFlags

Can be 0 or the following flag.

Value | Description
DMUS_TRACK_PARAMF_CLOCK | The value in rtTime is in clock time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
DMUS_E_TYPE_DISABLED
DMUS_E_GET_UNSUPPORTED
DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::SetParamEx


IDirectMusicTrack8::Init

The Init method initializes the track. This method is called by a segment when a track is added.

Syntax

HRESULT Init(
  IDirectMusicSegment* pSegment
);

Parameters

pSegment

Segment to which this track belongs.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

If the track plays messages, it should call IDirectMusicSegment8::SetPChannelsUsed in the Init method.

This method should be called whenever track data is changed after the track is inserted in a segment.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface


IDirectMusicTrack8::InitPlay

The IDirectMusicTrack8::InitPlay method is called when a track is ready to start playing. The method returns a pointer to state data.

Syntax

HRESULT InitPlay(
  IDirectMusicSegmentState* pSegmentState,
  IDirectMusicPerformance* pPerformance,
  void** ppStateData,
  DWORD dwVirtualTrackID,
  DWORD dwFlags
);

Parameters

pSegmentState

Address of the calling IDirectMusicSegmentState or IDirectMusicSegmentState8 interface.

pPerformance

Address of the calling IDirectMusicPerformance or IDirectMusicPerformance8 interface.

ppStateData

Address of a variable that receives a pointer to state information. The format and use of the data is specific to the track. The data should be created in the InitPlay method and freed in the IDirectMusicTrack8::EndPlay method. The pointer is passed to the IDirectMusicTrack8::Play and IDirectMusicTrack8::PlayEx methods.

dwVirtualTrackID

Virtual track ID assigned to this track instance.

dwFlags

DMUS_SEGF_FLAGS that control the track's behavior. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

The dwFlags parameter passes the flags that were handed to the performance in the call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx. The track determines how it should perform, based on the DMUS_SEGF_CONTROL and DMUS_SEGF_SECONDARY flags. For example, the tempo track automatically plays the tempo changes only if it is part of a primary segment or a secondary control segment (DMUS_SEGF_SECONDARY is not set, or DMUS_SEGF_CONTROL is set).

A track can return NULL in *ppStateData.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface


IDirectMusicTrack8::IsParamSupported

The IsParamSupported method ascertains whether the track supports a given data type.

Syntax

HRESULT IsParamSupported(
  REFGUID rguidType
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data. See Standard Track Parameters.

Return Values

If the method succeeds and the type is supported, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_TYPE_DISABLED
DMUS_E_TYPE_UNSUPPORTED
E_POINTER
E_NOTIMPL

Remarks

If a parameter has been disabled by using one of the SetParam methods, the IDirectMusicTrack8::IsParamSupported method returns DMUS_E_TYPE_DISABLED when passed the corresponding parameter type (either GUID_TempoParam or GUID_TimeSignature).

The method also returns DMUS_E_TYPE_DISABLED if passed GUID_DisableTempo when that parameter has already been disabled, or if passed GUID_EnableTempo when that parameter is currently enabled. The same is true for GUID_DisableTimeSig and GUID_EnableTimeSig.

The method returns DMUS_E_TYPE_UNSUPPORTED when the track does not support the parameter referred to by a GUID_EnableTempo, GUID_EnableTimeSig, GUID_DisableTempo, or GUID_DisableTimeSig parameter call.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParam
  • Performance Parameters


IDirectMusicTrack8::Join

The Join method appends one track to another.

Syntax

HRESULT Join(
  IDirectMusicTrack* pNewTrack,
  MUSIC_TIME mtJoin,
  IUnknown* pContext,
  DWORD dwTrackGroup,
  IDirectMusicTrack** ppResultTrack)
);

Parameters

pNewTrack

Pointer to an IDirectMusicTrack8 interface that specifies the track to append to this one.

mtJoin

Time within this track where pNewTrack is to begin.

pContext

IUnknown interface pointer of the context segment. This object determines the time signature for tracks that use measures and beats, such as the signpost track.

dwTrackGroup

Group or groups to which the new track belongs. For more information on track groups, see IDirectMusicSegment8::InsertTrack and Identifying the Track.

ppResultTrack

Address of a variable that receives the IDirectMusicTrack interface of the concatenated track. Use QueryInterface to obtain IDirectMusicTrack8. If NULL, no new track is created and the current track becomes the concatenated track.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_POINTER
E_INVALIDARG
E_OUTOFMEMORY

Remarks

This method is supported by the band, chordmap, tempo, style, chord, signpost, and command tracks.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface


IDirectMusicTrack8::Play

The Play method causes the track to play. It performs any work that the track must do when the segment is played, such as creating and sending messages.

Syntax

HRESULT Play(
  void* pStateData,
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  MUSIC_TIME mtOffset
  DWORD dwFlags,
  IDirectMusicPerformance* pPerf,
  IDirectMusicSegmentState* pSegSt,
  DWORD dwVirtualID
);

Parameters

pStateData

Pointer to state data from the IDirectMusicTrack8::InitPlay method. The format and use of the data is specific to the track.

mtStart

Start time.

mtEnd

End time.

mtOffset

Offset to add to all messages sent to IDirectMusicPerformance8::SendPMsg.

dwFlags

Flags that indicate the state of this call. See DMUS_TRACKF_FLAGS. A value of 0 indicates that this call to Play continues playback from the previous call.

pPerf

Performance used to allocate and send messages.

pSegSt

Segment state that this track belongs to. The IDirectMusicSegmentState8::QueryInterface method can be called to obtain an IDirectMusicGraph8 interface—to call IDirectMusicGraph8::StampPMsg, for instance.

dwVirtualID

Virtual identifier of the track. This value must be put in the dwVirtualTrackID member of any message (see DMUS_PMSG) that is sent by IDirectMusicPerformance8::SendPMsg.

Return Values

If the method succeeds, the return value can be S_OK or DMUS_S_END.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_POINTER

Remarks

If the track is empty, the method returns DMUS_S_END.

Tracks generate messages in a medium-priority thread. You can call time-consuming functions, such as code to stream data from a file, from within a track's Play method. However, be sure to follow the guidelines for safe multithreading.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::PlayEx


IDirectMusicTrack8::PlayEx

The PlayEx method causes the track to play in clock time. It performs any work that the track must do when the segment is played, such as creating and sending messages.

Syntax

HRESULT PlayEx(
  void* pStateData,
  REFERENCE_TIME rtStart,
  REFERENCE_TIME rtEnd,
  REFERENCE_TIME rtOffset,
  DWORD dwFlags,
  IDirectMusicPerformance* pPerf,
  IDirectMusicSegmentState* pSegSt,
  DWORD dwVirtualID
);

Parameters

pStateData

Pointer to state data from the IDirectMusicTrack8::InitPlay method. The format and use of the data is specific to the track.

rtStart

Start time.

rtEnd

End time.

rtOffset

Offset to add to all messages sent to IDirectMusicPerformance8::SendPMsg.

dwFlags

Flags that indicate the state of this call. See DMUS_TRACKF_FLAGS. A value of 0 indicates that this call to PlayEx continues playback from the previous call.

pPerf

Performance used to allocate and send messages.

pSegSt

Segment state that this track belongs to. The IDirectMusicSegmentState8::QueryInterface method can be called to obtain an IDirectMusicGraph8 interface—for instance, to call IDirectMusicGraph8::StampPMsg.

dwVirtualID

Virtual identifier of the track. This value must be put in the dwVirtualTrackID member of any message (see DMUS_PMSG) that is sent by IDirectMusicPerformance8::SendPMsg.

Return Values

If the method succeeds, the return value can be S_OK or DMUS_S_END.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_NOT_INIT
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::Play


IDirectMusicTrack8::RemoveNotificationType

The RemoveNotificationType method removes a type of event for which notifications are required.. It is similar to, and called by, the IDirectMusicSegment8::RemoveNotificationType method.

Syntax

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType

Reference to (C++) or address of (C) the identifier of the notification type to remove. For the defined types, see DMUS_NOTIFICATION_PMSG.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If the track does not support notifications, the method returns E_NOTIMPL.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::AddNotificationType
  • Notification and Event Handling


IDirectMusicTrack8::SetParam

The SetParam method sets data on a track, in music time.

Syntax

HRESULT SetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.

mtTime

Time, in track time, at which to set the data.

pParam

Address of a structure containing the data, or NULL if no data is required for this parameter. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_SET_UNSUPPORTED
DMUS_E_TYPE_DISABLED
E_OUTOFMEMORY
E_POINTER

Remarks

The IDirectMusicTrack8::SetParamEx method can be used for greater functionality.

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::IsParamSupported
  • IDirectMusicTrack8::SetParamEx
  • Setting and Retrieving Track Parameters


IDirectMusicTrack8::SetParamEx

The SetParamEx method sets data on a track, in either clock or music time.

Syntax

HRESULT SetParamEx(
  REFGUID rguidType,
  REFERENCE_TIME rtTime,
  void* pParam,
  void * pStateData,
  DWORD dwFlags
 );

Parameters

rguidType

Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.

rtTime

Time at which to set the data. Unless DMUS_TRACK_PARAMF_CLOCK is set in dwFlags, this is in music time.

pParam

Address of a structure that contains the data, or NULL if no data is required for this parameter. The structure must be of the appropriate kind and size for the data type identified by rguidType.

pStateData

Pointer to a buffer that contains state data for the track.

dwFlags

Can be 0 or the following flag.

Value | Description
DMUS_TRACK_PARAMF_CLOCK | The value in rtTime is in clock time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
DMUS_E_SET_UNSUPPORTED
DMUS_E_TYPE_DISABLED
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

  • IDirectMusicTrack8 Interface
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParam


IKsControl Interface

The IKsControl interface is used to get, set, or query the support of properties, events, and methods. This interface is part of the Windows Driver Model kernel streaming architecture, but is also used by DirectMusic to expose properties of DirectMusic ports. To retrieve this interface, call the IDirectMusicPort8::QueryInterface method with IID_IKsControl in the riid parameter.

Routing of the property item request to the port varies, depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation on top of the Win32 handle-based multimedia calls (midiOut and midiIn functions).

Property item requests to a port that represents a pluggable software synthesizer are answered totally in user mode. The topology of this type of port is a synthesizer (represented by an IDirectMusicSynth interface) connected to a sink node (an IDirectMusicSynthSink interface). The property request is given first to the synthesizer node, and then to the sink node if it is not recognized by the synthesizer.

In addition to the methods inherited from IUnknown, the IKsControl interface exposes the following methods.

Method | Description
KsProperty | Retrieves or sets the value of a property.
KsEvent | Not supported by DirectMusic.
KsMethod | Not supported by DirectMusic.

Requirements

Header: Declared in dmksctrl.h.

See Also

  • DirectMusic Interfaces
  • Property Sets for DirectMusic Ports


IKsControl::KsProperty

The KsProperty method retrieves or sets the value of a property. For an overview, see Property Sets for DirectMusic Ports.

Syntax

HRESULT KsProperty(
  PKSPROPERTY pProperty,
  ULONG ulPropertyLength,
  LPVOID pvPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

pProperty

Address of a KSPROPERTY structure that gives the property set, item, and operation to perform. If this property contains instance data, that data should reside in memory immediately following the structure.

ulPropertyLength

Length of the memory pointed to by pProperty, including any instance data.

pvPropertyData

For a set operation, the address of a memory buffer containing data that represents the new value of the property. For a get operation, the address of a memory buffer big enough to hold the value of the property. For a basic support query, the address of a buffer at least a DWORD in size.

ulDataLength

Length of the buffer pointed to by pvPropertyData.

pulBytesReturned

On a KSPROPERTY_TYPE_GET or KSPROPERTY_TYPE_BASICSUPPORT call, address of a variable that receives the number of bytes returned in pvPropertyData by the port.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the error values shown in the following table.

Return code
E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY
E_POINTER
DMUS_E_UNKNOWN_PROPERTY

Requirements

Header: Declared in dmksctrl.h.

See Also

  • IKsControl Interface
  • Property Sets for DirectMusic Ports


IReferenceClock Interface

The IReferenceClock interface provides the reference time for the filter graph.

Filters that can act as a reference clock can expose this interface. It is also exposed by the System Reference Clock. The filter graph manager uses this interface to synchronize the filter graph. Applications can use this interface to retrieve the current reference time, or to request notification of an elapsed time.

For more information, see Time and Clocks in DirectShow.

Filter developers: Implement this interface if you are writing a filter that generates reliable clock times. For example, audio renderers implement this interface, because audio sound boards usually contain a reference clock. Use the CBaseReferenceClock class to implement this interface.

To increase the chances that a non-rendering filter will be selected by the Filter Graph Manager as the reference close, follow these steps:

  1. Implement IReferenceClock in the filter.
  2. Implement IAMFilterMiscFlags in the filter.
  3. Return AM_FILTER_MISC_FLAGS_IS_SOURCE from IAMFilterMiscFlags::GetMiscFlags.
  4. Implement IAMPushSource on all output pins.
  5. Return (* pFlags) = 0 from IAMPushSource::GetPushSourceFlags.
  6. You may return E_NOTIMPL from all other IAMPushSource methods.

In addition to the methods inherited from IUnknown, the IReferenceClock interface exposes the following methods.

Method | Description
GetTime | Retrieves the current reference time.
AdviseTime | Creates a one-shot advise request.
AdvisePeriodic | Creates a periodic advise request.
Unadvise | Removes a pending advise request.


IReferenceClock::AdvisePeriodic

The AdvisePeriodic method creates a periodic advise request.

Syntax

HRESULT AdvisePeriodic(
  REFERENCE_TIME rtStartTime,
  REFERENCE_TIME rtPeriodTime,
  HSEMAPHORE hSemaphore,
  DWORD_PTR *pdwAdviseCookie
);

Parameters

rtStartTime

[in] Time of the first notification, in 100-nanosecond units. Must be greater than zero and less than MAX_TIME.

rtPeriodTime

[in] Time between notifications, in 100-nanosecond units. Must be greater than zero.

hSemaphore

[in] Handle to a semaphore, created by the caller.

pdwAdviseCookie

[out] Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid time values.
E_OUTOFMEMORY | Failure.
E_POINTER | NULL pointer argument.

Remarks

At each notification time, the clock releases the semaphore specified in the hSemaphore parameter. When no further notifications are required, call IReferenceClock::Unadvise and pass the pdwAdviseToken value returned from this call.

The following code example creates an advise request that signals five seconds from the time it is created, and again every second thereafter:

IReferenceClock *pRefClock = NULL;
// Get an IReferenceClock pointer (not shown).

DWORD          dwAdviseToken;
HANDLE         hSemaphore = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
REFERENCE_TIME rtPeriodTime = 10000000; // A one-second interval
REFERENCE_TIME rtNow;

pRefClock->GetTime(&rtNow);
pRefClock->AdvisePeriodic(rtNow + (5 * rtPeriodTime),
                          rtPeriodTime,
                          hSemaphore,
                          &dwAdviseToken);
...

pRefClock->Unadvise(dwAdviseToken);

See Also

  • Error and Success Codes
  • IReferenceClock Interface


IReferenceClock::AdviseTime

The AdviseTime method creates a one-shot advise request.

Syntax

HRESULT AdviseTime(
  REFERENCE_TIME rtBaseTime,
  REFERENCE_TIME rtStreamTime,
  HEVENT hEvent,
  DWORD_PTR *pdwAdviseCookie
);

Parameters

rtBaseTime

[in] Base reference time, in 100-nanosecond units. See Remarks.

rtStreamTime

[in] Stream offset time, in 100-nanosecond units. See Remarks.

hEvent

[in] Handle to an event, created by the caller.

pdwAdviseCookie

[out] Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid time values.
E_OUTOFMEMORY | Failure.
E_POINTER | NULL pointer argument.

Remarks

This method creates a one-shot advise request for the reference time baseTime + streamTime. The sum must be greater than zero and less than MAX_TIME, or the method returns E_INVALIDARG. At the requested time, the clock signals the event specified in the hEvent parameter.

To cancel the notification before the time is reached, call the Unadvise method and pass the pdwAdviseToken value returned from this call. After the notification has occurred, the clock automatically clears it, so it is not necessary to call Unadvise. However, it is not an error to do so.

See Also

  • Error and Success Codes
  • IReferenceClock Interface


IReferenceClock::GetTime

The GetTime method retrieves the current reference time.

Syntax

HRESULT GetTime(
  REFERENCE_TIME *pTime
);

Parameters

pTime

[out] Pointer to a variable that receives the current time, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_POINTER | NULL pointer argument.
S_FALSE | Returned time is the same as the previous value.
S_OK | Success.

See Also

  • Error and Success Codes
  • IReferenceClock Interface


IReferenceClock::Unadvise

The Unadvise method removes a pending advise request.

Syntax

HRESULT Unadvise(
  DWORD_PTR dwAdviseCookie
);

Parameters

dwAdviseCookie

[in] Identifier of the request to remove. Use the value returned by IReferenceClock::AdviseTime or IReferenceClock::AdvisePeriodic in the pdwAdviseToken parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Not found.
S_OK | Success.

See Also

  • Error and Success Codes
  • IReferenceClock Interface


DirectMusic Messages

DirectMusic message structures are all based on the DMUS_PMSG structure. Because C does not support inheritance, the members of this structure are included in each derived structure as the DMUS_PMSG_PART macro.

For an overview of messages, see Using DirectMusic Messages.

This section contains information about the following structures used to contain message information.

Structure | Description
DMUS_CHANNEL_PRIORITY_PMSG | Contains message data about a channel priority change.
DMUS_CURVE_PMSG | Contains message data for a curve.
DMUS_LYRIC_PMSG | Contains message data for a string.
DMUS_MIDI_PMSG | Contains data for a standard MIDI message such as a control change or pitch bend.
DMUS_NOTE_PMSG | Contains message data for a MIDI note.
DMUS_NOTIFICATION_PMSG | Contains message data for a notification.
DMUS_PATCH_PMSG | Contains message data for a MIDI program change.
DMUS_PMSG | Contains information common to all DirectMusic messages.
DMUS_SYSEX_PMSG | Contains data for a MIDI system exclusive message.
DMUS_TEMPO_PMSG | Contains data for a message that controls the performance's tempo.
DMUS_TIMESIG_PMSG | Contains data for a message that controls the time signature of the performance.
DMUS_TRANSPOSE_PMSG | Contains message data for a transposition.
DMUS_WAVE_PMSG | Contains message data for a wave sound.

See Also

  • IDirectMusicPerformance8::AllocPMsg
  • IDirectMusicPerformance8::FreePMsg
  • IDirectMusicPerformance8::SendPMsg
  • IDirectMusicTool8::ProcessPMsg


DMUS_CHANNEL_PRIORITY_PMSG

The DMUS_CHANNEL_PRIORITY_PMSG structure contains message data about a channel priority change.

Syntax

typedef struct _DMUS_CHANNEL_PRIORITY_PMSG {
  DMUS_PMSG_PART
  DWORD dwChannelPriority;
} DMUS_CHANNEL_PRIORITY_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

dwChannelPriority

Priority of the channel. For a list of defined values, see the Remarks for IDirectMusicPort8::GetChannelPriority.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg
  • IDirectMusicPort8::SetChannelPriority


DMUS_CURVE_PMSG

The DMUS_CURVE_PMSG structure contains message data for a curve.

Syntax

typedef struct DMUS_CURVE_PMSG {
  DMUS_PMSG_PART
  MUSIC_TIME mtDuration;
  MUSIC_TIME mtOriginalStart;
  MUSIC_TIME mtResetDuration;
  short  nStartValue;
  short  nEndValue;
  short  nResetValue;
  WORD   wMeasure;
  short  nOffset;
  BYTE   bBeat;
  BYTE   bGrid;
  BYTE   bType;
  BYTE   bCurveShape;
  BYTE   bCCData;
  BYTE   bFlags;
  WORD   wParamType;
  WORD   wMergeIndex;
} DMUS_CURVE_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

mtDuration

Duration of the curve. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, in which case the duration is in milliseconds and is unaffected by a change in tempo.

mtOriginalStart

Original start time. Must be set to either zero when this message is created, or to the original start time of the curve.

mtResetDuration

Length of time after the end of the curve during which a reset can take place in response to an invalidation. Ignored if DMUS_CURVE_RESET is not in bFlags. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, in which case it is in milliseconds and is unaffected by a change in tempo.

nStartValue

Start value of the curve.

nEndValue

End value of the curve.

nResetValue

Value to set upon a flush or invalidation. Ignored if DMUS_CURVE_RESET is not in bFlags.

wMeasure

Measure in which this curve occurs.

nOffset

Offset from the grid at which this curve occurs, in music time.

bBeat

Beat count (within a measure) at which this curve occurs.

bGrid

Grid offset from the beat at which this curve occurs.

bType

Type of curve. This can be one of the following values.

Value | Description
DMUS_CURVET_CCCURVE | Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn.).
DMUS_CURVET_MATCURVE | Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE | Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE | Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
DMUS_CURVET_RPNCURVE | RPN curve of type defined in wParamType.
DMUS_CURVET_NRPNCURVE | NRPN curve of type defined in wParamType.

bCurveShape

Shape of curve. This can be one of the following values.

Value | Description
DMUS_CURVES_EXP | Exponential curve shape.
DMUS_CURVES_INSTANT | Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR | Linear curve shape.
DMUS_CURVES_LOG | Logarithmic curve shape.
DMUS_CURVES_SINE | Sine curve shape.

bCCData

Controller number if bType is DMUS_CURVET_CCCURVE; otherwise ignored.

bFlags

Can be zero, or one or more of the following values.

Value | Description
DMUS_CURVE_RESET | The value of nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If this flag is not set, the curve stays permanently at the new value.
DMUS_CURVE_START_FROM_CURRENT | Ignore nStartValue and start the curve at the current value. Implemented for volume, expression, pitch bend, filter cutoff, pan, and mod wheel. See Remarks.

wParamType

MIDI parameter number. This value is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure. See Remarks.

wMergeIndex

Merge index. Supported for transpose, pitch bend, volume, expression, pan, filter, mod wheel, chorus, and reverb controllers. This value is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure. See Remarks.

Remarks

An RPN or NRPN curve type in wParamType is stored as two bytes with seven significant bits. For example, if the MSB is 0x23 and the LSB is 0x74, the value in wParamType is 0x2374.

Data in nStartValue, nEndValue, and nResetValue is limited to 14 bits. For MIDI data consisting of two seven-bit bytes, the value is stored as a word with the upper two bits empty.

All curves with wMergeIndex of 0 override each other. If wMergeIndex is another value, the values generated by the curve are added to the values for merge index 0. For example, if an application uses curves with 0 and 3, the 0 curves always replace each other but add to the 3 curves, and the 3 curves also always replace each other and add to the 0 curves.

The DMUS_CURVE_START_FROM_CURRENT flag does not cause the current controller value to be saved in the message. Therefore tools do not have access to this data unless they store the last known value.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg
  • Curves


DMUS_LYRIC_PMSG

The DMUS_LYRIC_PMSG structure contains message data for a string.

Syntax

typedef struct _DMUS_LYRIC_PMSG {
  DMUS_PMSG_PART
  WCHAR  wszString[1];
} DMUS_LYRIC_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

wszString

Null-terminated Unicode string. The array is sized when the message is created.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg


DMUS_MIDI_PMSG

The DMUS_MIDI_PMSG structure contains data for a standard MIDI message such as a control change or pitch bend.

Syntax

typedef struct DMUS_MIDI_PMSGG {
  DMUS_PMSG_PART
  BYTE  bStatus;
  BYTE  bByte1;
  BYTE  bByte2;
  BYTE  bPad[1];
} DMUS_MIDI_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

bStatus

Standard MIDI status byte.

bByte1

First byte of the MIDI message. Ignored for MIDI messages that do not require it.

bByte2

Second byte of the MIDI message. Ignored for MIDI messages that do not require it.

bPad

Padding to a WORD boundary.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg
  • MIDI Messages


DMUS_NOTE_PMSG

The DMUS_NOTE_PMSG structure contains message data for a MIDI note.

Syntax

typedef struct DMUS_NOTE_PMSG {
  DMUS_PMSG_PART
  MUSIC_TIME mtDuration;
  WORD   wMusicValue;
  WORD   wMeasure;
  short  nOffset;
  BYTE   bBeat;
  BYTE   bGrid;
  BYTE   bVelocity;
  BYTE   bFlags;
  BYTE   bTimeRange;
  BYTE   bDurRange;
  BYTE   bVelRange;
  BYTE   bPlayModeFlags;
  BYTE   bSubChordLevel;
  BYTE   bMidiValue;
  char   cTranspose;
} DMUS_NOTE_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

mtDuration

Duration of the note.

wMusicValue

Description of the note. In most play modes, this is a packed array of 4-bit values, as follows.

Value | Description
Octave | In the range from –2 through 14. The note is transposed up or down by the octave times 12.
Chord position | In the range from 0 through 15, although it should never be above 3. The first position in the chord is 0.
Scale position | In the range from 0 through 15. Typically it is only from 0 through 2, but it is possible to have a one-note chord and have everything above the chord be interpreted as a scale position.
Accidental | In the range from –8 through 7, but typically in the range from –2 through 2. This represents an offset that takes the note out of the scale.

In the fixed-play modes, the music value is a MIDI note value in the range from 0 through 127.

wMeasure

Measure in which this note occurs.

nOffset

Offset from the grid at which this note occurs, in music time.

bBeat

Beat (in measure) at which this note occurs.

bGrid

Grid offset from the beat at which this note occurs.

bVelocity

Note velocity.

bFlags

See DMUS_NOTEF_FLAGS.

bTimeRange

Range by which to randomize the time at which the note plays.

bDurRange

Range by which to randomize the duration of the note.

bVelRange

Range by which to randomize the velocity of the note.

bPlayModeFlags

Play mode determining how the music value is related to the chord and subchord. For a list of values, see DMUS_PLAYMODE_FLAGS.

bSubChordLevel

Subchord level that the note uses. See DMUS_SUBCHORD.

bMidiValue

MIDI note value, converted from wMusicValue.

cTranspose

Transposition to add to bMidiValue after conversion from wMusicValue.

Remarks

When the output tool receives a message with DMUS_NOTEF_NOTEON in bFlags, it sends a MIDI note-on message to the synthesizer. It then clears the DMUS_NOTEF_NOTEON flag, adds mtDuration to the time stamp, and requeues the message so that the note is turned off at the appropriate time.

The values in bTimeRange and bDurRange have a logarithmic relationship to actual time. A value of 255 specifies that the time can be randomized by up to 825 music time ticks in either direction.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg
  • Music Values and MIDI Notes


DMUS_NOTIFICATION_PMSG

The DMUS_NOTIFICATION_PMSG structure contains message data for a notification.

Syntax

typedef struct DMUS_NOTIFICATION_PMSG {
  DMUS_PMSG_PART
  GUID guidNotificationType;
  DWORD  dwNotificationOption;
  DWORD  dwField1;
  DWORD  dwField2;
} DMUS_NOTIFICATION_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

guidNotificationType

Identifier of the notification type. The following types are defined.

Value | Description
GUID_NOTIFICATION_CHORD | Chord change.
GUID_NOTIFICATION_COMMAND | Command event.
GUID_NOTIFICATION_MEASUREANDBEAT | Measure and beat event.
GUID_NOTIFICATION_PERFORMANCE | Performance event, further defined in dwNotificationOption.
GUID_NOTIFICATION_RECOMPOSE | A track has been recomposed.
GUID_NOTIFICATION_SEGMENT | Segment event, further defined in dwNotificationOption.

dwNotificationOption

Identifier of the notification subtype. If the notification type is GUID_NOTIFICATION_SEGMENT, this member can contain one of the following values.

Value | Description
DMUS_NOTIFICATION_SEGABORT | The segment was stopped prematurely, or was removed from the primary segment queue.
DMUS_NOTIFICATION_SEGALMOSTEND | The segment has reached the end minus the Prepare Time.
DMUS_NOTIFICATION_SEGEND | The segment has ended.
DMUS_NOTIFICATION_SEGLOOP | The segment has looped.
DMUS_NOTIFICATION_SEGSTART | The segment has started.

If the notification type is GUID_NOTIFICATION_COMMAND, this member can contain one of the following values.

Value | Description
DMUS_NOTIFICATION_GROOVE | Groove level change.
DMUS_NOTIFICATION_EMBELLISHMENT | Embellishment command (intro, fill, break, or end).

If the notification type is GUID_NOTIFICATION_PERFORMANCE, this member can contain one of the following values.

Value | Description
DMUS_NOTIFICATION_MUSICALMOSTEND | The currently playing primary segment has reached the end minus the prepare time, and no more primary segments are cued to play.
DMUS_NOTIFICATION_MUSICSTARTED | Playback has started.
DMUS_NOTIFICATION_MUSICSTOPPED | Playback has stopped.

If the notification type is GUID_NOTIFICATION_MEASUREANDBEAT, this member contains DMUS_NOTIFICATION_MEASUREBEAT. No other subtypes are defined.

If the notification type is GUID_NOTIFICATION_CHORD, this member contains DMUS_NOTIFICATION_CHORD. No other subtypes are defined.

If the notification type is GUID_NOTIFICATION_RECOMPOSE, this member contains DMUS_NOTIFICATION_RECOMPOSE. No other subtypes are defined.

dwField1

Extra data specific to the type of notification. For GUID_NOTIFICATION_MEASUREANDBEAT notifications, this member returns the beat number within the measure.

dwField2

Extra data specific to the type of notification. Reserved for future or application-defined use.

Remarks

For most notifications, the punkUser member (see DMUS_PMSG) contains the IUnknown pointer of the segment state. This is especially useful in the cases of chords and commands, in which you can query for the IDirectMusicSegmentState8 interface, call IDirectMusicSegmentState8::GetSegment to get the IDirectMusicSegment8 pointer, and then call the IDirectMusicSegment8::GetParam method to get the chord or command at the time given in the notification message's mtTime member.

For notifications of type GUID_NOTIFICATION_PERFORMANCE, the punkUser member is always NULL.

Applications can define their own notification message types and subtypes and use dwField1 and dwField2 for extra data. Such custom notification messages can be allocated and sent like any other message. Application-defined tracks can send messages of a particular type after the GUID (guidNotificationType) has been handed to IDirectMusicTrack8::AddNotificationType.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg
  • Notification and Event Handling


DMUS_PATCH_PMSG

The DMUS_PATCH_PMSG structure contains message data for a MIDI program change.

Syntax

typedef struct DMUS_PATCH_PMSG {
  DMUS_PMSG_PART
  BYTE  byInstrument;
  BYTE  byMSB;
  BYTE  byLSB;
  BYTE  byPad[1];
} DMUS_PATCH_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

byInstrument

Patch number of the instrument.

byMSB

Most significant byte of bank select.

byLSB

Least significant byte of bank select.

byPad

Padding to a WORD boundary. This value is ignored.

Requirements

Header: Declared in dmusici.h.

See Also

  • DMUS_MIDI_PMSG
  • IDirectMusicPerformance8::SendPMsg
  • MIDI Messages


DMUS_PMSG

The DMUS_PMSG structure contains information common to all DirectMusic messages. Because C does not support inheritance, the members of this structure are contained in all message types (including DMUS_PMSG itself) as the DMUS_PMSG_PART macro, which expands to the syntax shown here.

Syntax

typedef struct DMUS_PMSG {
  DWORD      dwSize;
  REFERENCE_TIME   rtTime;
  MUSIC_TIME mtTime;
  DWORD      dwFlags;
  DWORD      dwPChannel;
  DWORD      dwVirtualTrackID;
  IDirectMusicTool*  pTool;
  IDirectMusicGraph* pGraph;
  DWORD      dwType;
  DWORD      dwVoiceID;
  DWORD      dwGroupID;
  IUnknown*  punkUser;
} DMUS_PMSG;

Members

dwSize

Size of the structure, in bytes. This member is initialized by IDirectMusicPerformance8::AllocPMsg.

rtTime

Reference time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_REFTIME is present in dwFlags.

mtTime

Music time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_MUSICTIME is present in dwFlags.

dwFlags

Flags from the DMUS_PMSGF_FLAGS or DMUS_TIME_RESOLVE_FLAGS enumeration. It must contain DMUS_PMSGF_REFTIME or DMUS_PMSGF_MUSICTIME.

dwPChannel

Performance channel. The port, channel group, and MIDI channel can be derived from this value by using the IDirectMusicPerformance8::PChannelInfo method. Set this value to zero for messages that are not channel-specific, such as tempo messages. To send the message to more than channel, use one of the following values.

Value | Description
DMUS_PCHANNEL_BROADCAST_AUDIOPATH | Send a copy of the message to all channels of the audiopath.
DMUS_PCHANNEL_BROADCAST_GROUPS | Send a copy of the message to each channel group in the performance. Used for messages that need to be sent only once per channel group, such as system exclusive messages.
DMUS_PCHANNEL_BROADCAST_PERFORMANCE | Send a copy of the message to all channels of the performance.
DMUS_PCHANNEL_BROADCAST_SEGMENT | Send a copy of the message to all channels of the segment.

dwVirtualTrackID

Identifier of the track. Set to zero if the message is not being sent by a track.

pTool

Address of the tool interface. Can be set by using IDirectMusicGraph8::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.

pGraph

Address of the tool graph interface. Can be set by using IDirectMusicGraph8::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.

dwType

Message type (see DMUS_PMSGT_TYPES).

dwVoiceID

Reserved. Must be zero.

dwGroupID

Identifier of the track group or groups that the message belongs to if the message is being generated by a track. (Tracks are assigned to groups in the IDirectMusicSegment8::InsertTrack method.) For most purposes, this value can be 0xFFFFFFFF.

punkUser

Address of an IUnknown interface supplied by the application. This pointer is always released when the message is freed. If the application wants to retain the object, it should call AddRef before the message is freed. If the message does not need a COM pointer, this value should be NULL.

Remarks

The DMUS_PMSG structure is used by itself for messages containing the following values in the dwType member.

Value | Description
DMUS_PMSGT_STOP | Sending a message of this type stops the performance at the specified time.
DMUS_PMSGT_DIRTY | When a control segment starts or ends, all tools in the segment and performance graphs receive a message of this type, indicating that if they cache data from get-parameter calls, they must call the method again to refresh their data. Tools that want to receive this message type must indicate this through a call to IDirectMusicTool8::GetMediaTypes. Tools in the performance graph receive one copy of the message for each segment in the performance. Such tools can safely ignore the extra messages with the same time stamp.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg


DMUS_SYSEX_PMSG

The DMUS_SYSEX_PMSG structure contains data for a MIDI system-exclusive message.

Syntax

typedef struct DMUS_SYSEX_PMSG {
  DMUS_PMSG_PART
  DWORD dwLen;
  BYTE  abData[1];
} DMUS_SYSEX_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

dwLen

Length of the data, in bytes.

abData

Array of data. For an example of how to allocate memory and copy data to this member, see the Remarks for IDirectMusicPerformance8::SendPMsg.

Remarks

The data part of a system exclusive message must begin with the System Exclusive identifier (0xF0) and end with EOX (0xF7).

Requirements

Header: Declared in dmusici.h.

See Also

  • DMUS_MIDI_PMSG
  • DMUS_PATCH_PMSG
  • IDirectMusicPerformance8::SendPMsg
  • MIDI Messages


DMUS_TEMPO_PMSG

The DMUS_TEMPO_PMSG structure contains data for a message that controls the performance's tempo.

Syntax

typedef struct DMUS_TEMPO_PMSG {
  DMUS_PMSG_PART
  double dblTempo;
} DMUS_TEMPO_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

dblTempo

Tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg


DMUS_TIMESIG_PMSG

The DMUS_TIMESIG_PMSG structure contains data for a message that controls the time signature of the performance.

Syntax

typedef struct _DMUS_TIMESIG_PMSG {
  DMUS_PMSG_PART
  BYTE bBeatsPerMeasure;
  BYTE bBeat;
  WORD wGridsPerBeat;
} DMUS_TIMESIG_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

bBeatsPerMeasure

Beats per measure (top of the time signature).

bBeat

Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.

wGridsPerBeat

Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Remarks

Time signature messages are generated by the time signature track and the style track. In general, a segment contains one or the other, but not both. A segment representing a MIDI file has a time signature track, but most segments authored with an application such as DirectMusic Producer contain time signature information in the style track.

By default, only the primary segment sends time signature messages. For information on how to change this behavior, see Disabling and Enabling Track Parameters.

The time signature is used by the performance to resolve time to measure, beat, and grid boundaries in all methods in which the time can be adjusted by DMUS_SEGF_FLAGS or DMUS_TIME_RESOLVE_FLAGS. The time signature and style tracks also use the time signature to generate notifications on measure and beat boundaries. For more informaton, see the DMUS_NOTIFICATION_PMSG structure.

Requirements

Header: Declared in dmusici.h.

See Also

  • DMUS_TIMESIGNATURE
  • IDirectMusicPerformance8::SendPMsg


DMUS_TRANSPOSE_PMSG

The DMUS_TRANSPOSE_PMSG structure contains message data for a transposition.

Syntax

typedef struct _DMUS_TRANSPOSE_PMSG {
  DMUS_PMSG_PART
  short nTranspose;
  WORD wMergeIndex;
} DMUS_TRANSPOSE_PMSG;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG.

nTranspose

Number of semitones by which to transpose. This can be a negative value.

wMergeIndex

Merge index. When a transpose message follows a preceding message with the same wMergeIndex, the value in nTranspose becomes the new setting. When the second transpose message has a different wMergeIndex, the value in nTranspose is added to the previous setting. This member is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure.

Remarks

If the transposition of a note puts it outside the standard MIDI range from 0 through 127, it does not play.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicPerformance8::SendPMsg


DMUS_WAVE_PMSG

The DMUS_WAVE_PMSG structure contains message data for a wave sound.

Syntax

typedef struct _DMUS_WAVE_PMSG {
  DMUS_PMSG_PART
  REFERENCE_TIME rtStartOffset;
  REFERENCE_TIME rtDuration;
  long  lOffset;
  long  lVolume;
  long  lPitch;
  BYTE  bFlags;
} DMUS_WAVE_PMSG;
;

Members

DMUS_PMSG_PART

Macro for common message members. See DMUS_PMSG. The punkUser member contains the address of the IUnknown interface of the voice object associated with the wave.

rtStartOffset

How far into the wave to start, in reference time units only.

rtDuration

Duration of the wave. If DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, this value is in reference time units. Otherwise it is in music time.

lOffset

Offset from actual time to logical time, in either reference or music time.

lVolume

Initial volume, in hundredths of a decibel.

lPitch

Transposition of the pitch, in hundredths of a semitone.

bFlags

Can be zero or one of the following values.

Value | Description
DMUS_WAVEF_IGNORELOOPS | Wave is not invalidated when a segment loop point is reached.
DMUS_WAVEF_NOINVALIDATE | Wave is not invalidated.
DMUS_WAVEF_OFF | This message is stopping playback of the wave.
DMUS_WAVEF_STREAMING | Wave is streaming.

Remarks

Applications cannot send messages of this type by using IDirectMusicPerformance8::SendPMsg, because they have no way of obtaining a pointer to a wave object. However, tools can process wave messages.

Requirements

Header: Declared in dmusici.h.


DirectMusic Structures

This section contains reference information for the following run-time structures used in DirectMusic.

Structure | Description
DMUS_AUDIOPARAMS | Describes required resources for the default synthesizer and buffers of a performance.
DMUS_BAND_PARAM | Used to set and retrieve band parameters.
DMUS_BUFFERDESC | Describes a buffer for the IDirectMusic8::CreateMusicBuffer method.
DMUS_CHORD_KEY | Describes a chord in the IDirectMusicPerformance8::MIDIToMusic and IDirectMusicPerformance8::MusicToMIDI methods.
DMUS_CHORD_PARAM | Used to set and retrieve chord parameters. Equivalent to DMUS_CHORD_KEY.
DMUS_CLOCKINFO8 | Contains information about a clock enumerated by using the IDirectMusic8::EnumMasterClock method.
DMUS_COMMAND_PARAM | Used to set and retrieve command track parameters.
DMUS_COMMAND_PARAM_2 | Used to set and retrieve command track parameters with additional timing information.
DMUS_EVENTHEADER | Describes an event in a port buffer.
DMUS_MUTE_PARAM | Used to set and retrieve mute track parameters.
DMUS_NOTERANGE | Specifies a range of notes that an instrument must respond to.
DMUS_OBJECTDESC | Describe a loadable object.
DMUS_PLAY_MARKER_PARAM | Contains information about a play marker.
DMUS_PORTCAPS | Contains information about an enumerated port.
DMUS_PORTPARAMS8 | Specifies parameters for the opening of a DirectMusic port.
DMUS_RHYTHM_PARAM | Contains parameters for chord rhythm.
DMUS_SCRIPT_ERRORINFO | Contains information about a script error.
DMUS_SUBCHORD | Describes a subchord.
DMUS_SYNTHSTATS8 | Describes the status of a synthesizer.
DMUS_TEMPO_PARAM | Used to set and retrieve tempo track parameters.
DMUS_TIMESIGNATURE | Contains information about a time signature in a style, style track, or time signature track.
DMUS_VALID_START_PARAM | Used to retrieve valid start times from a marker track.
DMUS_VARIATIONS_PARAM | Contains information about variations associated with channels.
DMUS_VERSION | Contains version information for an object.
DMUS_WAVES_REVERB_PARAMS | Contains information about reverberation effects on a DirectX 7.0 synthesizer.
KSPROPERTY | Used by the IKsControl::KsProperty method to identify a property and operation.

Special categories of structures are contained in the following sections:

  • DirectMusic Messages
  • DirectMusic File Structures
  • DLS Structures


DMUS_AUDIOPARAMS

The DMUS_AUDIOPARAMS structure describes required resources for the default synthesizer and buffers of a performance. It is passed to the IDirectMusicPerformance8::InitAudio method to request desired features and to receive information about what requests were granted.

Syntax

typedef struct _DMUS_AUDIOPARAMS {
  DWORD  dwSize;
  BOOL fInitNow;
  DWORD  dwValidData;
  DWORD  dwFeatures;
  DWORD  dwVoices;
  DWORD  dwSampleRate;
  CLSID  clsidDefaultSynth;
} DMUS_AUDIOPARAMS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_AUDIOPARAMS) before the structure is used.

fInitNow

Boolean value that specifies whether the sink and synthesizer are created immediately. If so, results are returned in this structure.

dwValidData

Flags that specify which members of this structure are valid. If fInitNow is TRUE when the structure is passed, this member receives flags that specify what members received data. The following values are defined.

Flag | Description
DMUS_AUDIOPARAMS_FEATURES | The dwFeatures member contains or has received data.
DMUS_AUDIOPARAMS_VOICES | The dwVoices member contains or has received data.
DMUS_AUDIOPARAMS_SAMPLERATE | The dwSampleRate member contains or has received data.
DMUS_AUDIOPARAMS_DEFAULTSYNTH | The clsidDefaultSynth member contains or has received data. If this flag is not set, the Microsoft software synthesizer is the default synthesizer.

dwFeatures

Flags that specify required capabilities. The following values are defined.

Flag | Description
DMUS_AUDIOF_3D | 3-D buffers.
DMUS_AUDIOF_ALL | Combination of all other flags.
DMUS_AUDIOF_BUFFERS | Multiple buffers. Always set this flag when using audiopaths.
DMUS_AUDIOF_ENVIRON | Environmental modeling.
DMUS_AUDIOF_EAX | EAX effects.
DMUS_AUDIOF_DMOS | Additional DMOs.
DMUS_AUDIOF_STREAMING | Support for streaming waveforms.

dwVoices

Number of voices. The default value is 64.

dwSampleRate

Sample rate of the sink and synthesizer, in the range from 11,025 to 96,000 kHz. The default value is 22,050.

clsidDefaultSynth

Class identifier of the default synthesizer. This is the synthesizer used by standard audiopaths and audiopaths created from configurations that request the default synthesizer.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_BAND_PARAM

The DMUS_BAND_PARAM structure is used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a band track and rguidType is GUID_BandParam.

Syntax

typedef struct _DMUS_BAND_PARAM {
  MUSIC_TIME mtTimePhysical;
  IDirectMusicBand *pBand;
} DMUS_BAND_PARAM;

Members

mtTimePhysical

Actual time at which the band change will be made. See Remarks.

pBand

Address of the IDirectMusicBand8 interface of the band. When this structure is retrieved by a GetParam call, a reference to the band object is added. The application is responsible for releasing this reference.

Remarks

The value in mtTimePhysical is the actual time at which the band change will be made, whereas the value in the mtTime parameter of the set-parameter method is the point in the performance where the change belongs, for example, synchronized with a beat or measure. You can set mtTimePhysical to a time slightly before mtTime to ensure that notes are always played by the correct band, even when a band change is made at the start of a loop.

If the track is a clock-time track, mtTimePhysical is interpreted in the track's internal time format. This is the number of milliseconds after the beginning of playback. Because this can be confusing, it is recommended that GUID_BandParam not be used with clock-time tracks.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx
  • Performance Parameters


DMUS_BUFFERDESC

The DMUS_BUFFERDESC structure is used to describe a buffer for the IDirectMusic8::CreateMusicBuffer method.

Syntax

typedef struct _DMUS_BUFFERDESC {
  DWORD dwSize;
  DWORD dwFlags;
  GUID  guidBufferFormat;
  DWORD cbBuffer;
} DMUS_BUFFERDESC, *LPDMUS_BUFFERDESC;

Members

dwSize

Size of this structure, in bytes. This member must be initialized to sizeof(DMUS_BUFFERDESC) before the structure is used.

dwFlags

No flags are defined.

guidBufferFormat

Identifier of the KS format of the buffer. The value GUID_NULL represents KSDATAFORMAT_SUBTYPE_DIRECTMUSIC.

If guidBufferFormat represents a KS format other than KSDATAFORMAT_SUBTYPE_DIRECTMUSIC, the application must verify that the port playing back the data understands the specified format; if not, the buffer is ignored. To find out whether the port supports a specific KS format, use the IKsControl::KsProperty method.

cbBuffer

Minimum size of the buffer, in bytes. The amount of memory allocated can be slightly higher because the system pads the buffer to a multiple of 4 bytes. The buffer must be at least 32 bytes to accommodate a single MIDI channel message, and at least 28 bytes plus the size of the data to accommodate a system exclusive message or other unstructured data.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • DMUS_EVENTHEADER
  • IDirectMusicBuffer8::PackStructured
  • IDirectMusicBuffer8::PackUnstructured


DMUS_CHORD_KEY

The DMUS_CHORD_KEY structure is used to describe a chord in the IDirectMusicPerformance8::MIDIToMusic and IDirectMusicPerformance8::MusicToMIDI methods.

Syntax

typedef struct _DMUS_CHORD_KEY {
  WCHAR         wszName[16];
  WORD          wMeasure;
  BYTE          bBeat;
  BYTE          bSubChordCount;
  DMUS_SUBCHORD SubChordList[DMUS_MAXSUBCHORD];
  DWORD         dwScale;
  BYTE          bKey;
  BYTE          bFlags;
} DMUS_CHORD_KEY;

Members

wszName

Name of the chord as specified in the Chordmap Designer component of DirectMusic Producer; for example, 2CM.

wMeasure

Measure that the chord falls on.

bBeat

Beat that the chord falls on.

bSubChordCount

Number of chords in the chord's list of subchords.

SubChordList

Array of DMUS_SUBCHORD structures, describing the components that make up the chord.

dwScale

Scale underlying the entire chord. Each of the lower 24 bits represents a note in a two-octave scale, where position 0 is the root note of the scale.

bKey

Key underlying the entire chord, where 0 is C, 1 is C# or Bb, and so on.

bFlags

Can be zero, or DMUS_CHORDKEYF_SILENT if the chord is silent. See Remarks.

Remarks

This structure is also defined as a DMUS_CHORD_PARAM structure for use in setting and retrieving the GUID_ChordParam track parameter.

If a chord is flagged as a silent chord, it is not taken into consideration when a pattern is selected to be played. For instance, if there is a chord change on beat 1 and the silent chord is on beat 3, a pattern with a whole measure chord rhythm can still be played.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx
  • Performance Parameters


DMUS_CHORD_PARAM

The DMUS_CHORD_PARAM structure is used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a chord track and rguidType is GUID_ChordParam.

Syntax

typedef DMUS_CHORD_KEY DMUS_CHORD_PARAM;

Members

See DMUS_CHORD_KEY.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx
  • Performance Parameters


DMUS_CLOCKINFO8

The DMUS_CLOCKINFO8 structure contains information about a clock enumerated by using the IDirectMusic8::EnumMasterClock method.

Syntax

typedef struct _DMUS_CLOCKINFO{
  DWORD           dwSize;
  DMUS_CLOCKTYPE  ctType;
  GUID            guidClock;
  WCHAR           wszDescription[DMUS_MAX_DESCRIPTION];
  DWORD           dwFlags;
} DMUS_CLOCKINFO8, *LPDMUS_CLOCKINFO8;

typedef DMUS_CLOCKINFO8 DMUS_CLOCKINFO;
typedef DMUS_CLOCKINFO *LPDMUS_CLOCKINFO;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_CLOCKINFO8) before the structure is passed to a method.

ctType

Member of the DMUS_CLOCKTYPE enumeration specifying the type of clock.

guidClock

Identifier of the clock. This value can be passed to the IDirectMusic8::SetMasterClock method to set the master clock for DirectMusic.

wszDescription

Description of the clock.

dwFlags

Flags. Can be 0 or DMUS_CLOCKF_GLOBAL.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_COMMAND_PARAM

The DMUS_COMMAND_PARAM structure is used as the pParam parameter in calls to various get-parameter and set-parameter methods when the track is a command track and the rguidType parameter is GUID_CommandParam.

Syntax

typedef struct {
  BYTE bCommand;
  BYTE bGrooveLevel;
  BYTE bGrooveRange;
  BYTE bRepeatMode;
} DMUS_COMMAND_PARAM;

Members

bCommand

Command type. See DMUS_COMMANDT_TYPES.

bGrooveLevel

Groove level of the command. The groove level is a value in the range from 1 through 100.

bGrooveRange

Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the actual groove level could be anywhere from 33 through 37. If bGrooveRange is an odd number, 1 is subtracted from it.

bRepeatMode

Flag that specifies how patterns are selected from among multiple matching patterns. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusici.h.

See Also

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx


DMUS_COMMAND_PARAM_2

The DMUS_COMMAND_PARAM_2 structure is used as the pParam parameter in calls to various get-parameter and set-parameter methods when the track is a command track and the rguidType parameter is GUID_CommandParam2.

Syntax

typedef struct _DMUS_COMMAND_PARAM_2 {
  MUSIC_TIME mtTime;
  BYTE bCommand;
  BYTE bGrooveLevel;
  BYTE bGrooveRange;
  BYTE bRepeatMode;
} DMUS_COMMAND_PARAM_2;

Members

mtTime

Time of the command.

bCommand

Command type. See DMUS_COMMANDT_TYPES.

bGrooveLevel

Groove level of the command. The groove level is a value in the range from 1 through 100.

bGrooveRange

Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the groove level could be anywhere from 33 through 37. If bGrooveRange is an odd number, 1 is subtracted from it.

bRepeatMode

Flag that specifies how patterns are selected for repetition. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx


DMUS_EVENTHEADER

The DMUS_EVENTHEADER structure precedes and describes an event in a port buffer.

Syntax

typedef struct _DMUS_EVENTHEADER {
  DWORD     cbEvent;
  DWORD     dwChannelGroup;
  REFERENCE_TIME  rtDelta;
  DWORD     dwFlags;
} DMUS_EVENTHEADER, *LPDMUS_EVENTHEADER;

Members

cbEvent

Number of bytes in the event.

dwChannelGroup

Group to which the event belongs.

rtDelta

Offset from the start time of the buffer.

dwFlags

Set to DMUS_EVENT_STRUCTURED if the event is parsable MIDI data.

Remarks

The Pshpack4.h header file is included before the declaration of this structure to turn off automatic alignment of structures so that the data immediately follows the header. (For more information, see the comments in Pshpack4.h.) Poppack.h is then included to turn alignment back on, and the entire structure (header plus event) is padded to an 8-byte boundary.

Requirements

Header: Declared in dmusbuff.h.

See Also

  • DirectMusic Structures
  • IDirectMusicBuffer8::GetNextEvent
  • IDirectMusicBuffer8::PackStructured
  • IDirectMusicBuffer8::PackUnstructured


DMUS_MUTE_PARAM

The DMUS_MUTE_PARAM structure is used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a mute track and rguidType is GUID_MuteParam.

Syntax

typedef struct _DMUS_MUTE_PARAM {
  DWORD  dwPChannel;
  DWORD  dwPChannelMap;
  BOOL fMute;
} DMUS_MUTE_PARAM;

Members

dwPChannel

Performance channel to mute or remap. If the structure is being passed to a get method, this member must be initialized.

dwPChannelMap

Channel to which dwPChannel is being mapped. This member is ignored if fMute is TRUE.

fMute

TRUE if dwPChannel is being muted.

Remarks

If you want all the notes on channel 3 to play on channel 9 instead, set dwPChannel to 3 and dwPChannelMap to 9 before passing the structure to one of the set methods. If you want to mute the notes on PChannel 8, set dwPChannel to 8 and dwPChannelMap to 0xFFFFFFFF.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx


DMUS_NOTERANGE

The DMUS_NOTERANGE structure specifies a range of notes that an instrument must respond to. An array of these structures is passed to the IDirectMusicPerformance8::DownloadInstrument and IDirectMusicPort8::DownloadInstrument methods to specify what notes the instrument should respond to and, therefore, what instrument regions need to be downloaded.

Syntax

typedef struct _DMUS_NOTERANGE {
  DWORD dwLowNote;
  DWORD dwHighNote;
} DMUS_NOTERANGE, *LPDMUS_NOTERANGE;

Members

dwLowNote

Low note for this range of MIDI notes to which the instrument must respond.

dwHighNote

High note for this range of MIDI notes to which the instrument must respond.

Requirements

Header: Declared in dmdls.h.

See Also

  • DirectMusic Structures


DMUS_OBJECTDESC

The DMUS_OBJECTDESC structure is used to describe a loadable object. This structure is passed to the IDirectMusicLoader8::GetObject method to identify the object that the loader should retrieve from storage. Information about an object is retrieved in this structure by the IDirectMusicLoader8::EnumObject and IDirectMusicObject8::GetDescriptor methods.

Syntax

typedef struct _DMUS_OBJECTDESC {
  DWORD         dwSize;
  DWORD         dwValidData;
  GUID          guidObject;
  GUID          guidClass;
  FILETIME      ftDate;
  DMUS_VERSION  vVersion;
  WCHAR         wszName[DMUS_MAX_NAME];
  WCHAR         wszCategory[DMUS_MAX_CATEGORY];
  WCHAR         wszFileName[DMUS_MAX_FILENAME];
  LONGLONG      llMemLength;
  LPBYTE        pbMemData;
  IStream*      pStream
} DMUS_OBJECTDESC, *LPDMUS_OBJECTDESC;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_OBJECTDESC) before the structure is passed to any method.

dwValidData

Flags describing which members are valid and giving further information about some members. The following values are defined:

Flag | Description
DMUS_OBJ_CATEGORY | The wszCategory member is valid.
DMUS_OBJ_CLASS | The guidClass member is valid.
DMUS_OBJ_DATE | The ftDate member is valid.
DMUS_OBJ_FILENAME | The wszFileName member is valid. The presence of this flag is assumed if DMUS_OBJ_FULLPATH is set.
DMUS_OBJ_FULLPATH | The wszFileName member contains either the full path of a file or a path relative to the application directory. The directory set by IDirectMusicLoader8::SetSearchDirectory is not searched. If this flag is not set, wszFilename is always assumed to be relative to the application directory, or to the search directory if SetSearchDirectory has been called for this object type.
DMUS_OBJ_LOADED | The object is currently loaded in memory.
DMUS_OBJ_MEMORY | The object is in memory, and llMemLength and pbMemData are valid.
DMUS_OBJ_NAME | The wszName member is valid.
DMUS_OBJ_OBJECT | The guidObject member is valid.
DMUS_OBJ_STREAM | The pStream member contains a pointer to the data stream.
DMUS_OBJ_URL | The wszFileName member contains a URL. URLs are not currently supported by the DirectMusic loader.
DMUS_OBJ_VERSION | The vVersion member is valid.

guidObject

Unique identifier for this object.

guidClass

Unique identifier for the class of object. See DirectMusic Component GUIDs.

ftDate

Date that the object was last edited.

vVersion

DMUS_VERSION structure containing version information.

wszName

Name of the object.

wszCategory

Category for the object.

wszFileName

File path. If DMUS_OBJ_FULLPATH is set, this is the full path; otherwise, it is the file name. If the IDirectMusicLoader8::SetSearchDirectory method has been called, this member must contain only a file name.

llMemLength

Size of data in memory.

pbMemData

Pointer to data in memory. Do not use this value except when loading from a resource contained in the executable file.

pStream

Address of the IStream interface of a custom stream that can be used to load the object into memory. In most cases this value should be NULL.See Remarks.

Remarks

At least one of wszName, guidObject, and wszFileName must contain valid data to retrieve the object by using the IDirectMusicLoader8::GetObject method.

The name and category strings use 16-bit characters in the WCHAR format, not 8-bit ANSI characters. Be sure to convert as appropriate. You can use the C library mbstowcs function to convert from multibyte to Unicode and the wcstombs function to convert from Unicode back to multibyte.

Instead of passing on object descriptor to IDirectMusicLoader8::GetObject or IDirectMusicLoader8::SetObject with a filename or memory pointer, an application can pass a stream. This is done by setting the DMUS_OBJ_STREAM flag in dwValidData and a pointer to the stream in pStream. When the application calls GetObject, the loader saves the stream's current location, reads the object from the stream, and then restores the saved location. The application can continue reading from the stream without being affected by the call to GetObject.

When SetObject is called with a stream, the loader makes a clone of the stream object, and this clone is used if the object is later loaded. Thus an application can release a stream or continue to read from it after passing it to the loader by using SetObject. The actual data of the stream is not copied, so the application should not change or delete the data.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_PLAY_MARKER_PARAM

The DMUS_PLAY_MARKER_PARAM structure contains information about a play marker.

Syntax

typedef struct _DMUS_PLAY_MARKER_PARAM {
  MUSIC_TIME mtTime;
} DMUS_PLAY_MARKER_PARAM;

Members

mtTime

Time of the first legal segment play marker before or at the requested time. The value is an offset from the requested time.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • GUID_Play_Marker


DMUS_PORTCAPS

The DMUS_PORTCAPS structure contains information about a port enumerated by a call to the IDirectMusic8::EnumPort method. The structure is also used to return information through the IDirectMusicPort8::GetCaps method.

Syntax

typedef struct _DMUS_PORTCAPS {
  DWORD dwSize;
  DWORD dwFlags;
  GUID  guidPort;
  DWORD dwClass;
  DWORD dwType;
  DWORD dwMemorySize;
  DWORD dwMaxChannelGroups;
  DWORD dwMaxVoices;
  DWORD dwMaxAudioChannels;
  DWORD dwEffectFlags;
  WCHAR wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_PORTCAPS, *LPDMUS_PORTCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTCAPS) before the structure is passed to any method.

dwFlags

Flags describing various capabilities of the port. This field can contain one or more of the following values:

Flag | Description
DMUS_PC_AUDIOPATH | Multiple outputs can be connected to DirectSound for audiopaths.
DMUS_PC_DIRECTSOUND | The port supports streaming waveform data to DirectSound.
DMUS_PC_DLS | The port supports DLS Level 1 sample collections.
DMUS_PC_DLS2 | The port supports DLS Level 2 sample collections.
DMUS_PC_EXTERNAL | The port connects to devices outside the host—for example, devices connected over an external MIDI port such as the MPU-401.
DMUS_PC_GMINHARDWARE | The synthesizer has its own GM instrument set, so GM instruments do not need to be downloaded.
DMUS_PC_GSINHARDWARE | This port contains the Roland GS sound set in hardware.
DMUS_PC_MEMORYSIZEFIXED | Memory available for DLS instruments cannot be adjusted.
DMUS_PC_SHAREABLE | More than one port can be created that uses the same range of channel groups on the device. Unless this bit is set, the port can be opened only in exclusive mode. In exclusive mode, an attempt to create a port fails unless free channel groups are available to assign to the create request.
DMUS_PC_SOFTWARESYNTH | The port is a software synthesizer.
DMUS_PC_WAVE | Streaming and one-shot waveforms are supported.
DMUS_PC_XGINHARDWARE | The port contains the Yamaha XG extensions in hardware.

guidPort

Identifier of the port. This value can be passed to the IDirectMusic8::CreatePort method to get an IDirectMusicPort8 interface for the port.

dwClass

Class of this port. The following classes are defined:

Value | Description
DMUS_PC_INPUTCLASS | Input port.
DMUS_PC_OUTPUTCLASS | Output port.

dwType

Type of this port. The following types are defined:

Value | Description
DMUS_PORT_WINMM_DRIVER | Windows multimedia driver.
DMUS_PORT_USER_MODE_SYNTH | User-mode synthesizer.
DMUS_PORT_KERNEL_MODE | WDM driver.

dwMemorySize

Amount of memory available to store DLS instruments. If the port is using system memory and the amount is therefore limited only by the available system memory, this member contains DMUS_PC_SYSTEMMEMORY.

dwMaxChannelGroups

Maximum number of channel groups supported by this port. A channel group is a set of 16 MIDI channels.

dwMaxVoices

Maximum number of voices that can be allocated when this port is opened. The value can be –1 if the driver does not support returning this parameter.

dwMaxAudioChannels

Maximum number of audio channels that can be rendered by the port. The value can be –1 if the driver does not support returning this parameter.

dwEffectFlags

Flags indicating what audio effects are available on the port.

The following flags are defined:

Flag | Description
DMUS_EFFECT_NONE | No effects are supported.
DMUS_EFFECT_REVERB | The port supports reverb.
DMUS_EFFECT_CHORUS | The port supports chorus.
DMUS_EFFECT_DELAY | The port supports delay.

wszDescription

Description of the port. This can be a system-generated name, such as L"MPU-401 Output Port [330]", or a user-specified friendly name, such as L"Port w/ External SC-55".

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Structures


DMUS_PORTPARAMS8

The DMUS_PORTPARAMS8 structure contains parameters for the opening of a DirectMusic port. These parameters are passed in when the IDirectMusic8::CreatePort method is called.

The define DMUS_PORTPARAMS resolves to DMUS_PORTPARAMS8. This structure supersedes the earlier version of DMUS_PORTPARAMS, which is now declared as DMUS_PORTPARAMS7.

Syntax

typedef struct _DMUS_PORTPARAMS8 {
  DWORD dwSize;
  DWORD dwValidParams;
  DWORD dwVoices;
  DWORD dwChannelGroups;
  DWORD dwAudioChannels;
  DWORD dwSampleRate;
  DWORD dwEffectFlags;
  DWORD fShare;
  DWORD dwFeatures;
} DMUS_PORTPARAMS8;

typedef DMUS_PORTPARAMS8 DMUS_PORTPARAMS;
typedef DMUS_PORTPARAMS *LPDMUS_PORTPARAMS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTPARAMS8) before the structure is passed to a method.

dwValidParams

Specifies which members in this structure are valid. Setting the flag for a particular port parameter means that you want to have this parameter set on the method call or want to override the default value when the port is created. The following flags have been defined:

DMUS_PORTPARAMS_VOICES
DMUS_PORTPARAMS_CHANNELGROUPS
DMUS_PORTPARAMS_AUDIOCHANNELS
DMUS_PORTPARAMS_SAMPLERATE
DMUS_PORTPARAMS_EFFECTS
DMUS_PORTPARAMS_SHARE
DMUS_PORTPARAMS_FEATURES

dwVoices

Number of voices required on this port. This is not an absolute maximum; the port can create additional temporary voices to enable smooth transitions when lower-priority voices have to be dropped.

dwChannelGroups

Number of channel groups to be allocated on this port. Must be less than or equal to the number of channel groups specified in the DMUS_PORTCAPS structure returned by the IDirectMusic8::EnumPort and IDirectMusicPort8::GetCaps methods.

dwAudioChannels

Desired number of output channels.

dwSampleRate

Desired sample rate, in hertz.

dwEffectFlags

Flags indicating which special effects are wanted. The following values are defined:

Flag | Description
DMUS_EFFECT_NONE | No effects are wanted.
DMUS_EFFECT_REVERB | Reverb is wanted.
DMUS_EFFECT_CHORUS | Chorus is wanted.
DMUS_EFFECT_DELAY | Delay is wanted.

fShare

If TRUE, all ports use the channel groups assigned to this port. If FALSE, the port is opened in exclusive mode, and the use of the same channel groups by other ports is forbidden.

dwFeatures

Miscellaneous capabilities of the port. The following values are defined.

Flag | Description
DMUS_PORT_FEATURE_AUDIOPATH | Supports an audiopath connection to DirectSound buffers.
DMUS_PORT_FEATURE_STREAMING | Supports streaming waveforms through the synthesizer.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Structures
  • DMUS_PORTCAPS


DMUS_RHYTHM_PARAM

The DMUS_RHYTHM_PARAM structure is used as the pParam parameter in calls to the various get-parameter methods when the track is a chord track and rguidType is GUID_RhythmParam.

Syntax

typedef struct {
  DMUS_TIMESIGNATURE  TimeSig;
  DWORD  dwRhythmPattern;
} DMUS_RHYTHM_PARAM;

Members

TimeSig

DMUS_TIMESIGNATURE structure containing the time signature of the rhythm parameter. This structure must be initialized before the DMUS_RHYTHM_PARAM structure is passed to the get method.

dwRhythmPattern

Rhythm pattern for a sequence of chords. Each bit represents a beat in one or more measures, with 1 signifying a chord on the beat and 0 signifying no chord.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx


DMUS_SCRIPT_ERRORINFO

The DMUS_SCRIPT_ERRORINFO structure contains information about a script error.

Syntax

typedef struct _DMUS_SCRIPT_ERRORINFO {
  DWORD   dwSize;
  HRESULT hr;
  ULONG   ulLineNumber;
  LONG    ichCharPosition;
  WCHAR   wszSourceFile[DMUS_MAX_FILENAME];
  WCHAR   wszSourceComponent[DMUS_MAX_FILENAME];
  WCHAR   wszDescription[DMUS_MAX_FILENAME];
  WCHAR   wszSourceLineText[DMUS_MAX_FILENAME];
} DMUS_SCRIPT_ERRORINFO;

Members

dwSize

Size of this structure, in bytes. This member must be initialized to sizeof(DMUS_SCRIPT_ERRORINFO) before the structure is passed to any of the IDirectMusicScript8 methods.

hr

Result code obtained from DirectMusic or the script engine.

ulLineNumber

Line number in the script where the error occurred.

ichCharPosition

Position in the line where a syntax error was found, if wszSourceLineText contains a string.

wszSourceFile

File name of the script.

wszSourceComponent

Name of the component that generated the error. For example, this could be DirectMusic or the script parsing engine.

wszDescription

Description of the error.

wszSourceLineText

Text of the script line where a syntax error occurred. If the error is not in the syntax, this is an empty string.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_SUBCHORD

The DMUS_SUBCHORD structure is used in the SubChordList member of a DMUS_CHORD_PARAM structure.

Syntax

typedef struct {
  DWORD dwChordPattern;
  DWORD dwScalePattern;
  DWORD dwInversionPoints;
  DWORD dwLevels;
  BYTE  bChordRoot;
  BYTE  bScaleRoot;
} DMUS_SUBCHORD;

Members

dwChordPattern

Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.

dwScalePattern

Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.

dwInversionPoints

Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.

dwLevels

Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.

bChordRoot

Root of the subchord, in which 0 is the lowest C in the range and 23 is the top B.

bScaleRoot

Root of the scale, in which 0 is the lowest C in the range and 23 is the top B.

Remarks

Chords authored in DirectMusic Producer can have up to four component subchords, each assigned to a different level. Different parts in a pattern can be assigned to different chord levels, so that when the pattern plays, the transpositions within different parts may vary. In the DirectMusic API, complex chords can be added to a track by using the GUID_ChordParam parameter.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_SYNTHSTATS8

The DMUS_SYNTHSTATS8 structure is used by the IDirectMusicPort8::GetRunningStats method to return the current running status of a synthesizer.

Syntax

typedef struct DMUS_SYNTHSTATS {
  DWORD dwSize;
  DWORD dwValidStats;
  DWORD dwVoices;
  DWORD dwTotalCPU;
  DWORD dwCPUPerVoice;
  DWORD dwLostNotes;
  DWORD dwFreeMemory;
  long  lPeakVolume;
  DWORD dwSynthMemUse;
} DMUS_SYNTHSTATS8;

typedef struct _DMUS_SYNTHSTATS8 *LPDMUS_SYNTHSTATS8;

Members

dwSize

Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_SYNTHSTATS) before the structure is passed to a method.

dwValidStats

Flags that specify which fields in this structure have been filled in by the synthesizer. The following flags have been defined:

DMUS_SYNTHSTATS_VOICES
DMUS_SYNTHSTATS_TOTAL_CPU
DMUS_SYNTHSTATS_CPU_PER_VOICE
DMUS_SYNTHSTATS_FREE_MEMORY
DMUS_SYNTHSTATS_LOST_NOTES
DMUS_SYNTHSTATS_PEAK_VOLUME

dwVoices

Average number of voices playing.

dwTotalCPU

Total percentage of the CPU being consumed, multiplied by 100.

dwCPUPerVoice

Percentage of the CPU being consumed per voice, multiplied by 100.

dwLostNotes

Number of notes lost. Notes can be dropped because of voice-stealing or because too much of the CPU is being consumed.

dwFreeMemory

Amount of memory currently available to store DLS instruments. If the synthesizer is using system memory and the amount is therefore limited only by the available system memory, this value is set to DMUS_SYNTHSTATS_SYSTEMMEMORY.

lPeakVolume

Peak volume, measured in hundredths of decibels.

dwSynthMemUse

Memory used by synthesizer waveform data.

Remarks

All the running status parameters, with the exception of dwFreeMemory, are refreshed every second. For example, dwLostNotes provides the total number of notes lost over a one-second period.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Structures


DMUS_TEMPO_PARAM

The DMUS_TEMPO_PARAM structure is used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a tempo track and rguidType is GUID_TempoParam.

Syntax

typedef struct _DMUS_TEMPO_PARAM {
  MUSIC_TIME  mtTime;
  double  dblTempo;
} DMUS_TEMPO_PARAM;

Members

mtTime

Time for which the tempo was retrieved. This is an offset from the time requested in the mtTime parameter of the GetParam or GetParamEx method. This member is ignored in calls to SetParam.

dblTempo

The tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx


DMUS_TIMESIGNATURE

The DMUS_TIMESIGNATURE structure is used by the IDirectMusicStyle8::GetTimeSignature method to retrieve information about a style's time signature. It is also used in the DMUS_RHYTHM_PARAM structure and in the various get-parameter methods when the rguidType parameter is GUID_TimeSignature and the track is a time signature or style track.

Syntax

typedef struct _DMUS_TIMESIGNATURE {
  MUSIC_TIME mtTime;
  BYTE  bBeatsPerMeasure;
  BYTE  bBeat;
  WORD  wGridsPerBeat;
} DMUS_TIMESIGNATURE;

Members

mtTime

Music time at which this time signature occurs.

bBeatsPerMeasure

Top of time signature.

bBeat

Bottom of time signature.

wGridsPerBeat

Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • DMUS_TIMESIG_PMSG
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_VALID_START_PARAM

The DMUS_VALID_START_PARAM structure is used as the pParam parameter in calls to various get-parameter methods when rguidType is GUID_Valid_Start_Time.

Syntax

typedef struct _DMUS_VALID_START_PARAM {
  MUSIC_TIME mtTime;
} DMUS_VALID_START_PARAM;

Members

mtTime

Next valid point at which the segment can start.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures
  • IDirectMusicPerformance8::GetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicTrack8::GetParamEx


DMUS_VARIATIONS_PARAM

The DMUS_VARIATIONS_PARAM structure contains information about variations associated with channels. It is used when retrieving the GUID_Variations parameter.

Syntax

typedef struct _DMUS_VARIATIONS_PARAM {
  DWORD   dwPChannelsUsed;
  DWORD*  padwPChannels;
  DWORD*  padwVariations;
} DMUS_VARIATIONS_PARAM;

Members

dwPChannelsUsed

The number of performance channels in use.

padwPChannels

Address of an array of performance channels in use.

padwVariations

Address of an array of variations in effect for each channel, where each bit set represents a variation.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_VERSION

The DMUS_VERSION structure contains version information for an object described in the DMUS_OBJECTDESC structure.

Syntax

typedef struct _DMUS_VERSION {
  DWORD  dwVersionMS;
  DWORD  dwVersionLS;
} DMUS_VERSION, FAR *LPDMUS_VERSION;

Members

dwVersionMS

Most significant DWORD of the version number.

dwVersionLS

Least significant DWORD of the version number.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Structures


DMUS_WAVES_REVERB_PARAMS

The DMUS_WAVES_REVERB_PARAMS structure contains information about reverberation effects in the Microsoft software synthesizer provided with DirectX 7.0.

Syntax

typedef struct _DMUS_WAVES_REVERB_PARAMS {
  float  fInGain;
  float  fReverbMix;
  float  fReverbTime;
  float  fHighFreqRTRatio;
} DMUS_WAVES_REVERB_PARAMS;

Members

fInGain

Input gain, in decibels. The default value is 0.

fReverbMix

Reverb mix, in decibels. A value of 0 means 100 percent wet reverb (no direct signal). Negative values give a drier signal. The coefficients are calculated so that the overall output level stays approximately constant, regardless of the amount of reverb mix. The default value is –10.0.

fReverbTime

Reverb decay time, in milliseconds. The default value is 1000.

fHighFreqRTRatio

Ratio of the high frequencies to the global reverb time. Unless a very bright reverb is wanted, this should be set to a value less than 1. For example, if fReverbTime is 1000 ms and dHighFreqRTRatio is 0.1, the decay time for high frequencies is 100 ms. The default value is 0.001.

Remarks

The TrueVerb reverberation technology from Waves is licensed to Microsoft as the SimpleVerb implementation for use in the Microsoft software synthesizer.

In DirectX 8.0 and later, music reverberation is handled by a DMO. For more information, see Waves Reverberation.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Structures


KSPROPERTY

The KSPROPERTY structure is used by the IKsControl::KsProperty method to identify a property and operation.

KSPROPERTY is defined as a KSIDENTIFIER structure, which is declared as follows.

Syntax

typedef struct {
  union {
    struct {
    GUID   Set;
    ULONG  Id;
    ULONG  Flags;
    };
    LONGLONG  Alignment;
  };
} KSIDENTIFIER, *PKSIDENTIFIER;

Members

Set

Identifier of the property set. The following property-set GUIDs are predefined by DirectMusic:

Value | Description
GUID_DMUS_PROP_DLS1 | Item 0 is a Boolean indicating whether or not this port supports downloading DLS level 1 samples.
GUID_DMUS_PROP_DLS2 | Item 0 is a Boolean indicating whether or not this port supports downloading DLS level 2 samples.
GUID_DMUS_PROP_Effects | Item 0 contains DMUS_EFFECT_NONE or one or more effects flags (see the dwEffectFlags member of DMUS_PORTCAPS). This property is used to set or retrieve the current state of the effects.
GUID_DMUS_PROP_GM_Hardware | Item 0 is a Boolean indicating whether or not this port supports GM in hardware.
GUID_DMUS_PROP_GS_Capable | Item 0 is a Boolean indicating whether or not this port supports the minimum Requirements for Roland GS extensions.
GUID_DMUS_PROP_GS_Hardware | Item 0 is a Boolean indicating whether or not this port supports Roland GS extensions in hardware.
GUID_DMUS_PROP_INSTRUMENT2 | Item 0 is a Boolean indicating whether or not this port supports downloading samples using the DMUS_ARTICULATION2 structure.
GUID_DMUS_PROP_LegacyCaps | Item 0 is the MIDIINCAPS or MIDIOUTCAPS structure that describes the underlying Windows multimedia device implementing this port. A MIDIINCAPS structure is returned if dwClass is DMUS_PC_INPUTCLASS in this port's capabilities structure. Otherwise, a MIDIOUTCAPS structure is returned.
GUID_DMUS_PROP_MemorySize | Item 0 is the number of bytes of sample RAM free on this device.
GUID_DMUS_PROP_SampleMemorySize | Item 0 is the number of bytes of sample RAM, both free and used, available on this device.
GUID_DMUS_PROP_SamplePlaybackRate | Item 0 is the synthesizer's sample rate. The DLS level 2 file format supports conditional chunks to determine whether a region or articulation should be downloaded. This allows authors to create optional waveforms intended for different sample rates. Setting a sample rate of 96 kHz or greater may cause reverberation effects to fail.
GUID_DMUS_PROP_SynthSink_DSOUND | Item 0 is a Boolean indicating whether or not this port supports DirectSound.
GUID_DMUS_PROP_SynthSink_WAVE | Item 0 is a Boolean indicating whether or not this port supports waveform output using the waveOut functions.
GUID_DMUS_PROP_Volume | Item 1 (DMUS_ITEM_Volume) is a LONG in the range from DMUS_VOLUME_MAX through DMUS_VOLUME_MIN. This is the signed value, in hundredths of a decibel, which is added to the gain of all voices after all DLS articulation has been performed. By default, when a port is added to the performance, this property is set to the master volume. For master volume, see Setting and Retrieving Global Parameters.
GUID_DMUS_PROP_WavesReverb | Item 0 is a DMUS_WAVES_REVERB_PARAMS structure containing reverb parameters.
GUID_DMUS_PROP_WriteLatency | Item 0 is a user-defined value in milliseconds (in the range 0 to 100) that is added to the latency of a user-mode synthesizer that sends its output to DirectSound. The default value is 55. The latency is the delay between when the synthesizer writes data to a buffer and when the data is sent to the device. Increasing the latency can solve some sound breakup problems. The property must be reset each time the port is activated.
GUID_DMUS_PROP_WritePeriod | Item 0 is the period, in milliseconds (in the range 2 to 100), at which the processing thread runs when the synthesizer is a user-mode synthesizer that sends its output to DirectSound. The default value is 10. If your application requires the absolute lowest latency possible, you can set this property to values smaller than the default value of 10 to process data more often, but performance will suffer because of frequent context switching. To reduce CPU consumption at the expense of latency, set this property to more than 10. The value is the same for all port instances that use the standard DirectSound sink. The property must be set each time the port is activated.
GUID_DMUS_PROP_XG_Capable | Item 0 is a Boolean indicating whether or not this port supports the minimum Requirements for Yamaha XG extensions.
GUID_DMUS_PROP_XG_Hardware | Item 0 is a Boolean indicating whether or not this port supports Yamaha XG extensions in hardware.

Id

Item within the property set.

Flags

One of the following flags to specify the operation:

Flag | Description
KSPROPERTY_TYPE_GET | Retrieve the given property item's value.
KSPROPERTY_TYPE_SET | Set the given property item's value.
KSPROPERTY_TYPE_BASICSUPPORT | Ascertain the type of support available for the property set. The data returned by IKsControl::KsProperty in *pvPropertyData is a DWORD containing one or both of KSPROPERTY_TYPE_GET and KSPROPERTY_TYPE_SET, indicating which operations are possible.

Alignment

Not used in DirectMusic.

Requirements

Header: Declared in dmksctrl.h.

See Also

  • DirectMusic Structures
  • Property Sets for DirectMusic Ports


DLS Structures

This section contains reference information for structures used with Downloadable Sounds. Most applications do not need to use these structures, because DirectMusic handles the details of loading DLS collections and downloading instruments to the synthesizer. They are of interest chiefly for applications that edit DLS.

For an overview of using DLS data, see Low-Level DLS.

For more information on DLS data formats, see the specification from the MIDI Manufacturers Association.

The following structures are included in this section.

Structure | Description
DMUS_ARTICPARAMS | Describes parameters for a DLS articulation chunk.
DMUS_ARTICULATION | Describes a DLS level 1 articulation chunk.
DMUS_ARTICULATION2 | Describes a DLS level 1 or level 2 articulation chunk.
DMUS_COPYRIGHT | Describes an optional copyright chunk in DLS data
DMUS_DOWNLOADINFO | Used as a header for DLS data to be downloaded to a port.
DMUS_EXTENSIONCHUNK | Describes a DLS extension chunk.
DMUS_INSTRUMENT | Contains an instrument definition in a DLS download chunk.
DMUS_LFOPARAMS | Defines the low-frequency oscillator for a DLS articulation chunk
DMUS_MSCPARAMS | Defines the pan for a DLS articulation chunk.
DMUS_OFFSETTABLE | Used in the header of DLS instrument data being downloaded to a port.
DMUS_PEGPARAMS | Defines the pitch envelope for a DLS level 1 articulation chunk.
DMUS_REGION | Defines a region for a DLS download.
DMUS_VEGPARAMS | Defines a volume envelope for a DLS level 1 articulation chunk.
DMUS_WAVE | Defines a wave chunk for a DLS download.
DMUS_WAVEARTDL | Contains information for downloading waveform articulation.
DMUS_WAVEDATA | Contains a data chunk for a DLS waveform download.
DMUS_WAVEDL | ontains information about waveform data downloaded to the synthesizer


DMUS_ARTICPARAMS

The DMUS_ARTICPARAMS structure describes parameters for a DLS level 1 articulation chunk. All parameters for articulation are stored in one chunk, which comprises a series of structures defining each functional area of the articulation. If an instrument or region uses articulation, it references this chunk by index from the DMUS_ARTICULATION chunk.

Syntax

typedef struct {
  DMUS_LFOPARAMS LFO;
  DMUS_VEGPARAMS VolEG;
  DMUS_PEGPARAMS PitchEG;
  DMUS_MSCPARAMS Misc;
} DMUS_ARTICPARAMS;

Members

LFO

DMUS_LFOPARAMS structure containing parameters for a low-frequency oscillator.

VolEG

DMUS_VEGPARAMS structure containing parameters for a volume-envelope generator.

PitchEG

DMUS_PEGPARAMS structure containing parameters for a pitch-envelope generator.

Misc

DMUS_MSCPARAMS structure containing the initial pan position.

Remarks

DLS level 2 articulation is handled differently and does not use this structure. See DMUS_ARTICULATION2.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_ARTICULATION

The DMUS_ARTICULATION structure describes a DLS instrument articulation chunk. It is used when the format identifier in the dwDLType member of the DMUS_DOWNLOADINFO structure is DMUS_DOWNLOADINFO_INSTRUMENT. This chunk connects all available DLS articulation data in one list. For example, it might have a DLS Level 1 chunk and a manufacturer's proprietary articulation chunk. The DLS chunk is referenced by ulArt1Idx, and all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx.

Syntax

typedef struct {
  ULONG ulArt1Idx;
  ULONG ulFirstExtCkIdx;
} DMUS_ARTICULATION;

Members

ulArt1Idx

Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS articulation.

ulFirstExtCkIdx

Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation.

Remarks

The articulation chunk consists of a DMUS_ARTICPARAMS structure.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • DMUS_ARTICULATION2


DMUS_ARTICULATION2

The DMUS_ARTICULATION2 structure describes a DLS instrument articulation chunk. This structure is used when the format identifier in the dwDLType member of the DMUS_DOWNLOADINFO structure is DMUS_DOWNLOADINFO_INSTRUMENT2. The DLS level 1 chunk is referenced by ulArt1Idx, and all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx. DLS level 2 articulation chunks also use ulNextArtIdx.

Syntax

typedef struct {
  ULONG ulArt1Idx;
  ULONG ulFirstExtCkIdx;
  ULONG ulNextArtIdx;
} DMUS_ARTICULATION;

Members

ulArt1Idx

Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS level 1 or 2 articulation.

ulFirstExtCkIdx

Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation. DLS level 2 chunks can also be placed here.

ulNextArtIdx

Index of additional articulation chunks to better support DLS level 2 articulations.

Remarks

The articulation chunk consists of a CONNECTIONLIST structure followed by an array of CONNECTION structures. These structures are declared in Dls1.h. For more information, see the Downloadable Sounds Level 2 specification, published by the MIDI Manufacturers Association.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • DMUS_ARTICULATION


DMUS_COPYRIGHT

The DMUS_COPYRIGHT structure describes an optional copyright chunk in DLS data.

Syntax

typedef struct {
  ULONG cbSize;
  BYTE  byCopyright[ ];
} DMUS_COPYRIGHT;

Members

cbSize

Size of data.

byCopyright[ ]

Copyright data.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_DOWNLOADINFO

The DMUS_DOWNLOADINFO structure is used as a header for DLS data to be downloaded to a port. It defines the size and functionality of the download and is always followed by a DMUS_OFFSETTABLE chunk.

Syntax

typedef struct _DMUS_DOWNLOADINFO {
  DWORD dwDLType;
  DWORD dwDLId;
  DWORD dwNumOffsetTableEntries;
  DWORD cbSize;
} DMUS_DOWNLOADINFO;

Members

dwDLType

Type of data being downloaded. The following types are defined:

Value | Description
DMUS_DOWNLOADINFO_INSTRUMENT | Instrument definition, starting with the DMUS_INSTRUMENT structure.
DMUS_DOWNLOADINFO_INSTRUMENT2 | Instrument definition supporting DLS level 2 articulation, starting with the DMUS_INSTRUMENT structure.
DMUS_DOWNLOADINFO_WAVE | PCM waveform data, starting with the DMUS_WAVE structure.

dwDLId

Unique 32-bit identifier for the object. See Remarks.

dwNumOffsetTableEntries

Number of entries in the DMUS_OFFSETTABLE structure that follows.

cbSize

Total size of DMUS_DOWNLOADINFO, DMUS_OFFSETTABLE, and the actual data chunk.

Remarks

The identifier in dwDLId is used to connect objects and is obtained by using the IDirectMusicPortDownload8::GetDLId method. Primarily it connects the regions in an instrument to wave chunks. For example, if a download is given a dwDLId of 3, an instrument chunk downloads with the value 3 placed in the WaveLink.ulTableIndex member of one of its DMUS_REGION structures. This indicates that the region is connected to the wave chunk.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • Low-Level DLS


DMUS_EXTENSIONCHUNK

The DMUS_EXTENSIONCHUNK structure describes a DLS extension chunk. All extensions to the DLS file format that are unknown to DirectMusic are downloaded in this variable-size chunk.

Syntax

typedef struct {
  ULONG  cbSize;
  ULONG  ulNextExtCkIdx;
  FOURCC ExtCkID;
  BYTE byExtCk[ ];
} DMUS_EXTENSIONCHUNK;

Members

cbSize

Size of chunk.

ulNextExtCkIdx

Index, in the DMUS_OFFSETTABLE structure, of the next extension chunk. If 0, there are no more third-party extension chunks.

ExtCkID

Chunk identifier.

byExtCk[ ]

Data.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_INSTRUMENT

The DMUS_INSTRUMENT structure contains an instrument definition in a DLS download chunk.

Syntax

typedef struct {
  ULONG ulPatch;
  ULONG ulFirstRegionIdx;
  ULONG ulGlobalArtIdx;
  ULONG ulFirstExtCkIdx;
  ULONG ulCopyrightIdx;
  ULONG ulFlags;
} DMUS_INSTRUMENT;

Members

ulPatch

Patch number of instrument.

ulFirstRegionIdx

Index of first region chunk (see DMUS_REGION) within the instrument. There should always be a region, but for compatibility with future synthesizer architectures, it is acceptable to have 0 in this member.

ulGlobalArtIdx

Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk (see DMUS_ARTICULATION and DMUS_ARTICULATION2) for the instrument. If 0, the instrument does not have global articulation.

ulFirstExtCkIdx

Index, in the DMUS_OFFSETTABLE structure, of the first extension chunk (see DMUS_EXTENSIONCHUNK) within the instrument. This is used to add new chunks that DirectMusic is unaware of. If 0, no third-party extension chunks are associated with the instrument.

ulCopyrightIdx

Index, in the DMUS_OFFSETTABLE structure, of an optional copyright chunk (see DMUS_COPYRIGHT). If 0, no copyright information is associated with the instrument.

ulFlags

Additional flags for the instrument. The following flag is defined:

Flag | Description
DMUS_INSTRUMENT_GM_INSTRUMENT | The instrument is a standard General MIDI instrument. In the case of patch overlap, GM instruments always have lower priority than other DLS instruments. For example, if a GM instrument is downloaded with patch 0 and a non-GM instrument is also downloaded at patch 0, the non-GM instrument is always selected for playback.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_LFOPARAMS

The DMUS_LFOPARAMS structure defines the low-frequency oscillator for a DLS articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

Syntax

typedef struct {
  PCENT pcFrequency;
  TCENT tcDelay;
  GCENT gcVolumeScale;
  PCENT pcPitchScale;
  GCENT gcMWToVolume;
  PCENT pcMWToPitch;
} DMUS_LFOPARAMS;

Members

pcFrequency

Frequency, in pitch units. See Remarks.

tcDelay

Initial delay, in time cents. See Remarks.

gcVolumeScale

Scaling of output to control tremolo, in attenuation units. See Remarks.

pcPitchScale

Scaling of LFO output to control vibrato, in pitch units. See Remarks.

gcMWToVolume

Modulation wheel range to control tremolo, in attenuation units. See Remarks.

pcMWToPitch

Modulation wheel range to control tremolo, in attenuation units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents, pitch cents, and attenuation as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • DMUS_ARTICPARAMS


DMUS_MSCPARAMS

The DMUS_MSCPARAMS structure defines the pan for a DLS articulation chunk. This structure is used in the DMUS_ARTICPARAMS structure.

Syntax

typedef struct {
  PERCENT ptDefaultPan;
} DMUS_MSCPARAMS;

Members

ptDefaultPan

Default pan, ranging from –50 through 50 percent, in units of 0.1 percent shifted left by 16.

Remarks

PERCENT is defined as long. For more information about pan values, see the DLS specification from the MIDI Manufacturers Association.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • DMUS_ARTICPARAMS


DMUS_OFFSETTABLE

The DMUS_OFFSETTABLE structure is used in the header of DLS instrument data being downloaded to a port.

Syntax

typedef struct _DMUS_OFFSETTABLE {
  ULONG ulOffsetTable[DMUS_DEFAULT_SIZE_OFFSETTABLE];
} DMUS_OFFSETTABLE;

Members

ulOffsetTable

Array of byte offsets into the data.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • Low-Level DLS


DMUS_PEGPARAMS

The DMUS_PEGPARAMS structure defines the pitch envelope for a DLS level 1 articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

Syntax

typedef struct {
  TCENT tcAttack;
  TCENT tcDecay;
  PERCENT ptSustain;
  TCENT tcRelease;
  TCENT tcVel2Attack;
  TCENT tcKey2Decay;
  PCENT pcRange;
} DMUS_PEGPARAMS;

Members

tcAttack

Attack time, in time cents. See Remarks.

tcDecay

Decay time, in time cents. See Remarks.

ptSustain

Sustain, in hundredths of a percent shifted left by 16.

tcRelease

Release time, in time cents. See Remarks.

tcVel2Attack

Velocity to attack, in time cents. See Remarks.

tcKey2Decay

Key to decay, in time cents. See Remarks.

pcRange

Envelope range, in pitch units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents and pitch cents as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures
  • DMUS_ARTICPARAMS


DMUS_REGION

The DMUS_REGION structure defines a region for a DLS download. One or more regions can be embedded in an instrument buffer and referenced by the instrument header chunk, DMUS_INSTRUMENT.

Syntax

typedef struct {
  RGNRANGE RangeKey;
  RGNRANGE RangeVelocity;
  USHORT fusOptions;
  USHORT usKeyGroup;
  ULONG  ulRegionArtIdx;
  ULONG  ulNextRegionIdx;
  ULONG  ulFirstExtCkIdx;
  WAVELINK WaveLink;
  WSMPL  WSMP;
  WLOOP  WLOOP[1];
} DMUS_REGION;

Members

RangeKey

Key range for this region.

RangeVelocity

Velocity range for this region.

fusOptions

Options for the synthesis of this region. The following flag is defined:

Flag | Description
F_RGN_OPTION_SELFNONEXCLUSIVE | If a second note-on for the same note is received by the synthesis engine, the second note is played, as well as the first. This option is off by default so that the synthesis engine forces a note-off of the first note.

usKeyGroup

Key group for a drum instrument. Key group values allow multiple regions within a drum instrument to belong to the same group. If a synthesis engine is instructed to play a note with a key group setting and any other notes are currently playing with this same key group, the synthesis engine turns off all notes with the same key group value as soon as possible. Currently, key groups from 1 through 15 are legal, and 0 indicates no key group.

ulRegionArtIdx

Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk for the region. If 0, the region does not have an articulation and relies on the instrument's global articulation.

ulNextRegionIdx

Index, in the DMUS_OFFSETTABLE structure, of the next region in the region list. If 0, there are no more regions.

ulFirstExtCkIdx

Index, in the DMUS_OFFSETTABLE structure, of the third-party extension chunk list. If 0, no extension chunks are associated with the region.

WaveLink

Standard DLS structure (declared in the Dls1.h header file) for managing a link from the region to a waveform. The ulTableIndex member of the WAVELINK structure contains the download identifier of the associated buffer. (For more information, see DMUS_DOWNLOADINFO and Low-Level DLS.)

WSMP

Standard DLS structure (declared in Dls1.h) for managing the playback of the waveform. If the cSampleLoops member is 1, the following WLOOP structure carries the loop start and end points.

WLOOP[ ]

Structure describing a loop. The WLOOP type is declared in Dls1.h.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_VEGPARAMS

The DMUS_VEGPARAMS structure defines a volume envelope for a DLS level 1 articulation chunk.

Syntax

typedef struct {
  TCENT tcAttack;
  TCENT tcDecay;
  PERCENT ptSustain;
  TCENT tcRelease;
  TCENT tcVel2Attack;
  TCENT tcKey2Decay;
} DMUS_VEGPARAMS;

Members

tcAttack

Attack time, in time cents. See Remarks.

tcDecay

Decay time, in time cents. See Remarks.

ptSustain

Sustain, in hundredths of a percent and shifted left by 16.

tcRelease

Release time, in time cents. See Remarks.

tcVel2Attack

Velocity to attack, in time cents. See Remarks.

tcKey2Decay

Key to decay, in time cents. See Remarks.

Remarks

The DLS Level 1 specification defines time cents as a 32-bit logarithmic value. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Header: Declared in dmdls.h.

See Also

  • DMUS_ARTICPARAMS

See Also

  • DLS Structures


DMUS_WAVE

The DMUS_WAVE structure defines a wave chunk for a DLS download.

Syntax

typedef struct {
  ULONG  ulFirstExtCkIdx;
  ULONG  ulCopyrightIdx;
  ULONG  ulWaveDataIdx;
  WAVEFORMATEX  WaveformatEx;
} DMUS_WAVE;

Members

ulFirstExtCkIdx

Index, in the DMUS_OFFSETTABLE structure, of third-party extension chunks. If 0, no extension chunks are associated with the waveform.

ulCopyrightIdx

Index, in the DMUS_OFFSETTABLE structure, of copyright chunks. If 0, no copyright information is associated with the waveform.

ulWaveDataIdx

Index, in the DMUS_OFFSETTABLE structure, of waveform data. See DMUS_WAVEDATA.

WaveformatEx

WAVEFORMATEX structure that specifies the WAV format of the chunk.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_WAVEARTDL

The DMUS_WAVEARTDL structure contains information for downloading waveform articulation.

Syntax

typedef struct _DMUS_WAVEARTDL {
  ULONG ulDownloadIdIdx;
  ULONG ulBus;
  ULONG ulBuffers;
  ULONG ulMasterDLId;
  USHORT  usOptions
} DMUS_WAVEARTDL, *LPDMUS_WAVEARTDL;

Members

ulDownloadIdIdx

Download identifiers of each buffer.

ulBus

Playback bus.

ulBuffers

Buffers.

ulMasterDLId

Download identifier of master voice of subordinate group.

usOptions

Downloadable Sounds Level 2 region options.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_WAVEDATA

The DMUS_WAVEDATA structure contains a data chunk for a DLS waveform download. The nature of the data is defined by the WaveformatEx member of the DMUS_WAVE structure.

Syntax

typedef struct {
  ULONG cbSize;
  BYTE byData[ ];
} DMUS_WAVEDATA;

Members

cbSize

Size of data.

byData[ ]

PCM waveform data.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DMUS_WAVEDL

ontains information about waveform data downloaded to the synthesizer.

Syntax

typedef struct _DMUS_WAVEDL {
  ULONG  cbWaveData;
} DMUS_WAVEDL, *LPDMUS_WAVEDL;

Members

cbWaveData

Number of bytes of data.

Requirements

Header: Declared in dmdls.h.

See Also

  • DLS Structures


DirectMusic File Format

This section describes the format of files created in DirectMusic Producer and read by DirectMusic when IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile is called. Most applications don't parse these files directly. This format information is included for developers of music-authoring applications or DirectMusic plug-ins who want to be able to save data in a compatible format or load data into their own objects.

DirectMusic data is stored in the resource interchange file format (RIFF). The following topics contain general information about RIFF files:

  • About RIFF
  • RIFF Notation

The following topics describe how DirectMusic data is organized in RIFF chunks:

  • Common Chunks
  • Audiopath Form
  • Band Form
  • Chordmap Form
  • Container Form
  • DirectSound Buffer Configuration Form
  • Effects Form
  • Reference List
  • Script Form
  • Segment Form
  • Style Form
  • Tool Form
  • Toolgraph Form
  • Track Form
  • Wave Header Chunk

The following section is a reference to structures used to contain data in RIFF chunks:

  • DirectMusic File Structures


About RIFF

The basic building block of a RIFF file is a chunk. A chunk is a logical unit of data. Each chunk contains the following fields:

  • A four-character code (FOURCC) specifying the chunk identifier. Conventionally, this is uppercase for registered chunk types, and lowercase otherwise.
  • A DWORD value specifying the size of the data member in the chunk.
  • The data.

A chunk contained in another chunk is a subchunk. The only chunks allowed to contain subchunks are those with a chunk identifier of RIFF or LIST.

The first chunk in a file must be identified as RIFF. All other chunks in the file are subchunks of this chunk. RIFF chunks are also called forms.

A LIST chunk is a grouping of subchunks. Some of these subchunks might appear multiple times, but a LIST is not an array. The terminology can be confusing. You might expect the chunk labeled <part-list>, for example, to be a list of musical parts. In fact, it is a list of the elements of a "part" chunk, which describes a single part.

RIFF chunks include an additional field in the first 4 bytes of the data field. This additional field provides the form type of the chunk. The form type is a four-character code identifying the format of the data stored in the file. For example, DirectMusic styles have the form type DMST.

LIST chunks also include an additional field in the first 4 bytes of the data field. This field contains the list type of the field. The list type is a four-character code identifying the contents of the list. For example, DirectMusic styles have a LIST chunk with a list type of "part" that contains data pertaining to a particular part (instrument track) in the performance.

Note Every four-character code used in DirectMusic files has a corresponding macro in Dmusicf.h. For example, the FOURCC for DMST is returned by the DMUS_FOURCC_STYLE_FORM macro.

For more information on RIFF files in general, see Resource Interchange File Format Services in the Platform SDK documentation.


RIFF Notation

The descriptions of DirectMusic files in the following sections use a subset of the conventional notation for RIFF files. The principal parts of this notation are shown in the following table.

Notation | Description
<element> | File element labeled "element", or of type element.
[ <element> ] | Optional file element.
<element>... | One or more copies of the specified element.
[<element>]... | Zero or more copies of the specified element.
name, 'name', NAME, or 'NAME' | FOURCC identifier of a form type, list type, or chunk.
// Comment | Comment.

Labels are used only in the notation, not in the files themselves. The label <cheh-ck> refers to a chunk with a unique FOURCC identifier and format. Wherever a chunk of this kind occurs in the notation, the same label is used.

The data or subelements associated with a label are shown as in the following example:

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This notation indicates that the chunk labeled <cheh-ck> consists of the FOURCC identifier "cheh" followed by a DMUS_IO_CHORDENTRY structure.

Note The data in every chunk is preceded by a DWORD showing the size of the data. This element is not shown in the notation.

The next example shows a list element, consisting of the FOURCC "LIST" followed by the list identifier "cmap" and one or more elements labeled <choe-list>. The <choe-list> element would be expanded elsewhere.

<cmap-list> -> LIST( 'cmap'
  <choe-list>... )


Common Chunks

The following chunks occur in various list chunks and forms.

<guid-ck>

This is the GUID identifier of the element.

<guid-ck> -> guid( <GUID> )

<vers-ck>

This chunk contains version information for the element.

<vers-ck> -> vers( <DMUS_IO_VERSION> )

<UNFO-list>

The UNFO chunk is like a standard RIFF INFO list, except that it uses Unicode characters. INFO and UNFO lists consist of various chunks that contain null-terminated strings.

<UNFO-list> -> LIST( 'UNFO'
  <unfo-text-ck>...
  )

See Also

  • Reference List


Audiopath Form

The following notation shows the organization of the audiopath form.

RIFF( 'DMAP'
  [<guid-ck>]    // GUID for path.
  [<vers-ck>]    // Version information.
  [<UNFO-list>]  // Name, author, copyright, comments.
  [<DMTG-form>]  // Toolgraph.
  [<pcsl-list>]  // Port configurations.
  [<dbfl-list>]... // DirectSound buffer descriptors.
)

All elements are optional.

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<DMTG-form>

See Toolgraph Form.

<pcsl-list>

Information about the configuration of ports is stored in this list.

<pcsl-list> -> LIST( 'pcsl'
  <pcfl-list>...
  )

The port configuration list consists of an array of lists in the following format:

LIST( 'pcfl'
  <pcfh-ck>    // Header chunk.
  <pprh-ck>    // Port parameters used to create the port.
  [<dbfl-list>]... // DirectSound buffer descriptors.
  [<pchl-list>]  // Pchannel-to-buffer assignments.
  )

The port configuration list consists of several chunks, starting with headers describing the port configuration and parameters:

<pcfh-ck> -> pcfh( <DMUS_IO_PORTCONFIG_HEADER> )

<pprh-ck> -> pprh( <DMUS_PORTPARAMS8> )

The optional buffer descriptors are each contained in a chunk with the following format.

<dbfl-list> -> LIST( 'dbfl'
  <ddah-ck>   // Buffer attributes header
  [<DSBC-form>] // Buffer configuration
)

This buffer description list begins with a header describing buffer attributes.

<ddah-ck> -> ( 'ddah' < DMUS_IO_BUFFER_ATTRIBUTES_HEADER > )

The header is followed by an optional DirectSound Buffer Configuration Form. This is not required for standard buffer types.

The final chunk in the port configuration list is a list containing one or more assignments of performance channels to buffers.

pchl-list -> LIST( 'pchl'
  <pchh-ck>...
)

This list consists of an array of chunks, each of which describes one assignment of channels to buffers.

<pchh-ck> -> pchh(
  <DMUS_IO_PCHANNELTOBUFFER_HEADER>
  <GUID>... // Array of GUIDs specifying the buffers.
)

<dbfl-list>

The last part of the audiopath form consists of optional buffer descriptors identical in format to those in the port configuration list, <pcsl-list>.


Band Form

The following notation shows the format of the top-level chunk, or form, of a band file. Band forms can also be contained in other chunks.

RIFF( 'DMBD'
  [<guid-ck>]   // GUID for band
  [<vers-ck>]   // Optional version information
  [<UNFO-list>] // Name, author, copyright information, comments
  <lbil-list>   // Instruments
  )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<lbil-list>

The data is contained in an array of lists.

<lbil-list> -> LIST( 'lbil'
  <lbin-list>...
  )

Each instrument is described in a list that has the following format:

<lbin-list> -> LIST( 'lbin'
  <bins-ck>
  [<DMRF-list>]
  )

Within the instrument list, the following chunk contains a header describing the instrument:

<bins-ck> -> bins( <DMUS_IO_INSTRUMENT> )

The instrument list can also contain <DMRF-list>, which in this case is a reference to a DLS file. See Reference List.


Chordmap Form

The following notation shows the organization of the top-level chunk, or form, of a chordmap file:

RIFF( 'DMPR'
  <perh-ck>   // Chordmap header chunk
  [ <guid-ck> ] // GUID chunk
  [ <vers-ck> ] // Version chunk
  [ <UNFO-list> ] // UNFO list
  <chdt-ck>   // Chord data chunk
  <chpl-list>   // Chord palette
  <cmap-list>   // Chord graph
  <spsq-list>   // Signpost list
)

<perh-ck>

This is the basic header information for a chordmap.

<perh-ck> -> perh( <DMUS_IO_CHORDMAP> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<chdt-ck>

<chdt-ck> -> chdt(
  <WORD>  // Size of DMUS_IO_CHORDMAP_SUBCHORD.
  <DMUS_IO_CHORDMAP_SUBCHORD>...
  )

The <chdt-ck> chunk contains a WORD indicating the number of bytes per subchord followed by an array of unique subchords. The subchord identifiers referred to in other parts of this file all correspond directly to an index into this array.

<chpl-list>

<chpl-list> -> LIST( 'chpl'
  <chrd-list>...
  )

This list contains the chord palette. There must be exactly 24 items in this list.

<chrd-list> -> LIST( 'chrd'
  <UNAM-ck>  // Chord name
  <sbcn-ck>  // Subchord indexes
  )

This list contains the basic chord information. This information is simply the chord's name and a list of identifiers for the subchords it comprises.

<UNAM-ck> -> UNAM ( <WCHAR>... )

The UNAM chunk stores the name of the chord.

<sbcn-ck> -> sbcn( <WORD>... )

The "sbcn" chunk contains one or more subchord identifiers. These correspond directly to an index into the array found in <chdt-ck>. A maximum of four chords is supported.

<cmap-list>

This list contains the entire chord connection graph for the chordmap. The bulk of the data for the chordmap resides in this chunk.

<cmap-list>  ->  LIST( 'cmap'
  <choe-list>...
  )

Each list contains data for a single entry in the chord graph, along with pointers to all the chords that can occur next in the chord graph.

<choe-list> -> LIST( 'choe'
  <cheh-ck>  // Chord entry data.
  <chrd-list>  // Chord data; see above.
  <ncsq-ck>  // Next chord list.
  )

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This is the chord entry header. The identifier in the structure is the identifier for the chord connection graph, not a subchord identifier.

<ncsq-ck> -> ncsq (
  <WORD>   // Size of DMUS_IO_NEXTCHORD.
  <DMUS_IO_NEXTCHORD>...
  )

The "ncsq" chunk contains data that connects one chord in the connection graph to another. Each chord in the connection graph is represented by a 16-bit identifier.

<spsq-list>

This chunk contains data for each of the signposts.

<spsq-list> -> LIST( 'spsq'
  <spst-list>...
  )

The <spst-list> contains data for a single signpost, consisting of a header, chord information, and optional cadence chords.

<spst-list>  ->  LIST( 'spst'
  <spsh-ck>
  <chrd-list>   // Chord data
  [ <cade-list> ] // Cadence chords
  )

The <spsh-ck> contains the signpost data.

<spsh-ck> -> spsh( <DMUS_IO_CHORDMAP_SIGNPOST> )

For <chrd-list>, see <chpl-list>, described previously.

The <cade-list> chunk contains the chord information for cadence chords. Support for up to two cadence chords in this list is provided. Any additional chords are ignored.

<cade-list> -> LIST( 'cade'
  <chrd-list>...
  )


Container Form

The container form is a chunk that contains other chunks such as segment or style forms. It can be contained within a segment or script file. It is organized as follows:

RIFF ( 'DMCN'
  <conh-ck>   // Container header chunk.
  [<guid-ck>]   // GUID for container.
  [<vers-ck>]   // Optional version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  <cosl-list>   // List of objects.
)

<conh-ck>

This chunk contains a header structure.

<conh-ck> -> 'conh' ( <DMUS_IO_CONTAINER_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<cosl-list>

The final element of the container form is an array of chunks that describe the objects in the container.

<cosl-list> -> LIST ( 'cosl'
  <cobl-list>...
  )

Each object is stored in the following format:

<cobl-list> -> LIST( 'cobl'
  [<coba-ck>]
  <cobh-ck>   // Required header
  [<data> ] or [ DMRF-list ]

The first element is an alias, or alternative name by which this object is known within the container.

<coba-ck> -> coba( <WCHAR>... )  // Null-terminated string

The second element header for the object.

<cobh-ck> -> cobh ( <DMUS_IO_CONTAINED_OBJECT_HEADER> )

The header is normally followed by object data of the type specified in <cobh-ck>. This can be in the form of a RIFF chunk such as a Segment Form or a Style Form. If it is a DMRF-list, it is a reference to the object. For more information on DMRF, see Reference List.


DirectSound Buffer Configuration Form

The following notation shows the organization of a chunk containing information about a DirectSound buffer configuration.

RIFF ( 'DSBC'
  [<guid-ck>]   // GUID identifier for this buffer configuration.
  [<vers-ck>]   // Optional version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  <dsbd-ck>   // DirectSound buffer descriptor.
  [<bsid-ck>]   // Bus identifiers.
  [<ds3d-ck>]   // 3-D parameters.
  [<fxls-list>] // Effect descriptors.
  )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<dsbd-ck>

The DirectSound buffer descriptor is organized as follows:

<dsbd-ck> -> 'dsbd' (
  <DSOUND_IO_DSBUFFERDESC>
  )

<bsid-ck>

The bus identifiers are stored in the following chunk.

<bsid-ck> -> 'bsid' ( <DSOUND_IO_DSBUSID> )

The DSOUND_IO_DSBUSID structure is an array of bytes whose size is specified by the chunk size.

<ds3d-ck>

The 3-D parameters of the buffer are stored in the following chunk.

<ds3d-ck> -> 'ds3d'( <DSOUND_IO_3D> )

<fxls-list>

The next list contains information about DMOs associated with the buffer.

<fxls-list> -> LIST ( 'fxls'
  <DSFX-form>...
  )

Each DMO is stored in an Effects Form.


Effects Form

The effects form describes a DMO effect.

RIFF ( 'DSFX'
  <fxhr-ck>
  [<data-ck>]
)

<fxhr-ck>

The header chunk describes the effect.

<fxhr-ck> -> fxhr ( <DSOUND_IO_DXDMO_HEADER> )

<data-ck>

The data chunk is an optional set of values for the effect parameters in the format expected by the DMO.

<data-ck> -> data ( <DSOUND_IO_DXDMO_DATA> )


Reference List

The reference list chunk contains information about a reference to an object in another file. For example, a band object might contain a reference to a DLS collection in a separate file. This subchunk is used in many different chunks.

The notation for a reference list is as follows:

<DMRF-list> ->LIST( 'DMRF'
  <refh-ck>   // Reference header
  [<guid-ck>]   // Object GUID
  [<date-ck>]   // File date
  [<name-ck>]   // Name
  [<file-ck>]   // File name
  [<catg-ck>]   // Category name
  [<vers-ck>]   // Version information
)

<refh-ck>

The data begins with a header that includes information about the object being referred to:

<refh-ck> -> refh( <DMUS_IO_REFERENCE> )

All other chunks are optional.

<guid-ck>

See Common Chunks.

<date-ck>

The date chunk contains a date in a FILETIME structure.

<date-ck> -> date( <FILETIME> )

<name-ck>, <file-ck>, <catg-ck>

The name, file name, and category name are null-terminated strings.

<name-ck> -> name( <WCHAR>... )
<file-ck> -> file( <WCHAR>... )  // Null-terminated string
<catg-ck> -> catg( <WCHAR>... )  // Null-terminated string

<vers-ck>

See Common Chunks.


Script Form

This section describes the organization of a chunk containing information about a DirectMusic script.

RIFF ( 'DMSC'
  <schd-ck>   // Script header chunk.
  [<guid-ck>]   // GUID for script.
  [<vers-ck>]   // Optional version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  <scve-ck>   // Version of DirectMusic.
  <DMCN-form>   // Container of content referenced by the script.
  <scla-ck>   // Scripting language.
  <scsr-ck> or <DMRF> // Source code.
)

<schd-ck>

The header chunk contains flags in a DMUS_IO_SCRIPT_HEADER structure.

<schd-ck> -> schd( <DMUS_IO_SCRIPT_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<scve-ck>

This chunk describes the version of DirectMusic against which the script was authored.

<scve-ck> -> scve( <DMUS_IO_VERSION> )

<DMCN-form>

For information on this chunk, see Container Form.

<scla-ck>

This chunk consists of a null-terminated string describing the scripting language.

<scla-ck> -> scla( <WCHAR>... )

<scsr-ck> or <DMRF>

The final chunk can contain the source code as a null-terminated array of WCHAR values.

<scsr-ck> -> scsr( <WCHAR>... )

Alternatively, the final chunk can be a Reference List chunk pointing to a text file containing the script code. The guidClassID member of the DMUS_IO_REFERENCE must be GUID_NULL, because this text file is not a DirectMusic object.


Segment Form

The following notation shows the organization of the top-level chunk of a segment file. This form can also be contained within a Container Form.

RIFF( 'DMSG'
  <segh-ck>   // Segment header chunk.
  [<guid-ck>]   // GUID for the segment.
  [<vers-ck>]   // Optional version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  [<DMCN-form>] // Optional container of objects embedded in file.
  <trkl-list>   // Tracks.
  [<DMTG-form>] // Optional toolgraph.
  [<DMAP-form>] // Optional audiopath.
  )

<segh-ck>

This chunk contains the basic header information for a segment.

<segh-ck> -> segh( <DMUS_IO_SEGMENT_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

See Common Chunks.

<DMCN-form>

See Container Form.

<trkl-list>

This is the track list. Each track is encapsulated in a Track Form.

<trkl-list> -> LIST( 'trkl'
  <DMTK-form>...
  )

<DMTG-form>

See Toolgraph Form.

<DMAP-form>

See Audiopath Form.


Style Form

The following notation shows the organization of the top-level chunk of a style file. This form can also be contained within a Container Form.

RIFF( 'DMST'
  <styh-ck>   // Style header chunk
  <guid-ck>   // Unique identifier
  [<UNFO-list>] // Name, author, copyright information, comments
  [<vers-ck>]   // Version chunk
  <part-list>...  // Array of parts in the style, used by patterns
  <pttn-list>...  // Array of patterns in the style
  <DMBD-form>...  // List of bands in the style
  [<prrf-list>] // List of chordmap references in the style
)

<styh-ck>

This chunk contains the basic header information for a style.

<styh-ck> -> styh( <DMUS_IO_STYLE> )

<guid-ck>,<UNFO-list>, <vers-ck>

For information on these three chunks, see Common Chunks.

<part-list>

Each musical part in the style is described in a chunk with the following format.

<part-list> -> LIST('part'
  <prth-ck>   // Part header chunk
  [<UNFO-list>]
  [<note-ck>]   // Notes in part.
  [<crve-ck>]   // Curves in part.
  [<mrkr-ck>]   // Markers in part.
  [<rsln-ck>]   // Variation resolutions in part.
  [<anpn-ck>]   // Resolution anticipations in part.
  )

The part list includes a header, an optional UNFO chunk, and a list of elements, as shown in the following notation. (For the UNFO list, see Common Chunks.)

<prth-ck> -> prth( <DMUS_IO_STYLEPART> )

<note-ck> -> note(
  < DWORD >  // Size of DMUS_IO_STYLENOTE
  < DMUS_IO_STYLENOTE >...
  )

<crve-ck> -> crve(
  < DWORD >  // Size of DMUS_IO_STYLECURVE.
  < DMUS_IO_STYLECURVE >...
  )

<mrkr-ck> -> mrkr(
  < DWORD > // Size of DMUS_IO_STYLEMARKER.
  < DMUS_IO_STYLEMARKER >...
  )

<rsln-ck> -> rsln(
  < DWORD > // Size of DMUS_IO_STYLERESOLUTION.
  < DMUS_IO_STYLERESOLUTION >...
  )

<anpn-ck> -> anpn(
  < DWORD > Size of DMUS_IO_STYLE_ANTICIPATION.
  < DMUS_IO_STYLE_ANTICIPATION >...
  )

<pttn-list>

Each pattern is described in a chunk with the following format.

<pttn-list> -> LIST( 'pttn'
  <ptnh-ck>   // Pattern header chunk.
  <rhtm-ck>   // List of rhythms for chord matching.
  [<UNFO-list>]
  [<mtfs-ck>]   // Motif settings chunk.
  [<DMBD-form>] // Band to be associated with the pattern
                //   (for motifs).
  <pref-list>...  // Array of part reference Ids.
  )

The first chunk of the pattern list is a header:

<ptnh-ck> -> ptnh( <DMUS_IO_PATTERN> )

The second chunk is a rhythm list:

<rhtm-ck> -> rhtm( <DWORD>... )

This chunk consists of an array of DWORDs, one for each measure, giving the rhythm pattern. For information on the arrangement of the bits, see the dwRhythmPattern member of DMUS_RHYTHM_PARAM.

For the optional UNFO list, see Common Chunks.

The next chunk of the pattern list describes the motif settings:

<mtfs-ck> -> mtfs( <DMUS_IO_MOTIFSETTINGS> )

For the <DMBD-form> chunk of the pattern list, see Band Form.

The last chunk of the pattern list is a part reference list.

<pref-list> -> LIST( 'pref'
  <prfc-ck> // Part reference chunk
  )

The only element is a part reference.

<prfc-ck> -> prfc( <DMUS_IO_PARTREF> )

<DMBD-form>

The next chunk in the style form is a Band Form.

<prrf-list>

The final chunk contains an array of chordmap references:

<prrf-list> -> LIST( 'prrf'
  <DMRF-list>...
  )

For more information on <DMRF-list>, see Reference List.


Tool Form

The tool form contains information about tools. Tools can be embedded in a Toolgraph Form or stored as separate files.

<DMTL-form> -> RIFF( 'DMTL'
  <tolh-ck>
  [<data>]    // Tool data
)

<tolh-ck>

This is the tool header chunk.

<tolh-ck> -> tolh( <DMUS_IO_TOOL_HEADER> )

<data>

The <data> element is a chunk of the type identified in the DMUS_IO_TOOL_HEADER structure. The format of this chunk depends on the definition of the tool. It can be a list or a normal chunk.


Toolgraph Form

A toolgraph chunk can occur either as a top-level form or as a subchunk of a Segment Form or Container Form.

RIFF( 'DMTG'
  [<guid-ck>]   // GUID for toolgraph.
  [<vers-ck>]   // Version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  <toll-list>   // List of tools.
)

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<toll-list>

The main and only required part of the toolgraph chunk is the tool list, which consists of an array of tool forms:

<toll-list> -> LIST( 'toll'
  <DMTL-form>...
  )

For more information on the <DMTL-form> chunk, see Tool Form.


Track Form

The track form contains information about a single track. It can be embedded in a Segment Form or stored in its own file.

<DMTK-form> -> RIFF( 'DMTK'
  <trkh-ck>
  [<trkx-ck>]   // Optional track flags.
  [<guid-ck>]   // GUID for track object instance.
  [<vers-ck>]   // Version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  [<data>]    // Track data.
)

<trkh-ck>

The first chunk contains the basic header information for a track.

<trkh-ck> -> trkh( <DMUS_IO_TRACK_HEADER> )

<trkx-ck>

This optional chunk contains flags for the track.

<trkx-ck> -> trkx( <DMUS_IO_TRACK_EXTRAS_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<data>

The last element in the track form is the data for the track. The chunk type used for the data is identified in the DMUS_IO_TRACK_HEADER structure. The following standard track chunks are defined:

  • Band Track Form
  • Chord Track List
  • Chordmap Track List
  • Command Track Chunk
  • Lyrics Track List
  • Marker Track List
  • Mute Track Chunk
  • Parameter Control Track List
  • Pattern Track Form
  • Script Track List
  • Segment Trigger Track List
  • Sequence Track Chunk
  • Signpost Track Chunk
  • Style Track List
  • Sysex Track Chunk
  • Tempo Track Chunk
  • Time Signature Track List
  • Wave Track List


Band Track Form

The band track form can be a top-level form but is also found as the data part of a Track Form. It is organized as follows:

RIFF( 'DMBT'
  [<bdth-ck>]   // Band track header.
  [<guid-ck>]   // GUID for band track.
  [<vers-ck>]   // Version information.
  [<UNFO-list>] // Name, author, copyright information, comments.
  <lbdl-list>   // List of band lists.
  )

<bdth-ck>

This optional chunk contains header information for a band track. The only data in the structure is a flag for automatic downloading.

<bnth-ck> -> bdth( <DMUS_IO_BAND_TRACK_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<lbdl-list>

The last chunk contains one or more bands.

<lbdl-list> -> LIST( 'lbdl'
  <lbnd-list>...
  )

Each band is encapsulated in a list of the following type.

<lbnd-list> -> LIST( 'lbnd'
  <bdih-ck> or <bd2h-ck>
  <DMBD-form>
  )

The band list begins with a header. In older files, this is <bdih-ck>; newer content uses <bd2h-ck>.

<bdih-ck> -> ( <DMUS_IO_BAND_ITEM_HEADER> )

<bd2h-ck> -> ( <DMUS_IO_BAND_ITEM_HEADER2> )

The header is followed by a Band Form containing information about the instruments in the band.


Chord Track List

The chord track list contains chord data for a Track Form. It is organized as follows:

<cord-list> -> LIST( 'cord'
  <crdh-ck>    // Header
  <crdb-ck>... // Chord body chunks
  )

<crdh-ck>

<crdh-ck> -> crdh ( <DWORD> )

The header is a DWORD containing the chord root in the upper 8 bits and the scale in the lower 24 bits. For an explanation of what these bits represent, see DMUS_IO_SUBCHORD.

The body of data for the chord track list consists of information about a chord change and the component subchords:

<crdb-ck> -> crdb(
  <DWORD>     // Size of DMUS_IO_CHORD
  <DMUS_IO_CHORD>
  <DWORD>     // Number of subchords
  <DWORD>     // Size of DMUS_IO_SUBCHORD
  <DMUS_IO_SUBCHORD>...
  )


Chordmap Track List

The chordmap track list contains data for a Track Form. It is organized as follows:

<pftr-list> -> LIST('pftr'
  <pfrf-list>...
  )

The data consists of one or more lists containing time stamps and references to chordmaps:

<pfrf-list> -> LIST('pfrf'
  <stmp-ck>
  <DMRF-list>
  )

The notation for the time stamp chunk is as follows:

<stmp-ck> -> stmp( <DWORD> )

For information on <DMRF-list>, see Reference List.


Command Track Chunk

The command track chunk contains data for a Track Form. It is organized as follows:

<cmnd-ck> -> cmnd(
  <DWORD>  //Size of DMUS_IO_COMMAND
  <DMUS_IO_COMMAND>...
  )


Lyrics Track List

The lyrics track list contains data for a Track Form.

<lyrt-list> -> LIST( 'lyrt'
  <lyrl-list>
  )

The sole chunk in the lyrics track list is another list containing an array of lyrics events:

<lyrl-list> -> LIST(
  <lyre-list>...
  )

Each lyrics event is stored in another list, as follows:

<lyre-list> -> LIST(
  <lyrh-ck>   // Event header chunk
  <lyrn-ck>   // Notification text
  )

The first chunk is a header:

<lyrh-ck> -> lyrh( <DMUS_IO_LYRICSTRACK_EVENTHEADER> )

The second chunk contains the text associated with the event, in a null-terminated string:

<lyrn-ck> -> lyrn( <WCHAR>... )


Marker Track List

The marker track list contains data for a Track Form. It is organized as follows:

<mark-list> -> LIST ( 'MARK'
  [<vals-ck>]
  [<play-ck>]
)

The first element in the list is an array of chunks defining valid start points:

<vals-ck> -> vals(
  DWORD  // size of DMUS_IO_VALID_START
  <DMUS_IO_VALID_START>...
  )

The second element is an array of chunks defining valid play points.

<play-ck> -> play(
  DWORD  // size of DMUS_IO_PLAYMARKER
  <DMUS_IO_PLAYMARKER>...
  )


Mute Track Chunk

The mute track chunk contains data for a Track Form. It is organized as follows:

<mute-ck> -> mute(
  <DWORD>  //Size of DMUS_IO_MUTE
  <DMUS_IO_MUTE>...
  )


Parameter Control Track List

The parameter control track list contains data for a Track Form.

<prmt-list> -> LIST( 'prmt'
  <prol-list>...
  )

The list contains an array of lists, each of which describes an object.

<prol-list> -> LIST( 'proh'
  <proh-ck>   // Object header chunk.
  <prpl-list>...  // Array of parameters.
  )

The first chunk in the object list is a header.

<proh-ck> -> proh( <DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER> )

The second chunk contains parameter lists, organized as shown in the following notation:

<prpl-list> -> LIST( 'prpl'
  <prph-ck>   // Parameter header.
  <prcc-ck>   // Array of curves.
  )

The header of the parameter list is described as follows:

<prph-ck> -> prph( <DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER> )

The array of curves is described in the following chunk.

<prcc-ck> -> prcc(
  <DWORD> // Size of DMUS_IO_PARAMCONTROLTRACK_CURVEINFO.
 <DMUS_IO_PARAMCONTROLTRACK_CURVEINFO>... // Curves, sorted in order of mtTime.
  )


Pattern Track Form

The pattern track form can be a top-level form but is also found as data for a Track Form. It is organized as follows:

RIFF( 'DMPT'
  <styh-ck>     // Style header chunk
  <pttn-list>   // The pattern
  )

For information on <styh-ck>, see Style Form.

The <pattn-list> used in the pattern track is not the same as the one used in the Style Form. The pattern track version also contains part lists.

<pttn-list> -> LIST( 'pttn'
  <ptnh-ck>      // Pattern header chunk.
  <rhtm-ck>      // List of rhythms for chord matching.
  [<UNFO-list>]
  <part-list>... // Array of parts in the pattern; see Style Form.
  [<mtfs-ck>]    // Motif settings chunk.
  [<DMBD-form>]  // Band to be associated with the pattern
                 //   (for motifs).
  <pref-list>... // Array of part reference IDs.
  )


Script Track List

The script track list contains data for a Track Form.

<scrt-list> -> LIST( 'scrt'
  <scrl-list>
  )

The list contains another list that contains an array of script events.

<scrl-list> -> LIST( 'scrl'
  <scre-list>...
  )

Each <scre-list> chunk describes an event as follows:

<scre-list> -> LIST( 'scre'
  <scrh-ck>   // Event header chunk
  <DMRF>      // Reference
  <scrn-ck>   // Routine name
  )

Each script track event begins with a header:

<scrh-ck> -> 'scrh'( <DMUS_IO_SCRIPTTRACK_EVENTHEADER> )

For information on the DMRF chunk, see Reference List.

The last chunk of the script track event is the null-terminated name of a routine:

<scrn-ck> -> 'scrn'( <WCHAR>... )


Segment Trigger Track List

The segment trigger track list contains data for a Track Form. It is organized as follows:

<SEGT-list> -> LIST( 'segt'
  [<sgth-ck>]   // Segment track header.
  <lsgl-list>   // List of segment lists.
  )

The first chunk is the track header:

<sgth-ck> -> 'sgth' ( <DMUS_IO_SEGMENT_TRACK_HEADER> )

The next chunk is a list containing an array of segments:

<lsgl-list> -> LIST( 'lsgl'
  <lseg-list>...
  )

Each "lseg" list describes a single segment item:

<lseg-list> -> LIST( 'lseg'
  <sgih-ck>
  <DMRF-list>
  [<snam-ck>]  // Motif name
  )

The first chunk of the segment item is a header:

<sgih-ck> -> ( <DMUS_IO_SEGMENT_ITEM_HEADER> )

This is followed by a reference to a segment file or a style file. It is a reference to a style if the DMUS_SEGMENTTRACKF_MOTIF flag is present in the item header. For more information, see Reference List.

The last chunk of the segment item contains the null-terminated name of a motif, if the DMUS_SEGMENTTRACKF_MOTIF flag is present in the item header.

<snam-ck> -> ( <WCHAR>... )


Sequence Track Chunk

The sequence track chunk contains data for a Track Form. It is organized as follows:

<seqt> -> seqt(
  <evtl-ck>
  <curl-ck>
  )

The sequence track chunk can contain two chunks, one for sequence items and one for curve items:

<evtl-ck> -> evtl(
  <DWORD>   // Size of DMUS_IO_SEQ_ITEM
  <DMUS_IO_SEQ_ITEM>...
  )

<curl-ck> -> curl(
  <DWORD>   // Size of DMUS_IO_CURVE_ITEM
  <DMUS_IO_CURVE_ITEM>...
  )

Note The sequence track chunk does not conform to the convention that only RIFF and LIST chunks can have subchunks.


Signpost Track Chunk

The signpost track chunk contains data for a Track Form. It is organized as follows:

<sgnp-list> -> sgnp(
  <DWORD>  // Size of DMUS_IO_SIGNPOST.
  <DMUS_IO_SIGNPOST>...
  )


Style Track List

The style track list contains data for a Track Form. It is organized as follows:

<sttr-list> -> LIST('sttr'(
  <strf-list>...
  )

The data consists of one or more lists containing time stamps and references to styles:

<strf-list> -> LIST('strf'(
  <stmp-ck>
  <DMRF-list>
  )

The first chunk contains time stamp data, as follows:

<stmp-ck> -> stmp( <DWORD> )

For information on <DMRF-list>, see Reference List.


Sysex Track Chunk

The sysex track chunk contains data for a Track Form. It is an array of system exclusive message items, each consisting of a DMUS_IO_SYSEX_ITEM structure followed by the number of bytes specified in the dwSysExLength member.

<syex-ck> -> 'syex' (
  {
  <DMUS_IO_SYSEX_ITEM>
  <BYTE>...   // Data
  }...
  )


Tempo Track Chunk

The tempo track chunk contains data for a Track Form. It is organized as follows:

<tetr-ck> -> tetr(
  <DWORD>  // Size of DMUS_IO_TEMPO_ITEM.
  <DMUS_IO_TEMPO_ITEM>...
  )


Time Signature Track List

The time signature track list contains data for a Track Form. It is organized as follows:

<tims-list> -> LIST( 'TIMS'
  <tims-ck> // Time signatures
  )

The time signature array is contained in the following chunk:

<tims-ck> -> tims (
  <DWORD>  // Size of DMUS_IO_TIMESIGNATURE_ITEM.
  <DMUS_IO_TIMESIGNATURE_ITEM>...
  )


Wave Track List

The following notation shows the organization of a chunk containing data for a wave track:

<wavt-list> -> LIST ( 'wavt'
  <wath-ck>      // Wave track header
  <wavp-list>... // Wave parts
  }

<wath-ck>

This chunk contains header information for a wave. It is followed by an array of lists describing wave parts:

<wath-ck> -> wath( <DMUS_IO_WAVE_TRACK_HEADER> )

<wavp-list>

<wavp-list> -> LIST ( 'wavp'
  <waph-ck>   // Wave part header
  <wavi-list>   // Wave items
  )

The wave part list begins with a header.

<waph-ck> -> 'waph' ( <DMUS_IO_WAVE_PART_HEADER> )

The second part of the wave part list is an array of wave items:

<wavi-list> -> LIST( 'wavi'
  <wave-list>...
  )

Each wave item is described in a list chunk as follows:

<wave-list> -> LIST( 'wave'
  <waih-ck>   // Wave item header.
  <DMRF-list>   // Reference to wave object.
  )

The wave description begins with a header chunk:

<waih-ck> -> ( <DMUS_IO_WAVE_ITEM_HEADER> )

For more information on <DMRF-list>, see Reference List.


Wave Header Chunk

The wave header chunk is a special chunk added to WAV files for DirectMusic. It specifies streaming capabilities.

<wavh-ck> -> ( <DMUS_IO_WAVE_HEADER>)


DirectMusic File Structures

This section contains reference information for data structures used in DirectMusic files. Most applications do not need to know about these structures because each standard DirectMusic object handles the loading of its own data through its IPersistStream interface. The structures are chiefly of interest for music-authoring applications that need to save data in a format compatible with DirectMusic.

The following structures are used in DirectMusic files:

Structure | Description
DMUS_IO_BAND_ITEM_HEADER | Contains information about a band change. Superseded by DMUS_IO_BAND_ITEM_HEADER2.
DMUS_IO_BAND_ITEM_HEADER2 | Contains information about a band change.
DMUS_IO_BAND_TRACK_HEADER | Contains information about the default behavior of a band track.
DMUS_IO_BUFFER_ATTRIBUTES_HEADER | Describes attributes of a DirectSound buffer.
DMUS_IO_CHORD | Contains information about a chord change.
DMUS_IO_CHORDENTRY | Contains information about a chord entry.
DMUS_IO_CHORDMAP | Contains information about a chordmap.
DMUS_IO_CHORDMAP_SIGNPOST | Contains information about a signpost chord in a chordmap.
DMUS_IO_CHORDMAP_SUBCHORD | Contains information about a subchord.
DMUS_IO_COMMAND | Contains information about a command event.
DMUS_IO_CONTAINED_OBJECT_HEADER | Used before each object in a Container Form.
DMUS_IO_CONTAINER_HEADER | Used in the Container Form.
DMUS_IO_CURVE_ITEM | Contains information about a curve event in a track.
DMUS_IO_INSTRUMENT | Contains information about an instrument.
DMUS_IO_LYRICSTRACK_EVENTHEADER | Used in a Lyrics Track List.
DMUS_IO_MOTIFSETTINGS | Contains information about a motif.
DMUS_IO_MUTE | Contains information about a mute event on a channel.
DMUS_IO_NEXTCHORD | Contains information about the next chord in a chord graph.
DMUS_IO_PARAMCONTROLTRACK_CURVEINFO | Used in a Parameter Control Track List.
DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER | Used in a Parameter Control Track List.
DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER | Used in a Parameter Control Track List.
DMUS_IO_PARTREF | Contains information about a part reference.
DMUS_IO_PATTERN | Contains information about a pattern.
DMUS_IO_PCHANNELTOBUFFER_HEADER | Defines a range of performance channels and the buffers they connect to.
DMUS_IO_PLAYMARKER | Contains information about a play marker, which is a point within a primary segment where a new segment is permitted to start playing.
DMUS_IO_PORTCONFIG_HEADER | Contains information about a port configuration.
DMUS_IO_REFERENCE | Contains information about a reference to another object that might be stored in another file.
DMUS_IO_SCRIPT_HEADER | Used in the Script Form.
DMUS_IO_SCRIPTTRACK_EVENTHEADER | Used in a Script Track List
DMUS_IO_SEGMENT_HEADER | Contains information about a segment.
DMUS_IO_SEGMENT_ITEM_HEADER | Contains information about a segment referenced in a Segment Trigger Track List.
DMUS_IO_SEGMENT_TRACK_HEADER | Contains information about a Segment Trigger Track List.
DMUS_IO_SEQ_ITEM | Contains information about an item of data in a sequence track.
DMUS_IO_SIGNPOST | Contains information about a signpost in a signpost track to associate it with signpost chords in a chordmap.
DMUS_IO_STYLE | Contains information about the time signature and tempo of a style.
DMUS_IO_STYLE_ANTICIPATION | Describes a resolution anticipation.
DMUS_IO_STYLECURVE | Contains information about a curve in a style.
DMUS_IO_STYLEMARKER | Contains information about a marker in a style.
DMUS_IO_STYLENOTE | Contains information about a note in a style.
DMUS_IO_STYLEPART | Contains information about a musical part.
DMUS_IO_STYLERESOLUTION | Describes a style resolution.
DMUS_IO_SUBCHORD | Contains information about a subchord.
DMUS_IO_SYSEX_ITEM | Contains information about a system exclusive MIDI message.
DMUS_IO_TEMPO_ITEM | Contains information about a tempo change in a track.
DMUS_IO_TIMESIG | Contains information about the time signature of a segment.
DMUS_IO_TIMESIGNATURE_ITEM | Contains information about a time signature change.
DMUS_IO_TOOL_HEADER | Contains information about a tool.
DMUS_IO_TRACK_EXTRAS_HEADER | Used in the Track Form
DMUS_IO_TRACK_HEADER | Contains information about a track.
DMUS_IO_VALID_START | Contains information about a valid start point in a segment that is to be cued to a rhythm.
DMUS_IO_VERSION | Contains the version number of the data.
DMUS_IO_WAVE_HEADER | Describes streaming characteristics of a wave.
DMUS_IO_WAVE_ITEM_HEADER | Contains data for a wave sound in a Wave Track List
DMUS_IO_WAVE_PART_HEADER | Contains data for a Wave Track List.
DMUS_IO_WAVE_TRACK_HEADER | Contains data for a wave track in a Wave Track List.
DSOUND_IO_3D | Contains 3-D parameters for a DirectSound buffer.
DSOUND_IO_DSBUFFERDESC | Describes a DirectSound buffer.
DSOUND_IO_DSBUSID | Contains bus identifiers.
DSOUND_IO_DXDMO_DATA | Contains data for a DMO.
DSOUND_IO_DXDMO_HEADER | Contains header information for a DMO.

See Also

  • DirectMusic File Format


DMUS_IO_BAND_ITEM_HEADER

The DMUS_IO_BAND_ITEM_HEADER structure contains information about a band change. Used in the Band Track Form of older files. It has been superseded by DMUS_IO_BAND_ITEM_HEADER2.

Syntax

typedef struct _DMUS_IO_BAND_ITEM_HEADER {
  MUSIC_TIME lBandTime;
} DMUS_IO_BAND_ITEM_HEADER;

Members

lBandTime

Time of the band change.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_BAND_ITEM_HEADER2

The DMUS_IO_BAND_ITEM_HEADER2 structure contains information about a band change. Used in the Band Track Form.

Syntax

typedef struct _DMUS_IO_BAND_ITEM_HEADER2 {
  MUSIC_TIME lBandTimeLogical;
  MUSIC_TIME lBandTimePhysical;
} DMUS_IO_BAND_ITEM_HEADER2;

Members

lBandTimeLogical

Time in the music with which the band change is associated.

lBandTimePhysical

Precise time when band change will take effect. Should be close to logical time.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • Segment Timing


DMUS_IO_BAND_TRACK_HEADER

The DMUS_IO_BAND_TRACK_HEADER structure contains information about the default behavior of a band track. Used in the Band Track Form.

Syntax

typedef struct _DMUS_IO_BAND_TRACK_HEADER {
  BOOL bAutoDownload;
} DMUS_IO_BAND_TRACK_HEADER;

Members

bAutoDownload

Flag for automatic downloading of instruments when a segment is played.

Remarks

For more information on automatic downloading, see Using Bands.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_BUFFER_ATTRIBUTES_HEADER

The DMUS_IO_BUFFER_ATTRIBUTES_HEADER structure describes attributes of a DirectSound buffer. Used in the Audiopath Form.

Syntax

typedef struct _DMUS_IO_BUFFER_ATTRIBUTES_HEADER {
  GUID  guidBufferID;
  DWORD dwFlags;
} DMUS_IO_BUFFER_ATTRIBUTES_HEADER;

Members

guidBufferID

Unique identifier of the buffer configuration. The following values are defined for standard buffer types.

Value
GUID_Buffer_Reverb
GUID_Buffer_EnvReverb
GUID_Buffer_Stereo
GUID_Buffer_3D_Dry
GUID_Buffer_Mono

dwFlags

Flags describing the buffer. The following values are defined.

Value | Description
DMUS_BUFFERF_DEFINED | One of the standard buffer types.
DMUS_BUFFERF_MIXIN | Mix-in buffer.
DMUS_BUFFERF_SHARED | Buffer shared among audiopaths.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CHORD

The DMUS_IO_CHORD structure contains information about a chord change. Used in the Chord Track List.

Syntax

typedef struct _DMUS_IO_CHORD {
  WCHAR   wszName[16];
  MUSIC_TIME  mtTime;
  WORD    wMeasure;
  BYTE    bBeat;
  BYTE    bFlags
} DMUS_IO_CHORD;

Members

wszName

Name of the chord.

mtTime

Time of the chord.

wMeasure

Measure that the chord falls on.

bBeat

Beat that the chord falls on.

bFlags

Flags. The following value is defined as shown.

Value | Description
DMUS_CHORDKEYF_SILENT | The chord is silent. See the Remarks for DMUS_CHORD_KEY.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CHORDENTRY

The DMUS_IO_CHORDENTRY structure contains information about a chord entry. Used in the Chordmap Form.

Syntax

typedef struct _DMUS_IO_CHORDENTRY {
  DWORD dwFlags;
  WORD  wConnectionID;
} DMUS_IO_CHORDENTRY;

Members

dwFlags

Flag indicating whether the chord is a starting chord (bit 2 set) or an ending chord (bit 3 set) in the chord graph.

wConnectionID

Replaces the run-time pointer to this. Each chord entry is tagged with a unique connection identifier.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CHORDMAP

The DMUS_IO_CHORDMAP structure contains information about a chordmap. Used in the Chordmap Form.

Syntax

typedef struct _DMUS_IO_CHORDMAP {
  WCHAR wszLoadName[20];
  DWORD dwScalePattern;
  DWORD dwFlags;
} DMUS_IO_CHORDMAP;

Members

wszLoadName

Name of the chordmap, used in the object description when the chordmap is loaded.

dwScalePattern

Scale associated with the chordmap. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.

dwFlags

Flags. Can be zero or the following value.

Value | Description
DMUS_CHORDMAPF_VERSION8 | The chordmap was created for DirectX 8.0 or later.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CHORDMAP_SIGNPOST

The DMUS_IO_CHORDMAP_SIGNPOST structure contains information about a signpost chord in a chordmap. Used in the Chordmap Form.

Syntax

typedef struct _DMUS_IO_CHORDMAP_SIGNPOST {
  DWORD dwChords;
  DWORD dwFlags;
} DMUS_IO_CHORDMAP_SIGNPOST;

Members

dwChords

Types of signpost supported by this chord. The values are used to match against the same values as they appear in templates. Composing from template consists of (among other things) looking for these values in the template and finding actual chords in the chordmap that match these values. The following flags are defined.

Value
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE

dwFlags

Flags defining whether this chord is to be preceded by cadence chords. Signpost chords can have up to two cadence chords. This value can be SPOST_CADENCE1 (first cadence), SPOST_CADENCE2 (second cadence), or a combination of these two flags.

Requirements

Header: Declared in dmusicf.h.

See Also

See Also

  • DirectMusic File Structures
  • DMUS_IO_SIGNPOST


DMUS_IO_CHORDMAP_SUBCHORD

The DMUS_IO_CHORDMAP_SUBCHORD structure contains information about a subchord. Used in the Chordmap Form.

Syntax

typedef struct _DMUS_IO_CHORDMAP_SUBCHORD {
  DWORD dwChordPattern;
  DWORD dwScalePattern;
  DWORD dwInvertPattern;
  BYTE  bChordRoot;
  BYTE  bScaleRoot;
  WORD  wCFlags;
  DWORD dwLevels;
} DMUS_IO_CHORDMAP_SUBCHORD;

Members

dwChordPattern

Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.

dwScalePattern

Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.

dwInvertPattern

Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.

bChordRoot

Root of the subchord, where 0 is the lowest C in the range and 23 is the top B.

bScaleRoot

Root of the scale, where 0 is the lowest C in the range and 23 is the top B.

wCFlags

Reserved for future use.

dwLevels

Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_SUBCHORD


DMUS_IO_COMMAND

The DMUS_IO_COMMAND structure contains information about a command event. Used in the Command Track Chunk.

Syntax

typedef struct _DMUS_IO_COMMAND {
  MUSIC_TIME  mtTime;
  WORD    wMeasure;
  BYTE    bBeat;
  BYTE    bCommand;
  BYTE    bGrooveLevel;
  BYTE    bGrooveRange;
  BYTE    bRepeatMode;
} DMUS_IO_COMMAND;

Members

mtTime

Time of the command.

wMeasure

Measure that the command falls on.

bBeat

Beat that the command falls on.

bCommand

Command type. See DMUS_COMMANDT_TYPES.

bGrooveLevel

Groove level, or 0 if the command is not a groove command.

bGrooveRange

Size of the range within which the groove level can be randomized. If this value is an odd number, the groove range is bGrooveRange – 1. For instance, if the groove level is 35 and bGrooveRange is 5, the adjusted groove range is 4 and the groove level could be anywhere from 33 to 37.

bRepeatMode

Flag that specifies how patterns are selected for repetition. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CONTAINED_OBJECT_HEADER

The DMUS_IO_CONTAINED_OBJECT_HEADER structure is used before each object in a Container Form.

Syntax

typedef struct _DMUS_IO_CONTAINED_OBJECT_HEADER {
  GUID    guidClassID;
  DWORD   dwFlags;
  FOURCC  ckid;
  FOURCC  fccType;
} DMUS_IO_CONTAINED_OBJECT_HEADER;

Members

guidClassID

Class identifier of the object.

dwFlags

Can be zero or the following flag.

Value | Description
DMUS_CONTAINED_OBJF_KEEP | Keep the object cached in the loader after the container is released.

ckid

Identifier of the data chunk. If this value is zero, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.

fccType

List type. If this value is zero, ckid is valid and must be nonzero.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CONTAINER_HEADER

The DMUS_IO_CONTAINER_HEADER structure is used in the Container Form.

Syntax

typedef struct _DMUS_IO_CONTAINER_HEADER {
  DWORD   dwFlags;
} DMUS_IO_CONTAINER_HEADER;

Members

dwFlags

DWORD value that specifies flags. Can be zero or the following value.

Value | Description
DMUS_CONTAINER_NOLOADS | Contained items are not loaded when the container is loaded. Entries are created in the loader, but the objects are not created until they are specifically loaded.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_CURVE_ITEM

The DMUS_IO_CURVE_ITEM structure contains information about a curve event in a track. Used in the Sequence Track Chunk.

Syntax

typedef struct _DMUS_IO_CURVE_ITEM {
  MUSIC_TIME  mtStart;
  MUSIC_TIME  mtDuration;
  MUSIC_TIME  mtResetDuration;
  DWORD   dwPChannel;
  short   nOffset;
  short   nStartValue;
  short   nEndValue;
  short   nResetValue;
  BYTE    bType;
  BYTE    bCurveShape;
  BYTE    bCCData;
  BYTE    bFlags;
  WORD    wParamType;
  WORD    wMergeIndex
} DMUS_IO_CURVE_ITEM;

Members

mtStart

Start time of the curve.

mtDuration

Duration of the curve.

mtResetDuration

Time after the curve is finished during which a reset can occur.

dwPChannel

Performance channel for the event.

nOffset

Offset from the grid boundary at which the curve occurs, in music time. Because MIDI curves are associated with the closest grid when loaded, this value can be positive or negative.

nStartValue

Start value.

nEndValue

End value.

nResetValue

Reset value, set upon a flush or invalidation within the time set by mtResetDuration.

bType

Type of curve. The following types are defined as shown.

Type | Description
DMUS_CURVET_CCCURVE | Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).
DMUS_CURVET_MATCURVE | Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE | Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE | Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
DMUS_CURVET_NRPNCURVE | NRPN curve.
DMUS_CURVET_RPNCURVE | RPN curve.

bCurveShape

Shape of curve. The following shapes are defined as shown.

Shape | Description
DMUS_CURVES_EXP | Exponential curve shape.
DMUS_CURVES_INSTANT | Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR | Linear curve shape.
DMUS_CURVES_LOG | Logarithmic curve shape.
DMUS_CURVES_SINE | Sine curve shape.

bCCData

CC number if this is a control change type.

bFlags

Set to DMUS_CURVE_RESET if the nResetValue must be set when an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.

wParamType

Parameter number for RPN and NRPN types.

wMergeIndex

Merge index. Supported for mod wheel, reverb send, chorus send, pitch bend, volume, and expression controllers.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • Curves
  • DMUS_IO_SEQ_ITEM


DMUS_IO_INSTRUMENT

The DMUS_IO_INSTRUMENT structure contains information about an instrument. Used in the Band Form.

Syntax

typedef struct _DMUS_IO_INSTRUMENT {
  DWORD  dwPatch;
  DWORD  dwAssignPatch;
  DWORD  dwNoteRanges[4];
  DWORD  dwPChannel;
  DWORD  dwFlags;
  BYTE bPan;
  BYTE bVolume;
  short  nTranspose;
  DWORD  dwChannelPriority;
  short  nPitchBendRange;
} DMUS_IO_INSTRUMENT;

Members

dwPatch

MSB, LSB, and program change to define instrument.

dwAssignPatch

MSB, LSB, and program change to assign to instrument when downloading.

dwNoteRanges

128 bits; one for each MIDI note that the instrument must be able to play.

dwPChannel

Performance channel that the instrument plays on.

dwFlags

Control flags. The following values are defined as shown.

Value | Description
DMUS_IO_INST_ASSIGN_PATCH | The dwAssignPatch member is valid.
DMUS_IO_INST_BANKSELECT | The dwPatch member contains a valid bank select, both MSB and LSB.
DMUS_IO_INST_CHANNEL_PRIORITY | The dwChannelPriority member is valid.
DMUS_IO_INST_GM | Instrument is from the General MIDI collection.
DMUS_IO_INST_GS | Instrument is from the Roland GS collection.
DMUS_IO_INST_NOTERANGES | The dwNoteRanges member is valid.
DMUS_IO_INST_PAN | The bPan member is valid.
DMUS_IO_INST_PATCH | The dwPatch member is valid.
DMUS_IO_INST_PITCHBENDRANGE | The nPitchBendRange member is valid.
DMUS_IO_INST_TRANSPOSE | The nTranspose member is valid.
DMUS_IO_INST_USE_DEFAULT_GM_SET | The default General MIDI instrument set should be downloaded to the port, even if the port has GM in hardware. When a MIDI file that contains an XG or GS reset is parsed, the bank-select message is sent, whether or not GUID_StandardMIDIFile was commanded on the band. In other words, GUID_StandardMIDIFile is effective only for pure GM files.
DMUS_IO_INST_VOLUME | The bVolume member is valid.
DMUS_IO_INST_XG | Instrument is from the Yamaha XG collection.

bPan

Pan for the instrument.

bVolume

Volume for the instrument.

nTranspose

Number of semitones to transpose notes.

dwChannelPriority

Channel priority. For a list of defined values, see IDirectMusicPort8::GetChannelPriority.

nPitchBendRange

Number of semitones shifted by pitch bend.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_LYRICSTRACK_EVENTHEADER

The DMUS_IO_LYRICSTRACK_EVENTHEADER structure is used in a Lyrics Track List.

Syntax

typedef struct _DMUS_IO_LYRICSTRACK_EVENTHEADER {
  DWORD dwFlags;
  DWORD dwTimingFlags;
  MUSIC_TIME lTimeLogical;
  MUSIC_TIME lTimePhysical;
} DMUS_IO_LYRICSTRACK_EVENTHEADER;

Members

dwFlags

Reserved; must be zero.

dwTimingFlags

Flags to determine the timing of the notification. Can be one or more of the members of the DMUS_PMSGF_FLAGS enumeration shown in the following table.

Value | Description
DMUS_PMSGF_TOOL_IMMEDIATE | Message should be processed immediately, regardless of its time stamp.
DMUS_PMSGF_TOOL_QUEUE | Message should be processed just before its time stamp, allowing for port latency.
DMUS_PMSGF_TOOL_ATTIME | Message should be processed at the time stamp.

lTimeLogical

Time in the music with which the event is associated.

lTimePhysical

Precise time when the event will be triggered. This should be close to logical time.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • Segment Timing


DMUS_IO_MOTIFSETTINGS

The DMUS_IO_MOTIFSETTINGS structure contains information about a motif. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_MOTIFSETTINGS {
  DWORD   dwRepeats;
  MUSIC_TIME  mtPlayStart;
  MUSIC_TIME  mtLoopStart;
  MUSIC_TIME  mtLoopEnd;
  DWORD   dwResolution;
} DMUS_IO_MOTIFSETTINGS;

Members

dwRepeats

Number of repetitions.

mtPlayStart

Start of playback, normally 0.

mtLoopStart

Start of looping portion, normally 0.

mtLoopEnd

End of looping portion. Must be greater than mtLoopStart, or zero to loop the entire motif.

dwResolution

Default resolution. See DMUS_TIME_RESOLVE_FLAGS.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • IDirectMusicSegment8::SetLoopPoints


DMUS_IO_MUTE

The DMUS_IO_MUTE structure contains information about a mute event on a channel. Used in the Mute Track Chunk.

Syntax

typedef struct _DMUS_IO_MUTE {
  MUSIC_TIME  mtTime;
  DWORD   dwPChannel;
  DWORD   dwPChannelMap;
} DMUS_IO_MUTE;

Members

mtTime

Time of the event.

dwPChannel

Performance channel to mute or remap.

dwPChannelMap

Channel to which dwPChannel is being mapped, or 0xFFFFFFFF if dwPChannel is to be muted.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_MUTE_PARAM


DMUS_IO_NEXTCHORD

The DMUS_IO_NEXTCHORD structure contains information about the next chord in a chord graph. Used in the Chordmap Form.

Syntax

typedef struct _DMUS_IO_NEXTCHORD {
  DWORD dwFlags;
  WORD  nWeight;
  WORD  wMinBeats;
  WORD  wMaxBeats;
  WORD  wConnectionID;
} DMUS_IO_NEXTCHORD;

Members

dwFlags

Reserved for future use.

nWeight

Likelihood (in the range from 1 through 100) that this link is followed when traversing the chord graph.

wMinBeats

Smallest number of beats that this chord is allowed to play in a composed segment.

wMaxBeats

Largest number of beats that this chord is allowed to play in a composed segment.

wConnectionID

Refers to the wConnectionID member of a DMUS_IO_CHORDENTRY structure.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PARAMCONTROLTRACK_CURVEINFO

The DMUS_IO_PARAMCONTROLTRACK_CURVEINFO structure is used in a Parameter Control Track List.

Syntax

typedef struct _DMUS_IO_PARAMCONTROLTRACK_CURVEINFO {
  MUSIC_TIME  mtStartTime;
  MUSIC_TIME  mtEndTime;
  float   fltStartValue;
  float   fltEndValue;
  DWORD   dwCurveType;
  DWORD   dwFlags;
} DMUS_IO_PARAMCONTROLTRACK_CURVEINFO;

Members

mtStartTime

Start time of the curve.

mtEndTime

End time of the curve.

fltStartValue

Start value of the curve.

fltEndValue

End value of the curve.

dwCurveType

Item from the MP_CURVE_TYPE enumeration. See MP_CURVE_TYPE in the DirectShow documentation.

dwFlags

Combination of the MPF_ENVLP_* constants. See Envelope Flags in the DirectShow documentation.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER

The DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER structure is used in a Parameter Control Track List.

Syntax

typedef struct _DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER {
  DWORD dwFlags;
  GUID guidTimeFormat;
  DWORD dwPChannel;
  DWORD dwStage;
  DWORD dwBuffer;
  GUID guidObject;
  DWORD dwIndex;
} DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER;

Members

dwFlags

Reserved; must be zero.

guidTimeFormat

Time format to set the object to. Must be GUID_TIME_REFERENCE or GUID_TIME_MUSIC, which are defined in Medparam.h.

dwPChannel

Performance channel, 0, or DMUS_PCHANNEL_ALL.

dwStage

Stage in the path.

dwBuffer

Index of the buffer, if there is more than one.

guidObject

Class identifier of the object, such as GUID_DSFX_STANDARD_CHORUS.

dwIndex

Index of the object in the list of matching objects.

Remarks

For more information on the possible values for each member, see IDirectMusicSegmentState8::GetObjectInPath.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER

The DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER structure is used in a Parameter Control Track List.

Syntax

typedef struct _DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER {
  DWORD dwFlags;
  DWORD dwIndex;
} DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER;

Members

dwFlags

Reserved; must be zero.

dwIndex

Index number of the parameter on the object.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PARTREF

The DMUS_IO_PARTREF structure contains information about a part reference. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_PARTREF {
  GUID  guidPartID;
  WORD  wLogicalPartID;
  BYTE  bVariationLockID;
  BYTE  bSubChordLevel;
  BYTE  bPriority;
  BYTE  bRandomVariation;
  WORD  wPad;
  DWORD dwPChannel;
} DMUS_IO_PARTREF;

Members

guidPartID

Identifier of the part.

wLogicalPartID

Identifier corresponding to a particular MIDI channel on a port. This member has been superseded by dwPChannel and is no longer used.

bVariationLockID

Variation lock identifier. Parts with the same value in this member always play the same variation. A value of 0 means that the part plays its variations independently of all other parts.

bSubChordLevel

Subchord level that this part wants. See Remarks.

bPriority

Reserved for future use.

bRandomVariation

Can be 0, meaning that matching variations play sequentially, or one of the members of the DMUS_VARIATIONT_TYPES enumeration.

wPad

Padding for alignment; value not used.

dwPChannel

Performance channel of the part.

Remarks

The bSubChordLevel member contains a zero-based index value. At run time, 1 is shifted left by this value to yield a 1-bit value for comparison with the dwLevels member of a DMUS_SUBCHORD structure. Thus, a part with a bSubChordLevel of 0 would be mapped to any subchord that contained 1 in dwLevels.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PATTERN

The DMUS_IO_PATTERN structure contains information about a pattern. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_PATTERN {
  DMUS_IO_TIMESIG  timeSig;
  BYTE     bGrooveBottom;
  BYTE     bGrooveTop;
  WORD     wEmbellishment;
  WORD     wNbrMeasures;
  BYTE     bDestGrooveBottom;
  BYTE     bDestGrooveTop;
  DWORD    dwFlags;
} DMUS_IO_PATTERN;

Members

timeSig

DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.

bGrooveBottom

Bottom of the groove range.

bGrooveTop

Top of the groove range.

wEmbellishment

Type of embellishment. One or more of the constants from the DMUS_EMBELLISHT_TYPES enumeration, or a value defined by the content provider, such as a custom embellishment number assigned in DirectMusic Producer.

wNbrMeasures

Length of the pattern in measures.

bDestGrooveBottom

Bottom of groove range for next pattern.

bDestGrooveTop

Top of groove range for next pattern.

dwFlags

Flags. Can be zero or the value shown in the following table.

Value | Description
DMUS_PATTERNF_PERSIST_CONTROL | Variation settings in the state data of a pattern-based track persist in the track after it stops playing.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PCHANNELTOBUFFER_HEADER

The DMUS_IO_PCHANNELTOBUFFER_HEADER structure defines a range of performance channels and the buffers they connect to. Used in the port configuration list of an Audiopath Form.

Syntax

typedef struct _DMUS_IO_PCHANNELTOBUFFER_HEADER {
  DWORD  dwPChannelBase;
  DWORD  dwPChannelCount;
  DWORD  dwBufferCount;
  DWORD  dwFlags;
} DMUS_IO_PCHANNELTOBUFFER_HEADER;

Members

dwPChannelBase

First performance channel.

dwPChannelCount

Number of performance channels.

dwBufferCount

Number of buffers the channels connect to.

dwFlags

Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PLAYMARKER

The DMUS_IO_PLAYMARKER structure contains information about a play marker, which is a point within a primary segment where a new segment is permitted to start playing. Used in the Marker Track List.

Syntax

typedef struct _DMUS_IO_PLAY_MARKER {
  MUSIC_TIME mtTime;
} DMUS_IO_PLAY_MARKER;

Members

mtTime

Time of legal play point.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_PORTCONFIG_HEADER

The DMUS_IO_PORTCONFIG_HEADER structure contains information about a port configuration. It is used in the Audiopath Form.

Syntax

typedef struct _DMUS_IO_PORTCONFIG_HEADER {
  GUID  guidPort;
  DWORD dwPChannelBase;
  DWORD dwPChannelCount;
  DWORD dwFlags;
} DMUS_IO_PORTCONFIG_HEADER;

Members

guidPort

Unique identifier of port.

dwPChannelBase

First performance channel.

dwPChannelCount

Number of performance channels.

dwFlags

Configuration flags. The following values are defined.

Value | Description
DMUS_PORTCONFIGF_DRUMSON10 | Drums are on channel 10.
DMUS_PORTCONFIGF_USEDEFAULT | Use the default port.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_REFERENCE

The DMUS_IO_REFERENCE structure contains information about a reference to another object that might be stored in another file. Used in the Reference List chunk.

Syntax

typedef struct _DMUS_IO_REFERENCE {
  GUID  guidClassID;
  DWORD dwValidData;
} DMUS_IO_REFERENCE;

Members

guidClassID

Class identifier.

dwValidData

Flags to indicate which data chunks for the reference are present. For a list of values, see the corresponding member of DMUS_OBJECTDESC.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_SCRIPT_HEADER

The DMUS_IO_SCRIPT_HEADER structure is used in the Script Form.

Syntax

typedef struct _DMUS_IO_SCRIPT_HEADER {
  DWORD  dwFlags;
} DMUS_IO_SCRIPT_HEADER;

Members

dwFlags

DWORD value that specifies the loading behavior of the script. Can be one or more of the values shown in the following table.

Value | Description
DMUS_SCRIPTIOF_LOAD_ALL_CONTENT | All content in the script's container is loaded.
DMUS_SCRIPTIOF_DOWNLOAD_ALL_SEGMENTS | If DMUS_SCRIPTIOF_LOAD_ALL_CONTENT is set, the bands from all the segments in the script's container are downloaded when the script is initialized. Otherwise, a segment's bands are downloaded when the script loads the segment. If DMUS_SCRIPTIOF_DOWNLOAD_ALL_SEGMENTS is not set, the script must manually download and unload the segment's bands.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_SCRIPTTRACK_EVENTHEADER

The DMUS_IO_SCRIPTTRACK_EVENTHEADER structure is used in a Script Track List.

Syntax

typedef struct _DMUS_IO_SCRIPTTRACK_EVENTHEADER {
  DWORD dwFlags;
  MUSIC_TIME lTimeLogical;
  MUSIC_TIME lTimePhysical;
} DMUS_IO_SCRIPTTRACK_EVENTHEADER;

Members

dwFlags

Flag that determines when the event is set. Can be one of the values shown in the following table.

Value | Description
DMUS_IO_SCRIPTTRACKF_PREPARE | Fire the event in advance of the time stamp, at prepare time. This is the default because it leaves the script enough time to change the music happening at the target time.
DMUS_IO_SCRIPTTRACKF_QUEUE | Fire the event just before the time stamp, at queue time.
DMUS_IO_SCRIPTTRACKF_ATTIME | Fire the event exactly at the time stamp.

lTimeLogical

Logical time of the event.

lTimePhysical

Actual time of the event.

Requirements

Header: Declared in dmusicf.h.

See Also

  • Segment Timing

See Also

  • DirectMusic File Structures


DMUS_IO_SEGMENT_HEADER

The DMUS_IO_SEGMENT_HEADER structure contains information about a segment. Used in the Segment Form.

Syntax

typedef struct _DMUS_IO_SEGMENT_HEADER {
  DWORD    dwRepeats;
  MUSIC_TIME   mtLength;
  MUSIC_TIME   mtPlayStart;
  MUSIC_TIME   mtLoopStart;
  MUSIC_TIME   mtLoopEnd;
  DWORD    dwResolution;
  REFERENCE_TIME rtLength;
  DWORD    dwFlags;
  DWORD    dwReserved;
  REFERENCE_TIME rtLoopStart;
  REFERENCE_TIME rtLoopEnd;
  REFERENCE_TIME rtPlayStart;
} DMUS_IO_SEGMENT_HEADER;

Members

dwRepeats

Number of repetitions.

mtLength

Length of the segment.

mtPlayStart

Start of playback, normally 0.

mtLoopStart

Start of the looping portion, normally 0.

mtLoopEnd

End of the looping portion. Must be greater than mtPlayStart, or zero to loop the entire segment.

dwResolution

Default resolution. See DMUS_TIME_RESOLVE_FLAGS.

rtLength

Length of the segment in reference time. Valid if the DMUS_SEGIOF_REFLENGTH flag is set.

dwFlags

Can be 0 or one or more of the following flags.

Value | Description
DMUS_SEGIOF_REFLENGTH | The value in rtLength overrides mtLength.
DMUS_SEGIOF_CLOCKTIME | The segment is played in clock time.

dwReserved

Reserved.

rtLoopStart

Loop start in clock time.

rtLoopEnd

Loop end in clock time.

rtPlayStart

Start point in clock time.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DMUS_IO_MOTIFSETTINGS
  • IDirectMusicSegment8::SetLoopPoints

See Also

  • DirectMusic File Structures


DMUS_IO_SEGMENT_ITEM_HEADER

The DMUS_IO_SEGMENT_ITEM_HEADER structure contains information about a segment referenced in the Segment Trigger Track List.

Syntax

typedef struct _DMUS_IO_SEGMENT_ITEM_HEADER{
  MUSIC_TIME  lTimeLogical;
  MUSIC_TIME  lTimePhysical;
  DWORD     dwPlayFlags;
  DWORD     dwFlags;
} DMUS_IO_SEGMENT_ITEM_HEADER;

Members

lTimeLogical

Time in the music with which the event is associated.

lTimePhysical

Actual time at which the segment is to play.

dwPlayFlags

Flags that will be passed to IDirectMusicPerformance8::PlaySegmentEx. See DMUS_SEGF_FLAGS.

dwFlags

Can be zero or the following value.

Value | Description
DMUS_SEGMENTTRACKF_MOTIF | The DMRF chunk is a link to a style, and the 'snam' chunk is the name of a motif within the style.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_SEGMENT_TRACK_HEADER

The DMUS_IO_SEGMENT_TRACK_HEADER structure contains information about a Segment Trigger Track List.

Syntax

typedef struct _DMUS_IO_SEGMENT_TRACK_HEADER {
  DWORD dwFlags;
} DMUS_IO_SEGMENT_TRACK_HEADER;

Members

dwFlags

Reserved. Must be zero.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_SEQ_ITEM

The DMUS_IO_SEQ_ITEM structure contains information about an item of data in a sequence track. Used in the Sequence Track Chunk.

Syntax

typedef struct _DMUS_IO_SEQ_ITEM {
  MUSIC_TIME  mtTime;
  MUSIC_TIME  mtDuration;
  DWORD   dwPChannel;
  short   nOffset
  BYTE    bStatus;
  BYTE    bByte1;
  BYTE    bByte2;
} DMUS_IO_SEQ_ITEM;

Members

mtTime

Logical time of the event.

mtDuration

Duration for which the event is valid.

dwPChannel

Performance channel for the event.

nOffset

Offset from mtTime at which the note is played, in music time.

bStatus

MIDI event type. Equivalent to the MIDI status byte, but without channel information.

bByte1

First byte of the MIDI data.

bByte2

Second byte of the MIDI data.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_IO_CURVE_ITEM
  • MIDI Messages


DMUS_IO_SIGNPOST

The DMUS_IO_SIGNPOST structure contains information about a signpost in a signpost track to associate it with signpost chords in a chordmap. Used in the Signpost Track Chunk.

Syntax

typedef struct _DMUS_IO_SIGNPOST {
  MUSIC_TIME  mtTime;
  DWORD   dwChords;
  WORD    wMeasure;
} DMUS_IO_SIGNPOST;

Members

mtTime

Time of the signpost.

dwChords

Types of signpost chords allowed to be associated with this signpost. The values are used to match against the same values as they appear in templates. Composing from a template consists of (among other things) looking for these values in the template and finding actual chords in the chordmap that match these values. The following flags are defined as shown.

Value
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE

wMeasure

Measure on which the signpost falls.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_IO_CHORDMAP_SIGNPOST


DMUS_IO_STYLE

The DMUS_IO_STYLE structure contains information about the time signature and tempo of a style. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLE {
  DMUS_IO_TIMESIG  timeSig;
  double     dblTempo;
} DMUS_IO_STYLE;

Members

timeSig

DMUS_IO_TIMESIG structure containing the default time signature for the style.

dblTempo

Tempo of the style.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_STYLE_ANTICIPATION

The DMUS_IO_STYLE_ANTICIPATION structure describes a resolution anticipation. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLE_ANTICIPATION {
  MUSIC_TIME  mtGridStart;
  DWORD   dwVariation;
  short   nTimeOffset;
  BYTE    bTimeRange;
} DMUS_IO_STYLE_ANTICIPATION;

Members

mtGridStart

Offset within the part, in grids, at which the event is to play. See Remarks.

dwVariation

Variations, where each bit set specifies a valid variation.

nTimeOffset

Offset of the time from mtGridStart.

bTimeRange

Range by which to randomize time. See Remarks.

Remarks

The time of the event can be calculated as follows, where TimeSig is a DMUS_IO_TIMESIG structure containing the time signature:

mtEventTime = nTimeOffset + ((mtGridStart / TimeSig.wGridsPerBeat) *
((DMUS_PPQ * 4) / TimeSig.bBeat) + (mtGridStart %
TimeSig.wGridsPerBeat) * (((DMUS_PPQ * 4)/ TimeSig.bBeat) /
TimeSig.wGridsPerBeat))

The value in bTimeRange is converted to music time when the event occurs, according to the formula given in the Remarks to DMUS_IO_STYLENOTE.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_STYLECURVE

The DMUS_IO_STYLECURVE structure contains information about a curve in a style. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLECURVE {
  MUSIC_TIME  mtGridStart;
  DWORD   dwVariation;
  MUSIC_TIME  mtDuration;
  MUSIC_TIME  mtResetDuration;
  short   nTimeOffset;
  short   nStartValue;
  short   nEndValue;
  short   nResetValue;
  BYTE    bEventType;
  BYTE    bCurveShape;
  BYTE    bCCData;
  BYTE    bFlags;
  WORD    wParamType;
  WORD    wMergeIndex;
} DMUS_IO_STYLECURVE;

Members

mtGridStart

Offset, in grids, at which the curve occurs.

dwVariation

Variations that this curve belongs to. Each bit corresponds to one of 32 variations.

mtDuration

Duration of the curve.

mtResetDuration

Time after the curve is finished during which a reset can occur.

nTimeOffset

Offset from mtGridStart at which the curve occurs. See the Remarks for DMUS_IO_STYLE_ANTICIPATION.

nStartValue

Start value.

nEndValue

End value.

nResetValue

Reset value, set upon a flush or invalidation during the time specified by mtResetDuration.

bEventType

Type of curve. See DMUS_IO_CURVE_ITEM.

bCurveShape

Shape of curve. See DMUS_IO_CURVE_ITEM.

bCCData

CC number if this is a control change type.

bFlags

Set to DMUS_CURVE_RESET if the nResetValue must be set when an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.

wParamType

RPN or NRPN parameter number.

wMergeIndex

Merge index. Supported for mod wheel, reverb send, chorus send, pitch bend, volume, and expression controllers.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_CURVE_PMSG
  • DMUS_IO_CURVE_ITEM


DMUS_IO_STYLEMARKER

The DMUS_IO_STYLEMARKER structure contains information about a marker in a style. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLEMARKER {
  MUSIC_TIME  mtGridStart;
  DWORD   dwVariation;
  WORD    wMarkerFlags;
} DMUS_IO_STYLEMARKER;

Members

mtGridStart

Offset, in grids, at which the marker occurs.

dwVariation

Variations that this marker belongs to. Each bit corresponds to one of 32 variations.

wMarkerFlags

Flags that specify behavior of the marker. Can be zero or one or more of the following values. If zero, the behavior is as it was in DirectX version 7.0.

Value | Description
DMUS_MARKERF_START | Start a variation.
DMUS_MARKERF_STOP | Stop a variation.
DMUS_MARKERF_CHORD_ALIGN | New variations must align with a chord. This flag is ignored unless combined with one or both of DMUS_MARKERF_START and DMUS_MARKERF_STOP.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_STYLENOTE

The DMUS_IO_STYLENOTE structure contains information about a note in a style. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLENOTE {
  MUSIC_TIME  mtGridStart;
  DWORD   dwVariation;
  MUSIC_TIME  mtDuration;
  short   nTimeOffset;
  WORD    wMusicValue;
  BYTE    bVelocity;
  BYTE    bTimeRange;
  BYTE    bDurRange;
  BYTE    bVelRange;
  BYTE    bInversionID;
  BYTE    bPlayModeFlags;
  BYTE    bNoteFlags;
} DMUS_IO_STYLENOTE;

Members

mtGridStart

Offset, in grids, at which the note occurs.

dwVariation

Variations that this note belongs to. Each bit corresponds to one of 32 variations.

mtDuration

Duration of the note.

nTimeOffset

Time after mtGridStart at which the event occurs. See the Remarks for DMUS_IO_STYLE_ANTICIPATION.

wMusicValue

Position in the scale.

bVelocity

Note velocity.

bTimeRange

Range within which to randomize start time. See Remarks.

bDurRange

Range within which to randomize duration. See Remarks.

bVelRange

Range within which to randomize velocity.

bInversionID

Identifier of inversion group to which this note belongs.

bPlayModeFlags

Flags to override the play mode of the part. For a list of values, see DMUS_PLAYMODE_FLAGS.

bNoteFlags

Flags. See DMUS_NOTEF_FLAGS.

Remarks

The values in bTimeRange and bDurRange are converted to music time when the note is played, using the following function:

int StoredRangeToActualRange(BYTE bRange)
{
  int nResult = 0;
  if (0 <= bRange && bRange <= 190)
  {
    nResult = bRange;
  }
  else if (191 <= bRange && bRange <= 212)
  {
    nResult = ((bRange - 190) * 5) + 190;
  }
  else if (213 <= bRange && bRange <= 232)
  {
    nResult = ((bRange - 212) * 10) + 300;
  }
  else // bRange > 232
  {
    nResult = ((bRange - 232) * 50) + 500;
  }
  return nResult;
}

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_STYLEPART

The DMUS_IO_STYLEPART structure contains information about a musical part. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLEPART {
  DMUS_IO_TIMESIG  timeSig;
  DWORD    dwVariationChoices[32];
  GUID     guidPartID;
  WORD     wNbrMeasures;
  BYTE     bPlayModeFlags;
  BYTE     bInvertUpper;
  BYTE     bInvertLower;
  BYTE     bPad[3];
  DWORD    dwFlags;
} DMUS_IO_STYLEPART;

Members

timeSig

DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.

dwVariationChoices

Each element corresponds to one of 32 possible variations. The flags set in each element indicate which types of chord are supported by that variation (see Remarks). One of the mode masks is also set to indicate whether the variations are in DirectMusic or IMA mode.

The following flags are defined as shown.

Value | Description
DMUS_VARIATIONF_MAJOR | Seven positions in the scale for major chords.
DMUS_VARIATIONF_MINOR | Seven positions in the scale for minor chords.
DMUS_VARIATIONF_OTHER | Seven positions in the scale for other chords.
DMUS_VARIATIONF_ROOT_SCALE | Handles chord roots in the scale.
DMUS_VARIATIONF_ROOT_FLAT | Handles flat chord roots (based on scale notes).
DMUS_VARIATIONF_ROOT_SHARP | Handles sharp chord roots (based on scale notes).
DMUS_VARIATIONF_TYPE_TRIAD | Handles simple chords for triads.
DMUS_VARIATIONF_TYPE_6AND7 | Handles simple chords for 6 and 7.
DMUS_VARIATIONF_TYPE_COMPLEX | Handles complex chords.
DMUS_VARIATIONF_DEST_TO1 | Handles transitions to the 1 chord.
DMUS_VARIATIONF_DEST_TO5 | Handles transitions to the 5 chord.
DMUS_VARIATIONF_MODES | Mode mask. Obsolete.
DMUS_VARIATIONF_MODES_EX | Mode mask.
DMUS_VARIATIONF_IMA25_MODE | Mode mask. If (dwVariationChoices & DMUS_VARIATIONF_MODES_EX) == DMUS_VARIATIONF_IMA25_MODE, the variations are in Interactive Music Architecture mode.
DMUS_VARIATIONF_DMUS_MODE | Mode mask. If dwVariationChoices contains this mask, the variations are in DirectMusic mode. All variations authored in DirectMusic Producer use this mode.

guidPartID

Unique identifier of the part.

wNbrMeasures

Length of the part, in measures.

bPlayModeFlags

Flags to define the play mode. For a list of values, see DMUS_PLAYMODE_FLAGS.

bInvertUpper

Upper limit of inversion.

bInvertLower

Lower limit of inversion.

bPad

Unused.

dwFlags

Flags that specify the behavior of the part. Can include the values shown in the following table.

Value | Description
DMUS_PARTF_USE_MARKERS | Part uses marker events.
DMUS_PARTF_ALIGN_CHORDS | Part is allowed to switch only on chord-aligned markers.

Remarks

The flags in dwVariationChoices determine the types of chords supported by a given variation in DirectMusic mode. The first seven flags (bits 1 through 7) are set if the variation supports major chords rooted in scale positions. For example, if bits 1, 2, and 4 are set, the variation supports major chords rooted in the tonic, second, and fourth scale positions.

The next seven flags serve the same purpose for minor chords, and the following seven flags serve the same purpose for chords that are not major or minor (for example, SUS 4 chords). Bits 22, 23, and 24 are set if the variation supports chords rooted in the scale, chords rooted sharp of scale tones, and chords rooted flat of scale tones, respectively. For example, to support a C# minor chord in the scale of C major, bits 8 (for tonic minor) and 24 (for sharp) must be set. Bits 25, 26, and 27 handle chords that are triads, sixth or seventh chords, and chords with extensions, respectively. Bits 28 and 29 handle chords that are followed by tonic and dominant chords, respectively.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_STYLERESOLUTION

The DMUS_IO_STYLERESOLUTION structure describes a style resolution. Used in the Style Form.

Syntax

typedef struct _DMUS_IO_STYLERESOLUTION {
  DWORD  dwVariation;
  WORD wMusicValue;
  BYTE bInversionID;
  BYTE bPlayModeFlags;
} DMUS_IO_STYLERESOLUTION;

Members

dwVariation

Variations, where each bit specifies a valid variation.

wMusicValue

Position in scale.

bInversionID

Inversion group to which this note belongs.

bPlayModeFlags

Play mode flags. See DMUS_PLAYMODE_FLAGS.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_SUBCHORD

The DMUS_IO_SUBCHORD structure contains information about a subchord. Used in the Chord Track List.

Syntax

typedef struct _DMUS_IO_SUBCHORD {
  DWORD dwChordPattern;
  DWORD dwScalePattern;
  DWORD dwInversionPoints;
  DWORD dwLevels;
  BYTE  bChordRoot;
  BYTE  bScaleRoot;
} DMUS_IO_SUBCHORD;

Members

dwChordPattern

Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.

dwScalePattern

Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.

dwInversionPoints

Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.

dwLevels

Which levels are supported by this subchord. Certain instruments can be assigned different levels (such as to play only the lower subchords of a chord), and this value is a way of mapping subchords to those levels.

bChordRoot

Root of the subchord, where 0 is the lowest C in the range and 23 is the top B.

bScaleRoot

Root of the scale, where 0 is the lowest C in the range and 23 is the top B.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_SUBCHORD


DMUS_IO_SYSEX_ITEM

The DMUS_IO_SYSEX_ITEM structure contains information about a system exclusive MIDI message. Used in the Sysex Track Chunk.

Syntax

typedef struct _DMUS_IO_SYSEX_ITEM {
  MUSIC_TIME  mtTime;
  DWORD   dwPChannel;
  DWORD   dwSysExLength;
} DMUS_IO_SYSEX_ITEM;

Members

mtTime

Time of the message.

dwPChannel

Performance channel of the event.

dwSysExLength

Length of the data, in bytes.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • MIDI System Messages


DMUS_IO_TEMPO_ITEM

The DMUS_IO_TEMPO_ITEM structure contains information about a tempo change in a track. Used in the Tempo Track Chunk.

Syntax

typedef struct _DMUS_IO_TEMPO_ITEM {
  MUSIC_TIME  lTime;
  double  dblTempo;
} DMUS_IO_TEMPO_ITEM;

Members

lTime

Time of the tempo change.

dblTempo

Tempo, in beats per minute.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_TIMESIG

The DMUS_IO_TIMESIG structure contains information about the time signature of a segment. Used in the DMUS_IO_STYLE, DMUS_IO_VERSION, and DMUS_IO_PATTERN structures.

Syntax

typedef struct _DMUS_IO_TIMESIG {
  BYTE  bBeatsPerMeasure;
  BYTE  bBeat;
  WORD  wGridsPerBeat;
} DMUS_IO_TIMESIG;

Members

bBeatsPerMeasure

Beats per measure (top of time signature).

bBeat

Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.

wGridsPerBeat

Grids (subdivisions) per beat.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_IO_TIMESIGNATURE_ITEM


DMUS_IO_TIMESIGNATURE_ITEM

The DMUS_IO_TIMESIGNATURE_ITEM structure contains information about a time signature change. Used in the Time Signature Track List.

Syntax

typedef struct _DMUS_IO_TIMESIGNATURE_ITEM {
  MUSIC_TIME  lTime;
  BYTE    bBeatsPerMeasure;
  BYTE    bBeat;
  WORD    wGridsPerBeat;
} DMUS_IO_TIMESIGNATURE_ITEM;

Members

lTime

Time of the event.

bBeatsPerMeasure

Beats per measure (top of time signature).

bBeat

Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.

wGridsPerBeat

Grids (subdivisions) per beat.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • DMUS_IO_TIMESIG
  • DMUS_TIMESIG_PMSG


DMUS_IO_TOOL_HEADER

The DMUS_IO_TOOL_HEADER structure contains information about a tool. Used in the Tool Form.

Syntax

typedef struct _DMUS_IO_TOOL_HEADER {
  GUID  guidClassID;
  long  lIndex;
  DWORD cPChannels;
  FOURCC  ckid;
  FOURCC  fccType;
  DWORD dwPChannels[1];
} DMUS_IO_TOOL_HEADER;

Members

guidClassID

Class identifier of the tool.

lIndex

Position in the graph.

cPChannels

Number of items in the dwPChannels array.

ckid

Identifier of tool's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.

fccType

List type. If this value is 0, ckid is valid and must be nonzero.

dwPChannels

Array of performance channels for which the tool is valid.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • IDirectMusicGraph8::InsertTool


DMUS_IO_TRACK_EXTRAS_HEADER

The DMUS_IO_TRACK_EXTRAS_HEADER structure is used in the Track Form.

Syntax

typedef struct _DMUS_IO_TRACK_EXTRAS_HEADER {
  DWORD  dwFlags;

  DWORD  dwPriority;

} DMUS_IO_TRACK_EXTRAS_HEADER;

Members

dwFlags

Flags for control tracks. For possible values, see IDirectMusicSegment8::SetTrackConfig.

dwPriority

Priority for composition.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_TRACK_HEADER

The DMUS_IO_TRACK_HEADER structure contains information about a track. Used in the Track Form.

Syntax

typedef struct _DMUS_IO_TRACK_HEADER {
  GUID   guidClassID;
  DWORD  dwPosition;
  DWORD  dwGroup;
  FOURCC ckid;
  FOURCC fccType;
} DMUS_IO_TRACK_HEADER;

Members

guidClassID

Class identifier of the track.

dwPosition

Position in the track list.

dwGroup

Group bits for the track.

ckid

Identifier of the track's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.

fccType

List type. If this value is 0, ckid is valid and must be nonzero.

See Also

  • DirectMusic File Structures
  • IDirectMusicSegment8::GetTrackGroup
  • IDirectMusicSegment8::InsertTrack
  • Track Form


DMUS_IO_VALID_START

The DMUS_IO_VALID_START structure contains information about a valid start point in a segment that is to be cued to a rhythm. Used in the Marker Track List.

Syntax

typedef struct _DMUS_IO_VALID_START {
  MUSIC_TIME mtTime;
} DMUS_IO_VALID_START;

Members

mtTime

Time of the start point.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_VERSION

The DMUS_IO_VERSION structure contains the version number of the data. Used in the version subchunk of various chunks. See Common Chunks.

Syntax

typedef struct _DMUS_IO_VERSION {
  DWORD  dwVersionMS;
  DWORD  dwVersionLS;
} DMUS_IO_VERSION;

Members

dwVersionMS

High-order 32 bits of the version number.

dwVersionLS

Low-order 32 bits of the version number.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_WAVE_HEADER

The DMUS_IO_WAVE_HEADER structure describes streaming characteristics of a wave. It is used in the Wave Header Chunk of a WAV file.

Syntax

typedef struct _DMUS_IO_WAVE_HEADER {
  REFERENCE_TIME  rtReadAhead;
  DWORD     dwFlags;
} DMUS_IO_WAVE_HEADER;

Members

rtReadAhead

Time to read ahead in a streaming wave.

dwFlags

Flags. Can be zero or one or more of the following values.

Value | Description
DMUS_WAVEF_NOPREROLL | Preroll data is not downloaded with the wave.
DMUS_WAVEF_STREAMING | The wave is streamed.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_WAVE_ITEM_HEADER

The DMUS_IO_WAVE_ITEM_HEADER structure contains data for a wave sound in a Wave Track List.

Syntax

typedef struct _DMUS_IO_WAVE_ITEM_HEADER {
  long     lVolume;
  long     lPitch;
  DWORD    dwVariations;
  REFERENCE_TIME rtTime;
  REFERENCE_TIME rtStartOffset;
  REFERENCE_TIME rtReserved;
  REFERENCE_TIME rtDuration;
  MUSIC_TIME   mtLogicalTime;
  DWORD    dwLoopStart;
  DWORD    dwLoopEnd;
  DWORD    dwFlags;
  WORD     wVolumeRange;
  WORD     wPitchRange;
} DMUS_IO_WAVE_ITEM_HEADER;

Members

lVolume

Gain, in hundredths of a decibel. Must be a negative value.

lPitch

Pitch offset, in hundredths of a semitone.

dwVariations

Variation flags. One bit is set for each variation this wave belongs to.

rtTime

Start time, in reference time if the track is in clock time format; otherwise in music time.

rtStartOffset

Distance into wave to start playback, in reference time.

rtReserved

Not used.

rtDuration

Duration, in reference time if the track is in clock time format; otherwise in music time.

mtLogicalTime

Musical boundary where this belongs. Ignored if the track is in clock time format.

dwLoopStart

Start point for a looping wave.

dwLoopEnd

End point for a looping wave.

dwFlags

Flags. Can be 0 or one of the values in the following table.

Value | Description
DMUS_WAVEF_IGNORELOOPS | Wave is not invalidated when a segment loop point is reached.
DMUS_WAVEF_NOINVALIDATE | This wave is not to be invalidated.
DMUS_WAVEF_STREAMING | Wave is streaming.

wVolumeRange

Amount by which volume can be randomized, in hundredths of a decibel.

wPitchRange

Amount by which pitch can be randomized, in hundredths of a semitone.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures
  • Segment Timing


DMUS_IO_WAVE_PART_HEADER

The DMUS_IO_WAVE_PART_HEADER structure contains data for a Wave Track List.

Syntax

typedef struct _DMUS_IO_WAVE_PART_HEADER {
  long lVolume;
  DWORD  dwVariations;
  DWORD  dwPChannel;
  DWORD  dwLockToPart;
  DWORD  dwFlags;
  DWORD  dwIndex;
} DMUS_IO_WAVE_PART_HEADER;

Members

lVolume

Gain, in hundredths of a decibel, to apply to all waves in this wave part. This must be a negative value.

dwVariations

Active variations. One bit is set for each active variation.

dwPChannel

Performance channel of the part.

dwLockToPart

Variation lock identifier. Parts with the same value in this member always play the same variation. A value of 0 means that the part plays its variations independently of all other parts.

dwFlags

Flags for managing how variations are chosen, in the lower four bits. See DMUS_VARIATIONT_TYPES.

dwIndex

Index for distinguishing multiple parts on the same performance channel.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DMUS_IO_WAVE_TRACK_HEADER

The DMUS_IO_WAVE_TRACK_HEADER structure contains data for a wave track in a Wave Track List.

Syntax

typedef struct _DMUS_IO_WAVE_TRACK_HEADER {
  long lVolume;
  DWORD  dwFlags;
} DMUS_IO_WAVE_TRACK_HEADER;

Members

lVolume

Gain, hundredths of a decibel, to be applied to all waves.

dwFlags

Flags. Can be 0 or one or more of the values shown in the following table.

Value | Description
DMUS_WAVETRACKF_SYNC_VAR | The track gets its variations from a pattern track. For more information, see GUID_Variations.
DMUS_WAVETRACKF_PERSIST_CONTROL | Variation control information persists from one playback instance to the next.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DSOUND_IO_3D

The DSOUND_IO_3D structure contains 3-D parameters for a DirectSound buffer in a DirectSound Buffer Configuration Form.

Syntax

typedef struct _DSOUND_IO_3D {
  GUID guid3DAlgorithm;
  DS3DBUFFER ds3d;
} DSOUND_IO_3D;

Members

guid3DAlgorithm

Unique identifier of the 3-D algorithm to use. See DSBUFFERDESC.

ds3d

DS3DBUFFER structure that contains the parameters. This information is valid only if DSBCAPS_CTRL3D is set in the buffer description.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DSOUND_IO_DSBUFFERDESC

The DSOUND_IO_DSBUFFERDESC structure describes a DirectSound buffer. Used in the DirectSound Buffer Configuration Form.

Syntax

typedef struct _DSOUND_IO_DSBUFFERDESC {
  DWORD dwFlags;
  WORD nChannels;
  LONG lVolume;
  LONG lPan;
  DWORD dwReserved;
} DSOUND_IO_DSBUFFERDESC;

Members

dwFlags

Buffer creation flags. See DSBUFFERDESC.

nChannels

Number of channels. Other parameters of the format are determined by the sink that owns the buffer.

lVolume

Initial volume. Used only if DSBCAPS_CTRLVOLUME is in dwFlags.

lPan

Initial pan. Used only if DSBCAPS_CTRLPAN is in dwFlags.

dwReserved

Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DSOUND_IO_DSBUSID

The DSOUND_IO_DSBUSID structure contains bus identifiers. Used in the DirectSound Buffer Configuration Form.

Syntax

typedef struct _DSOUND_IO_DSBUSID {
  DWORD busid[1];
} DSOUND_IO_DSBUSID;

Members

busid

Array of DWORDs containing the bus identifiers. The size of the array can be determined from the chunk size.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DSOUND_IO_DXDMO_DATA

The DSOUND_IO_DXDMO_DATA structure contains data for a DMO.

Syntax

typedef struct _DSOUND_IO_DXDMO_DATA {
  DWORD data[1];
} DSOUND_IO_DXDMO_DATA;

Members

data

Array of DWORD values containing the data. The size of the array can be determined from the chunk size.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


DSOUND_IO_DXDMO_HEADER

The DSOUND_IO_DXDMO_HEADER structure contains header information for a DMO chunk in an Effects Form.

Syntax

typedef struct _DSOUND_IO_DXDMO_HEADER {
  DWORD dwEffectFlags;
  GUID guidDSFXClass;
  GUID guidReserved;
  GUID guidSendBuffer;
  DWORD dwReserved;
} DSOUND_IO_DXDMO_HEADER;

Members

dwEffectFlags

Effect creation flags. See DSEFFECTDESC.

guidDSFXClass

Class identifier of the effect.

guidReserved

Reserved. Must be GUID_NULL.

guidSendBuffer

Unique identifier of the buffer to send to, if this is a send effect.

dwReserved

Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic File Structures


Standard Track Parameters

This section describes the standard track parameters that can be set and retrieved by using the following methods.

  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::GetParamEx
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParam
  • IDirectMusicTrack8::SetParamEx

Parameter types are listed in this section under their GUIDs, as specified in the rGuidType parameter of the method call.

The following information is given for each parameter type:

Element | Description
Track type | Tracks to which the parameters apply. See Standard Track Types. Although parameters are always associated with particular tracks, applications usually call the method on the segment or the performance and let DirectMusic find the appropriate track. See Identifying the Track.
Data type | Type of data pointed to by the pParam parameter of the method call by which the parameter is set or retrieved.
mtTime | Significance, if any, of the mtTime parameter of the method call by which the parameter is set or retrieved.

The standard parameter types are listed in the following table.

Parameter GUID | Description
GUID_BandParam | Sets or retrieves a band.
GUID_ChordParam | Sets or retrieves a chord change.
GUID_Clear_All_Bands | Clears all bands from the track.
GUID_CommandParam | Sets or retrieves a groove or embellishment command.
GUID_CommandParam2 | Sets or retrieves a groove or embellishment command, with additional timing information.
GUID_CommandParamNext | Sets or retrieves a groove or embellishment command to follow all other commands in the command track.
GUID_ConnectToDLSCollection | Connects all bands in the track to a DLS collection.
GUID_Disable_Auto_Download | Disables automatic downloading of instruments and waves.
GUID_DisableTempo | Disables tempo messages.
GUID_DisableTimeSig | Disables time signature messages.
GUID_Download | Downloads instrument data or wave data to the performance.
GUID_DownloadToAudioPath | Downloads instrument data or wave data to an audiopath.
GUID_Enable_Auto_Download | Enables automatic downloading of instruments and waves.
GUID_EnableTempo | Enables tempo messages.
GUID_EnableTimeSig | Enables time signature messages.
GUID_IDirectMusicBand | Sets a band.
GUID_IDirectMusicChordMap | Sets or retrieves the chordmap.
GUID_IDirectMusicStyle | Sets or retrieves the style.
GUID_MuteParam | Sets or retrieves channel-mapping and muting information.
GUID_Play_Marker | Retrieves the next point in the currently playing segment at which a new segment can start.
GUID_RhythmParam | Retrieves the rhythm pattern for a sequence of chords stored in a measure in the track.
GUID_SeedVariations | Seeds the random number generator for variation selection.
GUID_StandardMIDIFile | Ensures that a standard MIDI file plays correctly.
GUID_TempoParam | Sets or retrieves the tempo.
GUID_TimeSignature | Retrieves the time signature.
GUID_Unload | Unloads instrument or wave data from the performance.
GUID_UnloadFromAudioPath | Unloads instrument or wave data from an audiopath.
GUID_Valid_Start_Time | Retrieves the next valid point within a segment at which it can start.
GUID_Variations | Retrieves the variations in effect across performance channels.


GUID_BandParam

Sets or retrieves a band.

Element | Description
Track type | Band
Data type (*pParam) | DMUS_BAND_PARAM
mtTime | Logical time at which to set the band, or the time for which to retrieve the band.

Remarks

When this parameter is retrieved by a GetParam call, a reference to the band object is created in DMUS_BAND_PARAM.pBand. The application is responsible for releasing this reference.

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_ChordParam

Sets or retrieves a chord change.

Element | Description
Track type | Chord
Data type (*pParam) | DMUS_CHORD_PARAM
mtTime | The time, in track time, at which to add the chord to the track, or the time at or directly after the chord to be retrieved from the track.

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_Clear_All_Bands

Clears all bands from the track. This parameter can be set but not retrieved.

Element | Description
Track type | Band
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParam

Sets or retrieves a groove or embellishment command.

Element | Description
Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParam2

Sets or retrieves a groove or embellishment command.

Element | Description
Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM_2. The mtTime member of this structure gives the actual time of the command.
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParamNext

Sets or retrieves a groove or embellishment command to follow all other commands in the command track.

Element | Description
Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM_2
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_ConnectToDLSCollection

Connects all bands in the track to a DLS collection. This parameter can be set but not retrieved.

Element | Description
Track type | Band
Data type (*pParam) | IDirectMusicCollection8 interface pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Playing a MIDI File with Custom Instruments.


GUID_Disable_Auto_Download

Disables automatic downloading of instruments and waves. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • GUID_Enable_Auto_Download
  • Using Bands


GUID_DisableTempo

Disables tempo messages. This parameter can be set but not retrieved.

Element | Description
Track type | Tempo
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Disabling and Enabling Track Parameters
  • GUID_EnableTempo


GUID_DisableTimeSig

Disables time signature messages. This parameter can be set but not retrieved.

Element | Description
Track type | Pattern, time signature, style, motif
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Disabling and Enabling Track Parameters
  • GUID_EnableTimeSig


GUID_Download

Downloads instrument data or wave data. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | IDirectMusicPerformance8 interface pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8::Download


GUID_DownloadToAudioPath

Downloads instrument data or wave data. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | IDirectMusicAudioPath8 interface pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8::Download


GUID_Enable_Auto_Download

Enables automatic downloading of instruments and waves. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • GUID_Disable_Auto_Download
  • Using Bands


GUID_EnableTempo

Enables tempo messages. This parameter can be set but not retrieved.

Element | Description
Track type | Tempo
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Disabling and Enabling Track Parameters
  • GUID_DisableTempo


GUID_EnableTimeSig

Enables time signature messages. This parameter can be set but not retrieved.

Element | Description
Track type | Pattern, time signature, style, motif
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Disabling and Enabling Track Parameters
  • GUID_DisableTimeSig


GUID_IDirectMusicBand

Sets a band. This parameter can be set but not retrieved.

Element | Description
Track type | Band
Data type (*pParam) | IDirectMusicBand8 interface pointer
mtTime | The time, in track time, at which to add the band to the track.

Remarks

For an explanation of the table, see Standard Track Parameters.

This parameter has been superseded by GUID_BandParam, which allows you to specify the physical time.

Requirements

Header: Declared in dmusici.h.


GUID_IDirectMusicChordMap

Sets or retrieves the chordmap.

Element | Description
Track type | Chordmap
Data type (*pParam) | IDirectMusicChordMap8 interface pointer or address of a variable to receive this pointer.
mtTime | The time, in track time, at which to add the chordmap to the track, or the time at or directly after the chordmap to be retrieved from the track.

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_IDirectMusicStyle

Sets or retrieves the style.

Element | Description
Track type | Style
Data type (*pParam) | IDirectMusicStyle8 interface pointer or address of a variable to receive this pointer
mtTime | The time, in track time, at which to add the style to the track, or the time at or directly after the style to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_MuteParam

Sets or retrieves channel-mapping and muting information.

Element | Description
Track type | Mute.
Data type (*pParam) | DMUS_MUTE_PARAM. The dwPChannel member must be initialized before this structure is passed to the get method.
mtTime | The time, in track time, at which to add the mute event to the track, or the time at or directly after the mute event to be retrieved from the track.

Remarks

For an explanation of the table, see Standard Track Parameters.

You cannot dynamically change the mapping or muting of a channel by setting this parameter while the mute track is playing. Parameters in the mute track are retrieved by internal GetParam calls from other tracks, and the application has no control over the timing of such calls. Changes in the mapping or muting of channels should be authored into the mute track of a segment played as a controlling segment, or done at run time by tools.

Requirements

Header: Declared in dmusici.h.


GUID_Play_Marker

Retrieves the next point in the currently playing segment at which a new segment can start. This parameter can be retrieved but not set.

Element | Description
Track type | Marker
Data type (*pParam) | DMUS_PLAY_MARKER_PARAM
mtTime | Track time at which to start seeking a marker

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Segment Timing


GUID_RhythmParam

Retrieves the rhythm pattern for a sequence of chords stored in a measure in the track. This parameter can be retrieved but not set.

Element | Description
Track type | Chord
Data type (*pParam) | DMUS_RHYTHM_PARAM. The TimeSig member must be initialized before this structure is passed to the get method.
mtTime | The time, in track time, at or directly after the beginning of the measure containing the rhythm pattern to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_SeedVariations

Seeds the random number generator for variation selection. A nonzero value is used as the seed. A value of 0 resets the default behavior of getting the seed from the system clock. This parameter can be set but not retrieved.

Element | Description
Track type | Pattern, style, motif
Data type (*pParam) | Long
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Setting this parameter to nonzero is useful for testing because it ensures that the same sequence of random numbers is generated each time. The parameter should be set only once, before the track is played. The style and command track must be designed so that each time that the segment is played, the same patterns are chosen at the same places in the segment. Each loop plays different variations than the one before it does, but each time the entire segment is replayed from the beginning, each loop sounds the same as the first time the segment was played.

Requirements

Header: Declared in dmusici.h.


GUID_StandardMIDIFile

Ensures that a standard MIDI file (one not authored specifically for DirectMusic) plays correctly. This parameter can be set but not retrieved.

Element | Description
Track type | Band
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Setting this parameter ensures that channels do not play silently if the file contains no patch changes. It also causes bank selects to be ignored. The parameter must be set before any instruments are downloaded.

Do not set this parameter if the file might contain DLS instrument data. Doing so causes the DSL instruments to be ignored and standard GM instruments to be used.

If you are writing an application to play MIDI content that might or might not contain DLS instruments, you should ascertain for each file whether or not the file contains a DLS chunk. The four-character code for this chunk is "DLS ", defined as FOURCC_DLS in Dls1.h. If the file contains this chunk, do not set the GUID_StandardMIDIFile parameter.

See Also

  • About RIFF

Requirements

Header: Declared in dmusici.h.


GUID_TempoParam

Sets or retrieves the tempo.

Element | Description
Track type | Tempo
Data type (*pParam) | DMUS_TEMPO_PARAM. When setting the parameter, the mtTime member of the structure is ignored. When getting the parameter, the mtTime member receives the offset of the tempo change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the tempo, or the time at or directly after the tempo change to retrieve

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_TimeSignature

Retrieves the time signature. This parameter can be retrieved but not set.

Element | Description
Track type | Time signature and style
Data type (*pParam) | DMUS_TIMESIGNATURE. The mtTime member receives the offset of the time signature change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the time signature, or the time at or directly after the time signature change to retrieve

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_Unload

Unloads instrument or wave data. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | IDirectMusicPerformance8 interface pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8::Unload


GUID_UnloadFromAudioPath

Unloads instrument or wave data. This parameter can be set but not retrieved.

Element | Description
Track type | Band, wave
Data type (*pParam) | IDirectMusicAudioPath8 interface pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • IDirectMusicSegment8::Unload


GUID_Valid_Start_Time

Retrieves the next valid point within a segment at which it can start. This parameter can be retrieved but not set.

Element | Description
Track type | Marker, motif, pattern
Data type (*pParam) | DMUS_VALID_START_PARAM
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

  • Segment Timing


GUID_Variations

Retrieves the variations in effect across performance channels. This parameter can be retrieved but not set.

Element | Description
Track type | Pattern
Data type (*pParam) | DMUS_VARIATIONS_PARAM
mtTime | Not used.

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


DirectMusic Enumerated Types

This section contains references for the following enumerated types.

Enumerated Type | Description
DMUS_CHORDKEYF_FLAGS | Used in the bFlags member of the DMUS_CHORD_KEY structure.
DMUS_CLOCKTYPE | Used in the ctType member of the DMUS_CLOCKINFO8 structure.
DMUS_COMMANDT_TYPES | Used in the wCommand parameter of the IDirectMusicComposer8::AutoTransition and IDirectMusicComposer8::ComposeTransition methods and in the bCommand member of the DMUS_COMMAND_PARAM structure.
DMUS_COMPOSEF_FLAGS | Used in the dwFlags parameter of the IDirectMusicComposer8::AutoTransition and IDirectMusicComposer8::ComposeTransition methods.
DMUS_CURVE_FLAGS | Used in the bFlags member of the DMUS_CURVE_PMSG structure.
DMUS_EMBELLISHT_TYPES | Used in the wEmbellishment member of the DMUS_IO_PATTERN structure.
DMUS_NOTEF_FLAGS | Used in the bFlags member of the DMUS_NOTE_PMSG structure.
DMUS_PATTERNT_TYPES | Used in various command structures to control the way patterns are selected in sequential commands.
DMUS_PLAYMODE_FLAGS | Used in various structures to specify play modes.
DMUS_PMSGF_FLAGS | Used in the dwFlags member of the DMUS_PMSG structure.
DMUS_PMSGT_TYPES | Used in the dwType member of the DMUS_PMSG structure to identify the type of message.
DMUS_SEGF_FLAGS | Passed to various methods of IDirectMusicPerformance8 to control the timing and other aspects of actions on a segment.
DMUS_SHAPET_TYPES | Used in the wShape parameter of the IDirectMusicComposer8::ComposeSegmentFromShape and IDirectMusicComposer8::ComposeTemplateFromShape methods to specify the desired pattern of the groove level.
DMUS_STYLET_TYPES | Used in the IDirectMusicPatternTrack8::SetPatternByName and IDirectMusicStyle8::EnumPattern methods to specify a type of pattern.
DMUS_TIME_RESOLVE_FLAGS | Used in the dwFlags member of the DMUS_PMSG structure and in the dwTimeResolveFlags parameter of the IDirectMusicPerformance8::GetResolvedTime method.
DMUS_TRACKF_FLAGS | Used in the dwFlags parameter of the IDirectMusicTrack8::Play and IDirectMusicTrack8::PlayEx methods.
DMUS_VARIATIONT_TYPES | Used in the DMUS_IO_PARTREF structure to specify the way variations are selected in sequential commands.


DMUS_CHORDKEYF_FLAGS

The DMUS_CHORDKEYF_FLAGS enumerated type is used in the bFlags member of the DMUS_CHORD_KEY structure.

Syntax

typedef enum enumDMUS_CHORDKEYF_FLAGS {
  DMUS_CHORDKEYF_SILENT  = 1,
} DMUS_CHORDKEYF_FLAGS;

Constants

DMUS_CHORDKEYF_SILENT

The chord is silent.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_CLOCKTYPE

The DMUS_CLOCKTYPE enumerated type is used in the ctType member of the DMUS_CLOCKINFO8 structure.

Syntax

typedef enum {
  DMUS_CLOCK_SYSTEM = 0,
  DMUS_CLOCK_WAVE   = 1
} DMUS_CLOCKTYPE;

Constants

DMUS_CLOCK_SYSTEM

Clock is the system clock.

DMUS_CLOCK_WAVE

Clock is on a waveform-playback device.

Requirements

Header: Declared in dmusicc.h.

See Also

  • DirectMusic Enumerated Types


DMUS_COMMANDT_TYPES

The DMUS_COMMANDT_TYPES enumerated type is used in the wCommand parameter of the IDirectMusicComposer8::AutoTransition and IDirectMusicComposer8::ComposeTransition methods and in the bCommand member of the DMUS_COMMAND_PARAM structure.

Syntax

typedef enum enumDMUS_COMMANDT_TYPES {
  DMUS_COMMANDT_GROOVE      = 0,
  DMUS_COMMANDT_FILL        = 1,
  DMUS_COMMANDT_INTRO       = 2,
  DMUS_COMMANDT_BREAK       = 3,
  DMUS_COMMANDT_END         = 4,
  DMUS_COMMANDT_ENDANDINTRO = 5
} DMUS_COMMANDT_TYPES;

Constants

DMUS_COMMANDT_GROOVE

The command is a groove command.

DMUS_COMMANDT_FILL

The command is a fill.

DMUS_COMMANDT_INTRO

The command is an introduction.

DMUS_COMMANDT_BREAK

The command is a break.

DMUS_COMMANDT_END

The command is an ending.

DMUS_COMMANDT_ENDANDINTRO

The command is an ending and an introduction.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_COMPOSEF_FLAGS

The DMUS_COMPOSEF_FLAGS enumerated type is used in the dwFlags parameter of the IDirectMusicComposer8::ComposeTransition and IDirectMusicComposer8::AutoTransition methods.

Syntax

typedef enum enumDMUS_COMPOSEF_FLAGS {
  DMUS_COMPOSEF_NONE                =       0,
  DMUS_COMPOSEF_ALIGN               =      0x1,
  DMUS_COMPOSEF_OVERLAP             =      0x2,
  DMUS_COMPOSEF_IMMEDIATE           =      0x4,
  DMUS_COMPOSEF_GRID                =      0x8,
  DMUS_COMPOSEF_BEAT                =     0x10,
  DMUS_COMPOSEF_MEASURE             =     0x20,
  DMUS_COMPOSEF_AFTERPREPARETIME    =     0x40,
  DMUS_COMPOSEF_VALID_START_BEAT    =     0x80,
  DMUS_COMPOSEF_VALID_START_GRID    =    0x100,
  DMUS_COMPOSEF_VALID_START_TICK    =    0x200,
  DMUS_COMPOSEF_SEGMENTEND          =    0x400,
  DMUS_COMPOSEF_MARKER              =    0x800,
  DMUS_COMPOSEF_MODULATE            =   0x1000,
  DMUS_COMPOSEF_LONG                =   0x2000,
  DMUS_COMPOSEF_ENTIRE_TRANSITION   =   0x4000,
  DMUS_COMPOSEF_1BAR_TRANSITION     =   0x8000,
  DMUS_COMPOSEF_ENTIRE_ADDITION     =  0x10000,
  DMUS_COMPOSEF_1BAR_ADDITION       =  0x20000,
  DMUS_COMPOSEF_VALID_START_MEASURE =  0x40000,
  DMUS_COMPOSEF_DEFAULT             =  0x80000,
  DMUS_COMPOSEF_NOINVALIDATE        = 0x100000,
  DMUS_COMPOSEF_USE_AUDIOPATH       = 0x200000,
  DMUS_COMPOSEF_INVALIDATE_PRI      = 0x400000
}  DMUS_COMPOSEF_FLAGS;

Constants

DMUS_COMPOSEF_NONE

No flags. By default, the transition starts on a measure boundary.

DMUS_COMPOSEF_ALIGN

Align transition to the time signature of the currently playing segment.

DMUS_COMPOSEF_OVERLAP

Overlap the transition into pToSeg. Not implemented.

DMUS_COMPOSEF_IMMEDIATE

AutoTransition only. Start transition immediately.

DMUS_COMPOSEF_GRID

AutoTransition only. Start transition on a grid boundary.

DMUS_COMPOSEF_BEAT

AutoTransition only. Start transition on a beat boundary.

DMUS_COMPOSEF_MEASURE

AutoTransition only. Start transition on a measure boundary.

DMUS_COMPOSEF_AFTERPREPARETIME

AutoTransition only. Use the DMUS_SEGF_AFTERPREPARETIME flag when cueing the transition.

DMUS_COMPOSEF_VALID_START_BEAT

Allow the switch to occur on any beat. Used in conjunction with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_VALID_START_GRID

Allow the switch to occur on any grid. Used in conjunction with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_VALID_START_TICK

Allow the switch to occur at any time. Used in conjunction with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_SEGMENTEND

Play the transition at the end of the current segment.

DMUS_COMPOSEF_MARKER

Play the transition at the next marker in the current segment.

DMUS_COMPOSEF_MODULATE

Compose a transition that modulates smoothly from pFromSeg to pToSeg, using the chord of pToSeg.

DMUS_COMPOSEF_LONG

Composes a long transition. If this flag is not set, the length of the transition is at most one measure unless the wCommand parameter of ComposeTransition or AutoTransition specifies an ending and the style contains an ending of greater than one measure. If this flag is set, the length of the transition increases by one measure.

DMUS_COMPOSEF_ENTIRE_TRANSITION

Include the entire transition pattern.

DMUS_COMPOSEF_1BAR_TRANSITION

Include one bar of the transition pattern.

DMUS_COMPOSEF_ENTIRE_ADDITION

Include the additional transition pattern in its entirety. Used in combination with DMUS_COMPOSEF_LONG.

DMUS_COMPOSEF_1BAR_ADDITION

Include one bar of the additional transition pattern. This is the default behavior when DMUS_COMPOSEF_LONG is specified.

DMUS_COMPOSEF_VALID_START_MEASURE

Allow the switch to occur on any bar. Used in combination with DMUS_COMPOSEF_ALIGN.

DMUS_COMPOSEF_DEFAULT

Use the segment's default boundary.

DMUS_COMPOSEF_NOINVALIDATE

Do not invalidate segments that are playing.

DMUS_COMPOSEF_USE_AUDIOPATH

Use the audiopaths embedded in the segments.

DMUS_COMPOSEF_INVALIDATE_PRI

Invalidate only the primary segment when transitioning to a new segment.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types
  • DMUS_SEGF_FLAGS


DMUS_CURVE_FLAGS

The DMUS_CURVE_FLAGS enumerated type is used in the bFlags member of the DMUS_CURVE_PMSG structure.

Syntax

typedef enum enumDMUS_CURVE_FLAGS {
  DMUS_CURVE_RESET              = 1,
  DMUS_CURVE_START_FROM_CURRENT = 2,
} DMUS_CURVE_FLAGS;

Constants

DMUS_CURVE_RESET

The value of DMUS_CURVE_PMSG.nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If this flag is not set, the curve stays permanently at the new value.

DMUS_CURVE_START_FROM_CURRENT

Ignore DMUS_CURVE_PMSG.nStartValue and start the curve at the current value. This works only for volume, expression, and pitch bend.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_EMBELLISHT_TYPES

The DMUS_EMBELLISHMENT_TYPES enumerated type is used in the wEmbellishment member of the DMUS_IO_PATTERN structure.

Syntax

typedef enum enumDMUS_EMBELLISHT_TYPES {
    DMUS_EMBELLISHT_NORMAL =      0,
    DMUS_EMBELLISHT_FILL   =      1,
    DMUS_EMBELLISHT_BREAK  =      2,
    DMUS_EMBELLISHT_INTRO  =      4,
    DMUS_EMBELLISHT_END    =      8,
    DMUS_EMBELLISHT_MOTIF  =     16,
    DMUS_EMBELLISHT_ALL    = 0xFFFF
} DMUS_EMBELLISHT_TYPES;

Constants

DMUS_EMBELLISHT_NORMAL

Normal pattern.

DMUS_EMBELLISHT_FILL

Fill pattern.

DMUS_EMBELLISHT_BREAK

Break pattern.

DMUS_EMBELLISHT_INTRO

Intro pattern.

DMUS_EMBELLISHT_END

End pattern.

DMUS_EMBELLISHT_MOTIF

Motif pattern.

DMUS_EMBELLISHT_ALL

Combination of all types.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Enumerated Types


DMUS_NOTEF_FLAGS

The DMUS_NOTEF_FLAGS enumerated type is used in the bFlags member of the DMUS_NOTE_PMSG structure.

Syntax

typedef enum enumDMUS_NOTEF_FLAGS {
  DMUS_NOTEF_NOTEON               =    1,
  DMUS_NOTEF_NOINVALIDATE         =    2,
  DMUS_NOTEF_NOINVALIDATE_INSCALE =    4,
  DMUS_NOTEF_NOINVALIDATE_INCHORD =    8,
  DMUS_NOTEF_REGENERATE           = 0x10,
} DMUS_NOTEF_FLAGS;

Constants

DMUS_NOTEF_NOTEON

MIDI note-on. When a DMUS_NOTE_PMSG is first sent by the IDirectMusicPerformance8::SendPMsg method, this flag should be set. If the flag is not set, the message is a note-off.

DMUS_NOTEF_NOINVALIDATE

Do not invalidate the note.

DMUS_NOTEF_NOINVALIDATE_INSCALE

Do not invalidate if the note is still within the scale.

DMUS_NOTEF_NOINVALIDATE_INCHORD

Do not invalidate if the note is still within the chord.

DMUS_NOTEF_REGENERATE

Regenerate the note when a chord change occurs. The note's music value, subchord level, and play mode flags are used to construct a new note according to the new chord and scale. If the original note had a timing offset, this is applied to the start time of the new note.

Remarks

The NOINVALIDATE flags ensure that the note plays for its full duration even when messages are invalidated.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_PATTERNT_TYPES

The DMUS_PATTERNT_TYPES enumerated type is used in various command structures to control the way patterns are selected in sequential commands.

Syntax

typedef enum enumDMUS_PATTERNT_TYPES {
  DMUS_PATTERNT_RANDOM       = 0,
  DMUS_PATTERNT_REPEAT       = 1,
  DMUS_PATTERNT_SEQUENTIAL   = 2,
  DMUS_PATTERNT_RANDOM_START = 3,
  DMUS_PATTERNT_NO_REPEAT    = 4,
  DMUS_PATTERNT_RANDOM_ROW   = 5
} DMUS_PATTERNT_TYPES;

Constants

DMUS_PATTERNT_RANDOM

Select a random matching pattern. This is the behavior in versions prior to DirectX 8.0.

DMUS_PATTERNT_REPEAT

Repeat the last matching pattern.

DMUS_PATTERNT_SEQUENTIAL

Play matching patterns sequentially, in the order loaded, starting with the first.

DMUS_PATTERNT_RANDOM_START

Play matching patterns sequentially, in the order loaded, starting at a random point in the sequence.

DMUS_PATTERNT_NO_REPEAT

Play randomly, but do not play the same pattern twice.

DMUS_PATTERNT_RANDOM_ROW

Play randomly, but do not repeat any pattern until all have played.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Enumerated Types
  • DMUS_COMMAND_PARAM_2
  • DMUS_COMMAND_PARAM
  • DMUS_IO_COMMAND
  • DMUS_VARIATIONT_TYPES


DMUS_PLAYMODE_FLAGS

The DMUS_PLAYMODE_FLAGS enumerated type is used in various structures to specify play modes. The play mode determines how a music value is transposed to a MIDI note.

Syntax

typedef enum enumDMUS_PLAYMODE_FLAGS {
  DMUS_PLAYMODE_KEY_ROOT        =  1,
  DMUS_PLAYMODE_CHORD_ROOT      =  2,
  DMUS_PLAYMODE_SCALE_INTERVALS =  4,
  DMUS_PLAYMODE_CHORD_INTERVALS =  8,
  DMUS_PLAYMODE_NONE            = 16,
} DMUS_PLAYMODE_FLAGS;

Constants

DMUS_PLAYMODE_KEY_ROOT

Transpose over the key root.

DMUS_PLAYMODE_CHORD_ROOT

Transpose over the chord root.

DMUS_PLAYMODE_SCALE_INTERVALS

Use scale intervals from a scale pattern.

DMUS_PLAYMODE_CHORD_INTERVALS

Use chord intervals from a chord pattern.

DMUS_PLAYMODE_NONE

No mode. Indicates that the parent part's mode should be used.

Remarks

The following defined values represent combinations of play mode flags:

DMUS_PLAYMODE_ALWAYSPLAY

Combination of DMUS_PLAYMODE_SCALE_INTERVALS, DMUS_PLAYMODE_CHORD_INTERVALS, and DMUS_PLAYMODE_CHORD_ROOT. If it is desirable to play a note that is above the top of the chord, this mode finds a position for the note by using intervals from the scale. Essentially, this mode is a combination of the normal and melodic playback modes, in which a failure in normal mode causes a second try in melodic mode.

DMUS_PLAYMODE_FIXED

Interpret the music value as a MIDI value. This is defined as 0 and signifies the absence of other flags. This flag is used for drums, sound effects, and sequenced notes that should not be transposed by the chord or scale.

DMUS_PLAYMODE_FIXEDTOCHORD

Same as DMUS_PLAYMODE_CHORD_ROOT. The music value is a fixed MIDI value, but it is transposed over the chord root.

DMUS_PLAYMODE_FIXEDTOKEY

Same as DMUS_PLAYMODE_KEY_ROOT. The music value is a fixed MIDI value, but it is transposed over the key root.

DMUS_PLAYMODE_MELODIC

Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The chord root is used, but the notes track only the intervals in the scale. The key root and chord intervals are ignored. This is useful for melodic lines that play relative to the chord root.

DMUS_PLAYMODE_NORMALCHORD

Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_CHORD_INTERVALS. This is the prevalent playback mode. The notes track the intervals in the chord, which is based on the chord root. If the music value has a scale component, the additional intervals are pulled from the scale and added. If the chord does not have an interval to match the chord component of the music value, the note is silent.

DMUS_PLAYMODE_PEDALPOINT

Combination of DMUS_PLAYMODE_KEY_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The key root is used, and the notes track only the intervals in the scale. The chord root and intervals are ignored. This is useful for melodic lines that play relative to the key root.

DMUS_PLAYMODE_PEDALPOINTALWAYS

Combination of DMUS_PLAYMODE_PEDALPOINT and DMUS_PLAYMODE_PEDALPOINTCHORD. Chord intervals are used if possible; otherwise scale intervals are used.

DMUS_PLAYMODE_PEDALPOINTCHORD

Combination of DMUS_PLAYMODE_MELODIC and DMUS_PLAYMODE_NORMALCHORD. The key root is used and the notes track only the intervals in the chord. The chord root and scale intervals are completely ignored. This is useful for chordal lines that play relative to the key root.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types
  • DMUS_IO_STYLENOTE
  • DMUS_IO_STYLEPART
  • DMUS_NOTE_PMSG
  • IDirectMusicPerformance8::MIDIToMusic
  • IDirectMusicPerformance8::MusicToMIDI
  • Music Values and MIDI Notes


DMUS_PMSGF_FLAGS

The DMUS_PMSGF_FLAGS enumerated type is used in the dwFlags member of the DMUS_PMSG structure.

Syntax

typedef enum enumDMUS_PMSGF_FLAGS {
  DMUS_PMSGF_REFTIME    = 1,
  DMUS_PMSGF_MUSICTIME  = 2,
  DMUS_PMSGF_TOOL_IMMEDIATE = 4,
  DMUS_PMSGF_TOOL_QUEUE   = 8,
  DMUS_PMSGF_TOOL_ATTIME  = 0x10,
  DMUS_PMSGF_TOOL_FLUSH   = 0x20,
  DMUS_PMSGF_LOCKTOREFTIME  = 0x40,
  DMUS_PMSGF_DX8    = 0x80
} DMUS_PMSGF_FLAGS;

Constants

DMUS_PMSGF_REFTIME

The rtTime member is valid.

DMUS_PMSGF_MUSICTIME

The mtTime member is valid.

DMUS_PMSGF_TOOL_IMMEDIATE

Message should be processed immediately, regardless of its time stamp.

DMUS_PMSGF_TOOL_QUEUE

Message should be processed just before its time stamp, allowing for port latency.

DMUS_PMSGF_TOOL_ATTIME

Message should be processed at the time stamp.

DMUS_PMSGF_TOOL_FLUSH

Message is being flushed.

DMUS_PMSGF_LOCKTOREFTIME

Value in rtTime cannot be overridden by a tempo change.

DMUS_PMSGF_DX8

Message has valid members not present in versions prior to DirectX 8.0.

Requirements

Header: Declared in dmusici.h.

See Also

See Also

  • DirectMusic Enumerated Types
  • IDirectMusicPerformance8::SendPMsg
  • IDirectMusicTool8::GetMsgDeliveryType


DMUS_PMSGT_TYPES

The DMUS_PMSGT_TYPES enumerated type is used in the dwType member of the DMUS_PMSG structure to identify the type of message.

Syntax

typedef enum enumDMUS_PMSGT_TYPES {
  DMUS_PMSGT_MIDI     = 0,
  DMUS_PMSGT_NOTE     = 1,
  DMUS_PMSGT_SYSEX    = 2,
  DMUS_PMSGT_NOTIFICATION   = 3,
  DMUS_PMSGT_TEMPO    = 4,
  DMUS_PMSGT_CURVE    = 5,
  DMUS_PMSGT_TIMESIG    = 6,
  DMUS_PMSGT_PATCH    = 7,
  DMUS_PMSGT_TRANSPOSE    = 8,
  DMUS_PMSGT_CHANNEL_PRIORITY = 9,
  DMUS_PMSGT_STOP     = 10,
  DMUS_PMSGT_DIRTY    = 11,
  DMUS_PMSGT_WAVE     = 12,
  DMUS_PMSGT_LYRIC    = 13,
  DMUS_PMSGT_SCRIPTLYRIC  = 14,
  DMUS_PMSGT_USER     = 255
} DMUS_PMSGT_TYPES;

Constants

DMUS_PMSGT_MIDI

MIDI channel message. See DMUS_MIDI_PMSG.

DMUS_PMSGT_NOTE

Music note. See DMUS_NOTE_PMSG.

DMUS_PMSGT_SYSEX

MIDI system exclusive message. See DMUS_SYSEX_PMSG.

DMUS_PMSGT_NOTIFICATION

Notification message. See DMUS_NOTIFICATION_PMSG.

DMUS_PMSGT_TEMPO

Tempo message. See DMUS_TEMPO_PMSG.

DMUS_PMSGT_CURVE

Control change and pitch-bend curve. See DMUS_CURVE_PMSG.

DMUS_PMSGT_TIMESIG

Time signature. See DMUS_TIMESIG_PMSG.

DMUS_PMSGT_PATCH

Patch change. See DMUS_PATCH_PMSG.

DMUS_PMSGT_TRANSPOSE

Transposition. See DMUS_TRANSPOSE_PMSG.

DMUS_PMSGT_CHANNEL_PRIORITY

Channel priority change. See DMUS_CHANNEL_PRIORITY_PMSG.

DMUS_PMSGT_STOP

Stop message. See DMUS_PMSG.

DMUS_PMSGT_DIRTY

A control segment has started or ended. See DMUS_PMSG.

DMUS_PMSGT_WAVE

Control information for playing a waveform. See DMUS_WAVE_PMSG.

DMUS_PMSGT_LYRIC

Lyric message. See DMUS_LYRIC_PMSG.

DMUS_PMSGT_SCRIPTLYRIC

Lyric message sent by a script. See DMUS_LYRIC_PMSG.

DMUS_PMSGT_USER

User-defined message.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_SEGF_FLAGS

The DMUS_SEGF_FLAGS enumerated type is passed to various methods of IDirectMusicPerformance8 to control the timing and other aspects of actions on a segment.

Syntax

typedef enum enumDMUS_SEGF_FLAGS {
  DMUS_SEGF_REFTIME             = 1<<6,
  DMUS_SEGF_SECONDARY           = 1<<7,
  DMUS_SEGF_QUEUE               = 1<<8,
  DMUS_SEGF_CONTROL             = 1<<9,
  DMUS_SEGF_AFTERPREPARETIME    = 1<<10,
  DMUS_SEGF_GRID                = 1<<11,
  DMUS_SEGF_BEAT                = 1<<12,
  DMUS_SEGF_MEASURE             = 1<<13,
  DMUS_SEGF_DEFAULT             = 1<<14,
  DMUS_SEGF_NOINVALIDATE        = 1<<15,
  DMUS_SEGF_ALIGN               = 1<<16,
  DMUS_SEGF_VALID_START_BEAT    = 1<<17,
  DMUS_SEGF_VALID_START_GRID    = 1<<18,
  DMUS_SEGF_VALID_START_TICK    = 1<<19,
  DMUS_SEGF_AUTOTRANSITION      = 1<<20,
  DMUS_SEGF_AFTERQUEUETIME      = 1<<21,
  DMUS_SEGF_AFTERLATENCYTIME    = 1<<22,
  DMUS_SEGF_SEGMENTEND          = 1<<23,
  DMUS_SEGF_MARKER              = 1<<24,
  DMUS_SEGF_TIMESIG_ALWAYS      = 1<<25,
  DMUS_SEGF_USE_AUDIOPATH       = 1<<26,
  DMUS_SEGF_VALID_START_MEASURE = 1<<27,
  DMUS_SEGF_INVALIDATE_PRI      = 1<<28
} DMUS_SEGF_FLAGS;

Constants

DMUS_SEGF_REFTIME

Time parameter is in reference time.

DMUS_SEGF_SECONDARY

Secondary segment.

DMUS_SEGF_QUEUE

For a primary segment, play at the end of the primary segment queue. For a secondary segment, play at the end of the secondary segment specified in the pFrom parameter of IDirectMusicPerformance8::PlaySegmentEx.

DMUS_SEGF_CONTROL

Play as a control segment. Valid for secondary segments only. See Remarks.

DMUS_SEGF_AFTERPREPARETIME

Resolve time to a time after the prepare time. See IDirectMusicPerformance8::GetPrepareTime.

DMUS_SEGF_GRID

Resolve time to a grid boundary.

DMUS_SEGF_BEAT

Resolve time to a beat boundary.

DMUS_SEGF_MEASURE

Resolve time to a measure boundary.

DMUS_SEGF_DEFAULT

Use flags embedded in the segment. This resolves the time to the segment's default boundary and also causes the segment to play on its embedded audiopath, if it was configured to do so in the authoring application.

DMUS_SEGF_NOINVALIDATE

Setting this flag in IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx for a primary or control segment causes the new segment not to cause an invalidation. Without this flag, an invalidation occurs, cutting off and resetting any currently playing curve or note. This flag should be combined with DMUS_SEGF_AFTERPREPARETIME so that notes in the new segment do not play over notes played by the old segment.

DMUS_SEGF_ALIGN

The beginning of the segment can be aligned with a boundary, such as measure or beat, that has already passed. For this to happen, the segment must have a valid start point that falls before the next boundary. Start points can be defined in the segment, or one of the DMUS_SEGF_VALID_START_* flags can be used to define the granularity of valid start points. Any DMUS_SEGF_VALID_START_* flag takes effect only if a valid start point is not defined in the segment.

DMUS_SEGF_VALID_START_BEAT

Allow the start to occur on any beat. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_GRID

Allow the start to occur on any grid. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_TICK

Allow the start to occur at any time. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_AUTOTRANSITION

Compose and play a transition segment, using the transition template.

DMUS_SEGF_AFTERQUEUETIME

Resolve time to a time after the queue time. This is the default for primary segments. Ignored if DMUS_SEGF_AFTERPREPARETIME is also set.

DMUS_SEGF_AFTERLATENCYTIME

Resolve time to a time after the latency time. This is true for all segments, so this flag currently has no effect.

DMUS_SEGF_SEGMENTEND

Play at the end of the primary segment that is playing at the start time. If the new segment is being played as a primary segment, any primary segments already queued after the currently playing primary segment are flushed. If no primary segment is playing, use other resolution flags. When combined with DMUS_SEGF_ALIGN, this flag causes the beginning of the cued segment to be aligned with the beginning of the current primary segment.

DMUS_SEGF_MARKER

Resolve time to the next marker in the primary segment. If there are no markers, use other resolution flags.

DMUS_SEGF_TIMESIG_ALWAYS

Align start time with current time signature, even if there is no primary segment.

DMUS_SEGF_USE_AUDIOPATH

Use the audiopath embedded in the segment. Automatic downloading of bands must be enabled to ensure that the segment plays correctly.

DMUS_SEGF_VALID_START_MEASURE

Allow the start to occur at the beginning of a measure. Used in combination with DMUS_SEGF_ALIGN.

DMUS_SEGF_INVALIDATE_PRI

Invalidate only the primary segment when transitioning to a new segment.

Remarks

The primary segment is the default control segment. The DMUS_SEGF_CONTROL flag can be used to make a secondary segment the control segment. If the DMUS_SEGF_CONTROL flag is set, DMUS_SEGF_SECONDARY is assumed. For more information, see Control Segments.

No more than one flag from each of the following groups should be specified.

Boundary

This flag controls the point in the currently playing primary segment at which the start point of the cued segment falls. It can be combined with DMUS_SEGF_MARKER, in which case the boundary flag will be used only if no marker exists in the primary segment.

DMUS_SEGF_BEAT
DMUS_SEGF_DEFAULT
DMUS_SEGF_GRID
DMUS_SEGF_MEASURE
DMUS_SEGF_QUEUE
DMUS_SEGF_SEGMENTEND

Alignment

This flag controls the segment start time of the cued segment, when its play time falls in the past. It must be combined with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_BEAT
DMUS_SEGF_VALID_START_GRID
DMUS_SEGF_VALID_START_MEASURE
DMUS_SEGF_VALID_START_TICK

It is possible to combine one flag from each group. For example, combining DMUS_SEGF_MEASURE with DMUS_SEGF_ALIGN and DMUS_SEGF_VALID_START_BEAT causes the start point of the cued segment to fall at a measure boundary in the current primary segment. If this boundary has already passed, the cued segment starts playing at the next beat boundary within itself that is not aligned to a past time. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types
  • DMUS_TIME_RESOLVE_FLAGS
  • IDirectMusicPerformance8::Invalidate
  • IDirectMusicPerformance8::PlaySegment
  • IDirectMusicPerformance8::PlaySegmentEx
  • IDirectMusicPerformance8::Stop
  • IDirectMusicSegment8::GetDefaultResolution
  • IDirectMusicSegment8::SetDefaultResolution
  • Segment Timing


DMUS_SHAPET_TYPES

The DMUS_SHAPET_TYPES enumerated type is used in the wShape parameter of the IDirectMusicComposer8::ComposeSegmentFromShape and IDirectMusicComposer8::ComposeTemplateFromShape methods to specify the desired pattern of the groove level.

Syntax

typedef enum enumDMUS_SHAPET_TYPES {
  DMUS_SHAPET_FALLING  = 0,
  DMUS_SHAPET_LEVEL    = 1,
  DMUS_SHAPET_LOOPABLE = 2,
  DMUS_SHAPET_LOUD     = 3,
  DMUS_SHAPET_QUIET    = 4,
  DMUS_SHAPET_PEAKING  = 5,
  DMUS_SHAPET_RANDOM   = 6,
  DMUS_SHAPET_RISING   = 7,
  DMUS_SHAPET_SONG     = 8
} DMUS_SHAPET_TYPES;

Constants

DMUS_SHAPET_FALLING

Groove level falls.

DMUS_SHAPET_LEVEL

Groove level remains even.

DMUS_SHAPET_LOOPABLE

Segment is arranged to loop back to the beginning.

DMUS_SHAPET_LOUD

Groove level is high.

DMUS_SHAPET_QUIET

Groove level is low.

DMUS_SHAPET_PEAKING

Groove level rises to a peak, and then falls.

DMUS_SHAPET_RANDOM

Groove level is random.

DMUS_SHAPET_RISING

Groove level rises.

DMUS_SHAPET_SONG

Segment is in a song form. Several phrases of 6 to 8 bars are composed and put together to give a verse-chorus effect, with variations in groove level.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_STYLET_TYPES

The DMUS_STYLET_TYPES enumerated type is used in the IDirectMusicPatternTrack8::SetPatternByName and IDirectMusicStyle8::EnumPattern methods to specify a type of pattern.

Syntax

typedef enum enumDMUS_STYLET_TYPES {
  DMUS_STYLET_PATTERN  = 0,
  DMUS_STYLET_MOTIF    = 1,
} DMUS_STYLET_TYPES;

Constants

DMUS_STYLET_PATTERN

Normal pattern.

DMUS_STYLET_MOTIF

Motif pattern.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types


DMUS_TIME_RESOLVE_FLAGS

The DMUS_TIME_RESOLVE_FLAGS enumerated type is used in the dwFlags member of the DMUS_PMSG structure and in the dwTimeResolveFlags parameter of the IDirectMusicPerformance8::GetResolvedTime method.

Syntax

typedef enum enumDMUS_TIME_RESOLVE_FLAGS {
  DMUS_TIME_RESOLVE_AFTERPREPARETIME = DMUS_SEGF_AFTERPREPARETIME,
  DMUS_TIME_RESOLVE_AFTERQUEUETIME   = DMUS_SEGF_AFTERQUEUETIME,
  DMUS_TIME_RESOLVE_AFTERLATENCYTIME = DMUS_SEGF_AFTERLATENCYTIME,
  DMUS_TIME_RESOLVE_GRID             = DMUS_SEGF_GRID,
  DMUS_TIME_RESOLVE_BEAT             = DMUS_SEGF_BEAT,
  DMUS_TIME_RESOLVE_MEASURE          = DMUS_SEGF_MEASURE
  DMUS_TIME_RESOLVE_MARKER           = DMUS_SEGF_MARKER,
  DMUS_TIME_RESOLVE_SEGMENTEND       = DMUS_SEGF_SEGMENTEND,
} DMUS_TIME_RESOLVE_FLAGS;

Constants

DMUS_TIME_RESOLVE_AFTERPREPARETIME

Resolve to a time after the prepare time.

DMUS_TIME_RESOLVE_AFTERQUEUETIME

Resolve to a time after the queue time.

DMUS_TIME_RESOLVE_AFTERLATENCYTIME

Resolve to a time after the latency time.

DMUS_TIME_RESOLVE_GRID

Resolve to a time on a grid boundary.

DMUS_TIME_RESOLVE_BEAT

Resolve to a time on a beat boundary.

DMUS_TIME_RESOLVE_MEASURE

Resolve to a time on a measure boundary.

DMUS_TIME_RESOLVE_MARKER

Resolve to a marker.

DMUS_TIME_RESOLVE_SEGMENTEND

Resolve to the end of the segment.

Remarks

These flags can be used interchangeably with the corresponding DMUS_SEGF_FLAGS.

Requirements

Header: Declared in dmusici.h.

See Also

  • DirectMusic Enumerated Types
  • Timing


DMUS_TRACKF_FLAGS

The DMUS_TRACKF_FLAGS enumerated type is used in the dwFlags parameter of the IDirectMusicTrack8::Play and IDirectMusicTrack8::PlayEx methods.

Syntax

typedef enum enumDMUS_TRACKF_FLAGS {
  DMUS_TRACKF_SEEK   = 1,
  DMUS_TRACKF_LOOP   = 2,
  DMUS_TRACKF_START  = 4,
  DMUS_TRACKF_FLUSH  = 8,
  DMUS_TRACKF_DIRTY  = 0x10,
  DMUS_TRACKF_NOTIFY_OFF = 0x20,
  DMUS_TRACKF_PLAYOFF  = 0x40,
  DMUS_TRACKF_LOOPEND  = 0x80,
  DMUS_TRACKF_STOP   = 0x100,
  DMUS_TRACKF_RECOMPOSE  = 0x200,
  DMUS_TRACKF_CLOCK  = 0x400,
} DMUS_TRACKF_FLAGS;

Constants

DMUS_TRACKF_SEEK

IDirectMusicTrack8::Play was called in response to seeking, meaning that the mtStart parameter is not necessarily the same as the mtEnd of the previous call.

DMUS_TRACKF_LOOP

Play was called in response to a loop.

DMUS_TRACKF_START

This is the first call to IDirectMusicTrack8::Play. DMUS_TRACKF_SEEK can also be set if the track is not playing from the beginning.

DMUS_TRACKF_FLUSH

Play was called in response to a flush or invalidation that requires the track to replay something that it played previously. In this case, DMUS_TRACKF_SEEK is set, as well.

DMUS_TRACKF_DIRTY

A control segment has begun or ended. Tracks that normally wait until mtNext to call IDirectMusicTrack8::GetParam or IDirectMusicTrack8::GetParamEx should make the call right away, instead of waiting, because their data might now be invalid. For more information on setting control segments, see DMUS_SEGF_FLAGS.

DMUS_TRACKF_NOTIFY_OFF

Track is not to send notifications.

DMUS_TRACKF_PLAYOFF

Track is not to play, but can still send notifications.

DMUS_TRACKF_LOOPEND

End of range is also a loop end.

DMUS_TRACKF_STOP

End of range is also end of playing this segment.

DMUS_TRACKF_RECOMPOSE

Track should be recomposed on each loop. A signpost track is recomposed using a different chord progression, and a melody formulation track is recomposed using different melody fragments.

DMUS_TRACKF_CLOCK

Time parameters are in reference time. Valid only for IDirectMusicTrack8::PlayEx.

Remarks

When Play is called in response to a repeat, DMUS_TRACKF_LOOP and DMUS_TRACKF_SEEK are set.

To support invalidation, tracks must support seeking..

Requirements

Header: Declared in dmplugin.h.

See Also

  • DirectMusic Enumerated Types


DMUS_VARIATIONT_TYPES

The DMUS_VARIATIONT_TYPES enumerated type is used in the DMUS_IO_PARTREF structure to specify the way variations are selected in sequential commands.

Syntax

typedef enum enumDMUS_VARIATIONT_TYPES
{
  DMUS_VARIATIONT_SEQUENTIAL   = 0,
  DMUS_VARIATIONT_RANDOM       = 1,
  DMUS_VARIATIONT_RANDOM_START = 2,
  DMUS_VARIATIONT_NO_REPEAT    = 3,
  DMUS_VARIATIONT_RANDOM_ROW   = 4
} DMUS_VARIATIONT_TYPES;

Constants

DMUS_VARIATIONT_SEQUENTIAL

Play matching variations sequentially, in the order loaded, starting with the first.

DMUS_VARIATIONT_RANDOM

Select a random matching variation. This is the behavior in versions prior to DirectX 8.0.

DMUS_VARIATIONT_RANDOM_START

Play matching variations sequentially, in the order loaded, starting at a random point in the sequence.

DMUS_VARIATIONT_NO_REPEAT

Play randomly, but do not play the same variation twice.

DMUS_VARIATIONT_RANDOM_ROW

Play randomly, but do not repeat any variation until all have played.

Requirements

Header: Declared in dmusicf.h.

See Also

  • DirectMusic Enumerated Types
  • DMUS_COMMAND_PARAM_2
  • DMUS_COMMAND_PARAM
  • DMUS_IO_COMMAND
  • DMUS_PATTERNT_TYPES


DirectMusic GUIDs

This section lists globally unique identifiers used in DirectMusic. The following topics are covered:

  • DirectMusic Interface GUIDs
  • DirectMusic Component GUIDs


DirectMusic Interface GUIDs

The following GUIDs are used as interface identifiers (IIDs) to obtain DirectMusic interfaces.

IID | Interface
IID_IDirectMusic8 | IDirectMusic8
IID_IDirectMusicAudioPath8 | IDirectMusicAudioPath8
IID_IDirectMusicBand8 | IDirectMusicBand8
IID_IDirectMusicBuffer8 | IDirectMusicBuffer8
IID_IDirectMusicChordMap8 | IDirectMusicChordMap8
IID_IDirectMusicCollection8 | IDirectMusicCollection8
IID_IDirectMusicComposer8 | IDirectMusicComposer8
IID_IDirectMusicContainer8 | IDirectMusicContainer8
IID_IDirectMusicDownload8 | IDirectMusicDownload8
IID_IDirectMusicDownloadedInstrument8 | IDirectMusicDownloadedInstrument8
IID_IDirectMusicGetLoader8 | IDirectMusicGetLoader8
IID_IDirectMusicGraph8 | IDirectMusicGraph8
IID_IDirectMusicInstrument8 | IDirectMusicInstrument8
IID_IDirectMusicLoader8 | IDirectMusicLoader8
IID_IDirectMusicObject8 | IDirectMusicObject8
IID_IDirectMusicPatternTrack8 | IDirectMusicPatternTrack8
IID_IDirectMusicPerformance8 | IDirectMusicPerformance8
IID_IDirectMusicPort8 | IDirectMusicPort8
IID_IDirectMusicPortDownload8 | IDirectMusicPortDownload8
IID_IDirectMusicScript8 | IDirectMusicScript8
IID_IDirectMusicSegment8 | IDirectMusicSegment8
IID_IDirectMusicSegmentState8 | IDirectMusicSegmentState8
IID_IDirectMusicStyle8 | IDirectMusicStyle8
IID_IDirectMusicThru8 | IDirectMusicThru8
IID_IDirectMusicTool8 | IDirectMusicTool8
IID_IDirectMusicTrack8 | IDirectMusicTrack8
IID_IKsControl | IKsControl
IID_IReferenceClock | IReferenceClock

Note Where different versions of an interface are available, the identifier is shown only for the most recent one. Where an interface has not changed from previous versions of DirectX, the IID in the table is defined as the original IID. For example, IID_IDirectMusicInstrument8 is defined as IID_IDirectMusicInstrument in Dmusicc.h, because IDirectMusicInstrument8 is the same as IDirectMusicInstrument.

A few alternative identifiers, such as IID_IDirectMusicPerformance2, are defined for obtaining special implementations of interfaces. Most applications should not use these implementations.


DirectMusic Component GUIDs

The following GUIDS are used as class identifiers (CLSIDs) of DirectMusic components.

CLSID | Component
CLSID_DirectMusic | DirectMusic object
CLSID_DirectMusicAudioPathConfig | Audiopath configuration
CLSID_DirectMusicBand | Band
CLSID_DirectMusicBandTrack | Band track
CLSID_DirectMusicChordMap | Chordmap
CLSID_DirectMusicChordMapTrack | Chordmap track
CLSID_DirectMusicChordTrack | Chord track
CLSID_DirectMusicCollection | Collection
CLSID_DirectMusicCommandTrack | Command (groove) track
CLSID_DirectMusicComposer | Composer
CLSID_DirectMusicContainer | Container
CLSID_DirectMusicGraph | Toolgraph
CLSID_DirectMusicLoader | Loader
CLSID_DirectMusicLyricsTrack | Lyric track
CLSID_DirectMusicMarkerTrack | Marker track
CLSID_DirectMusicMotifTrack | Motif track
CLSID_DirectMusicMuteTrack | Mute track
CLSID_DirectMusicParamControlTrack | Parameter control track
CLSID_DirectMusicPatternTrack | Pattern track
CLSID_DirectMusicPerformance | Performance
CLSID_DirectMusicScript | Script
CLSID_DirectMusicScriptTrack | Script track
CLSID_DirectMusicSegment | Segment
CLSID_DirectMusicSegmentState | Segment state
CLSID_DirectMusicSegmentTriggerTrack | Segment trigger track
CLSID_DirectMusicSeqTrack | Sequence track
CLSID_DirectMusicSignPostTrack | Signpost track
CLSID_DirectMusicStyle | Style
CLSID_DirectMusicStyleTrack | Style track
CLSID_DirectMusicSynth | Synthesizer
CLSID_DirectMusicSysExTrack | Sysex track
CLSID_DirectMusicTempoTrack | Tempo track
CLSID_DirectMusicTimeSigTrack | Time signature track
CLSID_DirectMusicWaveTrack | Wave track
CLSID_DirectSoundWave | Wave


DirectMusic Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectMusic methods. For a list of the specific codes that each method can return, see the individual method descriptions. The lists given there are not necessarily comprehensive.

Error codes are presented in the following sections:

  • DirectMusic Return Values by Number
  • DirectMusic Return Values by Name


DirectMusic Return Values by Number

The following table lists DirectMusic return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | S_OK
0x00000001 | S_FALSE
0x08781091 | DMUS_S_PARTIALLOAD
0x08781092 | DMUS_S_PARTIALDOWNLOAD
0x08781200 | DMUS_S_REQUEUE
0x08781201 | DMUS_S_FREE
0x08781202 | DMUS_S_END
0x08781210 | DMUS_S_STRING_TRUNCATED
0x08781211 | DMUS_S_LAST_TOOL
0x08781212 | DMUS_S_OVER_CHORD
0x08781213 | DMUS_S_UP_OCTAVE
0x08781214 | DMUS_S_DOWN_OCTAVE
0x08781215 | DMUS_S_NOBUFFERCONTROL
0x08781216 | DMUS_S_GARBAGE_COLLECTED
0x80004001 | E_NOTIMPL
0x80004002 | E_NOINTERFACE
0x80004003 | E_POINTER
0x80040110 | CLASS_E_NOAGGREGATION
0x80040110 | CLASS_E_NOAGGREGATION
0x80040154 | REGDB_E_CLASSNOTREG
0x8007000E | E_OUTOFMEMORY
0x80070057 | E_FAIL
0x80070057 | E_INVALIDARG
0x88781101 | DMUS_E_DRIVER_FAILED
0x88781102 | DMUS_E_PORTS_OPEN
0x88781103 | DMUS_E_DEVICE_IN_USE
0x88781104 | DMUS_E_INSUFFICIENTBUFFER
0x88781105 | DMUS_E_BUFFERNOTSET
0x88781106 | DMUS_E_BUFFERNOTAVAILABLE
0x88781108 | DMUS_E_NOTADLSCOL
0x88781109 | DMUS_E_INVALIDOFFSET
0x88781111 | DMUS_E_ALREADY_LOADED
0x88781113 | DMUS_E_INVALIDPOS
0x88781114 | DMUS_E_INVALIDPATCH
0x88781115 | DMUS_E_CANNOTSEEK
0x88781116 | DMUS_E_CANNOTWRITE
0x88781117 | DMUS_E_CHUNKNOTFOUND
0x88781119 | DMUS_E_INVALID_DOWNLOADID
0x88781120 | DMUS_E_NOT_DOWNLOADED_TO_PORT
0x88781121 | DMUS_E_ALREADY_DOWNLOADED
0x88781122 | DMUS_E_UNKNOWNDOWNLOAD
0x88781123 | DMUS_E_SET_UNSUPPORTED
0x88781124 | DMUS_E_GET_UNSUPPORTED
0x88781125 | DMUS_E_NOTMONO
0x88781126 | DMUS_E_BADARTICULATION
0x88781127 | DMUS_E_BADINSTRUMENT
0x88781128 | DMUS_E_BADWAVELINK
0x88781128 | DMUS_E_BUFFER_EMPTY
0x88781129 | DMUS_E_NOARTICULATION
0x8878112A | DMUS_E_NOTPCM
0x8878112B | DMUS_E_BADWAVE
0x8878112C | DMUS_E_BADOFFSETTABLE
0x8878112D | DMUS_E_UNKNOWN_PROPERTY
0x8878112E | DMUS_E_NOSYNTHSINK
0x8878112F | DMUS_E_ALREADYOPEN
0x88781130 | DMUS_E_ALREADYCLOSED
0x88781131 | DMUS_E_SYNTHNOTCONFIGURED
0x88781132 | DMUS_E_SYNTHACTIVE
0x88781133 | DMUS_E_CANNOTREAD
0x88781134 | DMUS_E_DMUSIC_RELEASED
0x88781136 | DMUS_E_BUFFER_FULL
0x88781137 | DMUS_E_PORT_NOT_CAPTURE
0x88781138 | DMUS_E_PORT_NOT_RENDER
0x88781139 | DMUS_E_DSOUND_NOT_SET
0x8878113A | DMUS_E_ALREADY_ACTIVATED
0x8878113B | DMUS_E_INVALIDBUFFER
0x8878113C | DMUS_E_WAVEFORMATNOTSUPPORTED
0x8878113D | DMUS_E_SYNTHINACTIVE
0x8878113E | DMUS_E_DSOUND_ALREADY_SET
0x8878113F | DMUS_E_INVALID_EVENT
0x88781150 | DMUS_E_UNSUPPORTED_STREAM
0x88781151 | DMUS_E_ALREADY_INITED
0x88781152 | DMUS_E_INVALID_BAND
0x88781155 | DMUS_E_TRACK_HDR_NOT_FIRST_CK
0x88781156 | DMUS_E_TOOL_HDR_NOT_FIRST_CK
0x88781157 | DMUS_E_INVALID_TRACK_HDR
0x88781158 | DMUS_E_INVALID_TOOL_HDR
0x88781159 | DMUS_E_ALL_TOOLS_FAILED
0x88781160 | DMUS_E_ALL_TRACKS_FAILED
0x88781161 | DMUS_E_NOT_FOUND
0x88781162 | DMUS_E_NOT_INIT
0x88781163 | DMUS_E_TYPE_DISABLED
0x88781164 | DMUS_E_TYPE_UNSUPPORTED
0x88781165 | DMUS_E_TIME_PAST
0x88781166 | DMUS_E_TRACK_NOT_FOUND
0x88781167 | DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT
0x88781170 | DMUS_E_NO_MASTER_CLOCK
0x88781180 | DMUS_E_LOADER_NOCLASSID
0x88781181 | DMUS_E_LOADER_BADPATH
0x88781182 | DMUS_E_LOADER_FAILEDOPEN
0x88781183 | DMUS_E_LOADER_FORMATNOTSUPPORTED
0x88781184 | DMUS_E_LOADER_FAILEDCREATE
0x88781185 | DMUS_E_LOADER_OBJECTNOTFOUND
0x88781186 | DMUS_E_LOADER_NOFILENAME
0x88781200 | DMUS_E_INVALIDFILE
0x88781201 | DMUS_E_ALREADY_EXISTS
0x88781202 | DMUS_E_OUT_OF_RANGE
0x88781203 | DMUS_E_SEGMENT_INIT_FAILED
0x88781204 | DMUS_E_ALREADY_SENT
0x88781205 | DMUS_E_CANNOT_FREE
0x88781206 | DMUS_E_CANNOT_OPEN_PORT
0x88781207 | DMUS_E_CANNOT_CONVERT
0x88781210 | DMUS_E_DESCEND_CHUNK_FAIL
0x88781211 | DMUS_E_NOT_LOADED
0x88781213 | DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE
0x88781214 | DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
0x88781215 | DMUS_E_SCRIPT_ERROR_IN_SCRIPT
0x88781216 | DMUS_E_SCRIPT_CANTLOAD_OLEAUT32
0x88781217 | DMUS_E_SCRIPT_LOADSCRIPT_ERROR
0x88781218 | DMUS_E_SCRIPT_INVALID_FILE
0x88781219 | DMUS_E_INVALID_SCRIPTTRACK
0x8878121A | DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
0x8878121B | DMUS_E_SCRIPT_ROUTINE_NOT_FOUND
0x8878121C | DMUS_E_SCRIPT_CONTENT_READONLY
0x8878121D | DMUS_E_SCRIPT_NOT_A_REFERENCE
0x8878121E | DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED
0x88781220 | DMUS_E_INVALID_SEGMENTTRIGGERTRACK
0x88781221 | DMUS_E_INVALID_LYRICSTRACK
0x88781222 | DMUS_E_INVALID_PARAMCONTROLTRACK
0x88781223 | DMUS_E_AUDIOVBSCRIPT_SYNTAXERROR
0x88781224 | DMUS_E_AUDIOVBSCRIPT_RUNTIMEERROR
0x88781225 | DMUS_E_AUDIOVBSCRIPT_OPERATIONFAILURE
0x88781226 | DMUS_E_AUDIOPATHS_NOT_VALID
0x88781227 | DMUS_E_AUDIOPATHS_IN_USE
0x88781228 | DMUS_E_NO_AUDIOPATH_CONFIG
0x88781229 | DMUS_E_AUDIOPATH_INACTIVE
0x8878122A | DMUS_E_AUDIOPATH_NOBUFFER
0x8878122B | DMUS_E_AUDIOPATH_NOPORT
0x8878122C | DMUS_E_NO_AUDIOPATH
0x8878122D | DMUS_E_INVALIDCHUNK
0x8878122E | DMUS_E_AUDIOPATH_NOGLOBALFXBUFFER
0x8878122F | DMUS_E_INVALID_CONTAINER_OBJECT


DirectMusic Return Values by Name

The following list describes all DirectMusic return values. To find a constant from its value, see DirectMusic Return Values by Number.

CLASS_E_NOAGGREGATION

Aggregation is not supported. The LPUNKNOWN parameter should be set to NULL.

DMUS_E_ALL_TOOLS_FAILED

The graph object was unable to load all tools from the IStream object data, perhaps because of errors in the stream or because the tools are incorrectly registered on the client.

DMUS_E_ALL_TRACKS_FAILED

The segment object was unable to load all tracks from the IStream object data, perhaps because of errors in the stream or because the tracks are incorrectly registered on the client.

DMUS_E_ALREADY_ACTIVATED

The port has been activated, and the parameter cannot be changed.

DMUS_E_ALREADY_DOWNLOADED

The buffer has already been downloaded.

DMUS_E_ALREADY_EXISTS

The tool is already contained in the graph. You must create a new instance.

DMUS_E_ALREADY_INITED

The object has already been initialized.

DMUS_E_ALREADY_LOADED

A DLS collection is already open.

DMUS_E_ALREADY_SENT

The message has already been sent.

DMUS_E_ALREADYCLOSED

The port is not open.

DMUS_E_ALREADYOPEN

The port is already open.

DMUS_E_AUDIOPATH_INACTIVE

The audiopath is inactive, perhaps because the performance has been closed down.

DMUS_E_AUDIOPATH_NOBUFFER

The audiopath could not be created because a requested buffer could not be created.

DMUS_E_AUDIOPATH_NOGLOBALFXBUFFER

An attempt was made to create an audiopath that sends to a nonexistent global effects buffer.

DMUS_E_AUDIOPATH_NOPORT

The audiopath could not be used for playback because it lacked port assignments.

DMUS_E_AUDIOPATHS_IN_USE

The performance has set up audiopaths, so performance channels cannot be allocated.

DMUS_E_AUDIOPATHS_NOT_VALID

Performance channels have been set up by using IDirectMusicPerformance8::AssignPChannel, so the performance cannot support audiopaths.

DMUS_E_AUDIOVBSCRIPT_OPERATIONFAILURE

A script routine written in AudioVBScript failed because a function outside the script failed to complete.

DMUS_E_AUDIOVBSCRIPT_RUNTIMEERROR

A script routine written in AudioVBScript failed because an invalid operation occurred—for example, adding an integer to an object, or attempting to call a routine that does not exist.

DMUS_E_AUDIOVBSCRIPT_SYNTAXERROR

A script routine written in AudioVBScript could not be read because it contained a statement not allowed by the language.

DMUS_E_BADARTICULATION

Invalid articulation chunk in DLS collection.

DMUS_E_BADINSTRUMENT

Invalid instrument chunk in DLS collection.

DMUS_E_BADOFFSETTABLE

The offset table has errors.

DMUS_E_BADWAVE

Corrupt wave header.

DMUS_E_BADWAVELINK

The wave-link chunk in DLS collection points to invalid wave.

DMUS_E_BUFFER_EMPTY

There is no data in the buffer.

DMUS_E_BUFFER_FULL

The specified number of bytes exceeds the maximum buffer size.

DMUS_E_BUFFERNOTAVAILABLE

The buffer is not available for download.

DMUS_E_BUFFERNOTSET

No buffer was prepared for the data.

DMUS_E_CANNOT_CONVERT

The requested conversion between music and MIDI values could not be made. This usually occurs when the provided DMUS_CHORD_KEY structure has an invalid chord or scale pattern.

DMUS_E_CANNOT_FREE

The message could not be freed, either because it was not allocated or because it has already been freed.

DMUS_E_CANNOT_OPEN_PORT

The default system port could not be opened.

DMUS_E_CANNOTREAD

An error occurred when trying to read from the IStream object.

DMUS_E_CANNOTSEEK

The IStream object does not support Seek.

DMUS_E_CANNOTWRITE

The IStream object does not support Write.

DMUS_E_CHUNKNOTFOUND

A chunk with the specified header could not be found.

DMUS_E_DESCEND_CHUNK_FAIL

An attempt to descend into a chunk failed.

DMUS_E_DEVICE_IN_USE

The device is in use, possibly by a non-DirectMusic client, and cannot be opened again.

DMUS_E_DMUSIC_RELEASED

The operation cannot be performed because the final instance of the DirectMusic object was released. Ports cannot be used after final release of the DirectMusic object.

DMUS_E_DRIVER_FAILED

An unexpected error was returned from a device driver, indicating possible failure of the driver or hardware.

DMUS_E_DSOUND_ALREADY_SET

A DirectSound object has already been set.

DMUS_E_DSOUND_NOT_SET

The port could not be created because no DirectSound object has been specified.

DMUS_E_GET_UNSUPPORTED

Getting the parameter is not supported.

DMUS_E_INSUFFICIENTBUFFER

The buffer is not large enough for the requested operation.

DMUS_E_INVALID_BAND

The file does not contain a valid band.

DMUS_E_INVALID_CONTAINER_OBJECT

The file does not contain a valid container object.

DMUS_E_INVALID_DOWNLOADID

An invalid download identifier was used in the process of creating a download buffer.

DMUS_E_INVALID_EVENT

The event either is not a valid MIDI message or makes use of running status and cannot be packed into the buffer.

DMUS_E_INVALID_LYRICSTRACK

The file contains an invalid lyrics track.

DMUS_E_INVALID_PARAMCONTROLTRACK

The file contains an invalid parameter control track.

DMUS_E_INVALID_SCRIPTTRACK

The file contains an invalid script track.

DMUS_E_INVALID_SEGMENTTRIGGERTRACK

The file contains an invalid segment trigger track.

DMUS_E_INVALID_TOOL_HDR

The IStream object's data contains an invalid tool header and cannot be read by the graph object.

DMUS_E_INVALID_TRACK_HDR

The IStream object's data contains an invalid track header and cannot be read by the segment object.

DMUS_E_INVALIDBUFFER

An invalid DirectSound buffer was handed to a port.

DMUS_E_INVALIDCHUNK

Invalid data was found in a RIFF file chunk.

DMUS_E_INVALIDFILE

Not a valid file.

DMUS_E_INVALIDOFFSET

Wave chunks in the DLS collection file are at incorrect offsets.

DMUS_E_INVALIDPATCH

No instrument in the collection matches the patch number.

DMUS_E_INVALIDPOS

Error reading wave data from a DLS collection. Indicates bad file.

DMUS_E_LOADER_BADPATH

The file path is invalid.

DMUS_E_LOADER_FAILEDCREATE

The object could not be found or created.

DMUS_E_LOADER_FAILEDOPEN

File open failed because the file does not exist or is locked.

DMUS_E_LOADER_FORMATNOTSUPPORTED

The object cannot be loaded because the data format is not supported.

DMUS_E_LOADER_NOCLASSID

No class identifier was supplied in the object description.

DMUS_E_LOADER_NOFILENAME

No file name was supplied in the object description.

DMUS_E_LOADER_OBJECTNOTFOUND

The object was not found.

DMUS_E_NO_AUDIOPATH

An attempt was made to play on a nonexistent audiopath.

DMUS_E_NO_AUDIOPATH_CONFIG

The object does not contain an embedded audiopath configuration.

DMUS_E_NO_MASTER_CLOCK

There is no master clock in the performance. Be sure to call the IDirectMusicPerformance8::Init method.

DMUS_E_NOARTICULATION

Articulation missing from an instrument in the DLS collection.

DMUS_E_NOSYNTHSINK

No sink is connected to the synthesizer.

DMUS_E_NOT_DOWNLOADED_TO_PORT

The object cannot be unloaded because it is not present on the port.

DMUS_E_NOT_FOUND

The requested item is not contained by the object.

DMUS_E_NOT_INIT

A required object is not initialized or failed to initialize.

DMUS_E_NOT_LOADED

An attempt to use this object failed because it was not loaded.

DMUS_E_NOTADLSCOL

The object being loaded is not a valid DLS collection.

DMUS_E_NOTMONO

The wave chunk has more than one interleaved channel. DLS format requires mono.

DMUS_E_NOTPCM

Waveform data is not in PCM format.

DMUS_E_OUT_OF_RANGE

The requested time is outside the range of the segment.

DMUS_E_PORT_NOT_CAPTURE

The port is not a capture port.

DMUS_E_PORT_NOT_RENDER

The port is not an output port.

DMUS_E_PORTS_OPEN

The requested operation cannot be performed while there are instantiated ports in any process in the system.

DMUS_E_SCRIPT_CANTLOAD_OLEAUT32

Loading of Oleaut32.dll failed. ActiveX scripting languages require use of oleaut32.dll. On platforms where this file is not present, only the AudioVBScript language can be used.

DMUS_E_SCRIPT_CONTENT_READONLY

Script variables for content referenced or embedded in a script cannot be set.

DMUS_E_SCRIPT_ERROR_IN_SCRIPT

An error was encountered while parsing or executing the script.

DMUS_E_SCRIPT_INVALID_FILE

The script file is invalid.

DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE

The ActiveX scripting engine for the script's language is not compatible with DirectMusic.

DMUS_E_SCRIPT_LOADSCRIPT_ERROR

The script that was loaded contains an error.

DMUS_E_SCRIPT_NOT_A_REFERENCE

An attempt was made to set a script's variable by reference to a value that is not an object type.

DMUS_E_SCRIPT_ROUTINE_NOT_FOUND

The script does not contain a routine with the specified name.

DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE

A variant was used that had a type not supported by DirectMusic.

DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED

An attempt was made to set a script's variable by value to an object that does not support a default value property.

DMUS_E_SCRIPT_VARIABLE_NOT_FOUND

The script does not contain a variable with the specified name.

DMUS_E_SEGMENT_INIT_FAILED

Segment initialization failed, probably because of a critical memory situation.

DMUS_E_SET_UNSUPPORTED

Setting the parameter is not supported.

DMUS_E_SYNTHACTIVE

The synthesizer has been activated, and the parameter cannot be changed.

DMUS_E_SYNTHINACTIVE

The synthesizer has not been activated and cannot process data.

DMUS_E_SYNTHNOTCONFIGURED

The synthesizer is not properly configured or opened.

DMUS_E_TIME_PAST

The time requested is in the past.

DMUS_E_TOOL_HDR_NOT_FIRST_CK

The stream object's data does not have a tool header as the first chunk and, therefore, cannot be read by the graph object.

DMUS_E_TRACK_HDR_NOT_FIRST_CK

The stream object's data does not have a track header as the first chunk and, therefore, cannot be read by the segment object.

DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT

The track does not support clock-time playback or parameter retrieval.

DMUS_E_TRACK_NOT_FOUND

There is no track of the requested type.

DMUS_E_TYPE_DISABLED

A track parameter is unavailable because it has been disabled.

DMUS_E_TYPE_UNSUPPORTED

Parameter is unsupported on this track.

DMUS_E_UNKNOWN_PROPERTY

The property set or item is not implemented by this port.

DMUS_E_UNKNOWNDOWNLOAD

The synthesizer does not support this type of download.

DMUS_E_UNSUPPORTED_STREAM

The IStream object does not contain data supported by the loading object.

DMUS_E_WAVEFORMATNOTSUPPORTED

Invalid buffer format was handed to the synthesizer sink.

DMUS_S_DOWN_OCTAVE

The note has been lowered by one or more octaves to fit within the range of MIDI values.

DMUS_S_END

The operation succeeded and reached the end of the data.

DMUS_S_FREE

The allocated memory should be freed.

DMUS_S_GARBAGE_COLLECTED

The requested operation was not performed because the object has been released.

DMUS_S_LAST_TOOL

There are no more tools in the graph.

DMUS_S_NOBUFFERCONTROL

Although the audio output from the port is routed to the same device as the given DirectSound buffer, buffer controls such as pan and volume do not affect the output.

DMUS_S_OVER_CHORD

No MIDI values have been calculated because the music value has the note at a position higher than the top note of the chord.

DMUS_S_PARTIALDOWNLOAD

Some instruments could not be downloaded to the port.

DMUS_S_PARTIALLOAD

The object could only load partially. This can happen if some components, such as embedded tracks and tools, are not registered properly. It can also happen if some content is missing; for example, if a segment uses a DLS collection that is not in the loader's current search directory.

DMUS_S_REQUEUE

The message should be passed to the next tool.

DMUS_S_STRING_TRUNCATED

The method succeeded, but the returned string was truncated.

DMUS_S_UP_OCTAVE

The note has been raised by one or more octaves to fit within the range of MIDI values.

E_FAIL

The method did not succeed.

E_INVALIDARG

Invalid argument. Often, this error results from failing to initialize the dwSize member of a structure before passing it to the method.

E_NOINTERFACE

No object interface is available.

E_NOTIMPL

The method is not implemented. This value might be returned if a driver does not support a feature necessary for the operation.

E_OUTOFMEMORY

Insufficient memory to complete the task.

E_POINTER

An invalid pointer, usually NULL, was passed as a parameter.

REGDB_E_CLASSNOTREG

The object class is not registered.

S_FALSE

The method succeeded, but there was nothing to do.

S_OK

The operation was completed successfully.


DirectSound

This section provides information about using Microsoft® DirectSound® to play and capture sounds in applications written in C and C++.

Information is presented in the following sections:

  • What's New in DirectSound. A guide to new features of DirectSound in Microsoft DirectX® 9.0.
  • Introduction to DirectSound. An overview of what DirectSound is and what it can do for your application, a comparison of DirectSound and Microsoft DirectMusic®, and a brief first look at the steps your application must take to play sounds.
  • Getting Started with DirectSound. Information on setting up and debugging DirectSound projects.
  • Using DirectSound. A guide to using the application programming interface (API). You'll probably want to familiarize yourself with the table of contents for this section, and then refer to parts of it as you need specific information. It should be used in conjunction with the reference section.
  • Advanced Topics in DirectSound. Information of interest mostly for developing specialized applications or applications that need highly optimized performance.
  • DirectSound C++ Samples. A guide to the sample applications in the SDK, to point you to the sample code you need. As well as showing how to implement basic functionality, each sample demonstrates one or more particular features of DirectSound.
  • DirectSound C/C++ Reference. Detailed information about all the API elements declared in Dsound.h.


What's New in DirectSound

The DirectSound application programming interface (API) has not been significantly revised for DirectX 9.0. However, many performance enhancements have been implemented.

In addition, the following changes have been made:

  • The maximum frequency of sound buffers has been increased from 100 kHz to 200 kHz, where supported by the operating system. (These higher frequencies are not supported by DirectShow.)
  • Frequency and effects controls (DSBCAPS_CTRLFREQUENCY and DSBCAPS_CRTLFX) can now be combined on buffers. Combining these flags makes it possible to have Doppler shift on buffers with effects.
  • Audio formats described by the WAVEFORMATEXTENSIBLE structure are fully supported throughout DirectSound.
  • The standard effect DMOs can process audio data in WAVE_FORMAT_IEEE_FLOAT format.
  • The standard effects support parameter curves (when hosted outside of DirectSound) without having to call IMediaObjectInPlace::Process on them repeatedly in very small increments.


Introduction to DirectSound

This section provides a quick overview of the capabilities of DirectSound and what you need to do to get started with the API. Information is presented in the following sections:

  • The Power of DirectSound
  • DirectSound and DirectMusic


The Power of DirectSound

DirectSound enables the playing of sounds with very low latency and gives applications a high level of control over hardware resources.

By using the DirectSound interfaces in your application, you can do the following:

  • Play sounds from files or resources in WAV format.
  • Play multiple sounds simultaneously.
  • Assign high-priority sounds to hardware-controlled buffers.
  • Locate sounds in a customizable 3-D environment.
  • Add effects such as echo and chorus, and change effect parameters dynamically.
  • Capture WAV sounds from a microphone or other input.

DirectSound works on Microsoft® Windows® 98, Microsoft® Windows® 2000, and later operating systems. Some functionality, chiefly capture effects, is available only on Microsoft Windows XP and later.

See Also

  • DirectSound and DirectMusic


DirectSound and DirectMusic

DirectSound and DirectMusic are separate components of DirectX with some overlapping functionality. Both play WAV sounds, and DirectMusic ultimately synthesizes all sounds into waveforms that are played through DirectSound buffers.

DirectMusic is a much more full-featured API that offers a complete solution for most audio scenarios in games and other interactive applications. Despite its name, DirectMusic plays all kinds of sounds including nonmusical sound effects. DirectSound is the API of choice for scenarios that require low-level management of hardware resources, such as games with many short sounds that must be played with the lowest possible latency and use of system resources.

You can use the DirectSound API independently to play WAV sounds, even in applications that use DirectMusic to play other content. You can also use DirectSound to manipulate sound buffers that are managed by DirectMusic. For example, you can obtain a DirectSound buffer from a DirectMusic audiopath and move it in 3-D space.

The following table summarizes the functionality offered by the two APIs.

Functionality | DirectMusic | DirectSound
Play WAV sounds | Yes | Yes
Play MIDI | Yes | No
Play DirectMusic Producer segments | Yes | No
Load content files and manage objects | Yes | No, but some support in sample code
Control musical parameters at run time | Yes | No
Manage timeline for cuing sounds | Yes | No
Use downloadable sounds (DLS) | Yes | No
Set volume, pitch, and pan of individual sounds | Yes, through DirectSound API | Yes
Set volume on multiple sounds (audiopaths) | Yes | No
Implement 3-D sounds | Yes, through DirectSound API | Yes
Apply effects (DMOs) | Yes, through DirectMusic Producer content or DirectSound API | Yes
Chain buffers for mix-in (send) effects | Yes, through DirectMusic Producer content | No
Capture WAV sounds | No | Yes
Implement full duplex | No | Yes
Capture MIDI | Yes | No
Control allocation of hardware buffers | No | Yes


Getting Started with DirectSound

This section gives information on setting up and debugging DirectSound projects, as well as a brief overview of the programming steps required to play a sound.

More information on getting started is included in the following topics:

  • Building DirectSound Projects
  • Debugging DirectSound Projects
  • Adjusting DirectSound Acceleration for Testing
  • First Steps in DirectSound Programming


Building DirectSound Projects

Projects need to include the Dsound.h header file. If you are using DirectSound in conjunction with DirectMusic, this header is included when you include Dmusici.h.

If you are using the DirectSound API directly and want to be able to use helper functions such as DirectSoundCreate8, be sure to link to Dsound.lib and include the appropriate folder in the library search path.

You must also ensure that your application has access to the GUIDs used by DirectSound. Define INITGUID before all other preprocessor directives, or link to Dxguid.lib.


Debugging DirectSound Projects

The DirectSound dynamic-link library (DLL) installed with the debug version of the DirectX software development kit generates information in the debug output window as the application is running.

You can set the debug level within the range from 0 to 5 by using the Debug Output Level slider on the DirectSound page of the DirectX Properties in Control Panel. A setting of 0 produces no debugging information, and 5 produces the most detail. For most purposes it is unnecessary to set the level higher than 2; output at higher levels does not pertain to errors or warnings but is purely informational.


Adjusting DirectSound Acceleration for Testing

By using the Sounds and Audio Devices page in Control Panel, you can adjust the performance of DirectSound on the system. Click the Advanced button in the Sound Playback group on the Audio tab. In the Advanced Audio Properties dialog box, choose the Performance tab. A slider lets you adjust hardware acceleration to one of the following settings:

Full

Enables complete DirectSound acceleration, including the enabling of IKsPropertySet extensions.

Standard

Enables acceleration of DirectSound secondary buffers, but disables any hardware-specific IKsPropertySet extensions. This is the default setting on Windows 2000.

Basic

Disables hardware acceleration of DirectSound secondary buffers. This option is useful if you want to emulate a nonaccelerated sound card for testing purposes.

Emulation

Forces DirectSound into emulation mode, where it acts as if there is no DirectSound-compatible driver on the system. All mixing is done by DirectSound in user mode, and the resulting data is sent to the Win32 waveform-audio functions. This typically results in a large increase in latency.


First Steps in DirectSound Programming

This topic provides a brief overview of the steps you must take to play a sound by using the DirectSound API. For details, see Using DirectSound.

Playing a short sound requires the following steps:

1. Create a device object

Call DirectSoundCreate8 to create an object that supports the IDirectSound8 interface. This object usually represents the default playback device. Optionally, you can first enumerate available devices to obtain the GUID of the device you want to use, and pass this to DirectSoundCreate8.

Note DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly unless you are using effect DMOs.

2. Create a secondary buffer

Use IDirectSound8::CreateSoundBuffer to create a buffer object that will contain sound data. Such buffers are called secondary buffers, to distinguish them from the primary buffer, which is the object that mixes all sounds.

3. Obtain PCM data

Read data from a WAV file or resource into a private buffer. The DirectX SDK contains sample code that you can use to do this.

4. Put data in the buffer

Prepare the secondary buffer for a write operation by calling IDirectSoundBuffer8::Lock. In most cases, this method returns a single memory address. Copy data from your private buffer to that address, and then call IDirectSoundBuffer8::Unlock.

5. Play the buffer

Play the sound by calling IDirectSoundBuffer8::Play. You can instruct the buffer either to stop when it reaches the end, or to continue playing over and over again until you call IDirectSoundBuffer8::Stop. You can start and stop the buffer repeatedly; however, only one instance of the sound can play at one time, unless you create other buffers containing the same data. Any number of buffers can be played at a given time, and mixing is done automatically.

The preceding steps apply to the simplest possible scenario, that of a short sound that fits into a buffer of a reasonable size. Typically, sounds that last more than a few seconds are streamed: that is, data that has already been played is periodically replaced by new data.

Sample code distributed with the SDK shows how to perform many common tasks using DirectSound. For more information, see DirectSound C++ Samples.


Using DirectSound

This section is a guide to using the Microsoft® DirectSound® application programming interface (API) in application development.

Information is presented in the following topics:

  • DirectSound Playback Objects
  • DirectSound Devices
  • DirectSound Buffers
  • Using WAV Data
  • 3-D Sound
  • Using Effects
  • Capturing Waveforms

See Also

  • Introduction to DirectSound
  • Advanced Topics in DirectSound
  • DirectSound C/C++ Reference


DirectSound Playback Objects

The following objects are used in playing sounds:

Object | Number | Purpose | Main interfaces
Device | One in each application | Manages the device and creates sound buffers. | IDirectSound8
Secondary buffer | One for each sound | Manages a static or streaming sound and plays it into the primary buffer. | IDirectSoundBuffer8, IDirectSound3DBuffer8, IDirectSoundNotify8
Primary buffer | One in each application | Mixes and plays sounds from secondary buffers, and controls global 3-D parameters. | IDirectSoundBuffer, IDirectSound3DListener8
Effect | Zero or more for each secondary buffer | Transforms the sound in a secondary buffer. | Interface for the particular effect, such as IDirectSoundFXChorus8

The first step in implementing DirectSound in an application is to create a device object, which represents the rendering device. This object is then used to create buffers.

Note DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly, by calling CoInitialize or CoInitializeEx, unless you are using effect DMOs.

Secondary buffers are created and managed by the application. DirectSound automatically creates and manages the primary buffer, and an application can play sounds without obtaining an interface to this object. However, in order to obtain the IDirectSound3DListener8 interface, the application must explicitly create a primary buffer object.

When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the rendering device. Only the available processing time limits the number of buffers that DirectSound can mix.

Note Under the Windows driver model (WDM), mixing is done by the kernel mixer, and the primary buffer does not actually contain any data. For more information, see DirectSound Driver Models.

A short sound can be loaded into a secondary buffer in its entirety and played at any time by a simple method call. Longer sounds have to be streamed. An application can ascertain when it is time to stream more data into the buffer either by polling the position of the play cursor or by requesting notification when the play cursor reaches certain points.

Secondary buffers can contain effects such as chorus and echo. They can also have 3-D control capabilities. Global 3-D parameters are controlled by the IDirectSound3DListener8 interface on the primary buffer.


DirectSound Devices

The DirectSound device object represents a rendering device and is used to manage the device and to create sound buffers.

Multiple applications can create objects for the same sound device. When the input focus changes between applications, the audio output automatically switches from one application's streams to the other's. As a result, applications do not have to repeatedly play and stop their buffers when the input focus changes.

This section describes how your application can enumerate available sound devices, create the device object, and use the IDirectSound8 methods of the object to manage the device. The following topics are covered:

  • Enumerating Sound Devices
  • Creating the Device Object
  • Cooperative Levels
  • Device Capabilities
  • Speaker Configuration


Enumerating Sound Devices

If your application is simply going to play sounds through the user's preferred playback device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCreate8 function, you can specify a default device. For more information, see Creating the Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

The following callback function adds the name of each enumerated device to a combo box and stores its GUID as the item data. Values for the first three parameters are supplied by the device driver. The fourth parameter is passed on from the DirectSoundEnumerate function; this parameter can be used to pass any 32-bit value, and in this case is the window handle of the combo box. Macros defined in Windowsx.h are used to add strings and data to the combo box.

BOOL CALLBACK DSEnumProc(LPGUID lpGUID,
         LPCTSTR lpszDesc,
         LPCTSTR lpszDrvName,
         LPVOID lpContext )
{
  HWND hCombo = (HWND)lpContext;
  LPGUID lpTemp = NULL;

  if (lpGUID != NULL)  //  NULL only for "Primary Sound Driver".
  {
    if ((lpTemp = (LPGUID)malloc(sizeof(GUID))) == NULL)
    {
        return(TRUE);
    }
    memcpy(lpTemp, lpGUID, sizeof(GUID));
  }

  ComboBox_AddString(hCombo, lpszDesc);
  ComboBox_SetItemData(hCombo,
      ComboBox_FindString(hCombo, 0, lpszDesc),
      lpTemp );
  free(lpTemp);
  return(TRUE);
}

The enumeration is set in motion when the dialog box containing the combo box is initialized. Assume that hCombo is the handle of the combo box and hDlg is the handle of the dialog box.

if (FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,
    (VOID*)&hCombo)))
{
  EndDialog(hDlg, TRUE);
  return(TRUE);
}

In this case, the address of the combo box handle is passed into DirectSoundEnumerate, which in turn passes it to the callback function. This parameter can be any 32-bit value that you want to have access to within the callback.

Note The first device enumerated is always called the Primary Sound Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred playback device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Driver" to a list when presenting the user with a choice of devices. The primary device is also enumerated with its proper name and GUID.


Creating the Device Object

The simplest way to create the device object is by using the DirectSoundCreate8 function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by enumerating devices, or you can pass one of the following GUIDs to specify a default device:

GUID definition | Description
DSDEVID_DefaultPlayback | The default system audio device. You can also specify this device by passing a NULL pointer in the device GUID parameter. The default device is the one enumerated as "Primary DirectSound Driver".
DSDEVID_DefaultVoicePlayback | The default voice communications device. Typically this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call to DirectSoundCreate8 fails.

The function returns an error if there is no sound device or, under VXD drivers, if the sound device is under the control of an application using the standard Win32 waveform-audio functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.

The following code creates an object for the default device and obtains the IDirectSound8 interface:

LPDIRECTSOUND8 lpds;
HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));

Note DirectSoundCreate8 does not cause CoInitialize or CoInitializeEx to be called. If your application uses effect DMOs, it must initialize COM explicitly before creating any objects.

If your application will capture sounds as well as play them, you can conveniently create both rendering and capture devices, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.

You can also create the device object by using standard COM functions, as follows.

  1. Initialize COM at the start of your application by calling CoInitializeEx.
    HRESULT hr = CoInitializeEx(NULL, 0);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}
  2. Create the device object by using CoCreateInstance and the IDirectSound8::Initialize method, rather than the DirectSoundCreate8 function.
    LPDIRECTSOUND8 lpds;
hr = CoCreateInstance(&CLSID_DirectSound8,
          NULL,
          CLSCTX_INPROC_SERVER,
          IID_IDirectSound8,
          (LPVOID*) &lpds);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

    CLSID_DirectSound8 is the class identifier of the DirectSound driver object class and IID_IDirectSound8 is the interface identifier. The lpds parameter receives the interface pointer.

  3. Call the IDirectSound8::Initialize method to associate the object with a device. This method takes the same device GUID parameter that DirectSoundCreate8 uses.
    hr = lpds->Initialize(NULL);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}
  4. Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
    CoUninitialize();


Cooperative Levels

Because Windows is a multitasking environment, more than one application can be working with a device driver at any one time. Through the use of cooperative levels, DirectX makes sure that each application does not gain access to the device in the wrong way or at the wrong time. Each DirectSound application has a cooperative level that determines the extent to which it is allowed to access the device.

After creating a device object, you must set the cooperative level for the device by using the IDirectSound8::SetCooperativeLevel method. Unless you do this, no sounds will be heard.

The following example sets the cooperative level for the DirectSound device represented by the IDirectSound8 interface at lpDirectSound. The hwnd parameter is the handle to the application window.

HRESULT hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

DirectSound defines three cooperative levels for sound devices, specified by the values DSSCL_NORMAL, DSSCL_PRIORITY, and DSSCL_WRITEPRIMARY. These levels are explained in the following topics:

  • Normal Cooperative Level
  • Priority Cooperative Level
  • Write-primary Cooperative Level

Note The DSSCL_EXCLUSIVE cooperative level is obsolete. It is no longer possible for a DirectX application to mute other applications. Applications that request the exclusive level are granted the priority level instead.


Normal Cooperative Level

At the normal cooperative level (DSSCL_NORMAL), the application cannot set the format of the primary buffer, write to the primary buffer, or compact the on-board memory of the device. All applications at this cooperative level use a primary buffer format of 22 kHz, stereo sound, and 8-bit samples, so that the device can switch between applications as smoothly as possible.


Priority Cooperative Level

When using a DirectSound device with the priority cooperative level (DSSCL_PRIORITY), the application has first rights to hardware resources, such as hardware mixing, and can set the format of the primary sound buffer and compact the on-board memory of the device.

Game applications should use the priority cooperative level in almost all circumstances. This level gives the most robust behavior while allowing the application control over sampling rate and bit depth. The priority cooperative level also allows audio from other applications, such as IP telephony, to be heard along with the audio from the game.


Write-primary Cooperative Level

The highest cooperative level is write-primary (DSSCL_WRITEPRIMARY). When using a DirectSound device with this cooperative level, your application has direct access to the primary sound buffer on non-WDM drivers. In this mode, the application must write directly to the primary buffer. Secondary buffers cannot be played while this is happening.

An application must be set to the write-primary level in order to obtain direct write access to the audio samples in the primary buffer. If the application is not set to this level, then all calls to the IDirectSoundBuffer::Lock method on the primary buffer will fail.

Note The primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

When your application is set to the write-primary cooperative level and gains the foreground, all secondary buffers for other applications are stopped and marked as lost. When your application in turn moves to the background, its primary buffer is marked as lost and must be restored when the application again moves to the foreground. For more information, see Buffer Management.

You cannot set the write-primary cooperative level if a DirectSound driver is not present on the user's system. To determine whether this is the case, call the IDirectSound8::GetCaps method and check for the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

See Also

  • Writing to the Primary Buffer


Device Capabilities

DirectSound enables your application to examine the hardware capabilities of the sound device. Many applications do not need to do this, because DirectSound automatically takes advantage of any available hardware acceleration. However, high-performance applications can use the information to scale their sound requirements to the available hardware. For example, an application might choose to play more sounds if hardware mixing is available than if it is not.

After calling the DirectSoundCreate8 function to create a device object, your application can retrieve the capabilities of the sound device by calling the IDirectSound8::GetCaps method.

The following example retrieves the capabilities of the device represented by the IDirectSound8 interface pointer lpDirectSound:

DSCAPS dscaps;

dscaps.dwSize = sizeof(DSCAPS);
HRESULT hr = lpDirectSound->GetCaps(&dscaps);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

The DSCAPS structure receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available. Note that the dwSize member of this structure must be initialized before the method is called.

If your application scales to hardware capabilities, you should call the IDirectSound8::GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.


Speaker Configuration

DirectSound uses the speaker configuration—that is, the position of the speakers relative to the listener—to optimize 3-D effects for the user's sound system.

In Windows® 98, Windows 2000, and later operating systems, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using IDirectSound8::GetSpeakerConfig. Applications should not override the setting by calling IDirectSound8::SetSpeakerConfig, as this is a global setting that affects other users and applications.


DirectSound Buffers

DirectSound buffer objects control the delivery of waveform data from a source to a destination. The source might be a synthesizer, another buffer, a WAV file, or a resource. For most buffers, the destination is a mixing engine called the primary buffer. From the primary buffer, the data goes to the hardware that converts the samples to sound waves.

Information about using DirectSound buffers is contained in the following topics:

  • Buffer Basics
  • Creating Secondary Buffers
  • Duplicating Buffers
  • Buffer Control Options
  • 3-D Algorithms for Buffers
  • Filling and Playing Static Buffers
  • Using Streaming Buffers
  • Playback Controls
  • Play and Write Cursors
  • Play Buffer Notification
  • Mixing Sounds
  • Looping Sounds
  • Buffer Management

For information about capture buffers, see Capturing Waveforms.


Buffer Basics

Your application must create at least one secondary sound buffer for storing and playing individual sounds.

A secondary buffer can exist throughout the life of an application, or it can be destroyed when no longer needed. It can be a static buffer that contains a single short sound, or a streaming buffer that is refreshed with new data as it plays. To limit demands on memory, long sounds should be played through streaming buffers that hold no more than a few seconds of data.

You mix sounds from different secondary buffers simply by playing them at the same time. Any number of secondary buffers can be played at one time, up to the limits of available processing power.

Secondary buffers are not all created alike. Characteristics of buffers include the following:

  • Format. The format of a buffer must match the format of the waveform data it plays.
  • Controls. Different buffers can have different controls, such as volume, frequency, and movement in two or three dimensions. When creating a buffer, you should specify only the controls you need; for example, don't create a 3-D buffer for a sound that isn't in a 3-D environment.
  • Location. A buffer can be in memory managed by hardware, or in memory managed by software. Hardware buffers are more efficient but limited in number.

See Also

  • DSBUFFERDESC


Creating Secondary Buffers

To create a buffer, call the IDirectSound8::CreateSoundBuffer method. This method returns a pointer to an IDirectSoundBuffer interface, from which the application can obtain an IDirectSoundBuffer8 interface.

The following example function creates a secondary sound buffer and returns the IDirectSoundBuffer8 interface.

HRESULT CreateBasicBuffer(LPDIRECTSOUND8 lpDirectSound, LPDIRECTSOUNDBUFFER8* ppDsb8)
{
  WAVEFORMATEX wfx;
  DSBUFFERDESC dsbdesc;
  LPDIRECTSOUNDBUFFER pDsb = NULL;
  HRESULT hr;

  // Set up WAV format structure.

  memset(&wfx, 0, sizeof(WAVEFORMATEX));
  wfx.wFormatTag = WAVE_FORMAT_PCM;
  wfx.nChannels = 2;
  wfx.nSamplesPerSec = 22050;
  wfx.nBlockAlign = 4;
  wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
  wfx.wBitsPerSample = 16;

  // Set up DSBUFFERDESC structure.

  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags =
    DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;
  dsbdesc.dwBufferBytes = 3 * wfx.nAvgBytesPerSec;
  dsbdesc.lpwfxFormat = &wfx;

  // Create buffer.

  hr = lpDirectSound->CreateSoundBuffer(&dsbdesc, &pDsb, NULL);
  if (SUCCEEDED(hr))
  {
     hr = pDsb->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*) ppDsb8);
     pDsb->Release();
  }
  return hr;
}

The example function creates a streaming buffer large enough to hold 3 seconds of streaming data. Nonstreaming buffers should be made just large enough to accommodate the entire sound.

If the location of a buffer is not specified, DirectSound places it in hardware-controlled memory if possible. Because hardware buffers are mixed by the sound card processor, they have much less impact on application performance.

If you wish to specify the location of a buffer rather than letting DirectSound decide where it belongs, set either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC structure. If the DSBCAPS_LOCHARDWARE flag is set and there are insufficient hardware resources, the buffer creation request fails.

To take advantage of the voice management features of DirectSound, specify the DSBCAPS_LOCDEFER flag when creating the buffer. This flag defers the allocation of resources for the buffer until it is played. For more information, see Dynamic Voice Management.

You can ascertain the location of an existing buffer by using the IDirectSoundBuffer8::GetCaps method and checking the dwFlags member of the DSBCAPS structure for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

Buffer objects are owned by the device object that created them. When the device object is released, all buffers created by that object are also released and should not be referenced.


Duplicating Buffers

You can create two or more secondary buffers containing the same data by using the IDirectSound8::DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. Because the duplicate buffer shares memory with the original buffer, changes to the data of one buffer will be reflected in duplicate buffers.


Buffer Control Options

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the dwFlags member of the DSBUFFERDESC structure, which can contain one or more of the flags in the following table.

Flag | Description
DSBCAPS_CTRL3D | The sound source can be moved in 3—D space.
DSBCAPS_CTRLFX | Effects can be added to the buffer.
DSBCAPS_CTRLFREQUENCY | The frequency of the sound can be changed.
DSBCAPS_CTRLPAN | The sound source can be moved from left to right.
DSBCAPS_CTRLPOSITIONNOTIFY | Notification positions can be set on the buffer.
DSBCAPS_CTRLVOLUME | The volume of the sound can be changed.

Note that certain combinations of controls are not allowed. For more information, see DSBUFFERDESC.

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the IDirectSoundBuffer8::SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and returns the DSERR_CONTROLUNAVAIL error code.

See Also

  • Playback Controls


3-D Algorithms for Buffers

When you create a secondary buffer with the DSBCAPS_CTRL3D control flag, you can also specify an algorithm to be used in spatializing the sound if the buffer is in software. By default, no head-related transfer function (HRTF) processing is performed, and the location of the sound relative to the listener is indicated by panning and volume only. You can request two levels of HRTF for the buffer.

For more information, see DSBUFFERDESC.


Filling and Playing Static Buffers

A secondary buffer that contains an entire self-contained sound is called a static buffer. Although it is possible to reuse the same buffer for different sounds, typically data is written to a static buffer only once.

Static buffers are created and managed just like streaming buffers. The only difference is in the way they are used: static buffers are filled once and then played, but streaming buffers are constantly refreshed with data as they are playing.

Note A static buffer is not necessarily one created by setting the DSBCAPS_STATIC flag in the buffer description. This flag requests allocation of memory on the sound card, which is not available on most modern hardware. A static buffer can exist in system memory and can be created with either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag.

Loading data into a static buffer is a three-step process:

  1. Lock the entire buffer by using IDirectSoundBuffer8::Lock. You specify the offset within the buffer where you intend to begin writing (normally 0), and get back the memory address of that point.
  2. Write the audio data to the returned address by using a standard memory-copy routine.
  3. Unlock the buffer using IDirectSoundBuffer8::Unlock.

These steps are shown in the following example, where lpdsbStatic is an IDirectSoundBuffer8 interface pointer and pbData is the address of the data source:

LPVOID lpvWrite;
DWORD  dwLength;

if (DS_OK == lpdsbStatic->Lock(
      0,          // Offset at which to start lock.
      0,          // Size of lock; ignored because of flag.
      &lpvWrite,  // Gets address of first part of lock.
      &dwLength,  // Gets size of first part of lock.
      NULL,       // Address of wraparound not needed.
      NULL,       // Size of wraparound not needed.
      DSBLOCK_ENTIREBUFFER))  // Flag.
{
  memcpy(lpvWrite, pbData, dwLength);
  lpdsbStatic->Unlock(
      lpvWrite,   // Address of lock start.
      dwLength,   // Size of lock.
      NULL,       // No wraparound portion.
      0);         // No wraparound size.
}
else
(
  ErrorHandler();  // Add error-handling here.
}

To play the buffer, call IDirectSoundBuffer8::Play, as in the following example:

lpdsbStatic->SetCurrentPosition(0);
HRESULT hr = lpdsbStatic->Play(
    0,  // Unused.
    0,  // Priority for voice management.
    0); // Flags.
if (FAILED(hr))
(
  ErrorHandler();  // Add error-handling here.
}

Because the DSBPLAY_LOOPING flag is not set in the example, the buffer automatically stops when it reaches the end. You can also stop it prematurely by using IDirectSoundBuffer8::Stop. When you stop a buffer prematurely, the play cursor position remains where it is. Hence the call to IDirectSoundBuffer8::SetCurrentPosition in the example, which ensures that the buffer starts from the beginning.


Using Streaming Buffers

A streaming buffer plays a long sound that cannot all fit into the buffer at once. As the buffer plays, old data is periodically replaced with new data.

To play a streaming buffer, call the IDirectSoundBuffer8::Play method, specifying DSBPLAY_LOOPING in the dwFlags parameter.

To halt playback, call the IDirectSoundBuffer8::Stop method. This method stops the buffer immediately, so you need to be sure that all data has been played. This can be done by polling the play position or by setting a notification position.

Streaming into a buffer requires the following steps:

  1. Ascertain whether the buffer is ready to receive new data. This can be done either by polling the play cursor or by waiting for a notification.
  2. Lock a portion of the buffer by using IDirectSoundBuffer8::Lock. This method returns one or two addresses where data can now be written.
  3. Write the audio data to the returned address or addresses by using a standard memory-copy routine.
  4. Unlock the buffer using IDirectSoundBuffer8::Unlock.

The reason IDirectSoundBuffer8::Lock might return two addresses is that you can lock any number of bytes, up to the size of the buffer, regardless of the start point. If necessary, the locked portion wraps around to the beginning of the buffer. If it does, you have to perform two separate memory copies.

For example, say you lock 30,000 bytes beginning at offset 20,000 in a 40,000-byte buffer. When you call Lock in this case, it returns four values:

  • The memory address of offset 20,000.
  • The number of bytes locked from that point to the end of the buffer; that is, 20,000 bytes. You write this number of bytes to the first address.
  • The memory address of offset 0.
  • The number of bytes locked from that point; that is, 10,000 bytes. You write this number of bytes to the second address.

If no wraparound is necessary, the last two values are NULL and 0 respectively.

Although it's possible to lock the entire buffer, you must not do so while it is playing. Normally you refresh only a fraction of the buffer each time. For example, you might lock and write to the first quarter of the buffer as soon as the play cursor reaches the second quarter, and so on. You must never write to the part of the buffer that lies between the play cursor and the write cursor.

The following function writes data to a sound buffer, starting at the position passed in dwOffset:

BOOL AppWriteDataToBuffer(
    LPDIRECTSOUNDBUFFER8 lpDsb,  // The buffer.
    DWORD dwOffset,              // Our own write cursor.
    LPBYTE lpbSoundData,         // Start of our data.
    DWORD dwSoundBytes)          // Size of block to copy.
{
  LPVOID  lpvPtr1;
  DWORD dwBytes1;
  LPVOID  lpvPtr2;
  DWORD dwBytes2;
  HRESULT hr;

  // Obtain memory address of write block. This will be in two parts
  // if the block wraps around.

  hr = lpDsb->Lock(dwOffset, dwSoundBytes, &lpvPtr1,
      &dwBytes1, &lpvPtr2, &dwBytes2, 0);

  // If the buffer was lost, restore and retry lock.

  if (DSERR_BUFFERLOST == hr)
  {
    lpDsb->Restore();
    hr = lpDsb->Lock(dwOffset, dwSoundBytes,
        &lpvPtr1, &dwBytes1,
        &lpvPtr2, &dwBytes2, 0);
  }
  if (SUCCEEDED(hr))
  {
    // Write to pointers.

    CopyMemory(lpvPtr1, lpbSoundData, dwBytes1);
    if (NULL != lpvPtr2)
    {
      CopyMemory(lpvPtr2, lpbSoundData+dwBytes1, dwBytes2);
    }

    // Release the data back to DirectSound.

    hr = lpDsb->Unlock(lpvPtr1, dwBytes1, lpvPtr2,
    dwBytes2);
    if (SUCCEEDED(hr))
    {
      // Success.
      return TRUE;
    }
  }

  // Lock, Unlock, or Restore failed.

  return FALSE;
}

See Also

  • Play and Write Cursors
  • Play Buffer Notification
  • Reading WAV Data
  • Using Buffers Efficiently


Playback Controls

To retrieve and set the volume at which a buffer is played, your application can use the IDirectSoundBuffer8::GetVolume and IDirectSoundBuffer8::SetVolume methods. Setting the volume on the primary buffer changes the waveform-audio volume of the sound card. Volume is measured as hundredths of decibels (dB) of attenuation; it is not possible to amplify the default volume. Note that the decibel scale is not linear; a reduction in volume of 3 dB is equivalent to a halving of the sound energy, and sounds generally become inaudible long before the maximum attenuation of 100 dB is reached.

By calling the IDirectSoundBuffer8::GetFrequency and IDirectSoundBuffer8::SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the position of the sound source on the left-right axis, you can call the IDirectSoundBuffer8::GetPan and IDirectSoundBuffer8::SetPan methods. Buffers with 3-D capabilities cannot be panned.

In order to use any of these controls, you must set the appropriate flags when creating the buffer. See Buffer Control Options.


Play and Write Cursors

DirectSound maintains two pointers into the buffer: the play cursor and the write cursor. These positions are byte offsets into the buffer, not absolute memory addresses.

The IDirectSoundBuffer8::Play method always starts playing at the position of the play cursor. When a buffer is created, the play cursor is set to 0. As the buffer is played, the cursor moves and always points to the next byte of data to be played. When the buffer is stopped, the cursor remains where it is.

The write cursor is the point after which it is safe to write data into the buffer. The block between the play cursor and the write cursor is already committed to be played, and cannot be changed safely.

You might visualize the buffer as a clock face, with data written to it in a clockwise direction. The play cursor and the write cursor are like two hands sweeping around the face at the same speed, the write cursor always keeping a little ahead of the play cursor. If the play cursor points to the 1 and the write cursor points to the 2, it is only safe to write data after the 2. Data between the 1 and the 2 may already have been queued for playback by DirectSound and should not be touched.

The write cursor moves with the play cursor, not with data written to the buffer. If you're streaming data, you are responsible for maintaining your own pointer into the buffer to indicate where the next block of data should be written.

An application can retrieve the play and write cursors by calling the IDirectSoundBuffer8::GetCurrentPosition method. The IDirectSoundBuffer8::SetCurrentPosition method lets you move the play cursor. Applications do not control the position of the write cursor.

To ensure that the play cursor is reported as accurately as possible, always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.


Play Buffer Notification

DirectSound can notify your application when the play cursor reaches certain points in a buffer, or when the buffer stops. This can be useful in two common situations:

  • The application must take some action, such as playing another buffer, when a sound has finished playing.
  • The application is streaming data to the buffer, and needs to know when the play cursor reaches predefined points so that data that has been played can be replaced by new data.

Note If you are taking advantage of voice management, it's possible that a buffer could be terminated before a notification position is reached. See the Remarks for DSBPOSITIONNOTIFY.

Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

First you obtain a pointer to the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method. A separate interface must be obtained from each buffer on which you want to set notifications.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to SetNotificationPositions.

The following example function sets a single notification position. The event will be signaled when playback stops, either because the end of a nonlooping buffer has been reached, or because the application called the IDirectSoundBuffer8::Stop method. Assume that hMyEvent is a handle returned by CreateEvent and that lpDsbSecondary is a secondary buffer created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

HRESULT SetStopNotification(HANDLE hMyEvent,
        LPDIRECTSOUNDBUFFER8 lpDsbSecondary)
{
  LPDIRECTSOUNDNOTIFY8 lpDsNotify;
  DSBPOSITIONNOTIFY PositionNotify;
  HRESULT hr;

  if (SUCCEEDED(
      hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify8,
             (LPVOID*)&lpDsNotify)))
  {
    PositionNotify.dwOffset = DSBPN_OFFSETSTOP;
    PositionNotify.hEventNotify = hMyEvent;
    hr = lpDsNotify->SetNotificationPositions(1, &PositionNotify);
    lpDsNotify->Release();
  }
  return hr;
}


Mixing Sounds

Secondary buffers played simultaneously are automatically mixed in the primary buffer. Under the Windows driver model, the mixing is done in the kernel mixer. Different secondary buffers can have different WAV formats (for example, different sampling rates), and sounds are converted to the format of the primary buffer or kernel mixer as necessary.

On VXD drivers, the DirectSound mixer produces the best sound quality if all your application's sounds use the same WAV format and the hardware output format is matched to the format of the sounds. If this is done, the mixer does not need to perform any format conversion. Your application can change the hardware output format by creating a primary sound buffer object and calling the IDirectSoundBuffer8::SetFormat method. To do this, you need the Priority Cooperative Level. You must set the format of the primary buffer before creating any secondary buffers. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

On WDM drivers, setting the primary buffer format has no effect. The format is determined by the kernel mixer. For more information, see DirectSound Driver Models.


Looping Sounds

DirectSound does not directly support looping, or repetition of a portion of a sound. Although it is possible to implement looping on a static buffer by resetting the play cursor to the start of the loop each time it reaches the end of the loop, doing so might result in audio glitches, as DirectSound must discard any preprocessed data and begin preprocessing again.

To repeat a portion of a sound, play the sound in a streaming buffer and implement the loop in your source data.

See Also

  • Using Streaming Buffers


Buffer Management

The IDirectSoundBuffer8::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the IDirectSoundBuffer8::GetStatus method to determine if the buffer is playing or if it has stopped.

Use the IDirectSoundBuffer8::GetFormat method to retrieve information about the format of the sound data in a buffer. You also can use IDirectSoundBuffer8::SetFormat to set the format of the sound data in the primary buffer. For more information, see Mixing Sounds.

Note The SetFormat method cannot be called on secondary buffers. After a secondary buffer is created, its format is fixed. To play a sound that is in another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is returned when the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the IDirectSoundBuffer8::Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.


Using WAV Data

Under the Windows driver model (WDM), DirectSound hardware buffers can play any uncompressed or compressed sound format that can be described in a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure, provided the format is supported by the hardware. Software buffers and non-WDM hardware buffers support only 8-bit and 16-bit uncompressed formats.

Waveform (or WAV) data is usually stored in files or resources in Resource Interchange File Format (RIFF). The data includes a description of the WAV format, including parameters such as the sampling rate and number of output channels.

More information on WAV sounds is included in the following topics:

  • Multichannel WAV Formats
  • Reading WAV Data
  • Calculating the Duration of a WAV Sound


Multichannel WAV Formats

On WDM drivers, DirectSound buffers support WAV formats that have more than two output channels, for speaker configurations such as 5.1, which has speakers at the front left, front center, front right, back left, and back right, plus a low-frequency enhancer.

The WAVEFORMATEXTENSIBLE structure describes a multichannel wave format. This structure is an extension of WAVEFORMATEX that configures the extra bytes already supported by the cbSize member of WAVEFORMATEX. A WAVEFORMATEXTENSIBLE structure can be cast as WAVEFORMATEX wherever the latter is expected, as for example in the DSBUFFERDESC structure.

If the system is configured for fewer physical speakers than the number of channels specified in a multichannel WAV file, the audio data is mixed appropriately and output to the existing speakers.

DirectSound does not support effects or 3-D processing on buffers in a multichannel format. An attempt to create a buffer with the DSBCAPS_CTRL3D or DSBCAPS_CTRLFX flag and a multichannel WAV format will fail.

For more information on multichannel WAV formats, see Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.


Reading WAV Data

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

To store WAV sounds in an executable, import your WAV files as resources and give them string names. Note that the CWaveFile Sample Class expects these resources to be of type "WAVE" or "WAV", and expects to find them in the executable module rather than a DLL.

The DirectSound API does not include methods for loading sound data. However, the Dsutil.cpp file used by many of the SDK sample applications implements several classes that can be used to create sound buffers from files, resources, or a memory location.

The basic steps involved in using the sample classes to initialize DirectSound and to create and load buffers are as follows:

  1. Create an object of the CSoundManager Sample Class.
  2. Call CSoundManager::Initialize to create the device object.
  3. Pass the name of a file or resource to CSoundManager::Create or a memory location to CSoundManager::CreateFromMemory. These methods return an object of the CSound Sample Class representing one or more static buffers just large enough to contain the data. (You can create multiple buffers to play several instances of the sound at the same time.) Alternatively, pass the name of a file or resource to CSoundManager::CreateStreaming. This method returns an object of the CStreamingSound Sample Class representing a single streaming buffer .
  4. Call the FillBufferWithSound method on the object retrieved in the preceding step. This reads the data from the file, resource, or memory location into the buffer. For a streaming buffer, it fills the buffer only with as much data as it can hold; to refresh the data as the buffer plays, use CStreamingSound::HandleWaveStreamNotification.

Note that the actual reading of data is done by a CWaveFile object that is a protected member of the CSound or CStreamingSound object. You do not normally need to use the CWaveFile class directly; however, you can refer to the implementation of this class for information on how to parse WAV data.

See Also

  • DirectSound Sample Framework


Calculating the Duration of a WAV Sound

The length of time a waveform will play is determined by the data size and the format. The data size and format can be retrieved by using the CWaveFile::GetSize and CWaveFile::GetFormat methods in the DirectSound sample framework.

The following example function, which does not use the sample classes, returns the duration of a WAV file, in milliseconds:

DWORD GetSoundLength(LPSTR strFileName)
{
  CWaveFile* pWav;
  DWORD dwLen = 0;
  DWORD dwSize;
  WAVEFORMATEX* wfx;

  pWav = new CWaveFile();
  if (SUCCEEDED(pWav->Open(strFileName, NULL, WAVEFILE_READ)))
  {
    wfx = pWav->GetFormat();
    dwSize = pWav->GetSize();
    dwLen = (DWORD) (1000 * dwSize / wfx->nAvgBytesPerSec);
    pWav->Close();
  }
  if (pWav) delete pWav;
  return dwLen;
}

See Also

  • CWaveFile Sample Class
  • DirectSound Sample Framework
  • Reading WAV Data


3-D Sound

Using DirectSound, you can create a 3-D world for sounds that can be integrated with 3-D graphics. You can locate sound sources and the listener in space, apply Doppler shift to moving sounds, and control physical parameters such as the rate at which sound attenuates over distance.

DirectSound can creates virtual 3-D effects on two speakers or a set of headphones. It will also take advantage of multichannel systems with WDM drivers if the user has selected a surround sound speaker configuration in Control Panel. For more information, see DSBUFFERDESC.

The following topics cover some general aspects of 3-D sound:

  • Coordinates of 3-D Space
  • Perception of Sound Positions

Information on how to use 3-D sound in an application is found in the following sections:

  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners


Coordinates of 3-D Space

The position, velocity, and orientation of sound sources and listeners in 3-D space are represented by Cartesian coordinates, which are values on three axes: the x-axis, the y-axis, and the z-axis. The axes are relative to a viewpoint established by the application. Values on the x-axis increase from left to right, on the y-axis from down to up, and on the z-axis from near to far.

The D3DVECTOR structure contains values describing position, velocity, or orientation on the three axes.

Conventionally, vectors are expressed as three values enclosed in parentheses and separated by commas, in the order (x, y, z).

For position, the values are in meters by default. If your application does not use the meter as its unit of measure for 3-D graphics, you can set a distance factor, which is a floating-point value representing meters per application-specified distance unit. For example, if your application uses feet, it could specify a distance factor of .3048, which is the number of meters in a foot. For more information, see Distance Factor.

For velocity, the vector describes the rate of movement along each axis in units per second. Again, the default unit is meters, but this can be changed by the application.

For orientation, the values are in arbitrary units and are relative to one another. If the base view of the 3-D world is facing north toward the horizon, and the orientation of the listener is (-1, 0, 1) the listener is facing northwest. Because the values within a vector are not in absolute units, the vector could equally well be expressed as (-5, 0, 5) or (-0.25, 0, 0.25).

You can see how vectors in 2-D space work by drawing them on a sheet of graph paper. Let the values increase from the bottom of the paper to the top and from left to right. A line drawn from (0, 0) to (1, 1) has the same orientation, or direction, as one drawn from (0, 0), to (5, 5). However, the second line indicates a greater distance, or velocity. 3-D vectors work in just the same way, with an additional axis in the up-down direction.


Perception of Sound Positions

In the real world, the perception of a sound's position in space is influenced by several factors. Not all of these factors are acoustical; one of the most important is sight. Clues from the sounds themselves include the following:

  • Overall loudness. As a sound source moves away from the listener, its perceived volume decreases at a fixed rate. This phenomenon is known as rolloff.
  • Interaural intensity difference. A sound coming from the listener's right sounds louder in the right ear than in the left.
  • Interaural time difference. A sound emitted by a source to the listener's right will arrive at the right ear slightly before it arrives at the left ear. The duration of this offset is approximately a millisecond.
  • Muffling. The shape and orientation of the ears ensures that sounds coming from behind the listener are slightly muffled compared with sounds coming from in front. In addition, if a sound is coming from the right, the sound reaching the left ear will be muffled by the mass of the listener's head as well as by the orientation of the left ear.
  • Effect of the earlobes. The pinnae, or folds of the ear, cause subtle changes to the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function (HRTF).


DirectSound 3-D Buffers

Each sound source in a 3-D environment is represented by an IDirectSound3DBuffer8 interface. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag. Methods of the interface are used to set and retrieve parameters of a single sound source.

Applications must supply monaural sound sources when using the 3-D capabilities of DirectSound. If you attempt to create a buffer with the DSBCAPS_CTRL3D flag set and a WAV format with more than one channel, an error results.

This section describes how your applications can obtain and manage 3-D buffer objects.The following topics are discussed:

  • Obtaining the 3-D Buffer Object
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones
  • Batch Parameters for 3-D Buffers


Obtaining the 3-D Buffer Object

The IDirectSound3DBuffer8 interface is obtained from a secondary DirectSound buffer that has been created with the DSBCAPS_CTRL3D flag in the dwFlags member of the DSBUFFERDESC structure.

If your application is creating and managing its own DirectSound secondary buffers without using the DirectMusic performance, you can retrieve the IDirectSound3DBuffer8 interface by calling QueryInterface method on the buffer, as in the following sample code, where lpDsbSecondary is an IDirectSoundBuffer8 interface.

LPDIRECTSOUND3DBUFFER8 lpDs3dBuffer;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSound3DBuffer8,
                (LPVOID *)&lpDs3dBuffer);

See Also

  • Using Effects in DirectMusic


Minimum and Maximum Distances

As a listener approaches a sound source, the sound gets louder; the volume doubles when the distance is halved. Past a certain point, however, it is not reasonable for the volume to continue to increase. This is the minimum distance for the sound source.

The minimum distance that you set for a sound determines how quickly that sound fades away with distance. For example, you might set this value to 100 meters for a jet engine and to 2 centimeters for a bee. With these settings, the jet engine is at half volume when 200 meters away from the listener, but the bee is at half volume when only 4 centimeters away.

The following illustration shows how minimum and maximum distance affect the volume of a jet engine and a bee at increasing distances.

Minimum and maximum distances

The default minimum distance for a sound buffer, DS3D_DEFAULTMINDISTANCE, is defined as 1 unit, or 1 meter at the default distance factor. Unless you change this value, the sound is at full volume when it is 1 meter away from the listener, at half volume at 2 meters, at quarter volume at 4 meters, and so on. For most sounds you will probably want to set a larger minimum distance so that the sound does not fade so rapidly as it moves away.

The maximum distance for a sound source is the distance beyond which the volume of the sound no longer decreases. The default maximum distance for a DirectSound 3-D buffer (DS3D_DEFAULTMAXDISTANCE) is 1 billion, meaning that in most cases the attenuation will continue to be calculated long after the sound has moved out of hearing range. To avoid unnecessary processing on software buffers under VXD drivers, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer. In DirectMusic, this flag is automatically set on standard 3-D buffers created as part of an audiopath.

The maximum distance can also be used to prevent a sound from becoming inaudible. For example, if you have set the minimum distance for a sound at 100 meters, that sound might become effectively inaudible at 1,000 meters or less. By setting the maximum distance at 800 meters, you ensure that the sound always has at least one-eighth of its maximum volume regardless of the distance. In this case, of course, you would not set the DSBCAPS_MUTE3DATMAXDISTANCE flag.

By default, distance values are expressed in meters.

To adjust the effect of distance on volume for all sound buffers, you can change the rolloff factor.

See Also

  • IDirectSound3DBuffer8::GetMinDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMaxDistance
  • Distance Factor
  • Rolloff Factor


Processing Mode

Sound buffers have three processing modes: normal, head-relative, and disabled.

In normal mode, the sound source is positioned and oriented absolutely in world space. This is the default mode, and is used for sound sources that do not move and turn with the listener.

In head-relative mode, the 3-D properties of the sound source are all relative to the current position, velocity, and orientation of the listener. As the listener moves and turns, the buffer is automatically repositioned in world space. Head-relative mode can be used for sounds such as a fly buzzing around the listener's head. However, most sounds that travel with the listener don't have to be 3-D sounds at all.

In disabled mode, 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

See Also

  • IDirectSound3DBuffer8::SetMode


Buffer Position and Velocity

As a sound source moves, it is up to the application to specify values for its position and velocity.

Position is measured in distance units along each of the three axes, relative to either world space or the listener, depending on the processing mode.

Velocity is measured in distance units per second along each of the three axes of a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.

See Also

  • IDirectSound3DBuffer8::GetPosition
  • IDirectSound3DBuffer8::SetPosition
  • IDirectSound3DBuffer8::GetVelocity
  • IDirectSound3DBuffer8::SetVelocity
  • Distance Factor
  • Doppler Effect


Sound Cones

A sound with no orientation has the same amplitude at a given distance in all directions. A sound with an orientation is loudest in the direction of orientation. The model that describes the loudness of the oriented sound is called a sound cone. Sound cones are made up of an inside (or inner) cone and an outside (or outer) cone. The outside cone angle must always be equal to or greater than the inside cone angle.

At any angle within the inner cone, the volume of the sound is just what it would be if there were no cone, after taking into account the basic volume of the buffer, the distance from the listener, the listener's orientation, and so on.

At any angle outside the outer cone, the normal volume is attenuated by a factor set by the application. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.

Between the inner and outer cones is a zone of transition from the inside volume to the outside volume. The volume decreases as the angle increases.

The following illustration shows the concept of sound cones.

Every 3-D sound buffer has a sound cone, but by default a buffer behaves like an omnidirectional sound source, because the outside volume is not attenuated, and the inside and outside cone angles are 360 degrees. Unless the application changes these values, the sound does not have any apparent orientation.

Designing sound cones properly can add dramatic effects to your application. For example, you could position a sound source in the center of a room, setting its orientation toward an open door in a hallway. Then set the angle of the inside cone so that it extends to the width of the doorway, make the outside cone a bit wider, and set the outside cone volume to inaudible. A listener moving along the hallway will begin to hear the sound only when near the doorway, and the sound will be loudest as the listener passes in front of the open door.

See Also

  • IDirectSound3DBuffer8::GetConeAngles
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::GetConeOutsideVolume
  • IDirectSound3DBuffer8::SetConeOutsideVolume


Batch Parameters for 3-D Buffers

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. If the sound source is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DBuffer8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DBUFFER structure, and passing the structure back to IDirectSound3DBuffer8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


DirectSound 3-D Listeners

In a virtual 3-D environment as in the real world, sounds exist only in relation to a point of reception. The 3-D sound effects in a DirectX application are affected not only by the position, orientation, and velocity values of the sound sources, but also by the position, orientation, and velocity of the virtual listener.

By default, the listener is stationary at the zero point of all vectors, oriented with the nose toward the positive Z-axis and the top of the head toward the positive Y-axis. The application can change all these values to reflect the movement and facing of the user within virtual space. The listener object also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a listener object and manage global 3-D sound parameters. The following topics are discussed:

  • Obtaining the 3-D Listener
  • Spatial Parameters of the Listener
  • Distance Factor
  • Doppler Effect
  • Rolloff Factor
  • Batch Parameters for 3-D Listeners
  • Deferred Settings


Obtaining the 3-D Listener

Global sound parameters are set and retrieved by using the IDirectSound3DListener8 interface from the primary buffer. There is only one primary buffer in an application, and only one listener.

If your application is not using DirectMusic audiopaths, you must create a primary buffer object and then obtain the listener interface from that. Create the primary buffer by using the IDirectSound8::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the dwFlags member of the DSBUFFERDESC structure. Call the QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DListener8 interface for that buffer.

The following example function retrieves an interface to the listener.

GetListener(LPDIRECTSOUND8 lpds, LPDIRECTSOUND3DLISTENER8* ppListener)
{
  DSBUFFERDESC             dsbd;
  LPDIRECTSOUNDBUFFER      lpdsbPrimary;  // Cannot be IDirectSoundBuffer8.
  LPDIRECTSOUND3DLISTENER8 lp3DListener = NULL;
  HRESULT hr;

  ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
  dsbd.dwSize = sizeof(DSBUFFERDESC);
  dsbd.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;

  if (SUCCEEDED(hr = lpds->CreateSoundBuffer(&dsbd, &lpdsbPrimary, NULL)))
  {
    hr = lpdsbPrimary->QueryInterface(IID_IDirectSound3DListener8,
                                 (LPVOID *)ppListener);
    lpdsbPrimary->Release();
  }
  return hr;
}

See Also

  • Using 3-D Sound in DirectMusic


Spatial Parameters of the Listener

Like a sound source, the listener has a position, orientation, and velocity in the 3-D world.

The orientation of the listener is defined by the relationship between two vectors that share an origin at the center of the listener's head: the top and front vectors. The top vector points straight up through the top of the head, and the front vector points forward through the listener's face at right angles to the top vector, as in the following illustration.

By default, the front vector is (0.0, 0.0, 1.0), and the top vector is (0.0, 1.0, 0.0). The two vectors must always be at right angles to one another. If necessary, DirectSound will adjust the front vector so that it is at right angles to the top vector.

Position is measured in distance units along a vector.

Velocity is measured in distance units per second along a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.

See Also

  • IDirectSound3DListener8::GetOrientation
  • IDirectSound3DListener8::SetOrientation
  • IDirectSound3DListener8::GetPosition
  • IDirectSound3DListener8::SetPosition
  • IDirectSound3DListener8::GetVelocity
  • IDirectSound3DListener8::SetVelocity


Distance Factor

The distance factor is the number of meters in a vector unit. By default, the distance factor is 1.0. If the velocity of a buffer is (2.0, 0.0, 0.0), the sound source is considered to be moving along the x-axis at 2 meters per second. Applications that are using a different unit of measurement for 3-D graphics vectors might want to change the distance factor accordingly.

Suppose, for example, that the basic unit of measurement in your application is the foot, or 0.3048 meters. You set the distance factor to 0.3048. From then on, you use feet in parameters to method calls, and they are automatically converted to meters.

The distance factor mainly affects Doppler shift, by changing the actual velocity represented by n units per second. It does not directly affect rolloff, because the rate of attenuation over distance is based on the minimum distance in vector units. If you set the minimum distance for a given sound at 2 units, the volume will be halved at a distance of 4 units, regardless of whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.

See Also

  • IDirectSound3DListener8::GetDistanceFactor
  • IDirectSound3DListener8::SetDistanceFactor


Doppler Effect

DirectSound automatically creates Doppler shift effects for any buffer or listener that has a velocity. Effects are cumulative: if the listener and the sound buffer are both moving, the system automatically calculates the relative velocity and adjusts the Doppler effect accordingly.

In order to have realistic Doppler shift effects in your application, you must calculate the speed of any object that is moving and set the appropriate velocity for that sound source or listener. You are free to exaggerate or lessen this value in a particular case in order to create special effects. You can also globally increase or decrease Doppler shift by changing the Doppler factor.

The Doppler factor can range from DS3D_MINDOPPLERFACTOR to DS3D_MAXDOPPLERFACTOR, defined as 0.0 and 10.0 respectively. A value of 0 means no Doppler shift is applied to a sound. Every other value represents a multiple of the real-world Doppler shift.

See Also

  • IDirectSound3DListener8::GetDopplerFactor
  • IDirectSound3DListener8::SetDopplerFactor


Rolloff Factor

Rolloff is the amount of attenuation that is applied to sounds, based on the listener's distance from the sound source. DirectSound can ignore rolloff, exaggerate it, or give it the same effect as in the real world, depending on a global parameter called the rolloff factor.

The rolloff factor can range from DS3D_MINROLLOFFFACTOR to DS3D_MAXROLLOFFFACTOR, defined as 0.0 and 10.0 respectively. A value of DS3D_MINROLLOFFFACTOR means that sounds remain at full volume regardless of their distance from the listener. Every other value represents a multiple of the real-world rolloff.

The rolloff factor is global. To change the effect of distance for an individual sound buffer, you can set the minimum distance for the buffer.

See Also

  • IDirectSound3DListener8::GetRolloffFactor
  • IDirectSound3DListener8::SetRolloffFactor
  • Minimum and Maximum Distances


Batch Parameters for 3-D Listeners

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. If the listener is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DListener8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DLISTENER structure, and passing the structure back to IDirectSound3DListener8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


Deferred Settings

Every change to 3-D sound buffer and listener settings causes remixing, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, set the DS3D_DEFERRED flag in the dwApply parameter of any of the IDirectSound3DListener8 or IDirectSound3DBuffer8 methods that change 3-D settings. Then call the IDirectSound3DListener8::CommitDeferredSettings method to execute all of the deferred commands at once.

Deferred settings are overwritten by immediate settings. For example, if you set the listener velocity to (1.0, 0.0, 0.0) with the DS3D_DEFERRED flag and then set it to (2.0, 0.0, 0.0) with the DS3D_IMMEDIATE flag, the velocity becomes (2.0, 0.0, 0.0) and does not change when CommitDeferredSettings is called.


Using Effects

DirectX provides support for effects processing of sounds by DirectX Media Objects (DMOs). A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system.

All the standard DMOs except Waves reverberation can process 8- or 16-bit PCM data with one or two channels at any sample rate supported by DirectSound. Waves reverberation does not support 8-bit samples.

To implement effects, a DirectSound application must first call CoInitialize to initialize COM. Doing so does not preclude creating the device object by using DirectSoundCreate8.

Using the DirectSound API, it is not possible to create chains of effects, where the output of multiple buffers is mixed into another buffer containing an effect. Buffer chains are available, however, in content authored for DirectMusic. For more information, see Buffer Chains.

The following topics contain information on setting up and using effects:

  • Setting Effects on Buffers
  • Effect Parameters
  • Standard Effects


Setting Effects on Buffers

You can set any number of effects on a secondary buffer that was created with the DSBCAPS_CTRLFX flag in the DSBUFFERDESC structure. The buffer must be stopped and not locked. In DirectX 9.0, effects are never hardware-accelerated. It is possible to set an effect on a hardware buffer, but doing so confers no advantages.

Effects might not work smoothly on very small buffers. DirectSound does not permit the creation of effects-capable buffers that hold less than 150 milliseconds of data. This value is defined as DSBSIZE_FX_MIN.

The following sample function sets an echo effect on a buffer and displays the result in the output window of the development environment.

HRESULT SetEcho(LPDIRECTSOUNDBUFFER8 pDSBuffer)
{
  HRESULT hr;
  DWORD dwResults[1];  // One element for each effect.

  // Describe the effect.
  DSEFFECTDESC dsEffect;
  memset(&dsEffect, 0, sizeof(DSEFFECTDESC));
  dsEffect.dwSize = sizeof(DSEFFECTDESC);
  dsEffect.dwFlags = 0;
  dsEffect.guidDSFXClass = GUID_DSFX_STANDARD_ECHO;

  // Set the effect
  if (SUCCEEDED(hr = pDSBuffer->SetFX(1, &dsEffect, dwResults)))
  {
    switch (dwResults[0])
    {
      case DSFXR_LOCHARDWARE:
        OutputDebugString("Effect was placed in hardware.");
        break;
      case DSFXR_LOCSOFTWARE:
        OutputDebugString("Effect was placed in software.");
        break;
      case DSFXR_UNALLOCATED:
        OutputDebugString("Effect is not yet allocated to hardware or software.");
        break;
    }
  }
  return hr;
}


Effect Parameters

To set or retrieve parameters of sound effects, you must first obtain the appropriate interface to the buffer that contains the effect. The following interfaces give you access to parameters of the standard DMOs available on all systems.

  • IDirectSoundFXChorus8
  • IDirectSoundFXCompressor8
  • IDirectSoundFXDistortion8
  • IDirectSoundFXEcho8
  • IDirectSoundFXFlanger8
  • IDirectSoundFXGargle8
  • IDirectSoundFXI3DL2Reverb8
  • IDirectSoundFXParamEq8
  • IDirectSoundFXWavesReverb8

To obtain one of these interfaces, pass the corresponding IID to the QueryInterface method of the buffer containing the effect. For a list of IIDs, see DirectSound Interface GUIDs.

Changes in effect parameters do not always take place immediately. For efficiency, DirectSound processes 100 milliseconds of sound data in a buffer, starting at the play cursor, before the buffer is played. This preprocessing happens after all of the following calls:

  • IDirectSoundBuffer8::SetCurrentPosition
  • IDirectSoundBuffer8::SetFX
  • IDirectSoundBuffer8::Stop
  • IDirectSoundBuffer8::Unlock


Standard Effects

This topic is an introduction to the sound effects provided with DirectX. The following effects are covered:

  • Chorus
  • Compression
  • Distortion
  • Echo
  • Environmental Reverberation
  • Flange
  • Gargle
  • Parametric Equalizer
  • Waves Reverberation


Chorus

Chorus is a voice-doubling effect created by echoing the original sound with a slight delay and slightly modulating the delay of the echo.

This effect is represented by the IDirectSoundFXChorus8 interface. Its parameters are contained in the DSFXChorus structure.


Compression

Compression is a reduction in the fluctuation of a signal above a certain amplitude.

This effect is represented by the IDirectSoundFXCompressor8 interface. Its parameters are contained in the DSFXCompressor structure.


Distortion

Distortion is achieved by adding harmonics to the signal in such a way that, as the level increases, the top of the waveform becomes squared off or clipped.

This effect is represented by the IDirectSoundFXDistortion8 interface. Its parameters are contained in the DSFXDistortion structure.


Echo

An echo effect causes an entire sound to be repeated after a fixed delay.

This effect is represented by the IDirectSoundFXEcho8 interface. Its parameters are contained in the DSFXEcho structure.


Environmental Reverberation

DirectX provides partial support for environmental reverberation in accordance with the Interactive 3-D Audio Level 2 (I3DL2) specification, published by the Interactive Audio Special Interest Group. The DirectX environmental reverb effect is an implementation of the listener properties in the I3DL2 specification. Source properties are not supported.

Sounds reaching the listener have three temporal components:

  • The direct path is the audio signal that goes straight from the sound source to the listener, without bouncing off any surface.
  • Early reflections are the audio signals that reach the listener after one or two reflections off surfaces such as the walls, floor, and ceiling. If a signal is the result of the sound hitting only one wall on its way to the listener, it is called a first-order reflection. If it bounces off two walls before reaching the listener, it is called a second-order reflection. Humans can typically perceive individual reflections only of the first or second order.
  • Late reverberation, or simply reverb, consists of the combined lower-order reflections, usually a dense succession of echoes of diminishing intensity.

The combination of early reflections and late reverberation is sometimes called the room effect.

Note In the DirectSound implementation, only the signal sent to the room effect is heard. To hear the direct path, play the sound simultaneously in another buffer that does not have the environmental reverb effect.

Reverberation properties include the following:

  • Attenuation of the early reflections and late reverberation.
  • Rolloff factor, or the rate at which reflected signals become attenuated with distance. The rolloff factor for the direct path is managed by the DirectSound listener.
  • Reflections delay. This is the interval between the arrival of the direct-path signals and the arrival of the first early reflections.
  • Reverb delay. This is the interval between the first of the early reflections and the onset of late reverberation.
  • Decay time. This is the interval between the onset of late reverberation and the time when its intensity has been reduced by 60 dB.
  • Diffusion, which is proportional to the number of echos per second in the late reverberation. Depending on the implementation, the density of echos can change as the reverberation decays. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.
  • Density, which is is proportional to the number of resonances per hertz in the late reverberation. Lower densities produce hollower sounds like those found in small rooms. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.

Reverb properties are represented by an IDirectSoundFXI3DL2Reverb8 interface, and the parameters of the environment are contained in a DSFXI3DL2Reverb structure.

DirectX supports many sets of default parameters, or presets, that describe the reverb properties of audio environments ranging from mountains to sewer pipes. Most applications can simply choose one of these environments by using IDirectSoundFXI3DL2Reverb8::SetPreset.

To set custom properties, use IDirectSoundFXI3DL2Reverb8::SetAllParameters. You can retrieve the current properties by using IDirectSoundFXI3DL2Reverb8::GetAllParameters.


Flange

Flange is an echo effect in which the delay between the original signal and its echo is very short and varies over time. The result is sometimes referred to as a sweeping sound. The term flange originated with the practice of grabbing the flanges of a tape reel to change the speed.

This effect is represented by the IDirectSoundFXFlanger8 interface. Its parameters are contained in the DSFXFlanger structure.


Gargle

The gargle effect modulates the amplitude of the signal.

This effect is represented by the IDirectSoundFXGargle8 interface. Its parameters are contained in the DSFXGargle structure.


Parametric Equalizer

A parametric equalizer amplifies or attenuates signals of a given frequency.

Parametric equalizer effects for different pitches can be applied in parallel by setting multiple instances of the GUID_DSFX_STANDARD_PARAMEQ effect on the same buffer. In this way, the application can have tone control similar to that provided by a hardware equalizer.

This effect is represented by the IDirectSoundFXParamEq8 interface. Its parameters are contained in the DSFXParamEq structure.


Waves Reverberation

The Waves reverberation effect is intended for use with music. The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

This effect is represented by the IDirectSoundFXWavesReverb8 interface. Its parameters are contained in the DSFXWavesReverb structure.


Capturing Waveforms

The DirectSound capture device object, represented by the IDirectSoundCapture8 interface, is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. Data can be captured in PCM or compressed formats.

The DirectSound capture buffer object, represented by the IDirectSoundCaptureBuffer8 interface, represents a buffer used for receiving data from the input device. Like playback buffers, this buffer is conceptually circular: when input reaches the end of the buffer, it automatically starts again at the beginning.

The methods of IDirectSoundCaptureBuffer8 enable you to retrieve the properties of the buffer, start and stop audio capture, and lock portions of the memory, so that you can safely retrieve data for saving to a file or for playback in a full-duplex implementation. On operating systems that support capture effects, this interface also provides methods for retrieving DMOs and ascertaining the status of effects.

More information about waveform capture is found in the following topics:

  • Enumerating Capture Devices
  • Creating the Capture Device Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Capture Buffer Effects
  • Using the Capture Buffer
  • Writing to a WAV File


Enumerating Capture Devices

If your application is simply going to capture sounds through the user's preferred capture device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function, you can specify a default device. For more information, see Creating the Capture Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

For a sample callback function, see Enumerating Sound Devices.

The enumeration is set in motion by using the DirectSoundCaptureEnumerate function, as follows:

DWORD pv;  // Can be any 32-bit type.

HRESULT hr = DirectSoundCaptureEnumerate(
    (LPDSENUMCALLBACK)DSEnumProc, (VOID*)&pv);

The second parameter can be any 32-bit value that you want to have access to within the callback.

Note The first device enumerated is always called the Primary Sound Capture Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred capture device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Capture Driver" to a list when presenting the user with a choice of devices. The primary capture device is also enumerated with its proper name and GUID.


Creating the Capture Device Object

You can create the capture device object by calling either the DirectSoundCaptureCreate8 or the DirectSoundFullDuplexCreate8 function. Both these functions retrieve a pointer to the IDirectSoundCapture8 interface.

The lpcGUID parameter to DirectSoundCaptureCreate, or the pcGuidRenderDevice parameter to DirectSoundFullDuplexCreate8, can be a GUID obtained by enumeration, or it can be one of the following predefined GUIDs:

GUID | Description
DSDEVID_DefaultCapture | The default system capture device. You can also specify this device by passing a NULL pointer instead of a device GUID.
DSDEVID_DefaultVoiceCapture | The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call fails.

You can also use the CoCreateInstance function to create the object. The procedure is similar to that for the device object; see Creating the Device Object. If you use CoCreateInstance, the object is created for the default capture device selected by the user in Control Panel.

If you want playback and capture device objects to coexist, then you should create and initialize the playback device object before creating and initializing the capture device object, or use DirectSoundFullDuplexCreate8.

Some audio devices aren't configured for full duplex audio by default. If your application has problems with creating and initializing both a playback device object and a capture device object, you should advise the user to check the audio device properties to ensure that full duplex is enabled.


Capture Device Capabilities

To retrieve the capabilities of a capture device, call the IDirectSoundCapture8::GetCaps method. The parameter to this method is a pointer to a DSCCAPS structure. As with other such structures, you have to initialize the dwSize member before passing it. On return, the structure contains the number of channels the device supports, as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.

On non-WDM drivers, a capture device can be used by only one application at a time. If the driver supports simultaneous use of the device by more than one application, DSCCAPS_MULTIPLECAPTURE is returned in the dwFlags member of DSCCAPS. Each application can set its own format for the capture buffer.


Creating a Capture Buffer

To create a capture buffer, call the IDirectSoundCapture8::CreateCaptureBuffer method.

One of the parameters to the method is a DSCBUFFERDESC structure that describes the characteristics of the desired buffer. The last member of this structure is a WAVEFORMATEX structure, which must be initialized with the details of the desired WAV format.

Note that if your application is playing sounds as well as capturing them, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example function creates a capture buffer that will hold 1 second of data. Note that the interface to the capture device object passed in as a parameter must be obtained by using the DirectSoundCaptureCreate8 function rather than the earlier DirectSoundCaptureCreate function; otherwise the buffer will not support the IDirectSoundCaptureBuffer8 interface.

HRESULT CreateCaptureBuffer(LPDIRECTSOUNDCAPTURE8 pDSC,
                            LPDIRECTSOUNDCAPTUREBUFFER8* ppDSCB8)
{
  HRESULT hr;
  DSCBUFFERDESC               dscbd;
  LPDIRECTSOUNDCAPTUREBUFFER  pDSCB;
  WAVEFORMATEX                wfx =
    {WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0};
    // wFormatTag, nChannels, nSamplesPerSec, mAvgBytesPerSec,
    // nBlockAlign, wBitsPerSample, cbSize

  if ((NULL == pDSC) || (NULL == ppDSCB8)) return E_INVALIDARG;
  dscbd.dwSize = sizeof(DSCBUFFERDESC);
  dscbd.dwFlags = 0;
  dscbd.dwBufferBytes = wfx.nAvgBytesPerSec;
  dscbd.dwReserved = 0;
  dscbd.lpwfxFormat = &wfx;
  dscbd.dwFXCount = 0;
  dscbd.lpDSCFXDesc = NULL;

  if (SUCCEEDED(hr = pDSC->CreateCaptureBuffer(&dscbd, &pDSCB, NULL)))
  {
    hr = pDSCB->QueryInterface(IID_IDirectSoundCaptureBuffer8, (LPVOID*)ppDSCB8);
    pDSCB->Release();
  }
  return hr;
}


Capture Buffer Information

You can use the IDirectSoundCaptureBuffer8::GetCaps method to retrieve the size of a capture buffer. Be sure to initialize the dwSize member of the DSCBCAPS structure before passing it as a parameter.

To retrieve information about the format of the data in the buffer, as set when the buffer was created, call IDirectSoundCaptureBuffer8::GetFormat. This method returns the format information in a WAVEFORMATEX structure.

Note that your application can allow for extra format information in the WAVEFORMATEX structure by first calling the GetFormat method with NULL as the lpwfxFormat parameter. In this case the DWORD pointed to by the lpdwSizeWritten parameter receives the size of the structure needed to receive complete format information.

To find out what a capture buffer is currently doing, call the IDirectSoundCaptureBuffer8::GetStatus method. This method fills a DWORD variable with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to IDirectSoundCaptureBuffer8::Start.

The IDirectSoundCaptureBuffer8::GetCurrentPosition method returns the offsets of the read and capture cursors within the buffer. The read cursor is at the end of the data that has been fully captured into the buffer at this point. The capture cursor is at the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read cursor.


Capture Buffer Notification

To copy data out of the capture buffer at regular intervals, your application has to know when the read cursor, which is the point up to which it is safe to read data, reaches certain points in the buffer. One way to get this information is to poll the position of the read cursor using IDirectSoundCaptureBuffer8::GetCurrentPosition. A more efficient way is to use notifications. Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is running.

First you must obtain the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to SetNotificationPositions.

The following example sets up three notification positions in a one-second buffer. One event will be signaled when the read position nears the halfway point in the buffer, another will be signaled when it nears the end of the buffer, and the third will be signaled when capture stops.

HRESULT SetCaptureNotifications(LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB)
{
  #define cEvents  3

  LPDIRECTSOUNDNOTIFY8 pDSNotify;
  WAVEFORMATEX         wfx;
  HANDLE     rghEvent[cEvents] = {0};
  DSBPOSITIONNOTIFY  rgdsbpn[cEvents];
  HRESULT    hr;

  if (NULL == pDSCB) return E_INVALIDARG;
  if (FAILED(hr = pDSCB->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&pDSNotify)))
  {
    return hr;
  }
  if (FAILED(hr = pDSCB->GetFormat(&wfx, sizeof(WAVEFORMATEX), NULL)))
  {
    return hr;
  }

  // Create events.
  for (int i = 0; i < cEvents; ++i)
  {
    rghEvent[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (NULL == rghEvent[i])
    {
      hr = GetLastError();
      return hr;
    }
  }

  // Describe notifications.

  rgdsbpn[0].dwOffset = (wfx.nAvgBytesPerSec/2) -1;
  rgdsbpn[0].hEventNotify = rghEvent[0];

  rgdsbpn[1].dwOffset = wfx.nAvgBytesPerSec - 1;
  rgdsbpn[1].hEventNotify = rghEvent[1];

  rgdsbpn[2].dwOffset = DSBPN_OFFSETSTOP;
  rgdsbpn[2].hEventNotify = rghEvent[2];

  // Create notifications.

  hr = pDSNotify->SetNotificationPositions(cEvents, rgdsbpn);
  pDSNotify->Release();
  return hr;
}


Capture Buffer Effects

Two capture buffer effects are available as kernel mode implementations on Microsoft® Windows® XP:

  • Acoustic echo cancellation (AEC)
  • Noise suppression

Both the DirectSoundFullDuplexCreate8 function and the IDirectSoundCapture8::CreateCaptureBuffer method take as a parameter a DSCBUFFERDESC structure that points to an array of DSCEFFECTDESC structures describing desired effects. However, to use the Microsoft implementations you must create the capture buffer by using DirectSoundFullDuplexCreate8. You must also play the secondary sound buffer created by that function; until you do so, the effects are not applied.

In the dwFlags member for each DSCEFFECTDESC structure, you must specify either DSCFX_LOCHARDWARE or DSCFX_LOCSOFTWARE. In most cases, specify DSCFX_LOCSOFTWARE. Buffer creation fails if the effect is not available in the specified location.

The effect is identified in the guidDSCFXClass member of the DSCEFFECTDESC structure. To obtain the Microsoft software implementation, specify DSCFX_MS_AEC or DSCFX_MS_NS in the guidDSCFXInstance member. To use another implementation available in hardware or software, obtain the class and instance GUID from the manufacturer.

After the buffer has been created, you can retrieve information about the effects by using the IDirectSoundCaptureBuffer8::GetFXStatus method.

Acoustic echo cancellation (AEC) is primarily of interest for applications that use voice communication from one site to another. The signal from a microphone at site A is output from the speakers at site B and picked up by the microphone at site B. Without AEC, the signal is then sent back to site A, resulting in an echo and possibly a feedback squeal. AEC overcomes this problem by monitoring the incoming signal at each site, adjusting it to take the room environment into account, and then removing it from the outgoing signal. It also removes any local sounds being played by the computer, such as music, so that these do not interfere with the voice signal being sent over the network.

AEC has the following limitations:

  • If the acoustic environment changes, the adaptive filter can take two seconds or more to adjust.
  • Any late reverberations occurring more than 128 milliseconds after the original signal are not removed from the outgoing signal.
  • Only one capture buffer at a time can use AEC.
  • AEC cannot be created if another application is capturing.
  • Regardless of the input or output format, the kernel mixer processes the sound in 16-bit mono format. As a result, the quality of the sound may be reduced. To minimize processor usage, capture sounds in a 16-bit mono format.
  • AEC does not work with some combinations of sound cards and drivers. Applications should always provide the user with the option of turning off AEC.

Use the IDirectSoundCaptureFXAec8·interface to set and retrieve AEC parameters on a capture buffer that contains this effect. You can also enable noise fill, which is a means of preventing complete silence when there is no new data in the outgoing signal.

Noise suppression can be applied only if AEC is also enabled. The noise suppression capture effect removes constant background noise, such as fan noise. Use the IDirectSoundCaptureFXNoiseSuppress8 interface to set and retrieve parameters.

The effect interfaces are obtained from the capture buffer object by using IDirectSoundCaptureBuffer8::GetObjectInPath.


Using the Capture Buffer

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the IDirectSoundCaptureBuffer8::Start method. Normally you should pass DSCBSTART_LOOPING in the dwFlags parameter so that the buffer will keep running continuously rather than stopping when it reaches the end. Audio data from the input device begins filling the buffer from the beginning.
  2. Wait until the desired amount of data is available. For one method of determining when the capture cursor reaches a certain point, see Capture Buffer Notification.
  3. When sufficient data is available, lock a portion of the capture buffer by calling the IDirectSoundCaptureBuffer8::Lock method.

    To make sure you are not attempting to lock a portion of memory that is about to be used for capture, you can first obtain the position of the read cursor by calling IDirectSoundCaptureBuffer8::GetCurrentPosition.

    As parameters to the Lock method, you pass the size and offset of the block of memory you want to read. The method returns a pointer to the address where the memory block begins, and the size of the block. If the block wraps around from the end of the buffer to the beginning, two pointers are returned, one for each section of the block. The second pointer is NULL if the locked portion of the buffer does not wrap around.

  4. Copy the data from the buffer, using the addresses and block sizes returned by the Lock method.
  5. Unlock the buffer with the IDirectSoundCaptureBuffer8::Unlock method.
  6. Repeat steps 2 to 5 until you are ready to stop capturing data. Then call the IDirectSoundCaptureBuffer8::Stop method.


Writing to a WAV File

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

The DirectSound API does not include methods for writing to WAV files. However, the Dsutil.cpp file used by many of the SDK sample applications implements a CWaveFile class that has the following methods for managing capture files:

  • Open. Opens a file and writes the header chunks.
  • Write. Writes from a buffer to the data chunk and advances the write cursor.
  • Close. Writes the size of the data chunk in the header and closes the file.

The first step in writing a WAV file is to call the CWaveFile::Open method. This creates the file and writes the WAV format chunk. The parameters are the filename, a pointer to an initialized WAVEFORMATEX structure, and the WAVEFILE_WRITE flag. The method returns an HRESULT.

The following code opens a WAV file for writing:

CWaveFile   g_pWaveFile;
WAVEFORMATEX  wfxInput;

ZeroMemory( &wfxInput, sizeof(wfxInput));
wfxInput.wFormatTag = WAVE_FORMAT_PCM;
wfxInput.nSamplesPerSec = 22050
wfxInput.wBitsPerSample =  8;
wfxInput.nChannels = 1;
wfxInput.nBlockAlign =
    wfxInput.nChannels * (wfxInput.wBitsPerSample / 8);
wfxInput.nAvgBytesPerSec =
    wfxInput.nBlockAlign * wfxInput.nSamplesPerSec;

g_pWaveFile = new CWaveFile;
if (FAILED(g_pWaveFile->Open("mywave.wav", &wfxInput,
    WAVEFILE_WRITE)))
{
  g_pWaveFile->Close();
}

The application can now begin copying data from the capture buffer to the file.

The following example function is called each time the read cursor reaches a notification position. In this function, the following global variables are used:

  • g_pDSBCapture is a pointer to the IDirectSoundCaptureBuffer8 interface of the capture buffer.
  • g_dwNextCaptureOffset tracks the buffer offset of the next block of data that will be copied to the file.
  • g_dwCaptureBufferSize is the size of the capture buffer, used in calculating wraparound.
HRESULT RecordCapturedData()
{
  HRESULT hr;
  VOID* pbCaptureData  = NULL;
  DWORD dwCaptureLength;
  VOID* pbCaptureData2 = NULL;
  DWORD dwCaptureLength2;
  VOID* pbPlayData   = NULL;
  UINT  dwDataWrote;
  DWORD dwReadPos;
  LONG lLockSize;

  if (NULL == g_pDSBCapture)
      return S_FALSE;
  if (NULL == g_pWaveFile)
      return S_FALSE;

  if (FAILED (hr = g_pDSBCapture->GetCurrentPosition(
    NULL, &dwReadPos)))
      return hr;

  // Lock everything between the private cursor
  // and the read cursor, allowing for wraparound.

  lLockSize = dwReadPos - g_dwNextCaptureOffset;
  if( lLockSize < 0 ) lLockSize += g_dwCaptureBufferSize;

  if( lLockSize == 0 ) return S_FALSE;

  if (FAILED(hr = g_pDSBCapture->Lock(
        g_dwNextCaptureOffset, lLockSize,
        &pbCaptureData, &dwCaptureLength,
        &pbCaptureData2, &dwCaptureLength2, 0L)))
    return hr;

  // Write the data. This is done in two steps
  // to account for wraparound.

  if (FAILED( hr = g_pWaveFile->Write( dwCaptureLength,
      (BYTE*)pbCaptureData, &dwDataWrote)))
    return hr;

  if (pbCaptureData2 != NULL)
  {
    if (FAILED(hr = g_pWaveFile->Write(
        dwCaptureLength2, (BYTE*)pbCaptureData2,
        &dwDataWrote)))
      return hr;
  }

  // Unlock the capture buffer.

 g_pDSBCapture->Unlock( pbCaptureData, dwCaptureLength,
    pbCaptureData2, dwCaptureLength2  );

  // Move the capture offset forward.

  g_dwNextCaptureOffset += dwCaptureLength;
  g_dwNextCaptureOffset %= g_dwCaptureBufferSize;
  g_dwNextCaptureOffset += dwCaptureLength2;
  g_dwNextCaptureOffset %= g_dwCaptureBufferSize;

  return S_OK;
}

When capturing is finished, the application closes the WAV file.

g_pWaveFile->Close();

See Also

  • CaptureSound Sample


Advanced Topics in DirectSound

This section contains information about optimizations and advanced features not needed by all Microsoft® DirectSound® applications.

Information is presented in the following topics:

  • DirectSound Driver Models
  • Property Sets for DirectSound Buffers
  • Optimizing DirectSound Performance
  • Writing to the Primary Buffer


DirectSound Driver Models

Under the VXD driver model, all DirectSound mixing is done in Dsound.vxd, a virtual device driver. Dsound.vxd also provides close access to the actual DMA buffer that the sound card uses to receive data from the host CPU. This is the same as the DirectSound primary buffer. A DirectSound application can set specific properties of the primary buffer, such as sampling rate and bit depth, thus changing the properties of the hardware itself.

Under the Windows Driver Model (WDM), DirectSound does not have direct access to the sound hardware, except in the case of hardware-accelerated buffers. Instead, DirectSound sends data to the kernel mixer. The kernel mixer's job is to convert the format of multiple audio streams to a common format, mix them together and send the result to the hardware. In a sense, it does what Dsound.vxd does. One major difference is that Dsound.vxd mixes only DirectSound buffer data, but the kernel mixer mixes all Windows audio data, including data from applications that use the Win32 waveOut functions. The rule that DirectSound and the waveform-audio output device cannot both be open at the same time is not true on systems with WDM drivers.

Of particular importance is the kernel mixer's relationship with the audio hardware. the kernel mixer is the only software on the system that can specify the format of the hardware's DMA buffer. It selects the format on the basis of sounds it is asked to mix. It sets the output format to the highest-quality format of sounds that it is asked to mix, or to the closest format to this that the hardware supports.

This has one very important implication: DirectSound cannot set the format of the hardware's DMA buffer. For your application, this means that the hardware format is based on the data you actually play. If you play a 44 kHz file, Kmixer will mix all data up to 44 kHz and ensure that the hardware is running at 44 kHz.

As an application developer, you don't choose the driver model used. That is completely determined by the type of sound card, the version of Windows, and the installed driver. For this reason, it is very important that you cover all possibilities when you test your application. DirectSound might be using Dsound.vxd or it might be using the kernel mixer, and you should ensure that your application's behavior and performance are acceptable on both.


System Property Sets

Information about system-wide DirectSound device properties can be obtained from an object of class CLSID_DirectSoundPrivate (11AB3EC0-25EC-11d1-A4D8-00C04FC28ACA). This class supports the IKsPropertySet interface. The CLSID and properties are defined in Dsconf.h.

  1. To create an object of this classCall the LoadLibrary function to load Dsound.dll.
  2. Call the GetProcAddress function to obtain the DllGetClassObject function.
  3. Call DllGetClassObject to obtain the IClassFactory interface of the class factory for the CLSID_DirectSoundPrivate class.
  4. Call IClassFactory::CreateInstance to create the CLSID_DirectSoundPrivate object and retrieve the IKsPropertySet interface (IID_IKsPropertySet).

The CLSID_DirectSoundPrivate object supports one property set, DSPROPSETID_DirectSoundDevice (84624F82-25EC-11d1-A4D8-00C04FC28ACA). This property set exposes the following three read-only properties.

  • DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING
  • DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION
  • DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING

This property retrieves the DirectSound device GUID corresponding to a specified Windows Multimedia device name.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
DeviceName | String | [in] Name of device
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [out] DirectSound device ID

DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION

This property retrieves a full description of a DirectSound device specified by GUID.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
Type | DIRECTSOUNDDEVICE_TYPE | [out] Device type: DIRECTSOUNDDEVICE_TYPE_EMULATED, DIRECTSOUNDDEVICE_TYPE_VXD or DIRECTSOUNDDEVICE_TYPE_WDM
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in, out] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [in] DirectSound device GUID, or NULL for the default device of the type specified by DataFlow
Description | String | [out] Description of DirectSound device
Module | String | [out] Module name of the DirectSound driver
Interface | String | [out] PnP device interface name
WaveDeviceID | ULONG | [out] Identifier of the corresponding Windows Multimedia device

DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

This property enumerates all DirectSound render or capture devices.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_DATA structure, available in Ansi and Unicode versions. This structure has the following members.

Member | Type | Description
Callback | LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK | [in] Application-defined callback function. When IKsPropertySet::Get is called, this function is called once for each device enumerated. It takes as parameters a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure describing the enumerated device, and the value in Context.
Context | LPVOID | [in] User-defined value to be passed to the callback function for each device enumerated.


Property Sets for DirectSound Buffers

To make use of extended properties on sound cards, you must first determine whether the driver supports the IKsPropertySet interface, and obtain a pointer to the interface if it is supported. You can do this by calling the QueryInterface method of an existing interface on a DirectSound 3-D buffer object, as follows:

HRESULT hr = lpDirectSound3DBuffer->QueryInterface(
    IID_IKsPropertySet,
    (void**)&lpKsPropertySet));

In the example, lpDirectSound3DBuffer is a pointer to the buffer's interface and lpKsPropertySet receives the address of the IKsPropertySet interface if one is found. IID_IKsPropertySet is a GUID defined in Dsound.h. The interface is available only if the buffer is hardware-accelerated and the underlying driver supports property sets.

Note The declaration of this interface in Dsound.h is different from that in Ksproxy.h and Strmif.h. If your project includes Ksproxy.h or Strmif.h but you wish to use the DirectSound implementation, be sure to include Dsound.h first. Failing to do so may cause your application to stop responding when a method of IKsPropertySet is called.

You can look for a particular property by using the IKsPropertySet::QuerySupport method. The value of the PropertySetId parameter is a GUID defined by the hardware vendor.

After you've determined that support for a particular property exists, you can change the state of the property by using the IKsPropertySet::Set method and determine its present state by using the IKsPropertySet::Get method. The state of the property is set or returned in the pPropertyData parameter.

Additional property parameters may also be passed to the object in the pPropertyParams parameter to the IKsPropertySet::Set method. The exact way in which this parameter is to be used is defined in the hardware vendor's specifications for the property set, but typically it would be used to define the instance of the property set. In practice, the pPropertyParams parameter is rarely used.


Optimizing DirectSound Performance

This section offers miscellaneous tips for improving the performance of applications that play their audio data directly into DirectSound buffers. The following topics are covered:

  • Using Hardware Mixing
  • Dynamic Voice Management
  • Using Buffers Efficiently


Using Hardware Mixing

Modern sound cards are designed to connect to the peripheral component interconnect (PCI) local bus. This bus provides the card with rapid access to system memory. As a result, it is practical for the audio processor to mix data directly from buffers in system memory, and it is unnecessary to have memory buffers on the card itself.

On PCI cards, static buffers and streaming buffers are effectively the same, and the same buffers may be reported in DSCAPS as both static and streaming buffers. The DSBCAPS_STATIC flag in DSBUFFERDESC does not affect the location of a DirectSound buffer.

The following tips will help you make the most of hardware mixing.

  • At run time, use the IDirectSound8::GetCaps method to determine what formats are supported by the sound-accelerator hardware, and use only those formats if possible.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • To force a buffer to be created in hardware, specify the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBUFFERDESC structure. If you do this and resources for hardware mixing are not available, the IDirectSound8::CreateSoundBuffer method will fail.
  • Use voice management to enable DirectSound to assign buffers to hardware resources when they are available, and to force termination of less important buffers in order to free hardware resources. See Dynamic Voice Management.


Dynamic Voice Management

Many sound cards maintain their own secondary buffers and handle 3-D effects and mixing for them. These hardware buffers, as they are called, usually reside in system memory rather than on the card itself, but because they are mixed by the device, they make far smaller demands on the system processor than do software buffers. It is therefore most efficient to have as many buffers as possible allocated to hardware, especially 3-D buffers.

By default, DirectSound allocates buffers to hardware whenever it can. However, it can create only as many hardware buffers as the device can play at one time. In other words, the number of hardware buffers is limited by the availability of hardware voices. DirectSound allocates a hardware voice when a buffer is created and releases it only when the buffer is destroyed. If an application creates many buffers, some of them will likely end up in software, which means that they will be managed and mixed by the CPU rather than the sound card.

Note The DirectSound voice manager allocates hardware mixing resources, not memory. On a PCI card, the buffer occupies the same memory before and after it is allocated, regardless of whether it is allocated to the hardware mixer or the software mixer.

Dynamic voice management helps you overcome the limited availability of hardware resources by deferring voice allocation until buffers are played, and by enabling DirectSound to stop lower-priority sounds prematurely and release their resources so that these resources can be allocated to new sounds.

To defer the allocation of resources for hardware mixing and 3-D effects to the moment when the buffer is played, specify the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure passed to IDirectSound8::CreateSoundBuffer. When you call IDirectSoundBuffer8::Play or IDirectSoundBuffer8::AcquireResources on such a buffer, DirectSound places the buffer in hardware if possible, and in software otherwise.

When calling Play, you can attempt to free a hardware voice for the buffer by passing one of the flags in the following table, or one of the first two flags in combination with the third. DirectSound then searches for a playing buffer that is suitable for termination as specified by the flags.

Flag | Criterion
DSBPLAY_TERMINATEBY_TIME | Select the buffer that has been playing longer than any other candidate buffers.
DSBPLAY_TERMINATEBY_DISTANCE | Select the 3-D candidate buffer farthest from the listener.
DSBPLAY_TERMINATEBY_PRIORITY | Select the buffer that has the lowest priority of candidate buffers, as set in the call to Play. If this is combined with one of the other two flags, the other flag is used only to resolve ties.

If it finds a suitable buffer, DirectSound stops it and allocates the voice it was using to the newly played buffer. If no buffer is suitable for termination, the newly played buffer is played in software, unless the DSBPLAY_LOCHARDWARE flag was specified, in which case the call to Play fails.

For more information on how deferred buffers are dealt with when played, see IDirectSoundBuffer8::Play.

Note Do not use the DSBCAPS_STATIC flag in combination with DSBCAPS_LOCDEFER when creating buffers. DSBCAPS_STATIC buffers are placed in on-card memory when this is available, as is the case on some older cards. If you create such a buffer with the DSBCAPS_LOCDEFER flag, the buffer memory is not copied to the sound card until the buffer is played for the first time, which can result in unacceptable delays.


Using Buffers Efficiently

When using streaming buffers, limit the frequency of notifications and data writes. Do not create buffers with many notification positions, or small buffers with notifications at very short intervals. A streaming buffer can hold a second or two of data and have just two notification positions.

Performance is affected when you change the pan, volume, or frequency on a secondary buffer. This is because DirectSound mixes sounds a short time before playing them, and any change causes the premix buffer to be flushed and remixed.

To minimize the number of control changes, reduce the frequency of calls to IDirectSoundBuffer8::SetVolume, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetFrequency. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame. On 3-D buffers, use deferred settings to make

Keep in mind that 3-D buffers in software make high demands on the central processing unit. To limit these demands you can do the following:

  • Put frequently-used sounds in hardware buffers if possible.
  • Don't create 3-D buffers for sounds that won't benefit from the effect.
  • Use IDirectSound3DBuffer8::SetMode with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer that is no longer moving in relation to the listener.
  • Make parameter changes in batches, or use deferred settings to make changes to all buffers and the listener at once.

See Also

  • Batch Parameters for 3-D Buffers
  • Batch Parameters for 3-D Listeners
  • Deferred Settings
  • Minimum and Maximum Distances


Writing to the Primary Buffer

For applications that require specialized mixing or other effects not supported by secondary buffers, DirectSound allows direct access to the primary buffer.

When you obtain write access to the primary buffer, other DirectSound features become unavailable. Secondary buffers are not mixed, so hardware-accelerated mixing is unavailable.

Most applications should use secondary buffers instead of directly accessing the primary buffer. Applications can write to a secondary buffer easily because the larger buffer size provides more time to write the next block of data, thereby minimizing the risk of gaps in the audio. Even if an application has simple audio requirements, such as using one stream of audio data that does not require mixing, it will achieve better performance by using a secondary buffer to play its audio data.

Note Writing directly to the primary buffer offers no advantages under the Windows driver model (WDM). Under WDM, the primary buffer is in effect a secondary buffer that is mixed by the kernel mixer. For more information on WDM, see DirectSound Driver Models.

You cannot specify the size of the primary buffer, and you must accept the returned size after the buffer is created. A primary buffer is typically very small, so if your application writes directly to this kind of buffer, it must write blocks of data at short intervals to prevent the previously written data from being replayed.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the IDirectSoundBuffer8::GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBCAPS structure that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer. Note that the primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

BOOL AppCreateWritePrimaryBuffer(
  LPDIRECTSOUND8 lpDirectSound,
  LPDIRECTSOUNDBUFFER *lplpDsb,
  LPDWORD lpdwBufferSize,
  HWND hwnd)
{
  DSBUFFERDESC dsbdesc;
  DSBCAPS dsbcaps;
  HRESULT hr;
  WAVEFORMATEX wf;

  // Set up wave format structure.
  memset(&wf, 0, sizeof(WAVEFORMATEX));
  wf.wFormatTag = WAVE_FORMAT_PCM;
  wf.nChannels = 2;
  wf.nSamplesPerSec = 22050;
  wf.nBlockAlign = 4;
  wf.nAvgBytesPerSec =
      wf.nSamplesPerSec * wf.nBlockAlign;
  wf.wBitsPerSample = 16;

  // Set up DSBUFFERDESC structure.
  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
  // Buffer size is determined by sound hardware.
  dsbdesc.dwBufferBytes = 0;
  dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.

  // Obtain write-primary cooperative level.
  hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_WRITEPRIMARY);
  if SUCCEEDED(hr)
  {
    // Try to create buffer.
    hr = lpDirectSound->CreateSoundBuffer(&dsbdesc,
      lplpDsb, NULL);
    if SUCCEEDED(hr)
    {
      // Set primary buffer to desired format.
      hr = (*lplpDsb)->SetFormat(&wf);
      if SUCCEEDED(hr)
      {
        // If you want to know the buffer size, call GetCaps.
        dsbcaps.dwSize = sizeof(DSBCAPS);
        (*lplpDsb)->GetCaps(&dsbcaps);
        *lpdwBufferSize = dsbcaps.dwBufferBytes;
        return TRUE;
      }
    }
  }
  // Failure.
  *lplpDsb = NULL;
  *lpdwBufferSize = 0;
  return FALSE;
}

The following example illustrates how an application might implement a custom mixer. The AppMixIntoPrimaryBuffer sample function would have to be called at regular intervals, frequently enough to prevent the sound device from repeating blocks of data. The CustomMixer function is an application-defined function that mixes several streams together, as specified in an application-defined APPSTREAMINFO structure, and writes the result to the specified pointer.

BOOL AppMixIntoPrimaryBuffer(
    APPSTREAMINFO* lpAppStreamInfo,
    LPDIRECTSOUNDBUFFER lpDsbPrimary,
    DWORD dwDataBytes,
    DWORD dwOldPos,
    LPDWORD lpdwNewPos)
{
  LPVOID lpvPtr1;
  DWORD dwBytes1;
  LPVOID lpvPtr2;
  DWORD dwBytes2;
  HRESULT hr;
  // Obtain write pointer.
  hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
          &lpvPtr1, &dwBytes1,
          &lpvPtr2, &dwBytes2, 0);

  // If DSERR_BUFFERLOST is returned, restore and retry lock.

  if (DSERR_BUFFERLOST == hr)
  {
    lpDsbPrimary->Restore();
    hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
            &lpvPtr1, &dwBytes1,
            &lpvPtr2, &dwBytes2, 0);
  }
  if SUCCEEDED(hr)
  {
    // Mix data into the returned pointers.
    CustomMixer(lpAppStreamInfo, lpvPtr1, dwBytes1);
    *lpdwNewPos = dwOldPos + dwBytes1;
    if (NULL != lpvPtr2)
    {
      CustomMixer(lpAppStreamInfo, lpvPtr2, dwBytes2);
      *lpdwNewPos = dwBytes2; // Because it wrapped around.
    }
    // Release the data back to DirectSound.
    hr = lpDsbPrimary->Unlock(lpvPtr1, dwBytes1,
            lpvPtr2, dwBytes2);
    if SUCCEEDED(hr)
    {
      return TRUE;
    }
  }
  // Lock or Unlock failed.
  return FALSE;
}


DirectSound C++ Samples

The sample applications described in this section demonstrate the use and capabilities of the Microsoft® DirectMusic® application programming interface (API) in Microsoft® DirectX® for C++.

The following samples are found on the Start menu under Programs/Microsoft DirectX 9.0 SDK/C++ Samples/DirectSound Samples.

  • AdjustSound Sample
  • AmplitudeModulation Sample
  • CaptureSound Sample
  • Enumerate DirectSound Devices Sample
  • Full Duplex Filter Sample
  • Play 3D Sound Sample
  • Play Sound Sample
  • SoundFX Sample
  • Stream Data Sample
  • Voice Management Sample

The source code is in the following folder, where SDK root is the installation folder for the DirectX SDK, such as C:\DXSDK:

(SDK root)\samples\C++\DirectSound

The samples use common source files that implement functions and classes for basic DirectSound functionality and for general tasks such as finding media files. For more information, see DirectSound Sample Framework.


DirectSound Sample Framework

The core functionality for the DirectSound samples is in a common set of classes, declared in Dsutil.h and implemented in Dsutil.cpp.

These files are found in the following folders:

(SDK root)\samples\C++\Common\Include
(SDK root)\samples\C++\Common\Src

To use the sample framework, your project must link to Dxerr9.lib and Winmm.lib.

The framework classes provide basic functionality for the samples, and you can use them as a starting-point for your own applications. However, they are not intended to be a full-featured wrapper for the DirectSound API.

The following classes are used in the samples:

Class | Description
CSound Sample Class | Represents a static buffer.
CSoundManager Sample Class | Contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.
CStreamingSound Sample Class | Represents a sound in one or more streaming buffers.
CWaveFile Sample Class | Used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory.

See Also

  • DirectSound C++ Samples


CSound Sample Class

The CSound sample class represents a sound in one or more static buffers. An object of this class can be used to play multiple instances of a sound effect. The object is usually created through a call to the Create method of the CSoundManager Sample Class.

class CSound
{
protected:
    LPDIRECTSOUNDBUFFER* m_apDSBuffer;
    DWORD                m_dwDSBufferSize;
    CWaveFile*           m_pWaveFile;
    DWORD                m_dwNumBuffers;
    DWORD                m_dwCreationFlags;

    HRESULT RestoreBuffer(LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored);

public:
    CSound(LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize,
        DWORD dwNumBuffers, CWaveFile* pWaveFile, DWORD dwCreationFlags);
    virtual ~CSound();

    HRESULT Get3DBufferInterface(DWORD dwIndex,
        LPDIRECTSOUND3DBUFFER* ppDS3DBuffer);
    HRESULT FillBufferWithSound(LPDIRECTSOUNDBUFFER pDSB,
        BOOL bRepeatWavIfBufferLarger);
    LPDIRECTSOUNDBUFFER GetFreeBuffer();
    LPDIRECTSOUNDBUFFER GetBuffer(DWORD dwIndex);
    HRESULT Play(DWORD dwPriority = 0, DWORD dwFlags = 0,
        LONG lVolume = 0, LONG lFrequency = 0);
    HRESULT Play3D(LPDS3DBUFFER p3DBuffer, DWORD dwPriority = 0,
        DWORD dwFlags = 0, LONG lFrequency = 0);
    HRESULT Stop();
    HRESULT Reset();
    BOOL    IsSoundPlaying();
};

Constructor

The constructor fills one or more buffers with the data from a specified WAV file and initializes private data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
FillBufferWithSound | Fills the specified buffer with the data from the WAV file that was passed to the object constructor. If the buffer is larger than the data, data can optionally be repeated; otherwise the rest of the buffer is filled with silence.
Get3DBufferInterface | Retrieves the IDirectSound3DBuffer8 interface pointer for the specified buffer, if the buffer has 3-D capabilities.
GetBuffer | Retrieves the IDirectSoundBuffer interface of the specified buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
GetFreeBuffer | Retrieves the IDirectSoundBuffer interface of the first buffer that is not playing. If all buffers are playing, the method returns a randomly selected buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
IsSoundPlaying | Returns a Boolean variable that indicates whether the specified buffer is playing.
Play | Plays a buffer. The method selects the buffer to play by calling GetFreeBuffer, and restores it if necessary The application can pass in a voice management flag; the DSBPLAY_LOOPING flag to repeat the sound; a volume in hundredths of decibels (where 0 is full volume and -10,000 is silence); and a frequency in hertz that is added to the basic frequency of the sound.
Play3D | Plays a 3-D buffer. This method is similar to Play, but the application also passes in a DS3DBUFFER structure describing the 3-D parameters to be set. (Note that if the CSound object has more than one buffer, there is no way to determine which one is played by this call. If you want to set 3-D parameters dynamically while the buffer is playing, add functionality to return a buffer pointer.)
Reset | Sets the play cursor on all buffers to the beginning.
Stop | Stops all buffers.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • DirectSound Buffers


CSoundManager Sample Class

The CSoundManager sample class contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.

class CSoundManager
{
protected:
    LPDIRECTSOUND8 m_pDS;

public:
    CSoundManager();
    ~CSoundManager();

    HRESULT Initialize( HWND hWnd, DWORD dwCoopLevel );
    inline  LPDIRECTSOUND8 GetDirectSound() { return m_pDS; }
    HRESULT SetPrimaryBufferFormat( DWORD dwPrimaryChannels,
        DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
    HRESULT Get3DListenerInterface(LPDIRECTSOUND3DLISTENER* ppDSListener );
    HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName,
        DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL,
        DWORD dwNumBuffers = 1 );
    HRESULT CreateFromMemory( CSound** ppSound, BYTE* pbData,
        ULONG ulDataSize, LPWAVEFORMATEX pwfx, DWORD dwCreationFlags = 0,
        GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
    HRESULT CreateStreaming( CStreamingSound** ppStreamingSound,
        LPTSTR strWaveFileName, DWORD dwCreationFlags,
        GUID guid3DAlgorithm, DWORD dwNotifyCount, DWORD dwNotifySize,
        HANDLE hNotifyEvent );
};

Constructor

The constructor initializes a data member.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Create | Creates a CSound object associated with a WAV file and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateFromMemory | Creates a CSound object associated with a waveform in memory and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateStreaming | Creates a CStreamingSound object associated with a WAV file and containing a single streaming buffer. The application specifies notification positions and an event. In response to notifications, the application calls CStreamingSound::HandleWaveStreamNotification to refresh the data in the buffer. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
Get3DListenerInterface | Retrieves the IDirectSound3DListener8 interface.
GetDirectSound | Retrieves the IDirectSound8 interface of the DirectSound object created by Initialize.
Initialize | Creates the DirectSound object and sets the cooperative level.
SetPrimaryBufferFormat | Sets the format of the primary buffer. This method should not be used by most applications. For more information, see Mixing Sounds.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • CSound Sample Class
  • CStreamingSound Sample Class
  • DirectSound Buffers


CStreamingSound Sample Class

The CStreamingSound sample class represents a streaming buffer. The class inherits from CSound. An object of this class is usually created through a call to the CreateStreaming method of the CSoundManager Sample Class.

A CStreaming object has only one buffer. When calling methods inherited from CSound that take a buffer index, pass 0.

class CStreamingSound : public CSound
{
protected:
    DWORD m_dwLastPlayPos;
    DWORD m_dwPlayProgress;
    DWORD m_dwNotifySize;
    DWORD m_dwNextWriteOffset;
    BOOL  m_bFillNextNotificationWithSilence;

public:
    CStreamingSound(LPDIRECTSOUNDBUFFER pDSBuffer, DWORD dwDSBufferSize,
        CWaveFile* pWaveFile, DWORD dwNotifySize);
    ~CStreamingSound();

    HRESULT HandleWaveStreamNotification(BOOL bLoopedPlay);
    HRESULT Reset();
};

Constructor

The constructor calls the CSound constructor to fill the buffer with data from the beginning of the WAV file, and initializes private data members.

Public Methods

In addition to the methods inherited from CSound, the class contains the following public methods, in alphabetical order.

Method | Description
HandleWaveStreamNotification | Restores the buffer if necessary, then reads data from the file and writes it to the part of the buffer that has just been played. If the end of data is reached, the rest of the buffer is filled with silence, and the buffer is stopped after all data has been played. Call this method in response to notifications received in the message loop. Pass in TRUE as the parameter to repeat the sound when it reaches the end.
Reset | Restores the buffer if necessary, then resets the play position and the file so that the sound can begin playing again from the beginning.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • CSound Sample Class
  • DirectSound Buffers


CWaveFile Sample Class

The CWaveFile sample class is used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory. An object of this class is created by CSoundManager when creating a CSound or CStreamingSound object. Applications do not usually need to call methods of CWaveFile directly.

class CWaveFile
{
public:
    WAVEFORMATEX* m_pwfx;
    HMMIO         m_hmmio;
    MMCKINFO      m_ck;
    MMCKINFO      m_ckRiff;
    DWORD         m_dwSize;
    MMIOINFO      m_mmioinfoOut;
    DWORD         m_dwFlags;
    BOOL          m_bIsReadingFromMemory;
    BYTE*         m_pbData;
    BYTE*         m_pbDataCur;
    ULONG         m_ulDataSize;
    CHAR*         m_pResourceBuffer;

protected:
    HRESULT ReadMMIO();
    HRESULT WriteMMIO(WAVEFORMATEX *pwfxDest);

public:
    CWaveFile();
    ~CWaveFile();

    HRESULT Open(LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT OpenFromMemory(BYTE* pbData, ULONG ulDataSize,
        WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT Close();
    HRESULT Read(BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead);
    HRESULT Write(UINT nSizeToWrite, BYTE* pbData, UINT* pnSizeWrote);
    DWORD   GetSize();
    HRESULT ResetFile();
    WAVEFORMATEX* GetFormat() { return m_pwfx; };
};

Constructor

The constructor initializes data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Close | Closes the file. If the file is being written to, first writes RIFF chunk sizes.
GetFormat | Returns a WAVEFORMATEX structure describing the format of the waveform.
GetSize | Retrieves the size of the data chunk, after Open has been called.
Open | Opens the file or loads the resource and retrieves the WAV format and data chunk size, or opens the file for writing and writes the header chunks. The strFileName parameter can be a file path or the name of a resource of type "WAVE" or "WAV". Pass WAVEFILE_READ in dwFlags to read from the file, or WAVEFILE_WRITE if capturing to the file. Use the pwfx parameter to specify the format of captured data; this parameter is ignored if the file is being read.
OpenFromMemory | Initializes data members so that subsequent calls to Read will get data from the supplied memory location rather than from a file or resource. It is assumed that the data does not contain any RIFF headers, and that pbData points to the start of the waveform samples.
Read | Reads data from the file, resource, or memory and copies it to the supplied address, which the application is responsible for obtaining by using IDirectSoundBuffer8::Lock. Read advances the pointer into the data by the number of bytes specified in dwSizeToRead.
ResetFile | Resets the pointer into the file or data to the beginning of the data chunk.
Write | Writes data to the file from the specified address, which the application is responsible for obtaining by using IDirectSoundCaptureBuffer8::Lock.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • Reading WAV Data
  • Writing to a WAV File


AdjustSound Sample

Description

The AdjustSound sample shows how to create a DirectSound secondary buffer to play a WAV file, and how to change the parameters of the buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\AdjustSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Focus and Buffer Mixing options; note that the various settings are explained under Expected Behavior as you select them. Click Play. If you don't hear any sound, check the Status pane. The application might fail to create the buffer in hardware if this option has been selected.

By using the sliders you can adjust the frequency, pan, and volume dynamically as the buffer is playing.

Programming Notes

To set the focus behavior of the buffer, the application calls IDirectSound8::CreateSoundBuffer with DSBCAPS_GLOBALFOCUS or DSBCAPS_STICKYFOCUS, or neither of these flags. To set the memory location of the buffer, it sets either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE, or neither of these flags to allow DirectSound to create the buffer in a either hardware or software.

Parameters are set by using IDirectSoundBuffer8::SetFrequency, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetVolume.

For a simpler example of how to set up a DirectSound buffer without as many controls, see the Play Sound Sample.

See Also

  • DirectSound C++ Samples
  • DirectSound Buffers


AmplitudeModulation Sample

Description

The AmplitudeModulation sample shows how to apply an effect to a DirectSound secondary buffer and modify the parameters of the effect.

Path

Source: (SDK root)\Samples\C++\DirectSound\AmplitudeModulation

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Play the default sound or load another WAV file by clicking Sound File. Change the parameters of the effect by selecting one of the Wave Form options and moving the slider to change the modulation rate.

Programming Notes

The application takes the following steps to set an effect on a buffer and change its parameters:

  1. Creates the buffer with the DSBCAPS_CTRLFX flag.
  2. Describe the effect in a DSEFFECTDESC structure, setting the guidDSFXClass member to the GUID of the effect desired.
  3. Passes the buffer description to IDirectSoundBuffer8::SetFX.
  4. Calls IDirectSoundBuffer8::GetObjectInPath to get an interface pointer to the effect, in this case IDirectSoundFXGargle8.
  5. In the OnEffectChanged function, uses IDirectSoundFXGargle8::SetAllParameters to change the parameters of the gargle effect.

See Also

  • DirectSound C++ Samples
  • Using Effects


CaptureSound Sample

Description

The CaptureSound application shows how to capture waveforms to a file.

Path

Source: (SDK root)\Samples\C++\DirectSound\CaptureSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a device and a format. Create a file, or replace an existing one, by clicking Sound File. Click Record to start and stop recording.

Programming Notes

The sample relies on notifications to ascertain when data should be read from the buffer. The notification positions are set up in the InitNotifications function, and the events are received in the WinMain function.

See Also

  • DirectSound C++ Samples
  • Capturing Waveforms


Enumerate DirectSound Devices Sample

Description

The Enumerate DirectSound Devices sample shows how to enumerate and create playback and capture devices.

Path

Source: (SDK root)\Samples\C++\DirectSound\EnumDevices

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a playback and capture device from the dropdown lists. Click Create.

Programming Notes

The sample demonstrates the use of the DSEnumCallback function. The handle of the listbox is passed to this function as the pContext parameter so that the name of the device can be displayed and the GUID can be stored as list item data.

See Also

  • DirectSound C++ Samples
  • Enumerating Capture Devices
  • Enumerating Sound Devices


Full Duplex Filter Sample

Description

The Full Duplex Filter sample application shows how to capture and play back sounds at the same time.

Path

Source: (SDK root)\Samples\C++\DirectSound\FullDuplexFilter

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Be sure your sound card is configured for full-duplex operation and that you have a microphone attached. Choose a format from the Output Format list. A list of formats appears in the Input Format list. Select one. Click OK. If full duplex is successfully created, another dialog box is displayed with a Record button. Click this button. Speak into the microphone and your voice is heard over the speakers.

Programming Notes

The sample does not use the DirectSoundFullDuplexCreate8 function, which is not supported on earlier operating systems. Note that the DirectSound device is created before the DirectSoundCapture device.

See Also

  • DirectSound C++ Samples
  • Creating the Capture Device Object
  • Creating the Device Object


Play 3D Sound Sample

Description

The Play 3D Sound sample shows how to create a 3-D sound buffer and manipulate its properties. It is similar to the 3D Audio Sample but uses only the DirectSound API.

Path

Source: (SDK root)\Samples\C++\DirectSound\Play3DSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Click Sound File and load a WAV file. Play the sound. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

For a simpler example of how to set up a DirectSound buffer without 3-D positioning, see the Play Sound Sample.

The sample obtains an IDirectSound3DListener8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure containing the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer. This creates a primary buffer object with 3-D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DListener8 interface. This interface controls global 3-D properties.

The sample obtains an IDirectSound3DBuffer8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure, setting the DSBCAPS_CTRL3D capabilties flag and and a 3-D virtualization algorithm.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer, creating a secondary buffer object with 3-D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DBuffer8 interface. This interface controls the 3-D properties of sounds played through the buffer.

The application sets the parameters of the listener by calling IDirectSound3DListener8::SetAllParameters. The listener properties are described in a DS3DLISTENER structure. To set the position of the sound source, the application calls IDirectSound3DBuffer8::SetAllParameters, passing in a DS3DBUFFER structure.

If the DS3D_DEFERRED flag is set when parameters are set, nothing is actually changed until IDirectSound3DListener8::CommitDeferredSettings is called. This method commits all deferred settings for buffers as well as the listener, and makes it possible for DirectSound to perform calculations once instead of many times.

See Also

  • DirectSound C++ Samples
  • 3-D Sound


Play Sound Sample

Description

The Play Sound sample shows how to play a WAV file in a DirectSound secondary buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\PlaySound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a sound in a DirectSound Buffer, as follows:

Set up DirectSound:

  1. Call the DirectSoundCreate function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. This sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Load a WAV file into a DirectSound buffer:

  1. Read the WAV file header to get the data size and format.
  2. If the WAV file is a reasonable size, create a secondary buffer in the same format as the data, large enough to hold the entire file. If the WAV file is too large, data will have to be streamed to the buffer. See Stream Data Sample.
  3. Fill the buffer with data. Obtain a pointer into the buffer by calling IDirectSoundBuffer8::Lock. Because data is not being streamed as the buffer is playing, the entire buffer can be locked. After the memory has been copied, call IDirectSoundBuffer8::Unlock.

Play the DirectSound buffer:

  1. Check to see if the buffer has been lost. If so, restore it.
  2. To play the buffer call IDirectSoundBuffer8::Play.

Free DirectSound:

Call Release on all the DirectSound interfaces that were obtained. Release buffers before releasing the DirectSound object.

See Also

  • DirectSound C++ Samples
  • Filling and Playing Static Buffers


SoundFX Sample

Description

The SoundFX sample shows how to use DMOs with DirectSound and how to manipulate effect parameters. It is similar to the DirectMusic AudioFX Sample but does not use an audiopath or any of the DirectMusic interfaces.

Path

Source: (SDK root)\Samples\C++\DirectSound\SoundFX

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

A default sound file is loaded when the application is run. If you wish, load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. An IDirectSoundBuffer8 interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

  • DirectSound C++ Samples
  • Using Effects
  • Using Effects


Stream Data Sample

Description

The Stream Data sample shows how to stream a WAV file to a DirectSound secondary buffer. It is similar to the Play Sound Sample, but adds support for streaming.

Path

Source: (SDK root)\Samples\C++\DirectSound\StreamData

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a streaming sound in a DirectSound secondary buffer.

Set up DirectSound:

  1. Call the DirectSoundCreate8 function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. The sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Create a DirectSound buffer and set up the notifications:

  1. Read the WAV file header to get the data size and format.
  2. Choose a DirectSound buffer size. For this sample, the buffer holds about 3 seconds of data.
  3. Create a DirectSound buffer of that size and with the same format as the WAV file. Also set the DSBCAPS_CTRLPOSITIONNOTIFY flag so that the buffer can send notification events whenever playback has reached certain points in the buffer. On some drivers, using this flag limits the buffer to software, because the hardware buffers do not support position notifications.
  4. Set up the notifications on the buffer by obtaining an IDirectSoundNotify8 interface from the buffer and calling IDirectSoundNotify8::SetNotificationPositions. See the InitDSoundNotification function. When the play cursor passes a notification position, it signals a Win32 event.

Play the DirectSound buffer:

  1. Ascertain if the buffer has been lost, and call IDirectSoundBuffer8::Restore if so.
  2. Fill the entire buffer with data from the file.
  3. Call IDirectSoundBuffer8::Play with the DSBPLAY_LOOPING flag. The looping flag needs to be set so that the buffer will continue playing after the first batch of data has been played.

Check to ascertain if a notification is signaled:

  1. Look for a signaled event in the message loop or in a separate thread by calling MsgWaitForMultipleObjects.
  2. If a buffer notification event has been signaled, lock the section of the buffer that has just been played and fill it with new data. See the HandleNotification function.

Stop the buffer:

When handling the event notification, keep track of how much data has been put in the buffer. When the entire WAV file has been put into the buffer, and after DirectSound has played it all, it is necessary to manually stop the buffer since the buffer will continuously loop otherwise.

See Also

  • DirectSound C++ Samples
  • Using Streaming Buffers


Voice Management Sample

Description

The Voice Management sample shows how to implement dynamic voice management when creating DirectSound secondary buffers.

Path

Source: (SDK root)\Samples\C++\DirectSound\VoiceManagement

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select the Voice Allocation Flags, Buffer Priority, and Voice Management Flags options. Note that the effect of the selected options is described under Expected Behavior. Create the buffer and play the sound by clicking Play.

Programming Notes

To use voice management flags, the buffer must be created using DSBCAPS_LOCDEFER. Otherwise DirectSound will not be able to dynamically place the buffer in either hardware or software at run time.

When playing the buffer, call IDirectSoundBuffer8::Play with a valid combination of voice management flags. Run the sample to observe the result of any combination of flags.

See Also

  • DirectSound C++ Samples
  • Dynamic Voice Management


DirectSound C/C++ Reference

This section contains reference information for the Microsoft® DirectSound® application programming interface (API). Reference material is divided into the following categories.

  • DirectSound Interfaces
  • DirectSound Callback Function
  • DirectSound Functions
  • DirectSound Structures
  • DirectSound Return Values


DirectSound Interfaces

This section contains references for methods of the DirectSound interfaces shown in the following table.

Interface | Description
IDirectSound8 | Used to create buffer objects and set up the environment.
IDirectSound3DBuffer8 | Used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.
IDirectSound3DListener8 | Used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.
IDirectSoundBuffer8 | Used to manage sound buffers.
IDirectSoundCapture8 | Used to create sound capture buffers.
IDirectSoundCaptureBuffer8 | Used to manipulate sound capture buffers.
IDirectSoundCaptureFXAec8 | Used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation.
IDirectSoundCaptureFXNoiseSuppress8 | Used to set and retrieve parameters on a capture buffer that supports noise suppression.
IDirectSoundFullDuplex8 | Represents a full-duplex stream.
IDirectSoundFXChorus8 | Used to set and retrieve effect parameters on a buffer that supports chorus.
IDirectSoundFXCompressor8 | Used to set and retrieve effect parameters on a buffer that supports compression.
IDirectSoundFXDistortion8 | Used to set and retrieve effect parameters on a buffer that supports distortion.
IDirectSoundFXEcho8 | Used to set and retrieve effect parameters on a buffer that supports echo.
IDirectSoundFXFlanger8 | Used to set and retrieve effect parameters on a buffer that supports flange.
IDirectSoundFXGargle8 | Used to set and retrieve effect parameters on a buffer that supports amplitude modulation.
IDirectSoundFXI3DL2Reverb8 | Used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.
IDirectSoundFXParamEq8 | Used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.
IDirectSoundFXWavesReverb8 | Used to set and retrieve effect parameters on a buffer that supports Waves reverberation effects.
IDirectSoundNotify8 | Sets up notification events for a playback or capture buffer.
IKsPropertySet | Enables drivers to provide extended capabilities that can be used without API extensions.

For DirectX 8.0 and later, only IDirectSound8, IDirectSoundBuffer8, and IDirectSoundCaptureBuffer8 are new interfaces that supersede interfaces with similar, unnumbered names. Other interface names ending in 8 are simple defines for unchanged or new unnumbered interfaces. For example, IDirectSoundCapture8 is exactly equivalent to IDirectSoundCapture.

All interfaces that have a defined name ending in 8 are documented under that defined name, and it is recommended that you always use this name in your code.

For information on which methods are supported by an earlier version of an interface, see the declaration of the interface in Dsound.h.

When a method takes an interface pointer as an in parameter, you can pass in the newer version even where the parameter type is declared as the earlier version. For example, a pointer to either IDirectSoundBuffer or IDirectSoundBuffer8 can be passed to IDirectSound8::DuplicateSoundBuffer as the pDSBufferOriginal parameter.

When a method returns an interface, however, it is usually the earlier interface, and to obtain the newer interface you must use QueryInterface. This is the case, for example, with the ppDSBuffer parameter of IDirectSound8::CreateSoundBuffer.


IDirectSound8 Interface

The IDirectSound8 interface is used to create buffer objects, manage devices, and set up the environment. This interface supersedes IDirectSound and adds new methods.

Obtain this interface by using the DirectSoundCreate8 or DirectSoundFullDuplexCreate8 function, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSound8.

In addition to the methods inherited from IUnknown, the IDirectSound8 interface exposes the following methods.

Method | Description
Compact | Moves the unused portions of on-board sound memory, if any, to a contiguous block so that the largest portion of free memory will be available.
CreateSoundBuffer | Creates a sound buffer object to manage audio samples.
DuplicateSoundBuffer | Creates a new secondary buffer that shares the original buffer's memory.
GetCaps | Retrieves the capabilities of the hardware device.
GetSpeakerConfig | Retrieves the speaker configuration.
Initialize | Initializes a device object that was created by using the CoCreateInstance function.
SetCooperativeLevel | Sets the cooperative level of the application for this sound device.
SetSpeakerConfig | Specifies the speaker configuration of the device.
VerifyCertification | Ascertains whether the device driver is certified for DirectX.

The LPDIRECTSOUND8 type is defined as a pointer to the IDirectSound8 interface:

typedef struct IDirectSound8  *LPDIRECTSOUND8;

Remarks

Only objects of class CLSID_DirectSound8 support this interface. All device objects created by DirectSoundCreate8 and DirectSoundFullDuplexCreate8 fall into this category. Objects of class CLSID_DirectSound, which include all those created by using the earlier DirectSoundCreate function, support only the earlier IDirectSound interface.

The behavior of CLSID_DirectSound8 objects is somewhat different from that of CLSID_DirectSound objects. These differences are found in the IDirectSound interface as well as the IDirectSound8 interface. Specific differences in the behavior of the newer object include the following:

  • In calls to IDirectSound::CreateSoundBuffer and IDirectSound8::CreateSoundBuffer, DSBCAPS_CTRL3D cannot be set on a buffer with a non-mono format, and DSBCAPS_CTRL3D cannot be combined with DSBCAPS_CTRLPAN.
  • New buffer creation flags are supported.
  • Buffers are not filled with silence on creation.
  • The IDirectSoundBuffer interface returned by CreateSoundBuffer can be queried for the IDirectSoundBuffer8 interface.
  • WAV formats in the DSBUFFERDESC structure that have the WAVE_FORMAT_EXTENSIBLE format tag are checked more strictly for validity.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces


IDirectSound8::Compact

The Compact method moves the unused portions of on-board sound memory, if any, to a contiguous block so that the largest portion of free memory will be available.

Syntax

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_PRIOLEVELNEEDED
DSERR_UNINITIALIZED

Remarks

Sound cards using the PCI bus do not have on-board memory.

The application's device object must have at least the DSSCL_PRIORITY cooperative level. See IDirectSound8::SetCooperativeLevel.

This method will fail if any operations are in progress.

Requirements

Header: Declared in dsound.h

See Also

  • IDirectSound8 Interface


IDirectSound8::CreateSoundBuffer

The CreateSoundBuffer method creates a sound buffer object to manage audio samples.

Syntax

HRESULT CreateSoundBuffer(
  LPCDSBUFFERDESC pcDSBufferDesc,
  LPDIRECTSOUNDBUFFER * ppDSBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSBufferDesc

Address of a DSBUFFERDESC structure that describes the sound buffer to create.

ppDSBuffer

Address of a variable that receives the IDirectSoundBuffer interface of the new buffer object. Use QueryInterface to obtain IDirectSoundBuffer8. IDirectSoundBuffer8 is not available for the primary buffer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK, or DS_NO_VIRTUALIZATION if a requested 3-D algorithm was not available and stereo panning was substituted. See the description of the guid3DAlgorithm member of DSBUFFERDESC.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_DS8_REQUIRED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

DirectSound does not initialize the contents of the buffer, and the application cannot assume that it contains silence.

If an attempt is made to create a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • IDirectSound8::DuplicateSoundBuffer
  • Creating Secondary Buffers


IDirectSound8::DuplicateSoundBuffer

The DuplicateSoundBuffer method creates a new secondary buffer that shares the original buffer's memory.

Syntax

HRESULT DuplicateSoundBuffer(
  LPDIRECTSOUNDBUFFER pDSBufferOriginal,
  LPDIRECTSOUNDBUFFER * ppDSBufferDuplicate
);

Parameters

pDSBufferOriginal

Address of the IDirectSoundBuffer or IDirectSoundBuffer8 interface of the buffer to duplicate.

ppDSBufferDuplicate

Address of a variable that receives the IDirectSoundBuffer interface pointer for the new buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

This method is not valid for buffers created with the DSBCAPS_CTRLFX flag.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

The buffer memory is released when the last object referencing it is released.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • IDirectSound8::CreateSoundBuffer


IDirectSound8::GetCaps

The GetCaps method retrieves the capabilities of the hardware device that is represented by the device object.

Syntax

HRESULT GetCaps(
  LPDSCAPS pDSCaps
);

Parameters

pDSCaps

Address of a DSCAPS structure that receives the capabilities of this sound device.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS structure describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • Device Capabilities


IDirectSound8::GetSpeakerConfig

The GetSpeakerConfig method retrieves the speaker configuration.

Syntax

HRESULT GetSpeakerConfig(
  LPDWORD pdwSpeakerConfig
);

Parameters

pdwSpeakerConfig

Address of the speaker configuration for this device. The speaker configuration is specified with one of the values shown in the following table.

Value | Description
DSSPEAKER_5POINT1 | The audio is played through a speaker arrangement of five surround speakers with a subwoofer.
DSSPEAKER_DIRECTOUT | The audio is passed through directly, without being configured for speakers.
DSSPEAKER_HEADPHONE | The audio is played through headphones.
DSSPEAKER_MONO | The audio is played through a single speaker.
DSSPEAKER_QUAD | The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO | The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND | The audio is played through surround speakers.
DSSPEAKER_7POINT1 | The audio is played through a speaker arrangement of seven surround speakers with a subwoofer.

DSSPEAKER_STEREO can be combined with one of the values shown in the following table.

Value | Description
DSSPEAKER_GEOMETRY_WIDE | The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW | The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN | The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX | The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The value returned at pdwSpeakerConfig can be a packed DWORD containing both configuration and geometry information. Use the DSSPEAKER_CONFIG and DSSPEAKER_GEOMETRY macros to unpack the DWORD, as in the following example:

if (DSSPEAKER_CONFIG(dwSpeakerConfig) == DSSPEAKER_STEREO)
  {
  if (DSSPEAKER_GEOMETRY(dwSpeakerConfig) ==
        DSSPEAKER_GEOMETRY_WIDE)
    {
      // Configuration is wide stereo.
 ...}
  }

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • IDirectSound8::SetSpeakerConfig
  • Speaker Configuration


IDirectSound8::Initialize

The Initialize method initializes a device object that was created by using the CoCreateInstance function.

Syntax

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice

Address of the globally unique identifier (GUID) specifying the sound driver to which this device object binds. Pass NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALREADYINITIALIZED
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER

Remarks

This method is provided for compliance with the Component Object Model (COM) protocol. If the DirectSoundCreate8 function was used to create the device object, this method returns DSERR_ALREADYINITIALIZED. If IDirectSound8::Initialize is not called when using CoCreateInstance to create the device object, any method called afterward returns DSERR_UNINITIALIZED.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface


IDirectSound8::SetCooperativeLevel

The SetCooperativeLevel method sets the cooperative level of the application for this sound device.

Syntax

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwLevel
);

Parameters

hwnd

Handle to the application window.

dwLevel

Requested level. Specify one of the values shown in the following table.

Value | Description
DSSCL_EXCLUSIVE | For DirectX 8.0 and later, has the same effect as DSSCL_PRIORITY. For previous versions, sets the application to the exclusive level. This means that when it has the input focus, the application will be the only one audible; sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted. With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the IDirectSoundBuffer8::SetFormat method, after the application gains the input focus.
DSSCL_NORMAL | Sets the normal level. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY | Sets the priority level. Applications with this cooperative level can call the IDirectSoundBuffer8::SetFormat and IDirectSound8::Compact methods.
DSSCL_WRITEPRIMARY | Sets the write-primary level. The application has write access to the primary buffer. No secondary buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the IDirectSound8::GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY.

Do not call this method if any buffers are locked.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • Cooperative Levels


IDirectSound8::SetSpeakerConfig

The SetSpeakerConfig method specifies the speaker configuration of the device.

Note This function controls a global Windows setting that affect all users and applications on the system. It is provided only for use by configuration utilities provided by audio device vendors. No other applications should call it.

Syntax

HRESULT SetSpeakerConfig(
  DWORD dwSpeakerConfig
);

Parameters

dwSpeakerConfig

Speaker configuration of the specified device object. This parameter can be one of the values shown in the following tables.

Value | Description
DSSPEAKER_5POINT1 | The audio is played through a speaker arrangement of surround speakers with a subwoofer.
DSSPEAKER_DIRECTOUT | The audio is passed through directly, without being configured for speakers.
DSSPEAKER_HEADPHONE | The speakers are headphones.
DSSPEAKER_MONO | The speakers are monaural.
DSSPEAKER_QUAD | The speakers are quadraphonic.
DSSPEAKER_STEREO | The speakers are stereo (default value).
DSSPEAKER_SURROUND | The speakers are surround sound.
DSSPEAKER_7POINT1 | The audio is played through a speaker arrangement of seven surround speakers with a subwoofer.

DSSPEAKER_STEREO can be combined with one of the values in the following table.

Value | Description
DSSPEAKER_GEOMETRY_WIDE | The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW | The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN | The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX | The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALID PARAM
DSERR_UNINITIALIZED

Remarks

If a geometry value is to be used, it must be packed in a DWORD along with the DSSPEAKER_STEREO flag. This can be done by using the DSSPEAKER_COMBINED macro, as in the following C++ example:

lpds->SetSpeakerConfig(DSSPEAKER_COMBINED(
    DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE));

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface
  • IDirectSound8::GetSpeakerConfig
  • Speaker Configuration


IDirectSound8::VerifyCertification

The VerifyCertification method ascertains whether the device driver is certified for DirectX.

Syntax

VerifyCertification(
  LPDWORD pdwCertified
);

Parameters

pdwCertified

Address of a DWORD variable that receives one of the values shown in the following table.

Value | Description
DS_CERTIFIED | Driver is certified for DirectSound.
DS_UNCERTIFIED | Driver is not certified for DirectSound.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED

Remarks

This method may attempt to retrieve certification information from the Internet.

On emulated devices, the method returns DSERR_UNSUPPORTED. Emulated devices are identified by the DSCAPS_EMULDRIVER flag in the dwFlags member of DSCAPS.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound8 Interface


IDirectSound3DBuffer8 Interface

The IDirectSound3DBuffer8 interface is used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.

IDirectSound3DBuffer8 is a define for IDirectSound3DBuffer. The two interface names are interchangeable.

The IDirectSound3DBuffer8 interface is obtained from a buffer that was created with the DSBCAPS_CTRL3D flag. You can get it from the IDirectSoundBuffer8 interface by using the QueryInterface method, or retrieve it from an audiopath by using IDirectMusicSegmentState8::GetObjectInPath or IDirectMusicAudioPath8::GetObjectInPath.

In addition to the methods inherited from IUnknown, the IDirectSound3DBuffer8 interface exposes the following methods, arranged by category.

3-D mode

Method | Description
GetMode | Retrieves the operation mode for 3-D sound processing.
SetMode | Sets the operation mode for 3-D sound processing.

Batch parameters

Method | Description
GetAllParameters | Retrieves all 3-D properties of the sound buffer.
SetAllParameters | Sets all 3-D properties of the sound buffer.

Minimum and maximum distance

Method | Description
GetMaxDistance | Retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.
GetMinDistance | Retrieves retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.
SetMaxDistance | Sets the maximum distance.
SetMinDistance | Sets the minimum distance.

Position

Method | Description
GetPosition | Retrieves the position of the sound source.
SetPosition | Sets the position of the sound source.

Sound projection cone

Method | Description
GetConeAngles | Retrieves the inside and outside angles of the sound projection cone.
GetConeOrientation | Retrieves the orientation of the sound projection cone.
GetConeOutsideVolume | Retrieves the volume of the sound outside the outside angle of the sound projection cone.
SetConeAngles | Sets the inside and outside angles of the sound projection cone.
SetConeOrientation | Sets the orientation of the sound projection cone.
SetConeOutsideVolume | Sets the volume of the sound outside the outside angle of the sound projection cone.

Velocity

Method | Description
GetVelocity | Retrieves the velocity of the sound source.
SetVelocity | Sets the velocity of the sound source.

The LPDIRECTSOUND3DBUFFER type is defined as a pointer to the IDirectSound3DBuffer8 interface:

typedef struct IDirectSound3DBuffer  *LPDIRECTSOUND3DBUFFER;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • DirectSound 3-D Buffers


IDirectSound3DBuffer8::GetAllParameters

The GetAllParameters method retrieves the 3-D properties of the sound buffer.

Syntax

HRESULT GetAllParameters(
  LPDS3DBUFFER pDs3dBuffer
);

Parameters

pDs3dBuffer

Address of a DS3DBUFFER structure that receives the information describing the 3-D characteristics of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • Batch Parameters for 3-D Buffers


IDirectSound3DBuffer8::GetConeAngles

The GetConeAngles method retrieves the inside and outside angles of the sound projection cone.

Syntax

HRESULT GetConeAngles(
  LPDWORD pdwInsideConeAngle,
  LPDWORD pdwOutsideConeAngle
);

Parameters

pdwInsideConeAngle

Addresses of a variable that receives the inside angle of the sound projection cone, in degrees. This is the angle within which the sound is at its normal volume.

pdwOutsideConeAngle

Addresses of a variable that receives the outside angle of the sound projection cone, in degrees. This is the angle outside of which the sound is at its outside volume.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::GetConeOutsideVolume
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetConeOrientation

The GetConeOrientation method retrieves the orientation of the sound projection cone.

Syntax

HRESULT GetConeOrientation(
  D3DVECTOR * pvOrientation
);

Parameters

pvOrientation

Address of a D3DVECTOR structure that receives the orientation of the sound projection cone. The vector information represents the center of the sound cone.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the SetConeOrientation method. DirectSound normalizes orientation vectors so that all axes have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetConeOutsideVolume

The GetConeOutsideVolume method retrieves the volume of the sound outside the outside angle of the sound projection cone.

Syntax

HRESULT GetConeOutsideVolume(
  LPLONG plConeOutsideVolume
);

Parameters

plConeOutsideVolume

Address of a variable that receives the cone outside volume for this buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are expressed as attenuation, in hundredths of a decibel. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetMaxDistance

The GetMaxDistance method retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

Syntax

HRESULT GetMaxDistance(
  D3DVALUE * pflMaxDistance
);

Parameters

pflMaxDistance

Address of a variable that receives the maximum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMinDistance
  • IDirectSound3DBuffer8::SetMaxDistance
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::GetMinDistance

The GetMinDistance method retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

Syntax

HRESULT GetMinDistance(
  D3DVALUE * pflMinDistance
);

Parameters

pflMinDistance

Address of a variable that receives the minimum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::GetMode

The GetMode method retrieves the operation mode for 3-D sound processing.

Syntax

HRESULT GetMode(
  LPDWORD pdwMode
);

Parameters

pdwMode

Address of a variable that receives the mode setting. This value will be one of those in the following table.

Value | Description
DS3DMODE_DISABLE | Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • Processing Mode


IDirectSound3DBuffer8::GetPosition

The GetPosition method retrieves the position of the sound source.

Syntax

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition

Address of a D3DVECTOR structure that receives the position of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • Buffer Position and Velocity


IDirectSound3DBuffer8::GetVelocity

The GetVelocity method retrieves the velocity of the sound source.

Syntax

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity

Address of a D3DVECTOR structure that receives the sound buffer's velocity, in meters per second by default.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetPosition
  • IDirectSound3DBuffer8::SetVelocity
  • Buffer Position and Velocity


IDirectSound3DBuffer8::SetAllParameters

The SetAllParameters method sets all 3-D sound buffer properties.

Syntax

HRESULT SetAllParameters(
  LPCDS3DBUFFER pcDs3dBuffer,
  DWORD dwApply
);

Parameters

pcDs3dBuffer

Address of a DS3DBUFFER structure that describes the 3-D characteristics of the sound buffer.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • Batch Parameters for 3-D Buffers
  • Deferred Settings


IDirectSound3DBuffer8::SetConeAngles

The SetConeAngles method sets the inside and outside angles of the sound projection cone.

Syntax

HRESULT SetConeAngles(
  DWORD dwInsideConeAngle,
  DWORD dwOutsideConeAngle,
  DWORD dwApply
);

Parameters

dwInsideConeAngle

Inside cone angle, in degrees. This is the angle within which the sound is at its normal volume.

dwOutsideConeAngle

Outside cone angle, in degrees. This is the angle outside of which the sound is at its outside volume.

dwApply

Value that indicates when the setting should be applied. Must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetConeOrientation

The SetConeOrientation method sets the orientation of the sound projection cone.

Syntax

HRESULT SetConeOrientation(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the sound cone orientation vector. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

This method has no effect unless the cone angle and cone outside volume have also been set to values other than the default.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetConeOutsideVolume

The SetConeOutsideVolume method sets the volume of the sound outside the outside angle of the sound projection cone.

Syntax

HRESULT SetConeOutsideVolume(
  LONG lConeOutsideVolume,
  DWORD dwApply
);

Parameters

lConeOutsideVolume

Cone outside volume, in hundredths of a decibel.

dwApply

Value that specifies when the setting should be applied. This value must be one of the those shown in the following table.

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSoundBuffer8::SetVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetMaxDistance

The SetMaxDistance method sets the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

Syntax

HRESULT SetMaxDistance(
  D3DVALUE flMaxDistance,
  DWORD dwApply
);

Parameters

flMaxDistance

Maximum distance, in meters by default. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • Deferred Settings
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::SetMinDistance

The SetMinDistance method sets the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

Syntax

HRESULT SetMinDistance(
  D3DVALUE flMinDistance,
  DWORD dwApply
);

Parameters

flMinDistance

Minimum distance, in meters by default. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetMaxDistance
  • Deferred Settings
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::SetMode

The SetMode method sets the operation mode for 3-D sound processing.

Syntax

HRESULT SetMode(
  DWORD dwMode,
  DWORD dwApply
);

Parameters

dwMode

Flag specifying the 3-D sound processing mode to be set. The following flags are defined:

Value | Description
DS3DMODE_DISABLE | Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h

See Also

  • IDirectSound3DBuffer8 Interface
  • Deferred Settings
  • Processing Mode


IDirectSound3DBuffer8::SetPosition

The SetPosition method sets the position of the sound source.

Syntax

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the position vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • Deferred Settings
  • Buffer Position and Velocity


IDirectSound3DBuffer8::SetVelocity

The SetVelocity method sets the velocity of the sound source.

Syntax

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the velocity vector, in meters per second by default. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the position of the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetVelocity
  • IDirectSound3DBuffer8::SetPosition
  • Buffer Position and Velocity
  • Deferred Settings


IDirectSound3DListener8 Interface

The IDirectSound3DListener8 interface is used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.

The interface can be obtained by calling the IDirectSoundBuffer8::QueryInterface method on a primary buffer created with the DSBCAPS_CTRL3D flag.

In addition to the methods inherited from IUnknown, the IDirectSound3DListener8 interface exposes the following methods, arranged by category.

Batch parameters

Method | Description
CommitDeferredSettings | Commits any deferred settings made since the last call to this method.
GetAllParameters | Retrieves all 3-D parameters of the sound environment and the listener.
SetAllParameters | Sets all 3-D parameters of the sound environment and the listener.

Global sound properties

Method | Description
GetDistanceFactor | Retrieves the distance factor, which is the number of meters in a vector unit.
GetDopplerFactor | Retrieves the multiplier for the Doppler effect.
GetRolloffFactor | Retrieves the rolloff factor, which determines the rate of attenuation over distance.
SetDistanceFactor | Sets the distance factor.
SetDopplerFactor | Sets the multiplier for the Doppler effect.
SetRolloffFactor | Sets the rolloff factor.

Listener properties

Method | Description
GetOrientation | Retrieves the orientation of the listener's head.
GetPosition | Retrieves the listener's position.
GetVelocity | Retrieves the listener's velocity.
SetOrientation | Sets the orientation of the listener's head.
SetPosition | Sets the listener's position.
SetVelocity | Sets the listener's velocity.

The LPDIRECTSOUND3DLISTENER type is defined as a pointer to the IDirectSound3DListener interface:

typedef struct IDirectSound3DListener  *LPDIRECTSOUND3DLISTENER;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces


IDirectSound3DListener8::CommitDeferredSettings

The CommitDeferredSettings method commits any deferred settings made since the last call to this method.

Syntax

HRESULT CommitDeferredSettings();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • Deferred Settings


IDirectSound3DListener8::GetAllParameters

The GetAllParameters method retrieves all 3-D parameters of the sound environment and the listener.

Syntax

HRESULT GetAllParameters(
  LPDS3DLISTENER pListener
);

Parameters

pListener

Address of a DS3DLISTENER structure that receives the state of the 3-D world and listener.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetAllParameters


IDirectSound3DListener8::GetDistanceFactor

The GetDistanceFactor method retrieves the distance factor, which is the number of meters in a vector unit.

Syntax

HRESULT GetDistanceFactor(
  D3DVALUE * pflDistanceFactor
);

Parameters

pflDistanceFactor

Address of a variable that receives the distance factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetDistanceFactor
  • Distance Factor


IDirectSound3DListener8::GetDopplerFactor

The GetDopplerFactor method retrieves the multiplier for the Doppler effect.

Syntax

HRESULT GetDopplerFactor(
  D3DVALUE * pflDopplerFactor
);

Parameters

pflDopplerFactor

Address of a variable that receives the Doppler factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetDopplerFactor
  • Doppler Effect


IDirectSound3DListener8::GetOrientation

The GetOrientation method retrieves the orientation of the listener's head.

Syntax

HRESULT GetOrientation(
  D3DVECTOR * pvOrientFront,
  D3DVECTOR * pvOrientTop
);

Parameters

pvOrientFront

Address of a D3DVECTOR structure that receives the listener's front orientation vector.

pvOrientTop

Address of a D3DVECTOR structure that receives the listener's top orientation vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using SetOrientation. DirectSound normalizes orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetOrientation
  • Spatial Parameters of the Listener


IDirectSound3DListener8::GetPosition

The GetPosition method retrieves the listener's position.

Syntax

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition

Address of a D3DVECTOR structure that receives the listener's position vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetPosition
  • Spatial Parameters of the Listener


IDirectSound3DListener8::GetRolloffFactor

The GetRolloffFactor method retrieves the rolloff factor, which determines the rate of attenuation over distance.

Syntax

HRESULT GetRolloffFactor(
  D3DVALUE * pflRolloffFactor
);

Parameters

pflRolloffFactor

Address of a variable that receives the rolloff factor. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetRolloffFactor
  • Rolloff Factor


IDirectSound3DListener8::GetVelocity

The GetVelocity method retrieves the listener's velocity.

Syntax

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity

Address of a D3DVECTOR structure that receives the listener's velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the listener's position. To move the listener, use the IDirectSound3DListener8::SetPosition method.

The default velocity is (0,0,0).

Remarks

By default, measurement units are meters per second, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetVelocity
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetAllParameters

The SetAllParameters method sets all 3-D parameters of the sound environment and the listener.

Syntax

HRESULT SetAllParameters(
  LPCDS3DLISTENER pcListener,
  DWORD dwApply
);

Parameters

pcListener

Address of a DS3DLISTENER structure that contains information describing all 3-D listener parameters.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetAllParameters
  • Deferred Settings


IDirectSound3DListener8::SetDistanceFactor

The SetDistanceFactor method sets the distance factor, which is the number of meters in a vector unit.

Syntax

HRESULT SetDistanceFactor(
  D3DVALUE flDistanceFactor,
  DWORD dwApply
);

Parameters

flDistanceFactor

Distance factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The distance factor has a range of DS3D_MINDISTANCEFACTOR to DS3D_MAXDISTANCEFACTOR, defined in Dsound.h as FLT_MIN and FLT_MAX respectively. The default value is DS3D_DEFAULTDISTANCEFACTOR, or 1.0.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetDistanceFactor
  • Deferred Settings
  • Distance Factor


IDirectSound3DListener8::SetDopplerFactor

The SetDopplerFactor method sets the multiplier for the Doppler effect.

Syntax

HRESULT SetDopplerFactor(
  D3DVALUE flDopplerFactor,
  DWORD dwApply
);

Parameters

flDopplerFactor

Doppler factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetDopplerFactor
  • Deferred Settings
  • Doppler Effect


IDirectSound3DListener8::SetOrientation

The SetOrientation method sets the orientation of the listener's head.

Syntax

HRESULT SetOrientation(
  D3DVALUE xFront,
  D3DVALUE yFront,
  D3DVALUE zFront,
  D3DVALUE xTop,
  D3DVALUE yTop,
  D3DVALUE zTop,
  DWORD  dwApply
);

Parameters

xFront, yFront, zFront

Values that specify the coordinates of the front orientation vector. D3DVALUE is defined as float.

xTop, yTop, zTop

Values that specify the coordinates of the top orientation vector.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the top vector after setting the front vector.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetOrientation
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetPosition

The SetPosition method sets the listener's position.

Syntax

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the listener's position vector. Note that DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetPosition
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetRolloffFactor

The SetRolloffFactor method sets the rolloff factor, which determines the rate of attenuation over distance.

Syntax

HRESULT SetRolloffFactor(
  D3DVALUE flRolloffFactor,
  DWORD dwApply
);

Parameters

flRolloffFactor

Rolloff factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetRolloffFactor
  • Deferred Settings
  • Rolloff Factor


IDirectSound3DListener8::SetVelocity

The SetVelocity method sets the listener's velocity.

Syntax

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the listener's velocity vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the IDirectSound3DListener8::SetPosition method. The default velocity is (0,0,0).

By default, measurement units are meters per second, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetVelocity
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSoundBuffer8 Interface

The IDirectSoundBuffer8 interface is used to manage sound buffers.

The IDirectSoundBuffer8 interface supersedes IDirectSoundBuffer and adds new methods.

To obtain the interface, use the IDirectSound8::CreateSoundBuffer method to retrieve IDirectSoundBuffer, and then pass IID_IDirectSoundBuffer8 to IDirectSoundBuffer::QueryInterface.

For the primary buffer, you must use the IDirectSoundBuffer interface; IDirectSoundBuffer8 is not available. IDirectSoundBuffer is not documented separately. For documentation, see the corresponding IDirectSoundBuffer8 methods.

Not all methods of IDirectSoundBuffer are valid for primary buffers. For example, SetCurrentPosition will fail. See the reference topics for individual methods.

In addition to the methods inherited from IUnknown, the IDirectSoundBuffer8 interface exposes the following methods, arranged by category.

Effects

Method | Description
GetObjectInPath | Retrieves an interface for an effect object associated with the buffer.
SetFX | Enables effects on a buffer.

Resource management

Method | Description
AcquireResources | Allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag.
Restore | Restores the memory allocation for a lost sound buffer

Play management

Method | Description
GetCurrentPosition | Retrieves the position of the play and write cursors in the sound buffer.
Lock | Readies all or part of the buffer for a data write and returns pointers to which data can be written.
Play | Causes the sound buffer to play, starting at the play cursor.
SetCurrentPosition | Sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.
Stop | Causes the sound buffer to stop playing.
Unlock | Releases a locked sound buffer.

Sound parameters

Method | Description
GetFrequency | Retrieves the frequency, in samples per second, at which the buffer is playing.
GetPan | Retrieves the relative volume of the left and right audio channels.
GetVolume | Retrieves the attenuation of the sound.
SetFrequency | Sets the frequency at which the audio samples are played.
SetPan | Sets the relative volume of the left and right channels.
SetVolume | Sets the attenuation of the sound.

Miscellaneous

Method | Description
GetCaps | Retrieves the capabilities of the buffer object.
GetFormat | Retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.
GetStatus | Retrieves the status of the sound buffer.
Initialize | Initializes a sound buffer object if it has not yet been initialized.
SetFormat | Sets the format of the primary buffer.

The following table shows which methods are supported for buffer objects obtained from a DirectMusic audiopath. Mix-in buffers accept sends from other buffers, and exist only in audiopath configurations created in DirectMusic Producer. All other buffers in the audiopath are sink-in buffers, which means that they accept data only from the synthesizer sink.

IDirectSoundBuffer8 method | Mix-in | Sink-in
AcquireResources | No | No
GetCaps | Yes | Yes
GetCurrentPosition | No | No
GetFormat | Yes | Yes
GetFrequency | No | No
GetObjectInPath | Yes | Yes
GetPan | Yes | Yes
GetStatus | Yes | Yes
GetVolume | Yes | Yes
Initialize | No | No
Lock | No | No
Play | Yes | No
Restore | No | No
SetCurrentPosition | No | No
SetFormat | No | No
SetFrequency | No | No
SetFX | Yes | Yes
SetPan | Yes | Yes
SetVolume | Yes | Yes
Stop | Yes | No
Unlock | No | No

The LPDIRECTSOUNDBUFFER8 type is defined as a pointer to the IDirectSoundBuffer interface:

typedef struct IDirectSoundBuffer8  *LPDIRECTSOUNDBUFFER8;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces


IDirectSoundBuffer8::AcquireResources

The AcquireResources method allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure.

Syntax

HRESULT AcquireResources(
  DWORD dwFlags,
  DWORD dwEffectsCount,
  LPDWORD pdwResultCodes
);

Parameters

dwFlags

Flags specifying how resources are to be allocated for a buffer created with the DSBCAPS_LOCDEFER flag. For a list of values, see the voice management and voice allocation flags for IDirectSoundBuffer8::Play.

dwEffectsCount

Number of elements in the pdwResultFlags array, or 0 if pdwResultCodes is NULL.

pdwResultCodes

Address of an array of DWORD variables that receives information about the effects associated with the buffer. This array must contain one element for each effect that was assigned to the buffer by IDirectSoundBuffer8::SetFX. For each effect, one of the following values is returned.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | The effect is available but was not created because the method failed for some other reason.
DSFXR_UNKNOWN | No effect was created because the effect isn't registered on the system.

This parameter can be NULL if result codes are not wanted.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM

Remarks

Normally, buffers created with DSBCAPS_LOCDEFER are not allocated resources until IDirectSoundBuffer8::Play is called. IDirectSoundBuffer8::AcquireResources can be used to allocate resources for a deferred buffer before it is played. By doing so, the application can retrieve information about effects processing and set effect parameters.

If the method fails, check the values in pdwResultCodes to determine which effects caused the failure.

A buffer with acquired resources that is not yet playing is not a candidate for premature termination by the voice management flags passed to the Play method.

Resources that have been acquired by AcquireResources are released when playback is stopped.

If the method is called on a buffer on which it has already been called, the status of the effects is returned but no additional resources are allocated.

The dwEffectsCount parameter to this function must be the same as the one passed in the call to IDirectSoundBuffer8::SetFX.

If an attempt is made to acquire resources for a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFX
  • DSBCAPS
  • Dynamic Voice Management


IDirectSoundBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer object.

Syntax

HRESULT GetCaps(
  LPDSBCAPS pDSBufferCaps
);

Parameters

pDSBufferCaps

Address of a DSBCAPS structure to contain the capabilities of this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The DSBCAPS structure contains similar information to the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and performance measures.

The flags specified in the dwFlags member of the DSBCAPS structure are the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • DSBCAPS
  • DSBUFFERDESC


IDirectSoundBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the position of the play and write cursors in the sound buffer.

Syntax

HRESULT GetCurrentPosition(
  LPDWORD pdwCurrentPlayCursor,
  LPDWORD pdwCurrentWriteCursor
);

Parameters

pdwCurrentPlayCursor

Address of a variable that receives the offset, in bytes, of the play cursor. This parameter can be NULL if the value is not wanted.

pdwCurrentWriteCursor

Address of a variable that receives the offset, in bytes, of the write cursor. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The write cursor is the point in the buffer ahead of which it is safe to write data to the buffer. Data should not be written to the part of the buffer after the play cursor and before the write cursor.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetCurrentPosition
  • Play and Write Cursors


IDirectSoundBuffer8::GetFormat

The GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

Syntax

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat

Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure that receives a description of the sound data in the buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the variable at pdwSizeWritten receives the size of the structure needed to receive the data.

dwSizeAllocated

Size, in bytes, of the structure at pwfxFormat. If pwfxFormat is not NULL, this value must be equal to or greater than the size of the expected data.

pdwSizeWritten

Address of a variable that receives the number of bytes written to the structure at pwfxFormat. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The format structure can have a variable length that depends on the format. Before retrieving the format description, the application should query the buffer object for the size of the format by calling this method and specifying NULL for the pwfxFormat parameter. The necessary size of the structure is returned in the pdwSizeWritten parameter. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFormat


IDirectSoundBuffer8::GetFrequency

The GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.

Syntax

HRESULT GetFrequency(
  LPDWORD pdwFrequency
);

Parameters

pdwFrequency

Address of a variable that receives the frequency at which the audio buffer is being played, in hertz.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value for software buffers is in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX, defined in Dsound.h. Hardware buffers can return other values.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFrequency
  • Playback Controls
  • Buffer Control Options


IDirectSoundBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface for an effect object associated with the buffer.

Syntax

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject

Unique class identifier of the object being searched for, such as GUID_DSFX_STANDARD_ECHO. Set this parameter to GUID_All_Objects to search for objects of any class.

dwIndex

Index of the object within objects of that class in the path. See Remarks.

rguidInterface

Unique identifier of the desired interface. See Remarks.

ppObject

Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND
E_NOINTERFACE

Remarks

Any DMO that has been set on a buffer by using IDirectSoundBuffer8::SetFX can be retrieved, even it has not been allocated resources.

The following interfaces can be retrieved for the various DMOs supplied with DirectX.

rguidInterface | *ppObject
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8

In addition, the following interfaces are available for any of the standard DMOs. For information on these interfaces, see the Help for DirectX Media Objects.

rguidInterface | *ppObject
IID_IMediaObject | IMediaObject
IID_IMediaObjectInPlace | IMediaObjectInPlace
IID_IMediaParams | IMediaParams

Note When the DirectSound API is used to play buffers, parameter curves (envelopes) set by using the IMediaParams interface do not work, because DirectSound does not timestamp the DMO buffers.

The value in dwIndex is the index of the object within the array of effects passed to IDirectSoundBuffer8::SetFX. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundFXChorus8 Interface
  • IDirectSoundFXCompressor8 Interface
  • IDirectSoundFXDistortion8 Interface
  • IDirectSoundFXEcho8 Interface
  • IDirectSoundFXFlanger8 Interface
  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXParamEq8 Interface
  • DirectSound Effect GUIDs


IDirectSoundBuffer8::GetPan

The GetPan method retrieves the relative volume of the left and right audio channels.

Syntax

HRESULT GetPan(
  LPLONG plPan
);

Parameters

plPan

Address of a variable that receives the relative volume, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is effectively silent. The value DSBPAN_RIGHT means the left channel is effectively silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetPan
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::GetStatus

The GetStatus method retrieves the status of the sound buffer.

Syntax

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus

Address of a variable that receives the status of the sound buffer. The status can be a combination of the following flags:

Value | Description
DSBSTATUS_BUFFERLOST | The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING | The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. This value is returned only in combination with DSBSTATUS_PLAYING.
DSBSTATUS_PLAYING | The buffer is playing. If this value is not set, the buffer is stopped.
DSBSTATUS_LOCSOFTWARE | The buffer is playing in software. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_LOCHARDWARE | The buffer is playing in hardware. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_TERMINATED | The buffer was prematurely terminated by the voice manager and is not playing. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

Remarks

DSBSTATUS_PLAYING is set if the buffer is being heard. Because of latency, a call to IDirectSoundBuffer8::Play or IDirectSoundBuffer8::Stop might not immediately change the status.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • Buffer Management


IDirectSoundBuffer8::GetVolume

The GetVolume method retrieves the attenuation of the sound.

Syntax

HRESULT GetVolume(
  LPLONG plVolume
);

Parameters

plVolume

Address of a variable that receives the attenuation, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is between DSBVOLUME_MAX and DSBVOLUME_MIN. These values are defined as 0 and –10,000, respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the sound. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for practical purposes, is silence.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::Initialize

The Initialize method initializes a sound buffer object if it has not yet been initialized.

Syntax

HRESULT Initialize(
  LPDIRECTSOUND pDirectSound,
  LPCDSBUFFERDESC pcDSBufferDesc
);

Parameters

pDirectSound

Address of the device object associated with this buffer.

pcDSBufferDesc

Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSound8::CreateSoundBuffer method calls Initialize internally, applications do not need to call this method.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • DSBUFFERDESC


IDirectSoundBuffer8::Lock

The Lock method readies all or part of the buffer for a data write and returns pointers to which data can be written.

Syntax

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID * ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID * ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset

Offset, in bytes, from the start of the buffer to the point where the lock begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the dwFlags parameter.

dwBytes

Size, in bytes, of the portion of the buffer to lock. The buffer is conceptually circular, so this number can exceed the number of bytes between dwOffset and the end of the buffer.

ppvAudioPtr1

Address of a variable that receives a pointer to the first locked part of the buffer.

pdwAudioBytes1

Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer .

ppvAudioPtr2

Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.

pdwAudioBytes2

Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.

dwFlags

Flags modifying the lock event. The following flags are defined:

Value | Description
DSBLOCK_FROMWRITECURSOR | Start the lock at the write cursor. The dwOffset parameter is ignored.
DSBLOCK_ENTIREBUFFER | Lock the entire buffer. The dwBytes parameter is ignored.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method accepts an offset and a byte count, and returns two write pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

After writing data to the pointers returned by this method, the application must immediately call IDirectSoundBuffer8::Unlock to notify DirectSound that the data is ready for playback. Failure to do so can cause audio breakup or silence on some sound device configurations.

This method returns write pointers only. The application should not try to read sound data from this pointer, because the data might not be valid. For example, if the buffer is located in on-card memory, the pointer might be an address to a temporary buffer in system memory. When IDirectSoundBuffer8::Unlock is called, the contents of this temporary buffer are transferred to the on-card memory.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundBuffer8::Play

The Play method causes the sound buffer to play, starting at the play cursor.

Syntax

HRESULT Play(
  DWORD dwReserved1,
  DWORD dwPriority,
  DWORD dwFlags
);

Parameters

dwReserved1

Reserved. Must be 0.

dwPriority

Priority for the sound, used by the voice manager when assigning hardware mixing resources. The lowest priority is 0, and the highest priority is 0xFFFFFFFF. If the buffer was not created with the DSBCAPS_LOCDEFER flag, this value must be 0.

dwFlags

Flags specifying how to play the buffer. The following flags are defined:

Looping flag

Value | Description
DSBPLAY_LOOPING | After the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing a primary buffer.

Voice allocation flags

The voice allocation flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag. One of the following flags can be used to force the processing of the sound into hardware or software. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound is played in either software or hardware, depending on the availability of resources at the time the method is called. See Remarks.

Value | Description
DSBPLAY_LOCHARDWARE | Play this voice in a hardware buffer only. If the hardware has no available voices and no voice management flags are set, the call to IDirectSoundBuffer8::Play fails. This flag cannot be combined with DSBPLAY_LOCSOFTWARE.
DSBPLAY_LOCSOFTWARE | Play this voice in a software buffer only. This flag cannot be combined with DSBPLAY_LOCHARDWARE or any voice management flag.

Voice management flags

The voice management flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag, and are used for sounds that are to play in hardware. These flags enable hardware resources that are already in use to be yielded to the current sound. Only buffers created with the DSBCAPS_LOCDEFER flag are candidates for premature termination. See Remarks.

Value | Description
DSBPLAY_TERMINATEBY_TIME | If the hardware has no available voices, a currently playing nonlooping buffer will be stopped to make room for the new buffer. The buffer prematurely terminated is the one with the least time left to play.
DSBPLAY_TERMINATEBY_DISTANCE | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be selected from buffers that have the buffer's DSBCAPS_ MUTE3DATMAXDISTANCE flag set and are beyond their maximum distance. If there are no such buffers, the method fails.
DSBPLAY_TERMINATEBY_PRIORITY | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be the one with the lowest priority as set by the dwPriority parameter passed to IDirectSoundBuffer8::Play for the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If IDirectSound8::SetCooperativeLevel has not been called, the method returns DS_OK, but no sound will be produced until a cooperative level has been set.

If the application is multithreaded, the thread that plays the buffer must continue to exist as long as the buffer is playing. Buffers created on WDM drivers stop playing when the thread is terminated.

If the buffer specified in the method is already playing, the call to the method succeeds and the buffer continues to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

When called on the primary buffer, this method causes the buffer to start playing to the sound device. If the application has set the DSSCL_WRITEPRIMARY cooperative level, any audio data put in the primary buffer by the application is sent to the sound device. Under any other cooperative level, the primary buffer plays silence if no secondary buffers are playing. Primary buffers must be played with the DSBPLAY_LOOPING flag set.

If the method is called with a voice allocation or voice management flag set on a buffer that was not created with the DSBCAPS_LOCDEFER flag, the call fails with DSERR_INVALIDPARAM.

DSBPLAY_TERMINATEBY_TIME and DSBPLAY_TERMINATEBY_DISTANCE cannot be combined, but either may be combined with DSBPLAY_TERMINATEBY_PRIORITY, in which case the DSBPLAY_TERMINATEBY_TIME or DSBPLAY_TERMINATEBY_DISTANCE flag is used to determine which buffer should be terminated in the event of a priority tie.

The following table shows the behavior of the method under various combinations of the voice allocation and voice management flags when no free hardware voices are available.

 | DSBPLAY_LOCHARDWARE | Neither DSBPLAY_LOCHARDWARE nor DSBPLAY_LOCSOFTWARE | DSBPLAY_LOCSOFTWARE
DSBPLAY_TERMINATEBY_TIME | Sound with least time left to play is terminated and the new sound plays on the released voice. | Sound with least time left to play is terminated and the new sound plays on the released voice. | New sound plays in software.
DSBPLAY_TERMINATEBY_DISTANCE | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the call fails. | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.
DSBPLAY_TERMINATEBY_PRIORITY | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the call fails. | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::SetCooperativeLevel
  • Dynamic Voice Management
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundBuffer8::Restore

The Restore method restores the memory allocation for a lost sound buffer.

Syntax

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, IDirectSoundBuffer8::Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary buffer.

After DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The IDirectSoundBuffer8::GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetStatus
  • IDirectSoundBuffer8::Lock
  • IDirectSoundBuffer8::Play
  • Buffer Management


IDirectSoundBuffer8::SetCurrentPosition

The SetCurrentPosition method sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.

Syntax

HRESULT SetCurrentPosition(
  DWORD dwNewPosition
);

Parameters

dwNewPosition

Offset of the play cursor, in bytes, from the beginning of the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on the primary buffer.

If the buffer is playing, the cursor immediately moves to the new position and play continues from that point. If it is not playing, playback will begin from the new position the next time the IDirectSoundBuffer8::Play method is called.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • IDirectSoundBuffer8::Play
  • Play and Write Cursors


IDirectSoundBuffer8::SetFormat

The SetFormat method sets the format of the primary buffer. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

Because primary sound buffers do not support the IDirectSoundBuffer8 interface, this method must be called on IDirectSoundBuffer.

On WDM drivers, setting the primary buffer format has no effect. The output format is determined by the kernel mixer. For more information, see DirectSound Driver Models.

Syntax

HRESULT SetFormat(
  LPCWAVEFORMATEX pcfxFormat
);

Parameters

pcfxFormat

Address of a WAVEFORMATEX structure that describes the new format for the primary sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

The format of the primary buffer should be set before secondary buffers are created.

The method fails if the application has the DSSCL_NORMAL cooperative level.

If the application is using DirectSound at the DSSCL_WRITEPRIMARY cooperative level, the buffer must be stopped before SetFormat is called. If the format is not supported, the method fails.

If the cooperative level is DSSCL_PRIORITY, DirectSound stops the primary buffer, changes the format, and restarts the buffer. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest supported format. To determine whether this has happened, an application can call the IDirectSoundBuffer8::GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

This method is not available for secondary sound buffers. If a new format is required, the application must create a new DirectSoundBuffer object.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetFormat


IDirectSoundBuffer8::SetFrequency

The SetFrequency method sets the frequency at which the audio samples are played.

Syntax

HRESULT SetFrequency(
  DWORD dwFrequency
);

Parameters

dwFrequency

Frequency, in hertz (Hz), at which to play the audio samples. A value of DSBFREQUENCY_ORIGINAL resets the frequency to the default value of the buffer format.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

Before setting the frequency, you should ascertain whether the frequency is supported by checking the dwMinSecondarySampleRate and dwMaxSecondarySampleRate members of the DSCAPS structure for the device. Some operating systems do not support frequencies greater than 100,000 Hz.

This method is not valid for the primary buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • IDirectSound8::GetCaps
  • IDirectSoundBuffer8::GetFrequency
  • IDirectSoundBuffer8::Play
  • IDirectSoundBuffer8::SetFormat
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::SetFX

The SetFX method enables effects on a buffer.

For this method to succeed, CoInitialize must have been called. This is done automatically in applications that create DirectSound by using IDirectMusicPerformance8::InitAudio. However, applications that create DirectSound by using DirectSoundCreate8 must also call CoInitialize.

The buffer must not be playing or locked.

Syntax

HRESULT SetFX(
  DWORD dwEffectsCount,
  LPDSEFFECTDESC pDSFXDesc,
  LPDWORD pdwResultCodes
);

Parameters

dwEffectsCount

Number of elements in the pDSFXDesc and pdwResultCodes arrays. If this value is 0, pDSFXDesc and pdwResultCodes must both be NULL. Set to 0 to remove all effects from the buffer.

pDSFXDesc

Address of an array of DSEFFECTDESC structures, of size dwEffectsCount, that specifies the effects wanted on the buffer. Must be NULL if dwEffectsCount is 0.

pdwResultCodes

Address of an array of DWORD elements, of size dwEffectsCount. Each element receives one of the following values indicating the result of the attempt to create the corresponding effect in the pDSFXDesc array.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_UNALLOCATED | Effect has not yet been assigned to hardware or software. This value is returned if the buffer was created with the DSBCAPS_LOCDEFER flag in DSBUFFERDESC.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | Effect is available but was not created because one of the other effects requested could not be created. If any of the effects requested cannot be created, none of them are, and the call fails.
DSFXR_UNKNOWN | Effect is not registered on the system, and the method failed as a result.

This parameter must be NULL if dwEffectsCount is 0, or can be NULL if results are not wanted.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

Return code
CO_E_NOTINITIALIZED
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_INVALIDCALL
DSERR_NOINTERFACE
DSERR_PRIOLEVELNEEDED

In addition, the method can return an error value from DMO methods, including IMediaObject::SetInputType and IMediaObject::SetOutputType. See the DirectShow documentation for possible error values.

Remarks

If the method fails, the value for each effect in pdwResultCodes is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values to determine which effects caused the failure.

For the method to succeed, the buffer must have been created with the DSBCAPS_CTRLFX flag and must not be playing or locked.

If the method returns DSERR_NOINTERFACE or another COM error, check the result code array for DSFXR_PRESENT or DSFXR_UNKNOWN to ascertain which effect caused the error. If the method returns DSERR_INVALIDPARAM, check the result codes for DSFXR_FAILED to see which effects failed to acquire resources.

If the buffer is part of an audiopath, the audiopath must be inactive. See IDirectMusicAudioPath8::Activate.

An effect must be set on a buffer before the effect interface can be obtained. To obtain the effect interface, use IDirectSoundBuffer8::GetObjectInPath.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::AcquireResources
  • DSBCAPS
  • Buffer Control Options
  • Setting Effects on Buffers


IDirectSoundBuffer8::SetPan

The SetPan method sets the relative volume of the left and right channels.

Syntax

HRESULT SetPan(
  LONG lPan
);

Parameters

lPan

Relative volume between the left and right channels.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB and is effectively silent. The value DSBPAN_RIGHT means the left channel is silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetPan
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::SetVolume

The SetVolume method sets the attenuation of the sound.

Syntax

HRESULT SetVolume(
  LONG lVolume
);

Parameters

lVolume

Attenuation, in hundredths of a decibel (dB).

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are defined in Dsound.h as 0 and –10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. DirectSound does not support amplification.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetPan
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetPan
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::Stop

The Stop method causes the sound buffer to stop playing.

Syntax

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_PRIOLEVELNEEDED

Remarks

For secondary sound buffers, IDirectSoundBuffer8::Stop sets the play cursor to the sample that follows the last sample played. This means that when the IDirectSoundBuffer8::Play method is next called on the buffer, it will continue playing where it left off.

For the primary buffer, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the play cursor to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if IDirectSoundBuffer8::Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of IDirectSoundBuffer8::Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::Play


IDirectSoundBuffer8::Unlock

The Unlock method releases a locked sound buffer.

Syntax

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1

Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundBuffer8::Lock method.

dwAudioBytes1

Number of bytes written to the portion of the buffer at pvAudioPtr1. See Remarks.

pvAudioPtr2

Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundBuffer8::Lock method.

dwAudioBytes2

Number of bytes written to the portion of the buffer at pvAudioPtr2. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundBuffer8::Lock method to ensure the correct pairing of IDirectSoundBuffer8::Lock and IDirectSoundBuffer8::Unlock. The second pointer is needed even if nothing was written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually written to each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to commit to the device.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • IDirectSoundBuffer8::Lock
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundCapture8 Interface

The IDirectSoundCapture8 interface is used to create sound capture buffers.

The interface is obtained by using the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 functions, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundCapture8.

IDirectSoundCapture8 is a define for IDirectSoundCapture. The two interface names are interchangeable. However, objects supporting this interface can have different functionality, depending on their class. For more information, see DirectSoundCaptureCreate8 and IDirectSoundCapture8::CreateCaptureBuffer.

In addition to the methods inherited from IUnknown, the IDirectSoundCapture8 interface exposes the following methods.

Method | Description
CreateCaptureBuffer | Creates a buffer for capturing waveform audio.
GetCaps | Retrieves the capabilities of the capture device.
Initialize | Initializes a capture device object created by using CoCreateInstance.

The LPDIRECTSOUNDCAPTURE type is defined as a pointer to the IDirectSoundCapture interface:

typedef struct IDirectSoundCapture *LPDIRECTSOUNDCAPTURE;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Creating the Capture Device Object


IDirectSoundCapture8::CreateCaptureBuffer

The CreateCaptureBuffer method creates a buffer for capturing waveform audio.

Syntax

HRESULT CreateCaptureBuffer(
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPDIRECTSOUNDCAPTUREBUFFER * ppDSCBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSCBufferDesc

Pointer to a DSCBUFFERDESC structure containing values for the capture buffer being created.

ppDSCBuffer

Address of a variable that receives an IDirectSoundCaptureBuffer interface pointer. Use QueryInterface to obtain IDirectSoundCaptureBuffer8. See Remarks.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

On Microsoft Windows 98 and Windows 2000, each capture device supports a single buffer.

The IDirectSoundCaptureBuffer8 interface is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from DirectSoundCaptureCreate8, IDirectSoundCaptureBuffer8 is supported. If IDirectSoundCapture8 was obtained from the earlier DirectSoundCaptureCreate function, only IDirectSoundCaptureBuffer is supported.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCapture8 Interface
  • Creating a Capture Buffer


IDirectSoundCapture8::GetCaps

The GetCaps method retrieves the capabilities of the capture device.

Syntax

HRESULT GetCaps(
  LPDSCCAPS pDSCCaps
);

Parameters

pDSCCaps

Pointer to a DSCCAPS structure to be receive information about the capture device. When the method is called, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCapture8 Interface
  • Capture Device Capabilities


IDirectSoundCapture8::Initialize

The Initialize method initializes a capture device object created by using CoCreateInstance. Calling this method is not required when the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function is used to create the object.

Syntax

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice

Address of the GUID specifying the sound driver to which the DirectSoundCapture object binds. Use NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_ALREADYINITIALIZED

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCapture8 Interface


IDirectSoundCaptureBuffer8 Interface

The IDirectSoundCaptureBuffer8 interface is used to manipulate sound capture buffers.

To obtain the IDirectSoundCaptureBuffer8 interface, call the IDirectSoundCapture8::CreateCaptureBuffer method to obtain IDirectSoundCaptureBuffer, then pass IID_IDirectSoundCaptureBuffer8 to IDirectSoundCaptureBuffer::QueryInterface.

Note IDirectSoundCaptureBuffer8 cannot be obtained if the IDirectSoundCapture8 interface was obtained by using the DirectSoundCaptureCreate function. See DirectSoundCaptureCreate8.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureBuffer8 interface exposes the following methods, arranged by category.

Capture management

Method | Description
Lock | Locks a portion of the buffer, allowing the application to read or write audio data.
Start | Begins capturing data into the buffer.
Stop | Stops the buffer so that it is no longer capturing data.
Unlock | Unlocks the buffer.

Effects

Method | Description
GetFXStatus | Retrieves the status of capture effects.
GetObjectInPath | Retrieves an interface to an effect object associated with the buffer.

Initialization

Method | Description
Initialize | Initializes a capture buffer object. Not used by applications.

Information

Method | Description
GetCaps | Retrieves the capabilities of the buffer.
GetCurrentPosition | Retrieves the positions of the capture and read cursors in the buffer.
GetFormat | Retrieves the waveform format of the capture buffer.
GetStatus | Retrieves the status of the capture buffer.

The LPDIRECTSOUNDCAPTUREBUFFER8 type is defined as a pointer to the IDirectSoundCaptureBuffer8 interface:

typedef struct IDirectSoundCaptureBuffer8 *LPDIRECTSOUNDCAPTUREBUFFER8;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces


IDirectSoundCaptureBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer.

Syntax

HRESULT GetCaps(
  LPDSCBCAPS pDSCBCaps
);

Parameters

pDSCBCaps

Pointer to a DSCBCAPS structure that receives information about the capture buffer. On input, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface


IDirectSoundCaptureBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the positions of the capture and read cursors in the buffer.

The capture cursor is ahead of the read cursor. The data after the read position up to and including the capture position is not necessarily valid data.

Syntax

HRESULT GetCurrentPosition(
  LPDWORD pdwCapturePosition,
  LPDWORD pdwReadPosition
);

Parameters

pdwCapturePosition

Address of a variable that receives the offset from the start of the buffer, in bytes, of the capture cursor. The parameter can be NULL if this value is not wanted.

pdwReadPosition

Address of a variable that receives the offset from the start of the buffer, in bytes, of the read cursor.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::GetFormat

The GetFormat method retrieves the waveform format of the capture buffer.

Syntax

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat

Address of a WAVEFORMATEX structure that receives a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify NULL.; in this case, the DWORD pointed to by the pdwSizeWritten parameter receives the size of the structure needed to receive complete format information.

dwSizeAllocated

Size, in bytes, of the WAVEFORMATEX structure. DirectSoundCapture writes, at most, dwSizeAllocated bytes to the structure.

pdwSizeWritten

Address of a variable that receives the number of bytes written to the WAVEFORMATEX structure; or, if pwfxFormat is NULL, the size of the WAVEFORMATEX structure that would be necessary to receive the information. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::GetFXStatus

The GetFXStatus method retrieves the status of capture effects.

Syntax

HRESULT GetFXStatus(
  DWORD dwFXCount,
  LPDWORD pdwFXStatus
);

Parameters

dwFXCount

Number of elements in the pdwFXStatus array.

pdwFXStatus

Address of an array of DWORD variables that receive the status of each effect. This should contain the same number of elements as the array passed in the dwFXCount member of the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer. The possible values returned in the array are as follows:

Value | Description
DSCFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSCFXR_LOCSOFTWARE | Effect is instantiated in software.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface to an effect object associated with the buffer.

Syntax

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject

Value of type REFGUID that specifies the unique class identifier of the object being searched for, such as GUID_DSCFX_CLASS_AEC.

dwIndex

Index of the object within objects of that class in the path. See Remarks.

rguidInterface

Unique identifier of the desired interface, such as IID_IDirectSoundCaptureFXAec8.

ppObject

Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND
E_NOINTERFACE

Remarks

The value in dwIndex is the index of the object within the array of effects in the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureBuffer8::GetStatus

The GetStatus method retrieves the status of the capture buffer.

Syntax

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus

Address of a variable that receives the status of the capture buffer. The status can be set to one or more of the following:

Value | Description
DSCBSTATUS_CAPTURING | The buffer is capturing audio data.
DSCBSTATUS_LOOPING | The buffer is looping.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::Initialize

The Initialize method initializes a capture buffer object. Because the IDirectSoundCapture8::CreateCaptureBuffer method and the DirectSoundFullDuplexCreate8 function call the IDirectSoundCaptureBuffer8::Initialize method internally, this method is not used by applications.

Syntax

HRESULT Initialize(
  LPDIRECTSOUNDCAPTURE pDirectSoundCapture,
  LPCDSCBUFFERDESC pcDSCBufferDesc
);

Parameters

pDirectSoundCapture

Address of the DirectSoundCapture object associated with this DirectSoundCaptureBuffer object.

pcDSCBufferDesc

Address of a DSCBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface


IDirectSoundCaptureBuffer8::Lock

The Lock method locks a portion of the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into memory.

Syntax

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID *ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID *ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset

Offset, in bytes, from the start of the buffer to the point where the lock begins.

dwBytes

Size, in bytes, of the portion of the buffer to lock. Because the buffer is conceptually circular, this number can exceed the number of bytes between dwOffset and the end of the buffer.

ppvAudioPtr1

Address of a variable that receives a pointer to the first locked part of the buffer.

pdwAudioBytes1

Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer.

ppvAudioPtr2

Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.

pdwAudioBytes2

Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.

dwFlags

Flags modifying the lock event. This value can be zero or the following flag:

Value | Description
DSCBLOCK_ENTIREBUFFER | Ignore dwBytes and lock the entire capture buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

This method accepts an offset and a byte count, and returns two read pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

The application should read data from the pointers returned by this method and then immediately call IDirectSoundCaptureBuffer8::Unlock. The sound buffer should not remain locked while it is running; if it does, the capture cursor will reach the locked bytes and audio problems may result.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Start

The Start method begins capturing data into the buffer. If the buffer is already capturing, the method has no effect.

Syntax

HRESULT Start(
  DWORD dwFlags
);

Parameters

dwFlags

Flags that specify the behavior of the buffer when capturing sound data. The following flag is defined:

Value | Description
DSCBSTART_LOOPING | After the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Remarks

If the buffer is already capturing, a call to this method using a different value in dwFlags might not change the value returned by IDirectSoundCaptureBuffer8::GetStatus.

If the application is multithreaded, the thread that starts the buffer must continue to exist as long as the buffer is capturing. Buffers created on WDM drivers stop capturing when the thread is terminated.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Stop

The Stop method stops the buffer so that it is no longer capturing data. If the buffer is not capturing, the method has no effect.

Syntax

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Unlock

The Unlock method unlocks the buffer.

Syntax

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1

Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundCaptureBuffer8::Lock method.

dwAudioBytes1

Number of bytes read from the pvAudioPtr1 parameter. See Remarks.

pvAudioPtr2

Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundCaptureBuffer8::Lock method.

dwAudioBytes2

Number of bytes read from the pvAudioPtr2 parameter. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundCaptureBuffer8::Lock method to ensure the correct pairing of IDirectSoundCaptureBuffer8::Lock and IDirectSoundCaptureBuffer8::Unlock. The second pointer is needed even if zero bytes were written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually read from each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to transfer from the device.

Make sure that the capture buffer does not remain locked for long periods of time.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureFXAec8 Interface

The IDirectSoundCaptureFXAec8 interface is used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation. This interface requires Microsoft® Windows® XP or later operating systems.

IDirectSoundCaptureFXAec8 is a define for IDirectSoundCaptureFXAec. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXAec8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the acoustic echo cancellation parameters of a buffer.
GetStatus | Retrieves the status of the effect.
Reset | Resets the effect to its initial state.
SetAllParameters | Sets the acoustic echo cancellation parameters of a buffer.

The LPDIRECTSOUNDCAPTUREFXAEC8 type is defined as a pointer to the IDirectSoundCaptureFXAec8 interface:

typedef struct IDirectSoundCaptureFXAec8 *LPDIRECTSOUNDCAPTUREFXAEC8;

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::GetAllParameters

The GetAllParameters method retrieves the acoustic echo cancellation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSCFXAec pDscFxAec
);

Parameters

pDscFxAec

Address of a DSCFXAec structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_E_OUTOFMEMORY

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::GetStatus

The IDirectSoundCaptureFXAec8::GetStatus method retrieves the status of the effect.

Syntax

HRESULT GetStatus(
  PDWORD pdwStatus
);

Parameters

pdwStatus

Address of a DWORD variable to receive the status. The following flags are defined. See Remarks.

Constant | Value
DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED | 0x0
DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED | 0x1
DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED | 0x2
DSCFX_AEC_STATUS_CURRENTLY_CONVERGED | 0x8

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_E_OUTOFMEMORY

Remarks

The three least significant bits in *pdwStatus describe the convergence history; that is, the success of the effect in canceling the echo. The convergence history can be used by the application to determine if the algorithm has converged and remained in the converged state since it started processing data.

Initially, the AEC algorithm sets the three lower bits to 0 for the uninitialized state (DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED). When the AEC algorithm has converged, the convergence history is switched to the DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED state. If the AEC algorithm ever loses convergence, the convergence history is then transitioned to the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state. A transition from DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED to DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED is also possible. The convergence history remains in the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state until the algorithm is reset or timely data is no longer arriving on the capture or render stream.

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::Reset

The IDirectSoundCaptureFXAec8::Reset method resets the effect to its initial state.

Syntax

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_E_OUTOFMEMORY.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::SetAllParameters

The SetAllParameters method sets the acoustic echo cancellation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSCFXAec  pcDscFxAec
);

Parameters

pcDscFxAec

Address of a DSCFXAec structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_E_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8 Interface

The IDirectSoundCaptureFXNoiseSuppress8 interface is used to set and retrieve parameters on a capture buffer that supports noise suppression. This interface requires Microsoft Windows XP or later.

IDirectSoundCaptureFXNoiseSuppress8 is a define for IDirectSoundCaptureFXNoiseSuppress. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXNoiseSuppress8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the noise suppression parameters of a buffer.
Reset | Resets the effect to its initial state.
SetAllParameters | Sets the noise suppression parameters of a buffer.

The LPDIRECTSOUNDNOISESUPPRESS8 type is defined as a pointer to the IDirectSoundNoiseSuppress8 interface:

typedef struct IDirectSoundCaptureFXNoiseSuppress8  *LPDIRECTSOUNDCAPTUREFXNOISESUPPRESS8;

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters

The GetAllParameters method retrieves the noise suppression parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSCFXNoiseSuppress pDsFxNoiseSuppress
);

Parameters

pDscFxNoiseSuppress

Address of a DSCFXNoiseSuppress structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_E_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::Reset

The IDirectSoundCaptureFXNoiseSuppress8::Reset method resets the effect to its initial state.

Syntax

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_E_OUTOFMEMORY.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters

The SetAllParameters method sets the noise suppression parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSCFXNoiseSuppression  pcDscFxNoiseSuppress
);

Parameters

pcDscFxNoiseSuppress

Address of a DSCFXNoiseSuppress structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_E_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundFullDuplex8 Interface

The IDirectSoundFullDuplex8 interface represents a full-duplex stream.

The interface is obtained by using the DirectSoundFullDuplexCreate8 function. This function initializes DirectSound capture and playback.

The interface can also be obtained by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundFullDuplex8.

Note An object of this type can be created on earlier operating systems by using CoCreateInstance or CoCreateInstanceEx. However, a call to Initialize will fail.

IDirectSoundFullDuplex8 is a define for IDirectSoundFullDuplex. The interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectSoundFullDuplex8 interface exposes the following method.

Method | Description
Initialize | Initializes a full duplex object that was created by using CoCreateInstance.

The LPDIRECTSOUNDFULLDUPLEX type is defined as a pointer to IDirectSoundFullDuplex.

typedef struct IDirectSoundFullDuplex *LPDIRECTSOUNDFULLDUPLEX;

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces


IDirectSoundFullDuplex8::Initialize

The Initialize method initializes a full duplex object that was created by using CoCreateInstance.

Syntax

HRESULT Initialize(
  LPCGUID  pCaptureGuid,
  LPCGUID  pRenderGuid,
  LPCDSCBUFFERDESC  lpDscBufferDesc,
  LPCDSBUFFERDESC  lpDsBufferDesc,
  HWND  hWnd,
  DWORD  dwLevel,
  LPLPDIRECTSOUNDCAPTUREBUFFER8  lplpDirectSoundCaptureBuffer8,
  LPLPDIRECTSOUNDBUFFER8  lplpDirectSoundBuffer8
);

Parameters

pCaptureGuid

Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default capture device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pRenderGuid

Address of the GUID that identifies the sound rendering device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, NULL for the default rendering device, or one of the following values:

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

lpDscBufferDesc

Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.

lpDsBufferDesc

Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.

hWnd

Handle to the application window.

dwLevel

Cooperative level for the device. For more information, see IDirectSound8::SetCooperativeLevel.

lplpDirectSoundCaptureBuffer8

Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.

lplpDirectSoundBuffer8

Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If it fails, the return value may be one of the following values:

Return code
DSERR_ALREADYINITIALIZED
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Declared in dsound.h.

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundFullDuplex8 Interface


IDirectSoundFXChorus8 Interface

The IDirectSoundFXChorus8 interface is used to set and retrieve effect parameters on a buffer that supports chorus.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXChorus8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the chorus parameters of a buffer.
SetAllParameters | Sets the chorus parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXChorus8::GetAllParameters

The GetAllParameters method retrieves the chorus parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXChorus pDsFxChorus
);

Parameters

pDsFxChorus

Address of a DSFXChorus structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXChorus8 Interface
  • Effect Parameters


IDirectSoundFXChorus8::SetAllParameters

The SetAllParameters method sets the chorus parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXChorus  pcDsFxChorus
);

Parameters

pcDsFxChorus

Address of a DSFXChorus structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXChorus8 Interface
  • Effect Parameters


IDirectSoundFXCompressor8 Interface

The IDirectSoundFXCompressor8 interface is used to set and retrieve effect parameters on a buffer that supports compression.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXCompressor8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the compressor parameters of a buffer.
SetAllParameters | Sets the compressor parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXCompressor8::GetAllParameters

The GetAllParameters method retrieves the compression parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXCompressor pDsFxCompressor
);

Parameters

pDsFxCompressor

Address of a DSFXCompressor structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXCompressor8 Interface
  • Effect Parameters


IDirectSoundFXCompressor8::SetAllParameters

The SetAllParameters method sets the compression parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXCompressor pcDsFxCompressor
);

Parameters

pcDsFxCompressor

Address of a DSFXCompressor structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXCompressor8 Interface
  • Effect Parameters


IDirectSoundFXDistortion8 Interface

The IDirectSoundFXDistortion8 interface is used to set and retrieve effect parameters on a buffer that supports distortion.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXDistortion8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the distortion parameters of a buffer.
SetAllParameters | Sets the distortion parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXDistortion8::GetAllParameters

The GetAllParameters method retrieves the distortion parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXDistortion  pDsFxDistortion
);

Parameters

pDsFxDistortion

Address of a DSFXDistortion structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXDistortion8 Interface
  • Effect Parameters


IDirectSoundFXDistortion8::SetAllParameters

The SetAllParameters method sets the distortion parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXDistortion  pcDsFxDistortion
);

Parameters

pcDsFxDistortion

Address of a DSFXDistortion structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXDistortion.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXDistortion8 Interface
  • Effect Parameters


IDirectSoundFXEcho8 Interface

The IDirectSoundFXEcho8 interface is used to set and retrieve effect parameters on a buffer that supports echo.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXEcho8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the echo parameters of a buffer.
SetAllParameters | Sets the echo parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXEcho8::GetAllParameters

The GetAllParameters method retrieves the echo parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXEcho pDsFxEcho
);

Parameters

pDsFxEcho

Address of a DSFXEcho structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXEcho8 Interface
  • Effect Parameters


IDirectSoundFXEcho8::SetAllParameters

The SetAllParameters method sets the echo parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXEcho  pcDsFxEcho
);

Parameters

pcDsFxEcho

Address of a DSFXEcho structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXEcho8 Interface
  • Effect Parameters


IDirectSoundFXFlanger8 Interface

The IDirectSoundFXFlanger8 interface is used to set and retrieve effect parameters on a buffer that supports flange.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXFlanger8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the flanger parameters of a buffer.
SetAllParameters | Sets the flanger parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXFlanger8::GetAllParameters

The GetAllParameters method retrieves the flange parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXFlanger  pDsFxFlanger
);

Parameters

pDsFxFlanger

Address of a DSFXFlanger structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXFlanger8 Interface
  • Effect Parameters


IDirectSoundFXFlanger8::SetAllParameters

The SetAllParameters method sets the flange parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXFlanger pcDsFxFlanger
);

Parameters

pcDsFxFlanger

Address of a DSFXFlanger structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXFlanger8 Interface
  • Effect Parameters


IDirectSoundFXGargle8 Interface

The IDirectSoundFXGargle8 interface is used to set and retrieve effect parameters on a buffer that supports amplitude modulation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXGargle8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the gargle parameters of a buffer.
SetAllParameters | Sets the gargle parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXGargle8::GetAllParameters

The GetAllParameters method retrieves the amplitude modulation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXGargle  pDsFxGargle
);

Parameters

pDsFxGargle

Address of a DSFXGargle structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXGargle8 Interface
  • Effect Parameters


IDirectSoundFXGargle8::SetAllParameters

The SetAllParameters method sets the amplitude modulation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXGargle  pcDsFxGargle
);

Parameters

pcDsFxGargle

Address of a DSFXGargle structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXGargle8 Interface
  • Effect Parameters


IDirectSoundFXI3DL2Reverb8 Interface

The IDirectSoundFXI3DL2Reverb8 interface is used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXI3DL2Reverb8 interface exposes the following methods.

Parameters

Method | Description
GetAllParameters | Retrieves the I3DL2 environmental reverberation parameters of a buffer.
GetQuality | Retrieves the quality of the environmental reverberation effect.
SetAllParameters | Sets the I3DL2 environmental reverberation parameters of a buffer.
SetQuality | Sets the quality of the environmental reverberation effect.

Presets

Method | Description
GetPreset | Retrieves an identifier for standard reverberation parameters of a buffer.
SetPreset | Sets standard reverberation parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Environmental Reverberation
  • Using Effects


IDirectSoundFXI3DL2Reverb8::GetAllParameters

The GetAllParameters method retrieves the I3DL2 environmental reverberation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXI3DL2Reverb pDsFxI3DL2Reverb
);

Parameters

pDsFxI3DL2Reverb

Address of a DSFXI3DL2Reverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::GetPreset

The GetPreset method retrieves an identifier for standard reverberation parameters of a buffer.

Syntax

HRESULT GetPreset(
  LPDWORD  pdwPreset
);

Parameters

pdwPreset

Address of a DWORD that receives one of the preset identifiers. For a list of defined values, see IDirectSoundFXI3DL2Reverb8::SetPreset.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::GetQuality

The GetQuality method retrieves the quality of the environmental reverberation effect.

Syntax

HRESULT GetQuality(
  LONG * plQuality
);

Parameters

plQuality

Address of a LONG variable to receive the quality of the effect.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXI3DL2Reverb8::SetQuality
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetAllParameters

The SetAllParameters method sets the I3DL2 environmental reverberation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXI3DL2Reverb  pcDsFxI3DL2Reverb
);

Parameters

pcDsFxI3DL2Reverb

Address of a DSFXI3DL2Reverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetPreset

The SetPreset method sets standard reverberation parameters of a buffer.

Syntax

HRESULT SetPreset(
  DWORD  dwPreset
);

Parameters

dwPreset

Value that specifies a preset. The following constants are defined. See Dsound.h for the default parameters associated with each preset.

Value
DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT
DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC
DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL
DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM
DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE
DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA
DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR
DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR
DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY
DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST
DSFX_I3DL2_ENVIRONMENT_PRESET_CITY
DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS
DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY
DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN
DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT
DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE
DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER
DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetQuality

The SetQuality method sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

Syntax

HRESULT SetQuality(
  LONG lQuality
);

Parameters

lQuality

Quality of the effect, in the range from DSFX_I3DL2REVERB_QUALITY_MIN to DSFX_I3DL2REVERB_QUALITY_MAX. The default value is 2.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXI3DL2Reverb8::GetQuality
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXParamEq8 Interface

The IDirectSoundFXParamEq8 interface is used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.

In addition to the methods inherited from IUnknown, the IDirectSoundFXParamEq8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the parametric equalizer parameters of a buffer.
SetAllParameters | Sets the parametric equalizer parameters of a buffer.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXParamEq8::GetAllParameters

The GetAllParameters method retrieves the parametric equalizer parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXParamEq pDsFxParamEq
);

Parameters

pDsFxParamEq

Address of a DSFXParamEq structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXParamEq8 Interface
  • Effect Parameters


IDirectSoundFXParamEq8::SetAllParameters

The SetAllParameters method sets the parametric equalizer parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXParamEq  pcDsFxParamEq
);

Parameters

pcDsFxParamEq

Address of a DSFXParamEq structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXParamEq.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXParamEq8 Interface
  • Effect Parameters


IDirectSoundFXWavesReverb8 Interface

The IDirectSoundFXWavesReverb8 interface is used to set and retrieve effect parameters on a buffer that supports Waves reverberation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXWavesReverb8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the Waves reverb parameters of a buffer.
SetAllParameters | Sets the Waves reverb equalizer parameters of a buffer.

Remarks

The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXWavesReverb8::GetAllParameters

The GetAllParameters method retrieves the music reverberation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXWavesReverb  pDsFXWavesReverb
);

Parameters

pDsFXWavesReverb

Address of a DSFXWavesReverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXWavesReverb8 Interface
  • Effect Parameters


IDirectSoundFXWavesReverb8::SetAllParameters

The SetAllParameters method sets the music reverberation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXWavesReverb  pcDsFXWavesReverb
);

Parameters

pcDsFXWavesReverb

Address of a DSFXWavesReverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundFXWavesReverb8 Interface
  • Effect Parameters


IDirectSoundNotify8 Interface

The IDirectSoundNotify8 interface sets up notification events for a playback or capture buffer.

IDirectSoundNotify8 is a define for IDirectSoundNotify. The two interface names are interchangeable.

The interface is obtained by calling the QueryInterface method of an existing interface on a DirectSound buffer object. Secondary buffers support notifications only if they are created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

In addition to the methods inherited from IUnknown, the IDirectSoundNotify8 interface exposes the following method.

Method | Description
SetNotificationPositions | Sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

The LPDIRECTSOUNDNOTIFY type is defined as a pointer to the IDirectSoundNotify interface:

typedef struct IDirectSoundNotify  *LPDIRECTSOUNDNOTIFY;

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Play Buffer Notification


IDirectSoundNotify8::SetNotificationPositions

The SetNotificationPositions method sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

Syntax

HRESULT SetNotificationPositions(
  DWORD dwPositionNotifies,
  LPCDSBPOSITIONNOTIFY pcPositionNotifies
);

Parameters

dwPositionNotifies

Number of DSBPOSITIONNOTIFY structures.

pcPositionNotifies

Pointer to an array of DSBPOSITIONNOTIFY structures.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The value DSBPN_OFFSETSTOP can be specified in the dwOffset member to tell DirectSound to signal the associated event when the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method is called or when the end of the buffer has been reached and the playback is not looping. If it is used, this should be the last item in the position-notify array.

If a position-notify array has already been set, the method replaces the previous array.

The buffer must be stopped when this method is called.

Requirements

Header: Declared in dsound.h.

See Also

  • IDirectSoundNotify8 Interface


IKsPropertySet Interface

The IKsPropertySet interface allows drivers to provide extended capabilities that can be used without API extensions. DirectSound supports this interface for accessing properties of sound drivers.

The IKsPropertySet interface is part of the WDM KS (Win32® driver model kernel streaming) architecture.

Note The declaration of this interface in Dsound.h is different from that in Ksproxy.h and Strmif.h. If your project includes Ksproxy.h or Strmif.h but you wish to use the DirectSound implementation, be sure to include Dsound.h first. Failing to do so may cause your application to stop responding when a method of IKsPropertySet is called.

To retrieve this interface, call the QueryInterface method of any interface on a DirectSound buffer.

In addition to the methods inherited from IUnknown, the IKsPropertySet interface exposes the following methods.

Method | Description
Get | Retrieves data for an item in a property set.
QuerySupport | Ascertains whether a property in a property set is supported on the port or device.
Set | Sets the value of a property in a property set.

Requirements

Header: Declared in dsound.h.

See Also

  • DirectSound Interfaces
  • Property Sets for DirectSound Buffers


IKsPropertySet::Get

The Get method retrieves data for an item in a property set.

Syntax

HRESULT Get(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be accessed.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set GUID.

pInstanceData

Instance data for the get call.

ulInstanceLength

Number of bytes pointed to by pInstanceData.

pPropertyData

Data to set for this item.

ulDataLength

Number of bytes pointed to by pPropertyData

pulBytesReturned

Address of a variable that receives the number of bytes written into pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return one E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in dsound.h.

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


IKsPropertySet::QuerySupport

The QuerySupport method ascertains whether a property in a property set is supported on the port or device.

Syntax

HRESULT QuerySupport(
  REFGUID rguidPropSet,
  ULONG ulId,
  PULONG pulTypeSupport
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be queried.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.

pulTypeSupport

Address of a variable that receives information about support for the property. This variable can receive one or both of the following flags. See Remarks.

Value | Description
KSPROPERTY_SUPPORT_GET | The property item may be retrieved.
KSPROPERTY_SUPPORT_SET | The property item may be set.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK. (See Remarks.)

If it fails, the method may return one of the following error values:

Return code
E_NOTIMPL (See Remarks.)
E_POINTER

Remarks

Whether it is valid to support some properties within the set but not others depends on the definition of the property set. Consult the hardware manufacturer's specification for the property set of interest.

Some implementations may return S_OK when the property is not supported, and others may return E_NOTIMPL. To be sure that a property is supported, check both the return value of the method and the value returned in pulTypeSupport. If S_OK is returned but pulTypeSupport does not contain a valid flag, the property is not supported.

Requirements

Header: Declared in dsound.h.

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


IKsPropertySet::Set

The Set method sets the value of a property in a property set.

Syntax

HRESULT Set(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be accessed.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.

pInstanceData

Instance data for the set call. If there are multiple objects within the port that this operation could act on, the instance data specifies which object should be used. No standard property set items at the DirectMusic® API level use instance data; however, vendor-defined extensions are free to use it.

ulInstanceLength

Number of bytes pointed to by pInstanceData.

pPropertyData

Property data to set for this item.

ulDataLength

Number of bytes pointed to by pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in dsound.h.

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


DirectSound Callback Function

This section contains reference information for the following DirectSound callback function.

Function | Description
DSEnumCallback | Application-defined callback function that enumerates the DirectSound drivers.


DSEnumCallback

The DSEnumCallback function is an application-defined callback function that enumerates the DirectSound drivers. The system calls this function in response to the application's call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function.

Syntax

BOOL CALLBACK DSEnumCallback(
  LPGUID  lpGuid,
  LPCSTR  lpcstrDescription,
  LPCSTR  lpcstrModule,
  LPVOID  lpContext
);

Parameters

lpGuid

Address of the GUID that identifies the device being enumerated, or NULL for the primary device. This value can be passed to the DirectSoundCreate8 or DirectSoundCaptureCreate8 function to create a device object for that driver.

lpcstrDescription

Address of a null-terminated string that provides a textual description of the DirectSound device.

lpcstrModule

Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.

lpContext

Address of application-defined data. This is the pointer passed to DirectSoundEnumerate or DirectSoundCaptureEnumerate as the lpContext parameter.

Return Values

Returns TRUE to continue enumerating drivers, or FALSE to stop.

Remarks

The memory pointed to by lpGuid, lpcstrDescription, and lpcstrModule is local in scope. If you want to save these values, you must allocate them in global memory.

The primary device is enumerated twice, first with NULL in lpGuid and then with its GUID in that parameter.

Requirements

Header: Declared in Dsound.h.

See Also

  • DirectSoundEnumerate
  • Enumerating Sound Devices
  • Enumerating Capture Devices


DirectSound Functions

This section contains reference information for the following DirectSound and DirectSoundCapture global functions.

Function | Description
DirectSoundCaptureCreate8 | Creates and initializes an object that supports the IDirectSoundCapture8 interface.
DirectSoundCaptureEnumerate | Enumerates the DirectSoundCapture objects installed in the system.
DirectSoundCreate8 | Creates and initializes an object that supports the IDirectSound8 interface.
DirectSoundEnumerate | Enumerates the DirectSound drivers installed in the system.
DirectSoundFullDuplexCreate8 | Creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface.
GetDeviceID | Retrieves the unique device identifier of the default playback and capture devices selected by the user.


DirectSoundCaptureCreate8

The DirectSoundCaptureCreate8 function creates and initializes an object that supports the IDirectSoundCapture8 interface.

This function creates an object that supports capture effects. Although the older DirectSoundCaptureCreate function can also be used to obtain the IDirectSoundCapture8 interface, the object created by that function cannot be used to create capture buffers that support the IDirectSoundCaptureBuffer8 interface.

Syntax

HRESULT WINAPI DirectSoundCaptureCreate8(
  LPCGUID lpcGUID,
  LPDIRECTSOUNDCAPTURE8 *lplpDSC,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGUID

Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

lplpDSC

Address of a variable to receive an IDirectSoundCapture8 interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following values.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.

See Also

  • Creating the Capture Device Object


DirectSoundCaptureEnumerate

The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.

Syntax

HRESULT WINAPI DirectSoundCaptureEnumerate(
  LPDSENUMCALLBACK  lpDSEnumCallback,
  LPVOID  lpContext
);

Parameters

lpDSEnumCallback

Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system.

lpContext

Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.

See Also

  • Enumerating Capture Devices


DirectSoundCreate8

The DirectSoundCreate8 function creates and initializes an object that supports the IDirectSound8 interface.

Syntax

HRESULT WINAPI DirectSoundCreate8(
  LPCGUID  lpcGuidDevice,
  LPDIRECTSOUND8 * ppDS8,
  LPUNKNOWN  pUnkOuter
);

Parameters

lpcGuidDevice

Address of the GUID that identifies the sound device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default device, or one of the following values.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device. Equivalent to NULL.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

ppDS8

Address of a variable to receive an IDirectSound8 interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The application must call the IDirectSound8::SetCooperativeLevel method immediately after creating a device object.

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.

See Also

  • IDirectSound8::GetCaps
  • IDirectSound8::SetCooperativeLevel
  • Creating the Device Object


DirectSoundEnumerate

The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.

Syntax

HRESULT WINAPI DirectSoundEnumerate(
  LPDSENUMCALLBACK  lpDSEnumCallback,
  LPVOID  lpContext
);

Parameters

lpDSEnumCallback

Address of the DSEnumCallback function that will be called for each device installed in the system.

lpContext

Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.

See Also

  • Enumerating Sound Devices


DirectSoundFullDuplexCreate8

The DirectSoundFullDuplexCreate8 function creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface. This function requires Microsoft Windows XP. Full duplex can be implemented on other operating systems, but the capture and rendering devices must be created separately.

Syntax

HRESULT WINAPI DirectSoundFullDuplexCreate8(
  LPCGUID  pcGuidCaptureDevice,
  LPCGUID  pcGuidRenderDevice,
  LPCDSCBUFFERDESC  pcDSCBufferDesc,
  LPCDSBUFFERDESC  pcDSBufferDesc,
  HWND  hWnd,
  DWORD  dwLevel,
  LPDIRECTSOUNDFULLDUPLEX*  ppDSFD,
  LPDIRECTSOUNDCAPTUREBUFFER8  *ppDSCBuffer8,
  LPDIRECTSOUNDBUFFER8  *ppDSBuffer8,
  LPUNKNOWN  pUnkOuter
);

Parameters

pcGuidCaptureDevice

Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default capture device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pcGuidRenderDevice

Address of the GUID that identifies the sound render device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default render device, or one of the following values.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

pcDSCBufferDesc

Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.

pcDSBufferDesc

Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.

hWnd

Handle to the application window.

dwLevel

Cooperative level for the device. For more information, see IDirectSound8::SetCooperativeLevel.

ppDSFD

Address of a variable that receives the IDirectSoundFullDuplex8 interface pointer.

ppDSCBuffer8

Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.

ppDSBuffer8

Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return code
DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.

See Also

  • Creating the Capture Device Object
  • Creating the Device Object


GetDeviceID

The GetDeviceID function retrieves the unique device identifier of the default playback and capture devices selected by the user in Control Panel.

Syntax

HRESULT GetDeviceID(
  LPCGUID  pGuidSrc,
  LPGUID  pGuidDest
);

Parameters

pGuidSrc

Address of a variable that specifies a valid device identifier, or the address of one of the following predefined variables.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pGuidDest

Address of a variable that receives the unique identifier of the device.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Remarks

If pGuidSrc points to a valid device identifier, the same value is returned in pGuidDest. If pGuidSrc is one of the listed constants, pGuidDest returns the address of the corresponding device GUID.

Requirements

Header: Declared in Dsound.h.
Import Library: Use Dsound.lib.


DirectSound Structures

This section contains reference information for the following structures used with DirectSound.

Structure | Description
D3DVECTOR | Describes a vector.
DS3DBUFFER | Contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer.
DS3DLISTENER | Describes the 3-D world parameters and position of the listener.
DSBCAPS | Describes the capabilities of a DirectSound buffer object.
DSBPOSITIONNOTIFY | Describes a notification position.
DSBUFFERDESC | Describes the characteristics of a buffer.
DSCAPS | Describes the capabilities of a device.
DSCBCAPS | Describes the capabilities of a capture buffer.
DSCBUFFERDESC | Describes a capture buffer.
DSCCAPS | Describes the capabilities of a capture device.
DSCEFFECTDESC | Contains parameters for an effect associated with a capture buffer.
DSCFXAec | Contains parameters for acoustic echo cancellation in a capture buffer.
DSCFXNoiseSuppress | Contains parameters for noise suppression in a capture buffer.
DSEFFECTDESC | Describes an effect associated with a buffer.
DSFXI3DL2Reverb | Contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.
DSFXChorus | Contains parameters for a chorus effect.
DSFXCompressor | Contains parameters for a compression effect.
DSFXDistortion | Contains parameters for a distortion effect.
DSFXEcho | Contains parameters for an echo effect.
DSFXFlanger | Contains parameters for a flange effect.
DSFXGargle | Contains parameters for an amplitude modulation effect.
DSFXParamEq | Contains parameters for a parametric equalizer effect.
DSFXWavesReverb | Contains parameters for a Waves reverberation effect.
WAVEFORMATEX | Defines the format of waveform-audio data.
WAVEFORMATEXTENSIBLE | Defines the format of waveform-audio data for formats having more than two channels.

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DSCAPS:

DSCAPS dscaps;

ZeroMemory(&dscaps, sizeof(dscaps));
dscaps.dwSize = sizeof(dscaps);


D3DVECTOR

The D3DVECTOR structure defines a vector.

Syntax

typedef struct _D3DVECTOR {
    float x;
    float y;
    float z;
} D3DVECTOR;

Members

x, y, z

Values for the axes of the vector.

Requirements

Header: Declared in D3d8types.h.

See Also

  • Coordinates of 3-D Space


DS3DBUFFER

The DS3DBUFFER structure contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer. This structure is used with the IDirectSound3DBuffer8::GetAllParameters and IDirectSound3DBuffer8::SetAllParameters methods.

Syntax

typedef struct {
  DWORD      dwSize;
  D3DVECTOR  vPosition;
  D3DVECTOR  vVelocity;
  DWORD      dwInsideConeAngle;
  DWORD      dwOutsideConeAngle;
  D3DVECTOR  vConeOrientation;
  LONG       lConeOutsideVolume;
  D3DVALUE   flMinDistance;
  D3DVALUE   flMaxDistance;
  DWORD      dwMode;
} DS3DBUFFER, *LPDS3DBUFFER;

typedef const DS3DBUFFER *LPCDS3DBUFFER;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

vPosition

A D3DVECTOR structure that describes the current position of the 3-D sound buffer.

vVelocity

A D3DVECTOR structure that describes the current velocity of the 3-D sound buffer.

dwInsideConeAngle

The angle of the inside sound projection cone.

dwOutsideConeAngle

The angle of the outside sound projection cone.

vConeOrientation

A D3DVECTOR structure that describes the current orientation of this 3-D buffer's sound projection cone.

lConeOutsideVolume

The cone outside volume.

flMinDistance

The minimum distance.

flMaxDistance

The maximum distance.

dwMode

The 3-D sound processing mode to be set. This value must be one of the values shown in the following table.

Value | Description
DS3DMODE_DISABLE | 3-D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Default. Normal processing.

Requirements

Header: Declared in Dsound.h.

See Also

  • DirectSound 3-D Buffers


DS3DLISTENER

The DS3DLISTENER structure describes the 3-D world parameters and the position of the listener. This structure is used with the IDirectSound3DListener8::GetAllParameters and IDirectSound3DListener8::SetAllParameters methods.

Syntax

typedef struct {
  DWORD      dwSize;
  D3DVECTOR  vPosition;
  D3DVECTOR  vVelocity;
  D3DVECTOR  vOrientFront;
  D3DVECTOR  vOrientTop;
  D3DVALUE   flDistanceFactor;
  D3DVALUE   flRolloffFactor;
  D3DVALUE   flDopplerFactor;
} DS3DLISTENER, *LPDS3DLISTENER;

typedef const DS3DLISTENER *LPCDS3DLISTENER;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

vPosition

D3DVECTOR structure that describes the listener's position.

vVelocity

D3DVECTOR structure that describes the listener's velocity.

vOrientFront

D3DVECTOR structure that describes the listener's front orientation.

vOrientTop

D3DVECTOR structure that describes the listener's top orientation.

flDistanceFactor

Number of meters in a vector unit.

flRolloffFactor

Ratio of attenuation over distance to that in the real world.

flDopplerFactor

Ratio of Doppler effect to that in the real world.

Requirements

Header: Declared in Dsound.h.

See Also

  • DirectSound 3-D Listeners


DSBCAPS

The DSBCAPS structure describes the capabilities of a DirectSound buffer object. It is used by the IDirectSoundBuffer8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwBufferBytes;
  DWORD  dwUnlockTransferRate;
  DWORD  dwPlayCpuOverhead;
} DSBCAPS, *LPDSBCAPS;

typedef const DSBCAPS *LPCDSBCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags that specify buffer-object capabilities. Use one or more of the values shown in the following table.

Value | Description
DSBCAPS_CTRL3D | The buffer has 3-D control capability.
DSBCAPS_CTRLFREQUENCY | The buffer has frequency control capability.
DSBCAPS_CTRLFX | The buffer supports effects processing.
DSBCAPS_CTRLPAN | The buffer has pan control capability.
DSBCAPS_CTRLVOLUME | The buffer has volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY | The buffer has position notification capability. See the Remarks for DSBUFFERDESC.
DSBCAPS_GETCURRENTPOSITION2 | The buffer uses the new behavior of the play cursor when IDirectSoundBuffer8::GetCurrentPosition is called. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. This flag affects only emulated devices; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS | The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER | The buffer can be assigned to a hardware or software resource at play time, or when IDirectSoundBuffer8::AcquireResources is called.
DSBCAPS_LOCHARDWARE | The buffer uses hardware mixing.
DSBCAPS_LOCSOFTWARE | The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE | The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted. Applies only to software buffers.
DSBCAPS_PRIMARYBUFFER | The buffer is a primary buffer.
DSBCAPS_STATIC | The buffer is in on-board hardware memory.
DSBCAPS_STICKYFOCUS | The buffer has sticky focus. If the user switches to another application not using DirectSound, the buffer is still audible. However, if the user switches to another DirectSound application, the buffer is muted.

dwBufferBytes

Size of this buffer, in bytes.

dwUnlockTransferRate

The rate, in kilobytes per second, at which data is transferred to the buffer memory when IDirectSoundBuffer8::Unlock is called. High-performance applications can use this value to determine the time required for IDirectSoundBuffer8::Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.

dwPlayCpuOverhead

The processing overhead as a percentage of main processor cycles needed to mix this sound buffer. For hardware buffers, this member will be zero because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.

Remarks

The DSBCAPS structure contains information similar to that found in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

The dwFlags member contains the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag is specified, according to the location of the buffer. In the DSBUFFERDESC structure, these flags are optional and are used to force the buffer to be located in either hardware or software.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSound8::CreateSoundBuffer
  • IDirectSoundBuffer8::GetCaps


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY structure describes a notification position. It is used by the IDirectSoundNotify8::SetNotificationPositions method.

Syntax

typedef struct {
  DWORD   dwOffset;
  HANDLE  hEventNotify;
} DSBPOSITIONNOTIFY, *LPDSBPOSITIONNOTIFY;

typedef const DSBPOSITIONNOTIFY *LPCDSBPOSITIONNOTIFY;

Members

dwOffset

Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.

hEventNotify

Handle to the event to be signaled when the offset has been reached.

Remarks

The DSBPN_OFFSETSTOP value in the dwOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method.

When a playback buffer was created with DSBCAPS_LOCDEFER and DSBCAPS_CTRLPOSITIONNOTIFY along with any voice management flag, it is possible that a sound that has notifications set, but not yet reached, will be terminated by the voice manager. In this case, no event is signaled.

Requirements

Header: Declared in Dsound.h.

See Also

  • Play Buffer Notification
  • Capture Buffer Notification


DSBUFFERDESC

The DSBUFFERDESC structure describes the characteristics of a new buffer object. It is used by the IDirectSound8::CreateSoundBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

Syntax

typedef struct {
  DWORD     dwSize;
  DWORD     dwFlags;
  DWORD     dwBufferBytes;
  DWORD     dwReserved;
  LPWAVEFORMATEX  lpwfxFormat;
  GUID      guid3DAlgorithm;
} DSBUFFERDESC, *LPDSBUFFERDESC;

typedef const DSBUFFERDESC *LPCDSBUFFERDESC;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags specifying the capabilities of the buffer. The following values are defined.

Value | Description
DSBCAPS_CTRL3D | The buffer has 3-D control capability. Cannot be combined with DSBCAPS_CTRLPAN, and cannot be set for a buffer with a stereo format in lpwfxFormat.
DSBCAPS_CTRLFREQUENCY | The buffer has frequency control capability.
DSBCAPS_CTRLFX | The buffer supports effects processing. The WAV format in lpwfxFormat must be an 8-bit or 16-bit PCM format with no more than two channels, and the buffer must be large enough to hold at least DSBSIZE_FX_MIN milliseconds of data.
DSBCAPS_CTRLPAN | The buffer has pan control capability. Cannot be combined with DSBCAPS_CTRL3D.
DSBCAPS_CTRLPOSITIONNOTIFY | The buffer has position notification capability. See Remarks.
DSBCAPS_CTRLVOLUME | The buffer has volume control capability.
DSBCAPS_GETCURRENTPOSITION2 | The IDirectSoundBuffer8::GetCurrentPosition method uses the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards. If a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS | The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER | The buffer can be assigned to a hardware or software resource at play time. This flag must be set for buffers that use voice management.
DSBCAPS_LOCHARDWARE | The buffer must use hardware mixing, If the device does not support hardware mixing or if the required hardware memory is not available, the call to IDirectSound8::CreateSoundBuffer method will fail. The application must ensure that a mixing channel is available for this buffer; this condition is not guaranteed. If neither this flag nor DSBCAPS_LOCSOFTWARE is specified, the buffer is placed in hardware if resources are available, or in software if hardware resources are not available.
DSBCAPS_LOCSOFTWARE | The buffer must be in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE | The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted. Applies only to software buffers.
DSBCAPS_PRIMARYBUFFER | The buffer is a primary buffer. If this value is not specified, a secondary sound buffer is created. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STATIC | The buffer is placed in on-board hardware memory, if available. No error occurs if such memory is not available. This flag has no effect on cards using the PCI bus. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STICKYFOCUS | The buffer has sticky focus. If the user switches to another application not using DirectSound, the application's normal buffers are muted, but sticky focus buffers are still audible.

dwBufferBytes

Size of the new buffer, in bytes. This value must be 0 when creating a buffer with the DSBCAPS_PRIMARYBUFFER flag. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.

dwReserved

Reserved. Must be 0.

lpwfxFormat

Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure specifying the waveform format for the buffer. This value must be NULL for primary buffers. The application can use IDirectSoundBuffer8::SetFormat to set the format of the primary buffer.

guid3DAlgorithm

Unique identifier of the two-speaker virtualization algorithm to be used by DirectSound3D hardware emulation. If DSBCAPS_CTRL3D is not set in dwFlags, this member must be GUID_NULL (DS3DALG_DEFAULT).

The following algorithm identifiers are defined.

Value | Description | Availability
DS3DALG_DEFAULT | DirectSound uses the default algorithm. In most cases this is DS3DALG_NO_VIRTUALIZATION. On WDM drivers, if the user has selected a surround sound speaker configuration in Control Panel, the sound is panned among the available directional speakers. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_NO_VIRTUALIZATION | 3-D output is mapped onto normal left and right stereo panning. At 90 degrees to the left, the sound is coming out of only the left speaker; at 90 degrees to the right, sound is coming out of only the right speaker. The vertical axis is ignored except for scaling of volume due to distance. Doppler shift and volume scaling are still applied, but the 3-D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3-D audio effect. When the DS3DALG_NO_VIRTUALIZATION algorithm is specified, HRTF processing will not be done. Because DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2-D hardware voice if no free 3-D hardware voices are available. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_HRTF_FULL | The 3-D API is processed with the high quality 3-D audio algorithm. This algorithm gives the highest quality 3-D audio effect, but uses more CPU cycles. See Remarks. | Applies to software mixing only. Available on Microsoft Windows 98 Second Edition and later operating systems when using WDM drivers.
DS3DALG_HRTF_LIGHT | The 3-D API is processed with the efficient 3-D audio algorithm. This algorithm gives a good 3-D audio effect, but uses fewer CPU cycles than DS3DALG_HRTF_FULL. | Applies to software mixing only. Available on Windows 98 Second Edition and later operating systems when using WDM drivers.

Remarks

When creating a primary buffer, applications must set the dwBufferBytes member to zero. DirectSound will determine the best buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer8::GetCaps.

The DSBCAPS_CTRLDEFAULT flag is no longer supported. This flag was defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

On VXD drivers, a sound buffer created with DSBCAPS_CTRLPOSITIONNOTIFY is always a software buffer, because the VXD driver model does not support notifications. With WDM drivers, a notification-enabled buffer can be in hardware, if hardware resources are available.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in hardware, meaning that it will be mixed by the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in software, where it is mixed by the CPU. These flags are also defined for the dwFlags member of the DSBCAPS structure.

The 3-D algorithms represent selection of the software emulation layer only—that is, the software algorithm that is used when no hardware is present for acceleration. In order to maximize hardware utilization, DS3DALG_NO_VIRTUALIZATION is treated as a special case. If no free 3-D hardware voices are available, the buffer is then treated as a 2-D buffer, but with 3-D control. Specifically, when a sound buffer is created with DS3DALG_NO_VIRTUALIZATION, or when the buffer is played if the buffer was created with DSBPLAY_LOCDEFER, the following procedure is followed:

  1. If a free hardware 3-D voice is available, that 3-D hardware voice is used.
  2. If no free hardware 3-D voices are available and a 2-D hardware voice is available, that 2-D hardware voice will be used. This is possible because the DS3DALG_NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm
  3. If no free 2-D or 3-D hardware voices are available, the voice will be played in software using the DS3DALG_NO_VIRTUALIZATION algorithm.

If a speaker configuration other than DSSPEAKER_HEADPHONE or DSSPEAKER_STEREO is in effect, the processing will be done as if for a two-speaker configuration.

If a buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

Requirements

Header: Declared in Dsound.h.

See Also

  • DirectSound Buffers
  • Dynamic Voice Management
  • IDirectSound8::CreateSoundBuffer


DSCAPS

The DSCAPS structure describes the capabilities of a device. It is used by the IDirectSound8::GetCaps method.

Syntax

typedef {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwMinSecondarySampleRate;
  DWORD  dwMaxSecondarySampleRate;
  DWORD  dwPrimaryBuffers;
  DWORD  dwMaxHwMixingAllBuffers;
  DWORD  dwMaxHwMixingStaticBuffers;
  DWORD  dwMaxHwMixingStreamingBuffers;
  DWORD  dwFreeHwMixingAllBuffers;
  DWORD  dwFreeHwMixingStaticBuffers;
  DWORD  dwFreeHwMixingStreamingBuffers;
  DWORD  dwMaxHw3DAllBuffers;
  DWORD  dwMaxHw3DStaticBuffers;
  DWORD  dwMaxHw3DStreamingBuffers;
  DWORD  dwFreeHw3DAllBuffers;
  DWORD  dwFreeHw3DStaticBuffers;
  DWORD  dwFreeHw3DStreamingBuffers;
  DWORD  dwTotalHwMemBytes;
  DWORD  dwFreeHwMemBytes;
  DWORD  dwMaxContigFreeHwMemBytes;
  DWORD  dwUnlockTransferRateHwBuffers;
  DWORD  dwPlayCpuOverheadSwBuffers;
  DWORD  dwReserved1;
  DWORD  dwReserved2;
} DSCAPS, *LPDSCAPS;

typedef const DSCAPS *LPCDSCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags describing device capabilities. Can include the values shown in the following table.

Value | Description
DSCAPS_CERTIFIED | The driver has been tested and certified by Microsoft. This flag is always set for WDM drivers. To test for certification, use IDirectSound8::VerifyCertification.
DSCAPS_CONTINUOUSRATE | The device supports all sample rates between the dwMinSecondarySampleRate and dwMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER | The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT | The device supports a primary buffer with 16-bit samples.
DSCAPS_PRIMARY8BIT | The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO | The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO | The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT | The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT | The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO | The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO | The device supports hardware-mixed stereo secondary buffers.

dwMinSecondarySampleRate, dwMaxSecondarySampleRate

Minimum and maximum sample rate specifications that are supported by this device's hardware secondary sound buffers.

dwPrimaryBuffers

Number of primary buffers supported. This value will always be 1.

dwMaxHwMixingAllBuffers

Number of buffers that can be mixed in hardware. This member can be less than the sum of dwMaxHwMixingStaticBuffers and dwMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.

dwMaxHwMixingStaticBuffers

Maximum number of static buffers.

dwMaxHwMixingStreamingBuffers

Maximum number of streaming sound buffers.

dwFreeHwMixingAllBuffers

Number of unallocated buffers. On WDM drivers, this includes dwFreeHw3DAllBuffers.

dwFreeHwMixingStaticBuffers

Number of unallocated static buffers.

dwFreeHwMixingStreamingBuffers

Number of unallocated streaming buffers.

dwMaxHw3DAllBuffers

Maximum number of 3-D buffers.

dwMaxHw3DStaticBuffers

Maximum number of static 3-D buffers.

dwMaxHw3DStreamingBuffers

Maximum number of streaming 3-D buffers.

dwFreeHw3DAllBuffers

Number of unallocated 3-D buffers.

dwFreeHw3DStaticBuffers

Number of unallocated static 3-D buffers.

dwFreeHw3DStreamingBuffers

Number of unallocated streaming 3-D buffers.

dwTotalHwMemBytes

Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.

dwFreeHwMemBytes

Size, in bytes, of the free memory on the sound card.

dwMaxContigFreeHwMemBytes

Size, in bytes, of the largest contiguous block of free memory on the sound card.

dwUnlockTransferRateHwBuffers

The rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers. This and the number of bytes transferred determines the duration of a call to the IDirectSoundBuffer8::Unlock method.

dwPlayCpuOverheadSwBuffers

The processing overhead, as a percentage of main processor cycles, needed to mix software buffers. This varies according to the bus type, the processor type, and the clock speed.

dwReserved1

Not used.

dwReserved2

Not used.

Remarks

Some audio cards may be unable to report accurately the number of available or free hardware buffers. This can happen, for example, when the card can play more sounds at lower sampling rates than at higher rates. In general, a nonzero value in any of the members relating to number of free hardware buffers signifies that at least one hardware resource of the appropriate type is available.

The unlock transfer rate for software buffers is 0, because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSound8::GetCaps


DSCBCAPS

The DSCBCAPS structure describes the capabilities of a capture buffer. It is used by the IDirectSoundCaptureBuffer8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwBufferBytes;
  DWORD  dwReserved;
} DSCBCAPS, *LPDSCBCAPS;

typedef const DSCBCAPS *LPCDSCBCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero or DSCBCAPS_WAVEMAPPED. The Win32 wave mapper will be used for formats not supported by the device.

dwBufferBytes

The size, in bytes, of the capture buffer.

dwReserved

Reserved for future use.

Requirements

Header: Declared in Dsound.h.


DSCBUFFERDESC

The DSCBUFFERDESC structure describes a capture buffer. It is used by the IDirectSoundCapture8::CreateCaptureBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSCBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

Syntax

typedef struct {
  DWORD     dwSize;
  DWORD     dwFlags;
  DWORD     dwBufferBytes;
  DWORD     dwReserved;
  LPWAVEFORMATEX  lpwfxFormat;
  DWORD     dwFXCount;
  LPDSCEFFECTDESC lpDSCFXDesc;
} DSCBUFFERDESC, *LPDSCBUFFERDESC;

typedef const DSCBUFFERDESC *LPCDSCBUFFERDESC;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero, or one or more of the flags shown in the following table.

Value | Description
DSCBCAPS_CTRLFX | The buffer supports effects. See Remarks.
DSCBCAPS_WAVEMAPPED | The Win32 wave mapper will be used for formats not supported by the device.

dwBufferBytes

Size of capture buffer to create, in bytes.

dwReserved

Reserved for future use.

lpwfxFormat

Pointer to a WAVEFORMATEX structure containing the format in which to capture the data.

dwFXCount

Number of elements in the array pointed to by lpDSCFXDesc. Must be zero unless DSCBCAPS_CTRLFX is present in dwFlags.

lpDSCFXDesc

Address of an array of DSCEFFECTDESC structures that describe effects supported by hardware for the buffer. User-mode DMOs are not supported.

Remarks

The DSCBCAPS_CTRLFX flag is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from the DirectSoundCaptureCreate8 function, this flag is supported; if it was obtained from the earlier DirectSoundCaptureCreate function, it is not supported.

Capture effects require Microsoft® Windows® XP.

Requirements

Header: Declared in Dsound.h.


DSCCAPS

The DSCCAPS structure describes the capabilities of the capture device. It is used by the IDirectSoundCapture8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwFormats;
  DWORD  dwChannels;
} DSCCAPS, *LPDSCCAPS;

typedef const DSCCAPS *LPCDSCCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero or one or more of the following flags.

Value | Description
DSCCAPS_CERTIFIED | The driver for the device is a certified WDM driver.
DSCCAPS_EMULDRIVER | There is no DirectSoundCapture driver for the device, so the standard waveform audio functions are being used.
DSCCAPS_MULTIPLECAPTURE | Multiple capture objects can be used simultaneously on the capture device.

dwFormats

Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions, and are defined in MMSystem.h in the Platform SDK.

dwChannels

Number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

Requirements

Header: Declared in Dsound.h.


DSCEFFECTDESC

The DSCEFFECTDESC structure contains parameters for an effect associated with a capture buffer.

Syntax

typedef struct _DSCEFFECTDESC {
  DWORD   dwSize;
  DWORD   dwFlags;
  GUID    guidDSCFXClass;
  GUID    guidDSCFXInstance;
  DWORD   dwReserved1;
  DWORD   dwReserved2;
} DSCEFFECTDESC, *LPDSCEFFECTDESC;

typedef const DSCEFFECTDESC *LPCDSCEFFECTDESC;

Members

dwSize

Size of the structure, in bytes.

dwFlags

Flags that specify desired parameters of the effect. When this structure is passed to DirectSoundFullDuplexCreate8, or IDirectSoundCapture8::CreateCaptureBuffer, this member must be one of the values shown in the following table.

Value | Description
DSCFX_LOCHARDWARE | Effect specified by guidDSCFXInstance must be in hardware.
DSCFX_LOCSOFTWARE | Effect specified by guidDSCFXInstance must be in software.

On return, this member can contain one of the values shown in the following table.

Value | Description
DSCFXR_LOCHARDWARE | Effect was created in hardware.
DSCFXR_LOCSOFTWARE | Effect was created in software.

guidDSCFXClass

Value of type GUID that specifies the class identifier of the effect. The following standard identifiers are defined.

Value | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation.
GUID_DSCFX_CLASS_NS | Noise suppression.

guidDSCFXInstance

Value of type GUID that specifies the unique identifier of the preferred effect. The following standard identifiers are defined.

Value | Description
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation. Available in software only.
GUID_DSCFX_MS_NS | Microsoft noise suppression. Available in software only.
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation.
GUID_DSCFX_SYSTEM_NS | System default noise suppression.

dwReserved1

Reserved. Must be zero.

dwReserved2

Reserved. Must be zero.

Requirements

Header: Declared in Dsound.h.


DSCFXAec

The DSCFXAec structure contains parameters for acoustic echo cancellation in a capture buffer.

Structure

typedef struct _DSCFXAec {
  BOOL  fEnable;
  BOOL  fNoiseFill;
  DWORD  dwMode;
} DSCFXAec, *LPDSCFXAec;

typedef const DSCFXAec *LPCDSCFXAec;

Members

fEnable

Boolean value that specifies whether the effect is enabled.

fNoiseFill

Boolean value that specifies whether to enable background comfort noise, which makes the capture signal sound more natural by preventing periods of dead silence. By default, background comfort noise is not enabled.

dwMode

Operation mode. This member contains one of the following values.

Constant | Description
DSCFX_AEC_MODE_PASS_THROUGH | The effect is passing capture and render data through without modifying it.
DSCFX_AEC_MODE_HALF_DUPLEX | The effect is running in half duplex mode. Not presently supported.
DSCFX_AEC_MODE_FULL_DUPLEX | The effect is running in full duplex mode.

Remarks

The dwMode member is ignored when this structure is passed to IDirectSoundCaptureFXAec8::SetAllParameters.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSoundCaptureFXAec8::GetAllParameters
  • IDirectSoundCaptureFXAec8::SetAllParameters


DSCFXNoiseSuppress

The DSCFXNoiseSuppress structure contains parameters for noise suppression in a capture buffer.

Syntax

typedef struct _DSCFXNoiseSuppress {
  BOOL  fEnable;
} DSCFXNoiseSuppress, *LPDSCFXNoiseSuppress;

typedef const DSCFXNoiseSuppress *LPCDSCFXNoiseSuppress;

Members

fEnable

Boolean value that specifies whether the effect is enabled.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters
  • IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters


DSEFFECTDESC

The DSEFFECTDESC structure describes an effect associated with a buffer.

Syntax

typedef struct _DSEFFECTDESC {
  DWORD      dwSize;
  DWORD      dwFlags;
  GUID       guidDSFXClass;
  DWORD_PTR  dwReserved1;
  DWORD_PTR  dwReserved2
} DSEFFECTDESC, *LPDSEFFECTDESC;

typedef const DSEFFECTDESC *LPCDSEFFECTDESC;

Members

dwSize

Size of the structure, in bytes.

dwFlags

Flags. Can be zero or one of the following values.

Value | Description
DSFX_LOCHARDWARE | Effect must be in hardware. If the effect is not available in hardware, IDirectSoundBuffer8::SetFX raises an error. Because DirectX 9.0 does not support hardware acceleration of effects, this flag should not be used.
DSFX_LOCSOFTWARE | Effect must be in software, even if the hardware supports acceleration of guidDSFXClass. If the effect is not available in software, SetFX raises an error. In DirectX 9.0, all effects are in software regardless of whether this flag is set.

guidDSFXClass

Class identifier of the effect. The following standard effect classes are defined.

Value | Description
GUID_DSFX_STANDARD_CHORUS | Chorus
GUID_DSFX_STANDARD_COMPRESSOR | Compressor
GUID_DSFX_STANDARD_DISTORTION | Distortion
GUID_DSFX_STANDARD_ECHO | Echo
GUID_DSFX_STANDARD_FLANGER | Flanger
GUID_DSFX_STANDARD_GARGLE | Gargle
GUID_DSFX_STANDARD_I3DL2REVERB | Interactive 3D Level 2 reverb
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer
GUID_DSFX_WAVES_REVERB | Waves reverb

dwReserved1

Reserved for future use.

dwReserved2

Reserved for future use.

Remarks

Custom effects can be implemented as DMOs. Effect DMOs must implement the IMediaObject and IMediaObjectInPlace interfaces.

If dwFlags is zero, the effect is placed in hardware if possible. If the hardware does not support the effect (always the case in DirectX 9.0), software is used. If the effect is not available at all, the call to SetFX fails.

An effect of class GUID_DSFX_WAVES_REVERB can be set only on a buffer that has a 16-bit audio format.

Requirements

Header: Declared in Dsound.h.

See Also

  • DSBCAPS
  • IDirectSoundBuffer8::SetFX
  • Using Effects


DSFXI3DL2Reverb

The DSFXI3DL2Reverb structure contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.

Syntax

typedef struct _DSFXI3DL2Reverb {
  LONG  lRoom;
  LONG  lRoomHF;
  FLOAT flRoomRolloffFactor;
  FLOAT flDecayTime;
  FLOAT flDecayHFRatio;
  LONG  lReflections;
  FLOAT flReflectionsDelay;
  LONG  lReverb;
  FLOAT flReverbDelay;
  FLOAT flDiffusion;
  FLOAT flDensity;
  FLOAT flHFReference;
} DSFXI3DL2Reverb, *LPDSFXI3DL2Reverb;

typedef const DSFXI3DL2Reverb *LPCDSFXI3DL2Reverb;

Members

lRoom

Attenuation of the room effect, in millibels (mB), in the range from DSFX_I3DL2REVERB_ROOM_MIN to DSFX_I3DL2REVERB_ROOM_MAX. The default value is DSFX_I3DL2REVERB_ROOM_DEFAULT, or -1000 mB.

lRoomHF

Attenuation of the room high-frequency effect, in mB, in the range from DSFX_I3DL2REVERB_ROOMHF_MIN to DSFX_I3DL2REVERB_ROOMHF_MAX. The default value is DSFX_I3DL2REVERB_ROOMHF_DEFAULT, or -100 mB.

flRoomRolloffFactor

Rolloff factor for the reflected signals, in the range from DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN to DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX. The default value is DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT, or 0.0. The rolloff factor for the direct path is controlled by the DirectSound listener.

flDecayTime

Decay time, in seconds, in the range from DSFX_I3DL2REVERB_DECAYTIME_MIN to DSFX_I3DL2REVERB_DECAYTIME_MAX. The default value is DSFX_I3DL2REVERB_DECAYTIME_DEFAULT, or 1.49 second.

flDecayHFRatio

Ratio of the decay time at high frequencies to the decay time at low frequencies, in the range from DSFX_I3DL2REVERB_DECAYHFRATIO_MIN to DSFX_I3DL2REVERB_DECAYHFRATIO_MAX. The default value is DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT, or 0.83.

lReflections

Attenuation of early reflections relative to lRoom, in mB, in the range from DSFX_I3DL2REVERB_REFLECTIONS_MIN to DSFX_I3DL2REVERB_REFLECTIONS_MAX. The default value is DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT, or -2602 mB.

flReflectionsDelay

Delay time of the first reflection relative to the direct path, in seconds, in the range from DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN to DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT. The default value is 0.007 seconds.

lReverb

Attenuation of late reverberation relative to lRoom, in mB, in the range -from DSFX_I3DL2REVERB_REVERB_MIN to DSFX_I3DL2REVERB_REVERB_MAX. The default value is DSFX_I3DL2REVERB_REVERB_DEFAULT, or 200 mB.

flReverbDelay

Time limit between the early reflections and the late reverberation relative to the time of the first reflection, in seconds, in the range from DSFX_I3DL2REVERB_REVERBDELAY_MIN to DSFX_I3DL2REVERB_REVERBDELAY_MAX. The default value is DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT, or 0.011 seconds.

flDiffusion

Echo density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DIFFUSION_MIN to DSFX_I3DL2REVERB_DIFFUSION_MAX. The default value is DSFX_I3DL2REVERB_DIFFUSION_DEFAULT, or 100.0 percent.

flDensity

Modal density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DENSITY_MIN to DSFX_I3DL2REVERB_DENSITY_MAX. The default value is DSFX_I3DL2REVERB_DENSITY_DEFAULT, or 100.0 percent.

flHFReference

Reference high frequency, in hertz, in the range from DSFX_I3DL2REVERB_HFREFERENCE_MIN to DSFX_I3DL2REVERB_HFREFERENCE_MAX. The default value is DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT, or 5000.0 Hz.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface


DSFXChorus

The DSFXChorus structure contains parameters for a chorus effect.

Syntax

typedef struct _DSFXChorus {
  FLOAT   fWetDryMix;
  FLOAT   fDepth;
  FLOAT   fFeedback;
  FLOAT   fFrequency;
  LONG    lWaveform;
  FLOAT   fDelay;
  LONG    lPhase;
} DSFXChorus, *LPDSFXChorus;

typedef const DSFXChorus *LPCDSFXChorus;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXCHORUS_WETDRYMIX_MIN through DSFXCHORUS_WETDRYMIX_MAX (all wet). The default value is 50.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator, in hundredths of a percentage point. Must be in the range from DSFXCHORUS_DEPTH_MIN through DSFXCHORUS_DEPTH_MAX. The default value is 10.

fFeedback

Percentage of output signal to feed back into the effect's input, in the range from DSFXCHORUS_FEEDBACK_MIN to DSFXCHORUS_FEEDBACK_MAX. The default value is 25.

fFrequency

Frequency of the LFO, in the range from DSFXCHORUS_FREQUENCY_MIN to DSFXCHORUS_FREQUENCY_MAX. The default value is 1.1.

lWaveform

Waveform shape of the LFO. Defined values are DSFXCHORUS_WAVE_TRIANGLE and DSFXCHORUS_WAVE_SIN. By default, the waveform is a sine.

fDelay

Number of milliseconds the input is delayed before it is played back, in the range from DSFXCHORUS_DELAY_MIN to DSFXCHORUS_DELAY_MAX. The default value is 16 ms.

lPhase

Phase differential between left and right LFOs, in the range from DSFXCHORUS_PHASE_MIN through DSFXCHORUS_PHASE_MAX. Possible values are defined as follows.

Value
DSFXCHORUS_PHASE_NEG_180
DSFXCHORUS_PHASE_NEG_90
DSFXCHORUS_PHASE_ZERO
DSFXCHORUS_PHASE_90
DSFXCHORUS_PHASE_180

The default value is DSFXCHORUS_PHASE_90.

Requirements

Header: Declared in Dsound.h.

See Also

  • Chorus
  • IDirectSoundFXChorus8 Interface


DSFXCompressor

The DSFXCompressor structure contains parameters for a compression effect.

Syntax

typedef struct _DSFXCompressor {
  FLOAT  fGain;
  FLOAT  fAttack;
  FLOAT  fRelease;
  FLOAT  fThreshold;
  FLOAT  fRatio;
  FLOAT  fPredelay;
} DSFXCompressor, *LPDSFXCompressor;

typedef const DSFXCompressor *LPCDSFXCompressor;

Members

fGain

Output gain of signal after compression, in the range from DSFXCOMPRESSOR_GAIN_MIN to DSFXCOMPRESSOR_GAIN_MAX. The default value is 0 dB.

fAttack

Time before compression reaches its full value, in the range from DSFXCOMPRESSOR_ATTACK_MIN to DSFXCOMPRESSOR_ATTACK_MAX. The default value is 10 ms.

fRelease

Speed at which compression is stopped after input drops below fThreshold, in the range from DSFXCOMPRESSOR_RELEASE_MIN to DSFXCOMPRESSOR_RELEASE_MAX. The default value is 200 ms.

fThreshold

Point at which compression begins, in decibels, in the range from DSFXCOMPRESSOR_THRESHOLD_MIN to DSFXCOMPRESSOR_THRESHOLD_MAX. The default value is -20 dB.

fRatio

Compression ratio, in the range from DSFXCOMPRESSOR_RATIO_MIN to DSFXCOMPRESSOR_RATIO_MAX. The default value is 3, which means 3:1 compression.

fPredelay

Time after lThreshold is reached before attack phase is started, in milliseconds, in the range from DSFXCOMPRESSOR_PREDELAY_MIN to DSFXCOMPRESSOR_PREDELAY_MAX. The default value is 4 ms.

Requirements

Header: Declared in Dsound.h.

See Also

  • Compression
  • IDirectSoundFXCompressor8 Interface


DSFXDistortion

The DSFXDistortion structure contains parameters for a distortion effect.

Syntax

typedef struct _DSFXDistortion {
  FLOAT  fGain;
  FLOAT  fEdge;
  FLOAT  fPostEQCenterFrequency;
  FLOAT  fPostEQBandwidth;
  FLOAT  fPreLowpassCutoff;
} DSFXDistortion, *LPDSFXDistortion;

typedef const DSFXDistortion *LPCDSFXDistortion;

Members

fGain

Amount of signal change after distortion, in the range from DSFXDISTORTION_GAIN_MIN through DSFXDISTORTION_GAIN_MAX. The default value is -18 dB.

fEdge

Percentage of distortion intensity, in the range in the range from DSFXDISTORTION_EDGE_MIN through DSFXDISTORTION_EDGE_MAX. The default value is 15 percent.

fPostEQCenterFrequency

Center frequency of harmonic content addition, in the range from DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN through DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX. The default value is 2400 Hz.

fPostEQBandwidth

Width of frequency band that determines range of harmonic content addition, in the range from DSFXDISTORTION_POSTEQBANDWIDTH_MIN through DSFXDISTORTION_POSTEQBANDWIDTH_MAX. The default value is 2400 Hz.

fPreLowpassCutoff

Filter cutoff for high-frequency harmonics attenuation, in the range from DSFXDISTORTION_PRELOWPASSCUTOFF_MIN through DSFXDISTORTION_PRELOWPASSCUTOFF_MAX. The default value is 8000 Hz.

Remarks

The values in fPostEQBandwidth, fPostEQCenterFrequency, and fPreLowpassCutoff cannot exceed one-third of the frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXDistortion8::SetAllParameters.

Requirements

Header: Declared in Dsound.h.

See Also

  • Distortion
  • IDirectSoundFXDistortion8 Interface


DSFXEcho

The DSFXEcho structure contains parameters for an echo effect.

Syntax

typedef struct _DSFXEcho {
  FLOAT  fWetDryMix;
  FLOAT  fFeedback;
  FLOAT  fLeftDelay;
  FLOAT  fRightDelay;
  LONG   lPanDelay;
} DSFXEcho, *LPDSFXEcho;

typedef const DSFXEcho *LPCDSFXEcho;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXECHO_WETDRYMIX_MIN through DSFXECHO_WETDRYMIX_MAX (all wet). The default value is 50.

fFeedback

Percentage of output fed back into input, in the range from DSFXECHO_FEEDBACK_MIN through DSFXECHO_FEEDBACK_MAX. The default value is 50.

fLeftDelay

Delay for left channel, in milliseconds, in the range from DSFXECHO_LEFTDELAY_MIN through DSFXECHO_LEFTDELAY_MAX. The default value is 500 ms.

fRightDelay

Delay for right channel, in milliseconds, in the range from DSFXECHO_RIGHTDELAY_MIN through DSFXECHO_RIGHTDELAY_MAX. The default value is 500 ms.

lPanDelay

Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as DSFXECHO_PANDELAY_MIN (equivalent to FALSE) and DSFXECHO_PANDELAY_MAX (equivalent to TRUE).

Requirements

Header: Declared in Dsound.h.

See Also

  • Echo
  • IDirectSoundFXEcho8 Interface


DSFXFlanger

The DSFXFlanger structure contains parameters for a flange effect.

Syntax

typedef struct _DSFXFlanger {
  FLOAT  fWetDryMix;
  FLOAT  fDepth;
  FLOAT  fFeedback;
  FLOAT  fFrequency;
  LONG   lWaveform;
  FLOAT  fDelay;
  LONG   lPhase;
} DSFXFlanger, *LPDSFXFlanger;

typedef const DSFXFlanger *LPCDSFXFlanger;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXFLANGER_WETDRYMIX_MIN through DSFXFLANGER_WETDRYMIX_MAX (all wet). The default value is 50.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator (LFO), in hundredths of a percentage point. Must be in the range from DSFXFLANGER_DEPTH_MIN through DSFXFLANGER_DEPTH_MAX. The default value is 100.

fFeedback

Percentage of output signal to feed back into the effect's input, in the range from DSFXFLANGER_FEEDBACK_MIN to DSFXFLANGER_FEEDBACK_MAX. The default value is -50.

fFrequency

Frequency of the LFO, in the range from DSFXFLANGER_FREQUENCY_MIN to DSFXFLANGER_FREQUENCY_MAX. The default value is 0.25.

lWaveform

Waveform shape of the LFO. By default, the waveform is a sine. Possible values are defined in the following table.

Value | Description
DSFXFLANGER_WAVE_TRIANGLE | Triangle.
DSFXFLANGER_WAVE_SIN | Sine.

fDelay

Number of milliseconds the input is delayed before it is played back, in the range from DSFXFLANGER_DELAY_MIN to DSFXFLANGER_DELAY_MAX. The default value is 2 ms.

lPhase

Phase differential between left and right LFOs, in the range from DSFXFLANGER_PHASE_MIN through DSFXFLANGER_PHASE_MAX. Possible values are defined in the following table.

Value
DSFXFLANGER_PHASE_NEG_180
DSFXFLANGER_PHASE_NEG_90
DSFXFLANGER_PHASE_ZERO
DSFXFLANGER_PHASE_90
DSFXFLANGER_PHASE_180

The default value is DSFXFLANGER_PHASE_ZERO.

Requirements

Header: Declared in Dsound.h.

See Also

  • Flange
  • IDirectSoundFXFlanger8 Interface


DSFXGargle

The DSFXGargle structure contains parameters for an amplitude modulation effect.

Syntax

typedef struct _DSFXGargle {
  DWORD  dwRateHz;
  DWORD  dwWaveShape;
} DSFXGargle, *LPDSFXGargle;

typedef const DSFXGargle *LPCDSFXGargle;

Members

dwRateHz

Rate of modulation, in Hertz. Must be in the range from DSFXGARGLE_RATEHZ_MIN through DSFXGARGLE_RATEHZ_MAX. The default value is 20.

dwWaveShape

Shape of the modulation waveform. The following values are defined.

Value | Description
DSFXGARGLE_WAVE_TRIANGLE | Triangular waveform.
DSFXGARGLE_WAVE_SQUARE | Square waveform.

The default value is DSFXGARGLE_WAVE_TRIANGLE.

Requirements

Header: Declared in Dsound.h.

See Also

  • Gargle
  • IDirectSoundFXGargle8 Interface


DSFXParamEq

The DSFXParamEq structure contains parameters for a parametric equalizer effect.

Syntax

typedef struct _DSFXParamEq {
  FLOAT  fCenter;
  FLOAT  fBandwidth;
  FLOAT  fGain;
} DSFXParamEq, *LPDSFXParamEq;

Members

fCenter

Center frequency, in hertz, in the range from DSFXPARAMEQ_CENTER_MIN to DSFXPARAMEQ_CENTER_MAX. This value cannot exceed one-third of the frequency of the buffer. The default value is 8000.

fBandwidth

Bandwidth, in semitones, in the range from DSFXPARAMEQ_BANDWIDTH_MIN to DSFXPARAMEQ_BANDWIDTH_MAX. The default value is 12.

fGain

Gain, in the range from DSFXPARAMEQ_GAIN_MIN to DSFXPARAMEQ_GAIN_MAX. The default value is 0.

Remarks

The value in fCenter cannot exceed one-third of the frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXParamEq8::SetAllParameters.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSoundFXParamEq8 Interface
  • Parametric Equalizer


DSFXWavesReverb

The DSFXWavesReverb structure contains parameters for a Waves reverberation effect.

Syntax

typedef struct _DSFXWavesReverb {
  FLOAT  fInGain;
  FLOAT  fReverbMix;
  FLOAT  fReverbTime;
  FLOAT  fHighFreqRTRatio;
} DSFXWavesReverb, *LPDSFXWavesReverb;

typedef const DSFXWavesReverb *LPCDSFXWavesReverb;

Members

fInGain

Input gain of signal, in decibels (dB), in the range from DSFX_WAVESREVERB_INGAIN_MIN through DSFX_WAVESREVERB_INGAIN_MAX. The default value is DSFX_WAVESREVERB_INGAIN_DEFAULT, or 0 dB.

fReverbMix

Reverb mix, in dB, in the range from DSFX_WAVESREVERB_REVERBMIX_MIN through DSFX_WAVESREVERB_REVERBMIX_MAX. The default value is DSFX_WAVESREVERB_REVERBMIX_DEFAULT, or 0 dB.

fReverbTime

Reverb time, in milliseconds, in the range from DSFX_WAVESREVERB_REVERBTIME_MIN through DSFX_WAVESREVERB_REVERBTIME_MAX. The default value is DSFX_WAVESREVERB_REVERBTIME_DEFAULT, or 1000.

fHighFreqRTRatio

High-frequency reverb time ratio, in the range from DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN through DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX. The default value is DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT, or 0.001.

Requirements

Header: Declared in Dsound.h.

See Also

  • IDirectSoundFXWavesReverb8 Interface


WAVEFORMATEX

The WAVEFORMATEX structure defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

This structure is part of the Platform SDK and is not declared in Dsound.h. It is documented here for convenience.

Syntax

typedef struct {
  WORD  wFormatTag;
  WORD  nChannels;
  DWORD nSamplesPerSec;
  DWORD nAvgBytesPerSec;
  WORD  nBlockAlign;
  WORD  wBitsPerSample;
  WORD  cbSize;
} WAVEFORMATEX;

Members

wFormatTag

Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the Mmreg.h header file. For one- or two-channel PCM data, this value should be WAVE_FORMAT_PCM.

nChannels

Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.

nSamplesPerSec

Sample rate, in samples per second (hertz). If wFormatTag is WAVE_FORMAT_PCM, then common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nAvgBytesPerSec

Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nBlockAlign

Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE, nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Software must process a multiple of nBlockAlign bytes of data at a time. Data written to and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample

Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. If wFormatTag is WAVE_FORMAT_EXTENSIBLE, this value can be any integer multiple of 8. Some compression schemes cannot define a value for wBitsPerSample, so this member can be zero.

cbSize

Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats (and only WAVE_FORMAT_PCM formats), this member is ignored.

Requirements

Header: Declared in Mmreg.h.

See Also

  • WAVEFORMATEXTENSIBLE


WAVEFORMATEXTENSIBLE

The WAVEFORMATEXTENSIBLE structure defines the format of waveform-audio data for formats having more than two channels.

This structure is part of the Platform SDK and is declared in Mmreg.h. It is documented here for convenience.

Syntax

typedef struct {
  WAVEFORMATEX  Format;
  union {
    WORD  wValidBitsPerSample;
    WORD  wSamplesPerBlock;
    WORD  wReserved;
  } Samples;
  DWORD   dwChannelMask;
  GUID    SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;

Members

Format

WAVEFORMATEX structure that specifies the basic format. The wFormatTag member must be WAVE_FORMAT_EXTENSIBLE, defined in Mmreg.h. The cbSize member must be at least 22.

wValidBitsPerSample

Number of bits of precision in the signal. Usually equal to WAVEFORMATEX.wBitsPerSample.

wSamplesPerBlock

Number of samples contained in one compressed block of audio data. This value is used in buffer estimation. This value is used with compressed formats that have a fixed number of samples within each block. This value can be set to zero if a variable number of samples is contained in each block of compressed audio data. In this case, buffer estimation and position information needs to be obtained in other ways.

wReserved

Reserved for internal use by operating system. Set to zero.

dwChannelMask

Bitmask specifying the assignment of channels in the stream to speaker positions. See Remarks.

SubFormat

Subformat of the data, such as KSDATAFORMAT_SUBTYPE_PCM. The subformat information is similar to that provided by the tag in the WAVEFORMATEX structure's wFormatTag member.

Remarks

The dwChannelMask member specifies which channels are present in the multichannel stream. The least significant bit corresponds with the front left speaker, the next least significant bit corresponds to the front right speaker, and so on. The bits, in order of significance, are defined in Ksmedia.h and Mmreg.h as follows:

Speaker position | Flag bit
SPEAKER_FRONT_LEFT | 0x1
SPEAKER_FRONT_RIGHT | 0x2
SPEAKER_FRONT_CENTER | 0x4
SPEAKER_LOW_FREQUENCY | 0x8
SPEAKER_BACK_LEFT | 0x10
SPEAKER_BACK_RIGHT | 0x20
SPEAKER_FRONT_LEFT_OF_CENTER | 0x40
SPEAKER_FRONT_RIGHT_OF_CENTER | 0x80
SPEAKER_BACK_CENTER | 0x100
SPEAKER_SIDE_LEFT | 0x200
SPEAKER_SIDE_RIGHT | 0x400
SPEAKER_TOP_CENTER | 0x800
SPEAKER_TOP_FRONT_LEFT | 0x1000
SPEAKER_TOP_FRONT_CENTER | 0x2000
SPEAKER_TOP_FRONT_RIGHT | 0x4000
SPEAKER_TOP_BACK_LEFT | 0x8000
SPEAKER_TOP_BACK_CENTER | 0x10000
SPEAKER_TOP_BACK_RIGHT | 0x20000

For more information on this structure, see the document Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.

Requirements

Header: Declared in Mmreg.h, Ksproxy.h.

See Also

  • Multichannel WAV Formats


DirectSound GUIDs

This section lists globally unique identifiers used in DirectSound. The following topics are covered:

  • DirectSound Interface GUIDs
  • DirectSound Component GUIDs
  • DirectSound Device GUIDs
  • DirectSound Effect GUIDs


DirectSound Interface GUIDs

The following GUIDs are used as interface identifiers (IIDs) to obtain DirectSound interfaces.

IID | Interface
IID_IDirectSound3DBuffer8 | IDirectSound3DBuffer8
IID_IDirectSound3DListener8 | IDirectSound3DListener8
IID_IDirectSound8 | IDirectSound8
IID_IDirectSoundBuffer8 | IDirectSoundBuffer8
IID_IDirectSoundCapture8 | IDirectSoundCapture8
IID_IDirectSoundCaptureBuffer8 | IDirectSoundCaptureBuffer8
IID_IDirectSoundCaptureFXAec8 | IDirectSoundCaptureFXAec8
IID_IDirectSoundCaptureFXNoiseSuppress8 | IDirectSoundCaptureFXNoiseSuppress8
IID_IDirectSoundFullDuplex8 | IDirectSoundFullDuplex8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundNotify8 | IDirectSoundNotify8
IID_IKsPropertySet | IKsPropertySet
IID_IReferenceClock | IReferenceClock

Note Where an interface has not changed from previous versions of DirectX, the IID in the table is defined in Dsound.h as the original IID. For example, IID_IDirectSound3DBuffer8 is defined as IID_IDirectSound3DBuffer, because IDirectSoundBuffer8 is the same as IDirectSoundBuffer.


DirectSound Component GUIDs

The following GUIDS are used as class identifiers (CLSIDs) in the creation of DirectSound components.

CLSID | Component
CLSID_DirectSound | DirectSound playback device
CLSID_DirectSound8 | DirectSound8 playback device
CLSID_DirectSoundCapture | DirectSoundCapture device
CLSID_DirectSoundCapture8 | DirectSoundCapture8 device
CLSID_DirectSoundFullDuplex | Full duplex device

Note For information about the differences between the older and newer versions of playback and capture device components, see IDirectSound8 Interface and IDirectSoundCapture8::CreateCaptureBuffer.


DirectSound Device GUIDs

The following GUIDs are used to identify default playback and capture devices.

Device ID | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

See Also

  • Creating the Device Object
  • Creating the Capture Device Object
  • DirectSoundCaptureCreate8
  • DirectSoundCreate8
  • DirectSoundFullDuplexCreate8
  • GetDeviceID
  • IDirectSoundFullDuplex8::Initialize


DirectSound Effect GUIDs

The following GUIDs are used to identify capture and playback effects.

GUID | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation capture effect
GUID_DSCFX_CLASS_NS | Noise suppression capture effect
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation capture effect
GUID_DSCFX_MS_NS | Microsoft noise suppression capture effect
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation capture effect
GUID_DSCFX_SYSTEM_NS | System default noise suppression capture effect
GUID_DSFX_STANDARD_CHORUS | Chorus effect
GUID_DSFX_STANDARD_COMPRESSOR | Compressor effect
GUID_DSFX_STANDARD_DISTORTION | Distortion effect
GUID_DSFX_STANDARD_ECHO | Echo effect
GUID_DSFX_STANDARD_FLANGER | Flanger effect
GUID_DSFX_STANDARD_GARGLE | Gargle effect
GUID_DSFX_STANDARD_I3DL2REVERB | Environmental reverberation effect
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer effect
GUID_DSFX_WAVES_REVERB | Waves reverberation effect

See Also

  • IDirectSoundBuffer8::GetObjectInPath
  • DSCEFFECTDESC
  • DSEFFECTDESC


DirectSound Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectSound methods. For a partial list of the specific codes that each method can return, see the individual method descriptions.

Note The lists of error codes in method descriptions are not necessarily comprehensive. Applications should always check for method failure and not just for specific codes. For example, most methods can return DSERR_NODRIVER if the driver is removed while the application is running, or DSERR_OUTOFMEMORY if no more memory is available for operations.

Error codes are presented in the following sections:

  • DirectSound Return Values by Number
  • DirectSound Return Values by Name


DirectSound Return Values by Number

The following table lists DirectSound return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | DS_OK
0x00000007 | DSERR_OUTOFMEMORY
0x000001AE | DSERR_NOINTERFACE
0x0878000A | DS_NO_VIRTUALIZATION
0x08780014 | DS_INCOMPLETE
0x80004001 | DSERR_UNSUPPORTED
0x80004005 | DSERR_GENERIC
0x80070005 | DSERR_ACCESSDENIED
0x80070057 | DSERR_INVALIDPARAM
0x8878000A | DSERR_ALLOCATED
0x8878001E | DSERR_CONTROLUNAVAIL
0x88780032 | DSERR_INVALIDCALL
0x88780046 | DSERR_PRIOLEVELNEEDED
0x88780064 | DSERR_BADFORMAT
0x88780078 | DSERR_NODRIVER
0x88780082 | DSERR_ALREADYINITIALIZED
0x88780096 | DSERR_BUFFERLOST
0x887800A0 | DSERR_OTHERAPPHASPRIO
0x887800AA | DSERR_UNINITIALIZED
0x887810B4 | DSERR_BUFFERTOOSMALL
0x887810BE | DSERR_DS8_REQUIRED
0x887810C8 | DSERR_SENDLOOP
0x887810D2 | DSERR_BADSENDBUFFERGUID
0x887810DC | DSERR_FXUNAVAILABLE
0x88781161 | DSERR_OBJECTNOTFOUND


DirectSound Return Values by Name

The following list describes all DirectSound return values. To find a constant from its value, see DirectSound Return Values by Number.

DS_OK

The method succeeded.

DS_NO_VIRTUALIZATION

The buffer was created, but another 3-D algorithm was substituted.

DS_INCOMPLETE

The method succeeded, but not all the optional effects were obtained.

DSERR_ACCESSDENIED

The request failed because access was denied.

DSERR_ALLOCATED

The request failed because resources, such as a priority level, were already in use by another caller.

DSERR_ALREADYINITIALIZED

The object is already initialized.

DSERR_BADFORMAT

The specified wave format is not supported.

DSERR_BADSENDBUFFERGUID

The GUID specified in an audiopath file does not match a valid mix-in buffer.

DSERR_BUFFERLOST

The buffer memory has been lost and must be restored.

DSERR_BUFFERTOOSMALL

The buffer size is not great enough to enable effects processing.

DSERR_CONTROLUNAVAIL

The buffer control (volume, pan, and so on) requested by the caller is not available. Controls must be specified when the buffer is created, using the dwFlags member of DSBUFFERDESC.

DSERR_DS8_REQUIRED

A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface.

DSERR_FXUNAVAILABLE

The effects requested could not be found on the system, or they are in the wrong order or in the wrong location; for example, an effect expected in hardware was found in software.

DSERR_GENERIC

An undetermined error occurred inside the DirectSound subsystem.

DSERR_INVALIDCALL

This function is not valid for the current state of this object.

DSERR_INVALIDPARAM

An invalid parameter was passed to the returning function.

DSERR_NOAGGREGATION

The object does not support aggregation.

DSERR_NODRIVER

No sound driver is available for use, or the given GUID is not a valid DirectSound device ID.

DSERR_NOINTERFACE

The requested COM interface is not available.

DSERR_OBJECTNOTFOUND

The requested object was not found.

DSERR_OTHERAPPHASPRIO

Another application has a higher priority level, preventing this call from succeeding.

DSERR_OUTOFMEMORY

The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.

DSERR_PRIOLEVELNEEDED

A cooperative level of DSSCL_PRIORITY or higher is required.

DSERR_SENDLOOP

A circular loop of send effects was detected.

DSERR_UNINITIALIZED

The IDirectSound8::Initialize method has not been called or has not been called successfully before other methods were called.

DSERR_UNSUPPORTED

The function called is not supported at this time.


DirectShow

The Microsoft® DirectShow® application programming interface is a media-streaming architecture for the Microsoft Windows® platform. Using DirectShow, your applications can perform high-quality video and audio playback or capture.

The DirectShow documentation is divided into the following sections:

  • Introduction to DirectShow
  • Getting Started
  • About DirectShow
  • Using DirectShow
  • DirectShow Tutorials
  • DirectShow Samples
  • DirectShow Reference
  • Microsoft TV Technologies C++ Reference
  • Microsoft TV Technologies Visual Basic and Script Reference
  • DirectShow Editing Services C++ Reference
  • DirectShow Editing Services Visual Basic Reference
  • Stream Buffer Engine Reference
  • Appendixes


Introduction to DirectShow

Microsoft® DirectShow® is an architecture for streaming media on the Microsoft Windows® platform. DirectShow provides for high-quality capture and playback of multimedia streams. It supports a wide variety of formats, including Advanced Systems Format (ASF), Motion Picture Experts Group (MPEG), Audio-Video Interleaved (AVI), MPEG Audio Layer-3 (MP3), and WAV sound files. It supports capture using Windows Driver Model (WDM) devices or older Video for Windows devices. DirectShow is integrated with other DirectX technologies. It automatically detects and uses video and audio acceleration hardware when available, but also supports systems without acceleration hardware.

DirectShow simplifies media playback, format conversion, and capture tasks. At the same time, it provides access to the underlying stream control architecture for applications that require custom solutions. You can also create your own DirectShow components to support new formats or custom effects.

Examples of the types of applications you can write with DirectShow include DVD players, video editing applications, AVI to ASF converters, MP3 players, and digital video capture applications.

DirectShow is based on the Component Object Model (COM). To write a DirectShow application, you must understand COM client programming. For most applications, you do not need to implement your own COM objects. DirectShow provides the components you need. (If you want to extend DirectShow by writing your own components, however, you must implement them as COM objects.)

This section contains the following topics:

  • What's New in DirectShow?
  • Supported Formats in DirectShow
  • DirectShow FAQ


What's New in DirectShow?

This section describes DirectShow features that are new in Microsoft® Windows® XP Service Pack 1 and in DirectX 9.0. To see what was new for DirectShow in DirectX 8.1 and other releases, see Previous DirectShow What's New Sections. Windows XP Service Pack 1 contains the DirectX 8.1 runtime libraries, plus the libraries that support the XP-only functionality described in What's New for Windows XP Service Pack 1. To use the DirectX 9.0 libraries on Windows XP Service Pack 1, for example to use the new Video Mixing Renderer-9, you must manually install DirectX 9.0.

  • What's New for DirectX 9.0
  • What's New for Windows XP Service Pack 1


What's New for DirectX 9.0

  • Video Mixing Renderer Filter 9 (VMR-9). This new, redistributable rendering filter is similar in concept and design to the VMR that is available for Microsoft Windows XP. The VMR-9 is more powerful than the original VMR (now called "VMR-7") because it is fully compatible with the DirectX 9.0 graphics capabilities and it offers improved support for deinterlacing and ProcAmp control (brightness, contrast, hue, and saturation).
  • MPEG-2 Sections and Tables Filter. This new filter enables an application to get PSI tables from an MPEG-2 transport stream.
  • Microsoft TV Technologies now supports DVB-T (terrestrial) and DVB-C (cable), in addition to DVB-S (satelite). For more information, see BDA Network Provider Filter.
  • New deinterlacing support in DirectX Video Acceleration.
  • New deinterlacing support in the DV Video Decoder filter. The DV Decoder filter now supports interlaced output, as well as deinterlaced output. This feature enables the VMR to perform the deinterlacing, for improved rendering quality. This feature does not involve any changes to the DirectShow APIs.
  • New Encoder API Specification. The Encoder API defines a standard, format-neutral way in which software or hardware encoders can communicate with applications and device drivers. For more information, see Encoder API.
  • IGetCapabilitiesKey is a new interface that filters can implement in order to enable applications to query for the filter's capabilities.
  • DirectShow Editing Services (DES) now supports plug-in video resizing filters. For more information, see Providing a Custom Video Resizer.
  • The DVD Graph Builder enables applications to use the VMR-9 through the IDvdGraphBuilder::RenderDvdVideoVolume method. The DVD Navigator now supports playback of audio during fast forward; users can now watch a movie at speeds higher than 1x without raising the pitch of the audio track, on decoders that support this feature.
  • The AmCap sample application now supports MPEG-2 program stream input, for example from analog TV Tuners that stream MPEG-2 content. A third-party DirectShow-compatible MPEG-2 decoder is still required to decode the streams.
  • Enhancements to the GraphEdit utility.
  • A new utility program called Profile Enumerator that displays information about Windows Media® system profiles installed on your machine. This program is located in [SDK root]\bin\DXUtils.
  • AVStream driver development and run-time support on all platforms prior to Windows XP has been improved for close functional parity with Windows XP. A few AVStream and core Kernel Streaming behavioral differences still exist that will be documented fully in the next release. Please contact Microsoft through the DirectX beta site to request a preliminary version of these differences.
  • The Analog TV Tuner filter now supports adding new channel frequencies, via the registry. This feature extends the existing mechanism for adding channel frequency overrides. For more information, see International Analog TV Tuning.
  • New samples. Several new samples are included with the SDK:
    • AudioBox. Audio-only media player, similar to the Jukebox sample.
    • CompressView. This sample demonstrates how to recompress an audio or video file using a different compression type.
    • CaptureTex9 Captures live video onto a Direct3D 9 texture surface (a waving flag).
    • DSNetwork Filters Sample. These sample filters send and receive multicast MPEG-2 transport streams.
    • GrabBitmaps. This sample shows how to grab bitmaps from a video stream.
    • Metronome Filter Sample. This sample filter shows how to implement a reference clock. The filter uses the microphone input to listen for audio spikes (such as clicks, hand claps, or coughs), which it uses to determine a clock rate. Clap faster or slower, and the playback rate of the video changes accordingly.
    • PlayDVD . A new DVD player sample.
    • PSI Parser Filter Sample. This sample filter shows how to retrieve program information from an MPEG-2 transport stream.
    • Push Source Filters Sample This sample consists of three source filters that demonstrate various ways to introduce in-memory video data into a filter graph.
    • RenderLog. This sample creates a text log of DirectShow's progress while rendering a media file. If you receive an error when you call IGraphBuilder::RenderFile, you can use this tool to create and view the render log.
    • RGB Filters Sample. This sample includes several filters that are useful for testing.
    • Texture3D9 Draws video on a Microsoft DirectX 9.0 texture surface. This sample builds on the Direct3D Tutorial05 sample, adding support for rendering video onto a Direct3D9 surface.
    • TransViewer. This sample enables you to preview all of the DirectShow Editing Services transitions installed on your system.

    The following new samples demonstrate various features of the VMR-7. These samples are located in the [sdkroot]\DXSDK\Samples\C++\DirectShow\VMR folder.

    • Blender. Demonstrates how to mix and blend multiple video streams.
    • MonitorInfo. Displays information about the monitors available on the user's system.
    • Pip. Demonstrates how to create picture-in-picture effects using the VMR.
    • Text. Displays alpha-blended text over the video.
    • Ticker. Extends the Text sample. This sample draws horizontally scrolling text across the bottom of the video.
    • VMRMulti. Plays multiple video files over a Direct3D background.
    • VMRXclBasic. Shows how to play video in exclusive mode.
    • Watermark. Places an alpha-blended bitmap over the video.
    • Windowless. Demonstrates basic playback using the VMR.

    The following new samples demonstrate various features of the VMR-9. These samples are located in the [sdkroot]\DXSDK\Samples\C++\DirectShow\VMR9 folder.

    • BitmapMix an interactive video player that uses the Windowless mode of the VMR-9 to blend an animated alpha-blended bitmap with a running video onto a Direct3D surface.
    • Blender Demonstrates how to mix and blend multiple video streams.
    • MonitorInfo Displays information about the monitors available on the user's system.
    • MultiVMR9 This 3-sample set demonstrates how to use a custom VMR-9 allocator-presenter in a multi-graph environment.
    • Pip Demonstrates how to create picture-in-picture effects using the VMR.
    • Text Displays alpha-blended text over the video.
    • Ticker Extends the Text sample. This sample draws horizontally scrolling text across the bottom of the video.
    • VMR9Allocator Implements a custom allocator-presenter for the VMR-9.
    • VMRPlayer Uses Windowless mode of the VMR-9 to blend one or two running videos and a static image.
    • Watermark Places an alpha-blended bitmap over the video.
    • Windowless Demonstrates basic playback using the VMR.
  • Removed Samples:
    • JukeboxASF has been removed, and Windows Media™ support has been added to the Jukebox sample.
  • Managed code for audio and video file playback. The Microsoft.DirectX.AudioVideoPlayback managed code namespace provides playback and simple control of audio and video media. For more information, refer to the DirectX documentation for the managed DirectX components.


What's New for Windows XP Service Pack 1

New Stream Buffer Engine Components: In Windows XP, Service Pack 1, the stream buffer engine filters and helper objects have been added. These are special DirectShow filters and helper objects that enable video applications to seek, pause, and record streamed video without interrupting the stream. The Video Control is also updated for Service Pack 1 to support the stream buffer engine. For more information, see Using the Stream Buffer Engine.

New TV Ratings Components: The new Extended Data Services (XDS) components can be used in conjunction with the content security components and stream buffer engine to supply TV ratings data for parental control and channel blocking application features. For more information, see TV Ratings Components.

New Stream Buffer Content Security Components: The new encryption and decryption filters can be used to protect content acquired through the stream buffer engine. For more information, see TV Ratings Components.

New Video Control Features: The Video Control now supports full DVD navigation and file playback, as well as the new functionality provided by the stream buffer engine, content security components, and TV ratings components. For more information, see Using the Video Control.


Supported Formats in DirectShow

DirectShow is an open architecture, which means that it can support any format as long as there are filters to parse and decode it. The filters provided by Microsoft, either as redistributables through DirectShow or as Windows operating system components, provide default support for the following file and compression formats.

Note An asterisk (*) indicates that DirectShow applications must use the Windows Media™ Format SDK to support this format. For more information, see the Audio and Video section of the MSDN Library.

File types:

  • Windows Media™ Audio (WMA)*
  • Windows Media™ Video (WMV)*
  • Advanced Systems Format (ASF)*
  • Motion Picture Experts Group (MPEG)
  • Audio-Video Interleaved (AVI)
  • QuickTime (version 2 and lower)
  • WAV
  • AIFF
  • AU
  • SND
  • MIDI

Compression formats:

  • Windows Media Video*
  • ISO MPEG-4 video version 1.0*
  • Microsoft MPEG-4 version 3*
  • Sipro Labs ACELP*
  • Windows Media Audio*
  • MPEG Audio Layer-3 (MP3) (decompression only)
  • Digital Video (DV)
  • MPEG-1
  • MJPEG
  • Cinepak

Microsoft does not provide an MPEG-2 decoder. Several DirectShow-compatible hardware and software MPEG-2 decoders are available from third parties.

For information on the availability of particular third-party codecs for redistribution with DirectShow applications, contact the codec manufacturer.


DirectShow FAQ

This article answers many frequently asked questions about Microsoft® DirectShow®. It contains the following sections:

  • General Questions
  • Programming Questions

General Questions

What operating systems does DirectShow support?

DirectShow supports Microsoft® Windows® 9x, Microsoft® Windows® 2000, Microsoft® Windows® Me, and Microsoft® Windows® XP.

How much COM knowledge do I need to program with DirectShow?

For application development, you need to understand the basics of working with COM objects: how to instantiate them, access the interfaces they expose, and manage reference counts on those interfaces. Filter development requires more COM knowledge.

What formats does DirectShow support?

See Supported Formats in DirectShow.

Is there a DirectShow Hardware Compatibility List (HCL)?

No. DirectShow uses Microsoft® DirectDraw® and Microsoft® DirectSound® hardware capabilities if they are available. When no special hardware is available, DirectShow uses GDI to draw video and the waveOut* multimedia APIs to play audio.

What languages can I use to write a DirectShow application?

DirectShow is designed primarily for C++ development. (You can also use C.) With Microsoft® Visual Basic®, you can access a only a small subset of the DirectShow API. DirectShow supports script-based DVD applications, using Microsoft® JScript® or Visual Basic Scripting Edition. It is also possible to write DirectShow applications using Borland Delphi; however, the SDK documentation does not address this topic.

For more information, see the following topics:

  • Controlling Filter Graphs Using C
  • Using DirectShow with Visual Basic
  • Writing a Script-Based DVD Application

What compiler do I need for DirectShow development?

Any compiler capable of generating Component Object Model (COM) objects should work once the compiler's environment has been configured correctly.

How does DirectShow relate to Microsoft® Windows Media™?

See Windows Media Applications.

How does DirectShow relate to the other components in Microsoft® DirectX®?

Internally, DirectShow uses DirectSound and DirectDraw when the hardware supports it. The Video Renderer and Overlay Mixer filters use DirectDraw 3 and DirectDraw 5 surfaces. The Video Mixing Renderer 7 (Windows XP only) uses DirectDraw 7 surfaces. The Video Mixing Renderer 9 uses the latest Microsoft® Direct3D® APIs. You do not need to use the other DirectX APIs to write a DirectShow application, although it is possible to combine them. For an example, see the Texture3D Sample.

How does DirectShow relate to Microsoft® ActiveMovie®?

ActiveMovie was the original name for DirectShow. The term ActiveMovie is no longer used but some API names still retain the initials "AM", for example AM_MEDIA_TYPE and IAMVideoAccelerator.

Is DirectShow limited to multimedia applications?

The default components included with DirectShow are primarily designed for streaming audio and video data. However, the DirectShow architecture has been successfully used for many kinds of data-streaming solutions.

Is the source code to the GraphEdit utility available? Can GraphEdit be redistributed?

No, the source is not available, and Graphedt.exe is not redistributable.

Do DMOs replace DirectShow filters?

Microsoft® DirectX® Media Objects (DMOs) can be used in a DirectShow application. For encoders, decoders, and effects, you are encouraged to write a DMO instead of a DirectShow filter. For other purposes, a DirectShow filter might be more appropriate. For more information about DMOs, see the "DirectX Media Objects" node in the DirectX SDK documentation.

Where can I get more information about DirectShow?

  • World Wide Web: MSDN DirectX Developer Center.
  • Mailing list: http://discuss.microsoft.com/archives/DIRECTXAV.htm. A portion of its charter is below:

    The primary function of this list is to provide a forum where Developers and content creators using Microsoft's audio and streaming video technologies (DirectSound, DirectMusic, DirectShow) can exchange information and ideas. The list caters to all levels of DirectX expertise, from novice to advanced developer.

While it is expected that various members of the Microsoft DirectX development team will review and possibly comment on list topics, DirectXAV is not intended as a Microsoft support forum and there is no guarantee that Microsoft personnel will respond directly to inquiries. Often, your best source of help will be other members of the DirectXAV community who have faced similar issues themselves in the past.

Topics that are appropriate to this list include: compositional techniques using DirectMusic Producer; audio, music or streaming video programming techniques; sound design techniques; general issues or information about the relevant APIs; code snippets; suggestions; hints and tips; device driver quality; future feature requests; real-life experiences using the APIs, and so on.

To subscribe to DirectX DEV, send an e-mail to LISTSERV@discuss.microsoft.com with a message body of subscribe directxdev. To subscribe to DirectX A/V, send an e-mail to LISTSERV@discuss.microsoft.com with a message body of subscribe directxav.

  • UseNet: microsoft.public.win32.programming.directx.video

I'm facing a difficult problem in developing my application/filter. Where can I get developer support?

You should contact DirectX SDK support for specific developer support issues:

  • For DirectX SDK support call (800) 936-5800. If you are an MSDN subscriber you can use an MSDN support incident (4 free with an MSDN subscription or free if you have a premier or priority contract with Microsoft). Otherwise there is a fee for this service. See The MSDN Online Support Home Page for more information.
  • You can have the charge made to a phone bill by calling 900-555-2300. You can also submit the question via the Web at http://support.microsoft.com/support/webresponse.asp.

Is there a book that explains DirectShow?

Currently, there is only one book devoted entirely to DirectShow:

  • Programming Microsoft DirectShow by Michael Linetsky (Wordware Publishing Inc.)

DirectShow is discussed briefly in some existing DirectX books, including:

  • Sams Teach Yourself DirectX in 24 Hours by Robert Dunlop, Dale Shepherd, and Mark Martin (Sams)
  • DirectX, RDX, RSX, and MMX Technology by Rohan Coelho and Maher Hawash (Addison Wesley)

The July 2002 issue of MSDN Magazine contains a good introductory article about DirectShow and describes how to write a simply video effects filter.

I have some ideas on how Microsoft could improve DirectShow.

Microsoft welcomes suggestions, questions, and comments. Let us know what you think. What are we missing? What areas would you most like to see improved? What types of tutorials and samples would you most like to see? Your input will help us to prioritize future work. If you have questions or suggestions pertaining to the new DirectShow documentation, please send a message to askdshow@microsoft.com.

I'm playing an AVI format file with Windows Media Player. I can hear the audio, but there doesn't seem to be any video—instead, I just see black. What's wrong?

Probably the file was encoded with a codec that is not present on your system. Although the AVI file format is common, AVI files can be created with many different codecs (coder/decoder). If you try to play an AVI file that uses an unsupported codec, you might hear the audio component, but the video will display as a black screen or the screen contents will remain unchanged.

Note The Windows Media Player often attempts to download and install a codec if it is not present on your system.

How do I know what codec a media file is using?

Do the following:

  • Right-click the file in Explorer
  • Click Properties.
  • Click the Summary tab.

Programming Questions

How do I build my application? What libraries and header files do I need?

See Setting Up the Build Environment.

GraphEdit displays a lot of filters that aren't documented. What are these filters?

GraphEdit enumerates all of the filters that are registered on your system in a filter category. This might include filters installed by third-party applications, or installed by other Microsoft technologies, such as Windows Media or NetMeeting. Also, some DirectShow filters act as wrappers for codecs or hardware devices, with each codec or device appearing as a distinct filter. The Microsoft H.263 Video Codec is used by NetMeeting and is no longer supported in DirectShow. For more information, see Enumerating Devices and Filters.

I'm having trouble building my custom graph programmatically.

First try building the filter graph with GraphEdit. This tool enables you to simulate lots of possibilities quickly. GraphEdit is always a great place to test out the graph before attempting to build it with source code.

For more information about graph building, see the following articles:

  • Building the Filter Graph
  • Enumerating Objects in a Filter Graph

How can I detect whether DirectShow is installed on a given machine?

Call CoCreateInstance to create an instance of the Filter Graph Manager. If this call succeeds, DirectShow is installed on the machine. The following code shows how to do this:

IGraphBuilder *pGraph;

HRESULT hr = CoCreateInstance(CLSID_FilterGraph,
    NULL, CLSCTX_INPROC_SERVER,
    IID_IGraphBuilder, (void **) &pGraph);

How do I change a filter's settings without displaying the property page?

Most filters expose one or more interfaces for setting properties on the filter. Consult the reference page for the filter in question. (See DirectShow Filters.)

Why can't I use the ASF Writer and ASF Reader filters?

Prior to DirectX 9.0, it was necessary to provide a unique software certificate in order to use these filters in an application. Also, they were not available in GraphEdit. The unique certificate was a requirement of version 7.0 of the Windows Media™ Format SDK. In DirectX 9.0 both filters are based on version 7.1 of that SDK which does not require a unique certificate for reading or writing unprotected content. Therefore, for unprotected content both filters are now available to applications and in GraphEdit. If you are creating or reading files that have been protected with Digital Rights Management a unique certificate is still required.

When Windows Media™ Format 9 Series SDK is released, it will contain versions of these filters that supersede the version found in the DirectShow SDK.

Can DirectShow notify an application of its current playback position on a regular basis?

There is no callback notification of position. Use a timer and retrieve the current position by calling the IMediaSeeking::GetCurrentPosition method.

I wrote a filter. How do I install it?

See How to Register DirectShow Filters.

Can I test my filter with GraphEdit?

While you are developing a filter, GraphEdit can help you to visualize the connections between filters. It can also provide a quick test of a filter's functionality. However, it is not meant as a robust test platform.

How can I determine the number of pins on a filter?

See Enumerating Objects in a Filter Graph.

At what privilege ring do filters run?

Filters run at ring 3, although some filters control streaming devices that run at ring 0. For more information, see How Hardware Devices Participate in the Filter Graph.

Do I Need To Use A Kernel Debugger?

That depends on your specific project. Installing the DirectX debug runtime libraries means that you are installing debug drivers and other kernel mode components, and that if your application causes a debug assert in one of these components, your machine will automatically reboot unless you have a kernel debugger attached to your process.

How does the DEFINE_GUID macro work?

The DEFINE_GUID macro solves the problem of declaring extern references to GUID values in your source code. For example, suppose that your project has three source files, Src1.cpp, Src2.cpp, and Src3.cpp, and all three files use a certain GUID value that you have defined. The GUID value must be defined exactly once in your project, and the other source files must declare extern references to it. With the DEFINE_GUID macro, you can use the same header file for both purposes. In your header file, declare the GUID as follows:

DEFINE_GUID(CLSID_MyObject,
0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);

(Where this example has zeroes, put the actual GUID values.) You can use the Guidgen utility to create a new GUID and paste it into the header file in the DEFINE_GUID format. Include this header file in any source files that references the GUID. In exactly one of the source files, include the header file Initguid.h before your header file. For example:

// Src1.cpp
#include <initguid.h>
#include "MyGuids.h"

// Src2.cpp
#include "MyGuids.h"

// Src3.cpp
#include "MyGuids.h"

Wherever the Initguid.h header file is not included, the DEFINE_GUID macro creates an extern reference to the GUID value. When the Initguid.h header file is included, it redefines the DEFINE_GUID macro so that DEFINE_GUID creates a defining declaration of the GUID.

If you do not include Initguid.h in any of the source files, you will get a link error "unresolved external symbol." If you include Initguid.h twice for the same GUID, you will get a compile error "redefinition; multiple initialization." To resolve these errors, make sure that Initguid.h is included exactly once. Also, do not include Initguid.h inside a precompiled header file, because the precompiled header in effect gets included in every source file.


Getting Started

This section contains articles covering basic Microsoft® DirectShow® concepts needed for application development. You can use this section as a high-level introduction to DirectShow. You need only a general understanding of programming and media to understand the topics in this section.

  • Setting Up the Build Environment
  • Introduction to DirectShow Application Programming
  • How To Play a File


Setting Up the Build Environment

This article describes how to build Microsoft® DirectShow® applications. You can build a project from the command line, or from within the Microsoft® Visual Studio® environment that comes with Microsoft® Visual C++®:

Header Files

All DirectShow applications use the header file shown in the following table.

Header File | Required For
Dshow.h | All DirectShow applications.

Some DirectShow interfaces require additional header files. These requirements are noted in the interface reference.

Library Files

DirectShow uses the library files shown in the following table.

Library File | Description
Strmiids.lib | Exports class identifiers (CLSIDs) and interface identifiers (IIDs). All DirectShow applications require this library.
Quartz.lib | Exports the AMGetErrorText function. If you do not call this function, this library is not required.

In your build environment, place the DirectX SDK Include and Lib directories first in the Visual Studio search path. This ensures that you are using the most recent versions of these files.

See Also

  • Building DirectShow Filters


Introduction to DirectShow Application Programming

This article introduces the basic terminology and concepts that are used in DirectShow. After reading this section, you will be ready to write your first DirectShow application.

Filters and Filter Graphs

The building block of DirectShow is a software component called a filter. A filter is a software component that performs some operation on a multimedia stream. For example, DirectShow filters can

  • read files
  • get video from a video capture device
  • decode various stream formats, such as MPEG-1 video
  • pass data to the graphics or sound card

Filters receive input and produce output. For example, if a filter decodes MPEG-1 video, the input is the MPEG-encoded stream and the output is a series of uncompressed video frames.

In DirectShow, an application performs any task by connecting chains of filters together, so that the output from one filter becomes the input for another. A set of connected filters is called a filter graph. For example, the following diagram shows a filter graph for playing an AVI file.

Filter Graph to play an AVI file

The File Source filter reads the AVI file from the hard disk. The AVI Splitter filter parses the file into two streams, a compressed video stream and an audio stream. The AVI Decompressor filter decodes the video frames. The Video Renderer filter draws the frames to the display, using DirectDraw or GDI. The Default DirectSound Device filter plays the audio stream, using DirectSound.

The application does not have to manage all of this data flow. Instead, the filters are controlled by a high-level component called the Filter Graph Manager. The application makes high-level API calls such as "Run" (to move data through the graph) or "Stop" (to stop the flow of data). If you require more control over the stream operations, you can access the filters directly through COM interfaces. The Filter Graph Manager also passes event notifications to the application.

The Filter Graph Manager serves another purpose as well: It provides methods for the application to build the filter graph, by connecting the filters together. (DirectShow also provides various helper objects that simplify this process. These are thoroughly described in the documentation.)

Writing a DirectShow Application

In broad terms, there are three tasks that any DirectShow application must perform. These are illustrated in the following diagram:

Typical DirectShow application

  1. The application creates an instance of the Filter Graph Manager.
  2. The application uses the Filter Graph Manager to build a filter graph. The exact set of filters in the graph will depend on the application.
  3. The application uses the Filter Graph Manager to control the filter graph and stream data through the filters. Throughout this process, the application will also respond to events from the Filter Graph Manager.

When processing is completed, the application releases the Filter Graph Manager and all of the filters.

DirectShow is based on COM; the Filter Graph Manager and the filters are all COM objects. You should have a general understanding of COM client programming before you begin programming DirectShow. The article "Using COM" in the DirectX SDK documentation is a good overview of the subject. Many books about COM programming are also available.

To get started with DirectShow, read the article How To Play a File, which presents a simple console application to play a video file. The section About DirectShow explains the DirectShow architecture in more detail, while the section Using DirectShow examines the major scenarios that are supported by DirectShow, such as capture, video editing, DVD playback, and television.


How To Play a File

This article is intended to give you the flavor of DirectShow programming. It presents a simple console application that plays an audio or video file. The program is only a few lines long, but it demonstrates some of the power of DirectShow programming.

As the article Introduction to DirectShow Application Programming describes, a DirectShow application always performs the same basic steps:

  1. Creates an instance of the Filter Graph Manager.
  2. Uses the Filter Graph Manager to build a filter graph.
  3. Runs the graph, which causes data to move through the filters.

Start by calling CoInitialize to initialize the COM library:

HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
{
    // Add error-handling code here. (Omitted for clarity.)
}

To keep things simple, this example ignores the return value, but you should always check the HRESULT value from any method call.

Next, call CoCreateInstance to create the Filter Graph Manager:

IGraphBuilder *pGraph;
HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL,
    CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);

As shown, the class identifier (CLSID) is CLSID_FilterGraph. The Filter Graph Manager is provided by an in-process DLL, so the execution context is CLSCTX_INPROC_SERVER. DirectShow supports the free-threading model, so you can also call CoInitializeEx with the COINIT_MULTITHREADED flag.

The call to CoCreateInstance returns the IGraphBuilder interface, which mostly contains methods for building the filter graph. Two other interfaces are needed for this example:

  • IMediaControl controls streaming. It contains methods for stopping and starting the graph.
  • IMediaEvent has methods for getting events from the Filter Graph Manager. In this example, the interface is used to wait for playback to complete.

Both of these interfaces are exposed by the Filter Graph Manager. Use the returned IGraphBuilder pointer to query for them:

IMediaControl *pControl;
IMediaEvent   *pEvent;
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

Now you can build the filter graph. For file playback, this is done by a single method call:

hr = pGraph->RenderFile(L"C:\\Example.avi", NULL);

The IGraphBuilder::RenderFile method builds a filter graph that can play the specified file. The first parameter is the file name, represented as a wide character (2-byte) string. The second parameter is reserved and must equal NULL.

This method can fail if the specified file does not exist, or the file format is not recognized. Assuming that the method succeeds, however, the filter graph is now ready for playback. To run the graph, call the IMediaControl::Run method:

hr = pControl->Run();

When the filter graph runs, data moves through the filters and is rendered as video and audio. Playback occurs on a separate thread. You can wait for playback to complete by calling the IMediaEvent::WaitForCompletion method:

long evCode = 0;
pEvent->WaitForCompletion(INFINITE, &evCode);

This method blocks until the file is done playing, or until the specified time-out interval elapses. The value INFINITE means the application blocks indefinitely until the file is done playing. For a more realistic example of event handling, see Responding to Events.

When the application is finished, release the interface pointers and close the COM library:

pControl->Release();
pEvent->Release();
pGraph->Release();
CoUninitialize();

Sample Code

Here is the complete code listing for the example described in this article:

#include <dshow.h>
void main(void)
{
    IGraphBuilder *pGraph = NULL;
    IMediaControl *pControl = NULL;
    IMediaEvent   *pEvent = NULL;

    // Initialize the COM library.
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr))
    {
        printf("ERROR - Could not initialize COM library");
        return;
    }

    // Create the filter graph manager and query for interfaces.
    hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                        IID_IGraphBuilder, (void **)&pGraph);
    if (FAILED(hr))
    {
        printf("ERROR - Could not create the Filter Graph Manager.");
        return;
    }

    hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

    // Build the graph. IMPORTANT: Change this string to a file on your system.
    hr = pGraph->RenderFile(L"C:\\Example.avi", NULL);
    if (SUCCEEDED(hr))
    {
        // Run the graph.
        hr = pControl->Run();
        if (SUCCEEDED(hr))
        {
            // Wait for completion.
            long evCode;
            pEvent->WaitForCompletion(INFINITE, &evCode);

            // Note: Do not use INFINITE in a real application, because it
            // can block indefinitely.
        }
    }
    pControl->Release();
    pEvent->Release();
    pGraph->Release();
    CoUninitialize();
}

See Also

  • Basic DirectShow Tasks
  • PlayWnd Sample


About DirectShow

This section describes the overall architecture of DirectShow. There is a lot of information in this section, and you may not need to know all of it. Therefore, you might prefer to skim this section at first, and then look in Using DirectShow for the topics that match your application requirements. You can refer back to this section if you have specific questions about some aspect of the DirectShow architecture.

This section contains the following topics:

  • DirectShow System Overview
  • The Filter Graph and Its Components
  • Building the Filter Graph
  • Data Flow in the Filter Graph
  • Event Notification in DirectShow
  • Time and Clocks in DirectShow
  • Dynamic Graph Building
  • Plug-in Distributors


DirectShow System Overview

The Challenge of Multimedia

Working with multimedia presents several major challenges:

  • Multimedia streams contain large amounts of data, which must be processed very quickly.
  • Audio and video must be synchronized so that it starts and stops at the same time, and plays at the same rate.
  • Data can come from many sources, including local files, computer networks, television broadcasts, and video cameras.
  • Data comes in a variety of formats, such as Audio-Video Interleaved (AVI), Advanced Streaming Format (ASF), Motion Picture Experts Group (MPEG), and Digital Video (DV).
  • The programmer does not know in advance what hardware devices will be present on the end-user's system.

The DirectShow Solution

DirectShow is designed to address each of these challenges. Its main design goal is to simplify the task of creating digital media applications on the Windows® platform, by isolating applications from the complexities of data transports, hardware differences, and synchronization.

To achieve the throughput needed to stream video and audio, DirectShow uses DirectDraw® and DirectSound® whenever possible. These technologies render data efficiently to the user's sound and graphics cards. DirectShow synchronizes playback by encapsulating media data in time-stamped samples. To handle the variety of sources, formats, and hardware devices that are possible, DirectShow uses a modular architecture, in which the application mixes and matches different software components called filters.

DirectShow provides filters that support capture and tuning devices based on the Windows Driver Model (WDM), as well as filters that support legacy Video for Windows (VfW) capture cards, and codecs written for the Audio Compression Manager (ACM) and Video Compression Manager (VCM) interfaces.

The following diagram shows the relationship between an application, the DirectShow components, and some of the hardware and software components that DirectShow supports.

High level architecture

As illustrated here, DirectShow filters communicate with, and control, a wide variety of devices, including the local file system, TV tuner and video capture cards, VfW codecs, the video display (through DirectDraw or GDI), and the sound card (through DirectSound). Thus, DirectShow insulates the application from many of the complexities of these devices. DirectShow also provides native compression and decompression filters for certain file formats.


The Filter Graph and Its Components

This article describes the major components of DirectShow. It is intended as an introduction for application developers and for developers writing custom DirectShow filters. Application developers can usually ignore many of the low-level details of DirectShow. However, it is still a good idea to read this section, to have a general understanding of the DirectShow architecture.

This article contains the following sections:

  • About DirectShow Filters
  • About the Filter Graph Manager
  • About Media Types
  • About Media Samples and Allocators
  • How Hardware Devices Participate in the Filter Graph


About DirectShow Filters

DirectShow uses a modular architecture, where each stage of processing is done by a COM object called a filter. DirectShow provides a set of standard filters for applications to use, and developers can write their own custom filters that extend the functionality of DirectShow. To illustrate, here are the steps needed to play an AVI video file, along with the filters that perform each step:

  • Read the raw data from the file as a byte stream (File Source filter)
  • Examine the AVI headers, and parse the byte stream into separate video frames and audio samples (AVI Splitter filter)
  • Decode the video frames (various decoder filters, depending on the compression format).
  • Draw the video frames (Video Renderer filter)
  • Send the audio samples to the sound card (Default DirectSound Device filter).

These filters are shown in the following diagram:

Filter graph for playing back an AVI file with compressed video

As the diagram shows, each filter is connected to one or more other filters. The connection points are also COM objects, called pins. Filters use pins to move data from one filter the next. The arrows in the diagram show the direction in which the data travels. In DirectShow, a set of filters is called a filter graph.

Filters have three possible states: running, stopped, and paused. When a filter is running, it processes media data. When it is stopped, it stops processing data. The paused state is used to cue data before running; the section Data Flow in the Filter Graph describes this concept in more detail. With very rare exceptions, state changes are coordinated throughout the entire filter graph; all the filters in the graph switch states in unison. Thus, the entire filter graph is also said to be running, stopped, or paused.

Filters can be grouped into several broad categories:

  • A source filter introduces data into the graph. The data might come from a file, a network, a camera, or anywhere else. Each source filter handles a different type of data source.
  • A transform filter takes an input stream, processes the data, and creates an output stream. Encoders and decoders are examples of transform filters.
  • Renderer filters sit at the end of the chain. They receive data and present it to the user. For example, a video renderer draws video frames on the display; an audio renderer sends audio data to the sound card; and a file-writer filter writes data to a file.
  • A splitter filter splits an input stream into two or more outputs, typically parsing the input stream along the way. For example, the AVI Splitter parses a byte stream into separate video and audio streams.
  • A mux filter takes multiple inputs and combines them into a single stream. For example, the AVI Mux performs the inverse operation of the AVI Splitter. It takes audio and video streams and produces an AVI-formatted byte stream.

The distinctions between these categories are not absolute. For example, the ASF Reader filter acts as both a source filter and a splitter filter.

All DirectShow filters expose the IBaseFilter interface, and all pins expose the IPin interface. DirectShow also defines many other interfaces that support more specific functionality.

See Also

  • About the Filter Graph Manager
  • Data Flow in the Filter Graph
  • DirectShow Filters


About the Filter Graph Manager

The Filter Graph Manager is a COM object that controls the filters in a filter graph. It performs many functions, including the following:

  • Coordinating state changes among the filters.
  • Establishing a reference clock.
  • Communicating events back to the application.
  • Providing methods for applications to build the filter graph.

Each of these functions is decribed briefly here. Details can be found elsewhere in the documentation.

State changes. State changes within filters must occur in a particular order. Therefore, the application does not issue state-change commands directly to the filters. Instead, it gives a single command to the Filter Graph Manager, which distributes the command to each of the filters. Seeking works in a similar fashion: The application gives a seek command to the Filter Graph Manager, which distributes it to the filters.

Reference clock. All of the filters in the graph use the same clock, called a reference clock. The reference clock ensures that all the streams are synchronized. The time at which a video frame or audio sample should be renderered is called the presentation time. The presentation time is measured relative to the reference clock. The Filter Graph Manager chooses a reference clock, usually either the clock on the sound card, or the system clock.

Graph events. The Filter Graph Manager uses an event queue to inform the application of events that occur in the filter graph. This mechanism is similar to a Windows message loop.

Graph-building methods. The Filter Graph Manager provides methods for the application to add filters to the graph, connect filters to other filters, and disconnect filters.

One function the Filter Graph Manager does not handle is moving data from one filter to the next. This is done by the filters themselves, through their pin connections. Processing always happens on a separate thread.

Note Filters always reside in the same process as the Filter Graph Manager, and are loaded from in-process servers. Therefore, method calls are not marshalled between filters, or between filters and the Filter Graph Manager.

See Also

  • Data Flow in the Filter Graph
  • Event Notification in DirectShow
  • Setting the Graph Clock
  • Time and Clocks in DirectShow


About Media Types

Because DirectShow is modular, it requires a way to describe the format of the data at each point in the filter graph. For example, consider AVI playback. Data enters the graph as a stream of RIFF chunks. These are parsed into video and audio streams. The video stream consists of video frames, which are probably compressed. After decoding, the video stream is a series of uncompressed bitmaps. The audio stream goes through a similar process.

Media Types: How DirectShow Represents Formats

The media type is a universal and extensible way to describe digital media formats. When two filters connect, they agree on a media type. The media type identifies what kind of data the upstream filter will deliver to the downstream filter, and the physical layout of the data. If two filters cannot agree on a media type, they will not connect.

For some applications, you will never have to worry about media types. In file playback, for example, DirectShow handles all of the details. Other kinds of applications may need to work directly with media types.

Media types are defined using the AM_MEDIA_TYPE structure. This structure contains the following information:

  • Major type: The major type is a GUID that defines the overall category of the data. Major types include video, audio, unparsed byte stream, MIDI data, and so forth.
  • Subtype: The subtype is another GUID, which further defines the format. For example, within the video major type, there are subtypes for RGB-24, RGB-32, UYVY, and so forth. Within audio, there is PCM audio, MPEG-1 payload, and others. The subtype provides more information than the major type, but it does not define everything about the format. For example, video subtypes do not define the image size or the frame rate. These are defined by the format block, described below.
  • Format block: The format block is a block of data that describes the format in detail. The format block is allocated separately from the AM_MEDIA_TYPE structure. The pbFormat member of the AM_MEDIA_TYPE structure points to the format block.

    The pbFormat member is typed void* because the layout of the format block changes depending on the media type. For example, PCM audio uses a WAVEFORMATEX structure. Video uses various structures, including VIDEOINFOHEADER and VIDEOINFOHEADER2. The formattype member of the AM_MEDIA_TYPE structure is a GUID that specifies which structure is contained in the format block. Each format structure is assigned a GUID. The cbFormat member specifies the size of the format block. Always check these values before dereferencing the pbFormat pointer.

If the format block is filled in, then the major type and subtype contain redundant information. The major type and subtype, however, provide a convenient way to identify formats without a complete format block. For example, you can specify a generic 24-bit RGB format (MEDIASUBTYPE_RGB24), without knowing all of the information required by the VIDEOINFOHEADER structure, such as image size and frame rate.

For example, a filter might use the following code to check a media type:

HRESULT CheckMediaType(AM_MEDIA_TYPE *pmt)
{
    if (pmt == NULL) return E_POINTER;

    // Check the major type. We're looking for video.
    if (pmt->majortype != MEDIATYPE_Video)
    {
        return VFW_E_INVALIDMEDIATYPE;
    }

    // Check the subtype. We're looking for 24-bit RGB.
    if (pmt->subtype != MEDIASUBTYPE_RGB24)
    {
        return VFW_E_INVALIDMEDIATYPE;
    }

    // Check the format type and the size of the format block.
    if ((pmt->formattype == FORMAT_VideoInfo) &&
         (pmt->cbFormat >= sizeof(VIDEOINFOHEADER) &&
         (pmt->pbFormat != NULL))
    {
        // Now it's safe to coerce the format block pointer to the
        // correct structure, as defined by the formattype GUID.
        VIDEOINFOHEADER *pVIH = (VIDEOINFOHEADER*)pmt->pbFormat;

        // Examine pVIH (not shown). If it looks OK, return S_OK.
        return S_OK;
    }

    return VFW_E_INVALIDMEDIATYPE;
}

The AM_MEDIA_TYPE structure also contains some optional fields. These can be used to provide additional information, but filters are not required to use them:

  • lSampleSize. If this field is non-zero, it defines the size of each sample. If it is zero, it indicates that the sample size may change from sample to sample.
  • bFixedSizeSamples. If this Boolean flag is TRUE, it means the value in lSampleSize is valid. Otherwise, you should ignore lSampleSize.
  • bTemporalCompression. If this Boolean flag is FALSE, it means that all frames are key frames.


About Media Samples and Allocators

Filters deliver data across pin connections. Data moves from the output pin of one filter to the input pin of another filter. The most common way for the output pin to deliver the data is by calling the IMemInputPin::Receive method on the input, although a few other mechanisms exist as well.

Depending on the filter, memory for the media data can be allocated in various ways: on the heap, in a DirectDraw surface, using shared GDI memory, or using some other allocation mechanism. The object responsible for allocating the memory is called an allocator, which is a COM object that exposes the IMemAllocator interface.

When two pins connect, one of the pins must provide an allocator. DirectShow defines a sequence of method calls that is used to establish which pin provides the allocator. The pins also agree on the number of buffers that the allocator will create, and the size of the buffers.

Before streaming begins, the allocator creates a pool of buffers. During streaming, the upstream filter fills buffers with data and delivers them to the downstream filter. But the upstream filter does not give the downstream filter raw pointers to the buffers. Instead, it uses COM objects called media samples, which the allocator creates to manage the buffers. Media samples expose the IMediaSample interface. A media sample contains:

  • a pointer to the underlying buffer
  • a time stamp
  • various flags
  • optionally, a media type

The time stamp defines the presentation time, which the renderer filter uses to schedule rendering. The flags indicate things like whether there was a break in the data since the previous sample. The media type provides a way for filters to change formats mid-stream. Usually, the sample has no media type, which indicates that the format has not changed since the previous sample.

While a filter is using a buffer, it holds reference count on the sample. The allocator uses the reference count to determine when it can re-use the buffer. This prevents a filter from overwriting a buffer that another filter is still using. A sample does not return to the allocator's pool of available samples until every filter has released it.

See Also

  • The topic Samples and Allocators provides a more detailed description of how allocators work.
  • The topic Data Flow in the Filter Graph gives a general overview of data flow in DirectShow.

The following topics are intended for developers who are writing their own custom filters:

  • Data Flow for Filter Developers
  • Threads and Critical Sections


How Hardware Devices Participate in the Filter Graph

This article describes how Microsoft® DirectShow® interacts with audio and video hardware.

Wrapper Filters

All DirectShow filters are user mode software components. In order for a kernel mode hardware device, such as a video capture card, to join a DirectShow filter graph, the device must be represented as a user-mode filter. This function is performed by specialized "wrapper" filters provided with DirectShow. These filters include the Audio Capture filter, the VFW Capture filter, the TV Tuner filter, the TV Audio filter, and the Analog Video Crossbar filter. DirectShow also provides a filter called KsProxy, which can represent any type of Windows Driver Model® (WDM) streaming device. Hardware vendors can extends KsProxy to support custom functionality, by providing a Ksproxy plug-in, which is a COM object aggregated by KsProxy.

The wrapper filters expose COM interfaces that represent the capabilities of the device. The application uses these interfaces to pass information to and from the filter. The filter translates the COM method calls into device driver calls, passes that information to the driver in kernel mode, and then translates the result back to the application. The TV Tuner, TV Audio, Analog Video Crossbar, and KsProxy filters support custom driver properties through the IKsPropertySet interface. The VFW Capture filter and the Audio Capture filter are not extensible in this way.

For application developers, wrapper filters enable the application to control devices just as they control any other DirectShow filter. No special programming is required; the details of communicating with the kernel mode device are encapsulated within the filter.

Video for Windows Devices

The VFW Capture filter supports earlier Video for Windows (VfW) capture cards. When a VfW card is present on the target system, it can be discovered and added to the filter graph using the DirectShow System Device Enumerator. For details, see Enumerating Devices and Filters.

Audio Capture and Mixing Devices (Sound Cards)

Newer sound cards have input jacks for microphones and other types of devices. Typically these cards also have on-board mixing capabilities for controlling the volume, treble, and bass of each individual input. In DirectShow, the sound card's inputs and mixer are wrapped by the Audio Capture filter. Each sound card can be discovered with the System Device Enumerator. To view the sound cards in your system, run GraphEdit and select from the Audio Capture Sources category. Each filter in that category is a separate instance of the Audio Capture filter. (See Using GraphEdit.)

WDM Streaming Devices

Newer hardware decoders and capture cards conform to the Windows Driver Model (WDM) specification. These devices have greater functionality than VfW devices and are portable between Windows NT/Windows 2000 and Windows 98/Me. WDM video capture cards can supporting features that are not available under VfW, including the enumeration of capture formats, programmatic control of video parameters such as hue and brightness, programmatic input selection, and TV Tuner support.

To support WDM streaming devices, DirectShow provides the KsProxy filter (ksproxy.ax). KsProxy has been called the "Swiss Army Knife filter" because it does so many different things. The number of pins on the filter, and the number of COM interfaces exposed by the filter, depend on the capabilities of the underlying driver. KsProxy does not appear in the filter graph under the name "KsProxy." It always takes the friendly name of the device, which is found in the registry. To view the WDM devices on your system, run GraphEdit and select from the WDM Streaming categories. Even if you have only one WDM card on your system, that card might contain more than one device. Each device is represented as a separate filter, and each of these filters is actually KsProxy.

An application uses the System Device Enumerator to find WDM device monikers on the system. KsProxy is instantiated by calling BindToObject on the moniker. Because KsProxy can represent all kinds of WDM devices, it must query the driver to determine which property sets the driver supports. Property sets are collections of data structures used by WDM drivers, and also by some user mode filters, such as MPEG-2 software decoders. KsProxy configures itself to expose the COM interfaces that correspond to those property sets. KsProxy translates the COM method calls into property sets and sends these to the driver. Hardware vendors can extend KsProxy by supplying plug-ins, which are vendor-specific interfaces that expose the special capabilities of a device. All these details are hidden from application. The application controls the device by way of KsProxy, in the same way as any other DirectShow filter.

Kernel Streaming

WDM devices support kernel streaming, in which data is streamed entirely in kernel mode without ever switching to user mode. Switching between kernel mode and user mode is computationally expensive; kernel streaming allows for high bit rates without burdening the host CPU. WDM-based filters can use kernel streaming to pass multimedia data directly from one hardware device to another, either on the same card or on a different card, without copying the data into the system's main memory.

From an application's point of view, it appears as if the data moves from one user mode filter to the next. In reality, the data might never pass into user mode at all, but instead might be streamed directly from one kernel mode device to another until it is rendered on the video graphics card. Some scenarios, such as capture to a file, require that the data pass from kernel mode to user mode at some point. However, this switch does not necessarily require the data to be copied to a new location in memory.

Application developers generally do not need to be concerned with the details of kernel streaming, except as background information. See the Microsoft DDK for more detailed information about WDM, kernel streaming, KsProxy, and related topics.


Building the Filter Graph

The article The Filter Graph and Its Components, describes the basic building blocks of a DirectShow filter graph. This section examines how these building blocks are created and connected together so that they can begin to process data. This section contains the following topics:

  • Graph-Building Components
  • Overview of Graph Building
  • Intelligent Connect


Graph-Building Components

DirectShow provides several components that can be used to build filter graphs. These include the following:

  • Filter Graph Manager. This object controls the filter graph. It supports the IGraphBuilder, IMediaControl, and IMediaEventEx interfaces, among others. All DirectShow applications use this object at some point, although in some cases another object creates the Filter Graph Manager for the application.
  • Capture Graph Builder. This object provides additional methods for building filter graphs. It was originally designed for building graphs that perform video capture (hence the name) but is useful for many other types of custom filter graph. It supports the ICaptureGraphBuilder2 interface.
  • Filter Mapper and System Device Enumerator. These objects locate filters that are registered on the user's system, or that represent hardware devices.
  • DVD Graph Builder. This object builds filter graphs for DVD playback and navigation. It supports the IDvdGraphBuilder interface. Script-based applications can use the MSWebDVD Microsoft® Active X® control for DVD playback.
  • Video Control. This ActiveX control is available on Microsoft Windows® XP. It handles digital and analog television in DirectShow. For more information, see Using the Video Control.

Intelligent Connect

The term "Intelligent Connect" covers a set of algorithms that the Filter Graph Manager uses to build all or part of a filter graph. Whenever the Filter Graph Manager requires additional filters to complete the graph, it does roughly the following:

  1. If there is a filter currently in the graph, with at least one unconnected input pin, the Filter Graph Manager tries to use that filter.
  2. Otherwise, the Filter Graph Manager looks in the registry for filters that can accept the correct media type for the connection. Each filter has a registry value called "Merit," which indicates roughly how likely the filter is to be useful in completing the graph. The Filter Graph Manager tries filters in order of merit value. For each stream type (such as audio, video, or MIDI), the default renderer has a high merit. Decoders also have high merit. Special-purpose filters have low merit.

If the Filter Graph Manager gets stuck, it will back out and try a different combination of filters. You can find the exact details in the topic Intelligent Connect.


Overview of Graph Building

To create a filter graph, begin by creating an instance of the Filter Graph Manager:

IGraphBuilder* pIGB;
HRESULT hr = CoCreateInstance(CLSID_FilterGraph,
    NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder,
    (void **)&pIGB);

The Filter Graph Manager supports the following graph-building methods:

  • IFilterGraph::ConnectDirect tries to make a direct connection between two pins. If the pins cannot connect, the method fails.
  • IGraphBuilder::Connect connects two pins. If possible, it makes a direct connection. Otherwise, it uses intermediate filters to complete the connection.
  • IGraphBuilder::Render starts from an output pin and builds the rest of the graph. This methods adds filters as needed, working downstream, until it reaches a renderer filter.
  • IGraphBuilder::RenderFile builds a complete file-playback graph.
  • IFilterGraph::AddFilter adds a filter to the graph. It does not connect the filter. You must create the filter before calling this method, either by calling CoCreateInstance or by using the Filter Mapper or System Device Enumerator.

These methods provide three basic approaches to building the graph:

  1. The Filter Graph Manager builds the entire graph.
  2. The Filter Graph Manager builds part of the graph.
  3. The application builds the entire graph.

The Filter Graph Manager Builds the Entire Graph

If you simply want to play a file that is authored in a recognized format, such as AVI, MPEG, WAV, or MP3, use the RenderFile method. The article How To Play a File shows how to do this.

The RenderFile method starts by looking in the regstry for a source file that can parse the file. It uses the protocol (such as "http://" in the file name), the file extension, or pre-defined byte patterns in the file to determine the source filter. For details, see Registering a Custom File Type.

To build the rest of the graph, the Filter Graph Manager uses an iterative process wherein it takes the media types that a filter supports on its output pins, and searches the registry for filters that will accept that media type as input. It uses several criteria to narrow the search and prioritize filters:

  • The filter category identifies the general functionality of the filter.
  • The media type describes what kind of data the filter can accept as input or deliver as output.
  • The merit determines the order in which filters are tried. If two filters in the same filter category both support the same input types, the Filter Graph Manager selects the one with the highest merit value. Some filters are purposely given a low merit value because they are designed for specialized purposes and should only be added to the graph by the application.

The Filter Graph Manager uses the Filter Mapper object to search the registry.

As each filter is added, the Filter Graph Manager tries to connect it to the previous filter's output pin. The filters negotiate to determine whether they can connect, and if so, what media type to use for the connection. If the new filter cannot connect, the Filter Graph Manager discards it and tries another filter. This process continues until every stream is rendered.

The Filter Graph Manager Builds Part of the Graph

To do something beyond simply playing a file, your application must perform at least some of the graph building work. For example, a video capture application must select a capture source filter and add it to the graph. If you are writing data to an AVI file, you must add the AVI Mux and File Writer filters to the graph. However, it is often possible to let the Filter Graph Manager complete the graph. For example, you can render a pin for preview by calling the Render method.

The Application Builds the Entire Graph

In some scenarios, your application may need to build the graph by adding and connecting each filter. In this case, you probably know specifically which filters should be added to the graph. With this approach, the application adds each filter by calling AddFilter, enumerates the pins on the filters, and connects them by calling either Connect or ConnectDirect.

See Also

  • Building Graphs with the Capture Graph Builder
  • Enumerating Devices and Filters
  • Enumerating Objects in a Filter Graph
  • General Graph-Building Techniques


Intelligent Connect

Intelligent Connect is the mechanism the Filter Graph Manager uses to build filter graphs. It consists of several related algorithms that select filters and add them to the filter graph. For application programming, you rarely need to know the details of Intelligent Connect. Read this section if you are having trouble building a certain filter graph and want to troubleshoot the problem, or if you are writing your own filter and want to make it available for automatic graph building.

Intelligent Connect involves the following IGraphBuilder methods:

  • IGraphBuilder::Render
  • IGraphBuilder::AddSourceFilter
  • IGraphBuilder::RenderFile
  • IGraphBuilder::Connect

The Render method builds a subsection of a graph. It starts from an unconnected output pin and works downstream, adding new filters as needed. The starting filter must already be in the graph. At each step, the Render method searches for a filter that can connect to the previous filter. The stream can branch if a connecting filter has multiple output pins. The search stops when every stream has a renderer. If the Render method gets stuck, it might back up and try again, using a different set of filters.

To connect each output pin, the Render method does the following:

  1. If the pin supports the IStreamBuilder interface, the Filter Graph Manager delegates the entire process to the pin's IStreamBuilder::Render method. By exposing this interface, the pin assumes responsibility for building the remainder of the graph, down to the renderer. However, very few pins support this interface.
  2. The Filter Graph Manager tries to use filters that are cached in memory, if any. Throughout the Intelligent Connect process, the Filter Graph Manager may cache filters from earlier steps in the process. (Also, see Dynamic Graph Building.)
  3. If the filter graph contains any filters with unconnected input pins, the Filter Graph Manager tries them next. You can force the Render method to try a particular filter by adding that filter to the graph before calling Render.
  4. Finally, the Filter Graph Manager searches the registry, using the IFilterMapper2::EnumMatchingFilters method. It tries to match the output pin's preferred media types against media types listed in the registry.

Each filter is registered with a merit, a numerical value that indicates how preferable the filter is, relative to other filters. The EnumMatchingFilters method returns filters in order of merit, with a minimum merit of MERIT_DO_NOT_USE + 1. It ignores filters with a merit of MERIT_DO_NOT_USE or less. Filters are also grouped into categories, defined by GUID. Categories themselves have merit, and the EnumMatchingFilters method ignores any category with a merit of MERIT_DO_NOT_USE or less, even if the filters in that category have higher merit values.

To summarize, the Render method tries filters in the following order:

  1. Use IStreamBuilder.
  2. Try cached filters.
  3. Try filters in the graph.
  4. Look up filters in the registry.

The AddSourceFilter method adds a source filter that can render a specified file. First it looks in the registry and matches against the protocol (such as http://), the file extension, or a set of predetermined check bytes, which are bytes at particular offsets in the file that match certain patterns. For details, see Registering a Custom File Type. Assuming that the method locates an appropriate source filter, it then creates an instance of that filter, adds it to the graph, and calls the filter's IFileSourceFilter::Load method with the file name.

The RenderFile method builds a default playback graph from a file name. Internally, this method uses AddSourceFilter to locate the correct source filter, and Render to build the rest of the graph.

The Connect method connects and output pin to an input pin. This method adds intermediate filters if needed, using a variation of the algorithm described for the Render method:

  1. Try a direct connection between the filters, with no intermediate filters.
  2. Try cached filters.
  3. Try filters in the graph.
  4. Look up filters in the registry.

See Also

  • Filter Categories
  • Merit
  • Simulating Graph Building with GraphEdit


Data Flow in the Filter Graph

This section describes how media data moves through the filter graph. Usually, you do not need to know these details to write a DirectShow application, although in some situations you may find it helpful. If you are writing a DirectShow filter, you will need to understand this material.

This section contains the following topics:

  • Transports
  • Samples and Allocators
  • Filter States
  • Pull Model

See Also

  • Data Flow for Filter Developers


Transports

In order to move media data through the filter graph, a DirectShow filter must support one of several possible protocols. These protocols are called transports. When two filters connect, they must support the same transport; otherwise they cannot exchange media data. Typically, a transport requires that one of the pins support a particular interface. When the filters connect, one pin queries the other for the interface.

Most DirectShow filters hold media data in main memory, and deliver it to other filters across pin connections. This type of transport is called local memory transport. Although local memory transport is the most common transport in DirectShow, not all filters use it. For example, some filters send media data along a hardware path, and use pins only to deliver control information. For example, see the IOverlay interface.

DirectShow defines two mechanisms for local memory transport, the push model and the pull model. In the push model, a source filter generates data and delivers it to the next filter downstream. That filter passively receives the data, processes it, and sends it further downstream. In the pull model, the source filter is connected to a parser filter. The parser filter requests data from the source filter. The source filter responds to the requests by delivering data. The push model uses the IMemInputPin interface, and the pull model uses the IAsyncReader interface.

The push model is more common than the pull model. Therefore, the articles that follow assume a push model. The last article in this section, Pull Model, describes how the IAsyncReader interface differs from IMemInputPin.


Samples and Allocators

When a pin delivers media data to another pin, it does not pass a direct pointer to the memory buffer. Instead, it delivers a pointer to a COM object that manages the memory. This object, called a media sample, exposes the IMediaSample interface. The receiving pin accesses the memory buffer by calling IMediaSample methods, such as IMediaSample::GetPointer, IMediaSample::GetSize, and IMediaSample::GetActualDataLength.

Samples always travel downstream, from output pin to input pin. In the push model, the output pin delivers a sample by calling IMemInputPin::Receive on the input pin. The input pin will either process the data synchronously (that is, completely inside the Receive method), or process it asynchronously on a worker thread. The input pin is allowed to block within the Receive method, if it needs to wait for resources.

Another COM object, called an allocator, is responsible for creating and managing media samples. Allocators expose the IMemAllocator interface. Whenever a filter needs a media sample with an empty buffer, it calls the IMemAllocator::GetBuffer method, which returns a pointer to the sample. Every pin connection shares one allocator. When two pins connect, they decide which filter will provide the allocator. The pins also set properties on the allocator, such as the number of buffers and the size of each buffer. (For details, see How Filters Connect and Negotiating Allocators.)

The following illustration shows the relationships among the allocator, the media samples, and the filter.

Media Samples and Allocators

Media Sample Reference Counts

An allocator creates a finite pool of samples. At any time, some samples may be in use, while others are available for GetBuffer calls. The allocator uses reference counting to keep track of the samples. The GetBuffer method returns a sample with a reference count of 1. If the reference count goes to zero, the sample goes back into the allocator's pool, where it can be used in the next GetBuffer call. As long as the reference count remains above zero, the sample is not available to GetBuffer. If every sample belonging to the allocator is in use, the GetBuffer method blocks until a sample becomes available.

For example, suppose that an input pin receives a sample. If it processes the sample synchronously, inside the Receive method, it does not increment the reference count. After Receive returns, the output pin releases the sample, the reference count goes to zero, and the sample returns to the allocator's pool. On the other hand, if the input pin processes the sample on a worker thread, it increments the reference count before leaving the Receive method. The reference count is now 2. When the output pin releases the sample, the count goes to 1; the sample does not yet return to the pool. After the worker thread is done with the sample, it calls Release to free the sample. Now the sample returns to the pool.

When a pin receives a sample, it can copy the data to another sample, or it can modify the original sample and deliver that one to the next filter. Potentially, a sample can travel the entire length of the graph, each filter calling AddRef and Release in turn. Therefore, the output pin must never re-use a sample after it calls Receive, because a downstream filter may be using the sample. The output pin must always call GetBuffer to get a new sample.

This mechanism reduces the amount of memory allocation, because filters re-use the same buffers. It also prevents filters from accidentally writing over data that has not been processed, because the allocator maintains a list of available samples.

A filter can use separate allocators for input and output. It might do this if it expands the input data (for example, by decompressing it). If the output is no larger than the input, a filter might process the data in place, without copying it to a new sample. In that case, two or more pin connections can share one allocator.

Committing and Decommitting Allocators

When a filter first creates an allocator, the allocator has not reserved any memory buffers. At this point, any calls to the GetBuffer method will fail. When streaming starts, the output pin calls IMemAllocator::Commit, which commits the allocator, causing it to allocate memory. Pins can now call GetBuffer.

When streaming stops, the pin calls IMemAllocator::Decommit, which decommits the allocator. All subsequent calls to GetBuffer fail until the allocator is committed again. Also, if any calls to GetBuffer are currently blocked waiting for a sample, they immediately return a failure code. The Decommit method may or may not free the memory, depending on the implementation. For example, the CMemAllocator class waits until its destructor method to free memory.


Filter States

Filters have three possible states: stopped, paused, and running. The purpose of the paused state is to cue data in the graph, so that a run command responds immediately. The Filter Graph Manager controls all state transitions. When an application calls IMediaControl::Run, IMediaControl::Pause, or IMediaControl::Stop, the Filter Graph Manager calls the corresponding IMediaFilter method on all of the filters. Transitions between stopped and running always go through the paused state, so if the application calls Run on a stopped graph, the Filter Graph Manager pauses the graph before running it.

For most filters, the running and paused states are identical. Consider the following filter graph:

    Source > Transform > Renderer

Assume for now that the source filter is not a live capture source. When the source filter pauses, it creates a thread that generates new data and writes it into media samples as quickly as possible. The thread "pushes" the samples downstream by calling IMemInputPin::Receive on the transform filter's input pin. The transform filter receives the samples on the source filter's thread. It may use a worker thread to deliver the samples to the renderer, but typically it delivers them on the same thread. While the renderer is paused, it waits to receive a sample. After it receives one, it blocks and holds that sample indefinitely. If it is a video renderer, it displays the sample as a poster image, repainting the image as necessary.

At this point, the stream is fully cued and ready for rendering. If the graph remains paused, samples will "pile up" in the graph behind the first sample, until every filter is blocked in Receive or GetBuffer. No data is lost, though. Once the source thread is unblocked, it simply resumes from the point where it blocked.

The source filter and the transform filter ignore the transition from paused to running—they simply continue to process data as fast as possible. But when the renderer runs, it starts rendering samples. First it renders the sample it held while it was paused. Then, each time it receives a new sample, it calculates the sample's presentation time. (For details, see Time and Clocks in DirectShow.) The renderer holds each sample until the presentation time, at which point it renders the sample. While it waits for the presentation time, it either blocks in the Receive method, or receives new samples on a worker thread with a queue. Filters upstream from the renderer are not involved in scheduling.

Live sources, such as capture devices, are an exception to this general architecture. With a live source, it is not appropriate to cue any data in advance. The application might pause the graph and then wait for a long time before running it. The graph should not render "stale" samples. Therefore, a live source produces no samples while paused, only while running. To signal this fact to the Filter Graph Manager, the source filter's IMediaFilter::GetState method returns VFW_S_CANT_CUE. This return code indicates that the filter has switched to the paused state, even though the renderer did not receive any data.

When a filter stops, it rejects any more samples delivered to it. Source filters shut down their streaming threads, and other filters shut down any worker threads they may have created. Pins decommit their allocators.

State Transitions

The Filter Graph Manager carries out all state transitions in upstream order, starting from the renderer and working backward to the source filter. This ordering is necessary to prevent samples from being dropped and to prevent the graph from deadlocking. The most crucial state transitions are between paused and stopped:

  • Stopped to paused: As each filter pauses, it becomes ready to receive samples from the next filter. The source filter is the last to pause. It creates the streaming thread and begins delivering samples. Because all of the downstream filters are paused, no filter rejects any samples. The Filter Graph Manager does not complete the transition until every renderer in the graph has received a sample (with the exception of live sources, as described earlier).
  • Paused to stopped: When a filter stops, it releases any samples that it holds, which unblocks any upstream filters waiting in GetBuffer. If the filter is waiting for a resouce inside the Receive method, it stops waiting and returns from Receive, which unblocks the calling filter. Therefore, when the Filter Graph Manager stops the next upstream filter, that filter is not blocked in either GetBuffer or Receive, and can respond to the stop command. The upstream filter might deliver a few extra samples before it gets the stop command, but the downstream filter simply rejects them, because it already stopped.


Pull Model

In the IMemInputPin interface, the upstream filter determines what data to send, and it pushes the data to the downstream filter. For some filters, a pull model is more appropriate. Here, the downstream filter requests data from the upstream filter. Samples still travel downstream, from output pin to input pin, but the downstream filter initiates the data flow. This type of connection uses the IAsyncReader interface.

The typical use for the pull model is in file playback. For example, in an AVI playback graph, the Async File Source filter performs generic file reading operations and delivers the data as a byte stream, with no format information. The AVI Splitter filter reads the AVI headers and parses the stream into video and audio samples. The AVI Splitter can determine what data it needs better than the Async File Source filter, and therefore it uses IAsyncReader instead of IMemInputPin.

To request data from the output pin, the input pin calls one of the following methods:

  • IAsyncReader::Request
  • IAsyncReader::SyncRead
  • IAsyncReader::SyncReadAligned.

The first method is asynchronous, to support multiple overlapped reads. The others are synchronous.

In theory, any filter can support IAsyncReader, but in practice it is designed for source filters that connect to parser filters. The parser acts very much like a source filter in the push model. When it pauses, it creates a streaming thread that pulls data from the IAsyncReader connection and pushes it downstream. The outpin pins use IMemInputPin, anfd the rest of the graph uses the standard push model.


Event Notification in DirectShow

This article describes how events are raised in a Microsoft® DirectShow® filter graph, and how an application can retrieve event notifications and respond to them. It contains the following sections.

  • Overview of Event Notification
  • Retrieving Events
  • Learning When an Event Occurs


Overview of Event Notification

A filter notifies the Filter Graph Manager about an event by posting an event notification. The event could be something expected, such as the end of a stream, or it could represent an error, such as a failure to render a stream. The Filter Graph Manager handles some filter events by itself, and it leaves others for the application to handle. If the Filter Graph Manager does not handle a filter event, it places the event notification into a queue. The filter graph can also queue its own event notifications for the application.

An application retrieves events from the queue and responds to them based on the type of event. Event notification in DirectShow is therefore similar to the Microsoft® Windows® message queuing scheme. An application can also cancel the Filter Graph Manager's default behavior for a given event type. The Filter Graph Manager then puts those events directly into the queue for the application to handle.

This mechanism enables

  • The Filter Graph Manager to communicate with the application.
  • Filters to communicate with both the application and the Filter Graph Manager.
  • The application to determine its degree of involvement in handling events.


Retrieving Events

The Filter Graph Manager exposes three interfaces that support event notification.

  • IMediaEventSink contains the method for filters to post events.
  • IMediaEvent contains methods for applications to retrieve events.
  • IMediaEventEx inherits from and extends the IMediaEvent interface.

Filters post event notifications by calling the IMediaEventSink::Notify method on the Filter Graph Manager. An event notification consists of an event code, which defines the type of event, and two DWORD parameters that give additional information. Depending on the event code, the parameters might contain pointers, return codes, reference times, or other information. For a complete list of event codes and parameters, see Event Notification Codes.

To retrieve an event from the queue, the application calls the IMediaEvent::GetEvent method on the Filter Graph Manager. This method blocks until there is an event to return or until a specified time elapses. Assuming there is a queued event, the method returns with the event code and the two event parameters. After calling GetEvent, an application should always call the IMediaEvent::FreeEventParams method to release any resources associated with the event parameters. For example, a parameter might be a BSTR value that was allocated by the filter graph.

The following code example provides an outline of how to retrieve events from the queue.

long evCode, param1, param2;
HRESULT hr;
while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
{
    switch(evCode)
    {
        // Call application-defined functions for each
        // type of event that you want to handle.
    }
    hr = pEvent->FreeEventParams(evCode, param1, param2);
}

To override the Filter Graph Manager's default handling for an event, call the IMediaEvent::CancelDefaultHandling method with the event code as a parameter. You can reinstate the default handling by calling the IMediaEvent::RestoreDefaultHandling method. If the filter graph performs no default handling for the specified event code, calling these methods has no effect.


Learning When an Event Occurs

To process DirectShow events, an application needs a way to find out when events are waiting in the queue. The Filter Graph Manager provides two ways to do this:

  • Window notification: The Filter Graph Manager sends a user-defined Windows message to an application window whenever there is a new event.
  • Event signaling: The Filter Graph Manager signals a Windows event if there are DirectShow events in the queue, and reset the event if the queue is empty.

An application can use either technique. Window notification is usually simpler.

Window Notification

To set up window notification, call the IMediaEventEx::SetNotifyWindow method and specify a private message. Applications can use message numbers in the range from WM_APP through 0xBFFF as private messages. Whenever the Filter Graph Manager places a new event notification in the queue, it posts this message to the designated window. The application responds to the message from within the window's message loop.

The following code example shows how to set the notification window.

#define WM_GRAPHNOTIFY WM_APP + 1   // Private message.
pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);

The message is an ordinary Windows message, and is posted separately from the DirectShow event notification queue. The advantage of this approach is that most applications already implement a message loop. Therefore, you can incorporate DirectShow event handling without much additional work.

The following code example shows an outline of how to respond to the notification message. For a complete example, see Responding to Events.

LRESULT CALLBACK WindowProc( HWND hwnd, UINT msg, UINT wParam, LONG lParam)
{
    switch (msg)
    {
        case WM_GRAPHNOTIFY:
            HandleEvent();  // Application-defined function.
            break;
        // Handle other Windows messages here too.
    }
    return (DefWindowProc(hwnd, msg, wParam, lParam));
}

Because event notification and the message loop are both asynchronous, the queue might contain more than one event by the time your application responds to the message. Also, events can sometimes be cleared from the queue if they become invalid. Therefore, in your event handling code, call GetEvent until it returns a failure code, indicating that the queue is empty.

Before you release the IMediaEventEx pointer, cancel event notification by calling SetNotifyWindow with a NULL pointer. In your event processing code, check whether your IMediaEventEx pointer is valid before calling GetEvent. These steps prevent a possible error, in which the application receives the event notification after it has released the IMediaEventEx pointer.

Event Signaling

The Filter Graph Manager keeps a manual-reset event that reflects the state of the event queue. If the queue contains pending event notifications, the Filter Graph Manager signals the manual-reset event. If the queue is empty, a call to the IMediaEvent::GetEvent method resets the event. An application can use this event to determine the state of the queue.

Note The terminology can be confusing here. The manual-reset event is the type of event created by the Windows CreateEvent function; it has nothing to do with the events defined by DirectShow.

Call the IMediaEvent::GetEventHandle method to retrieve a handle to the manual-reset event. Wait for the event to be signaled by calling a function such as WaitForMultipleObjects. Once the event is signaled, call IMediaEvent::GetEvent to retrieve the DirectShow event.

The following code example illustrates this approach. It retrieves the event handle, then waits in 100-millisecond intervals for the event to be signaled. If the event is signaled, it calls GetEvent and prints the event code and event parameters to the console window. The loop terminates when the EC_COMPLETE event occurs, indicating that playback has completed.

HANDLE  hEvent;
long    evCode, param1, param2;
BOOLEAN bDone = FALSE;
HRESULT hr = S_OK;
hr = pEvent->GetEventHandle((OAEVENT*)&hEvent);
if (FAILED(hr)
{
    /* Insert failure-handling code here. */
}
while(!bDone)
{
    if (WAIT_OBJECT_0 == WaitForSingleObject(hEvent, 100))
    {
        while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
        {
            printf("Event code: %#04x\n Params: %d, %d\n", evCode, param1, param2);
            pEvent->FreeEventParams(evCode, param1, param2);
            bDone = (EC_COMPLETE == evCode);
        }
    }
}

Because the filter graph automatically sets or resets the event when appropriate, your application should not do so. Also, when you release the filter graph, the filter graph closes the event handle, so do not use the event handle after that point.


Time and Clocks in DirectShow

This article gives an overview of time and clocks in the Microsoft DirectShow architecture. It contains the following sections.

  • Reference Clocks
  • Clock Times
  • Time Stamps
  • Live Sources


Reference Clocks

One function of the Filter Graph Manager is to synchronize all of the filters in the graph to the same clock, called the reference clock.

Any object that exposes the IReferenceClock interface can act as the reference clock. The reference clock might be provided by a DirectShow filter — typically the audio renderer, which has access to a hardware timer. As a fallback, the Filter Graph Manager can use the system time.

Nominally, a reference clock measures time in 100-nanosecond intervals, although the actual accuracy of the clock might be less. To retrieve the clock's current time, call the IReferenceClock::GetTime method. The clock's baseline—the time from which it starts counting—depends on the implementation, so the value returned by GetTime is not inherently meaningful. What matters is the delta from when the graph started running.

Although the accuracy of a reference clock can vary, the times returned by the GetTime method are guaranteed to increase monotonically. In other words, clock times will never go backward. If a reference clock is generating clock times from a hardware source and the hardware clock jumps backward (for example, if there is an adjustment to the clock), the GetTime method should continue to return the last reported time until the hardware clock catches up. For more information, see CBaseReferenceClock Class.

Default Reference Clock

The Filter Graph Manager automatically selects a reference clock when the graph runs. It uses the following algorithm to select the clock:

  • If the application has selected a clock (see below), use that clock.
  • If the graph contains a live source filter that supports IReferenceClock, use that filter. For the definition of a live source, see Live Sources.
  • If the graph does not contain any live source filters, use any filter in the graph that supports IReferenceClock, starting from the renderers and working upstream. Prefer connected filters over unconnected filters. (If the graph is rendering an audio stream, this step in the algorithm will normally select the audio renderer filter.)
  • If no filter provides a suitable clock, use the System Reference Clock, which is based on the system time.

Setting the Reference Clock

An application can select a clock by calling the IMediaFilter::SetSyncSource method on the Filter Graph Manager. You should do this only if you have a particular reason to prefer another clock.

You can instruct the Filter Graph Manager not to use a reference clock by calling SetSyncSource with the value NULL. For example, you might do this to process samples as quickly as possible. To restore the default reference clock, call the IFilterGraph::SetDefaultSyncSource method on the Filter Graph Manager.

Whenever the reference clock changes, the Filter Graph Manager notifies each filter by calling its IMediaFilter::SetSyncSource method. Applications should never call this method on filters.

See Also

  • Setting the Graph Clock


Clock Times

DirectShow defines two related clock times: reference time and stream time.

  • Reference time is the absolute time returned by the reference clock.
  • Stream time is defined relative to when the graph last started running.
    • While the graph is running, stream time equals reference time minus start time.
    • While the graph is paused, stream time remains at the stream time when it was paused.
    • After a seek operation, stream time resets to zero.
    • While the graph is stopped, stream time is undefined.

When a media sample has a time stamp t, it means the sample should be rendered at stream time t. For this reason, stream time is also called presentation time.

When an application calls IMediaControl::Run to run the filter graph, the Filter Graph Manager calls IMediaFilter::Run on each filter. To compensate for the slight amount of time it takes for the filters to start running, the Filter Graph Manager specifies a start time slightly in the future.

See Also

  • Time Stamps


Time Stamps

The time stamp defines a media sample's start and finish times, measured in stream time. The time stamp is sometimes called the presentation time. When reading the rest of this article, it is important to remember that not all formats use time stamps in the same way. For example, not all MPEG samples are time stamped. In MPEG filter graphs, the time stamp is not applied to each frame until they are output from the decoder.

When a renderer filter receives a sample, it schedules rendering based on the time stamp. If the sample arrives late, or has no time stamp, the filter renders the sample immediately. Otherwise, the filter waits until the sample's start time before it renders the sample. (It waits for the start time by calling the IReferenceClock::AdviseTime method.)

Source filters and parser filters are responsible for setting the correct time stamps on the samples they process. Use the following guidelines.

  • File playback: The first sample is time stamped with a start time of zero. Subsequent time stamps are determined by the sample length and the playback rate, which itself is determined by the file format. The filter that parses the file is responsible for calculating the correct time stamps (for example, the AVI Splitter).
  • Video and audio capture: Every sample is time stamped with a start time equal to the stream time when it was captured, with the following caveats:
    • Video frames from a preview pin (as opposed to a capture pin) are not time stamped. Because of graph latency, a video frame that is stamped with the capture time will always arrive late at the video renderer. This may cause the renderer to drop frames, in an attempt at quality control. For information about quality control, see Quality-Control Management.
    • Audio capture: The audio capture filter uses its own set of buffers, which are separate from those used by the audio driver. The audio driver fills the capture filter's buffers at fixed intervals. The interval depends on the driver, but generally is not more than 10 milliseconds. The time stamps on the audio samples reflect the time when the driver filled the audio capture filter's buffers. These times can be slightly inaccurate, especially if the application is using a very small buffer size. However, the media times will accurately reflect the number audio samples in the buffer.
  • Mux filters: Depending on the output format, a mux filter may need to generate time stamps, or it may not. For example, the AVI file format uses a fixed frame rate with no time stamps, so the AVI Mux filter assumes that samples are arriving at approximately the right time. If the incoming time stamps show a gap larger than one frame, however, the AVI Mux writes an index entry with size zero, to indicate a dropped frame. On file playback, new time stamps are generated at run time, as described previously.

To set the time stamp on a sample, call the IMediaSample::SetTime method.

Optionally, the filter can also specify a media time for the sample. In a video stream, media time represents the frame number. In an audio stream, media time represents the sample number in the packet. For example, if each packet contains one second of 44.1 kilohertz (kHz) audio, the first packet has a media start time of zero and a media stop time of 44100. In a seekable stream, the media time is always relative to the start time of the stream. For example, suppose you seek to 2 seconds from the start of a 15-fps video stream. The first media sample after the seek has a time stamp of zero but a media time of 30.

Renderer and mux filters can use the media time to determine whether frames or samples have been dropped, by checking for gaps. However, filters are not required to set the media time. To set the media time on a sample, call the IMediaSample::SetMediaTime method.


Live Sources

A live source, also called a push source, receives data in real time. Examples include video capture and network broadcasts. In general, a live source cannot control the rate at which data arrives.

A filter is considered to be a live source if either of the following are true:

  • The filter returns the AM_FILTER_MISC_FLAGS_IS_SOURCE flag from the IAMFilterMiscFlags::GetMiscFlags method, and at least one of its output pins exposes the IAMPushSource interface.
  • The filter exposes the IKsPropertySet interface and has a capture pin (PIN_CATEGORY_CAPTURE). See Pin Property Set for more information.

If a live source filter provides a clock, the Filter Graph Manager will prefer that clock when it chooses the graph reference clock. See Reference Clocks for more information.

Latency

A filter's latency is the amount of time it takes the filter to process a sample. For live sources, the latency is determined by the size of the buffer used to hold samples. For example, suppose the filter graph has a video source with a latency of 33 milliseconds (ms) and an audio source with a latency of 500 ms. Each video frame arrives at the video renderer about 470 ms before the matching audio sample reaches the audio renderer. Unless the graph compensates for the difference, the audio and video will not be synchronized.

Live sources can be synchronized through the IAMPushSource interface. The Filter Graph Manager does not synchronize live sources unless the application enables synchronization by calling the IAMGraphStreams::SyncUsingStreamOffset method. If synchronization is enabled, the Filter Graph Manager queries each source filter for IAMPushSource. If the filter supports IAMPushSource, the Filter Graph Manager calls IAMLatency::GetLatency to retrieve the filter's expected latency. (The IAMPushSource interface inherits IAMLatency.) From the combined latency values, the Filter Graph Manager determines the maximum expected latency in the graph. It then calls IAMPushSource::SetStreamOffset to give each source filter a stream offset, which that filter adds to the time stamps that it generates.

This method is intended primarily for live preview. However, note that a preview pin on a live capture device (such as a camera) does not set time stamps on the samples it delivers. Therefore, to use this method with a live capture device, you must preview from the capture pin. For more information, see DirectShow Video Capture Filters.

Currently the IAMPushSource interface is supported by the VFW Capture filter and the Audio Capture filter.

Rate Matching

If a renderer filter schedules samples using one reference clock, but the source filter produces them using a different clock, glitches can occur in playback. The renderer might run faster than the source, causing gaps in the data. Or it might run slower than the source, causing samples to "bunch up," until at some point the graph will drop samples. Typically, a live source cannot control its production rate, so instead the renderer should match rates with the source.

Currently, only the audio renderer performs rate matching, because glitches in audio playback are more noticeable than glitches in video. To perform rate-matching, the audio renderer must select something against which it will match rates. It uses the following algorithm:

  • If the graph is not using a reference clock, the audio renderer does not try to match rates. (Whenever the graph has no reference clock, samples are always rendered immediately as they arrive.)
  • Otherwise, if there is a reference clock for the graph, the audio renderer checks whether there is a live source upstream, using the criteria described previously. If not, the audio renderer does not match rates.
  • If there is a live source upstream, and that source exposes the IAMPushSource interface on its output pin, the audio renderer calls IAMPushSource::GetPushSourceFlags. It looks for one of the following flags:
    • AM_PUSHSOURCECAPS_INTERNAL_RM. This flag means the source filter has its own rate-matching mechanism, so the audio renderer does not match rates.
    • AM_PUSHSOURCECAPS_NOT_LIVE. This flag means the source filter is not really a live source, even though it exposes the IAMPushSource interface. Therefore, the audio renderer does not match rates.
    • AM_PUSHSOURCECAPS_PRIVATE_CLOCK. This flag means the source filter is using a private clock to generate time stamps. In this case, the audio renderer matches rates against the time stamps. (If the samples have no time stamps, however, the renderer ignores this flag.)
  • If GetPushSourceFlags returns no flags (zero), the audio renderer's behavior depends on the graph clock and whether the samples have time stamps:
    • If the audio renderer is not the graph clock, and the samples have time stamps, the audio renderer matches rates against the time stamps.
    • If the samples do not have time stamps, the audio renderer tries to match the rate of incoming audio data.
    • If the audio renderer is the graph clock, it tries to match the incoming data rate.

The reason for the last case is the following: If the audio renderer is the reference clock, and the source filter is using the same clock to generate time stamps, then the audio renderer cannot match rates against the time stamps. If it did, in effect it would be trying to match rates with itself, which could cause the clock to drift. Therefore, in this case the renderer matches the rate of incoming audio data.


Dynamic Graph Building

If you need to modify an existing filter graph, you can stop the graph, make the changes, and restart the graph. This is usually the best approach. However, under some circumstances, you might want to alter a graph while it is still running. For example:

  • The application inserts a video effects filter during playback.
  • A source filter switches media types midstream, possibly requiring a new decompression filter.
  • The application adds a new video stream to the graph.

These are all examples of dynamic graph building, a term that covers any kind of change to a filter graph while the graph continues to run. Dynamic graph building can be initiated by an application or by a filter in the graph. Three distinct scenarios are possible:

  • Dynamic Format Changes: A filter can change formats midstream, without the need to remove or replace any filters.
  • Dynamic Reconnection: Changing the graph by adding or removing filters.
  • Filter Chains: Adding, removing, and controlling chains of filters.


Dynamic Reconnection

In most DirectShow filters, pins cannot be reconnected while the graph is actively streaming data. The application must stop the graph before reconnecting the pins. However, some filters do support pin reconnections while the graph is running, a process known as dynamic reconnection. This can be done either by the application, or by a filter in the graph.

As an example, consider the following graph:

Dynamic graph-building diagram

One scenario for dynamic reconnection might be to remove Filter 2 from the graph, while the graph is running, and replace it with another filter. For this scenario to work, the following must be true:

  • The input pin on Filter 3 (pin D) must support the IPinConnection interface. This interface enables the pin to be reconnected without stopping the filter.
  • The output pin on Filter 1 (pin A) must be able to block the flow of media data while the reconnection occurs. No data can travel between pin A and pin D during the reconnection. Generally, this means the output pin must support the IPinFlowControl interface. However, if Filter 1 is the filter that initiates the reconnection, it might have some internal mechanism to block its own data flow.

The dynamic reconnection will involve the following steps:

  1. Block the data stream from pin A.
  2. Reconnect pin A to pin D, possibly through a new intermediate filter.
  3. Unblock pin A so that data starts to flow again.

Step 1. Block the Data Stream

To block the data stream, call IPinFlowControl::Block on pin A. This method can be called either asynchronously or synchronously. To call the method asynchronously, create a Win32 event object and pass the event handle to the Block method. The method will return immediately. Wait for the event to be signaled, using a function such as WaitForSingleObject. The pin signals the event when it has blocked the data flow. For example:

// Create an event
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (hEvent != NULL)
{
    // Block the data flow.
    hr = pFlowControl->Block(AM_PIN_FLOW_CONTROL_BLOCK, hEvent);
    if (SUCCEEDED(hr))
    {
        // Wait for the pin to finish.
        DWORD dwRes = WaitForSingleObject(hEvent, dwMilliseconds);
    }
}

To call the method synchronously, simply pass the value NULL instead of the event handle. Now the method will block until the operation completes. This may not happen until the pin is ready to deliver a new sample. If the filter is paused, this can take an arbitrary length of time. Therefore, do not make the synchronous call from your main application thread. Use a worker thread, or else call the method asynchronously.

Step 2. Reconnect the Pins

To reconnect the pins, query the Filter Graph Manager for the IGraphConfig interface and call either IGraphConfig::Reconnect or IGraphConfig::Reconfigure. The Reconnect method is simpler to use; it does the following:

  • Stops the intermediate filters (Filter 2 in the example) and removes them from the graph.
  • Adds new intermediate filters, if needed.
  • Connects all the pins.
  • Pauses or runs any new filters, to match the state of the graph.

The Reconnect method has several optional parameters that can be used to specify the media type for the pin connection and the intermediate filter to use. For example:

pGraph->AddFilter(pNewFilter, L"New Filter for the Graph");
pConfig->Reconnect(
    pPinA,      // Reconnect this output pin...
    pPinD,      // ... to this input pin.
    pMediaType, // Use this media type.
    pNewFilter, // Connect them through this filter.
    NULL,
    0);

For details, consult the reference page. If the Reconnect method is not flexible enough, you can use the Reconfigure method, which calls an application-defined callback method to reconnect the pins. To use this method, implement the IGraphConfigCallback interface in your application.

Before calling Reconfigure, block the data flow from the output pin, as described previously. Then push any data that is still pending in the section of the graph that you are reconnecting, as follows:

  1. Call IPinConnection::NotifyEndOfStream on the input pin furthest downstream in the reconnection chain (pin D in the example). Pass in a handle to a Win32 event.
  2. Call IPin::EndOfStream on the input pin that is immediately downstream from the output pin where you blocked the data flow. (In this example, the data flow was blocked at pin A, so you would call EndOfStream on pin B.)
  3. Wait for the event to be signaled. The input pin (pin D) signals the event when it receives the end-of-stream notification. This indicates that no data is traveling between the pins, and that the caller can safely reconnect the pins.

Note that the IGraphConfig::Reconnect method automatically handles the previous steps. You only need to perform these steps if you are using the Reconfigure method.

After the data is pushed through the graph, call Reconfigure and pass a pointer to your IGraphConfigCallback callback interface. The Filter Graph Manager will call the IGraphConfigCallback::Reconfigure method that you have provided.

Step 3. Unblock the Data Flow

After you have reconnected the pins, unblock the data flow by calling IPinFlowControl::Block with a value of zero for the first parameter.

Note If a dynamic reconnection is performed by a filter, there are some threading issues that you must be aware of. If the Filter Graph Manager tries to stop the filter, it can deadlock, because the graph waits for the filter to stop, while at the same time the filter may be waiting for data to be pushed through the graph. To prevent the possible deadlock, some of the methods described in this section take a handle to a Win32 event. The filter should signal the event if the Filter Graph Manager attempts to stop the filter. For more information, see IGraphConfig and IPinConnection.


Filter Chains

A filter chain is a sequence of filters that meets the following conditions:

  • Each filter in the chain has at most one connected input pin and one connected output pin.
  • It is possible to traverse every filter in the chain without traversing filters outside the chain.

For example, in the following diagram, filters A–B, C–D, and F–G–H are filter chains. Each subchain in F–G–H (F–G and G–H) is also a filter chain. A filter chain can consist of a single filter, so filters A, B, C, D, F, G, and H are also distinct filter chains. Filter E has two input connections, so any sequence of filters that includes filter E is not a filter chain.

Filter chain (Example 1)

The IFilterChain interface provides the following methods for controlling filter chains:

IFilterChain::StartChain | Starts a chain.
IFilterChain::StopChain | Stops a chain.
IFilterChain::PauseChain | Pauses a chain.
IFilterChain::RemoveChain | Removes a chain from the graph.

There is no specific method for adding a chain. To add a chain, insert the new filters using the IFilterGraph::AddFilter method. Then connect the filters by calling IGraphBuilder::Connect, IGraphBuilder::Render, or similar methods.

When the graph is running, a filter chain can switch between running and stopped. When the graph is paused, it can switch between paused and stopped. These are the only state transitions possible with filter chains.

Filter Chain Guidelines

When you use IFilterChain methods, it is important to make sure that the filters in the graph can support filter chaining operations. Otherwise, you might cause deadlocks or graph errors. Filters connected to the chain must function correctly after the chain changes state.

The best way to use IFilterChain is with a set of filters that you have designed specifically for chaining. Use the following guidelines to ensure that your filters are safe for filter chain operations. These points refer to the following diagram:

Filter chain (Example 2)

  • Before the filter chain's state changes, all data processing calls at the boundary of the filter chain must be completed. This rule applies to the methods IMemInputPin::Receive, IPin::NewSegment, and IPin::EndOfStream. Filters in the chain must return from calls to these methods made by filters outside the chain; and filters outside the chain must return from calls made by filters within the chain.

For example, in the previous diagram, filter B must complete any data processing calls from filter A, and filter E must finish any calls from filter D. If the pins expose the IPinFlowControl and IPinConnection interfaces, you can push the data through the graph by calling the IPinFlowControl::Block and IGraphConfig::PushThroughData methods, as described in Dynamic Reconnection. Filters might also support private methods for pushing the data.

  • Upstream filters must expect the chain's state to change. For example, in the previous diagram, suppose the chain is stopped but filter A calls IMemInputPin::Receive. The call fails and the response of filter A is to stop streaming. When the application restarts the chain, it has no effect because filter A is no longer streaming data.
  • Downstream filters must also expect the chain's state to change. If not, the downstream filter might block while it waits for samples that never arrive. For example, multiplexer (MUX) filters often require data from all of their input pins. Halting the flow of data from one input pin might block the other streams from processing. This can cause the graph to deadlock.
  • Each pin connection from a filter outside the chain to a filter within the chain should have its own allocator, which is not shared by other connections. When the chain changes state or is removed from the graph, the allocator might be decommitted. If other connections were using the same allocator, they can no longer process samples.
  • Do not remove a chain unless the filters connected to the chain support dynamic disconnection. Typically, the connected filters will support the IPinConnection or IPinFlowControl interface, but might support private interfaces instead.


Plug-in Distributors

Plug-in distributors (PIDs) are a way to extend the functionality of the filter graph manager. A plug-in distributor is a COM object that the filter graph manager aggregates at run time. Applications obtain access to the PID through the filter graph manager.

When the filter graph manager is queried for an interface that it does not support, it searches the registry for a key with the following form:

HKEY_CLASSES_ROOT\Interface\IID\Distributor

IID is a string containing the interface identifier. If the registry entry exists, the value of the entry defines the class identifier (CLSID) of a PID that supports the interface. The filter graph manager aggregates the PID and returns an interface pointer, thereby acting as the outer IUnknown for the PID. When the application calls methods on the interface, it is actually calling them on the PID. However, the existence of the PID is transparent to the application.

The term distributor stems from the fact that a PID can query its outer IUnknown pointer for interfaces on the filter graph manager. By calling the IFilterGraph::EnumFilters method, the PID can enumerate the filters in the graph and distribute method calls to those filters. In this way, a PID can serve as a single control point for the application to call methods on filters.

When the filter graph manager aggregates a PID, it queries the PID for the IDistributorNotify interface. If the PID supports this interface, the filter graph manager uses it to notify the PID about changes in the graph:

  • When the filter graph switches between run, paused, and stopped states, it calls IDistributorNotify::Run, IDistributorNotify::Pause, or IDistributorNotify::Stop.
  • When a reference clock is set, the filter graph manager calls IDistributorNotify::SetSyncSource.
  • When filters are added or removed, or pin connections are changed, the filter graph manager calls IDistributorNotify::NotifyGraphChange.

To implement a custom PID, create a COM object that supports aggregation. It must support an interface that the filter graph manager does not already support. Optionally, it can support the IDistributorNotify interface.

If the PID obtains any interface pointers from the filter graph manager, it should release them immediately. Otherwise, it might create a circular reference count, which could prevent the filter graph manager from being destroyed. Holding a reference count on the filter graph manager is unnecessary in any case, because the filter graph manager controls the PID's lifetime.

Because a PID is designed specifically for aggregation by the filter graph manager, you might want to enforce this in the PID's constructor method. Check whether the outer IUnknown pointer is NULL, and if so, return the error code VFW_E_NEED_OWNER. (See Error and Success Codes.) Also, to prevent other objects from aggregating the PID, you can query the outer IUnknown pointer for the IGraphBuilder interface. Return an error code if the object does not expose IGraphBuilder.


Using DirectShow

This section contains the following topics:

  • Simulating Graph Building with GraphEdit
  • Basic DirectShow Tasks
  • Audio Capture
  • Video Capture
  • DirectShow Editing Services
  • DVD Applications
  • MPEG-2 Support in DirectShow
  • Windows Media Applications
  • Microsoft TV Technologies
  • Using the Video Mixing Renderer
  • Using the Stream Buffer Engine
  • Writing DirectShow Filters
  • Encoder and Decoder Development


Simulating Graph Building with GraphEdit

The Microsoft® DirectX® SDK provides a debugging utility called GraphEdit, which you can use to create and test filter graphs.

This article contains the following sections:

  • Overview of GraphEdit
  • Using GraphEdit
  • Loading a Graph From an External Process
  • Saving a Filter Graph to a GraphEdit File
  • Loading a GraphEdit File Programmatically

See Also

  • GraphEdit File Format


Overview of GraphEdit

GraphEdit is a visual tool for building filter graphs. With GraphEdit, you can experiment with a filter graph before you write any application code. You can also load a filter graph that your application creates, to verify that your application is building the correct graph. If you develop a custom filter, GraphEdit provides a quick way to test it: Simply load a graph with your custom filter and try running the graph. If you are new to DirectShow, GraphEdit is a good way to become familiar with filter graphs and the DirectShow architecture.

The following illustration shows how GraphEdit represents a simple filter graph.

Simple filter graph in GraphEdit

Each filter is represented as a rectangle. Smaller squares along the edges of the filters represent pins. Input pins are on the left side of the filter, and output pins are on the right side. The arrows represent the connections between pins.

With GraphEdit, you can:

  • Create and modify filter graphs using a visual, drag-and-drop interface.
  • Simulate programmatic calls to build a graph, such as IGraphBuilder::RenderFile.
  • Run, pause, stop, and seek a graph.
  • See what filters are registered on your computer, and view registry information for each filter.
  • View filter property pages.
  • View the media types of pin connections.


Using GraphEdit

When you install the DirectX SDK, GraphEdit appears in the Start menu under Microsoft DirectX SDK, in the submenu DX Utilities. The executable file is GraphEdt.exe.

What follows are brief descriptions of some things you can do using GraphEdit. For more detailed information about these features—and others—consult the GraphEdit application help.

Build a File Playback Graph

GraphEdit can build a filter graph for file playback. This feature is equivalent to calling the IGraphBuilder::RenderFile method in an application. From the File menu, click Render Media File. GraphEdit displays an Open File dialog box. Select a multimedia file and click Open. GraphEdit builds a filter graph to play the file you've selected.

You can also render a media file located at a URL. From the File menu, click Render URL. GraphEdit displays a dialog box in which to type the URL.

Build a Custom Filter Graph

GraphEdit can build a custom filter graph, using any of the filters registered on your system. From the Graph menu, click Insert Filters. A dialog box appears with a list of the filters on your system, organized by filter category. GraphEdit builds this list from information in the registry. The following illustration shows the dialog box.

Which filters do you want to insert?

To add a filter to the graph, select the name of the filter and click the Insert Filters button, or double-click the filter name. After you have added the filters, you can connect two filters by dragging the mouse from one filter's output pin to another filter's input pin. If the pins accept the connection, GraphEdit draws an arrow connecting them.

Connecting two filters

Run the Graph

Once you have built a filter graph in Graph Edit, you can run the graph to see whether it works as you expect. The Graph menu contains the menu commands Play, Pause, and Stop. These commands invoke to the IMediaControl methods Run, Pause, and Stop, respectively. The GraphEdit toolbar has buttons for these commands, as well:

Pause, Play, and Stop buttons

Note The GraphEdit Stop command first pauses the graph and seeks to time zero (assuming the graph is seekable). For file playback, this action resets the video window to the first frame. Then GraphEdit calls IMediaControl::Stop.

If the graph is seekable, you can seek it by dragging the slider bar that appears below the toolbar. Dragging the slider bar invokes the IMediaSeeking::SetPositions method.

View Property Pages

Some filters support custom property pages, which provide a user interface for setting properties on the filter. To view a filter's property page in GraphEdit, right-click the filter and select Properties from the pop-up window. GraphEdit displays a property page that contains the property sheets defined by the filter (if any). In addition, GraphEdit includes a property sheet for each pin on the filter. The pin property sheets are defined by GraphEdit, not by the filter. If the pin is connected, the pin property sheet displays the media type for the connection. Otherwise, it lists the pin's preferred media types.


Loading a Graph From an External Process

GraphEdit can load a filter graph created by an external process. With this feature, you can see exactly what filter graph your application builds, with only a minimal amount of additional code in your application.

Note This feature requires Windows 2000, or Windows XP.

The application must register the filter graph instance in the Running Object Table (ROT). The ROT is a globally accessible look-up table that keeps track of running objects. Objects are registered in the ROT by moniker. To connect to the graph, GraphEdit searches the ROT for monikers whose display name matches a particular format:

!FilterGraph X pid Y

where X is the hexadecimal address of the Filter Graph Manager, and Y is the process id, also in hexadecimal.

When your application first creates the filter graph, call the following function:

HRESULT AddToRot(IUnknown *pUnkGraph, DWORD *pdwRegister)
{
    IMoniker * pMoniker;
    IRunningObjectTable *pROT;
    if (FAILED(GetRunningObjectTable(0, &pROT))) {
        return E_FAIL;
    }
    WCHAR wsz[256];
    wsprintfW(wsz, L"FilterGraph %08x pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId());
    HRESULT hr = CreateItemMoniker(L"!", wsz, &pMoniker);
    if (SUCCEEDED(hr)) {
        hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, pUnkGraph,
            pMoniker, pdwRegister);
        pMoniker->Release();
    }
    pROT->Release();
    return hr;
}

This function creates a moniker and a new ROT entry for the filter graph. The first parameter is a pointer to the filter graph. The second parameter receives a value that identifies the new ROT entry. Before the application releases the filter graph, call the following function to remove the ROT entry. The pdwRegister parameter is the identifier returned by the AddToRot function.

void RemoveFromRot(DWORD pdwRegister)
{
    IRunningObjectTable *pROT;
    if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) {
        pROT->Revoke(pdwRegister);
        pROT->Release();
    }
}

The following code example shows how to call these functions. In this example, the code that adds and removes ROT entries is conditionally compiled, so that it is included only in debug builds.

IGraphBuilder *pGraph;
DWORD dwRegister;

// Create the filter graph manager.
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                        IID_IGraphBuilder, (void **)&pGraph);
#ifdef _DEBUG
hr = AddToRot(pGraph, &dwRegister);
#endif

// Rest of the application (not shown).

#ifdef _DEBUG
RemoveFromRot(dwRegister);
#endif
pGraph->Release();

To view the filter graph in GraphEdit, run your application and GraphEdit at the same time. In the GraphEdit File menu, click Connect. In the Connect To Graph dialog box, select the process id (pid) of your application and click OK. GraphEdit loads the filter graph and displays it. Don't use any other GraphEdit features on this graph—it might cause unexpected results. For example, don't add or remove filters, or stop and start the graph. Close GraphEdit before exiting your application.

Note Your application might hit various asserts when it exits. You can ignore these.

The following illustration shows the Connect To Graph dialog box.

Connect to graph

When GraphEdit loads the graph, it executes in the context of the target application. Therefore, GraphEdit might block because it is waiting for the thread. For example, this can occur if you are stepping through your code in the debugger.

This feature should be used only in debug builds of your application, not retail builds, because it enables other applications to view or control the filter graph.

Connecting to a Remote Graph from the Command Line

GraphEdit supports a command-line option to load a remote graph automatically on startup. The syntax is:

GraphEdt -a moniker

where moniker is a moniker created using the AddToRot function, described previously.


Saving a Filter Graph to a GraphEdit File

The following code example shows how to save a filter graph to a GraphEdit (.grf) file. This can be useful for debugging your applications.

HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath)
{
    const WCHAR wszStreamName[] = L"ActiveMovieGraph";
    HRESULT hr;

    IStorage *pStorage = NULL;
    hr = StgCreateDocfile(
        wszPath,
        STGM_CREATE | STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE,
        0, &pStorage);
    if(FAILED(hr))
    {
        return hr;
    }

    IStream *pStream;
    hr = pStorage->CreateStream(
        wszStreamName,
        STGM_WRITE | STGM_CREATE | STGM_SHARE_EXCLUSIVE,
        0, 0, &pStream);
    if (FAILED(hr))
    {
        pStorage->Release();
        return hr;
    }

    IPersistStream *pPersist = NULL;
    pGraph->QueryInterface(IID_IPersistStream, (void**)&pPersist);
    hr = pPersist->Save(pStream, TRUE);
    pStream->Release();
    pPersist->Release();
    if (SUCCEEDED(hr))
    {
        hr = pStorage->Commit(STGC_DEFAULT);
    }
    pStorage->Release();
    return hr;
}

For example, the following code builds a file playback graph and saves it to a file named MyGraph.grf:

void __cdecl main(void)
{
    HRESULT hr;
    IGraphBuilder *pGraph;
    CoInitialize(NULL);

    // Create the Filter Graph Manager and render a file.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
        IID_IGraphBuilder, reinterpret_cast<void**>(&pGraph));
    hr = pGraph->RenderFile(L"C:\\Video.avi", NULL);

    if (SUCCEEDED(hr))
    {
        hr = SaveGraphFile(pGraph, L"C:\\MyGraph.grf");
    }

    pGraph->Release();
    CoUninitialize();
}

For more information about the StgCreateDocfile function, see the Platform SDK documentation.


Loading a GraphEdit File Programmatically

An application can use the IPersistStream interface to load a GraphEdit (.grf) file. Use the following code:

HRESULT LoadGraphFile(IGraphBuilder *pGraph, const WCHAR* wszName)
{
    IStorage *pStorage = 0;
    if (S_OK != StgIsStorageFile(wszName))
    {
        return E_FAIL;
    }
    HRESULT hr = StgOpenStorage(wszName, 0,
        STGM_TRANSACTED | STGM_READ | STGM_SHARE_DENY_WRITE,
        0, 0, &pStorage);
    if (FAILED(hr))
    {
        return hr;
    }
    IPersistStream *pPersistStream = 0;
    hr = pGraph->QueryInterface(IID_IPersistStream,
             reinterpret_cast<void**>(&pPersistStream));
    if (SUCCEEDED(hr))
    {
        IStream *pStream = 0;
        hr = pStorage->OpenStream(L"ActiveMovieGraph", 0,
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
        if(SUCCEEDED(hr))
        {
            hr = pPersistStream->Load(pStream);
            pStream->Release();
        }
        pPersistStream->Release();
    }
    pStorage->Release();
    return hr;
}

It should be noted that GraphEdit files are intended only for testing and debugging. They are not meant for use by end-user applications.

For more information about the StgIsStorageFile and StgOpenStorage functions, see the Platform SDK documentation.


Basic DirectShow Tasks

This section describes some basic tasks in DirectShow. These tasks are relevant in many application scenarios; they are not specific to any one domain. This section contains the following topics:

  • Video Rendering
  • Responding to Events
  • Enumerating Devices and Filters
  • Enumerating Objects in a Filter Graph
  • General Graph-Building Techniques
  • Seeking the Filter Graph
  • Setting the Graph Clock
  • Debugging in DirectShow


Video Rendering

This section provides an overview of video rendering in DirectShow. It contains the following topics:

  • About Video Rendering in DirectShow
  • Setting the Video Window
  • Using Windowless Mode

See Also

  • Using the Video Mixing Renderer


About Video Rendering in DirectShow

DirectShow provides several filters that render video:

  • Video Renderer filter. This filter is available for all platforms that support DirectX, and has no particular system requirements. The Video Renderer uses DirectDraw whenever possible to render the video; otherwise, it uses GDI. This filter is the default video renderer on platforms earlier than Windows XP.
  • Video Mixing Renderer Filter 7 (VMR-7). The VMR-7 is available on Windows XP, where it is the default video renderer. The VMR-7 always uses DirectDraw 7 for rendering. It provides many powerful features not available in the older Video Renderer filter, including a plug-in model where the application controls the DirectDraw surfaces used for rendering.
  • Video Mixing Renderer Filter 9 (VMR-9). The VMR-9 is a newer version of the Video Mixing Renderer that uses Direct3D 9 for rendering. It is available for all platforms that support DirectX. It is not the default renderer, however, because it has higher system requirements than the Video Renderer filter.

Generally, the VMR-9 is preferred whenever possible, because it provides the best features, using the newest graphics APIs. For more information about using the VMR-7 and VMR-9 filters, see Using the Video Mixing Renderer.

Windowed Mode and Windowless Mode

A DirectShow video renderer can operate in either windowed mode or windowless mode.

  • In windowed mode, the renderer creates its own window to display the video. Typically you will make this window the child of an application window. For more information, see Setting the Video Window.
  • In windowless mode, the renderer draws the video directly onto an application window. It does not create its own window. For more information about this mode, see Using Windowless Mode.

The Video Renderer filter supports windowed mode only. The VMR-7 and VMR-9 filters support both modes. They default to windowed mode for backward compatibility.


Setting the Video Window

In windowed mode, the video renderer creates a window, onto which it paints the video frames. Most of the time, you will want to attach this window to one of your own application windows.

Note The Video Renderer filter always uses windowed mode. The VMR-7 and VMR-9 both default to windowed mode, but they also support windowless mode.

Unless you specify otherwise, the video renderer's window is a top-level window with its own borders and title bar. To make the video appear within your own application window, make the video window a child of the application window. This is done by setting the video window's owner, style, and position, through the IVideoWindow interface.

Before starting playback, query the Filter Graph Manager for the IVideoWindow interface:

IVideoWindow *pVidWin = NULL;
pGraph->QueryInterface(IID_IVideoWindow, (void **)&g_pVidWin);

Call the IVideoWindow::put_Owner method with a handle to your application window. This method takes a variable of type OAHWND, so cast the handle to this type:

pVidWin->put_Owner((OAHWND)hwnd);

Change the style of the video window by calling the IVideoWindow::put_WindowStyle method:

pVidWin->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);

The WS_CHILD flag sets the window to be a child window, and the WS_CLIPSIBLINGS flag prevents the window from drawing inside the client area of another child window.

To set the position of the video relative to your window's client area, call the IVideoWindow::SetWindowPosition method. This method takes a rectangle that specifies the left edge, top edge, width, and height of the video window. For example, the following code stretches the video window to fit the entire client area of the parent window:

RECT grc;
GetClientRect(hwnd, &grc);
pVidWin->SetWindowPosition(0, 0, grc.right, grc.bottom);

You can also get the native size of the video by calling the IBasicVideo::GetVideoSize method on the Filter Graph Manager. You can use that information to scale the video and keep the correct aspect ratio.

Before the application exits, stop the graph and reset the video window's owner to NULL. Otherwise, window messages might be sent to the wrong window, which is likely to cause errors. Also, hide video window, or else you might see a video image flicker on the screen momentarily:

pControl->Stop();
pVidWin->put_Visible(OAFALSE);
pVidWin->put_Owner(NULL);

See Also

  • Video Rendering


Using Windowless Mode

The Video Mixing Renderer filters (VMR-7 and VMR-9) both support windowless mode, which represents a major improvement over the IVideoWindow interface. This article describes the differences between windowless mode and windowed mode, and how to use windowless mode.

To remain backward-compatible with existing applications, the VMR defaults to windowed mode. In windowed mode, the renderer creates its own window to display the video. Typically the application sets the video window to be a child of the application window. The existence of a separate video window causes some problems, however:

  • Most importantly, there is a potential for deadlocks if window messages are sent between threads.
  • The Filter Graph Manager must forward certain window messages, such as WM_PAINT, to the Video Renderer. The application must use the Filter Graph Manager's implementation of IVideoWindow (and not the Video Renderer's), so that the Filter Graph Manager maintains the correct internal state.
  • To receive mouse or keyboard events from the video window, the application must set a "message drain," causing the video window to forward these messages to the application.
  • To prevent clipping problems, the video window must have the right window styles.

Windowless mode avoids these problems by having the VMR draw directly on the application window's client area, using DirectDraw to clip the video rectangle. Windowless mode significantly reduces the chance of deadlocks. Also, the application does not have to set the owner window or the window styles. In fact, when the VMR is in windowless mode, it does not even expose the IVideoWindow interface, which is no longer needed.

To use windowless mode, you must explicitly configure the VMR. However, you will find that is more flexible and easier to use than windowed mode.

Configure the VMR for Windowless Mode

To override the VMR's default behavior, configure the VMR before building the filter graph:

  1. Create the Filter Graph Manager.
  2. Create the VMR and add it to the filter graph.
  3. Call IVMRFilterConfig::SetRenderingMode on the VMR with the VMRMode_Windowless flag.
  4. Call IVMRWindowlessControl::SetVideoClippingWindow on the VMR. Specify a handle to the window where the video should appear.

Now build the rest of the filter graph by calling IGraphBuilder::RenderFile or other graph-building methods. The Filter Graph Manager automatically uses the instance of the VMR that you added to the graph. (For details on why this happens, see Intelligent Connect.)

The following code shows a helper function that creates the VMR, adds it to the graph, and sets up windowless mode.

HRESULT InitWindowlessVMR(
    HWND hwndApp,                  // Window to hold the video.
    IGraphBuilder* pGraph,         // Pointer to the Filter Graph Manager.
    IVMRWindowlessControl** ppWc,  // Receives a pointer to the VMR.
    )
{
    if (!pGraph || !ppWc) return E_POINTER;
    IBaseFilter* pVmr = NULL;
    IVMRWindowlessControl* pWc = NULL;
    // Create the VMR.
    HRESULT hr = CoCreateInstance(CLSID_VideoMixingRenderer, NULL,
        CLSCTX_INPROC, IID_IBaseFilter, (void**)&pVmr);
    if (FAILED(hr))
    {
        return hr;
    }

    // Add the VMR to the filter graph.
    hr = pGraph->AddFilter(pVmr, L"Video Mixing Renderer");
    if (FAILED(hr))
    {
        pVmr->Release();
        return hr;
    }
    // Set the rendering mode.
    IVMRFilterConfig* pConfig;
    hr = pVmr->QueryInterface(IID_IVMRFilterConfig, (void**)&pConfig);
    if (SUCCEEDED(hr))
    {
        hr = pConfig->SetRenderingMode(VMRMode_Windowless);
        pConfig->Release();
    }
    if (SUCCEEDED(hr))
    {
        // Set the window.
        hr = pVmr->QueryInterface(IID_IVMRWindowlessControl, (void**)&pWc);
        if( SUCCEEDED(hr))
        {
            hr = pWc->SetVideoClippingWindow(hwndApp);
            if (SUCCEEDED(hr))
            {
                *ppWc = pWc; // Return this as an AddRef'd pointer.
            }
            else
            {
                // An error occurred, so release the interface.
                pWc->Release();
            }
        }
    }
    pVmr->Release();
    return hr;
}

This function assumes that are displaying only one video stream and are not mixing a static bitmap over the video. For details, see VMR Windowless Mode. You would call this function as follows:

IVMRWindowlessControl *pWc = NULL;
hr = InitWindowlessVMR(hwnd, pGraph, &g_pWc);
if (SUCCEEDED(hr))
{
    // Build the graph. For example:
    pGraph->RenderFile(wszMyFileName, 0);
    // Release the VMR interface when you are done.
    pWc->Release();
}

Position the Video

After configuring the VMR, the next step is to set the position of the video. There are two rectangles to consider, the source rectangle and the destination rectangle. The source rectangle defines which portion of the video to display. The destination rectangle specifies the region in the window's client area that will contain the video. The VMR crops the video image to the source rectangle and stretches the cropped image to fit the destination rectangle.

Call the IVMRWindowlessControl::SetVideoPosition method to specify both rectangles. The source rectangle must be equal to or smaller than the native video size; you can use the IVMRWindowlessControl::GetNativeVideoSize method to get the native video size.

For example, the following code sets the source rectangle equal to the upper-left quadrant of the video image, and the destination rectangle equal to the upper-left corner of the window:

// Find the native video size.
long lWidth, lHeight;
HRESULT hr = g_pWc->GetNativeVideoSize(&lWidth, &lHeight, NULL, NULL);
if (SUCCEEDED(hr))
{
    RECT rcSrc, rcDest;
    // Set the source rectangle.
    SetRect(&rcSrc, 0, 0, lWidth/2, lHeight/2);

    // Get the window client area.
    GetClientRect(hwnd, &rcDest);
    // Set the destination rectangle.
    SetRect(&rcDest, 0, 0, rcDest.right/2, rcDest.bottom/2);

    // Set the video position.
    hr = g_pWc->SetVideoPosition(&rcSrc, &rcDest);
}

Handle Window Messages

Because the VMR does not have its own window, you must inform it when the video needs to be repainted or modified.

  • When you receive a WM_PAINT message, call IVMRWindowlessControl::RepaintVideo to repaint the image.
  • When you receive a WM_DISPLAYCHANGE message, call IVMRWindowlessControl::DisplayModeChanged. The VMR takes any actions that are needed to display the video at the new resolution or color depth.
  • When you receive a WM_SIZE message, recalculate the position of the video and call SetVideoPosition again if necessary.

The following example shows a WM_PAINT message handler. It paints a region defined by the client rectangle minus the video rectangle. Do not draw onto the video rectangle, because the VMR will paint over it, causing flickering. For the same reason, do not set a background brush in your window class.

void OnPaint(HWND hwnd)
{
    PAINTSTRUCT ps;
    HDC         hdc;
    RECT        rcClient;
    GetClientRect(hwnd, &rcClient);
    hdc = BeginPaint(hwnd, &ps);
    if (g_pWc != NULL)
    {
        // Find the region where the application can paint by subtracting
        // the video destination rectangle from the client area.
        // (Assume that g_rcDest was calculated previously.)
        HRGN rgnClient = CreateRectRgnIndirect(&rcClient);
        HRGN rgnVideo  = CreateRectRgnIndirect(&g_rcDest);
        CombineRgn(rgnClient, rgnClient, rgnVideo, RGN_DIFF);

        // Paint on window.
        HBRUSH hbr = GetSysColorBrush(COLOR_BTNFACE);
        FillRgn(hdc, rgnClient, hbr);

        // Clean up.
        DeleteObject(hbr);
        DeleteObject(rgnClient);
        DeleteObject(rgnVideo);

        // Request the VMR to paint the video.
        HRESULT hr = g_pWc->RepaintVideo(hwnd, hdc);
    }
    else  // There is no video, so paint the whole client area.
    {
        FillRect(hdc, &rc2, (HBRUSH)(COLOR_BTNFACE + 1));
    }
    EndPaint(hwnd, &ps);
}

Although you must respond to WM_PAINT messages, there is nothing you need to do between WM_PAINT messages to update the video. As this example shows, windowless mode lets you treat the video image simply as a self-drawing region on the window.

See Also

  • Using the Video Mixing Renderer
  • Video Rendering


Responding to Events

This article describes how to respond to events that occur in a filter graph.

How Event Notification Works

While a DirectShow application is running, events can occur within the filter graph. For example, a filter might encounter a streaming error. Filters alert the Filter Graph Manager by sending events, which consist of an event code and two event parameters. The event code indicates the type of event, and the event parameters supply additional information. The meaning of the parameters depends on the event code. For a complete list of event codes, see Event Notification Codes.

Some events are handled silently by the Filter Graph Manager, without the application being notified. Other events are placed on a queue for the application. Depending on the application, there are various events that you might need to handle. This article focuses on three events that are very common:

  • The EC_COMPLETE event indicates that playback has completed normally.
  • The EC_USERABORT event indicates that the user has interrupted playback. Video renderers send this event if the user closes the video window.
  • The EC_ERRORABORT event indicates that an error has caused playback to halt.

Using Event Notification

An application can instruct the Filter Graph Manager to send a Windows message to a designated window whenever a new event occurs. This enables the application to respond inside the window's message loop. First, define the message that will be sent to the application window. Applications can use message numbers in the range from WM_APP through 0xBFFF as private messages:

#define WM_GRAPHNOTIFY  WM_APP + 1

Next, query the Filter Graph Manager for the IMediaEventEx interface and call the IMediaEventEx::SetNotifyWindow method:

IMediaEventEx *g_pEvent = NULL;
g_pGraph->QueryInterface(IID_IMediaEventEx, (void **)&g_pEvent);
g_pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);

This method designates the specified window (g_hwnd) as the recipient of the message. Call the method after you create the filter graph, but before running the graph.

WM_GRAPHNOTIFY is an ordinary Windows message. Whenever the Filter Graph Manager puts a new event on the event queue, it posts a WM_GRAPHNOTIFY message to the designated application window. The message's lParam parameter is equal to the third parameter in SetNotifyWindow. This parameter enables you to send instance data with the message. The window message's wParam parameter is always zero.

In your application's WindowProc function, add a case statement for the WM_GRAPHNOTIFY message:

case WM_GRAPHNOTIFY:
    HandleGraphEvent();
    break;

In the event handler function, call the IMediaEvent::GetEvent method to retrieve events from the queue:

void HandleGraphEvent()
{
    // Disregard if we don't have an IMediaEventEx pointer.
    if (g_pEvent == NULL)
    {
        return;
    }
    // Get all the events
    long evCode, param1, param2;
    HRESULT hr;
    while (SUCCEEDED(g_pEvent->GetEvent(&evCode, &param1, &param2, 0)))
    {
        g_pEvent->FreeEventParams(evCode, param1, param2);
        switch (evCode)
        {
        case EC_COMPLETE:  // Fall through.
        case EC_USERABORT: // Fall through.
        case EC_ERRORABORT:
            CleanUp();
            PostQuitMessage(0);
            return;
        }
    }
}

The GetEvent method retrieves the event code and the two event parameters. The fourth GetEvent parameter specifies the length of time to wait for an event, in milliseconds. Because the application calls this method in response to a WM_GRAPHNOTIFY message, the event is already queued. Therefore, we set the time-out value to zero.

Event notification and the message loop are both asynchronous, so the queue might hold more than one event by the time your application responds to the message. Also, the Filter Graph Manager can remove certain events from the queue, if they become invalid. Therefore, you should call GetEvent until it returns a failure code, indicating the queue is empty.

In this example, the application responds to EC_COMPLETE, EC_USERABORT, and EC_ERRORABORT by invoking the application-defined CleanUp function, which causes the application to quit gracefully. The example ignores the two event parameters. After you retrieve an event, call IMediaEvent::FreeEventParams to any free resources associated with the event parameters.

Note that an EC_COMPLETE event does not cause the filter graph to stop. The application can either stop or pause the graph. If you stop the graph, filters release any resources they are holding. If you pause the graph, filters continue to hold resources. Also, when a video renderer pauses, it displays a static image of the most recent frame.

Before you release the IMediaEventEx pointer, cancel event notification by calling SetNotifyWindow with a NULL pointer:

// Disable event notification before releasing the graph.
g_pEvent->SetNotifyWindow(NULL, 0, 0);
g_pEvent->Release();
g_pEvent = NULL;

In the WM_GRAPHNOTIFY message handler, check the IMediaEventEx pointer before calling GetEvent:

if (g_pEvent == NULL) return;

This prevents a possible error that can occur if the application receives the event notification after releasing the pointer.

See Also

  • Event Notification in DirectShow


Enumerating Devices and Filters

Sometimes an application needs to locate a particular filter on the user's system. For example, a video capture application might display a list of available capture devices. Because Microsoft® DirectShow® uses a component-based architecture, you cannot know at design time which filters are installed on the user's system. This is particularly true for filters that represent hardware devices. DirectShow provides two components that locate registered filters:

  • The System Device Enumerator finds filters by their category.
  • The Filter Mapper finds filters according to search criteria supplied by the application.

The enumerators discussed in this section follow the standard form used by COM enumeration interfaces. For more information, see the IEnumXXXX topic in the Microsoft Platform Software Development Kit (SDK).

This section contains the following topics:

  • Using the System Device Enumerator
  • Using the Filter Mapper


Using the System Device Enumerator

The System Device Enumerator provides a uniform way to enumerate, by category, the filters registered on a user's system. Moreover, it differentiates between individual hardware devices, even if the same filter supports them. This is particularly useful for devices that use the Windows Driver Model (WDM) and the KSProxy filter. For example, the user might have several WDM video capture devices, all supported by the same filter. The System Device Enumerator treats them as separate device instances.

The System Device Enumerator works by creating an enumerator for a specific category, such as audio capture or video compression. The category enumerator returns a unique moniker for each device in the category. The category enumerator automatically includes any relevant Plug and Play devices in the category. For a list of categories, see Filter Categories.

To use the System Device Enumerator, do the following:

  1. Create the system device enumerator by calling CoCreateInstance. The class identifier (CLSID) is CLSID_SystemDeviceEnum.
  2. Obtain a category enumerator by calling ICreateDevEnum::CreateClassEnumerator with the CLSID of the desired category. This method returns an IEnumMoniker interface pointer. If the category is empty (or does not exist), the method returns S_FALSE rather than an error code. If so, the returned IEnumMoniker pointer is NULL and dereferencing it will cause an exception. Therefore, explicitly test for S_OK when you call CreateClassEnumerator, instead of calling the usual SUCCEEDED macro.
  3. Use the IEnumMoniker::Next method to enumerate each moniker. This method returns an IMoniker interface pointer. When the Next method reaches the end of the enumeration, it also returns S_FALSE, so again check for S_OK.
  4. To retrieve the friendly name of the device (for example, to display in the user interface), call the IMoniker::BindToStorage method.
  5. To create and initialize the DirectShow filter that manages the device, call IMoniker::BindToObject on the moniker. Call IFilterGraph::AddFilter to add the filter to the graph.

The following diagram illustrates this process.

The following example shows how to enumerate the video compressors installed on the user's system. For brevity, the example performs minimal error checking.

// Create the System Device Enumerator.
HRESULT hr;
ICreateDevEnum *pSysDevEnum = NULL;
hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
    IID_ICreateDevEnum, (void **)&pSysDevEnum);
if (FAILED(hr))
{
    return hr;
}

// Obtain a class enumerator for the video compressor category.
IEnumMoniker *pEnumCat = NULL;
hr = pSysDevEnum->CreateClassEnumerator(CLSID_VideoCompressorCategory, &pEnumCat, 0);

if (hr == S_OK)
{
    // Enumerate the monikers.
    IMoniker *pMoniker = NULL;
    ULONG cFetched;
    while(pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK)
    {
        IPropertyBag *pPropBag;
        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
            (void **)&pPropBag);
        if (SUCCEEDED(hr))
        {
            // To retrieve the filter's friendly name, do the following:
            VARIANT varName;
            VariantInit(&varName);
            hr = pPropBag->Read(L"FriendlyName", &varName, 0);
            if (SUCCEEDED(hr))
            {
                // Display the name in your UI somehow.
            }
            VariantClear(&varName);

            // To create an instance of the filter, do the following:
            IBaseFilter *pFilter;
            hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter,
                (void**)&pFilter);
            // Now add the filter to the graph.
            //Remember to release pFilter later.
            pPropBag->Release();
        }
        pMoniker->Release();
    }
    pEnumCat->Release();
}
pSysDevEnum->Release();

Device Monikers

The IMoniker::GetDisplayName method returns the display name of the moniker. For device monikers, you can pass the display name to the IFilterGraph2::AddSourceFilterForMoniker method to create a capture filter for the device:

LPOLESTR strName = NULL;
IBaseFilter pSrc = NULL;
hr = pMoniker->GetDisplayName(NULL, NULL, &strName);
if (SUCCEEDED(hr))
{
    // Query the Filter Graph Manager for IFilterGraph2.
    IFilterGraph2 *pFG2 = NULL;
    hr = pGraph->QueryInterface(IID_IFilterGraph2, (void**)&pFG2);
    if (SUCCEEDED(hr))
    {
        hr = pFG2->AddSourceFilterForMoniker(pMoniker, 0, L"Source", &pSrc);
        pFG2->Release();
    }
    CoTaskMemFree(strName);
}

// If successful, remember to release pSrc.

Although the display name is readable, you would not typically display it to an end-user. Get the friendly name from the property bag instead, as described previously.

The IMoniker::ParseDisplayName method or the MkParseDisplayName function can be used to create a default device moniker for a given filter category. Use a display name with the form @device:*:{category-clsid}, where category-clsid is the string representation of the category GUID. The default moniker is the first moniker returned by the device enumerator for that category.

For example, the following code creates the default moniker for the video capture category:

// Video capture category
WCHAR szMon[] = L"@device:*:{860BB310-5D01-11d0-BD3B-00A0C911CE86}";
IBindCtx *pBindCtx;
hr = CreateBindCtx(0, &pBindCtx);

ULONG chEaten = 0;
IMoniker *pMoniker = 0;
hr = MkParseDisplayName(pBindCtx, szMon, &chEaten, &pMoniker);
pBindCtx->Release();
if (SUCCEEDED(hr))
{
    // Get the display name, or bind to a DirectShow filter.
    pMoniker->Release();
}


Using the Filter Mapper

The Filter Mapper is a COM object that enumerates filters based on various search criteria. The Filter Mapper is less efficient than the System Device Enumerator, so if you need filters from a particular category, you should use the System Device Enumerator. But if you need to locate a filter that supports a certain combination of media types, but does not fall into a clear-cut category, you might need to use the Filter Mapper. (An example would be a renderer filter or a decoder filter.)

The Filter Mapper exposes the IFilterMapper2 interface. To search for a filter, call the IFilterMapper2::EnumMatchingFilters method. This method takes several parameters that define the search criteria, and returns an enumerator for the matching filters. The enumerator supports the IEnumMoniker interface, and supplies a unique moniker for each matching filter.

The following example enumerates filters that accept digital video (DV) input and have at least one output pin, of any media type. (The DV Video Decoder filter matches these criteria.)

IFilterMapper2 *pMapper = NULL;
IEnumMoniker *pEnum = NULL;

hr = CoCreateInstance(CLSID_FilterMapper2,
    NULL, CLSCTX_INPROC, IID_IFilterMapper2,
    (void **) &pMapper);

if (FAILED(hr))
{
    // Error handling omitted for clarity.
}

GUID arrayInTypes[2];
arrayInTypes[0] = MEDIATYPE_Video;
arrayInTypes[1] = MEDIASUBTYPE_dvsd;

hr = pMapper->EnumMatchingFilters(
        &pEnum,
        0,                  // Reserved.
        TRUE,               // Use exact match?
        MERIT_DO_NOT_USE+1, // Minimum merit.
        TRUE,               // At least one input pin?
        1,                  // Number of major type/subtype pairs for input.
        arrayInTypes,       // Array of major type/subtype pairs for input.
        NULL,               // Input medium.
        NULL,               // Input pin category.
        FALSE,              // Must be a renderer?
        TRUE,               // At least one output pin?
        0,                  // Number of major type/subtype pairs for output.
        NULL,               // Array of major type/subtype pairs for output.
        NULL,               // Output medium.
        NULL);              // Output pin category.

// Enumerate the monikers.
IMoniker *pMoniker;
ULONG cFetched;
while (pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK)
{
    IPropertyBag *pPropBag = NULL;
    hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
       (void **)&pPropBag);

    if (SUCCEEDED(hr))
    {
        // To retrieve the friendly name of the filter, do the following:
        VARIANT varName;
        VariantInit(&varName);
        hr = pPropBag->Read(L"FriendlyName", &varName, 0);
        if (SUCCEEDED(hr))
        {
            // Display the name in your UI somehow.
        }
        VariantClear(&varName);

        // To create an instance of the filter, do the following:
        IBaseFilter *pFilter;
        hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pFilter);
        // Now add the filter to the graph. Remember to release pFilter later.

        // Clean up.
        pPropBag->Release();
    }
    pMoniker->Release();
}

// Clean up.
pMapper->Release();
pEnum->Release();

The EnumMatchingFilters method has a fairly large number of parameters, which are commented in the example. The significant ones for this example include:

  • Minimum merit value: The filter must have a merit value above MERIT_DO_NOT_USE.
  • Input types: The caller passes an array containing pairs of major types and subtypes. Only filters that support at least one of these pairs will match.
  • Exact match: A filter can register NULL values for major type, subtype, pin category, or medium. Unless you specify exact matching, a NULL value acts as a wildcard, matching any value that you specify. With exact matching, the filter must exactly match your criteria. However, if you give a NULL parameter in the search criteria, it always acts as a wildcard or "don't care" value, matching any filter.


Enumerating Objects in a Filter Graph

An application might need to locate a particular filter in the filter graph, or even a particular pin on a filter. For example, it might use an interface that a particular filter exposes. Or, it might construct a specialized filter graph and need to call methods on individual pins to connect the filters. For this purpose, DirectShow provides several methods for enumerating objects in a filter graph.

The enumerators discussed in this section follow the standard form used by COM enumeration interfaces. For more information, see the IEnumXXXX topic in the Platform SDK. For information on enumerating filters that are registered on the user's computer, but aren't yet in the filter graph, see Enumerating Devices and Filters.

This article contains the following topics:

  • Enumerating Filters
  • Enumerating Pins
  • Enumerating Media Types


Enumerating Filters

The Filter Graph Manager supports the IFilterGraph::EnumFilters method, which enumerates all the filters in the filter graph. It returns a pointer to the IEnumFilters interface. The IEnumFilters::Next method retrieves IBaseFilter interface pointers.

The following example shows a function that enumerates the filters in a graph and displays a message box with each filter's name. It uses the IBaseFilter::QueryFilterInfo method to retrieve the name of the filter. Note the places where the function calls Release on an interface to decrement the reference count.

HRESULT EnumFilters (IFilterGraph *pGraph)
{
    IEnumFilters *pEnum = NULL;
    IBaseFilter *pFilter;
    ULONG cFetched;

    HRESULR hr = pGraph->EnumFilters(&pEnum);
    if (FAILED(hr)) return hr;

    while(pEnum->Next(1, &pFilter, &cFetched) == S_OK)
    {
        FILTER_INFO FilterInfo;
        hr = pFilter->QueryFilterInfo(&FilterInfo);
        if (FAILED(hr))
        {
            MessageBox(NULL, TEXT("Could not get the filter info"),
                TEXT("Error"), MB_OK | MB_ICONERROR);
            continue;  // Maybe the next one will work.
        }

#ifdef UNICODE
        MessageBox(NULL, FilterInfo.achName, TEXT("Filter Name"), MB_OK);
#else
        char szName[MAX_FILTER_NAME];
        int cch = WideCharToMultiByte(CP_ACP, 0, FilterInfo.achName,
            MAX_FILTER_NAME, szName, MAX_FILTER_NAME, 0, 0);
        if (chh > 0)
            MessageBox(NULL, szName, TEXT("Filter Name"), MB_OK);
#endif

        // The FILTER_INFO structure holds a pointer to the Filter Graph
        // Manager, with a reference count that must be released.
        if (FilterInfo.pGraph != NULL)
        {
            FilterInfo.pGraph->Release();
        }
        pFilter->Release();
    }

    pEnum->Release();
    return S_OK;
}


Enumerating Pins

Filters support the IBaseFilter::EnumPins method, which enumerates the pins available on the filter. It returns a pointer to the IEnumPins interface. The IEnumPins::Next method retrieves IPin interface pointers.

The following example shows a function that locates a pin with a given direction (input or output) on a given filter. It uses the PIN_DIRECTION enumeration to specify the pin direction, and the IPin::QueryDirection method to find the direction of each enumerated pin. If this function finds a matching pin, it returns an IPin interface pointer with an outstanding reference count. The caller is responsible for releasing the interface.

IPin *GetPin(IBaseFilter *pFilter, PIN_DIRECTION PinDir)
{
    BOOL       bFound = FALSE;
    IEnumPins  *pEnum;
    IPin       *pPin;

    HRESULT hr = pFilter->EnumPins(&pEnum);
    if (FAILED(hr))
    {
        return NULL;
    }
    while(pEnum->Next(1, &pPin, 0) == S_OK)
    {
        PIN_DIRECTION PinDirThis;
        pPin->QueryDirection(&PinDirThis);
        if (bFound = (PinDir == PinDirThis))
            break;
        pPin->Release();
    }
    pEnum->Release();
    return (bFound ? pPin : NULL);
}

This function could easily be modified to return the nth pin with the specified direction, or the nth unconnected pin. (To find out if a pin is connected to another pin, call the IPin::ConnectedTo method.)


Enumerating Media Types

Pins support the IPin::EnumMediaTypes method, which enumerates a pin's preferred media types. It returns a pointer to the IEnumMediaTypes interface. The IEnumMediaTypes::Next method retrieves pointers to AM_MEDIA_TYPE structures describing media types.

The media type enumerator exists primarily to help the Filter Graph Manager make intelligent connections, and your applications will probably not use it. A pin does not necessarily return any preferred media types. Moreover, the media types it returns might depend on the filter's connection status. For example, a filter's output pin might return a different set of media types depending on which media type was set for the filter's input pin.


General Graph-Building Techniques

Every DirectShow application starts by building a filter graph. As you read the overview topics in the DirectShow documentation, you will find that most start by describing what kind of filter graph you need. In some cases, there is a method or a helper object specifically designed for building that type of graph. For example, the DVD Graph Builder object builds DVD playback graphs. In other cases, the application must construct the graph by adding filters and connecting them.

This section presents some helper functions that implement basic graph-building operations. They can be used by any DirectShow application that needs to build or modify a filter graph. This section contains the following topics:

  • Add a Filter by CLSID
  • Find an Unconnected Pin on a Filter
  • Connect Two Filters
  • Find an Interface on a Filter or Pin
  • Find a Filter's Peer
  • Remove All the Filters in the Graph
  • Building Graphs with the Capture Graph Builder

See Also

  • Enumerating Devices and Filters
  • Enumerating Objects in a Filter Graph
  • Intelligent Connect


Add a Filter by CLSID

The following function creates a filter with a specified class identifier (CLSID) and adds it to the filter graph:

HRESULT AddFilterByCLSID(
    IGraphBuilder *pGraph,  // Pointer to the Filter Graph Manager.
    const GUID& clsid,      // CLSID of the filter to create.
    LPCWSTR wszName,        // A name for the filter.
    IBaseFilter **ppF)      // Receives a pointer to the filter.
{
    if (!pGraph || ! ppF) return E_POINTER;
    *ppF = 0;
    IBaseFilter *pF = 0;
    HRESULT hr = CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER,
        IID_IBaseFilter, reinterpret_cast<void**>(&pF));
    if (SUCCEEDED(hr))
    {
        hr = pGraph->AddFilter(pF, wszName);
        if (SUCCEEDED(hr))
            *ppF = pF;
        else
            pF->Release();
    }
    return hr;
}

The function calls CoCreateInstance to create the filter, and then calls IFilterGraph::AddFilter to add the filter to the graph. The following code example uses this function to add the AVI Mux filter to the graph:

IBaseFilter *pMux;
hr = AddFilterByCLSID(pGraph, CLSID_AviDest, L"AVI Mux", &pMux);
if (SUCCEEDED(hr))
{
    /* ... */
   pMux->Release();
}

Note that some filters cannot be created with CoCreateInstance. This is often the case with filters that manage other software components. For example, the AVI Compressor filter is a wrapper for video codecs, and the WDM Video Capture filter is a wrapper for WDM capture drivers. These filters must be created using either the System Device Enumerator or the Filter Mapper. For more information, see Enumerating Devices and Filters.


Find an Unconnected Pin on a Filter

The following function searches on a filter for an unconnected pin, either input or output. It returns the first matching pin. Finding unconnected pins is useful when you are connecting filters.

HRESULT GetUnconnectedPin(
    IBaseFilter *pFilter,   // Pointer to the filter.
    PIN_DIRECTION PinDir,   // Direction of the pin to find.
    IPin **ppPin)           // Receives a pointer to the pin.
{
    *ppPin = 0;
    IEnumPins *pEnum = 0;
    IPin *pPin = 0;
    HRESULT hr = pFilter->EnumPins(&pEnum);
    if (FAILED(hr))
    {
        return hr;
    }
    while (pEnum->Next(1, &pPin, NULL) == S_OK)
    {
        PIN_DIRECTION ThisPinDir;
        pPin->QueryDirection(&ThisPinDir);
        if (ThisPinDir == PinDir)
        {
            IPin *pTmp = 0;
            hr = pPin->ConnectedTo(&pTmp);
            if (SUCCEEDED(hr))  // Already connected, not the pin we want.
            {
                pTmp->Release();
            }
            else  // Unconnected, this is the pin we want.
            {
                pEnum->Release();
                *ppPin = pPin;
                return S_OK;
            }
        }
        pPin->Release();
    }
    pEnum->Release();
    // Did not find a matching pin.
    return E_FAIL;
}

The function uses the IEnumPins interface to loop through the pins on the filter. For each pin, it calls IPin::QueryDirection to determine the direction of the pin. If the direction matches, it calls the IPin::ConnectedTo method to test whether the pin is already connected to another pin.

The following code example uses this function to find an unconnected output pin on a filter:

IPin *pOut = NULL;
HRESULT hr = GetUnconnectedPin(pFilter, PINDIR_OUTPUT, &pOut);
if (SUCCEEDED(hr))
{
    /* ... */
    pOut->Release();
}

See Also

  • Enumerating Pins
  • ICaptureGraphBuilder2::FindPin


Connect Two Filters

The following function connects an output pin from one filter to the first available input pin on another filter:

HRESULT ConnectFilters(
    IGraphBuilder *pGraph, // Filter Graph Manager.
    IPin *pOut,            // Output pin on the upstream filter.
    IBaseFilter *pDest)    // Downstream filter.
{
    if ((pGraph == NULL) || (pOut == NULL) || (pDest == NULL))
    {
        return E_POINTER;
    }
#ifdef debug
        PIN_DIRECTION PinDir;
        pOut->QueryDirection(&PinDir);
        _ASSERTE(PinDir == PINDIR_OUTPUT);
#endif

    // Find an input pin on the downstream filter.
    IPin *pIn = 0;
    HRESULT hr = GetUnconnectedPin(pDest, PINDIR_INPUT, &pIn);
    if (FAILED(hr))
    {
        return hr;
    }
    // Try to connect them.
    hr = pGraph->Connect(pOut, pIn);
    pIn->Release();
    return hr;
}

To retrieve an available input pin on the downstream filter, this function calls the GetUnconnectedPin function, which is described in Find an Unconnected Pin on a Filter. If there is an unconnected input pin on the downstream filter, the function calls IGraphBuilder::Connect to connect the two pins. If the pins cannot connect directly to each other, the Connect method may put additional filters between them, in order to complete the connection.

Here is an overloaded version of the same function. The second parameter is a pointer to a filter, rather than a pin. The function connects the first filter to the second filter:

HRESULT ConnectFilters(
    IGraphBuilder *pGraph,
    IBaseFilter *pSrc,
    IBaseFilter *pDest)
{
    if ((pGraph == NULL) || (pSrc == NULL) || (pDest == NULL))
    {
        return E_POINTER;
    }

    // Find an output pin on the first filter.
    IPin *pOut = 0;
    HRESULT hr = GetUnconnectedPin(pSrc, PINDIR_OUTPUT, &pOut);
    if (FAILED(hr))
    {
        return hr;
    }
    hr = ConnectFilters(pGraph, pOut, pDest);
    pOut->Release();
    return hr;
}

The following example uses this function to connect the AVI Mux filter to the File Writer filter. This example also uses the AddFilterByCLSID function, which is described in Add a Filter by CLSID.

IBaseFilter *pMux, *pWrite;
hr = AddFilterByCLSID(pGraph, CLSID_AviDest, L"AVI Mux", &pMux);
if (SUCCEEDED(hr))
{
    hr = AddFilterByCLSID(pGraph, CLSID_FileWriter, L"File Writer", &pWrite);
    if (SUCCEEDED(hr))
    {
        hr = ConnectFilters(pGraph, pMux, pWrite);
        /* Use IFileSinkFilter to set the file name (not shown). */
       pWrite->Release();
    }
    pMux->Release();
}

See Also

  • ICaptureGraphBuilder2::RenderStream


Find an Interface on a Filter or Pin

For many operations in DirectShow, the application calls methods on the Filter Graph Manager. In some situations, however, the application must call a method directly on a filter or pin. For example, many filters expose specialized interfaces that are used to configure the filter.

In the case of a filter interface, you might already have a pointer to the filter's IBaseFilter interface. In that case, simply use QueryInterface to get the other interface. But some filters might be added to the graph by the Filter Graph Manager. (For details, see Intelligent Connect.) In that case, use the IEnumFilters interface to loop through all the filters in the graph, and query each one in turn. The following function demonstrates this:

HRESULT FindFilterInterface(
    IGraphBuilder *pGraph, // Pointer to the Filter Graph Manager.
    REFGUID iid,           // IID of the interface to retrieve.
    void **ppUnk)          // Receives the interface pointer.
{
    if (!pGraph || !ppUnk) return E_POINTER;

    HRESULT hr = E_FAIL;
    IEnumFilters *pEnum = NULL;
    IBaseFilter *pF = NULL;
    if (FAILED(pGraph->EnumFilters(&pEnum)))
    {
        return E_FAIL;
    }
    // Query every filter for the interface.
    while (S_OK == pEnum->Next(1, &pF, 0))
    {
        hr = pF->QueryInterface(iid, ppUnk);
        pF->Release();
        if (SUCCEEDED(hr))
        {
            break;
        }
    }
    pEnum->Release();
    return hr;
}

The following example uses this function:

hr = pGraph->RenderFile(L"C:\\Example.avi", 0);
if (SUCCEEDED(hr))
{
    IIPDVDec *pDvDec;
    hr = FindFilterInterface(pGraph, IID_IIPDVDec, (void**)&pDvDec);
    if (SUCCEEDED(hr))
    {
        pDvDec->put_IPDisplay(DVRESOLUTION_QUARTER);
        pDvDec->Release();
    }
    else if (hr == E_NOINTERFACE)
    {
        // This file does not contain DV video.
    }
    else
    {
        // Some other error occurred.
    }
}

First, the example renders an AVI file for playback. Then, if the file contains DV-encoded video, the example sets the output resolution to one-quarter size. The interface for setting the output resolution is the IIPDVDec interface, which is exposed by the DV Video Decoder filter. If the AVI file contains DV-encoded video, the RenderFile method automatically puts the DV Video Decoder in the filter graph. If so, the FindFilterInterface function succeeds and returns a pointer to the IIPDVDec interface. Otherwise, the function returns E_NOINTERFACE, which simply means the AVI file does not contain DV video.

To find an interface on a pin, use the IEnumPins interface to loop through the pins on a filter. The following function shows how to do this:

HRESULT FindPinInterface(
    IBaseFilter *pFilter,  // Pointer to the filter to search.
    REFGUID iid,           // IID of the interface.
    void **ppUnk)          // Receives the interface pointer.
{
    if (!pFilter || !ppUnk) return E_POINTER;

    HRESULT hr = E_FAIL;
    IEnumPins *pEnum = 0;
    if (FAILED(pFilter->EnumPins(&pEnum)))
    {
        return E_FAIL;
    }
    // Query every pin for the interface.
    IPin *pPin = 0;
    while (S_OK == pEnum->Next(1, &pPin, 0))
    {
        hr = pPin->QueryInterface(iid, ppUnk);
        pPin->Release();
        if (SUCCEEDED(hr))
        {
            break;
        }
    }
    pEnum->Release();
    return hr;
}

The next function searches for an interface on a filter or a pin:

HRESULT FindInterfaceAnywhere(
    IGraphBuilder *pGraph,
    REFGUID iid,
    void **ppUnk)
{
    if (!pGraph || !ppUnk) return E_POINTER;
    HRESULT hr = E_FAIL;
    IEnumFilters *pEnum = 0;
    if (FAILED(pGraph->EnumFilters(&pEnum)))
    {
        return E_FAIL;
    }
    // Loop through every filter in the graph.
    IBaseFilter *pF = 0;
    while (S_OK == pEnum->Next(1, &pF, 0))
    {
        hr = pF->QueryInterface(iid, ppUnk);
        if (FAILED(hr))
        {
            // The filter does not expose the interface, but maybe
            // one of its pins does.
            hr = FindPinInterface(pF, iid, ppUnk);
        }
        pF->Release();
        if (SUCCEEDED(hr))
        {
            break;
        }
    }
    pEnum->Release();
    return hr;
}

Note that all of the functions shown here stop at the first successful QueryInterface.

See Also

  • DirectShow DV Filters
  • Enumerating Filters
  • Enumerating Pins
  • ICaptureGraphBuilder2::FindInterface


Find a Filter's Peer

Given a filter, you can traverse the graph by finding the filters to which it is connected. Start by enumerating the filter's pins. For each pin, check whether that pin is connected to another pin. If so, query the other pin for it's owning filter. You can walk the graph in the upstream direction by enumerating the filter's input pins, or in the downstream direction by enumerating the output pins.

The following function searches upstream or downstream for a connected filter. It returns the first matching filter that it finds:

// Get the first upstream or downstream filter
HRESULT GetNextFilter(
    IBaseFilter *pFilter, // Pointer to the starting filter
    PIN_DIRECTION Dir,    // Direction to search (upstream or downstream)
    IBaseFilter **ppNext) // Receives a pointer to the next filter.
{
    if (!pFilter || !ppNext) return E_POINTER;

    IEnumPins *pEnum = 0;
    IPin *pPin = 0;
    HRESULT hr = pFilter->EnumPins(&pEnum);
    if (FAILED(hr)) return hr;
    while (S_OK == pEnum->Next(1, &pPin, 0))
    {
        // See if this pin matches the specified direction.
        PIN_DIRECTION ThisPinDir;
        hr = pPin->QueryDirection(&ThisPinDir);
        if (FAILED(hr))
        {
            // Something strange happened.
            hr = E_UNEXPECTED;
            pPin->Release();
            break;
        }
        if (ThisPinDir == Dir)
        {
            // Check if the pin is connected to another pin.
            IPin *pPinNext = 0;
            hr = pPin->ConnectedTo(&pPinNext);
            if (SUCCEEDED(hr))
            {
                // Get the filter that owns that pin.
                PIN_INFO PinInfo;
                hr = pPinNext->QueryPinInfo(&PinInfo);
                pPinNext->Release();
                pPin->Release();
                pEnum->Release();
                if (FAILED(hr) || (PinInfo.pFilter == NULL))
                {
                    // Something strange happened.
                    return E_UNEXPECTED;
                }
                // This is the filter we're looking for.
                *ppNext = PinInfo.pFilter; // Client must release.
                return S_OK;
            }
        }
        pPin->Release();
    }
    pEnum->Release();
    // Did not find a matching filter.
    return E_FAIL;
}

The function calls IBaseFilter::EnumPins to enumerate the first filter's pins. For each pin, it calls IPin::QueryDirection to check whether the pin matches the specified direction (input or output). If so, the function determines whether that pin is connected to another pin, by calling the IPin::ConnectedTo method. Finally, it calls IPin::QueryPinInfo on the connected pin. This method returns a structure that contains, among other things, a pointer to that pin's owning filter. This pointer is returned to the caller in the ppNext parameter. The caller must release the pointer.

The following code shows how to call this function:

IBaseFilter *pF; // Pointer to some filter.
IBaseFilter *pUpstream = NULL;
if (SUCCEEDED(GetNextFilter(pF, PINDIR_INPUT, &pUpstream)))
{
    // Use pUpstream ...
    pUpstream->Release();
}

A filter might be connected to two or more filters in either direction. For example, it might be a splitter filter, with several filters downstream from it. Or it might be a mux filter, with several filters upstream from it. Therefore, you might want to collect all of them into a list.

The following code shows one possible way to implement such a function. It uses the DirectShow CGenericList class; you could write an equivalent function using some other data structure.

#include <streams.h>  // Link to the DirectShow base class library
// Define a typedef for a list of filters.
typedef CGenericList<IBaseFilter> CFilterList;

// Forward declaration. Adds a filter to the list unless it's a duplicate.
void AddFilterUnique(CFilterList &FilterList, IBaseFilter *pNew);

// Find all the immediate upstream or downstream peers of a filter.
HRESULT GetPeerFilters(
    IBaseFilter *pFilter, // Pointer to the starting filter
    PIN_DIRECTION Dir,    // Direction to search (upstream or downstream)
    CFilterList &FilterList)  // Collect the results in this list.
{
    if (!pFilter) return E_POINTER;

    IEnumPins *pEnum = 0;
    IPin *pPin = 0;
    HRESULT hr = pFilter->EnumPins(&pEnum);
    if (FAILED(hr)) return hr;
    while (S_OK == pEnum->Next(1, &pPin, 0))
    {
        // See if this pin matches the specified direction.
        PIN_DIRECTION ThisPinDir;
        hr = pPin->QueryDirection(&ThisPinDir);
        if (FAILED(hr))
        {
            // Something strange happened.
            hr = E_UNEXPECTED;
            pPin->Release();
            break;
        }
        if (ThisPinDir == Dir)
        {
            // Check if the pin is connected to another pin.
            IPin *pPinNext = 0;
            hr = pPin->ConnectedTo(&pPinNext);
            if (SUCCEEDED(hr))
            {
                // Get the filter that owns that pin.
                PIN_INFO PinInfo;
                hr = pPinNext->QueryPinInfo(&PinInfo);
                pPinNext->Release();
                if (FAILED(hr) || (PinInfo.pFilter == NULL))
                {
                    // Something strange happened.
                    pPin->Release();
                    pEnum->Release();
                    return E_UNEXPECTED;
                }
                // Insert the filter into the list.
                AddFilterUnique(FilterList, PinInfo.pFilter);
                PinInfo.pFilter->Release();
            }
        }
        pPin->Release();
    }
    pEnum->Release();
    return S_OK;
}
void AddFilterUnique(CFilterList &FilterList, IBaseFilter *pNew)
{
    if (pNew == NULL) return;

    POSITION pos = FilterList.GetHeadPosition();
    while (pos)
    {
        IBaseFilter *pF = FilterList.GetNext(pos);
        if (IsEqualObject(pF, pNew))
        {
            return;
        }
    }
    pNew->AddRef();  // The caller must release everything in the list.
    FilterList.AddTail(pNew);
}

To complicate matters somewhat, a filter can have multiple pin connections to the same filter. To avoid putting duplicates into the list, query each IBaseFilter pointer for IUnknown and compare the IUnknown pointers. By the rules of COM, two interface pointers refer to the same object if and only if they return identical IUnknown pointers. In the previous example, the AddFilterUnique function handles this detail.

The following example shows how to use the GetPeerFilters function:

IBaseFilter *pF; // Pointer to some filter.
CFilterList FList(NAME("MyList"));  // List to hold the downstream peers.
hr = GetPeerFilters(pF, PINDIR_OUTPUT, FList);
if (SUCCEEDED(hr))
{
    POSITION pos = FList.GetHeadPosition();
    while (pos)
    {
        IBaseFilter *pDownstream = FList.GetNext(pos);
        pDownstream->Release();
    }
}


Remove All the Filters in the Graph

The easiest way to remove all of the filters in a filter graph is simply to release the Filter Graph Manager and create a new one. Make sure to release every pointer that your application has to any interfaces on the Filter Graph Managers, as well as pointers to objects in the graph, including filters, pins, the reference clock, and so forth.

Alternatively, you can remove the filters one at a time, using the IFilterGraph::RemoveFilter method:

// Stop the graph.
pControl->Stop();

// Enumerate the filters in the graph.
IEnumFilters *pEnum = NULL;
HRESULT hr = pGraph->EnumFilters(&pEnum);
if (SUCCEEDED(hr))
{
    IBaseFilter *pFilter = NULL;
    while (S_OK == pEnum->Next(1, &pFilter, NULL))
     {
         // Remove the filter.
         pGraph->RemoveFilter(pFilter);
         // Reset the enumerator.
         pEnum->Reset();
         pFilter->Release();
    }
    pEnum->Release();
}

This example uses the IFilterGraph::EnumFilters method to enumerate the filters in the graph. Removing a filter causes the enumerator object to become out of sync with the graph. Use the IEnumFilters::Reset method to reset the enumerator. Otherwise, any subsequent call to IEnumFilters::Next will fail.


Building Graphs with the Capture Graph Builder

Despite its name, the Capture Graph Builder is useful for building many kinds of custom filter graphs, not only capture graphs. This article provides a brief overview of how to use this object.

The Capture Graph Builder exposes the ICaptureGraphBuilder2 interface. Start by calling CoCreateInstance to create the Capture Graph Builder and the Filter Graph Manager. Then initialize the Capture Graph Builder by calling ICaptureGraphBuilder2::SetFiltergraph with a pointer to the Filter Graph Manager, as follows:

IGraphBuilder *pGraph = NULL;
ICaptureGraphBuilder2 *pBuilder = NULL;

// Create the Filter Graph Manager.
HRESULT hr =  CoCreateInstance(CLSID_FilterGraph, NULL,
    CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);

if (SUCCEEDED(hr))
{
    // Create the Capture Graph Builder.
    hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL,
        CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2,
        (void **)&pBuilder);
    if (SUCCEEDED(hr))
    {
        pBuilder->SetFiltergraph(pGraph);
    }
};

Connecting Filters

The ICaptureGraphBuilder2::RenderStream method connects two or three filters together in a chain. Generally, the method works best when each filter has no more than one input pin or output pin of the same type. This discussion begins by ignoring the first two parameters of RenderStream and focusing on the last three parameters. The third parameter is an IUnknown pointer, which can specify either a filter (as an IBaseFilter interface pointer) or an output pin (as an IPin interface pointer). The fourth and fifth parameters specify IBaseFilter pointers. The RenderStream method connects all three filters in a chain. For example, suppose that A, B, and C are filters. Assume for now that each filter has exactly one input pin and one output pin. The following call connects A to B, and then B to C:

RenderStream(NULL, NULL, A, B, C)

All connections are "intelligent," meaning that additional filters are added to the graph as needed. For details, see Intelligent Connect. To connect just two filters, set the middle value to NULL. For example, this call connects A to C:

RenderStream(NULL, NULL, A, NULL, C)

You can create longer chains by calling the method twice:

RenderStream(NULL, NULL, A, B, C)

RenderStream(NULL, NULL, C, D, E)

If the last parameter is NULL, the method automatically locates a default renderer. It uses the Video Renderer for video and the DirectSound Renderer for audio. Thus:

RenderStream(NULL, NULL, A, NULL, NULL)

is equivalent to

RenderStream(NULL, NULL, A, NULL, R)

where R is the appropriate renderer. To connect the Video Mixing Renderer filter instead of the Video Renderer, however, you must specify it explicitly.

If you specify a filter in the third parameter, rather than a pin, you may need to indicate which output pin should be used for the connection. That is the purpose of the method's first two parameters. The first parameter applies only to capture filters. It specifies a GUID that indicates a pin category. For a complete list of categories, see Pin Property Set. Two of the categories are valid for all capture filters:

  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW

If a capture filter does not supply separate pins for capture and preview, the RenderStream method inserts a Smart Tee filter, which splits the stream into a capture stream and a preview stream. From the application's standpoint, you can simply treat all capture filters as having separate pins and ignore the underlying topology of the graph.

For file capture, connect the capture pin to a mux filter. For live preview, connect the preview pin to a renderer. If you switch the two categories, the graph might drop an excessive number of frames during the file capture; but if the graph is connected properly, it drops preview frames as needed in order to maintain throughput on the capture stream.

The following example shows how to connect both streams:

// Capture to file:
pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, NULL, pCapFilter, NULL, pMux);
// Preview:
pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, NULL, pCapFilter, NULL, NULL);

Some capture filters also support closed captions, indicated by PIN_CATEGORY_VBI. To capture the closed captions to a file, render this category to the mux filter. To view the closed captions in your preview window, connect to the renderer:

// Capture to file:
pBuilder->RenderStream(&PIN_CATEGORY_VBI, NULL, pCapFilter, NULL, pMux);
// Preview on screen:
pBuilder->RenderStream(&PIN_CATEGORY_VBI, NULL, pCapFilter, NULL, NULL);

The second parameter to RenderFile identifies the media type, and is typically one of the following:

  • MEDIATYPE_Audio
  • MEDIATYPE_Video
  • MEDIATYPE_Interleaved (DV)

You can use this parameter whenever the filter's output pins support the enumeration of preferred media types. For file sources, the Capture Graph Builder automatically adds a parser filter if needed, and then queries the media types on the parser. (For an example, see Recompressing an AVI File.) Also, if the last filter in the chain has several input pins, the method attempts to enumerate their media types. However, not all filters support this functionality.

Finding Interfaces on Filters and Pins

After you build a graph, you will typically need to locate various interfaces exposed by filters and pins in the graph. For example, a capture filter might expose the IAMDroppedFrames interface, while the filter's output pins might expose the IAMStreamConfig interface.

The simplest way to find an interface is to use the ICaptureGraphBuilder2::FindInterface method. This method walks the graph (filters and pins) until it locates the desired interface. You can specify the starting point for the search, and you can limit the search to filters upstream or downstream from the starting point.

The following example searches for the IAMStreamConfig interface on a video preview pin:

IAMStreamConfig *pConfig = NULL;
HRESULT hr = pBuild->FindInterface(
    &PIN_CATEGORY_PREVIEW,
    &MEDIATYPE_Video,
    pVCap,
    IID_IAMStreamConfig,
    (void**)&pConfig
);
if (SUCCESSFUL(hr))
{
    /* ... */
    pConfig->Release();
}

Finding Pins

Less commonly, you may need to locate an individual pin on a filter, although in most cases the RenderStream and FindInterface methods will save you the trouble. If you do need to find a particular pin on a filter, the ICaptureGraphBuilder2::FindPin helper method is useful. Specify the category, the media type (video or audio), the direction, and whether the pin must be unconnected.

For example, the following code searches for an unconnected video preview pin on a capture filter:

IPin *pPin = NULL;
hr = pBuild->FindPin(
    pCap,                   // Pointer to the filter to search.
    PINDIR_OUTPUT,          // Search for an output pin.
    &PIN_CATEGORY_PREVIEW,  // Search for a preview pin.
    &MEDIATYPE_Video,       // Search for a video pin.
    TRUE,                   // The pin must be unconnected.
    0,                      // Return the first matching pin (index 0).
    &pPin);                 // This variable receives the IPin pointer.
if (SUCCESSFUL(hr))
{
    /* ... */
    pPin->Release();
}

See Also

  • Video Capture


Seeking the Filter Graph

This section describes how an application can seek to different positions within a media stream. It contains the following topics:

  • Querying for Seeking Capabilities
  • Setting and Retrieving the Position
  • Setting the Playback Rate
  • Time Formats For Seek Commands


Querying for Seeking Capabilities

Microsoft® DirectShow® supports seeking through the IMediaSeeking interface. The Filter Graph Manager exposes this interface, but the seeking functionality is always implemented by filters in the graph.

Some data cannot be seeked. For example, you cannot seek a live video stream from a camera. If a stream is seekable, however, there are various types of seeking it might support. These include:

  • Seeking to an arbitrary position in the stream.
  • Retrieving the duration of the stream.
  • Retrieving the current position within the stream.
  • Playing backwards.

The IMediaSeeking interface defines a set of flags, AM_SEEKING_SEEKING_CAPABILITIES, that describe the possible seeking capabilities. To retrieve the stream's capabilities, call the IMediaSeeking::GetCapabilities method. The method returns a bitwise combination of flags. The application can test them using the & (bitwise AND) operator. For example, the following code checks whether the graph can seek to an arbitrary position:

DWORD dwCap = 0;
HRESULT hr = pSeek->GetCapabilities(&dwCap);
if (AM_SEEKING_CanSeekAbsolute & dwCap)
{
    // Graph can seek to absolute positions.
}


Setting and Retrieving the Position

The filter graph maintains two position values, current position and stop position. These are defined as follows:

  • When the graph is running, the current position is the current playback position, relative to the begining of the source. When the graph is stopped or paused, the current position is the point where streaming will begin on the next run command.
  • The stop position is the point where the stream will end. When the graph reaches the stop position, no more data is streamed, and the filter graph manager posts an EC_COMPLETE event. (The graph does not automatically switch to a stopped state, however. For more information, see Responding to Events.)

To retrieve these values, call the IMediaSeeking::GetPositions method. The returned values are always relative to the original media source. By default, the values are in reference time units. In some cases, you can change the time units; for more information, see Time Formats For Seek Commands.

To seek to a new position or set a new stop position, call the IMediaSeeking::SetPositions method, as shown in the following example:

#define ONE_SECOND 10000000
REFERENCE_TIME rtNow  = 2 * ONE_SECOND,
               rtStop = 5 * ONE_SECOND;

hr = pSeek->SetPositions(
    &rtNow,  AM_SEEKING_AbsolutePositioning,
    &rtStop, AM_SEEKING_AbsolutePositioning
    );

Note One second is 10,000,000 units of reference time. For convenience, the example defines this value as ONE_SECOND. If you are using the DirectShow base-class library, the constant UNITS has the same value.

The rtNow parameter specifies the new current position. The second parameter is a flag that defines how to interpret rtNow. In this example, the AM_SEEKING_AbsolutePositioning flag indicates that rtNow specifies an absolute position in the source. Therefore, the filter graph will seek to a position two seconds from the start of the stream. The rtStop parameter gives the stop time. The last parameter specifies that rtStop is also an absolute position.

To specify a position relative to the previous position value, use the AM_SEEKING_RelativePositioning flag. To leave one of the position values unchanged, use the AM_SEEKING_NoPositioning flag. The corresponding time parameter can be NULL in that case. The following example seeks forward by 10 seconds but leaves the stop position unchanged:

REFERENCE_TIME rtNow = 10 * ONE_SECOND;
hr = pSeek->SetPositions(
    &rtNow, AM_SEEKING_RelativePositioning,
    NULL, AM_SEEKING_NoPositioning
    );

If the filter graph is stopped, the video renderer does not update the image after a seek operation. To the user, it will appear as if the seek did not happen. To update the image, pause the graph after the seek operation. Pausing the graph cues a new video frame for the video renderer. You can use the IMediaControl::StopWhenReady method, which pauses the graph and then stops it.


Setting the Playback Rate

To change the playback rate, call the IMediaSeeking::SetRate method. Specify the new rate as a fraction of the original rate. For example, to play at twice-normal speed, use the following:

pSeek->SetRate(2.0)

Rates greater than one are faster than normal. Rates between zero and one are slower than normal. Negative rates are defined as backward playback, but in practice most filters do not support it. Currently none of the standard DirectShow filters support backwards playback.

Regardless of the playback rate, the current position and the stop position are always expressed relative to the original source. For example, if a source file is 20 seconds long at normal playback rate, setting the current position to 10 seconds will seek to the middle of the file. If the playback rate is 2.0, the stop position is 20 seconds, and you seek to the 10-second position, the file will play for 5 seconds of real time: 10 seconds' worth, at twice the normal playback speed. At a playback rate of 2.0, the current position increases at twice the rate of the reference clock.


Time Formats For Seek Commands

Many of the methods in the IMediaSeeking interface have parameters that express position values, such as current position or stop position. By default, these parameters are expressed in units of 100 nanoseconds, also called reference time. Any filter that can seek must support seeking by reference time. Some filters can seek using other units of time as well, such as seeking to a particular frame number, or seeking to a given byte offset within a stream. Each of these time units is called a time format, and is defined by a globally unique identifier (GUID). For a list of the time formats that are defined by DirectShow, see Time Format GUIDs. Third parties can also define GUIDs for custom time formats.

To determine whether the filters currently in the filter graph support a particular time format, call the IMediaSeeking::IsFormatSupported method. The method returns S_OK if the format is supported. Otherwise, it returns S_FALSE or an error code. If a format is supported, you can switch to that format by calling the IMediaSeeking::SetTimeFormat method. If the SetTimeFormat method succeeds, subsequent seek commands are expressed using the new time format.

The follow example checks whether the graph supports seeking by frame number. If so, it seeks to frame number 20:

hr = pSeek->IsFormatSupported(&TIME_FORMAT_FRAME);
if (hr == S_OK)
{
    hr = pSeek->SetTimeFormat(&TIME_FORMAT_FRAME);
    if (SUCCEEDED(hr))
    {
        // Seek to frame number 20.
        LONGLONG rtNow = 20;
        hr = pSeek->SetPositions(
            &rtNow, AM_SEEKING_AbsolutePositioning,
            0, AM_SEEKING_NoPositioning);
    }
}

Note that time formats only apply to seek commands. They do not affect graph playback or other actions.


Setting the Graph Clock

When you build a filter graph, the Filter Graph Manager automatically chooses a reference clock for the graph. All filters in the graph are synchronized to the reference clock. In particular, renderer filters use the reference clock to determine the presentation time of each sample.

There is usually no reason for an application to override the Filter Graph Manager's choice of reference clock. However, you can do so by calling the IMediaFilter::SetSyncSource method on the Filter Graph Manager. This method takes a pointer to the clock's IReferenceClock interface. Call the method while the graph is stopped. The following example shows how to specify a clock:

IGraphBuilder *pGraph = 0;
IReferenceClock *pClock = 0;

CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
    IID_IGraphBuilder, (void **)&pGraph);

// Build the graph.
pGraph->RenderFile(L"C:\\Example.avi", 0);

// Create your clock.
hr = CreateMyPrivateClock(&pClock);
if (SUCCEEDED(hr))
{
    // Set the graph clock.
    IMediaFilter *pMediaFilter = 0;
    pGraph->QueryInterface(IID_IMediaFilter, (void**)&pMediaFilter);
    pMediaFilter->SetSyncSource(pClock);
    pClock->Release();
    pMediaFilter->Release();
}

This example assumes that CreateMyPrivateClock is an application-defined function that creates a clock and returns an IReferenceClock pointer.

You can also set the filter graph to run with no clock, by calling SetSyncSource with the value NULL. If there is no clock, the graph runs as quickly as possible. With no clock, renderer filters do not wait for a sample's presentation time. Instead, they render each sample as soon as it arrives. Setting the graph to run without a clock is useful if you want to process data quickly, rather than previewing it in real time.

See Also

  • Time and Clocks in DirectShow


Debugging in DirectShow

This article provides some tips for debugging Microsoft® DirectShow® applications and filters. Most of the debugging facilities described in this article require the DirectShow bass class library. See DirectShow Base Classes for more information.

Assertion Checking

Use assertion checking liberally. Assertions can verify assumptions that you make in your code about preconditions and postconditions. DirectShow provides several assertion macros. For more information, see Assert and Breakpoint Macros.

Object Names

In debug builds, there is a global list of objects that derive from the CBaseObject class. As objects are created, they are added to the list. When they are destroyed, they are removed from the list. To display a list of those objects, call the DbgDumpObjectRegister function.

The constructor method for the CBaseObject base class—and most classes derived from it—includes a parameter for the name of the object. Give your objects unique names to identify them. Use the NAME macro when you declare the name, so that the name is allocated only in debug builds. In retail builds, the name becomes NULL.

Debug Logging

The DbgLog function displays debugging messages as your program executes. Use this function to trace the execution of your application or filter. You can log return codes, the values of variables, and any other relevant information.

Every debug message has a type, such as LOG_TRACE or LOG_ERROR, and a debug level, which indicates the importance of the message. Messages with lower debug levels are more important than those with higher levels.

In the following example, a hypothetical filter disconnects a pin from an array of pins. If the disconnect attempt succeeds, the filter displays a LOG_TRACE message. If the attempt fails, it displays a LOG_ERROR message:

hr = m_PinArray[iPin]->Disconnect();
if (FAILED(hr))
{
    DbgLog((LOG_ERROR, 1, TEXT("Could not disconnect pin %d. HRESULT = %#x", iPin, hr));

   // Error handling code (not shown).
}
DbgLog((LOG_TRACE, 3, TEXT("Disconnected pin %d"), iPin));

When you are debugging, you can set the debug level for each message type. Also, each module (DLL or executable) maintains its own debugging levels. If you are testing a filter, raise the debug levels for the DLL that contains the filter.

For more information, see Debug Output Functions.

Critical Sections

To make deadlocks easier to track, include assertions that determine whether the calling code owns a given critical section. The CritCheckIn and CritCheckOut functions indicate whether the calling thread owns a critical section. Typically, you would call these functions from inside an assert macro.

You can also use the DbgLockTrace function to trace when critical sections are held or released.

Pointer Validation

Consider validating pointers in debug builds. For example, the ValidateReadPtr macro checks whether a specified pointer points to readable memory. Currently, the DirectShow pointer validation macros use Microsoft® Win32® pointer validation functions, such as IsBadReadPtr. On some systems, these functions swap in every page in the specified range, which can greatly reduce performance. For more information, see Pointer Validation Macros.

Troubleshooting Tips

This following tips will help you to avoid deadlocks or crashes in your application.

Global Objects

A global C++ object should not create DirectShow objects in its constructor method or release them in its destructor method. Doing so can cause the application to block indefinitely, for the following reason:

Threads cannot exit while inside a DLL's entry-point function. Kernel 32 holds a global process lock during the entry-point function, and the lock prevents the thread from exiting. Because some DirectShow objects own threads, they can block if released from inside a DLL entry-point function. If an application has a global C++ object, the C runtime DLL calls the object's destructor when the DLL is unloaded. If the destructor releases DirectShow objects, it can block as a result.

For similar reasons, a DLL should not create or release DirectShow objects in its entry point routine.

Releasing Interfaces

You should release all DirectShow interface pointers while your application is still processing messages, before it exits the message loop. Otherwise, you might see various asserts, because some DirectShow objects send messages during their clean-up routines.

(As a corollary, if you are using the ATL CWindowImpl class, do not wait until OnFinalMessage to free the interfaces. Instead, free them when you handle the WM_CLOSE message.)

Reference Counts

When the debug version of Quartz.dll unloads, it checks whether any DirectShow objects have reference counts that were not released. If so, it throws an assertion:

g_cFGObjects == 0

When this assertion fails, it means your application has leaked a reference count. Review your code and make sure that you release all interface pointers.

See Also

  • Simulating Graph Building with GraphEdit


Audio Capture

An application can use Microsoft® DirectShow® to capture audio data from microphones, tape players, and other devices, through the inputs on the sound card. Typical scenarios include:

  • Recording a voiceover narration for later dubbing over a video stream.
  • Converting legacy analog audio content to digital format.
  • Capturing voice or music for transmission over a network.

End users have several options for capturing audio from the sound card to the hard disk. Most cards provide applications for mixing and recording from their audio inputs. The Microsoft® Windows® operating system provides Sound Recorder, a simple utility application for recording from a microphone. Microsoft® Windows Media™ Tools includes the Windows Media Encoder stand-alone application. The Windows Media Encoder can also be incorporated into a DirectShow application as a Microsoft® DirectX® Media Object (DMO). This section describes how to integrate audio capture functionality within your own application using DirectShow.

This section contains the following topics:

  • About the Audio Capture Filter
  • Creating an Audio Capture Graph
  • Creating an Audio Capture Graph with Preview
  • Setting Audio Capture Properties


About the Audio Capture Filter

DirectShow enables capture from the analog inputs on a sound card through the Audio Capture Filter. This filter uses the Microsoft® Platform SDK waveInXXX APIs to control any device whose driver supports these APIs. Each card on the system is represented by a separate instance of the filter.

The Audio Capture filter exposes each input on the card, such as the microphone or the MIDI input, as an input pin. The input pins represent what the driver exposes as audio source lines. No data travels through these input pins, however, and they do not connect to other DirectShow filters. They simply provide a way for an application to control the inputs. The application can use an input pin to enable or disable the input, or to set mixing properties such as bass equalization, treble equalization, pan, and so forth. The amount of control that is available depends on the driver. To fully understand and exploit the capabilities of a particular sound card, you will need the documentation from the card's manufacturer.

Note You can capture from the CD-Audio input, but this audio stream has already gone through the digital-to-analog converter, so there will be a loss of sound quality from the original CD.


Creating an Audio Capture Graph

The first step for an audio capture application is to build a filter graph. The configuration of the graph depends on the type of file that you want to create.

  • Audio-only AVI file: Audio Capture Filter to AVI Mux filter, and AVI Mux to File Writer filter.
  • WAV file: Audio Capture Filter to WavDest Filter Sample to File Writer Filter
  • Windows Media Audio (.wma) file: Audio Capture Filter to WM ASF Writer filter.

The WavDest filter is provided as an SDK sample. To use it, you must build and register the filter.

To use the ASF Writer filter, you must install the Windows Media SDK and obtain a software key to unlock the filter. For more information, see Windows Media Applications.

You can build the filter graph using the Capture Graph Builder object, or you can build the graph "manually"; that is, have the application programmatically add and connect each filter. This article describes the manual approach. For more information about using the Capture Graph Builder, see Video Capture. Much of the information in that article applies to audio-only graphs.

Adding the Audio Capture Device

Because the Audio Capture Filter communicates with a specific hardware device, you cannot simply call CoCreateInstance to create the filter. Instead, use the System Device Enumerator to enumerate all of the devices in the "Audio Capture Sources" category, which is identified by the class identifier CLSID_AudioInputDeviceCategory.

The System Device Enumerator returns a list of monikers for the devices; each moniker's friendly name corresponds to the name of the device. Choose one of the returned monikers and use it to create an instance of the Audio Capture Filter for that device. Add the filter to the filter graph. The user's preferred audio recording device appears first in the moniker list. (The user selects a preferred device by clicking Sounds and Multimedia in Control Panel.)

For more information, see Using the System Device Enumerator.

Adding the Multiplexer and the File Writer

An audio capture graph must contain a multiplexer and a file writer.

A multiplexer is a filter that combines one or more streams into a single stream with a particular format. For example, the AVI Mux filter combines audio and video streams into an interleaved AVI stream. For audio capture, there is typically only a single audio stream, but the audio data must still be packaged into a format that can be saved to disk, which requires a multiplexer. The choice of multiplexer depends on the target format:

  • AVI: AVI Multiplexer
  • WAV: WavDest
  • WMA: ASF Writer

A file writer is a filter that writes incoming data to a file. For AVI or WAV files, use the File Writer Filter. For WMA files, the ASF Writer acts as both multiplexer and file writer.

After you create the filters and add them to the graph, connect the Audio Capture Filter's output pin to the multiplexer's input pin, and connect the multiplexer's output pin to the filter writer's input pin (assuming these are separate filters). To specify the file name, query the file writer for the IFileSinkFilter interface and call the IFileSinkFilter::SetFileName method.

Example Code

The following example shows how to build an audio capture graph using the WavDest filter. The same principles apply for the other file types.

IBaseFilter *pSrc = NULL, *pWaveDest = NULL, *pWriter = NULL;
IFileSinkFilter *pSink= NULL;
IGraphBuilder *pGraph;
// Create the Filter Graph Manager.
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
    IID_IGraphBuilder, (void**)&pGraph);

// Not shown: Use the System Device Enumerator to create the
// audio capture filter.

// Add the audio capture filter to the filter graph.
pGraph->AddFilter(pSrc, L"Capture");

// Add the WavDest and the File Writer.
AddFilterByCLSID(pGraph, CLSID_WavDest, L"WavDest", &pWavDest);
AddFilterByCLSID(pGraph, CLSID_FileWriter, L"File Writer", &pWriter);

// Set the file name.
pWriter->QueryInterface(IID_IFileSinkFilter, (void**)&pSink);
pSink->SetFileName(L"C:\\MyWavFile.wav", NULL);

// Connect the filters.
ConnectFilters(pGraph, pSrc, pWavDest);
ConnectFilters(pGraph, pWavDest, pWriter);

This example uses the AddFilterByCLSID function described in Add a Filter by CLSID, and the ConnectFilters function described in Connect Two Filters. Neither of these is a DirectShow API.


Creating an Audio Capture Graph with Preview

The filter graph described in Creating an Audio Capture Graph performs capture only, with no preview. To preview and capture at the same time, the filter graph needs to use the Infinite Pin Tee Filter. This filter has one input pin and creates as many output pins as needed. (It starts with one output pin. Each time you connect an output pin, it creates another one.) The Infinite Pin Tee filter delivers every sample that it receives, unchanged, through all of its output pins.

Connect the Audio Capture Filter to the Infinite Pin Tee, and connect the Infinite Pin Tee to the multiplexer and the DirectSound Renderer Filter. Connect the multiplexer to the file writer, as before. The following diagram illustrates the resulting filter graph for an AVI file.

Audio Capture Graph with Preview

Because the DirectSound Renderer is the default audio renderer, you can simply call the IGraphBuilder::Render method on the Infinite Pin Tee's output pin. The Filter Graph Manager uses Intelligent Connect to create the renderer, add it to the filter graph, and connect the pins.


Setting Audio Capture Properties

Each input pin on the Audio Capture Filter exposes the IAMAudioInputMixer interface. Use this interface to enable or disable a particular input, by calling the IAMAudioInputMixer::put_Enable method on the pin. Also use this interface to set properties of an input, such as the bass, treble, and volume levels. If you are capturing multiple inputs at once, you can control the overall bass, treble, and volume levels through the IAMAudioInputMixer interface on the filter itself.

The available sampling rates and audio formats for capture are determined by the driver. Use the IAMStreamConfig interface on the Audio Capture Filter's output pin to enumerate the available sampling rates and formats and set the desired format. The filter can connect downstream to any filter that accepts the output pin's media type.

The Audio Capture Filter also exposes the IAMBufferNegotiation interface. This interface is useful for controlling the amount of latency in audio preview. By default, the Audio Capture filter uses a half-second buffer size. This buffer size is optimal for capturing but causes a half-second preview delay. To reduce the latency, call the IAMBufferNegotiation::SuggestAllocatorProperties method before you connect the Audio Capture Filter's output pin. This method takes a pointer to the ALLOCATOR_PROPERTIES structure. Use the cbBuffer member to specify the buffer size, in bytes. An 80 millisecond buffer is generally safe, but buffers of 30 or 40 milliseconds might be sufficient. If the buffers are too small, the sound quality will be degraded.


Video Capture

This section describes how to use Microsoft DirectShow to write video capture applications.

  • About Video Capture in DirectShow
  • Selecting a Capture Device
  • Previewing Video
  • Capturing Video to a File
  • Controlling a Capture Graph
  • Video Capture Tasks
  • Digital Video in DirectShow
  • Controlling a DV Camcorder
  • Analog Television
  • Advanced Capture Topics


About Video Capture in DirectShow

The term video capture, as used in this documentation, describes any application where video is received from a hardware device. Video capture devices include not only cameras, but also TV tuner cards, video tape recorders (VTRs), and so forth. The captured video can be saved to disk or previewed live.

This section describes some of the concepts you must understand in order to use DirectShow for video capture:

  • About the Capture Graph Builder
  • About Video Capture Devices
  • DirectShow Video Capture Filters


About the Capture Graph Builder

A filter graph that performs video or audio capture is called a capture graph. Capture graphs are often more complicated than file playback graphs. To make it easier for applications to build capture graphs, DirectShow provides a helper object called the Capture Graph Builder. The Capture Graph Builder exposes the ICaptureGraphBuilder2 interface, which contains methods for building and controlling a capture graph.

Using the Capture Graph Builder

Start by calling CoCreateInstance to create new instances of the Capture Graph Builder and the Filter Graph Manager. Then initialize the Capture Graph Builder by calling ICaptureGraphBuilder2::SetFiltergraph with a pointer to the Filter Graph Manager's IGraphBuilder interface.

Initializing the Capture Graph Builder

The following code shows a helper function to perform these steps:

HRESULT InitCaptureGraphBuilder(
  IGraphBuilder **ppGraph,  // Receives the pointer.
  ICaptureGraphBuilder2 **ppBuild  // Receives the pointer.
)
{
    if (!ppGraph || !ppBuild)
    {
        return E_POINTER;
    }
    IGraphBuilder *pGraph = NULL;
    ICaptureGraphBuilder2 *pBuild = NULL;

    // Create the Capture Graph Builder.
    HRESULT hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL,
        CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void**)&pGraph);
    if (SUCCEEDED(hr))
    {
        // Create the Filter Graph Manager.
        hr = CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER,
            IID_IGraphBuilder, (void**)&pGraph);
        if (SUCCEEDED(hr))
        {
            // Initialize the Capture Graph Builder.
            pBuild->SetFiltergraph(pGraph);

            // Return both interface pointers to the caller.
            *ppBuild = pBuild;
            *ppGraph = pGraph; // The caller must release both interfaces.
            return S_OK;
        }
        else
        {
            pBuild->Release();
        }
    }
    return hr; // Failed
}

Throughout this section on video capture, it is assumed that you are using the Capture Graph Builder to create the capture graph. However, it is possible to build capture graphs entirely by using IGraphBuilder methods. This is considered an advanced topic, however, and the Capture Graph Builder methods are preferred. For more information, see Advanced Capture Topics.


About Video Capture Devices

Most new video capture devices use Windows Driver Model (WDM) drivers. In the WDM architecture, Microsoft supplies a set of hardware-independent drivers, called class drivers, and the hardware vendor provides hardware-specific minidrivers. A minidriver implements any functions that are specific to the device; for most functions, the minidriver calls the Microsoft class driver.

In a DirectShow filter graph, any WDM capture device appears as the WDM Video Capture filter. The WDM Video Capture filter configures itself based on the characteristics of the driver. It appears under a name provided by the driver — you will not see a filter called "WDM Video Capture Filter" anywhere in the graph.

Some older capture devices still use Video for Windows (VFW) drivers. Although these drivers are now obsolete, they are supported in DirectShow through the VFW Capture filter.


DirectShow Video Capture Filters

Capture filters in DirectShow have some features that distinguish them from other kinds of filters. Although the Capture Graph Builder hides many of the details, it is a good idea to read this section, in order to have a general understanding of DirectShow capture graphs.

Pin Categories

A capture filter often has two or more output pins that deliver the same kind of data — for example, a preview pin and a capture pin. Therefore, media types are not a good way to distinguish the pins. Instead, the pins are distinguished by their functionality, which is identified using a GUID, called the pin category.

For a discussion of how to query pins for their category, see Working with Pin Categories. For most applications, however, you will not have to query pins directly. Instead, various ICaptureGraphBuilder2 methods take parameters that specify the pin category on which to operate. The Capture Graph Builder automatically locates the correct pin.

Preview Pins and Capture Pins

Some video capture devices have separate output pins for preview and capture. The preview pin is used to render video to the screen, while the capture pin is used to write video to a file.

A preview pin and a capture pin have the following differences:

  • A preview pin drops frames as needed to maintain throughput on the capture pin.
  • Each frame from a capture pin is time-stamped with the stream time when the frame was captured. A preview pin does not time stamp the samples it delivers.

The reason that preview frames do not have time stamps is that the filter graph introduces a small amount of latency into the stream. If the capture time is used as the presentation time, the video renderer treats every sample as being slightly late. This can cause the video renderer to drop frames while it tries to catch up. Removing the time stamps ensures that the renderer presents each sample when it arrives, without dropping frames.

The pin category for preview pins is PIN_CATEGORY_PREVIEW. The category for capture pins is PIN_CATEGORY_CAPTURE.

Video Port Pins

A video port is a hardware connection between a video device (such as an analog TV tuner) and the video card. A video port enables the device to send video data directly to the graphics card. The video is displayed on the screen using a hardware overlay. A video port might be an actual cable that connects two devices on separate cards; or it might be a hard-wired connection on the same card.

The advantage of a video port is that the video goes directly into video memory, without any work by the CPU. However, video ports have some drawbacks:

  • A video port always uses the overlay surface during capture, regardless of whether you want to preview the video.
  • Flipping between frames occurs automatically, which makes it difficult to synchronize the flip with other video operations.

If a capture device uses a video port, the capture filter has a video port pin instead of a preview pin. The pin category for video port pins is PIN_CATEGORY_VIDEOPORT.

Every capture filter has at least one capture pin. In addition it might have a preview pin or a video port pin, but never both. Filters can have multiple capture pins and preview pins, each delivering a separate media type. Thus, a single filter could have a video capture pin, a video preview pin, an audio capture pin, and an audio preview pin. (There is nothing equivalent to a video port for audio, however.)

Upstream WDM Filters

Windows Driver Model (WDM) devices may require some additional filters upstream from the capture filter. These filters include the following:

  • TV Tuner Filter. Controls tuning for analog TV tuners.
  • TV Audio Filter. Controls audio settings for analog TV tuners.
  • Analog Video Crossbar Filter. Routes video and audio signals through the hardware device. For example, a device might have multiple inputs, such as S-Video and composite video. The crossbar filter enables the application to select the input.

Although these are separate filters in DirectShow, they typically represent the same hardware device. Each filter controls a different function of the device. The filters are connected by pins, but no media data moves across the pin connections. Therefore, the pins on these filters do not connect by establishing a media type. Instead, they use GUID values called mediums. Medium GUIDs are uniquely defined for a given device minidriver. For example, the TV Tuner filter and the Video Capture filter for the same TV card will both support the same medium, which enables the application to build the graph correctly.

In practice, as long as you are using ICaptureGraphBuilder2 to build your capture graphs, these filters are added to the graph automatically. For a more detailed discussion, see WDM Class Driver Filters.


Selecting a Capture Device

To select a capture device, use the System Device Enumerator, as described in the topic Using the System Device Enumerator. This helper object returns a collection of device monikers, selected by filter category. (A moniker is a COM object that contains information about another object, which enables the application to get information about the object without creating the object itself. Later, the application can use the moniker to create the object. For more information about monikers, see the documentation for IMoniker in the Platform SDK.)

For capture devices, the following categories are relevant.

Category GUID | Description
CLSID_AudioInputDeviceCategory | Audio capture devices
CLSID_VideoInputDeviceCategory | Video capture devices

A device can appear in both categories. The following code creates an enumerator for video capture devices:

ICreateDevEnum *pDevEnum = NULL;
IEnumMoniker *pEnum = NULL;

// Create the System Device Enumerator.
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
    CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
    reinterpret_cast<void**>(&pDevEnum));
if (SUCCEEDED(hr))
{
    // Create an enumerator for the video capture category.
    hr = pDevEnum->CreateClassEnumerator(
        CLSID_VideoInputDeviceCategory,
        &pEnum, 0);
}

The IEnumMoniker interface returns a list of IMoniker interfaces, each of which represents a device moniker. Typically, you would display a list of devices and enable the user to select one. Call the IMoniker::BindToStorage method, which returns an IPropertyBag interface pointer, and then call IPropertyBag::Read to read properties from the moniker. Properties include the following.

Property | Description
FriendlyName | The name of the device.
Description | A description of the device.
DevicePath | A unique string.

  • The FriendlyName property is available for every device. It contains a human-readable name for the device.
  • The Description property is available only for DV and D-VHS/MPEG camcorder devices. For more information, see MSDV Driver and MSTape Driver. If available, it contains a description of the device which is more specific than the FriendlyName property. Typically it includes the vendor name.
  • The DevicePath property is not a human-readable string, but is guaranteed to be unique per device. You can use this property to distinguish between two or more instances of the same model of device.

The following code example shows how to populate a list box with the device names:

HWND hList; // Handle to the list box.
IMoniker *pMoniker = NULL;
while (pEnum->Next(1, &pMoniker, NULL) == S_OK)
{
    IPropertyBag *pPropBag;
    hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
        (void**)(&pPropBag));
    if (FAILED(hr))
    {
        pMoniker->Release();
        continue;  // Skip this one, maybe the next one will work.
    }
    // Find the description or friendly name.
    VARIANT varName;
    VariantInit(&varName);
    hr = pPropBag->Read(L"Description", &varName, 0);
    if (FAILED(hr))
    {
        hr = pPropBag->Read(L"FriendlyName", &varName, 0);
    }
    if (SUCCEEDED(hr))
    {
        // Add it to the application's list box.
        USES_CONVERSION;
        (long)SendMessage(hList, LB_ADDSTRING, 0,
            (LPARAM)OLE2T(varName.bstrVal));
        VariantClear(&varName);
    }
    pPropBag->Release();
    pMoniker->Release();
}

When the user selects a device, create the capture filter for the device by calling IMoniker::BindToObject on the moniker. Then call AddFilter to add the filter to the filter graph:

IBaseFilter *pCap = NULL;
hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pCap);
if (SUCCEEDED(hr))
{
    hr = m_pGraph->AddFilter(pCap, L"Capture Filter");
}


Previewing Video

To build a video preview graph, call the ICaptureGraphBuilder2::RenderStream method as follows:

ICaptureGraphBuilder2 *pBuild; // Capture Graph Builder
// Initialize pBuild (not shown).

IBaseFilter *pCap; // Video capture filter.
/* Initialize pCap and add it to the filter graph (not shown). */

hr = pBuild->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
    pCap, NULL, NULL);

This example assumes the following:

  • pBuild was initialized, as described in About the Capture Graph Builder.
  • pCap was initialized, by creating an instance of the capture filter and adding it to the filter graph, as described in Selecting a Capture Device.

The first parameter to the RenderStream method specifies a pin category; for a preview graph, use PIN_CATEGORY_PREVIEW. The second parameter specifies a media type, as a major type GUID. For video, use MEDIATYPE_Video. DV devices deliver interleaved audio and video, for which the media type is MEDIATYPE_Interleaved. (For more information about DV capture, see Digital Video in DirectShow.)

The third parameter is a pointer to the capture filter's IBaseFilter interface. The next two parameters are not needed in this example. They are used to specify additional filters that might be needed to render the stream. Setting the last parameter to NULL causes the Capture Graph Builder to select a default renderer for the stream, based on the media type. For video, the Capture Graph Builder always uses the Video Renderer filter as the default renderer.

Note In Windows XP, although the Video Mixing Renderer (VMR) is the default video renderer for IGraphBuilder methods, it is not the default renderer for the RenderStream method. On any platform, the Capture Graph Builder always uses the old Video Renderer filter unless you specify otherwise.

Although the pin category is given as PIN_CATEGORY_PREVIEW, it does not matter whether the filter actually has a preview pin; it could have a video port pin or just a capture pin. In either case, the Capture Graph Builder automatically builds the correct graph.

The following diagram shows the simplest possible graph for previewing video.

Video Preview Graph

In this diagram, the capture filter has a preview pin, which connects directly to the video renderer.

If the capture filter has only a capture pin, the Capture Graph Builder inserts a Smart Tee filter, which splits the stream into a capture stream and a preview stream. This is described in more detail in Combining Video Capture and Preview.

In some cases, the video stream must go through the Overlay Mixer filter. If so, the RenderStream method adds it to the graph automatically.

See Also

  • Combining Video Capture and Preview


Capturing Video to a File

This section describes how to capture video from a device to a file. It contains the following topics:

  • Capturing Video to an AVI File
  • Capturing Video to a Windows Media File
  • Custom File Formats
  • Video Port Pins in File Capture
  • Capturing to Multiple Files
  • Combining Video Capture and Preview


Capturing Video to an AVI File

The following illustration shows the simplest possible graph for capturing video to an AVI file.

AVI Video Capture Graph

The AVI Mux filter takes the video stream from the capture pin and packages it into an AVI stream. An audio stream could also be connected to the AVI Mux filter, in which case the mux would interleave the two streams. The File Writer filter writes the AVI stream to disk.

To build the graph, start by calling the ICaptureGraphBuilder2::SetOutputFileName method, as follows:

IBaseFilter *pMux;
hr = pBuild->SetOutputFileName(
    &MEDIASUBTYPE_Avi,  // Specifies AVI for the target file.
    L"C:\\Example.avi", // File name.
    &pMux,              // Receives a pointer to the mux.
    NULL);              // (Optional) Receives a pointer to the file sink.

The first parameter specifies the file type — in this case, AVI. The second parameter gives the file name. For AVI, the SetOutputFileName method cocreates the AVI Mux filter and the File Writer filter and adds them to the graph. It also sets the file name on the File Writer filter, by calling the IFileSinkFilter::SetFileName method, and connects the two filters. The method returns a pointer to the AVI Mux in the third parameter. Optionally, it returns a pointer to the IFileSinkFilter interface in the fourth parameter. If you don't need this interface, you can set this parameter to NULL, as shown in the previous example.

Next, call the ICaptureGraphBuilder2::RenderStream method to connect the capture filter to the AVI Mux, as follows:

hr = pBuild->RenderStream(
    &PIN_CATEGORY_CAPTURE, // Pin category.
    &MEDIATYPE_Video,      // Media type.
    pCap,                  // Capture filter.
    NULL,                  // Intermediate filter (optional).
    pMux);                 // Mux or file sink filter.

// Release the mux filter.
pMux->Release();

The first parameter gives the pin category, which is PIN_CATEGORY_CAPTURE for capture. The second parameter gives the media type. The third parameter is a pointer to the capture filter's IBaseFilter interface. The fourth parameter is optional; it lets you route the video stream through an intermediate filter, such as an encoder, before passing it to the mux filter. Otherwise, set this parameter to NULL, as shown in the previous example. The fifth parameter is the pointer to the mux filter. This pointer is obtained by calling the SetOutputFileName method.

To capture audio, call RenderStream with the media type MEDIATYPE_Audio. If you are capturing audio and video from two separate devices, it is a good idea to make the audio stream the master stream. This helps to prevent drift between the two streams, because the AVI Mux filter adjust the playback rate on the video stream to match the audio stream. To set the master stream, call the IConfigAviMux::SetMasterStream method on the AVI Mux filter:

IConfigAviMux *pConfigMux = NULL;
hr = pMux->QueryInterface(IID_IConfigAviMux, (void**)&pConfigMux);
if (SUCCEEDED(hr))
{
    pConfigMux->SetMasterStream(1);
    pConfigMux->Release();
}

The parameter to SetMasterStream is the stream number, which is determined by the order in which you call RenderStream. For example, if you call RenderStream first for video and then for audio, the video is stream 0 and the audio is stream 1.

You may also want to set how the AVI Mux filter interleaves the audio and video streams, by calling the IConfigInterleaving::put_Mode method.

IConfigInterleaving *pInterleave = NULL;
hr = pMux->QueryInterface(IID_IConfigInterleaving, (void**)&pInterleave);
if (SUCCEEDED(hr))
{
    pInterleave->put_Mode(INTERLEAVE_CAPTURE);
    pInterleave->Release();
}

With the INTERLEAVE_CAPTURE flag, the AVI Mux performs interleaving at a rate that is suitable for video capture. You can also use INTERLEAVE_NONE, which means no interleaving — the AVI Mux will simply write the data in the order that it arrives. The INTERLEAVE_FULL flag means the AVI Mux performs full interleaving; however, this mode is less suitable for video capture because it requires the most overheard.

Encoding the Video Stream

You can encode the video stream by inserting an encoder filter between the capture filter and the AVI Mux filter. Use the System Device Enumerator or the Filter Mapper to select an encoder filter. (For more information, see Enumerating Devices and Filters.)

Specify the encoder filter as the fourth parameter to RenderStream, shown in bold in the following example:

IBaseFilter *pEncoder;
/* Create the encoder filter (not shown). */
// Add it to the filter graph.
pGraph->AddFilter(pEncoder, L"Encoder);

/* Call SetOutputFileName as shown previously. */

// Render the stream.
hr = pBuild->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
    pCap, pEncoder, pMux);
pEncoder->Release();

The encoder filter might support IAMVideoCompression or other interfaces for setting the encoding parameters. For a list of possible interfaces, see File Encoding and Decoding Interfaces.


Capturing Video to a Windows Media File

To capture video and encode it to a Windows Media Video (WMV) file, connect the capture pin to the WM ASF Writer filter:

Windows Media Capture Graph

The easiest way to build this graph is by specifing MEDIASUBTYPE_Asf in the ICaptureGraphBuilder2::SetOutputFileName method:

IBaseFilter* pASFWriter = 0;
hr = pBuild->SetOutputFileName(
    &MEDIASUBTYPE_Asf,   // Create a Windows Media file.
    L"C:\\VidCap.wmv",   // File name.
    &pASFWriter,         // Receives a pointer to the filter.
    NULL);  // Receives an IFileSinkFilter interface pointer (optional).

The value MEDIASUBTYPE_Asf tells the Capture Graph Builder to use the WM ASF Writer filter as the file sink. The Capture Graph Builder creates the filter, adds it to the graph, and calls IFileSinkFilter::SetFileName to set the name of the output file. It returns a pointer to the filter as an outgoing parameter (pASFWriter in the previous example).

Use the IConfigAsfWriter interface on the WM ASF Writer to set the Windows Media profile. You must do this before you connect any pins on the WM ASF Writer.

IConfigAsfWriter *pConfig = 0;
hr = pASFWriter->QueryInterface(IID_IConfigAsfWriter, (void**)&pConfig);
if (SUCCEEDED(hr))
{
     // Configure the ASF Writer filter.
    pConfig->Release();
}

For more information about setting the profile, see Creating ASF Files in DirectShow.

Call ICaptureGraphBuilder2::RenderStream to connect the capture filter to the ASF Writer:

hr = pBuild->RenderStream(
    &PIN_CATEGORY_CAPTURE,   // Capture pin.
    &MEDIATYPE_Video,        // Video. Use MEDIATYPE_Audio for audio.
    pCap,                    // Pointer to the capture filter.
    0,
    pASFWriter);             // Pointer to the sink filter (ASF Writer).

Each input pin on the WM ASF Writer filter corresponds to a stream in the Windows Media profile. You must connect every pin, so that the file content matches the profile.


Custom File Formats

If you have a custom mux or file-writer filter that supports your own file format, you can specify the CLSID as the first parameter of the SetOutputFileName method:

IBaseFilter *pMux = 0;
IFileSinkFilter *pSink = 0;
hr = pBuild->SetOutputFileName(&CLSID_MyCustomMuxFilter,
    L"C:\\VidCap.avi", &pMux, &pSink);

For more information about this usage, see ICaptureGraphBuilder2::SetOutputFileName.


Video Port Pins in File Capture

If the capture device has a video port, the video port pin must be connected to a video renderer, even if you only want to capture to a file.

If you call RenderStream with the value PIN_CATEGORY_CAPTURE and the device has a video port pin, the Capture Graph Builder automatically connects the video port pin to the Overlay Mixer filter and connects the Overlay Mixer to the Video Renderer. The Capture Graph Builder hides the video window by calling IVideoWindow::put_AutoShow with the value OAFALSE. If the application later calls RenderStream with PIN_CATEGORY_PREVIEW, the Capture Graph Builder calls put_AutoShow with the value OATRUE, in order to show the video window.

After you call RenderStream with PIN_CATEGORY_CAPTURE, you can check whether it has added the Video Renderer by querying the Filter Graph Manager for the IVideoWindow interface.


Capturing to Multiple Files

After you have captured some video to a file, you can switch to a new file by stopping the graph and setting the file name on the File Writer filter. Call the IFileSinkFilter::SetFileName method on the File Writer. You can get a pointer to the IFileSinkFilter interface when you build the graph, through the pSink parameter of the SetOutputFileName method. The following code shows how to do this:

IBaseFilter *pMux;
IFileSinkFilter *pSink
hr = pBuild->SetOutputFileName(&MEDIASUBTYPE_Avi, L"C:\\YourFileName.avi",
    &pMux, &pSink);
if (SUCCEEDED(hr))
{
    hr = pBuild->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
        pCap, NULL, pMux);

    if (SUCCEEDED(hr))
    {
        pControl->Run();
        /* Wait awhile, then stop the graph. */
        pControl->Stop();
        // Change the file name and run the graph again.
        pSink->SetFileName(L"YourFileName02.avi", 0);
        pControl->Run();
    }
    pMux->Release();
    pSink->Release();
}


Combining Video Capture and Preview

The previous sections describe how to capture video to various file formats. The section Previewing Video describes how to build a live preview graph. However, many applications must do both at once. To build a combined preview and file-writing graph, simply make two calls to ICaptureGraphBuilder2::RenderStream:

// Render the preview stream to the video renderer.
hr = pBuild->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, pCap,
    NULL, NULL);

// Render the capture stream to the mux.
hr = pBuild->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, pCap,
    NULL, pMux);

In this code, the Capture Graph Builder is hiding some details:

  • If the capture filter has a preview pin or video port pin, plus a capture pin, the RenderStream method simply renders both pins, as shown in the following illustration.

    Capture and Preview Graph

  • If the filter has only a capture pin, the Capture Graph Builder uses the Smart Tee filter to split the capture stream. The following illustration shows the graph with a Smart Tee.

    Capture and Preview Graph with Smart Tee Filter

The Smart Tee filter has a capture pin and a preview pin. It takes a single video stream from the capture filter and splits it into two streams, one for capture and one for preview. To maintain throughput on the capture pin, the preview pin drops frames as needed. It also strips the time stamps from each sample before delivering it, for the reasons discussed in the topic DirectShow Video Capture Filters.

Although the Smart Tee splits the stream, it does not physically duplicate the video data. Instead, it uses custom media sample objects that share the buffers. The samples are marked "read-only" to ensure that downstream filters do not write on the data.


Controlling a Capture Graph

The Filter Graph Manager's IMediaControl interface has methods for running, stopping, and pausing the entire graph. If the filter graph has capture and preview streams, however, you probably want to control the two streams independently. For example, you might want to preview the video without capturing it. You can do this through the ICaptureGraphBuilder2::ControlStream method.

Note This method does not work when capturing to an Advanced Systems Format (ASF) file.

Controlling the Capture Stream

The following code sets the video capture stream to run for four seconds, starting one second after the graph runs:

// Control the video capture stream.
REFERENCE_TIME rtStart = 10000000, rtStop = 50000000;
const WORD wStartCookie = 1, wStopCookie = 2;  // Arbitrary values.
hr = pBuild->ControlStream(
    &PIN_CATEGORY_CAPTURE, // Pin category.
    &MEDIATYPE_Video,      // Media type.
    pCap,                 // Capture filter.
    &rtStart, &rtStop,     // Start and stop times.
    wStartCookie, wStopCookie  // Values for the start and stop events.
);
pControl->Run();

The first parameter specifies which stream to control, as a pin category GUID. The second parameter gives the media type. The third parameter is a pointer to the capture filter. To control all the capture streams in the graph, set the second and third parameters to NULL.

The next two parameters define the times when the stream will start and stop, relative to the time when the graph starts running. Call IMediaControl::Run to run the graph. Until you run the graph, the ControlStream method has no effect. If the graph is already running, the settings take effect immediately.

The last two parameters are used for getting event notifications when the stream starts and stops. For each stream that you control using this method, the filter graph sends a pair of events: EC_STREAM_CONTROL_STARTED when the stream starts, and EC_STREAM_CONTROL_STOPPED when the stream stops. The values of wStartCookie and wStopCookie are used as the second event parameter. Thus, lParam2 in the start event equals wStartCookie, and lParam2 in the stop event equals wStopCookie. The following code shows how to get these events:

while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
{
    switch (evCode)
    {
    case EC_STREAM_CONTROL_STARTED:
    // param2 == wStartCookie
    break;

    case EC_STREAM_CONTROL_STOPPED:
    // param2 == wStopCookie
    break;

    }
    pEvent->FreeEventParams(evCode, param1, param2);
}

The ControlStream method defines some special values for the start and stop times.

 | Start | Stop
MAXLONGLONG | Never start this stream. | Do not stop until the graph stops.
NULL | Start immediately when the graph runs. | Stop immediately.

For example, the following code stops the capture stream immediately:

pBuild->ControlStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, pCap,
    0, 0,     // Start and stop times.
    wStartCookie, wStopCookie);

Although you can stop the capture stream and restart it later, this will create a gap in the time stamps. On playback, the video will appear to stall during the gap (depending on the file format).

Controlling the Preview Stream

To control the preview pin, call ControlStream but set the first parameter to PIN_CATEGORY_PREVIEW. This works just like it does for PIN_CATEGORY_CAPTURE, except that you cannot use reference times to specify the start and stop, because the preview frames do not have time stamps. Therefore, you must use NULL or MAXLONGLONG. Use NULL to start the preview stream:

pBuild->ControlStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, pCap,
    NULL,    // Start now.
    0,       // (Don't care.)
    wStartCookie, wStopCookie);

Use MAXLONGLONG to stop the preview stream:

pBuild->ControlStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, pCap,
    0,               // (Don't care.)
    MAXLONGLONG,     // Stop now.
    wStartCookie, wStopCookie);

It does not matter whether the preview stream comes from a preview pin on the capture filter, or from the Smart Tee filter. The ControlStream method works either way.

For video port pins, however, the method will fail. In that case, another approach is to hide the video window. Query the graph for IVideoWindow, and use the IVideoWindow::put_Visible method to show or hide the window.

// Hide the video window.
IVideoWindow *pVidWin = 0;
hr = pGraph->QueryInterface(IID_IVideoWindow, (void**)&pVidWin);
if (SUCCEEDED(hr))
{
    pVidWin->put_Visible(OAFALSE);
    pVidWin->Release();
}

Also, if you call IVideoWindow::put_AutoShow with the value OAFALSE before you run the graph, the Video Renderer filter hides the window until you specify otherwise. By default, the Video Renderer shows the window when you run the graph.

Remarks about Stream Control

The default behavior for a pin is to deliver samples when the graph runs. For example, suppose that you call ControlStream with PIN_CATEGORY_CAPTURE but not with PIN_CATEGORY_PREVIEW. When you run the graph, the preview stream will run immediately, while the capture stream will run at whatever time you specified in ControlStream.

If you are capturing more than one stream and sending them to a mux filter — for example, if you are capturing audio and video to an AVI file — you should control both streams in tandem. Otherwise, the mux filter might block waiting for one stream, as it tries to interleave the two streams. Set the same start and stop times on all capture streams before running the graph:

pBuild->ControlStream(&PIN_CATEGORY_CAPTURE,
    NULL, NULL,       // All capture streams.
    &rtStart, rtStop,
    wStartCookie, wStopCookie);

Internally, the ControlStream method uses the IAMStreamControl interface, which is exposed on the pins of the capture filter, the Smart Tee filter (if present), and possibly the mux filter. You can use this interface directly, instead of calling ControlStream, although there is no particular advantage to doing so.


Video Capture Tasks

This section describes the following tasks that a video capture application might need to perform:

  • Configuring a Video Capture Device
  • Working with Crossbars
  • Device Removal Notification
  • Capturing an Image From a Still Image Pin


Configuring a Video Capture Device

This section describes the following ways to configure a video capture device:

  • Display VFW Capture Dialog Boxes
  • Configure the Video Quality
  • Configure the Video Output Format


Display VFW Capture Dialog Boxes

A capture device that still uses a Video for Windows (VFW) driver can support any of the following three dialog boxes, which are used to configure the device.

Dialog box | Description
Video Source | Used to select the video input and to adjust device settings, such as picture brightness or contrast.
Video Format | Used to select the image dimensions and bit depth.
Video Display | Used to control the appearance of the rendered video.

To show one of these dialog boxes, do the following:

  1. Stop the filter graph.
  2. Query the capture filter for the IAMVfwCaptureDialogs interface. If QueryInterface succeeds, it means the capture device is a VFW device.
  3. Call IAMVfwCaptureDialogs::HasDialog to check if the driver supports the dialog box that you wish to display. The VfwCaptureDialogs enumeration defines flags for each of the VFW dialog boxes. HasDialog returns S_OK if the dialog box is supported. It returns S_FALSE otherwise, so check for the value S_OK directly, rather than using the SUCCEEDED macro.
  4. If the dialog box is supported, call IAMVfwCaptureDialogs::ShowDialog to display the dialog box.
  5. Restart the graph.

The following code shows these steps for the Video Source dialog box:

pControl->Stop(); // Stop the graph.

// Query the capture filter for the IAMVfwCaptureDialogs interface.
IAMVfwCaptureDialogs *pVfw = 0;
hr = pCap->QueryInterface(IID_IAMVfwCaptureDialogs, (void**)&pVfw);
if (SUCCEEDED(hr))
{
    // Check if the device supports this dialog box.
    if (S_OK == pVfw->HasDialog(VfwCaptureDialog_Source))
    {
        // Show the dialog box.
        hr = pVfw->ShowDialog(VfwCaptureDialog_Source, hwndParent);
    }
}
pControl->Run();


Configure the Video Quality

Windows Driver Model (WDM) video capture devices can support various properties that control the quality of the output, such as brightness, contrast, saturation, and so forth. To set these properties, do the following:

  1. Query the capture filter for the IAMVideoProcAmp interface.
  2. For each property that you want to control, call the IAMVideoProcAmp::GetRange method. This method returns the range of values that the device supports for that property, the default value, and the minimum increments for the settings. The IAMVideoProcAmp::Get method returns the current value of the property. The VideoProcAmpProperty enumeration defines flags for each of the properties.
  3. To set a property, call the IAMVideoProcAmp::Set method. To restore a property to its default value, use GetRange to find the default and pass that value to the Set method. You do not have to stop the filter graph when you set the properties.

The following code configures a trackbar control so that it can be used to set the brightness. The range of the trackbar corresponds to the brightness range that the device supports, and position of the trackbar corresponds to the device's initial brightness setting.

HWND hTrackbar; // Handle to the trackbar control.
// Initialize hTrackbar (not shown).

// Query the capture filter for the IAMVideoProcAmp interface.
IAMVideoProcAmp *pProcAmp = 0;
hr = pCap->QueryInterface(IID_IAMVideoProcAmp, (void**)&pProcAmp);
if (FAILED(hr))
{
    // The device does not support IAMVideoProcAmp, so disable the control.
    EnableWindow(hTrackbar, FALSE);
}
else
{
    long Min, Max, Step, Default, Flags, Val;

    // Get the range and default value.
    hr = m_pProcAmp->GetRange(VideoProcAmp_Brightness, &Min, &Max, &Step,
        &Default, &Flags);
    if (SUCCEEDED(hr))
    {
        // Get the current value.
        hr = m_pProcAmp->Get(VideoProcAmp_Brightness, &Val, &Flags);
    }
    if (SUCCEEDED(hr))
    {
        // Set the trackbar range and position.
        SendMessage(hTrackbar, TBM_SETRANGE, TRUE, MAKELONG(Min, Max));
        SendMessage(hTrackbar, TBM_SETPOS, TRUE, Val);
        EnableWindow(hTrackbar, TRUE);
    }
    else
    {
        // This property is not supported, so disable the control.
        EnableWindow(hTrackbar, FALSE);
    }
}


Configure the Video Output Format

A capture device can support a range of output formats. For example, a device might support 16-bit RGB, 32-bit RGB, and YUYV. Within each of these formats, the device can support a range of frame sizes.

In a WDM device, the IAMStreamConfig interface is used to report which formats the device supports, and to set the format. (For legacy VFW devices, use the Video Format VFW dialog box, as described in Display VFW Capture Dialog Boxes.) The IAMStreamConfig interface is exposed on the capture filter's capture pin, preview pin, or both. Use the ICaptureGraphBuilder2::FindInterface method to get the interface pointer:

IAMStreamConfig *pConfig = NULL;
hr = pBuild->FindInterface(
    &PIN_CATEGORY_PREVIEW, // Preview pin.
    0,    // Any media type.
    pCap, // Pointer to the capture filter.
    IID_IAMStreamConfig, (void**)&pConfig);

The device has a list of media types that it supports. For each media type, the device also provides a set of capabilities. These include the range of frame sizes that are available for that format, how well the device can stretch or shrink the image, and the range of frame rates.

To get the number of media types, call the IAMStreamConfig::GetNumberOfCapabilities method. The method returns two values:

  • The number of media types.
  • The size of the structure that holds the capabilities information.

The size value is necessary because the IAMStreamConfig interface is used for both audio and video (and could be extended to other media types). For video, the capabilities are described using the VIDEO_STREAM_CONFIG_CAPS structure, while audio uses the AUDIO_STREAM_CONFIG_CAPS structure.

To enumerate the media types, call the IAMStreamConfig::GetStreamCaps method with a zero-based index. The GetStreamCaps method returns a media type and the corresponding capability structure:

int iCount = 0, iSize = 0;
hr = pConfig->GetNumberOfCapabilities(&iCount, &iSize);

// Check the size to make sure we pass in the correct structure.
if (iSize == sizeof(VIDEO_STREAM_CONFIG_CAPS)
{
    // Use the video capabilities structure.

    for (int iFormat = 0; iFormat < iCount; iFormat++)
    {
        VIDEO_STREAM_CONFIG_CAPS scc;
        AM_MEDIA_TYPE *pmtConfig;
        hr = pConfig->GetStreamCaps(iFormat, &pmtConfig, (BYTE*)&scc);
        if (SUCCEEDED(hr))
        {
            /* Examine the format, and possibly use it. */

            // Delete the media type when you are done.
            DeleteMediaType(pmtConfig);
        }
}

Note how the structures are allocated for the GetStreamCaps method. The method allocates the media type structure, whereas the caller allocates the capabilities structure. Coerce the capabilities structure to a byte array pointer. After you are done with the media type, delete the AM_MEDIA_TYPE structure, along with the media type's format block.

You can configure the device to use a format returned in the GetStreamCaps method. Simply call IAMStreamConfig::SetFormat with the media type:

hr = pConfig->SetFormat(pmtConfig);

If the pin is not connected, it will attempt to use this format when it does connect. If the pin is already connected, it attempts to reconnect using the new format. In either case, it is possible that the downstream filter will reject the format.

You can also modify the media type before passing it to the SetFormat method. This is where the VIDEO_STREAM_CONFIG_CAPS structure comes in. It describes all of the valid ways to change the media type. To use this information, you must understand the details of that particular media type.

For example, suppose that GetStreamCaps returns a 24-bit RGB format, with a frame size of 320 x 240 pixels. You can get this information by examining the major type, subtype, and format block of the media type:

if ((pmtConfig.majortype == MEDIATYPE_Video) &&
    (pmtConfig.subtype == MEDIASUBTYPE_RGB24) &&
    (pmtConfig.formattype == FORMAT_VideoInfo) &&
    (pmtConfig.cbFormat >= sizeof (VIDEOINFOHEADER)) &&
    (pmtConfig.pbFormat != NULL))
{
    VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)pmtConfig.pbFormat;
    // pVih contains the detailed format information.
    LONG lWidth = pVih->bmiHeader.biWidth;
    LONG lHeight = pVih->bmiHeader.biHeight;
}

The VIDEO_STREAM_CONFIG_CAPS structure gives the minimum and maximum width and height that can be used for this media type. It also gives you the "step" size, which defines the increments by which you can adjust the width or height. For example, the device might return the following:

  • MinOutputSize: 160 x 120
  • MaxOutputSize: 320 x 240
  • OutputGranularityX: 8 pixels (horizontal step size)
  • OutputGranularityY: 8 pixels (vertical step size)

Given these numbers, you could set the width to anything in the range (160, 168, 176, ... 304, 312, 320) and the height to anything in the range (120, 128, 136, ... 104, 112, 120).

Video Format Sizes

To set a new frame size, directly modify the AM_MEDIA_TYPE structure returned in GetStreamCaps:

pVih->bmiHeader.biWidth = 160;
pVih->bmiHeader.biHeight = 120;
pVih->bmiHeader.biSizeImage = DIBSIZE(pVih->bmiHeader);

Then pass the media type to the SetFormat method, as described previously.

The MinFrameInterval and MaxFrameInterval members of VIDEO_STREAM_CONFIG_CAPS are the minimum and maximum length of each video frame, which you can translate into frame rates as follows:

frames per second = 10,000,000 / frame duration

To request a particular frame rate, modify the value of AvgTimePerFrame in the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure in the media type. The device may not support every possible value between the minimum and maximum, so the driver will use the closest value that it can. To see what value the driver actually used, call IAMStreamConfig::GetFormat after you call SetFormat.

Some drivers may report MAXLONGLONG (0x7FFFFFFFFFFFFFFF) for the value of MaxFrameInterval, which in effect means there is no maximum duration. However, you might want to enforce a minimum frame rate in your application, such as 1 fps.

See Also

  • About Media Types


Working with Crossbars

If a video capture card has more than one physical input, or supports more than one hardware path for data, then the filter graph may contain the Analog Video Crossbar Filter. The Capture Graph Builder automatically adds this filter when needed; it will be upstream from the capture filter. Depending on the hardware, the filter graph might contain more than one instance of the crossbar filter.

The crossbar filter exposes the IAMCrossbar interface, which you can use to route a particular input to a particular output. For example, a video card might have a coaxial connector and an S-Video input. These would be represented as input pins on the crossbar filter. To select an input, route the corresponding input pin to the crossbar's output pin, using the IAMCrossbar::Route.

To locate crossbar filters in the graph, you can use the ICaptureGraphBuilder2::FindInterface method to search for filters that support IAMCrossbar. For example, the following code searches for two crossbars:

// Search upstream for a crossbar.
IAMCrossbar *pXBar1 = NULL;
hr = pBuild->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pSrc,
        IID_IAMCrossbar, (void**)&pXBar1);
if (SUCCEEDED(hr))
{
    // Found one crossbar. Get its IBaseFilter interface.
    IBaseFilter *pFilter = NULL;
    hr = pXBar1->QueryInterface(IID_IBaseFilter, (void**)&pFilter);
    if (SUCCEEDED(hr))
    {
        // Search upstream for another crossbar.
        IAMCrossbar *pXBar2 = NULL;
        hr = pBuild->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pFilter,
                 IID_IAMCrossbar, (void**)&pXBar2);
        pFilter->Release();

        if (SUCCEEDED(hr))
        {
            /* ... */
            pXBar2->Release();
        }
    }
    pXBar1->Release();
}

For a more generalized approach, see the CCrossbar class in the AmCap Sample.

Once you have a pointer to the IAMCrossbar interface, you can get information about the crossbar filter, including the physical type of each pin, and the matrix of which input pins can be routed to which output pins.

  • To determine the type of physical connector to which a pin corresponds, call the IAMCrossbar::get_CrossbarPinInfo method. The method returns a member of the PhysicalConnectorType enumeration. For example, an S-Video pin returns the value PhysConn_Video_SVideo.

The get_CrossbarInfo method also indicates whether two pins are related to each other. For example, a video tuner pin might be related to an audio tuner pin. Related pins have the same pin direction, and are typically part of the same physical jack or connector on the card.

  • To determine whether you can route a particular input pin to a given output pin, call the IAMCrossbar::CanRoute method.
  • To determine the current routing between pins, call the IAMCrossbar::get_IsRoutedTo method.

The previous methods all specify pins by index number, with output pins and input pins both indexed from zero. Call the IAMCrossbar::get_PinCounts method to find the number of pins on the filter.

For example, the following code displays information about a crossbar filter to the console window:

// Helper function to associate a name with the type.
const char * GetPhysicalPinName(long lType)
{
    switch (lType)
    {
    case PhysConn_Video_Tuner:            return "Video Tuner";
    case PhysConn_Video_Composite:        return "Video Composite";
    case PhysConn_Video_SVideo:           return "S-Video";
    case PhysConn_Video_RGB:              return "Video RGB";
    case PhysConn_Video_YRYBY:            return "Video YRYBY";
    case PhysConn_Video_SerialDigital:    return "Video Serial Digital";
    case PhysConn_Video_ParallelDigital:  return "Video Parallel Digital";
    case PhysConn_Video_SCSI:             return "Video SCSI";
    case PhysConn_Video_AUX:              return "Video AUX";
    case PhysConn_Video_1394:             return "Video 1394";
    case PhysConn_Video_USB:              return "Video USB";
    case PhysConn_Video_VideoDecoder:     return "Video Decoder";
    case PhysConn_Video_VideoEncoder:     return "Video Encoder";

    case PhysConn_Audio_Tuner:            return "Audio Tuner";
    case PhysConn_Audio_Line:             return "Audio Line";
    case PhysConn_Audio_Mic:              return "Audio Microphone";
    case PhysConn_Audio_AESDigital:       return "Audio AES/EBU Digital";
    case PhysConn_Audio_SPDIFDigital:     return "Audio S/PDIF";
    case PhysConn_Audio_SCSI:             return "Audio SCSI";
    case PhysConn_Audio_AUX:              return "Audio AUX";
    case PhysConn_Audio_1394:             return "Audio 1394";
    case PhysConn_Audio_USB:              return "Audio USB";
    case PhysConn_Audio_AudioDecoder:     return "Audio Decoder";

    default:                              return "Unknown Type";
    }
}

void DisplayCrossbarInfo(IAMCrossbar *pXBar)
{
    HRESULT hr;
    long cOutput = -1, cInput = -1;
    hr = pXBar->get_PinCounts(&cOutput, &cInput);

    for (long i = 0; i < cOutput; i++)
    {
        long lRelated = -1, lType = -1, lRouted = -1;

        hr = pXBar->get_CrossbarPinInfo(FALSE, i, &lRelated, &lType);
        hr = pXBar->get_IsRouted(i, &lRouted);

        printf("Output pin %d: %s\n", i, GetPhysicalPinName(lType));
        printf("\tRelated out: %d, Routed in: %d\n", lRelated, lRouted);
        printf("\tSwitching Matrix: ");

        for (long j = 0; j < cInput; j++)
        {
            hr = pXBar->CanRoute(i, j);
            printf("%d-%s", j, (S_OK == hr ? "Yes" : "No"));
        }
        printf("\n\n");
    }

    for (i = 0; i < cInput; i++)
    {
        long lRelated = -1, lType = -1;

        hr = pXBar->get_CrossbarPinInfo(TRUE, i, &lRelated, &lType);

        printf("Input pin %d - %s\n", i, GetPhysicalPinName(lType));
        printf("\tRelated in: %d\n", lRelated);
    }
}

For a hypothetical card, this function might produce the following output:

Output pin 0: S-Video
    Related out: 2, Routed in: 0
    Switching Matrix: 0-Yes 1-No 2-No 3-No
Output pin 1 - Video Tuner
    Related out: 2, Routed in: 1
    Switching Matrix: 0-No 1-Yes 2-No 3-No
Output pin 2 - Audio decoder
    Related out: 1, Routed in: -1
    Switching Matrix: 0-No 1-No 2-Yes 3-Yes

Input pin 0 - S-Video
    Related in: 2
Input pin 1 - Video Tuner
    Related in: 3
Input pin 2 - Audio line
    Related in: 0
Input pin 3 - Audio tuner
    Related in: 1

On the output side, the S-Video and the video tuner are both related to the audio decoder. On the input side, the video tuner is related to the audio tuner, and the S-Video is related to the audio line in. The S-Video input is routed to the S-Video output; and the video tuner input is routed to the video tuner output. Currently nothing is routed to the audio decoder, but either the audio line in or the audio tuner could be routed to it.

You can change the existing routing by calling the IAMCrossbar::Route method.


Device Removal Notification

If the user removes a Plug and Play device that the graph was using, the filter graph manager posts an EC_DEVICE_LOST event. If the device becomes available again, the filter graph manager posts another EC_DEVICE_LOST event. However, the previous state of the capture filter is no longer valid. The application must rebuild the graph to use the device.

DirectShow does not send any event when a new device is plugged in. To learn when a new device is available, the application can monitor WM_DEVICECHANGE window messages. For more information, see "Device Management" in the Platform SDK documentation.

See Also

  • Event Notification in DirectShow


Capturing an Image From a Still Image Pin

Some cameras can produce a still image separate from the capture stream, and often the still image is of higher quality than the images produced by the capture stream. The camera may have a button that acts as a hardware trigger, or it may support software triggering. A camera that supports still images will expose a still image pin, which is pin category PIN_CATEGORY_STILL.

The recommended way to get still images from the device is to use the Windows Image Acquisition (WIA) APIs. For more information, see "Windows Image Acquisition" in the Platform SDK documentation. However, you can also use DirectShow to capture an image.

To trigger the still pin, use the IAMVideoControl::SetMode method when the graph is running, as follows:

pControl->Run(); // Run the graph.
IAMVideoControl *pAMVidControl = NULL;
hr = pCap->QueryInterface(IID_IAMVideoControl, (void**)&pAMVidControl);
if (SUCCEEDED(hr))
{
    // Find the still pin.
    IPin *pPin = 0;
    hr = pBuild->FindPin(pCap, PINDIR_OUTPUT, &PIN_CATEGORY_STILL, 0,
        FALSE, 0, &pPin);
    if (SUCCEEDED(hr))
    {
        hr = pAMVidControl->SetMode(pPin, VideoControlFlag_Trigger);
        pPin->Release();
    }
    pAMVidControl->Release();
}

Query the capture filter for IAMVideoControl. If the interface is supported, get a pointer to the still pin's IPin interface by calling the ICaptureGraphBuilder2::FindPin method, as shown in the previous example. Then call put_Mode with the IPin pointer and the VideoControlFlag_Trigger flag.

Note Depending on the camera, you might need to render the capture pin (PIN_CATEGORY_CAPTURE) before the still pin will connect.

Example: Using the Sample Grabber Filter

One way to capture the image is with the Sample Grabber filter. The Sample Grabber uses an application-defined callback function to process the image. For more information about the Sample Grabber filter, see Using the Sample Grabber.

The following example assumes that the still pin delivers an uncompressed RGB image. First, define a class that will implement the Sample Grabber's callback interface, ISampleGrabberCB:

// Class to hold the callback function for the Sample Grabber filter.
class SampleGrabberCallback : public ISampleGrabberCB
{
    // Implementation is described later.
}

// Global instance of the class.
SampleGrabberCallback g_StillCapCB;

The implementation of the class is described shortly.

Next, connect the still pin to the Sample Grabber, and connect the Sample Grabber to the Null Renderer filter. The Null Renderer simply discards media samples that it receives; the actual work will be done within the callback. (The only reason for the Null Renderer is to connect the Sample Grabber's output pin to something.) Call CoCreateInstance to create the Sample Grabber and Null Renderer filters, and call AddFilter to add both filters to the graph:

// Add the Sample Grabber filter to the graph.
IBaseFilter *pSG_Filter;
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
    IID_IBaseFilter, (void**)&pSG_Filter);
hr = pGraph->AddFilter(pSG_Filter, L"SampleGrab");

// Add the Null Renderer filter to the graph.
IBaseFilter *pNull;
hr = CoCreateInstance(CLSID_NullRendere, NULL, CLSCTX_INPROC_SERVER,
    IID_IBaseFilter, (void**)&pNull);
hr = pGraph->AddFilter(pSG_Filter, L"NullRender");

You can use the RenderStream method to connect all three filters in one method call, going from the still pin to the Sample Grabber, and from the Sample Grabber to the Null Renderer:

hr = pBuild->RenderStream(
    &PIN_CATEGORY_STILL, // Connect this pin ...
    &MEDIATYPE_Video,    // with this media type ...
    pCap,                // on this filter ...
    pSG_Filter,          // to the Sample Grabber ...
    pNull);              // ... and finally to the Null Renderer.

Now use the ISampleGrabber interface to configure the Sample Grabber so that it buffers samples:

// Configure the Sample Grabber.
ISampleGrabber *pSG;
hr = pSG_Filter->QueryInterface(IID_ISampleGrabber, (void**)&pSG);
pSG->SetOneShot(FALSE);
pSG->SetBufferSamples(TRUE);

Set the callback interface with a pointer to your callback object:

pSG->SetCallback(&g_StillCapCB, 0); // 0 = Use the SampleCB callback method.

Get the media type that the still pin used to connect with the Sample Grabber:

// Store the media type for later use.
AM_MEDIA_TYPE g_StillMediaType;
hr = pSG->GetConnectedMediaType(&g_StillMediaType);
pSG->Release();

This media type will contain the BITMAPINFOHEADER structure that defines the format of the still image. Free the media type before the application exits:

// On exit, remember to release the media type.
FreeMediaType(g_StillMediaType);

What follows is an example of the callback class. Note that the class implements IUnknown, which it inherits through the ISampleGrabber interface, but it does not keep a reference count. This is safe because the application creates the object on the stack, and the object remains in scope throughout the lifetime of the filter graph.

All of the work happens in the BufferCB method, which is called by the Sample Grabber whenever it gets a new sample. In the following example, the method writes the bitmap to a file:

class SampleGrabberCallback : public ISampleGrabberCB
{
public:
    // Fake referance counting.
    STDMETHODIMP_(ULONG) AddRef() { return 1; }
    STDMETHODIMP_(ULONG) Release() { return 2; }

    STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject)
    {
        if (NULL == ppvObject) return E_POINTER;
        if (riid == __uuidof(IUnknown))
        {
            *ppvObject = static_cast<IUnknown*>(this);
             return S_OK;
        }
        if (riid == __uuidof(ISampleGrabberCB))
        {
            *ppvObject = static_cast<ISampleGrabberCB*>(this);
             return S_OK;
        }
        return E_NOTIMPL;
    }

    STDMETHODIMP SampleCB(double Time, IMediaSample *pSample)
    {
        return E_NOTIMPL;
    }

    STDMETHODIMP BufferCB(double Time, BYTE *pBuffer, long BufferLen)
    {
        if ((g_StillMediaType.majortype != MEDIATYPE_Video) ||
            (g_StillMediaType.formattype != FORMAT_VideoInfo) ||
            (g_StillMediaType.cbFormat < sizeof(VIDEOINFOHEADER)) ||
            (g_StillMediaType.pbFormat == NULL))
        {
            return VFW_E_INVALIDMEDIATYPE;
        }
        HANDLE hf = CreateFile("C:\\Example.bmp", GENERIC_WRITE,
        FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
        if (hf == INVALID_HANDLE_VALUE)
        {
            return E_FAIL;
        }
        long cbBitmapInfoSize = g_StillMediaType.cbFormat - SIZE_PREHEADER;
        VIDEOINFOHEADER *pVideoHeader =
           (VIDEOINFOHEADER*)g_StillMediaType.pbFormat;

        BITMAPFILEHEADER bfh;
        ZeroMemory(&bfh, sizeof(bfh));
        bfh.bfType = 'MB';  // Little-endian for "MB".
        bfh.bfSize = sizeof( bfh ) + BufferLen + cbBitmapInfoSize;
        bfh.bfOffBits = sizeof( BITMAPFILEHEADER ) + cbBitmapInfoSize;

        // Write the file header.
        DWORD dwWritten = 0;
        WriteFile( hf, &bfh, sizeof( bfh ), &dwWritten, NULL );
        WriteFile(hf, HEADER(pVideoHeader), cbBitmapInfoSize, &dwWritten, NULL);
        WriteFile( hf, pBuffer, BufferLen, &dwWritten, NULL );
        CloseHandle( hf );
        return S_OK;

    }
};


Digital Video in DirectShow

This section gives an overview of digital video (DV) in Microsoft® DirectShow®. It contains the following topics:

  • About Digital Video in DirectShow
  • Type-1 vs. Type-2 DV AVI Files
  • DirectShow DV Filters
  • Capture DV to File
  • Transmit DV from File to Tape

See Also

  • Controlling a DV Camcorder


About Digital Video in DirectShow

Digital video is captured from the MSDV Driver, which appears as a DirectShow filter in the video capture category when the device is plugged in. The friendly name of the filter is Microsoft DV Camera and VCR, or possibly a localized equivalent. For some DV devices, the Description property contains a more specific description of that model. See Selecting a Capture Device for more information.

MSDV has two output pins. One pin delivers interleaved audio-video. The other pin delivers DV-encoded video with no audio. MSDV cannot stream from both pins at once, so only one of the output pins can be connected at a time. For information on capturing from the device, see Capture DV to File.

Capturing DV data from the device

Most DV camcorders have a video tape recorder (VTR) unit, which can transmit from tape to the computer. From an application perspective, capturing from the tape works the same as capturing live video from the camera. For information about controling the transport (starting and stopping the tape, rewinding, and so forth), see Controlling a DV Camcorder.

In many camcorders, switching between VTR mode and camera mode causes the device to switch off. Therefore, DirectShow may lose the device when the user switches modes. For information about device removal events, see Device Removal Notification.

MSDV has one input pin, which is used to transmit video from the computer to the device. The output and input pins cannot be connected at the same time, because the device cannot stream in both directions at the same time. For information about sending DV to the device, see Transmit DV from File to Tape.

Transmitting DV data to the device


Type-1 vs. Type-2 DV AVI Files

DV cameras produce interleaved audio-video; each frame of video also contains the audio information. If you save DV data to an AVI file, you have a choice:

  • Store the interleaved data as one stream in the AVI file. This is known as a type-1 file.
  • Split the interleaved data into separate audio and video streams. This is known as a type-2 file.

For video capture, where maximum throughput is crucial, it is better to use a type-1 file, because type-2 files carry redundant audio data. (The video stream still has the audio data. The audio is simply hidden by labeling the stream as video.) Also, writing a type-2 file requires some additional processor time to split the interleaved stream.

On the other hand, type-1 files are less efficient for real-time editing. The application must extract the audio from the interleaved stream, make the edits, and interleave the data again. Also, the type-1 format is not compatible with Microsoft® Video for Windows® (VFW). DirectShow can handle both types of files.

For more information about DV in AVI files, see DV Data in the AVI File Format


DirectShow DV Filters

DirectShow provides several filters to support digital video (DV):

  • MSDV Driver. Represents a DV capture device.
  • DV Splitter. Splits an interleaved DV stream into an audio stream and a DV-encoded video stream.
  • DV Video Decoder. Decodes DV video to uncompressed video.
  • DV Video Encoder. Encodes uncompressed video to DV-encoded video.
  • DV Muxer. Combines audio and DV video into a single interleaved stream.

The DV Splitter and DV Video Decoder work together. The splitter takes the interleaved stream and outputs separate audio and DV video streams. The decoder converts the DV video to uncompressed video.

DV Splitter and DV Decoder

The DV Video Encoder and the DV Muxer reverse the process: The encoder converts uncompressed video to DV video, and the mux combines audio and DV video to create a single interleaved stream.

DV Encoder and DV Muxer

Another way to think of the splitter and mux filters is that the DV Mux converts type-2 DV to type-1 DV, while the DV Splitter does the opposite, converting type-1 to type-2.

Conversion between type-1 and type-2 DV

See Also

  • Type-1 vs. Type-2 DV AVI Files


Capture DV to File

This section describes how to capture digital video (DV) from a DV camera or from a VTR tape.

  1. Create an instance of the MSDV Driver filter. For more information, see Selecting a Capture Device.
  2. Initialize the Capture Graph Builder, as described in About the Capture Graph Builder.
  3. Build the capture graph, depending on the target file type:
    • Capture a Type-1 DV File
    • Capture a Type-2 DV File
    • Capture DV to Uncompressed RGB
  4. Run the graph.

Capturing from a VTR tape works just like capturing live video from the camera, except that you must play the tape, as described in Controlling a DV Camcorder. To avoid losing any frames, run the graph first, and then play the tape. When you are done transmitting, stop the tape first and then stop the graph.

Note The camcorder must be in VTR mode. See Device Type.

See Also

  • Type-1 vs. Type-2 DV AVI Files
  • Video Capture


Capture a Type-1 DV File

A type-1 DV AVI file contains a single interleaved stream. To capture a type-1 file while previewing, use the filter graph shown in the following diagram.

Type-1 Capture with Preview

Filters in this graph include:

  • The Smart Tee filter splits the interleaved DV into a capture stream and a preview stream. Both streams contain the same interleaved data.
  • The AVI Mux and File Writer write the interleaved stream to disk.
  • The DV Splitter splits the interleaved stream into a DV video stream and an audio stream. Both streams are rendererd for preview.
  • The DV Video Decoder decodes the DV video stream for previewing.

Build this graph as follows:

ICaptureGraphBuilder2 *pBuilder;  // Capture graph builder.
IBaseFilter           *pDV;       // DV capture filter (MSDV)
IBaseFilter           *pAviMux    // Avi Mux filter.

// Initialize pDV (not shown).
// Create and initialize the Capture Graph Builder (not shown).

// Create the file-writing section of the graph.
hr = pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi,
    OLESTR("C:\\Example1.avi"), &pAviMux, 0);

// Render the capture stream.
hr = pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
    pDV, 0, pAviMux);

// Render the preview stream.
hr = pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Interleaved,
    pDV, 0, 0);

// Remember to release all interfaces.
  1. Call ICaptureGraphBuilder2::SetOutputFileName to connect the AVI Mux filter to the File Writer filter.
  2. Call ICaptureGraphBuilder2::RenderStream with the pin category PIN_CATEGORY_CAPTURE to render the capture stream. The Capture Graph Builder automatically inserts the Smart Tee filter.
  3. Call RenderStream again, but with the pin category PIN_CATEGORY_PREVIEW, to render the preview stream. Skip this call if you do not want to preview the video.

For both calls to RenderStream, the media type is MEDIATYPE_Interleaved, meaning interleaved DV video. In this code, the Capture Graph Builder automatically adds every filter that is needed, except for the MSDV capture filter.


Capture a Type-2 DV File

A type-2 DV AVI file has two streams, one that contains DV video and another that contains audio. To capture a type-2 file while previewing, use the filter graph shown in the following diagram.

Type-2 Capture with Preview

This graph is almost the same as the graph for type-1 capture (see Capture a Type-1 DV File). However, the capture stream goes through the DV Splitter filter before reaching the AVI Mux filter. The AVI Mux therefore receives two streams, an audio stream and a DV-encoded video stream.

Build this graph as follows:

ICaptureGraphBuilder2 *pBuilder;  // Capture graph builder.
IBaseFilter           *pDV;       // DV capture filter (MSDV)
IBaseFilter           *pAviMux    // Avi Mux filter.
IBaseFilter           *pDVSplit;  // DV Splitter

// Initialize pDV (not shown).
// Create and initialize the Capture Graph Builder (not shown).

// Create the DV Splitter and add it to the filter graph.
hr = CoCreateInstance(CLSID_DVSplitter, 0, CLSCTX_INPROC_SERVER,
    IID_IBaseFilter, reinterpret_cast<void**>)(&pDVSplit));
hr = pGraph->AddFilter(pDVSplit, L"DV Splitter");

// Create the file-writing section of the graph.
hr = pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi,
    OLESTR("C:\\Example2.avi"), &pAviMux, 0);

// Connect the capture pin to the DV Splitter, and render one stream from
// the DV Splitter to the AVI Mux.
hr = pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
    pDV, pDVSplit, pAviMux);

// Render the other stream from the DV splitter to the AVI Mux.
hr = pBuilder->RenderStream(0, 0, pDVSplit, 0, pAviMux);

// Render the preview stream.
hr = pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Interleaved,
    pDV, 0, 0);

// Remember to release all interfaces.
  1. Create the DV Splitter and add it to the filter graph.
  2. Call ICaptureGraphBuilder2::SetOutputFileName to connect the AVI Mux filter to the File Writer filter.
  3. Call ICaptureGraphBuilder2::RenderStream to connect the MSDV capture filter to the DV Splitter. This call also connects one of the DV Splitter's output pins to the AVI Mux.
  4. Call RenderStream again to connect the DV Splitter's other pin to the AVI Mux.
  5. Call RenderStream a third time to render the preview stream. Skip this step if do not want to preview the video.


Capture DV to Uncompressed RGB

This example shows how to capture DV from the camcorder and save it to a file as uncompressed RGB while previewing. Use the filter graph shown in the following diagram.

Capturing Uncompressed RGB to File

The DV Splitter filter splits the interleaved audio/video into separate video and audio streams The DV-encoded video goes to the DV Video Decoder filter, which outputs uncompressed RGB video. The RGB video is routed through the Smart Tee filter to the AVI Mux filter (for capture) and the video renderer (for preview). Meanwhile, the audio stream from the DV Splitter goes through the Infinite Pin Tee filter to the AVI Mux and the audio renderer. The Filter Graph Manager keeps all of these streams synchronized, using the time stamps on the samples and the graph reference clock.

This graph might seem unnecessarily complicated, but it ensures that the DV-encoded video stream is decoded only once, which minimizes the CPU requirements. Also, note that the video goes through the Smart Tee filter while the audio goes through the Infinite Pin Tee filter. The Smart Tee can drop preview frames to improve capture performance, which is desirable for video but not for audio, where dropped samples are highly noticeable. Also, because the audio requires much lower bandwidth than the video, there is relatively little chance of dropping audio in the file.

You must build this graph one section at a time, but the RenderStream method can still help. Use the following code:

// Build the file-writing section of the graph.
hr = pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi,
    OLESTR("C:\\Example3.avi"), &pMux, 0);

// MSDV to DV splitter.
IBaseFilter *pDVSplit;  // Create the DV Splitter (CLSID_DVSplitter)
hr = pBuilder->RenderStream(0, &MEDIATYPE_Interleaved, pDV, 0, pDVSplit);

// Splitter to DV Decoder to Smart Tee.
IBaseFilter *pDVDec; // Create the DV Decoder (CLSID_DVVideoCodec)
IBaseFilter *pSmartTee; // Create the Smart Tee (CLSID_SmartTee)
hr = pBuilder->RenderStream(0, &MEDIATYPE_Video, pDVSplit, pDVDec,
    pSmartTee);

// Smart Tee (video) to Avi Mux.
IPin *pPin1;
hr = pBuilder->FindPin(pSmartTee, PINDIR_OUTPUT, 0, 0, TRUE, 0, &pPin1);
hr = pBuilder->RenderStream(0, 0, pPin1, 0, pMux);

// Smart Tee to preview.
IPin *pPin2;
hr = pBuilder->FindPin(pSmartTee, PINDIR_OUTPUT, 0, 0, TRUE, 1, &pPin2);
hr = pBuilder->RenderStream(0, 0, pPin2, 0, pMux);

// DV Splitter (audio) to Infinite Tee to Avi Mux.
IBaseFilter *pTee; // Create the Infinite Pin Tee (CLSID_InfTee)
hr = pBuilder->RenderStream(0, &MEDIATYPE_Audio, pDVSplit, pTee, pMux);

// Infinite Pin Tee to preview.
hr = pBuilder->RenderStream(0, 0, pTee, 0, 0);

You must create the DV Splitter, DV Video Decoder, Smart Tee, and Infinite Pin Tee filters, and add each one to the filter graph. (For brevity, these steps are omitted from the previous code.) This example uses the ICaptureGraphBuilder2::FindPin method to find the capture and preview pins on the Smart Tee filter; capture is always output pin 0, and preview is output pin 1.


Transmit DV from File to Tape

Transmit from DV AVI file to VTR tape is complicated somewhat by the fact that files can type-1 or type-2. To transmit a DV file to tape, do the following:

  1. Create an instance of the MSDV Driver filter. For more information, see Selecting a Capture Device.
  2. Initialize the Capture Graph Builder, as described in About the Capture Graph Builder.
  3. Build the graph, depending on the file type:
    • Transmit from Type-1 File
    • Transmit from Type-2 File
  4. Put the device into record-pause mode, as described in Controlling a DV Camcorder.
  5. Pause the filter graph. While the filter graph is paused, it sends a continuous stream that repeats the first frame of video.
  6. To start transmitting, put the device into record mode and then run the filter graph. It takes the device a certain amount of time until the recording head is able to record, so wait for about two seconds before running the graph. This might result in a few duplicated frames at the beginning of the tape, but it ensures that no data is lost.

Note The camcorder must in VTR mode. See Device Type.


Transmit from Type-1 File

To transmit a type-1 file while previewing the file, use the filter graph shown in the following diagram.

Type-1 Transmit with Preview

Filters in this graph include:

  • The AVI Splitter parses the AVI file. For a type-1 DV file, the output pin delivers interleaved DV samples.
  • The Infinite Pin Tee filter splits the interleaved DV into a transmit stream and a preview stream. Both streams contain the same interleaved data. (This graph uses the Infinite Pin Tee instead of the Smart Tee, because there is no danger of dropping frames when reading from a file, as there is with live capture.)
  • The DV Splitter splits the interleaved stream into a DV video stream, which is decoded by the DV Video Decoder, and an audio stream. Both streams are rendererd for preview.

Build this graph as follows:

ICaptureGraphBuilder2 *pBuilder;  // Capture graph builder.
IBaseFilter           *pDV;       // DV capture filter (MSDV)

// Initialize pDV (not shown).
// Create and initialize the Capture Graph Builder (not shown).

// Add the Infinite Pin Tee filter to the graph.
IBaseFilter *pTee;
hr = CoCreateInstance(CLSID_InfTee, 0, CLSCTX_INPROC_SERVER
    IID_IBaseFilter, reinterpret_cast<void**>)(&pTee));
hr = pGraph->AddFilter(pTee, L"Tee");

// Add the File Source filter to the graph.
IBaseFilter *pFileSource;
hr = pGraph->AddSourceFilter(
    L"C:\\YourFileNameHere.avi",
    L"Source",
    &pFileSource);

// Add the AVI Splitter filter to the graph.
IBaseFilter *pAviSplit;
hr = CoCreateInstance(CLSID_AviSplitter, 0, CLSCTX_INPROC_SERVER
    IID_IBaseFilter, reinterpret_cast<void**>)(&pAviSplit));
hr = pGraph->AddFilter(pAviSplit, L"AVI Splitter");

// Connect the file source to the AVI Splitter.
hr = pBuilder->RenderStream(0, 0, pFileSource, 0, pAviSplit);
if (FAILED(hr))
{
    // This is not an AVI file.
}

// Connect the file source to the Infinite Pin Tee.
hr = pBuilder->RenderStream(0, &MEDIATYPE_Interleaved, pAviSplit, 0, pTee);
if (FAILED(hr))
{
    // This is not a type-1 DV file.
}

// Render one stream from the Infinite Pin Tee to MSDV, for transmit.
hr = pBuilder->RenderStream(0, 0, pTee, 0, pDV);

// Render another stream from the Infinite Pin Tee for preview.
hr = pBuilder->RenderStream(0, 0, pTee, 0, 0);
  1. Call IGraphBuilder::AddSourceFilter to add the source filter to the filter graph.
  2. Create the AVI Splitter and the Infinite Pin Tee, and add them to the graph.
  3. Call ICaptureGraphBuilder2::RenderStream to connect the source filter to the AVI Splitter. Specifying MEDIATYPE_Interleaved to ensure that the method fails if the source file is not a type-1 DV file. In that case, you can back out and attempt to build a type-2 transmit graph instead.
  4. Call RenderStream again to route the interleaved stream from the AVI Splitter to the Infinite Pin Tee
  5. Call RenderStream a third time to route one stream from the Infinite Pin Tee to the MSDV filter, for transmit to the device.
  6. Call RenderStream one last time, to build the preview section of the graph.

If you do not want preview, simply connect the file source to the MSDV filter:

hr = pBuilder->RenderStream(0, &MEDIATYPE_Interleaved, pFileSource, 0, pDV);


Transmit from Type-2 File

To transmit a type-2 file while previewing, use the filter graph shown in the following diagram.

Type-2 Transmit with Preview

A type-2 file has two streams, one audio stream and one DV-encoded video stream. This graph uses the DV Muxer filter to combine the audio and video streams. It sends the interleaved stream to the MSDV filter, but splits the stream again for preview.

Build this graph as follows:

// Add the DV Mux filter to the graph.
IBaseFilter *pDVMux;
hr = CoCreateInstance(CLSID_DVMux, 0, CLSCTX_INPROC_SERVER
    IID_IBaseFilter, reinterpret_cast<void**>)(&pDVMux));
hr = pGraph->AddFilter(pDVMux, L"DV Mux");

// Add the File Source filter to the graph.
IBaseFilter *pFileSource;
hr = pGraph->AddSourceFilter(L"C:\\Example2.avi", L"Source",
    &pFileSource);

hr = pBuilder->RenderStream(0, 0, pFileSource, 0, pDVMux);
hr = pBuilder->RenderStream(0, 0, pFileSource, 0, pDVMux);

// Add the Infinite Pin Tee filter to the graph.
IBaseFilter *pTee;
hr = CoCreateInstance(CLSID_InfTee, 0, CLSCTX_INPROC_SERVER
    IID_IBaseFilter, reinterpret_cast<void**>)(&pTee));
hr = pGraph->AddFilter(pTee, L"Tee");

hr = pBuilder->RenderStream(0, 0, pDVMux, 0, pTee);
hr = pBuilder->RenderStream(0, 0, pTee, 0, pDV);
hr = pBuilder->RenderStream(0, &MEDIATYPE_Interleaved, pTee, 0, 0);

This code makes several calls to RenderStream:

The first two connect the source filter to the AVI Splitter and the AVI Splitter to the DV Mux. In the first call, the Capture Graph Builder automatically adds the AVI Splitter to the graph and connects one of the AVI Splitter's output pins to the DV Mux. In the second call, the Capture Graph Builder finds the AVI Splitter's second output pin and connects that to the DV Mux.

The third call to RenderStream connects the DV Muxer to the Infinite Pin Tee filter. The next call connects one stream from the Infinite Pin Tee to the MSDV capture filter. This stream is transmitted to the device. The last call to RenderStream builds the preview section of the graph.

If you do not want to preview while transmitting, you can omit the Infinite Pin Tee, and simply connect the DV Mux to the MSDV filter:

hr = pBuilder->RenderStream(0, 0, pDVMux, 0, pDV);


Controlling a DV Camcorder

This article describes how to control a digital video (DV) camcorder using Microsoft® DirectShow®. It contains the following sections:

  • External Device Interfaces for DV Camcorders
  • Getting Device Information
  • Device Control
  • Issuing Raw AV/C Commands

See Also

  • Digital Video in DirectShow.


External Device Interfaces for DV Camcorders

The WDM Video Capture filter exposes three interfaces for controlling a camcorder.

IAMExtDevice | The base interface for external device control.
IAMExtTransport | Controls the VCR functions.
IAMTimecodeReader | Reads timecode from the device.

Note To use these interfaces with the MSDV camcorder driver, include the header file XPrtDefs.h in your project.

After you select a capture device and create an instance of the capture filter, query the filter for these interfaces. The following example declares a custom structure that holds the interface pointers, along with Boolean values that specify the availability of each interface:

struct _MyDevCap
{
    IAMExtDevice       *pDevice;
    IAMExtTransport    *pTransport;
    IAMTimecodeReader  *pTimecode;
    BOOL                bHasDevice;
    BOOL                bHasTransport;
    BOOL                bHasTimecode;
} MyDevCap;

HRESULT hr;
IBaseFilter *pDVCam;  // Pointer to the capture filter.

// Create an instance of the capture filter (not shown).

hr = pDVCam->QueryInterface(IID_IAMExtDevice, (void **)&MyDevCap.pDevice);
MyDevCap.bHasDevice = (SUCCEEDED(hr));

hr = pDVCam->QueryInterface(IID_IAMExtTransport, (void **)&MyDevCap.pTransport);
MyDevCap.bHasTransport = (SUCCEEDED(hr));

hr = pDVCam->QueryInterface(IID_IAMTimecodeReader, (void **)&MyDevCap.pTimecode);
MyDevCap.bHasTimecode = (SUCCEEDED(hr));


Getting Device Information

The device control interfaces enable you to query the device for its status and capabilities. This section describes a few of the more useful items you can retrieve. For more information, refer to the interface references.

  • Device Type
  • Device Transport State
  • Getting Timecode from the Device
  • Signal Format


Device Type

The most important information about a capture device is whether it has VCR functions, or is strictly a camera. To find out, call the IAMExtDevice::GetCapability method with the value ED_DEVCAP_DEVICE_TYPE. If the method returns the value ED_DEVTYPE_VCR, the device is a VCR and has functions such as pause, stop, fast-forward, and rewind. The following code example shows how to query the device type:

if (MyDevCap.bHasDevice)
{
    LONG lDeviceType = 0;
    MyDevCap.pDevice->GetCapability(ED_DEVCAP_DEVICE_TYPE, &lDeviceType, 0);

    if (lDeviceType == ED_DEVTYPE_VCR)
    {
        // Device is a VCR. Enable all VCR functions.
    }
    else
    {
        // Device is a camera.
        // Enable record and record-pause; disable other functions.
    }
}

A camcorder can typically switch between VCR and camera functions. It returns the corresponding device type. If the camcorder goes offline, you should query it again the next time it becomes available. The filter graph manager posts an EC_DEVICE_LOST event when the device is removed.


Device Transport State

To retrieve the current state of the device, such as play, pause, or stop, call the IAMExtTransport::get_Mode method. The method retrieves a constant that indicates the device state:

Value | Device State
ED_MODE_PLAY | Play
ED_MODE_STOP | Stop
ED_MODE_FREEZE | Pause
ED_MODE_FF | Fast-forward
ED_MODE_REW | Rewind
ED_MODE_RECORD | Record
ED_MODE_RECORD_FREEZE | Record-pause

The following code checks the device state:

LONG State;
hr = MyDevCap.pTransport->get_Mode(&State);
if (SUCCEEDED(hr))
{
    switch (State)
    {
        case ED_MODE_PLAY:
        // ...
    }
}


Getting Timecode from the Device

While a DV tape is playing or is in record-pause mode, you can retrieve the SMPTE timecode or the absolute track number. To do this, call the IAMTimecodeReader::GetTimecode method. This method takes a pointer to a TIMECODE_SAMPLE structure, which describes the timecode. Before calling the method, initialize the dwFlags member of the structure. Use the value ED_DEVCAP_TIMECODE_READ to retrieve the timecode or the value ED_DEVCAP_ATN_READ to retrieve the absolute track number.

The timecode member of the TIMECODE_SAMPLE structure is a TIMECODE structure. When the method returns, the dwFrames member of the TIMECODE structure contains the timecode or track number. For timecode, the hours, minutes, seconds, and frames are packed into a DWORD as binary coded decimal (BCD) values, with the format hhmmssff. Use bitmasks to extract the individual values.

The following example retrieves the timecode and track number.

if (MyDevCap.bHasTimecode)
{
    TIMECODE_SAMPLE TimecodeSample;
    TimecodeSample.timecode.dwFrames = 0;
    char szBuf[32];

    TimecodeSample.dwFlags = ED_DEVCAP_TIMECODE_READ;
    if (hr = MyDevCap.pTimecode->GetTimecode(&TimecodeSample),  SUCCEEDED(hr))
    {
        DWORD dwTime = TimecodeSample.timecode.dwFrames; // Packed BCD value.
        int hour  = ((dwTime & 0x0F000000) >> 24) +
                    (10 * ((dwTime & 0xF0000000) >> 28));
        int min   = ((dwTime & 0x0F0000) >> 16) +
                    (10 * ((dwTime & 0xF00000) >> 20));
        int sec   = ((dwTime & 0x0F00) >> 8) +
                    (10 * ((dwTime & 0xF000) >> 12));
        int frame = (dwTime & 0x0F) +
                    (10 * ((dwTime & 0xF0) >> 4));
    }

    TimecodeSample.dwFlags = ED_DEVCAP_ATN_READ;
    if (hr = MyDevCap.pTimecode->GetTimecode(&TimecodeSample), SUCCEEDED(hr))
    {
        DWORD dwTrackNumber = TimecodeSample.timecode.dwFrames;
    }
}


Signal Format

A DV camcorder's signal format can be NTSC or PAL, either standard or long-play. To find out the signal format, call the IAMExtTransport::GetTransportBasicParameters method and pass in the ED_TRANSBASIC_INPUT_SIGNAL flag. The method returns a defined constant, indicating the format.

The following code checks the signal format, and uses this value to calculates the average time per frame. The variable Mode receives the signal-format constant.

LONG Mode, AvgTimePerFrame;
hr = MyDevCap.pTransport->GetTransportBasicParameters(
        ED_TRANSBASIC_INPUT_SIGNAL, &Mode, NULL);
if (SUCCEEDED(hr))
{
    switch (Mode)
    {
    case ED_TRANSBASIC_SIGNAL_525_60_SD: // NTSC SD
        AvgTimePerFrame = 33;  // 33 msec (29.97 FPS)
        break;
    case ED_TRANSBASIC_SIGNAL_525_60_SDL: // NTSC SDL
        AvgTimePerFrame = 33;
        break;
    case ED_TRANSBASIC_SIGNAL_625_50_SD: // PAL SD
        AvgTimePerFrame = 40;  // 40 msec (25 FPS)
        break;
    case ED_TRANSBASIC_SIGNAL_625_50_SDL: // PAL SDL
        AvgTimePerFrame = 40;
        break;
    default:
        // Unknown type
        AvgTimePerFrame = 33; // Default
        break;
    }
}


Device Control

To control a camcorder device, use the IAMExtTransport::put_Mode method. Specify the new state by using one of the constants listed in the previous section. For example, to stop the device, use the following:

MyDevCap.pTransport->put_Mode(ED_MODE_STOP);

Because the camcorder is a physical device, there might be a lag between when the command is issued and when it completes. Your application should create a secondary thread that waits for the command to finish. When the command finishes, the thread can update the user interface. Use a critical section to serialize the state change.

Some camcorders can notify the application when the state of the device changes. If the device supports this feature, the secondary thread can wait for the notification. If not, the application must poll the device at periodic intervals.

Notification

First declare a critical section variable, an event, and a thread handle. The critical section is used to synchronize the device state. The event is used to end the secondary thread when the application exits:

CRITICAL_SECTION csIssueCmd;
HANDLE           hThreadEndEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
HANDLE           hThread = 0;

After you create an instance of the capture filter, create the secondary thread:

DWORD ThreadId;
hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &ThreadId);

Within the secondary thread, make two calls to the IAMExtTransport::GetStatus method. In the first call, pass the value ED_NOTIFY_HEVENT_GET. This call retrieves a handle to an event that will be signaled when an operation completes:

HANDLE hEvent = NULL;
hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_GET, (long *)&hEvent);

In the second call, pass the value ED_MODE_CHANGE_NOTIFY, along with a pointer to a variable that will receive the device state:

LONG State;
hr = MyDevCap.pTransport->GetStatus(ED_MODE_CHANGE_NOTIFY, &State);

If the device supports notification, the return value from this call is E_PENDING. Otherwise, you must poll device, as described in the next section.

Assuming that the device does support notification, wait for the event to be signaled. When the next operation completes, the event is signaled and the value of State specifies the new device state. At this point, you can update the user interface to reflect the new state. Release the event handle by calling GetStatus with the flag ED_NOTIFY_HEVENT_RELEASE and the address of the handle.

The following code shows the complete thread procedure. The function UpdateTransportState is assumed to be an application-defined function that updates the user interface. Note that the thread waits for two events: the notification event (hEvent) and the thread-termination event (hThreadEndEvent). Also note where the critical section is used to protect the device state variable.

DWORD WINAPI ThreadProc(void *pParam)
{
    HRESULT hr;
    HANDLE  EventHandles[2];
    HANDLE  hEvent = NULL;
    DWORD   WaitStatus;
    LONG    State;

    // Get an event, which will be signaled when the next operation completes.
    hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_GET, (long *) &hEvent);

    while (hThread && hEvent && hThreadEndEvent) {
        EnterCriticalSection(&csIssueCmd);
            State = 0;
            hr = MyDevCap.pTransport->GetStatus(ED_MODE_CHANGE_NOTIFY, &State);
        LeaveCriticalSection(&csIssueCmd);

        if(hr == E_PENDING) {             // Device supports notification.
            EventHandles[0] = hEvent;
            EventHandles[1] = hThreadEndEvent;
            WaitStatus = WaitForMultipleObjects(2, EventHandles, FALSE, INFINITE);
            if(WAIT_OBJECT_0 == WaitStatus) {
                UpdateTransportState(State);
            }
            else {
                break;  // End this thread.
            }
        }
        else {
            break;  // End this thread. (Device does not support notification.)
        }

    } // while

    // Cancel notification.
    hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_RELEASE, (long *) &hEvent);
    return 1;
}

Also use the critical section when you issue commands to the device, as follows:

// Issue the "stop" command.
EnterCriticalSection(&csIssueCmd);
    if(hr = MyDevCap.pTransport->put_Mode(ED_MODE_STOP), SUCCEEDED(hr))
        UpdateTransportState(ED_MODE_STOP);
LeaveCriticalSection(&csIssueCmd);

Before the application exits, end the secondary thread:

if (hThread)
{
    // Signaling this event will cause the thread to end.
    if (SetEvent(ThreadEndEvent)) {
        // Wait for it to end.
        WaitForSingleObjectEx(hThread, INFINITE, FALSE);
    }
}
CloseHandle(hThreadEndEvent);
CloseHandle(hThread);

Polling the Device

If the device does not support notification, then calling IAMExtTransport::GetStatus with the ED_MODE_CHANGE_NOTIFY flag returns a value other than E_PENDING. In that case, you must poll the device to determine its state.

You should still use a secondary thread and a critical section, as described earlier. The thread queries the device for its state at a regular interval. The following example shows one way to implement the thread:

DWORD WINAPI ThreadProc(void *pParam)
{
    HRESULT hr;
    LONG State;
    DWORD WaitStatus;

    while (hThread && hThreadEndEvent)
    {
        EnterCriticalSection(&csIssueCmd);
            State = 0;
            hr = MyDevCap.pTransport->get_Mode(&State);
        LeaveCriticalSection(&csIssueCmd);
        UpdateTransportState(State);

        // Wait for a while, or until the thread ends.
        WaitStatus = WaitForSingleObjectEx(hThreadEndEvent, 200, FALSE);
        if (WaitStatus == WAIT_OBJECT_0)
            break; // Exit thread now.
                   // Otherwise, the wait timed out. Time to poll again.
    }
    return 1;
}


Issuing Raw AV/C Commands

The IAMExtDevice, IAMExtTransport, and IAMTimecodeReader interfaces work by translating the method calls into commands for the driver, and then interpreting the driver's response and returning it through an HRESULT or an output parameter. However, some device functions may not be accessible through these methods. Therefore, MSDV supports sending raw AV/C commands to the device, using the IAMExtTransport::GetTransportBasicParameters method.

You should keep the following points in mind when using this feature:

  • The command is passed directly to the device, with no error checking or parameter validation. For this reason, you should issue raw AV/C commands only when the DirectShow interfaces do not implement the functionality you need.
  • All raw AV/C commands are synchronous. The thread issuing the command blocks until the command returns.
  • Only one command can be given at a time. While the command is being processed, the device will reject any additional commands.

To send an AV/C command, format the command as an array of bytes. Then call the GetTransportBasicParameters method, passing in the ED_RAW_EXT_DEV_CMD flag, the array size, and the array. You must cast the array address to an LPOLESTR* type, because the original purpose of this parameter was to return a string value.

BYTE AvcCmd[] = { ... }; // Contains the AV/C command (not shown)
long cbCmd = sizeof(AvcCmd);
hr = pTransport->GetTransportBasicParameters(
    ED_RAW_EXT_DEV_CMD,
    &cbCmd,
    (LPOLESTR*) AvcCmd);

The contents of the array are passed directly to the device, so you must be careful to format it correctly. A command can target the unit (camcorder) or a subunit (tape or camera). The relevant standards are available from the 1394 Trade Association Web site.

  • AV/C Digital Interface Command Set General Specification
  • AV/C Tape Recorder/Player Subunit Specification

The former describes how to format AV/C commands and lists the unit commands. The latter specification lists the subunit commands.

The GetTransportBasicParameters method may return one of the following error codes:

Error Code | Description
ERROR_TIMEOUT | The command timed out.
ERROR_REQ_NOT_ACCEP | The device did not accept the command.
ERROR_NOT_SUPPORTED | The device does not support the command.
ERROR_REQUEST_ABORTED | The command was aborted. Possbly the device was removed or a bus reset occurred.

Note These errors are returned as Win32 error codes, not HRESULTs, so you should test for these values directly, rather than using the SUCCEEDED and FAILED macros.

If the method returns S_OK, the response from the device is copied into the array. The response payload might be larger than the command, so you must allocate a buffer large enough to hold it. The maximum payload size is 512 bytes. Note that a return value of S_OK does not always mean the device successfully carried out the command. The application must examine the response payload to determine the status.

The following example shows the command to search for an absolute track number search:

// Set up the ATN search command.
BYTE AvcCmd[] =
{
    0x00,   // ctype = "control"
    0x20,   // subunit_type, subunit_id
    0x52,   // opcode (ATN)
    0x20,   // operand 0 = "search"
    0x00,   // operand 1 = ATN
    0x00,   // operand 2 = ATN
    0x00,   // operand 3 = ATN
    0xFF   //  operand 4 = D-VCR medium type.
};
// Specify a track number.
ULONG ulTrackNumber = track_number; // Specify the track number here.
// Shift over by 1 (LSB of operand 1 is a 1-bit blank flag)
ulTrackNumber = ulTrackNumber << 1;
// Plug this number into operands 1 - 3.
AvcCmd[4] = (BYTE) (ulTrackNumber & 0x000000FF);
AvcCmd[5] = (BYTE)((ulTrackNumber & 0x0000FF00) >> 8);
AvcCmd[6] = (BYTE)((ulTrackNumber & 0x00FF0000) >> 16);


Analog Television

Analog television differs from other video capture scenarios in several ways:

  • The tuner card tunes to an analog signal, which is then digitized.
  • Audio is carried in the analog signal. How the audio reaches the sound card varies depending on the hardware.
  • The signal may contain additional data in the vertical blanking interval (VBI), such as cloced captions (CC), World Standard Teletext (WST), and extended data services (XDS).

The following diagram shows a typical filter for television preview:

Analog Television Graph

  • The TV Tuner filter controls tuning.
  • The TV Audio filter controls the audio decoding.
  • If the tuner card has more than one physical input, the Analog Video Crossbar filter enables the application to select which input is decoded and rendered.
  • The WDM Video Capture filter delivers the digitized video stream.

The Capture Graph Builder automatically inserts any filters that are required upstream from the capture filter.

This section contains the following topics:

  • Analog Television Tuning
  • Analog Television Audio
  • Closed Captions and Teletext


Analog Television Tuning

Tuning is controlled by the TV Tuner filter, through the IAMTVTuner interface. The IAMTVTuner interface inherits IAMTuner. To obtain a pointer to the interface, call the ICaptureGraphBuilder2::FindInterface method as follows:

IAMTVTuner *pTuner = NULL;
hr = pBuild->FindInterface(
    &LOOK_UPSTREAM_ONLY,  // Look upstream from pCap.
    NULL,                 // No particular media type.
    pCap,                 // Pointer to the capture filter.
    IID_IAMTVTuner, (void**)&pTuner);
if (SUCCEEDED(hr))
{
    // Use pTuner ...
    pTuner->Release();
}

The first parameter indicates to search upstream from the capture filter.

Frequency Tables

Internally, the TV Tuner filter keeps a list of frequency tables. Each frequency table corresponds to the broadcast or cable frequencies for a given country/region. There is also a generic "Unicable" frequency table, which is used when a country/region does not have a standard set of frequency assignments.

Each frequency table contains a list of tuning frequencies. For some countries/regions, the indexes in the table correspond directly to channel numbers — in other words, the frequency for channel n is the nth entry in the table. For some countries/regions, however, there is no direct correspondence between channel numbers and frequencies. In that case, the application must keep a list that maps channel numbers (typically chosen by the user) to frequency table entries. For example, what the user sees as "channel 5" might be entry number 12 in the frequency table.

For details, see International Analog TV Tuning.

Basic Tuning Operations

If the tuner supports multiple reception modes, such as television and FM radio, call IAMTuner::put_Mode to select the mode. The IAMTuner::GetAvailableModes method returns all of the modes that the tuner supports. For example, the following code checks whether the tuner supports FM radio, and if so, switches to that mode.

// Check whether the mode is supported.
long lModes = 0;
hr = m_pTuner->GetAvailableModes(&lModes);
if (SUCCEEDED(hr) && (lModes & AMTUNER_MODE_FM_RADIO))
{
    // Set the mode.
    hr = pTuner->put_Mode(AMTUNER_MODE_FM_RADIO);
}

To set the country/region, call the IAMTuner::put_CountryCode method. The tuner uses this value to select the appropriate frequency table. See Country/Region Assignments for more information.

To set the channel, call the IAMTuner::put_Channel method. The argument to this method is actually not a channel number, but rather an index into the current frequency table. As decribed previously, the index number may or may not correspond to a channel number. The IAMTuner::ChannelMinMax method returns the minimum and maximum index values for the current frequency table.

Overriding Frequency Entries

It is possible that some entries in the frequency tables might be incorrect or become obsolete. Therefore, a mechanism is provided for overriding individual entries using registry keys.

The specifics are explained in the topic International Analog TV Tuning. Each registry key defines a "tuning space" which contains one or more subkeys. Each subkey overrides one frequency entry. To set the current tuning space, use the IAMTuner::put_TuningSpace method. Activating the tuning space overrides the frequency entries in the current frequency table. Therefore, it is up to the application to maintain a correspondence between tuning spaces and countries/regions. The best approach is simply to use the country/region identifier as the name of the tuning space.

Fine Tuning the Frequency Entries

Broadcast frequencies may be adjusted up or down several kHz by the broadcast station to reduce potential interference with neighboring channels. Given the nominal frequency, the tuner card can scan for the exact frequency. The TV Tuner filter has a mechanism for saving the adjusted frequencies in the registry.

For each entry in the frequency table, call the put_Channel method to tune to that frequency. The tuner will scan for the most precise frequency. You can check whether the tuner achieved a horizontal lock by calling IAMTuner::SignalPresent. The TV Tuner filter also stores the result internally.

After scanning all of the frequencies, call the IAMTVTuner::StoreAutoTune method to write the updated values into the registry. The updated values are stored under the registry entry for the current tuning space.


Analog Television Audio

With analog television, the audio comes from the TV tuner. Different tuner cards must be configured differently. Some cards use an external connector to patch the audio to the sound card's Line In. Others use an internal connector to patch the audio to the sound card's CD input.

  • Previewing TV Audio
  • Capturing TV Audio


Previewing TV Audio

To preview audio, route the Audio Decoder pin on the crossbar filter to the Audio Tuner pin. To mute the audio, route the Audio Decoder pin to -1.

Routing the Audio Decoder pin

The basic approach is as follows:

  1. Use the ICaptureGraphBuilder2::FindInterface method to locate the crossbar filter.
  2. Use the IAMCrossbar::get_CrossbarPinInfo method to enumerate the crossbar filter's input and output pins. Search for an audio decoder output pin and an audio tuner input pin.
  3. If you find the correct pins, call IAMCrossbar::Route to route the pins. If not, look upstream for another crossbar and repeat the process.
  4. To mute the audio, route the audio decoder pin to -1.

Most TV tuners use a single crossbar filter, but some (for example, some ATI tuners) use two crossbar filters. Therefore, you might have to search for a second crossbar if the first one fails.

Note Contrary to what you might expect, no audio capture filter or audio renderer is required to preview the audio, because there is a physical connection between the tuner card and the sound card.

The following code shows these steps in more detail. First, here is a helper function that searches a crossbar filter for a specified pin type:

HRESULT FindCrossbarPin(
    IAMCrossbar *pXBar,                 // Pointer to the crossbar.
    PhysicalConnectorType PhysicalType, // Pin type to match.
    PIN_DIRECTION Dir,                  // Pin direction.
    long *pIndex)       // Receives the index of the pin, if found.
{
    BOOL bInput = (Dir == PINDIR_INPUT ? TRUE : FALSE);

    // Find out how many pins the crossbar has.
    long cOut, cIn;
    HRESULT hr = pXBar->get_PinCounts(&cOut, &cIn);
    if (FAILED(hr)) return hr;
    // Enumerate pins and look for a matching pin.
    long count = (bInput ? cIn : cOut);
    for (long i = 0; i < count; i++)
    {
        long iRelated = 0;
        long ThisPhysicalType = 0;
        hr = pXBar->get_CrossbarPinInfo(bInput, i, &iRelated,
            &ThisPhysicalType);
        if (SUCCEEDED(hr) && ThisPhysicalType == PhysicalType)
        {
            // Found a match, return the index.
            *pIndex = i;
            return S_OK;
        }
    }
    // Did not find a matching pin.
    return E_FAIL;
}

The next function attempts to activate or mute the audio, depending on the value of the bActivate parameter. It searches the specified crossbar filter for the required pins. If it cannot find them, it returns an error code.

HRESULT ConnectAudio(IAMCrossbar *pXBar, BOOL bActivate)
{
    // Look for the Audio Decoder output pin.
    long i = 0;
    HRESULT hr = FindCrossbarPin(pXBar, PhysConn_Audio_AudioDecoder,
        PINDIR_OUTPUT, &i);
    if (SUCCEEDED(hr))
    {
        if (bActivate)  // Activate the audio.
        {
            // Look for the Audio Tuner input pin.
            long j = 0;
            hr = FindCrossbarPin(pXBar, PhysConn_Audio_Tuner,
                PINDIR_INPUT, &j);
            if (SUCCEEDED(hr))
            {
                return pXBar->Route(i, j);
            }
        }
        else  // Mute the audio
        {
            return pXBar->Route(i, -1);
        }
    }
    return E_FAIL;
}

The next function searches the filter graph for a crossbar filter. If it finds one, it attempts to activate or mute the audio (using the previous function). If that operation fails, the method searches upstream for a second crossbar and tries again. For a more generalized approach to managing multiple crossbar filters in a graph, see the CCrossbar class in the AmCap sample application.

HRESULT ActivateAudio(ICaptureGraphBuilder2 *pBuild, IBaseFilter *pSrc,
  BOOL bActivate)
{
    // Search upstream for a crossbar.
    IAMCrossbar *pXBar1 = NULL;
    HRESULT hr = pBuild->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pSrc,
        IID_IAMCrossbar, (void**)&pXBar1);
    if (SUCCEEDED(hr))
    {
        hr = ConnectAudio(pXBar1, bActivate);
        if (FAILED(hr))
        {
            // Look for another crossbar.
            IBaseFilter *pF = NULL;
            hr = pXBar1->QueryInterface(IID_IBaseFilter, (void**)&pF);
            if (SUCCEEDED(hr))
            {
                // Search upstream for another one.
                IAMCrossbar *pXBar2 = NULL;
                hr = pBuild->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pF,
                    IID_IAMCrossbar, (void**)&pXBar2);
                pF->Release();
                if (SUCCEEDED(hr))
                {
                    hr = ConnectAudio(pXBar2, bActivate);
                    pXBar2->Release();
                }
            }
        }
        pXBar1->Release();
    }
    return hr;
}

The following code shows how to call these functions:

// Build the analog TV graph (not shown).
// Activate the audio.
hr = ActivateAudio(pBuild, pCap, TRUE);
// Later, mute the audio.
hr = ActivateAudio(pBuild, pCap, FALSE);

Note that these example functions repeat many of the same calls. For example, they enumerate the crossbar pins each time. In your own application, you might take a more object-oriented approach and write a helper class that caches some of the information.

See Also

  • Working with Crossbars


Capturing TV Audio

To capture audio from analog television to a file, use the Audio Capture Filter. Use the System Device Enumerator to create the Audio Capture Filter. There may be several audio capture devices on the user's system; the user must select the device that represents the sound card.

Connect the audio capture output pin to the mux filter:

hr = pBuild->RenderStream(
   &PIN_CATEGORY_CAPTURE, // Capture pin.
   &MEDIATYPE_Audio,      // Audio media type.
   pAudioCap,             // Pointer to the audio capture filter.
   NULL,                  // Optional audio compressor filter.
   pMux);                 // Pointer to the mux filter.

The input pins do not have to be connected to anything. Each input pin represents a physical input on the audio capture device. Use the IAMAudioInputMixer interface to enable the input that receives the audio stream from the tuner. The input pins are identified by name, such as "Line In" or "CD Audio." Unfortunately, the names can change from one device to the next. Also, different TV tuner cards use different inputs to the sound card. Therefore, it is up to the user to identify which input to use.

IEnumPins *pEnum = NULL;
hr = pAudioCap->EnumPins(&pEnum);
if (SUCCEEDED(hr))
{
    IPin *pPin = NULL;
    while (S_OK == pEnum->Next(1, &pPin, NULL))
    {
        IAMAudioInputMixer *pMix;
        hr = pPin->QueryInterface(IID_IAMAudioInputMixer, (void**)&pMix);
        if (SUCCEEDED(hr))
        {
            // Use IPin::QueryPinInfo to get the pin name.
            pPin->Release();
            if (...) // If the user selects this pin:
            {
                pMix->put_Enable(TRUE);
                pMix->put_MixLevel(1.0);
                pMix->Release();
                break;
            }
            pMix->Release();
        }
    }
}
pEnum->Release();

See Also

  • Audio Capture


Closed Captions and Teletext

Analog television signals can carry extra information in the vertical blanking interval (VBI), including closed captions and World Standard Teletext (WST). DirectShow provides a set of filters for decoding and viewing both CC and WST text.

  • Viewing Closed Captions
  • Viewing World Standard Teletext


Viewing Closed Captions

To support closed captions in analog television, the capture filter exposes a pin that delivers either VBI or closed caption data. The pin will have one of the following pin categories:

  • VBI pin (PIN_CATEGORY_VBI). Delivers a stream of VBI waveform samples. These are passed to a decoder filter that extracts the closed captioning data.
  • CC pin (PIN_CATEGORY_CC). Delivers closed-caption byte pairs, extracted from the line-21 data.
  • Hardware slicing CC pin (PINNAME_VIDEO_CC_CAPTURE).

To preview closed captions, call ICaptureGraphBuilder2::RenderStream with the VBI pin category, and if that fails, call it again with the CC category.

hr = pBuild->RenderStream(&PIN_CATEGORY_VBI, 0, pCap, 0, 0);
if (FAILED(hr))
{
    hr = pBuild->RenderStream(&PIN_CATEGORY_CC, 0, pCap, 0, 0);
}

The following diagram shows a typical filter graph for displaying closed captions.

Closed Captioning Preview Graph

This graph uses the following filters for closed caption display:

  • Tee/Sink-to-Sink Converter. Accepts the VBI information from the capture filter and splits it into separate streams for each of the data services present on the signal. Microsoft provides VBI codecs for Closed Caption, NABTS, and World Standard Teletext (WST).
  • CC Decoder. Decodes CC data from the sampled VBI waveforms provided by the capture filter.
  • Line 21 Decoder. Translates the CC byte pairs and draws the caption text onto bitmaps. The downstream filter (in this case the Overlay Mixer) overlays the bitmaps onto the video.

The Capture Graph Builder's RenderStream method adds these filters automatically. If the capture filter has a CC pin instead of a VBI pin, the CC pin is connected directly to the Line 21 Decoder filter.

Note If you are using the Video Mixing Renderer (VMR) filter for rendering, use the Line 21 Decoder Filter 2. This filter has the same functionality as the Line 21 Decoder, but the CLSID is CLSID_Line21Decoder2.

If the capture device uses a video port, the capture filter might have a video port VBI pin (PIN_CATEGORY_VIDEOPORT_VBI). This pin must be connected to the VBI Surface Allocator filter, which allocates surfaces to hold the captured VBI data. The RenderStream method adds this filter if it is required. The following diagram shows a filter graph with the VBI Surface Allocator.

Closed Captioning Preview Graph with VBI Surface Allocator

Enabling and Disabling the Captions

To control the captioning display, use the IAMLine21Decoder interface on the Line 21 Decoder filter. For example, you can turn off the captioning display using the SetServiceState method, as follows:

// Use the FindInterface method to find the interface.
IAMLine21Decoder *pLine21 = NULL;
hr = pBuild->FindInterface(
    &LOOK_DOWNSTREAM_ONLY, // Look downstream from pCap
    NULL,                  // No particular media type
    pCap,                  // Pointer to the capture filter.
    IID_IAMLine21Decoder, (void**)&pLine21);
if (SUCCEEDED(hr))
{
    pLine21->SetServiceState(AM_L21_CCSTATE_Off);
    // (Use AM_L21_CCSTATE_On to enable.)
    pLine21->Release();
}

This example uses the ICaptureGraphBuilder2::FindInterface method to locate the IAMLine21Decoder interface. The first parameter to FindInterface is &LOOK_DOWNSTREAM_ONLY, which specifies to search downstream from the capture filter (pCap).

Capturing Closed Caption Bitmaps

You can capture the caption bitmaps into a file. To do so, add the file-writing section of the filter graph, as described in Capturing Video to a File. Then render the CC or VBI pin to the mux filter:

hr = pBuild->RenderStream(&PIN_CATEGORY_VBI, 0, pCap, 0, pMux);
if (FAILED(hr))
{
    hr = pBuild->RenderStream(&PIN_CATEGORY_CC, 0, pCap, 0, pMux);
}

If you are also capturing the video, this will create a file with two separate video streams. It will not capture video with captions overlaid on top of the picture.


Viewing World Standard Teletext

World Standard Teletext (WST) is encoded in the vertical blanking interval (VBI) of the analog television signal. The filter graph for previewing teletext is similar to the graph used to view closed captions.

WST Preview Graph

This graph uses the following filters for WST display:

  • Tee/Sink-to-Sink Converter. Accepts the VBI information from the capture filter and splits it into separate streams for each of the data services present on the signal.
  • WST Codec. Decodes the Teletext data from the VBI samples.
  • WST Decoder. Translates teletext data and draws the text onto bitmaps. The downstream filter (in this case the Overlay Mixer) overlays the bitmaps onto the video.

The Capture Graph Builder's RenderStream method does not support the WST filters directly, so your application must do some extra work.

  1. Add the Overlay Mixer filter to the filter graph. The following code uses the AddFilterByCLSID function described in Add a Filter by CLSID. (AddFilter is not a DirectShow API.)
    IBaseFilter *pOvMix = NULL;  // Pointer to the Overlay Mixer filter.
hr = AddFilterByCLSID(pGraph, CLSID_OverlayMixer, L"OVMix", &pOvMix);
if (FAILED(hr))
{
    // Handle the error ...
}
  2. Connect the preview pin to the Video Renderer filter through the Overlay Mixer. You can use the RenderStream method, as follows:
    hr = pBuild->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
    pCap, pOvMix, 0);
  3. Add the Tee/Sink-to-Sink Converter filter to the filter graph. The following code uses the CreateKernalFilter function described in Creating Kernel-Mode Filters. (CreateKernelFilter is not a DirectShow API.)
    IBaseFilter* pKernelTee = NULL;
hr = CreateKernelFilter(AM_KSCATEGORY_SPLITTER,
    OLESTR("Tee/Sink-to-Sink Converter"), &pKernelTee);
if (SUCCEEDED(hr))
{
    hr = pGraph->AddFilter(pKernelTee, L"Kernel Tee");
}
  4. Add the WST Codec filter to the filter graph:
    IBaseFilter* pWstCodec = NULL;
hr = CreateKernelFilter(AM_KSCATEGORY_VBICODEC,
    OLESTR("WST Codec"), &pWstCodec);
if (SUCCEEDED(hr))
{
    hr = pGraph->AddFilter(pWstCodec, L"WST Codec");
}
  5. Call RenderStream to connect the capture filter's VBI pin to the Tee/Sink-to-Sink Converter, and the Tee/Sink-to-Sink Converter to the WST Codec filter:
    hr = pBuild->RenderStream(&PIN_CATEGORY_VBI, 0, pCap,
    pKernelTee, pWstCodec);
  6. Call RenderStream again to connect the WST Codec filter to the Overlay Mixer. The WST Decoder filter is automatically brought into the graph.
    hr = pBuild->RenderStream(0, 0, pWstCodec, 0, pOvMix);
  7. Remember to release all of the filter interfaces.
    pOvMix->Release();
pKernelTee->Release();
pWstCodec->Release();

Note Currently, the WST Decoder filter does not support connections to the Video Mixing Renderer (VMR) filter. Therefore, you must use the legacy Video Renderer filter to view teletext.

If the capture filter has a video port VBI pin (PIN_CATEGPORY_VIDEOPORT_VBI), connect it to the VBI Surface Allocator filter. The graph will not run correctly otherwise. The following code example uses the AddFilterByCLSID function, described in Add a Filter by CLSID, and the FindPinByCategory function, described in Working with Pin Categories. (Neither function is a DirectShow API.)

// Look for a video port VBI pin on the capture filter.
IPin *pVPVBI = NULL;
hr = FindPinByCategory(pCap, PINDIR_OUTPUT,
    PIN_CATEGORY_VIDEOPORT_VBI, &pVPVBI);
if (FAILED(hr))
{
    // No video port VBI pin; nothing else to do. OK to run the graph.
}
else
{
    // Found one. Connect it to the VBI Surface Allocator.
    IBaseFilter *pSurf = NULL;
    hr = AddFilterByCLSID(pGraph, CLSID_VBISurfaces, L"VBI Surf", &pSurf);
    if (SUCCEEDED(hr))
    {
        hr = pBuild->RenderStream(NULL, NULL, pVPVBI, 0, pSurf);
        pSurf->Release();
    }
    if (FAILED(hr))
    {
        // Handle the error (not shown). It is probably not safe to
        // run the graph at this point.
    }
    pVPVBI->Release();
}


Advanced Capture Topics

This section describes some advanced aspects of video capture in DirectShow. Most of the issues described in this section are automatically handled by the ICaptureGraphBuilder2 interface. However, the information here may be useful if you need to troubleshoot a video capture application. You should also read this section if your application builds a custom capture graph of some kind and you find that ICaptureGraphBuilder2 does not suit your needs. Finally, this section contains some information about using the Video Mixing Renderer (VMR) filter in a video capture application.

It is possible to build a video capture graph entirely using IGraphBuilder methods. You can also combine them, using ICaptureGraphBuilder2 for some tasks and IGraphBuilder for others.

This section contains the following topics:

  • Handling Repaint Events in Video Capture
  • Working with Pin Categories
  • Using the Smart Tee Filter
  • Using the Overlay Mixer in Video Capture
  • Video Port Pins
  • VideoInfo2 Format Type
  • Creating Kernel-Mode Filters
  • WDM Class Driver Filters


Handling Repaint Events in Video Capture

If you build a video capture graph without using the ICaptureGraphBuilder2 interface, and you preview the video using the old Video Renderer filter, then you should override the default handling for EC_REPAINT events. Query the Filter Graph Manager for the IMediaEvent interface and call the IMediaEvent::CancelDefaultHandling method with the value EC_REPAINT:

IMediaEvent *pEvent = 0;
hr = pGraph->QueryInterface(IID_IMediaEvent, (void**)&pEvent);
if (SUCCEEDED(hr))
{
    pEvent->CancelDefaultHandling (EC_REPAINT);
    pEvent->Release();
}

This prevents a possible error that can corrupt your capture file. If the user covers and uncovers the preview window, the Video Renderer filter receives a WM_PAINT message. By default, the Video Renderer requests a new frame, and the Filter Graph Manager pauses the graph in order to cue another video frame. If that happens while the graph is writing a file, it will corrupt the file. Overriding the default EC_REPAINT behavior prevents the renderer from requesting a new frame.

You do not have to perform this step if you are using the ICaptureGraphBuilder2 interface, because the Capture Graph Builder does it for you automatically. Also, it is not required if you are using the Video Mixing Renderer (VMR) for preview. The VMR always has the most recent frame available, so it does not send EC_REPAINT events.

See Also

  • Event Notification in DirectShow


Working with Pin Categories

To search on a filter for a pin with a given pin category, you can use the ICaptureGraphBuilder2::FindPin method. The following example searches for a video preview pin:

int i = 0;
hr = pBuild->FindPin(
    pFilter,               // Pointer to a filter to search.
    PINDIR_OUTPUT,         // Which pin direction?
    &PIN_CATEGORY_PREVIEW, // Which category? (NULL means "any category")
    &MEDIATYPE_Video,      // What media type? (NULL means "any type")
    FALSE,                 // Must be connected?
    i,                     // Get the i'th matching pin (0 = first match)
    &pPin                  // Receives a pointer to the pin.
);

The first parameter is a pointer to the filter's IBaseFilter interface. The next three parameters specify the direction, pin category, and media type. The value FALSE in the fifth parameter indicates that the pin can be either connected or unconnected. (For the exact definitions of these parameters, refer to the documentation for the method.) If the method finds a matching pin, it returns a pointer to the IPin interface in the pPin parameter.

Although the FindPin method is convenient, you can also write your own helper functions if you prefer. To determine a pin's category, call the IKsPropertySet::Get method as described in the topic Pin Property Set.

The following code shows a helper function that checks whether a pin matches a specified category:

BOOL PinMatchesCategory(IPin *pPin, const GUID& Category)
{
    if (pPin == NULL) return E_POINTER;

    BOOL bFound = FALSE;
    IKsPropertySet *pKs;
    HRESULT hr = pPin->QueryInterface(IID_IKsPropertySet, (void **)&pKs);
    if (SUCCEEDED(hr))
    {
        GUID PinCategory;
        DWORD cbReturned;
        hr = pKs->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0,
            &PinCategory, sizeof(GUID), &cbReturned);
        if (SUCCEEDED(hr))
        {
            bFound = (PinCategory == Category);
        }
        pKs->Release();
    }
    return bFound;
}

The next example is a function that searches for a pin by category, similar to the FindPin method:

HRESULT FindPinByCategory(
    IBaseFilter *pF,      // Pointer to the filter to search.
    PIN_DIRECTION PinDir, // Direction of the pin.
    const GUID& Category, // Pin category.
    IPin **ppPin)         // Receives a pointer to the pin.
{
    if (!pF || !ppPin) return E_POINTER;

    *ppPin = 0;
    HRESULT hr;
    IEnumPins *pEnum = 0;
    if (SUCCEEDED(pF->EnumPins(&pEnum)))
    {
        IPin *pPin = 0;
        while (hr = pEnum->Next(1, &pPin, 0), hr == S_OK)
        {
            PIN_DIRECTION ThisPinDir;
            hr = pPin->QueryDirection(&ThisPinDir);
            if (FAILED(hr))
            {
                pPin->Release();
                pEnum->Release();
                return E_UNEXPECTED; // Something strange happened.
            }
            if ((ThisPinDir == PinDir) &&
                PinMatchesCategory(pPin, Category))
            {
                *ppPin = pPin;  // Caller must release the interface.
                pEnum->Release();
                return S_OK;
            }
            pPin->Release();
        }
        pEnum->Release();
    }
    // No pin matches.
    return E_FAIL;
}

The following code uses the previous function to search for a video port pin on a filter:

IPin *pVP;
hr = FindPinByCategory(pFilter, PINDIR_OUTPUT,
    PIN_CATEGORY_VIDEOPORT, &pVP);
if (SUCCEEDED(hr))
{
    // Use pVP ...
    // Release when you are done.
    pVP->Release();
}

For more information about property sets, refer to the Microsoft® Windows® Driver Development Kit (DDK) documentation.

See Also

  • DirectShow Video Capture Filters


Using the Smart Tee Filter

If a capture filter has separate capture and preview pins, you can capture from one while previewing from the other. But if the filter has no preview pin, you can do the same thing by including the Smart Tee filter in the graph. This filter splits data from the capture pin into two identical streams, one for capture and one for preview.

Capture graph with Smart Tee filter

The ICaptureGraphBuilder2::RenderStream method automatically inserts the Smart Tee Filter if it is required. However, if you use IGraphBuilder methods to build your graph, and not RenderStream, you may need to insert the Smart Tee filter.

Before you render pins on the capture filter, check whether the filter has a preview pin or a video port pin. If it does not, and you wish to preview, add the Smart Tee filter to the graph and connect it to the capture pin on the capture filter.

Note You can treat a video port (VP) pin as a kind of preview pin, so a filter with a VP pin does not need a Smart Tee filter. However, VP pins have some other special requirements. For more information, see Video Port Pins.

See Also

  • Combining Video Capture and Preview
  • Working with Pin Categories


Using the Overlay Mixer in Video Capture

There are certain kinds of video that the Video Renderer filter cannot display by itself. In these situtations, the Video Renderer must work with the Overlay Mixer filter. The Overlay Mixer manages the rendering, while the Video Renderer manages the video window. The Overlay Mixer is needed in the following situations:

  • Video port (VP) pins. If the capture device uses a video port, the Overlay Mixer manages the hardware overlay.
  • Interlaced video. For interlaced video, the decoder requires a VIDEOINFOHEADER2 format, which the Video Renderer does not support.
  • Closed captions. The caption text is renderered as 8-bits-per-pixel bitmaps, which the Overlay Mixer overlays onto the video.

The Capture Graph Builder's RenderStream method inserts the Overlay Mixer whenever needed. If you are building the graph without using the Capture Graph Builder, however, you must check for each of these situations and insert the Overlay Mixer yourself.

Important If the device has a VP pin, you must connect the Overlay Mixer even if you do not need preview functionality in your application. With a video port, the capture device always sends the video data to the hardware overlay, so the Overlay Mixer is always needed.

The Video Mixing Renderer filters (VMR-7 and VMR-9) both support interlaced video, and are able to mix closed caption bitmaps onto the primary video. If you are using the VMR for those scernarios, then you do not need to use the Overlay Mixer. The VMR-9 does not support VP pin connections. The VMR-7 supports VP pin connections through the Video Port Manager filter. However, you may find that some drivers do not work correctly with the Video Port Manager. For that reason, the Overlay Mixer is still recommended for VP pins.

See Also

  • Video Port Pins
  • VideoInfo2 Format Type


Video Port Pins

A capture device with a hardware video port might use the video port extensions (VPE) in Microsoft® DirectX®. If so, the capture filter will have a video port (VP) pin. No video data travels from the VP pin through the filter graph. Instead, video frames are produced in hardware and sent directly to video memory. The VP pin allows control messages to be sent to the hardware.

It is important to connect the VP pin, even if your applications only performs file capture, and not preview. If you leave the pin unconnected, the graph will not run correctly. This is different from preview pins, which do not have to be connected.

The different DirectShow video renderers provide varying support for VP pins.

  • Video Renderer: Connect the VP pin to pin 0 on the Overlay Mixer filter, and connect the Overlay Mixer filter to the Video Renderer.
  • VMR-7: Connect the VP pin to the Video Port Manager filter, and connect the Video Port Manager to the VMR-7.
  • VMR-9: You cannot use the VMR-9 if the device has a VP pin, because Direct3D 9 does not support video ports. Use either the Video Renderer or the VMR-7.

For video port scenarios, the Overlay Mixer and Video Renderer are recommended over the Video Port Manager and VMR-7, because not all drivers support the Video Port Manager. In general the Overlay Mixer is a more reliable option for video ports.

The ICaptureGraphBuilder2::RenderStream method automatically inserts the Overlay Mixer if there is a VP pin. If you are building the graph without using this method, then check for a video port pin on the capture filter. If there is one, connect it to the Overlay Mixer filter.

Connecting a video port pin to the Overlay Mixer filter.

You can use the ICaptureGraphBuilder2::FindPin method to search for a VP pin on the capture filter:

hr = pBuild->FindPin(
    pCap,                    // Pointer to the capture filter.
    PINDIR_OUTPUT,           // Look for an output pin.
    &PIN_CATEGORY_VIDEOPORT, // Look for a video port pin.
    NULL,                    // Any media type.
    FALSE,                   // Pin can be connected.
    0,                       // Retrieve the first matching pin.
    &pVPPin                  // Receives a pointer to the pin.
);

After you add the Overlay Mixer to the graph, call FindPin again to find pin 0 on the Overlay Mixer. Pin 0 is always the first input pin on the filter.

pBuild->FindPin(pOvMix, PINDIR_INPUT, NULL, NULL, TRUE, 0, &pOVPin);

Connect the two pins by calling IGraphBuilder::Connect.

pGraph->Connect(pVPPin, pOvPin);

Then connect the Overlay Mixer's output pin to the Video Renderer filter. You can hide the video by calling the IVideoWindow::put_AutoShow and IVideoWindow::put_Visible methods on the Filter Graph Manager.

For TV tuners, the capture filter might also have a video port VBI pin (PIN_CATEGORY_VIDEOPORT_VBI). If so, connect that pin to the VBI Surface Allocator filter. For more information, see Viewing Closed Captions.

See Also

  • Using the Overlay Mixer in Video Capture


VideoInfo2 Format Type

A preview pin might prefer a media type with a VIDEOINFOHEADER2 format. This format structure supports special features such as interlaced video and picture aspect ratios.

The VMR-7 and the VMR-9 both support VIDEOINFOHEADER2 directly. When you connect the VMR to the decoder, they will negotiate the best format. The older Video Renderer filter, however, does not support VIDEOINFOHEADER2. To use VIDEOINFOHEADER2 format types with the Video Renderer filter, you must insert the Overlay Mixer filter into the graph.

  1. Enumerate the preferred media types on the decoder filter's output pin, using the IPin::EnumMediaTypes method.
  2. Check the first media type in the enumeration sequence.
  3. If the format type is FORMAT_VideoInfo2, connect the output pin to the Overlay Mixer. Then connect the Overlay Mixer to the video renderer. (See Video Port Pins.)

If you do not care about these features, you do not have to use the Overlay Mixer. Connect the decoder directly to the Video Renderer, and it will connect with a VIDEOINFOHEADER format instead.

See Also

  • Using the Overlay Mixer in Video Capture


Creating Kernel-Mode Filters

Certain kernel-mode filters cannot be created through CoCreateInstance, and thus do not have CLSIDs. These filters include the Tee/Sink-to-Sink Converter, the CC Decoder filter, and the WST Codec filter. To create one of these filters, use the System Device Enumerator object and search by the filter's name.

  1. Create the System Device Enumerator.
  2. Call the ICreateDevEnum::CreateClassEnumerator method with the CLSID of the filter category for that filter. This method creates an enumerator for the filter category. (An enumerator is simply an object that returns a list of other objects, using a defined COM interface.) The enumerator returns IMoniker pointers, which represent the filters in that category.
  3. For each moniker, call IMoniker::BindToStorage to get an IPropertyBag interface.
  4. Call IPropertyBag::Read to get the name of the filter.
  5. If the name matches, call IMoniker::BindToObject to create the filter.

The following code shows a function that performs these steps:

HRESULT CreateKernelFilter(
    const GUID &guidCategory,  // Filter category.
    LPCOLESTR szName,          // The name of the filter.
    IBaseFilter **ppFilter     // Receives a pointer to the filter.
)
{
    HRESULT hr;
    ICreateDevEnum *pDevEnum = NULL;
    IEnumMoniker *pEnum = NULL;
    if (!szName || !ppFilter)
    {
        return E_POINTER;
    }

    // Create the system device enumerator.
    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
        IID_ICreateDevEnum, (void**)&pDevEnum);
    if (FAILED(hr))
    {
        return hr;
    }

    // Create a class enumerator for the specified category.
    hr = pDevEnum->CreateClassEnumerator(guidCategory, &pEnum, 0);
    pDevEnum->Release();
    if (hr != S_OK) // S_FALSE means the category is empty.
    {
        return E_FAIL;
    }

    // Enumerate devices within this category.
    bool bFound = false;
    IMoniker *pMoniker;
    while (!bFound && (S_OK == pEnum->Next(1, &pMoniker, 0)))
    {
        IPropertyBag *pBag = NULL;
        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
        if (FAILED(hr))
        {
            pMoniker->Release();
            continue; // Maybe the next one will work.
        }
        // Check the friendly name.
        VARIANT var;
        VariantInit(&var);
        hr = pBag->Read(L"FriendlyName", &var, NULL);
        if (SUCCEEDED(hr) && (lstrcmpiW(var.bstrVal, szName) == 0))
        {
            // This is the right filter.
            hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter,
                (void**)ppFilter);
            bFound = true;
        }
        VariantClear(&var);
        pBag->Release();
        pMoniker->Release();
    }
    pEnum->Release();
    return (bFound ? hr : E_FAIL);
}

The following code example uses this function to create the CC Decoder filter and add it to the filter graph:

IBaseFilter *pCC = NULL;
hr = CreateKernelFilter(AM_KSCATEGORY_VBICODEC,
    OLESTR("CC Decoder"), &pCC);
if (SUCCEEDED(hr))
{
    hr = pGraph->AddFilter(pCC, L"CC Decoder");
    pCC->Release();
}

See Also

  • Using the System Device Enumerator


WDM Class Driver Filters

If a capture device uses a Windows Driver Model (WDM) driver, the graph might require certain filters upstream from the capture filter. These filters are called stream-class driver filters or WDM filters. They support additional functionality provided by the hardware. For example, a TV tuner card has functions for setting the channel. The corresponding filter is the TV Tuner filter, which exposes the IAMTVTuner interface. To make this functionality available to the application, you must connect the TV Tuner filter to the capture filter.

The ICaptureGraphBuilder2 interface provides the easiest way to add WDM filters to the graph. At some point while building the graph, call FindInterface or RenderStream. Either one of these methods will automatically locate the necessary WDM filters and connect them to the capture filter. The rest of this section describes how to add WDM filters manually. However, be aware that the recommend approach is simply to call one of these ICaptureGraphBuilder2 methods.

The pins on a WDM filter support one or more mediums. A medium defines a method of communication, such as a bus. You must connect pins that support the same medium. The REGPINMEDIUM structure, which is equivalent to the KSPIN_MEDIUM structure used for kernel streaming drivers, defines a medium in DirectShow. The clsMedium member of the REGPINMEDIUM structure specifies the class identifier (CLSID) for the medium. To retrieve a pin's medium, call the IKsPin::KsQueryMediums method. This method returns a pointer to a block of memory that contains a KSMULTIPLE_ITEM structure, followed by zero or more REGPINMEDIUM structures. Each REGPINMEDIUM structure identifies a medium the pin supports.

Do not connect a pin if the medium has a CLSID of GUID_NULL or KSMEDIUMSETID_Standard. These are default values indicating that the pin does not support mediums.

Also, do not connect a pin unless the filter requires exactly one connected instance of that pin. Otherwise, your application might try to connect various pins that shouldn't have connections, which can cause the program to stop responding. To find out the number of required instances, retrieve the KSPROPERTY_PIN_NECESSARYINSTANCES property set, as shown in the following code example. (For brevity, this example does not test any return codes or release any interfaces. Your application should do both, of course.)

// Obtain the pin factory identifier.
IKsPinFactory *pPinFactory;
hr = pPin->QueryInterface(IID_IKsPinFactory, (void **)&pPinFactory);

ULONG ulFactoryId;
hr = pPinFactory->KsPinFactory(&ulFactoryId);

// Get the "instance" property from the filter.
IKsControl *pKsControl;
hr = pFilter->QueryInterface(IID_IKsControl, (void **)&pKsControl);

KSP_PIN ksPin;
ksPin.Property.Set = KSPROPSETID_Pin;
ksPin.Property.Id = KSPROPERTY_PIN_NECESSARYINSTANCES;
ksPin.Property.Flags = KSPROPERTY_TYPE_GET;
ksPin.PinId = ulFactoryId;
ksPin.Reserved = 0;

KSPROPERTY ksProp;
ULONG ulInstances, bytes;
pKsControl->KsProperty((PKSPROPERTY)&ksPin, sizeof(ksPin),
    &ulInstances, sizeof(ULONG), &bytes);

if (hr == S_OK && bytes == sizeof(ULONG))
{
    if (ulInstances == 1)
    {
        // Filter requires one instance of this pin.
        // This pin is OK.
    }
}

The following pseudocode is an extremely brief outline showing how to find and connect the WDM filters. It omits many details, and is only meant to show the general steps your application would need to take.

Add supporting filters:
{
    foreach input pin:
        skip if (pin is connected)

        Get pin medium
        skip if (medium is GUID_NULL or KSMEDIUMSETID_Standard)

        Query filter for KSPROPERTY_PIN_NECESSARYINSTANCES property
        skip if (necessary instances != 1)

        Match an existing pin || Find a matching filter
}

Match an existing pin:
{
    foreach filter in the graph
        foreach unconnected pin
            Get pin medium
            if (mediums match)
                connect the pins
}

Find a matching filter:
{
    Query the filter graph manager for IFilterMapper2.
    Find a filter with an output pin that matches the medium.
    Add the filter to the graph.
    Connect the pins.
    Add supporting filters. (Recursive call.)
}


DirectShow Editing Services

Microsoft® DirectShow® Editing Services (DES) is an application programming interface (API) that supports video editing. This section describes how to use DES. It contains the following topics:

  • Introduction to DirectShow Editing Services
  • Getting Started with DirectShow Editing Services
  • Using DirectShow Editing Services

See Also

  • DirectShow Editing Services C++ Reference
  • DirectShow Editing Services Visual Basic Reference


Introduction to DirectShow Editing Services

Microsoft® DirectShow® Editing Services (DES) is an application programming interface (API) that greatly simplifies the tasks involved in video editing. DES is built on top of the core DirectShow architecture. It abstracts much of the complexity of DirectShow, and provides a set of interfaces designed specifically for manipulating video editing projects. As an application developer, you get the benefits of DirectShow inside a framework much better suited for creating video editing applications.

The core of DirectShow is a powerful architecture for handling streaming media. An application can use it to play multimedia content authored in a wide variety of formats, without the developer needing to worry about file compression and other tedious details. Prior to DES, however, DirectShow lacked the flexibility needed for nonlinear editing.

For example, suppose you wanted to create a video sequence consisting of 4 seconds from source A, followed by 10 seconds from source B, and ending with 5 seconds from source C. You could accomplish that much fairly easily using only the core DirectShow API.

But what if you decided that source C should come before source B, not after; that the sequence should use 8 seconds from source A, not 4; and that the entire production needed a separate audio track playing in the background? Even minor changes such as these could be difficult to implement. But the scenario just described is a trivial editing project in DES—you can do it with a handful of method calls.

Here are some of the features that DES brings to DirectShow:

  • A timeline model that organizes video and audio tracks into nested layers, making it easy to manipulate the final production
  • The ability to preview a video project on the fly
  • Project persistence through an XML-based format
  • Support for video and audio effects, as well as transitions between video tracks (such as fades and wipes)
  • Over 100 standard wipes, as defined by the Society of Motion Picture and Television Engineers (SMPTE)
  • Keying based on hue, luminance, RGB value, or alpha value
  • Automatic conversion of frame rates and audio sampling rates, enabling a production to use heterogeneous sources
  • Resizing or cropping of video

The quickest way to see DES in action is to run the sample application XTLTest Sample. This utility parses DES project files (authored in XML) and renders them to the screen. You can experiment with XtlTest by manually editing sample project files and then rendering them to see the change.


Getting Started with DirectShow Editing Services

This section describes the basic concepts you need to get started with Microsoft® DirectShow® Editing Services (DES). It contains the following topics:

  • DirectShow Editing Services Architecture
  • The Timeline Model
  • Transitions
  • Composition and Layering
  • Time in DirectShow Editing Services


DirectShow Editing Services Architecture

The following illustration shows the architecture of Microsoft® DirectShow® Editing Services (DES).

DirectShow Editing Services Architecture

  • Timeline: Represents a video production as a collection of source clips, transitions, and effects, organized into a set of nested tracks. For more information, see The Timeline Model.
  • XML Parser: Parses the timeline and generates an output file, or reads an input file and generates a timeline. DES supports an XML-based persistence format.
  • Render engine: Translates the timeline into a form that can be rendered as streaming media. By default, the render engine produces a DirectShow filter graph (see next section).
  • Media locator: Maintains a cache of locations of media elements. When an attempt to open a media element fails, DES uses the cache to locate the element, based on a history of successful opens.

The timeline is an abstract description of a video editing project. It specifies the source clips used in the project, start and stop times, effects and transitions, and so forth. The timeline does not render the video and audio streams, however. Instead, the render engine translates the timeline into a filter graph, for either preview or file output. An application manipulates the timeline rather than directly manipulating the filter graph, which would be cumbersome and error prone.

The following table lists the main tasks that a typical video editing application performs, along with the interfaces that support each task. Later sections describe these tasks and the interfaces in more detail.

Task | Interface(s)
Construct or modify a timeline. | IAMTimeline and the other IAMTimelineXXXX interfaces
Save and load project files. | IXml2Dex
Preview a project or write it to a file. | IRenderEngine, ISmartRenderEngine

In addition, an application might perform some or all of the following secondary tasks.

Task | Interface(s)
Obtain information about media files. (Number of streams; format and duration of each stream.) | IMediaDet
Set properties on transitions and effects. | IPropertySetter
Receive notification when errors occur during rendering. | IAMSetErrorLog, IAMErrorLog
Retrieve poster frames. | IMediaDet, ISampleGrabber


The Timeline Model

A timeline is an object that Microsoft® DirectShow® Editing Services (DES) uses to represent a video editing project. An editing project starts as a collection of source clips, taken from video files, sound files, or still image files. A linear sequence of clips forms a track. In DirectShow Editing Services (DES), audio and video are placed in separate tracks.

Tracks can also be layered. Multiple audio tracks are mixed together, and might include audio effects, such as fades or reverb. Multiple video tracks are used to create transitions. For example, you can create a wipe from one clip to another. Another example is a chroma key, in which the background of one clip is keyed out and replaced by a different track. (The weather forecaster in front of a satelite image is an example of chroma keying.)

DES uses a tree structure to represent an editing:

  • Audio and video clips form the leaf nodes, or source objects.
  • A collection of sources with a uniform media type (audio or video) is a track.
  • A collection of tracks is a composition. A composition is rendered as the composite of all the tracks it contains. Compositions can contain other compositions, which allows for complex arrangements of tracks.
  • A top-level collection of compositions and tracks (all representing the same media type) is a group.
  • A set of one or more groups forms a timeline. The timeline is the root node in the tree.

A timeline must contain at least one group. Each group represents a single stream in the final production. A typical project includes one video group and one audio group. Compositions are optional; they exist to provide more structure if needed.

The following illustration shows the child-parent relations that make up a timeline:

The following shows a timeline as a temporal sequence:

The arrow at the top represents the direction of the timeline, starting from time zero. Within the video group, track 1 has a higher priority than track 0. The source objects in track 1 obscure those in track 0. Where track 1 is empty, track 0 "shows through." As mentioned earlier, audio tracks are simply mixed together.

See Also

  • Constructing a Timeline


Transitions

A transition is a way to segue from one video track to another, using a visual effect such as a fade or a wipe. The following illustration shows a timeline with a transition:

Timeline with transition

The transition object is on track 1, and it represents a transition from track 0 to track 1. At the start of the transition, the rendered video is entirely from Track 0 (source A). At the end, the video is entirely from Track 1 (source C). In between, the output transitions from source A to source C. For example, in a fade transition, one source progressively fades to the other. The final output is schematized along the bottom of the illustration.

Transitions cannot overlap in time within the same track, but you can create overlapping transitions by using the composition object, as described in Composition and Layering.

A transition has a direction. By default, it starts from the lower priority track (source A, in the previous example.) and ends at the higher-priority track (source C). In between, the video is a mixture of the two sources. However, you can specify the opposite behavior, as shown in the following illustration:

NTrack with two transitions

Here, the first transition fades from track 0 fades track 1, which is the default behavior. The second transition fades from track 1 back to Track 0. Note that both transitions are located on track 1.

See Also

  • Transitions and Effects
  • Working with Effects and Transitions


Composition and Layering

In a collection of tracks, the first track has the lowest priority (priority 0) and each subsequent track has a priority one level higher. At each priority level, the source clips in that track hide the source clips in the tracks below it, unless that layer also contains a transition. Thus you can imagine DES making several passes when it renders.

First, it renders track 0. There is nothing "under" Track 0, so empty regions are rendered as a solid black image. Transitions in this layer occur between the black image and track 0 or vice versa. DES lays track 1 on top of track 0, generating any transitions between the two tracks. The result is the composite of the two tracks. Next, it places track 2 onto this composite. Transitions at this layer occur between the composite and track 2. The process continues until the last (highest-priority) track is put down.

When several tracks are composited together, they behave like a single track (called a virtual track). The composition object encapsulates this behavior, making complex transitions possible. For example, one video clip can wipe to a second clip, while the composite (both clips plus the wipe) fades to a third clip.


Time in DirectShow Editing Services

To edit video, you must work with some important timing concepts. For example:

  • Each clip has a duration.
  • Clips, transitions, and effects appear at certain times in a project.
  • Video has a frame rate, expressed in frames per second (fps).

Microsoft® DirectShow® Editing Services (DES) provides various methods that set or retrieve times and frame rates. The meaning of these values depends on the context.

Time Values

When a parameter expresses a time, three distinct meanings are possible:

  • Timeline time: The time relative to the beginning of the timeline. For example, a clip might start 2 seconds into the timeline, or a transition might occur 15 seconds into the timeline. The timeline determines the final rendered project, so you can also think of timeline time as "project time."
  • Media time: A point in a source file relative to the start of the file, as reached during normal playback. For example, if you have a 10-second video file, the point midway through the file occurs at 5 seconds, expressed as a media time.
  • Parent time: Time relative to an object in the timeline. For example, if an object starts at 8 seconds on the timeline and contains another object that starts at 10 seconds on the timeline, the child object starts at 2 seconds relative to the parent. Virtual tracks all start at time zero, relative to the timeline. So for any object in a virtual track, parent time equals timeline time.

Media time applies only to source objects. Each source object has a media start time and a media stop time. For example, suppose you have a 10-second video clip, and you want to use only 5 seconds from the middle of the clip, trimming the first 2 seconds and the last 3 seconds from the clip. If you want the clip to appear 20 seconds into the project (and assuming a normal playback rate) you would specify the following start and stop times.

  • Media start: 2 seconds
  • Media stop: 7 seconds
  • Timeline start: 20 seconds
  • Timeline stop: 25 seconds

    Inserting a source clip on a timeline

Frame Rates

Frame rate is the "speed" of a media stream, measured in frames per second. As with time values, the meaning of a frame rate depends on the context:

  • Output frame rate: The frame rate of the final rendered project, defined by the group. When you render the project, each group becomes a separate media stream with its own frame rate.
  • Source frame rate: The frame rate in which the source file was originally authored. The authored frame rate does not have to match the group's output frame rate. DES will automatically upsample or downsample the file as needed. For most media formats, DES can determine the frame rate by examining the format. A DIB sequence is an exception; you must specify the frame rate of a DIB sequence. (For more information, see Working with Sources.)

Playback rate: The apparent speed of a source clip when it appears in the project. For example, 10 seconds' of video can be fit into 5 seconds on the timeline. As a result, the speed of the clip increases by a factor of 2, as the following diagram illustrates.

Making a source play faster

(With an audio source, the pitch would shift as well.) The following formula determines a source clip's playback rate:

  • Playback rate = (Media Stop – Media Start) / (Timeline Stop – Timeline Start)

Note that each of these three rates is independent of the others:

  • You can speed up or slow down a clip by adjusting the media times; this does not affect the frame rate of the final output.
  • You can increase or decrease the output frame rate without affecting how fast a file plays.
  • You can mix, within the same group, source files that have different authored frame rates, and DES will upsample or downsample each clip to match the group's frame rate.

When you render a project, all times are rounded to the nearest frame boundary, as determined by the group frame rate. For example, suppose a video group has a frame rate of 30 fps. Each frame is roughly 33 milliseconds (ms). Suppose you add a 1.68-second source clip to the timeline, starting at time zero. The source does not end exactly on a frame boundary, so DES rounds the stop time to 1.6666 seconds (50 frames). If you seek to 1.68 seconds in the rendered project, you will actually seek past the end of the source, to the 51st frame.

However, DES does not overwrite the source's stop time. You might later change the group frame rate, or move the source to a new spot in the timeline where it rounds differently. Therefore, DES preserves the original stop time and rounds only when necessary. For more information, see IAMTimelineObj::FixTimes.


Using DirectShow Editing Services

This section describes in detail how to use Microsoft® DirectShow® Editing Services (DES) to develop a video editing application. It contains the following sections:

  • Overview of the Timeline Components
  • Loading and Previewing a Project
  • Constructing a Timeline
  • Working with Sources
  • Working with Effects and Transitions
  • Rendering a Project
  • Logging Errors
  • Using Windows Media With DirectShow Editing Services
  • Managing Video Editing Projects
  • Alpha Blending
  • Converting Cutlists to Timelines


Overview of the Timeline Components

The timeline in Microsoft® DirectShow® Editing Services (DES) is a COM component. The objects inside the timeline are also COM components. This article provides an overview of the interfaces exposed by the various objects.

This article contains the following topics:

  • The Timeline
  • Timeline Objects
  • Subobjects

For more information about timelines, see The Timeline Model. For a list of components in DES, see DirectShow Editing Services Objects.


The Timeline

The timeline exposes the IAMTimeline interface. This interface contains methods for setting properties on the timeline; for adding groups to the timeline; and for creating timeline objects, such as groups, tracks, and sources. To create a new timeline, call the standard CoCreateInstance function as follows:

IAMTimeline *pTL = NULL;
hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
        IID_IAMTimeline, (void**)&pTL);

The new timeline is empty. At this point you can either load an existing project file (see Loading and Previewing a Project), or build up the timeline by creating and inserting new objects (see Constructing a Timeline).


Timeline Objects

Each type of object in the timeline—source, track, effect, and so forth—is a distinct COM object. However, an application does not create them using the CoCreateInstance function. Instead, it calls the IAMTimeline::CreateEmptyNode method. This method creates an object of the requested type, initializes it, and returns a pointer to the object. For details, see Constructing a Timeline.

Every timeline object exposes the IAMTimelineObj interface. In addition, the various object types support their own specialized interfaces:

  • Source: IAMTimelineSrc
  • Track: IAMTimelineTrack
  • Composition: IAMTimelineComp
  • Group: IAMTimelineComp, IAMTimelineGroup
  • Effect: IAMTimelineEffect
  • Transition: IAMTimelineTrans

Note that groups are a type of composition, so they support IAMTimelineComp, as well as their own IAMTimelineGroup interface.

In addition to the interfaces listed previously, timeline objects expose other, secondary interfaces. These interfaces determine the relationships between the object types.

Interface | Meaning | Exposed By
IAMTimelineVirtualTrack | The object is a virtual track. Virtual tracks can reside inside compositions and hold other timeline objects. | Composition, Track
IAMTimelineEffectable | The object can have effects. | Composition, Track, Source
IAMTimelineTransable | The object can have transitions. | Composition, Track
IAMTimelineSplittable | The object can be split into two objects. | Track, Source, Effect, Transition


Subobjects

Sources, effects, and transitions have internal pointers to other COM objects, called subobjects. The subobject performs the actual work of the object. The subobject of a source is the component that creates the video or audio data. The subobject of an effect or transition is the component that transforms the data; for example, in a video effect, it creates the visual effect in the video stream.

The type of subobject depends on the type of object:

  • Source: Any DirectShow source filter or parser filter that supports seeking and produces a format that DES supports. It can be a compressed format if DirectShow filters exist to decode it.
  • Effect: For video, any 2-D one-input Microsoft® DirectX® Transform object. For audio, any DirectShow audio effect filter.
  • Transition: For video, any 2-D two-input DirectX Transform object. Audio does not support transitions.

Groups, compositions, and tracks do not have subobjects.

The application does not directly set the subobject pointer. For effects and transitions, the application calls the IAMTimelineObj::SetSubObjectGUID method to specify the GUID of the subobject. For source objects, an application typically calls the IAMTimelineSrc::SetMediaName to specify the name of a source file. However, the SetSubObjectGUID method can also be used for source objects, to specify the class identifier (CLSID) of a filter.

For more information, see Working with Sources and Working with Effects and Transitions.


Loading and Previewing a Project

This article describes how to load and preview a project file with Microsoft® DirectShow® Editing Services (DES). It presents a sample application that loads an XML project file into an empty timeline and renders the timeline for preview. You can modify the sample application to work with any example XML project file that ships with this SDK.

This article contains the following topics.

  • Loading a Project File
  • Previewing the Project
  • Previewing a Project: Example Code


Loading a Project File

To load a project file, you need two components: the XML parser and an empty timeline. The XML parser reads an XML project file and creates each object defined in the file. Then it inserts the objects into the timeline and sets any timeline attributes, such as the default frame rate. The following code example loads a file.

HRESULT         hr;
IAMTimeline     *pTL = NULL;
IXml2Dex        *pXML = NULL;
hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
            IID_IAMTimeline, (void**)&pTL);
hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
            IID_IXml2Dex, (void**)&pXML);
BSTR bstrFile = SysAllocStringLen(OLESTR("C:\\example.xtl"), 15);
hr = pXML->ReadXMLFile(pTL, bstrFile);
SysFreeString(bstrFile);
pXML->Release();

The parser exposes the IXml2Dex interface, which contains methods for loading and saving project files. The timeline exposes the IAMTimeline interface, which contains methods for manipulating the timeline and creating new timeline objects. Call the CoCreateInstance function to create each component, as shown. Remember that by creating a new instance, you are incrementing the reference count on the interface. To avoid memory leaks, always release an interface when you are through with it. In this example, the pointer to IXml2Dex is not needed for anything more, so you can release the interface. The pointer to IAMTimeline is still needed for previewing the timeline.

The IXml2Dex::ReadXMLFile method reads the specified file and populates the timeline with the objects defined in the file. The file name is specified using a BSTR value. To shorten the example, the file name in the example is given as a literal string. Normally, you obtain it from an Open File dialog or something similar.

If the ReadXML method is successful, it returns a success code. Otherwise, it returns an error code such as VFW_E_INVALID_FILE_FORMAT. Always check the return value, in order to handle error conditions gracefully. Again for brevity, the example code does not check for errors.


Previewing the Project

To preview the project, you need a component called a render engine, which builds a DirectShow filter graph from a timeline. The filter graph is what actually renders the project. You can use the render engine to preview a project or to write the final output file.

This article does not go into detail about the render engine. For preview, you only need a few method calls. You can find a more thorough discussion, including how to write output files, in Rendering a Project. The following code example shows how to construct a preview graph.

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
            IID_IRenderEngine, (void**) &pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd( );
hr = pRender->RenderOutputPins( );

Create the render engine using the CoCreateInstance function. Then call the following methods on the render engine's IRenderEngine interface:

  • SetTimelineObject. Specifies the timeline to use.
  • ConnectFrontEnd. Builds a partial filter graph, with one output pin for each group in the timeline.
  • RenderOutputPins Completes the preview graph by connecting each output pin to a video or audio renderer.

Once the graph is built, you can preview the project by running the graph, as you would with any DirectShow filter graph. First, obtain a pointer to the filter graph by calling the IRenderEngine::GetFilterGraph method.

IGraphBuilder   *pGraph = NULL;
hr = pRender->GetFilterGraph(&pGraph);

Query the filter graph for the IMediaControl and IMediaEvent interfaces. Use these two interfaces to run the graph and wait for playback to complete. For an explanation of how to use these interfaces, see How To Play a File and Responding to Events. The following code shows one way to use these interfaces.

IMediaControl   *pControl = NULL;
IMediaEvent     *pEvent = NULL;
long evCode;
pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
hr = pControl->Run();
hr = pEvent->WaitForCompletion(INFINITE, &evCode);
pControl->Stop();

The code in this example blocks program execution until playback completes, because of the INFINITE parameter in the IMediaEvent::WaitForCompletion method call. If something goes wrong during playback, however, it could cause the program to stop responding. In a real application, use a message loop to wait for playback to complete. It's also recommended that you provide the user with a way to interrupt playback.

When you finish using the render engine, always call the IRenderEngine::ScrapIt method. This method deletes the filter graph and releases any resources held by the render engine.

pRender->ScrapIt();


Previewing a Project: Example Code

The following code example shows how to load and preview a DES project. Error checking is omitted for clarity.

#include <dshow.h>
#include <qedit.h>

// Preview a timeline.
void PreviewTL(IAMTimeline *pTL, IRenderEngine *pRender)
{
    HRESULT hr;
    IGraphBuilder   *pGraph = NULL;
    IMediaControl   *pControl = NULL;
    IMediaEvent     *pEvent = NULL;

    // Build the graph.
    hr = pRender->SetTimelineObject(pTL);
    hr = pRender->ConnectFrontEnd( );
    hr = pRender->RenderOutputPins( );

    // Run the graph.
    hr = pRender->GetFilterGraph(&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
    hr = pControl->Run();

    long evCode;
    hr = pEvent->WaitForCompletion(INFINITE, &evCode);
    pControl->Stop();

    // Clean up.
    pEvent->Release();
    pControl->Release();
    pGraph->Release();
}

void main( void )
{
    HRESULT         hr;
    IAMTimeline     *pTL = NULL;
    IRenderEngine   *pRender = NULL;
    IXml2Dex        *pXML = NULL;

    CoInitialize(NULL);
    hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
                IID_IAMTimeline, (void**)&pTL);
    hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
                IID_IXml2Dex, (void**)&pXML);
    hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
                IID_IRenderEngine, (void**)&pRender);

    // Load a project file.
    BSTR bstrFile = SysAllocStringLen(OLESTR("C:\\example.xtl"), 15);
    hr = pXML->ReadXMLFile(pTL, bstrFile);
    SysFreeString(bstrFile);
    pXML->Release();

    PreviewTL(pTL, pRender);

    // Clean up.
    pRender->ScrapIt();
    pTL->Release();
    pRender->Release();
    CoUninitialize();
}


Constructing a Timeline

This article describes how to construct a timeline in Microsoft® DirectShow® Editing Services (DES). It presents an example console application that creates a timeline and renders it. The timeline is minimal, consisting of a single video group with one source clip, but it demonstrates most of the concepts needed to create more complex timelines.

This article contains the following topics.

  • Creating Timeline Objects
  • Creating Groups, Compositions, and Tracks
  • Setting the Group Media Type
  • Adding a Source
  • Creating a Timeline: Example Code


Creating Timeline Objects

The sample code presented in this article starts with an empty timeline, but the same steps apply if you load an existing project and want to add objects to it.

To create any type of object in the timeline, call the IAMTimeline::CreateEmptyNode method. For example, the following code creates a new group:

IAMTimelineObj *pGroupObj = NULL;
pTL->CreateEmptyNode(&pGroupObj, TIMELINE_MAJOR_TYPE_GROUP);

The second parameter is a member of the TIMELINE_MAJOR_TYPE enumeration. It specifies the type of timeline object to create, such as a group or a track.

The CreateEmptyNode method creates the object and returns a pointer to the object's IAMTimelineObj interface. It also increments the reference count on the IAMTimelineObj interface, so you must release the interface when you finish using it. Do not call the CoCreateInstance function. Instead, always use CreateEmptyNode to create a timeline object, because it initializes the new object for use in a timeline.

The IAMTimelineObj interface is a generic interface. It provides methods that are common to all types of timeline object. Each type of object exposes other interfaces as well. For example, groups expose the IAMTimelineGroup interface, among others. You can obtain pointers to the other interfaces by calling QueryInterface.

After you create an object, it is not yet a part of the timeline. The method to add an object to the timeline depends on the object type. The following section describes how to add groups, compositions, and tracks to the timeline.


Creating Groups, Compositions, and Tracks

Groups, compositions, and tracks are the intermediate layers between the timeline and the source clips. They are distinguished by the type of object they can contain.

  • Tracks contain source objects.
  • Compositions contain tracks and other compositions, but not source objects.
  • Groups are top-level compositions. Groups contain compositions and tracks, but compositions cannot contain groups.
  • A virtual track is any object that can reside inside a composition or a group. This includes tracks and compositions.

These objects expose the following interfaces:

Interface | Exposed By
IAMTimelineTrack | Tracks
IAMTimelineVirtualTrack | Tracks, Compositions
IAMTimelineComp | Compositions, Groups
IAMTimelineGroup | Groups

These interfaces contain the methods for adding objects to the timeline.

  • IAMTimeline::AddGroup: Inserts a group into the timeline.
  • IAMTimelineComp::VTrackInsBefore: Inserts a virtual track into a composition or group.
  • IAMTimelineTrack::SrcAdd: Inserts a source into a track.

For example, the following code inserts a new track into a group. As shown in the previous table, a group is considered a kind of composition, and a track is a kind of virtual track. Therefore, to insert the track into the group, you must query the group for its IAMTimelineComp interface and call the IAMTimelineComp::VTrackInsBefore method.

IAMTimelineGroup    *pGroup;
// Create a new group (not shown).

IAMTimelineComp     *pComp = NULL;
IAMTimelineObj      *pTrackObj = NULL;

pTL->CreateEmptyNode(&pTrackObj, TIMELINE_MAJOR_TYPE_TRACK);
pGroup->QueryInterface(IID_IAMTimelineComp, (void **)&pComp);
pComp->VTrackInsBefore(pTrackObj, 0);

The second parameter to VTrackInsBefore specifies the priority of the virtual track. Priority levels start at zero. If you specify the value –1, the virtual track is inserted at the end of the priority list. If you specify a value where there is already a virtual track, everything from that point on moves down the list by one priority level. Do not insert a virtual track at a priority greater than the number of virtual tracks, because it will cause undefined behavior.

To delete an object permanently from the timeline, call IAMTimelineObj::RemoveAll on the object. This method removes the object and all its children. To remove an object for the purpose of reinserting it elsewhere in the timeline, call IAMTimelineObj::Remove instead. Unlike RemoveAll, this method does not delete the object's children. To remove everything from the timeline, call IAMTimeline::ClearAllGroups.


Setting the Group Media Type

All groups must define an uncompressed media type, either audio or video. The uncompressed media type is the format that viewers see or hear during playback. Typically, the final output will be in a compressed format. For more information, see Rendering a Project.

To set the uncompressed format, create an AM_MEDIA_TYPE structure and fill it with the appropriate major type, subtype, and format header. For video, allocate a VIDEOINFOHEADER structure for the format block, and set the width, height, and bit depth. For audio, allocate a WAVEFORMATEX structure for the format block, and set the sample rate, bit depth, and number of channels. If you set just the major type, DES provides reasonable defaults for the other values. In practice, you should set the values explicitly to control the output.

After you initialize the media type structure, call the IAMTimelineGroup::SetMediaType method to set the media type for the group.

The following example specifies 16-bit RGB video, 320 pixels wide by 240 pixels high:

AM_MEDIA_TYPE mtGroup;
mtGroup.majortype = MEDIATYPE_Video;
mtGroup.subtype = MEDIASUBTYPE_RGB555;

// Set format headers.
mtGroup.pbFormat = (BYTE*)CoTaskMemAlloc(sizeof(VIDEOINFOHEADER));
if (mtGroup.pbFormat == NULL)
{
    return E_OUTOFMEMORY;
}

VIDEOINFOHEADER *pVideoHeader = (VIDEOINFOHEADER*)mtGroup.pbFormat;
ZeroMemory(pVideoHeader, sizeof(VIDEOINFOHEADER));
pVideoHeader->bmiHeader.biBitCount = 16;
pVideoHeader->bmiHeader.biWidth = 320;
pVideoHeader->bmiHeader.biHeight = 240;
pVideoHeader->bmiHeader.biPlanes = 1;
pVideoHeader->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pVideoHeader->bmiHeader.biSizeImage = DIBSIZE(pVideoHeader->bmiHeader);

// Set the format type and size.
mtGroup.formattype = FORMAT_VideoInfo;
mtGroup.cbFormat = sizeof(VIDEOINFOHEADER);

// Set the sample size.
mtGroup.bFixedSizeSamples = TRUE;
mtGroup.lSampleSize = DIBSIZE(pVideoHeader->bmiHeader);

// Now use this media type for the group.
pGroup->SetMediaType(&mtGroup);

// Clean up.
CoTaskMemFree(mtGroup.pbFormat);

The next example specifies an audio group, by setting the group media type to 16-bit stereo, 44100 samples per second:

AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));

mt.majortype = MEDIATYPE_Audio;
mt.subtype = MEDIASUBTYPE_PCM;
mt.formattype = FORMAT_WaveFormatEx;

// Set format block.
mt.pbFormat = (BYTE*)CoTaskMemAlloc(sizeof(WAVEFORMATEX));
if (mt.pbFormat == NULL)
{
    return E_OUTOFMEMORY;
}
mt.cbFormat = sizeof(WAVEFORMATEX);

// Fill in the WAVEFORMATEX structure.
WAVEFORMATEX *wave = (WAVEFORMATEX*) mt.pbFormat;
wave->wFormatTag = WAVE_FORMAT_PCM;
wave->nChannels = 2;  // Stereo
wave->nSamplesPerSec = 44100;
wave->wBitsPerSample = 16;
wave->nBlockAlign = wave->nChannels * wave->wBitsPerSample/8;
wave->nAvgBytesPerSec = wave->nSamplesPerSec * wave->nBlockAlign;
wave->cbSize = 0;

hr = pGroup->SetMediaType(&mt);
CoTaskMemFree(mt.pbFormat);

You can also use the CMediaType class in the DirectShow Base Classes to manage media types. It contains some useful helper methods, and automatically releases the format block.

See Also

  • About Media Types


Adding a Source

Create a source object the same way you create other timeline objects. Before inserting it into the timeline, however, you must specify at least the following properties on the source.

  • The start and stop times, relative to the timeline. Call the IAMTimelineObj::SetStartStop method.
  • The media file to use as a source. Call the IAMTimelineSrc::SetMediaName method with a wide-character string representing the name of the file.
  • The media start and stop times, which are relative to the original file. Call the IAMTimelineSrc::SetMediaTimes method. For more information about media times, see Time in DirectShow Editing Services.

In the following example, the source clip starts four seconds into the file. The media duration is 10 seconds, twice the length of the timeline duration, meaning the source will play at twice normal speed. The constant UNITS is defined as 10000000 (107) and equals one second.

pSourceObj->SetStartStop(0, 50000000)
BSTR bstrFile = SysAllocStringLen(OLESTR("C:\\example.avi"), 15);
pSource->SetMediaName(bstrFile);
SysFreeString(bstrFile);
pSource->SetMediaTimes(40000000, 140000000);

Note Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see IRenderEngine::SetDynamicReconnectLevel.

For more information about sources, see Working with Sources.


Creating a Timeline: Example Code

The following code example shows how to create and preview a timeline in DES.

Note For the sake of brevity, the sample code performs no error checking. In a real application, you should check the return values of method calls to make sure none has failed.

#include <dshow.h>
#include <qedit.h>

// Preview a timeline.
void PreviewTL(IAMTimeline *pTL, IRenderEngine *pRender)
{
    IGraphBuilder   *pGraph = NULL;
    IMediaControl   *pControl = NULL;
    IMediaEvent     *pEvent = NULL;

    // Build the graph.
    pRender->SetTimelineObject(pTL);
    pRender->ConnectFrontEnd( );
    pRender->RenderOutputPins( );

    // Run the graph.
    pRender->GetFilterGraph(&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
    pControl->Run();

    long evCode;
    pEvent->WaitForCompletion(INFINITE, &evCode);
    pControl->Stop();

    // Clean up.
    pEvent->Release();
    pControl->Release();
    pGraph->Release();
}

void main( void )
{
    // Start by making an empty timeline.

    IAMTimeline    *pTL = NULL;
    CoInitialize(NULL);
    CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
        IID_IAMTimeline, (void**)&pTL);

    // GROUP: Add a video group to the timeline.

    IAMTimelineGroup    *pGroup = NULL;
    IAMTimelineObj      *pGroupObj = NULL;
    pTL->CreateEmptyNode(&pGroupObj, TIMELINE_MAJOR_TYPE_GROUP);
    pGroupObj->QueryInterface(IID_IAMTimelineGroup, (void **)&pGroup);

    // Set the group media type. This example sets the type to "video" and
    // lets DES pick the default settings. For a more detailed example,
    // see "Setting the Group Media Type."
    AM_MEDIA_TYPE mtGroup;
    ZeroMemory(&mtGroup, sizeof(AM_MEDIA_TYPE));
    mtGroup.majortype = MEDIATYPE_Video;
    pGroup->SetMediaType(&mtGroup);
    pTL->AddGroup(pGroupObj);
    pGroupObj->Release();

    // TRACK: Add a track to the group.

    IAMTimelineObj      *pTrackObj;
    IAMTimelineTrack    *pTrack;
    IAMTimelineComp     *pComp = NULL;

    pTL->CreateEmptyNode(&pTrackObj, TIMELINE_MAJOR_TYPE_TRACK);
    pGroup->QueryInterface(IID_IAMTimelineComp, (void **)&pComp);
    pComp->VTrackInsBefore(pTrackObj, 0);
    pTrackObj->QueryInterface(IID_IAMTimelineTrack, (void **)&pTrack);

    pTrackObj->Release();
    pComp->Release();
    pGroup->Release();

    // SOURCE: Add a source to the track.

    IAMTimelineSrc *pSource = NULL;
    IAMTimelineObj *pSourceObj;
    pTL->CreateEmptyNode(&pSourceObj, TIMELINE_MAJOR_TYPE_SOURCE);
    pSourceObj->QueryInterface(IID_IAMTimelineSrc, (void **)&pSource);

    // Set the times and the file name.
    pSourceObj->SetStartStop(0, 50000000);
    BSTR bstrFile = SysAllocString(OLESTR("C:\\example.avi"));
    pSource->SetMediaName(bstrFile);
    SysFreeString(bstrFile);
    pSource->SetMediaTimes(40000000, 140000000);
    pTrack->SrcAdd(pSourceObj);

    pSourceObj->Release();
    pSource->Release();
    pTrack->Release();

    // Preview the timeline.
    IRenderEngine *pRenderEngine = NULL;
    CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
        IID_IRenderEngine, (void**) &pRenderEngine);
    PreviewTL(pTL, pRenderEngine);

    // Clean up.
    pRenderEngine->ScrapIt();
    pRenderEngine->Release();
    pTL->Release();
    CoUninitialize();
}


Working with Sources

A source object represents a single media stream from a source file. Sources provide the raw material for a project. Everything else in the timeline exists either to provide structure (tracks, compositions, and groups) or to modify sources (effects and transitions).

This article describes various details relating to sources in Microsoft® DirectShow® Editing Services (DES). For information on the basic steps needed to add a source to the timeline, see Constructing a Timeline.

This article contains the following sections.

  • Setting Properties on Sources
  • Using the Media Detector
  • Using the Media Locator
  • Other Source Objects


Setting Properties on Sources

When you create a new source object, there are a few properties you are required to set and others you can optionally set. You must set the following properties.

  • The start and stop times, relative to the rest of the timeline. Call the IAMTimelineObj::SetStartStop method. Do not set overlapping times on source objects within the same track, or it will cause undefined behavior.
  • The media file to use as a source clip. Call the IAMTimelineSrc::SetMediaName.
  • The media start and stop times, relative to the original source file. Call the IAMTimelineSrc::SetMediaTimes method. Exception: If the source is a still image, do not specify the media times. For more information about media times, see Time in DirectShow Editing Services.

A source object inherits its media type from the parent group, so it is not necessary to specify a media type.

Optional properties include the following:

  • The stretch mode. The stretch mode specifies how Microsoft® DirectShow® Editing Services (DES) renders a source whose size does not match the output dimensions. By default, DES stretches an image without preserving the aspect ratio. Alternatively, DES can crop an image or create a letterbox. Call the IAMTimelineSrc::SetStretchMode method to specify the stretch mode.
  • The duration of the source file. If you set this property before setting the media times, DES validates the media stop time and truncates the stop time if it exceeds the file duration. This can help avoid rendering errors later. You can obtain the duration of the file using the media detector, as described in Using the Media Detector. Call the IAMTimelineSrc::SetMediaLength method to specify the file duration.
  • The stream number. By default, a source object uses the first stream in the file that matches the media type of the parent group. If a file contains two or more streams of the same media type, select which stream to use by calling IAMTimelineSrc::SetStreamNumber. You can use the media detector to find the number of streams.


Using the Media Detector

The media detector is a helper object that can retrieve information about a file, such as the number of streams, their type, and their duration. It also contains methods for retrieving poster frames from a video stream. It exposes the IMediaDet interface.

The media detector operates in one of two modes. When you create an instance of the media detector, it is not attached to a particular source file. In this mode, you can retrieve stream information from multiple source files. However, once you use the media detector to obtain a poster frame, it switches to bitmap grab mode. In bitmap grab mode, the media detector is attached to a specific video stream, and the stream information methods no longer work. Moreover, there is no way to switch the media detector back to its starting mode. Therefore, obtain any stream information you need before retrieving poster frames, or else create new instances of the media detector for each stream.

To obtain stream information, do the following:

  1. Call IMediaDet::put_Filename with the name of the source file.
  2. Call IMediaDet::get_OutputStreams to obtain the number of streams in the source.
  3. Specify a stream number with IMediaDet::put_CurrentStream. Then call one or more of the following methods:
    • IMediaDet::get_StreamType: Retrieves the stream's media type.
    • IMediaDet::get_StreamLength: Retrieves the duration of the stream.
    • IMediaDet::get_FrameRate: Retrieves a video stream's frame rate.

To obtain a poster frame, specify the stream number, as in the previous step. Then call either IMediaDet::GetBitmapBits, which copies a poster frame into a buffer, or IMediaDet::WriteBitmapBits, which saves a poster frame to a file.


Using the Media Locator

The media locator is a helper object that verifies file names and searches for missing files on local or network directories. The media detector keeps a cache of directory paths where it has successfully found files in past searches. To locate a file, it searches the directories in its cache. Failing that, the media detector can display an Open File dialog for the user to locate a file manually. Assuming the user locates the file, the media locator adds the new directory to its cache. The media locator exposes the IMediaLocator interface.

Typically, your application does not directly create an instance of the media locator. Instead, the timeline and the render engine provide the following methods for validating file names using the media detector.

  • To validate file names in the timeline, call IAMTimeline::ValidateSourceNames. Optionally, this method also updates the source objects with the correct file names.
  • To validate file names when the project is rendered, call IRenderEngine::SetSourceNameValidation.

Both methods take flags that control the behavior of the media locator. For example, you can restrict the search to local directories.


Other Source Objects

In addition to video and audio sources, DirectShow Editing Sources (DES) supports the following source objects.

Still Images

DES supports the following file formats for still images:

  • Bitmap (.bmp)
  • GIF (Graphics Interchange Format)
  • JPEG (Joint Photographic Experts Group)
  • Targa or Truevision Graphics Adapter (.tga): Mode 2 (uncompressed RGB) in 16-bit, 24,-bit, or 32-bit format.

These files can be used as still images or to create animations. For bitmap, JPEG, and Targa files, if you are using the file as a still image, call the IAMTimelineSrc::SetDefaultFPS method to set the frame rate to zero.

DIB Sequences

Given a series of bitmap, JPEG, or Targa files, the render engine can construct a DIB sequence. To create a DIB sequence, give the files numerically sequential names, such as Image001.bmp, Image002.bmp, Image003.bmp, and so on. Use the first file in the sequence as the source. Set the frame rate for the sequence by calling IAMTimelineSrc::SetDefaultFPS. The render engine cycles through the images in the sequence at the specified frame rate.

If the sequence is too short to fill the duration, given the frame rate, the rest of the duration is solid black. No error occurs during rendering.

GIF Sources

DES supports GIF sources, including animated and transparent GIFs, using the GIF89a specification. With an animated GIF, unlike the other file types, you do not need to set the frame rate. The GIF file specifies the delay between each image in the animation.

To support transparent GIFs, DES converts transparent regions in the image to the RGB triplet RGB(0,0,0). You can then use the Key Transition to key on RGB(0,0,0).

DES also converts any black regions that fall within the range RGB(0–7,0–7,0–7) to the value RGB(8,8,8)—except for the transparency index, if it falls in that range. This conversion is not detectable to the eye.

Video Color Source

The Video Color Source object creates a continuous video image of a solid color. One use for this object is to make it a layer in a transition. For example, use it in a video fade-in or fade-out.

Custom Source Filters

DES can use a DirectShow source filter as a timeline source, if the filter meets the following conditions:

  • It supports seeking
  • It produces a format that DES supports. The format can be compressed as long as the user's system has a DirectShow filter capable of decoding it.

To use a custom source, specify the CLSID of the filter as the subobject GUID of the source object. For more information, see Subobjects. To support custom properties, implement them as IDispatch "put" properties. Only static properties are supported on source objects; dynamic properties are not supported.


Working with Effects and Transitions

Effects modify a single clip, track, or composition. Transitions create seques from one track or compositionsto another.

DirectShow Editing Services uses DirectX Transform objects for its video transitions and video effects. For video transitions, use any 2-D two-input DirectX Transform object. For video effects, use any 2-D one-input DirectX Transform object. Microsoft no longer supports the development of third-party DirectX Transform objects. However, several are provided with DirectShow and others are provided with Microsoft Internet Explorer. For more information about the transitions provided with Internet Explorerer, see Visual Filters and Transitions Reference.

For audio effects, you can use any DirectShow audio effect filter. DES also provides a Volume Envelope Effect for setting the volume on a track or clip. DES does not support audio transitions.

This section contains the following topics:

  • Adding Effect and Transition Objects
  • Previewing Effects and Transitions
  • Enumerating Effects and Transitions
  • Setting Properties on Effects and Transitions
  • Transition Direction


Adding Effect and Transition Objects

To add an effect or transition object, perform the following steps.

1. Create a Timeline Object

DES makes a distinction between the object that represents the effect or transition in the timeline (called the timeline object), and the that implements that effect or transition (called the subobject). For effects, the timeline object supports the IAMTimelineEffect interface. For transitions, it supports the IAMTimelineTrans interface. Both types support the IAMTimelineObj interface. These interfaces are used to insert the objects into the timeline, and to set timeline-related properties. To create the timeline object, call the IAMTimeline::CreateEmptyNode method with the type TIMELINE_MAJOR_TYPE_EFFECT or TIMELINE_MAJOR_TYPE_TRANSITION.

The following example creates a transition object:

IAMTimelineObj *pTransObj = NULL;
pTimeline->CreateEmptyNode(&pTransObj, TIMELINE_MAJOR_TYPE_TRANSITION);

2. Specify the Subobject

The timeline object acts as a wrapper for another object, called the subobject, which does the real work. The subobject implements a data transform that produces the desired effect or transition. For a list of transitions and effects supplied with DES, see Transitions and Effects.

To set the subobject, call the IAMTimelineObj::SetSubObjectGUID method on the timeline object, passing it the class identifier (CLSID) of the subobject. DirectShow provides an enumerator for video effects and video transitions, which you can use to obtain the CLSID. For more information, see Enumerating Effects and Transitions.

The following example sets the SMPTE Wipe Transition as the subobject :

hr = pTransObj->SetSubObjectGUID(CLSID_DxtJpeg);  // SMPTE Wipe

3. Set the Start and Stop Times

To set the start and stop times, call the IAMTimelineObj::SetStartStop method. These times are relative to the start time of the parent object. Effects can overlap within the same object, but transitions cannot.

The following example sets the start time to 5 seconds and the stop time to 10 seconds:

const REFERENCE_TIME ONE_SECOND = 10000000
hr = pTransObj->SetStartStop(5 * ONE_SECOND, 10 * ONE_SECOND);

When a transition is rendered, the progress of the transition at each frame is calculated based on a Progress property, which is normalized to a range of 0.0 to 1.0. DES uses the start time of each frame to calculate the progress value. This means if the transition stop time is equal to the source stop time, the Progress value will never reach exactly 1.0, because the start time of the last frame is slightly than the stop time. To make the transition reach 1.0, set the transition stop time to be at least one frame earlier than the source stop time.

4. Insert the Object into the Timeline

To insert the object into the timeline, call one of the following methods on the parent, depending on the object type:

  • Effects: IAMTimelineEffectable::EffectInsBefore
  • Transitions: IAMTimelineTransable::TransAdd

In the IAMTimelineEffectable::EffectInsBefore method, you must specify the priority of the effect. When effects overlap on the same object, they are applied in order of priority. The Volume Envelope audio effect is an exception; see the Volume Envelope Effect reference for details. Within a composition, all audio tracks are mixed before the audio effects for that composition are applied.

Because transitions cannot overlap on the same object, they do not have a priority value.

The following example adds the transition object to a track:

IAMTimelineTransable *pTransable = NULL;
hr = pTrack->QueryInterface(IID_IAMTimelineTransable, (void **)&pTransable);
hr = pTransable->TransAdd(pTransObj);
pTransable->Release();

The example queries the track object for the IAMTimelineTransable interface before calling AddTrans.

5. Set Properties

Many effects and transitions support custom properties. For information, see Setting Properties on Effects and Transitions.

Example

The following code example adds a SMPTE Wipe Transition to a track. It assumes that the track object already exists in the timeline.

IAMTimeline *pTL;
IAMTimelineTrack *pTrack;

// Create timeline with track (not shown).

// Create the transition object.
IAMTimelineObj *pTransObj = NULL;
hr = pTL->CreateEmptyNode(&pTransObj, TIMELINE_MAJOR_TYPE_TRANSITION);

// Set the subobject.
hr = pTransObj->SetSubObjectGUID(CLSID_DxtJpeg);  // SMPTE Wipe

// Set the start and stop times.
hr = pTransObj->SetStartStop(50000000, 100000000);

// Insert the transition object into the timeline.
IAMTimelineTransable *pTransable = NULL;
hr = pTrack->QueryInterface(IID_IAMTimelineTransable, (void **)&pTransable);
hr = pTransable->TransAdd(pTransObj);
pTransable->Release();
pTransObj->Release();


Previewing Effects and Transitions

Some effects and transitions take a relatively long time to render. During preview this can cause the video to become choppy or out of sync with the audio. You can increase preview speed by disabling effects or transitions:

  • To disable all effects, call IAMTimeline::EnableEffects.
  • To disable all transitions, call IAMTimeline::EnableTransitions.
  • To disable a particular transition, call IAMTimelineTrans::SetCutsOnly.

When effects are disabled, they are not rendered during preview. When a transition is disabled, it is rendered as a jump cut. The segue between tracks still occurs, but the visual effect is not rendered.

If an effect or transition cannot be rendered, the render engine substitutes a default effect or transition. Call the IAMTimeline::SetDefaultEffect method to set the default effect, and the IAMTimeline::SetDefaultTransition method to set the default transition. If you do not specify a default, or if the one you specify also causes an error, DES uses its own default.

Note You can also improve preview quality by increasing the amount of frame buffering. See IAMTimelineGroup::SetOutputBuffering.


Enumerating Effects and Transitions

DirectShow provides a System Device Enumerator object for enumerating devices. You can use it to retrieve monikers for effects or transitions installed on the user's system.

The system device enumerator exposes the ICreateDevEnum interface. It returns category enumerators for specified device categories. A category enumerator, in turn, exposes the IEnumMoniker interface and returns monikers for each device in the category. For a detailed discussion of using ICreateDevEnem, see Enumerating Devices and Filters. The following is a brief summary, specific to DirectShow Editing Services.

To enumerate effects or transitions, perform the following steps.

  1. Create an instance of the system device enumerator.
  2. Call the ICreateDevEnum::CreateClassEnumerator method to retrieve a category enumerator. Categories are defined by class identifiers (CLSIDs). Use CLSID_VideoEffects1Category for effects or CLSID_VideoEffects2Category for transitions.
  3. Call IEnumMoniker::Next to retrieve each moniker in the enumeration.
  4. For each moniker, call IMoniker::BindToStorage to retrieve its associated property bag.

The property bag contains the friendly name and the globally unique identifier (GUID) for the effect or transition. An application can display a list of friendly names and then obtain the corresponding GUID.

The following code example illustrates these steps.

ICreateDevEnum *pCreateDevEnum = NULL;
IEnumMoniker *pEnumMoniker = NULL;

// Create the System Device Enumerator.
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
    CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum);
if (FAILED(hr))
{
    // Error handling omitted for clarity.
}

// Create an enumerator for the video effects category.
hr = pCreateDevEnum->CreateClassEnumerator(
    CLSID_VideoEffects1Category,  // Video effects category.
    &pEnumMoniker, 0);

// Note: Use CLSID_VideoEffects2Category for video transitions.

if (hr == S_OK)  // S_FALSE means the category is empty.
{
    // Enumerate each video effect.
    IMoniker *pMoniker;
    while (S_OK == pEnumMoniker->Next(1, &pMoniker, NULL))
    {
        IPropertyBag *pBag;
        hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
            (void **)&pBag);
        if(FAILED(hr))
        {
            pMoniker->Release();
            continue; // Maybe the next one will work.
        }
        VARIANT var;
        VariantInit(&var);
        hr = pBag->Read(OLESTR("FriendlyName"), &var, NULL);
        if (SUCCEEDED(hr))
        {
            if ( ... )  // Check if var.bstrVal is the name you want.
            {
                VARIANT var2;
                GUID guid;
                var2.vt = VT_BSTR;
                pBag->Read(OLESTR("guid"), &var2, NULL);
                CLSIDFromString(var2.bstrVal, &guid);
                VariantClear(&var2);
                // GUID is now the CLSID for the effect.
            }
        }
        VariantClear(&var);
        pBag->Release();
        pMoniker->Release();
    }
    pEnumMoniker->Release();
}
pCreateDevEnum->Release();


Setting Properties on Effects and Transitions

Many effects and transitions support properties that control their behavior. An application can set the value of a property using the IPropertySetter interface. The underlying effect or transition object must support IDispatch for setting the properties. With video effects and transitions, the application can set a range of values that change over time. (For example, you can set a wipe transition to move back and forth across the frame.) With audio effects, the value of the property is static and cannot change over time. The only exception is the Volume Envelope effect, which supports a dynamic property for the volume level.

To set a property, perform the following steps.

  1. Create an instance of the property setter (CLSID_PropertySetter).
  2. Fill DEXTER_PARAM and DEXTER_VALUE structures with the property data. These structures are discussed below.
  3. Pass the DEXTER_PARAM and DEXTER_VALUE structures to the IPropertySetter::AddProp method.
  4. Repeat steps 2 and 3 for each property you want to set.
  5. Pass the IPropertySetter interface pointer to the IAMTimelineObj::SetPropertySetter method.

The DEXTER_PARAM structure specifies which property is being set. It contains the following members.

  • Name: Name of the property
  • dispID: Reserved, must be zero
  • nValues: Number of values

The DEXTER_VALUE structure specifies the value of a property at a given time. It contains the following members.

  • v: VARIANT type that specifies a new value for the property. The vt member of this VARIANT defines the data type of the property. For more information on the VARIANT type, see the Platform SDK.
  • rt: Reference time when the property assumes this value, relative to the starting time of the effect or transition. The start time of the effect or transition is relative to the start time of its parent object.
  • dwInterp: Flag that specifies how the property changes from the previous value to the new value. With the DEXTERF_JUMP flag, the property jumps instantly to the new value at the specified time. With the DEXTERF_INTERPOLATE flag, the property is interpolated linearly from the previous value.

If you set the vt member to VT_BSTR, the property setter makes any necessary conversions. For floating-point values, include the leading zero before the decimal place. For example, 0.3, not .3.

The value of a property can change over time, so the IPropertySetter::AddProp method takes a single DEXTER_PARAM structure and a pointer to an array of DEXTER_VALUE structures. The array defines a set of time-based values for the property. The members of the array must be in ascending time order, and the nValues member of the DEXTER_PARAM structure must equal the length of the array.

The following code example creates property data for the SMPTE Wipe transition. It sets the wipe code to 120, which creates an oval wipe. It sets the reference time to zero, indicating the start of the transition.

IPropertySetter     *pProp;   // Property setter
IAMTimelineObj      *pTransObj;  // Transition object
// Create an SMPTE Wipe transition object. (Not shown)

hr = CoCreateInstance(CLSID_PropertySetter, NULL, CLSCTX_INPROC_SERVER,
    IID_IPropertySetter, (void**) &pProp);

// Error checking is omitted for clarity...

DEXTER_PARAM param;
DEXTER_VALUE *pValue = (DEXTER_VALUE*)CoTaskMemAlloc(sizeof(DEXTER_VALUE));

// Initialize the parameter.
param.Name = SysAllocString(L"MaskNum");
param.dispID = 0;
param.nValues = 1;

// Initialize the value.
pValue->v.vt = VT_BSTR;
pValue->v.bstrVal = SysAllocString(L"120"); // Oval
pValue->rt = 0;
pValue->dwInterp = DEXTERF_JUMP;

pProp->AddProp(param, pValue);

// Free allocated resources.
SysFreeString(param.Name);
VariantClear(&(pValue->v));
CoTaskMemFree(pValue);

// Set the property on the transition.
pTransObj->SetPropertySetter(pProp);
pProp->Release();

Dynamically Changing Properties

After you render a video editing project, it is possible to modify an effect or transition object's properties while the graph is running. However, this is possible only if you set properties on that object before the application called IRenderEngine::ConnectFrontEnd. If so, you can call IAMTimelineObj::GetPropertySetter on the effect or transition, clear or modify the properties, and the changes will happen dynamically as the graph is running. There may be visual anomalies while the change occurs, so this is recommended only for preview. Do not change the properties while you are writing the project to a file.

If you did not set any properties on the effect or transition object before you called ConnectFrontEnd, you cannot add properties to it while the graph is running.


Transition Direction

A transition goes from input A to input B, and from time t0 to t1. Therefore, the direction of a transition can mean one of two things:

  • The mapping of timeline layers to inputs.
  • The progression over time.

The first is the input direction, and the second is the progress direction. You can control both directions.

  • Input direction: By default, a transition goes from the composite of the lower-priority layers to the layer that contains the transition. To reverse this direction, call the IAMTimelineTrans::SetSwapInputs method.
  • Progress direction: Most transitions support a standard Progress property, which specifies what percentage of the transition is reflected in the output at a given moment. By default, the value of the Progress property goes from 0.0 to 1.0 over the duration of the transition. To reverse the progress, set the Progress property to go from 1.0 to 0.0.

The following diagram illustrates the difference between input direction and progress direction. It shows four variations on a standard SMPTE Wipe transition.

The transition resides on track 1. By default, the wipe goes from left to right and from track 0 to track 1. Swapping inputs causes the wipe to go from track 1 to track 0, but still from left to right. Reversing the progress makes the transition go from right to left. You can combine both, as shown on the far left.

For more information about how DES renders transitions, see The Timeline Model.


Rendering a Project

This section describes how to render a video editing project in Microsoft® DirectShow® Editing Services (DES). It contains the following topics.

  • About the Render Engines
  • Previewing a Project
  • Writing a Project to a File
  • Providing a Custom Video Resizer
  • Selecting a Decoder in DirectShow Editing Services


About the Render Engines

This article describes how Microsoft DirectShow Editing Services (DES) renders a video editing project.

In DES, a project is represented as a timeline. The timeline is useful because it simplifies the most common tasks in video editing, such as rearranging source clips and adding video effects. The DirectShow stream architecture, on the other hand, requires a filter graph. Thus, to render your project, you must translate a timeline into a filter graph. The component that does this is called a render engine. DirectShow provides two render engines:

  • Basic render engine: Builds a filter graph that delivers uncompressed output.
  • Smart render engine: Builds a filter graph that delivers compressed output.

The smart render engine uses smart recompression to improve performance. With smart recompression, source files are recompressed only when the original file format differs from the final output format. If the formats match, the source is never decompressed. Smart recompression is supported only for video compression, not for audio compression.

For preview, use the basic render engine. The smart render engine can also preview, but less efficiently because it has to decompress the compressed stream. For writing files, use the smart render engine if you want smart recompression. Otherwise, use the basic render engine. Smart recompression can greatly reduce the time it takes to write the file.

Important Do not use the smart render engine to read or write Windows Media files.

Important Both render engines create an invisible window that processes messages. The thread that creates the render engine must have a message loop, to dispatch messages. Also, that thread must not exit until the Render Engine and the Filter Graph Manager are released. Otherwise, the application might deadlock.

Constructing the Filter Graph

The filter graph is built in two stages. In the first stage, the render engine constructs a "front end," which is a partial filter graph. The following diagram illustrates a typical front end:

Filter graph front end

The subsystems contain various specialized filters, which the render engine assembles automatically. The front end contains one output pin for each group in the timeline. The output pins deliver uncompressed data if you use the basic render engine, or compressed data if you use the smart render engine.

In the second step, the output pins are connected to rendering filters. For preview, the rendering filters are video and audio renderers. For file writing, the rendering filters are multiplexer (mux) filters and file-writer filters.

Completing the filter graph

See Also

  • Previewing a Project
  • Writing a Project to a File


Previewing a Project

To preview a project, first call CoCreateInstance to create an instance of the Basic Render Engine. The class identifier is CLSID_RenderEngine. Then call the IRenderEngine::SetTimelineObject method to specify the timeline that you are rendering.

The first time that you preview the timeline, perform the following calls in the order listed:

  1. Call IRenderEngine::SetRenderRange to specify which portion of the timeline to preview. (Optional)
  2. Call IRenderEngine::ConnectFrontEnd to build the front end of the graph.
  3. Call IRenderEngine::RenderOutputPins. This method connects each output pin to a video renderer or audio renderer, completing the graph.

The following code example shows these steps:

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL,
    CLSCTX_INPROC_SERVER, IID_IRenderEngine, (void**)&pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd();
hr = pRender->RenderOutputPins();

Now run the filter graph. First, call the IRenderEngine::GetFilterGraph method to retrieve a pointer to the Filter Graph Manager's IGraphBuilder interface. Then query the Filter Graph Manager for the IMediaControl interface and call IMediaControl::Run, as shown in the following code:

IGraphBuilder   *pGraph = NULL;
IMediaControl   *pControl = NULL;
hr = pRender->GetFilterGraph(&pGraph);
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pControl->Run();

Use the Filter Graph Manager's IMediaEventEx interface to wait for the preview to complete. You can also seek the graph using the Filter Graph Manager's IMediaSeeking interface, just as you would with a file playback graph.

To preview the project again, seek the graph back to time zero and call Run again. If you change the contents of the timeline, do the following:

  1. Call SetRenderRange. (Optional)
  2. Call ConnectFrontEnd.
  3. If the ConnectFrontEnd method returns S_WARN_OUTPUTRESET, call RenderOutputPins. (If ConnectFrontEnd returns S_OK, you can skip this step.)
  4. Seek the graph back to time zero.
  5. Run the graph.

The following example shows these steps:

hr = pRender->ConnectFrontEnd();
if (hr == S_WARN_OUTPUTRESET)
{
    hr = pRender->RenderOutputPins();
}
LONGLONG llStart = 0;
hr = pSeek->SetPositions(&llStart, AM_SEEKING_AbsolutePositioning, 0, 0);
hr = pControl->Run();

For a complete example that loads and previews a project file, see Loading and Previewing a Project.

See Also

  • Managing Video Editing Projects


Writing a Project to a File

This article describes how to write a video editing project to a file. First it describes how to write a file with the basic render engine. Then it describes smart recompression with the smart render engine.

For an overview of how Microsoft® DirectShow® Editing Services renders projects, see About the Render Engines.

Using the Basic Render Engine

Start by building the front end of the graph, as follows:

  1. Create the render engine.
  2. Specify the timeline.
  3. Set the render range. (Optional)
  4. Build the front end of the graph.

The following code example shows these steps.

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC,
    IID_IRenderEngine, (void**) &pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd( );

Next, add multiplexer and file-writing filters to the filter graph. The easiest way to do this is with the Capture Graph Builder, a DirectShow component for building capture graphs. The capture graph builder exposes the ICaptureGraphBuilder2 interface. Perform the following steps:

  1. Create an instance of the capture graph builder.
  2. Obtain a pointer to the graph and pass it to the graph builder.
  3. Specify the name and media type of the output file. This step also obtains a pointer to the mux filter, which is required later.

The following code example shows these steps.

CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
    IID_ICaptureGraphBuilder2, (void **)&pBuilder);

// Get a pointer to the graph front end.
IGraphBuilder *pGraph;
pRender->GetFilterGraph(&pGraph);
pBuilder->SetFiltergraph(pGraph);

// Create the file-writing section.
IBaseFilter *pMux;
pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi,
    OLESTR("Output.avi"), &pMux, NULL);

Finally, connect the output pins on the front end to the mux filter.

  1. Retrieve the number of groups.
  2. For each pin, obtain a pointer to the pin.
  3. Optionally, create an instance of a compression filter to compress the stream. The type of compressor will depend on the media type of the group. You can use the System Device Enumerator to enumerate the available compression filters. For more information, see Enumerating Devices and Filters.
  4. Optionally, set compression parameters such as the key-frame rate. This step is discussed in detail later in the article.
  5. Call ICaptureGraphBuilder2::RenderStream. This method takes pointers to the pin, the compression filter (if any), and the multiplexer.

The following code example shows how to connect the output pins.

long NumGroups;
pTimeline->GetGroupCount(&NumGroups);

// Loop through the groups and get the output pins.
for (i = 0; i < NumGroups; i++)
{
    IPin *pPin;
    if (pRender->GetGroupOutputPin(i, &pPin) == S_OK)
    {
        IBaseFilter *pCompressor;
        // Create a compressor filter. (Not shown.)
        // Set compression parameters. (Not shown.)

        // Connect the pin.
        pBuilder->RenderStream(NULL, NULL, pPin, pCompressor, pMux);
        pCompressor->Release();
        pPin->Release();
    }
}

To set compression parameters (step 4, previously), use the IAMVideoCompression interface. This interface is exposed on the output pins of compression filters. Enumerate the compression filter's pins, and query each output pin for IAMVideoCompression. (For information about enumerating pins, see Enumerating Pins.) Be sure to release all the interface pointers that you obtained during this step.

After you build the filter graph, call the IMediaControl::Run method on the filter graph manager. As the filter graph runs, it writes the data to a file. Use event notification to wait for playback to complete. (See Responding to Events.) When playback finishes, you must explicitly call IMediaControl::Stop to stop the filter graph. Otherwise, the file is not written correctly.

Using the Smart Render Engine

To get the benefits of smart recompression, use the smart render engine in place of the basic render engine. The steps in building the graph are almost the same. The major difference is that compression is handled in the front end of the graph, not in the file-writing section.

Important Do not use the smart render engine to read or write Windows Media files.

Each video group has a property that specifies the compression format for that group. The compression format must exactly match the group's uncompressed format in height, width, bit depth, and frame rate. The smart render engine uses the compression format when it constructs the graph. Before you set the compression format, make sure to set the uncompressed format for that group by calling IAMTimelineGroup::SetMediaType.

To set a group's compression format, call the IAMTimelineGroup::SetSmartRecompressFormat method. This method takes a pointer to an SCompFmt0 structure. The SCompFmt0 structure has two members: nFormatId, which must be zero, and MediaType, which is an AM_MEDIA_TYPE structure. Initialize the AM_MEDIA_TYPE structure with the format information.

Note If you want the final project to have the same format as one of your source files, you can get the AM_MEDIA_TYPE structure directly from the source file, using the media detector. See IMediaDet::get_StreamMediaType.

Cast the SCompFmt0 variable to a pointer of type long, as shown in the following example.

SCompFmt0 *pFormat = new SCompFmt0;
memset(pFormat, 0, sizeof(SCompFmt0));
pFormat->nFormatId = 0;

// Initialize pFormat->MediaType. (Not shown.)

pGroup->SetSmartRecompressFormat( (long*) pFormat );

The smart render engine automatically searches for a compatible compression filter. You can also specify a compression filter for a group by calling ISmartRenderEngine::SetGroupCompressor.

To build the graph, use the same steps that were described for the Basic Render Enginer in the previous section. The only differences are the following:

  • Use the smart render engine, not the basic render engine. The class identifier is CLSID_SmartRenderEngine.
  • Set compression parameters after you build the front end but before you render the output pins. Call the ISmartRenderEngine::GetGroupCompressor method to obtain a pointer to a group's compression filter. Then query for the IAMVideoCompression interface, as described previously.
  • When you render the output pins, there is no need to insert a compression filter. The stream is already compressed.


Providing a Custom Video Resizer

Note This feature requires DirectX 9.0 or later.

When DirectShow Editing Services (DES) resizes a video source clip, the default behavior is a StretchBlt, which is fast but not anti-aliased. You can change the resizing behavior by implementing a custom resizer as a DirectShow transform filter. The filter must expose the IResize interface, which enables DES to specify the input and output video size. For information about writing a transform filter, see Writing Transform Filters. The CTransformFilter base class is recommended as the starting point. When you implement the filter, note the following:

  • Support the IResize interface on the filter (not the pins).
  • The filter should accept only VIDEOINFOHEADER formats (FORMAT_VideoInfo). Reject other format types.
  • The video format from DES may be any uncompressed RGB type, including 32-bit RGB with alpha (MEDIASUBTYPE_ARGB32). Your filter can safely reject formats with biHeight < 0.
  • Before the Render Engine connects the filter's output pin, it calls IResize::put_MediaType to set the output type. It may also call IResize::put_Size to adjust the output size. It can call these two methods in any order, any number of times, before it connects the output pin.
  • After the Render Engine connects the output pin, it might call put_Size again. The resizer filter should reconnect its output pin with the new size.
  • Inside the filter's CTransformFilter::Transform method, stretch the input video to the output size.
  • Your filter should never set the discontinuity flag on the output sample, or attach a media type to the output sample.
  • To save the filter's state in a GraphEdit (.grf) file, implement the IPersistStream interface. (This is optional, but useful for testing.)

To use the resizer filter, the filter must be registered as a COM object on the user's system. Before the application renders the video project, query the Render Engine for the IRenderEngine2 interface and call IRenderEngine2::SetResizerGUID with the CLSID of the resizer filter.


Selecting a Decoder in DirectShow Editing Services

When DirectShow Editing Services (DES) renders a video editing project, the Rendering Engine automatically selects the necessary decoders. This may happen inside the IRenderEngine::ConnectFrontEnd method, or else dynamically during rendering.

A user might install several decoders that are capable of decoding a particular file. This is particularly true for MPEG-2 content, because DirectShow does not provide an MPEG-2 decoder, so users often install third-party decoders. When multiple decoders are available, DES uses the Intelligent Connect algorithm to select the decoder.

There is no way for the application to specify directly which decoder to use. However, you can choose the decoder indirectly through the IAMGraphBuilderCallback callback interface. By implementing this interface in your application, you can receive notifications during the graph-building process and reject certain filters from the graph.

Start by implementing a class that exposes the IAMGraphBuilderCallback interface:

class GraphBuilderCB : public IAMGraphBuilderCallback
{
public:
     // Method declarations (not shown).
};

Then create an instance of the Filter Graph Manager and register your class to receive callback notifications:

// Declare an instance of the callback object.
GraphBuilderCB GraphCB;

// Create the Filter Graph Manager.
CComPtr<IGraphBuilder> pGraph;
hr = pGraph.CoCreateInstance(CLSID_FilterGraph);
if (FAILED(hr))
{
    // Handle error (not shown).
}
// Register to receive the callbacks.
CComQIPtr<IObjectWithSite> pSite(pGraph);
if (pSite)
{
    hr = pSite->SetSite((IUnknown*)&GraphCB);
}

Next, create the Render Engine and call the IRenderEngine::SetFilterGraph method with a pointer to the Filter Graph Manager. This ensures that the Render Engine does not create its own Filter Graph Manager, but instead uses the instance that you have configured for callbacks.

CComPtr<IRenderEngine> pRender;
hr = pRender.CoCreateInstance(CLSID_RenderEngine);
if (FAILED(hr))
{
    // Handle error (not shown).
}

hr = pRender->SetFilterGraph(pGraph);

When the project is rendered, the application's IAMGraphBuilderCallback::SelectedFilter method is called immediately before the Filter Graph Manager creates a new filter. The SelectedFilter method receives a pointer to an IMoniker interface that represents a moniker for the filter. Examine the moniker, and if you decide to reject the filter, return a failure code from the SelectedFilter method.

The difficult part is to identify which monikers represent decoders — and in particular, which monikers represent decoders that you want to reject. One solution is the following:

  • Before rendering the project, use the IFilterMapper2::EnumMatchingFilters method to create a list of filters that are registered as accepting the desired input type. For video or audio compression types, this list should map to a set of decoders.
  • The EnumMatchingFilters method returns a collection of monikers. For each moniker in the collection, get the DisplayName property, as described in Using the Filter Mapper.
  • Store a list of the display names, but omit the display name that matches the filter you want to use for decoding. Display names for software filters have the following form:
    OLESTR("@device:sw:{CategoryGUID}\{FilterCLSID}");

    where CategoryGUID is the GUID of the filter category, and FilterCLSID is the filter's CLSID. For DMOs, the format is the same, but change sw to dmo.

    The list now contains display names for every filter that outputs the desired media type but is not your preferred filter.

  • In the SelectedFilter method, get the DisplayName property on the proposed moniker and check it against the stored list. If the display name matches an entry in the list, reject that filter. Otherwise, accept it by returning S_OK.


Logging Errors

Microsoft® DirectShow® Editing Services (DES) provides a built-in mechanism for logging errors that occur when loading, constructing, or rendering a DES project. This article presents a sample console application that loads an XML project file and attempts to render it. If an error occurs, the application prints an error message in the console window. The sample code presented in this article builds on the example given in Loading and Previewing a Project.

Note Your application is not required to implement error logging. DES does not log errors unless you explicitly request it.

This article assumes that you understand COM client programming and the DES timeline model. In addition, you need to understand the basics of COM object programming. For information about timelines in DES, see The Timeline Model.

This article contains the following sections.

  • Overview of Error Logging
  • Creating an Error Logging Class
  • Implementing IAMErrorLog
  • Setting the Error Log
  • DES Error Logging: Example Code


Overview of Error Logging

To give applications maximum flexibility in handling errors, DES uses a callback mechanism. Your application implements a method for logging an error. At run time, if an error occurs, DES calls the method you have provided. The method takes parameters that describe the error. What the method does with this information is up to you. (It should return as quickly as possible, however, or it might interfere with the execution of the program.)

The error logging callback method is contained in a COM interface, IAMErrorLog. Your application must implement this interface. Like all COM interfaces, IAMErrorLog inherits the IUnknown interface, so your application must implement that as well.

You have several choices for implementing these COM interfaces. You can use the Active Template Library (ATL), which provides stock implementations of the IUnknown methods. DirectShow also provides a C++ base class, CUnknown, that makes it easy to implement a COM interface. For information on using CUnknown, see How to Implement IUnknown.

The sample code in this article defines a self-contained C++ class, which implements both IUnknown and IAMErrorLog. The result is not a true COM object, because it does not support CoCreateInstance. However, this approach is adequate for the purpose of the example.


Creating an Error Logging Class

First, declare a class that will implement error logging. The class inherits the IAMErrorLog interface. It contains declarations for the three IUnknown methods, and for the single method in IAMErrorLog. The class declaration is as follows:

class CErrReporter : public IAMErrorLog
{
protected:
    long    m_lRef; // Reference count.

public:
    CErrReporter() { m_lRef = 0; }

    // IUnknown
    STDMETHOD(QueryInterface(REFIID, void**));
    STDMETHOD_(ULONG, AddRef());
    STDMETHOD_(ULONG, Release());

    // IAMErrorLog
    STDMETHOD(LogError(LONG, BSTR, LONG, HRESULT, VARIANT*));
};

The only member variable in the class is m_lRef, which holds the object's reference count.

Next, define the methods in IUnknown. The following example shows a standard implementation for these methods:

STDMETHODIMP CErrReporter::QueryInterface(REFIID riid, void **ppv)
{
    if (ppv == NULL) return E_POINTER;

    *ppv = NULL;
    if (riid == IID_IUnknown)
        *ppv = static_cast<IUnknown*>(this);
    else if (riid == IID_IAMErrorLog)
        *ppv = static_cast<IAMErrorLog*>(this);

    else
    return E_NOINTERFACE;

    AddRef();
    return S_OK;
}

STDMETHODIMP_(ULONG) CErrReporter::AddRef()
{
    return InterlockedIncrement(&m_lRef);
}

STDMETHODIMP_(ULONG) CErrReporter::Release()
{
    // Store the decremented count in a temporary
    // variable.
    ULONG uCount = InterlockedDecrement(&m_lRef);
    if (uCount == 0)
    {
        delete this;
    }
    // Return the temporary variable, not the member
    // variable, for thread safety.
    return uCount;
}

With the COM framework in place, you can now implement the IAMErrorLog interface. The next section describes how to do this.


Implementing IAMErrorLog

The IAMErrorLog interface contains a single method, LogError. The parameters to the method contain information about the error that occurred.

STDMETHODIMP LogError(
    LONG Severity,          // Reserved. Do not use.
    BSTR ErrorString,       // Description.
    LONG ErrorCode,         // Error code.
    HRESULT hresult,        // HRESULT that caused the error.
    VARIANT *pExtraInfo);   // Extra information about the error.

The error code and the error string are defined by DirectShow Editing Services. For a list of errors, see Rendering Errors.

The pExtraInfo parameter contains a pointer to a VARIANT type that holds additional information about the error. The data type and contents of the VARIANT depend on the specific error that occurred. For example, if the error was caused by an incorrect file name, the VARIANT is a string with the bad file name. Some errors do not have extra information, so pExtraInfo might be NULL. The following code shows how to test the vt member of the VARIANT, which indicates the data type, and format a message accordingly.

if( pExtraInfo )    // Report extra information, if any.
{
    printf("\tExtra info: ");
    if( pExtraInfo->vt == VT_BSTR )      // Extra info is a BSTR.
    {
        UINT len = SysStringLen(pExtraInfo->bstrVal);
        char *szExtra = new char[len];
        if (szExtra != NULL)
        {
            // Note - If the BSTR contains embedded NULL characters, this
            // will only pick up the first sub-string.
            WideCharToMultiByte(CP_ACP, 0, pExtraInfo->bstrVal, -1,
                szExtra, len, 0, 0);
            printf("%s\n", szExtra);
            delete [] szExtra;
        }
    }
    else if( pExtraInfo->vt == VT_I4 )   // Extra info is an integer.
        printf("%d\n", pExtraInfo->lVal);

    else if( pExtraInfo->vt == VT_R8 )   // Extra info is floating-point.
        printf("%f\n", pExtraInfo->dblVal);
}

Note Do not free the VARIANT pointed to by pExtraInfo. Also, the VARIANT becomes invalid after the method returns, so do not reference it later.


Setting the Error Log

After you implement the error logging class, create a new instance of the class. Then, give DES a pointer to it by calling the IAMSetErrorLog::put_ErrorLog method on the timeline. Query the timeline for the IAMSetErrorLog interface. To ensure that all errors are logged, you should call this method before you load, save, or render the timeline.

IAMSetErrorLog  *pSetLog = NULL;
IAMErrorLog     *pLog = new CErrReporter();

pTL->QueryInterface(IID_IAMSetErrorLog, (void **)&pSetLog);
pSetLog->put_ErrorLog(pLog);
pSetLog->Release();

Error logging has no effect on the return values that you receive when you call methods in your application. Error logging complements but does not replace the usual error handling techniques. To create a robust application, always check HRESULT values.


DES Error Logging: Example Code

The following sample code presents a complete console application that loads and previews an XML project file, using the error logging class described in this section. (See Logging Errors.) The name of the project file is hard-coded into the application.

To make the code shorter, the console application uses ATL smart pointers, which removes the need to call QueryInterface and Release. If you prefer, you can modify the sample application in Loading and Previewing a Project. Simply add the code shown in the previous section.

#include <atlbase.h>
#include <dshow.h>
#include <qedit.h>
#include <stdio.h>

// Declare error logging class.
class CErrReporter;

// (The implementation of CErrReporter was given previously.)

void __cdecl main(void)
{
    HRESULT hr = CoInitialize(NULL);

    if (FAILED(hr))
    {
        // Error handling is omitted for clarity.
    }

    { // Scope for smart pointers.

    CComPtr<IAMTimeline>   pTL;
    CComPtr<IRenderEngine> pRenderEngine;
    CComPtr<IXml2Dex>      pXML;
    CComPtr<IGraphBuilder> pGraph;

    hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
                IID_IAMTimeline, (void**) &pTL);
    hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
                IID_IXml2Dex, (void**) &pXML);
    hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
                IID_IRenderEngine, (void**) &pRenderEngine);

    // Set the error log.
    CComQIPtr<IAMSetErrorLog, &IID_IAMSetErrorLog> pSetLog(pTL);
    if (pSetLog)
    {
        IAMErrorLog *pLog = new CErrReporter;
        pSetLog->put_ErrorLog(pLog);
    }

    // Load and preview the project.
    CComBSTR bstrFile(OLESTR("C:\\example.xtl"));
    hr = pXML->ReadXMLFile(pTL, bstrFile);
    if (SUCCEEDED(hr))
    {
        hr = pRenderEngine->SetTimelineObject(pTL);
        hr = pRenderEngine->ConnectFrontEnd( );
        hr = pRenderEngine->RenderOutputPins( );
        hr = pRenderEngine->GetFilterGraph(&pGraph);

        CComQIPtr<IMediaControl, &IID_IMediaControl> pControl(pGraph);
        CComQIPtr<IMediaEvent, &IID_IMediaEvent> pEvent(pGraph);
        pControl->Run();

        long evCode;
        hr = pEvent->WaitForCompletion(INFINITE, &evCode);
        pControl->Stop();
    }
    // Clean up.
    pRenderEngine->ScrapIt();
    }
    CoUninitialize();
}


Using Windows Media With DirectShow Editing Services

This section describes how to use Windows Media–based content in a DirectShow Editing Services (DES) application. There are two main scenarios:

  • Source clips. A DES project can contain audio and video clips from Windows Media files.
  • Target format. Windows Media is an ideal format for the final output of a video editing project.

To work with Windows Media files, the application must provide a software certificate, also called a key. It does this by implementing a key provider object. The key provider is a COM object the exposes the IServiceProvider interface. For information about implementing the key provider, see Unlocking the Windows Media Format SDK.

To use DES with Windows Media files, the following DES objects require the software key:

  • The render engine, for previewing or file writing.
  • The MediaDet object, to get video frames or media types from ASF files.

Important Do not use the Smart Render Engine to read or write Windows Media files. Always use the Basic Render Engine (CLSID_RenderEngine).

To give an object the software key, query that object for the IObjectWithSite interface and call IObjectWithSite::SetSite with a pointer to your key provider. For example, the following code provides the software key to the render engine:

// Create your key provider, using an application-defined function:
IServiceProvider *pKey;
hr = MyCreateKeyProviderFunction(&pKey);

// Query the Render Engine for IObjectWithSite.
IObjectWithSite *pOWS;
hr = pRenderEngine->QueryInterface(__uuidof(IObjectWithSite),
    reinterpret_cast<void**>(&pOWS));
if (SUCCEEDED(hr))
{
    // Give it your key provider.
    hr = pOWS->SetSite(pKey);
    pOWS->Release();
}
pKey->Release();

To use Windows Media source clips in a DES project, simply call IObjectWithSite::SetSite on the render engine with a pointer to your key provider.

For information about writing Windows Media files, see Writing a Windows Media File in DES.


Writing a Windows Media File in DES

This section describes how to write a Windows Media file using DirectShow Editing Services (DES).

Important Do not use the Smart Render Engine to write Windows Media files. Always use the Basic Render Engine (CLSID_RenderEngine).

To write a Windows Media file, do the following:

  1. Call SetSite on the render engine, with a pointer to your key provider.
  2. Build the front end of the graph. (See Rendering a Project.)
  3. Create the WM ASF Writer filter and add it to the graph.
  4. Use the IFileSinkFilter interface on the WM ASF Writer filter to set the file name.
  5. Configure the WM ASF Writer to use a Windows Media profile. Each profile has a predefined number of streams. You must choose a profile that matches the groups in your project.

    The IConfigAsfWriter interface contains a few different methods for setting the profile. For example, the ConfigureFilterUsingProfileGuid method specifies a system profile as a GUID. Or, you can use Windows Media Format methods to get an IWMProfile pointer and then call IConfigAsfWriter::ConfigureFilterUsingProfile. For more information, see Configuring the ASF Writer.

  6. Connect the front end to the ASF Writer. The front end of the graph contains one output pin for each group. Assuming that you specified a compatible profile, the ASF Writer should have a matching set of input pins. Connect each output pin to the corresponding input pin. The easiest way to do this is using the ICaptureGraphBuilder2::RenderStream method. First, create a new instance of the Capture Graph Builder and initialize it with a pointer to the Filter Graph Manager:
    ICaptureGraphBuilder2 *pBuild = 0;
hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, 0, CLSCTX_INPROC_SERVER,
    IID_ICaptureGraphBuilder2, (void**)&pBuild);
pBuild->SetFiltergraph(pGraph);

    Next, retrieve the output pin for each group by calling the IRenderEngine::GetGroupOutputPin method. Call RenderStream to connect the pin to the ASF Writer:

    long cGroups = 0;
hr = pTimeline->GetGroupCount(&cGroups);
for (long i = 0; i < cGroups; i++)
{
    IPin *pPin;
    hr = pRenderEngine->GetGroupOutputPin(i, &pPin);
    if (SUCCEEDED(hr))
    {
        hr = pBuild->RenderStream(0, 0, pPin, 0, pASF);
    }
    pPin->Release();
}
pBuild->Release


Managing Video Editing Projects

The following tips will help you to manage projects in Microsoft® DirectShow® Editing Services.

Changes to the Timeline

  • If you change the timeline after you build the filter graph, call IRenderEngine::ConnectFrontEnd again to rebuild the front end. Usually, this does not affect the rest of the graph. Occasionally, however, the render engine needs to delete the entire graph before it rebuilds the front end. (For example, this happens if you add or remove a group.) The ConnectFrontEnd method returns S_WARN_OUTPUTRESET to signal that it deleted the graph. If this happens, your application must rebuild the rendering section of the graph.
  • To remove all objects completely from the timeline, call the IAMTimeline::ClearAllGroups method.

Cleanup

  • When you are finished using a render engine, call the IRenderEngine::ScrapIt method. As with any COM object, be sure to release every interface pointer when you are finished using it.
  • The render engine does not keep a reference count on the timeline. Do not release the timeline before you are done using it, and always call ScrapIt on the render engine first.
  • If you release all references to a timeline, do not use any of the objects in that timeline, even if you are holding reference counts on them.

Multiple Timeline Instances

  • Do not move timeline objects between timelines. Every object in a timeline must be created by that timeline. The timeline holds an internal cache with information about the objects that it creates; moving timeline objects can disrupt the cache.
  • Never use the same instance of a render engine with more than one timeline. The render engine holds a cache with information about the timeline. Multiple timelines will disrupt the cache and cause unpredictable results. If you need two active timelines, make separate instances of render engines for each timeline.
  • A timeline can use more than one render engine, but not at the same time. Delete the old render engine before using another render engine. (You would typically do this when you switch from using the basic render engine for preview to the smart render engine for file writing.)

Persistence

  • The filter graph is not persistent when you save the project to an XML file. Therefore, you lose any information relating to smart recompression, compression format, or compression parameters. It is up to the application to restore these parameters after it loads a project.


Alpha Blending

This article describes alpha blending in Microsoft® DirectShow® Editing Services (DES).

Alpha measures the transparency of a pixel or image. In 32-bit uncompressed RGB video, four components define each pixel: an alpha channel (A) and three color components (RGB). A pixel with an alpha value of zero is completely transparent. A pixel with an alpha value of 255 is opaque. Between these values, the pixel has various degrees of transparency.

DirectShow defines two media types for 32-bit RGB video:

  • MEDIASUBTYPE_ARGB32: The video is 32-bit RGB with a valid alpha channel.
  • MEDIASUBTYPE_RGB32: Pixels are 32 bits, but the alpha channel is not necessarily valid.

To perform alpha blending in DES, set the video group's uncompressed media type to MEDIASUBTYPE_ARGB32. In C++, call the IAMTimelineGroup::SetMediaType method. In the XTL format, setting the bitdepth attribute of the group element to 32 accomplishes this as well.

Next, you need video data that contains an alpha channel. There are several options:

  • You can use an AVI file that already has 32-bit RGB video with alpha data. Currently, alpha is not supported for MPEG or Microsoft® Windows Media™ Format (WMF) source files.
  • DES supports 32-bit bitmap (.bmp) and Targa (.tga) files with alpha data.
  • You can write a custom source filter that creates 32-bit RGB data with alpha. The output media type must be MEDIASUBTYPE_ARGB32. Use the filter as the subobject in a timeline source object.

If your video source does not have alpha, you can use an effect that creates alpha data. The Alpha Setter Effect sets the alpha channel for the entire image to a constant value. To vary the alpha over time, use the IPropertySetter interface with the Alpha Setter Effect. The original source does not have to be 32 bits, as long as the group's uncompressed media type is MEDIASUBTYPE_ARGB32.

Finally, pass the video to an effect or transition that performs alpha blending. The Compositor Transition performs alpha blending, and the Key Transition can key by alpha value.

The following sample XTL project performs alpha blending:

<timeline>
<group type="video" bitdepth="32" width="320" height="240">
<track>
  <clip start="0" stop="6" src="c:\Example.avi" />
</track>
<track>
  <clip start="0" stop="6" src="c:\Example2.avi">
    <!-- Alpha Setter effect. -->
    <effect clsid="{506D89AE-909A-44f7-9444-ABD575896E35}" start="0" stop="6">
      <param name="alpha" value="255">
        <linear time="6" value="0" />
      </param>
    </effect>
  </clip>
  <!-- Key transition, with alpha keying. -->
  <transition clsid="{C5B19592-145E-11d3-9F04-006008039E37}" start="0" stop="6">
    <param name="KeyType" value="3" />
  </transition>
</track>
</group>
</timeline>


Converting Cutlists to Timelines

This article describes how to convert an existing cutlist application to Microsoft® DirectShow® Editing Services (DES).

Cutlists were a feature in earlier versions of DirectShow that provided limited support for non-linear editing. As of Microsoft® DirectX® 8.0, cutlists are no longer supported. A feature-for-feature conversion to DES should be straightforward to implement. At the very least, you will see the following benefits:

  • Support for heterogeneous sources.
  • Support for compressed sources.
  • Automatic conversion of frame rates.
  • Support for stretching video to fill the frame, or to create a letterbox.
  • Support for slow- and fast-motion audio and video.
  • Better support for audio gaps (silence).

Moving beyond cutlists, you can add features such as project persistence, compositing of multiple tracks, effects, transitions, and poster frames.

A typical cutlist application performs the following steps:

  1. Create separate cutlists for the video and audio streams (IStandardCutList).
  2. For each source file, create a video file clip, audio file clip, or both (IFileClip).
  3. From each file clip, create one or more cuts (IAMCutListElement). Add them to the cutlists.
  4. Create a cutlist graph builder (ICutListGraphBuilder).
  5. Add each cutlist to the cutlist graph builder.
  6. Optionally, set the output file name.
  7. Render and play the graph.

The equivalent steps in DES are:

  1. Create a timeline (IAMTimeline).
  2. For each video and audio stream in the final production, create one group (IAMTimelineGroup).
  3. Add one or more tracks (IAMTimelineTrack) to each group.
  4. Create source objects (IAMTimelineSrc) and add them to the tracks.
  5. Create a render engine (IRenderEngine).
  6. Add the timeline to the render engine.
  7. Render and play the graph.

To highlight some of the differences:

File clips: In DES, there is no object equivalent to the file clip. A source object is roughly equivalent to a cut. As with cuts, more than one source object can refer to the same source file.

Media type: With cutlists, there are two distinct file-clip objects for audio and video. Each has its own CLSID. In DES, the group's media type determines the source object's media type.

File output: There is no direct equivalent in DES to the ICutListGraphBuilder::SetOutputFileName method. File output is somewhat more complicated in DES. However, you gain a great deal of control over the format and compression type. For more information, see Writing a Project to a File.

Modifying projects: With cutlists, you can add new cuts, but you cannot modify or remove cuts. With DES, you can add, remove, rearrange, or modify source objects. For more information, see Managing Video Editing Projects.


DVD Applications

Microsoft® DirectShow® provides a component called the DVD Navigator source filter which simplifies DVD navigation tasks in C++. The DVD Navigator has all the capabilities that you find on a full-featured stand-alone DVD player, plus additional capabilities specific to playing DVDs on personal computers. Using the DVD Navigator, C++ and scripting developers can create full-featured DVD applications without referring to the DVD specification. The DVD Navigator, in coordination with the decoder filters, also handles regional management and copyright protection (CSS and Macrovision), isolating application developers from these details.

The DVD Navigator filter works across an entire DVD-Video "volume," which consists of the files in the VIDEO_TS directory. Unlike most DirectShow source filters that work with individual streams or files, the DVD Navigator uses the DVD-Video structure of titles, chapters, and time codes. Developers wishing to play individual MPEG-2 files in DirectShow should use the MPEG-2 Demultiplexer instead of the DVD Navigator filter. See MPEG-2 Support in DirectShow for more information.

C++ developers control the DVD Navigator directly through the Component Object Model (COM) interfaces it exposes. Script or Visual Basic developers targeting Windows 2000 platforms or earlier can control the DVD Navigator indirectly through the MSWebDVD ActiveX® control. On Windows XP, this same DVD-Navigator based functionality is also provided through the Video Control using the MSVidWebDVD object. For more information, see Using the Video Control.

Most DVD applications, including as players with customized interfaces, Web pages that control DVD playback, PowerPoint presentations with embedded DVD video, can be created in HTML or Visual Basic using the MSVidWebDVD object, together with the Video Control. This is simpler and faster than using C++, which is only required for more specialized applications, such as games, programs that overlay graphics on video, custom ActiveX controls or DLLs, and so on. The MSWebDVD ActiveX control is another lightweight control, but its functionality is contained within the MSVidWebDVD object, and is only recommended with Windows 2000 or earlier platforms.

Note DirectShow provides all the filters necessary to navigate and play DVD-Video except the MPEG-2 decoder. To play DVDs using an application based on DirectShow, users must have installed on their system a third-party hardware or software decoder that is DirectShow-compatible.

This section contains the following topics.

  • DVD Support Features in DirectShow
  • What Background Do I Need to Write a DVD Application?
  • DVD Basics
  • Writing a DVD Application in C++
  • Shortcuts to C++ DVD Reference Pages
  • Writing a Script-Based DVD Application
  • MSWebDVD ActiveX Control

To develop a DVD application using the Video Control, see DVD Applications in Visual Basic (Video Control).

For references on DVD/MPEG2 decoder development, see DVD Decoder Development in DirectShow.

DVD-ROM content developers: The DVD-ROM Boilerplate video is located in the Extras\DirectShow\DVDBoilerplate folder of the DirectX SDK. (Click on "Explore this CD" to navigate to the folder. This folder does not install to your local drive.) The boilerplate video is provided for developers producing DVD-ROM titles that contain no DVD-Video formatted data. A disc without a proper DVD-Video zone may behave unpredictably when placed in a standalone DVD-Video player, possibly ejecting the disc or locking up. This confusing situation can be avoided by adding the DVD-ROM boilerplate video to the disc. When the disc is inserted into a DVD-Video player it will display a message informing the user that the disc is designed to work in a DVD-ROM PC with Microsoft® Windows®.


DVD Support Features in DirectShow

The functionality of the DVD Navigator filter is exposed through two interfaces, IDvdControl2, which provides the "set" methods for the DVD Navigator, and IDvdInfo2, which provides the "get" methods. Scripting support for the DVD Navigator, including most new features, is provided through the MSWebDVD Microsoft® ActiveX® control and through the Video Control on Windows® XP.

The DVD Navigator supports the following features:

  • Karaoke support: You can now write a DVD-karaoke application using the DVD Navigator. (This requires a compatible decoder.)
  • Simplified access to DVD text information strings: The DVD Navigator now parses these strings and enables applications to easily enumerate, identify, and retrieve them.
  • Audio volume control through IBasicAudio
  • Support for customizing the DVD Navigator's behavior when the Stop command is issued: Applications can now instruct the DVD Navigator to either resume from the current location when restarting the filter graph, or start play from the beginning of the disc.
  • Digital Theater Systems (DTS) and Sony Dynamic Digital Sound (SDDS) audio support: Now DTS and SDDS audio streams are recognized by the DVD Navigator and passed to the audio decoder. (A third-party DTS-compatible or SDDS-compatible decoder is required to decode and play the audio.)
  • Improved support for parental level changes: The DVD Navigator now allows an application to accept, reject, or ignore parental level change commands from the disc.
  • Advanced options for managing the state of the DVD Navigator and synchronizing commands
  • Support for frame stepping, frame-accurate seeking, and reverse play: These new features require an updated video decoder that supports them.
  • The ability to save the current location in a title and return to it at any time.
  • Simplified support for time events in non-sequential PGC titles: For non-sequential PGC titles, the DVD Navigator now relays the raw timecode information to the application.
  • A new, more convenient data structure for handling timecode information: The DVD_HMSF_TIMECODE structure can be used in place of the binary coded decimal (BCD) format. DVD_HMSF_TIMECODE contains easily accessed members for hours, minutes, seconds, and frames, and can be cast to/from a ULONG.
  • The ability to control whether the filter graph flushes after a seek operation: The graph buffers can contain up to a few seconds of video at any given time. You can now instruct the graph to either finish playing the buffered video after a seek, or begin playing immediately at the new location.
  • The ability to set values in general parameter registers: An advanced feature for those familiar with the DVD specification who wish to implement advanced functionality.
  • The ability to generate numeric disc identifiers that are for all practical purposes unique: This is helpful in MSWebDVD applications where a disc needs to be associated with particular Web-based enhancements.


What Background Do I Need to Write a DVD Application?

All application developers should have a basic familiarity with the features provided by DVD technology such as parental management levels, multiple audio and subpicture streams, and angle blocks. DVD Basics briefly describes each of these features; more complete descriptions are available in third-party publications. You don't need to refer to the DVD specification unless you intend to implement advanced features beyond the Annex J command set.

C/C++ developers using the Microsoft® DirectShow® Component Object Model (COM) application programming interface (API) should be familiar with COM client programming techniques such as creating COM objects and obtaining and releasing COM interface pointers. You might also need a general knowledge of filter graph operations, because you might need to access and manipulate the graph directly.

If you are using Microsoft® Visual Basic®, Microsoft® JScript®, or Visual Basic Scripting Edition (VBScript), you should be familiar with the basics of hosting Microsoft® ActiveX® controls within an application. Writing a Script-Based DVD Application shows how to embed the control in a Web page and receive event notifications from it.


DVD Basics

The features that make DVD attractive to consumers—seamless branching, multiple languages, parental control, karaoke support, and multiple angles—also make the developer's job a little more complex. A DVD player must not only play back audio, video, and subpicture streams, but also must keep track of the navigation options that the disc is currently permitting, and correctly handle many types of user commands. The DVD Navigator shields you from much of this complexity while enabling you to create a fully-functional DVD application. You do not need to refer to the DVD specification to use the DVD Navigator API effectively, but you do need to know basic DVD navigation concepts. The following sections provide some necessary background information. You can find further information on DVD in third-party publications or on the World Wide Web.

  • Navigation Control Data
  • Audio, Video and Subpicture Data
  • Titles and Chapters
  • Menus
  • Parental Management Levels
  • Domains
  • User Operation Controls

Navigation Control Data

The audio and video data on a DVD-Video disc is interleaved at regular intervals with various kinds of navigation control data. This data may be an instruction that tells the player to do something, for example move to some particular place on the disc, or it may be an informational-only marker informing the player for example that the content that follows has a higher parental management level than the previous content, or that the chapter skip operation is disabled. The player relays this information to an application, and it is the responsibility of the application to act on it. These navigation markers are part of what give DVD its higher level of user-interactivity compared to Video CDs. A DVD-player application must handle events that originate with the disc as well as events that originate with the user.

Audio, Video and Subpicture Data

A DVD-Video disc contains three primary types of streams: video, audio and subpicture.

  • The video stream can contain up to nine "angles," which can be thought of as substreams. DVD authors can include multiple angles wherever they wish to offer the viewer a choice of camera angles from which to view the same scene. Only one angle can be active at a time. The video stream also contains line 21 Closed Caption data, if any exists.
  • There can be up to eight separate audio streams, or tracks, providing up to eight multichannel soundtracks and allowing DVD karaoke discs to make use of multichannel audio.
  • There can be up to 32 subpicture stream containing bitmap graphics used for menu buttons and subtitles. The subpicture data streams are independent of the Closed Caption data in the video stream, although they may look similar when they appear in the video rectangle. If a disc contains both subpicture and Closed Caption data, you cannot display both at the same time.

Titles and Chapters

The main logical division on a DVD-Video disc is a title. A title can represent an entire movie or a 30-second video clip. There may be up to 99 titles on a disc and disc authors may divide the title into as many as 999 logical chapters. In most feature films on DVD, movie content is formatted as a series of chapters which automatically play one after another. On such discs, the end-of-chapter marker contains a branching instruction that tells the player to continue playing the next chapter in the sequence. These titles are referred to as One Sequential PGC Titles. (PGC stands for program chain, another name for a group of chapters that belong together. This term is not used in the DVD Navigator documentation.) On discs with other types of content, such as karaoke discs, an end-of-chapter marker might instruct the player to show a menu, or it might simply instruct the player to stop.

DVD application developers use title and chapter numbers to jump to specific points on a disc. For finer access, a title number and timecode can be used. Timecodes can only be used with One Sequential PGC Titles, since other types do not contain timecode maps.

Menus

Menus are the principle means by which users interact with the content on a DVD when played in a traditional player. Menus enable users to choose which video title to show, which audio soundtrack to play, which subtitles to display, which camera angle to view, and what other special features to enable. DirectShow DVD application developers have the choice of enabling menus as in a traditional player or creating a new computer-based interface that replaces or supplements the menus authored on the disc. The application can also simulate user interaction by programmatically selecting and activating menu buttons.

The Video Manager Menu
The top level menu is the Video Manager Menu (VMGM), also called the Top Menu or Title Menu. This menu usually has buttons that enable the user to go to the main titles or groups of titles on the disc. A group of titles is called a title set. For example, on a disc that has a feature film, a title set called "Interviews With the Director and Cast," and a title set called "Coming Attractions," the VMGM would probably have three buttons. Clicking the "Coming Attractions" button would take the user to a Video Title Set Menu (VTSM) with buttons for each separate title in the title set.

Because a disc can contain soundtracks in up to eight languages. It can also contain multiple VMGMs in languages that correspond to those on the soundtracks.

The VMGM appears when the user starts playing the disc unless the first title on the disc is authored as an autoplay title. In this case there may not be a VMGM. Most feature films on DVD are authored as autoplay titles.

Video Title Set Menus and Submenus
A Video Title Set Menu, also called a Root Menu (even though it's not at the root!), is a submenu of the VMGM. There can be from 1 to 99 titles in a title set. The VTSM has buttons enabling the user to go to any of the titles in the title set. In addition, the VTSM can also have submenus which enable the user to go to choose options for the audio stream, camera angle, subpicture stream, or chapter. These submenus are always valid for all the titles in the title set. VTSM submenus are not used on most DVDs. The root menu and all other submenus are optional, so never assume that all submenus in a VTSM have a common root menu.

Parental Management Levels

All or part of a DVD disc can be encoded with a Parental Management Level (PML) numbered from one to eight. Eight is the most restrictive level (adults only) and one is the least restrictive (all ages). The idea is to prevent children from watching adult content without parental consent, while allowing adults to watch child-safe content. In the United States and Canada, the levels map to the rating system of the MPAA (G, PG, PG-13, NC-17), but this is not the case in other countries or regions.

Because chapters can exist logically within a parental block, there may be two versions of the same chapter in a title, each assigned a different PML and in a different parental block. For example, a child who logs in and plays the disc would see one version of Chapter 3, and an adult who logs in would see a different version, assuming that the application supports PMLs.

A title or chapter can also contain temporary PMLs, whose content is rated higher than the PML for the title or chapter as a whole. This means that a title may have more than one parental level. Temporary PMLs are generally authored as angle blocks, so that a scene in a film may have two versions, one rated for younger viewers and one for adults.

It is the responsibility of the player application to enforce the parental levels.

Domains

The concept of the domain is very important to DVD navigation, but domains are not physically marked on the disc in the same way that titles, menus, and angle blocks are, and so DVD authors have no control over them. A DVD domain can be thought of as a type of state variable, with five possible values, that a DVD player monitors in order to keep track of the type of content that the player is currently reading from the disc. DVD players use domains to keep from issuing meaningless commands to the DVD drive. For example, a "SelectButton" command is only meaningful if a menu is displayed, and a "FastForward" command makes no sense if the player is currently stopped or is showing a menu, which is a still image. The following table summarizes the domains and their meaning from the perspective of an application.

Domain | What the DVD Navigator is reading
First Play | The initial section of the disc, for example, the FBI warning.
Video Manager Menu | The main menu for the entire disc or disc side. Any menu-related methods are valid.
Video Title Set Menu | The menu for a title or group of titles, or one of its submenus—subpicture, language, audio, or angle. Any menu-related methods are valid.
Title | The video content in a title. The menu-related methods are not valid.
Stop | Nothing. The head is retracted from the disc. From here you can call Play.

User Operation Controls

User Operation Controls (UOPs) are markers on a disc that DVD authors can insert anywhere to restrict a user's navigation options. Most discs follow standard UOP restrictions. For example, most discs do not allow the viewer to fast forward or show a menu while in First Play domain. In principle, each disc can insert any UOP command at any point on the disc, even if the command would otherwise be valid within the current domain. For example, a disc may be authored to disallow fast forwarding in a certain title or to prevent a particular menu from being shown after the user enters the title domain. The DVD Navigator complies with all such commands from the disc and will not allow an application to override the disc's UOP controls.


Writing a DVD Application in C++

This article describes the main steps in creating a DVD application in C++. Most of the code examples presented here are from the DirectShow 8.0 DVD sample application, located in the sample directory in the DirectShow SDK. This article contains the following sections. For background information on basic general concepts in DVD, see DVD Basics.

If you wish to use the Video Control and MSVidWebDVD object, refer to the MSVidWebDVD scripting reference pages

NOTE Neither Windows XP nor the DirectX SDK offers an MPEG-2 decoder for writing DVD applications. Many DVD hardware providers offer hardware or software decoding options, and many DVDs come packaged with a DVD decoder. Be sure to check that your target machine can support DVD decoding by trapping errors such as VFW_E_DVD_DECNOTENOUGH (in C++).

  • Writing a DVD Application: The Basics
  • DVD Filter Graph Configuration
  • Building the DVD Filter Graph
  • Obtaining the DVD Interface Pointers
  • Handling DVD Event Notifications
  • Working With DVD Menus
  • Audio and Subpicture Streams
  • Enforcing Parental Management Levels
  • Working with DVD Text Strings
  • Saving and Restoring DvdState Objects
  • Playing Karaoke Audio Streams
  • Synchronizing DVD Commands
  • DVD Command Flags
  • Handling Disc Ejections


Writing a DVD Application: The Basics

When writing a DVD application, you supply the code for the user interface, and call into the Microsoft® DirectShow® application programming interface (API) to issue all DVD playback and navigation commands. This involves calling the Component Object Model (COM) CoCreateInstance method on the DVD Graph Builder object, which does the actual work of creating the DVD filter graph. After the filter graph is created, you can obtain pointers to the IDvdControl2 and IDvdInfo2 interfaces exposed by the DVD Navigator source filter. After you have the interface pointers, you can connect your user interface to the DVD navigation commands such as PlayTitle, Pause, and so on. This basic process is quite simple and is similar to the creation of other types of DirectShow applications.


DVD Filter Graph Configuration

In previous versions of DirectX, application developers didn't need to be concerned with the details of the DVD filter graph because there was only one video renderer used in all cases—the Overlay Mixer. In Windows XP, the Video Mixing Renderer 7 was introduced, and in DirectX 9.0 the Video Mixing Renderer 9 became available for downlevel support. So there are now three different renderers to choose from. The renderer that your application uses will depend on (1) the operating system, (2) the type of MPEG-2 decoder, and (3) the video hardware present on the user's system.

The following illustration shows a DVD filter graph with a software decoder for applications that run on Microsoft® Windows® 98SE, Windows 2000, or Windows Me.

DVD Filter Graph

On Windows XP, the Overlay Mixer and Video Renderer are replaced by the Video Mixing Renderer Filter 7, and the Line 21 Decoder is replaced by the Line 21 Decoder 2 filter, as shown in the following illustration. This graph also has a software decoder.

DVD Filter Graph for Windows XP

When a hardware decoder is present, it is typically connected directly to the video card by a video port. This enables the decoded video bits to be sent directly to the frame buffer on the graphics card without passing into host memory. To manage this direct connection on earlier versions of Windows, DirectShow supports DirectDraw Video Port Extensions (VPE) through an interface on the Overlay Mixer Filter. The following diagram shows a filter graph with a hardware decoder for applications running on Windows® 98SE, Windows 2000, or Windows Me.

DVD graph with a hardware decoder for Windows 98/2000

The next diagram shows a DVD filter graph for applications running on Windows XP.

DVD graph for Windows XP with a hardware decoder

In all these graphs, the DVD Navigator is the source filter; it performs several tasks:

  • Reads the navigation and video data from the disc.
  • Demultiplexes the video, audio, and subpicture data into separate streams.
  • Pumps the streams into the graph for further processing and eventual rendering.
  • Informs your application of DVD-related events.

On the audio stream, the DVD Navigator connects downstream to an audio decoder, which connects to the DirectSound Renderer Filter, the default audio renderer. On the video and subpicture streams, the downstream filters are the third-party video decoder, and the Video Mixing Renderer (or the Overlay Mixer, and the Video Renderer on downlevel applications). If your application will handle line 21 closed-captioned data, you must add the DirectShow Line 21 Decoder 2 filter to the graph. This involves a single method call; the filter will be connected automatically.

Your application communicates with and controls the DVD Navigator through the custom interfaces that the DVD Navigator exposes: IDvdControl2—the "set" methods—and IDvdInfo2—the "get" methods. It also must communicate with the filter graph manager (through IMediaControl) to stop, start, and otherwise control the graph. You might also need to control other individual filters, such as the Overlay Mixer filter for switching between windowed and full-screen display. For more information, see IMixerPinConfig2. The exact configuration of the graph will vary depending on what type of MPEG-2 decoder you have installed, whether you need to handle line 21 closed-captioned data, and other factors.


Building the DVD Filter Graph

The recommended way to build the DVD playback filter graph is to have a DVD Graph Builder object do it for you automatically. This approach is demonstrated below and in the DVD sample application. If you need to build your DVD filter graph manually, you can do so by following the basic rules of graph building discussed elsewhere in the DirectShow documentation. Generally, you should not manually add, remove, connect, or disconnect individual filters in the graph created by the DVD Graph Builder, because doing so might confuse the cleanup code.

When creating an instance of the DVD Graph Builder object, an application receives a pointer to the object's IDvdGraphBuilder interface. Call IDvdGraphBuilder::GetFiltergraph to obtain the filter graph manager's IGraphBuilder interface, and then call QueryInterface on IGraphBuilder to obtain IMediaEventEx. Use this interface to begin receiving events before building the rest of the graph. This will ensure that your application receives events from the DVD Navigator when it is initialized. To build the graph, simply call the IDvdGraphBuilder::RenderDvdVideoVolume method. For more information, see Building the Filter Graph.

On Windows XP, without the DirectX 9 runtimes, the DVD Graph Builder will always use the Video Mixing Renderer 7 (VMR-7) in the graph, unless:

  • the caller queries interfaces found only the Overlay Mixer, such as IMixerPinConfig2. This sends a hint to the DVD Graph Builder that the application wants to use the Overlay Mixer and not the VMR. Windows Media Player also has a dialog box option to force the use of the Overlay Mixer.
  • the installed decoder is not VMR-compatible. During graph building, the new IAMDecoderCaps interface is used to check for the decoder's VMR support. If that is not present, the DVD Graph Builder will use the Overlay Mixer.
  • while using a hardware decoder, the decoder cannot connect to the Video Port Manager (VPM). If a hardware decoder cannot use the VPM, then it cannot use the VMR, and so the DVD Graph Builder then tries to build a graph using the Overlay Mixer.
  • the display card is known to have insufficient resources and/or capabilities to support the VMR but does not correctly report this in the driver. (Some known cases are specifically excluded by the DVD Graph Builder.)
  • the connection between the decoder and the VMR fails for any reason, usually due to a lack of VRAM to create the necessary surfaces. In these cases, the DVD Graph Builder switches off VMR use and tries to use the Overlay Mixer to build a graph.

On any system with a software MPEG-2 decoder and the DirectX 9 runtimes installed, the application should attempt to create the DVD Graph Builder with the AM_DVD_VMR9_ONLY f lag in the dwFlags parameter of IDvdGraphBuilder::RenderDvdVideoVolume. This method instructs the DVD Graph Builder to use only the Video Mixing Renderer 9 (VMR-9). When this flag is specified, if the graph builder cannot use the VMR-9 in the graph due to any reason, for example if

  • the video card's capabilities are not adequate for VMR-9, or
  • the decoder is not VMR-9 compliant, or
  • the only video decoder is hardware based (uses video port or analog overlay), or
  • there is not enough display resources ( for example, low VRAM, known bad VGA cards, or too high resolution)

then RenderDvdVideoVolume will fail, and the application has the option of attempting to build the graph with the VMR-7 or the Overlay Mixer.

Also, since the VMR-9 does not support video ports or analog overlays, if the filter graph is using a hardware MPEG-2 decoder, especially for video, then the application must use the Overlay Mixer in all such cases.

An application can also call IDvdGraphBuilder::GetDvdInterface for any of the VMR-9 interfaces, which will result in the VMR-9 being inserted in the graph. The application then has an opportunity to configure the VMR-9 before starting to build the graph.


Obtaining the DVD Interface Pointers

After the filter graph is built, your application can obtain the pointers it needs to control the DVD Navigator, the Filter Graph Manager, and the video window. The basic steps, with error-checking and other code left out for simplicity, are illustrated in the following code example. The complete code is found in the DVD Sample application in the CDvdCore::BuildGraph method.

// Create an instance of the DVD Graph Builder object.
HRESULT hr;
hr = CoCreateInstance(CLSID_DvdGraphBuilder,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDvdGraphBuilder,
                          reinterpret_cast<void**>(&m_pIDvdGB));

// Build the DVD filter graph.
AM_DVD_RENDERSTATUS buildStatus;
hr = m_pIDvdGB->RenderDvdVideoVolume(pszwDiscPath, m_dwRenderFlags, &buildStatus);

// Get the pointers to the DVD Navigator interfaces.
hr = m_pIDvdGB->GetDvdInterface(IID_IDvdInfo2, reinterpret_cast<void**>(&m_pIDvdI2));
hr = m_pIDvdGB->GetDvdInterface(IID_IDvdControl2, reinterpret_cast<void**>(&m_pIDvdC2));
   ...
// Get a pointer to the filter graph manager.
hr = m_pDvdGB->GetFiltergraph(&m_pGraph);
...
// Use the graph pointer to get a pointer to IMediaControl,
// for controlling the filter graph as a whole.
hr = m_pGraph->QueryInterface(IID_IMediaControl, reinterpret_cast<void**>(&m_pIMC));
...
// Get a pointer to IMediaEventEx,
// used for handling DVD and other filter graph events.
hr = m_pGraph->QueryInterface(IID_IMediaEventEx, reinterpret_cast<void**>(&m_pME));
...
// Use the graph builder pointer again to get the IVideoWindow interface,
// to set the window style and message-handling behavior of the video renderer filter.
hr = m_pIDvdGB->GetDvdInterface(IID_IVideoWindow, reinterpret_cast<void**>(&m_pIVW));

hr = m_pDvdGB->GetDvdInterface(IID_IAMLine21Decoder, reinterpret_cast<void**>(&pL21Dec));


Handling DVD Event Notifications

The DVD Navigator sends notifications to an application-specified window when certain events take place, such as when the DVD domain changes, when a new parental management level is encountered, and when the DVD Navigator is about to enter an angle block. The event parameters can contain additional information related to the event. Error messages and warnings are also sent in this way. The application specifies the window that will handle the event notifications by using the IMediaEventEx pointer to call SetNotifyWindow, as follows:

const DWORD WM_DVD_EVENT = WM_USER + 100;
hr = m_pIME->SetNotifyWindow(reinterpret_cast<OAHWND>(m_hWnd), WM_DVD_EVENT, 0);

In the preceding example, m_hWnd is the HWND of the window to receive the messages and WM_DVD_EVENT is the application-defined message (greater than WM_USER) that will signal that a DVD event has taken place. The event itself is retrieved by the application through a call to IMediaEvent::GetEvent. Because more than one event might be in the event queue at any given time, the application must call GetEvent within a loop that repeats until all queued events have been retrieved, as shown in the following code example.

while (SUCCEEDED(m_pIME->GetEvent(&lEvent, &lParam1, &lParam2, lTimeOut)))
{
    HRESULT hr;
    switch (lEvent)
    {

    case EC_DVD_CURRENT_HMSF_TIME:
        {
            DVD_HMSF_TIMECODE *pTC = reinterpret_cast<DVD_HMSF_TIMECODE *>(&lParam1);
            m_CurTime = *pTC;
            ...
        }
        break;
        ...
    } // switch
}

DVD events might contain additional information in the lParam1 or lParam2 parameters, as illustrated above where the current time is contained in lParam1. The preceding code example is from the DVD sample application in Dvdcore.cpp. For a complete list of all DVD events and their parameters, see DVD Event Notification Codes.


Working With DVD Menus

The logical structure of DVD menus is discussed in DVD Basics. An application can display a menu from the disc by calling IDvdControl2::ShowMenu and passing the index of the desired menu.

Keep in mind that selecting a button merely highlights its borders. To cause the associated command to be fired, the button must be activated. Some IDvdControl2 methods select a specified button, some activate a button, and SelectAndActivateButton does both. The selection and activation of menu buttons using the mouse is demonstrated in the DVD sample application in CDvdCore::OnMouseEvent.

The IDvdControl2 menu-related methods enable an application to control menus programmatically. An application can highlight or select a button based on a mouse movement or any other user action or some other program logic. An application can also implement and control a custom menu or bitmap representing the buttons on a DVD remote control. In the DVD sample application, the relative button menu commands are connected to the keyboard arrow keys (see CDvdCore::OnKeyEvent). Activating a button programmatically can be done in various ways, but the button must always be selected before it can be activated.


Audio and Subpicture Streams

A DVD-Video disc can have up to eight audio streams, numbered zero through seven, each with up to six discrete channels. (Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.) Only one of these streams can be selected at any given time. For subpictures, up to 32 streams are available, although only one stream can be activated at any given time. Discs are generally authored with default audio and subpicture streams, but an application can enable users to view a list of all the available streams, and select the one in the language they prefer. The basic steps in this process are the same for both audio and subpicture streams.

  1. Determine the number of streams available for a title.
  2. Iterate through the streams and retrieve the stream attributes for each.
  3. Retrieve the language code from the returned locale identifier (LCID) and create a human-readable string.
  4. Populate a list box or other user interface (UI) control to enable the user to select a preferred stream.

In the DVD sample application, the CAudioLangDlg::MakeAudioStreamList method in Dialogs.cpp demonstrates the basic steps.


Enforcing Parental Management Levels

Any title or portion of a title on a DVD-Video disc can be assigned a generic parental management level (PML) from 1 through 8. When the DVD Navigator is reading content that has a PML, it is said to be in a parental block. A parental block may consist of part of a chapter, multiple chapters, or multiple titles. A DVD application intended for an international market should not hard code a particular rating system into its parental management logic.

The DVD Navigator itself does not enforce the PMLs; it merely informs your application when it encounters PML information on the disc. By default, it ignores this information on the disc and plays the highest level content. To enforce the PMLs, your application must implement some form of password control logic that associates users with levels, instruct the DVD Navigator to send it PML event notifications (by calling the IDvdControl2::SetOption method on startup, with the parameters DVD_NotifyParentalLevelChange and TRUE), and respond to those events to allow or disallow access as appropriate.

A DVD title can have one overall PML, but disc authors can give certain sections of that title higher or more restrictive PMLs. These are called temporary PML commands; these commands always contain two branching instructions: one to follow if the temporary PML command is accepted by the player application, and the other to follow if the command is rejected. The sequence of events is as follows. The DVD Navigator is reading video content (DVD Title Domain) when it encounters a temporary PML command on the disc. It checks its internal flag to see whether the application has requested to be notified of this event. If the flag is not set, the DVD continues playing, following the "parental level change rejected" branch specified on the disc. If the flag is set, the DVD sends an EC_DVD_PARENTAL_LEVEL_CHANGE event to the application and waits in a paused state until it gets a response. When your application receives the event, it uses its own logic to determine whether to accept the command. It then calls IDvdControl2::AcceptParentalLevelChange with an argument of TRUE or FALSE. If TRUE, the DVD Navigator resumes playing, following the "parental level change accepted" branch specified on the disc. Otherwise it resumes playing and follow the "parental level change rejected" branch.


Saving and Restoring DvdState Objects

IDvdState objects enable applications to save a snapshot of the user session, including information such as the current location on the disc, the parental level of the person who is viewing, the selected audio and subpicture streams, and so on. This means that users can save their place on a DVD-Video disc and watch it at a later time.

Applications can't create DvdState objects. These objects are created internally by the DVD Navigator when an application calls IDvdInfo2::GetState. DvdState objects expose the IDvdState interface to allow applications to query for certain information.

In the DVD sample application, the CDvdCore::RestoreBookmark and CDvdCore::SaveBookmark functions show how to save and retrieve DvdState objects.


Seeking a DVD to a Specified Time

To accurately seek to a specified time on a disc, call IDvdControl2::Run, then PlayAtTime, specifying the time and setting dwFlags to DVD_CMD_FLAG_Flush.


Working with DVD Text Strings

DVD discs, especially karaoke discs, might contain a database of text information to supplement the video or audio content. Such text on karaoke discs can include song titles, artist names, record labels, and so on. Versions of this text can be present in more than one language. These strings are optional; discs are not required to have them. If present, they are organized in a way that closely mirrors the logical hierarchy of the DVD volume. Each string is preceded by a number that identifies what part of the disc structure the string belongs to or gives some clue as to the content of the string. A subset of the string types is defined in the DVD_TextStringType enumeration.

There are two basic types of text strings: structure identifiers and content strings. Types with a value of 0x01 through 0x20 are structure identifiers. They are empty strings; the numerical code is used to identify the logical structure to which any following content strings belong. This structure corresponds very closely to the logical structure of a DVD disc contents: volume, title, chapter, and so on. The remaining types identify content strings that hold information that may be displayed to the viewer in a user interface. The exact way in which content strings are used is not closely defined, so DVD authors can use them in various ways.

Historically, DVD text strings have been used almost exclusively on karaoke discs, and these discs mostly use the 0x01 and 0x02 structure identifiers and the 0x30 type content string. But it is reasonable to assume that, as time goes by, more types of DVD-Video discs will contain text strings and these strings will be organized in more complex ways to provide fuller descriptions of disc contents.

For information on DVD text strings, see the DVD Forum's Web site.

The CDvdCore::GetDvdText method in the DVDSample application demonstrates the basic steps in enumerating and displaying DVD text strings.


Playing Karaoke Audio Streams

The DVD Navigator can play DVD-Video discs with karaoke audio streams, but karaoke playback also requires a decoder that supports multichannel karaoke mixing. Specifically, the decoder must support the DVD Karaoke Property Set (AM_PROPERTY_DVDKARAOKE).

Karaoke discs are a type of DVD-Video disc and have the same navigation structure. Songs are generally formatted as titles, and titles can be grouped into title sets based on performer, musical style, or other criteria. The main difference between karaoke and other types of DVD-Videos is the audio stream. Karaoke discs all contain multichannel audio, usually Dolby AC-3. Channels 0 and 1 always contain the background instrumental music, while channels 2 through 5 can each contain any combination of guide vocals, guide melodies, and sound effects. A karaoke application can control the volume and destination speaker for each auxiliary channel.

When the DVD Navigator detects karaoke content on a disc and goes into karaoke mode, it informs the decoder, which then should mute the upper three channels (the auxiliary channels) until any or all of them are explicitly turned on by an application. The basic tasks of a karaoke application are to:

  1. Determine the number of auxiliary channels and their contents using IDvdInfo2 methods.
  2. Provide a user interface that displays the channel contents and enables users to turn any auxiliary channel on or off at any time, using IDvdControl2::SelectKaraokeAudioPresentationMode.

These steps are illustrated in the DVD Sample application in DVDCore.cpp in the GetAudioAttributes method.


Synchronizing DVD Commands

This section contains the following subtopics.

  • About Command Synchronization
  • Approach 1: No Synchronization
  • Approach 2: Simple Blocking Without Synchronization
  • Approach 3: Using Only the Synchronization Object
  • Approach 4: Synchronization of One Command at a Time Using Events
  • Approach 5: Synchronization Using Events and IDvdCmd Objects

About Command Synchronization

Command synchronization is an advanced topic for developers who are familiar with the DVD Navigator and DVD navigation issues in general, and whose application requires the sophisticated functionality that command synchronization provides. If you are just starting out with the DVD Navigator, or if your application does not require command synchronization, simply use the various play commands as illustrated in Approach #1. You can always incorporate command synchronization later.

The various playback methods in IDvdControl2—for example, PlayTitle—are asynchronous in nature. When the method is called, it immediately returns a result before it has carried out all the necessary steps. During the period between the successful return of the method call and the ultimate completion of the operation, other commands might be issued that put the DVD Navigator into a new DVD domain or new filter state that prevents the method from successfully completing all the necessary steps. For example, assume your application calls PlayTitle, and immediately afterward, the user clicks the Stop button. If the commands are not synchronized, the DVD Navigator can enter the DVD Stop domain before the disc begins playing at the specified location. This is because PlayTitle returns successfully before the entire operation is carried out. When the disc finally begins to play, the DVD Navigator is no longer in the correct state, and an error will result.

Because many method calls depend on the DVD Navigator being in a particular state, applications need a way to synchronize commands. This involves the following two basic capabilities.

  • Knowing when an asynchronous operation is actually finished and what the final result is, as distinct from the return value of the method call, which only indicates whether an operation successfully started.
  • Being able to block the DVD Navigator from processing subsequent commands until an operation is completed.

The DVD Navigator gives applications these capabilities, along with several options for synchronizing commands. Each playback method in IDvdControl2 has two parameters used for synchronization: an interface pointer to a synchronization object, and a set of DVD command flags. An application can use these parameters to implement command synchronization in various ways depending on its needs.

Approach 1: No Synchronization

To maintain the asynchronous nature of the method call, use the following syntax, where pDVDControl2 is an IDvdControl2 pointer.

HRESULT hr = pDVDControl2->PlayTitle( uTitle,
                                      DVD_CMD_FLAG_None, // = 0
                                      NULL);

Approach 2: Simple Blocking Without Synchronization

This approach uses the DVD command flags to implement simple blocking without managing command synchronization objects. This is the simplest way to synchronize commands, because you do not have to manage synchronization objects or handle event notifications, but it does not enable you to determine the return status of any particular command.

HRESULT hr = pDVDControl2->PlayTitle( uTitle,
                                      EC_DVD_CMD_FLAG_Block,
                                      NULL);

Approach 3: Using Only the Synchronization Object

This approach is functionally equivalent to Approach 2. It provides another way to block the DVD Navigator directly without processing event notifications. When an application passes the address of an IDvdCmd pointer, it receives a command synchronization object that is associated with this specific command. Calling the object's WaitToEnd function will block the DVD Navigator until the method successfully completes. In the meantime, new commands might be added to the queue. Be sure to release the object when you are done with it.

IDvdCmd* pObj;
HRESULT hr = pDVDControl2->PlayTitle(uTitle,  0, &pObj);
if(SUCCEEDED(hr))
{
    pObj->WaitToEnd();
    pObj->Release();
}

Approach 4: Synchronization of One Command at a Time Using Events

By specifying the DVD_CMD_FLAG_SendEvents flag in the dwFlags parameter of the various "play" method calls(PlayChapter, PlayAtTimeInTitle, and so on), the DVD Navigator will not block on the method call. Instead, it sends your application EC_DVD_CMD_START and EC_DVD_CMD_END (see DVD Event Notification Codes) event notifications when the command begins and then when its entire asynchronous operation completes. This enables you to synchronize single events without managing IDvdCmd objects. By not using IDvdCmd objects, you cannot know for sure which command the event is associated with. For many situations, such information is probably not needed anyway, so this approach is sufficient in those cases.

// Call PlayChapterInTitle using "SendEvents".
HRESULT hr = pDVDControl2->PlayChapterInTitle( uTitle, 0x2,
                    DVD_CMD_FLAG_SendEvents, NULL);
...

// In the event notification handler function
switch (lEvent)
{
   case EC_DVD_CMD_END:
       DoSomething();
       break;
}

Approach 5: Synchronization Using Events and IDvdCmd Objects

This approach provides the greatest control over command synchronization, but it is also the most complex to implement. It enables applications to know which command an event is associated with, so that the application can tailor its responses to the EC_DVD_CMD_END events. The first example shows a single-threaded solution, and the second example shows a multithreaded solution.

// Global variable.
IDvdCmd *pGlobalObj = 0;
...

// The navigator assigns pGlobalObj before the event is issued.
// Otherwise, the event could occur while pGlobalObj is still NULL.
HRESULT hr = pDVDControl2->PlayTitle( uTitle,
DVD_CMD_FLAG_SendEvents, &pGlobalObj );
if(FAILED(hr))
{
    pGlobalObj = NULL;
}
...

// In your event handling code:
switch (lEvent)
{
case EC_DVD_CMD_END:
   {
       IDvdCmd* pObj = GetDvdCmd(lParam1);
       HRESULT hr = (HRESULT)lParam2;
       if (pObj != NULL)
       {
           if (pGlobalObj == pObj)
           {
               ...
               pGlobalObj->Release();
               pGlobalObj = NULL;
           }
           pObj->Release();
       }
    }
    break;

} // switch

When your event loop is on a separate thread, use the following approach:

// In global code
IDvdCmd *pGlobalObj=0;
CCritSec globalCritSect;
...

{ // Scope for lock
    CAutoLock(globalCritSect);
    HRESULT hr = pDVDControl2->PlayTitle(uTitle,
DVD_CMD_FLAG_SendEvents, &pGlobalObj);
    if (FAILED(hr))
    {
        pGlobalObj = NULL;
    }
}
...

// In your event handling code:
switch (lEvent)
{
case EC_DVD_CMD_COMPLETE:
// Fall through.
case EC_DVD_CMD_CANCEL:
    {
        CAutoLock(globalCritSect);

        IDvdCmd *pObj = GetDvdCmd(lParam1);
        HRESULT hr = (HRESULT)lParam2;
        if (pObj != NULL)
        {
            if (pGlobalObj == obj)
            {
                ...
                pGlobalObj->Release();
                pGlobalObj = NULL;
            }
            pObj->Release();
        }
    }
    break;
} // switch

The CCritSec and CAutoLock classes are defined in the DirectShow base-class library.


DVD Command Flags

The DVD command flags passed in the dwFlags parameter of SetOption are used either in addition to or in place of the synchronization object, depending on which approach you are using for the particular method call. The use of DVD_CMD_FLAG_Block was shown in Approach 2 and DVD_CMD_FLAG_SendEvents was illustrated in Approaches 4 through 6. Either of these flags can also be combined in a bitwise OR with another flag, DVD_CMD_FLAG_Flush. This flag causes the method to be executed immediately, without waiting for the one or two seconds of video in the filter graph's buffers to play. Specifying this flag results in a faster response time to user input. Do not use this flag if you need to ensure that a particular video segment finishes completely before the next command is issued. The four flags and their meanings are summarized in the following table.

Name | Numeric value | Meaning
DVD_CMD_FLAG_None | 0x00000000 | No flags, meaning the buffer is not flushed before the new command, no events are fired when the operation completes, and the DVD Navigator is not blocked after the method returns.
DVD_CMD_FLAG_Flush | 0x00000001 | Empty the buffers and immediately start play at the new location.
DVD_CMD_FLAG_SendEvents | 0x00000002 | Tells the DVD navigator to signal the completion of asynchronous operations and their return value by sending events back to the application.
DVD_CMD_FLAG_Block | 0x00000004 | Blocks the DVD Navigator until the asynchronous operation completes or is canceled.


Handling Disc Ejections

When the user ejects a DVD from the drive, the DVD Navigator sends your application an EC_DVD_DISC_EJECTED message. The application can safely ignore this message and let the DVD Navigator manage the graph's state. An application can also handle the EC_DVD_DISC_EJECTED method to implement custom behavior when a disc is ejected. If you handle the message, you must set the DVD_ResetOnStop flag to TRUE with the SetOption method and then call IMediaControl::Stop before closing the application or playing another disc.


Shortcuts to C++ DVD Reference Pages

The following interfaces are those typically used when writing a DVD application in C++.

Interface | Purpose
IAMLine21Decoder | Controls closed captioning display.
IDvdCmd | Used in advanced command synchronization techniques to control a command object.
IDvdControl2 | Issues commands to the DVD Navigator filter (the "set" methods).
IDvdGraphBuilder | Creates the DVD filter graph.
IDvdInfo2 | Queries the DVD Navigator for state information and information on the disc (the "get" methods).
IDvdState | Saves information, such as bookmarks, to disc.
IVideoFrameStep | Controls "frame stepping" if the decoder supports it.


Writing a Script-Based DVD Application

This article describes the basic tasks involved in writing a script-based DVD application using the MSWebDVD ActiveX® Control. Developers targeting Microsoft® Windows® 2000 and earlier platforms should use this control. Developers targeting Windows XP should use the Video Control. For background information on the DVD navigation concepts discussed here, see DVD Basics.

  • Embedding the MSWebDVD Object
  • Enabling Users to Issue DVD Commands
  • Working With DVD Menus
  • Audio and Subpicture Streams
  • Enforcing Parental Management Levels
  • Saving and Restoring Bookmarks
  • Handling DVD Event Notifications
  • Handling UOP Event Notifications
  • Synchronizing HTML Content with the Video
  • Working with LCIDs
  • Playing Karaoke Discs
  • Working with DVD Text Strings


Embedding the MSWebDVD Object

In a Web Page: The MSWebDVD object handles all the DVD navigation commands as well as the display of the video rectangle. It will appear on your Web page as the video display rectangle. Therefore, you must embed it within the HTML document's BODY element. Set the rectangle width and height, and the default values for any properties as required by your application.

<OBJECT CLASSID=clsid:38EE5CEE-4B62-11D3-854F-00A0C9C898E7 ID=DVD
    STYLE="height:369px; width:740px">
<PARAM NAME="BackColor" VALUE="1048592">
<PARAM NAME="EnableResetOnStop" VALUE="-1">
<PARAM NAME="ColorKey" VALUE="1048592">
</OBJECT>

In a Microsoft® PowerPoint® presentation: Use the Control Toolbox palette, choose the "Insert Object" icon, insert the MSWebDVD control, then drag to size. (Scripting must be done in Visual Basic Scripting Edition®.)


Enabling Users to Issue DVD Commands

To enable users to control the DVD player, you need to provide a UI with buttons for issuing DVD commands such as "Stop" and "Play." The following code example shows how to hook up basic HTML buttons to the MSWebDVD object methods.

<INPUT ID=button1 NAME="button1" TYPE=button VALUE="Play" onClick='Play();'>
<INPUT ID=button2 NAME="button2" TYPE=button VALUE="Pause" onClick='Pause();'>

<SCRIPT LANGUAGE="JScript">
function Play(){
     DVD.Play();
}

function Pause(){
  DVD.Pause();
}

</SCRIPT>


Working With DVD Menus

MSWebDVD automatically handles menu commands when the user clicks on the on-screen buttons with the mouse. An application does not need to do anything to implement basic mouse support. But an application can override this automatic mouse handling at any time in order to cause additional actions to take place when a user clicks on a menu button. For example, you could cause certain text or images to be displayed on the Web page depending on which button the user clicks. To implement custom mouse handling, use the MSWebDVD menu-related methods such as SelectAndActivateButton, GetButtonAtPosition, and so on. To completely disable automatic mouse handling, set the DisableAutoMouseProcessing property to true.

MSWebDVD also offers a set of methods (for example, SelectUpperButton) which allow you to display an image map on your Web page representing a DVD remote control, with buttons that move the current menu selection up, down, right and left. These buttons are referred to as "directional" or "relative" buttons in the documentation. Unlike the buttons that appear within the DVD menus, the directional buttons are supplied by an application.


Audio and Subpicture Streams

A DVD-Video disc can have up to eight audio streams, numbered zero through seven, each with up to six discrete channels. Only one of these streams can be active at any given time. For subpictures, up to 32 streams are available, numbered 0 through 31, although for audio only one stream can be active at any given time. Discs are generally authored with default audio and subpicture streams, but an application can enable the user to see all the streams that are available for a given title, and select the one in the language they prefer. The basic steps in this process are the same for both audio and subpicture streams:

  1. Determine the number of streams available for a specified title.
  2. Iterate through the streams and retrieve the stream attributes for each.
  3. Retrieve the language code from the returned locale identifier (LCID) and create a human-readable string.
  4. Populate a "Select" box or other user interface control to enable the user to select the preferred stream.

(Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.)


Enforcing Parental Management Levels

Any title or portion of a title on a DVD-Video disc can be assigned a generic parental management level (PML) from 1 through 8. Eight is the most restrictive level and one is the least restrictive. The idea is to provide a mechanism to prevent children from watching adult content without parental consent, but the specific meaning of each level varies from country/region to country/region. In the United States and Canada, the levels map to the rating system of the Motion Picture Association of America (G, PG, PG-13, NC-17), but this is not the case in other countries or regions. A DVD application intended for an international market should not hard code any particular rating system into its parental management logic.

The MSWebDVD object by default ignores PMLs on the disc. For an application to be notified of PML markers on the disc, it must call NotifyParentalLevels(true). MSWebDVD will then inform your application when it encounters PML information on the disc. To enforce PMLs, your application must implement some form of password control logic that associates users with levels, and respond to EC_DVD_PARENTAL_LEVEL_CHANGE events to allow or disallow access as appropriate.


Saving and Restoring Bookmarks

Bookmarks are an internal data structure that the MSWebDVD object uses to create a snapshot of the current user session, including information such as the current location on the disc, the parental level of the person who was viewing at the time, the selected audio and subpicture streams, and so on. This means that users can save their place on a DVD-Video disc and come back to watch it at a later time.

The SaveBookmark method enables a user to save their place on a disc and the RestoreBookmark method enables the same user to begin viewing again from the stored location.

Only one bookmark can be stored at a time. Calling SaveBookmark twice will cause the first bookmark to be overwritten. Bookmarks are specific to a computer. Running the same HTML page on a different computer and calling RestoreBookmark will restore the last-saved bookmark on that computer or will return an error if no bookmark was previously saved.


Handling DVD Event Notifications

The MSWebDVD object sends notifications to an application-specified method when certain events take place, such as when the DVD domain changes, when a new parental management level is encountered, when it is about to enter an angle block, and so on. The event parameters can contain additional information related to the event. Error messages and warnings are also sent in this way. To capture the various DVD event notifications, enter the following HTML SCRIPT tag below the OBJECT tag for the MSWebDVD object.

<SCRIPT LANGUAGE="JScript" FOR=DVD EVENT="DVDNotify(EventCode, Param1, Param2)">
    ProcessDVDEvent(EventCode, Param1, Param2)
</SCRIPT>

Then, in script, define the event codes and the ProcessDVDEvent function, as shown in the next code example. (You may give your event handling function any name; it isn't required to be "ProcessEvents." For more information about the event codes, see DVD Event Notification Codes.

<SCRIPT LANGUAGE="JScript">

// DVD event codes are valued 257 through 283
var EC_DVDBASE = 256;

var EC_DVD_DOMAIN_CHANGE = (EC_DVDBASE + 1);
var EC_DVD_TITLE_CHANGE = (EC_DVDBASE + 2);
var EC_DVD_CHAPTER_START = (EC_DVDBASE + 3);
var EC_DVD_AUDIO_STREAM_CHANGE = (EC_DVDBASE + 4);
var EC_DVD_SUBPICTURE_STREAM_CHANGE = (EC_DVDBASE + 5);
var EC_DVD_ANGLE_CHANGE  = (EC_DVDBASE + 6);
var EC_DVD_BUTTON_CHANGE = (EC_DVDBASE + 7);
var EC_DVD_VALID_UOPS_CHANGE = (EC_DVDBASE + 8);
var EC_DVD_STILL_ON  = (EC_DVDBASE + 9);
var EC_DVD_STILL_OFF  = (EC_DVDBASE + 10);
var EC_DVD_CURRENT_TIME  = (EC_DVDBASE + 11); // not used by MSWebDVD
var EC_DVD_ERROR  = (EC_DVDBASE + 12);
var EC_DVD_WARNING  = (EC_DVDBASE + 13);
var EC_DVD_CHAPTER_AUTOSTOP  = (EC_DVDBASE + 14);
var EC_DVD_NO_FP_PGC  = (EC_DVDBASE + 15);
var EC_DVD_PLAYBACK_RATE_CHANGE  = (EC_DVDBASE + 16);
var EC_DVD_PARENTAL_LEVEL_CHANGE  = (EC_DVDBASE + 17);
var EC_DVD_PLAYBACK_STOPPED  = (EC_DVDBASE + 18);
var EC_DVD_ANGLES_AVAILABLE  = (EC_DVDBASE + 19);
var EC_DVD_PLAYPERIOD_AUTOSTOP  = (EC_DVDBASE + 20);
var EC_DVD_BUTTON_AUTO_ACTIVATED  = (EC_DVDBASE + 21);
var EC_DVD_CMD_START  = (EC_DVDBASE + 22);            // not used by MSWebDVD
var EC_DVD_CMD_END = (EC_DVDBASE + 23);               // not used by MSWebDVD
var EC_DVD_DISC_EJECTED  = (EC_DVDBASE + 24);
var EC_DVD_DISC_INSERTED  = (EC_DVDBASE + 25);
var EC_DVD_CURRENT_HMSF_TIME  = (EC_DVDBASE + 26);
var EC_DVD_KARAOKE_MODE  = (EC_DVDBASE + 27);

var nCurDomain;
var nCurParentalLevel;

function ProcessDVDEvent(EventCode, Param1, Param2)
{
    switch (EventCode)
    {
    case EC_DVD_DOMAIN_CHANGE:
        nCurDomain = Param1;
        // do something
        break;
    case EC_DVD_PARENTAL_LEVEL_CHANGE:
        nCurParentalLevel = Param1;
        // do something
        break;

    // handle any other events you are interested in

    default:
        break;
    }
}
</SCRIPT>


Handling UOP Event Notifications

The MSWebDVD object sends UOP event notifications to inform an application when a specific user operation (UOP) has been enabled or disabled by the disc. Each user operation has its own event, with a single Boolean parameter indicating whether that operation is now enabled or disabled. See MSWebDVD Events for more information on specific events.

For each event that you wish to handle, specify an event handler as shown in the following example. (You can call your handler method anything you like.)

<SCRIPT LANGUAGE="JScript" FOR=DVD EVENT="PlayForwards(bEnabled)">
    PlayForwardsEventHandler(bEnabled)
</SCRIPT>

Now define your handler method to respond appropriately to the event. Assume that the "button_Play" variable here is the id attribute of the "Play" button in your application.

function PlayForwardsEventHander(bEnabled)
{
  if(bEnabled == true)
    button_Play.disabled = false;
  else
    button_Play.disabled = true;
}


Synchronizing HTML Content with the Video

By handling timecode events from the disc, a Web application can synchronize HTML content to the video. For example, you can cause images or text on the page to change at specified points in the video. The following code snippet shows one way to synchronize JScript function calls to timecode events:

//DVDTriggerPoints array holds frame count for each trigger. Must be in ascending order.
//Use timecode2frames() to convert timecodes (hh:mm:ss:ff) to total number of frames.

var DVDTriggerPoints = new Array(
  timecode2frames("01:15:24:00"),
  timecode2frames("01:23:02:00"));

//DVDTriggerProcs array holds functions to be called at each trigger point defined in DVDTimePoints.
var DVDTriggerProcs = new Array(
  "showDogPic();",
  "showCatPic();");

//DVDTriggerIndex keeps track of current trigger (it indexes DVDTriggerPoints and DVDTriggerProcs).
var DVDTriggerIndex = 0;

//Handle DVD Events
function ProcessDVDEvent(EventCode, Param1, Param2) {
  switch (EventCode) {
     case EC_DVD_CURRENT_HMSF_TIME:
          if(MSWebDVD.CurrentDomain == 4) {  //Don't bother checking unless disc is playing.
             if (DVDTriggerIndex < DVDTimePoints.length) {  //Are there trigger points left to check?
                currentDVDTime = (MSWebDVD.DVDTimeCode2bstr(Param1));
                 if (timecode2frames(currentDVDTime)>= DVDTriggerPoints[DVDTimeIndex]) {
                     // if trigger point has passed, execute the associated function
                    eval(DVDTriggerProcs[DVDTimeIndex++]);
                 }
             }
          }
       break;

       // handle other events
   }
}

function timecode2frames(timeCode) {

   if (timeCode != "undefined") {
       return timeCode.substring(0,2)*108000
       + timeCode.substring(3,5)*1800
       + timeCode.substring(6,8)*30
       + timeCode.substring(9,11);
   } else {
       return 0;
   }
}


Working with LCIDs

The LCID, or "locale identifer," is a 32-bit data type into which are packed several different values that help to identify a particular geographical region. One of these internal values is the "primary language ID" which identifies the basic language of the region or locale, such as English, Spanish, or Russian.

MSWebDVD requires a complete valid LCID as an input parameter for two methods: SelectDefaultAudioLanguage and SelectDefaultSubpictureLanguage. This can be any valid LCID recognized by Windows®, and even some that are not recognized by Windows. (It is not necessary that the host system actually support the locale with fonts, keyboard mappings, and so on.) The following table lists some common LCIDs as well as well as some less common ones that are valid for MSWebDVD even through Windows does not recognize them by default. This is not a complete list of all possible LCIDs.

Some Valid LCIDs

Afrikaans | 0x0436 | Albanian | 0x041c | Arabic (Algeria) | 0x1401
Arabic (Bahrain) | 0x3c01 | Arabic (Egypt) | 0x0c01 | Arabic (Iraq) | 0x0801
Arabic (Jordan) | 0x2c01 | Arabic (Kuwait) | 0x3401 | Arabic (Lebanon) | 0x3001
Arabic (Libya) | 0x1001 | Arabic (Morocco) | 0x1801 | Arabic (Oman) | 0x2001
Arabic (Qatar) | 0x4001 | Arabic (Saudi Arabia) | 0x0401 | Arabic (Syria) | 0x2801
Arabic (Tunisia) | 0x1c01 | Arabic (U.A.E.) | 0x3801 | Arabic (Yemen) | 0x2401
Basque | 0x042d | Belarusian | 0x0423 | Bulgarian | 0x0402
Catalan | 0x0403 | Chinese (Hong Kong SAR) | 0x0c04 | Chinese (PRC) | 0x0804
Chinese (Singapore) | 0x1004 | Chinese (Taiwan) | 0x0404 | Croatian | 0x041a
Czech | 0x0405 | Danish | 0x0406 | Dutch (Belgian) | 0x0813
Dutch (Standard) | 0x0413 | English (Australian) | 0x0c09 | English (Belize) | 0x2809
English (Canadian) | 0x1009 | English (Caribbean) | 0x2409 | English (Ireland) | 0x1809
English (Jamaica) | 0x2009 | English (New Zealand) | 0x1409 | English (South Africa) | 0x1c09
English (Trinidad) | 0x2c09 | English (United Kingdom) | 0x0809 | English (United States) | 0x0409
Estonian | 0x0425 | Faeroese | 0x0438 | Farsi | 0x0429
Finnish | 0x040b | French (Belgian) | 0x080c | French (Canadian) | 0x0c0c
French (Luxembourg) | 0x140c | French (Standard) | 0x040c | French (Swiss) | 0x100c
German (Austrian) | 0x0c07 | German (Liechtenstein) | 0x1407 | German (Luxembourg) | 0x1007
German (Standard) | 0x0407 | German (Swiss) | 0x0807 | Greek | 0x0408
Hebrew | 0x040d | Hungarian | 0x040e | Icelandic | 0x040f
Indonesian | 0x0421 | Italian (Standard) | 0x0410 | Italian (Swiss) | 0x0810
Japanese | 0x0411 | Korean | 0x0412 | Korean (Johab) | 0x0812
Latvian | 0x0426 | Lithuanian | 0x0427 | Malay (Malaysian) | 0x043e
Malay (Brunei) | 0x083e | Norwegian (Bokmal) | 0x0414 | Norwegian (Nynorsk) | 0x0814
Polish | 0x0415 | Portuguese (Brazil) | 0x0416 | Portuguese (Portugal) | 0x0816
Romanian | 0x0418 | Russian | 0x0419 | Serbian (Cyrillic) | 0x0c1a
Serbian (Latin) | 0x081a | Slovak | 0x041b | Slovenian | 0x0424
Spanish (Argentina) | 0x2c0a | Spanish (Bolivia) | 0x400a | Spanish (Chile) | 0x340a
Spanish (Colombia) | 0x240a | Spanish (Costa Rica) | 0x140a | Spanish (Dominican Republic) | 0x1c0a
Spanish (Ecuador) | 0x300a | Spanish (El Salvador) | 0x440a | Spanish (Guatemala) | 0x100a
Spanish (Honduras) | 0x480a | Spanish (Mexican) | 0x080a | Spanish (Modern Sort) | 0x0c0a
Spanish (Nicaragua) | 0x4c0a | Spanish (Panama) | 0x180a | Spanish (Paraguay) | 0x3c0a
Spanish (Peru) | 0x280a | Spanish (Puerto Rico) | 0x500a | Spanish (Traditional Sort) | 0x040a
Spanish (Uruguay) | 0x380a | Spanish (Venezuela) | 0x200a | Swahili | 0x0441
Swedish | 0x041d | Swedish (Finland) | 0x081d | Thai | 0x041e
Turkish | 0x041f | Ukrainian | 0x0422 |  |

Several MSWebDVD methods and properties return locale identifier (LCID) values that identify which languages are available on the soundtracks or subtitles. To make use of this information, your application will need to extract the primary language ID from the returned LCID. To do this, perform a bitwise AND operation on the value of iLCID and 0x3FF. (The primary language ID is contained in the least significant 10 bits of the LCID.) The following code snippet shows how to do this.

iPrimaryLang = iLCID & 0x3FF;

To obtain a human-readable string from the primary language ID, call GetLangFromLangID as shown in this example:

sLanguage = DVD.GetLangFromLangID(iPrimaryLang);

See the Microsoft® Platform SDK for more information on LCIDs and language identifiers.

The following table lists the primary language IDs for the LCIDs in the table above.

Some Valid Primary Language IDs

Afrikaans | 0x36 | Albanian | 0x1c | Arabic | 0x01 | Basque | 0x2d
Belarusian | 0x23 | Bulgarian | 0x02 | Catalan | 0x03 | Chinese | 0x04
Croatian | 0x1a | Czech | 0x05 | Danish | 0x06 | Dutch | 0x13
English | 0x09 | Estonian | 0x25 | Faeroese | 0x38 | Farsi | 0x29
Finnish | 0x0b | French | 0x0c | German | 0x07 | Greek | 0x08
Hebrew | 0x0d | Hungarian | 0x0e | Icelandic | 0x0f | Indonesian | 0x21
Italian | 0x10 | Japanese | 0x11 | Korean | 0x12 | Latvian | 0x26
Lithuanian | 0x27 | Malay | 0x3e | Norwegian | 0x14 | Polish | 0x15
Portuguese | 0x16 | Romanian | 0x18 | Russian | 0x19 | Serbian | 0x1a
Slovak | 0x1b | Slovenian | 0x24 | Spanish | 0x0a | Swahili | 0x41
Swedish | 0x1d | Thai | 0x1e | Turkish | 0x1f | Ukrainian | 0x22


Playing Karaoke Discs

Karaoke discs are a type of DVD-Video disc and have the same navigation structure. Songs are generally formatted as titles, and titles can be grouped together into title sets based on performer, musical style, or other criteria. The main difference between karaoke and other types of DVD-Videos is the audio stream. Karaoke discs all contain multichannel audio, usually Dolby AC-3. Channels 0 and 1 always contain the background instrumental music, while channels 2 through 5 contain guide vocals or guide melodies or sound effects. A karaoke application can control the volume and destination speaker for each auxiliary channel.

Karaoke playback also requires an audio decoder that supports the multichannel karaoke mixing information sent by the DVD Navigator. Specifically, the decoder must support the DVD Karaoke Property Set (AM_PROPERTY_DVDKARAOKE).

When the DVD Navigator detects karaoke content on a disc and goes into karaoke mode, it informs the decoder, which then should mute the upper three channels (the auxiliary channels) until any or all of them are explicitly turned on by an application. The basic tasks of a karaoke application will therefore be to

  1. determine the number of auxiliary channels and their contents
  2. provide a user interface that displays the channel contents and allows users to turn any auxiliary channel on or off at any time.


Working with DVD Text Strings

DVD discs, especially karaoke discs, might contain a database of text information to supplement the video or audio content. Such text on karaoke discs might include song titles, artist names, record labels, and so on. Versions of this text can be present in more than one language. These strings are optional; discs are not required to have them. If present they are organized in a way that closely mirrors the logical hierarchy of the DVD volume. Each string is preceded by a number that identifies what part of the disc structure it belongs to or gives some clue as to the content of the string.

There are two basic types of text strings: structure identifiers and content strings. Types with a value of 0x01 through 0x20 are structure identifiers. They are empty strings; the numerical code is used to identify the logical structure to which any following content strings belong. This structure corresponds very closely to the logical structure of a DVD disc contents: volume, title, chapter, and so on. The remaining types identify content strings that hold information that may be displayed to the viewer in a user interface. The exact way in which content strings are used is not closely defined, so DVD authors might use them in various ways.

Historically, DVD text strings have been used almost exclusively on karaoke discs, and these discs mostly use the 0x01 and 0x02 structure identifiers and the 0x30 type content string. But it is reasonable to assume that as time goes by, (1) more types of DVD-Video discs will contain text strings and (2) these strings will be organized in more complex ways in order to provide fuller descriptions of disc contents.

The following code shows how to determine the number of text string language blocks on the disc, and retrieve the human-readable string(s) that could be shown to the user to allow them to choose the language they are interested in. In this code the strings are added to an HTML SELECT element called "TextLanguageList." For more information on LCIDs and primary language IDs, see GetLangFromLangID

  function GetTextLanguages()
  {
    //get the number of text blocks
    var numLangs = DVD.GetDVDTextNumberOfLanguages();
      var iLCID;
      var iPrimaryLang;
      var sLanguage;
      var oOption;

    for (j = 0; j < numLangs; j++)
    {
    //get the locale identifier for the language block
        iLCID = DVD.GetDVDTextLanguageLCID(j);

    //get the primary language ID from the LCID
        iPrimaryLang = iLCID & 0x3FF;

    //get the human-readable string from the primary language ID
        sLanguage = DVD.GetLangFromLangID(iPrimaryLang);

    //add it to the SELECT element on the HTML page
        oOption = document.createElement("OPTION");
        oOption.text = sLanguage;
        document.all.TextLanguageList.add(oOption);
    }

  } //end function GetTextStrings

The following test code demonstrates how to enumerate the strings and examine the text string type. It just dumps the results into an HTML TEXTAREA element called "myTextArea" so you can see how the numeric string types are used to organize the content strings. A real application would probably create its own data structure to hold the strings, or else would display them in a more useful way for the viewer.

  // iLanguage is the 0-based index for the language block
   function GetTextStrings(iLanguage)
   {

      var numStrings, stringType, j;

      numStrings = DVD.GetDVDTextNumberOfStrings(iLanguage);

      for( j = 0; j < numStrings; j++)
      {
        stringType = DVD.GetDVDTextStringType(iLanguage, j);

        if(stringType > 0x20) //there is actually some text to read here
        {
          myTextArea.value += (stringType + ": " + DVD.GetDVDTextString(iLanguage, j) + "\n");
        }
        else // It's a node indicating what level of the volume structure
            // the following strings will apply to
        {
          myTextArea.value += (stringType + "\n");
        }

      }
    } //end function GetTextStrings

DVD Text String Types

This table lists a subset of the DVD text string types. All types with a value 0x20 and below are empty strings that merely indicate the node level in the disc's content data structure. The other strings are content strings. Most title and song names are type 0x30. The types in the Title, SubTitle and Original categories help to further identify the particular genre. The exact meaning and intended use of these categories is defined in a public document that can be downloaded from the DVD Forum's Web site.

Structure Identifiers

Volume | 0x01 | Indicates that the strings that follow pertain to the DVD volume.
Title | 0x02 | Indicates that the strings that follow pertain to a title.
ParentalID | 0x03 | Indicates that the strings that follow pertain to a particular parental ID.
Chapter | 0x04 | Indicates that the strings that follow pertain to a chapter.
Cell | 0x05 | Indicates that the strings that follow pertain to a cell (typically consisting of one scene from a movie).

Stream Identifiers

Audio | 0x10 | Indicates that the strings that follow pertain to an audio stream.
Subpicture | 0x11 | Indicates that the strings that follow pertain to a subpicture stream.
Angle | 0x12 | Indicates that the strings that follow pertain to an angle block.

Audio Channel Identifiers

Channel 0x20 Indicates that the strings that follow pertain to one channel in an audio stream.

General Content Strings

Name | 0x30 | The most common identifer for title names, chapter names, song names, and so on
Comments | 0x31 | General comments about the title, chapter, song, and so on

Title Content Strings

Series | 0x38 | Additional information about the title, chapter, song, and so on
Movie | 0x39 | Additional information about the title or chapter if this is a movie.
Video | 0x3a | Additional information about the title or chapter if this is a video.
Album | 0x3b | Additional information about the title or chapter if this is an album.
Song | 0x3c | Additional information about the title or chapter if this is a song.
Other | 0x3f | Additional information about the title or chapter if this belongs to some other genre or category.

Secondary Title Content Strings

Series | 0x40 | Additional information about the title, chapter, song, and so on
Movie | 0x41 | Additional information about the title or chapter if this is a movie.
Video | 0x42 | Additional information about the title or chapter if this is a video.
Album | 0x43 | Additional information about the title or chapter if this is an album.
Song | 0x44 | Additional information about the title or chapter if this is a song.
Other | 0x45 | Additional information about the title or chapter if this is this belongs to some other genre or category.

Original Content Strings

Series | 0x48 | Additional information about the title, chapter, song, and so on
Movie | 0x49 | Additional information about the title or chapter if this is a movie.
Video | 0x4a | Additional information about the title or chapter if this is a video.
Album | 0x4b | Additional information about the title or chapter if this is an album.
Song | 0x4c | Additional information about the title or chapter if this is a song.
Other | 0x4f | Additional information about the title or chapter if this is this belongs to some other genre or category.

Other Info Content Strings

Other Scene | 0x50 | Additional information about an alternate scene in a movie title or chapter.
Other Cut | 0x51 | Additional information about an alternate cut in a movie title or chapter.
Other Take | 0x52 | Additional information about an alternate take in a movie title or chapter.


MSWebDVD ActiveX Control

These pages document the methods and properties of objects exposed by the Microsoft® MSWebDVD ActiveX® control.

Object | Purpose
MSWebDVD | Controls all DVD commands and queries.
MSDVDAdm | Controls default settings in the Windows Registry.
DVDRect | Defines rectangles for use in various MSWebDVD methods.

MSWebDVD Events documents the event notifications sent to applications by the MSWebDVD Active X control.

When writing for Windows XP and later platforms, MSVidWebDVD object is the preferred DVD control object.


MPEG-2 Support in DirectShow

This section describes the components that you can use to play MPEG-2 content in DirectShow.

Note Although DVD video is based on MPEG-2, this section does not describe DVD playback or navigation. For information about DVD in DirectShow, see DVD Applications.

MPEG-2 data can come from a local file, or from a live source, such as a network broadcast or D-VHS device. File playback is called pull mode, because the parser filter pulls data from the file into the filter graph. Live sources are called push mode, because the source filter pushes data into the graph.

DirectShow provides two filters that can parse MPEG-2 system streams:

  • MPEG-2 Demultiplexer ("demux"): This filter supports push mode for program streams and transport streams. In Windows XP, it also supports pull mode for program streams.
  • MPEG-2 Splitter: This filter supports pull mode for program streams on downlevel platforms. This filter is deprecated in Windows XP.

DirectShow does not provide any MPEG-2 decoders or encoders. To use the MPEG-2 demux or MPEG-2 splitter, you must have DirectShow-compatible MPEG-2 audio and video decoders that accept packetized elementary streams (PES).

This section contains the following topics:

  • Overview of MPEG-2 Systems
  • Using the MPEG-2 Demultiplexer
  • Using the MPEG-2 Splitter
  • MPEG Sample Properties
  • Getting MPEG-2 PSI Tables

See Also

  • DSNetwork Filters Sample
  • PSI Parser Filter Sample


Overview of MPEG-2 Systems

This section gives a general, non-technical overview of the MPEG-2 Systems layer. MPEG-2 Systems is the standard that defines how audio and video streams are multiplexed in MPEG-2. For more information, see the Moving Picture Experts Group home page.

Elementary Streams

MPEG-2 multiplexing starts with one or more byte streams, called elementary streams (ES), that contain video, audio, or other data. For example, a video ES contains compressed video frames, plus sequence headers, group-of-picture (GOP) headers, and anything else needed by the decoder to decode the stream. The Systems layer does not define the contents of the ES byte stream.

An elementary stream is broken up into packets, forming a packetized elementary stream (PES). PES packets have variable length. The contents of the packet are called the payload. Each PES packet also includes a header. The multiplexer assigns a 1-byte stream ID to every PES; individual PES packets are identified by the stream ID in the packet header. For audio streams, the stream ID has the form 110xxxxx. For video, the stream ID has the form 1110yyyy.

The MPEG-2 standard defines two ways to deliver packetized elementary streams: program streams and transport streams.

Program Streams

Program streams are designed for environments that are relatively error-free, such as local file storage. In a program stream, the PES packets are multiplexed and organized into units called packs. All of the PES streams in a program stream are synchronized to the same clock.

Transport Streams

Transport streams (TS) are designed for unreliable or error-prone environments, such as network broadcasts. Also, they can contain multiple programs that are synchronized to different clocks. A transport stream adds a second layer of packetizing — the PES streams are packaged inside transport stream packets, which have a fixed size of 188 bytes per packet. TS packets can also contain program information streams, which are described in the following section.

Each TS packet has a 4-byte header, plus an optional adaptation field that contains additional header information. The multiplexer assigns a program ID (PID) to each PES stream or program information stream. The PIDs are used to identify the TS packets, similar to the way stream IDs identify PES packets. (If a transport stream contains multiple programs, the stream IDs might not be unique, but the PID assignments are unique within the transport stream.)

Program Specific Information

Because a transport stream can carry multiple programs, there must be a way to associate the various PES packets with the programs they belong to. This is accomplished using tables that identify the program streams. Collectively, this data is called Program Specific Information (PSI). The PSI data is carried in TS packets, just like the PES data. There are various types of PSI data, including:

  • Program Association Table (PAT). The PAT is always assigned to PID 0x000. Each entry in the PAT is a PID that identifies the PMT packets for that program (see next item).
  • Program Map Table (PMT). Each PMT defines one program. The PMT contains a list of streams; each table entry gives the PID for that stream, plus a code that identifies the stream type. ISO/IEC 13818-1 defines some standard stream types; an abbreviated list is shown in the following table.
    stream_type | Description
    0x01 | MPEG-1 video
    0x02 | MPEG-2 video
    0x03 | MPEG-1 audio
    0x04 | MPEG-2 audio
    0x80 - 0xFF | User private

    Other standards that are based on MPEG-2, such as ATSC, may define additional stream types in the "user private" range. For example, ATSC defines 0x81 as Dolby AC-3 audio.

  • Conditional Access Tables (CAT)
  • Network Identification Tables (NIT)

See Also

  • MPEG-2 Support in DirectShow


Using the MPEG-2 Demultiplexer

This section describes how to use the MPEG-2 Demultiplexer ("demux") filter. It contains the following topics:

  • MPEG-2 Demux Run-Time Modes
  • Configuring the Demux Output Pins
  • Using the Demux with Elementary Streams
  • Using the Demux with PSI Streams
  • Demux Clock Behavior

See Also

  • MPEG-2 Support in DirectShow


MPEG-2 Demux Run-Time Modes

The MPEG-2 Demultiplexer ("demux") can operate in push mode or pull mode. In push mode, the data comes from a live source, such as a network broadcast. In pull mode, the data comes from a local file.

  • Pull mode is available only in Windows XP, and only for program streams. On down-level platforms, use the MPEG-2 Splitter filter.
  • Push mode is available on all platforms, for both program streams and transport streams.

The demux therefore supports three possible modes: Program streams in pull mode, program streams in push mode, and transport streams in push mode. The demux determines which mode to use at run time. The mode is determined when the input pin connects, or when the first output pin is configured, whichever happens first:

  • When the input pin connects: On Windows XP, the demux queries the upstream filter for the IAsyncReader interface; if the upstream filter exposes that interface, the demux configures itself for program streams in pull mode. Otherwise, the demux uses push mode, and the media type determines the stream type (program stream or transport stream). See MPEG-2 Demultiplexer Media Types for a list of input types.
  • When the first output pin is configured: If you create an output pin and query it for IMPEG2PIDMap, the demux configures itself for transport streams in push mode. If you query the pin for IMPEG2StreamIdMap, the demux configures itself for program streams, also in push mode. Any subsequent queries for the other interface fail, because the demux cannot operate in two modes at once.

Once the demux has configured itself for a particular mode, it remains in that mode. To use a different mode, you must create a new instance of the demux.

See Also

  • Using the MPEG-2 Demultiplexer


Configuring the Demux Output Pins

When the MPEG-2 demux receives a packet of data, it must determine which output pin should parse and deliver the data. In program stream mode, the demux maps stream IDs to output pins. In transport stream mode, it maps PIDs to output pins. For example, in transport stream mode, if PID 0x31 is mapped to pin 0, then every TS packet with that PID number is routed to output pin 0. If the demux receives a packet whose stream ID or PID is not mapped to any output pin, it simply discards the packet.

In pull mode, the demux automatically creates output pins for the audio and video streams in the file, and maps the stream IDs to the pins.

In push mode, the output pins must be configured by the application or by another filter. For digital television sources using the Broadcast Driver Architecture (BDA), the network provider filter works with the TIF filter to configure the demux. The application does not have to do anything. In other scenarios, the application must configure the output pins.

The demux starts with no output pins. To create an output pin, call the IMpeg2Demultiplexer::CreateOutputPin method on the filter. This method takes a media type and a pin name, and returns an IPin pointer. The media type is used when the pin connects to another filter, typically a decoder — an example is given the section Using the Demux with Elementary Streams. The pin name can be anything you like, except that duplicate pin names are not allowed.

Next, assign one or more stream IDs or PIDs to the new output pin. For program streams, query the pin for IMPEG2StreamIdMap and call IMPEG2StreamIdMap::MapStreamId. For transport streams, query the pin for IMPEG2PIDMap and call IMPEG2PIDMap::MapPID.

There are several ways that the demux can parse TS packets. For each output pin, the parsing method is determined by the MediaSampleContent parameter to the MapPID method.

Value | Description
MEDIA_ELEMENTARY_STREAM | The filter delivers PES payloads. In this mode, the filter depacketizes the PES packets, so the downstream filter receives the ES byte stream, without the PES packet headers. (Audio and video streams only.)
MEDIA_MPEG2_PSI | The filter delivers complete PSI sections, such as PAT tables, PMT tables, CAT tables, and so forth.
MEDIA_TRANSPORT_PAYLOAD | The filter extracts the payloads from the TS packets and delivers them without further parsing. For elementary streams, this means the demux will deliver entire PES packets, including the PES packet headers.
MEDIA_TRANSPORT_PACKET | The filter delivers entire TS packets. The demux routes the TS packets according to their PIDs, but does not otherwise examine or process the packets. Packets with errors are not filtered out. The demux does not re-multiplex the packets, and the resulting output stream is not a compliant MPEG-2 transport stream. This mode is called pass through mode.

For program streams, the demux always delivers PES payloads.

See Also

  • Using the MPEG-2 Demultiplexer


Using the Demux with Elementary Streams

When the MPEG-2 demux delivers PES payloads, it sends the ES byte stream in batches of media samples. The default sample size is 8K. The demux starts a new media sample on each PES boundary, but may break a single PES payload into several samples. For example, if a PES payload is 20K, it will be delivered in two 8K samples followed by one 4K sample. The demux does not examine the contents of the byte stream. It is up to the decoder to parse the sequence headers and look for format changes.

When the demux filter's output pin connects to the decoder, it offers the media type that was specified when the pin was created. Because the demux does not examine the ES byte stream, it does not validate the media type. In theory, an MPEG-2 decoder should be able to connect with just the major type and subtype filled in, to indicate the type of data. The decoder should then examine the sequence headers that arrive in the media samples. However, in practice, many decoders will not connect unless the media type includes a complete format block.

For example, suppose that PID 0x31 contains MPEG-2 main profile video. At a minimum, you would need to do the following steps.

First, create a media type for MPEG-2 video. Leaving aside the format block for now:

AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE);
mt.majortype = MEDIATYPE_Video ;
mt.subtype = MEDIASUBTYPE_MPEG2_VIDEO;
// Possibly create a format block (not shown here).

Next, create an output pin on the demux:

// Query the demux filter for IMpeg2Demultiplexer.
IMpeg2Demultiplexer *pDemux;
hr = pFilter->QueryInterface(IID_IMpeg2Demultiplexer, (void**)&pDemux);
if (SUCCEEDED(hr))
{
    // Create a new output pin.
    IPin *pPin0;
    hr = pDemux->CreateOutputPin(&mt, L"Video Pin", &pPin0);
    if (SUCCEEDED(hr))
    {
        ....
    }
}

Then, query the new pin for the IMPEG2PIDMap interface and call MapPID. Specify PID number 0x30, and MEDIA_ELEMENTARY_STREAM for PES payloads.

// Query the pin for IMPEG2PIDMap. This implicitly configures the
// demux to carry a transport stream.
IMPEG2PIDMap *pPidMap;
hr = pPin0->QueryInterface(IID_IMPEG2PIDMap, (void**)&pPidMap);
if (SUCCEEDED(hr))
{
    // Assign PID 0x31 to pin 0. Set the type to "PES payload."
    ULONG Pid = 0x031;
    hr = pPidMap->MapPID(1, &Pid, MEDIA_ELEMENTARY_STREAM);
    pPidMap->Release();
}

Finally, release all interfaces when you are done:

pPin0->Release();
pDemux->Release();

Here is a more complete example of setting the media type, including the format block. This example still assumes an MPEG-2 main profile video. The details will vary depending on stream contents:

// Set up a byte array to hold the first sequence header.
// This may or may not be required, depending on the decoder.
BYTE SeqHdr[] = { ... };  // Contains the sequence header (not shown).

AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video ;
mt.subtype = MEDIASUBTYPE_MPEG2_VIDEO;
mt.formattype = FORMAT_MPEG2Video;

// Allocate the format block, including space for the sequence header.
mt.cbFormat = sizeof(MPEG2VIDEOINFO) + sizeof(SeqHdr);
mt.pbFormat = (BYTE*)CoTaskMemAlloc(mt.cbFormat);
if (mt.pbFormat == NULL)
{
    // Out of memory; return an error code.
}
ZeroMemory(mt.pbFormat, mt.cbFormat);

// Cast the buffer pointer to an MPEG2VIDEOINFO struct.
MPEG2VIDEOINFO *pMVIH = (MPEG2VIDEOINFO*)mt.pbFormat;

RECT rcSrc = {0, 480, 0, 720};        // Source rectangle.
pMVIH->hdr.rcSource = rcSrc;
pMVIH->hdr.dwBitRate = 4000000;       // Bit rate.
pMVIH->hdr.AvgTimePerFrame = 333667;  // 29.97 fps.
pMVIH->hdr.dwPictAspectRatioX = 4;    // 4:3 aspect ratio.
pMVIH->hdr.dwPictAspectRatioY = 3;

// BITMAPINFOHEADER information.
pMVIH->hdr.bmiHeader.biSize = 40;
pMVIH->hdr.bmiHeader.biWidth = 720;
pMVIH->hdr.bmiHeader.biHeight = 480;

pMVIH->dwLevel = AM_MPEG2Profile_Main;  // MPEG-2 profile.
pMVIH->dwProfile = AM_MPEG2Level_Main;  // MPEG-2 level.

// Copy the sequence header into the format block.
pMVIH->cbSequenceHeader = sizeof(SeqHdr); // Size of sequence header.
memcpy(pMVIH->dwSequenceHeader, SeqHdr, sizeof(SeqHdr));

See Also

  • Using the MPEG-2 Demultiplexer


Using the Demux with PSI Streams

To get PSI information from an MPEG-2 transport stream using the MPEG-2 demux filter, create an output pin on the demux with the following media type:

  • Major type: KSDATAFORMAT_TYPE_MPEG2_SECTIONS
  • Subtype: MEDIASUBTYPE_None
  • Format type: GUID_NULL

Then call the output pin's IMPEG2PIDMap::MapPID method with the desired PID and the flag MEDIA_MPEG2_PSI.

// Query the demux filter for IMpeg2Demultiplexer.
IMpeg2Demultiplexer *pDemux = NULL;
hr = pFilter->QueryInterface(IID_IMpeg2Demultiplexer, (void**)&pDemux);
if (SUCCEEDED(hr))
{
    // Define the media type.
    AM_MEDIA_TYPE mt;
    ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
    mt.majortype = KSDATAFORMAT_TYPE_MPEG2_SECTIONS;
    mt.subtype = MEDIASUBTYPE_None;

    // Create a new output pin.
    IPin *pPin;
    hr = pDemux->CreateOutputPin(&mt, L"PSI Pin", &pPin);
    if (SUCCEEDED(hr))
    {
        // Map the PID.
        IMPEG2PIDMap *pPidMap = NULL;
        hr = pPin->QueryInterface(IID_IMPEG2PIDMap, (void**)&pPidMap);
        if (SUCCEEDED(hr))
        {
            ULONG Pid[] = { 0x00 }; // Map any desired PIDs.
            ULONG cPid = 1;
            hr = pPidMap->MapPID(cPid, Pid, MEDIA_MPEG2_PSI);
            pPidMap->Release();
        }
        pPin->Release();
    }
    pDemux->Release();
}

Each complete PSI section is delivered in one media sample. To retrieve the PID number associated with a table section, call IMediaSample2::GetProperties on the media sample. The PID is given in the low 13 bits of the dwTypeSpecificFlags flag in the AM_SAMPLE2_PROPERTIES structure. This is useful if you map multiple PSI PIDs to the same output pin.

See Also

  • Using the MPEG-2 Demultiplexer


Demux Clock Behavior

In push mode, the MPEG-2 demux exposes the IReferenceClock interface. It acts as a live source, so it will be chosen as the graph reference clock by default; see Live Sources for more information.

With transport streams, the demux synchronizes its clock to the PCR stream that corresponds to the audio or video stream that was mapped last. With program streams, the demux synchronizes its clock to the SCR stream. Synchronizing the filter clock to the PCR or SCR stream prevents data overflow or underflow, which could result if the graph clock varied from the stream clock.

The demux also translates PES PTS values into DirectShow reference times, and uses these values to time stamp the media samples. The time stamps apply to the next frame boundary; there is no guarantee that the frame boundary will align with the start of the media sample.

The demux guarantees that the time stamps increase monotonically. This means, for example, that if a transport stream includes a segment such as a commercial that was created with a different clock than the main program, the demux will adjust the presentation time stamps to hide the time discontinuity from downstream filters.

See Also

  • Using the MPEG-2 Demultiplexer


Using the MPEG-2 Splitter

Note In Microsoft® Windows® XP, the MPEG-2 Splitter filter is deprecated. Use the MPEG-2 Demultiplexer instead.

The MPEG-2 Splitter filter supports pull-mode playback of MPEG-2 program streams that contain at least one of the following stream types.

  • MPEG-2 video
  • MPEG-2 audio
  • Dolby AC-3 audio encoded as defined for DVD-Video
  • LPCM (Linear Pulse Code Modulated) audio encoded as defined for DVD-Video

For a list of media types that the MPEG-2 Splitter supports, see MPEG-2 Splitter Media Types.

The MPEG-2 Splitter does not parse transport streams. Use the MPEG-2 Demultiplexer filter for transport streams (push mode only).

Time Stamps

When playing back MPEG-2 program streams, the MPEG-2 Splitter filter treats the first system clock reference it encounters as the time origin of any stream. This differs from the MPEG-1 Stream Splitter, which uses presentation time stamps. The IAMParse::GetParseTime method returns the (possibly estimated) stream system clock time for the data it has processed.

If the MPEG-2 splitter filter encounters an input sample with the discontinuity property set (the discontinuity property can be set by using IMediaSample::SetDiscontinuity or IMediaSample2::SetProperties), it skips data until it finds the first pack in the data and adjusts its time stamps so that the system clock reference (SCR) for that pack is considered identical to the SCR time before the discontinuity. If the SCR clock appears either to jump backward or to jump forward by more than a second, then (in line with the MPEG-2 program stream specification), this is also treated as a clock discontinuity and the apparent clock discrepancy is subtracted from the time stamps passed to downstream filters.

Stream Selection

When playing back the MPEG-2 program stream, the first video stream and first audio stream found traversing the program stream are chosen. Up to one audio and one video output pin are supported. Through the IAMStreamSelect interface, different streams of the same type can be selected up to the number specified by the audio limit in the system header. For MPEG-2 audio, it is currently assumed the streams form a contiguous range starting at stream 0xC0.

Supported Interfaces

The MPEG-2 splitter filter supports the following interfaces.

  • IAMParse—MPEG-2 program stream only
  • IAMStreamSelect—MPEG-2 program stream only, audio streams only
  • IMediaSeeking—includes byte mode seeking

See Also

  • MPEG-2 Support in DirectShow


MPEG Sample Properties

MPEG samples have the following characteristics.

Time Stamps

Not all samples have start and stop times. The sample stop time for packet and payload data is not useful; it is usually set to the start time plus one. MPEG packet or payload data samples will have a start and stop time set if the system layer packet they are generated from had a valid PTS.

For more information about time stamps, see section 2.4.1 of ISO1-11172: "The packet header may contain decoding and/or presentation time stamps (DTS and PTS) that refer to the first access unit in the packet."

For MPEG_Stream major types, the start time is the byte position of the first byte, rated at 1 byte per second. The stop time is the byte position of the last byte. Thus, consecutive samples should have the stop time of the first packet equal to the start time of the next packet. For Video CD data, the origin of the medium must match the format of a video-CD file exposed by CDFS with the standard RIFF chunk at the start.

For MPEG video packet and payload types, the time stamp is the presentation time for the first video frame whose picture start code begins in the sample.

For MPEG audio packet and payload types, the time stamp is the presentation time for the first audio frame whose sync code starts in the sample.

It is assumed that packet and payload data without time stamps can be successfully prerolled by the handling filters.

Discontinuities

If there is a break in the stream (for example, a gap in the real-time data, or an error in the data or after a seek), the discontinuity property is set on the next media sample. This also allows for a time-stamp discontinuity.

End-of-Stream Notifications

When the deoder receives this notification, it must process any buffered data. Any new data must then start with the discontinuity property.

See Also

  • MPEG-2 Support in DirectShow


Getting MPEG-2 PSI Tables

The MPEG-2 Sections and Tables filter retrieves Program Specific Information (PSI) tables from an MPEG-2 transport stream. You can use this filter to obtain any kind of PSI data, such as ATSC Program and System Information Protocol (PSIP) tables, DVB service information (SI), conditional access tables (CATs), DSM-CC messages, or private table data.

To use this filter, connect it to the MPEG-2 Demultiplexer ("demux"). In a digital television graph, the filter is connected to pin 5 on the demux by default. For other kinds of filter graph, the application should create a new output pin on the demux and connect it to the filter. Create the output pin by calling the IMpeg2Demultiplexer::CreateOutputPin method on the demux. Set the major type to MEDIATYPE_MPEG2_SECTIONS and the subtype to MEDIASUBTYPE_MPEG2DATA.

To get PSI tables from the transport stream, use the IMpeg2Data interface on the filter. If you already have a pointer to the filter from building the graph, call QueryInterface to get the interface pointer. Otherwise, use IFilterGraph::EnumFilters to enumerate the filters in the graph, and then query each filter for the interface. (See the example code in Find an Interface on a Filter or Pin.) For digital television applications, if your application uses the Video Control to build the graph, call the IMSVidGraphSegmentContainer::get_Graph method to get a pointer to the filter graph.

The application can retrieve a single table section, a complete table, or a continuous stream of table sections.

Get a Section or Complete Table

To get one section from a table, call the IMpeg2Data::GetSection method:

#include <mpeg2data.h>

IMpeg2Data *pMPEG = NULL; // Pointer to the Sections and Tables filter.
ISectionList *pSectionList = NULL;

// Initialize pMPEG by searching the graph for a filter that exposes the
// IMpeg2Data interface (not shown). Run the graph to get MPEG-2 data.

// Get the next section with PID 0, which is reserved for the PAT.
PID pid = 0x00;
TID tid = 0x00;
DWORD dwTimeout = 5000; // msec

hr = pMPEG->GetSection(pid, tid, NULL, dwTimeout, &pSectionList);
if (SUCCEEDED(hr))
{
    // Use pSectionList to access the data
    pSectionList->Release();
}

The first two parameters of GetSection specify a packet identifier (PID) and a table identifier (TID). The method blocks until the filter receives a section that matches these values or the method times out, whichever happens first. Note that you do not have to map the PID on the demux filter; the GetSection method automatically does this. The third parameter is an optional pointer to an MPEG2_FILTER structure; this can be used to specify additional fields to match, such as the version number or the current/next indicator. The GetSection method returns a pointer to the ISectionList interface, which is used to get the section data.

To get a complete table, call the IMpeg2Data::GetTable method. This method has the same semantics as the GetSection method. However, it blocks until the filter has accumulated a complete table (or the method times out). If the method succeeds, the ISectionList interface references a list of all the sections in the table, rather than one section.

Use the ISectionList interface to access the section data. Call ISectionList::GetNumberOfSections to find how many sections were captured. Then call ISectionList::GetSectionData to get data from each section:

hr = pMPEG->GetTable(pid, tid, NULL, dwTimeout, &pSectionList);
if (SUCCEEDED(hr))
{
    WORD cSections;
    hr = pSectionList->GetNumberOfSections(&cSections);
    for (WORD i = 0; i < cSections; i++)
    {
        // Iterate through the list of sections.
        SECTION *pSection;
        DWORD cbSize;
        hr = pSectionList->GetSectionData(i, &cbSize, &pSection);
        if (SUCCEEDED(hr))
        {
            // Examine the data contained in pSection.
        }
    }
    pSectionList->Release();
}

The GetSectionData method returns the data as a SECTION structure. This structure contains the section header fields, plus a pointer to the rest of the data. If the section_syntax_indicator bit in the header is set to 1, it means the section contains extended header information. You can get the extended header fields by casting the SECTION structure to a LONG_SECTION type. For DSM-CC messages, you can cast the SECTION structure to a DSMCC_SECTION structure.

The following code is a function that displays section data in the debugger window. This function shows how to access all of the header fields; for the remaining data, it displays the raw byte values.

#include <mpeg2data.h>
#include <mpeg2bits.h>

void PrintByteArray(const BYTE *pData, long cbSize); // Forward declare.

HRESULT PrintMpeg2Section(SECTION *pSection, DWORD dwPacketLength)
{
    if (!pSection)
    {
        return E_POINTER;
    }
    if (dwPacketLength < sizeof(SECTION))
    {
        ATLTRACE(L"Malformed MPEG-2 section data.\n");
        return E_FAIL;
    }

    // Coerce the header bits to a bit field structure.
    MPEG_HEADER_BITS *pHeader = (MPEG_HEADER_BITS*)&pSection->Header.W;

    ATLTRACE(L"Packet Length: %d bytes.\n", dwPacketLength);
    ATLTRACE(L"Table ID: 0x%.2x\n", pSection->TableId);
    ATLTRACE(L"Section Syntax Indicator: 0x%x\n",
        pHeader->SectionSyntaxIndicator);
    ATLTRACE(L"Private Indicator: 0x%x\n", pHeader->PrivateIndicator);
    ATLTRACE(L"Reserved: 0x%x\n", pHeader->Reserved);
    ATLTRACE(L"Section Length: %d\n", pHeader->SectionLength);

    if (pHeader->SectionSyntaxIndicator)
    {
        // Coerce the section structure to a long section header.
        LONG_SECTION *pLong = (LONG_SECTION*) pSection;

        MPEG_HEADER_VERSION_BITS *pVersion =
            (MPEG_HEADER_VERSION_BITS*)&pLong->Version.B;

        ATLTRACE(L"Long section fields ...\n");
        ATLTRACE(L"TID Extension: 0x%.4x\n", pLong->TableIdExtension);
        ATLTRACE(L"Reserved: 0x%x\n", pVersion->Reserved);
        ATLTRACE(L"Version: %d\n", pVersion->VersionNumber);
        ATLTRACE(L"Current/Next: 0x%x\n", pVersion->CurrentNextIndicator);
        ATLTRACE(L"Section Number: %d\n", pLong->SectionNumber);
        ATLTRACE(L"Last Section Number: %d\n", pLong->LastSectionNumber);

        // Look for DSM-CC message types.
        if (pSection->TableId == 0x3B || pSection->TableId == 0x3C)
        {
            // Coerce the section structure to a DSM-CC header.
            DSMCC_SECTION *pDsmcc = (DSMCC_SECTION*) pSection;

            ATLTRACE(L"DSM-CC section fields ...\n");
            ATLTRACE(L"Protocol Discriminator: 0x%.2x\n",
                pDsmcc->ProtocolDiscriminator);
            ATLTRACE(L"Type: 0x%.2x\n", pDsmcc->DsmccType);
            ATLTRACE(L"MessageId: 0x%.4x\n", pDsmcc->MessageId);
            ATLTRACE(L"TransactionId: 0x%.8x\n", pDsmcc->TransactionId);
            ATLTRACE(L"Reserved: 0x%.2x\n", pDsmcc->Reserved);
            ATLTRACE(L"AdaptationLength: 0x%.2x\n",
                pDsmcc->AdaptationLength);
            ATLTRACE(L"MessageLength: 0x%.4x\n", pDsmcc->MessageLength);
            ATLTRACE(L"Remaining bytes ...\n");
            PrintByteArray(pDsmcc->RemainingData,
                pDsmcc->MessageLength + pDsmcc->AdaptationLength);
        }
        else
        {
            // This is not a DSM-CC message. Print the remaining bytes.
            ATLTRACE(L"Remaining bytes ...\n");
            PrintByteArray(pLong->RemainingData, pHeader->SectionLength - 5);
        }
    }
    else
    {
        // Not a long section header. Print the remaining bytes.
        ATLTRACE(L"Section bytes ...\n");
        PrintByteArray(pSection->SectionData, pHeader->SectionLength);
    }

    return S_OK;
}

void PrintByteArray(const BYTE *pData, long cbSize)
{
    for (int iter = 0; iter < cbSize; iter++)
    {
        ATLTRACE(L"0x%.2x ", pData[iter]);
        if (iter % 8 == 7)
        {
            ATLTRACE(L"\n");
        }
    }
}

Note that some of the header information is packed into bit fields. Within the header structures, these fields are defined as simple byte and WORD types. To get the individual bit fields, you must coerce some of the structure members, as shown in the example. For example, the Header.W member of the SECTION structure can be cast to an MPEG_HEADER_BITS structure.

The data that follows the header is returned as an unparsed byte array. It is up to the client to parse the data. Therefore, you must understand the format of the transport stream that you expect to receive. Often, this will depend on the network standard in use. For example, ATSC and DVB use different specifications for service information tables. Typically you will need to apply bit masks to get some of the fields, and convert the data from network byte order to host byte order.

Get a Stream of Sections

Instead of making synchronous requests for one section or one table at a time, you can use the IMpeg2Data::GetStreamOfSections method to get a continuous stream of sections. The GetStreamOfSections method returns immediately, and the caller provides an event which is signaled whenever new data arrives. Start by creating the event, and then call GetStreamOfSections with the PID and TID values to match against:

HANDLE hCompleted = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!hCompleted)
{
    // The event was not created. Handle the error.
}
IMpeg2Stream *pStream = 0;
hr = pMPEG->GetStreamOfSections(pid, tid, NULL, hCompleted, &pStream);

If successful, the method returns an IMpeg2Stream interface pointer. Use this interface to get the section data.

Allocate one or more buffers to hold the data. Each buffer must be 4096 bytes or larger. Also declare an MPEG_STREAM_BUFFER structure to manage the buffers. For each section that you retrieve, set the pDataBuffer member of the structure to point to a buffer, and set dwDataBufferSize equal to the size of the buffer. Set the other members to zero:

const int cBufferSize = 4096; // Buffer size.
BYTE Buffer1[cBufferSize];    // The buffer.
MPEG_STREAM_BUFFER streamBuffer;  // Structure to manage the buffer(s).

ZeroMemory(&streamBuffer, sizeof(MPEG_STREAM_BUFFER));
streamBuffer.dwDataBufferSize = cBufferSize;
streamBuffer.pDataBuffer = (BYTE*)Buffer1;

Call IMpeg2Stream::SupplyDataBuffer and wait for the event to be signaled. When the event is signaled, examine the hr field in the MPEG_STREAM_BUFFER structure. If this field contains a success code, it means the request was successful and the buffer contains one section. The dwSizeOfDataRead field specifies the size of the section data. The data is unparsed, in network byte order.

hr = pStream->SupplyDataBuffer(&streamBuffer);
if (SUCCEEDED(hr))
{
    DWORD dwWait = WaitForSingleObject(hRequestCompleted, dwTimeout);
    if (dwWait == WAIT_OBJECT_0)
    {
        if (SUCCEEDED(streamBuffer.hr))
        {
            // Buffer1 contains section data.
        }
    }
}

See Also

  • Microsoft TV Technologies
  • MPEG-2 Support in DirectShow


Windows Media Applications

With Microsoft® DirectShow® you can create applications that play and write Advanced Systems Format (ASF) files, including ASF files containing Windows Media®-based content and files that are protected by Digital Rights Management (DRM). Advanced Systems Format (ASF) is the file container for Windows Media-based content and also for MPEG-4 content that is created with the Microsoft MPEG-4 Encoder DMO. In DirectShow, this Encoder (and the corresponding MPEG-4 decoder) can only be accessed through the WM ASF Reader and WM ASF Writer filters. These filters use the Windows Media Format SDK, which must be installed separately.

Important The WM ASF Reader and WM ASF Writer filters were first made available in DirectShow 8.0; they are wrapper filters for the Windows Media Format SDK. The filters that ship with DirectShow 8.1 and 9.0 support Version 7.0 and 7.1 of the Windows Media Format SDK. When the Windows Media Format 9 Series SDK is released, it will contain versions of these filters (along with the DMO Wrapper filter) that support Windows Media 9 Series. Documentation for these filters is in the Windows Media 9 Series SDK, not in the DirectShow SDK. These filters will supersede the filters in DirectX 9.0. Developers are highly encouraged to install the Windows Media 9 Series SDK and use the latest version of the WM ASF Reader, WM ASF Writer, and DMO Wrapper filters.

If you install the Windows Media Format 9 Series SDK after installing the DirectX 8.x or 9.x SDK, you will overwrite the DirectX version of qasf.dll with the Windows Media 9 Series version. This should not present any problems except possibly in one scenario where it will result in different behavior in the DirectShow IGraphBuilder::RenderFile method. The Windows Media Format 9 Series SDK version of the WM ASF Reader is the default source filter for the .asf, .wmv, and .wma file name extensions. This means that the WM ASF Reader is automatically created and added to the filter graph by the Filter Graph Manager in methods such as IGraphBuilder::RenderFile or IGraphBuilder::AddSourceFilter when a file of this type is specified. In DirectX 9.0 and earlier, and Windows XP Service Pack 1 and earlier, the RenderFile method will cause the older Windows Media Source Filter to be loaded for file playback. This behavior was maintained to ensure backward compatibility with applications that used the Windows Media Player 6.4.

For more information on the Windows Media suite of software development kits, see the Audio and Video section of the MDSN Library.

This article contains the following topics:

  • Reading ASF Files in DirectShow
  • Creating ASF Files in DirectShow


Reading ASF Files in DirectShow

For reasons related to backward compatibility, two source filters are available for ASF files. To create an application that reads ASF files, you will need to understand the difference between the two filters in order to use the right filter for your requirements.

Note The following paragraph only applies if the Windows Media 9 Series runtime libraries are not installed on a system.

The Windows Media Source Filter is the filter that is called into the graph automatically when you use methods like IGraphBuilder::RenderFile or IGraphBuilder::AddSourceFilter. This is the filter that is used by Windows Media Player 6.4. This filter is geared toward network playback and provides support for fast forwarding but not rate control. For simple playback, this filter is sufficient but in general is considered legacy technology and inferior to the WM ASF Reader, which is a wrapper filter for the Windows Media Format SDK and enables applications to make use of most of the features of that SDK for Windows Media playback. The WM ASF Reader supports the IMediaSeeking::SetRate method. Values of -1 to -10 and 1 to 10 are accepted. To use this filter, you must use the COM CoCreateInstance function to instantiate it, and call IFilterGraph::AddFilter to add it to the graph. The WM ASF Reader exposes interfaces of the Windows Media Format Reader object to enable applications to program directly to that SDK when necessary.

See Also

  • Windows Media Source Filter
  • WM ASF Reader Filter


Creating ASF Files in DirectShow

This section describes how to use the Microsoft® DirectShow® WM ASF Writer filter to create files in Advanced Systems Format (ASF). ASF is a container format that can contain any type of compressed or uncompressed data. Microsoft® Windows Media™ Format files are ASF files that use certain codecs as specified in the Windows Media Format Software Development Kit (SDK). These files use the extensions ".wma" for Windows Media Audio files and ".wmv" for Windows Media Video files.

This topic contains the following sections:

  • The DirectShow SDK and the Windows Media Format SDK
  • Configuring the ASF Writer
  • Building a Filter Graph for ASF Output
  • Unlocking the Windows Media Format SDK


The DirectShow SDK and the Windows Media Format SDK

DirectShow and the Windows Media Format SDK offer complementary solutions for writing applications that create and play back Windows Media Format streams. For more information, see the "Audio and Video" section of the MSDN Library.

The ASF Writer filter accepts any number of input streams and creates an ASF file. The filter uses the Windows Media Format SDK to convert uncompressed audio or video files to Windows Media-based content. The compressed content is then stored in the ASF container format. If the content is audio only, then the file is given a ".wma" extension and is referred to as a "Windows Media Audio" file. If the content is video only or video and audio, then the file is given a ".wmv" extension and is referred to as a "Windows Media Video" file. Either type of file may also include metadata.

You can use the WM ASF Writer in various scenarios including digital video (DV) capture, audio recompression, and conversion of Audio-Video Interleaved (AVI) or MPEG multimedia files for network streaming. This filter provides the only way to create Microsoft® Windows Media™ Audio (WMA) and Windows Media Video (WMV) files in DirectShow®. The filter can also create files that are secured by Digital Rights Management (DRM), and can also create MPEG-4 content using the Microsoft MPEG-4 Encoder. This content is stored in the ASF container format.

Important The most recent version of the WM ASF Writer and WM ASF Reader filters now ship with the Windows Media Format 9 Series SDK. The filters that ship with DirectX 9.0 and later will be obsolete after Windows Media Format 9 Series SDK is released. The DirectX 9.0 version of the filters can be used only in conjunction with version 7.0 or 7.1 of the Windows Media Format SDK; those versions will no longer be available for download after Windows Media 9 Series is released.


Configuring the ASF Writer

When the WM ASF Writer filter is created, it is configured automatically with a default system profile. System profiles are discussed in detail in the Windows Media Format SDK; basically, they describe various attributes of a Windows Media Format file such as bit rate, number and type of streams, compression quality, and so on. If the default profile is not suitable, an application can modify it using the filter's IConfigAsfWriter interface methods. The filter uses the profile to determine what kind of Windows Media Format file to write, how many input pins it must set up, and what media types they can accept. The filter must be added to the graph before it can be configured, and it must be configured before it can be connected to upstream filters.

There are various ways to specify a profile to the WM ASF Writer. The WM ASF Writer has a property page that lists the profiles available on the system. This list shows what kinds of streams the filter can create based on the specified input streams. The profile descriptions appear as human-readable strings such as "250 Video—Creates video content for clients with 250 Kbps network connections, such as cable modems, DSL, and LAN connections" or "128 CD Quality Audio—creates CD transparency quality audio content for clients with high-speed Internet and LAN connections. Also suited for local playback." An application can expose this property page to the end user to enable the user to select a profile. For information on how to display a filter's property page, see Displaying a Filter's Property Pages. If you don't want to use the property page, you can get the list of profiles directly by using the Windows Media Format SDK and present these to the end user in your user interface. You can also create a custom profile and pass it directly to the filter, or pass the filter a globally unique identifier (GUID) for a profile from the Wmsysprf.h header file in the Windows Media Format SDK.

The DirectX 9.0 SDK provides a utility program called Profile Enumerator that displays information about system profiles installed on your machine. This program is located in [SDK root]\bin\DXUtils.

The filter allows profiles to be reset while its input pins are connected, but if the profile is changed—for example, from a one-input audio stream profile to a two-input audio and video profile—only the previously connected audio stream is reconnected.

Because the Windows Media Format SDK requires an audio stream to work, the WM ASF Writer must always have an input audio pin, even if it is for a dummy stream—that is, a muted, low-bit-rate audio stream. All input data must be time-stamped, and all input pins must be connected before the filter can be run or paused.


Building a Filter Graph for ASF Output

You can build a filter graph using the WM ASF Writer in two ways. The first way is to manually add each filter to the graph and connect the pins. After adding the WM ASF Writer, configure it through the IConfigAsfWriter methods, if the default profile is not suitable, and connect the WM ASF Writer input pins to the corresponding output pins on the upstream filters.

The second way is to call the IGraphBuilder::RenderFile method with the name of the file to convert to ASF. RenderFile automatically builds a complete graph for rendering the file. In your application code, you then manually remove the renderer filters and insert the WM ASF Writer. This involves five basic steps:

  1. Add the WM ASF Writer to the graph.
  2. Disconnect the renderer filters and store the output pins they were connected to.
  3. Remove the renderer filters from the graph.
  4. Configure the WM ASF Writer.
  5. Connect the WM ASF Writer input pins to the output pins by using IGraphBuilder::Connect.

The following illustration shows typical WM ASF Writer filter graph configurations.

ASF Writer filter graphs


Unlocking the Windows Media Format SDK

To access version 7 or 7.1 of the Windows Media Format SDK, an application must provide a software certificate, also called a key, at run time. This key is contained in a static library called wmstub.lib to which the application links at build time. An individualized key is only required for creating or reading DRM-protected files. Non-DRM files can be created using the static library provided with the Windows Media Format SDK. For details on obtaining the DRM key, see the Windows Media Format SDK. A DirectShow application provides its certificate to the WM ASF Writer when it is added to the filter graph. The application must register as a key provider using the COM IServiceProvider and IObjectWithSite interfaces. Using this technique, the application implements a key provider class derived from IServiceProvider. This class implements the three standard COM methods—AddRef, QueryInterface, and Release—along with one additional method, QueryService, which is called by the filter graph manager. QueryService calls the Windows Media Format SDK method WMCreateCertificate and returns to the filter graph manager a pointer to the certificate that was created. If the certificate is valid, the filter graph manager allows the graph-building process to proceed.

Note To build an application, include Wmsdkidl.h for the prototype for WMCreateCertificate, and link to the Wmstub.lib library.

The following code example illustrates the basic steps in this process:

// Declare and implement a key provider class derived from IServiceProvider.

class CKeyProvider : public IServiceProvider {
public:
    // IUnknown interface
    STDMETHODIMP QueryInterface(REFIID riid, void ** ppv);
    STDMETHODIMP_(ULONG) AddRef();
    STDMETHODIMP_(ULONG) Release();

    CKeyProvider();

    // IServiceProvider
    STDMETHODIMP QueryService(REFIID siid, REFIID riid, void **ppv);

private:
    ULONG m_cRef;
};

CKeyProvider::CKeyProvider() : m_cRef(0)
{
}

// IUnknown methods
ULONG CKeyProvider::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}

ULONG CKeyProvider::Release()
{
    ASSERT(m_cRef > 0);

    ULONG lCount = InterlockedDecrement(&m_cRef);
    if (m_cRef == 0)
    {
        delete this;
        return (ULONG)0;
    }
    return (ULONG)lCount;
}

// We only support IUnknown and IServiceProvider.
HRESULT CKeyProvider::QueryInterface(REFIID riid, void ** ppv)
{
    if (!ppv) return E_POINTER;

    if (riid == IID_IUnknown)
    {
        *ppv = (void *) static_cast<IUnknown *>(this);
        AddRef();
        return S_OK;
    }
    if (riid == IID_IServiceProvider)
    {
        *ppv = (void *) static_cast<IServiceProvider *>(this);
        AddRef();
        return S_OK;
    }

    return E_NOINTERFACE;
}

STDMETHODIMP CKeyProvider::QueryService(REFIID siid, REFIID riid, void **ppv)
{
    if (!ppv) return E_POINTER;

    if (siid == __uuidof(IWMReader) && riid == IID_IUnknown)
    {
        IUnknown *punkCert;
        HRESULT hr = WMCreateCertificate(&punkCert);
        if (SUCCEEDED(hr))
        {
            *ppv = (void *) punkCert;
        }
        return hr;
    }
    return E_NOINTERFACE;
}

////////////////////////////////////////////////////////////////////
//
// These examples illustrate the sequence of method calls
// in your application. Error checking is omitted for brevity.
//
///////////////////////////////////////////////////////////////////

// Create the filter graph manager, but don't add any filters.
IGraphBuilder *pGraph;
hr = CreateFilterGraph(&pGraph);

...

// Instantiate the key provider class, and AddRef it
// so that COM doesn't try to free our static object.

CKeyProvider prov;
prov.AddRef();  // Don't let COM try to free our static object.

// Give the graph an IObjectWithSite pointer for callbacks and QueryService.
IObjectWithSite* pObjectWithSite = NULL;

hr = pGraph->QueryInterface(IID_IObjectWithSite, (void**)&pObjectWithSite);
if (SUCCEEDED(hr))
{
    // Use the IObjectWithSite pointer to specify our key provider object.
    // The filter graph manager will use this pointer to call
    // QueryService to do the unlocking.
    // If the unlocking succeeds, then we can build our graph.

    pObjectWithSite->SetSite((IUnknown *) (IServiceProvider *) &prov);
    pObjectWithSite->Release();
}

// Now build the graph.


Microsoft TV Technologies

Microsoft TV Technologies enables the rapid development of digital and analog TV applications on the Microsoft® Windows® platform. It consists of several components provided by Microsoft, along with specifications for additional components to be provided by third parties. Applications can be written for Microsoft TV Technologies in C++, Microsoft Visual Basic®, Visual Basic Scripting Edition, or JScript.

Microsoft TV Technologies provides built-in software support for all major analog and digital broadcast standards, including ATSC, DVB, NTSC, PAL, SECAM and more. Full support is also provided for IP data services and closed captioning.

Applications based on Microsoft TV Technologies are de-coupled from the details of tuning and are therefore network-independent. This means that the same application can be used with an analog terrestrial or cable broadcast, a ATSC terrestrial broadcast, a DVB-S network, or any other network type for which support may be added in the future by Microsoft or a third party.

Note This documentation assumes that the reader has a basic understanding of the analog, ATSC, and DVB broadcast standards, as well as MPEG-2 transport streams in general. Information on these topics is widely available on the World Wide Web.

This section contains the following articles:

  • Overview of Microsoft TV Technologies
  • Using the Video Control
  • The Microsoft Unified Tuning Model
  • TV Ratings Components
  • Writing Digital TV Applications with DirectX

See Also

  • Microsoft TV Technologies C++ Reference
  • Microsoft TV Technologies Visual Basic and Script Reference
  • Analog Television


Overview of Microsoft TV Technologies

This section provides an overview of the Microsoft TV Technologies architecture.

  • Microsoft TV Technologies Application Interface
  • Microsoft TV Technologies System Requirements
  • Basic Tasks for TV Applications


Microsoft TV Technologies Application Interface

The most important concepts in Microsoft® TV Technologies are the Video Control and the Microsoft Unified Tuning Model. Both are shown in the following illustration.

Microsoft TV Technologies Architecture

The Video Control is an ActiveX® control that handles television tuning, DVD and file playback, and stream buffering. The Video Control can be hosted in any ActiveX container, including Visual Basic® forms, Web pages running in Microsoft® Internet Explorer, or even Microsoft PowerPoint® presentations. For the first time, you can write advanced television applications using Visual Basic or script languages.

Note The Video Control is available in Windows XP only. For applications intended to run on Windows 98SE, Windows 2000, and Windows Millennium Edition, see Writing Digital TV Applications with DirectX.

Internally, the Video Control creates a DirectShow filter graph. It also creates various helper components that manage the filter graph. These components are grouped into three categories:

  • Input devices represent data sources, such as a TV tuners.
  • Output devices represent renderers, such as video renderers or audio renderers.
  • Features represent additional services that DirectShow can provide, such as closed captioning or IP data services.

Devices and features provide the application with a higher level of abstraction than the underlying DirectShow filters. They give you a consistent set of interfaces for controlling DirectShow, organized around functionality rather than the internal implementation. For more information about using the Video Control, see Using the Video Control.

The Unified Tuning Model is an API that defines tuning on any type of network, using any kind of compatible device. Microsoft TV Technologies includes software components that implement the Unified Tuning Model for several network types, including ATSC and Digital Cable. Third parties can implement the Unified Tuning Model for other network types. By using the tuning model to perform tuning, an application will automatically support any new network types that may be introduced in the future, either by Microsoft or by third parties.

From the application's standpoint, the main object in the Unified Tuning Model is the tune request. A tune request contains all the information that the Video Control needs to tune to a particular broadcast service. Tune requests are typically created by a separate component, called a guide store loader, and then stored in a database. The application performs tuning by getting a tune request from the database and submitting it to the Video Control. For more information, see The Microsoft Unified Tuning Model.


Microsoft TV Technologies System Requirements

This topic applies to Windows XP only.

The minimum system requirements for running digital TV applications are greater than the minimum requirements for Microsoft® Windows® XP. A digital TV application requires the following:

  • BDA-compatible digital TV tuner
  • 600-MHz CPU with 128 MB RAM
  • DirectX Video Acceleration-compatible video card with 32 MB VRAM
  • DirectX VA-compatible MPEG2 decoder

Further requirements for the video card are described in VMR System Requirements


Basic Tasks for TV Applications

This topic applies to Windows XP only.

Application development using Microsoft TV Technologies is based on a few fundamental tasks. Some of these tasks are optional, depending on what type of application you are developing. This section gives a brief desciption of each task. It is not specific to any programming language; later sections give detailed information for script, Visual Basic, and C++.

  1. Create an instance of the Video Control. The Video Control provides access to the TV tuner devices, audio and video rendering devices, and various features such as closed captioning and IP data services. For more information, see Using the Video Control.
  2. Activate the desired features. IP data services and closed captioning are exposed to applications as "features" by the Video Control. The Video Control exposes a FeaturesAvailable collection, which contains the features that are available. To enable some or all of these features, the application creates a new collection object, adds the desired features from the FeaturesAvailable collection, and sets the new collection as the Video Control's FeaturesActive property.
  3. Obtain or create a tune request. A tune request contains tuning information for a particular network type. The recommended approach is to implement an object called a guide store loader that reads electronic program guide (EPG) data and uses it to populate a database with tune requests. With this approach, the application does not depend on the underlying network type. Instead, it simply pulls generic tune request objects from the data base.

    An alternate approach is for the application to create the tune request. This approach requires the application to target specific network types, because different network types have different requirements for tune requests.

  4. Submit the tune request to the Video Control. The application gives the tune request to the Video Control by calling the Video Control's View method.
  5. Configure the Video Mixing Renderer for custom rendering. (Optional) The Video Mixing Renderer (VMR) enables you to create custom mixing effects, such as alpha-blending a bitmap over the video rectangle. The application configures the VMR through the MSVidVideoRenderer object, which is obtained through the Video Control's VideoRendererActive property.
  6. Set up event notication. (Optional) For most applications, it is useful to receive event notifications from the Video Control. The mechanism for receiving events depends on the programming language; details are given in the language-specific sections of the documentation.
  7. Access IP data in the broadcast stream. (Optional) If the Data Services feature is enabled, IP data in the broadcast stream is routed to the NDIS stack. To receive this data, the application must open a socket using Winsock and listen on the specified multicast address, as it would for any other IP data.
  8. Create a default tune request. (Required for script applications only) When Microsoft Internet Explorer encounters a "TV:" URL in a Web page, it automatically loads the Video Control and tunes it to the default tune request, which is stored in the system registry. This registry entry must be created by a C++ application, using the ICreatePropBagOnRegKey interface.

See Also

  • TV Applications in Script (Video Control)
  • TV Applications in Visual Basic (Video Control)
  • TV Applications in C++ (Video Control)


Microsoft TV Technologies Internals

This section provides background information on the underlying DirectShow filters and drivers that comprise the Microsoft TV Technologies system architecture. This material is relevant for developers of third-party components such as Guide Store Loaders, MPEG-2 decoders, and BDA device drivers. Applications running on Windows® XP do not communicate directly with the filter graph. Applications running on Windows 98SE, Windows Me, or Windows 2000 cannot use the Video Control, so these applications must build the filter graph and store tune requests.

The following illustration shows all of the Microsoft TV Technologies system components used for the reception of digital TV broadcasts.

Microsoft TV Technologies System Architecture

  • The BDA Network Provider is a user-mode filter that works with the tuner, the MPEG-2 Demultiplexer, and the Transport Information Filter (TIF) to perform tuning and to route of elementary streams based on the tune request.

    Microsoft provides Network Provider filters for ATSC, DVB-C, DVB-T, and DVB-S standards.

  • BDA Device Filters: The driver specification associated with Microsoft TV Technologies is called Broadcast Driver Architecture (BDA). It is used by independent hardware vendors (IHVs) who wish to create digital TV tuning devices that work with Windows. IHVs also use BDA to support new network types or custom hardware functionality. BDA-compatible drivers are automatically represented as DirectShow filters through the KsProxy wrapper filter. The exact names of these filters, and the number of different filters that are used to represent the device, may vary depending on the driver. The details of BDA are not important for application developers; BDA is documented in the DirectX 9.0 DDK and the Microsoft Platform DDK for Windows XP.
  • The MPEG-2 Demultiplexer filter accepts the MPEG-2 transport stream from the capture filter and demultiplexes the stream based on packet IDs (PIDs) provided by the Network Provider. The Network Provider configures the output pins on the demux.
  • The BDA MPEG-2 Transport Information Filter (TIF) receives the PSI packets, parses the tables, and provides information to the Network Provider. The MPEG-2 Sections and Tables filter also receives PSI packets. Third-parties can develop software components called guide store loaders that receive table data from the TIF and the MPEG-2 Sections and Tables filter, and use this data to create tune requests. For more information, see The Microsoft Unified Tuning Model.
  • MPEG-2 Decoders: A digital TV filter graph requires a third-party MPEG-2 decoder capable of decoding High Definition Television (HDTV) video streams. Some decoders may decode audio and video in the same filter, while others may have separate filters for audio and video. To achieve the performance necessary to support HDTV, the decoder should support Microsoft DirectX Video Acceleration (DXVA), which is a specification for hardware acceleration of digital video decoding processing. DXVA is documented in the DirectX 9.0 DDK and the Microsoft Platform DDK for Windows XP. The user-mode interface for DXVA, IAMVideoAccelerator, is used by software decoders and is documented in this SDK.

Note The illustration above shows a software decoder. Hardware decoders are also supported. When a hardware decoder is used, the Video Port Manager filter connects to one of the decoder's output pins and manages the video port connection to the graphics card.

  • Video and Audio Renderers: The Video Mixing Renderer (VMR) is a video rendering filter that replaces both the Overlay Mixer filter and Video Renderer filter. For more information, see Using the Video Mixing Renderer. The audio renderer plays the decoded audio stream through the system's speakers.
  • Data Services Filters: These filters accept IP data from the MPEG-2 Demultiplexer and pass it either to the renderer (in the case of Line 21 or closed captioning data) or else to Winsock. The data services filters that are present in the graph depend on the type of data being processed. The illustration above shows the filters that are used to pass IP data to Winsock: the BDA MPE filter and the BDA IP Sink filter.


Using the Video Control

This topic applies to Windows XP only.

The Video Control is a lightweight ActiveX® control that gives Automation clients access to the powerful features of DirectShow. For the first time, you can write advanced television applications using Visual Basic or script languages.

The Video Control can be hosted in any ActiveX container, including a Visual Basic® form, a Web page running in Microsoft® Internet Explorer, or a Microsoft PowerPoint® presentation. Using the Video Control, you can:

  • Play analog or digital TV broadcasts from a variety of network types, including analog, ATSC, and DVB.
  • Create sophisticated mixing and blending effects using the Video Mixing Renderer.
  • Create DVD-based applications.
  • Create stream buffer applications.
  • Play local video and audio files.

These tasks can be done with only a few lines of code. More importantly, this code can be neutral as to the network type. As new network types are supported, the application will automatically support them, without any changes to the application. This is possible because the tuning information is stored in Tune Request objects, which encapsulate network details. The application simply retrieves the tune request from whatever storage mechanism it uses, and submits the tune request to the Video Control.

  • This section contains the following topics:
  • Video Control Overview
  • Tuning with the Video Control
  • Using the Stream Buffer Engine with the Video Control
  • TV Applications in Script (Video Control)
  • TV Applications in Visual Basic (Video Control)
  • TV Applications in C++ (Video Control)
  • DVD Applications in Visual Basic (Video Control)


Video Control Overview

This topic applies to Windows XP only.

The Video Control manages filter graphs for receiving television broadcasts. It supports digital TV devices that are compatible with Broadcast Driver Architecture (BDA); it also supports analog TV devices that do not use BDA, as long as those devices use Windows Driver Model (WDM) drivers.

In traditional DirectShow programming, an application creates an instance of the Filter Graph Manager, and uses the Filter Graph Manager to create the filter graph. The application has access to individual filters in the graph, but the Filter Graph Manager is responsible for making the filters work together.

Filter graphs for television applications are relatively complex. Although it is possible to create a TV graph directly through the Filter Graph Manager, doing so is complicated and likely to be error-prone, especially for digital TV. The Video Control makes it convenient to build both analog and digital TV graphs. Moreover, unlike the Filter Graph Manager, the Video Control is fully Automation-compatible, so you can use it in Microsoft Visual Basic® applications or even Web pages, through script.

Devices and Features

Rather than expose individual filters to applications, the Video Control exposes high-level objects called devices. A device might represent a single filter, several filters, or a software component outside the graph. Unlike DirectShow filters, devices are Automation-compatible. Also, devices enable to underlying filter graph to change without affecting the application.

Currently, the following types of device are supported:

  • Input devices
  • Output devices
  • Features

Applications can communicate directly with these objects to perform various tasks, but the Video Control handles the low-level details of making these components work together as a unit.

Input Device Objects

Input devices include TV tuners, DVD playback, and file playback. The following types of TV tuner devices are supported:

  • Analog TV tuners compatible with the Windows Driver Model (WDM)
  • Digital TV tuners compatible with Broadcast Driver Architecture (BDA)

Output Device Objects

By default, the Video Control builds the filter graph with one video renderer and one audio renderer.

The video renderer is always the Video Mixing Renderer (VMR), for both analog and digital TV filter graphs. The VMR's mode of operation differs depending on the type of graph. For analog TV graphs, the Video Control puts the VMR into mixing mode, and applications cannot modify this setting. Mixing mode is required to display closed captioning on analog TV pictures. For digital graphs, the Video Control puts the VMR into non-mixing mode. To enable video mixing, the application must activate the closed caption feature. (You can activate the feature without displaying the captions themselves, if desired.)

For audio, the Video Control uses whichever device is appropriate for the audio stream generated by the input device. The Video Control uses DirectSound if the sound card supports it.

Feature Objects

Features represent a service on a television signal, or a client-side capability, or both. Applications determine which features to enable. The following features are supported:

  • Data Services: When this feature is active, the Video Control routes IP data present in an analog or digital television stream to the NDIS stack, where applications can access it via Winsock. This feature is also required to display closed captioning in analog broadcasts.
  • Closed Captioning: When this feature is active, applications can enable and disable closed captioning at any time on any channel or service where it is available. On analog TV graphs, closed captioning requires both the closed captioning feature and the Data Services feature.
  • Encoder: Required for using the Stream Buffer Engine with the Video Control.


Tuning with the Video Control

This topic applies to Windows XP only.

The Video Control is designed to shield applications from the complexities of TV tuning and filter-graph building on the PC. To perform tuning, the application obtains a tune request, which is an object that contains information about the network type, the channel, and so forth. The application passes the tune request to the Video Control's View command.

An application can retrieve a tune request from a database or other storage mechanism or it can create a tune request programmatically. The details of creating the request will depend on the network type, such as analog, ATSC, or DVB. This approach sacrifices network independence, but retains device independence. In other words, if the application creates an ATSC tune request, it will not function with a DVB network, but it work with different BDA-compliant tuner cards. For more information, see The Microsoft Unified Tuning Model.

Once the Video Control receives the tune request, it searches the local system for an appropriate input device. When the application calls Build or Run, the Video Control builds and configures the filter graph based on the selected input device. When the application calls Run, the Video Control renders the television.


Using the Stream Buffer Engine with the Video Control

This topic applies to Windows XP Service Pack 1 only.

The Video Control can pause a live video stream using the Stream Buffer Engine.

To do so, create two instances of the Video Control. The first instance is for creating the tune request and recording the content into the stream buffer. The second instance is for playing back the content from the stream buffer.

Using the first instance of the Video Control, do the following:

  1. Create a tune request.
  2. Pass the tune request to the Video Control by calling the View method.
  3. Add the video encoder feature (CLSID_MSVidEncoder) to the active features collection.
  4. Enumerate the available output devices in the GUID_NULL category. Find the Stream Buffer Sink device and set it to be the active output device.
  5. Specify a file name for the output device.
  6. Disable video and audio rendering.
  7. Run the Video Control.

Using the second instance of the Video Control, do the following:

  1. Enumerate the available input devices in the GUID_NULL category. Set the Stream Buffer Source device as the active input device.
  2. Specify the same file name used previously in step 5 of the first instance of the Video Control.
  3. Run the Video Control.

See Also

  • Using the Stream Buffer Engine in Script


TV Applications in Script (Video Control)

This topic applies to Windows XP only.

Hosting the Video Control in a scripting application is straightforward, and involves only a few basic operations.

The examples in this section use Visual Basic Scripting Edition in a Web page. Note that the ProgID's used to create the objects begin with either "MSVidCtl" for Video Control objects, or "BDATuner" for Tuning Model objects.

This section contains the following topics:

  • Embedding the Video Control in a Web Pagee
  • Creating a Tune Request (Script)
  • Selecting from Multiple Input Devices (Script)
  • Activating Video Control Features (Script)
  • Binding Event Handlers to Events in Script Applications
  • Performing Custom Video Mixing in Script
  • Using the Stream Buffer Engine in Script


Embedding the Video Control in a Web Page

This topic applies to Windows XP only.

Use the OBJECT tag to embed the Video Control in a Web page. You can specify either the CLASSID attribute or the DATA attribute, as follows:

  • <OBJECT ID="MSVidCtl" CLASSID="CLSID:B0EDF163-910A-11D2-B632-00C04F79498E"></OBJECT>
  • <OBJECT DATA="tv:"></OBJECT>

With the CLASSID attribute, the Video Control is created but does not tune to any program. It appears as a blank video rectangle until the Video Control receives a tune request through script. With the DATA attribute, the Video Control automatically tunes to the default tune request specified in the system registry (if any).

The default tune request must be created using C++. Script-based applications cannot access the system registry. The default tune request might be created during the installation process for a particular device or service, or by a C++ application. For more information, see ICreatePropBagOnRegKey.

The Video Control appears as a visible rectangle on the display, so it should be embedded and positioned inside the BODY tag of the Web page. To specify the dimensions of the rectangle, use the WIDTH and HEIGHT attributes, as shown in the following example:

<OBJECT DATA="tv:" WIDTH="320" HEIGHT="280"></OBJECT>

To tune to a program, call the View method on the MSVidCtl object.

dim objTuneRequest  ' Tune Request
' Create the tune request (not shown)
MSVidCtl.View objTuneRequest

For information about creating a tune request object, see Creating Tune Requests (Script).

To begin viewing the program, call the Run method:

MSVidCtl.Run


Creating a Tune Request (Script)

This topic applies to Windows XP only.

A tune request contains all the information necessary for the Video Control to tune to a given channel or frequency. Tune requests are represented by objects such as IATSCChannelTuneRequest, IDVBTuneRequest, and ITuneRequest (for analog TV). Tune requests encapsulate all the details of tuning across various network types.

Typically, an application will create an Electronic Program Guide (EPG) database to hold tune requests. The data base can be populated from a remote server or from in-band tuning information that comes from the Transport Information Filter. When the user selects a program to view, the application obtains the tune request from the database and passes it to the Video Control. For more information, see Transport Information Interfaces and The Microsoft Unified Tuning Model.

In some cases, it may be preferable to create a tune request programmatically, instead of get it from a database. The drawback is that this approach is not network-independent. If you obtain tune requests from a database, the details of the network type are transparent to the application. If you create tune requests programmatically, however, you must target a particular network type.

The following code illustrates how to create a tune request for a program on an ATSC network:

Dim objTuner
Dim objTSContainer
Dim objTuningSpace
Dim objTuneRequest
Dim objLocator

Set objTSContainer = CreateObject("BDATuner.SystemTuningSpaces")
Set objTuningSpace = objTSContainer("ATSC")
Set objTuneRequest = objTuningSpace.CreateTuneRequest
Set objLocator = CreateObject("BDATuner.ATSCLocator")
objLocator.PhysicalChannel = 46
objTuneRequest.Locator = objLocator
objTuneRequest.Channel = -1
objTuneRequest.MinorChannel = -1
MSVidCtl.View objTuneRequest
MSVidCtl.Run

The next example shows how to create a tune request to view a program on an analog TV network:

Dim objTuner
Dim objTSContainer
Dim objTuningSpace
Dim objTuneRequest

Set objTSContainer = CreateObject("BDATuner.SystemTuningSpaces")
Set objTuningSpace = objTSContainer("Cable")
Set objTuneRequest = objTuningSpace.CreateTuneRequest
objTuneRequest.Channel = 5
MSVidCtl.View objTuneRequest
MSVidCtl.Run

Note that to tune to a program on an ATSC network type, you must change the PhysicalChannel property on the ILocator object. On ATSC networks, the tune request's Channel property is just the channel number the broadcaster is advertising for the sake of end users. Usually it maps to the analog channel number the broadcaster has historically been associated with. A broadcaster may transmit up to three separate programs simultaneously on ATSC; the MinorChannel property may have a value of 1 through 3. For the Channel property, a value of -1 instructs the Video Control to use the default value provided in the broadcast stream. For the MinorChannel property, a value of -1 instructs the Video Control to tune to the first minor channel on which a signal is present.


Selecting from Multiple Input Devices (Script)

This topic applies to Windows XP only.

It is possible that some systems may have more than one TV tuner card, even multiple cards of the same type. To handle this case, the application should provide the user a way to specify which particular piece of hardware to use when building the filter graph. An application retrieves the collection of available TV tuner devices on the system by specifying a GUID for each device category it is interested in. Currently two categories are supported. The application enables the user to select the active device by using the Video Control's InputActive property.

The Video Control recognizes the class ID strings for TV tuner device categories listed in the following table.

Device Category | Class ID String
Non-BDA analog TV tuners | {A799A800-A46D-11D0-A18C-00A02401DCD4}
BDA-compatible TV tuners | {71985F4B-1CA1-11D3-9CC8-00C04F7971E0}

The following example shows how to obtain a collection of available BDA-compatible tuning devices. For simplicity, this code just sets the first item in the collection as the active input.

Dim objInputs
Set objInputs = MSVidCtl.InputsAvailable("{71985F4B-1CA1-11D3-9CC8-00C04F7971E0}")
MSVidCtl.InputActive = objInputs(0)


Activating Video Control Features (Script)

This topic applies to Windows XP only.

Applications work with two separate collections of features. One contains the available features, and the other contains the features that are currently active. The available features collection is read-only and is obtained through the FeaturesAvailable property on the MSVidCtl object. It always contains the features listed in the table below.

Feature | Class ID String | Friendly Name String
Data Services | {334125C0-77E5-11D3-B653-00C04F79498E} | BDA IPSink
Closed Captioning | {7F9CB14D-48E4-43B6-9346-1AEBC39C64D3} | Line 21 Decoder
Encoding |  |

The application enumerates through those features and populates a new feature collection that contains the features to be activated. It passes this new collection to the Video Control in the FeaturesActive property. The Video Control uses this collection to create a new filter graph or to modify an existing one. There is no need to create a FeaturesActive collection unless you require one or more of the features.

The FeaturesActive collection remains in effect even when you change inputs. Features are identified by their class ID strings, which are listed in the following table. The friendly name string is the string that is returned from the IMSVidDevice.Name property.

The following code shows one way to create an ActiveFeatures collection and use it to configure the Video Control:

' Create variables with easy-to-remember names to hold the GUIDs.
strDS = "{334125C0-77E5-11D3-B653-00C04F79498E}"
strCA = "{1600F101-6666-4F66-B1E2-BF3C9FBB9BA6}"
strCC = "{7F9CB14D-48E4-43B6-9346-1AEBC39C64D3}"

' Create our two "features" collections.
Dim colFeaturesActive
Set colFeaturesActive = CreateObject("MSVidCtl.MSVidFeatures")
Dim colFeaturesAvailable
Set colFeaturesAvailable = objVidCtl.FeaturesAvailable

' Here we specify Data Services
For Each MSVidFeature in colFeaturesAvailable
    If (MSVidFeature.ClassID = strDS)Then
       colFeaturesActive.Add MSVidFeature
    End if
Next

objVidCtl.FeaturesActive = colFeaturesActive


Binding Event Handlers to Events in Script Applications

This topic applies to Windows XP only.

For script-based applications running in Microsoft Internet Explorer, the application must explicitly associate event handling methods with their respective events. The MSEventBinder object is provided for this purpose. Its use is illustrated in the following code:

<HEAD>
<OBJECT id=Binder classid="clsid:577FAA18-4518-445E-8F70-1473F8CF4BA4"></OBJECT>
<script language="vbscript">
dim bind_1

sub window_onload
  bind_1 = Binder.Bind(VidCtl, "StateChange", "handleStateChange")
end sub

sub handleStateChange(laststate, curstate)
  if curstate = 0 then
    StateSpan.innerHTML = "Stop"
  elseif curstate = 1 then
    StateSpan.innerHTML = "Pause"
  elseif curstate = 2 then
    StateSpan.innerHTML = "Play"
  end if
end sub

sub close()
  Binder.Unbind(bind_1)
end sub
</script>
</HEAD>
<BODY>
<OBJECT ID="VidCtl" DATA="tv:"></OBJECT>
<P>Current State: <SPAN style="color:red" id="StateSpan">Unknown</SPAN></P>
</BODY>
</HTML>


Performing Custom Video Mixing in Script

This topic applies to Windows XP only.

The Video Control works closely with the DirectShow Video Mixing Renderer filter (VMR). The VMR enables C++ developers to create powerful mixing effects by implementing custom compositors. Script-based applications can invoke and run this custom compositor through the Video Control, and also use the default capabilities of the VMR to perform effects such as overlaying an alpha-blended bitmap on the video frame. One limitation of script applictions running in Microsoft® Internet Explorer® is that they cannot save a captured frame to disk, since these applications cannot access the file system.

Some settings on the VMR must be made before the application calls Build or Run (in other words, before a filter graph is constructed). One such setting is whether the VMR should reduce the size of the native video before attempting to process it. (This is useful when viewing HDTV on a monitor that is set to a lower resolution.) To pre-configure the VMR, enumerate the MSVidVideoRendererDevices collection and get the one MSVidVideoRenderer item that it contains. Call its methods to configure it, and then set this object as the active renderer before calling Build or Run. For more information, see MSVidVideoRenderer and Using the Video Mixing Renderer.


Using the Stream Buffer Engine in Script

This topic applies to Windows XP Service Pack 1 only.

The Video Control can pause a live video stream using the Stream Buffer Engine. Place two separate instances of the Video Control in your Web page. The first instance will receive the tune request and record the content, using the MSVidStreamBufferSink (sink) object. The second instance will play back the content, using the MSVidStreamBufferSource (source) object.

In the following example, MSVidCtl_Sink is for the sink and MSVidCtl_Src is for the source:

<BODY>
    <!-- Stream Buffer Sink instance of the Video Control -->
    <OBJECT
        ID="MSVidCtl_Sink"
        CLASSID="CLSID:B0EDF163-910A-11D2-B632-00C04F79498E" >
    </OBJECT>
    <!-- Stream Buffer Source instance of the Video Control -->
    <OBJECT
        ID="MSVidCtl_Src"
        CLASSID="CLSID:B0EDF163-910A-11D2-B632-00C04F79498E" >
    </OBJECT>
</BODY>

Initialize the Stream Buffer Sink

First, create a tune request and pass it stream buffer sink instance of the Video Control. For details, see Creating a Tune Request (Script). Next, add the Encoder feature (CLSID_MSVidEncoder) to the active features collection:

ENC_CLSID = "{BB530C63-D9DF-4B49-9439-63453962E598}"
' Create an empty Features collection
Set MyFeatures = CreateObject("MSVidCtl.MSVidFeatures")

' Enumerate the available features
For Each feature In MSVidCtl.FeaturesAvailable
   ' Look for the MSVidEncoder feature
    If (feature.ClassID = ENC_CLSID) Then
        MyFeatures.Add feature
    End If
    ' Optionally, add other features (not shown).
Next

' Use this as the active features collection.
MSVidCtl_Sink.FeaturesActive = MyFeatures

Enumerate the available output devices in the GUID_NULL category, and set the MSVidStreamBufferSink object as the active output device:

GUID_NULL = "{00000000-0000-0000-0000-000000000000}"
SINK_CLSID = "{9E77AAC4-35E5-42A1-BDC2-8F3FF399847C}"

' Create an empty output device collection.
Set MyOutputs = CreateObject("MSVidCtl.MSVidOutputDevices")

' Enumerate the available output devices.
Dim objStreamBufferSink
For Each output In MSVidCtl.OutputsAvailable(GUID_NULL)
    If output.ClassID = SINK_CLSID Then
        ' This is the one we want.
        MyOutputs.add output
        Set objStreamBufferSink = output  ' Store this for later use.
    End If
Next

' Set the active outputs collection.
MSVidCtl_Sink.OutputsActive = outs

Specify a file name for the output device:

strFilename = "C:\Example.wmv
objStreamBufferSink.SinkName = strFilename

Disable video and audio rendering in the Video Control for the stream buffer sink. Rendering will be performed by the stream buffer source instance.

MSVidCtl_Sink.DisableVideo
MSVidCtl_Sink.DisableAudio

Initialize the Stream Buffer Source

Using the other instance of the Video Control, enumerate the available input devices in the GUID_NULL category. Set the MSVidStreamBufferSource device as the active input device.

DVR_CLSID = "{AD8E510D-217F-409B-8076-29C5E73B98E8}"
Dim objStreamBufferSource
' Enumerate the available inputs
For Each input in MSVidCtl_Src.InputsAvailable(GUID_NULL)
    If input.ClassID = DVR_CLSID Then
        ' This is the one we want.
        MSVidCtl_Src.InputActive = input
        Set objStreamBufferSource = input  ' Store this for later use.
    End If
Next

Specify the same file name used previously:

objStreamBufferSource.FileName = strFilename

Run both Video Control instances:

MSVidCtl_Src.Run
MSVidCtl_Sink.Run


TV Applications in Visual Basic (Video Control)

This topic applies to Windows XP only.

This section describes how to host the Video Control in a Visual Basic application. It contains the following articles:

Hosting the Video Control in a Visual Basic Form

Displaying Closed Captioning in Visual Basic

Mixing an Image Onto the Video Window in Visual Basic


Hosting the Video Control in a Visual Basic Form

This topic applies to Windows XP only.

This article shows how to use the Video Control to tune to a station using Visual Basic. First, create a project and add the following references:

  • MS Video Control 1.0 Type Library
  • Microsoft Tuner 1.0 Type Library

Also add the Video Control type library as a component. Draw the video control on your form and give it a name; for example, VidControl. To tune to a channel, do the following:

  1. Obtain a tune request, as an ITuneRequest interface. This interface provides polymorphism across network types. Depending on the network, the underlying object may be an IATSCChannelTuneRequest object, an IDVBTuneRequest object, or some other type.
  2. Call the View method on the Video Control, using the tune request as the argument.
  3. Call the Run method on the Video Control.

In step 1, it is preferable to get a pre-configured tune request from a database. That way, the application does not need to handle any details related to the network type. However, you can construct a tune request from scratch if you know the particular network type that you want to support. Do the following:

  1. Create the SystemTuningSpaces collection.
  2. Create a new tune request by calling ITuningSpace.CreateTuneRequest on one of the tuning spaces in the collection.
  3. For ATSC and DVB tuning, create a locator object, and assign it to the tune request's ITuneRequest.Locator property.
  4. Set the appropriate properties on the tune request and the locator. These will depend on the network type.

For example, the following procedure tunes to ATSC channel 46 when the form loads:

Private Sub Form_Load()
    Dim objTSContainer As New SystemTuningSpaces
    Dim objTuneRequest As IATSCChannelTuneRequest
    Dim objLocator As New ATSCLocator

    Set objTuneRequest = objTSContainer("ATSC").CreateTuneRequest
    objLocator.PhysicalChannel = 46
    objTuneRequest.Locator = objLocator

    VidControl.View objTuneRequest
    VidControl.Run
End Sub

The previous example specifies a tuning space in the SystemTuningSpaces collection by its unique name ("ATSC" in this example). You can also use a For...Each loop to iterate through the collection. For example, the following code populates a list box with the names of all the available tuning spaces:

For Each tunespace In objTSContainer
    TuneName = tunespace.UniqueName + " (" + tunespace.FriendlyName + ")"
    List1.AddItem TuneName
Next

Analog cable does not require a locator object. The next example tunes to NTSC analog cable, channel 6:

Dim objTSContainer As New SystemTuningSpaces
Dim objTuneRequest As IChannelTuneRequest

Set objTuneRequest = objTSContainer("Cable").CreateTuneRequest
objTuneRequest.Channel = 6

VidControl.View objTuneRequest
VidControl.Run

As these examples show, when the application builds a tune request, it must target specific network types. If it always gets a preconfigured tune request from a database, it will function with any supported network type.

To change channels within the same network type, simply submit another tune request to the Video Control by calling MSVidCtl.View.


Displaying Closed Captioning in Visual Basic

This topic applies to Windows XP only.

To enable closed captioning (CC), the application must activate the closed captioning feature. For analog television, the application must also activate the data services feature. You can find the features by enumerating them from the Video Control's available features collection. To activate a feature, add it to the active features collection.

To activate the closed captioning feature, perform the following steps:

  1. Create a new MSVidFeatures collection.
  2. Enumerate the available features from the Video Control's MSVidCtl.FeaturesAvailable property.
  3. Compare each feature's class identifier (CLSID) against the CLSID of the CC feature. For analog, also check for the CLSID of the data services feature. If the CLSID matches, add that feature to your collection object. Store a reference to the CC feature in a variable for later use.
  4. Set the Video Control's MSVidCtl.FeaturesActive property equal to your collection object.

Perform these steps before calling MSVidCtl.Build or MSVidCtl.Run. Once the CC feature is in the active features collection, you can enable or disable closed captioning at any time by setting the CC feature's MSVidClosedCaptioning.Enable property. By default, the feature is disabled.

The following code example enables closed captioning for analog television:

Const CLSID_CC As String = "{7F9CB14D-48E4-43B6-9346-1AEBC39C64D3}"
Const CLSID_DATASVC As String = "{334125C0-77E5-11D3-B653-00C04F79498E}"
Private mCCFeature as MSVidClosedCaptioning

Dim colFeatures As New MSVidFeatures
Dim objFeature As IMSVidFeature

' Find the CC and Data Services features, and add them to the collection.
For Each objFeature In VidControl.FeaturesAvailable
    If objFeature.ClassID = CLSID_CC Then
        colFeatures.Add objFeature
        Set mCCFeature = objFeature
    ElseIf objFeature.ClassID = CLSID_DATASVC Then
        colFeatures.Add objFeature
    End If
Next
' Use this collection for the active features.
VidControl1.FeaturesActive = colFeatures
mCCFeature.Enable = True

In this example, the CLSID_CC and CLSID_DATASVC constants contain the CLSIDs of the features, in string format. The application compares these strings against the IMSVidDevice.ClassID property. For digital television, you could omit the ElseIf clause, unless you wanted the data services feature in order to receive IP data.

Once the CC feature is active, you can display captions by setting the CC feature's MSVidClosedCaptioning.Enable property to True. You can hide the captions again by setting this property to False.


Mixing an Image Onto the Video Window in Visual Basic

This topic applies to Windows XP only.

This section describes how to display an alpha-blended image over the Video Control's video image. Internally, the Video Control uses the Video Mixing Renderer filter (VMR). After you call the View method on the Video Control to build the filter graph, the MSVidCtl.VideoRendererActive property holds a reference to an MSVidVideoRenderer device object, which controls the VMR.

First obtain an IPictureDisp object to use as the image. For example, you can load an image file, or capture a frame from the Video Control:

Dim iPic As IPictureDisp
' Load an image.
Set iPic = LoadPicture("MyPicture.gif")
' ... or capture a frame.
Set iPic = VideoControl.VideoRendererActive.Capture

Set the MSVidVideoRenderer.MixerBitmapPositionRect property to specify the position of the image as it will appear on the Video Control window. The default position is the entire window. The following example places the image in the upper-left corner of the window:

ScaleMode = 3 ' pixels
Dim iVid As MSVidVideoRenderer
Set iVid = gTV.VideoRendererActive
iVid.MixerBitmapPositionRect.Top = 0
iVid.MixerBitmapPositionRect.Left = 0
iVid.MixerBitmapPositionRect.Height = VideoControl.Height / 2
iVid.MixerBitmapPositionRect.Width = VideoControl.Width / 2
iVid.MixerBitmapPositionRect = rect

The MixerBitmapPositionRect property is an IMSVidRect object, which represents a rectangle. This example modifies the rectangle's coordinates in place. Note that if you set a reference to the MixerBitmapPositionRect property, the property returns a copy of the original rectangle. Modifying the copy does not change the original rectangle. For example:

Dim rect As IMSVidRect
Set rect = VideoControl.VideoRendererActive.MixerBitmapPositionRect
' This is a copy of the rectangle!
rect.Height = VideoControl.Height / 2
rect.Width = VideoControl.Width / 2
' To modify the original, put the copy back into the property:
VideoControl.VideoRendererActive.MixerBitmapPositionRect = rect

The rectangle coordinates are in pixels, not twips, so call the ScaleMode function before retrieving the Video Control's Height and Width properties.

Finally, specify the desired opacity and the image by setting the MSVidVideoRenderer.MixerBitmapOpacity and MSVidVideoRenderer.MixerBitmap properties:

iVid.MixerBitmapOpacity = 80
iVid.MixerBitmap = iPic

Opacity is expressed as a percentage from 0 to 100. You can set all three properties at once using the MSVidVideoRenderer.SetupMixerBitmap method:

VideoControl.VideoRendererActive.SetupMixerBitmap iPic, 80, rect


TV Applications in C++ (Video Control)

This topic applies to Windows XP only.

This section describes how to host the Video Control in a C++ application based on either MFC or ATL. It contains the following articles:

  • Testing TV Hardware and Software with GraphEdit
  • Video Control Interface Hierarchy
  • Using MFC to Host the Video Control
  • Using ATL 3.0 to Host the Video Control
  • Using ATL 7.0 to Host the Video Control
  • Creating a Tune Request (C++)
  • File Playback with the Video Control (C++)
  • Receiving Video Control Events in C++
  • Receiving Video Control Events in ATL
  • Displaying Closed Captioning in C++
  • Mixing an Image Onto the Video Window in C++


Testing TV Hardware and Software with GraphEdit

This topic applies to Windows XP only.

Whenever you write a DirectShow-based application, it is generally useful to start by creating a prototype filter graph in GraphEdit. Even though GraphEdit does not use the Video Control, creating the prototype is a quick way to verify that your TV device and third-party HDTV-compatible MPEG-2 decoder are installed and working properly.

Before you can build a digital TV graph, you must register the Dynamic Link Library (proppage.dll) provided by the Platform SDK. (At the command line, type "regsvr32 [path]proppage.dll".) This DLL contains the property page needed to tune the Network Provider filter. This property page is provided only for testing purposes. Working applications should provide their own user interface.

When building a graph using GraphEdit, it is important to remember that Broadcast Driver Architecture (BDA) allows for flexibility in the "topology" of the device. For application developers, this means that the names and number of filters used to represent the tuning device may vary depending on the manufacturer or the specific card. For example, some cards may expose a demodulator as a separate filter, while others may not. In general, most cards will probably expose two or three filters for a digital filter graph: a tuner, a demodulator, and a capture filter. Likewise, the MPEG-2 decoder may or may not expose a separate filter for audio decoding.

MSTV Filter Graph

When creating this filter graph in GraphEdit, the basic rule is to manually add and connect all the filters up through the MPEG-2 Demultiplexer, and then right-click on the output pins of the Demultiplexer to render each of the streams. "Render" in this context means that GraphEdit will automatically add and connect the remaining filters needed to render the stream. It is still necessary to click on the Run button to start the graph playing.

But before starting the graph, you must first tune to a channel. Right click on the Network Provider filter, select Properties and click on the Tune Request tab. Tune to a physical channel that you know is valid. The "-1" values for minor channel and major channel simply mean to use the defaults. Once the channel is selected, the graph is ready to be put into the Run state. It must be stopped before changing the channel.

Filters in a Digital Filter Graph

BDA Network Provider: A BDA Network Provider filter is always the first filter in the graph. This particular graph has the ATSC Network Provider. Microsoft also provides Network Providers for DVB. Third parties may also provide their own Network Provider that is customized for their own broadcasts. The Network Provider configures the downstream filters for a particular tuning space, which includes information on content multiplexing, modulation, and transmission standards. This filter implements the ITuner interface, which applications use to tune the device to the specified channel or frequency.

Digital TV Tuner: This kernel-mode KsProxy-based filter represents the tuner on the hardware device. It may or may not have any application-callable interfaces, depending on the implementation of the third-party driver. This filter might also encapsulate a demodulator device.

Digital TV Capture Filter: This kernel-mode KsProxy-based filter represents the demodulator/digitizer on the hardware device. Its single output pin delivers the MPEG-2 transport stream to the MPEG-2 Demultiplexer.

MPEG-2 Demultiplexer: In a digital TV graph, the MPEG-2 demultiplexer accepts the MPEG-2 transport stream from the capture filter and demultiplexes the stream. It typically has four output pins. Its first output pin delivers raw program service information (PSI) packets to the Transport Information Filter. The second pin delivers the video stream to the MPEG-2 decoder. The third pin delivers the audio to the audio decoder, and the fourth pin delivers IP data.

BDA MPEG-2 Transport Information Filter: So that a receiver can properly acquire all the elementary streams related to a specific program and so that a receiver can tell what programs are contained in the stream, the transport stream will also contain many sets of tables that act as a catalog of information contained in the transport stream. Under direction of the BDA Network Provider, the MPEG-2 Demultiplexer delivers these tables to the Transport Information Filter, which then parses these tables and provides the information to the Network Provider so that it can control the other receiver filters and nodes in the graph. The BDA Transport Information Filter also provides interfaces to enable the Guide Store loader to extract the relevant EPG and locator information and load it into an application-provided database for later retrieval by the application.

HDTV-capable MPEG-2 Decoder: A Digital TV filter graph requires a third-party decoder that is capable of decoding High Definition Television (HDTV) video streams. Some decoder implementations may operate on both audio and video streams in the same filter, while others may have separate filters for audio and video.

Video Renderer: Two video renderers are present on Microsoft XP, the older Video Renderer and the new Video Mixing Renderer (VMR). Both have the same name in GraphEdit but the old renderer is never used by the Video Control, so the "Video Renderer" in a TV graph is always the Video Mixing Renderer. The VMR renders the video stream onto the system's video memory. It can also display an application-specified alpha-blended bitmap over the video rectangle, or mix the TV video stream with other video streams for special effects.

BDA MPE Filter: This filter extracts IP packets from the Multi-Protocol Encapsulation (MPE) stream and delivers them to IP Sink.

BDA IP Sink: This filter accepts IP packets and delivers them to the host system via Winsock, where interested applications can listen for and receive IP data streams.


Video Control Interface Hierarchy

This topic applies to Windows XP only.

Tuners, renderers, and features expose a variety of interfaces, all of which ultimately derive from the IMSVidDevice interface. The following diagram shows the inheritance hierarchy for the devices and features that are currently supported:

Video Control Interface Hierarchy

The shaded interfaces are not directly exposed by any objects. They act as base interfaces, to support polymorphism. For example, the IMSVidCtl::get_InputActive method returns an IMSVidInputDevice pointer. The returned object might be a digital tuner that exposes IMSVidTuner, or an analog tuner that exposes IMSVidAnalogTuner. You can query the returned pointer to learn more about the object.


Using MFC to Host the Video Control

This topic applies to Windows XP only.

Note This article applies to MFC version 6.0, using Microsoft® Visual C++® version 6.0.

This article shows how to create an MFC application that hosts the Video Control. To set up the project, perform the following steps.

  1. Create a new project using the MFC App Wizard. A dialog-based application without the document-view architecture is probably simplest, but that is up to you. Check the boxes for Active X Control and Automation support.
  2. Link to strmiids.lib.
  3. Add wrapper classes for Video Control and its related interfaces, as follows:
    1. From the Project menu, select Add to Project and Components and Controls.
    2. Open the Registered ActiveX Controls folder.
    3. Select MS TV Video Control and click Insert.
    4. Accept all the wrapper classes that Class Wizard proposes to create. For the CMSVidCtl class, it is a good idea to change the default file names from msvidctl.* to something else, such as msvidctl_1.*, to avoid confusion with the DirectShow include files with the same name.
  4. In Resource View, open the dialog or window form. Add the Video Control to the form by dragging its icon from the Controls toolbar.
  5. Add a data member for the control, as follows:
    1. Right click the control and select Class Wizard.
    2. Select the Member Variables tab and click Add Variable.
    3. Type a variable name for the data member.
  6. Include the following header files:

    tuner.h

    msvidctl.h

    Tuner.h defines the Tuning Model interfaces, and msvidctl.h defines the Video Control interface. You must include msvidctl.h because MFC does not provide wrapper classes for certain derived classes that you will need to use.

The DLL for the Video Control, msvidctl.dll, contains two type libraries, but MFC does not create wrapper classes for all of the objects in both libraries. Therefore, you must use a combination of techniques to access and control the various Video Control and Tuning Model objects. The following code snippets illustrate these techniques.

Create an instance of an MFC-generated wrapper class

All the COM calls are hidden. Notice that the method names in the wrapper classes are slightly different from the names generated by MIDL in the original header files.

CMSVidVideoRenderer myRenderer = m_VidCtl.GetActiveRenderer();
CRect sourceRect = myRenderer.GetSourceSize();

Create an instance of a Tuning Model COM object

Since MFC does not create any wrapper classes for the Tuning Model objects, you must create and access them using the native COM methods such as CoCreateInstance and QueryInterface.

HRESULT hr;
CComPtr<ITuningSpaceContainer> pTuningSpaceContainer;
hr = CoCreateInstance(CLSID_SystemTuningSpaces,
    NULL,
    CLSCTX_INPROC_SERVER,
    IID_ITuningSpaceContainer,
    reinterpret_cast<void**> (&pTuningSpaceContainer));
if(FAILED(hr))
{
    AfxMessageBox("Failed to create system tuning spaces object");
    return false;
}
long count = 0;
hr = pTuningSpaceContainer->get_Count(&count);
if(FAILED(hr))
{
    AfxMessageBox("Failed to get count");
    return false;
}

Obtain a derived interface from a wrapper class

MFC does not create a wrapper class for some derived interfaces, such as IMSVidTuner. To get a pointer to these interfaces, to use the m_lpDispatch member of the wrapper class, which is an IDispatch pointer, to call QueryInterface.

CMSVidInputDevice inputDevice = m_VidCtl.GetInputActive();
if (inputDevice.m_lpDispatch)
{
    // We have an active input.
    CComPtr<IMSVidTuner> myTuner;
    inputDevice.m_lpDispatch->QueryInterface(
        __uuidof(IMSVidTuner),
        reinterpret_cast<void**> &myTuner);
    if (FAILED(hr))
    {
        AfxMessageBox("Failed to QI for tuner");
        return;
    }

    // Assume pATSCTR is an IATSCTuneRequest interface pointer.
    myTuner->put_Tune(pATSCTR);
}


Using ATL 3.0 to Host the Video Control

This topic applies to Windows XP only.

This article shows how to host the Video Control using ATL 3.0. The application hosts the Video Control inside a composite control. (A composite control is a type of ActiveX object that contains other controls.) To create the application, you must perform the following steps:

  • Create the framework with the ATL AppWizard.
  • Add the composite control, using the ATL CComCompositeControl class.
  • Add the Video Control to the composite control.
  • Add code for showing the composite control.

The remainder of this article describes these steps in more detail.

Create the Framework

Create a new project using the ATL COM AppWizard. Select Executable (EXE) for the server type. Include the header file Msvidctl.h, and link to the Strmiids.lib library.

Add the Composite Control

Use the ATL Object Wizard to create a composite control. For this example, the default attributes are fine. Give the control a name; for example, MyComposite.

Add the Video Control

Use the Dialog Editor to add the Video Control to the composite control, by doing the following:

  1. Right click the dialog box.
  2. Choose Insert ActiveX Control.
  3. Select MS TV Video Control. It should appear in the list if Msvidctl.dll is registered on your system.

Also, check Visible in the dialog properties. Otherwise, the control will not be visible.

Show the Composite Control

The ATL Object Wizard creates a generic WinMain function. Inside this function, add code before the message loop that creates and displays the composite control. The following code snippet shows the code that you need to add, in bold:

extern "C" int WINAPI _tWinMain(HINSTANCE hInstance,
    HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    /* ... */

    //Create the window and show the composite control.
    AtlAxWinInit();
    HWND hWnd = ::CreateWindow(TEXT("AtlAxWin"),
        Text("Your Control's ProgID Here"),
        // Example: TEXT("MyTVApp.MyComposite")
        NULL,
        CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, NULL,
        ::GetModuleHandle(NULL), NULL);

    MSG msg;
    while (GetMessage(&msg, 0, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    /* ... */
}

Also, add a message handler for the WM_CLOSE message. In it, destroy the window and post a quit message:

LRESULT MyComposite::OnClose(
    UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    DestroyWindow();
    PostQuitMessage(0);
    return 0;
}

Now you can get a pointer to the Video Control from within the control class as follows:

CComPtr<IMSVidCtl> pVidControl;
hr = GetDlgControl(IDC_MSVIDCTL1, __uuidof(IMSVidCtl),
        reinterpret_cast<void **>(&pVidControl));


Using ATL 7.0 to Host the Video Control

This topic applies to Windows XP only.

This article shows how to host the Video Control using ATL 7.0 and Visual Studio.NET. The application hosts the Video Control inside a composite control, which is a type of ActiveX object that contains other controls. To create the application, you must perform the following steps:

  • Create the framework with the ATL AppWizard.
  • Add the composite control, using the ATL CComCompositeControl class.
  • Add the Video Control to the composite control.
  • Add code for showing the composite control.

The remainder of this article describes these steps in more detail.

Create the Framework

Create a new project and select ATL Project from the project types. In the application settings, select Executable (EXE).

Include the header file Msvidctl.h, and link to the Strmiids.lib library.

Add the Composite Control

Add a composite control class to the project:

  1. From the Project menu, choose Add Class.
  2. Select ATL Control and click Open.
  3. Give the control a name, such as MyControl.
  4. Under Options, select Composite Control. For this example, the default values for the remaining options are fine.

Add the Video Control

Use the Dialog Editor to add the Video Control to the composite control, by doing the following:

  1. Right click the dialog box.
  2. Choose Insert ActiveX Control.
  3. Select MS TV Video Control. It should appear in the list if Msvidctl.dll is registered on your system.

Also, set the Visible property to true. Otherwise, the control will not be visible.

Show the Composite Control

In your module class that derives from CAtlExeModuleT, override the PreMessageLoop method to show the control window:

class CMyControlModule : public CAtlExeModuleT< CMyControlModule >
{
public :
    HRESULT PreMessageLoop(int nCmdShow)
    {
        HRESULT hr;
        hr = CAtlExeModuleT< CMyControlModule >::PreMessageLoop(nCmdShow);
        if (FAILED(hr))
        {
            return hr;
        }

        //Create the window and show the composite control.
        AtlAxWinInit();
        HWND hWnd = ::CreateWindow(TEXT("AtlAxWin7"),
            TEXT("Your Control's ProgID Here"),
            // Example: TEXT("MyTVApp.MyComposite")
            WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION,
            CW_USEDEFAULT, CW_USEDEFAULT,
            CW_USEDEFAULT, CW_USEDEFAULT,
            NULL, NULL,
            ::GetModuleHandle(NULL), NULL);
        if (hWnd == 0)
        {
            ::MessageBox(0, TEXT("Cannot create window"), 0, MB_OK);
            return E_FAIL;
        }
        ShowWindow(hWnd, nCmdShow);
        return S_OK;
    }
};

Now you can get a pointer to the Video Control from within the control class as follows:

CComPtr<IMSVidCtl> pVidControl;
hr = GetDlgControl(IDC_MSVIDCTL1, __uuidof(IMSVidCtl),
        reinterpret_cast<void **>(&pVidControl));


Creating a Tune Request (C++)

This topic applies to Windows XP only.

It is preferable to get a preconfigured tune request from a database. However, you can construct a tune request from scratch if you know the particular network type that you want to support.

To create an ATSC tune request, do the following:

  1. Create a system tuning spaces collection.
  2. Enumerate the tuning spaces to find the ATSC tuning space.
  3. Use the ATSC tuning space to create a new tune request.
  4. Create an ATSC locator object.
  5. Set the physical channel property on the locator.
  6. Associate the locator with the tune request.
  7. Give the tune request to the Video Control.
  8. Run the Video Control.

The following example omits any error checking. In working code, you should always check HRESULT return codes.

long lChannel = 46; // Use whatever channel number you like.
HRESULT hr = S_OK;

// Create the tuning space collection.
CComPtr<ITuningSpaceContainer> pTuningSpaceContainer;
hr = pTuningSpaceContainer.CoCreateInstance(CLSID_SystemTuningSpaces,
    NULL, CLSCTX_INPROC_SERVER);

// Find the ATSC tuning space in the tuning spaces collection.
CComPtr<IEnumTuningSpaces> pEnumTuningSpaces;
CComBSTR bstrATSC(L"ATSC");
CComPtr<ITuningSpace> pTuningSpace;

hr = pTuningSpaceContainer->get_EnumTuningSpaces(&pEnumTuningSpaces);
while (S_OK == pEnumTuningSpaces->Next(1, &pTuningSpace, NULL))
{
    CComBSTR bstrTemp;
    hr = pTuningSpace->get_UniqueName(&bstrTemp);
    if (bstrTemp == bstrATSC)
    {
        break;  // Found it.
    }
    pTuningSpace = NULL;  // Release for the next loop.
}

if (pTuningSpace == NULL) // Did not find it.
{
    // Handle the error.
}

// Create an ATSC Tune Request.
CComPtr<IATSCTuningSpace> pATSCTuningSpace;
pTuningSpace.QueryInterface(&pATSCTuningSpace);
CComPtr<ITuneRequest> pTuneRequest;
hr = pATSCTuningSpace->CreateTuneRequest(&pTuneRequest);

// Create an ATSC Locator and set the physical channel.
CComPtr<IATSCLocator> pATSCLocator;
pATSCLocator.CoCreateInstance(CLSID_ATSCLocator, NULL,
    CLSCTX_INPROC_SERVER);
hr = pATSCLocator->put_PhysicalChannel(lChannel);

// Set the channel and minor channel properties on the tune request
// to -1. The network provider will set these properties after it
// tunes to the ATSC channel.
CComPtr<IATSCChannelTuneRequest> pATSCTuneRequest;
pTuneRequest.QueryInterface(&pATSCTuneRequest);
hr = pATSCTuneRequest->put_Channel(-1);
hr = pATSCTuneRequest->put_MinorChannel(-1);

// Bind the locator to the tune request.
hr = pATSCTuneRequest->put_Locator(pATSCLocator);

// Give the tune request to the Video Control.
CComVariant var(pATSCTuneRequest);
hr = pMSVidCtl->View(&var);
hr = pMSVidCtl->Run();

As this example shows, when the application builds the tune request, it must target specific network types. On the other hand, if it always gets the tune request from the database, it will function with any supported network type.


File Playback with the Video Control (C++)

This topic applies to Windows XP only.

To play a media file with the Video Control, pass the file name to the IMSVidCtl::View method:

CComVariant var(OLESTR("C:\\Example.avi"));
hr = pVidControl->View(&var);

If the method call succeeds, the active input device is the MSVidFilePlaybackDevice object, which exposes the IMSVidFilePlayback interface. (The IMSVidFilePlayback interface inherits IMSVidPlayback.) You can use this interface to seek in the file, change the playback rate, or step through the file.

The following code shows how to obtain the input device and query for the playback interface:

CComPtr<IMSVidInputDevice> pInputDevice;
HRESULT hr = pVidControl->get_InputActive(&pInputDevice);
if (SUCCEEDED(hr))
{
    CComQIPtr<IMSVidFilePlayback> pFilePlayback(pInputDevice);
    if (pFilePlayback != NULL)
    {
         /* The file playback device is the active input. Call
            IMSVidFilePlayback methods to control the device. */
    }
}

To seek, call the put_CurrentPosition method:

hr = pFilePlayback->put_CurrentPosition(200); // 2 msec

The default units are hundredths of seconds. You can change this to frames by calling the IMSVidPlayback::put_PositionMode method.

To change the playback rate, call the put_Rate method:

hr = pFilePlayback->put_Rate(2.0); // Twice normal speed.

To step forward frame-by-frame, first call get_CanStep to determine whether the source file supports frame stepping. If so, call the Step method to step forward in the file:

VARIANT_BOOL fCan;
hr = pFilePlayback->get_CanStep(VARIANT_FALSE, &fCan);
if (SUCCEEDED(hr)) && (fCan == VARIANT_TRUE))
{
    hr = pFilePlayback->Step(2);  // Step two frames.
}


Receiving Video Control Events in C++

This topic applies to Windows XP only.

In a television application, various objects send events, including the Video Control. The application can listen for these events and respond to them. For example, the Video Control sends an event when the video window is clicked or receives a keystroke.

Objects send events using COM connection points. To catch an event, the client implements an event interface. The object fires events by calling methods on that interface. For example, the Video Control sends events through the _IMSVidCtlEvents interface. The mouse-click event is _IMSVidCtlEvents::Click.

_IMSVidCtlEvents Connection Point

In COM terminology, the event interface is the outgoing interface, the object that sends the events is the source, and any object that receives events is a sink. Typically the outgoing interface is a dispinterface, so the sink must implement IDispatch. The source fires events by calling IDispatch::Invoke with the dispatch identifier (dispid) of the method.

To receive events:

  • Implement the outgoing interface.
  • Call the IConnectionPointContainer::FindConnectionPoint method to retrieve a connection point from the Video Control. Pass in the interface identifier (IID) of the outgoing interface. The FindConnectionPoint method returns a pointer to the IConnectionPoint interface.
  • Call the IConnectionPoint::Advise method to establish the connection.

The following code sets up the connection point between the client and the Video Control:

HRESULT hr;
DWORD dwCookie;
CComPtr<IMSVidCtl> m_pVideoControl; // Pointer to the Video Control.

// Query the Video Control for IConnectionPointContainer.
CComQIPtr<IConnectionPointContainer> pContainer(m_pVideoControl);
if (pContainer)
{
    // Find the connection point.
    CComPtr<IConnectionPoint> pConnectPt;
    hr = pContainer->FindConnectionPoint(DIID__IMSVidCtlEvents,
            &pConnectPt);
    if (SUCCEEDED(hr))
    {
        // Get the IUnknown pointer of the event sink, which is
        // typically the client itself.
        CComQIPtr<IUknown> pUnk;
        this->QueryInterface(IID_IUnknown, (void**)&pUnk);
        hr = pConnectPt->Advise(pUnk, &dwCookie);
    }
}

The Advise method returns a token (also called a cookie) that identifies the connection. The source object continues to fire events until the sink breaks the connection. To break the connection, call the IConnectionPoint::Unadvise method and pass in the same token:

hr = pConnectPt->Unadvise(dwCookie);


Receiving Video Control Events in ATL

This topic applies to Windows XP only.

The Video Control sends events to the client through a dispinterface, _IMSVidCtlEvents. In ATL, you can create a dispinterface event sink by deriving from the IDispEventImpl or IDispEventSimpleImpl class template. One advantage of these classes is that you do not have to implement methods for all of the events. Instead, you can implement just the ones that you are interested in receiving.

This section gives a brief summary of this process. For details, consult the ATL documentation. The example uses IDispEventSimpleImpl to catch two events from the Video Control, _IMSVidCtlEvents::Click and _IMSVidCtlEvents::StateChange.

First, include IDispEventSimpleImpl the class template in your client's inheritance list:

class ATL_NO_VTABLE CMyContainer :
    /* ... */
    public IDispEventSimpleImpl<IDC_MSVIDCTL1, CMyContainer,
        &__uuidof(_IMSVidCtlEvents)>

The first parameter is the resource ID of the video control in your form. The second parameter is the name of your composite control class. The third parameter is the IID of the event interface.

Next, define variables of type _ATL_FUNC_INFO to hold the type information for the events you want to support. Declare the variables as extern in your header file:

/* In your header file: */
extern _ATL_FUNC_INFO OnClickInfo;       // Click event.
extern _ATL_FUNC_INFO OnStateChangeInfo; // StateChange event.

/* In your source file: */
_ATL_FUNC_INFO OnClickInfo = {CC_STDCALL, VT_EMPTY, 0};
_ATL_FUNC_INFO OnStateChangeInfo = {CC_STDCALL, VT_EMPTY, 2, { VT_I4, VT_I4} };

Each _ATL_FUNCT_INFO variable specifies type information for one method in the event interface. The information consists of the calling convention (always CC_STDCALL); the return type; the number of parameters; and an array of types, one for each parameter.

Now add entries for the two events in the event sink map:

BEGIN_SINK_MAP(CMyContainer)
   SINK_ENTRY_INFO(0, __uuidof(_IMSVidCtlEvents),
       DISPID_CLICK, OnClick, &OnClickInfo)
   SINK_ENTRY_INFO(0, __uuidof(_IMSVidCtlEvents),
       dispidStateChange, OnStateChange, &OnStateChangeInfo)
END_SINK_MAP()

Define the event handler methods in your composite control class:

void __stdcall OnStateChange(MSVidCtlStateList PrevState, MSVidCtlStateList CurrState)
{
     // Call an application-defined function to update the UI.
     MyUpdateState(PrevState, CurrState);
}

void __stdcall OnClick()
{
     // Call an application-defined function to update the UI.
     MyHandleClick();
}

ATL automatically sets up the connection when it shows the window, and automatically releases the connection when it unloads the control.

Dual Interface Events

Other Video Control objects, such as devices and features, send events through dual interfaces rather than dispinterfaces. (A dispinterface is invoked only through the IDispatch::Invoke method; it does not use a vtable. A dual interface can be invoked either through the Invoke method or through the vtable.)

In ATL, you can use the IDispatchImpl class template to handle dual interface events. The following discussion describes how to receive file playback events from the MSVidFilePlaybackDevice object, using the IMSVidFilePlaybackEvent interface.

First, add the IDispatchImpl class to your inheritance list:

    public IDispatchImpl<
       IMSVidFilePlaybackEvent,  // The event interface we're sinking.
       &__uuidof(IMSVidPlaybackEvent), // The IID of the interface.
       &LIBID_MSVidCtlLib, /*wMajor =*/ 1, /*wMinor =*/ 0  // Typelib
    >

Add the IMSVidFilePlaybackEvent interface to your component's COM map:

BEGIN_COM_MAP(CMyControl)
    /* ... */
    COM_INTERFACE_ENTRY(IMSVidFilePlaybackEvent)
    /* ... */
END_COM_MAP()

If the COM map already has an entry for IDispatch, this change may cause a compile error similar to the following:

    error C2594: 'static_cast' : ambiguous conversions from
    'CMyControl::_ComMapClass *' to 'IDispatch *'

This error occurs if your control inherits IDispatch through more than one interface. You can fix this by using the COM_INTERFACE_ENTRY2 macro to select one of the inheritance branches:

    COM_INTERFACE_ENTRY2(IDispatch, IMSVidFilePlaybackEvent)

Now implement the methods that are defined by the event interface. (You do not have to implement the IDispatch or IUnknown methods.) In the case of IMSVidFilePlaybackEvent, the interface defines one event, EndOfMedia.

STDMETHODIMP EndOfMedia(IMSVidPlayback *pPlayback)
{
    /* Perform any actions. */
    return S_OK;
}

To receive events, call the AtlAdvise function on the object that fires the events.

// Class member variables
CComPtr<IMSVidFilePlayback> m_pFilePlayback;
DWORD m_dwFileSinkCP; // Holds the connection point cookie.

// Here is the code to sink the events. First, check whether the
// MSVidFilePlaybackDevice object is the active input. If it is, you
// can query it for IMSVidFilePlayback.
CComPtr<IMSVidInputDevice> pInputDevice;
HRESULT hr = pVidControl->get_InputActive(&pInputDevice);
if (SUCCEEDED(hr))
{
    m_pFilePlayback = pInputDevice; // Implicit QueryInterface.
    if (m_pFilePlayback)
    {
        // Query ourselves for the IUnknown interface.
        CComPtr<IUnknown> pUnk;
        this->QueryInterface(IID_IUnknown, (void**)&pUnk);
        // Establish the connection point.
        hr = AtlAdvise(m_pFilePlayback, pUnk,
            __uuidof(IMSVidFilePlaybackEvent), &m_dwFileSinkCP);
    }
}

Before you release the object, call AtlUnadvise to release the connection point:

if (m_pFilePlayback)
{
    AtlUnadvise(m_pFilePlayback,
        __uuidof(IMSVidFilePlaybackEvent), m_dwFileSinkCP);
    m_pFilePlayback.Release();
}


Displaying Closed Captioning in C++

This topic applies to Windows XP only.

To display closed captioning (CC), the application must activate the closed captioning feature. For analog television, the application must also active the data services feature. You can find the features by enumerating the Video Control's available features collection. To activate a feature, add it to the active features collection.

To activate the closed captioning feature, perform the following steps:

Using CoCreateInstance, create an empty features collection as an MSVidFeatures object.

Retrieve the available features from the Video Control, by calling the IMSVidCtl::get_FeaturesAvailable method.

Loop through the returned collection, comparing each feature's CLSID against the CLSID of the CC feature. With analog TV, do the same for the data services feature. Call the IMSVidDevice::get__ClassID method to obtain the CLSID of each feature.

When you find a matching feature, add it to the features collection created in Step 1. Also, query the CC feature for the IMSVidClosedCaptioning interface and store this for later use.

Set the new features collection as the Video Control's active features collection, by calling the IMSVidCtl::put_FeaturesActive method.

Perform these steps before building the graph; that is, before calling IMSVidCtl::Build or IMSVidCtl::Run. If the graph is already built, call IMSVidCtl::Decompose to tear it down, and build it again afterward.

Once the CC feature is in the active features collection, you can build the graph. Enable or disable closed captioning at any time by calling the IMSVidClosedCaptioning::put_Enable method. By default, the feature is disabled.

Note Activating the CC feature causes the Video Control to build a filter graph that is capable of receiving and displaying closed captions. Enabling the CC feature causes the captions to be displayed.

The following code example activates and enables CC. It assumes that m_pVidControl is a member variable in the control container, which holds a pointer to the Video Control's IMSVidCtl interface. The bWantDataSvc parameter specifies whether to include data services. For brevity, the example performs only minimal error checking.

HRESULT CMyContainer::ActivateCC(bool bWantDataSvc)
{
    HRESULT hr = S_OK;
    _ASSERT(m_pVidControl != NULL);

    // Get the available features.
    CComPtr<IMSVidFeatures> pFeatures;
    hr = m_pVidControl->get_FeaturesAvailable(&pFeatures);
    if (SUCCEEDED(hr))
    {
        // Create an empty features collection.
        CComPtr<IMSVidFeatures> pActiveFeatures;
        hr = pActiveFeatures.CoCreateInstance(__uuidof(MSVidFeatures),
            NULL, CLSCTX_INPROC_SERVER);

        // Enumerate the features and look for CC.
        long lCount = 0;
        pFeatures->get_Count(&lCount);
        for (long ix = 0; ix < lCount; ix++)
        {
            CComVariant var(ix);
            CComPtr<IMSVidFeature> pFeature;
            GUID clsid;
            hr =  pFeatures->get_Item(var, &pFeature);
            hr = pFeature->get__ClassID(&clsid);
            if (clsid == __uuidof(MSVidClosedCaptioning))
            {
                // Found CC, add it to the collection.
                hr = pActiveFeatures->Add(pFeature);
                CComQIPtr<IMSVidClosedCaptioning> pCC(pFeature);
                if (pCC) {
                    hr = pCC->put_Enable(VARIANT_TRUE);
                }
            }
            else if (bWantDataSvc && clsid == __uuidof(MSVidDataServices))
            {
                hr = pActiveFeatures->Add(pFeature);
            }
        }
        // Set this collection as the active features collection.
        hr = m_pVidControl->put_FeaturesActive(pActiveFeatures);
    }
    return hr;
}


Mixing an Image Onto the Video Window in C++

This topic applies to Windows XP only.

This section describes how to display an alpha-blended image over the Video Control's video image. Internally, the Video Control uses the Video Mixing Renderer filter (VMR).

Mixing an IPictureDisp Object

In C++, you can specify the image either as an IPictureDisp object or as a bitmap. The IPictureDisp object is designed for Automation clients, and it is generally easier to work with a bitmap in C++. When you capture an image from the Video Control, however, it returns an IPictureDisp object. Therefore, the first example shows how to use the captured image as the mixing image. The result is to show a "snapshot" of the video in a corner of the window, while the video continues to play in the background.

First, submit a tune request and call the Video Control's IMSVidCtl::Run method. (For more information, see Tuning with the Video Control.)

To capture the image:

Call the IMSVidCtl::get_VideoRendererActive method. This method returns a pointer to the IMSVidVideoRenderer interface on the video renderer device.

Call the IMSVidVideoRenderer::Capture method. This method returns an IPictureDisp object, which contains the image.

Now you can use the IPictureDisp object as the VMR's mixer image, by calling the IMSVidVideoRenderer::SetupMixerBitmap method. The method takes the following parameters:

  • The IPictureDisp pointer.
  • The desired opacity, expressed as an integer from 0 to 100.
  • The position of the image on the video window, specified as an IMSVidRect interface.

The IMSVidRect interface is an Automation-compatible wrapper for a rectangle. The following example retrieves a rectangle by calling IMSVidVideoRenderer::get_MixerBitmap, but then overrides the dimensions of the rectangle. It then captures an image and mixes it onto the video window. For brevity, the example omits any error checking.

CComPtr<IMSVidCtl> m_pVideoControl;  // Video Control
CComPtr<IMSVidVideoRenderer> pVideo; // video renderer device
CComPtr<IPictureDisp> pPic;          // picture object
CComPtr<IMSVidRect> pRect;           // Automation-compatible rectangle
RECT rcWin;

/* Build and run the filter graph (not shown). */

// Capture the image.
hr = m_pVideoControl->get_VideoRendererActive(&pVideo);
hr = pVideo->Capture(&pPic);

// Set the rectangle to 1/4 of the window.
hr = pVideo->get_MixerBitmapPositionRect(&pRect);
::GetWindowRect(GetDlgItem(IDC_MSVIDCTL1), &rcWin);
hr = pRect->put_Width(rcWin.right / 2);
hr = pRect->put_Height(rcWin.bottom / 2);
hr = pRect->put_Top(0);
hr = pRect->put_Left(0);

// Set the mixer bitmap.
long lOpacity = 80;  // 0 = transparent, 100 = opaque
hr = pVideo->SetupMixerBitmap(pPic, lOpacity, pRect);

The position rectangle defaults to the entire video control window. If you don't want to specify the rectangle, you can use the IMSVidVideoRenderer::put_MixerBitmap and IMSVidVideoRenderer::put_MixerBitmapOpacity methods:

hr = pVideo->put_MixerBitmap(pPic);
hr = pVideo->put_MixerBitmapOpacity(lOpacity);

Mixing a Bitmap

In C++, you can also mix a bitmap that is specified as a DirectDraw surface or as a handle to a GDI object. To do so, use the IMSVidVideoRenderer::put__MixerBitmap method. This method acts as a pass-through to the VMR's IVMRMixerBitmap::SetAlphaBitmap method. As an alternative, you can use the IMSVidVideoRenderer::get__MixerBitmap method to obtain the VMR's IVMRMixerBitmap interface and call SetAlphaBitmap directly.

For more information, see Displaying an Application-Supplied Bitmap on the Composited Image. The example shown here is modified from the example code in that topic.

The following example loads a bitmap resource and displays it in the upper-left corner of the video window, blended at 50% opacity. For brevity, the example omits any error checking.

HRESULT ShowBitmap(IMSVidCtl *pVideoControl, WORD nID)
{
    CComPtr<IVMRMixerBitmap> pVmrBitmap;
    CComPtr<IMSVidVideoRenderer> pVideo;
    HRESULT hr = pVideoControl->get_VideoRendererActive(&pVideo);
    hr = pVideo->get__MixerBitmap(&pVmrBitmap);
    if (SUCCEEDED(hr))
    {
        RECT rc;
        HBITMAP hBitmap = LoadBitmap(hInst, MAKEINTRESOURCE(nID));
        ::GetWindowRect(GetDlgItem(IDC_MSVIDCTL1), &rc);
        hr = MixImage(hWnd, pVmrBitmap, hBitmap, rc.right, rc.bottom);
    }
}

HRESULT MixImage(HWND hwndApp, IVMRMixerBitmap* pBmp, HBITMAP hbm,
  long cx, long cy)
{
    HRESULT hr;
    BITMAP bm;
    HBITMAP hbmOld;
    HDC hdc = GetDC(hwndApp);
    HDC hdcBmp = CreateCompatibleDC(hdc);
    ReleaseDC(hwndApp, hdc);

    GetObject(hbm, sizeof(bm), &bm);
    hbmOld = (HBITMAP)SelectObject(hdcBmp, hbm);

    VMRALPHABITMAP bmpInfo;  // Holds information about the bitmap.
    ZeroMemory(&bmpInfo, sizeof(bmpInfo));
    bmpInfo.dwFlags = VMRBITMAP_HDC; // Tells the VMR we are using an HDC.
    bmpInfo.hdc = hdcBmp;

    // The source rectangle is the entire bitmap.
    SetRect(&bmpInfo.rSrc, 0, 0, bm.bmWidth, bm.bmHeight);

    // The target rectangle is the upper left corner of the video image,
    // expressed as a percentage of the image.
    bmpInfo.rDest.left = 0.f;
    bmpInfo.rDest.top = 0.f;
    bmpInfo.rDest.right = static_cast<float>(bm.bmWidth) /
                          static_cast<float>(cx);
    bmpInfo.rDest.bottom = static_cast<float>(bm.bmHeight) /
                           static_cast<float>(cy);
    bmpInfo.fAlpha = 0.5f; // Set the alpha to 50%
    hr = pBmp->SetAlphaBitmap(&bmpInfo);

    // Clean up.
    DeleteObject(SelectObject(hdcBmp, hbmOld));
    DeleteDC(hdcBmp);
    return hr;

}


DVD Applications in Visual Basic (Video Control)

This topic applies to Windows XP Service Pack 1 only.

Microsoft® DirectShow® provides several objects to control DVD playback. These include the MSWebDVD object, the MSVidWebDVD object, and the DVD Navigator filter. The recommended object is the MSVidWebDVD object, which provides all the capabilities of the MSWebDVD object, but is used in tandem with the Video Control which provides a range of additional abilities.

All DVD control objects actually use the DVD Navigator filter behind the scenes to access and control the DVD player. But unlike DVD Navigator filter, the MSVidWebDVD object handles mouse clicks and automates graph building. And unlike MSWebDVD, MSVidWebDVD is associated with the Video Control, to allow digital and analog television tuning as well as broadcast IP data services, all in the same screen space. This document describes the Microsoft Visual Basic® control of this object.

The MSVidWebDVD object operates in tandem with the MSVidCtl Microsoft ActiveX® control (also called the Video Control), and together they provide analog and digital television tuning, broadcast IP data services, file playback, and DVD playback for video or karaoke discs. MSVidCtl and MSVidWebDVD can be embedded in a Windows form or Web page, and can be controlled with Visual Basic, HTML scripting, or C++ in Microsoft Foundation Class or ATL forms.

To create the MSVidWebDVD object, you need Microsoft Windows XP and a DVD decoder installed on your computer. Currently, most codecs are suitable for either DVD play or digital television tuning, but not both. You cannot simultaneously register multiple codecs to handle both, so you may have to unregister existing codecs to register a DVD-capable codec that works with the Video Mixing Renderer. Although there is not now a method to determine if your codec is correct, a good rule of thumb is to use only Windows Hardware Quality Labs (WHQL) certified codecs. If you register a new video codec, be sure to uninstall the older codec by using regsvr32 with the /u command line switch.

This section contains the following topics:

  • Creating the MSVidWebDVD Object
  • Controlling Playback
  • Menus and Buttons
  • Audio Streams: Controlling Spoken Language
  • Subpicture Streams: Controlling Subtitles
  • Angle Blocks
  • Parental Management
  • Text Strings
  • DVD Error Handling

See Also

  • DVD Basics
  • MSVidCtl Object


Creating the MSVidWebDVD Object

This topic applies to Windows XP Service Pack 1 only.

This article describes how to instantiate the MSVidWebDVD object and associated objects for DVD playback.

NOTE Neither Windows XP nor the DirectX SDK offers an MPEG-2 decoder for writing DVD applications. Many DVD hardware providers offer hardware or software decoding options, and many DVDs come packaged with a DVD decoder.

The Video Control's DVD helper object is MSVidWebDVD. The MSVidWebDVD object is used only as a DVD controller—it is not represented on the screen—and it is instantiated programmatically. One other object, MSVidWebDVDAdm, is also used for some DVD tasks and is also instantiated in code.

The following list summarizes the steps necessary to create the objects for viewing DVD content in a Windows form or HTML page. Details follow the list.

  1. Add the MSVidCtl object to your form.
  2. Add features, such as closed captions, to MSVidCtl.
  3. Build the filter graph.
  4. Instantiate the MSVidWebDVD and MSVidWebDVDAdm objects.
  5. Run the graph.

First, create a Visual Basic project and add the MS Video Control 1.0 Type Library to your project as a reference and a component. See DVD Applications in Visual Basic (Video Control) for system requirements. Draw the MSVidCtl object, also called the Video Control, onto your form and give it a name, for example "oVideoControl".

If you wish to support closed captions, you can programmatically add the closed captioning feature to MSVidCtl. The following code shows a subroutine to add closed captioning:

Private g_msCC as MSVidClosedCaptioning
Sub AddCC()
   Dim oFeature As IMSVidFeature
   Dim oFeatureColl As New MSVidFeatures
   'Closed captioning GUID
   Const CLSID_CC = "{7F9CB14D-48E4-43B6-9346-1AEBC39C64D3}"

   For Each oFeature In oVideoControl.FeaturesAvailable
       If oFeature.ClassID = CLSID_CC Then
           oVideoControl.FeaturesActive.Add oFeature
           oFeatureColl.Add oFeature
           Set g_msCC = oFeature
       End If
   Next oFeature
End Sub
' Enable or disable closed captioning by setting
' g_msCC.Enable = True or False. May be done during playback.

Finally, build the filter graph and create the MSVidWebDVD and MSVidWebAdm objects. These objects are used to control most DVD functions. The MSVidWebDVD object can be created either by iterating through the MSVidCtl object's input types and searching for the DVD player, or by directly calling the View command on the MSVidCtl object, specifying the DVD player as the input device. This second, shorter method automates the iteration and makes accessing the DVD player quite simple.

The following code illustrates the short way to create the MSVidWebDVD object and the MSVidWebAdm object. The View, Build, and Run commands automate graph creation. The AddCC subroutine called is the one shown in the previous example.

Option Explicit
' Create the DVD and Adm objects. Be sure to create the DVD using
' WithEvents to access object-specific events.
Dim WithEvents oVidWebDVD As MSVidWebDVD
Dim oVidWebAdm As MSVidWebDVDAdm

' Build the graph to prepare for playback. Does not start playback.
Sub BuildGraph()
   ' First insert the DVD Navigator filter.
   oVideoControl.View ("DVD:")

   ' Then enable closed-captioning feature.
   ' All features must be added before Build or Run methods.
   Call AddCC

   ' Next build the graph.
   oVideoControl.Build

   ' Finally, instantiate the control objects.
   Set oVidWebDVD = oVideoControl.InputActive
   Set oVidWebAdm = oVidWebDVD.DVDAdm
 End Sub

' Start playback from Play button.
Sub cmdRun_Click()
   oVideoControl.Run
End Sub

See Also

  • Displaying Closed Captioning in Visual Basic
  • DVD Applications in Visual Basic (Video Control)


Controlling Playback

This topic applies to Windows XP Service Pack 1 only.

In general, the MSVidCtl object controls the larger tasks, such as acquiring the DVD player, handling display, and controlling the graph, while the MSVidWebDVD object typically handles specific DVD control, such as disc navigation and playback. However, certain methods exist in both objects. Such methods should only be accessed through the MSVidCtl object. Accessing these duplicate methods using the MSVidWebDVD object will cause an error:

  • View
  • Stop
  • Run
  • Pause

Playback speed, on the other hand, is controlled using the Rate property on the MSVidWebDVD object.

Because DVD authoring design is not enforced, you may find that your application will not work perfectly with all discs. For example, some discs have a single title that holds a complete movie made of chapters, while others may have a single movie broken across several titles. Discs are designed to work specifically with their own menu screens, not to make navigation or control easy for the Video Control. However, most MSVidWebDVD actions, such as navigating through titles, chapters, menu buttons, or screens, will work with most discs.

In addition, you cannot depend on a DVD to include text strings or parental levels appropriately, it is not possible to determine programmatically if a method or property can be used at any particular time, and there can be a lag between UOP setting changes and UOP messages. Therefore, rigorous error trapping is essential to designing a robust application. Ideally, applications will derive the most benefit from using the MSVidWebDVD object with custom-designed DVDs, such as educational or reference discs, where you can predict or control the disc design. For these discs, MSVidWebDVD presents a simple-to-use, full-featured object that allows you to quickly and easily design a complex interface for your DVDs.

See Also

  • DVD Applications in Visual Basic (Video Control)


Menus and Buttons

This topic applies to Windows XP Service Pack 1 only.

Menus are the full-page navigational splash screens designed by the DVD author that occur at the beginning of the DVD, and may appear elsewhere in the disc. Buttons are the selection items on the menu screens, rather than the buttons in the hosting form or Web page.

The MSVidWebDVD object automatically handles menu commands when the user clicks on the on-screen buttons with the mouse. An application does not need to do anything to implement basic mouse support. But an application can override this automatic mouse handling at any time in order to cause additional actions to take place when a user clicks on a menu button. For example, you could cause certain text or images to be displayed on a Web page depending on which button the user clicks. To implement custom mouse handling, use the MSVidWebDVD menu-related methods such as SelectAndActivateButton and ButtonAtPosition.

The MSVidWebDVD also offers a set of methods (for example, SelectUpperButton) which allow you to display an image map on your form representing a DVD remote control, with buttons that move the current button selection up, down, right and left. These buttons are referred to as "directional" or "relative" buttons in the documentation.

See Also

  • DVD Applications in Visual Basic (Video Control)


Audio Streams: Controlling Spoken Language

This topic applies to Windows XP Service Pack 1 only.

A DVD-Video disc can have up to eight audio streams, numbered zero through seven, each with up to six discrete channels. Audio streams specify a standard movie soundtrack, a director's comments soundtrack, alternate language soundtracks, or other audio features. Only one audio stream at a time can be enabled. Discs are generally authored with default audio streams, but an application can enable the user to see all the streams that are available for a given title, and select the one in the language they prefer.

Unfortunately, there is no way to determine the content of an audio stream programmatically; an audio stream may contain a simple soundtrack, director's comments, or other audio. So, for instance, there may be three audio streams listed as English language, but one may be director's comments, another may be a simple soundtrack in English, and the third may be a multi-speaker soundtrack.

Here are the basic steps to display a list of audio streams for user selection:

  1. Determine the number of streams available for a specified title.
  2. Iterate through the streams and retrieve the stream attributes for each.
  3. Check to see if the stream is enabled.
  4. Populate a Select box or other user interface control with valid streams to enable the user to select the preferred stream.

(Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.)

The following code fills a list box (lboAudioStream) with a list of available languages:

lboAudioStream.Clear
For i = 0 To oVidWebDVD.AudioStreamsAvailable - 1
   If oVidWebDVD.IsAudioStreamEnabled(i) Then
      lboAudioStream.AddItem oVidWebDVD.AudioLanguage(i), i
   End If
Next i
lboAudioStream.Selected(oVidWebDVD.CurrentAudioStream) = True

The following code changes the audio stream when the user clicks on the list box:

Private Sub lboAudioStream_Click()
   oVidWebDVD.CurrentAudioStream = lboAudioStream.ListIndex
End Sub

See Also

  • DVD Applications in Visual Basic (Video Control)


Subpicture Streams: Controlling Subtitles

This topic applies to Windows XP Service Pack 1 only.

Subpictures carry visual elements in the picture, such as subtitles and button highlights. Although subpicture streams frequently carry text, it should not be confused with closed captioning, which is added as a feature (see Creating the MSVidWebDVD Object for details). Subpicture stream numbers range from 0 through 31, plus number 63 for a muted low rate bitstream.

Each subpicture stream has an associated language property. This language property is the only information that can be obtained from an arbitrary stream. You can specify subpicture stream language independently of the audio track, so you may have an English soundtrack with French subtitles, for example. Only one subpicture stream at a time can be specified.

Unfortunately, there is no way programmatically to determine the kind of information that a subpicture stream contains, beyond its language. So, for instance, there may be an English stream and a French stream, but the English stream contains audio subtitles while the French stream contains only subtitles for onscreen text.

Here are the basic steps to display a list of subpicture stream languages for user selection:

  1. Determine the number of streams available for a specified title.
  2. Iterate through the streams and retrieve the language for each.
  3. Check to see if the stream is enabled.
  4. Populate a Select box or other user interface control with valid streams to enable the user to select the preferred stream.

(Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.)

The following code fills a list box (lboSubpicture) with the currently available subpicture streams:

lboSubpicture.Clear
For i = 0 To oVidWebDVD.SubpictureStreamsAvailable - 1
   If oVidWebDVD.IsSubpictureStreamEnabled(i) Then
      lboSubpicture.AddItem oVidWebDVD.SubpictureLanguage(i), i
   End If
Next i
lboSubpicture.Selected(oVidWebDVD.CurrentSubpictureStream) = True

The following code changes the subpicture stream when the user clicks the list box:

Private Sub lboSubpicture_Click()
   oVidWebDVD.CurrentSubpictureStream = lboSubpicture.ListIndex
End Sub

The following text toggles the subpicture stream on and off with a checkbox.

Private Sub chkCC_Click()
   chkSubpicture.SubpictureOn = CBool(chkSubpicture)
End Sub

See Also

  • DVD Applications in Visual Basic (Video Control)


Angle Blocks

This topic applies to Windows XP Service Pack 1 only.

An angle block usually denotes a video segment that was shot from more than one camera angle. There can be up to nine angles in an angle block, numbered from 1 through 9. When the DVD Navigator filter first enters an angle block, it sends your application an EC_DVD_ANGLES_AVAILABLE event notification with the number of angles in lParam1. A disc can be authored to automatically show a menu for available angles when it enters an angle block, but generally an application must determine the number of angles available and offer the user a way to select one.

The AnglesAvailable property lists the total number of angles available within the whole title, not the number of angles available at the time of the call. Thus, a call to AnglesAvailable might return a value of 9, when in fact there may only be 6 angles available in the current angle block, and 3 different angles available in the next angle block.

Angle numbers are not unique, but ordinal, so in a title of 9 angles, if block A has 6 angles and block B has 3 different angles, block A angles will be numbered 1–6, and block B angles will be numbered 1–3 (not 7–9).

Setting CurrentAngle to a number higher than the currently available highest angle will not cause an error, but merely set the currently viewed angle to the highest currently available angle. However, the angle number you set will be retained in the CurrentAngle property, and when (if) that angle does become available, the player will switch to that angle. Setting CurrentAngle to a number higher than the number of angles in the current title (returned by AnglesAvailable) will cause an error.

The following code shows how to populate the list box lboAngles with currently available angles, and how to enable or disable it as appropriate. It occurs within the DVDNotify event's Select Case block. For more information on handling disc events, see MSVidWebDVD Events.

Case EC_DVD_ANGLE_CHANGE
   lboAngles.Clear
   For i = 1 To oVidWebDVD.AnglesAvailable
      lboAngles.AddItem "Angle " & i
   Next i
Case EC_DVD_ANGLES_AVAILABLE
   lboAngles.Enabled = lParam1

The following text shows how to handle a click on the lboAngles list box to change the viewing angle:

Private Sub lboAngles_Click()
   ' Angle list is 1-based!
   oVidWebDVD.CurrentAngle = lboAngles.ListIndex + 1
End Sub

See Also

  • DVD Applications in Visual Basic (Video Control)


Parental Management

This topic applies to Windows XP Service Pack 1 only.

Any title or portion of a title on a disc allows eight parental management levels (PMLs), one through eight, with eight being the most restrictive. The idea is to provide a way of preventing children from viewing certain content without adult consent. However, there is no requirement that these levels be accurately set, nor is there any direct correlation between these values and the Motion Picture Association of America (MPAA) film ratings, and you cannot rely on DVDs to have parental levels set predictably or accurately.

Disc parental permissions may also be set dynamically, in which case the application must have enabled notification of parental level change using NotifyParentalLevelChange. Enable notification immediately upon running the movie, as parental levels are sometimes changed during the FBI warning section of the disc.

DVD authors have two ways to set the parental levels on a disc. One is through the video title set information. This automatically stops playback without allowing the user to override the settings if a more restrictive parental level is encountered.

The second method sends parental level change notifications to the application, which must then decide what to do. The DVD Navigator filter sends an EC_DVD_PARENTAL_LEVEL_CHANGE message when it encounters PMLs on the disc. By default, it does nothing else. However, if NotifyParentalLevelChange has been set to True, playback will be halted until AcceptParentalLevelChange is called to accept or reject the new level. For more information on handling disc events, see MSVidWebDVD Events.

Parental level is returned by the player as a two-byte value consisting of a series of bit flags indicating whether or not a DVD is playable by a particular parental level. The low byte of the return value is ignored, so the value 1111111100000000 would become 11111111. As an example, a return value of 11100000 (after the low byte has been removed) indicates a disc is playable by a parental level 6 and above. It is possible for all bits to be set to zero, in which case parental levels must be disabled using SelectParentalLevel to watch the movie.

The following code illustrates a message box popup that handles a temporary parental management level message. It is part of the Select Case block that handles DVDNotify event messages, and assumes NotifyParentalLevelChange has been set to True.

Private Sub ovidwebdvd_DVDNotify(ByVal lEventCode As Long, _
                ByVal lParam1 As Variant, ByVal lParam2 As Variant)
   Select Case lEventCode
      If Not (2 ^ (oVidWebDVD.PlayerParentalLevel + 7) And lParam1) Then
         Dim strPassword As String
         strPassword = InputBox("The disc has encountered restricted_
             material. Please enter your password", "Restricted title")
         oVidWebDVD.AcceptParentalLevelChange True, "", strPassword
      End If
   End Select
End Sub

See Also

  • DVD Applications in Visual Basic (Video Control)


Text Strings

This topic applies to Windows XP Service Pack 1 only.

DVD discs, especially karaoke discs, may contain a database of text information to supplement the video or audio content. Such text on karaoke discs might include song titles, artist names, record labels, and so on. Versions of this text can be present in more than one language. These strings are optional; discs are not required to have them. If present they are organized in a way that closely mirrors the logical hierarchy of the DVD volume. Each string is preceded by a number that identifies what part of the disc structure it belongs to or gives some clue as to the content of the string. Text strings do not contain the on-screen lyrics for karaoke discs, nor do they currently contain chapter or title names or information for movie DVDs.

There are two basic types of text strings: structure identifiers and content strings. Types with a value of 0x01 through 0x20 are structure identifiers. They are empty strings; the numerical code is used to identify the logical structure to which any following content strings belong. This structure corresponds very closely to the logical structure of DVD disc contents: volume, title, chapter, and so on. The remaining types identify content strings that hold information that may be displayed to the viewer in a user interface. The exact way in which content strings are used is not closely defined, so DVD authors might use them in various ways.

DVD text strings are currently used almost exclusively on karaoke discs, and these discs mostly use the 0x01 and 0x02 structure identifiers and the 0x30 type content string. But it is reasonable to assume that as time goes by, (1) more types of DVD-Video discs will contain text strings and (2) these strings will be organized in more complex ways in order to provide fuller descriptions of disc contents.

The following code shows how to determine the number of text string language blocks on the disc, and display the languages available in a list box lboTextLanguages. For more information on LCIDs and primary language IDs, see LanguageFromLCID

Function GetTextLanguages()
   Dim numLangs As Long, lPrimaryLang As Long
   Dim j As Long, lLCID As Long
   Dim strLanguage As String

   ' Get the number of text blocks.
   numLangs = oVidWeboVidWebDVD.DVDTextNumberOfLanguages()
   For j = 0 To numLangs - 1
      'get the locale identifier for the language block
      lLCID = oVidWebDVD.DVDTextLanguageLCID(j)

      ' Get the primary language ID from the LCID.
      lPrimaryLang = lLCID And &H3FF

      ' Get the human-readable string from the primary language ID.
      strLanguage = oVidWebDVD.LanguageFromLCID(lPrimaryLang)

      ' Add it to the list box.
      lboTextStrings.AddItem strLanguage
   Next j
End Sub

The following test code demonstrates how to enumerate the strings and examine the text string type. It enters the results into the list box lboStringTypes so you can see how the numeric string types are used to organize the content strings. A real application would probably create its own data structure to hold the strings, or else would display them in a more useful way for the viewer.

Function GetTextStrings(lLanguage)
' lLanguage is the 0-based index for the language block.

Dim numStrings As Long
Dim stringType As DVDTextStringType
Dim j As Integer

numStrings = oVidWebDVD.DVDTextNumberOfStrings(lLanguage)

For j = 0 To numStrings - 1
   stringType = oVidWebDVD.DVDTextStringType(lLanguage, j)

  If (stringType > &H20) Then 'There is actually some text to read here
     lboTextStringTypes.AddItem stringType & ": " & oVidWebDVD.DVDTextString(lLanguage, j)
  Else ' It's a node indicating what level of the volume structure.
       '   the following strings will apply to
     lboTextStringTypes.AddItem stringType
  End If
Next j

End Function

DVD Text String Types

This topic applies to Windows XP Service Pack 1 only.

The following tables list a subset of the DVD text string types. All types with a value 0x20 and below are empty strings that merely indicate the node level in the disc's content data structure. The other strings are content strings. Most title and song names are type 0x30. The types in the Title, SubTitle and Original categories help to further identify the particular genre. The exact meaning and intended use of these categories is defined in a public document that can be downloaded from the DVD Forum's Web site.

See Also

  • DVD Applications in Visual Basic (Video Control)

Structure Identifiers

Volume | 0x01 | Indicates that the strings that follow pertain to the DVD volume.
Title | 0x02 | Indicates that the strings that follow pertain to a title.
ParentalID | 0x03 | Indicates that the strings that follow pertain to a particular parental ID.
Chapter | 0x04 | Indicates that the strings that follow pertain to a chapter.
Cell | 0x05 | Indicates that the strings that follow pertain to a cell (typically consisting of one scene from a movie).

Stream Identifiers

Audio | 0x10 | Indicates that the strings that follow pertain to an audio stream.
Subpicture | 0x11 | Indicates that the strings that follow pertain to a subpicture stream.
Angle | 0x12 | Indicates that the strings that follow pertain to an angle block.

Audio Channel Identifiers

Channel 0x20 Indicates that the strings that follow pertain to one channel in an audio stream.

General Content Strings

Name | 0x30 | The most common identifer for title names, chapter names, song names, and so on.
Comments | 0x31 | General comments about the title, chapter, song, and so on.

Title Content Strings

Series | 0x38 | Additional information about the title, chapter, song, and so on.
Movie | 0x39 | Additional information about the title or chapter if this is a movie.
Video | 0x3a | Additional information about the title or chapter if this is a video.
Album | 0x3b | Additional information about the title or chapter if this is an album.
Song | 0x3c | Additional information about the title or chapter if this is a song.
Other | 0x3f | Additional information about the title or chapter if this belongs to some other genre or category.

Secondary Title Content Strings

Series | 0x40 | Additional information about the title, chapter, song, and so on.
Movie | 0x41 | Additional information about the title or chapter if this is a movie.
Video | 0x42 | Additional information about the title or chapter if this is a video.
Album | 0x43 | Additional information about the title or chapter if this is an album.
Song | 0x44 | Additional information about the title or chapter if this is a song.
Other | 0x45 | Additional information about the title or chapter if this belongs to some other genre or category.

Original Content Strings

Series | 0x48 | Additional information about the title, chapter, song, and so on.
Movie | 0x49 | Additional information about the title or chapter if this is a movie.
Video | 0x4a | Additional information about the title or chapter if this is a video.
Album | 0x4b | Additional information about the title or chapter if this is an album.
Song | 0x4c | Additional information about the title or chapter if this is a song.
Other | 0x4f | Additional information about the title or chapter if this belongs to some other genre or category.

Other Info Content Strings

Other Scene | 0x50 | Additional information about an alternate scene in a movie title or chapter.
Other Cut | 0x51 | Additional information about an alternate cut in a movie title or chapter.
Other Take | 0x52 | Additional information about an alternate take in a movie title or chapter.


DVD Error Handling

This topic applies to Windows XP Service Pack 1 only.

Error handling is crucial in DVD applications; most functions are only valid if the disc has enabled specific features or in specific domains. Visual Basic only returns the decimal equivalent of the first sixteen bits of error codes sent by DirectShow or Windows as the Err.Number value. The low 8 bits of this value must be parsed out and compared to standard DirectShow, DirectX, or Windows error messages to provide a comprehensive error management scheme.

The following code shows how to parse out the low 8 bits of an error code:

Private Sub Command1_Click()
   On Error GoTo Command1_Err

   ' Subroutine here...

   Exit Sub
Command1_Err:
   Dim LOWORD As Long
   Dim HIWORD As Long
   ' Parse out Low and high 8 bit values.
   GetHiLoWord Err.Number, LOWORD, HIWORD
   ' Display decimal and hex values.
   MsgBox "Error number " & vbCrLf & "Decimal: " & LOWORD & _
   vbCrLf & "Hex: " & Hex(LOWORD)
   Resume Next
End Sub

Function GetHiLoWord(lparam As Long, LOWORD As Long, HIWORD As Long)
' Parses out low and high 8 bits from 16-bit lparam variable.
   ' This is the LOWORD of lParam:
   LOWORD = lparam And &HFFFF&
   ' This is the HIWORD of lParam:
   HIWORD = lparam \ &H10000 And &HFFFF&
   gethiloword = 1
End Function

As part of error trapping, it is important to check for disabled user operations with the UOPValid method. This method checks to see if the disc has enabled or disabled certain method or property calls. However, it is important to realize that UOPValid only checks to see if the DVD author has specifically disabled an action; it does not indicate whether checking the property or performing the method is normally valid at the current time. Error trapping should handle attempts to perform an action not valid for the current domain or time.

An additional source of unexpected errors stems from the fact that the DVD Navigator filter only sends messages every 1/2 second. Therefore, it is possible that domain or UOP changes may have occurred without notification yet being sent. Attempting to perform an action that has been disabled, or in the previous domain, is a common cause of errors that should be trapped.

For more information on error codes, as well as how Visual Basic handles them, see Error and Success Codes.

See Also

  • Error and Success Codes
  • MSVidWebDVD.UOPValid


The Microsoft Unified Tuning Model

This section describes the purpose of the Microsoft Unified Tuning Model objects, and their relationships. This section contains the following topics.

  • Overview of the Tuning Process
  • Sequence of Operations in the Tuning Process
  • Tuning Spaces
  • Tune Requests
  • Locators
  • Components
  • Getting Program Information
  • Default Tuning Spaces

See Also

  • Microsoft Unified Tuning Model C++ Reference
  • Microsoft Unified Tuning Model Visual Basic Reference


Overview of the Tuning Process

The Unified Tuning Model enable applications to use a standard procedure for tuning to any program on any type of network using any kind of compatible device. When an application uses the tuning model to perform tuning, it will automatically work with any new network types that may be supported in the future, either by Microsoft or by third parties such as cable or satellite providers.

The following diagram shows the components that are involved in the tuning process:

The Video Control is an ActiveX control that builds and controls the filter graph. For more information, see Using the Video Control. The exact filters that appear in the graph depend on the underlying hardware. For more information, see Microsoft TV Technologies Internals.

Important The Video Control is available only for Windows XP. With DirectX, you can use tuning model objects to create analog and digital TV applications for Windows 98SE, Windows 2000 and Window Me, but without the benefit of the Video Control. For those platforms, the application must build the filter graph, as described in Writing Digital TV Applications with DirectX.

The application tunes to a program by submitting a tune request object to the Video Control (or to the Network Provider filter). The recommended way for the application to get tune requests is to create a tune request database, also called a guide store. A guide store contains information about programs that can be displayed to the end-user, along with network-specific tuning information for the tuning hardware.

Third parties can also provide a software component called a guide store loader, which populates a guide store using service information found in the transport stream. A guide store could also be populated using information downloaded from the Web or some other source.

The following illustration shows the general relationship among the Tuning Model objects. These objects are described in the following sections. The COM interfaces for C++ are also shown; for Visual Basic, the application invokes methods and properties on the object.

Tuning Model objects

The System Tuning Spaces object contains a collection of tuning spaces. Each tuning space represents a different network type. A tuning space is used to create tune request objects, which contain the information needed to tune to a program. Locator objects contain additional information about the signal. The tuning space may contain a default locator, which is used to locate the default transport stream within the multiplex. The tuning space object, the tune request object, and the locator object are all network-specific. Separate objects are provided for ATSC, DVB, analog television, and other network types.

A program contains one or more elementary streams. Each elementary stream is called a component, and is described by its component type, such as audio or video. Some components may be mutually exclusive. For example, a program might contain two audio streams in different languages. A tuning space can have a list of preferred component types. If so, these are used to select the default components from the stream. An application can override the defaults based on the user's preferences. For example, it might choose a secondary audio stream in another language.


Sequence of Operations in the Tuning Process

Tuning information is always contained in a tune request object. The application or the Video Control submits the tune request to the Network Provider. Tuning occurs in two general stages, locating and acquisition.

Locating the Signal

The Network Provider passes the tune request to the BDA MPEG-2 Transport Information Filter (TIF). The TIF fills in the information that the tuner needs to locate the signal, such as the carrier frequency. The tune request may or may not have a locator already attached to it. If not, the TIF creates the default locator for the tuning space. The TIF might update the locator with additional information, such as the TSID or network ID.

The Network Provider then tunes the BDA tuner to the correct frequency, and sets any other properties that are needed by the tuner, such as forward error correction (FEC) rates. The tuner passes the signal to the BDA capture filter, which digitizes the signal and delivers the MPEG-2 transport stream to the MPEG-2 Demultiplexer.

The TIF maps PID 0x00 to itself. PID 0x00 is reserved for the Program Association Table (PAT). As the TIF receives PAT sections, it notifies the Network Provider about which PIDs the PMTs and other tables are on. If the tune request is for another transport stream on the network, the Network Provider tunes the device again using the PMT information.

Acquiring the Signal

The Network Provider queries the TIF for the list of components in the program. It activates or deactivates particular components based on the preferred components list. It maps the corresponding PIDs on the demux, which then routes the streams to the correct output pins on the demux. The TIF continues to monitor the PMTs for service changes, and notifies the Network Provider if there are changes.


Tuning Spaces

A tuning space repesents a specific network type, such as ATSC digital antenna or DVB cable. A tuning space object performs several functions:

  • It stores information about the network, such as the range of physical channels.
  • It is a factory for tune requests.
  • It is persistable, so it can be stored in the system registry.

Default tuning spaces are provided for analog cable, analog antenna, ATSC digital cable, ATSC digital antenna, and analog auxiliary input. See Default Tuning Spaces for more information. Third parties can create their own tuning spaces to support DVB-T, DVB-S, or other network types.

Every tuning space object exposes the ITuningSpace interface. Additional network-specific interfaces are derived from ITuningSpace. For example, an ATSC tuning space exposes the IATSCTuningSpace interface.

System Tuning Spaces Collection

The SystemTuningSpaces object is a collection of all the tuning spaces available on the local system. Use this object to enumerate available tuning spaces and to add new tuning spaces. The SystemTuningSpaces object exposes the ITuningSpaceContainer interface.

The following code shows how to create the SystemTuningSpaces object and enumerate the tuning spaces using the ITuningSpaceContainer::get_EnumTuningSpaces method:

// Create the SystemTuningSpaces container.
CComPtr <ITuningSpaceContainer> pTuningSpaceContainer;
hr = pITuningSpaceContainer.CoCreateInstance(CLSID_SystemTuningSpaces);
if (SUCCEEDED(hr))
{
    // Get the enumerator for the collection.
    CComPtr<IEnumTuningSpaces> pTuningSpaceEnum;
    hr = pTuningSpaceContainer->get_EnumTuningSpaces(&pTuningSpaceEnum);
    if (SUCCEEDED(hr))
    {
        // Loop through the collection.
        CComPtr<ITuningSpace> pTuningSpace;
        while (S_OK == pTuningSpaceEnum->Next(1, &pTuningSpace, NULL))
        {
            // pTuningSpace points to the next tuning space.
            // You can query this pointer for derived interfaces.
        }
    }
}

Every tuning space has a UniqueName property, which is unique within a given computer's SystemTuningSpaces collection. Use this property to find a particular tuning space; call ITuningSpace::get_UniqueName to get the property.

Creating Tune Requests

To create a new tune request, call the ITuningSpace::CreateTuneRequest method on the tuning space. This method returns a tune request object that corresponds to the network type for that tuning space. The new tune request object is unitialized; tuning information for a specific channel or program must be added by calling methods on the tune request. For more information, see Tune Requests.

Creating New Tuning Spaces

Microsoft provides Network Provider filters for DVB tuning, and the Unified Tuning Model defines objects and interfaces for DVB tuning. However, there are no default DVB tuning spaces, because many of the required parameters are specific to individual broadcasters. In order to support DVB tuning, therefore, you must create a new tuning space and add it to the system registry, as follows:

  1. Create a DVB tuning space object. Use the DVBTuningSpace object for DVB-T or DVB-C, and the DVBSTuningSpace object for DVB-S.
  2. Set properties on the tuning space, using ITuningSpace and derived interfaces.
  3. Create a DVB locator object (DVBTLocator or DVBSLocator).
  4. Set properties on the locator, using ILocator and derived interfaces. For more information about locators, see Locators.
  5. Assign the locator as the default locator for the tuning space, by calling the ITuningSpace::put_DefaultLocator method.
  6. Optionally, create default component types. Assign them as the perferred component types for the tuning space by calling the ITuningSpace::put_DefaultPreferredComponentTypes method. For more information, see Components.
  7. Add the tuning space to the SystemTuningSpaces collection, by calling the ITuningSpaceContainer::Add method. The SystemTuningSpaces object automatically persists the tuning space in the registry.

You can also modify an existing tuning space. To do so, retrieve the tuning space from the SystemTuningSpaces collection, set the desired properties, and call ITuningSpaceContainer::put_Item to save the modified tuning space back into the collection.


Tune Requests

In digital television, tuning involves not only locating the signal on which a transport stream is being carried, but also finding the audio, video, and data elementary streams within that transport stream. In all tuning operations, the tune request object has a central role because it contains (or provides access to) all the information necessary for tuning.

The only way to create a tune request is by using the CreateTuneRequest method on the tuning space where the program is to be found. Both tune requests and tuning spaces are associated with a particular network type. For example, an ATSC tuning space object is used to create ATSC tune requests, a DVB-S tuning space object is used to create DVB-S tune requests, and so on. All tune requests contain references to the tuning space that was used to create it.

Tune requests for digital network types also contain references to a Locator object that contains further information necessary for tuning, and to a Components object that describes all the audio, video and data substreams that are available as part of the program. (These objects are discussed in detail later in this section.) All tune requests contain additional properties depending on their network type. For example, ATSC tune requests have a MajorChannel and MinorChannel property, and DVB-S tune requests have properties for getting and setting the transport stream ID (TSID) and original network ID (ONID).


Locators

Locator objects contain additional information about the signal and the transport stream that the Network Provider and tuner need in order to locate the service. Like tuning spaces and tune requests, locators are specific to a network type. A DVB-S tune request has a reference to a DVB-S locator, an ATSC tune request has a reference to an ATSC locator, and so on. Analog TV tuning spaces do not require locators because analog TV graphs are not based on Broadcast Driver Architecture and a tune request is never actually submitted to an analog TV tuner device.

Locators for DVB tuning spaces, especially for DVB-S providers, are more complex because these providers typically transmit many services on multiple transport streams simultaneously. Typically, the Guide Store Loader should be responsible for creating and configuring locators; it is only necessary to set those properties that will actually be used in the tuning process. A DVB-S provider may install a default locator along with its custom tuning space. This locator should contain the information to enable a tuner to locate the default transport stream on the network.


Components

In the context of MPEG-2, the term component refers to an elementary stream within a program. For example, a program might contain a video stream, two audio streams, a data stream, and so forth.

Components are represented by the IComponent interface. Each component has a type associated with it, represented by the IComponentType interface. The component type describes the component, and may include the media type of the stream. The IComponent interface is also used to activate or deactivate a given component. For example, if a program has two audio streams (say, English and Spanish), typically only one stream is active at a time.

Each tune request has a list of components. Initially this list might be empty, because the actual components have not been identified yet. After the Network Provider tunes to the program, the Transport Information Filter (TIF) begins to receive PSI tables, and is able to fill in some of the component information.

Note Components and component types are not used for analog network types.

To get the components list from a tune request, call the ITuneRequest::get_Components method, which returns a pointer to the IComponents interface. Then call IComponents::EnumComponents, which returns a pointer to the IEnumComponents interface. Use this interface to iterate through the collection:

CComPtr<IComponents> pComponents;
hr = pTuneRequest->get_Components(&pComponents);
if (SUCCEEDED(hr) && (pComponents != NULL))
{
    CComPtr<IEnumComponents> pEnum;
    hr = pComps->EnumComponents(&pEnum);
    if (SUCCEEDED(hr))
    {
        CComPtr<IComponent> pComponent;
        ULONG cFetched;
        while (S_OK == pEnum->Next(1, &pComponent, &cFetched))
        {
            // pComponent contains a pointer to the next component.
        }
        pComponent.Release();
    }
}

After the tune request is submitted to the Network Provider and data is moving through the filter graph, you can get the updated tune request by calling the Network Provider filter's ITuner::get_TuneRequest method. Use the returned ITuneRequest pointer to examine the updated component information. To change which components are active or inactive, update the component list and resubmit the tune request. IComponent::put_Status to change a component's active/inactive status.

Default Preferred Component Types

A tuning space can have a list of preferred component types. If so, the Network Provider uses the list to configure the output pins on the MPEG-2 Demultiplexer filter. Otherwise, the Network Provider creates a default set of output pins:

Pin | Description
Pin 1 | PSI Tables. This pin connects to the BDA MPEG-2 Transport Information Filter (TIF)
Pin 2 | Video
Pin 3 | Audio
Pin 4 | Data
Pin 5 | PSI Tables. This pin connects to the MPEG-2 Sections and Tables filter

To override the preferred component types for a tuning space, do the following:

  1. Get the tuning space from the SystemTuningSpaces collection, as described in Tuning Spaces.
  2. Create a new ComponentTypes collection object.
  3. Create one or more component type objects of the appropriate type. For MPEG-2 streams, use the MPEG2ComponentType object.
  4. Set the desired properties on each component type. At a minimum, set the category (audio, video, and so forth) by calling the IComponentType::put_Category method.
  5. Add each component to the collection by calling IComponents::Add.
  6. Call ITuningSpace::put_DefaultPreferredComponentTypes with a pointer to the component types collection.
  7. Persist the changes by putting the tuning space back into the SystemTuningSpaces collection. Call the ITuningSpaceContainer::put_Item method with a pointer to the tuning space object.

The following code shows these steps:

CComPtr <ITuningSpace> pTuningSpace;  // Pointer to the tuning space.
// Use the SystemTuningSpaces collection to get the tuning space
// (not shown).

// Create a new component types collection object.
CComPtr<IComponentTypes> pTypes;
hr = pTypes.CoCreateInstance(CLSID_ComponentTypes);

// Create a new MPEG-2 component type.
CComPtr<IMpeg2ComponentType> pType;
hr = pType.CoCreateInstance(CLSID_MPEG2ComponentType);

// Set the category.
hr = pType->put_Category(CategoryVideo);

// Add the new type to the collection.
CComVariant var;  // Receives the index into the collection.
hr = pTypes->Add(pType, &var);

// (Repeat for each component type.)

// Set the component type collection as the list of default types
// for the tuning space.
hr = pTuningSpace->put_DefaultPreferredComponentTypes(pTypes);

One reason to set the default component types is to specify a preferred language for an audio stream. Do this by calling the ILanguageComponentType::put_LangID method on the component type.


Getting Program Information

Custom guide store loaders need to get program information from the transport stream. There are several ways to do this:

  • Get information from the BDA MPEG-2 Transport Information Filter (TIF)
  • Get section data from the MPEG-2 Sections and Tables filter
  • Implement a custom filter that parses the raw PSI section packets.

You can combine any of these approaches within the same client.

To get program information from the TIF, implement the IGuideDataEvent interface in your component, and then set up a connection point with the TIF using the IConnectionPoint interface.

For information about using the MPEG-2 Sections and Tables filter, see Getting MPEG-2 PSI Tables.

The third option, implementing a custom filter, is not recommended because the MPEG-2 Sections and Tables filter already provides a much simpler way to get section data. If you do take this approach, you must create a list of default component types that includes an additional "CategoryOther" type, and set this list as the default preferred components list on the tuning space. This will cause the Network Provider filter to create an additional output pin on the MPEG-2 Demultiplexer filter, so that you can connect your filter to the graph. For more information about setting the default component types, see Components.

When your filter connects, call the IBDA_TIF_REGISTRATION::RegisterTIFEx method to register the filter with the Network Provider. This method returns a pointer to the IMPEG2PIDMap interface; use that interface to map the desired PIDs to that pin. (Do not use the IMPEG2PIDMap interface on the MPEG-2 Demultiplexer, because the Network Provider must be notified of all PID mappings in a BDA graph. It forwards the call to the demux.) When your filter is disconnected, call the IBDA_TIF_REGISTRATION::UnregisterTIF method to unregister with the Network Provider.


Default Tuning Spaces

Five default tuning spaces are provided in Microsoft Windows XP. The same tuning spaces are also provided with DirectX 9.0. These tuning spaces are persisted in the registry with the properties shown in the following tables. Use the SystemTuningSpaces object to access or modify these tuning spaces, or to add a new tuning space.

Analog tuning spaces have a network type of GUID_NULL, because analog TV graphs do not use a Network Provider filter. Also, analog tuning spaces do not use locators. The default country/region code in these tuning spaces is for the region that includes Canada, the United States, and parts of the Caribbean. The country/region code in the tuning space must correspond to the region setting in the host system. See Frequency Tables for a list of country/region codes.

Local Analog Cable

Property | Value
CLSID | CLSID_AnalogTVTuningSpace {8A674B4D-1F63-11D3-B64C-00C04F79498E}
Unique Name | Cable
Friendly Name | Local Analog Cable
Network Type | GUID_NULL {00000000-0000-0000-0000-000000000000}
Minimum Channel | 0x01
Maximum Channel | 0x9E
Input Type | 0x0 (Cable)
Country/Region Code | 0x01

Local Analog Antenna

Property | Value
CLSID | CLSID_AnalogTVTuningSpace {8A674B4D-1F63-11D3-B64C-00C04F79498E}
Unique Name | Antenna
Friendly Name | Local Analog Antenna
Network Type | GUID_NULL {00000000-0000-0000-0000-000000000000}
Minimum Channel | 0x02
Maximum Channel | 0x45
Input Type | 0x1 (Antenna)
Country/Region Code | 0x01

ATSC Digital Antenna

Property | Value
CLSID | CLSID_ATSCTuningSpace {A2E30750-6C3D-11D3-B653-00C04F79498E}
Unique Name | ATSC
Friendly Name | Local ATSC Digital Antenna
Network Type | CLSID_ATSCNetworkProvider {0DAD2FDD-5FD7-11D3-8F50-00C04F7971E2}
Minimum Channel | 0x01
Maximum Channel | 0x63
Input Type | 0x0 (Cable)
Country/Region Code | 0x00
Minimum Minor Channel | 0x00
Maximum Minor Channel | 0x03E7
Minimum Physical Channel | 0x02
Maximum Physical Channel | 0x9E

Default Locator for ATSC Digital Antenna

Property | Value
CLSID | CLSID_ATSCLocator {8872FF1B-98FA-4D7A-8D93-C9F1055F85BB}
Frequency | 0xFFFFFFFF (-1)
Inner FEC Method | 0xFFFFFFFF (-1)
Inner FEC Rate | 0xFFFFFFFF (-1)
Outer FEC Method | 0xFFFFFFFF (-1)
Outer FEC Rate | 0xFFFFFFFF (-1)
ModulationType | 0x7
Symbol Rate | 0xFFFFFFFF (-1)
Physical Channel | 0xFFFFFFFF (-1)
Transport Stream ID | 0xFFFFFFFF (-1)
Program Number | 0xFFFFFFFF (-1)

Local ATSC-style Digital Cable

Currently not supported.

Property | Value
CLSID | CLSID_ATSCTuningSpace {A2E30750-6C3D-11D3-B653-00C04F79498E}
Unique Name | Digital Cable
Friendly Name | Local ATSC-Style Digital Cable
Network Type | {143827AB-F77B-498d-81CA-5A007AEC28BF}
Minimum Channel | 0x02
MaximumChannel | 0x3E7
Input Type | 0x0 (Cable)
Country/Region Code | 0x00
Minimum Minor Channel | 0x00
Maximum Minor Channel | 0x03E7
Minimum Physical Channel | 0x02
Maximum Physical Channel | 0x03E7

Analog Auxiliary Input

Property | Value
CLSID | CLSID_AuxInTuningSpace {F9769A06-7ACA-4e39-9CFB-97BB35F0E77E}
Unique Name | AuxIn1
Friendly Name | Analog Auxiliary Input #1
Network Type | GUID_NULL {00000000-0000-0000-0000-000000000000}


TV Ratings Components

This topic applies to Windows XP Service Pack 1 only.

The Microsoft TV Ratings components allow an application to parse out rating information about a program from the broadcast stream, set a maximum allowable rating, and halt playback or perform another suitable action if the rating exceeds this maximum value. Rating information is provided by the broadcaster, and describes the appropriate age group and content attributes.

The Microsoft TV Ratings components are supported on Microsoft Windows XP Service Pack 1, and they are only used for analog television broadcasts. This section contains the following topics:

  • Overview of the TV Ratings System
  • Programming with the TV Ratings Objects
  • Setting Allowable Viewing Levels
  • Building the EvalRat and XDSToRat Objects

See Also

  • Microsoft TV Technologies
  • TV Ratings Reference


Overview of the TV Ratings System

This topic applies to Windows XP Service Pack 1 only.

The Microsoft TV Ratings system provides a way for DirectShow programmers to access content ratings from a broadcast stream and use them to make decisions about whether or not to display the content. These ratings are mandatory on all US broadcast streams, and are contained in the extended data services (XDS) channel of line 21.

Microsoft provides the following filters for this system:

  • XDS Codec filter
  • Encrypter/Tagger filter
  • Decrypter/Detagger filter

These filters host two objects that are provided by third-party developers:

  • The XDSToRat (Ratings Decoder) object is hosted by the XDS Codec filter.
  • The EvalRat (Ratings Evaluator) object is hosted by the Encrypter/Tagger filter and the Decrypter/Detagger filter.

The XDSToRat and EvalRat objects are both standard COM objects. The XDSToRat object exposes the IXDSToRat interface, and the EvalRat object exposes the IEvalRat interface.

Briefly, the TV Ratings system works as follows:

  • The XDS Codec filter receives XDS data from the CC Decoder filter or some other source. It passes this data to the XDSToRat object, which is responsible for parsing the data into content ratings. The XDSToRat object returns the decoded ratings to the XDS Codec filter, which makes them available to the Encrypter/Tagger filter.

    XDS Codec Filter

  • The Encrypter/Tagger filter encrypts the media samples that it receives. It also tags the samples with ratings information, taken from the XDS Codec filter.

  • The Decrypter/Detagger filter takes the ratings from the encrypted samples and passes them to the EvalRat object. The EvalRat object determines whether the content is allowed, based on the rating and the current permissions. If so, the Decrypter/Detagger filter decrypts the samples and passes them downstream for rendering. Otherwise, it blocks playback. The application sets permissions through an interface on the Decrypter/Detagger filter.

This architecture enables an application to create separate graphs for tuning and rendering, which is required when using the stream buffer engine. The tuning graph will contain the XDS Codec filter and the Encrypter/Tagger filter. The rendering graph will contain the Decrypter/Detagger filter.

Here is how the system works in more detail:

  1. The XDS Codec filter calls IXDSToRat::Init on the XDSToRat object, which sets the object to its initial state.
  2. The application uses the IDTFilter::put_BlockedRatingAttributes method on the Decrypter/Detagger filter to specify which ratings are permitted and which should be blocked. The Decrypter/Detagger filter passes this information to the EvalRat object. (For details, see Setting Allowable Viewing Levels.) This step can occur at any time.
  3. When the filter graph is running, the XDS Codec filter receives XDS packets from the line 21 stream. The XDS Codec filter sends the packets to the XDSRat object for parsing, two bytes at a time, by calling the IXDSToRat::ParseXDSBytePair method.
  4. If the XDSToRat object decodes a new rating, it returns this information and returns S_OK from the ParseXDSBytePair method. The XDS Codec stores the new rating and broadcasts a "new rating" event (EVENTID_XDSCodecNewXDSRating) to the entire filter graph, through the IBroadcastEvent interface.
  5. The Encrypter/Tagger filter listens for new rating events. Whenever it receives one, it gets the new rating from the XDS Codec filter. It uses this rating to tag the samples that it encrypts.
  6. The Decrypter/Detagger filter looks for ratings on the encrypted media samples. Whenever it finds a new rating, it broadcasts a "rating change" event (EVENTID_DTFilterRatingChange).
  7. The Decrypter/Detagger filter tests any new rating by calling IEvalRat::TestRating on the EvalRat object. If that rating is not allowed (by the permissions given in step 2), the Decrypter/Detagger filter blocks the stream and discards all samples, until the rating changes again.
  8. Whenever the Decrypter/Detagger filter blocks the stream, it broadcasts a "ratings block" event (EVENTID_DTFilterRatingsBlock). Whenever it unblocks the stream, it broadcasts a "ratings unblock" event (EVENTID_DTFilterRatingsUnBlock).
  9. If there is a discontinuity in the stream, such as a channel change, the XDS Codec filter calls IXDSToRat::Init again to reset the XDSToRat object. It also sets the current rating to "DontKnow" and broadcasts a "new rating" event (EVENTID_XDSCodecNewXDSRating).

The only actions the hosting application needs to take are:

  • Setting the viewing permissions.
  • Retrieving the current permissions.
  • Displaying the current permissions to the user.
  • Signaling to the user when the stream is blocked or unblocked.


Programming with the TV Ratings Objects

This topic applies to Windows XP Service Pack 1 only.

To support TV ratings in an application, connect the VBI pin on the capture filter to the CC Decoder filter, and connect the CC Decoder to the XDS Codec filter.

The application does not use the EvalRat or XDSToRat objects directly. Rather, all interaction is through the Decrypter/Detagger and XDS Codec filter, respectively. (Although the Encrypter/Tagger filter hosts an EvalRat object, there is no interaction at all with it. It only uses the MostRestrictiveRating method.)

The filters handle most of the details of filtering program ratings. The application is responsible for the following tasks:

  • Setting acceptable viewing levels
  • Optionally retrieving the set levels
  • Handling a rejected broadcast stream event
  • Optionally handling a ratings change event

An application can set detailed allowable viewing levels using any rating system listed in the EnTvRat_System enumeration, or can create a generic system of its own. Details are given in Setting Allowable Viewing Levels.

An application can retrieve these levels for display from the Decrypter/Detagger filter. To retrieve all the attributes, an application must iterate through all the levels of a system.

When a broadcast includes a rating that goes beyond acceptable viewing levels, the Decrypter/Detagger filter immediately ceases delivering samples until an acceptable rating is received, or some other action is taken.

See Also

  • Overview of the TV Ratings System
  • Setting Allowable Viewing Levels
  • TV Ratings Components


Setting Allowable Viewing Levels

This topic applies to Windows XP Service Pack 1 only.

TV ratings are a combination of three things: rating system, rating level, and attributes.

  • Rating systems vary by country/region, and one country/region may have more than one system. For example, Canada has both English and French rating systems, and the United States has both MPAA and TV rating systems. Rating systems are enumerated by the EnTvRat_System enumeration.
  • Each system has levels. For example, the MPAA uses G, PG, R, and other levels. The number of levels in use varies by system, but the Microsoft TV Rating system provides eight levels. Unused levels can be ignored. Each system has an enumeration that lists its levels.
  • Each level can have additional content attributes. For example, the United States TV system uses additional attribute tags for content containing violence, adult situations, and so on. Currently, only the United States TV rating system uses additional content attributes.

The rest of this document describes how to use read or set ratings for allowable viewing levels.

Each rating system can be treated as a permission grid, where each column specifies the allowable permissions and each row specifies a rating level. The use of this grid model allows very specific permissions to be set, and to even interleave allowable viewing levels with disallowed viewing levels. Because one level is prohibited does not require that more restrictive levels be prohibited as well. The following table shows a sample permission grid using the US TV rating system.

US TV rating system (US_TV)

Attribute Level | US_TV_ IsBlocked | US_TV_ IsViolent | US_TV_ IsSexualSituation | US_TV_ IsAdultLanguage | US_TV_ IsSexuallySuggestiveDialog | Not used | Not used | Not used
None | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
Y | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
Y7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
G | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0
PG | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0
14 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 0
MA | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0
None 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0

The preceding table shows the enumerated values for the attributes as column headings, and the levels as rows. Each row shows an 8-bit attribute field that is passed into the filter to describe viewing permissions. A value of 1 means restricted, and a value of 0 means not restricted.

The preceding table can be interpreted as follows:

  • No restrictions on nonrated programs (a nonrating is given to news or sports, generally).
  • No restrictions on "Y" or "Y7" rated programs.
  • Do not permit "G" rated programs.
  • Allow all "PG" programs except those showing violence.
  • Allow only "14" rated programs with no additional attributes or adult language.
  • Do not permit "MA" rated programs.

Notice that the IsBlocked bit blocks playback of that level regardless of any other attributes that are set, so when setting the IsBlocked bit, it is not necessary to specify any other restrictions (which will be ignored anyway).

Also notice how the restricted rated-G row does not prevent playback of more restrictive levels. This is an unlikely example of the use of this property, but it does show that levels do not affect each other, and that permissions for all levels must be set.

The enumerated names for levels and attributes are only used to make the code more readable. Any enumeration values used for levels or attributes in the same ordinal position can be substituted for any other. The essential idea is an eight-bit by eight-bit grid.

Permission grids must be set for each system that an application is likely to receive. Therefore, an application receiving United States broadcasts should complete permission grids for both MPAA and US TV styles; applications receiving Canadian broadcasts should complete permission grids for both English- and French-Canadian systems, and so on.

Unrated Programs

A program is unrated if a rating has not yet been detected in the broadcast. All programs are considered unrated when they are received, until a valid program rating is processed by the XDSToRat object.

Different broadcasters may post ratings information at different time intervals, and content may remain unrated for a significant amount of time. Also, programs can be changed to an unrated status by certain XDS codes. See EIA-608B, section 9.5.1.5.4 for details.

Note that "unrated" is not the same as the "None" or "Exempt" ratings in the US or Canadian TV rating systems, or "Not Rated" in the MPAA system. These are valid ratings, and are treated as such.

See Also

  • Building the EvalRat and XDSToRat Objects
  • Programming with the TV Ratings Objects


Building the EvalRat and XDSToRat Objects

This topic applies to Windows XP Service Pack 1 only.

In order to understand and build these objects, a programmer must be familiar with the EIA/CEA-608-B specifications, which explain the format of XDS packets.

To build the EvalRat or XDSToRat objects, an application must #include TvRatings.h.

Both objects are instantiated by, and controlled by, DirectShow filters. Both are created as standard COM objects. In addition to inheriting the standard COM interfaces, the XDSToRat object must support the IXDSToRat interface, and the EvalRat object must support the IEvalRat interface.

See Also

  • Setting Allowable Viewing Levels
  • TV Ratings Components


Writing Digital TV Applications with DirectX

This section describes how to build digital TV filter graphs for down-level platforms in which the Video Control is not available. For these platforms, the application must the graph manually, by adding and connecting each filter. (Note that the Capture Graph Builder object does not support digital TV graphs). The BDA Sample Application demonstrates how to build a basic digital TV filter graph.

Obtain a Tune Request

Start by obtaining a tune request, either from a guide store or by constructing one programmatically within the application. For more information, see The Microsoft Unified Tuning Model.

Create the Network Provider Filter

The first filter that appears in a digtial TV filter graph is a BDA Network Provider filter. The Network Provider controls tuning and works with the Transport Information Filter (TIF) to get program information from the transport stream. To select a Network Provider filter, query the tuning space for its network type property, which corresponds to the CLSID of the Network Provider for that tuning space. The following code shows how to create the Network Provider and add it to the graph:

CComPtr<ITuneRequest> pTuneRequest;  // Tune request
CComPtr<ITuningSpace> pTuningSpace;  // Tuning space
CComPtr<IBaseFilter> pNetworkProvider; // Network Provider filter
GUID CLSIDNetworkType; // GUID of the network type.

// Initialize the tune request (not shown).

// Find the tuning space for this tune request.
hr = pTuneRequest->get_TuningSpace(&pTuningSpace);
if (FAILED(hr))
{
    // Handle error.
}

// Find the network type.
hr = pTuningSpace->get__NetworkType(&CLSIDNetworkType);
if (FAILED(hr))
{
    // Handle error.
}
if (CLSID_NetworkType == GUID_NULL)
{
    // This tuning space is analog TV, AuxIn, or some other non-BDA type.
}
else
{
    // Create the network provider filter for this network type.
    hr = pNetworkProvider.CoCreateInstance(CLSIDNetworkType);
    if (SUCCEEDED(hr))
    {
        // Add the network provider to the graph.
        hr = pGraph->AddFilter(pNetworkProvider, L"Network Provider");
    }
}

The ITuneRequest::get_TuningSpace method gets a pointer to the tuning space for a particular tune request. Then call ITuningSpace::get__NetworkType to get the network type GUID. Pass this GUID to the CoCreateInstance function to create the Network Provider filter.

Analog Tuning Spaces

For some tuning spaces, the network type is GUID_NULL. This means the tuning space does not represent a digital TV network, so it is not handled by a BDA Network Provider filter. In that case, the application should build an analog TV capture graph as described in the sections Video Capture and Analog Television. The channel number on the tuning request indicates which channel to set on the TV Tuner filter.

The AuxInTuningSpace tuning space represents an auxiliary video input or "AuxIn". The channel number indicates the input source:

Channel Number | Input
0 | S-video
1 | Composite video

To find out if a tune request is an AuxIn type, query the tuning space for the IAuxInTuningSpace interface. If it exposes this interface, build an analog capture graph and use the crossbar filter to select the input source. For more information, see Working with Crossbars. For S-Video, route the PhysConn_Video_SVideo pin to the video output pin. For composite video, route the PhysConn_Video_Composite pin to the video output. In both cases, route the PhysConn_Audio_Line pin to the audio output.

For analog graphs, ignore the rest of this section.

Submit the Tune Request to the Network Provider

After you add the Network Provider to the graph, query it for the ITuner interface and call ITuner::put_TuneRequest with a pointer to the tune request:

// Query for ITuner.
CComQIPtr<ITuner> pTuner(pNetworkProvider);
if (pTuner)
{
    // Submit the tune request to the network provider.
    hr = pTuner->put_TuneRequest(pTuneRequest);
}

Add and Connect the Remaining Filters

After the Network Provider has been configured with a tune request, you can add the remaining filters to the graph. The Network Provider connects to a tuner filter in the "BDA Source Filters" catgegory (KSCATEGORY_BDA_NETWORK_TUNER). The tuner filter connects to one or more filters "BDA Receiver Components" category (KSCATEGORY_BDA_RECEIVER_COMPONENT). This catgegory includes the capture filter and possibly a demodulator filter, depending on the hardware. The application must enumerate the filters in this category and try connecting them, either by media type or by medium.

Connect the capture filter to the MPEG-2 Demultiplexer filter, which automatically configures its the output pins based on the preferred component types. Typically pin 1 connects to the BDA MPEG-2 Transport Information Filter (TIF). Typically you can simply render all of the output pins on the demux, and the correct renderer filters will be added to the graph. For IP data, connect the output pin on the demux to the BDA IP Sink filter, via the BDA MPE filter.

Define Default Preferred Component Types

A "component" refers to a program substream. The default preferred component types are those types of substreams that a user wishes to activate by default. For example, a user may specify that a Spanish audio stream should be played whenever one is available. The application creates a set of preferred components by instantiating an empty components collection object and filling it. The application can then persist and/or submit the components object to the Tuner, which will check it whenever there are changes in the available substreams.

Select a Substream

To specify which substreams to activate or inactivate, an application must first submit a tune request to the tuner. Once the tuner tunes to the specified channel or frequency, it will fill in the components collection in the tune request with information about each active and inactive substream. The application can then examine each component in this collection, and use the IComponent::put_Status method to activate or inactivate a particular substream.

Digital Tuning

After the initial tune request has been submitted, subsequent tuning is performed by submitting a new tune request to the Network Provider.


Using the Video Mixing Renderer

In terms of both performance and breadth of features, the Video Mixing Renderer (VMR) filter represents the next generation in video rendering on the Windows platform. The VMR replaces the Overlay Mixer and Video Renderer, and adds many new mixing features.

The VMR was first made available for the Windows XP platforms only. Beginning with DirectX 9.0, a separate version of the VMR, called the VMR-9, is available for redistribution on all platforms supported by DirectX. The two VMR filters are very similar in their implementation and the interfaces that they expose. The primary difference is that the original VMR (now called the VMR-7) uses DirectDraw 7 internally to control the video hardware, while the new version of VMR (called the VMR-9) uses Direct3D 9.

The VMR-9 has its own CLSID and its own set of interfaces, structures and enumeration types which are not always identical to the corresponding data types for the VMR-7, due to the underlying differences between DirectDraw 7 and Direct3D 9. The VMR-9 interfaces all end with "9", for example IVMRStreamConfig9, and the structures and enumeration types all have "VMR9" in their name to distinguish them from the data types used with the VMR-7.

To ensure backward-compatibility, the VMR-9 is not the default renderer on any system. To use the VMR-9, you must explicitly add it to the filter graph using the IFilterGraph::AddFilter method, and configure it before connecting it to any upstream filters.

This article contains the following sections. Except where noted, the information in these sections applies to both the VMR-7 and the VMR-9 filters:

  • Features of the VMR
  • VMR vs. Previous DirectShow Renderers
  • VMR System Requirements
  • Choosing the Right Renderer
  • VMR Filter Components
  • VMR Modes of Operation
  • Building a VMR-9 Filter Graph
  • Displaying an Application-Supplied Bitmap on the Composited Image
  • Multi-Monitor Support
  • Optimizing Mixing Performance
  • Setting Deinterlace Preferences
  • Using the VMR for DirectShow Filter Developers


Features of the VMR

The Video Mixing Renderer 7 (VMR-7) supports the following new features:

  • Real mixing of multiple video streams, using the alpha-blending capabilities of Direct3D hardware devices.
  • The ability to plug in your own compositing component to implement effects and transitions between multiple video streams entering the VMR.
  • True windowless rendering. It is no longer necessary to make the video playback window a child of the application's window in order to contain video playback. The VMR's new windowless rendering mode allows applications to easily host video playback within any window without having to forward window messages to the renderer for renderer-specific processing.
  • A new renderless playback mode where applications can supply their own allocator component to get access to the decoded video image prior to it being displayed on the screen.
  • Improved support for PCs equipped with multiple monitors.
  • Support for Microsoft's new DirectX Video Acceleration architecture.
  • Support for high-quality video playback concurrently on multiple windows.
  • Support for DirectDraw Exclusive Mode
  • 100% backward-compatibility with existing applications.
  • Support for frame stepping and a reliable way to capture the current image being displayed.
  • The ability for applications to easily alpha-blend their own static image data (such as channel logos or UI components) with the video in a smooth flicker-free way.

The VMR-9 supports all the features listed above, plus:

  • The ability to process video data directly with Direct3D APIs such as pixel shaders.
  • Improved support for interlaced video content.
  • Support on any platform supported by DirectX.


VMR vs. Previous DirectShow Renderers

With the old filters, different renderers would be required in the graph depending on the hardware configuration.

The Video Renderer filter was used to render a single video stream in non-video port scenarios. It was based on graphics hardware technology which is now over five years old, and on an older version of DirectDraw. In certain scenarios, it uses GDI for rendering. This is done either to conserve video resources, which were much more limited five years ago, or else to overcome limitations in DirectDraw that were related to multi-monitor support. Neither the VMR-7 nor the VMR-9 ever uses GDI for rendering; the VMR-7 is based completely on DirectDraw 7 and the VMR-9 is based on Direct3D 9.

In scenarios involving either a video port or multiple video input streams, prior to the VMR the Overlay Mixer filter was used for rendering. This filter only uses the hardware overlay on the graphics card, and so is generally limited to the one overlay surface provided by most cards. The Overlay Mixer performs destination color keying, but it is not capable of alpha blending. Because it does not have a window manager, it must use a second filter, the Video Renderer, for window management. The VMR is capable of true alpha blending, and can create multiple overlays in software in addition to the hardware overlays.

In video port scenarios where applications were overlaying closed captioning or other VBI data on the video, an additional filter, the VBI Surface Allocator, was required in order to allocate the additional video memory for the VBI text. For ISVs, the VMR-7 simplifies application development by combining allocation and rendering functionality into a single filter that is used in all scenarios. With the VMR, the VBI Surface Allocator is no longer needed. This filter is replaced in Windows XP by the new Video Port Manager filter which performs all of the video port tasks previously performed by the Overlay Mixer.

Note The VMR-9 does not support video ports.

The VMR is more robust than the earlier renderers, in part because it only uses DirectDraw 7 (or Direct3D 9 if you are using the VMR-9) interfaces, as opposed to the old renderers which used a mixture of interfaces from older and newer versions of DirectDraw. The VMR also employs a new image presentation mechanism which is designed for current and future generations of adapters, which have support for Direct3D, increased VRAM and video memory bandwidth, and hardware acceleration features. With the VMR, the focus is on front-end processing, and reduced dependence on video ports and overlays. But even with all its new functionality, the VMR is designed for maximum compatibility with existing applications.

The VMR is also extensible. Applications can provide their own sub-components to perform custom video effects and/or take control of the allocation and rendering process.


VMR System Requirements

The VMR uses the graphics-processing capabilities of the computer's display card exclusively; the VMR does not perform any blending or rendering of video using the host processor, because to do so would greatly impact the frame rate and quality of the video being displayed. When taking advantage of the new features offered by the VMR, particularly blending of multiple video streams and/or application images, the overall performance obtained is highly dependent on the capabilities of the graphics card being used on the computer. Graphics cards that perform well with the VMR have the following hardware support built into them:

  • Support for YUV and "non-power of 2" Direct3D texture surfaces.
  • The ability to StretchBlt from YUV to RGB DirectDraw surfaces.
  • At least 16MB of video memory if multiple video streams are to be blended together. The actual amount of memory required is dependent on the image size of the video streams and resolution of the display mode being used.
  • Support for an RGB overlay or the ability to blend to a YUV overlay surface.
  • Hardware-accelerated video (support for DirectX Video Acceleration) decoding.
  • High pixel fill rates.

Note The VMR requires that the system monitor be set for a color depth of at least 16 bits. The VMR cannot be put into a run state if the monitor is set for 256 colors. Also, some video cards cannot perform Direct3D operations when the display is set to 24 bits per pixel.


Choosing the Right Renderer

With DirectX 9.0, DirectShow provides four separate video renderers: the old Video Renderer, the Overlay Mixer, the VMR-7 and the VMR-9. For various reasons, no single renderer is preferable in all scenarios. The following guidelines should help you decide which renderer to use in your application:

  • Existing applications that require only basic video rendering, with no mixing

    Use the VMR-9 for its improved de-interlacing and ProcAmp support. Use the old default video renderer if you know in advance that the video hardware is not sufficient to support the VMR-7 or VMR-9.

  • Applications based on devices that use video ports

    Use the Overlay Mixer if support on platforms earlier than Windows XP is required. If the application will only run on Windows XP, then use the VMR-7. The VMR-9 does not support video ports.

  • Applications that require any of the special capabilities of the VMR

    Use the VMR-9 rather than the VMR-7 because the VMR-9 supports the latest Direct3D capabilities and is supported on all platforms supported by DirectX. If you specifically target the VMR-7, your application will run only on Windows XP.


VMR Filter Components

The VMR employs a modular design that enables applications to configure it for many different rendering scenarios. Depending on its configuration, the VMR contains from two to five subcomponents (in addition to its input pins).

VMR in Windowed Mode with Multiple Streams

Mixer: The mixer is a COM object that is loaded by the VMR when multiple input streams are detected. The mixer collects information about each input stream and sorts the streams into the correct Z-order. It is responsible for determining when each input pin receives a sample, and for instructing the image compositor at the proper time to perform the actual blending. The mixer also calculates the time stamp to be applied to each output image. When the application is supplying a bitmap to be displayed on top of the composited image, the mixer is responsible for ensuring that the bitmap is displayed on top even if the Z-order of the input streams is modified.

Image Compositor: The Image Compositor is a COM object that performs the actual blending of the input streams onto a single DirectDraw or Direct3D surface provided by the allocator-presenter. The VMR provides a default image compositor that enables applications to perform 2-D alpha-blending effects. Applications can provide a custom image compositor to enable other 2-D and 3-D effects, such as applying textures to portions of the image, per-pixel alpha blending, mapping the image to stationary or moving 3-D objects, and so on.

Allocator-Presenter: The allocator-presenter is a COM object that allocates the DirectDraw or Direct3D object and handles the communication with the graphics card. The drawing can be performed either as a flip or as a blit. You can plug in your own allocator-presenter in order to create and control the DirectDraw or Direct3D object, and/or to obtain access to the video bits at presentation time.

Core Synchronization Unit: The core synchronization unit is a COM object that ensures that each frame is presented at the correct time. It uses the IReferenceClock interface provided by the Filter Graph Manager and performs quality-management and frame-reporting functions.

Window Manager: The Window Manager is used only when the VMR is operating in windowed mode. The Window Manager is implemented as a static library, and it supports the old DirectShow IVideoWindow and IBasicVideo interfaces for backward-compatibility.


VMR Modes of Operation

The component architecture of the VMR enables applications to configure it in various ways, depending on how rendering is to be performed. The following table shows the three presentation modes and the two mixing modes, and the components that are present for each configuration.

Mode | Single Stream | Multiple Streams (Mixing Mode)
Windowed | Allocator-presenter Core Synchronization Unit Window Manager | Mixer Compositor* Allocator-presenter Core Synchronization Unit Window Manager
Windowless | Allocator-presenter Core Synchronization Unit | Mixer Compositor* Allocator-presenter Core Synchronization Unit
Renderless | Allocator-presenter (provided by application) Core Synchronization Unit | Mixer Compositor* Allocator-presenter (provided by application) Core Synchronization Unit

* Indicates that the application has the option to provide a custom component or use the default component.

In all configurations, the main point to remember when you create filter graphs with the VMR is that you must configure the VMR before you connect it.

For all configurations, pins cannot be dynamically added or removed after the VMR is connected to the upstream filter, but they can be connected and disconnected. If the application is unsure how many pins will be needed, it should configure the VMR for the maximum number that might be needed. The presence of unused input pins on the filter does not degrade rendering performance. Unlike the old Overlay Mixer, the VMR has no output pin because it does not require a separate filter for window management.

The following sections describe how to configure the VMR for a given mode:

  • VMR Windowed (Compatibility) Mode
  • VMR Windowless Mode
  • VMR with Multiple Streams (Mixing Mode)
  • VMR Renderless Playback Mode (Custom Allocator-Presenters)
  • DirectDraw Exclusive Mode


VMR Windowed (Compatibility) Mode

The VMR is designed to be compatible with all existing DirectShow applications. When it is used with an existing application, the VMR operates in windowed mode with a single video stream, also called compatibility mode. This mode is provided because the VMR-7 is the default renderer on Windows XP, and is therefore automatically used in calls to Intelligent Connect methods such as IGraphBuilder::RenderFile. If your application uses Intelligent Connect and requires only basic rendering capabilities, you do not need any special code to render correctly with the VMR-7 on Windows XP.

The VMR-9 also runs in windowed/compatibility mode by default. However, the VMR-9 is never the default video renderer. To use the VMR-9 in an application, you must explicitly add it to the filter graph. For that reason, and because windowless mode provides better functionality than windowed mode, there is no particular advantage to using the VMR-9 in windowed/compatibility mode.

Using the VMR-7 in Windowed/Compatibility Mode

No special programming is required to set up or control the VMR-7 in windowed/compatibility mode. Simply build the filter graph using the standard graph-building calls, and the VMR-7 will default to this mode.

In windowed/compatibility mode, the VMR-7 creates its own window to display the video. To do so, it loads the Window Manager component, which exposes the IVideoWindow and IBasicVideo interfaces. Your application can query the Filter Graph Manager for these interfaces, exactly as you would with the old Video Renderer filter. For more information, see Setting the Video Window.

The following illustration shows the VMR-7 in windowed/compatibility mode.

VMR in compatibility mode

To guarantee the maximum level of compatibility, the video window has the same class name as the one created by the old Video Renderer filter, and most of the Window Manager code from the old Video Renderer is still used by the VMR. In windowed/compatibility mode, the VMR consumes no more system resources than the old Video Renderer. Since the VMR-7 has only one input stream in windowed/compatibility mode, it does not load its mixer or compositor components.

By default, the VMR stretches the image to fill the video window. To preserve the aspect ratio of the source, call the IVMRAspectRatioControl::SetAspectRatioMode method with the VMR_ARMODE_LETTER_BOX flag.

Note MFC applications that place the video window in a child window must define an empty WM_ERASEBKGND message handler, or the video display area will not repaint correctly.

Using the VMR-7 in Windowed/Compatibility Mode with Multiple Streams

In windowed/compatibility mode, the VMR-7 creates a single input pin by default, and disables mixing mode. To enable mixing mode, you must configure the VMR before you connect it. For more information, see VMR with Multiple Streams (Mixing Mode). In mixing mode, the VMR loads the mixing and compositor components, which require more system resources.

Using the VMR-9 in Windowed Mode

Because the VMR-9 is not the default renderer, it does not have a compatibility mode as such. Instead, the VMR-9 defaults to windowed mode with four input pins. You can use this mode to mix up to four video streams. If you need to mix a larger number of streams, you must configure it as described in VMR with Multiple Streams (Mixing Mode). Otherwise, the VMR-9 in windowed mode behaves exactly like the VMR-7 in windowed/compatibility mode.


VMR Windowless Mode

Windowless mode is the preferred way for applications to render video inside an application window. In windowless mode, the Video Mixing Renderer does not load its Window Manager component, and therefore does not support the IBasicVideo or IVideoWindow interfaces. Instead, the application provides the playback window and sets a destination rectangle in the client area for the VMR to draw the video. The VMR uses a DirectDraw clipper object to ensure that the video is clipped to the application's window and does not appear on any other windows. The VMR does not subclass the application's window or install any system/process hooks.

In windowless mode, the sequence of events during connection and transition to the run state is as follows:

  • The upstream filter proposes a media type, which the VMR either accepts or rejects.
  • If the media type is accepted, the VMR calls the allocator-presenter to obtain a DirectDraw surface. If the surface is created successfully, the pins connect and the VMR is ready to transition into the run state.
  • When the filter graph runs, the decoder calls GetBuffer to get a media sample from the allocator. The VMR queries the allocator-presenter to ensure that the pixel depth, rectangle size, and other parameters on its DirectDraw surface are compatible with the incoming video. If they are compatible, the VMR returns the DirectDraw surface to the decoder. After the decoder has decoded into the surface, the VMR's Core Synchronization Unit validates the time stamps. This unit blocks the Receive call until the presentation time arrives. At that point, the VMR calls PresentImage on the allocator-presenter, which presents the surface to the graphics card.

The following illustration shows the VMR in windowless mode with multiple input streams.

VMR in Windowless Mode

Configuring the VMR-7 for Windowless Mode

To configure the VMR-7 for windowless mode, perform all of the following steps before connecting any of the VMR's input pins:

  1. Create the filter and add it to the graph.
  2. Call the IVMRFilterConfig::SetRenderingMode method with the VMRMode_Windowless flag.
  3. Optionally, configure the VMR for multiple input streams by calling IVMRFilterConfig::SetNumberOfStreams. The VMR creates an input pin for each stream. Use the IVMRMixerControl interface to set the Z-order and other parameters for the stream. For more information, see VMR with Multiple Streams (Mixing Mode).

    If you do not call SetNumberOfStreams, the VMR-7 defaults to one input pin. After the input pins are connected, the number of pins cannot be changed.

  4. Call IVMRWindowlessControl::SetVideoClippingWindow to specify the window in which the rendered video will appear.

Once these steps are completed, you can connect the VMR filter's input pins. There are various ways to build the graph, such as connecting pins directly, using Intelligent Connect methods such as IGraphBuilder::RenderFile, or using the Capture Graph Builder's ICaptureGraphBuilder2::RenderStream method. For more information, see General Graph-Building Techniques.

To set the position of the video within the application window, call the IVMRWindowlessControl::SetVideoPosition method. The IVMRWindowlessControl::GetNativeVideoSize method returns the native video size. During playback, the application should notify the VMR of the following Windows messages:

  • WM_PAINT: Call IVMRWindowlessControl::RepaintVideo to repaint the image.
  • WM_DISPLAYCHANGE: Call IVMRWindowlessControl::DisplayModeChanged. The VMR takes any actions that are needed to display the video at the new resolution or color depth.
  • WM_SIZE: Recalculate the position of the video and call SetVideoPosition again if necessary.

Note MFC applications must define an empty WM_ERASEBKGND message handler, or the video display area will not repaint correctly.

Configuring the VMR-9 for Windowless Mode

To configure the VMR-9 for windowless mode, use the steps described for the VMR-7 for Windowless mode, but use the IVMRFilterConfig9 and IVMRWindowlessControl9 interfaces. The only significant difference is that the VMR-9 creates four input pins by default, rather than one input pin. Therefore, you only need to call SetNumberOfStreams if you are mixing more than four video streams.

Example Code

The following code shows how to create a VMR-7 filter, add it to the DirectShow filter graph, and then put the VMR into windowless mode. For the VMR-9, use CLSID_VideoMixingRenderer9 in CoCreateInstance and the corresponding VMR-9 interfaces.

HRESULT InitializeWindowlessVMR(
    HWND hwndApp,         // Application window.
    IFilterGraph* pFG,    // Pointer to the Filter Graph Manager.
    IVMRWindowlessControl** ppWc,  // Receives the interface.
    DWORD dwNumStreams,  // Number of streams to use.
    BOOL fBlendAppImage  // Are we alpha-blending a bitmap?
    )
{
    IBaseFilter* pVmr = NULL;
    IVMRWindowlessControl* pWc = NULL;
    *ppWc = NULL;

    // Create the VMR and add it to the filter graph.
    HRESULT hr = CoCreateInstance(CLSID_VideoMixingRenderer, NULL,
       CLSCTX_INPROC, IID_IBaseFilter, (void**)&pVmr);
    if (FAILED(hr))
    {
        return hr;
    }
    hr = pFG->AddFilter(pVmr, L"Video Mixing Renderer");
    if (FAILED(hr))
    {
        pVmr->Release();
        return hr;
    }

    // Set the rendering mode and number of streams.
    IVMRFilterConfig* pConfig;
    hr = pVmr->QueryInterface(IID_IVMRFilterConfig, (void**)&pConfig);
    if (SUCCEEDED(hr))
    {
        pConfig->SetRenderingMode(VMRMode_Windowless);

        // Set the VMR-7 to mixing mode if you want more than one video
        // stream, or you want to mix a static bitmap over the video.
        // (The VMR-9 defaults to mixing mode with four inputs.)
        if (dwNumStreams > 1 || fBlendAppImage)
        {
            pConfig->SetNumberOfStreams(dwNumStreams);
        }
        pConfig->Release();

        hr = pVmr->QueryInterface(IID_IVMRWindowlessControl, (void**)&pWc);
        if (SUCCEEDED(hr))
        {
            pWc->SetVideoClippingWindow(hwndApp);
            *ppWc = pWc;  // The caller must release this interface.
        }
    }
    pVmr->Release();

    // Now the VMR can be connected to other filters.
    return hr;
}

The following sample applications demonstrate the concepts discussed in this topic:

  • VMRPlayer Sample
  • Cube Sample
  • VMRMix Sample

See Also

  • Using Windowless Mode


VMR with Multiple Streams (Mixing Mode)

The VMR can render multiple input streams. In this configuration, called mixing mode, the VMR loads its mixer and compositor to perform the mixing and blending prior to rendering. Mixing mode can be used either while the VMR is in windowed mode or windowless mode.

Mixing mode requires that the graphics driver supports the DDCAPS_BLTFOURCC and DDCAPS_BLTSTRETCH capability flags (color space conversion and stretch blitting, respectively). Almost all new graphics drivers have those capabilities. In addition, the driver must support the creation of Direct3D render targets for the current display pixel depth. Some devices do not support Direct3D operations when the display is set to 24 bits per pixel. For more information, see the DirectX Graphics SDK documentation.

Note When the VMR is mixing multiple video streams, the filter graph does not seek correctly. If you need to seek multiple video streams, you must create separate filter graphs that share the same custom allocator-presenter object. The VMRMulti sample application illustrates this approach.

Configuring the VMR-7 for Multiple Streams

To render multiple input streams with the VMR-7, do the following:

  1. Before connecting any of the VMR's input pins, call the IVMRFilterConfig::SetNumberOfStreams method with the number of streams. This causes the VMR to load the mixer and compositor and to create the specified number of input pins.
  2. Call IVMRFilterConfig::SetRenderingPrefs to specify various rendering preferences.
  3. Connect the pins to the upstream filters. The easiest way to do this is to call IGraphBuilder::RenderFile for each input stream. If the output pin on the upstream filter (usually a decoder) and the input pin on the VMR cannot agree on a connection, then a new instance of the VMR with default settings will be created. This will result in a new window with "ActiveMovie" in the title bar. To prevent this from happening, the application should always verify that the correct instance of the VMR is being used by calling a method such as IPin::ConnectedTo. Another option is to add the source filter and then connect the pins using IGraphBuilder::Connect.
  4. Use the IVMRMixerControl interface on the VMR to control parameters for each stream, such as the alpha value, the Z-ordering, and the output rectangle.
  5. Run the filter graph.

Configuring the VMR-9 for Multiple Streams

By default, the VMR-9 creates four input pins. If you want to mix more than four video streams, call IVMRFilterConfig9::SetNumberOfStreams before connecting any input pins. Use the IVMRMixerControl9 interface to set the stream parameters, such as alpha, Z-order, and position.

Positioning and Moving Video Rectangles in Composition Space

When the VMR mixes multiple input streams, it positions each stream within a normalized rectangle, called "composition space." Within composition space, the coordinates (0.0, 0.0) to (1.0, 1.0) form the visible video rectangle. Any coordinates that fall outside of this rectangle are clipped.

An application can perform special effects with moving, stretching, and shrinking the video from an input stream, by changing the destination rectangle in composition space for that stream. If the specified rectangle is a different size than the native video rectangle, the native video will be shrunk or stretched to fit. The destination rectangle is specified by calling the IVMRMixerControl::SetOutputRect method.

For example, assume that stream 0 (which corresponds to pin 0) contains the main video stream, and stream 1 (which corresponds to pin 1) contains a secondary video. Stream 1 can be positioned completely offscreen by specifying a normalized rectangle of { -1.0f, 0.0f, 0.0f, 1.0f }. Stream 1 can then be moved into the visible area by modifying the left and right sides of the rectangle on successive calls to SetOutputRect:

Time | Rectangle
t + 0 | { -1.0f, 0.0f, 0.0f, 1.0f }
t + 1 | { -0.9f, 0.0f, 0.1f, 1.0f }
t + 2 | { -0.8f, 0.0f, 0.2f, 1.0f }
... | ...
t + 10 | { 0.0f, 0.0f, 1.0f, 1.0f }

Moving a video streaam in composition space

At time t+10, the video from stream 1 is completely visible. In this example, the native size of stream 1 was maintained while it was moving. You could also stretch or shrink the rectangle to produce interesting effects. You can also flip the video vertically, by specifying a greater value for the top than the bottom, or mirror the video horizontally, by specifying a greater value for the left than the right.


VMR Renderless Playback Mode (Custom Allocator-Presenters)

In renderless playback mode, the VMR does not perform the rendering. Instead, it uses a custom allocator-presenter supplied by the application. This mode is useful for games and other types of applications that have sophisticated video effects. Renderless playback mode enables the applications to create and control its own DirectDraw surface (VMR-7) or Direct3D surface (VMR-9), and to access the video bits at presentation time.

In renderless mode, the VMR-9 does not automatically load its mixer component.

In renderless playback mode, the application does the following tasks:

  • Manages the playback window.
  • Allocates the DirectDraw or Direct3D object and the final frame buffer.
  • Notifies the rest of the playback system of the object being used.
  • Presents the frame buffer at the correct time.
  • Handles all resolution-mode changes, monitor changes, and surface losses. It must advise the rest of the playback system of these events.

The VMR does the following:

  • Handles all timing related to presenting the video frame.
  • Provides quality-control information to the application and the rest of the playback system.
  • Presents a consistent interface to the upstream components of the playback system, which are not aware that the application is providing the frame buffer allocation and performing the rendering.
  • Provides any mixing of video streams that may be required prior to rendering.

For more information about providing a custom allocator-presenter, see the following topics:

  • Supplying a Custom Allocator-Presenter for VMR-7
  • Supplying a Custom Allocator-Presenter for VMR-9


Supplying a Custom Allocator-Presenter for VMR-7

The allocator-presenter is responsible for allocating DirectDraw surfaces and presenting the video frames for rendering. In the vast majority of scenarios, the functionality of the default allocator-presenter will be more than sufficient for an application's needs. But by plugging in a custom allocator-presenter, an application can obtain direct access to the video bits and completely control the rendering process. The trade-off for this increased power is that the application must handle the added complexity of DirectDraw surface management.

Using a custom allocator-presenter

The preceding figure shows the communication interfaces used by the VMR and the allocator-presenter. A custom allocator-presenter that overrides all of the default allocation and presentation functionality must implement the IVMRImagePresenter and IVMRSurfaceAllocator interfaces, and optionally, IVMRWindowlessControl.

To replace the default allocator-presenter, an application calls the IVMRSurfaceAllocatorNotify::AdviseSurfaceAllocator method and passes in a pointer to the new allocator-presenter. In response to this call, the VMR will call the allocator-presenter's IVMRSurfaceAllocator::AdviseNotify method to provide the pointer to the VMR's IVMRSurfaceAllocatorNotify interface. The allocator-presenter will use this interface pointer when passing events to the VMR with the IVMRSurfaceAllocatorNotify::NotifyEvent method. This technique is demonstrated in the TxtPlayer Sample application.

As an alternate solution, an application can use both its own allocator-presenter and the default allocator-presenter. In this scenario, the custom allocator-presenter handles only those calls where custom functionality is needed, and passes the rest of the calls from the VMR through to the default allocator-presenter. In many cases, it is only necessary to override the IVMRImagePresenter interface.

Using two allocator-presenters

To use both a custom allocator-presenter and the default allocator-presenter, an application would first call IVMRSurfaceAllocatorNotify::AdviseSurfaceAllocator to provide a pointer to the new allocator-presenter. This causes the default allocator-presenter to be destroyed, so the application must create another instance of it by calling QueryInterface on the VMR and requesting the IVMRSurfaceAllocator interface. As shown in the preceding figure, the custom allocator-presenter overrides the IVMRImagePresenter interface methods, and simply passes all calls to the IVMRSurfaceAllocator interface through to the default implementation. The figure also shows the IVMRWindowlessControl interface as being implemented on the allocator-presenter. This technique is demonstrated in the Renderless Sample application.


Supplying a Custom Allocator-Presenter for VMR-9

To use a custom allocator-presenter with the Video Mixing Renderer 9 (VMR-9) filter, perform the following steps:

  1. Implement a class that supports the IVMRSurfaceAllocator9 and IVMRImagePresenter9 interfaces.
  2. Query the VMR-9 for the IVMRFilterConfig9 and IVMRSurfaceAllocatorNotify9 interfaces.
  3. Call the IVMRFilterConfig9::SetRenderingMode method with the VMR9Mode_Renderless flag.
  4. Call the IVMRSurfaceAllocatorNotify9::AdviseSurfaceAllocator method with a pointer to your allocator-presenter.
  5. Call the allocator-presenter's IVMRSurfaceAllocator9::AdviseNotify method with a pointer to the VMR-9 filter's IVMRSurfaceAllocatorNotify9 interface. This step and the previous step establish a communication link between the VMR-9 and the allocator-presenter.
  6. Allocate surfaces in the IVMRSurfaceAllocator9::InitializeDevice callback method:
    • Call the IVMRSurfaceAllocatorNotify9::SetD3DDevice method with a pointer to the Direct3D device and a handle to the monitor.
    • Create Direct3D surfaces that match the parameters given in the InitializeDevice method. You can use the VMR-9 filter's IVMRSurfaceAllocatorNotify9::AllocateSurfaceHelper method to allocate the surface.
    • Typically you will want the video frames to be drawn onto a texture surface, so that you can render the texture onto a Direct3D primitive. In that case, you may need to add the VMR9AllocFlag_TextureSurface flag to the VMR9AllocationInfo structure (the lpAllocInfo parameter). If the device does not support textures in the native video format, you might need to create a separate texture surface, and then copy the video frames from the video surface to the texture.
  7. The VMR-9 gets a surface from the allocator-presenter by calling the IVMRSurfaceAllocator9::GetSurface method.
  8. Present the image when the VMR-9 calls the IVMRImagePresenter9::PresentImage method. The parameters include a pointer to the Direct3D surface that contains the video image.
  9. If the Direct3D device is lost at any time, it is necessary to restore the device and the surfaces. For example, the device can be lost if the display mode changes or the user moves the window to another monitor.
  10. If the Direct3D device changes, call the VMR-9 filter's IVMRSurfaceAllocatorNotify9::ChangeD3DDevice method.
  11. When streaming stops, the VMR-9 calls the IVMRSurfaceAllocator9::TerminateDevice method. The allocator-presenter should release all of its Direct3D resources.

There are some differences between the VMR-7 and the VMR-9 in the way custom allocator-presenters are managed:

  • The VMR-9 filter's AllocateSurfaceHelper method is available for the allocator-presenter to use when allocating surfaces. This method makes it unnecessary for a custom allocator-presenter to forward any calls to the default allocator-presenter. For this reason, the CLSID of the VMR-9 filter's default allocator-presenter is not published.
  • Unlike the VMR-7, the VMR-9 does not provide a special DirectDraw Exclusive Mode allocator-presenter. The AllocateSurfaceHelper method makes this object unnecessary.
  • For interlaced video, the VMR-9 always de-interlaces the video before calling the PresentImage method. The allocator-presenter is no longer responsible for de-interlacing the image before displaying it.


DirectDraw Exclusive Mode

This topic applies to the VMR-7 only. The VMR-9 has a different technique for enabling exclusive mode.

In DirectDraw Exclusive Mode, an application takes exclusive control of the graphics hardware. This is useful for applications such as games, or perhaps full-screen video applications. Normally, the VMR creates the DirectDraw objects and sets the cooperative level to normal. However, to run the VMR in DirectDraw Exclusive Mode, the application itself must create the DirectDraw object and the primary surface, and call SetCooperativeLevel to specify exclusive mode.

The VMR has a special allocator-presenter that enables it to run in DirectDraw Exclusive Mode. To configure the VMR to use this allocator-presenter:

  1. Create the Filter Graph and add the VMR to it using the IFilterGraph::AddFilter method. For a code example, see VMR Windowless Mode.
  2. Create the Exclusive Mode allocator-presenter:
    IVMRImagePresenterExclModeConfig* pExclModeConfig;
CoCreateInstance(
        CLSID_AllocPresenterDDXclMode,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IVMRImagePresenterExclModeConfig,
        (void**)&pExclModeConfig
        );
  3. Configure the new allocator-presenter:
    pExclModeConfig->SetXlcModeDDObjAndPrimarySurface(...);
  4. Plug the new allocator-presenter into the VMR.
  5. Build the rest of the filter graph in the usual ways.


Building a VMR-9 Filter Graph

Because the Video Mixing Renderer 9 Filter (VMR-9) is not the default video renderer, an application that uses the VMR-9 must explicitly add it to the graph and connect it. This section presents two different approaches to building filter graphs with the VMR-9.

Using the Capture Graph Builder

The Capture Graph Builder is a helper object for building custom filter graphs. You can use it to build VMR-9 graphs as follows:

  1. Create and initialize the Capture Graph Builder, as described in the topic About the Capture Graph Builder.
  2. Call CoCreateInstance to create the VMR-9:
    IBaseFilter *pVmr = NULL;
hr = CoCreateInstance(CLSID_VideoMixingRenderer9, 0,
    CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&pVmr);
  3. Call IFilterGraph::AddFilter on the Filter Graph Manager to add the VMR-9 to the filter graph:
    hr = pGraph->AddFilter(pVmr, L"VMR9");
  4. Call IGraphBuilder::AddSourceFilter to add a source filter for the video file:
    IBaseFilter *pSource;
hr = pGraph->AddSourceFilter(L"C:\\Example.avi", L"Source1", &pSource);
  5. Call the ICaptureGraphBuilder2::RenderStream method to render the video stream to the VMR:
    hr = pBuild->RenderStream(0, 0, pSource, 0, pVmr);
  6. Optionally, call RenderStream again to render the audio stream:
    hr = pBuild->RenderStream(0, &MEDIATYPE_Audio, pSource, 0, NULL);

You can mix several video streams by calling AddSourceFilter and RenderStream for each source file.

Using the Filter Graph Manager

If you prefer not to use the Capture Graph Builder, you can build a VMR-9 graph simply using methods on the Filter Graph Manager, as follows:

  1. Create the VMR-9 and add it to the graph, as shown in the previous procedure.
  2. Use AddSourceFilter to add a source filter for the video file, as shown in the previous procedure.
  3. If you want to render the audio, create an instance of the DirectSound Renderer filter and add it to the filter graph.
  4. Use the IBaseFilter::EnumPins method to find an output pin on the source filter. See Enumerating Pins for details.
  5. Query the Filter Graph Manager for the IFilterGraph2 interface.
  6. Call IFilterGraph2::RenderEx with the AM_RENDEREX_RENDERTOEXISTINGRENDERERS flag. This call renders the output pin, using only the renderer filters already in the graph — in this case, the VMR-9 and the DirectSound Renderer. This prevents the Intelligent Connect logic from adding the default video renderer to the graph, which would leave the VMR-9 unconnected.

See Also

  • Building Graphs with the Capture Graph Builder


Displaying an Application-Supplied Bitmap on the Composited Image

Applications can use the VMR's "Mixer-Bitmap" feature to display alpha-blended channel logos, a user interface, or advertisements either partially or completely within the video rectangle. Because the blending is performed in hardware by the graphics processor, there is minimal impact to the playback performance of the Video Stream, and there are no detectable flicker or tearing artifacts. Applications can change the image displayed as frequently as they wish. It should be noted that changes are only reflected on the screen when the DirectShow filter graph is in the running state.

The VMR uses its mixer component to overlay the bitmap onto the composited image. With the VMR-7, the application must force the VMR to load its mixer, even if there is only a single video stream. This is not necessary with the VMR-9 since it loads its mixer by default.

To blend a static bitmap image with the video stream, the application creates the VMR and adds it to the graph, and then calls IVMRFilterConfig::SetNumberOfStreams. The value passed to this function identifies the number of input pins that the VMR should create. Applications can specify any value between 1 and MAX_MIXER_STREAMS; specifying a value of 1 is valid if the application only intends to display a single video stream. Even though the VMR-7 has a single input pin by default, this method must be called in order to force it to load its mixer component. (The VMR-9 loads its mixer and sets up four pins by default.)

The bitmap can be specified by either a handle to a GDI Device Context (hDC) or by a DirectDraw Surface interface. If the application wants the image to contain embedded alpha information (also known as per pixel alpha) it must place the image data in a DirectDraw Surface interface. This is because it is not currently possible to place per-pixel alpha information with a GDI Device Context. The DirectDraw surface must be either RGB32 or ARGB32, and should preferably be a system memory surface. It is not necessary for the surface dimensions to be a power of 2.

The VMR allows applications to specify the location and an overall transparency value for the image. The following code shows how to pass image data down to the VMR for subsequent blending:

HRESULT BlendApplicationImage(
  HWND hwndApp,
  IVMRWindowlessControl* pWc,
  HBITMAP hbm
)
{
    LONG cx, cy;
    HRESULT hr;
    hr = pWc->GetNativeVideoSize(&cx, &cy, NULL, NULL);
    if (FAILED(hr))
        return hr;

    HDC hdc = GetDC(hwndApp);
    if (hdc == NULL)
    {
        return E_FAIL;
    }

    HDC hdcBmp = CreateCompatibleDC(hdc);
    ReleaseDC(hwndApp, hdc);

    if (hdcBmp == NULL)
    {
        return E_FAIL;
    }

    BITMAP bm;
    if (0 == GetObject(hbm, sizeof(bm), &bm))
    {
        DeleteDC(hdcBmp);
        return E_FAIL;
    }

    HBITMAP hbmOld = (HBITMAP)SelectObject(hdcBmp, hbm);
    if (hbmOld == 0)
    {
        DeleteDC(hdcBmp);
        return E_FAIL;
    }

    VMRALPHABITMAP bmpInfo;
    ZeroMemory(&bmpInfo, sizeof(bmpInfo) );
    bmpInfo.dwFlags = VMRBITMAP_HDC;
    bmpInfo.hdc = hdcBmp;

    // Show the entire bitmap in the top-left corner of the video image.
    SetRect(&bmpInfo.rSrc, 0, 0, bm.bmWidth, bm.bmHeight);
    bmpInfo.rDest.left = 0.f;
    bmpInfo.rDest.top = 0.f;
    bmpInfo.rDest.right = (float)bm.bmWidth / (float)cx;
    bmpInfo.rDest.bottom = (float)bm.bmHeight / (float)cy;

    // Set the transparency value (1.0 is opaque, 0.0 is transparent).
    bmpInfo.fAlpha = 0.2f;

    IVMRMixerBitmap* pBmp;
    hr = pWc->QueryInterface(IID_IVMRMixerBitmap, (LPVOID *)&pBmp);
    if (SUCCEEDED(hr))
    {
        pBmp->SetAlphaBitmap(&bmpInfo);
        pBmp->Release();
    }

    DeleteObject(SelectObject(hdcBmp, hbmOld));
    DeleteDC(hdcBmp);
    return hr;
}

The concepts discussed in this topic are demonstrated in the VMRPlayer Sample sample application.


Creating Simple Animations with the Bitmap Image

To create a simple animated bitmap logo, put all of the bitmap "frames" into a single image, as shown in the following illustration.

VMR Image Strip

When you set the bitmap initially using IVMRMixerBitmap::SetAlphaBitmap, if the bitmap is in an HDC, set the rSrc field of the VMRALPHABITMAP structure to specify the size of the entire bitmap within the HDC. The top and left members of the structure are set to 0, and the right and bottom members are the width and height of the bitmap. If the bitmap is in a DirectDraw surface, then the size of the surface is known, so there is no need to specify rSrc in this method.

When you call IVMRMixerBitmap::UpdateAlphaBitmapParameters, use the rSrc member for both HDC and DirectDraw bitmaps, to specify the particular frame or rectangle within the image that you wish to display, and set the VMRBITMAP_SRCRECT flag in the dwFlags member.


Multi-Monitor Support

The VMR supports the IVMRMonitorConfig interface, which enables applications to control the VMR's behavior on multi-monitor systems. With the VMR-7, monitors are identified by a GUID, while with the VMR-9, an integer is used for this purpose.


Optimizing Mixing Performance

Important The optimizations described in this section are highly dependent on the underlying hardware. Unless you can guarantee what type of graphics hardware will be used with the application, by setting these flags you run the risk of seriously degrading the appearance of the rendered video image.

HDTV requires a lot of processing power, which on newer systems is provided mostly by the graphics card. But even if the graphics card and the decoder can support resolutions of 1920x1080, the user may not always have their monitor set to this resolution. In this case, the graphics chip is required to create a 1920x1080 image, and then reduce the resolution before sending it to the frame buffer.

Since this is a waste of processing power, the VMR provides a way to decimate (reduce) the image at the time it is being rendered onto the DirectDraw surface. This eliminates the extra memory copy required if the image has to be resized after it has been rendered. The method that provides this optimization is IVMRMixerControl::SetMixingPrefs, which must be called before the VMR is connected. The mixing preference flags cannot be changed once the graph is running. SetMixingPrefs can also be used to configure the filtering type and color space of the target surface.


Setting Deinterlace Preferences

The Video Mixing Renderer (VMR) supports hardware-accelerated deinterlacing, which improves rendering quality for interlaced video. The exact features that are available depend on the underlying hardware. The application can query for the hardware deinterlacing capabilities and set deinterlacing preferences through the IVMRDeinterlaceControl interface (VMR-7) or IVMRDeinterlaceControl9 interface (VMR-9). Deinterlacing is performed on a per-stream basis.

Note This section describes the IVMRDeinterlaceControl9 methods, but the VMR-7 versions are almost identical.

To get the deinterlacing capabilities for a video stream, do the following:

  1. Fill in a VMR9VideoDesc structure with a description of the video stream. Details of how to fill in this structure are given later.
  2. Pass the structure to the IVMRDeinterlaceControl9::GetNumberOfDeinterlaceModes method. Call the method twice. The first call returns the number of deinterlace modes the hardware supports for the specified format. Allocate an array of GUIDs of this size, and call the method again, passing in the address of the array. The second call fills the array with GUIDs. Each GUID identifies one deinterlacing mode.
  3. To get the capabiltiies of a particular mode, call the IVMRDeinterlaceControl9::GetDeinterlaceModeCaps method. Pass in the same VMR9VideoDesc structure, along with one of the GUIDs from the array. The method fills a VMR9DeinterlaceCaps structure with the mode capabilities.

The following code shows these steps:

VMR9VideoDesc VideoDesc;
DWORD dwNumModes = 0;
// Fill in the VideoDesc structure (not shown).
hr = pDeinterlace->GetNumberOfDeinterlaceModes(&VideoDesc,
    &dwNumModes, NULL);
if (SUCCEEDED(hr) && (dwNumModes != 0))
{
    // Allocate an array for the GUIDs that identify the modes.
    GUID *pModes = new GUID[dwNumModes];
    if (pModes)
    {
        // Fill the array.
        hr = pDeinterlace->GetNumberOfDeinterlaceModes(&VideoDesc,
            &dwNumModes, pModes);
        if (SUCCEEDED(hr))
        {
            // Loop through each item and get the capabilities.
            for (int i = 0; i < dwNumModes; i++)
            {
                VMR9DeinterlaceCaps Caps;
                hr = pDeinterlace->GetDeinterlaceModeCaps(pModes + i,
                    &VideoDesc, &Caps);
                if (SUCCEEDED(hr))
                {
                    // Examine the Caps structure.
                }
            }
        }
        delete [] pModes;
    }
}

Now the application can set the deinterlacing mode for the stream, using the following methods:

  • The SetDeinterlaceMode method sets the preferred mode. Use GUID_NULL to turn off deinterlacing.
  • The SetDeinterlacePrefs method specifies the behavior if the requested mode is not available.
  • The GetDeinterlaceMode method returns the preferred mode that you set.
  • The GetActualDeinterlaceMode method returns the actual mode in use, which might be a fallback mode, if the preferred mode is not available.

The method reference pages give more information.

Using the VMR9VideoDesc Structure

In the procedure given previously, the first step is to fill in a VMR9VideoDesc structure with a description of the video stream. Start by getting the media type of the video stream. You can do this by calling IPin::ConnectionMediaType on the VMR filter's input pin. Then confirm whether the video stream is interlaced. Only VIDEOINFOHEADER2 formats can be interlaced. If the format type is FORMAT_VideoInfo, it must be a progressive frame. If the format type is FORMAT_VideoInfo2, check the dwInterlaceFlags field for the AMINTERLACE_IsInterlaced flag. The presence of this flag indicates the video is interlaced.

Assume that the variable pBMI is a pointer to the BITMAPINFOHEADER structure in the format block. Set the following values in the VMR9VideoDesc structure:

  • dwSize: Set this field to sizeof(VMR9VideoDesc).
  • dwSampleWidth: Set this field to pBMI->biWidth.
  • dwSampleHeight: Set this field to abs(pBMI->biHeight).
  • SampleFormat: This field describes the interlace characteristics of the media type. Check the dwInterlaceFlags field in the VIDEOINFOHEADER2 structure, and set SampleFormat equal to the equivalent VMR9_SampleFormat flag. A helper function to do this is given below.
  • InputSampleFreq: This field gives the input frequency, which can be calculated from the AvgTimePerFrame field in the VIDEOINFOHEADER2 structure. In the general case, set dwNumerator to 10000000, and set dwDenominator to AvgTimePerFrame. However, you can also check for some well-known frame rates:
    Average time per frame | Frame rate (fps) | Numerator | Denominator
    166833 | 59.94 (NTSC) | 60000 | 1001
    333667 | 29.97 (NTSC) | 30000 | 1001
    417188 | 23.97 (NTSC) | 24000 | 1001
    200000 | 50.00 (PAL) | 50 | 1
    400000 | 25.00 (PAL) | 25 | 1
    416667 | 24.00 (Film) | 24 | 1

  • OutputFrameFreq: This field gives the output frequency, which can be calculated from the InputSampleFreq value and the interleaving characteristics of the input stream:
    • Set OutputFrameFreq.dwDenominator equal to InputSampleFreq.dwDenominator.
    • If the input video is interleaved, set OutputFrameFreq.dwNumerator to 2 x InputSampleFreq.dwNumerator. (After deinterlacing, the frame rate is doubled.) Otherwise, set the value to InputSampleFreq.dwNumerator.
  • dwFourCC: Set this field to pBMI->biCompression.

The following helper function converts AMINTERLACE_X flags to VMR9_SampleFormat values:

#define IsInterlaced(x) ((x) & AMINTERLACE_IsInterlaced)
#define IsSingleField(x) ((x) & AMINTERLACE_1FieldPerSample)
#define IsField1First(x) ((x) & AMINTERLACE_Field1First)

VMR9_SampleFormat ConvertInterlaceFlags(DWORD dwInterlaceFlags)
{
    if (IsInterlaced(dwInterlaceFlags)) {
        if (IsSingleField(dwInterlaceFlags)) {
            if (IsField1First(dwInterlaceFlags)) {
                return VMR9_SampleFieldSingleEven;
            }
            else {
                return VMR9_SampleFieldSingleOdd;
            }
        }
        else {
            if (IsField1First(dwInterlaceFlags)) {
                return VMR9_SampleFieldInterleavedEvenFirst;
             }
            else {
                return VMR9_SampleFieldInterleavedOddFirst;
            }
        }
    }
    else {
        return VMR9_SampleProgressiveFrame;  // Not interlaced.
    }
}


Using the VMR for DirectShow Filter Developers

This topic contains the following sections:

  • Requirements for Decoders
  • Stream Control
  • Quality Messages
  • Coordinate Mapping in the VMR
  • MPEG Decoder Preprocessing Transformations
  • Access to DirectDraw Surfaces
  • VMR Support for DirectX Video Acceleration
  • Working with Direct3D Render Targets
  • Per-Pixel Alpha Blending
  • DirectDraw Exclusive Mode
  • Optimizing Mixing Performance


Requirements for Decoders

Decoders that deliver samples to the VMR must observe the following rules:

  • There should be one subpicture frame delivered to the VMR for each video frame. The two frames should have the same time stamps.
  • If the subpicture has not changed, use the AM_GBF_NOTASYNCPOINT flag in the IMemAllocator::GetBuffer method to force the allocator to return a buffer containing the last frame delivered to the VMR. Just put a new time stamp on the sample and deliver it to the VMR again. If the subpicture fame is blank, you should still deliver it. The VMR will detect the empty frame and not blend it with the video. This test is performed by the VGA chip and does not affect the playback performance.
  • All samples, except for live streams, must have valid start and stop time stamps attached. (DVD is not a live stream.)
  • The media sample time stamps must be contiguous
  • The decoder must identify itself as VMR-capable for use by graph builders.
  • The subpicture stream should now contain embedded per-pixel alpha values. The ARGB4444 surface type is ideal for subpictures.
  • Do not assume that the stride of the subpicture is the same as the surface width. This is not always the case with the VMR.

See Also

  • About DirectX Video Acceleration


Stream Control

The IVMRVideoStreamControl interface on the VMR's input pin(s) enables applications and upstream filters to control the behavior of the mixer component, including the Z-order and the active state of the VMR's input streams. Although this interface is exposed on the pins, it operates on the VMR's mixer component, so it is only available when the mixer is loaded, which is when the VMR is processing multiple input streams. Upstream filters use the SetColorKey and GetColorKey methods to control the source color key. These methods enable effects such as the overlay of animation over video. Simply set the color key to the animation stream's background color, and the VMR will mix that stream with another video stream. Applications should take care not to change the color key to some value that is different than the value being used by an upstream filter, such as a decoder.

Filters use the GetStreamActiveState and SetStreamActiveState methods to tell the mixer whether to expect input data from a specified pin. For example, the Line21 Decoder uses these methods to activate the VMR's input pin for Line21 data only when that data is present in the stream. Setting a pin to an inactive state instructs the mixer not to wait for data from a specified pin before compositing the image.


Quality Messages

The VMR supports the IQualityControl interface and provides raw data to upstream filters. This behavior is identical to the old Overlay Mixer, but different from the old Video Renderer, which attempted to interpret the quality data before passing it upstream.


Coordinate Mapping in the VMR

This section describes the five transformations that are applied to a source image before it is mapped by the VMR onto the final output image.

  1. The transformation T(Src) maps the source rectangle to the destination rectangle. These are specified by the rcSource and rcTarget members of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure in the media type. This mapping preprocesses the source image as it passes to the VMR.
  2. The transformation T(Flag) performs any image manipulations specified by flags in the media sample. These included transformations such as the vertical translation and scale to accommodate the bob interlace flags. The interlace transformation doubles the image height and possibly translates the image by half of a video line if it is in the odd field.
  3. The transformation T(AR) adjusts the image to square pixels, based on the image aspect ratio. For VIDEOINFOHEADER media types, the aspect ratio is determined by the image size. For VIDEOINFOHEADER2 types, the aspect ratio is determined by the dwPictAspectRatioX and dwPictAspectRatioY fields, unless the AMCONTROL_PAD_TO_16x9 or AMCONTROL_PAD_TO_4x3 flags are set. This transformation assumes that the monitor display setting matches the physical aspect ratio of the monitor. For example, if the user has a monitor with 4 x 3 aspect ratio, but sets the display to 1280 x 768 pixels (5 x 3), the image will not have the correct aspect ratio.
  4. The transformation T(Mix) transforms positions the image within the destination image, using the normalized rectangles specified in the IVMRMixerControl methods. The normalized rectangles enable the application to organize how the source streams are positioned and scaled relative to each other. The VMR computes the destination image by computing the maximum dimensions of all the source images and centering each inside an overall bounding rectangle. The corners of the bounding rectangle are assigned the range (0,0) to (1,1). The bounding rectangle is fixed before the graph runs and remains constant even if streams are added or deleted. Destination rectangles for each stream can lie outside of the range (0,0) to (1,1) and still be valid. The normalized destination rectangle also has a pair of flags that modify the usage semantics of the destination coordinate. The flags can take the following values:
    • VMRDest_AdjustHeight (0x00000001): The height will be adjusted (and centered about the middle of the normalized rectangle) to maintain the image's aspect ratio.
    • VMRDest_AdjustWidth (0x00000002): The width will be adjusted (and centered about the middle of the normalized rectangle) to maintain the image's aspect ratio.
  5. Finally, a portion of the mixed image can be transformed by the mapping T(Dst), specified by the source and destination rectangles in the IBasicVideo interface on the VMR. If the Allocator-Presenter is replaced and the IBasicVideo interface is not used, the application must implement the IVMRWindowlessControl interface and map the coordinates back into a 2D linear space. The mouse coordinates returned to the DVD navigator must also be in this space. For example, if an application renders video onto a spinning cube, they would report back the entire display for the windowless control and return mouse coordinates relative to the display.

The overall image transformation from the source data to the final renderer is:

T = T(Src)* T(Flag) T(Ar) T(Mix)* T(Dst)*

where * indicates that the image could be clipped to the destination image at that stage. Note that these are all affine transformations, so the VMR can combine them into a single transformation.

The inverse of the transformation is:

Inverse of interlace transformation

The factor T(Src) T(Flag) T(Ar) is relative to the source resolution. In the factor T(Mix), the normalized source rectangle is relative to the aspect-corrected image. The normalized destination rectangle is relative to the output resolution. The following diagram shows these relationships.

Image Transformation Steps


MPEG Decoder Preprocessing Transformations

Letterbox and PanScan

The 4x3 image can be formed by either padding the top and bottom of the image (referred to as a Letterbox image) or by extracting a 4x3 portion of the image (referred to as a PanScan image). The menus and subpicture streams are overlaid on top of the final video image. The 16x9 ratio images are stored in a 4x3 anamorphic format. Stretching the anamorphic 4x3 aspect ratio 720x480 source video to a 16x9 aspect ratio forms the original 16x9 aspect image.

Below is a description of how to correctly display each of the modes and their highlights:

  • Widescreen: The source video stretched into the largest 16x9 area of the output window. The highlights are relative to the inside of the 16x9 area. Black bars should be added to either the top and bottom or to the sides to maintain a 16x9 area.
  • Pan Scan: From the 16x9 video, use the horizontal offset provided in the MPEG2 stream to extract a 4x3 subwindow. Place the 4x3 subwindow into the largest 4x3 area of the output client window. The highlight's coordinates are relative to the 4x3 output window and have no relationship to the source 16x9 video. Black bars should be added to either the top and bottom or to the sides to maintain a 4x3 area.
  • Letterbox: Compute the largest 4x3 area of the output window. Black bars should be added to either the top and bottom or to the sides to maintain a 4x3 area. The source anamorphic 4x3 video (representing a 16x9 image) is placed in the largest 16x9 subwindow inside of the 4x3 area. Black bars should be added to the top and bottom of the subwindow to maintain a 16x9 area. The highlight's coordinates are relative to the 4x3 area and have no relationship to the source 16x9 video. It is possible for a disk to specify a highlight that lies outside of the 16x9 area (but still in the 4x3 window). For 4x3 video, the video is placed in the largest 4x3 output area of the output client window. Black bars should be added to either the top and bottom or to the sides to maintain a 4x3 area.

MPEG preprocessing with the DVD Navigator and VMR

Currently, the decoder is passed a FORMAT_MPEG2_VIDEO media type (whose format block points to a MPEG2VIDEOINFO structure). On the output pins, the decoder produces a FORMAT_VideoInfo2 media type, whose format block points to a VIDEOINFOHEADER2 structure. The VIDEOINFOHEADER2's dwReserved field has been renamed to dwControls flags. Its new definition (in dvdmedia.h) is:

typedef struct tagVIDEOINFOHEADER2 {
  RECT     rcSource;
  RECT     rcTarget;
  DWORD    dwBitRate;
  DWORD    dwBitErrorRate;
  REFERENCE_TIME   AvgTimePerFrame;
  DWORD   dwInterlaceFlags;   // Use AMINTERLACE_* defines.
                             // Reject connection if undef'd bits are not 0.
  DWORD   dwCopyProtectFlags; // Use AMCOPYPROTECT_* defines.
                             // Reject connection if undef'd bits are not 0.
  DWORD   dwPictAspectRatioX; // X dimension of picture aspect ratio,
                              // for example, 16 for 16x9 display.
  DWORD   dwPictAspectRatioY; // Y dimension of picture aspect ratio,
                              // for example  9 for 16x9 display.
  union {
      DWORD dwControlFlags;   // Use AMCONTROL_* defines,
                              // use this from now on
      DWORD dwReserved1;    // for backward compatibility
                            //(must be 0;connection
                            // rejected otherwise).
    };
  DWORD     dwReserved2;  // Must be 0; reject connection otherwise.
  BITMAPINFOHEADER    bmiHeader;
} VIDEOINFOHEADER2;

The VIDEOINFOHEADER2.dwControlFlags will now contain the new bits.

AMCONTROL_USED | 0x00000001
AMCONTROL_PAD_TO_4x3 | 0x00000002
AMCONTROL_PAD_TO_16x9 | 0x00000004

AMCONTROL_USED is used to test whether these new flags are supported. A source filter should set the AMCONTROL_USED flag and see if QueryAccept(MediaType) succeeds on the downstream pin. If it is rejected, then the AMCONTROL flags cannot be used and dwReserved1 must be set to 0.

AMCONTROL_PAD_TO_4x3 indicates that the image should be padded and displayed in a 4x3 area.

AMCONTROL_PAD_TO_16x9 indicates that the image should be padded and displayed in a 16x9 area.

The decoder should either blindly copy or process the bits. If the decoder performs letterboxing itself, then it must alter the pixel aspect ratio, pad the image and remove the corresponding AMCONTROL_* bits.

The MPEG2VIDEOINFO.dwFlags now contains three flags for controlling for controlling how the content should be displayed:

  • AMMPEG2_DoPanScan (0x00000001): If this flag is set, the MPEG-2 video decoder should crop the output image based on pan-scan vectors in picture_display_extension and change the picture aspect ratio to 4x3. The VMR should not receive a 16x9 sample with this flag. A simple implementation might alter the source rectangle to indicate a 540 wide source region with a left edge equal to the display offset in the picture_display_extension.
  • AMMPEG2_LetterboxAnalogOut (0x00000020): When a hardware decoder displays this stream to a video output (usually an SVIDEO connector on the card), it should apply the rules for displaying a 16x9 sample on a 4x3 display.

    A software decoder (or a hardware decoder producing output sent to the VMR) has two options when processing images:

    1. 1)Ignore this flag and pass the VideoInfoHeader2 contents to the VMR (the AMCONTROL_PAD_TO_4x3 flag will already be set by the DVD Navigator on the sample). The VMR will encounter a 16x9 video sample with the AMCONTROL_PAD_TO_4x3 flag set and a 4x3 subpicture stream. The application must set the output normalized destination rectangles of the two streams to be the same width.
    2. 2)Convert the anamorphic stream to a 4x3 image by padding the top and bottom of the image and setting the image aspect ratio to 4x3 (see Letterbox above) and removing the AMCONTROL_PAD_TO_4x3 bit from the VIDEOINFOHEADER2.

    DirectXVA decoders that blend the video and subpicture streams will have to process this flag. If the hardware cannot scale the blended subpicture, then the decoder should produce a separate subpicture stream for the VMR to blend with the video.

  • AMMPEG2_WidescreenAnalogOut (0x00000200): When a hardware decoder displays this stream to a video output (usually an SVIDEO connector on the card), it should assume a 16x9 (anamorphic) display.

    A software decoder (or a hardware decoder producing output sent to the VMR) has two options when processing an anamorphic image:

    1. Ignore this flag and copy the VideoInfoHeader2 contents to the VMR. The VMR will pad 4x3 images to 16x9 if they have the AMCONTROL_PAD_TO_16x9 set.
    2. Pad the output image to a 16x9 image and remove the AMCONTROL_PAD_TO_16x9 bit.

Most decoders should use GetMediaType to detect a media change on the input pin and copy the VIDEOINFOHEADER2 contents (contained in the MPEG2INFOHEADER) to the output pin. They will probably only process the PanScan bit.

The following example code shows how to copy the VIDEOINFOHEADER2 contents from an input pin to an output pin.

#include <dvdmedia.h>
HRESULT CopyMPeg2ToVideoInfoHeader2(CMediaSample* pInSample, CMediaSample* pOutSample)
{
    HRESULT hr = S_OK;
    // Check for a media type on the input sample.
    AM_MEDIA_TYPE* pInType;
    if (pInSample->GetMediaType(&pInType) == S_OK)
    {
        // Make sure it's an MPEG2 Video format.
        if ((pInType->formattype == FORMAT_MPEG2_VIDEO) &&
            (pInType->cbFormat >= sizeof(MPEG2VIDEOINFO)))
        {
            hr = S_OK; // Initialize hr for the CMediaType constructor.
            CMediaType outType(*pInType, &hr);
            if (FAILED(hr))
            {
                DeleteMediaType( pInType );
                return hr;
            }

            // Set the format type GUID.
            outType.SetFormatType(&FORMAT_VideoInfo2);

            // Truncate the format block to include just the VIDEOINFOHEADER part.
            MPEG2VIDEOINFO *pMPeg2Header = (MPEG2VIDEOINFO*)pInType->pbFormat;
            BYTE *pVIH = (BYTE*)&pMPeg2Header->hdr;
            hr = (outType.SetFormat(pVIH, sizeof(VIDEOINFOHEADER2)) ? S_OK : E_OUTOFMEMORY);
            if (SUCCEEDED(hr))
            {
                hr = pOutSample->SetMediaType(&outType);
            }
        }
        else
        {
            ASSERT(FALSE); // Not a MPEG2 header.
            hr = VFW_E_INVALIDMEDIATYPE;
        }
        DeleteMediaType( pInType );
    }

    return hr;
}


WHQL tests

Test various combinations of PanScan/Letterbox and 704/720 wide images:

  • 16x9 video (704 or 720 wide), 16x9 subpicture (720 wide)
  • 16x9 video (704 or 720 wide) Letterbox, 4x3 subpicture
  • 16x9 video (704 or 720 wide) PanScan, 4x3 subpicture
  • 4x3 video (704 or 720 wide), 4x3 subpicture


Access to DirectDraw Surfaces

The Media Sample objects provided by the VMR to upstream filters support the IVMRSurface interface. To obtain the interface, call QueryInterface on the IMediaSample interface and specify IID_IVMRSurface. Upstream filters can then use the IVMRSurface methods to access and manipulate the surface that has been created by the VMR.


VMR Support for DirectX Video Acceleration

DirectX Video Acceleration is an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for hardware acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. DirectX VA is documented in the Windows DDK. The IAMVideoAccelerator interface, which provides user mode access to DirectX VA functionality on a hardware device, is documented in this SDK.

The VMR supports IAMVideoAccelerator, and its implementation is identical to the old Overlay Mixer except for one important difference. The Overlay Mixer guaranteed that the output is rendered into an overlay surface, while the VMR can send the output for further processing, for example a 3D operation, or it might send the output to an offscreen surface which is then blitted to the primary surface.

See Also

  • About DirectX Video Acceleration


Working with Direct3D Render Targets

New media subtypes have been defined for use with the VMR-7 and the VMR-9. When an upstream filter proposes a connection with one of these subtypes, it indicates to the VMR that the rendering is to be performed on a Direct3D render target. For VMR-7, this will be a DirectX 7 Direct3D render target, and for VMR-9 this will be a DirectX 9 Direct3D render target. If the VMR is in mixing mode, the surface will also be a Direct3D texture surface. If the VMR is not in mixing mode, the surface will be a regular Direct3D surface. The ARGB pixel formats are only supported when the VMR is in mixing mode. The new subtypes are:

VMR-7 | VMR-9
MEDIASUBTYPE_RGB32_D3D_DX7_RT | MEDIASUBTYPE_RGB32_D3D_DX9_RT
MEDIASUBTYPE_RGB16_D3D_DX7_RT | MEDIASUBTYPE_RGB16_D3D_DX9_RT
MEDIASUBTYPE_ARGB32_D3D_DX7_RT | MEDIASUBTYPE_ARGB32_D3D_DX9_RT
MEDIASUBTYPE_ARGB4444_D3D_DX7_RT | MEDIASUBTYPE_ARGB4444_D3D_DX9_RT
MEDIASUBTYPE_ARGB1555_D3D_DX7_RT | MEDIASUBTYPE_ARGB1555_D3D_DX9_RT

These new types are defined in uuids.h along with the other DirectShow media subtypes. The MEDIASUBTYPE_RGB32 media types are an RGBx888 format and MEDIASUBTYPE_RGB16 media types are an RGB565 format. For more information on these pixel formats, see the DirectX Graphics documentation.

Requesting an Unlocked Surface

Locking and unlocking DirectDraw surfaces are computationally expensive operations. When using the Direct3D render target media subtypes, the upstream filter needs the surfaces to be unlocked so that it can operate on them with the graphics hardware. To avoid an unnecessary locking-unlocking operation, the VMR supports a new flag on the IMemAllocator::GetBuffer method, AM_GBF_NODDRAWSURFACELOCK, that instructs the VMR not to lock the DirectDraw surface before passing a sample to the upstream filter. When this flag is used, calls to IMediaSample::GetPointer will fail because there is no locked pointer. To obtain access to the DirectDraw surface, the filter must call QueryInterface on the returned IMediaSample object and request the IVMRSurface interface. Obviously, the upstream filter must ensure that the surface is not locked when it releases the sample back to the free list.


Per-Pixel Alpha Blending

Four new media subtypes have been defined for per-pixel alpha blending. These subtypes are only supported when the VMR is in mixing mode. The VMR will reject the connection if it is not in mixing mode when an upstream filter attempts to connect using one of these subtypes. These subtypes are defined in uuids.h:

  • MEDIASUBTYPE_ARGB1555
  • MEDIASUBTYPE_ARGB4444
  • MEDIASUBTYPE_ARGB32
  • MEDIASUBTYPE_AYUV

For more information on MEDIASUBTYPE_AYUV, see the DXVA documentation in the Microsoft Platform DDK.


Using the Stream Buffer Engine

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Engine enables an application to seek, pause, and record a live video stream without interrupting the stream. Transitions between live and recorded content are seamless. Currently, the Stream Buffer Engine supports MPEG-2 video and digital video (DV) sources, at capture rates up to 20 megabits per second (Mbps).

Applications can use the Stream Buffer Engine to provide VCR-like functions, such as pause, seek, and multi-speed play ("trick mode"), while rendering a live video stream. Applications can also use the Stream Buffer Engine to record video for later playback.

You can use the Stream Buffer Engine directly in your application, or indirectly through the Video Control. The Video Control automatically encrypts the content using the TV Ratings Components.

To learn about using the Stream Buffer Engine with the Video Control, see the following topic:

  • Using the Stream Buffer Engine with the Video Control.

To learn about using the Stream Buffer Engine directly in a DirectShow-based application, see the following topics:

  • About the Stream Buffer Engine
  • Creating Stream Buffer Graphs
  • Creating Stream Buffer Recordings
  • Buffering in the Stream Buffer Engine
  • Stream Buffer Engine Reference


About the Stream Buffer Engine

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Engine uses two or more independent filter graphs. One filter graph, called the sink graph, captures data from a live source. The other graphs, called source graphs, render the data. Using several filter graphs is more flexible and scalable than using a single graph for both capture and rendering. The sink graph stores the data in a temporary buffer or in permanent files, while the source graphs read the data from those files. Several source graphs can read data from the same sink source.

A source graph can:

  • Seek forward or backward within the stored content.
  • Pause playback, without interrupting the data coming from the capture graph.
  • Play faster or slower than normal.
  • Play in reverse.

Tasks such as scheduling a viewing session or a recording session are left to the client application.


Creating Stream Buffer Graphs

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Engine uses multiple filter graphs:

  • A sink graph captures data and stores it in temporary backing files. The sink graph uses the Stream Buffer Sink filter.
  • One or more source graphs read the data from the backing files. The source graphs use the Stream Buffer Source filter.

Stream Buffer Engine filter graphs

The sink graph can also create permanent recordings, which can be viewed later using the Stream Buffer Source filter. Currently, the Stream Buffer Engine supports MPEG-2 video and digital video (DV) sources.

To build the sink graph:

  1. Create an instance of the Filter Graph Manager.
  2. Create the Stream Buffer Sink filter and add it to the filter graph.
  3. Build a regular DirectShow capture graph or television graph, but route all of the streams to the Stream Buffer Sink filter, instead of sending them to the usual renderer filters.
  4. Query the Stream Buffer Sink filter for the IStreamBufferSink interface.
  5. Call the IStreamBufferSink::LockProfile method. This method does several things:
    • Creates a named stub file that references the temporary backing files. The Stream Buffer Source filter can use this stub file to access the backing files.
    • Locks the Stream Buffer Sink filter, which prevents the inputs from changing.
    • Stores a profile that describes the input streams. This profile enables the Stream Buffer Source filter to render the streams from a separate filter graph.

    The profile is automatically unlocked when the graph stops.

For MPEG-2 content, insert the MPEG-2 Video Analyzer filter directly between the MPEG-2 Demultiplexer filter and the Stream Buffer Sink filter. The Video Analyzer filter enables the source graph to use playback rates faster than 4x or less than 0 (reverse playback).

MPEG-2 sink graph

For more information about building the capture portion of the sink graph, see the following topics:

  • Video Capture
  • Writing Digital TV Applications with DirectX

To build the source graph:

  1. Create a new instance of the Filter Graph Manager.
  2. Create the Stream Buffer Source filter and add it to the filter graph.
  3. Establish a source for the Stream Buffer Source filter, by doing one of the following:
    • Call IStreamBufferSource::SetStreamSink with a pointer to the sink filter's IStreamBufferSink interface. With this method, the sink graph and the source graph must share the same process space.
    • Call IFileSourceFilter::Load with the name of the stub file that was given in the LockProfile method. This is equivalent to calling SetStreamSink, but the graphs can be in separate processes.
    • Call IFileSourceFilter::Load with the name of a recorded file. (See Creating Stream Buffer Recordings.)
  4. Enumerate the output pins on the Stream Buffer Source filter.
  5. Call IGraphBuilder::Render on each pin to render the stream.

The following code shows how to create the source graph. Error checking is omitted for brevity.

// Create the filter graph.
CComPtr<IGraphBuilder> pSourceGraph;
hr = pSourceGraph.CoCreateInstance(CLSID_FilterGraph);

// Add the Stream Buffer Source filter to the graph.
CComPtr<IStreamBufferSource> pSource;
hr = pSource.CoCreateInstance(CLSID_StreamBufferSource);
CComQIPtr<IBaseFilter> pSourceF(pSource);
hr = pSourceGraph->AddFilter(pSourceF, L"SBESource");

// Set the stream sink.
hr = pSource->SetStreamSink(pSink);
// Or, pass in the file name, as follows:
// CComQIPtr<IFileSourceFilter> pFileSource(pSource);
// pFileSource->Load(L"StubFileNameHere", 0);

// Render each output pin.
CComPtr<IPin> pSourcePinOut;
CComPtr<IEnumPins> pPinEnum;
hr = pSourceF->EnumPins(&pPinEnum);
while (hr = pPinEnum->Next(1, &pSourcePinOut, 0), hr == S_OK)
{
    hr = pSourceGraph->Render(pSourcePinOut);
    pSourcePinOut.Release();
}

To start capturing, run the sink graph. To start playback, run the source graph. The source graph can be run, paused, or stopped independently of the sink graph.

There is normally no reason to stop the source graph until the viewing or recording session is over. The sink graph uses a ring buffer, so the total size of the temporary backing files will not exceed a preset maximum. Stopping the source graph will create holes in the recorded content. For television sources, it is possible to change channels while the source graph is running.

To seek the source graph, use the IStreamBufferMediaSeeking interface directly on the Stream Buffer Source filter. For finished recordings, you can also use the IMediaSeeking or IMediaPosition interfaces on the Filter Graph Manager. Do not use these interfaces for live content, however. For more information, see Stream Buffer Source Filter.


Creating Stream Buffer Recordings

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Sink filter writes data to temporary backing files. To create a permanent recording, call the IStreamBufferSink::CreateRecorder method on the Stream Buffer Sink filter. This method creates a new Recording object, which the application uses to start and stop the recording.

The CreateRecorder method specifies the type of recording to make:

  • A content recording writes the data to a new permanent file.
  • A reference recording creates a stub file that refers to the existing backing files, which are made permanent. Create a reference recording if you want to save data that has already been captured.

To start the recording, call IStreamBufferRecordControl::Start. In a reference recording, you can set a start time in the past, as long as the backing files still contain that portion of the stream. To stop the recording and close the file, call IStreamBufferRecordControl::Stop.

The following code shows how to create a reference recording:

CComPtr<IUnknown> pRecUnk;
hr = pSink->CreateRecorder(
    L"C:\\MyRecording.sbe",
    RECORDING_TYPE_REFERENCE,
    &pRecUnk);
if (SUCCEEDED(hr))
{
        // Start the recording.
        CComQIPtr<IStreamBufferRecordControl> pRecControl(pRecUnk);
        REFERENCE_TIME rtStart = -5000; // Start 5 seconds ago.
        pRecControl->Start(&rtStart);

        // Later:
        pRecControl->Stop(0); // Stop the recording and close the file.
}

To play the recording, create a source graph containing the Stream Buffer Source filter and call IFileSourceFilter::Load to set the file name. (See Creating Stream Buffer Graphs.)

Content Recordings

When a content recording begins, the Stream Buffer Sink filter stops writing to the backing files and starts writing to the recording file. The recording file is not destroyed when the application exits. The file length is limited only by disk storage space. When the recording ends, the Stream Buffer Sink filter starts writing data to the backing files again.

The sink filter can only make one content recording at a time.

Reference Recordings

A reference recording creates a stub file, which contains information about the recording but does not contain the captured data. The capture data remains in the backing files, and the stub file does not grow as more content is recorded.

A reference recording also creates data files that are hard links to the backing files. The data files are stored as hidden system files in the same directory as the stub file. The naming convention for these files is stubfilename_#.SBE. For example, if the stub file is named MyFile.SBE, the data files are named MyFile_1.SBE, MyFile_2.SBE, and so forth.

Each data file references an entire backing file, even if the backing file starts earlier than the start time for the recording, or stops later than the stop time. The stub file contains the start and stop times for the recording, so any additional data is skipped on playback.

Note Because the data files are actually hard links to the backing files, any limitations associated with hard links apply to these files. For example, hard links must be on the same volume as the original file. Also, the backing files are not deleted when the main stub file is deleted; the application should delete them when they are no longer wanted.


Buffering in the Stream Buffer Engine

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Sink filter stores the data that it captures in temporary backing files. By default, it uses six files, each holding 5 minutes of data, for a total buffer of 30 minutes. (The default settings can be changed through the IStreamBufferConfigure interface.)

Once the buffer limit is reached, the Stream Buffer Sink filter begins to delete files, starting from the oldest file. If a source graph is currently reading from that file, the sink filter deletes the next oldest file instead, creating a "time hole" in the playback. Time holes are caused when the source graph pauses for too long or seeks backward to the beginning of the buffer.

Time holes in stream buffer content

When the Stream Buffer Source filter reaches the gap where the file was deleted, it moves to the next file. However, because the presentation times haven't changed, the last frame from the older file is displayed for the duration of the deleted file. The video therefore appears to freeze for that period of time. To avoid this, the source graph should seek forward to the next valid data.

The Stream Buffer Engine sends several graph events to warn the application when files have gone stale or are about to go stale:

  • STREAMBUFFER_EC_CONTENT_BECOMING_STALE. Sent when the source filter lags behind the sink filter by more than a preset number of files. See IStreamBufferConfigure::GetBackingFileCount.
  • STREAMBUFFER_EC_STALE_DATA_READ. Sent when the source filter is reading a file that has been marked for deletion.
  • STREAMBUFFER_EC_STALE_FILE_DELETED. Sent when a file is deleted.
  • STREAMBUFFER_EC_TIMEHOLE. Sent when the source filter reaches a time hole. The event parameters indicate the time and size of the hole.

For more information, see Stream Buffer Engine Event Codes.

The content in a recording never goes stale. For more information, see Creating Stream Buffer Recordings.


Writing DirectShow Filters

If you are developing a filter for use in a Microsoft DirectShow filter graph, read the articles in this section. In general, you do not have to read this section if you are writing a DirectShow application. Most applications do not access filters or the filter graph at the level discussed in this section.

  • Introduction to DirectShow Filter Development
  • Building DirectShow Filters
  • How Filters Connect
  • Data Flow for Filter Developers
  • Threads and Critical Sections
  • Quality-Control Management
  • DirectShow and COM
  • Writing Transform Filters
  • Writing Video Renderers
  • Writing Capture Filters
  • Exposing Capture and Compression Formats
  • Registering a Custom File Type
  • Creating a Filter Property Page


Introduction to DirectShow Filter Development

This section gives a brief outline of the tasks involved in developing a custom DirectShow filter. It also provides links to topics that discuss these tasks in greater detail. Before reading this section, read the topics in About DirectShow, which describe the overall DirectShow architecture.

DirectShow Base Class Library

The DirectShow SDK includes a set of C++ classes for writing filters. Although they are not required, these classes are the recommended way to write a new filter. To use the base classes, compile them into a static library and link the .lib file to your project, as described in Building DirectShow Filters.

The base class library defines a root class for filters, the CBaseFilter class. Several other classes derive from CBaseFilter, and are specialized for particular kinds of filters. For example, the CTransformFilter class is designed for transform filters. To create a new filter, implement a class that inherits from one of the filter classes. For example, your class declaration might be as follows:

class CMyFilter : public CTransformFilter
{
private:
    /* Declare variables and methods that are specific to your filter.
public:
    /* Override various methods in CTransformFilter */
};

For more information about the DirectShow base classes, see the following topics:

  • DirectShow Base Classes
  • Building DirectShow Filters

Creating Pins

A filter must create one or more pins. The number of pins can be fixed at design time, or the filter can create new pins as needed. Pins generally derive from the CBasePin class, or from a class that inherits CBasePin, such as CBaseInputPin. The filter's pins should be declared as member variables in the filter class. Some of the filter classes already define the pins, but if your filter inherits directly from CBaseFilter, you must declare the pins in your derived class.

Negotiating Pin Connections

When the Filter Graph Manager tries to connect two filters, the pins must agree on various things. If they cannot, the connection attempt fails. Generally, pins negotiate the following:

  • Transport. The transport is the mechanism that the filters will use to move media samples from the output pin to the input pin. For example, they can use the IMemInputPin interface ("push model") or the IAsyncReader interface ("pull model").
  • Media type. Almost all pins use media types to describe the format of the data they will deliver.
  • Allocator. The allocator is the object that creates the buffers that hold the data. The pins must agree which pin will provide the allocator. They must also agree on the size of the buffers, the number of buffers to create, and other buffer properties.

The base classes implement a framework for these negotiations. You must complete the details by overriding various methods in the base class. The set of methods that you must override depends on the class and on the functionality of your filter. For more information, see How Filters Connect.

Processing and Delivering Data

The primary function of most filters is to process and deliver media data. How that occurs depends on the type of filter:

  • A push source has a worker thread that continuously fills samples with data and delivers them downstream.
  • A pull source waits for its downstream neighbor to request a sample. It responds by writing data into a sample and delivering the sample to the downstream filter. The downstream filter creates the thread that drives the data flow.
  • A transform filter has samples delivered to it by its upstream neighbor. When it receives a sample, it processes the data and delivers it downstream.
  • A renderer filter receives samples from upstream, and schedules them for rendering based on the time stamps.

Other tasks related to streaming include flushing data from the graph, handling the end of the stream, and responding to seek requests. For more information about these issues, see the following topics:

  • Data Flow for Filter Developers
  • Quality-Control Management
  • Threads and Critical Sections

Supporting COM

DirectShow filters are COM objects, typically packaged in DLLs. The base class library implements a framework for supporting COM. It is described in the section DirectShow and COM.


Building DirectShow Filters

The DirectShow base classes are recommended for implementing DirectShow filters. To build with the base classes, perform the following steps, in addition those listed in Setting Up the Build Environment:

  • Build the base class library, located in the directory Samples\Multimedia\DirectShow\BaseClasses, under the SDK root directory. There are two versions of the library: a retail version (Strmbased.lib) and a debug version (Strmbasd.lib).
  • Include the header file Streams.h.
  • Use the __stdcall calling convention.
  • Use the multithreaded C run-time library (debug or retail, as appropriate).
  • Include a definition (.def) file that exports the DLL functions. The following is an example of a definition file. It assumes that the output file is named MyFilter.dll.
    LIBRARY MYFILTER.DLL
EXPORTS
    DllMain             PRIVATE
    DllGetClassObject   PRIVATE
    DllCanUnloadNow     PRIVATE
    DllRegisterServer   PRIVATE
    DllUnregisterServer PRIVATE
  • Link to the following lib files.
    Debug Build | Strmbasd.lib, Msvcrtd.lib, Winmm.lib
    Retail Build | Strmbase.lib, Msvcrt.lib, Winmm.lib

  • Choose the "ignore default libraries" option in the linker settings.
  • Declare the DLL entry point in your source code, as follows:
    extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID);
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return DllEntryPoint((HINSTANCE)(hModule), dwReason, lpReserved);
}

Previous Versions

For versions of the base class library before DirectShow 9.0, you must also do the following:

  • For debug builds, define the preprocessor flag DEBUG.

This step is not required for the version of the base class library that is available in DirectShow 9.0 and later.

See Also

  • DirectShow Base Classes


How Filters Connect

This article describes how filters connect in Microsoft® DirectShow®. The article is intended for filter developers. If you are writing a DirectShow application, you can probably ignore the details presented here.

This article contains the following topics:

  • Pin Connections
  • Negotiating Media Types
  • Negotiating Allocators
  • Providing a Custom Allocator
  • Reconnecting Pins

See Also

  • CBasePin Connection Process


Pin Connections

Filters connect at their pins, through the IPin interface. Output pins connect to input pins. Each pin connection has a media type, described by the AM_MEDIA_TYPE structure.

An application connects filters by calling methods on the Filter Graph Manager, never by calling methods on the filters or pins themselves. The application can directly specify which filters to connect, by calling the IFilterGraph::ConnectDirect or IGraphBuilder::Connect method; or it can connect filters indirectly, using a graph-building method such as IGraphBuilder::RenderFile.

For the connection to succeed, both filters must be in the filter graph. The application can add a filter to the graph by calling the IFilterGraph::AddFilter method. The Filter Graph Manager may add filters to the graph, as well. When a filter is added, the Filter Graph Manager calls the filter's IBaseFilter::JoinFilterGraph method to notify the filter.

The general outline of the connection process is the following:

  1. The Filter Graph Manager calls IPin::Connect on the output pin, passing a pointer to the input pin.
  2. If the output pin accepts the connection, it calls IPin::ReceiveConnection on the input pin.
  3. If the input pin also accepts the connection, the connection attempt succeeds and the pins are connected.

Some pins can be disconnected and reconnected while the filter is active. This type of reconnection is called a dynamic reconnection. For more information, see Dynamic Graph Building. However, most filters do not support dynamic reconnection.

Filters are usually connected in downstream order—in other words, the filter's input pins are connected before its output pins. A filter should always support this order of connection. Some filters also support connections in the opposite order—output pins first, followed by input pins. For example, it might be possible to connect a MUX filter's output pin to the file-writer filter, before connecting the MUX filter's input pins.

When a pin's Connect or ReceiveConnection method is called, the pin must verify that it can support the connection. The details depend on the particular filter. The most common tasks include the following:

  • Check that the media type is acceptable
  • Negotiate an allocator
  • Query the other pin for required interfaces.


Negotiating Media Types

When the Filter Graph Manager calls the IPin::Connect method, it has several options for specifying a media type:

  • Complete type: If the media type is fully specified, the pins attempt to connect with that type. If they cannot, the connection attempt fails.
  • Partial media type: A media type is partial if the major type, subtype, or format type is GUID_NULL. The value GUID_NULL acts as a "wildcard," indicating that any value is acceptable. The pins negotiate a type that is consistent with the partial type.
  • No media type: If the Filter Graph Manager passes a NULL pointer, the pins can agree to any media type that is acceptable to both pins.

If the pins do connect, the connection always has a complete media type. The purpose of the media type given by the Filter Graph Manager is to limit the possible connection types.

During the negotiation process, the output pin proposes a media type by calling the input pin's IPin::ReceiveConnection method. The input pin can accept or reject the proposed type. This process repeats until either the input pin accepts a type, or the output pin runs out of types and the connection fails.

How an output pin selects media types to propose depends on the implementation. In the DirectShow base classes, the output pin calls IPin::EnumMediaTypes on the input pin. This method returns an enumerator that enumerates the input pin's preferred media types. Failing that, the output pin enumerates its own preferred types.

Working with Media Types

In any function that receives an AM_MEDIA_TYPE parameter, always validate the values of cbFormat and formattype before dereferencing the pbFormat member. The following code is incorrect:

if (pmt->formattype == FORMAT_VideoInfo)
{
    VIDEOINFOHEADER *pVIH = (VIDEOINFOHEADER*)pmt->pbFormat;
    // Wrong!
}

The following code is correct:

if ((pmt->formattype == FORMAT_VideoInfo) &&
    (pmt->cbFormat > sizeof(VIDEOINFOHEADER) &&
    (pbFormat != NULL))
{
    VIDEOINFOHEADER *pVIH = (VIDEOINFOHEADER*)pmt->pbFormat;
    // Now you can example pVIH.
}


Negotiating Allocators

When two pins connect, they need a mechanism for exchanging media data. This mechanism is called the transport. In general, the DirectShow architecture is neutral about transports. Two filters can agree to connect using any transport that both support.

The most common transport is the local memory transport, in which the media data resides in main memory. Two flavors of local memory transport exist, the push model and the pull model. In the push model, the source filter pushes data to the downstream filter, using the IMemInputPin interface on the downstream filter's input pin. In the pull model, the downstream filter requests data from the source filter, using the IAsyncReader interface on the source filter's output pin. For more information on these two data-flow models, see Data Flow in the Filter Graph.

In local memory transport, the object responsible for allocating memory buffers is called the allocator. An allocator supports the IMemAllocator interface. Both pins share a single allocator. Either pin can provide an allocator, but the ouput pin selects which allocator to use.

The output pin also sets the allocator properties, which determine how many buffers are created by the allocator, the size of each buffer, and the memory alignment. The output pin might defer to the input pin for the buffer requirements.

In an IMemInputPin connection, allocator negotiation works as follows:

  1. Optionally, the output pin calls IMemInputPin::GetAllocatorRequirements. This method retrieves the input pin's buffer requirements, such as memory alignment. In general, the output pin should honor the input pin's request, unless there is a good reason not to.
  2. Optionally, the output pin calls IMemInputPin::GetAllocator. This method requests an allocator from the input pin. The input pin provides one, or returns an error code.
  3. The output pin selects an allocator. It can use one provided by the input pin, or create its own.
  4. The output pin calls IMemAllocator::SetProperties to set the allocator properties. However, the allocator might not honor the requested properties. (For example, this can happen if the input pin provides the allocator.) The allocator returns the actual properties as an output parameter in the SetProperties method.
  5. The outpin calls IMemInputPin::NotifyAllocator to inform the input pin of the selection.
  6. The input pin should call IMemAllocator::GetProperties to verify whether the allocator properties are acceptable.
  7. The output pin is responsible for committing and decommitting the allocator. This occurs when streaming starts and stops.

In an IAsyncReader connection, allocator negotiation works as follows:

  1. The input pin calls IAsyncReader::RequestAllocator on the output pin. The input pin specifies its buffer requirements and, optionally, provides an allocator.
  2. The output pin selects an allocator. It can use the one provided by the input pin, if any, or create its own.
  3. The output pin returns the allocator as an outgoing parameter in the RequestAllocator method. The input pin should check the allocator properties.
  4. The input pin is responsible for committing and decommitting the allocator.
  5. At any time during the allocator negoriation process, either pin can fail the connection.
  6. If the output pin uses the input pin's allocator, it can use that allocator only to deliver samples to that input pin. The owning filter must not use the allocator to deliver samples to other pins.

See Also

  • Providing a Custom Allocator


Providing a Custom Allocator

This section describes how to provide a custom allocator for a filter. Only IMemInputPin connections are described, but the steps for an IAsyncReader connection are similar.

First, define a C++ class for the allocator. Your allocator can derive from one of the standard allocator classes, CBaseAllocator or CMemAllocator, or you can create an entirely new allocator class. If you create a new class, it must expose the IMemAllocator interface.

The remaining steps depend on whether your allocator belongs to an input pin or an output pin on your filter. Input pins play a different role than output pins during the allocator negotiation phase, because the output pin ultimately selects the allocator.

Providing a Custom Allocator for an Input Pin

To provide an allocator for an input pin, override the input pin's CBaseInputPin::GetAllocator method. Within this method, check the m_pAllocator member variable. If this variable is non-NULL, it means the allocator has already been selected for this connection, so the GetAllocator method must return a pointer to that allocator. If m_pAllocator is NULL, it means the allocator has not been selected, so the GetAllocator method should return a pointer to the input pin's preferred allocator. In that case, create an instance of your custom allocator and return its IMemAllocator pointer. The following code shows how to implement the GetAllocator method:

STDMETHODIMP CMyInputPin::GetAllocator(IMemAllocator **ppAllocator)
{
    CheckPointer(ppAllocator, E_POINTER);
    if (m_pAllocator)
    {
        // We already have an allocator, so return that one.
        *ppAllocator = m_pAllocator;
        (*ppAllocator)->AddRef();
        return S_OK;
    }
    // No allocator yet, so propose our custom allocator. The exact code
    // here will depend on your custom allocator class definition.
    HRESULT hr = S_OK;
    CMyAllocator *pAlloc = new CMyAllocator(&hr);
    if (!pAlloc)
    {
        return E_OUTOFMEMORY;
    }
    if (FAILED(hr))
    {
        delete pAlloc;
        return hr;
    }
    // Return the IMemAllocator interface to the caller.
    return pAlloc->QueryInterface(IID_IMemAllocator, (void**)ppAllocator);
}

When the upstream filter selects an allocator, it calls the input pin's IMemInputPin::NotifyAllocator method. Override the CBaseInputPin::NotifyAllocator method to check the allocator properties. In some cases, the input pin might reject the allocator if it is not your custom allocator, although this may cause the entire pin connection to fail.

Providing a Custom Allocator for an Output Pin

To provide an allocator for an output pin, override the CBaseOutputPin::InitAllocator method to create an instance of your allocator:

HRESULT MyOutputPin::InitAllocator(IMemAllocator **ppAlloc)
{
    HRESULT hr = S_OK;
    CMyAllocator *pAlloc = new CMyAllocator(&hr);
    if (!pAlloc)
    {
        return E_OUTOFMEMORY;
    }
    if (FAILED(hr))
    {
        delete pAlloc;
        return hr;
    }
    // Return the IMemAllocator interface.
    return pAlloc->QueryInterface(IID_IMemAllocator, void**)ppAllocator);}
}

By default, the CBaseOutputPin class requests an allocator from the input pin first. If that allocator is not suitable, the output pin creates its own allocator. To force the connection to use your custom allocator, override the CBaseOutputPin::DecideAllocator method. However, be aware that this can prevent your output pin from connecting with certain filters, because the other filter may also require its own custom allocator.

See Also

  • Negotiating Allocators


Reconnecting Pins

During a pin connection, a filter can disconnect and reconnect one of its other pins, as follows:

  1. The filter calls IPin::QueryAccept on the other filter's pin, and specifies the new media type.
  2. If QueryAccept returns S_OK, the filter calls IFilterGraph2::ReconnectEx to reconnect the pins.

The following are some examples of when a filter might need to reconnect pins:

  • Tee filters. A tee filter splits an input stream into multiple outputs without changing the data in the stream. A tee filter can accept a range of media types, but the types must match across all pin connections. Therefore, when the input pin connects, the filter might need to renegotiate any existing connections on the output pins, and vice versa. For an example, see the InfTee Filter Sample.
  • Trans-in-place filters. A <A HREF="#ProjectID110:transform_inplace_filter" ID="PopUp" CLASS="PopLink">transform-in-place filter</A> modifies the input data in the original buffer instead of copying the data to a separate output buffer. A trans-in-place filter must use the same allocator for both the upstream and the downstream connections. The first pin to connect (input or output) negotiates an allocator in the usual way. When the other pin connects, however, the fist allocator might not be acceptable. In that case, the second pin choose a different allocator, and the first pin reconnects using the new allocator. For an example implementation, see the CTransInPlaceFilter class.

In the ReconnectEx method, the Filter Graph Manager asynchronously disconnects and reconnects the pins. The filter must not attempt the reconnection unless QueryAccept returns S_OK. Otherwise, the pin will be left disconnected, causing graph errors. Also, the filter should request the reconnection from inside the IPin::Connect method, on the same thread. If the Connect method returns on one thread, while another thread makes the reconnection request, the Filter Graph Manager might run the graph before it makes the reconnection, causing graph errors.


Data Flow for Filter Developers

This section describes in detail how data moves through the filter graph. It focuses on local memory transport using the IMemInputPin or IAsyncReader interface. It is intended for developers who are writing their own custom filters. For a general introduction to how Microsoft DirectShow handles data flow, see Data Flow in the Filter Graph.

A lot of data moves through a filter graph. It falls roughly into two categories: media data and control data. In general, media data travels downstream and control data travels upstream. Media data includes the video frames, audio samples, MPEG packets, and so forth that make up a stream, but also includes flush commands, end-of-stream notifications, and other data that travels with the stream. Control data is not part of the media stream. Examples of control data are quality-control requests and seek commands.

This section contains the following articles.

  • Delivering Samples
  • Processing Data
  • End-of-Stream Notifications
  • New Segments
  • Flushing
  • Seeking
  • Dynamic Format Changes

See Also

  • Threads and Critical Sections
  • Quality-Control Management


Delivering Samples

This article describes how a filter delivers a sample. It describes both the push model, using IMemInputPin methods, and the pull model, using IAsyncReader.

Push Model: Delivering a Sample

The output pin delivers a sample by calling the IMemInputPin::Receive method or the IMemInputPin::ReceiveMultiple method, which is equivalent but delivers an array of samples. The input pin can block inside Receive (or ReceiveMultiple). If the pin might block, its IMemInputPin::ReceiveCanBlock method should return S_OK. If the pin guarantees never to block, ReceiveCanBlock should return S_FALSE. The S_OK return value does not mean that Receive always blocks, just that it might.

Although Receive can block to wait for a resource to become available, it should not block to wait for more data from the upstream filter. Doing so can cause a deadlock where the upstream filter waits for the downstream filter to release the sample, which never happens because the downstream filter is waiting on the upstream filter. If a filter has multiple input pins, however, one pin can wait for another pin to receive data. For example, the AVI Mux filter does this so that it can interleave audio and video data.

A pin might reject a sample for a number of reasons:

  • The pin is flushing (see Flushing).
  • The pin is not connected.
  • The filter is stopped.
  • Some other error occurred.

The Receive method should return S_FALSE in the first case, and a failure code in the other cases. The upstream filter should stop sending samples when the return code is anything other than S_OK.

You can consider the first three cases to be "expected" failures, in the sense that the filter was in the wrong state to receive samples. An unexpected failure would be one that causes the pin to reject a sample even though the pin is in a receiving state. If an error of this type occurs, the pin should send an end-of-stream notification downstream, and send an EC_ERRORABORT event to the Filter Graph Manager.

In the DirectShow base classes, the CBaseInputPin::CheckStreaming method checks for the general failure cases—flushing, stopped, and so forth. The derived class will need to check for failures that are specific to the filter. In case of an error, the CBaseInputPin::Receive method sends the end-of-stream notification and the EC_ERRORABORT event.

Pull Model: Requesting a Sample

In the IAsyncReader interface, the input pin requests samples from the output pin by calling one of the following methods:

  • IAsyncReader::Request
  • IAsyncReader::SyncRead
  • IAsyncReader::SyncReadAligned

The Request method is asynchronous; the input pin calls IAsyncReader::WaitForNext to wait for the request to complete. The other two methods are synchronous.

See Also

  • Receiving and Delivering Samples


Processing Data

Parsing Media Data

If your filter parses media data, do not trust headers or other self-describing data in the content. For example, do not trust size values that appear in AVI RIFF chunks or MPEG packets. Common examples of this kind of error include:

  • Reading N bytes of data, where the value of N came from the content, without checking N against the actual size of your buffer.
  • Jumping to a byte offset within a buffer, without verifying that the offset falls within the buffer.

Another common class of errors involves not validating format descriptions that are found in the content. For example:

  • A BITMAPINFOHEADER structure can be followed by a color table. The BITMAPINFO structure is defined as a BITMAPINFOHEADER structure followed by an array of RGBQUAD values that make up the color table. The size of the array is determined by the value of biClrUsed. Never copy a color table into a BITMAPINFO without first checking the size of the buffer that was allocated for the BITMAPINFO structure.
  • A WAVEFORMATEX structure might have extra format information appended to the structure. The cbSize member specifies the size of the extra information.

During pin connection, a filter should verify that all format structures are well-formed and contain reasonable values. If not, reject the connection. In the code that validates the format structure, be especially careful about arithmetic overflow. For example, in a BITMAPINFOHEADER, the width and height are 32-bit long values but the image size (which is a function of the product of the two) is only a DWORD value.

If format data from the source is larger than your allocated buffer, do not truncate the source data in order to copy it into your buffer. Doing so can create a structure whose implicit size is larger than its actual size. For example, a bitmap header might specify a palette table which no longer exists. Instead, reallocate the buffer or simply fail the connection.

Errors During Streaming

When the graph is running, if your filter receives malformed content, it should terminate streaming. Do the following:

  • Return an error code from Receive.
  • Call IPin::EndOfStream on the downstream filter.
  • Call CBaseFilter::NotifyEvent to post an EC_ERRORABORT event.

Format Changes

Several mechanisms exist for filters to change formats mid-stream. Each of them involves more than one step, which creates the potential for false acceptances. If your filter gets a request for a dynamic format change, then it must either reject the request, or else honor the new format when it arrives. Similarly, never switch formats unless the other filter agrees. For more information, see Dynamic Format Changes.


End-of-Stream Notifications

When a source filter is done sending data, it calls the IPin::EndOfStream method on the downstream input pin. The downstream filter propagates the call to the next filter, and so on. When the EndOfStream call reaches the renderer, the renderer sends an EC_COMPLETE event to the Filter Graph Manager. If the renderer has multiple input pins, it delivers the EC_COMPLETE event after every input pin has received the end-of-stream notification.

A filter must serialize EndOfStream calls with other streaming calls, such as IMemInputPin::Receive. (In other words, the downstream filter must always receive the calls in the correct order.)

In some cases, a downstream filter might detect the end of the stream before the source filter does. (For example, the downstream filter might be parsing the stream.) In that case, the downstream filter can send the end-of-stream notification, in which case it should return S_FALSE from IMemInputPin::Receive until the graph stops or flushes. The S_FALSE return value informs the source filter to stop sending data.

Default Handling of EC_COMPLETE

By default, the Filter Graph Manager does not forward every EC_COMPLETE event to the application. Instead, it waits until all streams have signaled EC_COMPLETE and then sends a single EC_COMPLETE event. Thus, the application receives the event after every stream has completed.

To determine the number of streams, the Filter Graph Manager counts the number of filters that support seeking (through IMediaSeeking or IMediaPosition) and have a rendered input pin, which is defined as an input pin with no corresponding outputs. The Filter Graph Manager determines whether a pin is rendered in one of two ways:

  • The pin's IPin::QueryInternalConnections method returns zero in the nPin parameter.
  • The filter exposes the IAMFilterMiscFlags interface and returns the AM_FILTER_MISC_FLAGS_IS_RENDERER flag.

End-of-Stream Notifications in Pull Mode

In an IAsyncReader connection, the source filter does not send an end-of-stream notification. Instread, this is done by the downstream filter, which is typically a parser filter. The parser sends the EndOfStream call downstream. It does not send one upstream to the source filter.

See Also

  • Delivering the End of Stream


New Segments

A segment is a group of media samples that share a common start time, stop time, and playback rate. The IPin::NewSegment method signals the start of a new segment. It provides a way for a source filter to inform downstream filters that the time and rate information has changed. For example, if the source filter seeks to a new point in the stream, it calls NewSegment with the new start time.

Some downstream filters use the segment information when they process samples. For example, in a format that uses interframe compression, if the stop time falls on a delta frame, the source filter may need to send additional samples after the stop time. This enables the decoder to decode the final delta frame. To determine the correct final frame, the decoder refers to the segment stop time. As another example, audio renderers use the segment rate along with the audio sampling rate to generate the correct audio output.

In the push model, the source filter initiates the NewSegment call. In the pull model, this is done by the parser filter. In either case, the filter calls NewSegment on the downstream input pin, which propagates the call to the next filter, until the call reaches the renderer. Filters must serialize NewSegment calls with other streaming calls, such as IMemInputPin::Receive.

Stream time resets to zero after each new segment. Time stamps on samples delivered after the segment start from zero.


Flushing

While the filter graph is running, arbitrary amounts of data can be moving through the graph. Some of it might be in queues, waiting to be delivered. There are times when the filter graph needs to remove this pending data as quickly as possible and replace it with new data. After a seek command, for example, the source filter generates samples from a new position in the source. To minimize latency, downstream filters should discard any samples that were created before the seek command. The process of discarding samples is called flushing. It enables the graph to be more responsive when events alter the normal data flow.

Flushing is handled slightly differently by the pull model than the push model. This article starts by describing the push model; then it describes the differences in the pull model.

Flushing happens in two stages.

  • First, the source filter calls IPin::BeginFlush on the downstream filter's input pin. The downstream filter starts rejecting samples from upstream. It also discards any samples it is holding, and sends the BeginFlush call downstream to the next filter.
  • When the source filter is ready to send new data, it calls IPin::EndFlush on the input pin. This signals the downstream filter that it can receive new samples. The downstream filter sends the EndFlush call to the next filter.

In the BeginFlush method, the input pin does the following:

  1. Calls BeginFlush on downstream input pins.
  2. Rejects any further calls that stream data, including Receive and EndOfStream.
  3. Unblocks any upstream filters that are blocked waiting for a sample from the filter's allocator. Some filters decommit their allocators for this purpose.
  4. Exits from any waits that block streaming. For example, renderer filters block when paused. They also block when they are waiting to render a sample at the correct stream time. The filter must unblock, so that samples queued upstream can be delivered and rejected. This step ensures that all upstream filters eventually unblock.

In the EndFlush method, the input pin does the following:

  1. Waits for all queued samples to be discarded.
  2. Frees any buffered data. This step can sometimes be performed in the BeginFlush method. However, BeginFlush is not synchronized with the streaming thread. The filter must not process or buffer any more data between the call to BeginFlush and the call to EndFlush.
  3. Clears any pending EC_COMPLETE notifications.
  4. Calls EndFlush downstream.

At this point, the filter can accept samples again. All samples are guaranteed to be more recent than the flush.

In the pull model, the parser filter initiates flushing, rather than the source filter. Not only does it call IPin::BeginFlush and IPin::EndFlush on the downstream filter, it also calls IAsyncReader::BeginFlush and IAsyncReader::EndFlush on the output pin of the source filter. If the source filter has pending read requests, it will discard them.

See Also

  • Flushing Data


Seeking

Filters support seeking through the IMediaSeeking interface. The application queries the Filter Graph Manager for IMediaSeeking and uses it to issue seek commands. The Filter Graph Manager distributes each seek command to all of the renderer filters in the graph. Each renderer passes the command upstream, through the output pins of the upstream filters, until it reaches a filter that can execute the seek. Typically a source filter or parser filter, such as the AVI Splitter, carries out the seek operation.

When a filter performs a seek operation, it flushes any pending data. The result is to minimize the latency of seek commands, because existing data is flushed from the graph. After a seek command, stream time resets to zero.

The following diagram illustrates the sequence of events.

If a parser filter has more than one output pin, it typically designates one of them to accept seek commands. The other pins reject or ignore any seek commands they receive. In this way, the parser keeps all of its streams synchronized.

The IMediaPosition interface has been deprecated for filters. Automation clients still need to use this interface on the Filter Graph Manager, because IMediaSeeking is not Automation-compatible, but the Filter Graph Manager translates all IMediaPosition calls into IMediaSeeking calls.

See Also

  • Flushing
  • Time and Clocks in DirectShow


Dynamic Format Changes

When two filters connect, they agree on a media type, which describes the format of the data that the upstream filter will deliver. In most cases, the media type is fixed for the duration of the connection. However, DirectShow does offer limited support for filters to change the media type. When a filter switches media types, it is called a dynamic format change. If you are writing a DirectShow filter, you should be aware of the mechanisms for dynamic format changes. Even if your filter does not support such changes, it should respond correctly if another filter requests a new format.

DirectShow defines several distinct mechanisms for dynamic format changes, depending on the state of filter graph and the type of change that is required.

  • If the graph is stopped, the pins can reconnect and renegotiate the media type. For more information, see Reconnecting Pins.
  • Some filters can reconnect pins even while the graph is active (running or paused). For more information about this mechanism, see Dynamic Reconnection.

Otherwise, if the graph is active, but the filters in question do not support dynamic pin reconnections, there are three possible mechanisms for changing the format:

  • QueryAccept (Downstream) is used when If an output pin proposes a format change to its downstream peer, but only if the new format does not require a larger buffer.
  • QueryAccept (Upstream) is used when an input pin proposes a format change to its upstream peer. The new format can be the same size, or it can be larger.
  • ReceiveConnection is used when an output pin proposes a format change to its downstream peer, and the new format requires a larger buffer.

See Also

  • Handling Format Changes from the Video Renderer


QueryAccept (Downstream)

This mechanism enables an output pin to propose a new format to its downstream peer. The new format must not require a larger buffer size. The output pin does the following:

  1. Calls IPin::QueryAccept or IPinConnection::DynamicQueryAccept on the downstream pin, to verify whether the other pin can accept the new media type (see illustration, step A).
  2. If the return value from step 1 is S_OK, the pin attaches the media type to the next sample. To do this, first it calls IMemAllocator::GetBuffer to obtain the sample (B). Then it calls IMediaSample::SetMediaType to attach the media type to that sample (C). By attaching the media type to the sample, the filter indicates that the format has changed, starting with that sample.
  3. The pin delivers the sample (D).
  4. When the downstream filter receives the sample, it calls IMediaSample::GetMediaType to retrieve the new media type.

All pins support the QueryAccept method. However, this method is slightly ambiguous, because a return value of S_OK does not always guarantee that you can change the format while the graph is active. Some filters might return S_OK but reject the change if the graph is active. The DynamicQueryAccept method, which is supported by some input pins, explicitly defines S_OK to mean the pin can change formats while active. If an input pin supports the IPinConnection interface, you should call DynamicQueryAccept rather than QueryAccept.

In most cases, this mechanism does not allow for drastic changes to the format, such as changing the bit depth. One situation in which it can be used is when a video decoder switches palettes. The basic details of the format stay the same, such as the image dimensions and the bit depth, but the new media type has a different set of palette entries.

Implementation Note

In the DirectShow base classes, CBasePin::QueryAccept calls the CheckMediaType method, which is also called during the initial pin connection. In the case of a transform filter, the input pin's CheckMediaType method should always check whether the output pin is connected, and if so, whether the input media type is compatible with the output media type. Therefore, this implementation will likely be valid for QueryAccept. If not, you should override QueryAccept in order to perform any additional checks that are needed. Also, note that the CTransformFilter class encapsulates this logic within the CheckInputType and CheckTransform methods. The CTransInPlaceFilter class, on the other hand, always calls QueryAccept on the next upstream or downstream filter.

The CBaseInputPin::Receive method checks for a media type on the incoming sample, and if there is one, calls CheckMediaType. However, it does not update the pin's m_mt member, which holds the current media type. When your filter processes the sample, you should check the sample for a media type. If there is a new type, you will probably need to store it, either by calling SetMediaType on your pin or by setting the value of m_mt directly. On the other hand, the CVideoTransformFilter class, which is designed for video transform filters, stores the media type when it changes. For details, see the source code for CVideoTransformFilter::Receive in the DirectShow base class library.

In some cases, you might simply pass the QueryAccept call downstream, then attach the media type to the output sample and let the downstream filter handle the format change.


QueryAccept (Upstream)

This mechanism enables an input pin to propose a format change to its upstream peer. The downstream filter must attach a media type to the sample that the upstream filter will obtain in its next call to IMemAllocator::GetBuffer. In order to do this, however, the downstream filter must provide a custom allocator for the connection. This allocator must implement a private method that the downstream filter can use to set the media type on the next sample.

The following steps occur:

  1. The downstream filter checks whether the pin connection uses the filter's custom allocator. If the upstream filter owns the allocator, the downstream filter cannot change the format.
  2. The downstream filter calls IPin::QueryAccept on the upstream output pin (see illustration, step A).
  3. If QueryAccept returns S_OK, the downstream filter calls the private method on its allocator in order to set the media type. Within this private method, the allocator calls IMediaSample::SetMediaType on the next available sample (B).
  4. The upstream filter calls GetBuffer to get a new sample (C) and IMediaSample::GetMediaType to get the media type (D).
  5. When the upstream filter delivers the sample, it should leave the media type attached to that sample. That way, the downstream filter can confirm that the media type has changed (E).

If the upstream filter accepts the format change, it must also be able to switch back to the original media type.

The main examples of this kind of format change involve the DirectShow video renderers.

  • The original Video Renderer filter can switch between RGB and YUV types during streaming. When the filter connects, it requires an RGB format that matches the current display settings. This guarantees that it can fall back on GDI if it needs to. After streaming begins, if DirectDraw is available, the Video Renderer requests a format change to a YUV type. Later, it might switch back to RGB if it loses the DirectDraw surface for any reason.
  • The newer Video Mixing Renderer (VMR) filter will connect with any format that is supported by the graphics hardware, including YUV types. However, the graphics hardware might change the stride of the underlying DirectDraw surface in order to optimize performance. The VMR filter uses QueryAccept to report the new stride, which is specified in the biWidth member of the BITMAPINFOHEADER structure. The source and target rectangles in the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure identify the region where the video should be decoded.

Implementation Note

It is unlikely that you will write a filter that needs to request upstream format changes, since this is mainly a feature of video renderers. However, if you write a video transform filter or a video decoder, your filter must respond correctly to requests from the video renderer.

A trans-in-place filter that sits between the video renderer and the decoder should pass all QueryAccept calls upstream. Store the new format information when it arrives.

A copy-transform filter (that is, a non-trans-in-place filter) should implement one of the following behaviors:

  • Pass format changes upstream and store the new format information when it arrives. Your filter must use a custom allocator so that it can attach the format to the upstream sample.
  • Perform the format conversion inside the filter. This is probably easier than passing the format change upstream. However, it might be less efficient than letting the decoder filter decode into the correct format.
  • As a last resort, simply reject the format change. (For more information, refer to the source code for the CTransInPlaceOutputPin::CheckMediaType method in the DirectShow base class library.) Rejecting a format change can reduce performance, however, because it prevents the video renderer from using the most efficient format.

The following pseudo-code shows how you might implement a copy-transform filter (derived from CTransformFilter) that can switch between YUV and RGB output types. This example assumes that the filter does the conversion itself, rather than passing the format change upstream.

HRESULT CMyTransform::CheckInputType(const CMediaType *pmt)
{
    if (pmt is a YUV type that you support) {
        return S_OK;
    }
    else {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
}

HRESULT CMyTransform::CheckTransform(
    const CMediaType *mtIn, const CMediaType *mtOut)
{
    if (mtOut is a YUV or RGB type that you support)
    {
        if ((mtIn has the same video dimensions as mtOut) &&
            (you support the mtIn-to-mtOut transform))
        {
            return S_OK;
        }
    }
    // otherwise
    return VFW_E_TYPE_NOT_ACCEPTED;
}

// GetMediaType: Return a preferred output type.
HRESULT CMyTransform::GetMediaType(int iPosition, CMediaType *pMediaType)
{
    if (iPosition < 0) {
        return E_INVALIDARG;
    }
    switch (iPosition)
    {
    case 0:
        Copy the input type (YUV) to pMediaType
        return S_OK;
    case 1:
        Construct an RGB type that matches the input type.
        return S_OK;
    default:
        return VFW_S_NO_MORE_ITEMS;
    }
}

// SetMediaType: Override from CTransformFilter.
HRESULT CMyTransform::SetMediaType(
    PIN_DIRECTION direction, const CMediaType *pmt)
{
    // Capture this information...
    if (direction == PINDIR_OUTPUT)
    {
       m_bYuv = (pmt->subtype == MEDIASUBTYPE_UYVY);
    }
    return S_OK;
}

HRESULT CMyTransform::Transform(
    IMediaSample *pSource, IMediaSample *pDest)
{
    // Look for format changes from downstream.
    CMediaType *pMT = NULL;
    HRESULT hr = pDest->GetMediaType((AM_MEDIA_TYPE**)&pMT);
    if (hr == S_OK)
    {
        hr = m_pOutput->CheckMediaType(pMT);
        if(FAILED(hr))
        {
            DeleteMediaType(pMT);
            return E_FAIL;
        }
        // Notify our own output pin about the new type.
        m_pOutput->SetMediaType(pMT);
        DeleteMediaType(pMT);
    }
    // Process the buffers
    if (m_bYuv) {
        return ProcessFrameYUV(pSource, pDest);
    }
    else {
        return ProcessFrameRGB(pSource, pDest);
    }
}


ReceiveConnection

This mechanism enables an output pin to propose a format change to its downstream peer, when the new format requires a larger buffer. The output pin does the following:

  1. Calls IPin::ReceiveConnection on the downstream input pin.
  2. If ReceiveConnection succeeds, calls IMemInputPin::NotifyAllocator on the input pin.

In addition, the output pin may need to call IMemAllocator::SetProperties and then decommit and recommit the allocator in order to change buffer sizes. Make sure to deliver all pending samples in the old format before changing the buffer size.

Some MPEG-2 decoders use this mechanism to switch between MPEG-1 and MPEG-2 output or if the video size changes.


Handling Format Changes from the Video Renderer

This section decribes how a decoder filter or transform filter should handle format changes from the video renderer.

Video Renderer Filter

When the old Video Renderer filter connects, it requires an RGB format that matches the display format of the primary monitor. This enables it to use GDI for rendering if DirectDraw is not available. When playback starts, the Video Renderer may switch to a DirectDraw-compatible format. To verfify whether the upstream filter can support the new format, the Video Renderer calls IPin::QueryAccept on the upstream filter's output pin. If the upstream filter accepts the new format, the QueryAccept method returns S_OK. The Video Renderer switches formats by attaching a media type with the new format to the next media sample returned by its allocator. The upstream filter should check for format changes by calling IMediaSample::GetMediaType on each sample. The Video Renderer may switch back and forth between the original format and new format at any time during streaming. It does not call QueryAccept after the first format change. Once the upstream filter has accepted the new format, it must be able to switch back and forth.

The upstream filter can reject the format change by returning S_FALSE from QueryAccept. In that case, the Video Renderer continues to GDI with the original format.

Video Mixing Renderer Filter

The Video Mixing Renderer filter (VMR-7 and VMR-9) will connect with any format that is supported by the graphics hardware on the system. It always uses DirectDraw for rendering, and it allocates the underlying DirectDraw surfaces when the upstream filter connects.

The graphics hardware may require a larger surface stride than the image width. In that case, the VMR requests a new format by calling QueryAccept. It reports the surface stride in the biWidth member of the BITMAPINFOHEADER in the video format. If the upstream filter does not return S_OK from QueryAccept, the VMR rejects the format and tries to connect using the next format advertised by the upstream filter. The VMR attaches the media type with the new format to the first media sample. After the first sample, the format remains constant; the VMR will not switch formats while the graph is running.

See Also

  • QueryAccept (Upstream)


Threads and Critical Sections

This article describes threading in DirectShow filters, and the steps you should take to avoid crashes or deadlocks in a custom filter.

This article contains the following topics.

  • The Streaming and Application Threads
  • Pausing
  • Receiving and Delivering Samples
  • Delivering the End of Stream
  • Flushing Data
  • Stopping
  • Getting Buffers
  • Streaming Threads and the Filter Graph Manager
  • Summary of Filter Threading

See Also

  • Data Flow for Filter Developers

The examples in this article use pseudocode to illustrate the code you will need to write. They assume that a custom filter is using classes derived from the DirectShow base classes, as follows:

  • CMyInputPin: Derived from CBaseInputPin.
  • CMyOutputPin: Derived from CBaseOutputPin.
  • CMyFilter: Derived from CBaseFilter.
  • CMyInputAllocator: The input pin's allocator, derived from CMemAllocator. Not every filter needs a custom allocator. For many filters, the CMemAllocator class is sufficient.


The Streaming and Application Threads

Any DirectShow application contains at least two important threads: the application thread, and one or more streaming threads. Samples are delivered on the streaming threads, and state changes happen on the application thread. The main streaming thread is created by a source or parser filter. Other filters might create worker threads that deliver samples, and these are considered streaming threads as well.

Some methods are called on the application thread, while others are called on a streaming thread. For example:

  • Streaming thread(s): IMemInputPin::Receive, IMemInputPin::ReceiveMultiple, IPin::EndOfStream, IMemAllocator::GetBuffer.
  • Application thread: IMediaFilter::Pause, IMediaFilter::Run, IMediaFilter::Stop, IMediaSeeking::SetPositions, IPin::BeginFlush, IPin::EndFlush.
  • Either: IPin::NewSegment.

Having a separate streaming thread allows data to flow through the graph while the application thread waits for user input. The danger of multiple threads, however, is that a filter may create resources when it pauses (on the application thread), use them inside a streaming method, and destroy them when it stops (also on the application thread). If you are not careful, the streaming thread might try to use the resources after they are destroyed. The solution is to protect resources using critical sections, and synchronize streaming methods with state changes.

A filter needs one critical section to protect the filter state. The CBaseFilter class has a member variable for this critical section, CBaseFilter::m_pLock. This critical section is called the filter lock. Also, each input pin needs a critical section to protect resources used by the streaming thread. These critical sections are called streaming locks; you must declare them in your derived pin class. It is easiest to use the CCritSec class, which wraps a Windows CRITICAL_SECTION object and can be locked using the CAutoLock class. The CCritSec class also provides some useful debugging functions. For more information, see Critical Section Debugging Functions.

When a filter stops or flushes, it must synchronize the application thread with the streaming thread. To avoid deadlocking, it must first unblock the streaming thread, which might be blocked for several reasons:

  • It is waiting to get a sample inside the IMemAllocator::GetBuffer method, because all of the allocator's samples are in use.
  • It is waiting for another filter to return from a streaming method, such as Receive.
  • It is waiting inside one of its own streaming methods, for some resource to become available.
  • It is a renderer filter waiting for the presentation time of the next sample
  • It is a renderer filter waiting inside the Receive method while paused.

Therefore, when the filter stops or flushes, it must do the following:

  • Release any sample it is holding for any reason. Doing so unblocks the GetBuffer method.
  • Return from any streaming method as quickly as possible. If a streaming method is waiting for a resource, it must stop waiting immediately.
  • Start rejecting samples in Receive, so that the streaming thread does not access any more resources. (The CBaseInputPin class handles this automatically.)
  • The Stop method must decommit all of the filter's allocators. (The CBaseInputPin class handles this automatically.)

Flushing and stopping both happen on the application thread. A filter stops in response to the IMediaControl::Stop method. The Filter Graph Manager issues the stop command in upstream order, starting from the renderers and working backward to the source filters. The stop command happens completely inside the filter's CBaseFilter::Stop method. When the method returns, the filter should be in a stopped state.

Flushing typically occurs because of a seek command. A flush command starts from the source or parser filter, and travels downstream. Flushing happens in two stages: The IPin::BeginFlush method informs a filter to discard all pending and incoming data; the IPin::EndFlush method signals the filter to accept data again. Flushing requires two stages because the BeginFlush call is on the application thread, during which the streaming thread continues to deliver data. Therefore, some samples may arrive after the BeginFlush call. The filter should discard these. Any samples that arrive after the EndFlush call are guaranteed to be new, and should be delivered.

The sections that follow contain code samples showing how to implement the most important filter methods, such as Pause, Receive, and so forth, in ways that avoid deadlocks and race conditions. Every filter has different requirements, however, so you will need to adapt these examples to your particular filter.

Note The CTransformFilter and CTransInPlaceFilter base classes handle many of the issues described in this article. If you are writing a transform filter, and your filter does not wait on events inside a streaming method, or hold onto samples outside of Receive, then these base classes should be sufficient.


Pausing

All filter state changes must hold the filter lock. In the Pause method, create any resources the filter needs:

HRESULT CMyFilter::Pause()
{
    CAutoLock lock_it(m_pLock);

    /* Create filter resources. */

    return CBaseFilter::Pause();
}

The CBaseFilter::Pause method sets the correct state on the filter (State_Paused) and calls the CBasePin::Active method on every connected pin in the filter. The Active method informs the pin that the filter has become active. If the pin creates resources, override the Active method, as follows:

HRESULT CMyInputPin::Active()
{
    // You do not need to hold the filter lock here. It is already held in Pause.

    /* Create pin resources. */

    return CBaseInputPin::Active()
}


Receiving and Delivering Samples

The following pseudocode shows how to implement the IMemInput::Receive method:

HRESULT CMyInputPin::Receive(IMediaSample *pSample)
{
    CAutoLock cObjectLock(&m_csReceive);

    // Perhaps the filter needs to wait on something.
    WaitForSingleObject(m_hSomeEventThatReceiveNeedsToWaitOn, INFINITE);

    // Before using resources, make sure it is safe to proceed. Do not
    // continue if the base-class method returns anything besides S_OK.
    hr = CBaseInputPin::Receive(pSample);
    if (hr != S_OK)
    {
        return hr;
    }

    /* It is safe to use resources allocated in Active and Pause. */

    // Deliver sample(s), via your output pin(s).
    for (each output pin)
        pOutputPin->Deliver(pSample);

    return hr;
}

The Receive method holds the streaming lock, not the filter lock. The filter might need to wait on some event before it can process the data, shown here by the call to WaitForSingleObject. Not every filter will need to do this. The CBaseInputPin::Receive method verifies some general streaming conditions. It returns VFW_E_WRONG_STATE if the filter is stopped, S_FALSE if the filter is flushing, and so forth. Any return code other than S_OK indicates that the Receive method should return immediately and not process the sample.

After the sample is processed, deliver it to the downstream filter by calling CBaseOutputPin::Deliver. This helper method calls IMemInputPin::Receive on the downstream input pin. A filter might deliver samples to several pins.


Delivering the End of Stream

When the input pin receives an end-of-stream notification, it propagates the call downstream. Any downstream filters that receive data from this input pin should also get the end-of-stream notification. Again, take the streaming lock and not the filter lock. If the filter has pending data that was not yet delivered, the filter should deliver it now, before it sends the end-of-stream notification. It should not send any data after the end of the stream.

HRESULT CMyInputPin::EndOfStream()
{
    CAutoLock lock_it(&m_csReceive);

    /* If the pin has not delivered all of the data in the stream
       (based on what it received previously), do so now.  */

    // Propagate EndOfStream call downstream, via your output pin(s).
    for (each output pin)
    {
        hr = pOutputPin->DeliverEndOfStream();
    }
    return S_OK;
}

The CBaseOutputPin::DeliverEndOfStream method calls IPin::EndOfStream on the downstream input pin.


Flushing Data

The following pseudocode shows how to implement the IPin::BeginFlush method:

HRESULT CMyInputPin::BeginFlush()
{
    CAutoLock lock_it(m_pLock);

    // First, make sure the Receive method will fail from now on.
    HRESULT hr = CBaseInputPin::BeginFlush();

    // Force downstream filters to release samples. If our Receive method
    // is blocked in GetBuffer or Deliver, this will unblock it.
    for (each output pin)
    {
        hr = pOutputPin->DeliverBeginFlush();
    }

    // Unblock our Receive method if it is waiting on an event.
    SetEvent(m_hSomeEventThatReceiveNeedsToWaitOn);

    // At this point, the Receive method can't be blocked. Make sure
    // it finishes, by taking the streaming lock. (Not necessary if this
    // is the last step.)
    {
        CAutoLock lock_2(&m_csReceive);

        /* Now it's safe to do anything that would crash or hang
           if Receive were executing. */
    }
    return hr;
}

When flushing starts, the BeginFlush method takes the filter lock, which serializes the state change. It is not yet safe to take the streaming lock, because flushing happens on the application thread, and the streaming thread might be in the middle of a Receive call. The pin needs to guarantee that Receive is not blocked, and that any subsequent calls to Receive will fail. The CBaseInputPin::BeginFlush method sets an internal flag, CBaseInputPin::m_bFlushing. When the flag is TRUE, the Receive method fails.

By delivering the BeginFlush call downstream, the pin guarantees that all downstream filters release their samples and return from Receive calls. This in turn guarantees that the input pin is not blocked waiting for GetBuffer or Receive. If your pin's Receive method ever waits on an event (for example, to get resources), the BeginFlush method should force the wait to terminate by setting the event. At this point, the Receive method is guaranteed to return, and the m_bFlushing flag prevents new Receive calls from doing any work.

For some filters, that is all BeginFlush needs to do. The EndFlush method will signal to the filter that it can start receiving samples again. Other filters may need to use variables or resources in BeginFlush that are also used in Receive. In that case, the filter should hold the streaming lock first. Be sure not to do this before any of the previous steps, because you might cause a deadlock.

The EndFlush method holds the filter lock and propagates the call downstream:

HRESULT CMyInputPin::EndFlush()
{
    CAutoLock lock_it(m_pLock);
    for (each output pin)
        hr = pOutputPin->DeliverEndFlush();
    return CBaseInputPin::EndFlush();
}

The CBaseInputPin::EndFlush method resets the m_bFlushing flag to FALSE, which allows the Receive method to start receiving samples again. This should be the last step in EndFlush, because the pin must not receive any samples until flushing is complete and all downstream filters are notified.


Stopping

The Stop method must unblock the Receive method and decommit the filter's allocators. Decommitting an allocator forces any pending GetBuffer calls to return, which unblocks upstream filters that are waiting for samples. The Stop method holds the filter lock and then calls the CBaseFilter::Stop method, which calls CBasePin::Inactive on all of the filter's pins:

HRESULT CMyFilter::Stop()
{
    CAutoLock lock_it(m_pLock);
    // Inactivate all the pins, to protect the filter resources.
    hr = CBaseFilter::Stop();

    /* Safe to destroy filter resources used by the streaming thread. */

    return hr;
}

Override the input pin's Inactive method as follows:

HRESULT CMyInputPin::Inactive()
{
    // You do not need to hold the filter lock here.
    // It is already locked in Stop.

    // Unblock Receive.
    SetEvent(m_hSomeEventThatReceiveNeedsToWaitOn);

    // Make sure Receive will fail.
    // This also decommits the allocator.
    HRESULT hr = CBaseInputPin::Inactive();

    // Make sure Receive has completed, and is not using resources.
    {
        CAutoLock c(&m_csReceive);

        /* It is now safe to destroy filter resources used by the
           streaming thread. */
    }
    return hr;
}


Getting Buffers

If your filter has a custom allocator that uses filter resources, the GetBuffer method should hold the streaming lock, as with other streaming methods:

HRESULT CMyInputAllocator::GetBuffer(
    IMediaSample **ppBuffer,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags)
{
    CAutoLock cObjectLock(&m_csReceive);

    /* Use resources. */

    return CMemAllocator::GetBuffer(ppBuffer, pStartTime, pEndTime, dwFlags);
}


Streaming Threads and the Filter Graph Manager

When the Filter Graph Manager stops the graph, it waits for all streaming threads to shut down. This has the following implications for filters:

  • A filter must never call methods on the Filter Graph Manager from a streaming thread.

    The Filter Graph Manager uses a critical section to synchronize its own operations. If a streaming thread tries to hold this critical section, it can cause a deadlock. For example: Suppose that another thread stops the graph. That thread takes the filter graph lock and waits for your filter to stop delivering data. If your filter is waiting for the lock, it will never stop, causing a deadlock.

  • A filter must never AddRef or QueryInterface the Filter Graph Manager from a streaming thread.

    If the filter holds a reference count on the Filter Graph Manager (through AddRef or QueryInterface), it might become the last object to hold a reference count. When the filter calls Release, the Filter Graph Manager destroys itself. Inside its cleanup routine, the Filter Graph Manager attempts to stop the graph, causing it to wait for the streaming thread to exit. However, it is waiting inside the streaming thread, so the streaming thread cannot exit. The result is a deadlock.


Summary of Filter Threading

The following methods are called on the streaming thread:

  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment
  • IMemAllocator::GetBuffer

The following methods are called on the application thread:

  • State changes: IBaseFilter::JoinFilterGraph, IMediaFilter::Pause, IMediaFilter::Run, IMediaFilter::Stop, IQualityControl::SetSink.
  • Reference clock: IMediaFilter::GetSyncSource, IMediaFilter::SetSyncSource.
  • Pin operations: IBaseFilter::FindPin, IPin::Connect, IPin::ConnectedTo, IPin::ConnectionMediaType, IPin::Disconnect, IPin::ReceiveConnection.
  • Allocator functions: IMemInputPin::GetAllocator, IMemInputPin::NotifyAllocator.
  • Flushing: IPin::BeginFlush, IPin::EndFlush.

This list is not exhaustive. When you implement a filter, you must consider which methods change the filter state, and which methods perform streaming operations.


Quality-Control Management

Quality control is a mechanism for adjusting the rate of data flow through the filter graph in response to run-time performance. If a renderer filter is receiving too much data or too little data, it can send a quality message. The quality message requests an adjustment in the data rate. By default, quality messages travel upstream from the renderer until they reach a filter that can respond (if any). An application can also implement a custom quality manager. In that case, the renderer passes quality messages directly to the application's quality manager.

This article contains the following topics.

  • Quality Messages
  • Default Quality Control


Quality Messages

Quality messages are defined with the Quality structure. This structure contains the following members:

  • Type: Defined by the QualityMessageType enumeration; either Famine, indicating that the filter is receiving too little data, or Flood, indicating that the filter is receiving too much data.
  • Proportion: The requested adjustment in the data rate, from a baseline of 1000. For example, 750 indicates 75% and 1500 indicates 150%.
  • Late: Reference time indicating how late the most recent sample arrived. The value is negative if the sample arrived early.
  • TimeStamp: The time stamp on the most recent sample.

For example, suppose that a sample with a time stamp of 240 milliseconds (ms) reaches the renderer at 280 ms, stream time. The renderer creates a quality message of type Famine. The sample arrived 40 ms late, so the Late member is 400000. (All reference times are in 100-nanosecond units.) The TimeStamp member is 2400000.

For the Proportion member, the renderer might use a running average to calculate the value. Perhaps samples have been arriving on time, and this sample is an anomaly. In that case the renderer might request only a small correction. On the other hand, if samples are consistently late, the renderer might request a larger correction.

Quality control is handled through the IQualityControl interface. It contains two methods.

  • Notify: Sends a quality message.
  • SetSink: Specifies a custom quality manager.

An object that implements IQualityControl receives quality messages through its Notify method. It can either handle the message or pass the message to another object. If the application calls the object's SetSink method, the object should delegate quality control to the specified quality manager.


Default Quality Control

The DirectShow Base Classes implement some default behaviors for video quality control.

Quality messages start at the renderer. The base class for video renderers is CBaseVideoRenderer, which has the following behavior:

  1. When the video renderer receives a sample, it compares the time stamp on the sample with the current reference time.
  2. The video renderer generates a quality message. In the base class, the Proportion member of the quality message is limited to a range of 500 (50%) to 2000 (200%). Values outside this range could result in abrupt quality changes.
  3. By default, the video renderer sends the quality message to the upstream output pin (the pin connected to its input pin). Applications can override this behavior by calling the SetSink method.

What happens next depends on the upstream filter. Typically, this is a transform filter. The base class for transform filters is CTransformFilter, which uses the CTransformInputPin and CTransformOutputPin classes to implement input and output pins. Together, these classes have the following behavior:

  1. The CTransformOutputPin::Notify method calls CTransformFilter::AlterQuality, a private method on the filter base class.
  2. Derived filters can override AlterQuality to handle the quality message. By default, AlterQuality ignores the quality message.
  3. If AlterQuality does not handle the quality message, the output pin calls CBaseInputPin::PassNotify, a private method on the filter's input pin.
  4. PassNotify passes the quality message to the appropriate place—the next upstream output pin, or a custom quality manager.

Assuming that no transform filter handles the quality message, the message eventually reaches the output pin on the source filter. In the base classes, CBasePin::Notify returns E_NOTIMPL. How a particular source filter handles quality messages depends on the nature of the source. Some sources, such as live video capture, cannot perform meaningful quality control. Other sources can adjust the rate at which they deliver samples.

The following diagram illustrates the default behavior.

Quality control in the base classes

The base video renderer implements IQualityControl::Notify, which means you can pass quality messages to the renderer itself. If you set the Proportion member to a value less than 1000, the video renderer inserts a wait period between each frame that it renders, in effect slowing down the renderer. (You might do this to reduce system usage, for example.) For more information, see CBaseVideoRenderer::ThrottleWait. Setting the Proportion member to a value greater than 1000 has no effect.


DirectShow and COM

This section contains the following articles.

  • How to Implement IUnknown
  • How to Create a DLL
  • How to Register DirectShow Filters


How to Implement IUnknown

Microsoft DirectShow is based on the Component Object Model (COM). If you write your own filter, you must implement it as a COM object. The DirectShow base classes provide a framework from which to do this. Using the base classes is not required, but it can simplify the development process. This article describes some of the internal details of COM objects and their implementation in the DirectShow base classes.

This article assumes that you know how to program COM client applications—in other words, that you understand the methods in IUnknown—but does not assume any prior experience developing COM objects. DirectShow handles many of the details of developing a COM object. If you have experience developing COM objects, you should read the section Using CUnknown, which describes the CUnknown base class.

COM is a specification, not an implementation. It defines the rules that a component must follow; putting those rules into effect is left to the developer. In DirectShow, all objects derive from a set of C++ base classes. The base class constructors and methods do most of the COM "bookkeeping" work, such as keeping a consistent reference count. By deriving your filter from a base class, you inherit the functionality of the class. To use base classes effectively, you need a general understanding of how they implement the COM specification.

This article contains the following topics.

  • How IUnknown Works
  • Using CUnknown


How IUnknown Works

The methods in IUnknown enable an application to query for interfaces on the component and manage the component's reference count.

Reference Count

The reference count is an internal variable, incremented in the AddRef method and decremented in the Release method. The base classes manage the reference count and synchronize access to the reference count among multiple threads.

Interface Queries

Querying for an interface is also straightforward. The caller passes two parameters: an interface identifier (IID), and the address of a pointer. If the component supports the requested interface, it sets the pointer to the interface, increments its own reference count, and returns S_OK. Otherwise, it sets the pointer to NULL and returns E_NOINTERFACE. The following pseudocode shows the general outline of the QueryInterface method. Component aggregation, described in the next section, introduces some additional complexity.

if (IID == IID_IUnknown)
    set pointer to (IUnknown *)this
    AddRef
    return S_OK

else if (IID == IID_ISomeInterface)
    set pointer to (ISomeInterface *)this
    AddRef
    return S_OK

else if ...

else
    set pointer to NULL
    return E_NOINTERFACE

The only difference between the QueryInterface method of one component and the QueryInterface method of another is the list of IIDs that each component tests. For every interface that the component supports, the component must test for the IID of that interface.

Aggregation and Delegation

Component aggregation must be transparent to the caller. Therefore, the aggregate must expose a single IUnknown interface, with the aggregated component deferring to the outer component's implementation. Otherwise, the caller would see two different IUnknown interfaces in the same aggregate. If the component is not aggregated, it uses its own implementation.

To support this behavior, the component must add a level of indirection. A delegating IUnknown delegates the work to the appropriate place: to the outer component, if there is one, or to the component's internal version. A nondelegating IUnknown does the work, as described in the previous section.

The delegating version is public and keeps the name IUnknown. The nondelegating version is renamed INonDelegatingUnknown. This name is not part of the COM specification, because it is not a public interface.

When the client creates an instance of the component, it calls the IClassFactory::CreateInstance method. One parameter is a pointer to the aggregating component's IUnknown interface, or NULL if the new instance is not aggregated. The component uses this parameter to store a member variable indicating which IUnknown interface to use, as shown in the following example:

CMyComponent::CMyComponent(IUnknown *pOuterUnkown)
{
    if (pOuterUnknown == NULL)
        m_pUnknown = (IUnknown *)(INonDelegatingUnknown *)this;
    else
        m_pUnknown = pOuterUnknown;

    [ ... more constructor code ... ]
}

Each method in the delegating IUnknown calls its nondelegating counterpart, as shown in the following example:

HRESULT QueryInterface(REFIID iid, void **ppv)
{
    return m_pUnknown->QueryInterface(iid, ppv);
}

By the nature of delegation, the delegating methods look identical in every component. Only the nondelegating versions change.


Using CUnknown

DirectShow implements IUnknown in a base class called CUnknown. You can use CUnknown to derive other classes, overriding only the methods that change across components. Most of the other base classes in DirectShow derive from CUnknown, so your component can inherit directly from CUnknown or from another base class.

INonDelegatingUnknown

CUnknown implements INonDelegatingUnknown. It manages reference counts internally, and in most situations your derived class can inherit the two reference-counting methods with no change. Be aware that CUnknown deletes itself when the reference count drops to zero. On the other hand, you must override CUnknown::NonDelegatingQueryInterface, because the method in the base class returns E_NOINTERFACE if it receives any IID other than IID_IUnknown. In your derived class, test for the IIDs of interfaces that you support, as shown in the following example:

STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
    if (riid == IID_ISomeInterface)
    {
        return GetInterface((ISomeInterface*)this, ppv);
    }
    // default
    return CUnknown::NonDelegatingQueryInterface(riid, ppv);
}

The utility function GetInterface (see COM Helper Functions) sets the pointer, increments the reference count in a thread-safe way, and returns S_OK. In the default case, call the base class method and return the result. If you derive from another base class, call its NonDelegatingQueryInterface method instead. This enables you to support all the interfaces that the parent class supports.

IUnknown

As mentioned earlier, the delegating version of IUnknown is the same for every component, because it does nothing more than invoke the correct instance of the nondelegating version. For convenience, the header file Combase.h contains a macro, DECLARE_IUNKNOWN, which declares the three delegating methods as inline methods. It expands to the following code:

STDMETHODIMP QueryInterface(REFIID riid, void **ppv) {
    return GetOwner()->QueryInterface(riid,ppv);
};
STDMETHODIMP_(ULONG) AddRef() {
    return GetOwner()->AddRef();
};
STDMETHODIMP_(ULONG) Release() {
    return GetOwner()->Release();
};

The utility function CUnknown::GetOwner retrieves a pointer to the IUnknown interface of the component that owns this component. For an aggregated component, the owner is the outer component. Otherwise, the component owns itself. Include the DECLARE_IUNKNOWN macro in the public section of your class definition.

Class Constructor

Your class constructor should invoke the constructor method for the parent class, in addition to anything it does that is specific to your class. The following example is a typical constructor method:

CMyComponent(TCHAR *tszName, LPUNKNOWN pUnk, HRESULT *phr)
    : CUnknown(tszName, pUnk, phr)
{
    /* Other initializations */
};

The method takes the following parameters, which it passes directly to the CUnknown constructor method.

  • tszName specifies a name for the component.
  • pUnk is a pointer to the aggregating IUnknown.
  • pHr is a pointer to an HRESULT value, indicating the success or failure of the method.

Summary

The following example shows a derived class that supports IUnknown and a hypothetical interface named ISomeInterface:

class CMyComponent : public CUnknown, public ISomeInterface
{
public:

    DECLARE_IUNKNOWN;

    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv)
    {
        if( riid == IID_ISomeInterface )
        {
            return GetInterface((ISomeInterface*)this, ppv);
        }
        return CUnknown::NonDelegatingQueryInterface(riid, ppv);
    }

    CMyComponent(TCHAR *tszName, LPUNKNOWN pUnk, HRESULT *phr)
        : CUnknown(tszName, pUnk, phr)
    {
        /* Other initializations */
    };

    // More declarations will be added later.
};

This example illustrates the following points:

  • The CUnknown class implements the IUnknown interface. The new component inherits from CUnknown and from any interfaces that the component supports. The component could derive instead from another base class that inherits from CUnknown.
  • The DECLARE_IUNKNOWN macro declares the delegating IUnknown methods as inline methods.
  • The CUnknown class provides the implementation for INonDelegatingUnknown.
  • To support an interface other than IUnknown, the derived class must override the NonDelegatingQueryInterface method and test for the IID of the new interface.
  • The class constructor invokes the constructor method for CUnknown.

The next step in writing a filter is to enable an application to create new instances of the component. This requires an understanding of DLLs and their relation to class factories and class constructor methods. For more information, see How to Create a DLL.


How to Create a DLL

This article describes how to implement a component as a dynamic-link library (DLL) in Microsoft DirectShow. This article is a continuation from How to Implement IUnknown, which describes how to implement the IUnknown interface by deriving your component from the CUnknown base class.

This article contains the following sections.

  • Class Factories and Factory Templates
  • Factory Template Array
  • DLL Functions

Registering a DirectShow filter (as opposed to a generic COM object) requires some additional steps that are not covered in this article. For information on registering filters, see How to Register DirectShow Filters.


Class Factories and Factory Templates

Before a client creates an instance of a COM object, it creates an instance of the object's class factory, using a call to the CoGetClassObject function. The client then calls the class factory's IClassFactory::CreateInstance method. It is the class factory that actually creates the component and returns a pointer to the requested interface. (The CoCreateInstance function combines these steps, inside the function call.)

The following illustration shows the sequence of method calls.

Method calls to create a class factory

CoGetClassObject calls the DllGetClassObject function, which is defined in the DLL. This function creates the class factory and returns a pointer to an interface on the class factory. DirectShow implements DllGetClassObject for you, but the function relies on your code in a specific way. To understand how it works, you must understand how DirectShow implements class factories.

A class factory is a COM object dedicated to creating another COM object. Each class factory has one type of object that it creates. In DirectShow, every class factory is an instance of the same C++ class, CClassFactory. Class factories are specialized by means of another class, CFactoryTemplate, also called the factory template. Each class factory holds a pointer to a factory template. The factory template contains information about a specific component, such as the component's class identifier (CLSID), and a pointer to a function that creates the component.

The DLL declares a global array of factory templates, one for each component in the DLL. When DllGetClassObject makes a new class factory, it searches the array for a template with a matching CLSID. Assuming it finds one, it creates a class factory that holds a pointer to the matching template. When the client calls IClassFactory::CreateInstance, the class factory calls the instantiation function defined in the template.

The following illustration shows the sequence of method calls.

Class factory templates in a DLL

The benefit of this architecture is that you can define just a few things that are specific to your component, such as the instantiation function, without implementing the entire class factory.


Factory Template Array

The factory template contains the following public member variables:

const WCHAR *              m_Name;                // Name
const CLSID *              m_ClsID;               // CLSID
LPFNNewCOMObject           m_lpfnNew;             // Function to create an instance
                                                  //   of the component
LPFNInitRoutine            m_lpfnInit;            // Initialization function (optional)
const AMOVIESETUP_FILTER * m_pAMovieSetup_Filter; // Set-up information (for filters)

The two function pointers, m_lpfnNew and m_lpfnInit, use the following type definitions:

typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(LPUNKNOWN pUnkOuter, HRESULT *phr);
typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid);

The first is the instantiation function for the component. The second is an optional initialization function. If you provide an initialization function, it is called from inside the DLL entry-point function. (The DLL entry-point function is discussed later in this article.)

Suppose you are creating a DLL that contains a component named CMyComponent, which inherits from CUnknown. You must provide the following items in your DLL:

  • The initialization function, a public method that returns a new instance of CMyComponent.
  • A global array of factory templates, named g_Templates. This array contains the factory template for CMyComponent.
  • A global variable named g_cTemplates that specifies the size of the array.

The following example shows how to declare these items:

// Public method that returns a new instance.
CUnknown * WINAPI CMyComponent::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CMyComponent *pNewObject = new CMyComponent(NAME("My Component"), pUnk, pHr );
    if (pNewObject == NULL) {
        *pHr = E_OUTOFMEMORY;
    }
    return pNewObject;
}

CFactoryTemplate g_Templates[1] =
{
    {
      L"My Component",                // Name
      &CLSID_MyComponent,             // CLSID
      CMyComponent::CreateInstance,   // Method to create an instance of MyComponent
      NULL,                           // Initialization function
      NULL                            // Set-up information (for filters)
    }
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

The CreateInstance method calls the class constructor and returns a pointer to the new class instance. The parameter pUnk is a pointer to the aggregating IUnknown. You can simply pass this parameter to the class constructor. The parameter pHr is a pointer to an HRESULT value. The class constructor sets this to an appropriate value, but if the constructor fails, set the value to E_OUTOFMEMORY.

The NAME macro generates a string in debug builds but resolves to NULL in retail builds. It is used in this example to give the component a name that appears in debug logs but does not occupy memory in the final version.

The CreateInstance method can have any name, because the class factory refers to the function pointer in the factory template. However, g_Templates and g_cTemplates are global variables that the class factory expects to find, so they must have exactly those names.


DLL Functions

A DLL must implement the following functions so that it can be registered, unregistered, and loaded into memory.

  • DllMain: The DLL entry point. The name DllMain is a placeholder for the library-defined function name. The DirectShow implementation uses the name DllEntryPoint. For more information, see the Platform SDK.
  • DllGetClassObject: Creates a class factory instance. Described in the previous sections.
  • DllCanUnloadNow: Queries whether the DLL can safely be unloaded.
  • DllRegisterServer: Creates registry entries for the DLL.
  • DllUnregisterServer: Removes registry entries for the DLL.

Of these, the first three are implemented by DirectShow. If your factory template provides an initialization function in the m_lpfnInit member variable, that function is called from inside the DLL entry-point function. For more information on when the system calls the DLL entry-point function, see DllMain in the Platform SDK.

You must implement DllRegisterServer and DllUnregisterServer, but DirectShow provides a function named AMovieDllRegisterServer2 that does the necessary work. Your component can simply wrap this function, as shown in the following example:

STDAPI DllRegisterServer()
{
    return AMovieDllRegisterServer2( TRUE );
}

STDAPI DllUnregisterServer()
{
    return AMovieDllRegisterServer2( FALSE );
}

However, within DllRegisterServer and DllUnregisterServer you can customize the registration process as needed. If your DLL contains a filter, you might need to do some additional work. For more information, see How to Register DirectShow Filters.

In your module-definition (.def) file, export all the DLL functions except for the entry-point function. The following is an example .def file:

EXPORTS
    DllGetClassObject PRIVATE
    DllCanUnloadNow PRIVATE
    DllRegisterServer PRIVATE
    DllUnregisterServer PRIVATE

You can register the DLL using the Regsvr32.exe utility.


How to Register DirectShow Filters

This article describes how to make a Microsoft DirectShow filter self-registering. It contains the following sections:

  • Layout of the Registry Keys
  • Declaring Filter Information
  • Declaring the Factory Template
  • Implementing DllRegisterServer
  • Guidelines for Registering Filters
  • Unregistering a Filter

This article does not describe how to create a DLL. For information on creating DLLs, see How to Create a DLL.


Layout of the Registry Keys

DirectShow filters are registered in two places:

  • The DLL that contains the filter is registered as the filter's COM server. When an application calls CoCreateInstance to create the filter, the Microsoft Windows COM library uses this registry entry to locate the DLL.
  • Additional information about the filter can be registered within a filter category. This information enables the System Device Enumerator and the Filter Mapper to locate the filter.

Filters are not required to register the additional filter information. As long as the DLL is registered as the COM server, an application can create the filter and add it to a filter graph. However, if you want your filter to be discoverable by the System Device Enumerator or the Filter Mapper, you must register the additional information.

The registry entry for the DLL has the following keys:

HKEY_CLASSES_ROOT
    CLSID
        Filter CLSID
            REG_SZ: (Default) = Friendly name

            InprocServer32
                REG_SZ: (Default) = File name of the DLL
                REG_SZ: ThreadingModel = Both

The registry entry for the filter information has the following keys:

HKEY_CLASSES_ROOT
    CLSID
        Category
            Instance
                Filter CLSID
                    REG_SZ: CLSID = Filter CLSID
                    REG_BINARY: FilterData = Filter information
                    REG_SZ: FriendlyName = Friendly name

Category is the GUID of a filter category. (See Filter Categories.) The filter information is packed into a binary format. The IFilterMapper2 interface unpacks this data when it searches the registry for a filter.

All of the filter category GUIDs are listed in the registry under the following key:

HKEY_CLASSES_ROOT\CLSID\{DA4E3DA0-D07D-11d0-BD50-00A0C911CE86}\Instance


Declaring Filter Information

The first step is to declare the filter information, if needed. DirectShow defines the following structures for describing filters, pins, and media types:

Structure | Description
AMOVIESETUP_FILTER | Describes a filter.
AMOVIESETUP_PIN | Describes a pin.
AMOVIESETUP_MEDIATYPE | Describes a media type.

These structures are nested. The AMOVEIESETUP_FILTER structure has a pointer to an array of AMOVIESETUP_PIN structures, and each of these has a pointer to an array of AMOVEIESETUP_MEDIATYPE structures. Taken together, these structures provide enough information for the IFilterMapper2 interface to locate a filter. They are not a complete description of a filter. For example, if the filter creates multiple instances of the same pin, you should declare only one AMOVIESETUP_PIN structure for that pin. Also, a filter is not required to support every combination of media types that it registers; nor is required to register every media type that it supports.

Declare the set-up structures as global variables within your DLL. The following example shows a filter with one output pin:

static const WCHAR g_wszName[] = L"Some Filter";

AMOVIESETUP_MEDIATYPE sudMediaTypes[] = {
    { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB24 },
    { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB32 },
};

AMOVIESETUP_PIN sudOutputPin = {
    L"",            // Obsolete, not used.
    FALSE,          // Is this pin rendered?
    TRUE,           // Is it an output pin?
    FALSE,          // Can the filter create zero instances?
    FALSE,          // Does the filter create multiple instances?
    &GUID_NULL,     // Obsolete.
    NULL,           // Obsolete.
    2,              // Number of media types.
    sudMediaTypes   // Pointer to media types.
};

AMOVIESETUP_FILTER sudFilterReg = {
    &CLSID_SomeFilter,      // Filter CLSID.
    g_wszName,              // Filter name.
    MERIT_NORMAL,           // Merit.
    1,                      // Number of pin types.
    &sudOutputPin           // Pointer to pin information.
};

The filter name is declared as a static global variable, because it will be used again elsewhere.


Declaring the Factory Template

The next step is to declare the factory template for your filter. A factory template is a C++ class that contains information for the class factory. In your DLL, declare a global array of CFactoryTemplate objects, one for each filter or COM component in your DLL. The array must be named g_Templates. For more information about factory templates, see How to Create a DLL.

The m_pAMovieSetup_Filter member of the factory template is a pointer to the AMOVIESETUP_FILTER structure described previously. The following example shows a factory template, using the structure given in the previous example:

CFactoryTemplate g_Templates[] = {
    {
        g_wszName,                      // Name.
        &CLSID_SomeFilter,              // CLSID.
        CSomeFilter::CreateInstance,    // Creation function.
        NULL,
        &sudFilterReg                   // Pointer to filter information.
    }
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

If you did not declare any filter information, m_pAMoveSetup_Filter can be NULL.


Implementing DllRegisterServer

The final step is to implement the DllRegisterServer function. The DLL that contains the component must export this function. The function will be called by a set-up application, or when the user runs the Regsvr32.exe tool.

The following example shows a minimal implementation of DlLRegisterServer:

STDAPI DllRegisterServer(void)
{
    return AMovieDllRegisterServer2(TRUE);
}

The AMovieDllRegisterServer2 function creates registry entries for every component in the g_Templates array. However, this function has some limitations. First, it assigns every filter to the "DirectShow Filters" category (CLSID_LegacyAmFilterCategory), but not every filter belongs in this category. Capture filters and compression filters, for example, have their own categories. Second, if your filter supports a hardware device, you might need to register two additional pieces of information that AMovieDLLRegisterServer2 does not handle: the medium and the pin category. A medium defines a method of communication in a hardware device, such as a bus. The pin category defines the function of a pin. For information on mediums, see KSPIN_MEDIUM in the Microsoft Windows Driver Development Kit (DDK). For a list of pin categories, see Pin Property Set.

If you want to specify a filter category, a medium, or a pin category, call the IFilterMapper2::RegisterFilter method from within DllRegisterServer. This method takes a pointer to a REGFILTER2 structure, which specifies information about the filter.

To complicate matters somewhat, the REGFILTER2 structure supports two different formats for registering pins. The dwVersion member specifies the format:

  • If dwVersion is 1, the pin format is AMOVIESETUP_PIN (described previously).
  • If dwVersion is 2, the pin format is REGFILTERPINS2.

The REGFILTERPINS2 structure includes entries for pin mediums and pin categories. Also, it uses bit flags for some items that AMOVIESETUP_PIN declares as Boolean values.

The following example shows how to call IFilterMapper2::RegisterFilter from inside DllRegisterServer:

REGFILTER2 rf2FilterReg = {
    1,              // Version 1 (no pin mediums or pin category).
    MERIT_NORMAL,   // Merit.
    1,              // Number of pins.
    &sudPins        // Pointer to pin information.
};

STDAPI DllRegisterServer(void)
{
    HRESULT hr;
    IFilterMapper2 *pFM2 = NULL;

    hr = AMovieDllRegisterServer2(TRUE);
    if (FAILED(hr))
        return hr;

    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);

    if (FAILED(hr))
        return hr;

    hr = pFM2->RegisterFilter(
        CLSID_SomeFilter,                // Filter CLSID.
        g_wszName,                       // Filter name.
        NULL,                            // Device moniker.
        &CLSID_VideoCompressorCategory,  // Video compressor category.
        g_wszName,                       // Instance data.
        &rf2FilterReg                    // Pointer to filter information.
    );
    pFM2->Release();
    return hr;
}


Guidelines for Registering Filters

The filter registry information determines how the Filter Graph Manager functions during Intelligent Connect. Thus, it affects every application written for DirectShow, not just the ones that will use your filter. You should make sure that your filter behaves correctly, by following these guidelines.

  1. Do you need the filter data in the registry? For many custom filters, there is no reason to make the filter visible to the Filter Mapper or the System Device Enumerator. As long as you register the DLL, your application can create the filter using CoCreateInstance. In that case, simply omit the AMOVIESETUP_FILTER structure from the factory template. (One drawback is that your filter will not be visible in GraphEdit. To get around this, you can create a private "Testing" category using the IFilterMapper2::CreateCategory method. You should only do this for debug builds.)
  2. Choose the correct filter category. The default "DirectShow Filters" category is for general purpose filters. Whenever appropriate, register your filter in a more specific category. When IFilterMapper2 searches for a filter, it ignores any category whose merit is MERIT_DO_NOT_USE or less. Categories not intended for normal playback have low merit.
  3. Avoid specifying MEDIATYPE_None, MEDIASUBTYPE_None, or GUID_NULL in the AMOVIESETUP_MEDIATYPE information for a pin. IFilterMapper2 treats these as wildcards, which can slow the graph-building process.
  4. Choose the lowest merit value possible. Here are some guidelines:
    Type of filter | Recommended merit
    Default renderer | MERIT_PREFERRED. For standard media types, however, a custom renderer should never be the default.
    Non-default renderer | MERIT_DO_NOT_USE or MERIT_UNLIKELY
    Mux | MERIT_DO_NOT_USE
    Decoder | MERIT_NORMAL
    Spitter, parser | MERIT_NORMAL or lower
    Special purpose filter; any filter that is created directly by the application | MERIT_DO_NOT_USE
    Capture | MERIT_DO_NOT_USE
    "Fallback" filter; for example, the Color Space Converter Filter | MERIT_UNLIKELY

    If you are giving a filter a merit of MERIT_DO_NOT_USE, consider whether you need to register this information in the first place. (See item 1.)

  5. Do not register a filter in the "DirectShow Filters" category that accepts 24-bit RGB. Your filter will interfere with the Color Space Converter filter.


Unregistering a Filter

To unregister a filter, implement the DllUnregisterServer function. Within this function, call the DirectShow AMovieDllRegisterServer2 function with a value of FALSE. If you called IFilterMapper2::RegisterFilter when you registered the filter, call the IFilterMapper2::UnregisterFilter method here.

The following example shows how to unregister a filter:

STDAPI DllUnregisterServer()
{
    HRESULT hr;
    IFilterMapper2 *pFM2 = NULL;

    hr = AMovieDllRegisterServer2(FALSE);
    if (FAILED(hr))
        return hr;

    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);

    if (FAILED(hr))
        return hr;

    hr = pFM2->UnregisterFilter(&CLSID_VideoCompressorCategory,
            g_wszName, CLSID_SomeFilter);

    pFM2->Release();
    return hr;
}


Writing Transform Filters

This section describes how to write a transform filter, defined as a filter that has exactly one input pin and one output pin. To illustrate the steps, this section describes a hypothetical transform filter that outputs run-length encoded (RLE) video. It does not describe the RLE-encoding algorithm itself, only the tasks that are specific to DirectShow. (DirectShow already provides an RLE codec through the AVI Compressor filter.)

This section assumes that you will use the DirectShow base class library to create filters. Although you can write a filter without it, the base class library is strongly recommended.

Note Before writing a transform filter, consider whether a DirectX Media Object (DMO) would fulfill your requirements. DMOs can do many of the same things as filters, and the programming model for DMOs is simpler. DMOs are hosted in DirectShow through the DMO Wrapper filter, but can also be used outside of DirectShow. DMOs are now the recommended solution for encoders and decoders.

This section includes the following topics:

  • Step 1. Choose a Base Class
  • Step 2. Declare the Filter Class
  • Step 3. Support Media Type Negotiation
  • Step 4. Set Allocator Properties
  • Step 5. Transform the Image
  • Step 6. Add Support for COM

See Also

  • Building DirectShow Filters
  • DirectShow Base Classes


Step 1. Choose a Base Class

Assuming that you decide to write a filter and not a DMO, the first step is choosing which base class to use. The following classes are appropriate for transform filters:

  • CTransformFilter is designed for transform filters that use separate input and output buffers. This kind of filter is sometimes called a copy-transform filter. When a copy-transform filter receives an input sample, it writes new data to an output sample and delivers the output sample to the next filter.
  • CTransInPlaceFilter is designed for filters that modify data in the original buffer, also called trans-in-place filters. When a trans-in-place filter receives a sample, it changes the data inside that sample and delivers the same sample downstream. The filter's input pin and output pin always connect with matching media types.
  • CVideoTransformFilter is designed primarily for video decoders. It derives from CTransformFilter, but includes functionality for dropping frames if the downstream renderer falls behind.
  • CBaseFilter is a generic filter class. The other classes in this list all derive from CBaseFilter. If none of them is suitable, you can fall back on this class. However, this class also requires the most work on your part.

Important In-place video transforms can have a serious impact on rendering performance. In-place transforms require read-modify-write operations on the buffer. If the memory resides on a graphics card, read operations are significantly slower. Moreover, even a copy transform can cause unintended read operations if you do not implement it carefully. Therefore, you should always do performance testing if you write a video transform.

For the example RLE encoder, the best choice is either CTransformFilter or CVideoTransformFilter. In fact, the differences between them are largely internal, so it is easy to convert from one to the other. Because the media types must be different on the two pins, the CTransInPlaceFilter class is not appropriate for this filter. This example will use CTransformFilter.


Step 2. Declare the Filter Class

Start by declaring a C++ class that inherits the base class:

class CRleFilter : public CTransformFilter
{
    /* Declarations will go here. */
};

Each of the filter classes has associated pin classes. Depending on the specific needs of your filter, you might need to override the pin classes. In the case of CTransformFilter, the pins delegate most of their work to the filter, so you probably don't need to override the pins.

You must generate a unique CLSID for the filter. You can use the Guidgen or Uuidgen utility; never copy an existing GUID. There are several ways to declare a CLSID. The following example uses the DEFINE_GUID macro:

[RleFilt.h]
// {1915C5C7-02AA-415f-890F-76D94C85AAF1}
DEFINE_GUID(CLSID_RLEFilter,
0x1915c5c7, 0x2aa, 0x415f, 0x89, 0xf, 0x76, 0xd9, 0x4c, 0x85, 0xaa, 0xf1);

[RleFilt.cpp]
#include <initguid.h>
#include "RleFilt.h"

Next, write a constructor method for the filter:

CRleFilter::CRleFilter()
  : CTransformFilter(NAME("My RLE Encoder"), 0, CLSID_RLEFilter)
{
   /* Initialize any private variables here. */
}

Notice that one of the parameters to the CTransformFilter constructor is the CLSID defined earlier.


Step 3. Support Media Type Negotiation

When two pins connect, they must agree on a media type for the connection. The media type describes the format of the data. Without the media type, a filter might deliver one kind of data, only to have another filter treat it as something else.

The basic mechanism for negotiating media types is the IPin::ReceiveConnection method. The output pin calls this method on the input pin with a proposed media type. The input pin accepts the connection or rejects it. If it rejects the connection, the output pin can try another media type. If no suitable types are found, the connection fails. Optionally, the input pin can advertise a list of types that it prefers, through the IPin::EnumMediaTypes method. The output pin can use this list when it proposes media types, although it does not have to.

The CTransformFilter class implements a general framework for this process, as follows:

  • The input pin has no preferred media types. It relies entirely on the upstream filter to propose the media type. For video data, this makes sense, because the media type includes the image size and the frame rate. Typically, that information must be supplied by an upstream source filter or parser filter. In the case of audio data, the set of possible formats is smaller, so it may be practical for the input pin to offer some preferred types. In that case, override CBasePin::GetMediaType on the input pin.
  • When the upstream filter proposes a media type, the input pin calls the CTransformFilter::CheckInputType method, which accepts or rejects the type.
  • The output pin will not connect unless the input pin is connected first. This behavior is typical for transform filters. In most cases, the filter must determine the input type before it can set the output type.
  • When the output pin does connect, it has a list of media types that it proposes to the downstream filter. It calls the CTransformFilter::GetMediaType method to generate this list. The output pin will also try any media types that the downstream filter proposes.
  • To check whether a particular output type is compatible with the input type, the output pin calls the CTransformFilter::CheckTransform method.

The three CTransformFilter methods listed previously are pure virtual methods, so your derived class must implement them. None of these methods belongs to a COM interface; they are simply part of the implementation provided by the base classes.

The following sections describe each method in more detail:

  • Step 3A. Implement the CheckInputType Method
  • Step 3B. Implement the GetMediaType Method
  • Step 3C. Implement the CheckTransform Method

See Also

  • How Filters Connect


Step 3A. Implement the CheckInputType Method

The CTransformFilter::CheckInputType method is called when the upstream filter proposes a media type to the transform filter. This method takes a pointer to a CMediaType object, which is a thin wrapper for the AM_MEDIA_TYPE structure. In this method, you should examine every relevant field of the AM_MEDIA_TYPE structure, including the fields in the format block. You can use the accessor methods defined in CMediaType, or reference the structure members directly. If any field is not valid, return VFW_E_TYPE_NOT_ACCEPTED. If the entire media type is valid, return S_OK.

For example, in the RLE encoder filter, the input type must be 8-bit or 4-bit uncompressed RGB video. There is no reason to support other input formats, such as 16- or 24-bit RGB, because the filter would have to convert them to a lower bit depth, and DirectShow already provides a Color Space Converter filter for that purpose. The following example assumes that the encoder supports 8-bit video but not 4-bit video:

HRESULT CRleFilter::CheckInputType(const CMediaType *mtIn)
{
    if ((mtIn->majortype != MEDIATYPE_Video) ||
        (mtIn->subtype != MEDIASUBTYPE_RGB8) ||
        (mtIn->formattype != FORMAT_VideoInfo) ||
        (mtIn->cbFormat < sizeof(VIDEOINFOHEADER)))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    VIDEOINFOHEADER *pVih =
        reinterpret_cast<VIDEOINFOHEADER*>(mtIn->pbFormat);
    if ((pVih->bmiHeader.biBitCount != 8) ||
        (pVih->bmiHeader.biCompression != BI_RGB))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Check the palette table.
    if (pVih->bmiHeader.biClrUsed > PALETTE_ENTRIES(pVih))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    DWORD cbPalette = pVih->bmiHeader.biClrUsed * sizeof(RGBQUAD);
    if (mtIn->cbFormat < sizeof(VIDEOINFOHEADER) + cbPalette)
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Everything is good.
    return S_OK;
}

In this example, the method first checks the major type and subtype. Then it checks the format type, to make sure the format block is a VIDEOINFOHEADER structure. The filter could also support VIDEOINFOHEADER2, but in this case there would be no real benefit. The VIDEOINFOHEADER2 structure adds support for interlacing and non-square pixels, which are not likely to be relevant in 8-bit video.

If the format type is correct, the example checks the biBitCount and biCompression members of the VIDEOINFOHEADER structure, to verify that the format is 8-bit uncompressed RGB. As this example shows, you must coerce the pbFormat pointer to the correct structure, based on the format type. Always check the format type GUID (formattype) and the size of the format block (cbFormat) before casting the pointer.

The example also verifies that the number of palette entries is compatible with the bit depth and the format block is large enough to hold the palette entries. If all of this information is correct, the method returns S_OK.


Step 3B. Implement the GetMediaType Method

Note This step is not required for filters that derive from CTransInPlaceFilter.

The CTransformFilter::GetMediaType method returns one of the filter's preferred output types, referenced by index number. This method is never called unless the filter's input pin is already connected. Therefore, you can use the media type from the upstream connection to determine the preferred output types.

An encoder typically offers a single preferred type, representing the target format. Decoders generally support a range of output formats, and offer them in order of descending quality or efficiency. For example, the list might be UYVY, Y211, RGB-24, RGB-565, RGB-555, and RGB-8, in that order. Effect filters may require an exact match between the output format and the input format.

The following example returns a single output type, which is constructed by modifying the input type to specify RLE8 compression:

HRESULT CRleFilter::GetMediaType(int iPosition, CMediaType *pMediaType)
{
    ASSERT(m_pInput->IsConnected());
    if (iPosition < 0)
    {
        return E_INVALIDARG;
    }
    if (iPosition == 0)
    {
        HRESULT hr = m_pInput->ConnectionMediaType(pMediaType);
        if (FAILED(hr))
        {
            return hr;
        }
        FOURCCMap fccMap = FCC('MRLE');
        pMediaType->subtype = static_cast<GUID>(fccMap);
        pMediaType->SetVariableSize();
        pMediaType->SetTemporalCompression(FALSE);

        ASSERT(pMediaType->formattype == FORMAT_VideoInfo);
        VIDEOINFOHEADER *pVih =
            reinterpret_cast<VIDEOINFOHEADER*>(pMediaType->pbFormat);
        pVih->bmiHeader.biCompression = BI_RLE8;
        pVih->bmiHeader.biSizeImage = DIBSIZE(pVih->bmiHeader);
        return S_OK;
    }
    // else
    return VFW_S_NO_MORE_ITEMS;
}

In this example, the method calls IPin::ConnectionMediaType to get the input type from the input pin. Then it changes some of the fields to indicate the compression format, as follows:

  • It assigns a new subtype GUID, which is constructed from the FOURCC code 'MRLE', using the FOURCCMap class.
  • It calls the CMediaType::SetVariableSize method, which sets the bFixedSizeSamples flag to FALSE and the lSampleSize member to zero, indicating variable-sized samples.
  • It calls the CMediaType::SetTemporalCompression method with the value FALSE, indicating that every frame is a key frame. (This field is informational only, so you could safely ignore it.)
  • It sets the biCompression field to BI_RLE8.
  • It sets the biSizeImage field to the image size.


Step 3C. Implement the CheckTransform Method

Note This step is not required for filters that derive from CTransInPlaceFilter.

The CTransformFilter::CheckTransform method checks if a proposed output type is compatible with the current input type. The method is also called if the input pin reconnects after the output pin connects.

The following example verifies whether the format is RLE8 video; the image dimensions match the input format; and the palette entries are the same. It also rejects source and target rectangles that do not match the image size.

HRESULT CRleFilter::CheckTransform(
    const CMediaType *mtIn, const CMediaType *mtOut)
{
    // Check the major type.
    if (mtOut->majortype != MEDIATYPE_Video)
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Check the subtype and format type.
    FOURCCMap fccMap = FCC('MRLE');
    if (mtOut->subtype != static_cast<GUID>(fccMap))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    if ((mtOut->formattype != FORMAT_VideoInfo) ||
        (mtOut->cbFormat < sizeof(VIDEOINFOHEADER)))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Compare the bitmap information against the input type.
    ASSERT(mtIn->formattype == FORMAT_VideoInfo);
    BITMAPINFOHEADER *pBmiOut = HEADER(mtOut->pbFormat);
    BITMAPINFOHEADER *pBmiIn = HEADER(mtIn->pbFormat);
    if ((pBmiOut->biPlanes != 1) ||
        (pBmiOut->biBitCount != 8) ||
        (pBmiOut->biCompression != BI_RLE8) ||
        (pBmiOut->biWidth != pBmiIn->biWidth) ||
        (pBmiOut->biHeight != pBmiIn->biHeight))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Compare source and target rectangles.
    RECT rcImg;
    SetRect(&rcImg, 0, 0, pBmiIn->biWidth, pBmiIn->biHeight);
    RECT *prcSrc = &((VIDEOINFOHEADER*)(mtIn->pbFormat))->rcSource;
    RECT *prcTarget = &((VIDEOINFOHEADER*)(mtOut->pbFormat))->rcTarget;
    if (!IsRectEmpty(prcSrc) && !EqualRect(prcSrc, &rcImg))
    {
        return VFW_E_INVALIDMEDIATYPE;
    }
    if (!IsRectEmpty(prcTarget) && !EqualRect(prcTarget, &rcImg))
    {
        return VFW_E_INVALIDMEDIATYPE;
    }

    // Check the palette table.
    if (pBmiOut->biClrUsed != pBmiIn->biClrUsed)
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    DWORD cbPalette = pBmiOut->biClrUsed * sizeof(RGBQUAD);
    if (mtOut->cbFormat < sizeof(VIDEOINFOHEADER) + cbPalette)
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    if (0 != memcmp(pBmiOut + 1, pBmiIn + 1, cbPalette))
    {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    // Everything is good.
    return S_OK;
}

Pin Reconnections

Applications can disconnect and reconnect pins. Suppose an application connects both pins, disconnects the input pin, and then reconnects the input pin using a new image size. In that case, CheckTransform fails because the dimensions of the image no longer match. This behavior is reasonable, although the filter could also try reconnecting the output pin with a new media type.

See Also

  • Reconnecting Pins
  • Source and Target Rectangles in Video Renderers


Step 4. Set Allocator Properties

Note This step is not required for filters that derive from CTransInPlaceFilter.

After two pins agree on a media type, they select an allocator for the connection and negotiate allocator properties, such as the buffer size and the number of buffers.

In the CTransformFilter class, there are two allocators, one for the upstream pin connection and one for the downstream pin connection. The upstream filter selects the upstream allocator and also chooses the allocator properties. The input pin accepts whatever the upstream filter decides. If you need to modify this behavior, override the CBaseInputPin::NotifyAllocator method.

The transform filter's output pin selects the downstream allocator. It performs the following steps:

  1. If the downstream filter can provide an allocator, the output pin uses that one. Otherwise, the output pin creates a new allocator.
  2. The output pin gets the downstream filter's allocator requirements (if any) by calling IMemInputPin::GetAllocatorRequirements.
  3. The output pin calls the transform filter's CTransformFilter::DecideBufferSize method, which is pure virtual. The parameters to this method are a pointer to the allocator and an ALLOCATOR_PROPERTIES structure with the downstream filter's requirements. If the downstream filter has no allocator requirements, the structure is zeroed out.
  4. In the DecideBufferSize method, the derived class sets the allocator properties by calling IMemAllocator::SetProperties.

Generally, the derived class will select allocator properties based on the output format, the downstream filter's requirements, and the filter's own requirements. Try to select properties that are compatible with the downstream filter's request. Otherwise, the downstream filter might reject the connection.

In the following example, the RLE encoder sets minimum values for the buffer size, buffer alignment, and buffer count. For the prefix, it uses whatever value the downstream filter requested. The prefix is typically zero bytes, but some filters require it. For example, the AVI Mux filter uses the prefix to write RIFF headers.

HRESULT CRleFilter::DecideBufferSize(
    IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pProp)
{
    AM_MEDIA_TYPE mt;
    HRESULT hr = m_pOutput->ConnectionMediaType(&mt);
    if (FAILED(hr))
    {
        return hr;
    }

    ASSERT(mt.formattype == FORMAT_VideoInfo);
    BITMAPINFOHEADER *pbmi = HEADER(mt.pbFormat);
    pProp->cbBuffer = DIBSIZE(*pbmi) * 2;
    if (pProp->cbAlign == 0)
    {
        pProp->cbAlign = 1;
    }
    if (pProp->cBuffers == 0)
    {
        pProp->cBuffers = 1;
    }
    // Release the format block.
    FreeMediaType(mt);

    // Set allocator properties.
    ALLOCATOR_PROPERTIES Actual;
    hr = pAlloc->SetProperties(pProp, &Actual);
    if (FAILED(hr))
    {
        return hr;
    }
    // Even when it succeeds, check the actual result.
    if (pProp->cbBuffer > Actual.cbBuffer)
    {
        return E_FAIL;
    }
    return S_OK;
}

The allocator may not be able to match your request exactly. Therefore, the SetProperties method returns the actual result in a separate ALLOCATOR_PROPERTIES structure (the Actual parameter, in the previous example). Even when SetProperties succeeds, you should check the result to make sure they meet your filter's minimum requirements.

Custom Allocators

By default, all of the filter classes use the CMemAllocator class for their allocators. This class allocates memory from the virtual address space of the client process (using VirtualAlloc). If your filter needs to use some other kind of memory, such as DirectDraw surfaces, you can implement a custom allocator. You can use the CBaseAllocator class or write an entirely new allocator class. If your filter has a custom allocator, override the following methods, depending on which pin uses the allocator:

  • Input pin: CBaseInputPin::GetAllocator and CBaseInputPin::NotifyAllocator.
  • Output pin: CBaseOutputPin::DecideAllocator.

If the other filter refuses to connect using your custom allocator, your filter can either fail the connection, or else connect with the other filter's allocator. In the latter case, you might need to set an internal flag indicating the type of allocator. For an example of this approach, see CDrawImage Class.


Step 5. Transform the Image

The upstream filter delivers media samples to the transform filter by calling the IMemInputPin::Receive method on the transform filter's input pin. To process the data, the transform filter calls the Transform method, which is pure virtual. The CTransformFilter and CTransInPlaceFilter classes use two different versions of this method:

  • CTransformFilter::Transform takes a pointer to the input sample and a pointer to the output sample. Before the filter calls the method, it copies the sample properties from the input sample to the output sample, including the time stamps.
  • CTransInPlaceFilter::Transform takes a pointer to the input sample. The filter modifies the data in place.

If the Transform method returns S_OK, the filter delivers the sample downstream. To skip a frame, return S_FALSE. If there is a streaming error, return a failure code.

The following example shows how the RLE encoder might implement this method. Your own implementation might differ considerably, depending on what your filter does.

HRESULT CRleFilter::Transform(IMediaSample *pSource, IMediaSample *pDest)
{
    // Get pointers to the underlying buffers.
    BYTE *pBufferIn, *pBufferOut;
    hr = pSource->GetPointer(&pBufferIn);
    if (FAILED(hr))
    {
        return hr;
    }
    hr = pDest->GetPointer(&pBufferOut);
    if (FAILED(hr))
    {
        return hr;
    }
    // Process the data.
    DWORD cbDest = EncodeFrame(pBufferIn, pBufferOut);
    KASSERT((long)cbDest <= pDest->GetSize());

    pDest->SetActualDataLength(cbDest);
    pDest->SetSyncPoint(TRUE);
    return S_OK;
}

This example assumes that EncodeFrame is a private method that implements the RLE encoding. The encoding algorithm itself is not described here; for details, see the topic "Bitmap Compression" in the Platform SDK documentation.

First, the example calls IMediaSample::GetPointer to retrieve the addresses of the underlying buffers. It passes these to the private EncoderFrame method. Then it calls IMediaSample::SetActualDataLength to specify the length of the encoded data. The downstream filter needs this information so that it can manage the buffer properly. Finally, the method calls IMediaSample::SetSyncPoint to set the key frame flag to TRUE. Run-length encoding does not use any delta frames, so every frame is a key frame. For delta frames, set the value to FALSE.

Other issues that you must consider include:

  • Time stamps. The CTransformFilter class timestamps the output sample before calling the Transform method. It copies the time stamp values from the input sample, without modifying them. If your filter needs to change the time stamps, call IMediaSample::SetTime on the output sample.
  • Format changes. The upstream filter can change formats mid-stream by attaching a media type to the sample. Before doing so, it calls IPin::QueryAccept on your filter's input pin. In the CTransformFilter class, this results in a call to CheckInputType followed by CheckTransform. The downstream filter can also change media types, using the same mechanism. In your own filter, there are two things to watch for:
    • Make sure that QueryAccept does not return false acceptances.
    • If your filter does accept format changes, check for them inside the Transform method by calling IMediaSample::GetMediaType. If that method returns S_OK, your filter must respond to the format change.

    For more information, see Dynamic Format Changes.

  • Threads. In both CTransformFilter and CTransInPlaceFilter, the transform filter delivers output samples synchronously inside the Receive method. The filter does not create any worker threads to process the data. Typically, there is no reason for a transform filter to create worker threads.


Step 6. Add Support for COM

The final step is adding support for COM.

Reference Counting

You do not have to implement AddRef or Release. All of the filter and pin classes derive from CUnknown, which handles reference counting.

QueryInterface

All of the filter and pin classes implement QueryInterface for any COM interfaces they inherit. For example, CTransformFilter inherits IBaseFilter (through CBaseFilter). If your filter does not expose any additional interfaces, you do not have to do anything else.

To expose additional interfaces, override the CUnknown::NonDelegatingQueryInterface method. For example, suppose your filter implements a custom interface named IMyCustomInterface. To expose this interface to clients, do the following:

  • Derive your filter class from that interface.
  • Put the DECLARE_IUNKNOWN macro in the public declaration section.
  • Override NonDelegatingQueryInterface to check for the IID of your interface and return a pointer to your filter.

The following code shows these steps:

CMyFilter : public CBaseFilter, public IMyCustomInterface
{
public:
    DECLARE_IUNKNOWN
    STDMETHODIMP NonDelegatingQueryInterface(REFIID iid, void **ppv);
};
STDMETHODIMP CMyFilter::NonDelegatingQueryInterface(REFIID iid, void **ppv)
{
    if (riid == IID_IMyCustomInterface) {
        return GetInterface(static_cast<IMyCustomInterface*>(this), ppv);
    }
    return CBaseFilter::NonDelegatingQueryInterface(riid,ppv);
}

For more information, see How to Implement IUnknown.

Object Creation

If you plan to package your filter in a DLL and make it available to other clients, you must support CoCreateInstance and other related COM functions. The base class library implements most of this; you just need to provide some information about your filter. This section gives a brief overview of what to do. For details, see How to Create a DLL.

First, write a static class method that returns a new instance of your filter. You can name this method anything you like, but the signature must match the one shown in the following example:

CUnknown * WINAPI CRleFilter::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CRleFilter *pFilter = new CRleFilter();
    if (pFilter== NULL)
    {
        *pHr = E_OUTOFMEMORY;
    }
    return pFilter;
}

Next, declare a global array of CFactoryTemplate class instances, named g_Templates. Each CFactoryTemplate class contains registry information for one filter. Several filters can reside in a single DLL; simply include additional CFactoryTemplate entries. You can also declare other COM objects, such as property pages.

static WCHAR g_wszName[] = L"My RLE Encoder";
CFactoryTemplate g_Templates[] =
{
  {
    g_wszName,
    &CLSID_RLEFilter,
    CRleFilter::CreateInstance,
    NULL,
    NULL
  }
};

Define a global integer named g_cTemplates whose value equals the length of the g_Templates array:

int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

Finally, implement the DLL registration functions. The following example shows the minimal implementation for these functions:

STDAPI DllRegisterServer()
{
    return AMovieDllRegisterServer2( TRUE );
}
STDAPI DllUnregisterServer()
{
    return AMovieDllRegisterServer2( FALSE );
}

Filter Registry Entries

The previous examples show how to register a filter's CLSID for COM. For many filters, this is sufficient. The client is then expected to create the filter using CoCreateInstance and add it to the filter graph by calling IFilterGraph::AddFilter. In some cases, however, you might want to provide additional information about the filter in the registry. This information does the following:

  • Enables clients to discover the filter using the Filter Mapper or the System Device Enumerator.
  • Enables the Filter Graph Manager to discover the filter during automatic graph building.

The following example registers the RLE encoder filter in the video compressor category. For details, see How to Register DirectShow Filters. Be sure to read the section Guidelines for Registering Filters, which describes the recommended practices for filter registration.

// Declare media type information.
FOURCCMap fccMap = FCC('MRLE');
REGPINTYPES sudInputTypes = { &MEDIATYPE_Video, &GUID_NULL };
REGPINTYPES sudOutputTypes = { &MEDIATYPE_Video, (GUID*)&fccMap };

// Declare pin information.
REGFILTERPINS sudPinReg[] = {
    // Input pin.
    { 0, FALSE, // Rendered?
         FALSE, // Output?
         FALSE, // Zero?
         FALSE, // Many?
         0, 0,
         1, &sudInputTypes  // Media types.
    },
    // Output pin.
    { 0, FALSE, // Rendered?
         TRUE, // Output?
         FALSE, // Zero?
         FALSE, // Many?
         0, 0,
         1, &sudOutputTypes      // Media types.
    }
};

// Declare filter information.
REGFILTER2 rf2FilterReg = {
    1,                // Version number.
    MERIT_DO_NOT_USE, // Merit.
    2,                // Number of pins.
    sudPinReg         // Pointer to pin information.
};

STDAPI DllRegisterServer(void)
{
    HRESULT hr = AMovieDllRegisterServer2(TRUE);
    if (FAILED(hr))
    {
        return hr;
    }
    IFilterMapper2 *pFM2 = NULL;
    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);
    if (SUCCEEDED(hr))
    {
        hr = pFM2->RegisterFilter(
            CLSID_RLEFilter,                // Filter CLSID.
            g_wszName,                       // Filter name.
            NULL,                            // Device moniker.
            &CLSID_VideoCompressorCategory,  // Video compressor category.
            g_wszName,                       // Instance data.
            &rf2FilterReg                    // Filter information.
            );
        pFM2->Release();
    }
    return hr;
}

STDAPI DllUnregisterServer()
{
    HRESULT hr = AMovieDllRegisterServer2(FALSE);
    if (FAILED(hr))
    {
        return hr;
    }
    IFilterMapper2 *pFM2 = NULL;
    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);
    if (SUCCEEDED(hr))
    {
        hr = pFM2->UnregisterFilter(&CLSID_VideoCompressorCategory,
            g_wszName, CLSID_RLEFilter);
        pFM2->Release();
    }
    return hr;
}

Also, filters do not have to be packaged inside DLLs. In some cases, you might write a specialized filter that is designed only for a specific application. In that case, you can compile the filter class directly in your application, and create it with the new operator, as shown in the following example:

#include "MyFilter.h"  // Header file that declares the filter class.
// Compile and link MyFilter.cpp.
int main()
{
    IBaseFilter *pFilter = 0;
    {
        // Scope to hide pF.
        CMyFilter* pF = new MyFilter();
        if (!pF)
        {
            printf("Could not create MyFilter.\n");
            return 1;
        }
        pF->QueryInterface(IID_IBaseFilter,
            reinterpret_cast<void**>(&pFilter));
    }

    /* Now use pFilter as normal. */

    pFilter->Release();  // Deletes the filter.
    return 0;
}

See Also

  • Intelligent Connect


Writing Video Renderers

This section describes how to write and use video renderers, both full-screen and custom renderers. It discusses how and why to support a full-screen renderer, and how to handle notifications, state changes, and dynamic format changes in a custom renderer.

  • Alternative Video Renderers
  • Source and Target Rectangles in Video Renderers


Alternative Video Renderers

This article describes some of the more complicated implementation requirements of a renderer; these apply to most renderers, although some aspects are video-specific (such as EC_REPAINT and other notifications). In particular, it discusses how to handle various notifications, state changes, and format changes. It also provides a summary of the notifications that a renderer is responsible for sending to the Filter Graph Manager.

This article contains the following sections:

  • Writing an Alternative Renderer
  • Handling End-of-stream and Flushing Notifications
  • Handling State Changes and Pause Completion
  • Handling Termination
  • Handling Dynamic Format Changes
  • Handling Persistent Properties
  • Handling EC_REPAINT Notifications
  • Handling Notifications in Full-Screen Mode
  • Summary of Notifications


Writing an Alternative Renderer

Microsoft DirectShow provides a window-based video renderer; it also provides a full-screen renderer in the run-time installation. You can use the DirectShow base classes to write alternative video renderers. For alternative renderers to interact correctly with DirectShow-based applications, the renderers must adhere to the guidelines outlined in this article. You can use the CBaseRenderer and CBaseVideoRenderer classes to help follow these guidelines when implementing an alternative video render. Because of the ongoing development of DirectShow, review your implementation periodically to ensure that the renderers are compatible with the most recent version of DirectShow.

This article discusses many notifications that a renderer is responsible for handling. A brief review of DirectShow notifications might help to set the stage. There are essentially three kinds of notifications that occur in DirectShow:

  • Stream notifications, which are events that occur in the media stream and are passed from one filter to the next. These can be begin-flushing, end-flushing or end-of-stream notifications and are sent by calling the appropriate method on the downstream filter's input pin (for example IPin::BeginFlush).
  • Filter graph manager notifications, which are events sent from a filter to the Filter Graph Manager such as EC_COMPLETE. This is accomplished by calling the IMediaEventSink::Notify method on the Filter Graph Manager.
  • Application notifications, which are retrieved from the Filter Graph Manager by the controlling application. An application calls the IMediaEvent::GetEvent method on the Filter Graph Manager to retrieve these events. Often, the Filter Graph Manager passes through the events it receives to the application.

This article discusses the responsibility of the renderer filter in handling stream notifications it receives and in sending appropriate Filter Graph Manager notifications.


Handling End-of-stream and Flushing Notifications

An end-of-stream notification begins at an upstream filter (such as the source filter) when that filter detects that it can send no more data. It is passed through every filter in the graph and eventually ends at the renderer, which is responsible for subsequently sending an EC_COMPLETE notification to the Filter Graph Manager. Renderers have special responsibilities when it comes to handling these notifications.

A renderer receives an end-of-stream notification when its input pin's IPin::EndOfStream method is called by the upstream filter. A renderer should note this notification and continue to render any data it has already received. Once all remaining data has been received, the renderer should send an EC_COMPLETE notification to the Filter Graph Manager. The EC_COMPLETE notification should be sent only once by a renderer each time it reaches the end of a stream. Furthermore, EC_COMPLETE notifications must never be sent except when the filter graph is running. Therefore, if the filter graph is paused when a source filter sends an end-of-stream notification, then EC_COMPLETE should not be sent until the filter graph is finally run.

Any calls to the IMemInputPin::Receive or IMemInputPin::ReceiveMultiple methods after an end-of-stream notification is signaled should be rejected. E_UNEXPECTED is the most appropriate error message to return in this case.

When a filter graph is stopped, any cached end-of-stream notification should be cleared and not resent when next started. This is because the Filter Graph Manager always pauses all filters just before running them so that proper flushing occurs. So, for example, if the filter graph is paused and an end-of-stream notification is received, and then the filter graph is stopped, the renderer should not send an EC_COMPLETE notification when it is subsequently run. If no seeks have occurred, the source filter will automatically send another end-of-stream notification during the pause state that precedes a run state. If, on the other hand, a seek has occurred while the filter graph is stopped, then the source filter might have data to send, so it won't send an end-of-stream notification.

Video renderers often depend on end-of-stream notifications for more than the sending of EC_COMPLETE notifications. For example, if a stream has finished playing (that is, an end-of-stream notification is sent) and another window is dragged over a video renderer window, a number of WM_PAINT window messages will be generated. The typical practice for running video renderers is to refrain from repainting the current frame upon receipt of WM_PAINT messages (based on the assumption that another frame to be drawn will be received). However, when the end-of-stream notification has been sent, the renderer is in a waiting state; it is still running but is aware that it will not receive any additional data. Under these circumstances, the renderer customarily draws the playback area black.

Handling flushing is an additional complication for renderers. Flushing is carried out through a pair of IPin methods called BeginFlush and EndFlush. Flushing is essentially an additional state that the renderer must handle. It is illegal for a source filter to call BeginFlush without calling EndFlush, so hopefully the state is short and discrete; however, the renderer must correctly handle data or notifications it receives during the flush transition.

Any data received after calling BeginFlush should be rejected immediately by returning S_FALSE. Furthermore, any cached end-of-stream notification should also be cleared when a renderer is flushed. A renderer will typically be flushed in response to a seek. The flush ensures that old data is cleared from the filter graph before fresh samples are sent. (Typically, the playing of two sections of a stream, one after another, is best handled through deferred commands rather than waiting for one section to finish and then issuing a seek command.)


Handling State Changes and Pause Completion

A renderer filter behaves the same as any other filter in the filter graph when its state is changed, with the following exception. After being paused, the renderer will have some data queued, ready to be rendered when subsequently run. When the video renderer is stopped, it holds on to this queued data. This is an exception to the DirectShow rule that no resources should be held by filters while the filter graph is stopped.

The reason for this exception is that by holding resources, the renderer will always have an image with which to repaint the window if it receives a WM_PAINT message. It also has an image to satisfy methods, such as CBaseControlVideo::GetStaticImage, that request a copy of the current image. Another effect of holding resources is that holding on to the image stops the allocator from being decommitted, which in turn makes the next state change occur much faster because the image buffers are already allocated.

A video renderer should render and release samples only while running. While paused, the filter might render them (for example, when drawing a static poster image in a window), but should not release them. Audio renderers will do no rendering while paused (although they can perform other activities, such as preparing the wave device, for example). The time at which the samples should be rendered is obtained by combining the stream time in the sample with the reference time passed as a parameter to the IMediaControl::Run method. Renderers should reject samples with start times less than or equal to end times.

When an application pauses a filter graph, the filter graph does not return from its IMediaControl::Pause method until there is data queued at the renderers. In order to ensure this, when a renderer is paused, it should return S_FALSE if there is no data waiting to be rendered. If it has data queued, then it can return S_OK.

The Filter Graph Manager checks all return values when pausing a filter graph, to ensure that the renderers have data queued. If one or more filters are not ready, then the Filter Graph Manager polls the filters in the graph by calling GetState. The GetState method takes a time-out parameter. A filter (typically a renderer) that is still waiting for data to arrive before completing the state change returns VFW_S_STATE_INTERMEDIATE if the GetState method expires. Once data arrives at the renderer, GetState should be returned immediately with S_OK.

In both the intermediate and completed state, the reported filter state will be State_Paused. Only the return value indicates whether the filter is really ready or not. If, while a renderer is waiting for data to arrive, its source filter sends an end-of-stream notification, then that should also complete the state change.

Once all filters actually have data waiting to be rendered, the filter graph will complete its pause state change.


Handling Termination

Video renderers must correctly handle termination events from the user. This implies correctly hiding the window and knowing what to do if a window is subsequently forced to be displayed. Also, video renderers must notify the Filter Graph Manager when its window is destroyed (or more accurately, when the renderer is removed from the filter graph) to free resources.

If the user closes the video window (for instance by pressing ALT+F4), the convention is to hide the window immediately and send an EC_USERABORT notification to the Filter Graph Manager. This notification is passed through to the application, which will stop the graph playing. After sending EC_USERABORT, a video renderer should reject any additional samples delivered to it.

The graph-stopped flag should be left on by the renderer until it is subsequently stopped, at which point it should be reset so that an application can override the user action and continue playing the graph if it desires. If ALT+F4 is pressed while the video is running, the window will be hidden and all further samples delivered will be rejected. If the window is subsequently shown (perhaps through IVideoWindow::put_Visible), then no EC_REPAINT notifications should be generated.

The video renderer should also send the EC_WINDOW_DESTROYED notification to the filter graph when the video renderer is terminating. In fact, it is best to handle this when the renderer's IBaseFilter::JoinFilterGraph method is called with a null parameter (indicating that the renderer is about to be removed from the filter graph), rather than waiting until the actual video window is destroyed. Sending this notification enables the plug-in distributor in the Filter Graph Manager to pass on resources that depend on window focus to other filters (such as audio devices).


Handling Dynamic Format Changes

Video renderers in DirectShow accept only video formats that can be drawn efficiently. For example, the Video Renderer filter accepts only the RGB format that matches the current display device mode (for example, RGB565 when the display is set to 16-bit color. As a last resort, it also accepts 8-bit palettized formats, as most display cards can draw this format efficiently. When the renderer has Microsoft® DirectDraw® loaded, it might later ask the source filter to switch to something that can be written onto a DirectDraw surface and drawn directly through display hardware. In some cases, the renderer's upstream filter might try to change the video format while the video is playing. This often occurs when a video stream has a palette change. It is most often the video decompressor that initiates a dynamic format change.

An upstream filter attempting to change formats dynamically should always call the IPin::QueryAccept method on the renderer input pin. A video renderer has some leeway as to what kinds of dynamic format changes it should support. At a minimum, it should allow the upstream filter to change palettes. When an upstream filter changes media types, it attaches the media type to the first sample delivered in the new format. If the renderer holds samples in a queue for rendering, it should not change the format until it renders the sample with the type change.

A video renderer can also request a format change from the decoder. For example, it might ask the decoder to provide a DirectDraw-compatible format with a negative biHeight. When the renderer is paused, it should call QueryAccept on the upstream pin to see which formats the decoder can provide. The decoder might not enumerate all of the types that it can accept, however, so the renderer should offer some types even if the decoder does not advertise them.

If the decoder can switch to the requested format, it returns S_OK from QueryAccept. The renderer then attaches the new media type to the next media sample on the upstream allocator. For this to work, the renderer must provide a custom allocator that implements a private method for attaching the media type to the next sample. (Within this private method, call IMediaSample::SetMediaType to set the type.)

The renderer's input pin should return the renderer's custom allocator in the IMemInputPin::GetAllocator method. Override IMemInputPin::NotifyAllocator so that it fails if the upstream filter does not use the renderer's allocator.

With some decoders, setting biHeight to a positive number on YUV types causes the decoder to draw the image upside down. (This is incorrect, and should be considered a bug in the decoder.)

Whenever a format change is detected by the video renderer, it should send an EC_DISPLAY_CHANGED notification. Most video renderers pick a format during connection so that the format can be drawn efficiently through GDI. If the user changes the current display mode without restarting the computer, a renderer might find itself with a bad image format connection and should send this notification. The first parameter should be the pin that needs reconnecting. The Filter Graph Manager will arrange for the filter graph to be stopped and the pin reconnected. During the subsequent reconnection, the renderer can accept a more appropriate format.

Whenever a video renderer detects a palette change in the stream it should send the EC_PALETTE_CHANGED notification to the Filter Graph Manager. The DirectShow video renderers detect whether a palette has really changed in dynamic format or not. The video renderers do this not only to filter out the number of EC_PALETTE_CHANGED notifications sent but also to reduce the amount of palette creation, installation, and deletion required.

Finally, the video renderer might also detect that the size of the video has changed, in which case, it should send the EC_VIDEO_SIZE_CHANGED notification. An application might use this notification to negotiate space in a compound document. The actual video dimensions are available through the IBasicVideo control interface. The DirectShow renderers detect whether the video has actually changed size or not prior to sending these events.


Handling Persistent Properties

All properties set through the IBasicVideo and IVideoWindow interfaces are meant to be persistent across connections. Therefore, disconnecting and reconnecting a renderer should show no effects on the window size, position, or styles. However, if the video dimensions change between connections, the renderer should reset the source and destination rectangles to their defaults. The source and destination positions are set through the IBasicVideo interface.

Both IBasicVideo and IVideoWindow provide enough access to properties to allow an application to save and restore all the data in the interface in a persistent format. This will be useful to applications that must save the exact configuration and properties of filter graphs during an editing session and restore them later.


Handling EC_REPAINT Notifications

The EC_REPAINT notification is sent only when the renderer is either paused or stopped. This notification signals to the Filter Graph Manager that the renderer needs data. If the filter graph is stopped when it receives one of these notifications, it will pause the filter graph, wait for all filters to receive data (by calling GetState), and then stop it again. When stopped, a video renderer should hold on to the image so that subsequent WM_PAINT messages can be handled.

Therefore, if a video renderer receives a WM_PAINT message when stopped or paused, and it has nothing with which to paint its window, then it should send EC_REPAINT to the Filter Graph Manager. If an EC_REPAINT notification is received while paused, then the Filter Graph Manager calls IMediaPosition::put_CurrentPosition with the current position (that is, seeks to the current position). This causes the source filters to flush the filter graph and causes new data to be sent through the filter graph.

A renderer must send only one of these notifications at a time. Therefore, once the renderer sends a notification, it should ensure no more are sent until some samples are delivered. The conventional way to do this is to have a flag to signify that a repaint can be sent, which is turned off after an EC_REPAINT notification is sent. This flag should be reset once data is delivered or when the input pin is flushed, but not if end-of-stream is signaled on the input pin.

If the renderer does not monitor its EC_REPAINT notifications, it will flood the Filter Graph Manager with EC_REPAINT requests (which are relatively expensive to process). For example, if a renderer has no image to draw, and another window is dragged across the window of the renderer in a full-drag operation, the renderer receives multiple WM_PAINT messages. Only the first of these should generate an EC_REPAINT event notification from the renderer to the Filter Graph Manager.

A renderer should send its input pin as the first parameter to the EC_REPAINT notification. By doing this, the attached output pin will be queried for IMediaEventSink, and if supported, the EC_REPAINT notification will be sent there first. This enables output pins to handle repaints before the filter graph must be touched. This will not be done if the filter graph is stopped, because no buffers would be available from the decommitted renderer allocator.

If the output pin cannot handle the request and the filter graph is running, then the EC_REPAINT notification is ignored. An output pin must return NOERROR (S_OK) from IMediaEventSink::Notify to signal that it processed the repaint request successfully. The output pin will be called on the Filter Graph Manager worker thread, which avoids having the renderer call the output pin directly, and so sidesteps any deadlock issues. If the filter graph is stopped or paused and the output doesn't handle the request, then the default processing is done.


Handling Notifications in Full-Screen Mode

The IVideoWindow plug-in distributor (PID) in the filter graph manages full-screen playback. It will swap a video renderer out for a specialist full-screen renderer, stretch a window of a renderer to full screen, or have the renderer implement full-screen playback directly. To interact in full-screen protocols, a video renderer should send an EC_ACTIVATE notification whenever its window is either activated or deactivated. In other words, an EC_ACTIVATE notification should be sent for each WM_ACTIVATEAPP message a renderer receives.

When a renderer is being used in full-screen mode, these notifications manage the switching into and out of that full-screen mode. Window deactivation typically occurs when a user presses ALT+TAB to switch to another window, which the DirectShow full-screen renderer uses as a cue to return to typical rendering mode.

When the EC_ACTIVATE notification is sent to the Filter Graph Manager upon switching out of full-screen mode, the Filter Graph Manager sends an EC_FULLSCREEN_LOST notification to the controlling application. The application might use this notification to restore the state of a full-screen button, for example. The EC_ACTIVATE notifications are used internally by DirectShow to manage full-screen switching on cues from the video renderers.


Summary of Notifications

This section lists the filter graph notifications that a renderer can send.

Event notification | Description
EC_ACTIVATE | Sent by video renderers in full-screen rendering mode for each WM_ACTIVATEAPP message received.
EC_COMPLETE | Sent by renderers after all data has been rendered.
EC_DISPLAY_CHANGED | Sent by video renderers when a display format changes.
EC_PALETTE_CHANGED | Sent whenever a video renderer detects a palette change in the stream.
EC_REPAINT | Sent by stopped or paused video renderers when a WM_PAINT message is received and there is no data to display. This causes the Filter Graph Manager to generate a frame to paint to the display.
EC_USERABORT | Sent by video renderers to signal a closure that the user requested (for example, a user closing the video window).
EC_VIDEO_SIZE_CHANGED | Sent by video renderers whenever a change in native video size is detected.
EC_WINDOW_DESTROYED | Sent by video renderers when the filter is removed or destroyed so that resources that depend on window focus can be passed to other filters.


Source and Target Rectangles in Video Renderers

There are three sizes found in the VIDEOINFO, VIDEOINFOHEADER, and VIDEOINFOHEADER2 format structures of video media types. This article explains what they are and how they work.

First, there is a size in the bmiHeader member of these structures. The bmiHeader member is a BITMAPINFOHEADER structure with its own width and height members, bmiHeader.biWidth and bmiHeader.biHeight.

Second, there is a rectangle in the rcSource member of these structures; and last, there is a rectangle in the rcTarget member of these structures.

Assume you have two filters, A and B, and that these filters are connected to each other (A on the left, or upstream, and B on the right, or downstream) with a certain video media type.

The buffers that pass between filters A and B have the size (bmiHeader.biWidth, bmiHeader.biHeight). Filter A should take a portion of its input video determined by rcSource and stretch that video to fill the rcTarget portion of the buffer. The portion of the input video to use is based on how rcSource compares to the (biWidth, biHeight) size of the media type that filters A and B originally connected with. If rcSource is empty, filter A uses its entire input video. If rcTarget is empty, filter A fills the entire output buffer.

For example, assume filter A is receiving video data that is 160 x 120 pixels. Assume also that filter A is connected to filter B with the following media type.

(biWidth, biHeight): 320, 240

rcSource: (0, 0, 0, 0)

rcTarget: (0, 0, 0, 0)

This means that filter A will stretch the video it receives by 2 in both the x and y directions, and fill a 320 x 240 output buffer.

As another example, assume filter A is receiving 160 x 120 video data, and that it is connected to filter B with the following media type.

(biWidth, biHeight): 320, 240

rcSource: (0, 0, 160, 240)

rcTarget: (0, 0, 0, 0)

The rcSource member is relative to the connected buffer size of 320, 240. Because the specified rcSource (0, 0, 160, 240) is the left half of the buffer, filter A will take the left half of its input video, or the (0, 0, 80, 120) portion, and stretch the video to a size of (320, 240) (by 4 in the x direction, and by 2 in the y direction) and filling the 320 x 240 output buffer.

Now assume that filter A calls CBaseAllocator::GetBuffer, and the media sample returned has a media type attached to it, signifying that filter B wants filter A to provide a different size or kind of video than it has previously been providing. Assume the new media type is:

(biWidth, biHeight): 640, 480

rcSource: (0, 0, 160, 120)

rcTarget: (0, 0, 80, 60)

This means that the media sample has a buffer that is 640 x 480 in size. The rcSource member is relative to the original connected media type (320, 240) not to the new media type of (640, 480), so rcSource specifies that the top-left corner (25%) of the input video is to be used. This portion of the input video is placed in the top-left (80, 60) pixels of the 640 x 480 output buffer, as specified by rcTarget of (0, 0, 80, 60). Because filter A is receiving 160 x 120 video, the top-left corner of the input video is an (80, 60) piece, the same size of the output bitmap, and no stretching is required.

Filter A will place no data in the other pixels of the output buffer, and will leave those bits untouched. The rcSource member is bounded by the biWidth and biHeight of the original connected media type between filters A and B, and rcTarget is bounded by the new biWidth and biHeight of the media sample. In the preceding example, rcSource could not go outside the boundaries of (0, 0, 320, 240) and rcTarget could not go outside the boundaries of (0, 0, 640, 480).


Writing Capture Filters

Writing audio and video capture filters is no longer recommended. Instead, DirectShow provides automatic support for audio and video capture devices, using wrapper filters and the System Device Enumerator. For more information about implementing a device driver, refer to the Windows Driver Development Kit (DDK) documentation.

This section is intended only for developers who need to capture some kind of custom data from an unusual hardware device.

This article contains the following sections:

  • Pin Requirements for Capture Filters
  • Implementing a Preview Pin (Optional)
  • Producing Data in a Capture Filter


Pin Requirements for Capture Filters

Pin Name

You can give a pin any name. If the pin name begins with the tilde (~) character, the Filter Graph Manager does not automatically render that pin when an application calls IGraphBuilder::RenderFile. For example, if the filter has a capture pin and a preview pin, you might want them "~Capture" and "Preview," respectively. If an application renders that filter in a graph, the preview pin will connect to its default renderer, and nothing will connect to the capture pin, which is a reasonable default behavior. This can also apply to pins that deliver informational data that is not meant to be rendered, or pins that need custom properties set. Note that pins with the tilde (~) prefix can still be connected manually by the application.

Pin Category

A capture filter always has a capture pin, and might have a preview pin. Some capture filters might have other output pins, to deliver other types of data, such as control information. Each output pin must expose the IKsPropertySet interface. Applications use this interface to determine the pin category. The pin typically returns either PIN_CATEGORY_CAPTURE or PIN_CATEGORY_PREVIEW. For more information, see Pin Property Set.

The following example shows how to implement IKsPropertySet to return the pin category on a capture pin:

// Set: Cannot set any properties.
HRESULT CMyCapturePin::Set(REFGUID guidPropSet, DWORD dwID,
    void *pInstanceData, DWORD cbInstanceData, void *pPropData,
    DWORD cbPropData)
{
    return E_NOTIMPL;
}

// Get: Return the pin category (our only property).
HRESULT CMyCapturePin::Get(
    REFGUID guidPropSet,   // Which property set.
    DWORD dwPropID,        // Which property in that set.
    void *pInstanceData,   // Instance data (ignore).
    DWORD cbInstanceData,  // Size of the instance data (ignore).
    void *pPropData,       // Buffer to receive the property data.
    DWORD cbPropData,      // Size of the buffer.
    DWORD *pcbReturned     // Return the size of the property.
)
{
    if (guidPropSet != AMPROPSETID_Pin)
        return E_PROP_SET_UNSUPPORTED;
    if (dwPropID != AMPROPERTY_PIN_CATEGORY)
        return E_PROP_ID_UNSUPPORTED;
    if (pPropData == NULL && pcbReturned == NULL)
        return E_POINTER;
    if (pcbReturned)
        *pcbReturned = sizeof(GUID);
    if (pPropData == NULL)  // Caller just wants to know the size.
        return S_OK;
    if (cbPropData < sizeof(GUID)) // The buffer is too small.
        return E_UNEXPECTED;
    *(GUID *)pPropData = PIN_CATEGORY_CAPTURE;
    return S_OK;
}

// QuerySupported: Query whether the pin supports the specified property.
HRESULT CMyCapturePin::QuerySupported(REFGUID guidPropSet, DWORD dwPropID,
    DWORD *pTypeSupport)
{
    if (guidPropSet != AMPROPSETID_Pin)
        return E_PROP_SET_UNSUPPORTED;
    if (dwPropID != AMPROPERTY_PIN_CATEGORY)
        return E_PROP_ID_UNSUPPORTED;
    if (pTypeSupport)
        // We support getting this property, but not setting it.
        *pTypeSupport = KSPROPERTY_SUPPORT_GET;
    return S_OK;
}


Implementing a Preview Pin (Optional)

If your filter has a preview pin, the preview pin must send a copy of the data delivered by the capture pin. Only send data from the preview pin when doing so will not cause the capture pin to drop frames. The capture pin always has priority over the preview pin.

The capture pin and the preview pin must send data with the same format. Therefore, they must connect using identical media types. If the capture pin connects first, the preview pin should offer the same media type, and reject any others types. If the preview pin connects first, and the capture pin connects with a different media type, the preview pin should reconnect using the new media type. If the filter downstream from the preview pin rejects the new type, the capture pin should also reject the type. Use the IPin::QueryAccept method to query the filter downstream from the preview pin, and use the IFilterGraph::Reconnect method to reconnect the pin. These rules also apply if the Filter Graph Manager reconnects the capture pin.

The following example shows an outline of this process:

// Override CBasePin::CheckMediaType.
CCapturePin::CheckMediaType(CMediaType *pmt)
{
    if (m_pMyPreviewPin->IsConnected())
    {
        // The preview pin is already connected, so query the pin it is
        // connected to. If the other pin rejects it, so do we.
        hr = m_pMyPreviewPin->GetConnected()->QueryAccept(pmt);
        if (hr != S_OK)
        {
            // The preview pin cannot reconnect with this media type.
            return E_INVALIDARG;
        }
        // The preview pin will reconnect when SetMediaType is called.
    }
    // Decide whether the capture pin accepts the format.
    BOOL fAcceptThisType = ...  // (Not shown.)
    return (fAcceptThisType? S_OK : E_FAIL);
}

// Override CBasePin::SetMediaType.
CCapturePin::SetMediaType(CMediaType *pmt);
{
    if (m_pMyPreviewPin->IsConnected())
    {
        // The preview pin is already connected, so it must reconnect.
        if (m_pMyPreviewPin->GetConnected()->QueryAccept(pmt) == S_OK)
        {
            // The downstream pin will accept the new type, so it's safe
            // to reconnect.
            m_pFilter->m_pGraph->Reconnect(m_pMyPreviewPin);
        }
        else
        {
            return VFW_E_INVALIDMEDIATYPE;
        }
    }
    // Now do anything that the capture pin needs to set the type.
    hr = MyInternalSetMediaType(pmt);

    // And finally, call the base-class method.
    return CBasePin::SetMediaType(pmt);
}

CPreviewPin::CheckMediaType(CMediaType *pmt)
{
    if (m_pMyCapturePin->IsConnected())
    {
       // The preview pin must connect with the same type.
       CMediaType cmt = m_pMyCapturePin->m_mt;
       return (*pmt == cmt ? S_OK : VFW_E_INVALIDMEDIATYPE);
    }
    // Decide whether the preview pin accepts the format. You can use your
    // knowledge of which types the capture pin will accept. Regardless,
    // when the capture pin connects, the preview pin will reconnect.
    return (fAcceptThisType? S_OK : E_FAIL);
}

See Also

  • How Filters Connect


Producing Data in a Capture Filter

State Changes

A capture filter should produce data only when the filter is running. Do not send data from your pins when the filter is paused. Also, return VFW_S_CANT_CUE from the CBaseFilter::GetState method when the filter is paused. This return code informs the Filter Graph Manager that it should not wait for any data from your filter while the filter is paused. For more information, see Filter States.

The following code shows how to implement the GetState method:

CMyVidcapFilter::GetState(DWORD dw, FILTER_STATE *pState)
{
    CheckPointer(pState, E_POINTER);
    *pState = m_State;
    if (m_State == State_Paused)
        return VFW_S_CANT_CUE;
    else
        return S_OK;
}

Controlling Individual Streams

A capture filter's output pins should support the IAMStreamControl interface, so that an application can turn each pin on or off individually. For example, an application can preview without capturing, and then switch to capture mode without rebuilding the filter graph. You can use the CBaseStreamControl class to implement this interface.

Time Stamps

When the filter captures a sample, time stamp the sample with the current stream time. The end time is the start time plus the duration. For example, if the filter is capturing at ten samples per second, and the stream time is 200,000,000 units when the filter captures the sample, the time stamps should be 200000000 and 201000000. (There are 10,000,000 units per second.) Use the IReferenceClock::GetTime method to get the current reference time, and the IMediaSample::SetTime method to set the time stamps.

Time stamps must always increase from one sample to the next. This is true even when the filter pauses. If the filter runs, pauses, and then runs again, the first sample after the pause must have a larger time stamp than the last sample before the pause.

Samples from the preview pin should not have time stamps, however. Preview samples always reach the renderer slightly after the time of capture, so the renderer will treat them as late samples. This might cause the renderer to drop samples, in a futile attempt to catch up. Note that the IAMStreamControl interface requires the pin to keep track of sample times. For a preview pin, you might need to modify the implementation so that it does not rely on time stamps.

Depending on the data you are capturing, it might be appropriate to set the media time on the samples.

For more information, see Time and Clocks in DirectShow.


Exposing Capture and Compression Formats

This article describes how to return capture and compression formats by using the IAMStreamConfig::GetStreamCaps method. This method can get more information about accepted media types than the traditional way of enumerating a pin's media types, so it should typically be used instead. GetStreamCaps can return information about the kinds of formats allowed for audio or video. Additionally, this article provides some sample code that demonstrates how to reconnect the input pin of a transform filter to ensure your filter can produce a particular output.

The GetStreamCaps method returns an array of pairs of media type and capabilities structures. The media type is an AM_MEDIA_TYPE structure and the capabilities are represented either by an AUDIO_STREAM_CONFIG_CAPS structure or a VIDEO_STREAM_CONFIG_CAPS structure. The first section in this article presents a video example and the second presents an audio example.

This article contains the following topics:

  • Video Capabilities
  • Audio Capabilities
  • Reconnecting Your Input to Ensure Specific Output Types


Video Capabilities

The IAMStreamConfig::GetStreamCaps method presents video capabilities in an array of pairs of AM_MEDIA_TYPE and VIDEO_STREAM_CONFIG_CAPS structures. You can use this to expose all the formats and resolutions supported on a pin as discussed below.

For audio-related examples of GetStreamCaps, see Audio Capabilities.

Suppose your capture card supports JPEG format at all resolutions between 160 x 120 pixels and 320 x 240 pixels, inclusive. The difference between supported resolutions is one in this case because you add or subtract one pixel from each supported resolution to get the next supported resolution. This difference in supported resolutions is called granularity.

Suppose your card also supports the size 640 x 480. The following illustrates this single resolution and the above range of resolutions (all sizes between 160 x 120 pixels and 320 x 240 pixels).

Resolution from 160 x 120 to 320 x 240 pixels, plus 640 x 480

Also, suppose it supports 24-bit color RGB format at resolutions between 160 x 120 and 320 x 240, but with a granularity of 8. The following illustration shows some of the valid sizes in this case.

Resolution from 160 x 120 to 320 to 240, with Granularity = 8

To put it another way, and listing more resolutions, the following are all among the list of valid resolutions.

  • 160 x 120
  • 168 x 120
  • 168 x 128
  • 176 x 128
  • 176 x 136
  • ... additional resolutions ...
  • 312 x 232
  • 320 x 240

Use GetStreamCaps to expose these color format and dimension capabilities by offering a media type of 320 x 240 JPEG (if that is your default or preferred size) coupled with minimum capabilities of 160 x 120, maximum capabilities of 320 x 240, and a granularity of 1. The next pair you expose by using GetStreamCaps is a media type of 640 x 480 JPEG coupled with a minimum of 640 x 480 and a maximum of 640 x 480 and a granularity of 0. The third pair includes a media type of 320 x 240, 24-bit RGB with minimum capabilities of 160 x 120, maximum capabilities of 320 x 240, and a granularity of 8. In this way you can publish almost every format and capability your card might support. An application that must know what compression formats you provide can get all the pairs and make a list of all the unique subtypes of the media types.

A filter obtains its media type source and target rectangles from the VIDEOINFOHEADER structure's rcSource and rcTarget members, respectively. Filters do not have to support source and target rectangles.

The cropping rectangle described throughout the IAMStreamConfig documentation is the same as the VIDEOINFOHEADER structure's rcSource rectangle for the output pin.

The output rectangle described throughout the IAMStreamConfig documentation is the same as the biWidth and biHeight members of the output pin's BITMAPINFOHEADER structure (see DV Data in the AVI File Format.).

If a filter's output pin is connected to a media type with nonempty source and target rectangles, then your filter is required to stretch the input format's source subrectangle into the output format's target subrectangle. The source subrectangle is stored in the VIDEO_STREAM_CONFIG_CAPS structure's InputSize member.

For example, consider the following video compressor scenario: The input image is in RGB format and has a size of 160 x 120 pixels. The source rectangle's upper-left corner is at coordinate (20,20), and its lower-right corner is at (30,30). The output image is in MPEG format with a size of 320 x 240. The target rectangle's upper-left corner is at (0,0) and its lower-right corner is at (100,100). In this case, the filter should take a 10 x 10 piece of the 160 x 120 RGB source bitmap, and make it fill the top 100 x 100 area of a 320 x 240 bitmap, leaving the rest of the 320 x 240 bitmap untouched. The following illustration shows this scenario.

A filter might not support this and can fail to connect with a media type where rcSource and rcTarget are not empty.

The VIDEOINFOHEADER structure exposes information about a filter's data rate capabilities. For example, suppose you connected your output pin to the next filter with a certain media type (either directly or by using the media type passed by the CMediaType::SetFormat function). Look at the dwBitRate member of that media type's VIDEOINFOHEADER format structure to see what data rate you should compress the video to. If you multiply the number of units of time per frame in the VIDEOINFOHEADER structure's AvgTimePerFrame member by the data rate in the dwBitRate member and divide by 10,000,000 (the number of units per second), you can figure out how many bytes each frame should be. You can produce a smaller sized frame, but never a larger one. To determine the frame rate for a video compressor or for a capture filter, use AvgTimePerFrame from your output pin's media type.


Audio Capabilities

For audio capabilities, IAMStreamConfig::GetStreamCaps returns an array of pairs of AM_MEDIA_TYPE and AUDIO_STREAM_CONFIG_CAPS structures. As with video, you can use this to expose all kinds of audio capabilities on the pin, such as data rate and whether it supports mono or stereo.

For video-related examples relating to GetStreamCaps, see Video Capabilities.

Suppose you support pulse code modulation (PCM) wave format (as represented by the WAVEFORMATEX structure) at sampling rates of 11,025, 22,050, and 44,100 samples per second, all at 8- or 16-bit mono or stereo. In this case, you would offer two pairs of structures. The first pair would have an AUDIO_STREAM_CONFIG_CAPS capability structure saying you support a minimum of 11,025 to a maximum of 22,050 samples per second with a granularity of 11,025 samples per second (granularity is the difference between supported values); an 8-bit minimum to a 16-bit maximum bits per sample with a granularity of 8 bits per sample; and one-channel minimum and two-channel maximum. The first pair's media type would be your default PCM format in that range, perhaps 22 kilohertz (kHz), 16-bit stereo. Your second pair would be a capability showing 44,100 for both minimum and maximum samples per second; 8-bit (minimum) and 16-bit (maximum) bits per sample, with a granularity of 8 bits per sample; and one-channel minimum and two-channel maximum. The media type would be your default 44 kHz format, perhaps 44 kHz 16-bit stereo.

If you support non-PCM wave formats, the media type returned by this method can show which non-PCM formats you support (with a default sample rate, bit rate, and channels) and the capabilities structure accompanying that media type can describe which other sample rates, bit rates, and channels you support.


Reconnecting Your Input to Ensure Specific Output Types

Filters implement the IAMStreamConfig::SetFormat method to set the audio or video format before the filter's pins are connected. If your output pin is already connected and you can provide a new type, then reconnect your pin, but only if the other filter can accept the new type. If the other filter cannot accept the media type, fail the call to SetFormat and leave your connection alone.

A transform filter may not have any preferred output types unless their input pin is connected. In that case, the SetFormat and IAMStreamConfig::GetStreamCaps methods should return VFW_E_NOT_CONNECTED until the input pin is connected. Otherwise, these methods can function as usual.

In certain cases it is useful to reconnect pins when you are offering a format on an established connection. For example, suppose that a filter can compress 24-bit RGB video into format X, and that it can compress 8-bit RGB video into format Y. The output pin can do either of the following:

  • Always offer both X and Y in GetStreamCaps, and always accept both X and Y in SetFormat.
  • Offer and accept just format X if the input type is 24-bit RGB. Offer and accept just format Y if the input type 8-bit RGB. Fail both methods if the input pin is not connected.

In either case, you will need some reconnecting code that looks like this:

HRESULT MyOutputPin::CheckMediaType(const CMediaType *pmtOut)
{
    // Fail if the input pin is not connected.
    if (!m_pFilter->m_pInput->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    // (Not shown: Reject any media types that you know in advance your
    // filter cannot use. Check the major type and subtype GUIDs.)

    // (Not shown: If SetFormat was previously called, check whether
    // pmtOut exactly matches the format that was specified in SetFormat.
    // Return S_OK if they match, or VFW_E_INVALIDMEDIATYPE otherwise.)

    // Now do the normal check for this media type.
    HRESULT hr;
    hr = m_pFilter->CheckTransform(
        &m_pFilter->m_pInput->CurrentMediaType(),  // The input type.
        pmtOut  // The proposed output type.
    );
    if (hr == S_OK)
    {
        // This format is compatible with the current input type.
        return S_OK;
    }

    // This format is not compatible with the current input type.
    // Maybe we can reconnect the input pin with a new input type.

    // Enumerate the upstream filter's preferred output types, and
    // see if one of them will work.
    CMediaType *pmtEnum;
    BOOL fFound = FALSE;
    IEnumMediaTypes *pEnum;
    hr = m_pFilter->m_pInput->GetConnected()->EnumMediaTypes(&pEnum);
    if (hr != S_OK)
    {
        return E_FAIL;
    }
    while (hr = pEnum->Next(1, (AM_MEDIA_TYPE **)&pmtEnum, NULL), hr == S_OK)
    {
        // Check this input type against the proposed output type.
        hr = m_pFilter->CheckTransform(pmtEnum, pmtOut);
        if (hr != S_OK)
        {
            DeleteMediaType(pmtEnum);
            continue; // Try the next one.
        }

        // This input type is a possible candidate. But, we have to make
        // sure that the upstream filter can switch to this type.
        hr = m_pFilter->m_pInput->GetConnected()->QueryAccept(pmtEnum);
        if (hr != S_OK)
        {
            // The upstream filter will not switch to this type.
            DeleteMediaType(pmtEnum);
            continue; // Try the next one.
        }
        fFound = TRUE;
        DeleteMediaType(pmtEnum);
        break;
    }
    pEnum->Release();

    if (fFound)
    {
        // This output type is OK, but if we are asked to use it, we will
        // need to reconnect our input pin. (See SetFormat, below.)
        return S_OK;
    }
    else
    {
        return VFW_E_INVALIDMEDIATYPE;
    }
}

HRESULT MyOutputPin::SetFormat(AM_MEDIA_TYPE *pmt)
{
    CheckPointer(pmt, E_POINTER);
    HRESULT hr;

    // Hold the filter state lock, to make sure that streaming isn't
    // in the middle of starting or stopping:
    CAutoLock cObjectLock(&m_pFilter->m_csFilter);

    // Cannot set the format unless the filter is stopped.
    if (m_pFilter->m_State != State_Stopped)
    {
        return VFW_E_NOT_STOPPED;
    }

    // The set of possible output formats depends on the input format,
    // so if the input pin is not connected, return a failure code.
    if (!m_pFilter->m_pInput->IsConnected())
    {
        return VFW_E_NOT_CONNECTED;
    }

    // If the pin is already using this format, there's nothing to do.
    if (IsConnected() && CurrentMediaType() == *pmt)
    {
        return S_OK;
    }

    // See if this media type is acceptable.
    if ((hr = CheckMediaType((CMediaType *)pmt)) != S_OK)
    {
        return hr;
    }

    // If we're connected to a downstream filter, we have to make
    // sure that the downstream filter accepts this media type.
    if (IsConnected())
    {
        hr = GetConnected()->QueryAccept(pmt);
        if (hr != S_OK)
        {
            return VFW_E_INVALIDMEDIATYPE;
        }
    }

    // Now make a note that from now on, this is the only format allowed,
    // and refuse anything but this in the CheckMediaType code above.

    // Changing the format means reconnecting if necessary.
    if (IsConnected())
    {
        m_pFilter->m_pGraph->Reconnect(this);
    }

    return NOERROR;
}

// Override CTransformFilter::SetMediaType to reconnect the input pin.
// This method is called immediately after the media type is set on a pin.
HRESULT MyFilter::SetMediaType(
    PIN_DIRECTION direction,
    const CMediaType *pmt
)
{
    HRESULT hr;
    if (direction == PINDIR_OUTPUT)
    {
        // Before we set the output type, we might need to reconnect
        // the input pin with a new type.
        if (m_pInput && m_pInput->IsConnected())
        {
            // Check if the current input type is compatible.
            hr = CheckTransform(
                    &m_pInput->CurrentMediaType(),
                    &m_pOutput->CurrentMediaType());
            if (SUCCEEDED(hr))
            {
                return S_OK;
            }
            // Otherwise, we need to reconnect the input pin.
            // Note: The CheckMediaType method has already called
            // QueryAccept on the upstream filter.
            hr = m_pGraph->Reconnect(m_pInput);
            return hr;
        }
    }
    return S_OK;
}


Registering a Custom File Type

This article describes how the Filter Graph Manager locates a source filter, given a file name. You can use this mechanism to register your own custom file types. Once the file type is registered, DirectShow will automatically load the correct source filter whenever an application calls IGraphBuilder::RenderFile or IGraphBuilder::AddSourceFilter.

To locate a source filter from a given file name, the Filter Graph Manager attempts to do the following, in order:

  1. Match the protocol, if any.
  2. Match the file extension.
  3. Match patterns of bytes within the file, called check bytes.

Protocols

Protocol names such as ftp or http are registered under the HKEY_CLASSES_ROOT key, with the following structure:

HKEY_CLASSES_ROOT
    <protocol>
        Source Filter = <Source filter CLSID>
        Extensions
            <.ext1> = <Source filter CLSID>
            <.ext2> = <Source filter CLSID>

If the file name contains a colon (':'), the Filter Graph Manager attempts to use the portion before the ':' as a protocol name. For example, if the name is "myprot://myfile.ext", it searches for a registry key named myprot. If this key exists and contains a subkey named Extensions, the Filter Graph Manager searches within that subkey for entries that match the file extension. The value of the key must be a GUID in string form; for example, "{00000000-0000-0000-0000-000000000000}". If the Filter Graph Manager cannot match anything within the Extensions subkey, it looks for a subkey named Source Filter, which must also be a GUID in string form.

If the Filter Graph Manager finds a matching GUID, it uses this as the CLSID of the source filter, and attempts to load the filter. If it does not find a match, it uses the File Source (URL) filter, which treats the file name as a URL.

There are two exceptions to this algorithm:

  • To exclude driver letters, single-character strings are not considered protocols.
  • If the string is "file:" or "file://", it is not treated as a protocol.

File Extensions

If there is no protocol in the file name, the Filter Graph Manager looks in the registry for entries with the key HKEY_CLASSES_ROOT\Media Type\Extensions\.ext\, where .ext is the file extension. If this key exists, the value Source Filter contains the CLSID of the source filter, in string form. Optionally, the key can have values for Media Type and Subtype, which give the major type and subtype GUIDs.

Check Bytes

Some file types can be identified by specific patterns of bits occurring at specific byte offsets in the file. The Filter Graph Manager looks in the registry for keys with the following form:

HKEY_CLASSES_ROOT\MediaType\{major type}\{subtype}

where major type and subtype are GUIDs that define the media type for the byte stream. Each key contains one or more subkeys, usually named 1, 2, and so on, which define the check bytes; and a subkey named Source Filter that gives the CLSID of the source filter, in string form. The check-byte subkeys are strings that contain one or more quads of numbers:

offset,cb,mask,val

To match the file, the Filter Graph Manager reads cb bytes, starting from byte number offset. It then performs a bitwise-AND against the value in mask. If the result equals val, the file is a match for that quad. The values mask and val are given in hex. A blank entry for mask is treated as a string of 1s of length cb. A negative value for offset indicates an offset from the end of the file. In order to match the key, the file must match all of the quads in any of the subkeys.

For example, assume the registry contains the following keys under HKCR\Media Type:

{e436eb83-524f-11ce-9f53-0020af0ba770}
    {7364696D-0000-0010-8000-00AA00389B71}
        0                    "0,4,,52494646,8,4,,524D4944"
        1                    "0,4,,4D546864"
        Source Filter        "{E436EBB5-524F-11CE-9F53-0020AF0BA770}"

The first key corresponds to the major type MEDIATYPE_Stream. The subkey below that corresponds to the subtype MEDIATYPE_Midi. The value for the Source Filter subkey is CLSID_AsyncReader, the CLSID of the File Source (Async) filter.

Each entry can have multiple quadruples; all of them must match. In the following example, the first 4 bytes of the file must be 0xAB, 0xCD, 0x12, 0x34; and the last 4 bytes of the file must be 0xAB, 0xAB, 0x00, 0xAB:

    0, 4, , ABCD1234,  -4, 4, , ABAB00AB

Also, there can be multiple entries listed under a single media type. A match to any of them is sufficient. This scheme allows for a set of alternative masks; for instance, .wav files that might or might not have a RIFF header.

Note This scheme is similar to the one used by the Microsoft® Win32® function GetClassFile.

Loading the Source Filter

Assuming that the Filter Graph Manager finds a matching source filter for the file, it adds that filter to the graph, queries the filter for the IFileSourceFilter interface, and calls IFileSourceFilter::Load. The arguments to the Load method are the file name and the media type, as determined from the registry.

If the Filter Graph Manager cannot find anything from the registry, it defaults to using the Async File Source filter. In that case, it sets the media type to MEDIATYPE_Stream, MEDIASUBTYPE_None.


Creating a Filter Property Page

This section describes how to create a property page for a custom DirectShow filter, using the CBasePropertyPage class. The example code in this section shows all the steps needed to create a property page. The example shows a property page for a hypothetical video effect filter that supports a saturation property. The property page has a slider, which the user can move to adjust the filter's saturation level.

This section contains the following topics:

  • Step 1. Define a Mechanism for Setting the Property
  • Step 2. Implement ISpecifyPropertyPages
  • Step 3. Support QueryInterface
  • Step 4. Create the Property Page
  • Step 5. Store a Pointer to the Filter
  • Step 6. Initialize the Dialog
  • Step 7. Handle Window Messages
  • Step 8. Apply Property Changes
  • Step 9. Disconnect the Property Page
  • Step 10. Support COM Registration


Step 1. Define a Mechanism for Setting the Property

The filter must support a way for the property page to communicate with it, so that the property page can set and retrieve properties on the filter. Possible mechanisms include the following:

  • Expose a custom COM interface.
  • Support Automation properties, through IDispatch.
  • Expose the IPropertyBag interface and define a set of named properties.

This example uses a custom COM interface, named ISaturation. This is not an actual DirectShow interface; it is defined only for this example. Start by declaring the interface in a header file, along with the interface identifier (IID):

// Always create new GUIDs! Never copy a GUID from an example.
DEFINE_GUID(IID_ISaturation, 0x19412d6e, 0x6401,
0x475c, 0xb0, 0x48, 0x7a, 0xd2, 0x96, 0xe1, 0x6a, 0x19);

interface ISaturation : public IUnknown
{
    STDMETHOD(GetSaturation)(long *plSat) = 0;
    STDMETHOD(SetSaturation)(long lSat) = 0;
};

You can also define the interface with IDL and use the MIDL compiler to create the header file. Next, implement the custom interface in the filter. This example uses "Get" and "Set" methods for the filter's saturation value. Notice that both methods protect the m_lSaturation member with a critical section.

class CGrayFilter : public ISaturation, /* Other inherited classes. */
{
private:
    CCritSec  m_csShared;    // Protects shared data.
    long      m_lSaturation; // Saturation level.
public:
    STDMETHODIMP GetSaturation(long *plSat)
    {
        if (!plSat) return E_POINTER;
        CAutoLock lock(&m_csShared);
        *plSat = m_lSaturation;
        return S_OK;
    }
    STDMETHODIMP SetSaturation(long lSat)
    {
        if (lSat < SATURATION_MIN || lSat > SATURATION_MAX)
        {
            return E_INVALIDARG;
        }
        CAutoLock lock(&m_csShared);
        m_lSaturation = lSat;
        return S_OK;
    }
};

Of course, the details of your own implementation will differ from the example shown here.

See Also

  • CCritSec Class


Step 2. Implement ISpecifyPropertyPages

Next, implement the ISpecifyPropertyPages interface in your filter. This interface has a single method, GetPages, which returns an array of CLSIDs for the property pages that the filter supports. In this example, the filter has a single property page. Start by generating the CLSID and declaring it in your header file:

// Always create new GUIDs! Never copy a GUID from an example.
DEFINE_GUID(CLSID_SaturationProp, 0xa9bd4eb, 0xded5,
0x4df0, 0xba, 0xf6, 0x2c, 0xea, 0x23, 0xf5, 0x72, 0x61);

Now implement the GetPages method:

class CGrayFilter : public ISaturation,
                    public ISpecifyPropertyPages,
                    /* Other inherited classes. */
{
public:
    STDMETHODIMP GetPages(CAUUID *pPages)
    {
        if (pPages == NULL) return E_POINTER;
        pPages->cElems = 1;
        pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID));
        if (pPages->pElems == NULL)
        {
            return E_OUTOFMEMORY;
        }
        pPages->pElems[0] = CLSID_SaturationProp;
        return S_OK;
    }
};

/* ... */

}

Allocate memory for the array using CoTaskMemAlloc. The caller will release the memory.


Step 3. Support QueryInterface

To expose the filter's new interfaces to clients, do the following:

  • Include the DECLARE_IUNKNOWN macro in the public declaration section of your filter:
    public:
    DECLARE_IUNKNOWN;
  • Override CUnknown::NonDelegatingQueryInterface to check for the IIDs of the two interfaces:
    STDMETHODIMP CGrayFilter::NonDelegatingQueryInterface(REFIID riid,
    void **ppv)
{
    if (riid == IID_ISpecifyPropertyPages)
    {
        return GetInterface(static_cast<ISpecifyPropertyPages*>(this),
           ppv);
    }
    if (riid == IID_ISaturation)
    {
        return GetInterface(static_cast<IYuvGray*>(this), ppv);
    }
    return CBaseFilter::NonDelegatingQueryInterface(riid, ppv);
}

See Also

  • How to Implement IUnknown


Step 4. Create the Property Page

At this point the filter supports everything that it needs for a property page. The next step is implementing the property page itself. Start by deriving a new class from CBasePropertyPage. The following example shows part of the declaration, including some private member variables that will be used later in the example:

class CGrayProp : public CBasePropertyPage
{
private:
    ISaturation *m_pGray;    // Pointer to the filter's custom interface.
    long        m_lVal       // Store the old value, so we can revert.
    long        m_lNewVal;   // New value.
public:
    /* ... */
};

Next, create a dialog resource in the resource editor, along with a string resource for the dialog title. The string will appear in the tab for the property page. The two resource IDs are arguments to the CBasePropertyPage constructor:

CGrayProp::CGrayProp(IUnknown *pUnk) :
  CBasePropertyPage(NAME("GrayProp"), pUnk, IDD_PROPPAGE, IDS_PROPPAGE_TITLE),
  m_pGray(0)
{ }

The following illustration shows the dialog resource for the example property page.

Property Page Dialog

Now you are ready to implement the property page. Here are the methods in CBasePropertyPage to override:

  • OnConnect is called when the client creates the property page. It sets the IUnknown pointer to the filter.
  • OnActivate is called when the dialog is created.
  • OnReceiveMessage is called when the dialog receives a window message.
  • OnApplyChanges is called when the user commits the property changes by clicking the OK or Apply button.
  • OnDisconnect is called when the user dismisses the property sheet.

The remainder of this tutorial describes each of these methods.


Step 5. Store a Pointer to the Filter

Override the CBasePropertyPage::OnConnect method to store a pointer to the filter. The following example queries the pUnk parameter for the filter's custom ISaturation interface:

HRESULT CGrayProp::OnConnect(IUnknown *pUnk)
{
    if (pUnk == NULL)
    {
        return E_POINTER;
    }
    ASSERT(m_pGray == NULL);
    return pUnk->QueryInterface(IID_ISaturation,
        reinterpret_cast<void**>(&m_pGray));
}


Step 6. Initialize the Dialog

Override the CBasePropertyPage::OnActivate method to initialize the dialog. In this example, the property page uses a slider control, so the first step in OnActivate is to initialize the common control library. The method then initializes the slider control using the current value of the filter's saturation property:

HRESULT CGrayProp::OnActivate(void)
{
    INITCOMMONCONTROLSEX icc;
    icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icc.dwICC = ICC_BAR_CLASSES;
    if (InitCommonControlsEx(&icc) == FALSE)
    {
        return E_FAIL;
    }

    ASSERT(m_pGray != NULL);
    HRESULT hr = m_pGray->GetSaturation(&m_lVal);
    if (SUCCEEDED(hr))
    {
        SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETRANGE, 0,
            MAKELONG(SATURATION_MIN, SATURATION_MAX));

        SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETTICFREQ,
            (SATURATION_MAX - SATURATION_MIN) / 10, 0);

        SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETPOS, 1, m_lVal);
    }
    return hr;
}


Step 7. Handle Window Messages

Override the CBasePropertyPage::OnReceiveMessage method to update the dialog controls in response to user input. If you don't handle a particular message, call the OnReceiveMessage method on the parent class. Whenever the user changes a property, do the following:

  • Set the m_bDirty variable of the property page to TRUE.
  • Call the IPropertyPageSite::OnStatusChange method of the property frame with the PROPPAGESTATUS_DIRTY flag. This flag informs the property frame that it should enable the Apply button. The CBasePropertyPage::m_pPageSite member holds a pointer to the IPropertyPageSite interface.

To simplify this step, you can add the following helper function to your property page:

private:
    void SetDirty()
    {
        m_bDirty = TRUE;
        if (m_pPageSite)
        {
            m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
        }
    }

Call this private method inside OnReceiveMessage whenever a user action changes a property, as shown in the following example:

BOOL CGrayProp::OnReceiveMessage(HWND hwnd,
    UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_DEFAULT)
        {
            // User clicked the 'Revert to Default' button.
            m_lNewVal = SATURATION_DEFAULT;
            m_pGray->SetSaturation(m_lNewVal);

            // Update the slider control.
            SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETPOS, 1,
                m_lNewVal);
            SetDirty();
            return (LRESULT) 1;
        }
        break;

    case WM_HSCROLL:
        {
            // User moved the slider.
            switch(LOWORD(wParam))
            {
            case TB_PAGEDOWN:
            case SB_THUMBTRACK:
            case TB_PAGEUP:
                m_lNewVal = SendDlgItemMessage(m_Dlg, IDC_SLIDER1,
                    TBM_GETPOS, 0, 0);
                m_pGray->SetSaturation(m_lNewVal);
                SetDirty();
            }
            return (LRESULT) 1;
        }
    } // Switch.

    // Let the parent class handle the message.
    return CBasePropertyPage::OnReceiveMessage(hwnd,uMsg,wParam,lParam);
}

The property page in this example has two controls, a slider bar and a Revert to Default button. If the user scrolls the slider bar, the property page sets the saturation value on the filter. If the user clicks the button, the property page restores the filter's default saturation value. In each case, m_lNewVal holds the current value and m_lVal holds the original value. The value of m_lVal is not updated until the user commits the change, which happens when the user clicks the OK or Apply button on the property frame.


Step 8. Apply Property Changes

Override the CBasePropertyPage::OnApplyChanges method to commit any property changes. In this example, the m_lNewVal variable is updated whenever the user scrolls the slider bar. The OnApplyChanges method copies this value into the m_lVal variable, overwriting the original value:

HRESULT CGrayProp::OnApplyChanges(void)
{
    m_lVal = m_lNewVal;
    return S_OK;
}


Step 9. Disconnect the Property Page

Override the CBasePropertyPage::OnDisconnect method to release any interfaces that you obtained in the OnConnect method. Also, if the user dismisses the property sheet without committing the changes, you should restore the original values if they have changed. There is no "OnCancel" method that gets called when the user cancels, so you need to keep track of whether the user has called OnApplyChanges. This example uses the m_lVal variable, described earlier:

HRESULT CGrayProp::OnDisconnect(void)
{
    if (m_pGray)
    {
        // If the user clicked OK, m_lVal holds the new value.
        // Otherwise, if the user clicked Cancel, m_lVal is the old value.
        m_pGray->SetSaturation(m_lVal);
        m_pGray->Release();
        m_pGray = NULL;
    }
    return S_OK;
}


Step 10. Support COM Registration

The last remaining task is to support COM registration, so that the property frame can create new instances of your property page. Add another CFactoryTemplate entry to the global g_Templates array, which is used to register all of the COM objects in your DLL. Do not include any filter set-up information for the property page.

const AMOVIESETUP_FILTER FilterSetupData =
{
    /* Not shown ... */
};

CFactoryTemplate g_Templates[] =
{
    // This entry is for the filter.
    {
        wszName,
        &CLSID_GrayFilter,
        CGrayFilter::CreateInstance,
        NULL,
        &FilterSetupData
    },
    // This entry is for the property page.
    {
        L"Saturation Props",
        &CLSID_SaturationProp,
        CGrayProp::CreateInstance,
        NULL, NULL
    }
};

If you declare g_cTemplates as shown in the following code, then it automatically has the correct value based on the array size:

int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]);

Also, add a static CreateInstance method to the property page class. You can name the method anything that you prefer, but the signature must match the one shown the following example:

static CUnknown * WINAPI CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CGrayProp *pNewObject = new CGrayProp(pUnk);
    if (pNewObject == NULL)
    {
        *pHr = E_OUTOFMEMORY;
    }
    return pNewObject;
}

To test the property page, register the DLL and then load the filter in GraphEdit. Left-click the filter to view the property page.

See Also

  • How to Create a DLL
  • Simulating Graph Building with GraphEdit


Encoder and Decoder Development

This section contains articles about encoder and decoder development for DirectShow. These topics are not relevant for application developers.

A software decoder that supports DirectX Video Acceleration (VA) must be implemented as a DirectShow copy transform filter. If the decoder does not support DirectX VA, it can also be implemented as a DirectX Media Object (DMO). A decoder that connects to a video renderer should not be implemented as a trans-in-place filter, because this will result in significant performance degradation. For information on how to write a copy transform filter, see Writing Transform Filters.

Software encoders can be implemented as either transform filters or DMOs. Encoders do not use DirectX VA, since DirectX VA currently is only used for decompression. The Encoder API specification described in this section is relevant for both hardware and software encoders.

This section contains the following topics:

Encoders

  • Encoder API

Decoders

  • How Decoders Use IAMVideoAccelerator
  • About DirectX Video Acceleration
  • Mapping DirectX Video Acceleration to IAMVideoAccelerator
  • DVD Decoder Development in DirectShow
  • Decoder Volume Control

See Also

  • Using the VMR for DirectShow Filter Developers


Encoder API

The Encoder API provides a uniform interface for configuring software and hardware encoders. Applications can use the Encoder API to configure an encoder and to store the configuration settings. Encoder vendors can use the Encoder API to expose the capabilities of an encoder. Although the Encoder API is designed primarily for encoders, it is general enough that decoders can support it as well.

The Encoder API is exposed to applications through the ICodecAPI interface, which is exposed by the encoder filter. The encoder filter may be a native DirectShow filter, a hardware encoder, or a DirectX Media Object (DMO).

  • Software filters: An encoder that is implemented as a native DirectShow filter should expose the ICodecAPI directly.
  • Hardware encoders: The encoding device is exposed through one or more AVStream minidrivers, which are represented in user mode by KSProxy. KSProxy translates ICodecAPI method calls into KS property sets. For more information, see "Encoder Minidrivers" in the DDK.
  • DMOs: The DMO should expose the ICodecAPI interface. DirectShow applications can query the DMO Wrapper filter, which exposes the interface by aggregating the DMO. Applications not based on DirectShow can query the DMO directly.

Encoder Capabilties

An encoder can register a list of high-level capabilities by storing them in the system registry. Each capability is identified by a GUID. To enumerate the capabilities of a particular encoder, do the following:

  1. Create the moniker that represents the encoder filter. (See Using the System Device Enumerator.)
  2. Query the filter moniker for the IGetCapabilitiesKey interface.
  3. Call IGetCapabilitiesKey::GetCapabilitiesKey. The method returns a handle to the registry key that contains the filter's capabilities list.
  4. Call RegEnumValue to enumerate the values for the returned key.

If you are devloping an encoder, create the registry entries for the capabilities when the filter is registered. For software filters, create a key named Capabilities that is adjacent to the FilterData and FriendlyName keys. Typically, you would add this information after calling AMovieDllRegisterServer2 to register the standard filter data. For more information, see How to Register DirectShow Filters. Alternatively, you can create a CapabilitiesLocation key that contains a string giving the location of the Capabilities key in the registry. The string should start with "HKLM\", "HKCR\", or "HKCU\" to indicate the registry subtree. For Plug and Play devices, the driver's setup files should create a Capabilities key adjacent to the filter's FriendlyName key, or it can use a CapabilitiesLocation key as described for software filters.

Once you have created the Capabilities key, create a value for each capability GUID. The name of the value should be the string form of the GUID, in the form {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Each value type should be one of the following:

  • Single numerical value. Use a DWORD value.
  • GUID. Use the string form of the GUID.
  • Numeric pairs. Use a string with the form "a,b" to represent pairs of values, such as width and height, or numerator and denominator for fractions.
  • Arrays of values. Use multi-strings (REG_SZ_MULTI) to represent more than one value.

The following example shows the registry layout for a software filter:

\HKCR\CLSID\Filter Category\Instance\Filter CLSID\Capabilities\
    Values:
    guid1: 1234 (REG_DWORD)
    guid2: "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" (REG_SZ)
    guid3: "2","4","6" (REG_SZ_MULTI)
    guid4: "720,480" (REG_SZ)

Encoder Profiles

An encoder profile is a fixed list of configuration settings that can be applied to an encoder at run time. Profiles are independent of the encoder; an application can select an encoder, then select a profile and apply the profile settings to the encoder. Profiles are identified by GUID and should be stored in the following location in the registry:

\HKLM\Software\Microsoft\EncoderProfiles\Profile GUID\

where Profile GUID is the string form of the GUID that identifies the profile. Create values for each setting. Also create a value named FriendlyName whose data contains a printable string identifying the profile (such as "LowBandwidthVideo").


Decoder Interfaces and Specifications

This section contains the following topics relevant to developer of hardware and software video decoders.

  • How Decoders Use IAMVideoAccelerator
  • About DirectX Video Acceleration
  • Mapping DirectX Video Acceleration to IAMVideoAccelerator
  • DVD Decoder Development in DirectShow
  • Decoder Volume Control


How Decoders Use IAMVideoAccelerator

The IAMVideoAccelerator interface enables generic video acceleration operations, including DirectX Video Acceleration (VA). For non-DirectX VA acceleration, the decoder and video driver must both adhere to a common protocol.

This section describes the general order of operations that any decoder should follow when using this interface. Further information specific to DirectX VA-based decoders can be found in Mapping DirectX Video Acceleration to IAMVideoAccelerator.

Note This interface is available in Microsoft Windows® 2000 and later.

The IAMVideoAccelerator interface is exposed on the input pin of the Overlay Mixer or Video Mixing Renderer (VMR). The IAMVideoAcceleratorNotify interface is exposed on the decoder's output pin. The sequence of events for connecting the filter pins is as follows:

  1. The filter graph manager calls decoder's output pin's IPin::Connect. An AM_MEDIA_TYPE is an optional parameter.
    • AM_MEDIA_TYPE is a data structure that describes a type of media. It contains a majortype GUID (which in our case should be MEDIATYPE_Video), a subtype GUID (which in our case should be a video accelerator GUID), and a variety of other things. One of those things is a format type GUID containing information about the media, including in our case the width and height of an uncompressed video picture, most likely in an MPEG1VIDEOINFO, VIDEOINFOHEADER, MPEG2VIDEOINFO, or VIDEOINFOHEADER2 structure.
    • The AM_MEDIA_TYPE structure, if present, tells the decoder to operate using the specified media type, which may be "fully specified" or "partially specified". If "fully specified," the decoder would normally simply attempt to operate with that media type. If "partially specified," it will attempt to find a "fully-specified" compatible mode of operation that it can use to connect in a manner consistent with the "partially-specified" media type.
    • The ordinary manner for attempting to find a "fully-specified" media type to use for a connection is to simply run through a list of every "fully-specified" media type that the output pin supports which is compatible with the "partially-specified" media type and attempt to connect with each of them until successful. The process would normally be similar if no AM_MEDIA_TYPE is contained in the IPin::Connect call, but with the output pin needing to check all of its media types.
  2. If the decoder wants to check whether a specific AM_MEDIA_TYPE (including a video accelerator GUID) is supported by the downstream input pin, it can call that pin's IPin::QueryAccept (with the video accelerator GUID as the subtype of the AM_MEDIA_TYPE) or it can simply attempt to connect to that pin as described in item 5 below.
  3. If the decoder does not know which video accelerator GUIDs the downstream input pin supports and does not wish to propose just some particular candidate video accelerator GUID by calling the downstream input pin's IPin::QueryAccept, the decoder can call IAMVideoAccelerator::GetVideoAcceleratorGUIDs to get a list of the video accelerator GUIDs the pin supports.
  4. For some particular video accelerator GUIDs, the decoder can call the downstream input pin's IAMVideoAccelerator::GetUncompFormatsSupported to get a list of the DDPIXELFORMAT pixel formats that can be used to render a specific video accelerator GUID. The list returned should be considered to be in decreasing preference order (that is, with the most preferred format listed first).
  5. The decoder calls the downstream input pin's IPin::ReceiveConnection, passing it an AM_MEDIA_TYPE with the proper video accelerator GUID as the subtype of the media type. This sets up the connection for operation, including the creation of the uncompressed output surfaces (which are allocated using the width and height found in AM_MEDIA_TYPE, and the number of surfaces to allocate found by a call described below, and whatever other information the video accelerator has available and wishes to use for that purpose—such as the video accelerator GUID itself). If the downstream input pin rejects the video accelerator GUID or some other aspect of the connection, this can cause the IPin::ReceiveConnection to fail. If IPin::ReceiveConnection fails, this is indicated in a returned HRESULT, and the decoder can try to make the call again, for example, with a new video accelerator GUID in the AM_MEDIA_TYPE structure.

    Note This is another way (and the most definitive way) for the decoder to determine what is supported by the downstream input pin—simply calling IPin::ReceiveConnection and trying to connect, and then checking whether the connection attempt was successful.

    • During the IPin::ReceiveConnection, the renderer calls the decoder's IAMVideoAcceleratorNotify::GetUncompSurfacesInfo, passing it the video accelerator GUID and an AMVAUncompBufferInfo structure, in order to figure out how many uncompressed surfaces to allocate. The decoder fills in and returns the structure, which contains the minimum and maximum number of surfaces to be allocated of the particular type, and a DDPIXELFORMAT structure describing the pixel format of the surfaces to be allocated.
    • MINOR NOTE: Nothing is actually passed in to the decoder in the call to IAMVideoAcceleratorNotify::GetUncompSurfacesInfo other than the video accelerator GUID.
  6. The renderer calls the decoder's IAMVideoAcceleratorNotify::SetUncompSurfacesInfo, passing to the decoder the actual number of uncompressed surfaces that were allocated.
  7. The renderer calls the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData to get any data needed to initialize the video accelerator.
  8. The decoder calls IAMVideoAccelerator::GetCompBufferInfo, passing it a video accelerator GUID, an AMVAUncompDataInfo structure, and the number of compressed buffer types, to get in return a set of AMVACompBufferInfo data structures, one corresponding to each type of compressed data buffer used by the video accelerator GUID.
    • The AMVAUncompDataInfo structure contains the width and height of the decoded uncompressed data (in pixels) and the DDPIXELFORMAT of the uncompressed picture.
    • The AMVACompBufferInfo data structures returned each contain:

      The number of compressed buffers needed of the specific type.

      The width and height of the surface to create (fields which may or may not have any actual meaning).

      Note The DirectDraw surface allocation operation for the compressed buffers does not currently provide for the width or height of these surfaces to be greater than or equal to 215, although the surface allocation call may not overtly fail if this limit is violated. Therefore, the driver could structure its requests for compressed buffer memory to avoid such extreme sizes. For example, rather than requesting a buffer with width="1" and height="65536", the driver should request a buffer of width="1024" and height="64".

      The total number of bytes to be used by the surface.

      A structure of type DDSCAPS2 defining a DirectDrawSurface object, describing the capabilities to create surfaces to store compressed data.

      A DDPIXELFORMAT, describing the pixel format used to create surfaces to store compressed data (a field which may or may not have any actual meaning).

Note The renderer's calls to some of the decoder's IAMVideoAcceleratorNotify interface methods may (and normally would) occur inside of the decoder's call to the renderer's IPin::ReceiveConnection. Specifically, this applies to the following:

  • IAMVideoAcceleratorNotify::GetUncompSurfacesInfo,
  • IAMVideoAcceleratorNotify::SetUncompSurfacesInfo, and
  • IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData.

Note To support dynamic format changes, the decoder may also call IPin::ReceiveConnection and other methods per above while the filters are connected and running. This capability is provided in order to support dynamic format changes (although not in the H.263, Annex P, sense - as all data sets are started up again from scratch and any reference picture information is therefore lost).

The following is a description of IAMVideoAccelerator use during operation after initialization:

  1. For each uncompressed surface, the decoder calls IAMVideoAccelerator::BeginFrame to begin the processing to create the output picture. When it does this, the decoder sends an AMVABeginFrameInfo structure.
    • The AMVABeginFrameInfo structure contains an index for a destination buffer, a pointer to some data to send downstream, and a pointer to a place where the accelerator can put some data for the decoder to read.
    • NOTE 1: The accelerator does not actually receive the destination buffer index, as it is translated by the renderer before going downstream.
    • NOTE 2: IAMVideoAccelerator::BeginFrame can be called more than once between calls to IAMVideoAccelerator::EndFrame.
    • NOTE 3: There is no assumption within the interface operation that IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame need to be called for the processing of every individual picture in the bitstream.

      What IAMVideoAccelerator::BeginFrame does, as far as the interface is concerned, is create an association within the renderer between an index and an uncompressed surface. It also provides a means to call a specific function in a device driver (with support of a means of passing arbitrary data back and forth between the decoder and the device driver).

      (However, in DirectX VA operation there is a requirement described below that IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame do need to be called for the processing of every individual picture in the bitstream.)

  2. For sending uncompressed data to the accelerator, the decoder calls:
    • IAMVideoAccelerator::QueryRenderStatus to determine whether a buffer is safe for reading from or writing to.
    • IAMVideoAccelerator::GetBuffer to lock and obtain access to a specified buffer (if it has not previously called this to get that access). GetBuffer can also be used to get a copy of the contents of the last uncompressed output picture for which IAMVideoAccelerator::BeginFrame was called, providing IAMVideoAccelerator::EndFrame has not been called for that destination buffer index. If the DDI returns a render status of DDERR_WASSTILLDRAWING for the requested buffer, a sleep loop will be operated within GetBuffer until this condition is cleared. In order to call GetBuffer, the decoder will need some information from an AMVACompBufferInfo data structure which is obtained by calling IAMVideoAccelerator::GetCompBufferInfo.
    • IAMVideoAccelerator::Execute to indicate that the data in a set of compressed buffers as indicated in an array of AMVABUFFERINFO data structures should be processed. A function code dwFunction is passed to the driver in this call. A lpPrivateInputData pointer is also passed to some data to send downstream, and a lpPrivateOutputData pointer is passed to a place where the downstream process can put some data for the decoder to read.
    • IAMVideoAccelerator::ReleaseBuffer to indicate that the decoder has completed use of a specified buffer for the moment and no longer needs locked access to the buffer. (If the decoder wishes to continue to use the buffer, it can simply not call IAMVideoAccelerator::ReleaseBuffer for the moment, thus avoiding the need to call IAMVideoAccelerator::GetBuffer until it really intends to not use the buffer anymore.) The decoder should not write into the buffer after Execute is called until QueryRenderStatus indicates that the buffer is safe for writing.
  3. To complete output processing for a destination buffer, the decoder calls IAMVideoAccelerator::EndFrame. It can pass some arbitrary data downstream with this call, and that's essentially all that happens as a result of this call. It doesn't send a destination buffer index in this call, so it can't indicate to the accelerator precisely what destination buffer is completed unless this indication is contained in the arbitrary data that is passed.
  4. To display a frame, the decoder calls IAMVideoAccelerator::DisplayFrame with the index of the frame to display and a IMediaSample structure containing start and stop time stamps and relevant flags such as dwTypeSpecificFlags (in the AM_SAMPLE2_PROPERTIES structure) and dwInterlaceFlags (in the VIDEOINFOHEADER2 structure). The decoder must verify that all decompression operations that affect the content of the frame have completed before calling DisplayFrame.
  5. Finally, the decoder should, upon completion of all processing, indicate completion of all remaining begun output frames by calling IAMVideoAccelerator::EndFrame and release all of its locked buffers by calling IAMVideoAccelerator::ReleaseBuffer for each unreleased buffer.


About DirectX Video Acceleration

DirectX VA describes an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for hardware acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. It provides an interface definition focused on support of MPEG-2 "main profile" video (formally ITU-T H.262 | ISO/IEC 13818-2), but is also intended to support other key video codecs (for example, ITU-T Recommendations H.263 and H.261, and MPEG-1 and MPEG-4). DirectX VA also specifies how device drivers can implement de-interlacing and frame rate conversion operations.

  • Note: The DirectX VA specification is now located in the Microsoft Platform DDK. Developers of software decoders as well as device drivers should refer to that specification.


Mapping DirectX Video Acceleration to IAMVideoAccelerator

The following section is primarily relevant for software decoder developers. It provides detailed information on how to use the IAMVideoAccelerator Interface when communicating through the Overlay Mixer or Video Mixing Renderer filter with a DirectX VA-enabled hardware device. This section covers the following topics:

  • Restricted Mode Profile and Configuration Establishment
  • DirectX Video Acceleration IAMVideoAccelerator Operational Specification
  • Operational Correspondence with Motion Compensation Device Driver


Restricted Mode Profile and Configuration Establishment

Due to the variety of types of data that can be decoded by DirectX VA, and the multiple decoding configurations supported within DirectX VA for each of these types of data (for example, using bitstream buffers versus host residual difference decoding versus accelerator-based IDCT with and without encryption of each relevant type of buffer, and so on), we believe it would be somewhat ungainly to simply specify a unique GUID for every unique data type and decoding configuration. This would create a large number of GUIDs (for example, hypothetically if there were 16 profiles of DirectX VA and 16 configurations possible for each, there would need to be 256 defined GUIDs—requiring 4 kilobytes of memory just to hold them all. This issue is the most difficult part of determining how to map DirectX VA into IAMVideoAccelerator, with the remainder of the operational definition mostly being quite straightforward. As a result, we specify a unique GUID only for each type of data (for each restricted mode profile) and allow an additional GUID to be associated with each type of encryption. The decoding configuration is then established between the decoder and accelerator by a lower-level subordinate negotiation using probing and locking operations to establish configurations for each type of DirectX VA function.


DirectX Video Acceleration IAMVideoAccelerator Operational Specification

The precise mechanism of operation is as follows:

  1. Each restricted mode profile defined herein has an associated DirectX VA GUID which can be supported by a downstream input pin's IPin::QueryAccept and IPin::ReceiveConnection and listed in IAMVideoAccelerator::GetVideoAcceleratorGUIDs.
  2. Similarly, each encryption protocol type for use with DirectX VA shall have an associated encryption protocol type GUID which can be supported by a downstream input pin's IPin::QueryAccept and IPin::ReceiveConnection and listed in IAMVideoAccelerator::GetVideoAcceleratorGUIDs. The "no encryption" GUID DXVA_NoEncrypt shall not be sent in this list, as support for it is required and therefore implicit.
  3. After calling IPin::ReceiveConnection to attempt a connection to the downstream input pin, the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData shall return a pointer to a DXVA_ConnectMode data structure containing the connection mode information for the connection. IAMVideoAccelerator::GetCompBufferInfo shall be called with *pdwNumTypesCompBuffers = 16 and shall return compressed buffer information based on the convention that the type number of each buffer (as defined in Section 3.4 of the DirectX VA specification) can be used directly as the zero-based index into the array of AMVACompBufferInfo data structures that is returned. This requires that for any buffer types that will not be used (including buffer type 0, since there is no defined use of that buffer type), the accelerator driver will provide AMVACompBufferInfo data structures with some form of "dummy" parameter values (such as dwNumCompBuffers=0, dwWidthToCreate=0, dwHeightToCreate=0, and dwBytesToAllocate=0).
  4. DXVA function indications and associated data buffers are sent using IAMVideoAccelerator::Execute. The DXVA function is indicated in the dwFunction parameter of the call. The only DXVA functions that are relevant for initialization are DXVA_ConfigQueryOrReplyFunc and DXVA_EncryptProtocolFunc.
    • If dwFunction contains a DXVA_ConfigQueryOrReplyFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to a configuration data structure, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where an alternative or duplicate configuration data structure can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains the S_OK or S_FALSE indication, or E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution (such as an invalid configuration parameter). All calls to IAMVideoAccelerator::Execute for all uses of DXVA_ConfigQueryOrReplyFunc shall precede all other calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to an encryption protocol data structure that begins with DXVA_EncryptProtocolHeader, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where the data to be returned (such as a certificate) by the encryption protocol (which will begin with DXVA_EncryptProtocolHeader) can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains S_OK as long as the encryption protocol is functioning normally and contains E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution.

      After initialization of operation in the above fashion, the actual operation of the decoder proceeds as follows:

  5. IAMVideoAccelerator::BeginFrame shall be called prior to sending any bDXVA_Func with compressed buffer parameters which cause writes to an uncompressed destination surface. The purpose of IAMVideoAccelerator::BeginFrame in DirectX VA is to associate destination surfaces with index values and to notify the video accelerator driver of the intent to initiate writes a surface so that the driver can respond with an indication of whether the surface is ready to be overwritten. The AMVABeginFrameInfo structure passed in IAMVideoAccelerator::BeginFrame shall contain a pInputData pointer to single WORD wBeginPictureIndex parameter matching the frame index passed into IAMVideoAccelerator::BeginFrame (and dwSizeInputData shall be 2). This is the index to be used in a compressed buffer to command a write to the surface (for example, to be used as wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex). Each call to IAMVideoAccelerator::BeginFrame shall be paired with a corresponding call to IAMVideoAccelerator::EndFrame as described below. For example, if a compressed picture is to be decoded and then alpha blended using front-end buffer-to-buffer blending with a graphic image, there would be a call to IAMVideoAccelerator::BeginFrame prior to decoding the compressed picture into a surface specified in wDecodedPictureIndex, then a call to IAMVideoAccelerator::EndFrame after passing all compressed buffers used to decode the picture, then a second call to IAMVideoAccelerator::BeginFrame prior to commanding alpha blending combination of the graphic source with the decoded picture into a surface specified in wBlendedDestinationIndex, and then a second call to IAMVideoAccelerator::EndFrame after the alpha blend combination operation.The pointer pOutputData in AMVABeginFrameInfo shall be NULL (and dwSizeOutputData shall be "0"). The HRESULT that is returned by IAMVideoAccelerator::BeginFrame shall be:
    • S_OK if the uncompressed surface is available and ready for use.
    • E_PENDING if the uncompressed surface is not yet available for use but will become available soon (if the uncompressed surface is being read for display and the reading/display of the surface has not yet been completed).
    • E_FAIL or E_INVALIDARG some other error indication only if a data format or protocol error is detected (such as an incorrect value of dwSizeInputData or a non-NULL pOutputData).
  6. DXVA function indications and assocated data buffers are sent using IAMVideoAccelerator::Execute. More than one bDXVA_Func value may be indicated in the same call to IAMVideoAccelerator::Execute. The bDXVA_Func values shall be packed into the dwFunction parameter of the call, with the first function command in the eight MSBs, the next command in the next eight bits, and so on, with any remaining bits padded out with zeros. The value 0xFF for bDXVA_Func indicates that the bDXVA_Func is extended to two or four bytes. If the second byte is also 0xFF, this indicates that bDXVA_Func is extended to four bytes. If the upper four bits of the third byte are 0xF or 0x0, this indicates that bDXVA_Func contains a DXVA_ConfigQueryOrReplyFunc or DXVA_EncryptProtocolFunc. Multi-byte commands shall not indicate continuation past the end of dwFunction. Care must be taken by the decoder to ensure that no sequential dependencies are present between different bDXVA_Func values specified in the same call to IAMVideoAccelerator::Execute and that all potential race conditions (such as between picture decoding and sub-picture blending, between sub-picture loading and sub-picture blending, and so on) are prevented by appropriate calls to IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::QueryRenderStatus before subsequent calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_ConfigQueryOrReplyFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to a configuration data structure, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where an alternative or duplicate configuration data structure can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains the S_OK or S_FALSE indication in response to the query, or E_FAIL or E_INVALIDARG some other error indication HRESULT in the event of a severe problem in protocol execution (such as an invalid.configuration parameter). All calls to IAMVideoAccelerator::Execute for all uses of DXVA_ConfigQueryOrReplyFunc shall precede all other calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to an encryption protocol data structure that begins with DXVA_EncryptProtocolHeader, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where the data to be returned (such as a certificate) by the encryption protocol (which will begin with DXVA_EncryptProtocolHeader) can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains S_OK as long as the encryption protocol is functioning normally and contains E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution.
    • If dwFunction does not contain a DXVA_ConfigQueryOrReplyFunc or DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator shall point to a buffer description list. The first four entries in the buffer description list structure for each buffer (dwTypeIndex, dwBufferIndex, dwDataOffset, and dwDataSize) shall be equal to those in the AMVABUFFERINFO data structure for the same buffer. If bDXVA_Func is equal to "1" is specified within dwFunction and bPicReadbackRequests is "1", the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area of persistent memory (for example heap) to be filled in with read-back macroblock data from the accelerator (such data not guaranteed to be present until IAMVideoAccelerator::QueryRenderStatus for writing to the same picture parameters buffer indicates S_OK as described in item 10 below). Otherwise, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to a single DWORD to be set to one of the following indication values (particularly useful for reporting bitstream errors in off-host VLD operation).
      Value | Description
      0 | Execution OK.
      1 | Minor problem in data format encountered.
      2 | Significant problem in data format encountered.
      3 | Severe problem in data format encountered.
      4 | Other severe problem encountered.

      If either type of "severe" problem is indicated, the software decoder should cease to operate the function(s) unless corrective action can be taken. This data returned from the accelerator shall not be read by the host until after the buffer rendering for the picture has completed, as can be tested by IAMVideoAccelerator::QueryRenderStatus. The returned HRESULT contains S_OK as long as the interface operation is functioning normally and may return E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem.

  7. The picture decoding parameters buffer shall be among the first buffers sent for the decoding of each picture when using IAMVideoAccelerator::Execute with bDXVA_Func equal to "1", and all the buffers for decoding a picture in a bitstream shall be sent before any buffers for decoding subsequent pictures. If a macroblock control command buffer is sent, a corresponding residual difference data buffer shall be sent (containing data for the same macroblocks) with the same IAMVideoAccelerator::Execute call.
  8. IAMVideoAccelerator::EndFrame shall be called after all compressed buffers have been sent that will cause the creation of the output content in a specified uncompressed surface (a result of operations specified for wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex). The purpose of this call to IAMVideoAccelerator::EndFrame is to notify the video accelerator hardware that all data needed for the specified operation has been sent. The pointer to data to send downstream through IAMVideoAccelerator::EndFrame shall point to a single WORD wEndPictureIndex containing the index of the frame that is ending. This parameter shall match the wBeginPictureIndex value specified in the prior call to IAMVideoAccelerator::BeginFrame before the sending of the relevant compressed buffers. Subsequent to a call to IAMVideoAccelerator::EndFrame, the uncompressed surface with index wEndPictureIndex shall not be found in any picture's wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex until after another call to IAMVideoAccelerator::BeginFrame is issued to announce that this will occur and an S_OK has been returned as a result. However, that destination surface index may occur in subsequent read access commands such as wForwardRefPictureIndex, wBackwardRefPictureIndex, wPicResampleSourcePicIndex, or bRefPicSelect[i]. The HRESULT returned by IAMVideoAccelerator::EndFrame shall be S_OK unless there is some kind of data format or protocol error, in which case it can be E_FAIL or E_INVALIDARG or some other error indication.
  9. In the case of field based decoding (for example, in MPEG-2 bitstreams) there will not be a one-to-one mapping of functional pictures in the bitstream to uncompressed surfaces in the accelerator interface. When decoding field pictures in an MPEG-2 bitstream, there will be two "pictures" decoded to produce one complete output uncompressed surface. In the DirectX VA interface definition, each frame corresponds to each use of wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex. Thus two pairs of calls to IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame are required for the decoding of field pictures into output uncompressed surfaces.
  10. A call to IAMVideoAccelerator::QueryRenderStatus with dwFlags equal to zero which occurs sometime after a call to IAMVideoAccelerator::EndFrame with a particular wEndPictureIndex and checks the status of a buffer that was sent that contained the wEndPictureIndex in wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex will return an S_OK indication if all of the operations to write the data to the uncompressed surface have completed and will return E_PENDING if the operation has not yet completed. E_FAIL or E_INVALIDARG or some other error indication may be returned in the event of a protocol error.


Operational Correspondence with Motion Compensation Device Driver

This section contains a description of the Motion Compensation device driver side of the DirectX VA interface. (Reference:Windows 2000 DDK - Graphics Drivers - Design Guide - 3.0 DirectDraw DDI - 3.12 Motion Compensation. See the Windows DDK for documentation on the structures in boldface.)

The following items refer to entries accessed through the DD_MOTIONCOMPCALLBACKS structure:

  1. At the start of the relevant processing, the device driver's DdMoCompCreate is used to notify the driver that the software decoder will start using a video acceleration object.
  2. GUIDs received from IAMVideoAccelerator::GetVideoAcceleratorGUIDs originate from the device driver's DdMoCompGetGUIDs.
  3. A call to the downstream input pin's IAMVideoAccelerator::GetUncompFormatsSupported returns data from the device driver's DdMoCompGetFormats.
  4. The DXVA_ConnectMode data structure from the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData is passed to the device driver's DdMoCompCreate.
  5. Data returned from IAMVideoAccelerator::GetCompBufferInfo originates from the device driver's DdMoCompGetBuffInfo.
  6. Buffers sent using IAMVideoAccelerator::Execute are received by the device driver's DdMoCompRender.
  7. Use of IAMVideoAccelerator::QueryRenderStatus invokes the device driver's DdMoCompQueryStatus. A return code of DDERR_WASSTILLDRAWING from DdMoCompQueryStatus will be seen by the host decoder as a return code of E_PENDING from IAMVideoAccelerator::QueryRenderStatus.
  8. Data sent to IAMVideoAccelerator::BeginFrame are received by the device driver's DdMoCompBeginFrame. A return code of E_PENDING is needed from DdMoCompBeginFrame in order for E_PENDING to be seen by the host decoder in response to IAMVideoAccelerator::BeginFrame.
  9. Data sent to IAMVideoAccelerator::EndFrame are received by the device driver's DdMoCompEndFrame.
  10. At the end of the relevant processing, the device driver's DdMoCompDestroy is used to notify the driver that the current video acceleration object will no longer be used, so that the driver can perform any necessary cleanup.


DVD Decoder Development in DirectShow

This section contains pointers to the reference pages for all the DirectShow property sets and interfaces that are either DVD-specific or else used extensively in DVD decoding. In addition to what is listed here, a decoder and its pins must also support the generic DirectShow filter interfaces as described in Writing DirectShow Filters.

This section contains the following topics.

  • Decoder Volume Control
  • DVD Region Change Support in Windows

    See also:

  • DVD Karaoke Property Set
  • DVD Copy Protection Property Set
  • DVD Subpicture Property Set
  • Pin Property Set
  • IKsPropertySet Interface
  • IVideoFrameStep Interface (hardware decoders only)
  • IVPConfig Interface (hardware decoders only)


Decoder Volume Control

Applications control audio volume through the IBasicAudio interface. An IBasicAudio interface handler is provided for KSProxy. For a decoder to handle the volume commands from KSProxy, it must add several registry keys in its setup script and support the KSPROPSETID_Wave property set.

Create some new registry keys for the driver:

  HKLM\SYSTEM\
    CurrentControlSet\Control
      DeviceClasses
        (decoder guid, eg 2721AE....)
          (Pnp id, eg ##?#VDGENDEV#...)
            #GLOBAL
              Device Parameters
                CLSID      REG_SZ   {17CCA...}
                  FriendlyName   REG_SZ   WDM DVD Driver
                    Interfaces <--- create this key
                    {b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d} <-- also create this key, it is not a value)
      MediaInterfaces
        {b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d} <-- create this key
          (default)        REG_SZ    'KsProxy IBasicAudio handler' <-- set this value
          IID    REG_SZ    56 a8 68 b3 0a d4 11 ce b0 3a 00 20 af 0b a7 70    <-- create this string value

To implement volume control, the driver also must support KSPROPSETID_Wave, along with KsProperty.Id = KSPROPERTY_WAVE_VOLUME. This property is passed to the driver through the IKsPropertySet::Get and IKsPropertySet::Set methods. The LeftAttenuation and RightAttentuation fields specify the left/right speaker volumes as linear values from 0x0000 to 0xffff.


DirectShow Tutorials

This section contains tutorials for Microsoft® DirectShow®.

  • Implementing a Seek Bar
  • Displaying a Filter's Property Pages
  • Grabbing a Poster Frame
  • Using the Sample Grabber
  • Recompressing an AVI File


Implementing a Seek Bar

This section describes how to implement a seek bar for a media-player application. The seek bar is implemented as a trackbar control. For an overview of seeking in DirectShow, see Seeking the Filter Graph.

When the application starts, initialize the trackbar:

void InitSlider(HWND hwnd)
{
    // Initialize the trackbar range, but disable the
    // control until the user opens a file.
    hScroll = GetDlgItem(hwnd, IDC_SLIDER1);
    EnableWindow(hScroll, FALSE);
    SendMessage(hScroll, TBM_SETRANGE, TRUE, MAKELONG(0, 100));
}

The trackbar is disabled until the user opens a media file. The trackbar range is set from 0 to 100. During file playback, the application will calculate the playback position as a percentage of the file duration, and update the trackbar accordingly. For example, trackbar position "50" always corresponds to the middle of the file.

When the user opens a file, build a file-playback graph using RenderFile. The code for this is shown in How To Play a File. Then query the Filter Graph Manager for the IMediaSeeking interface and store the interface pointer:

IMediaSeeking *g_pSeek = 0;
hr = pGraph->QueryInterface(IID_IMediaSeeking, (void**)&g_pSeek);

To determine whether the file is seekable, call either the IMediaSeeking::CheckCapabilities method or the IMediaSeeking::GetCapabilities method. These methods do almost the same thing, but their semantics are slightly different. The following example uses CheckCapabilites:

// Determine if the source is seekable.
BOOL  bCanSeek = FALSE;
DWORD caps = AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanGetDuration;
bCanSeek = (S_OK == pSeek->CheckCapabilities(&caps));
if (bCanSeek)
{
    // Enable the trackbar.
    EnableWindow(hScroll, TRUE);

    // Find the file duration.
    pSeek->GetDuration(&g_rtTotalTime);
}

The AM_SEEKING_CanSeekAbsolute flag checks whether the source file is seekable, and the AM_SEEKING_CanGetDuration flag checks whether the duration of the file can be determined in advance. If both of the capabilities are supported, the application enables the trackbar and retrieves the file duration.

If the graph is seekable, the application will use a timer to update the trackbar position during playback. When you run the filter graph to play the file, start the timer event by calling one of the Windows timer functions, such as SetTimer. For more information about timers, see the topic "Timers" in the Platform SDK.

void StartPlayback(HWND hwnd)
{
    pControl->Run();
    if (bCanSeek)
    {
        StopTimer(); // Make sure an old timer is not still active.
        nTimerID = SetTimer(hwnd, IDT_TIMER1, TICK_FREQ, (TIMERPROC)NULL);
        if (nTimerID == 0)
        {
            /* Handle Error */
        }
    }
}

void StopTimer()
{
    if (wTimerID != 0)
    {
        KillTimer(g_hwnd, wTimerID);
        wTimerID = 0;
    }
}

Use the timer event to update the position of the trackbar. Call IMediaSeeking::GetCurrentPosition to retrieve the currant playback position, and then calculate the position as a percentage of the file duration:

case WM_TIMER:
    if (wParam == IDT_TIMER1)
    {
        // Timer should not be running unless we really can seek.
        ASSERT(bCanSeek == TRUE);

        REFERENCE_TIME timeNow;
        if (SUCCEEDED(pSeek->GetCurrentPosition(&timeNow)))
        {
            long sliderTick = (long)((timeNow * 100) / g_rtTotalTime);
            SendMessage( hScroll, TBM_SETPOS, TRUE, sliderTick );
        }
    }
    break;

The user can also move the trackbar to seek the file. When the user drags or clicks the trackbar control, the application receives a WM_HSCROLL event. The low word of the wParam parameter is the trackbar notification message. For example, TB_ENDTRACK is sent at the end of the trackbar action, and TB_THUMBTRACK is sent continuously while the user drags the trackbar. The following code shows one way to handle the WM_HSCROLL message:

static OAFilterState state;
static BOOL bStartOfScroll = TRUE;

case WM_HSCROLL:
    short int userReq = LOWORD(wParam);
    if (userReq == TB_ENDTRACK || userReq == TB_THUMBTRACK)
    {
        DWORD dwPosition  = SendMessage(hTrackbar, TBM_GETPOS, 0, 0);
        // Pause when the scroll action begins.
        if (bStartOfScroll)
        {
            pControl->GetState(10, &state);
            bStartOfScroll = FALSE;
            pControl->Pause();
        }
        // Update the position continuously.
        REFERENCE_TIME newTime = (g_rtTotalTime/100) * dwPosition;
        pSeek->SetPositions(&newTime, AM_SEEKING_AbsolutePositioning,
            NULL, AM_SEEKING_NoPositioning);

        // Restore the state at the end.
        if (userReq == TB_ENDTRACK)
        {
            if (state == State_Stopped)
                pControl->Stop();
            else if (state == State_Running)
                pControl->Run();
            bStartOfScroll = TRUE;
        }
    }
}

If the user drags the trackbar, the application issues a series of seek commands, one for each TB_THUMBTRACK message that it receives. To make the seek operations as smooth as possible, the application pauses the graph. Pausing the graph halts playback but ensures that the video window is updated. When the application receives the TB_ENDTRACK message, it restores the graph to its original state.


Displaying a Filter's Property Pages

A property page is one way for a filter to support properties that the user can set. This article describes how to display a filter's property pages in an application. For more information about property pages, see the Platform SDK documentation.

Note Although many of the filters provided with DirectShow support property pages, they are intended for debugging purposes, and are not recommended for application use. In most cases the equivalent functionality is provided through a custom interface on the filter. An application should control these filters programatically, rather than expose their property pages to users.

Filters with property pages expose the ISpecifyPropertyPages interface. To determine whether a filter defines a property page, query the filter for this interface using QueryInterface.

If you directly created an instance of a filter (by calling CoCreateInstance), you already have a pointer to the filter. If not, you can enumerate the filters in the graph, using the IFilterGraph::EnumFilters method. For details, see Enumerating Objects in a Filter Graph.

Once you have the ISpecifyPropertyPages interface pointer, retrieve the filter's property pages by calling the ISpecifyPropertyPages::GetPages method. This method fills a counted array of globally unique identifiers (GUIDs) with the class identifier (CLSID) of each property page. A counted array is defined by a CAUUID structure, which you must allocate but do not have to initialize. The GetPages method allocates the array, which is contained in the pElems member of the CAUUID structure. When you are done, free the array by calling the CoTaskMemFree function.

The OleCreatePropertyFrame function provides a simple way to display the property pages inside a modal dialog box.

IBaseFilter *pFilter;
/* Obtain the filter's IBaseFilter interface. (Not shown) */
ISpecifyPropertyPages *pProp;
HRESULT hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pProp);
if (SUCCEEDED(hr))
{
    // Get the filter's name and IUnknown pointer.
    FILTER_INFO FilterInfo;
    hr = pFilter->QueryFilterInfo(&FilterInfo);
    IUnknown *pFilterUnk;
    pFilter->QueryInterface(IID_IUnknown, (void **)&pFilterUnk);

    // Show the page.
    CAUUID caGUID;
    pProp->GetPages(&caGUID);
    pProp->Release();
    OleCreatePropertyFrame(
        hWnd,                   // Parent window
        0, 0,                   // Reserved
        FilterInfo.achName,     // Caption for the dialog box
        1,                      // Number of objects (just the filter)
        &pFilterUnk,            // Array of object pointers.
        caGUID.cElems,          // Number of property pages
        caGUID.pElems,          // Array of property page CLSIDs
        0,                      // Locale identifier
        0, NULL                 // Reserved
    );

    // Clean up.
    pFilterUnk->Release();
    FilterInfo.pGraph->Release();
    CoTaskMemFree(caGUID.pElems);
}


Grabbing a Poster Frame

This article describes how to display a poster frame from a digital media file, using the Media Detector (MediaDet) object provided with DirectShow Editing Services.

The Media Detector is a helper object that can get format information from a media source file. It can also grab a bitmap image from a video stream in the source file. Assuming the file is seekable, you can obtain the image from any point in the file. The returned image is always in 24-bit RGB format.

The Media Detector is not a filter, and the application does not need to use the Filter Graph Manager or create a filter graph. Internally, the Media Detector creates a filter graph that contains the Sample Grabber Filter. To get a bitmap, the Media Detector seeks and pauses the filter graph, and then retrieves the bitmap from the Sample Grabber filter. The application communicates with the Media Detector through the IMediaDet interface. The Media Detector is a good example of encapsulating a filter graph inside a helper object, in order to shield applications from graph-related details.

The Media Detector operates in two modes. When you first create it, the Media Detector is in "information gathering" mode. You can specify the name of a media file and get information about each of the streams in the file, such as the format type, the frame rate, or the duration. If the file contains a video stream, you can switch the Media Detector into "bitmap grab" mode and retrieve bitmaps from the source. However, once you do so, you cannot switch the Media Detector back to its original mode; it is permanently attached to that video stream. To work with another stream or another file, you must create a new instance of the Media Detector.

Note The code examples in this tutorial use the ATL CComPtr class, which automatically manages reference counts. If you prefer to use raw interface pointers, remember to release every interface when you are done with it. Also, for brevity the code examples omit much of the error checking that an application should perform. In working code, always check HRESULT values.

This tutorial contains the following steps:

  • Step 1: Create the Windows Framework
  • Step 2: Add a Menu Command to Grab a Poster Frame
  • Step 3: Implement the Frame-Grabbing Function
  • Step 4: Draw the Bitmap on the Client Area


Step 1: Create the Windows Framework

Start by creating the basic framework of a Windows application, including WinMain and a window procedure. The WinMain function is not shown here; call CoInitialize before the message loop to initialize the COM library, and CoUninitialize after the message loop exits. Start with the following minimal window procedure:

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    static BITMAPINFOHEADER *pbmi = NULL;
    static BYTE *pBuffer = NULL;
    switch (msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        if (pbmi) delete [] pbmi;
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, msg, wparam, lparam);
    }
    return 0;
}

When you retrieve a poster frame from the Media Detector, it returns a buffer that contains a BITMAPINFOHEADER structure followed by the image bits. Therefore, define two static variables in the window procedure: pbmi will hold a pointer to the BITMAPINFOHEADER structure, and pBuffer will hold a pointer to the bitmap. The application will allocate the buffer in pbmi using new, so it must delete the buffer before the window is destroyed. The pBuffer pointer is calculated as an offset from pbmi, so there is no need to delete it.


Step 2: Add a Menu Command to Grab a Poster Frame

Next, add a command for the user to grab a poster frame from a file. Create a menu item with a resource ID of IDM_BITMAP, and add the following case statement to the window procedure:

case WM_COMMAND:
    switch (LOWORD(wparam))
    {
    case IDM_BITMAP:
        {
            HRESULT hr = DoShowBitmap(hwnd, &pbmi);
            if (SUCCEEDED(hr))
            {
                pBuffer = reinterpret_cast<BYTE*>(pbmi) +
                    sizeof(BITMAPINFOHEADER);
                InvalidateRect(hwnd, NULL, TRUE);
            }
            else
            {
                MessageBox(hwnd, TEXT("Cannot display the image."),
                    TEXT("Error"), MB_OK | MB_ICONERROR);
            }
        }
        break;  // IDM_BITMAP
    }
    break;  // WM_COMMAND

The DoShowBitmap function will return the allocated buffer in pbmi. Assuming the function succeeds, the address of the bitmap (pBuffer) can be calculated as an offset from pbmi. In the DoShowBitmap function, display an Open File dialog box for the user to choose a file, and then call the application-defined GetBitmap function, which will retrieve the bitmap:

HRESULT DoShowBitmap(HWND hwnd, BITMAPINFOHEADER** ppbmih)
{
    OPENFILENAME ofn;       // common dialog box structure
    // Initialize OPENFILENAME (not shown).
    // Display the Open File dialog box.
    if (GetOpenFileName(&ofn) != TRUE) // failed to open file
    {
        return E_FAIL;
    }
    return GetBitmap(ofn.lpstrFile, ppbmih);
}


Step 3: Implement the Frame-Grabbing Function

The next step is to implement the GetBitmap function, which uses the Media Detector to grab a poster frame. Inside this function, perform the following steps:

  1. Create the Media Detector.
  2. Specify a media file.
  3. Examine each stream in the file. If it is a video stream, get the native dimensions of the video.
  4. Obtain a poster frame, specifying the seek time and the target dimension.

Create the Media Detector object by calling CoCreateInstance:

CComPtr<IMediaDet> pDet;
hr = pDet.CoCreateInstance(__uuidof(MediaDet));

Specify a file name, using the IMediaDet::put_Filename method. This method takes a BSTR parameter.

hr = pDet->put_Filename(bstrFilename);

Get the number of streams, and loop through each stream checking the media type. The IMediaDet::get_OutputStreams method retrieves the number of streams, and the IMediaDet::put_CurrentStream method specifies which stream to examine. Exit the loop on the first video stream.

long lStreams;
bool bFound = false;
hr = pDet->get_OutputStreams(&lStreams);
for (long i = 0; i < lStreams; i++)
{
    GUID major_type;
    hr = pDet->put_CurrentStream(i);
    hr = pDet->get_StreamType(&major_type);
    if (major_type == MEDIATYPE_Video)  // Found a video stream.
    {
        bFound = true;
        break;
    }
}
if (!bFound) return VFW_E_INVALIDMEDIATYPE;

If no video stream was found, the function exits.

In the previous code, the IMediaDet::get_StreamType method returns just the major type GUID. This is convenient if you do not need to examine the complete media type. To get the video dimensions, however, it is necessary to examine the format block, so the full media type is needed. You can retrieve that by calling the IMediaDet::get_StreamMediaType method, which fills in an AM_MEDIA_TYPE structure. The Media Detector converts all video streams into uncompressed format, with a VIDEOINFOHEADER format block.

long width = 0, height = 0;
AM_MEDIA_TYPE mt;
hr = pDet->get_StreamMediaType(&mt);
if (mt.formattype == FORMAT_VideoInfo)
{
    VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)(mt.pbFormat);
    width = pVih->bmiHeader.biWidth;
    height = pVih->bmiHeader.biHeight;

    // We want the absolute height, and don't care about up-down orientation.
    if (height < 0) height *= -1;
}
else {
    return VFW_E_INVALIDMEDIATYPE; // This should not happen, in theory.
}
FreeMediaType(mt);

The get_StreamMediaType method allocates the format block, which the caller must free. This example uses the FreeMediaType function from the base class library.

Now you are ready to get the poster frame. First call the IMediaDet::GetBitmapBits method with a NULL pointer for the buffer:

long lSize;
hr = pDet->GetBitmapBits(0, &lSize, NULL, width, height);

This call returns the required buffer size in the lSize parameter. The first parameter specifies the stream time to seek to; this example uses time zero. For the width and height, this example uses the native video dimensions obtained earlier. If you specify other values, the Media Detector will stretch the bitmap to match.

If the method succeeds, allocate the buffer and call GetBitmapBits again:

if (SUCCEEDED(hr))
{
    char *pBuffer = new char[lSize];
    if (!pBuffer) return E_OUTOFMEMORY;
    hr = pDet->GetBitmapBits(0, NULL, pBuffer, width, height);
    if (FAILED(hr))
        delete [] pBuffer;
}

Here is the complete function, with somewhat better error handling.

HRESULT GetBitmap(LPTSTR pszFileName, BITMAPINFOHEADER** ppbmih)
{
    HRESULT hr;
    CComPtr<IMediaDet> pDet;
    hr = pDet.CoCreateInstance(__uuidof(MediaDet));
    if (FAILED(hr)) return hr;

    // Convert the file name to a BSTR.
    CComBSTR bstrFilename(pszFileName);
    hr = pDet->put_Filename(bstrFilename);
    if (FAILED(hr)) return hr;

    long lStreams;
    bool bFound = false;
    hr = pDet->get_OutputStreams(&lStreams);
    if (FAILED(hr)) return hr;

    for (long i = 0; i < lStreams; i++)
    {
        GUID major_type;
        hr = pDet->put_CurrentStream(i);
        if (SUCCEEDED(hr))
        {
            hr = pDet->get_StreamType(&major_type);
        }
        if (FAILED(hr)) break;

        if (major_type == MEDIATYPE_Video)
        {
            bFound = true;
            break;
        }
    }
    if (!bFound) return VFW_E_INVALIDMEDIATYPE;

    long width = 0, height = 0;
    AM_MEDIA_TYPE mt;
    hr = pDet->get_StreamMediaType(&mt);
    if (SUCCEEDED(hr))
    {
        if ((mt.formattype == FORMAT_VideoInfo) &&
            (mt.cbFormat >= sizeof(VIDEOINFOHEADER)))
        {
            VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*)(mt.pbFormat);
            width = pVih->bmiHeader.biWidth;
            height = pVih->bmiHeader.biHeight;

            // We want the absolute height, don't care about orientation.
            if (height < 0) height *= -1;
        }
        else
        {
            hr = VFW_E_INVALIDMEDIATYPE; // Should not happen, in theory.
        }
        FreeMediaType(mt);
    }
    if (FAILED(hr)) return hr;

    // Find the required buffer size.
    long size;
    hr = pDet->GetBitmapBits(0, &size, NULL, width, height);
    if (SUCCEEDED(hr))
    {
        char *pBuffer = new char[size];
        if (!pBuffer) return E_OUTOFMEMORY;
        try {
            hr = pDet->GetBitmapBits(0, NULL, pBuffer, width, height);
            if (SUCCEEDED(hr))
            {
                // Delete the old image, if any.
                if (*ppbmih) delete[] (*ppbmih);
                (*ppbmih) = (BITMAPINFOHEADER*)pBuffer;
            }
            else
            {
                delete [] pBuffer;
            }
        }
        catch (...) {
            delete [] pBuffer;
            return E_OUTOFMEMORY;
        }
    }
    return hr;
}


Step 4: Draw the Bitmap on the Client Area

The final step is to draw the bitmap onto the client area of the application window, using the Windows SetDIBitsToDevice function. This example simply paints the bitmap in the upper-left corner of the client area, without regard to the window size:

case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        if (pbmi)
        {
            int result = SetDIBitsToDevice(hdc, 0, 0,
                pbmi->biWidth,
                pbmi->biHeight,
                0, 0, 0,
                pbmi->biHeight,
                pBuffer,
                reinterpret_cast<BITMAPINFO*>(pbmi),
                DIB_RGB_COLORS);
        }
        EndPaint(hwnd, &ps);
    }
    break;


Using the Sample Grabber

The Sample Grabber filter is a transform filter that can be used to grab media samples from a stream as they pass through the filter graph.

If you simply want to grab a bitmap from a video file, it is easier to use the Media Detector (MediaDet) object. See Grabbing a Poster Frame for details. The Sample Grabber is more flexible, however, because it works with nearly any media type (see ISampleGrabber::SetMediaType for the few exceptions), and offers more control to the application.

Add the Sample Grabber to the Filter Graph

Start by creating an instance of the Sample Grabber filter and adding it to the filter graph:

// Create the Sample Grabber.
IBaseFilter *pGrabberF = NULL;
hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
    IID_IBaseFilter, (void**)&pGrabberF);
if (FAILED(hr))
{
    // Return an error.
}
hr = pGraph->AddFilter(pGrabberF, L"Sample Grabber");
if (FAILED(hr)
{
    // Return an error.
}

Query the Sample Grabber for the ISampleGrabber interface.

ISampleGrabber *pGrabber;
pGrabberF->QueryInterface(IID_ISampleGrabber, (void**)&pGrabber);

Set the Media Type

When you first create the Sample Grabber, it has no preferred media type. This means you can connect to almost any filter in the graph, but you would have no control over the type of data that it received. Before building the rest of the graph, therefore, you must set a media type for the Sample Grabber, by calling the ISampleGrabber::SetMediaType method.

When the Sample Grabber connects, it will compare this media type against the media type offered by the other filter. The only fields that it checks are the major type, subtype, and format type. For any of these, the value GUID_NULL means "accept any value." Most of the time, you will want to set the major type and subtype. For example, the following code specifies uncompressed 24-bit RGB video:

AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video;
mt.subtype = MEDIASUBTYPE_RGB24;
hr = pGrabber->SetMediaType(&mt);

The next example sets the media type based on the bit depth of the display:

// Find the current bit depth.
HDC hdc = GetDC(NULL);
int iBitDepth = GetDeviceCaps(hdc, BITSPIXEL);
ReleaseDC(NULL, hdc);

// Set the media type.
mt.majortype = MEDIATYPE_Video;
switch (iBitDepth)
{
case 8:
    mt.subtype = MEDIASUBTYPE_RGB8;
    break;
case 16:
    mt.subtype = MEDIASUBTYPE_RGB555;
    break;
case 24:
    mt.subtype = MEDIASUBTYPE_RGB24;
    break;
case 32:
    mt.subtype = MEDIASUBTYPE_RGB32;
    break;
default:
    return E_FAIL;
}
hr = pGrabber->SetMediaType(&mt);

Build the Filter Graph

Now you can build the rest of the filter graph. Because the Sample Grabber will only connect using the media type you have specified, this lets you take advantage of the Filter Graph Manager's Intelligent Connect mechanisms when you build the graph.

For example, if you specified uncompressed video, you can connect a source filter to the Sample Grabber, and the Filter Graph Manager will automatically add the file parser and the decoder. The following example uses the ConnectFilters helper function, which is listed in Connect Two Filters:

IBaseFilter *pSrc;
hr = pGraph->AddSourceFilter(wszFileName, L"Source", &pSrc);
if (FAILED(hr))
{
    // Return an error code.
}
hr = ConnectFilters(pGraph, pSrc, pGrabberF);

The Sample Grabber is a transform filter, so the output pin must be connected to another filter. Often, you may simply want to discard the samples after you are done with them. In that case, connect the Sample Grabber to the Null Renderer Filter, which discards the data that it receives.

Be aware that placing the Sample Grabber between a video decoder and the video renderer can significantly hurt rendering performance. The Sample Grabber is a trans-in-place filter, which means the output buffer is the same as the input buffer. For video rendering, the output buffer is likely to be located on the graphics card, where read operations are much slower, compared with read operations in main memory.

Run the Graph

The Sample Grabber operates in one of two modes:

  • Buffering mode makes a copy of each sample before delivering the sample downstream.
  • Callback mode invokes an application-defined callback function on each sample.

This article describes buffering mode. (Before using callback mode, be aware that the callback function must be quite limited. Otherwise, it can drastically reduce performance or even cause deadlocks. For more information, see ISampleGrabber::SetCallback.) To activate buffering mode, call the ISampleGrabber::SetBufferSamples method with the value TRUE.

Optionally, call the ISampleGrabber::SetOneShot method with the value TRUE. This causes the Sample Grabber to stop the graph after it receives the first media sample, which is useful if you want to grab a single frame from the stream. Seek to the desired time, run the graph, and wait for the EC_COMPLETE event. Note that the level of frame accuracy depends on the source. For example, seeking an MPEG file is often not frame accurate.

// Set one-shot mode and buffering.
hr = pGrabber->SetOneShot(TRUE);
hr = pGrabber->SetBufferSamples(TRUE);

pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.

To run the graph as fast as possible, turn of the graph clock as described in Setting the Graph Clock.

Grab the Sample

In buffering mode, the Sample Grabber stores a copy of every sample. The ISampleGrabber::GetCurrentBuffer method copies the buffer into a caller-allocated array. To determine the size of the array that is needed, first call GetCurrentBuffer with a NULL pointer for the array address:

// Find the required buffer size.
long cbBuffer = 0;
hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL);

Allocate the array and call the method a second time to copy the buffer:

char *pBuffer = new char[cbBuffer];
if (!pBuffer)
{
    // Out of memory. Return an error code.
}
hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer);

The ISampleGrabber::GetConnectedMediaType method returns the format of the buffer:

AM_MEDIA_TYPE mt;
hr = pGrabber->GetConnectedMediaType(&mt);
if (FAILED(hr))
{
    // Return error code.
}
// Examine the format block.
VIDEOINFOHEADER *pVih;
if ((mt.formattype == FORMAT_VideoInfo) &&
    (mt.cbFormat >= sizeof(VIDEOINFOHEADER)) &&
    (mt.pbFormat != NULL) )
{
    pVih = (VIDEOINFOHEADER*)mt.pbFormat;
}
else
{
    // Wrong format. Free the format block and return an error.
    FreeMediaType(mt);
    return VFW_E_INVALIDMEDIATYPE;
}
// You can use the media type to access the BITMAPINFOHEADRE information.
// For example, the following code draws the bitmap using GDI:
SetDIBitsToDevice(
    hdc, 0, 0,
    pVih->bmiHeader.biWidth,
    pVih->bmiHeader.biHeight,
    0, 0,
    0,
    pVih->bmiHeader.biHeight,
    pBuffer,
    (BITMAPINFO*)&pVih->bmiHeader,
    DIB_RGB_COLORS
);

// Free the format block when you are done:
FreeMediaType(mt);


Recompressing an AVI File

This article describes how to recompress an Audio-Video Interleaved (AVI) file using DirectShow. The article focuses on video compression, but the same principles apply for audio compression.

This article contains the following sections:

  • Choosing a Compression Filter
  • Setting Video Compression Properties
  • Building the Recompression Graph
  • Writing the File


Choosing a Compression Filter

Several types of software components can perform video or audio compression, such as:

  • Native DirectShow filters
  • Video Compression Manager (VCM) codecs
  • Audio Compression Manager (ACM) codecs
  • DirectX Media Objects (DMOs)

In DirectShow, VCM codecs are wrapped by the AVI Compressor Filter, and ACM codecs are wrapped by the ACM Wrapper Filter. DMOs are wrapped by the DMO Wrapper Filter. The system device enumerator provides a consistent way to enumerate and create any of these compressor types, without worrying about the underlying model.

For details about the system device enumerator, see Using the System Device Enumerator. Briefly, all DirectShow filters are classified by category, and each category is identified by a GUID. For video compressors, the category GUID is CLSID_VideoCompressorCategory. For audio compressors, it is CLSID_AudioCompressorCategory. To enumerate a particular category, the system device enumerator creates an enumerator object that supports the IEnumMoniker interface. The application uses this interface to retrieve device monikers, where each device moniker represents an instance of a DirectShow filter. You can use the moniker to create the filter, or to get the device's friendly name without creating the filter.

To enumerate the video or audio compressors available on the user's system, do the following:

  1. Call CoCreateInstance to create the system device enumerator, which has a class ID of CLSID_SystemDeviceEnum.
  2. Call ICreateDevEnum::CreateClassEnumerator with the filter category GUID. The method returns an IEnumMoniker interface pointer.
  3. Use the IEnumMoniker::Next method to enumerate the device monikers. This method returns an IMoniker interface, which represents the moniker.

To get the friendly name from a moniker, do the following:

  1. Call the IMoniker::BindToStorage method. This method returns an IPropertyBag interface pointer.
  2. Use the IPropertyBag::Read method to read the FriendlyName property.

Typically, an application would display a list of compressors, so that the user could choose one. For example, the following code populates a list box with the names of the available video compressors.

void OnInitDialog(HWND hDlg)
{
    HRESULT hr;
    ICreateDevEnum *pSysDevEnum = NULL;
    IEnumMoniker *pEnum = NULL;
    IMoniker *pMoniker = NULL;

    hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
        CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
        (void**)&pSysDevEnum);
    if (FAILED(hr))
    {
        // Handle the error.
    }

    hr = pSysDevEnum->CreateClassEnumerator(
             CLSID_VideoCompressorCategory, &pEnum, 0);
    if (hr == S_OK)  // S_FALSE means nothing in this category.
    {
        while (S_OK == pEnum->Next(1, &pMoniker, NULL))
        {
            IPropertyBag *pPropBag = NULL;
            pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
                (void **)&pPropBag);
            VARIANT var;
            VariantInit(&var);
            hr = pPropBag->Read(L"FriendlyName", &var, 0);
            if (SUCCEEDED(hr))
            {
                LRESULT iSel = AddString(GetDlgItem(hDlg,
                    IDC_CODEC_LIST), var.bstrVal);
            }
            VariantClear(&var);
            pPropBag->Release();
            pMoniker->Release();
        }
    }

    SendDlgItemMessage(hDlg, IDC_CODEC_LIST,
                       LB_SETCURSEL, 0, 0);
    pSysDevEnum->Release();
    pEnum->Release();
}

To create a filter instance from the moniker, call the IMoniker::BindToObject method. The method returns an IBaseFilter pointer.

IBaseFilter *pFilter = NULL;
hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter,
                                       (void**)&pFilter);
if (SUCCEEDED(hr))
{
    // Use the filter.
    // Remember to release the IBaseFilter interface.
}

For VCM codecs, each moniker represents one particular codec, even though all of the codecs are wrapped by the same AVI Compression filter. Calling BindToObject creates an instance of this filter, initialized for that codec. For this reason, you cannot call CoCreateInstance directly on the AVI Compression filter. You must go through the system device enumerator.


Setting Video Compression Properties

Video compression filters can support the IAMVideoCompression interface on their output pins. Use this interface to set compression properties, such as the key frame rate, the number of predicted (P) frames per key frame, and the relative compression quality.

First, call the IBaseFilter::EnumPins method to find the filter's output pin, and query the pin for the interface. Some filters may not support the interface at all. Others may expose the interface but not support every compression property. To determine which properties are supported, call IAMVideoCompression::GetInfo. This method returns several pieces of information:

  • A set of capabilities flags
  • A descriptive string and version-number string
  • Default values for key frame rate, P frame rate, and quality (when supported)

The method has the following syntax:

hr = pCompress->GetInfo(pszVersion, &cbVersion, pszDesc, &cbDesc,
         &lKeyFrame, &lPFrame, &dblQuality, &lCap);

The pszVersion and pszDesc parameters are wide-character buffers that receive the version string and description string. The cbVersion and cbDesc parameters receive the required buffer sizes in bytes (not characters). The lKeyFrame, lPFrame, and dblQuality parameters receive the default values for the key frame rate, P frame rate, and quality. Quality is expressed as a floating-point number from 0.0 to 1.0. The lCap parameter receives a bitwise OR of the capabilities flags, which are defined by the CompressionCaps enumerated type.

Any of these parameters can be NULL, in which case the method ignores that parameter. For example, to allocate buffers for the version and description strings, first call the method with NULL in the first and third parameters. Use the returned values for cbVersion and cbDesc to allocate the buffers and then call the method again:

int cbVersion, cbDesc; // Size in bytes, not characters!
hr = pCompress->GetInfo(0, &cbVersion, 0, &cbDesc, 0, 0, 0, 0);
if (SUCCEEDED(hr))
{
    WCHAR *pszVersion = new WCHAR[cbVersion/2]; // Wide character = 2 bytes
    WCHAR *pszDesc = new WCHAR[cbDesc/2];
    hr = pCompress->GetInfo(pszVersion, 0, pszDesc, 0, 0, 0, 0, 0);
}

The value of lCap indicates which of the other IAMVideoCompression methods the filter supports. For example, if lCap contains the CompressionCaps_CanKeyFrame flag, you can call IAMVideoCompression::get_KeyFrameRate to get the key frame rate and IAMVideoCompression::put_KeyFrameRate to set the key frame rate. A negative value indicates that the filter will use the default value, as obtained from IAMVideoCompression::GetInfo. For example:

if (lCap & CompressionCaps_CanKeyFrame)
{
    hr = pCompress->get_KeyFrameRate(&lKeyFrame);
    if (FAILED(hr) || lKeyFrame < 0)
    {
        lKeyFrame = lDefaultKeyFrame; // From GetInfo.
    }
}

The following code example tries to find the IAMVideoCompression interface on the output pin. If it succeeds, it retrieves the default and actual values for the compression properties:

HRESULT hr = E_FAIL;
IEnumPins *pEnum = NULL;
IPin *pPin = NULL;
IAMVideoCompression *pCompress = NULL;

// Find the pin that supports IAMVideoCompression (if any).
pFilter->EnumPins(&pEnum);
while (S_OK == pEnum->Next(1, &pPin, NULL))
{
    hr = pPin->QueryInterface(IID_IAMVideoCompression, (void**)&pCompress);
    pPin->Release();
    if (SUCCEEDED(hr)) // Found the interface.
    {
        break;
    }
}
if (SUCCEEDED(hr))
{
    long lCap;                     // Capability flags
    long lKeyFrame, lPFrame;       // Real values
    double m_Quality;
    long lKeyFrameDef, lPFrameDef; // Default values
    double QualityDef;

    // Get default values and capabilities.
    hr = pCompress->GetInfo(0, 0, 0, 0, &KeyFrameDef, &lPFrameDef,
             &QualityDef, &lCap);
    if (SUCCEEDED(hr))
    {
        // Get actual values where possible.
        if (lCap & CompressionCaps_CanKeyFrame)
        {
            hr = pCompress->get_KeyFrameRate(&lKeyFrame);
            if (FAILED(hr) || lKeyFrame < 0)
                lKeyFrame = lKeyFrameDef;
        }
        if (lCap & CompressionCaps_CanBFrame)
        {
            hr = pCompress->get_PFramesPerKeyFrame(&lPFrame);
            if (FAILED(hr) || lPFrame < 0)
                lPFrame = lPFrameDef;
        }
        if (lCap & CompressionCaps_CanQuality)
        {
            hr = pCompress->get_Quality(&Quality);
            if (FAILED(hr) || Quality < 0)
                Quality = QualityDef;
        }
    }
}

Note If you are using the ICaptureGraphBuilder2 interface to build your graph, you can obtain the IAMVideoCompression interface by calling ICaptureGraphBuilder2::FindInterface, instead of using IBaseFilter::EnumPins. The FindInterface method is a helper method that searches filters and pins in the graph for a specified interface.


Building the Recompression Graph

A typical filter graph for AVI file recompression looks like the following:

AVI Recompression Graph

The AVI Splitter Filter pulls data from the File Source (Async) Filter and parses it into video and audio streams. The video decompressor decodes the compressed video, where it is recompressed by the video compressor. The choice of decompressors depends on the source file; it will be handled automatically by Intelligent Connect. The application must choose the compressor, typically by presenting a list to the user. (See Choosing a Compression Filter.)

The compressed video then goes to the AVI Mux Filter. The audio stream in this example is not compressed, so it goes directly from the AVI Splitter to the AVI Mux. The AVI Mux interleaves the two streams, and the File Writer Filter writes the output to disk. Note that the AVI Mux is required even if the original file does not have an audio stream.

The easiest way to build this filter graph is to use the Capture Graph Builder, which is a DirectShow component for building capture graphs and other custom filter graphs.

Start by calling CoCreateInstance to create the Capture Graph Builder:

ICaptureGraphBuilder2 *pBuild = NULL;
hr = CoCreateInstance(CLSID_CaptureGraphBuilder2,
                        NULL, CLSCTX_INPROC_SERVER,
    IID_ICaptureGraphBuilder2, (void **)&pBuild);

Then use the Capture Graph Builder to build the filter graph:

  1. Build the rendering section of the graph, which includes the AVI Mux filter and the File Writer.
  2. Add the source filter and the compression filter to the graph.
  3. Connect the source filter to the MUX filter. The capture graph builder inserts whatever splitter and decoder filters are needed to parse the source file. It can also route the video and audio streams through compression filters.

The following sections explain each of these steps.

Build the Rendering Section

To build the rendering section of the graph, call the ICaptureGraphBuilder2::SetOutputFileName method. This method takes input parameters that specify the media subtype for the output and the name of the output file. It returns pointers to the MUX filter and the file writer. The MUX filter is needed for the next stage of graph building. The pointer to the file writer is not needed for this example, so that parameter can be NULL:

IBaseFilter *pMux = NULL;
hr = pBuild->SetOutputFileName(
        &MEDIASUBTYPE_Avi, // File type.
        wszOutputFile,     // File name, as a wide-character string.
        &pMux,             // Receives a pointer to the multiplexer.
        NULL);             // Receives a pointer to the file writer.

When the method returns, the MUX filter has an outstanding reference count, so be sure to release the pointer later.

The following diagram shows the filter graph at this point.

Rendering Section of the Filter Graph

The MUX filter exposes two interfaces for controlling the AVI format:

  • IConfigInterleaving Interface: Sets the interleaving mode.
  • IConfigAviMux Interface: Sets the master stream and the AVI compatibility index.

Add the Source and Compression Filters

The next step is to add the source and compression filters to the filter graph. The Capture Graph Builder automatically creates an instance of the Filter Graph Manager when you call SetOutputFileName. Get a pointer to it by calling the ICaptureGraphBuilder2::GetFiltergraph method:

IGraphBuilder *pGraph = NULL;
hr = pBuild->GetFiltergraph(&pGraph);

Now call the IGraphBuilder::AddSourceFilter method to add the Async File Source filter, and the IFilterGraph::AddFilter method to add the video compressor:

IBaseFilter *pSrc = NULL;
hr = pGraph->AddSourceFilter(wszInputFile, L"Source Filter", &pSrc);
hr = pGraph->AddFilter(pVComp, L"Compressor");

At this point, the source filter and the compression filter are not connected to anything else in the graph, as shown in the following illustration:

Filter Graph with Source and Compression Filters

Connect the Source to the Mux

The final step is to connect the source filter to the AVI Mux filter, through the video compressor. Use the ICaptureGraphBuilder2::RenderStream method, which connects an output pin on the source filter to a specified sink filter, optionally through a compression filter.

The first two parameters specify which of the source filter's pins to connect, by designating a pin category and a media type. The Async File Source filter has only one output pin, so these parameters should be NULL. The next three parameters specify the source filter, the compression filter (if any), and the Mux filter.

The following code example renders the video stream through the video compressor:

hr = pBuild->RenderStream(
        NULL,       // Output pin category
        NULL,       // Media type
        pSrc,       // Source filter
        pVComp,     // Compression filter
        pMux);      // Sink filter (the AVI Mux)

The following diagram shows the filter graph so far.

Rendered Video Stream

Assuming that the source file has an audio stream, the AVI Splitter filter has created an output pin for the audio. To connect this pin, call RenderStream again:

hr = pBuild->RenderStream(NULL, NULL, pSrc, NULL, pMux);

Here, no compression filter is specified. The source filter's output pin is already connected, so the RenderStream method searches for an unconnected output pin on the splitter filter. It finds the audio pin and connects it directly to the MUX filter. If the source file does not have an audio stream, the second call to RenderStream will fail. This is expected behavior. The graph is complete after the first call to RenderStream, so the failure in the second call is harmless.

In this example, the order of the two RenderStream calls is important. Because the second call does not specify a compressor, it will connect any unconnected pin from the AVI Splitter. If you make this call before the other one, it might connect the video stream to the AVI Mux, without your video compressor. Therefore, the more specific call (with the compression filter) must happen first.

The previous discussion has assumed that the source file is an AVI file. However, this technique also works with other file types, such as MPEG files. The resulting filter graph will be somewhat different.


Writing the File

To write the file, simply run the filter graph by calling the IMediaControl::Run method. Wait for playback to complete and explicitly stop the graph by calling IMediaControl::Stop; otherwise the file is not written correctly.

To display the progress of the file-writing operation, query the Mux filter for the IMediaSeeking interface. Call the IMediaSeeking::GetDuration method to retrieve the duration of the file. Periodically while the graph is running, call the IMediaSeeking::GetCurrentPosition method to retrieve the graph's current position in the stream. Current position divided by duration gives the percentage complete.

Note An application usually queries the Filter Graph Manager for IMediaSeeking, but file writing is an exception to this rule. The Filter Graph Manager calculates the current position from the starting position and how long the graph has been running, which is accurate for file playback but not for file writing. Therefore, to get an accurate result, you should retrieve the position from the MUX filter.

The following code gets the duration of the file, starts a timer to update the application UI, and runs the filter graph. (Error checking is omitted for clarity.)

IMediaSeeking *pSeek = NULL;
IMediaEventEx *pEvent = NULL;
IMediaControl *pControl = NULL;
REFERENCE_TIME rtTotal;

// Query for interfaces. Remember to release them later.
hr = pMux->QueryInterface(IID_IMediaSeeking, (void**)&pSeek);
hr = pGraph->QueryInterface(IID_IMediaEventEx, (void**)&pEvent);
hr = pGraph->QueryInterface(IID_IMediaControl, (void**)&pControl);

// Error checking is omitted for clarity.

// Set the DirectShow event notification window.
hr = pEvent->SetNotifyWindow((OAHWND)hwnd, WM_GRAPHNOTIFY, 0);

// Set the range of the progress bar to the file length (in seconds).
hr = pSeek->GetDuration(&rtTotal);
SendDlgItemMessage(hwnd, IDC_PROGRESS1, PBM_SETRANGE, 0,
   MAKELPARAM(0, rtTotal / 10000000));
// Start the timer.
UINT_PTR res = SetTimer(hwnd, nIDEvent, 100, NULL);
// Run the graph.
pControl->Run();

When the application receives a timer event, it can update the UI with the current position:

void OnTimer(HWND hDlg, IMediaSeeking *pSeek)
{
    REFERENCE_TIME rtNow;
    HRESULT hr = pSeek->GetCurrentPosition(&rtNow);
    if (SUCCEEDED(hr))
    {
        SendDlgItemMessage(hDlg, IDC_PROGRESS1, PBM_SETPOS, rtNow/10000000, 0);
    }
}

When the application receives a DirectShow completion event, it should stop the graph, as shown in the following code:

// Application window procedure
LRESULT CALLBACK WndProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    /*  ...  */
    case WM_GRAPHNOTIFY:
        DoHandleEvent();
        break;
    /*  ...  */
    }
}

void DoHandleEvent()
{
    long evCode, param1, param2;
    bool bComplete = false;
    if (!pEvent) return;

    // Get all the events, and see we're done.
    while (SUCCEEDED(pEvent->GetEvent(&evCode, &param1, &param2, 0))
    {
        pEvent->FreeEventParams(evCode, param1, param2);
        switch(evCode)
        {
            case EC_USERABORT:
            case EC_ERRORABORT:
            case EC_COMPLETE:
                bComplete = true;
                break;
        }
    }
    if (bComplete)
    {
        pControl->Stop(); // Important! You must stop the graph!

        // Turn off event notification.
        pEvent->SetNotifyWindow(NULL, 0, 0);
        pEvent->Release();
        pEvent = NULL;
        // Reset the progress bar to zero and get rid of the timer.
        SendDlgItemMessage(IDC_PROGRESS1, PBM_SETPOS, 0, 0);
        KillTimer(hwnd, nIDEvent);
    }
}


DirectShow Samples

The Microsoft® DirectShow® SDK samples are divided into categories according to functionality:

  • Base Classes
  • BDA Sample Application
  • Capture Samples
  • DMO Samples
  • DVD Samples
  • Filter Samples
  • Miscellaneous DirectShow Samples
  • Player Application Samples
  • Video Control Samples
  • Video Editing Samples
  • Video Mixing Renderer Samples

Building the Samples

There are multiple ways to build the DirrectShow SDK samples. Project files are included for both Visual C++ 6.0 and Visual Studio.NET. To build with Visual C++ 6.0, use the workspace files (.dsw). To build with Visual Studio.NET, use the solution files (.sln). All of the samples can be built for ANSI or Unicode.

Use the main workspace to build all of the samples

The easiest way to build all of the samples is to open DShow.dsw (or DShow.sln), which is located in the DirectShow samples root directory. This workspace includes references to each of the project files for the individual samples. You can batch-build all or some of the projects from this workspace.

Some of the projects included in the SDK build support libraries that are used by other projects. For example, the GargleDMO sample depends on the ControlBase and MedParamBase projects. If you build GargleDMO, Visual C++ will automatically build the and link these dependencies.

Use the workspace for a category of samples

Each of the subdirectories within the main DirectShow samples directory has a workspace (and solution) that builds all of the samples in that subdirectory. For example, if you want to build all of the capture samples, you can use the Capture.dsw workspace (or the Capture.sln solution) in the Capture directory.

Build individual projects

Each sample includes a workspace file and a solution file to build that sample individually. Many of samples link to the base class library, so you will need to build that first. See Base Classes.

See Also

  • Setting Up the Build Environment


Base Classes

Description

The Microsoft DirectShow base classes are a set of C++ classes and utility functions that you can use to implement DirectShow filters. For complete documentation of the base classes, see DirectShow Base Classes.

Path

Source: (SDK root)\Samples\C++\DirectShow\BaseClasses


BDA Sample Application

Description

Demonstrates how to construct a filter graph in DirectX 9.0 based on digital TV tuner cards that support the new Microsoft® Broadcast Driver Architecture (BDA). The sample also shows how to perform tuning based on the new Microsoft Tuning Model. The sample is discussed in more detail in the article Writing Digital TV Applications with DirectX. This sample does not use the Video Control or other TV components available on Windows® XP only.

Note To build this sample you must have strmbasd.lib or strmbase.lib present on your system. This library is created when you build the DirectShow base classes. For more information, see Using the DirectShow Base Classes.

Path

Source: (SDK root)\Samples\C++\DirectShow\BDA\BDASample

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Bdasample.exe


Capture Samples

The Microsoft® DirectShow® SDK includes the following sample capture applications.

C++ Applications

  • AmCap Sample
  • AudioCap Sample
  • CaptureTex Sample
  • CaptureTex9
  • DVApp Sample
  • PlayCap Sample
  • PlayCapMoniker Sample


AmCap Sample

Description

Video capture application.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\AMCap

Executable: (SDK root)\Samples\C++\DirectShow\Bin\AMCap.exe

User's Guide

This sample application demonstrates the following tasks related to audio and video capture:

  • Capture to a file
  • Live preview
  • Allocation of the capture file
  • Display of device property pages
  • Device enumeration
  • Stream control

Beginning in DirectX9, AMCap supports MPEG-2 program stream input, for example from analog TV Tuners that stream MPEG-2 content. A third-party DirectShow-compatible MPEG-2 decoder is still required to decode the streams.

See Also

  • Video Capture


AudioCap Sample

Description

Audio capture application.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\AudioCap

Executable: (SDK root)\Samples\C++\DirectShow\Bin\AudioCap.exe

User's Guide

This sample application demonstrates audio capture using DirectShow. The application enables the user to perform the following tasks:

  • Capture audio to a file.
  • Select the audio capture device.
  • View properties on the audio capture device.
  • Select the sample rate and number of channels (stereo or mono).

See Also

  • Audio Capture


CaptureTex Sample

Description

The CaptureTex samples shows how to render live video from a camera to a Direct3D surface. This example combines features from the Texture3D and PlayCap samples.

When the application starts, it enumerates the video capture devices on the system and loads the first device found. It then creates a renderer object to render the incoming video stream onto a Direct3D surface.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\CaptureTex

Executable: (SDK root)\Samples\C++\DirectShow\Bin\CaptureTex.exe

See Also

  • Video Capture


CaptureTex9 Sample

This sample combines features of the Texture3D9 and PlayCap samples to render live incoming video onto a waving flag.

CaptureTex9 will enumerate any existing video capture devices attached to the system and will load the first device found. A DirectShow renderer object will be created to render the incoming video stream onto a Direct3D9 surface, taking advantage of new Direct3D9 features.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\CaptureTex9

Executable: (SDK root)\Samples\C++\DirectShow\Bin\CaptureTex9.exe


DVApp Sample

Description

Digital Video (DV) capture application.

This sample demonstrates how to build various types of filter graphs for controlling DV camcorders. It also shows how to perform capture, preview, transmit, and device control with a DV camcorder.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\DVApp

Executable: (SDK root)\Samples\C++\DirectShow\Bin\DVApp.exe

User's Guide

The DVApp application supports the following modes:

  • Preview: Renders DV from the camcorder to a video window.
  • DV to type-1 file: Captures DV data from the camcorder to a type-1 DV file.
  • Type-1 file to DV: Transmits data from a type-1 DV file to the camcorder.
  • DV to type-2 file: Captures DV data from the camcorder to a type-2 DV file.
  • Type-2 file to DV: Transmits data from a type-2 DV file to the camcorder.

The capture and transmit modes also perform preview. Each of those modes has a No Preview option as well, which disables preview. Capturing without preview is more efficient and can reduce the number of dropped frames.

The application starts in preview mode. To select another mode, choose a mode from the Graph Mode menu. For each mode, DVApp builds a filter graph that supports the functionality of that mode. To save the graph as a GraphEdit (.grf) file, select Save Graph to File from the File menu. Quit DVApp before opening the file in GraphEdit.

To capture to a file:

  1. From the File menu, choose Set Output File and enter a file name.
  2. From the Graph Mode menu, select a DV to File mode (type 1 or type 2, with or without preview).
  3. Click Record.
  4. If the camcorder is in VTR mode, click Play.
  5. To stop capturing, click Stop.

To transmit from a file to the camcorder:

  1. From the File menu, click Set Input File and select a DV file. The file must match the selected mode (type 1 or type 2).
  2. From the Graph Mode menu, select a File to DV mode (type 1 or type 2, with or without preview).
  3. Click Play.
  4. To record the data to tape, click Record.
  5. To stop transmitting, click Stop.

If the camcorder is in VTR mode, the user can control the transport mechanism through the application's VCR-style buttons. To seek the tape, enter the target timecode and click the seek button.

To limit how much data the application captures, choose Capture Size from the File menu.

To check the tape format (NTSC or PAL), choose Check Tape from the Options menu.

To change the size of the preview window, choose Change Decode Size from the Options menu.

Programming Notes

The main purpose of this application is to show how to build various DV capture and transmit graphs.

Device Arrival and Removal

The application handles device arrival and removal, using two different techniques. For device arrival, the application's message loop responds to WM_DEVICECHANGE messages. For device removal, the application responds to EC_DEVICE_LOST events from the filter graph manager. Either approach works, although the EC_DEVICE_LOST event depends on the existence of the device in the filter graph.

The application only handles one device at a time. If the current device is removed, the application looks for another DV device on the system.

On some DV camcorders, the user must shut off the device when switching it between camera mode and VTR mode, which triggers a device-lost message. The application responds by enabling or disabling the appropriate menu commands. However, if the user toggles rapidly between modes, the camcorder might not generate a device-lost message. You can force the menus to update by choosing Refresh Mode from the Options menu. Some DV camcorders can toggle modes without shutting off, but send a device-lost message only when they switch to VTR mode.

Note Microsoft Windows NT 4.0 and earlier do not support the data types used for device arrival. In order to compile the application for these platforms, the data types are conditionally included if WINVER is less than 0x500. However, the application does not support device detection on those platforms.

Device Control

The functionality of the application's Play and Record button depends on the current mode:

  • Preview: The filter graph runs automatically. The Play button starts the transport.
  • Capture to file: The Record button runs the graph, and the Play button starts the transport.
  • Transmit to device: The Play button runs the graph, and the Record button starts the transport.

The sample application does not perform frame-accurate capture. At various points, the application calls the Sleep function to wait for the device to respond. Newer DV camcorders send a notification when the state of the device changes. Older devices might not support notification; for the purposes of a sample, calling Sleep is a simpler solution.

See Also

  • Digital Video in DirectShow
  • Controlling a DV Camcorder


PlayCap Sample

Description

Simple capture application.

This application creates a preview window for the first video capture device that it locates on the user's system (if any). It demonstrates a simple example of using the ICaptureGraphBuilder2 and ICreateDevEnum interfaces to build a capture graph.

For a sample capture application that supports more features, see AmCap Sample.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\PlayCap

Executable: (SDK root)\Samples\C++\DirectShow\Bin\PlayCap.exe

See Also

  • Video Capture


PlayCapMoniker Sample

Description

The PlayCapMoniker sample demonstrates how to build a video capture device using a device moniker. The application is a simple video capture device previewer. Unlike the AmCap Sample, it does not capture data to a file. Instead, it searches for the first available video capture device that is registered in the system, connects to it, and displays the video data in a small window.

This sample differs from the PlayCap Sample because PlayCap builds the capture graph using the ICaptureGraphBuilder2 interface, whereas this sample finds the moniker of the capture device and uses the IFilterGraph2::AddSourceFilterForMoniker method to begin the graph-building process.

Path

Source: (SDK root)\Samples\C++\DirectShow\Capture\PlayCapMoniker


DMO Samples

The Microsoft® DirectShow® SDK includes the following Microsoft® DirectX® Media Object (DMO) samples:

  • DMO Demo Sample
  • DMOEnum Sample
  • DMO Sample
  • Gargle DMO Sample

See Also

  • PlayDMO Sample


DMO Demo Sample

Description

This sample application demonstrates how to use Microsoft® DirectX® Media Objects (DMO). It streams audio data from a WAV file through an audio effect DMO to a Microsoft® DirectSound® buffer.

Path

Source: (SDK root)\Samples\C++\DirectShow\DMO\DMODemo

Executable: (SDK root)\Samples\C++\DirectShow\Bin\DMODemo.exe

User's Guide

Click the Sound File button to load a sound file. Use the drop-down combo box to select an audio effect DMO. Click the Play button to hear the sound file played with the audio effect.


DMOEnum Sample

Description

This sample application enumerates all of the Microsoft® DirectX® Media Objects (DMOs) registered in the user's system, and displays information about them.

Path

Source: (SDK root)\Samples\C++\DirectShow\Misc\DMOEnum

Executable: (SDK root)\Samples\C++\DirectShow\Bin\DMOEnum.exe

User's Guide

When the application launches, it enumerates all of the installed DMOs. If you select a specific DMO category, the application displays only the DMOs in that category. To view information about a DMO, select the DMO from the list. The application displays the number of streams, the preferred media types, the DLL server for that DMO, and other information about the DMO. To include or exclude keyed DMOs, toggle the Include Keyed DMOs? checkbox.

The application uses the DMOEnum function and the IEnumDMO interface to enumerate the DMOs. It uses the IMediaObject interface and other DMO interfaces to retrieve information about each DMO.


DMO Sample

Description

DMO Sample is a sample Microsoft® DirectX® Media Object (DMO). It takes MPEG-1 video packets as input and produces two output streams. The first output stream contains video frames in RGB 565 format. Each frame displays the time code taken from the MPEG-1 video, and is otherwise blank. The second output stream is an optional text stream with the time code.

DMO Sample uses the IMediaObjectImpl class template to implement the IMediaObject interface. The Active Template Library (ATL) handles various COM details, including registration, aggregation, IUnknown, and the DLL entry points.

Path

Source: (SDK root)\Samples\C++\DirectShow\DMO\DMOSample

User's Guide

The project workspace builds a DLL named Dmosample.dll. Use the Regsvr32 utility to register the DLL. To see the DMO in action, you can use the Microsoft® DirectShow® GraphEdit utility. You will need an MPEG-1 video file. Perform the following steps:

  1. Run GraphEdit.
  2. Render an MPEG-1 file:
    • From the File menu, click Render Media File.
    • Select an MPEG-1 video file and click Open.
  3. Remove the MPEG-1 Video Decoder filter from the filter graph by selecting the filter and pressing DELETE.
  4. Insert the DMO Sample in the graph:
    • From the Graph menu, click Insert Filters.
    • Expand the DirectShow Filters list.
    • Select DMO Sample and click Insert Filters.
    • Click Close.
  5. Connect the MPEG-1 Stream Splitter to the DMO Sample by dragging the mouse from the small box labeled Video on the MPEG-1 Stream Splitter to the box labeled in0 on the DMO Sample. (See illustration.)
  6. Connect the DMO Sample to the Video Renderer:
    • Drag the mouse from the box labeled out0 on the DMO Sample to the box labeled Input on the Video Renderer.
    • GraphEdit might automatically insert a Color Space Converter filter to convert between RGB types.
  7. Press the play button on the GraphEdit toolbar, or click Play from the Graph menu.

When the graph runs, a video window appears that displays the time codes.

Connecting the DMO Sample

Programming Notes

The DMO Sample contains the following source files:

File | Description
Dmosample.cpp | Code for implementing basic COM functionality in ATL.
Resource.h | Defines resource constants.
Sample.h, Sample.cpp | Defined the CSample class, which implements the DMO.
State.h, State.cpp | Defines the CStreamState class, a helper class that generates time stamps from the MPEG data.
Stdafx.h, Stdafx.cpp | Generates the precompiled header.
Util.h, Util.cpp | Contains utility functions for drawing the output image.
Dmosample.rc | Defines a resource with version information, and links to the Sample.rgs file.
Sample.rgs | Defines a text resource with registry information. ATL uses this resource to create registry entries when it registers the DLL.

The following remarks describe the implementation in greater detail.

Dmosample.cpp

The file contains the object map that ATL uses to create and register the DMO object. It also contains the exported DLL functions. These include the entry-point function (DllMain), and the functions that COM requires (DllCanUnloadNow, DllGetClassObject, DllRegisterServer, and DllUnregisterServer).

The ATL COM AppWizard automatically generates most of the code contained in this file. Two things are added:

  • The DllRegisterServer function calls DMORegister to add registry information about the DMO. The DMO is registered in the DMOCATEGORY_VIDEO_DECODER category.
  • The DllUnregisterServer function calls DMOUnregister.

Resource.h

The one constant declared in this header file, IDR_SAMPLE, is used by ATL's self-registration mechanism. The constant IDR_SAMPLE identifies a text resource, which is defined in the resource file Sample.rgs and imported by the resource file Dmosample.rc. The header file Sample.h contains the following line:

DECLARE_REGISTRY_RESOURCEID(IDR_SAMPLE)

This causes ATL to use the registration information declared in the IDR_SAMPLE resource.

Sample.h

The DEFINE_GUID macro declares the class identifier (CLSID) of the DMO.

The CSample class derives from the following classes:

  • IMediaObjectImpl template. The template parameters specify that the DMO has one input stream and two output streams.
  • CComObjectRootEx. An ATL class that declares the threading model. The template parameter, CComMultiThreadModel, creates a thread-safe object and provides the Lock and Unlock methods.
  • CComCoClass. An ATL class that declares a standard COM object.

CSample aggregates the Free Threaded Marshaler, which is an object that performs custom marshaling. If the COM library marshals a CSample pointer across threads within the sample process, the exact same pointer is returned. If the COM library tries to marshal the object across processes or across machines, it fails. ATL adds all of the code need to aggregrate the Free Threaded Marshaler. This code appears in the FinalConstruct and FinalRelease methods. The COM_INTERFACE_ENTRY_AGGREGATE entry in the COM map delegates the IMarshal interface to the Free Threaded Marshaler.

The CSample class declares the following member variables:

Variable | Description
m_pUnkMarshaler | Pointer to the Free Threaded Marshaler object.
m_pBuffer | Pointer to the input buffer. The DMO holds a reference count on the buffer until it processes all of the input.
m_pbData | Pointer to the next byte in the input buffer.
m_cbData | Number of bytes remaining to process.
m_rtFrame | Time stamp from the most recent output frame.
m_StreamState | Instance of the CStreamState helper class, which parses MPEG data.
m_bPicture | Boolean flag that indicates whether the DMO has picture information to output.

Sample.cpp

This file implements the methods in the CSample class.

  • InternalGetInputStreamInfo. The DMO can process any number of bytes, aligned on any boundary, so this method returns zero flags.
  • InternalGetOutputStreamInfo. The first output stream produces whole fixed-sized samples, one at a time, which is typical for video decoders. The second output stream is optional. The returned flags indicate these attributes.
  • InternalCheckInputType. The input type must be MPEG-1 Video Payload, with a format type of FORMAT_MPEGVideo. After the input type is set, the method rejects format changes.
  • InternalCheckOutputType. This method validates output formats. There are two output streams:
    • Stream 0. The only media type supported by this stream is RGB-565. A real video decoder would typically support a range of formats. Also, the frame size of the output must match the frame size of the input—which is generally the case for real video decoders. This stream cannot be set unless the input type is set.
    • Stream 1. The media type must be MEDIATYPE_Text.

    After the types are set, the method fails unless the new type matches the current type. If a DMO cannot handle format changes while streaming, it should include similar code. In fact, the sample DMO could easily accept format changes, because it generates output one frame at a time.

  • InternalGetInputType. This method returns no types. Therefore, any index value is out of range, and the return value is DMO_E_NO_MORE_ITEMS.
  • InternalGetOutputType. If the input type is not set, this method returns no types. Otherwise, it returns one type for each stream. For stream 0, it returns RGB-565 with a frame size equal to the input size. For stream 1, it returns MEDIATYPE_Text.
  • InternalGetInputSizeInfo. The minimum buffer size for the input stream is one byte, with no alignment requirements. The stream does not perform lookahead.
  • InternalGetOutputSizeInfo. For stream 0, the buffers must be large enough to hold an output sample. For stream 1, the buffers must be large enough to hold a text string with a time stamp.
  • InternalFlush. This method releases the input buffer by setting m_pBuffer (an ATL smart pointer) to NULL. It also calls the InternalDiscontinuity method, which resets the CStreamState object.
  • InternalProcessInput. This method processes as much input data as possible. It performs the following steps:

    1. Calls the IMediaBuffer::GetBufferAndLength method to retrieve a pointer to the input data and the size of the input.

    2. Holds a reference count on the input buffer. The m_pBuffer variable is an ATL smart pointer, so assigning to the variable has the effect of calling the IUnknown::AddRef method.

    3. Passes the time stamp to the CStreamState object. If the sample does not have a time stamp, the method uses the value INVALID_TIME.

    4. Calls Process, a private helper method, to process the data.

  • InternalProcessOutput. If there is no data to output, this method returns S_FALSE. Otherwise, it generates output data. For stream 0, it performs the following steps:

    1. Checks whether the output buffer is large enough to hold the output data. If not, the method returns an error.

    2. Calls the OurFillRect method to draw the background, and the DrawOurText method to draw the text.

    3. Sets the time stamp. If there is a valid time stamp for this frame, it is used. Otherwise, the previous time stamp is incremented by the average frame rate.

    4. Calls the Process method again to process any data that might remain in the input buffer. If this results in more output data, the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag is set.

    Stream 1 is optional, so the caller might not allocate a buffer for that stream. Assuming that stream 1 does have an output buffer, however, the DMO writes the time code as a text string. The time stamps and processing flags are taken from stream 0.

  • InternalAcceptingInput. If the DMO is still holding a reference count on the previous input buffer, it does not accept any more input.
  • Process. This private method steps through the input data one byte at a time, updating the CStreamState object. If the CStreamState object finds a picture boundary before the input data is exhausted, the Process method returns S_OK. Otherwise, it returns S_FALSE.


Gargle DMO Sample

Description

This sample is a DirectX Media Object (DMO) that creates a gargle effect, similar to the Gargle Filter Sample for Microsoft® DirectShow®.

This sample demonstrates how to implement the following interfaces:

  • IMediaObject
  • IMediaObjectInPlace
  • IMediaParamInfo
  • IMediaParams

Path

Source: (SDK root)\Samples\C++\DirectShow\DMO\GargleDMO

User's Guide

To use this DMO, build and register GargleDMO.dll. The sample project builds several intermediate libraries. To build the DLL in Microsoft® Visual Studio®, select Batch Build from the Build menu.

You can use the DMO in the DMO Demo Sample application, or with the DirectShow GraphEdit utility. GraphEdit automatically wraps the DMO in the DMO Wrapper filter.

You can also use the DMO in Microsoft® DirectMusic® applications, including the Microsoft® DirectMusic® Producer application included with the SDK. In DirectMusic Producer, use the Audiopath Designer to insert the DMO into an audiopath. To control media parameters, use the Parameter Control track. Insert a curve in the track and assign it to control any of the properties on the DMO. For more information, see the Audiopath Designer and Parameter Control Track topics in the DirectMusic Producer application help.

The Gargle DMO provides a property page for the user to set the shape of the modulating waveform (square or triangular) and the frequency. It also supports a custom interface, IGargleDMOSample, for setting these properties.

Programming Notes

The Gargle DMO sample is built with the Active Template Library (ATL). The source code is organized into three libraries:

ControlBase Library

  • Controlhelp.h, Controlhelp.cpp: Helper classes for the user interface controls; used by the property page.

GargleDMO Library

  • Gargle.h, Gargle.cpp: Implements the Gargle DMO, including the IMediaObjectInPlace interface and the custom IGargleDMOSample interface.
  • GargleDMO.cpp: Implements the DLL entry-point function, and the DLL functions needed by the COM library, such as DllGetClassObject.
  • GargleDMO.def: Exports the DLL functions needed by the COM library.
  • GargleDMOProp.h, GargleDMOProp.cpp: Implements the property page. The property pages uses ATL's IPropertyPageImpl class template.
  • IGargle.h: Declares the IGargleDMOSample interface.
  • Resource.h: Resource constants.
  • Stdafx.h, Stdafx.cpp: Basic functions required by ATL.

MedParamBase Library

  • Alist.h, Alist.cpp: Simple linked-list class.
  • Param.h, Param.cpp: Contains the CParamsManager class, which implements the IMediaParams and IMediaParamInfo interfaces for media parameters.

The Gargle DMO does not use the IMediaObjectImpl class template. It uses an older set of DMO base classes, which the IMediaObjectImpl class is designed to replace. The IMediaObjectImpl class offers the following improvements:

  • Implements better parameter checking.
  • Enforces a stricter calling sequence.
  • Provides a simpler model for initializing streaming resources in the IMediaObject::AllocateStreamingResources methods.


DVD Samples

The Microsoft® DirectShow® SDK includes the following sample DVD applications.

C++ Applications

  • DVD Sample
  • PlayDVD Sample

Visual Basic Applications

  • WebDVD Sample


DVD Sample

Description

DVDSample is a C++ DVD application. It demonstrates all basic playback and navigation functions as well as advanced features such as parental level management, bookmarks, karaoke, and command synchronization.

Path

Source: (SDK root)\Samples\C++\DirectShow\DVD\DVDSample

Executable: (SDK root)\Samples\C++\DirectShow\Bin\DVDSample.exe


PlayDVD Sample

Available in DirectX 9.0 only.

Description

PlayDVD is a simple windowed DVD player based on the PlayWnd sample. It allows you to render a DVD volume, watch movies, determine whether closed captioning and subpicture streams are displayed, adjust the playback rate and window size, and navigate the DVD menus with the keyboard or the mouse.

It does not implement all of the features provided by the DVD interfaces.

For a more detailed sample, see DVDSample.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\PlayDVD

Executable: (SDK root)\Samples\C++\DirectShow\Bin\PlayDVD.exe


WebDVD Sample

Description

Simple Microsoft® Visual Basic® DVD application.

Path

Source: (SDK root)\Samples\VBSamples\DirectShow\WebDVD

Executable: (SDK root)\Samples\VBSamples\DirectShow\Bin\VB_WebDVDSample.exe

User's Guide

The WebDVD sample shows how to use the MSWebDVD Microsoft® Active X® control to perform all aspects of DVD-Video playback and navigation.

You can initiate playback by calling the Play method. Once the DVD is playing, you can alter the path or behavior of playback by through the following methods:

  • Stop: Stops playback.
  • Eject: Ejects the DVD disk from the drive.
  • Pause Pauses playback for as long as you wish.
  • ActivateButton: Activates the currently selected button. You can select a button by:
    • Hovering over the button and see it get highlighted. The DisableAutoMouseProcessing property must be false (the default value) for this to have an effect.
    • Calling SelectAtPosition, SelectLeftButton, SelectRightButton, SelectLowerButton, or SelectUpperButton.
  • PlayNextChapter: Plays the next chapter within the current title.
  • PlayPrevChapter: Plays the previous chapter within the same title.

You can show six possible menus that may exist on a disk with the ShowMenu method:

  • Title
  • Root
  • Subpicture
  • Audio
  • Angle
  • Chapter

If the menu does not exist, you will get an error indicating that the specified menu does not exist.


Filter Samples

The Microsoft® DirectShow® SDK includes the following sample filters:

Source Filters

  • Async Filter Sample
  • Ball Filter Sample
  • Push Source Filters Sample

Transform Filters

  • Contrast Filter Sample
  • EZRGB24 Filter Sample
  • Gargle Filter Sample
  • Grabber Filter Sample
  • NullIP Filter Sample
  • NullNull Filter Sample
  • SampVid Filter Sample
  • Synth Filter Sample
  • WavDest Filter Sample

Renderer Filters

  • Dump Filter Sample
  • Scope Filter Sample
  • TextOut Filter Sample

Miscellaneous

  • DSNetwork Filters Sample
  • InfTee Filter Sample
  • Metronome Filter Sample
  • PSI Parser Filter Sample
  • RGB Filters Sample


Async Filter Sample

Description

The Async Filter sample is a file reader filter that supports progressive download. This sample filter implements the IAsyncReader and IFileSourceFilter interfaces. It supports MPEG files, but not AVI files.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Async

User's Guide

This sample includes a small command-line application, Memfile.exe, that demonstrates the filter. The command-line arguments specify a media file and a bit rate, in kilobytes per second. The application reads the file into memory at the specified rate and plays the file. To do so, it creates an instance of the filter, adds the filter to the filter graph, and renders the filter's output pin.

At the command line, type:

Memfile Filename BitRate

The Async sample filter does not support AVI files, because it cannot connect to the AVI Splitter filter. The Async filter's output pin proposes MEDIATYPE_Stream and MEDIASUBTYPE_NULL for the media type. The input pin on the AVI Splitter filter does not accept MEDIASUBTYPE_NULL, and does not propose any types of its own. Therefore, the pin connection fails. The Async filter could be enhanced to offer MEDIASUBTYPE_Avi when appropriate. For example, it could examine the file format, or use the file extension.


Ball Filter Sample

Description

The Ball Filter is a video source filter that produces an image of a bouncing ball. This sample illustrates format negotiation and the use of the source filter base classes CSource and CSourceStream.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Ball

User's Guide

The code in Fball.h and Fball.cpp manages the filter interfaces. Those two files contain approximately the minimum code required for a source filter. The Ball.h and Ball.cpp files contain the code that bounces the ball.

This filter has a single output pin, which provides a video stream that shows a ball bouncing around in the frame. The Ball filter also accepts quality management requests from the downstream filter, which illustrates a simple quality management strategy. This filter implements the IQualityControl interface for that purpose.


Contrast Filter Sample

Description

The Contrast Filter is a video transform filter that implements a contrast effect. This sample illustrates how to define and implement a simple custom interface. It also demonstrates how to use the CTransformFilter class to implement a simple effect filter.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Contrast

User's Guide

The Contrast filter is a simple transform filter that adjusts the contrast of an 8-bit palletized video stream that is passed through it. It provides a custom interface for adjusting the contrast. The Contrast filter also uses the CBasePropertyPage class to provide a property page for applications that do not provide a user interface.

The Contrast filter adjusts the contrast by manipulating the image palette. By changing the palette, the filter changes the contrast without changing the image pixels themselves.


DSNetwork Filters Sample

Description

The DSNetwork sample shows how to multicast an MPEG-2 transport stream. It includes two related filters:

  • MPEG-2 Multicast Sender: Sends a multicast stream.
  • MPEG-2 Multicast Receiver: Receives a multicast stream.

Both filters support a custom interface, IMulticastConfig, for setting the multicast address and Network Interface Card (NIC) address.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\DSNetwork

User's Guide

To use this sample, compile and build the Visual Studio project. It creates a DLL named dsnet.ax in the Filter\Debug or Filter\Release subdirectories. Use the Regsvr32 utility to register the DLL.

You will need an MPEG-2 transport stream in push mode. This can be a digital television tuner, an IEEE 1394 MPEG-2 camcorder, or anything else that delivers an MPEG-2 transport stream (other than a file source). You will need two graphs, a sending graph and a receiving graph.

You can test the filters in GraphEdit as follows:

  1. Launch GraphEdit and create the sending graph. Connect the MPEG-2 source to the Multicast Sender filter. You may need additional filters to connect them; the details will depend on the source.

    Multicast Sender graph

    If the source is a network provider, the graph must have a TIF filter. Use the Infinite Pin Tee filter to split the transport stream, and send one stream to the TIF (through the MPEG-2 Demultiplexer) and the other stream to the Multicast Sender.

    Multicast Sender graph with network provider

  2. Use the property page on the Multicast Sender to set the desired multicast address, port, and NIC.
  3. Run the graph. If you have a tool that monitors multicast packets, this is useful to make sure the graph is actually delivering data.
  4. Launch a second instance of GraphEdit and create the receiving graph. Connect the Multicast Receiver to the MPEG-2 Demultiplexer.

    Multicast Receiver graph

  5. Use the property page on the Multicast Receiver to set the IP address, port, and NIC. These must match the settings that you used for the Multicast Sender.
  6. Use the property page on the Demultiplexer filter to create one or more output pins. Map the transport stream PIDs to the appropriate pins. (You will need to know the PID mappings in the original source stream, or use the PSI Parser Filter Sample.)
  7. Render the output pins on the demux and run the graph.

An application should use the IMulticastConfig interface to configure the Multicast Sender and Receiver filters. Both filters expose this interface.

Call IMulticastConfig::SetMulticastGroup to set the multicast address and the port number. Both numbers must be in network byte order; the Windows Sockets library has some helper functions for converting them into the correct byte order. For example, the following code configures the filter for the multicast address 235.1.1.1, port number 5000:

// IP address.
const char ip_address[] = "235.1.1.1";
unsigned long ulIP = inet_addr(ip_address);
if (ulIP == INADDR_NONE)
{
    cout << "Invalid IP address: " << ip_address << "\n";
    return;
}
// Port number.
unsigned short usPort = htons(5000);
hr = pConfig->SetMulticastGroup(ulIP, usPort);
if (FAILED(hr))
{
    cout << "SetMulticastGroup failed\n";
    return;
}

The inet_addr function converts a "dot notation" string into network byte order, and the htons function converts the port number (represented as an unsigned short).

Next, call IMulticastConfig::SetNetworkInterface to specify the Network Interface Card (NIC) address. You will need to use the Windows Sockets library to obtain a list of valid NIC addresses on the user's system. You can use the CInterface class, defined in the DSNetwork sample, as a starting point. The following example uses this class to get the NIC address:

CInterface NIC;
hr = NIC.Initialize();
if (FAILED(hr))
{
    cout << "Could not initialize the NIC helper class\n";
    return;
}
// Use the first NIC address in the list.
unsigned long ulNIC = NIC[0]->iiAddress.AddressIn.sin_addr.S_un.S_addr;
hr = pConfig->SetNetworkInterface(ulNIC);
if (FAILED(hr))
{
    cout << "SetNetworkInterface failed: " << ulNIC << "\n";
    return;
}

For information about configuring the MPEG-2 Demultiplexer filter in the receiving graph, see Using the MPEG-2 Demultiplexer.

See Also

  • IMulticastConfig Interface


IMulticastConfig Interface

The implementation of this interface is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The IMulticastConfig interface sets the multicast address and Network Interface Card (NIC) address for the MPEG-2 Multicast Sender and MPEG-2 Multicast Receiver filters, which are provided as sample filters in the DSNetwork Filters Sample.

In addition to the methods inherited from IUnknown, the IMulticastConfig interface exposes the following methods.

Method | Description
GetMulticastGroup | Retrieves the filter's current multicast group address.
GetNetworkInterface | Returns the filter's current NIC address.
SetMulticastGroup | Sets the multicast group that the filter will send or listen to.
SetNetworkInterface | Sets the NIC address that the filter will use.


IMulticastConfig::GetMulticastGroup

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetMulticastGroup method retrieves the filter's current multicast group address.

Syntax

HRESULT GetMulticastGroup(
  ULONG*  pIP,
  USHORT*  pPort
);

Parameters

pIP

[out] Pointer to a variable that receives the IP address, in network order (bytes ordered from left to right). You can use the inet_ntoa function to convert this number to a string in standard dotted format.

pPort

[out] Pointer to a variable that receives the port number, in TCP/IP network byte order. You can use the ntohs function to convert this number to the byte order of the host computer.

Return Values

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success.

Remarks

The values returned by this method are not valid until the application configures the filter.

See Also

  • DSNetwork Filters Sample
  • IMulticastConfig Interface


IMulticastConfig::GetNetworkInterface

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetNetworkInterface method returns the filter's current Network Interface Card (NIC) address.

Syntax

HRESULT GetNetworkInterface(
  ULONG*  pNIC
);

Parameters

pNIC

[out] Pointer to a variable that receives the NIC address, in network order (bytes ordered from left to right). You can use the inet_ntoa function to convert this number to a string in standard dotted format.

Return Values

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success.

Remarks

The value returned by this method is not valid until the application configures the filter.

See Also

  • DSNetwork Filters Sample
  • IMulticastConfig Interface


IMulticastConfig::SetMulticastGroup

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The SetMulticastGroup method sets the multicast group that the filter will send or listen to.

Syntax

HRESULT SetMulticastGroup(
  ULONG  ulIP,
  USHORT  usPort
);

Parameters

ulIP

[in] Specifies the IP address, in network order (bytes ordered from left to right). You can use the inet_addr function to convert a standard dotted-format string (such as "255.255.255.255") to the correct binary number.

usPort

[in] Specifies the port number, in TCP/IP network byte order. You can use the htons function to convert the port number to the correct byte order.

Return Values

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_INVALIDARG | Invalid IP address.
E_UNEXPECTED | The operation could not be performed because the filter is not stopped.
S_OK | Success

Example Code

// Assign the multicast address 235.1.1.1, port 5000.
ULONG ulIP = inet_addr("235.1.1.1");
USHORT usPort = htons(5000);
hr = pConfig->SetMulticastGroup(ulIP, usPort);

See Also

  • DSNetwork Filters Sample
  • IMulticastConfig Interface


IMulticastConfig::SetNetworkInterface

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The SetNetworkInterface method sets the Network Interface Card (NIC) address that the filter will use.

Syntax

HRESULT SetNetworkInterface(
  ULONG  ulNIC
);

Parameters

ulNIC

[in] Specifies the NIC address, in network order (bytes ordered from left to right). You can use the inet_addr function to convert a standard dotted-format string (such as "255.255.255.255") to the correct binary number.

Return Values

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_INVALIDARG | Invalid IP address.
E_UNEXPECTED | The operation could not be performed because the filter is not stopped.
S_OK | The method succeeded.

Example Code

// Assign the NIC "127.0.0.1" as an example. In a real application,
// you would obtain a valid NIC at run time.
ULONG ulNIC = inet_addr("127.0.0.1");
hr = pConfig->SetNetworkInterface(ulNIC);

See Also

  • DSNetwork Filters Sample
  • IMulticastConfig Interface


Dump Filter Sample

Description

The Dump Filter is a renderer filter that writes the media samples it receives to a text file.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Dump

User's Guide

This filter is a useful debugging tool. For example, you can verify, bit by bit, the results of a transform filter. You can build a graph manually by using GraphEdit, and connect the Dump filter to the output of a transform filter or any other output pin. You can also connect a tee filter and put the Dump filter on one leg of the tee filter and the typical output on another leg to monitor the results in a real-time scenario.

This sample illustrates how to use the base filter class CBaseFilter and the rendered input pin class CRenderedInputPin. It also demonstrates how to implement the IFileSinkFilter interface. The Dump filter has a single input pin, which writes every sample that it receives directly to a file.


EZRGB24 Filter Sample

Description

The EZRGB24 filter is an image processing transform filter. This filter performs a number of individual video effects, including red, green, blue, darken, XOR, blur, gray, and emboss effects.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\EZRGB24

User's Guide

This sample shows how to use several Microsoft® DirectShow® classes, including CTransformFilter, CPersistStream, and CBasePropertyPage.


Gargle Filter Sample

Description

The Gargle Filter is an audio effect transform filter.

The Gargle filter modulates the waveform passing through it by multiplying the waveform by another waveform that is mathematically generated within the filter. The modulating waveform is, by default, a triangular wave. The property sheet also offers the alternative of a square wave. You can set the frequency of the modulating wave through the filter's property sheet. At low modulation frequencies, the effect sounds like a tremolo. At higher modulation frequencies, it sounds like a distortion, adding extra frequencies above and below the original unmodulated sound.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Gargle


Grabber Filter Sample

This sample provides modified source code for the Sample Grabber filter. To prevent conflicts with the existing Sample Grabber, the following changes have been made:

  • This sample filter has been renamed "SampleGrabber Example," to indicate that it is an example implementation.
  • The CLSID has been changed to CLSID_GrabberSample.
  • The filter supports a new interface, IGrabberSample.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Grabber

Sample Description

The Grabber is a trans-in-place filter that captures data traveling through a stream and notifies the application through a callback. It performs an in-place transform, so it does not require additional buffers or copying. However, if your callback function takes a long time to process, this benefit will be greatly reduced.

Limitations of the Original Sample Grabber Filter

The Sample Grabber that ships with DirectX has some limitations:

  • For video types, it requires a VIDEOINFOHEADER format. It cannot connect to filters that require other format types, such as VIDEOINFOHEADER2 or DVINFO. Therefore, it is not compatible with MPEG-2 or DV video, or with field-based video.
  • One-shot mode does not work correctly in some circumstances, such as when the upstream filter queues samples on a worker thread.
  • It must be connected to a renderer filter, even when the application does not require one (hence the Null Renderer filter).

The Grabber filter source code provides an opportunity for developers to make improvements and modifications suited for their own needs.

Recommendations for Use

When you are using the Grabber sample filter, follow these guidelines:

  • Do not call IGraphBuilder::RenderFile and assume that the Filter Graph Manager has inserted the filter in the correct place within a chain of filters. Verify that the filter is connected properly and is using the expected media type.
  • You must connect the filter's output pin to a downstream filter. If you want to retrieve data from the streams without rendering it, use the Null Renderer filter.
  • You can turn off the graph reference clock to make the filter graph run as quickly as possible. Call the IMediaFilter::SetSyncSource method with the value NULL.
  • The filter does not synchronize itself with the main application thread, so the application must handle multithreading issues.
  • Unlike the Sample Grabber filter, the Grabber sample does not buffer the data or support "one-shot" mode.

For more information, see How To Get Data from a Microsoft DirectShow Filter Graph at the MSDN Web site.

See Also

  • IGrabberSample Interface


IGrabberSample Interface

The implementation of this interface is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The IGrabberSample interface configures the Grabber filter, which is provided in the DirectShow SDK as a sample filter.

In addition to the methods inherited from IUnknown, the IGrabberSample interface exposes the following methods.

Method | Description
GetConnectedMediaType | Retrieves the media type for pin connection on the Grabber filter's input pin.
SetAcceptedMediaType | Sets the media type for pin connection on the Grabber filter's input pin.
SetCallback | Specifies a callback method that the Grabber filter will call whenever it receives a media sample.
SetDeliveryBuffer | Specifies a target memory buffer for media samples received by the Grabber filter.

See Also

  • Grabber Filter Sample


IGrabberSample::GetConnectedMediaType

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetConnectedMediaType method retrieves the media type for pin connection on the Grabber filter's input pin.

Syntax

HRESULT GetConnectedMediaType(
    CMediaType *pType
);

Parameters

pType

Pointer to a CMediaType object that receives the media type.

Return Value

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The input pin is not connected.

See Also

  • Grabber Filter Sample
  • IGrabberSample Interface


IGrabberSample::SetAcceptedMediaType

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The SetAcceptedMediaType method sets the media type for pin connection on the Grabber filter's input pin. This method is equivalent to the ISampleGrabber::SetMediaType method.

Syntax

HRESULT SetAcceptedMediaType(
    const CMediaType *pType
);

Parameters

pType

Pointer to a CMediaType object that specifies the media type. Use the value NULL to clear the media type that was set previously.

Return Value

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

See Also

  • Grabber Filter Sample
  • IGrabberSample Interface


IGrabberSample::SetCallback

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The SetCallback method specifies a callback method that the Grabber filter will call whenever it receives a media sample.

Syntax

HRESULT SetCallback(
    SAMPLECALLBACK Callback
);

Parameters

Callback

Pointer to the callback function. Specify NULL to cancel the callback. See Remarks for details.

Return Value

Returns S_OK.

Remarks

The callback function must have the following signature:

typedef HRESULT (*SAMPLECALLBACK) (
    IMediaSample *pSample,
    REFERENCE_TIME *StartTime,
    REFERENCE_TIME *StopTime,
    BOOL TypeChanged
);

The pSample parameter is a pointer to the media sample's IMediaSample interface. The StartTime and StopTime parameters are pointers to the sample start and stop times. The TypeChanged parameter equals TRUE if the connect type has changed since the last sample. However, the Grabber filter does not check for dynamic format changes on the media sample. The application should do this inside the callback function. For more information, see QueryAccept (Downstream).

See Also

  • Grabber Filter Sample
  • IGrabberSample Interface


IGrabberSample::SetDeliveryBuffer

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The SetDeliveryBuffer method specifies a target memory buffer for media samples received by the Grabber filter.

Syntax

HRESULT SetDeliveryBuffer(
    ALLOCATOR_PROPERTIES props,
    BYTE *pBuffer
);

Parameters

props

Specifies an ALLOCATOR_PROPERTIES structure that describes the properties of the buffer. The cBuffers member must equal 1.

pBuffer

Pointer to a buffer allocated by the caller.

Return Value

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
E_INVALIDARG | Invalid argument
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This method enables the application to allocate a block of memory that will receive media samples from the Grabber filter. The sample data will be written directly into the memory, without the filter performing a memory copy.

Internally, this method creates a custom allocator. The Grabber filter will force this allocator to be used for its upstream input pin connection. Be aware that this can cause connection failures with some filters, because the other filter may have incompatible allocator requirements.

Call this method before the Grabber's pins are connected; otherwise, the method returns E_INVALIDARG.

See Also

  • Grabber Filter Sample
  • IGrabberSample Interface


InfTee Filter Sample

Description

The InfTee filter provides a sample implementation of the DirectShow Infinite Pin Tee filter. The filter has one input pin and a dynamic number of output pins. All media samples sent to the filter are delivered simultaneously from all of the output pins.

This filter appears in GraphEdit under the name "Sample Infinite Pin Tee," to distinguish it from the standard Infinite Pin Tee filter that is provided in DirectShow.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\InfTee

User's Guide

Because this filter does not change the data that it receives, all pins must agree to the same media type. During the connection process, the filter might reconnect some pins in order to make the media types match.

Data arriving at the input pin is not copied before it is sent to the output pins. The filter also ensures that the data is delivered to the downstream filters, to guarantee that both outputs receive timely service. In particular, if one of the outputs can block in the COutputQueue::Receive member function, then the tee spins off a thread to deliver the sample. If there were no thread to deliver the sample, then the thread that delivers the sample to the tee input pin might pass the data to a downstream filter; at that point, it might block, keeping data from the other downstream filter for long periods of time.


Metronome Filter Sample

Description

This sample filter shows how to implement a reference clock. The filter uses your default microphone input to listen for audio spikes (such as clicks, hand claps, or coughs), which it uses to determine a clock rate.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Metronome

User's Guide

After building the filter, copy the filter DLL (Metronom.ax) to your Windows system directory. Run the Metronom.reg file to register the DLL.

To use the filter:

  1. Build a filter graph in GraphEdit that renders a video stream.
  2. Delete any rendered audio streams.
  3. Add the Metronome filter to the graph. It appears in the DirectShow Filters category.
  4. Run the graph. The video will begin playing at normal speed.
  5. Clap your hands or use a metronome to set a new speed.

Programming Notes

This filter works only for video. The audio renderer is not capable of synchronizing to radically different clock rates.

If you clap 92 times per minute (once every ~652 ms), the video will play at the normal rate. You can change this default by changing the value of the constant BPM in Metronom.cpp.

If you stop clapping for a period of time and then start clapping again, you must start again at approximately the same speed, or the filter will ignore it. Also, the video playback rate is limited by the CPU speed. If you exceed the limit for any length of time, the filter will stop responding to rate changes. If this happens, stop the graph and restart.

If you implement your own clock, the most important rules is that reference clocks must not go backwards. That is, they must never report a time value less than the previous time value.

See Also

  • CBaseReferenceClock Class


NullIP Filter Sample

Description

The NullIP filter is an in-place transform filter that does not modify the data. You can use it as the basis for implementing your own in-place transform filters.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\NullIP


NullNull Filter Sample

Description

The NullNull filter illustrates the simplest transform filter possible. The filter supports no functionality; you can use it as the basis for implementing your own transform filters.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\NullNull


PSI Parser Filter Sample

The PSI Parser filter receives Program Specific Information (PSI) from an MPEG-2 transport stream and extracts program information from the Program Association Table (PAT) and Program Map Tables (PMT). This information enables an application to configure the MPEG-2 Demultiplexer. The filter supports a custom interface, IMpeg2PsiParser, for retrieving the PSI information.

This filter is designed for MPEG-2 devices, such as IEEE 1394 MPEG-2 camcorders and D-VHS devices. See MSTape Driver for more information. Digital television broadcast sources should use a TIF filter to get program information.

User's Guide

You can test the PSI Parser filter in GraphEdit as follows:

  1. Launch GraphEdit.
  2. Insert an MPEG-2 transport source. MPEG-2 camcorders and D-VHS devices appear as "Microsoft AV/C Tape Subunit Device" in the Video Capture Sources category.
  3. Connect the source filter to the MPEG-2 Demultiplexer filter.
  4. Use the property page on the demux to create an output pin with media type MPEG-2 PSI. This pin will deliver the PAT and PMT sections.
  5. Use the demux property page to map PID 0x00 to the output pin. Set the content type to MPEG2 PSI Sections.
  6. Connect the demux output pin to PSI Parser.

    PSI Parser filter graph

  7. Run the graph, in order to feed PSI data to the PSI Parser filter. As the filter decodes the PAT sections, it automatically maps the PMT PIDs to the same output pin on the demux, so that it receives the PMT sections.
  8. Use the PSI Parser property page to select a program number. The elementary stream list in the property page will show the PID and stream type associated with each elementary stream in the selected program. The property page is designed to recognize stream types defined in ISO/IEC 13818-1.
  9. Enter the audio PID number in the Audio PID edit box, and the video PID number in the Video PID edit box.
  10. Click the View Program button. The PSI Parser will configure the output pins on the demux to match the program stream information and render the pins.

Note The PSI Parser property page is provided to make testing easier, and to provide sample code that configures the MPEG-2 Demultiplexer. It is not recommended for applications to use. Applications should configure the demux programmatically.

To use the PSI Parser filter in an application, start by building the filter graph from the MPEG-2 source to the MPEG-2 demux. Code for this step is not shown here, because the exact graph configuration will depend on the source.

Next, create an output pin on the demux for the PSI data. Map PID 0x00, which is reserved for PAT sections, to this pin, as shown in the following code:

// Set the media type to MPEG-2 table sections.
AM_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = KSDATAFORMAT_TYPE_MPEG2_SECTIONS;

// Create the pin.
IPin *pPsiPin;
hr = pDemux->CreateOutputPin(&mt, L"PSI", &pPsiPin);
if (SUCCEEDED(hr))
{
    // Map to PID 0.
    ULONG Pid = 0x00;
    hr = pPid->MapPID(1, &Pid, MEDIA_MPEG2_PSI);
}

For more information, see Using the MPEG-2 Demultiplexer.

Add the PSI Parser filter to the graph and connect it to the output pin on the demux. Query the PSI Parser for the IMpeg2PsiParser interface. Now run the graph and wait for EC_PROGRAM_CHANGED events, which signal a new PAT or PMT section. This event is a custom event defined by the PSI Parser filter. When you receive an EC_PROGRAM_CHANGED event, you can get the available PSI information by calling IMpeg2PsiParser methods. This section describes the methods you will need most often.

To get the number of programs, use the GetCountOfPrograms method:

int NumProgs = 0;
hr = pPsi->GetCountOfPrograms(&NumProgs);

To get the program number for a specific program, use the GetRecordProgramNumber method:

WORD ProgNum = 0;
for (int i = 0; iProgram < NumProgs; i++)
{
    hr = pPsi->GetRecordProgramNumber(i, &ProgNum);
    ...
}

The program number is used to obtain the PMT entries for individual programs. To get the number of elementary streams in a program, use the GetCountOfElementaryStreams method:

ULONG cElemStreams = 0;
hr = pPsi->GetCountOfElementaryStreams(ProgNum, &cElemStreams);

For each elementary stream, the GetRecordElementaryPid method returns the PID, and the GetRecordStreamType method returns the stream type:

BYTE ESType = 0;
WORD ESPid = 0;
for (ULONG j = 0; j < cElemStreams; j++)
{
    hr = pPsi->GetRecordElementaryPid(ProgNum, j, &ESPid);
    hr = pPsi->GetRecordStreamType(ProgNum, j, &ESType);
}

The PID and the stream type enable you to configure new output pins on the MPEG-2 Demultiplexer. This may require some knowledge of the original source. For example, ISO/IEC 13818-1 defines stream types 0x80 through 0xFF as "user private," but other standards that are based on MPEG-2 may assign other meanings to these types.

The MPEG-2 Demultiplexer can create new pins and new PID mappings while the graph is running, but you must stop the graph to connect pins.

See Also

  • IMpeg2PsiParser Interface


IMpeg2PsiParser Interface

The implementation of this interface is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The IMpeg2PsiParser interface retrieves Program Specific Information (PSI) from the PSI Parser filter, which is provided in the DirectShow SDK as a sample filter. An application can use this filter to map program IDs (PIDs) on the MPEG-2 Demultiplexer filter.

In addition to the methods inherited from IUnknown, the IMpeg2PsiParser interface exposes the following methods.

Method | Description
FindRecordProgramMapPid | Finds the Program Map Table (PMT) PID for a program, given the program number.
GetCountOfElementaryStreams | Retrieves the number of elementary streams in a specified program.
GetCountOfPrograms | Retrieves the number of programs in the transport stream.
GetPatVersionNumber | Retrieves the version_number field from the Program Association Table (PAT).
GetPmtVersionNumber | Retrieves the version_number field from a specified PMT.
GetRecordElementaryPid | Retrieves the PID assignment for a specified elementary stream in a program.
GetRecordProgramMapPid | Retrieves the PID assignment for a specified PMT.
GetRecordProgramNumber | Retrieves the program number for a specified program.
GetRecordStreamType | Retrieves the stream type for a specified elementary stream in a program.
GetTransportStreamId | Retrieves the transport_stream_id field from the PAT.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


IMpeg2PsiParser::FindRecordProgramMapPid

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The FindRecordProgramMapPid method finds the PMT PID for a program, given the program number.

Syntax

HRESULT FindRecordProgramMapPid(
    WORD wProgramNumber,
    WORD *pwVal
);

Parameters

wProgramNumber

[in] Specifies the program_number field of the PMT, as given in the PAT. Use the GetRecordProgramNumber method to obtain the program number.

pwVal

[out] Pointer to a variable that receives the program_map_ID field.

Return Values

This method returns an HRESULT value. Possible return codes include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

Remarks

The returned value gives the PID assignment for the PMT sections that define the program. To get the PID assignments for the elementary streams in the program, call the GetRecordElementaryPid method.

See Also

  • IMpeg2PsiParser Interface
  • IMpeg2PsiParser::GetRecordProgramMapPid
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetCountOfElementaryStreams

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetCountOfElementaryStreams method retrieves the number of elementary streams in a specified program.

Syntax

HRESULT GetCountOfElementaryStreams(
    WORD wProgramNumber,
    WORD *pwVal
);

Parameters

wProgramNumber

[in] Specifies the program_number field for the program, as given in the PAT.

pwVal

[out] Pointer to a variable that receives the number of elementary streams in the program.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

Remarks

Use the GetRecordProgramNumber method to obtain the program number.

See Also

  • IMpeg2PsiParser Interface
  • IMpeg2PsiParser::GetRecordProgramNumber
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetCountOfPrograms

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetCountOfPrograms method retrieves the number of programs in the transport stream.

Syntax

HRESULT GetCountOfPrograms(
    int *pNumOfPrograms
);

Parameters

pNumOfPrograms

[out] Pointer to a variable that receives the number of programs.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetPatVersionNumber

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetPatVersionNumber method retrieves the version_number field from the PAT. A transport stream contains at most one PAT. The version number is incremented whenever the information in the table changes.

Syntax

HRESULT GetPatVersionNumber(
    BYTE *pPatVersion
);

Parameters

pPatVersion

[out] Pointer to a variable that receives the version_number field.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetPmtVersionNumber

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetPmtVersionNumber method retrieves the version_number field from a specified PMT. The version number is incremented whenever the definition of the program changes.

Syntax

HRESULT GetPmtVersionNumber(
    WORD wProgramNumber,
    BYTE *pPmtVersion
);

Parameters

wProgramNumber

[in] Specifies the program_number field of the program, as given in the PAT.

pPmtVersion

[out] Pointer to a variable that receives the version_number field.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

Remarks

Use the GetRecordProgramNumber method to obtain the program number.

See Also

  • IMpeg2PsiParser Interface
  • IMpeg2PsiParser::GetRecordProgramNumber
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetRecordElementaryPid

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetRecordElementaryPid method retrieves the PID assignment for a specified elementary stream in a program.

Syntax

HRESULT GetRecordElementaryPid(
    WORD wProgramNumber,
    DWORD dwRecordIndex,
    WORD *pwVal
);

Parameters

wProgramNumber

[in] Specifies the program_number field of the program, as given in the PAT. Use the GetRecordProgramNumber method to obtain the program number.

dwRecordIndex

[in] Specifies the elementary stream, indexed from zero.

pwVal

[out] Pointer to a variable that receives the elementary_PID field from the PMT.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • IMpeg2PsiParser::GetRecordProgramNumber
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetRecordProgramMapPid

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetRecordProgramMapPid method retrieves the PID assignment for a specified PMT.

Syntax

HRESULT GetRecordProgramMapPid(
    DWORD dwIndex,
    WORD *pwVal
);

Parameters

dwIndex

[in] Specifies the PMT entry in the PAT, indexed from zero.

pwVal

[out] Pointer to a variable that receives the program_map_PID field from the PAT.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

Remarks

The returned value gives the PID assignment for the PMT sections that define the program. To get the PID assignments for the elementary streams in the program, call the GetRecordElementaryPid method.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetRecordProgramNumber

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetRecordProgramNumber method retrieves the program number for a specified program.

Syntax

HRESULT GetRecordProgramNumber(
    DWORD dwIndex,
    WORD *pwVal
);

Parameters

dwIndex

[in] Specifies the entry in the PAT that defines the program, indexed from zero.

pwVal

[out] Pointer to a variable that receives the program_number field from the PAT.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetRecordStreamType

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetRecordStreamType method retrieves the stream type for a specified elementary stream in a program.

Syntax

HRESULT GetRecordStreamType(
    WORD wProgramNumber,
    DWORD dwRecordIndex,
    BYTE *pbVal
);

Parameters

wProgramNumber

[in] Specifies the program_number field of the program, as given in the PAT. Use the GetRecordProgramNumber method to obtain the program number.

dwRecordIndex

[in] Specifies the elementary stream in the program, indexed from zero.

pbVal

[out] Pointer to a variable that receives the stream_type field from the PMT.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • IMpeg2PsiParser::GetRecordProgramNumber
  • PSI Parser Filter Sample


IMpeg2PsiParser::GetTransportStreamId

The implementation of this method is provided as sample code with the DirectShow SDK. It is not a supported DirectShow API.

The GetTransportStreamId method retrieves the transport_stream_id field from the PAT. This value is defined by the user, and can be used to distinguish a particular transport stream from other streams on the same network. A transport stream contains at most one PAT.

Syntax

HRESULT GetTransportStreamId(
    WORD *pStreamId
);

Parameters

pStreamId

[out] Pointer to a variable that receives the transport_stream_id field.

Return Values

The method returns an HRESULT value. Possible values include, but are not limited to, the values shown in the following table.

Value | Description
S_OK | Success.

See Also

  • IMpeg2PsiParser Interface
  • PSI Parser Filter Sample


Push Source Filters Sample

This sample consists of a set of three source filters that provide the following source data as a video stream:

  • CPushSourceBitmap - Single bitmap (loaded from current directory)
  • CPushSourceBitmapSet - Set of bitmaps (loaded from current directory)
  • CPushSourceDesktop - Copy of current desktop image (GDI only)

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\PushSource

User's Guide

To use a filter, load it into GraphEdit and render its output pin. This will connect a video renderer (and possibly a Color Space Converter filter) and allow you to display the output. If you want to render the output to an AVI file, load the AVI Mux, load a File Writer Filter, provide an output name to the File Writer, and render the PushSource filter's output pin. You can also load and connect video compressors, video effects, and so on.

NOTE: The desktop capture filter does not support hardware overlays, so it will not capture video rendered to an overlay surface or cursors displayed via hardware overlay. It uses GDI to convert the current desktop image into a bitmap, which is passed to the output pin as a media sample.


RGB Filters Sample

Description

This sample provides several filters that are useful for testing your own filters.

Filter | Description
AlphaRenderer | This filter renders video to an alpha blended checkerboard patter, based on the alpha values in the incoming video. It uses the media subtype MEDIASUBTYPE_ARGB32.
RateSource | This source filter outputs video at a specified frame rate, for testing different frame rates. It also supports seeking.
SourceARGB | This source filter outputs RGB 32 with alpha (MEDIASUBTYPE_ARGB32), for texting alpha support in downstream filters. It also supports seeking.
Source8Bit, Source555Bit, Source565Bit, Source24Bit, Source32Bit | These source filters output video in various uncompressed RGB formats, for testing pin connections in downstream filters. They also support seeking.
TransNull8, TransNull555, TransNull565, TransNull24, TransNull32, TransNull32a | Each of these trans-in-place filters requires a particular RGB media type. They are useful for testing pin connections in upstream filters. (They do not transform the video in any way.)
TransSmpte | This filter draws a SMPTE time stamp on the video, for testing frame-accurate filters. You can write the output video to disk. This filter supports 32-bit RGB only (MEDIASUBTYPE_RGB32, FORMAT_VideoInfo), although you could easily modify it for other media types.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\SampVid


SampVid Filter Sample

Description

The SameVid filter is a sample video renderer filter.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\SampVid


Scope Filter Sample

Description

The Scope filter is a renderer filter that displays sound data as wave forms.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Scope

User's Guide

To use this filter, open GraphEdit and render an audio file (or a video file with an audio stream). Disconnect the audio renderer temporarily and insert the Infinite-Pin Tee (InfTee Filter Sample) sample filter. Reconnect the audio renderer. Then connect the Infinite-Pin Tee filter's second output pin to the Scope filter. Now run the graph.

The Scope window is implemented as a dialog box, not as an actual window. Developers creating control panels to alter filter parameters in real time might want to use a technique like this rather than property pages.

The Scope filter demonstrates setting up a separate thread to process data. In this case, the data is just copied to a separate buffer on the IMemInputPin::Receive method, and is then drawn on the Scope window on the separate thread.

The Scope filter also enables you to monitor audio output to determine if you are clipping, so you can adjust the gain.

This filter appears in GraphEdit as "Oscilloscope."


Synth Filter Sample

Description

The Synth filter is a source filter that generates audio waveforms.

This filter illustrates dynamic graph building. It can switch between uncompressed PCM audio and compressed MS_ADPCM (Microsoft Adaptive Delta Pulse Code Modulation) format.

This filter appears in GraphEdit as "Audio Synthesizer Filter."

For more information about dynamic graph building, see Dynamic Graph Building.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\Synth

User's Guide

The Synth filter enables the user to set the waveform, frequency, number of channels, and other properties through the property page. To set either the upper or lower endpoint of the swept frequency range, hold down SHIFT while adjusting the frequency slider. The filter also supports a custom interface, ISynth2, for setting these properties.

To demonstrate the dynamic graph building feature, do the following:

  1. Build the filter and register it with the Regsvr32 utility.
  2. Launch GraphEdit.
  3. Insert the Audio Synthesizer filter. It appears in the DirectShow Filters category.
  4. Render the filter's output pin.
  5. Click the Play button.
  6. Open the filter's property page.
  7. In the Output Format area, select PCM or Microsoft ADPCM.

Programming Notes

This sample contains the following files:

  • Dynsrc.h, Dynsrc.cpp: Contains two base classes for source filters that support dynamic graph building, CDynamicSource and CDynamicSourceStream.
  • ISynth.h: Declares the custom ISynth2 interface for setting properties on the filter.
  • Resource.h: Contains resource constants.
  • Synth.def: Exports the DLL functions needed by the COM library.
  • Synth.h, Synth.cpp: Contains the CAudioSynth class, which generates the audio data, and the CSynthFilter class, which implements the filter.
  • Synth.rc: Contains resources used by the filter.
  • Synthprp.h, Synthprp.cpp: Implements the filter's property page.

The CDynamicSource class is adapted from the CSource base class. It uses one or more output pins derived from the CDynamicSourceStream class. The CDynamicSourceStream class is adapted from the CSourceStream class, but derives from the CDynamicOutputPin class rather than the CBaseOutputPin class.

The CDynamicSource class has the following methods not found in CSource:

  • Stop: Signals the stop event (CDynamicOutputPin::m_hStopEvent), and shuts down the worker thread for all unconnected pins. On a connected pin, the pin's Inactive method will shut down the worker thread.
  • Pause: Resets the stop event.
  • JoinFilterGraph: Calls the CDynamicOutputPin::SetConfigInfo method on each pin.

The CDynamicSourceStream class has the following methods not found in CSourceStream:

  • DestroySourceThread: Shuts down the worker thread.
  • FatalError: Signals an error to the filter graph manager.
  • OutputPinNeedsToBeReconnected: Signals that the output pin should be reconnected. When this method is called, the worker thread calls the CDynamicOutputPin::DynamicReconnect method to reconnect the pin.


TextOut Filter Sample

Description

This filter is a renderer that displays text data.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\TextOut

User's Guide

The DirectShow SDK includes an AVI file named Clocktxt.avi, which contains three streams: audio, video, and text. The text stream consists of NULL-terminated text strings. You can use the Text Display filter to render the text strings.

To use this filter, perform the following steps:

  1. Build and register the filter.
  2. Launch GraphEdit.
  3. Add the Text Display filter to the filter graph.
  4. Render the Clocktxt.avi file.
  5. Run the filter graph.


WavDest Filter Sample

Description

The WavDes filter writes an audio stream to a WAV file. It takes a single audio stream as input, and its output pin must be connected to the File Writer filter. This sample filter is based on the CTransformFilter class.

Path

Source: (SDK root)\Samples\C++\DirectShow\Filters\WavDest


Miscellaneous DirectShow Samples

The Microsoft® DirectShow® SDK includes the following miscellaneous samples.

C++ Applications

  • ASFCopy Sample
  • Mapper Sample
  • RenderLog Sample
  • SysEnum Sample

Visual Basic Applications

  • Builder Sample


ASFCopy Sample

Description

Transcodes one or more files to an ASF file.

Path

Source: (SDK root)\Samples\C++\DirectShow\Misc\ASFCopy

User's Guide

To build this sample, you must install the Microsoft® Windows Media™ Format SDK and link your application to WMVCore.lib. If you use version 7.1 of the Windows Media Format SDK, you must also link to wmstub.lib, which is distributed with the SDK. This library enables applications to create ASF files that are not protected by Digital Rights Management (DRM).

To create DRM-protected files, you must use a library that is unique to your application, and which must be obtained directly from Microsoft.

Usage:

ASFCopy [/v] /p profile file1 [file2 ...] target

The following command-line switches are supported.

Switch | Description
/p | Specifies the profile number.
/v | Verbose mode.

Specify an ASF profile using the /p switch. If you omit this switch, ASFCopy displays a list of the standard system profiles.

Specify the name of one or more source files, and the name of the target file. If you specify more than one source file, the application multiplexes all of the source files. You must specify a profile that matches the streams contained in the source files, or else the application will not work correctly. For example, if you specify Video for Web Servers (56 Kbps), the combined source files must have exactly one video stream and one audio stream.

See Also

  • Windows Media Applications


Mapper Sample

Description

This sample demonstrates using the IFilterMapper2::EnumMatchingFilters method to locate filters in the registry. The application's UI contains controls that match the parameters of the EnumMatchingFilters method, such as minimum merit value, pin categories, and media types. Select the search options that you want, then click the Search button to enumerate the filters that match those options.

Path

Source: (SDK root)\Samples\C++\DirectShow\Misc\Mapper

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Mapper.exe

See Also

  • Using the Filter Mapper


RenderLog Sample

Description

This sample demonstrates how to log the Filter Graph Manager's steps when it builds a Filter Graph.

Path

Source: (SDK root)\Samples\C++\DirectShow\Misc\RenderLog

Executable: (SDK root)\Samples\C++\DirectShow\Bin\RenderLog.exe

See Also

  • IGraphBuilder::SetLogFile


SysEnum Sample

Description

This sample demonstrates how to use the System Device Enumerator to enumerate devices and filters on the user's system.

Path

Source: (SDK root)\Samples\C++\DirectShow\Misc\SysEnum

Executable: (SDK root)\Samples\C++\DirectShow\Bin\SysEnum.exe

See Also

  • Enumerating Devices and Filters


Builder Sample

Description

This sample application demonstrates how to build filter graphs in Visual Basic.

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\Builder


Player Application Samples

The Microsoft® DirectShow® SDK includes the following sample player applications:

C++ Applications

  • AudioBox Sample
  • BGMusic Sample
  • CutScene Sample
  • DDrawXCL Sample
  • Jukebox Sample
  • JukeboxASF Sample
  • PlayDMO Sample
  • PlayWnd Sample
  • PlayWndASF Sample
  • StillView Sample
  • Texture3D Sample
  • Texture3D9 Sample

Visual Basic Applications

  • VBDemo Sample


AudioBox Sample

Description

This MFC application is an audio-only media player, similar to Jukebox sample. You can select a media directory and play all of the audio media files, in that directory, including Windows Media files. Options include seeking, muting the audio, random file selection, adjusting the volume, and looping the current file.

Path

Source: (SDK root)Samples\C++\DirectShow\Players\AudioBox

Executable: (SDK root)\Samples\C++\DirectShow\Bin\AudioBox .exe


BGMusic Sample

Description

The BGMusic sample is a playback application that cycles through a set of audio files.

This sample shows how to swap source filters in a filter graph. When the application begins, it renders the first audio file in the sequence and sets a timer. Whenever the timer goes off, the application removes the source filter and replaces it with a source filter for the next file. The files are all of the same type, so there is no need to rebuild the entire graph.

Path

Source: (SDK root)Samples\C++\DirectShow\Players\BGMusic

Executable: (SDK root)\Samples\C++\DirectShow\Bin\BGMusic.exe


CutScene Sample

Description

The CutScene sample plays a video file in full-screen mode until the user types ESC, ENTER, or the space bar.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\CutScene

Executable: (SDK root)\Samples\C++\DirectShow\Bin\CutScene.exe

User's Guide

Run this sample from the command line, with the name of a video file as a command-line argument.


DDrawXCL Sample

Description

This sample demonstrates how to play video in DirectDraw exclusive full-screen mode, using the IDDrawExclModeVideo interface on the Overlay Mixer filter.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\DDrawXCL

Executable: (SDK root)\Samples\C++\DirectShow\Bin\DDrawXCL.exe


Jukebox Sample

Description

The Jukebox sample is a video jukebox application.

This application scans a directory for media files and displays a list of the file names. The user can play an individual file or play all of the files in order. The jukebox also displays information about the filter graphs that it creates, including the names of the filters, the names of the pins, and the event codes that are generated.

Note This sample requires Microsoft Foundation Class Library 4.2 (Mfc42.dll).

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\Jukebox

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Jukebox.exe

User's Guide

If a directory name is specified as a command-line argument, the jukebox scans that directory at start-up. Otherwise, it scans the default SDK media directory, which is located at Multimedia\Media under the SDK root directory. The jukebox displays a list of all the media files in the directory, from which the user can select a file to play. To can scan a different directory, type the path name into the edit box and click the Set Media Directory button.

The jukebox offers the following user-interface elements:

  • Play, Stop, Pause, and FrameStep buttons: Use these buttons to control graph playback. (The FrameStep button might be disabled, if the graph does not support IVideoFrameStep.)
  • Thru and Loop buttons: Click the Thru button to play through the entire file list, starting from the current selection. Click the Loop button to loop the same file repeatedly. These two buttons are mutually exclusive.
  • Mute button: Mutes the audio.
  • Filters, Input Pins, and Output Pins: When the jukebox creates a graph, it displays a list of the filters in the graph. If the user selects one of the filter names, the jukebox displays a list of the filter's input pins and a list of the filter's output pins.
  • Display Events: If this box is checked, the jukebox displays the event codes that it receives. To clear the list, click the Clear button.
  • Filter Properties button: To view a filter's property pages, select the filter name and click the this button. If the filter does not support property pages, the button is disabled.


JukeboxASF Sample

Note: In DirectX 9.0, this sample has been removed, and Windows Media™ support has been added to the Jukebox sample.

Description

This sample is a version of the Jukebox Sample that plays Microsoft® Windows Media™ files that are not protected by Digital Rights Management (DRM).

To build this sample, you must install the Windows Media Format SDK and obtain a software certificate. After you obtain the software certificate, build the sample by linking two additional libraries: WMStub.lib and WMVCore.lib.

Note This sample requires Microsoft Foundation Class Library 4.2 (Mfc42.dll).

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\JukeboxASF


PlayDMO Sample

Description

PlayDMO is a player application that demonstrates how to use DirectX Media Objects (DMOs) in DirectShow. It enables the user to open any media file, apply any number of DMO audio effects to its audio stream (if any), and play the file.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\PlayDMO

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\PlayDMO.exe

User's Guide

Select a media file by typing its name in the edit box and clicking Browse For Media. Then select one or more audio effects from the Audio Effects DMOs list box. Click Apply to rebuild the filter graph with the selected DMOs. Click Play to rebuild the filter graph and play the file.

The Filters/DMOs In Graph list box displays all of the filters and DMOs in the filter graph. (The DMOs are managed by the DMO Wrapper Filter.) If you select one of these, the application displays the names of the pins. If you select a DMO while the graph is playing, the application also displays additional information about the DMO. If you select a filter or DMO that supports property pages, the application enables the Filter Properties button. Click this button to set the properties.

Note Because the application rebuilds the filter graph when you click Play, wait until the graph is playing to set the properties. Otherwise, you will lose your settings.

See Also

  • DMO Samples


PlayWnd Sample

Description

PlayWnd is a simple media player application.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\PlayWnd

Executable: (SDK root)\Samples\C++\DirectShow\Bin\PlayWnd.exe

User's Guide

The playback file can be specified as a command-line argument. Otherwise, the application displays an Open File dialog box on start-up. The selected file automatically begins playing.

If the media contains video, the player resizes its client area to the video's preferred size. If the media contains no video, only audio, the player displays a small default window.

The player supports the following keyboard commands:

  • To mute the audio, press the M key.
  • To toggle between full-screen mode and window mode, press the F key.
  • To pause or resume playback, press the P key.
  • To stop and seek to the start of the file, press the S key.
  • To close the file, press the ESC, F12, X, or Q key.


PlayWndASF Sample

Description

PlayWndASF is a version of the PlayWnd SamplePlayWndSample that plays Microsoft® Windows Media® files, including files that are protected by Digital Rights Management (DRM).

To build this sample, you must install the Windows Media Format SDK. If you install version 7.1 or earlier of that SDK, to support non-DRM playback only, you must link to the wmstub.lib and wmvcore.lib files that are provided with that SDK. If you use the Windows Media Format 9 Series SDK, no wmstub.lib file is required for non-DRM files.

To enable DRM support on all versions of the Windows Media Format SDK, you must obtain a unique DRM "stub library" from Microsoft. For more information, please visit the Microsoft Web site. For version 7.1 of the Windows Media Format SDK, use the DRM stub library instead of wmstub.lib. For the Windows Media Format 9 Series SDK, use the DRM stub library instead of wmvcore.lib.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\PlayWndASF

Executable: (SDK root)\Samples\C++\DirectShow\Bin\PlayWndASF.exe


StillView Sample

Description

StillView is a version of the Jukebox Sample that displays still images, including JPEG, GIF, bitmap, and Targa files.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\StillView

Executable: (SDK root)\Samples\C++\DirectShow\Bin\StillView.exe


Texture3D Sample

Description

Draws video on a Microsoft® Direct3D texture surface.

Note This sample does not support changing the display properties of the monitor while the sample is running.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\Texture3D

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Texture3D.exe


Texture3D9 Sample

Description

Draws video on a Microsoft DirectX 9.0 texture surface. This sample builds on the Direct3D Tutorial05 sample, adding support for rendering video onto a Direct3D9 surface.

Notes This sample does not support changing the display properties of the monitor while the sample is running.

Path

Source: (SDK root)\Samples\C++\DirectShow\Players\Texture3D9

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Texture3D9.exe


VBDemo Sample

Description

Simple media player application for Microsoft® Visual Basic®.

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\VBDemo


Video Control Samples

This topic applies to Windows XP only.

The Video Control is an Active X control available on Windows® XP only. It provides a simplified, Automation-compatible approach for creating analog and digital TV filter graphs. To create digital TV graphs with any of these applications, you must have a Broadcast Driver Architecture (BDA)-compatible ATSC or DVB tuner device and an HDTV-capable MPEG-2 decoder installed on the host system. Analog TV graphs can be created using any DirectShow-compatible TV device. See Using the Video Control for more information.

  • CPPVideoControl Sample
  • Video Control HTML Samples
  • VBVideoControl Sample


CPPVideoControl Sample

This topic applies to Windows XP only.

This sample demonstrates using the Microsoft Video Control in C++ to view ATSC digital television in a window. This is a simple ATL application that merely hosts the control and allows you to adjust the channel up or down.

When CPPVideoControl launches, it will look for an ATSC Network provider on your system. If a working tuner is found, CPPVideoControl builds the digital television filter graph, tunes to channel 46, and displays the broadcast signal. It may take several seconds to completely build the digital television filter graph, so please be patient.

Path

(SDK root)\Samples\Multimedia\DirectShow_WinXP\VideoControl\CPP


Video Control HTML Samples

This topic applies to Windows XP only.

These HTML samples demonstrate using the Microsoft Video Control to view ATSC digital, DVB digital, or analog television in a Windows XP browser window.

Path

(SDK root)\Samples\Multimedia\DirectShow_WinXP\VideoControl\HTML


VBVideoControl Sample

This topic applies to Windows XP only.

This sample demonstrates using the Microsoft Video Control in Visual Basic to view analog or digital television in a window.

When VBVideoControl launches, it presents you with a list of network providers. Choose a network provider that is available in your area (such as ATSC Digital Antenna TV) and click the Power On button. VBVideoControl will attempt to build a filter graph with the selected network provider. If successful, it will update the Visual Basic form to display additional buttons, which you may use to change channels, adjust volume, display device information, and select tuners. You may click Power Off to clear the form and select another tuner.

Note It may take several seconds to completely build the digital television filter graph, so please be patient.

Path

(SDK root)\Samples\Multimedia\DirectShow_WinXP\VideoControl\VisualBasic


Video Editing Samples

The Microsoft® DirectShow® SDK includes the following sample applications related to video editing.

C++ Applications

  • GrabBitmaps
  • SampGrabCB Sample
  • StillCap Sample
  • Timeline Test Sample
  • TransViewer Sample
  • XTLTest Sample

Visual Basic Applications

  • DexterVB Sample
  • SlideShowVB Sample
  • TrimmerVB Sample
  • XTLTestVB Sample


CompressView Sample

Description

The CompressView sample shows how recompress a video file. When the application starts, it enumerates the video compressors on the system and presents them in a list box. The user specifies an input file, an output file name, and a video compressor. The application reads the file, recompresses the video, and writes the result to an AVI file.

Some compressors cannot be used if they have Digital Rights Management (DRM) built into them, or if the compressor does not function in the expected manner.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\CompressView\

Executable: (SDK root)\Samples\C++\DirectShow\Bin\CompressView.exe

See Also

  • Recompressing an AVI File


GrabBitmaps Sample

Description

This C++ console application shows how to use the Sample Grabber filter to capture frames from a video file.

GrabBitmaps performs the following steps:

  • Opens a specified AVI file
  • Creates a filter graph with a sample grabber filter
  • Reads five frames at approximately one-second intervals
  • Writes the frames to bitmap (.BMP) files in the current directory

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\GrabBitmaps\

Usage

From the command line, type:

GrabBitmaps <filename>

Sample Output

Grabbing bitmaps from c:\movie.avi.
Found a sample at time 0 ms     [Bitmap00000.bmp]
Found a sample at time 998 ms   [Bitmap00998.bmp]
Found a sample at time 1996 ms  [Bitmap01996.bmp]
Found a sample at time 2994 ms  [Bitmap02994.bmp]
Found a sample at time 3992 ms  [Bitmap03992.bmp]
Sample grabbing complete.

See Also

  • Using the Sample Grabber


SampGrabCB Sample

Description

The SampGrabCB displays information about media samples as they move through the filter graph.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\SampGrabCB

User's Guide

This console application uses the IMediaDet interface to create a filter graph that contains the Sample Grabber filter. The application uses a callback function to retrieve samples from the video file.

Usage

From the command line, type:

SampGrabCB Filename

Sample Output

Grabbing samples from c:\Example.avi.Sample received = 00000  Clock = 158153069  Length=129600Sample received = 00001  Clock = 158153076  Length=129600Sample received = 00002  Clock = 158153076  Length=129600Sample received = 00003  Clock = 158153076  Length=129600Sample received = 00004  Clock = 158153077  Length=129600


StillCap Sample

Description

Video capture application that writes still images to bitmap files.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\StillCap

Executable: (SDK root)\Samples\C++\DirectShow\Bin\StillCap.exe

User's Guide

This application uses the ISampleGrabber interface to capture still images from a live capture stream to a bitmap file. It demonstrates how to put the Sample Grabber filter into a filter graph, and how to retrieve sample data in real time through a callback function.

The application builds a capture graph using the first video capture device it finds. To capture a still image, click the Snap Still button. By default, the bitmap is saved with the file name StillCap0000.bmp. If you select the check box labeled Increment filename after each capture?, the application saves each image under a new file name. Otherwise, the previous image is overwritten when you capture a new image.

This application also can capture video files. Click Video Capture in the Capture Type area; video capture starts automatically. To end the capture session, click Start Playback. The recorded file automatically plays back.

For simplicity, this sample uses 24-bit RGB format. If your video driver is set to 16-bit color, you might notice flicker when the application runs. To resolve this problem, set the bit depth of your display to 24 bits or 32 bits.


Timeline Test Sample

Description

This sample application builds a timeline with a transition. It demonstrates the following tasks in DirectShow Editing Services:

  • Creating a timeline.
  • Adding tracks, sources, transitions, and effects to the timeline.
  • Adding a SMPTE Wipe Transition.
  • Creating an audio crossfade using the Volume Envelope effect.
  • Setting properties on timeline objects.
  • Modifying a timeline and rendering the filter graph again.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\TimelineTest\


TransViewer Sample

Description

This sample application demonstrates video transitions using DirectShow Editing Services.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\TransViewer\

Executable: (SDK root)\Samples\C++\DirectShow\Bin\TransViewer.exe

User's Guide

When the application starts, it enumerates the available video transitions and displays them in a list. Select the transition you wish to view and click Preview. You can also select the video clips for the start and end of the transition, or use solid colors.

To set properties on a transition, select the transition from the list and click Properties. The application provides custom dialogs for the following transitions:

  • DxtCompositior Class: Compositor Transition
  • DxtJpeg Class: SMPTE Wipe Transition
  • DxtKey Class: Key Transition

For any other transitions, the application displays a generic dialog. You can use this dialog to set any IDispatch properties that the transition supports. For information about the transitions provided with Microsoft® Internet Explorer, see Visual Filters and Transitions Reference.

If you set properties on a transition and then select another transition, the application discards the properties.


XTLTest Sample

Description

The XTLTest sample is a command-line tool for rendering and previewing video editing projects. This tool renders DirectShow Editing Services (DES) project files.

To enable ASF support in this application, link the project to a Microsoft® Windows Media™ Format (WMF) SDK certificate and define USE_WMF_CERT when you compile the application. See the WMF SDK documentation for instructions on obtaining a certificate.

The DirectShow SDK includes several sample project files. These are located in the Samples\Media folder, and have the file name extension .xtl.

Note This application requires Internet Explorer 4.0 or later. If it is not present, the application displays the following error message: Unexpected error - DShow not installed correctly. For more information, see IXml2Dex.

Path

Source: (SDK root)\Samples\C++\DirectShow\Editing\Xtltest

User's Guide

This sample application demonstrates the following tasks related to video editing:

  • Previewing timelines and writing the rendered output to a file.
  • Setting timeline options when rendering timelines.

Usage

xtltest.exe [switches] input.xtl

By default, the application previews the project. The following command-line switches are supported.

Switch | Description
/C | No clock. Render the project as quickly as possible, without synchronizing audio and video.
/D | Load source files dynamically. For more information, see IRenderEngine::SetDynamicReconnectLevel.
/[double-double] | Set the rendering start and stop times. For example, /[3-4] renders one second of the timeline, starting 3 seconds into the project.
/G filename.grf | Output a GraphEdit file in .grf format.
/N | No rendering. The project is not previewed or rendered to a file. This option is useful for validating the input file, or with the /G switch.
/P [number] | Choose an ASF compression profile. Available only if the application is compiled with a WMF SDK certificate.
/P | List available ASF profiles. Available only if the application is compiled with a WMF SDK certificate.
/R | Activate smart recompression. The application uses the first clip in the timeline for the compression format. Use the /W switch with this option. For more information, see About the Render Engines.
/W filename | Render the timeline to a file. The file type is determined by the file extension. The application supports AVI and WAV files. If the application is compiled with a WMF SDK certificate, it also supports ASF files. This option suppresses preview.
/X filename.xtl | Save the project as an XML file. The new file is functionally identical to the input file, although the XML tags may differ.

Programming Notes

This sample demonstrates all of the steps required to read an XML project file, and then preview it or output it to a file.

For smart recompression, the application uses the format of the first non-muted source in the timeline. (It will fail if the first souce is an audio file.) The GetFirstSourceOnTimeline function retrieves the first non-muted source. This function demonstrates how to traverse the objects in a timeline. The GetSourceVideoType function retrieves the media type of the first video stream in a source. The application uses this media type when it calls IAMTimelineGroup::SetSmartRecompressFormat to set the recompression format. For more information, see Rendering a Project.

To handle error logging, the application defines a custom class, CErrorReporter. The class exposes the IAMErrorLog interface; however, it is not a true COM object, because it does not correctly handle reference counting. Therefore, the application must create it statically. For more information, see Logging Errors.

If USE_WMF_CERT is defined, the application includes support for writing WMF files. The CKeyProvider class implements the IServiceProvider interface. It calls the WMCreateCertificate function to create the WMF certificates. The helper function ListWMSDKProfiles lists the standard profiles that the WMF SDK provides. For more information, see Windows Media Applications and the Windows Media Format SDK.

Note If you install the Windows Media 9 Series Format SDK, make sure to compile the DirectX 9.0 version of this sample. Earlier versions of this sample are not compatible with the Windows Media 9 Series Format SDK.

See Also

  • XTL Reference


DexterVB Sample

Description

Video editing application for Microsoft® Visual Basic®.

This sample application is a graphical tool for creating DirectShow Editing Services timelines. It demonstrates the following tasks:

  • Loading and saving XTL project files
  • Adding, editing, and deleting timeline objects
  • Previewing a timeline

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\Editing\DexterVB

User's Guide

The following illustration shows the DexterVB application window.

DexterVB User Interface

The left pane displays a tree-view control that contains the timeline. The right pane displays information about the timeline. To view information about an object in the timeline, select the object's icon in the tree view.

To create a new timeline, choose New from the File menu. To open a project file, choose Open from the File menu. To save the current timeline to a project file, choose Save As from the File menu.

To modify the timeline, or any of the objects in the timeline, right-click the corresponding icon in the left pane. DexterVB displays a pop-up menu for that object. The following illustration shows the pop-up menu for the timeline.

Timeline Pop-Up Menu

For each object, the pop-up menu contains only the commands that apply to that object. The following commands are supported:

  • Add (Object Type): Inserts a new child of the specified type.
  • Collapse: Collapses the tree-view node for this object.
  • Delete: Removes the object from the timeline.
  • Edit: Enables the user to edit properties on the object.
  • Expand: Expands the tree-view node for this object.

The following commands are specific to the timeline itself:

  • Clear Render Engine: Deletes the filter graph.
  • Insert Group: Inserts a new group into the timeline.
  • Play: Previews the project. The user must render the timeline first.
  • Pause: Pauses preview.
  • Render Timeline: Builds a preview graph from this timeline.
  • Stop: Stops preview.


SlideShowVB Sample

Description

Microsoft® Visual Basic® application that creates a slide show from a series of video clips or image files.

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\Editing\SlideShowVB

User's Guide

This sample application demonstrates the following tasks:

  • Using the MediaDet object to obtain a poster frame from a source clip.
  • Saving a timeline as an XTL file.
  • Writing a timeline to an AVI file.
  • Loading media clips.

To use this application, do the following:

  • Drag video files or image files from your computer to the cells in the application window, starting from the cell in the upper-left corner.
  • Enter the length of time that each clip should play, in seconds.
  • Select a transition, using the combo box. The transitions have a fixed two-second duration.
  • To preview the slide show, click Play.
  • To save the slide show as an XTL project, click Write XTL.
  • To save the slide show as an AVI file, click Write AVI.


TrimmerVB Sample

Description

Microsoft® Visual Basic® application that trims a source clip and writes the trimmed clip to a new file.

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\Editing\TrimmerVB

User's Guide

This application enables the user to open a video source file, trim a desired amount from the front and the end of the clip, and then save the remaining portion to a new file.

To use this application, do the following:

  1. To choose a source file, click the Browse button. The first frame of the clip appears in all three preview areas.
  2. To select the start position, move the slider or click the frame step buttons. The preview frame in the Current Video Frame area is updated.
  3. To set the start position, click the Set Trim Preview Start Position button. The poster frame in Video Start Frame area is updated.
  4. To select the stop position, move the slider or click the frame step buttons.
  5. To set the stop position, click the Set Trim Preview Stop Position button. The poster frame in the Video Stop Frame area is updated.
  6. To write the new file, click the Write button. Wait for the progress indicator to complete.
  7. To view the new file, click the Playback button.


XTLTestVB Sample

Description

Microsoft® Visual Basic® application that previews video editing project files.

To use this application, drag a DirectShow Editing Services XTL file to the application window. The DirectShow SDK includes several sample project files. These are located in the Samples\Media folder, and have the file name extension .xtl.

Path

Source: (SDK root)\Extras\DirectShow\VB Samples\Editing\XTLTestVB

See Also

  • XTL Reference


Video Mixing Renderer Samples

The Microsoft® DirectShow® SDK includes the following sample applications for the Video Mixing Renderer (VMR) filter. Samples are provided for both the VMR-7 and the VMR-9. The VMR-7 samples require Windows XP.

VMR-7 and VMR-9

  • Blender Sample
  • MonitorInfo Sample
  • Pip Sample
  • Text Sample
  • Ticker Sample
  • VMRPlayer Sample
  • Watermark Sample
  • Windowless Sample

VMR-7 Only

  • Cube Sample
  • Renderless Sample
  • TxtPlayer Sample
  • VMRMix Sample
  • VMRMulti Sample
  • VMRXcl Sample
  • VMRXclBasic

VMR-9 Only

  • BitmapMix
  • MultiVMR9
  • VMR9Allocator


BitmapMix Sample

This sample is an interactive video player that uses the Windowless mode of the Video Mixing Renderer 9 filter to blend an animated alpha-blended bitmap with a running video onto a Direct3D surface.

Source: (SDK root)\Samples\C++\DirectShow\VMR9\BitmapMix

Executable: (SDK root)\Samples\C++\DirectShow\Bin\BitmapMix.exe

See Also

  • Video Mixing Renderer Filter 9


Blender Sample

Description

This sample uses the Video Mixing Renderer to blend multiple video streams. It demonstrates how to mix video streams in windowless mode.

The application mixes two video files selected by the user. You can manipulate the X, Y, width, height, and alpha blending values for each video stream. You can also flip or mirror each video stream by clicking its associated check box. Alpha values are set by default to allow both streams to be partially visible.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Blender

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Blender.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Blender

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Blender9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


Cube Sample

This topic applies to Windows XP only.

Description

This sample demonstrates using the Video Mixing Renderer 7 (VMR-7) and a plug-in compositor to render video on a spinning cube.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR\Cube

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Cube.exe

See Also

  • Using the Video Mixing Renderer


MonitorInfo Sample

Description

This sample enumerates the monitors on the user's system and displays information about each, including the dimensions, flags, handle, name, and optional description field. This sample demonstrates the IVMRMonitorConfig and IVMRMonitorConfig9 interfaces on the Video Mixing Renderer filter.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\MonitorInfo

Executable: (SDK root)\Samples\C++\DirectShow\Bin\MonitorInfo.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\MonitorInfo

Executable: (SDK root)\Samples\C++\DirectShow\Bin\MonitorInfo9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


MultiVMR9 Sample

This sample set demonstrates using a custom VMR9 allocator-presenter in a multi-graph environment. There are three sample folders:

  • DLL: Helper library which demonstrates how to implement a user-provided (customized) allocator-presenter for the Video Mixing Renderer 9 in a multi-graph environment.
  • MultiPlayer: Allows you to load and control multiple media files. You can seek each stream and control its position, FPS, aspect ratio, Z order, and alpha value.
  • GamePlayer: Illustrates how to integrate video powered by VMR9 into a Direct3D environment such as a 3D game.


Pip Sample

Description

This sample uses the Video Mixing Renderer to blend multiple video streams. It demonstrates how to mix video streams in windowless mode.

After loading two media files, you can use the keyboard and function keys to move and resize the secondary media stream. You can also flip, mirror, and swap the streams, with or without an animation effect.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Pip

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Pip.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Pip

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Pip9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


Renderless Sample

This topic applies to Windows XP only.

Description

This sample demonstrates using the Video Mixing Renderer Filter 7 (VMR-7) and a custom allocator-presenter to render video in a window.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR\Renderless

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Renderless.exe

See Also

  • VMR Renderless Playback Mode (Custom Allocator-Presenters)


Text Sample

Description

This sample uses the Video Mixing Renderer to blend video and text. It uses the IVMRMixerBitmap (or IVMRMixerBitmap9) interface to blend text onto the bottom portion of the video window.

The text is drawn onto a bitmap, which is then blended with the video. The text string updates automatically every two seconds, or you can advance the text by pressing the space bar. To adjust the font of the text, choose Set font... from the Text menu.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Text

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Text.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Text

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Text9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


Ticker Sample

Description

This sample uses the Video Mixing Renderer to blend video and text. It uses the IVMRMixerBitmap (or IVMRMixerBitmap9) interface to blend text onto the bottom portion of the video window.

The application creates a bitmap with a default text string and scrolls it across the bottom of the screen. To change the text, choose Set text string... from the Ticker menu. To set the font, choose Set font... from the Ticker menu. If you select Use static image from the Ticker menu, the application switches from a dynamic text string to a a static bitmap image.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Ticker

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Ticker.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Ticker

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Ticker9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


TxtPlayer Sample

This topic applies to Windows XP only.

Description

This sample demonstrates using the Video Mixing Renderer Filter 7 (VMR-7) and a custom allocator-presenter to render alpha-blended text over a running video.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR\TxtPlayer

Executable: (SDK root)\Samples\C++\DirectShow\Bin\TxtPlayer.exe

See Also

  • Supplying a Custom Allocator-Presenter for VMR-7


VMR9Allocator Sample

This sample shows how to implement a custom allocator-presenter for the VMR-9.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR9\VMR9Allocator

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMR9Allocator.exe


VMRMix Sample

This topic applies to Windows XP only.

Description

This sample demonstrates using the Video Mixing Renderer Filter 7 (VMR-7) in mixing mode. The application shows how to mix several video sources, alpha blend a static bitmap, and manage the source and destination rectangles for each video stream.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR\VMRMix

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRMix.exe

User's Guide

When the application starts, it prompts you to specify a directory that contains at least two video files. You can also specify various playback options, including the number of video streams to mix, the size of the playback window, and whether to display a static bitmap.

To start playback, click the Play button. Playback continues until the end of the longest file, or until you close the playback window.

Troubleshooting

This application was originally created as a stress test, so it can use significant system resources. If video playback is slow or freezes, try selecting fewer sources and turning off the option for full-screen mode.


VMRMulti Sample

This topic applies to Windows XP only.

Description

This sample uses the Video Mixing Renderer Filter 7 (VMR-7) to play multiple video files over a Direct3D background. The application uses separate filter graphs for each media files. The graphs can be controlled individually.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR\VMRMulti

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRMulti.exe

See Also

  • MultiVMR9 Sample


VMRPlayer Sample

Description

This sample uses the Video Mixing Renderer filter to alpha blend one or two running videos and a static image.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\VMRPlayer

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRPlayer.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\VMRPlayer

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRPlayer9.exe

User Guide's

To open the first video, choose Open Primary Stream from the File menu. To open a second video, choose Open Secondary Stream from the File menu (you must open the primary stream first). To play the video, click the Play button.

You can set the position, size, and alpha values of the videos by selecting Primary Stream or Secondard Stream from the VMR Properties menu.

To add a static bitmap over the video, choose Static App Image from the VMR Properties menu and click the Display App Image box. You can use the same dialog to control the position, size, and alpha value of the bitmap.

To capture the blended video image, choose Capture Bitmap Image from the VMR Properies menu.

You can also specify the primary image stream from the command line:

VMRPlayer /P filename

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


VMRXcl Sample

This topic applies to Windows XP only.

Description

This sample demonstrates how to use the Video Mixing Renderer Filter 7 (VMR-7) in DirectDraw exclusive mode and how to implement a custom allocator-presenter for the VMR. It also contains useful utilities to manage bitmaps as textures and TrueType fonts for text over video.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR9\VMRXcl

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRXcl.exe

See Also

  • DirectDraw Exclusive Mode
  • VMRXclBasic Sample


VMRXclBasic Sample

This topic applies to Windows XP only.

Description

This sample is a simpler version of the VMRXcl sample.

Path

Source: (SDK root)\Samples\C++\DirectShow\VMR9\VMRXclBasic

Executable: (SDK root)\Samples\C++\DirectShow\Bin\VMRXclBasic.exe


Watermark Sample

Description

This sample uses the Video Mixing Renderer to blend a bitmap onto a video stream. While the application is running, you can apply various effects to the watermark, including flip, mirror, animation, slide, and strobe. Animation is accomplished by cycling through a series of different bitmaps. The strobe effect uses alpha blending.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Watermark

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Watermark.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Watermark

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Watermark.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


Windowless Sample

Description

This sample demonstrates windowless mode in the Video Mixing Renderer filter. The application is similar to the PlayWnd sample.

You can capture the image from the video widow by right-clicking on the image, or by selecting Capture Current Frame from the Image menu.

Two versions of this sample are available, one for the VMR-7 and one for the VMR-9.

VMR-7

Source: (SDK root)\Samples\C++\DirectShow\VMR\Windowless

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Windowless.exe

VMR-9

Source: (SDK root)\Samples\C++\DirectShow\VMR9\Windowless

Executable: (SDK root)\Samples\C++\DirectShow\Bin\Windowless9.exe

See Also

  • Video Mixing Renderer Filter 7
  • Video Mixing Renderer Filter 9


DirectShow Reference

This section contains reference information for the core Microsoft® DirectShow® APIs and filters.

  • DirectShow Filters
  • Interfaces
  • DirectShow Structures
  • DirectShow Enumerated Types
  • Constants and GUIDs
  • Functions
  • MSWebDVD ActiveX Control
  • Property Sets
  • DirectShow Objects
  • DirectShow Base Classes


DirectShow Filters

DirectShow provides a set of default filters that install automatically with Microsoft® Windows®. These filters support many data formats while providing a high degree of hardware independence. An application can also register and install custom filters on the target system.

The ACM Wrapper, AVI Decompressor and AVI Compressor filters work with the Audio and Video Compression Managers to enable various codecs to be used in a DirectShow filter graph.

All the filters supported by the DirectShow Software Development Kit (SDK) are listed here. If a filter appears in GraphEdit but is not documented in this reference section, it means the filter has either been installed by a third party or else is used internally by some other Microsoft technology such as Windows Media™ Player or TAPI. Such filters are not supported by the DirectShow SDK.

Filter | Description
ACM Wrapper | Enables Audio Compression Manager (ACM) codecs to join a filter graph.
Analog Video Crossbar | Represents a video crossbar on a video capture device that supports the Windows Driver Model (WDM).
Audio Capture | Represents an audio capture device.
Audio Renderer (WaveOut) | Uses the waveOut* APIs to render waveform audio.
AVI Compressor | Enables Video Compression Manager (VCM) compressors to join a filter graph.
AVI Decompressor | Enables Video Compression Manager (VCM) decompressors to join a filter graph.
AVI Draw | Pulled automatically into a playback graph instead of the AVI Decompressor when video is being output to an external NTSC television monitor.
AVI Mux | Accepts multiple input streams and interleaves them into AVI format.
AVI Splitter | Splits audio and video streams in playback of AVI files.
BDA IP Sink | Delivers IP data to Winsock in BDA as well as non-BDA filter graphs.
BDA MPE Filter | Extracts the IP packets from the MPE frames and delivers them to BDA IP Sink and ultimately on to Winsock.
BDA MPEG-2 Transport Information Filter | Parses MPEG-2 DVB and ATSC tables and provides the information to the Network Provider.
BDA Network Provider | Source filter in all BDA filter graphs.
BDA SLIP Deframer | Used in either BDA or non-BDA analog television graphs where SLIP de-framing of IP data is required.
CC Decoder | Accepts sample waveforms delivered by a capture filter and delivers decoded closed-captioning data.
Color Space Converter | Converts from one RGB color type to another RGB type.
DirectSound Renderer | Renders audio using the Microsoft® DirectSound® API.
DMO Wrapper | Enables a DirectShow application to use a Microsoft® DirectX® Media Object (DMO) within a filter graph.
DV Muxer | Combines a digital video (DV)–encoded video stream with one or two audio streams to produce an interleaved DV stream.
DV Splitter | Splits an interleaved digital video (DV) stream into its component video and audio streams.
DV Video Decoder | Decodes a digital video (DV) stream into uncompressed video.
DV Video Encoder | Encodes an uncompressed video stream into digital video (DV).
DVD Navigator | Opens all necessary files in a DVD-Video volume, navigates through the linear DVD-Video .vob files, and parses the resulting MPEG-2 program stream.
File Source (Async) | Opens and reads local files of many different data formats and passes the data to a parser filter.
File Source (URL) | Works with any source file that can be identified by a Uniform Resource Locator (URL) and whose media major type is stream.
File Stream Renderer | Renders file names that are parsed by the Multi-File Parser filter.
File Writer | Used to write files to disc regardless of format.
Full Screen Renderer | Uses Microsoft® DirectDraw® to render full-screen video on older graphics cards.
Infinite Pin Tee | Delivers samples delivered to its input pin to a variable number of output pins.
Internal Script Command Renderer | Receives script commands and dispatches them to the application.
Line 21 Decoder | Converts line-21 closed caption information to bitmaps with caption text.
MIDI Parser | Reads MIDI data that is found in .MID and .RMI files.
MIDI Renderer | Renders MIDI data from the MIDI Parser filter.
MJPEG Compressor | Compresses an uncompressed video stream, using motion JPEG compression.
MJPEG Decompressor | Decodes a video stream from motion JPEG to uncompressed video.
MPEG-1 Audio Decoder | Decodes MPEG-1 Layer I and Layer II audio to PCM.
MPEG-1 Stream Splitter | Splits an MPEG-1 system stream into its component audio and video streams.
MPEG-1 Video Decoder | Decodes MPEG-1 video.
MPEG-2 Demultiplexer | Demultiplexes MPEG-2 transport and program streams that are delivered in push-mode.
MPEG-2 Sections and Tables | Receives PSI tables from an MPEG-2 transport stream.
MPEG-2 Splitter | Parses MPEG-2 program streams, creates an output pin for each stream, and outputs the compressed audio and/or video MPEG packets to an MPEG-2 decoder filter.
MSDV Driver | The Microsoft® Windows® Driver Model (WDM) driver for DV camcorders.
MSTape Driver | Supports D-VHS and MPEG camcorder devices.
MSYUV Color Space Converter Codec | Enables playback of video source data in YUV formats on clients whose video display adapter cannot be used for YUV-to-RGB conversions in hardware.
Multi-File Parser | Parses a simple file format that enables multiple file names to be specified as though they were one file.
NABTS/FEC VBI Codec Filter | Processes captured VBI lines and distributes decoded and/or forward-error-corrected SLIP packets containing NABTS data downstream to the BDA SLIP Deframer, the BDA IP Sink and ultimately to Winsock.
Null Renderer | Discards every sample it receives, without displaying or rendering the sample data.
Overlay Mixer | Designed specifically for DVD playback and broadcast video streams with line-21 closed captioning. (Superseded by Video Mixing Renderer on Windows XP.)
Overlay Mixer 2 | Like the Overlay Mixer, but can be added to a filter graph automatically.
QT Decompressor | Decompresses Apple® QuickTime® 2.0 video.
QuickTime Movie Parser | Splits Apple® QuickTime® data into audio and video streams.
SAMI (CC) Parser | Parses captioning data from Synchronized Accessible Media Interchange (SAMI) files.
Sample Grabber | Provides a way to retrieve samples as they pass through the filter graph.
Smart Tee | Used in video capture graphs to split the video stream into a preview stream and a capture stream.
Tee/Sink-to-Sink Converter | Provides an efficient means to duplicate streams of data within kernel mode without the expensive transitions between kernel and user mode.
TV Audio | Provides control of television audio decoding, stereo or monoaural selection, and secondary audio program (SAP) selection.
TV Tuner | Selects an analog broadcast or cable channel to be viewed.
VBI Surface Allocator | Controls the allocation of VBI buffers in analog television graphs with hardware video port capture scenarios.
VFW Capture Filter | Works with older video capture hardware that uses Video For Windows.
VGA 16 Color Ditherer | Converts from an RGB color type to a 4-bit color display so that AVI and MPEG video streams may be displayed on older 16-color monitors.
Video Mixing Renderer Filter 7 (VMR-7) | The default video renderer in Windows XP. Offers advanced rendering and video mixing capabilities.
Video Mixing Renderer Filter 9 (VMR-9) | Similar to VMR-7 but available on all platforms supported by DirectX.
Video Port Manager | Enables the Video Mixing Renderer to work seamlessly on systems where video data is transferred directly from a video capture device or hardware decoder to the graphics chip.
Video Renderer | Default video renderer on Windows 98SE, Windows 2000, and Windows Millennium Edition. Connects to any video transform filter that produces decompressed video data.
WAVE Parser | Parses WAV-format audio data from .wav, .au, or .aif files.
WDM Video Capture | Controls analog capture devices that use Windows Driver Model (WDM) drivers.
Windows Media Source Filter | Default source filter for playback of Windows Media and MPEG-4 content created using the Microsoft MPEG-4 Encoder. This is the source filter used by Windows Media™ Player 6.4.
WM ASF Reader | Source filter for file playback of Windows Media-based content and content created with any of the Microsoft MPEG-4 Encoder DMOs. Must be explicitly added to a filter graph. This filter is based on the Windows Media Format SDK.
WM ASF Writer | Accepts uncompressed input streams and creates ASF files containing either Windows Media streams or MPEG-4 streams using the Microsoft MPEG-4 Encoder DMO. This filter is based on the Windows Media Format SDK.
WST Codec | Decodes and/or duplicates the decoded and forward-error-corrected Teletext data for the WST Decoder filter.
WST Decoder | Accepts decoded World Standard Teletext data from the WST Codec and delivers the bitmaps to Pin 2 on the Overlay Mixer using fonts supplied by Microsoft.


ACM Wrapper Filter

The ACM Wrapper filter enables Audio Compression Manager (ACM) codecs to join a filter graph. It can act either as a decompression filter or as a compression filter.

As a decompression filter, the ACM Wrapper appears in the "DirectShow Filters" category (CLSID_LegacyAmFilterCategory) and has a merit of MERIT_NORMAL. The connection media type on the input pin determines which codec the filter uses. Typically, the application does not need to add the filter to the filter graph; it is pulled in automatically by the Filter Graph Manager when needed. Decompression is only to PCM audio.

As a compression filter, the ACM Wrapper appears in the "Audio Compressors" category (CLSID_AudioCompressorCategory) and has a merit of MERIT_DO_NOT_USE. Each codec appears as a separate instance. For compression, you cannot directly create the filter with CoCreateInstance. Instead, you must use the system device enumerator. For more information, see Using the System Device Enumerator.

Filter interfaces | IBaseFilter, IPersist, IPersistPropertyBag
Input pin media types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL, FORMAT_WaveFormatEx
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx.

Any combination of the following are possible:

  • Samples per second (kHz): 44.1, 22.05, 11.025, or 8.0.
  • Channels: Stereo or mono.
  • Bits per sample: 8 or 16.
Output pin interfaces | IAMStreamConfig, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_ACMWrapper
Property Page CLSID | No property page.
Executable | Quartz.dll
Merit | MERIT_NORMAL or MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory or CLSID_AudioCompressorCategory


Analog Video Crossbar Filter

The Analog Video Crossbar filter represents a video crossbar on a video capture device that supports the Windows Driver Model (WDM).

This filter is a wrapper filter for crossbars on WDM streaming devices. The filter's friendly name is taken from the device. Each output pin represents a hardware path for analog baseband video. One of the input pins comes from a TV Tuner (the TV Tuner Filter). Other input pins support video or audio streams. The filter supports any media subtypes and formats that are supported on the downstream connections.

You cannot directly create this filter with CoCreateInstance. The ICaptureGraphBuilder2 interface automatically adds this filter to the graph as needed.

For more information on wrapper filters and WDM streaming devices, see How Hardware Devices Participate in the Filter Graph.

Filter Interfaces | IAMCrossbar, ISpecifyPropertyPages, IPersistPropertyBag, IPersistStream
Input Pin Media Types | MEDIATYPE_AnalogAudio, MEDIATYPE_AnalogVideo
Input Pin Interfaces | IKsPropertySet
Output Pin Media Types | MEDIATYPE_AnalogAudio, MEDIATYPE_AnalogVideo
Output Pin Interfaces | IKsPropertySet
Filter CLSID | Not applicable
Property Page CLSID | CLSID_CrossbarFilterPropertyPage
Executable | ksxbar.ax
Merit | Driver-dependent.
Filter Category | AM_KSCATEGORY_CROSSBAR

See Also

  • Working with Crossbars


Audio Capture Filter

The Audio Capture filter represents an audio capture device. It has one capture output pin and several input pins (one for each type of input on the card, such as Line In, Mic, CD, and MIDI).

This filter can work with more than one hardware device, so calling CoCreateInstance to create the filter does not work. Instead, use the System Device Enumerator. The System Device Enumerator returns a unique moniker for each device. The moniker's friendly name corresponds to the name of the device. (This is the name that appears in GraphEdit.) For more information, see Enumerating Devices and Filters.

Filter Interfaces | IAMAudioInputMixer, IAMFilterMiscFlags, IAMResourceControl, IBaseFilter, IPersistPropertyBag, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_AnalogAudio, MEDIASUBTYPE_NULL
Input Pin Interfaces | IAMAudioInputMixer, IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMBufferNegotiation, IAMPushSource, IAMStreamConfig, IAMStreamControl, IKsPropertySet, IPin, IQualityControl
Filter CLSID | Not applicable
Property Page CLSID | CLSID_AudioInputMixerProperties
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_AudioInputDeviceCategory

Remarks

The input pins represent physical hardware connections and are never connected to other filters in DirectShow.

See Also

  • Audio Capture


Audio Renderer (WaveOut) Filter

This filter uses the waveOut* API to render waveform audio. However, the DirectSound Renderer Filter provides the same functionality using Microsoft® DirectSound®. By default, the Filter Graph Manager uses the DirectSound Renderer instead of this filter. Audio mixing is disabled in the waveOut Audio Renderer, so if you need to mix multiple audio streams during playback, use the DirectSound renderer.

This filter does not check the audio stream's subtype. The WAVEFORMAT or WAVEFORMATEX structure passed in the format contains the information needed for the connection.

This filter supports a range of sample rates that depends on the audio driver.

Filter Interfaces | IAMAudioRendererStats, IAMClockSlave, IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IMediaPosition, IMediaSeeking, IPersistPropertyBag, IPersistStream, IQualityControl, IReferenceClock
Input Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_None
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_AudioRender
Property Page CLSID | CLSID_AudioProperties, CLSID_AudioRendererAdvancedProperties
Executable | quartz.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_AudioRendererCategory


AVI Compressor Filter

The AVI Compressor filter enables Video Compression Manager (VCM) codecs to join a filter graph. Each codec appears as a separate instance of the filter. You cannot directly create this filter with CoCreateInstance. Instead, you must use the system device enumerator. For more information, see Using the System Device Enumerator.

The filter's input pin connects to filters that output uncompressed video data, such as video capture filters or the AVI Splitter Filter. The filter's output pin typically connects to a MUX filter, such as the AVI Mux Filter.

If the codec supports an old-style VFW configuration dialog box or About dialog box, an application can display it using the IAMVfwCompressDialogs interface.

Note MPEG compressors are never implemented as VCM codecs, but only as native DirectShow filters.

Filter Interfaces | IAMVfwCompressDialogs, IBaseFilter, IPersistPropertyBag, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | Not applicable
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_VideoCompressorCategory


AVI Decompressor Filter

The AVI Decompressor filter enables Video Compression Manager (VCM) codecs to join a filter graph. The application does not need to add the filter to the filter graph; it is pulled in automatically by the Filter Graph Manager when needed.

When the Filter Graph Manager is building a graph to render an AVI file, it checks the FOURCC in the file's AVI header to determine whether the video stream is compressed. If it is, the Filter Graph Manager adds the AVI Decompressor, which then searches the registry for an installed decompressor that can handle the file.

Note MPEG decompressors are never implemented as VCM codecs, but only as native DirectShow filters.

On its upstream pin the AVI Decompressor typically connects to the AVI Splitter. On its output pin it typically connects to the Video Renderer or the AVI Mux Filter.

Filter Interfaces | IBaseFilter
Input Pin Media Types | Major type: MEDIATYPE_Video Subtype: Must correspond to the FOURCC code for the compression type. For more information, see FOURCC Codes. Format type: FORMAT_VideoInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_AVIDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory


AVI Draw Filter

The AVI Draw filter is pulled automatically into a playback graph instead of the AVI Decompressor when video is being output to an external NTSC television monitor.

Filter Interfaces | IBaseFilter
Input Pin Media Types Major Type: MEDIATYPE_Video

Subtypes:

  • MEDIASUBTYPE_MJPG
  • MEDIASUBTYPE_TVMJ
  • MEDIASUBTYPE_WAKE
  • MEDIASUBTYPE_CFCC
  • MEDIASUBTYPE_IJPG
  • MEDIASUBTYPE_Plum
  • MEDIASUBTYPE_DVCS
  • MEDIASUBTYPE_DVSD
  • MEDIASUBTYPE_MDVF
  • Format type: FORMAT_VideoInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IOverlayNotify, IPin, IQualityControl
Filter CLSID | CLSID_AVIDraw
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL + 100
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

Since the AVI Draw filter and the VFW Capture Filter both connect to the same hardware, they cannot be in the same filter graph.


AVI Mux Filter

The AVI Mux filter accepts multiple input streams and interleaves them into AVI format. The filter uses separate input pins for each input stream, and one output pin for the AVI stream.

Video capture or authoring applications can use this filter to save files to disk in AVI format. The filter is typically connected to the File Writer filter, but it can connect to any filter whose input pin supports the IStream and IMemInputPin interfaces.

Filter Interfaces | IBaseFilter, IConfigAviMux, IConfigInterleaving, IMediaSeeking, IPersistMediaPropertyBag, ISpecifyPropertyPages
Input Pin Media Types Any major type that corresponds to an old-style FOURCC, or MEDIATYPE_AUXLine21Data. (For more information, see FOURCCMap Class.)
  • If the major type is MEDIATYPE_Audio, the format must be FORMAT_WaveFormatEx.
  • If the major type is MEDIATYPE_Video, the format must be FORMAT_VideoInfo or FORMAT_DvInfo.
  • If the major type is MEDIATYPE_Interleaved, the format must be FORMAT_DvInfo.
Input Pin Interfaces | IAMStreamControl, IMemInputPin, IPin, IPropertyBag, IQualityControl
Output Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_Avi
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_AviDest
Property Page CLSID | CLSID_AviMuxProptyPage, CLSID_AviMuxProptyPage1
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The following remarks describe various aspects of the AVI Mux filter's functionality.

Pins

When the AVI Mux filter is created, it has one input pin. As each input pin is connected, the filter creates a new input pin.

Stream Properties

The input pins support the IPropertyBag interface for setting properties on individual streams. Currently, the following property is defined:

Property | Description
name | The name of the stream. This property is written as a 'strn' chunk.

If the filter is running or paused, the IPropertyBag::Write method returns VFW_E_WRONG_STATE.

Frame Rates

If the upstream filter does not specify a frame rate in the AvgTimePerFrame member of the VIDEOINFOHEADER structure, the AVI Mux uses the time stamps on the first video frame. The AVI file format does not support variable frame rates.

Dropped Frames

The AVI Mux filter calculates dropped frames based on each sample's media times, if available, or else the sample's time stamps. It writes a zero-length index entry for every dropped frame.

Stream Duration

In the AVI Mux filter's implementation of IMediaSeeking::GetDuration, the filter queries each upstream source filter's IMediaSeeking interface and returns the duration of the longest stream. If one of the upstream filters fails the Mux's QueryInterface call for IMediaSeeking or fails IMediaSeeking::GetDuration, then the AVI Mux passes that failure code back to your application but will still fill in the output parameter pDuration with the longest duration, if any was found. In this case, the value of pDuration is not necessarily the length of the longest input stream.

AVI 2.0 File Format Extensions

DirectShow currently supports the following AVI 2.0 file format extensions:

  • Increased AVI file size (greater than 1 GB)
  • Hierarchical indexing

For more information, see version 1.02 of the OpenDML AVI File Format Extensions published by the OpenDML AVI M-JPEG File Format Subcommittee, February 28, 1996.


AVI Splitter Filter

The AVI Splitter Filter is used for playback of AVI files. It accepts data in AVI format and splits it into its constitutent streams for further procecessing and/or rendering. This filter is typically connected to the Async File Source filter on its input pin, although it can connect to any filter that has an output pin that supports IAsyncReader.

Filter Interfaces | IAMMediaContent, IBaseFilter, IPersistMediaPropertyBag
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_Avi.
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | Typically MEDIATYPE_Video or MEDIATYPE_Audio. The exact type depends on the content of the file, whether the file is compressed, and what codec was used.
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IPropertyBag, IQualityControl
Filter CLSID | CLSID_AviSplitter
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The output pins support the IPropertyBag::Read method for reading properties from individual streams.

Currently, the following property is defined.

Property | Description
name | Returns the name of the stream, taken from the 'strn' chunk in the AVI file. If this chunk is absent, the Read method returns E_INVALIDARG.

The IPropertyBag::Write method returns E_FAIL. The AVI Mux filter supports IPropertyBag::Write for saving stream properties into an AVI file.


BDA IP Sink Filter

The BDA IP Sink filter is a kernel-mode filter that delivers IP data to Winsock. This filter can be used in television filter graphs, both analog and digital, and BDA or non-BDA.

In an analog graph, the input pin connects to the BDA SLIP Deframer. In a digital graph, the input pin connects to the BDA MPE Filter. The filter has an output pin, but it does not send any IP data through this pin; all IP data goes to Winsock.

The filter exposes the IBDA_IPSinkInfo interface.

BDA IP Sink appears in GraphEdit under the "BDA Rendering Filters" category. Because this is a kernel-mode filter, applications cannot create it directly. Instead, use the System Device Enumerator, as described in Enumerating Devices and Filters. Add the filter to the filter graph by calling the IFilterGraph::AddFilter method.

This filter poses a security risk on systems which have source routing enabled because it could allow a malicious broadcast stream to mount a denial of service attack by flooding a network with a large amount of IP data packets. For this reason, if source routing is enabled at any time on the host system, the BDA IP Sink filter will be automatically disabled. It will continue to exist in the graph, and it will be able to transition into the run state, but it will drop all packets without sending them to the NDIS stack. If source routing is then disabled, data indication to NDIS resumes after a brief lapse of time. The filter monitors the state of source routing by periodically examining the registry key HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\IPEnableRouter. If you require the BDA IP Sink filter to be enabled while source routing is enabled, please contact Microsoft Product Support Services to obtain special instructions.

See Also

  • Microsoft TV Technologies


BDA MPE Filter

Multi-Protocol Encapsulation (MPE) is the protocol by which IP data is transmitted over digital television networks. The BDA MPE Filter is a kernel-mode filter that extracts the IP packets from the MPE frames and delivers them to BDA IP Sink and ultimately on to Winsock, where interested applications can listen for and process the data. The BDA SLIP Deframer performs the same function on analog television graphs, where the SLIP framing protocol is used.

The BDA MPE Filter appears in GraphEdit under the "BDA Receiver Component" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder will not add the filter automatically.

See Also

  • Microsoft TV Technologies


BDA MPEG-2 Transport Information Filter

Digital TV transmissions multiplex many programs and their related elementary streams (such as audio, video, IP data) in a single transport stream. So that a receiver can properly acquire all the elementary streams related to a specific program and so that a receiver can tell what programs are contained in the stream, the transport stream will also contain many sets of tables that act as a catalog of information contained in the transport stream. Under direction of the BDA Network Provider, the MPEG-2 Demultiplexer delivers these tables to the Transport Information Filter. The Transport Information Filter then parses these tables and provides the information to the Network Provider so that it can control the other receiver filters in the graph.

This filter also provides COM interfaces that enable a Guide Store loader application to retrieve in-band EPG information.

Filter Interfaces | IBaseFilter, IConnectionPointContainer, IGuideData, ITuneRequestInfo
Input Pin Media Types Major type: MEDIATYPE_MPEG2_SECTIONS

Subtypes:

  • MEDIASUBTYPE_ATSC_SI
  • MEDIASUBTYPE_DVB_SI

Format type: None
Input Pin Interfaces | IPin
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | Not applicable
Merit | MERIT_NORMAL
Filter Category | KSCATEGORY_BDA_TRANSPORT_INFORMATION

Remarks

Currently, the IGuideData interface is available only for DVB broadcasts. For other types, the filter returns E_NOINTERFACE when queried for the interface.

This filter supports event notifications through the IGuideDataEvent connection point interface. To set up the event sink, use the IConnectionPointContainer interface on the filter.

See Also

  • Microsoft TV Technologies


BDA Network Provider Filter

The BDA Network Provider is the source filter for any digital television filter graph based on Microsoft Broadcast Driver Architecture (BDA). The following Network Provider filters are available:

Network Provider | CLSID
Microsoft ATSC Network Provider | CLSID_ATSCNetworkProvider
Microsoft DVB-C Network Provider | CLSID_DVBCNetworkProvider
Microsoft DVB-S Network Provider | CLSID_DVBSNetworkProvider
Microsoft DVB-T Network Provider | CLSID_DVBTNetworkProvider

The information in the following table applies to all of these filters:

Filter Interfaces | IBaseFilter, IBDA_EthernetFilter, IBDA_NetworkProvider, IBDA_TIF_REGISTRATION, IBDA_IPV4Filter, IBDA_IPV6Filter, IFrequencyMap, IMPEG2_TIF_CONTROL, IScanningTuner, ITuner
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | Major type: KSDATAFORMAT_TYPE_BDA_ANTENNA
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | See previous table.
Merit | MERIT_DO_NOT_USE
Filter Category | KSCATEGORY_BDA_NETWORK_PROVIDER

Remarks

The Network Provider acts as the default tuner in a BDA filter graph, by exposing the ITuner interface. No signals or data actually pass through this filter. It works closely with the Transport Information Filter (TIF) and the MPEG-2 Demultiplexer to acquire transport streams and route the elementary stream to the appropriate downstream filters.

If you are creating a digital TV graph manually (rather than using the Video Control), use CoCreateInstance and IFilterGraph::AddFilter to add this filter to the graph. The ICaptureGraphBuilder2 interface does not automatically add this filter to the graph.

See Also

  • Microsoft TV Technologies


BDA SLIP Deframer Filter

The BDA SLIP Deframer is a kernel-mode filter that can be used in either BDA or non-BDA analog television graphs where SLIP de-framing of IP data (such as that found on the NABTS VBI scan lines) is required. It connects upstream to the NABTS/FEC VBI Codec and downstream to BDA IP Sink, which makes the IP packets available to interested applications via Winsock. There are no application-callable interfaces on the BDA SLIP Deframer. In digital television graphs, the BDA MPE Filter is used to extract the IP packets from the data stream.

The SLIP Deframer can process compressed IP headers. With IP header compression, the sender removes redundant header information from successive IP packets and replaces it with a shorter token. Typically, the sender compresses three out of four packets on each IP address. If the receiver starts in the middle of a cycle, the filter may be unable to decode the first few packets, until it receives the full header. The sender should send data redundantly, or else avoid using IP header compression.

The BDA SLIP Deframer appears in GraphEdit under the "BDA Receiver Component" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder cannot be used to add this filter to the graph.

This filter does not expose any application-callable interfaces.

See Also

  • Microsoft TV Technologies


CC Decoder Filter

The CC VBI Decoder is a kernel-mode stream class filter. It appears in GraphEdit under the "WDM Streaming VBI Codecs" category. It accepts sample waveforms delivered by a capture filter and delivers decoded closed-captioning data to the Line 21 Decoder and/or to interested applications.

This filter has two input pins, VBI and HWCC. The VBI pin is used for raw VBI data, and the HWCC pin is used when the VBI decoding is performed in hardware by the capture filter. When the data is received on the HWCC pin, the CC Decoder operates in "pass-through" mode, and sends the data directly to the Line 21 Decoder without processing it in any way. If the capture filter exposes an HWCC pin, it must be connected directly to the corresponding pin on the CC Decoder. The pin category is PINNAME_VIDEO_CC_CAPTURE.

The CC Decoder has up to eight output pins, each of which can select their own lines and substreams. The first output pin is connected to the Line-21 Decoder.

The CC Decoder filter appears in the "WDM Streaming VBI Codecs" filter category (AM_KSCATEGORY_VBICODEC).

Because this is a kernel-mode filter, applications cannot create it directly using CoCreateInstance. Instead, use the System Device Enumerator. For more information, see Creating Kernel-Mode Filters.

See Also

  • Viewing Closed Captions


Color Space Converter Filter

This transform filter converts from one RGB color type to another RGB type, such as between 24-bit and 8-bit RGB color. Since this type of conversion is generally handled more efficiently within a video decompressor, the main use of the Color Space Converter is when the stream source consists of uncompressed RGB frames.

Filter Interfaces | IBaseFilter
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are valid:
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are valid:
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_Colour
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory


DirectSound Renderer Filter

This filter renders audio using the Microsoft® DirectSound® API. This filter is currently the default audio renderer for waveform sound.

In addition to its basic sound-rendering capabilities, this filter can process Microsoft® DirectSound® API calls. Use the IAMDirectSound methods to set and retrieve the window that will handle the sound playback. The DirectSound Audio Renderer is the default audio rendering filter for Microsoft® DirectShow®.

Filter Interfaces | IAMAudioRendererStats, IAMClockSlave, IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IDirectSound3DBuffer, IDirectSound3dListener, IMediaPosition, IMediaSeeking, IQualityControl, IReferenceClock
Input Pin Media Types Major Type: MEDIATYPE_Audio

Subtypes:

  • MEDIASUBTYPE_PCM
  • MEDIASUBTYPE_IEEE_FLOAT
  • MEDIASUBTYPE_DOLBY_AC3_SPDIF
  • MEDIASUBTYPE_RAW_SPORT
  • MEDIASUBTYPE_SPDIF_TAG_241h
  • MEDIASUBTYPE_DRM_Audio

Format type: FORMAT_WaveFormatEx
Input Pin Interfaces | IMemInputPin, IPin, IPinConnection, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_DSoundRender
Property Page CLSID | CLSID_AudioProperties, CLSID_AudioRendererAdvancedProperties
Executable | quartz.dll
Merit | MERIT_PREFERRED
Filter Category | CLSID_AudioRendererCategory

Remarks

This filter acts as a wrapper for an audio device. To enumerate the audio devices available on the user's system, use the ICreateDevEnum interface with the audio renderer category (CLSID_AudioRendererCategory). For each audio device, the audio renderer category contains two filter instances. One of these corresponds to the DirectSound Renderer, and the other corresponds to the Audio Renderer (WaveOut) filter. The DirectSound instance has the friendly name "DirectSound: DeviceName," where DeviceName is the name of the device. The WaveOut instance has the friendly name DeviceName.

The audio renderer category contains two additional filter instances, named "Default DirectSound Device" and "Default WaveOut Device." These correspond to the default sound device, as chosen by the user through the Control Panel. They are actually mappings to one of the pairs described in the previous paragraph. For example, if the system has two audio devices, Device A and Device B, the audio renderer category will contain the following:

  • Device A
  • DirectSound: Device A
  • Device B
  • DirectSound: Device B
  • Default DirectSound Device
  • Default WaveOut Device

If the user selected Device A as the default device, then "Default DirectSound Device" is equivalent to "DirectSound: Device A," and "Default WaveOut Device" is equivalent to "Device A." If the user selects Device B as the default device, these mappings will change.

"Default DirectSound Device" is assigned a merit of MERIT_PREFERRED. The others have merit MERIT_DO_NOT_USE. Therefore, Intelligent Connect will always choose the default DirectSound device.

The DirectSound Renderer filter supports 3D sound through the DirectSound IDirectSound3DBuffer and IDirectSound3dListener interfaces. You can also query the filter for the current versions of these interfaces, IDirectSound3DBuffer8 and IDirectSound3dListener8. Run the graph before calling methods on these interfaces.


DMO Wrapper Filter

The DMO Wrapper filter enables a Microsoft® DirectShow® application to use a DirectX Media Object (DMO) within a filter graph. The filter wraps the DMO and handles all the details of using the DMO, such as passing data to and from the DMO. Also, the filter aggregates the DMO, so the application can query the filter for any COM interfaces that the DMO exposes.

Limitations

The current implementation of the DMO Wrapper has the following limitations:

  • It does not support DMOs with zero inputs, multiple inputs, or zero outputs. (It does support DMOs with one input and multiple outputs.)
  • It does not support custom transports. All data transport is done through the IMemInputPin interface.
  • It does not use the IMediaObjectInPlace interface; all processing is done using IMediaObject methods.
Filter Interfaces | IBaseFilter, IDMOWrapperFilter, IPersistStream
Input Pin Media Types | See Remarks
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | See Remarks
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DMOWrapperFilter
Property Page CLSID | No property page
Executable | Qasf.dll
Merit | See Remarks
Filter Category | See Remarks

Remarks

Pins: For each input stream on the DMO, the filter creates a corresponding input pin. For each output stream, it creates a corresponding output pin. The media types that each pin supports depends on the DMO.

Encoder Interfaces: If the DMO is a video encoder or an audio encoder, the output pin exposes the IAMStreamConfig interface. If the DMO is a video encoder, the output pin also exposes the IAMVideoCompression interface. In both cases, if the DMO supports the interface, the pin delegates to the DMO. Otherwise, the pin provides its own implementation.

Streaming: The filter uses the IMemInputPin interface to handle all streaming. It does not support IAsyncReader connections. The filter calls IMediaObject::ProcessOutput on the DMO only when it receives data from upstream (including end-of-stream notifications). Therefore, it does not support DMOs with zero input streams.

Seeking: All seek requests are passed to the upstream filter, through the first input pin on the DMO Wrapper. For multiple-output DMOs, this means that the upstream filter might receive multiple seek requests when the application seeks the graph.

Merit: DirectShow assigns all DMOs a default merit value of MERIT_NORMAL + 0x800. This value falls between MERIT_NORMAL and MERIT_PREFERRED. Decoder filters generally have a merit value of MERIT_NORMAL. Therefore, the filter graph manager will usually select a DMO decoder over a decoder filter. To override the default merit value, add a registry entry to the DMO's registry key in HKEY_CLASSES_ROOT\CLSID. Include a DWORD value named Merit whose value specifies the merit.

Category: The DMO Wrapper filter does not appear by itself in any category. When it wraps a DMO, it appears in the DirectShow category that corresponds to the DMO's category, under the name of the DMO.


DV Muxer Filter

This filter combines a digital video (DV)–encoded video stream with one or two audio streams to produce an interleaved DV stream. To write the stream to an AVI file, connect this filter to the AVI Mux filter and connect the AVI Mux to the File Writer filter. For more information, see Digital Video in DirectShow.

Filter Interfaces | IBaseFilter, IMediaSeeking
Input Pin Media Types | Video: MEDIATYPE_Video, MEDIASUBTYPE_dvsd, FORMAT_VideoInfo Audio: MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Interleaved, MEDIASUBTYPE_dvsd, FORMAT_DvInfo
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_DVMux
Property Page CLSID | No property page
Executable | qdv.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The DV Muxer can create two audio input pins. It supports the audio formats shown in the following table.

Audio Pin 1 |  |  | Audio Pin 2 |  |  | Output Format
Sample Rate (kHz) | Bits/Sample | Channels | Sample Rate | Bits/Sample | Channels
32 | 16 | Mono | Unconnected |  |  | SD 2 Channel
32 | 16 | Stereo | Unconnected |  |  | SD 4 Channel
44.1 or 48 | 16 | Stereo or Mono | Unconnected |  |  | SD 2 Channel
Unconnected |  |  | 32 | 16 | Stereo or Mono | Disallowed
Unconnected |  |  | 44.1 or 48 | 16 | Mono | Disallowed
Unconnected |  |  | 44.1 or 48 | 16 | Stereo | SD 2 Channel
32 | 16 | Mono | 32 | 16 | Mono | SD 2 Channel
32 | 16 | Stereo or Mono* | 32 | 16 | Stereo or Mono* | SD 4 Channel
44.1 | 16 | Mono | 44.1 | 16 | Mono | SD 2 Channel
48 | 16 | Mono | 48 | 16 | Mono | SD 2 Channel
* If at least one input pin is stereo.

For the purpose of this table, audio pin 1 is defined as the first input pin connected to an audio source, and audio pin 2 is defined as the second input pin connected to an audio source. Once an audio pin is connected, this numbering scheme remains in effect unless both audio pins are disconnected. For example, if you connect both audio pins and then disconnect audio pin 1, the remaining pin is still considered pin 2.

Audio supplied to pin 1 is recorded to the first audio block of the DV frames (CH1), and audio supplied to pin 2 is recorded to the second audio block (CH2). Exception: if the filter has a single stereo input at 44.1 kHz or 48 kHz, the left audio channel is recorded to the first audio block, and the right audio channel is recorded to the second audio block.

For SD 4-channel output: If the input is stereo, the left track is recorded to CHa or CHc, and the right track is recorded to CHb or CHd. If the input is mono, the audio is recorded to CHa or CHc, and CHb and CHd are silent.

By connecting and disconnecting audio pin 1, it is possible to reach a disallowed format. In that case, the filter's IMediaFilter::Pause method returns VFW_E_NOT_CONNECTED. This limitation prevents a situation in which the first audio block has no audio, but the second audio block does have audio. The second block should have audio only if the first block also has audio.

The DV Muxer does not permit audio inputs with different sampling rates. However, graph-building methods such as IGraphBuilder::Connect will typically add the ACM Wrapper filter, which will convert the second audio stream to match the first stream's sampling rate.

If the audio input is 48 kHz or 32 kHz, the audio output is locked. (It is not possible to lock 44.1-kHz audio.)

If no audio pins are connected, the output contains the audio data from the incoming DV frames. This might be silence, or valid audio data.

See Also

  • Digital Video in DirectShow


DV Splitter Filter

This filter splits an interleaved digital video (DV) stream into its component video and audio streams.

Filter Interfaces | IBaseFilter, IDVSplitter
Input Pin Media Types | MEDIATYPE_Interleaved, MEDIASUBTYPE_dvsd, FORMAT_DvInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Video: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_DvInfo Audio: MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVSplitter
Property Page CLSID | No property page.
Executable | qdv.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

Only one output pin at a time exposes the IMediaPosition and IMediaSeeking interfaces.

The DV Splitter filter can accept dynamic format changes in the audio stream. However, if the AVI Mux filter is downstream, it will reject the format change. If this happens, the DV Splitter stops producing an audio stream.

Note This limitation affects type-2 file capture only. For preview, there is no AVI Mux filter downstream. For type-1 file capture, the interleaved stream is not split in the first place. If the DV source is a live camera, there is normally no reason for the audio format to change. However, it might happen if you transmit from a VCR tape that contains heterogeneous sources edited together.

See Also

  • Digital Video in DirectShow


DV Video Decoder Filter

This filter decodes a digital video (DV) stream into uncompressed video.

Filter Interfaces | IBaseFilter, IDVRGB219, IIPDVDec, IPersistStream, ISpecifyPropertyPages
Input Pin Media Types
  • MEDIATYPE_Video
  • MEDIASUBTYPE_dvsd
  • FORMAT_VideoInfo, FORMAT_DvInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types Major type: MEDIATYPE_Video

Subtypes:

  • MEDIASUBTYPE_YUY2
  • MEDIASUBTYPE_UYVY
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
  • MEDIASUBTYPE_ARGB32
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_Y41P

Format types:

Format_VideoInfo, Format_VideoInfo2
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVVideoCodec
Property Page CLSID | CLSID_DVDecPropertiesPage
Executable | qdv.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

Use the IIPDVDec interface to set the decoding resolution to full, half size, quarter size, or one-eighth size.

Interlacing: Earlier versions of the decoder always deinterlace the video. As of DirectX 9.0, the DV Video Decoder can preserve the interlacing. This enables the interlaced video to be deinterlaced by the Video Mixing Renderer (VMR), for improved rendering quality. To use this feature, the downstream filter must support VIDEOINFOHEADER2 formats, indicated by that value Format_VideoInfo2 in the formattype member of the AM_MEDIA_TYPE structure. At full resolution output, the deinterlacing flags (dwInterlace) in the VIDEOINFOHEADER2 structure are set to AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOrWeave, indicating interlaced fields. At half resolution or lower, dwInterlace is set to zero, indicating progressive frames.

See Also

  • Digital Video in DirectShow


DV Video Encoder Filter

This filter encodes an uncompressed video stream into digital video (DV). It provides a custom interface, IDVEnc, for setting the encoding resolution and format.

Filter Interfaces | IAMVideoCompression, IBaseFilter, IDVEnc, IDVRGB219, IPersistStream, ISpecifyPropertyPages
Input Pin Media Types
  • Major type: MEDIATYPE_Video

    The following subtypes are valid:

    • MEDIASUBTYPE_RGB24
    • MEDIASUBTYPE_RGB565
    • MEDIASUBTYPE_RGB555
  • Format type: FORMAT_VideoInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types
  • Major type: MEDIATYPE_Video
  • Subtype: MEDIASUBTYPE_dvsd
  • Format type: FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVVideoEnc
Property Page CLSID | CLSID_DVEncPropertiesPage
Executable | qdv.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_VideoCompressorCategory

Remarks

For 16-bit video (MEDIASUBTYPE_RGB555 or MEDIASUBTYPE_RGB565), the input must be 720 x 480 pixels for NTSC, or 720 x 576 pixels for PAL. For 24-bit video, there are no size constraints on the input.

The output is always 720 x 480 for NTSC or 720 x 576 for PAL; 24-bit video is scaled to fit these dimensions.

See Also

  • Digital Video in DirectShow


DVD Navigator Filter

The DVD Navigator filter is the source filter for a DVD-Video playback filter graph. It opens all necessary files in a DVD-Video volume, navigates through the linear DVD-Video .vob files, and parses the resulting MPEG-2 program stream, splitting the stream into three (video, audio, subpicture) output pins.

The DVD Navigator filter also implements the IDvdControl2 and IDvdInfo2 interfaces that enable a DVD playback application to control DVD-Video playback.

Filter Interfaces | IBaseFilter, IDvdControl2, IDvdCmd, IDvdInfo2, IDvdState IFileSourceFilter, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_Stream; MEDIASUBTYPE_MPEG2_PROGRAM
Input Pin Interfaces | Not applicable.
Output Pin Media Types
  • MEDIATYPE_Audio, MEDIASUBTYPE_MPEG1AudioPayload
  • MEDIATYPE_Video, MEDIASUBTYPE_MPEG2_VIDEO
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_DVDNavigator
Property Page CLSID | No property page.
Executable | qdvd.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory

See Also

  • DVD Applications


File Source (Async) Filter

The Async File Source filter opens and reads local files of many different data formats and passes the data to a parser filter.

To downloading media files from the Web, use the File Source (URL) filter. To read ASF files, use the WM ASF Reader filter.

Filter Interfaces | IBaseFilter, IFileSourceFilter
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | MEDIATYPE_Stream. The subtype depends on the media format. (MEDIASUBTYPE_NULL if the filter doesn't recognize the format.)
Output Pin Interfaces | IAsyncReader, IPin
Filter CLSID | CLSID_AsyncReader
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory


File Source (URL) Filter

The URL File Source filter is a generic asynchronous source filter that works with any source file that can be identified by a Uniform Resource Locator (URL) and whose media major type is stream. This includes AVI, MOV, MPEG, and WAV files. It requires the downstream filter to be a parser, such as the MPEG-1 Stream Splitter, the AVI Splitter, or the QuickTime Movie Parser.

Filter Interfaces | IAMOpenProgress, IBaseFilter, IFileSourceFilter
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | MEDIATYPE_Stream. The subtype depends on the media format. (MEDIASUBTYPE_NULL if the filter doesn't recognize the format.)
Output Pin Interfaces | IAsyncReader, IPin
Filter CLSID | CLSID_URLReader
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

This filter uses Microsoft® Internet Explorer's URLMon and supports code pages.


File Stream Renderer Filter

The File Stream Renderer filter renders file names that are parsed by the Multi-File Parser filter. For more information, see the documentation for that filter.

The use of this filter is deprecated. To render multiple files within the same filter graph, the application should simply call RenderFile or AddSourceFilter multiple times.

Filter interfaces | IBaseFilter
Input pin media types
  • Major type: MEDIATYPE_File
  • Subtype: GUID_NULL
  • Format type: MEDIATYPE_File
Input pin interfaces | IPin, IQualityControl
Output pin media types | None
Output pin interfaces | IPin, IQualityControl, IStreamBuilder
Filter CLSID | CLSID_FileRend
Executable | Quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The filter's CLSID is not defined in Uuids.h. Use this macro in your own header file:

// {D51BD5A5-7548-11cf-A520-0080C77EF58A}
DEFINE_GUID(CLSID_FileRend,
0xd51bd5A5, 0x7548, 0x11cf, 0xa5, 0x20, 0x0, 0x80, 0xc7, 0x7e, 0xf5, 0x8a);


File Writer Filter

The File Writer filter can be used to write files to disc regardless of format. The filter simply writes to disc whatever it receives on its input pin, so it must be connected upstream to a multiplexer that can format the file correctly. You can create a new output file with the File Writer or specify an existing file; if the file already exists, it will be completely overwritten with the new data.

The time stamps on samples delivered to the file writer are byte offsets in the file. The input pin exposes the IStream interface and supports a subset of the interface. This enables the upstream filter to write data when the graph is stopped.

Note If you are writing ASF files using the Microsoft® Windows Media™ Software Development Kit, use the WM ASF Writer filter. The WM ASF Writer provides the only way to create ASF files in Microsoft DirectShow.

Filter Interfaces | IAMFilterMiscFlags, IBaseFilter, IFileSinkFilter, IFileSinkFilter2, IPersistStream
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl, IStream
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_FileWriter
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory


Full Screen Renderer Filter

The Full Screen Renderer filter provides full-screen video rendering on older hardware. Newer video cards can stretch the video efficiently enough that the Full Screen Renderer is not required. Therefore, the use of this filter is now deprecated.

Do not manually add this filter to the filter graph. If an application calls IVideoWindow::put_FullScreenMode, the Filter Graph Manager automatically selects the appropriate video renderer for full-screen mode. The selection is transparent to the application. With current video cards, the Filter Graph Manager is unlikely to select the Full Screen Renderer.

Filter Interfaces | IBaseFilter, IFullScreenVideoEx, IMediaPosition, IMediaSeeking, IQualityControl, IQualProp
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_Null
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_ModexRenderer
Property Page CLSID | CLSID_ModexProperties
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The Full Screen Renderer supports a static set of display modes. The video card on the user's system might not support every mode, however. To determine whether the card supports a particular mode, call the IFullScreenVideoEx::IsModeAvailable method. You can also disable a particular display mode programmatically, by calling the IFullScreenVideoEx::SetEnabled. The Full Screen Renderer currently supports the display modes shown in the following table:

Mode | Width | Height | Bit Depth
0 | 320 | 200 | 16
1 | 320 | 200 | 8
2 | 320 | 240 | 16
3 | 320 | 240 | 8
4 | 640 | 400 | 16
5 | 640 | 400 | 8
6 | 640 | 480 | 16
7 | 640 | 480 | 8
8 | 800 | 600 | 16
9 | 800 | 600 | 8
10 | 1024 | 768 | 16
11 | 1024 | 768 | 8
12 | 1152 | 864 | 16
13 | 1152 | 864 | 8
14 | 1280 | 1024 | 16
15 | 1280 | 1024 | 8

(All modes are RGB.) This list is subject to change, however. Use the IFullScreenVideoEx::GetModeInfo method to get information about the modes. The Full Screen Renderer always chooses the lowest-resolution mode available, limited by a property called the clip factor, which determines how much of the video the Full Screen Renderer is allowed to clip. For more information, see IFullScreenVideoEx::GetClipFactor.

When the application runs or pauses the filter graph, the Full Screen Renderer switches to the display mode that was chosen. When the graph stops, the Full Screen Renderer restores the original display mode.

The Full Screen Renderer can function only as the foreground active window. If the user switches to another application, the Full Screen Renderer hides the video by minimizing or hiding the video window.


Infinite Pin Tee Filter

This filter delivers samples delivered to its input pin to a variable number of output pins. When an instance of the filter is created, it has one output pin. Each time an output pin is connected, the filter creates another output pin. All output pins share the same media type as the input pin.

This filter is also provided as an SDK sample. See InfTee Filter Sample.

Filter Interfaces | IBaseFilter
Input Pin Media Types | Any media type.
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Any media type. The output type always matches the input type, for all output pins.
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_InfTee
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory


Internal Script Command Renderer Filter

Receives script commands and dispatches them to the application.

This filter accepts script commands in one of two formats:

  • MEDIATYPE_Text: Each media sample contains an ANSI text string.
  • MEDIATYPE_ScriptCommand: Each media sample contains two NULL-terminated Unicode strings, concatenated together. The first string describes the command type and the second string is the script command.

    When the filter receives a sample, it sends an EC_OLE_EVENT event notification. The first event parameter is a BSTR with the command type, or Text if the format is MEDIATYPE_Text. The second event parameter is a BSTR with the script command. The application can retrieve the event and respond to the script command.

For an example of how to use this filter, see SAMI (CC) Parser.

Filter Interfaces | IBaseFilter, IMediaPosition, IMediaSeeking
Input Pin Media Types
  • MEDIATYPE_ScriptCommand, MEDIASUBTYPE_NULL
  • MEDIATYPE_Text, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | {48025243-2D39-11CE-875D-00608CB78066}
Property Page CLSID | No property page
Executable | Quartz.dll
Merit | MERIT_PREFERRED + 1
Filter Category | CLSID_LegacyAmFilterCategory


Line 21 Decoder Filter

This Line 21 Decoder filter decodes line 21 data and draws the caption text onto bitmaps.

The input pin connects to any line 21 data provider, typically either a DVD video decoder or the CC Decoder filter. The CC Decoder provides line 21 data from the VBI of an analog television signal. The output pin connects to a secondary pin on the Overlay Mixer or to another video renderer, such as the VMR.

This filter accepts line 21 data in the standard byte-pair format or, for DVD, as a packet for the whole group of pictures (GOP). For every GOP in the DVD video stream, there can be a user data packet that has that particular GOP's header information and line 21 data.

Two versions of this filter are available:

Filter | CLSID
Line 21 Decoder | CLSID_Line21Decoder
Line 21 Decoder 2 | CLSID_Line21Decoder2

The version 1 filter is used on Microsoft® Windows® 9.x and Windows 2000 platforms. The version 2 filter is available only in Microsoft Windows XP, and is used whenever the Video Mixing Renderer is in the graph.

The information in the following table applies to both versions of the filter:

Filter Interfaces | IAMLine21Decoder, IBaseFilter
Input Pin Media Types Major Type: MEDIATYPE_AUXLine21Data

Subtype:

  • MEDIASUBTYPE_Line21_BytePair (standard line 21)
  • MEDIASUBTYPE_Line21_GOPPacket (DVD line 21)

Format Type: FORMAT_VideoInfo or GUID_NULL.
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types Major type: MEDIATYPE_Video

Subtype:

  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32

Format Type: FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | See previous table.
Property Page CLSID | None
Executable | qdvd.dll
Merit Line 21 Decoder: MERIT_NORMAL

Line 21 Decoder 2: MERIT_NORMAL + 2
Filter Category | CLSID_LegacyAmFilterCategory

See Also

  • Closed Captions and Teletext
  • DVD Filter Graph Configuration


MIDI Parser Filter

The MIDI Parser filter reads MIDI data that is found in .MID and .RMI files. The filter accepts a stream from the Async File Source or URL File Source filters and outputs MIDI samples to the MIDI Renderer for playback.

Filter Interfaces | IAMMediaContent, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_Midi
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Midi, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaSeeking, IQualityControl, IPin
Filter CLSID | CLSID_MIDIParser
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

For more information, see MIDI Renderer.


MIDI Renderer Filter

The MIDI Renderer filter renders MIDI data from the MIDI Parser filter.

Filter Interfaces | IAMClockSlave, IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IMediaPosition, IMediaSeeking, IQualityControl, IReferenceClock
Input Pin Media Types | MEDIATYPE_Midi, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | CLSID_AVIMIDIRender
Property Page CLSID | No property page
Executable | quartz.dll
Merit | MERIT_PREFERRED
Filter Category | CLSID_MidiRendererCategory

Remarks

The GUID for the format type is NULL, but the format block contains the following structure:

typedef struct _MIDIFORMAT {
    DWORD       dwDivision;
    DWORD       dwReserved[7];
} MIDIFORMAT, FAR * LPMIDIFORMAT;

The dwDivision member specifies the time division of the file. The time division is given in the header of any standard MIDI file (SMF), in the MThd chunk. The MIDI Renderer sets this property on the MIDI data stream by calling the midiStreamProperty function.

Samples from the MIDI Parser filter contain one second of MIDI data. The MIDI Renderer uses the midiStreamOut function to render the MIDI data. Each sample is a synchronization point: the start of the buffer contains all of the commands necessary to set the correct state for rendering that buffer.


MJPEG Compressor Filter

This filter compresses an uncompressed video stream, using motion JPEG compression.

Filter Interfaces | IBaseFilter, IPersistStream
Input Pin Media Types | MEDIATYPE_VIDEO, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_MJPG
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_MJPGEnc
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_VideoCompressorCategory

Remarks

This filter encodes using the media subtype MEDIASUBTYPE_MJPG, which corresponds to the FOURCC code 'MJPG'.


MJPEG Decompressor Filter

This filter decodes a video stream from motion JPEG to uncompressed video. Some digital video cameras produce a motion JPEG video stream.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_MJPG
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_VIDEO, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_MjpegDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

This filter is compatible with motion JPEG video that uses the FOURCC code 'MJPG'. It cannot decode other varieties of motion JPEG. For these, you will need to use a third-party decoder filter.


MPEG-1 Audio Decoder Filter

Decodes MPEG-1 Layer I and Layer II audio to PCM.

Filter Interfaces | IBaseFilter, ISpecifyPropertyPages
Input Pin Media Types MEDIATYPE_Audio, FORMAT_WaveFormatEx

The following subtypes are valid:
  • MEDIASUBTYPE_MPEG1Packet
  • MEDIASUBTYPE_MPEG1Payload
  • MEDIASUBTYPE_MPEG1AudioPayload
  • GUID_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_PCM
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_CMpegAudioCodec
Property Page CLSID | CLSID_MpegAudioDecoderPropertyPage
Executable | quartz.dll
Merit | 0x03680001
Filter Category | CLSID_LegacyAmFilterCategory


MPEG-1 Stream Splitter Filter

This filter splits an MPEG-1 system stream into its component audio and video streams.

Filter Interfaces | IAMMediaContent, IAMStreamSelect, IBaseFilter
Input Pin Media Types Major type: MEDIATYPE_Stream

Subtypes:

  • MEDIASUBTYPE_MPEG1System
  • MEDIASUBTYPE_MPEG1VideoCD
  • MEDIASUBTYPE_Audio
  • MEDIASUBTYPE_Video

See MPEG-1 Media Types
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types Major type: MEDIATYPE_Audio or MEDIATYPE_Video

Subtype: MEDIASUBTYPE_MPEG1Payload or MEDIASUBTYPE_MPEG1Packet

See MPEG-1 Media Types
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_MPEG1Splitter
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

This file supports pull mode via IAsyncReader only; it does not support push mode.

Because MPEG-1 content is not indexed, seeking can be very approximate. It is usually good for a fixed bitrate MPEG-1 system stream (which is usually hardware generated for video CD).

The filter supports the IAMMediaContent interface for retrieving ID3 metadata.

Not all MPEG samples have time stamps. The lack of a time stamp on an MPEG sample is not an error. For filter developers, this means that you should not return an error code from your input pin's Receive method if IMediaSample::GetTime fails. If Receive returns any value other than S_OK, it will cause the splitter to stop sending samples.


MPEG-1 Video Decoder Filter

Decodes MPEG-1 video.

Filter Interfaces | IBaseFilter, IMpegVideoDecoder, ISpecifyPropertyPages
Input Pin Media Types MEDIATYPE_Video, FORMAT_MPEGVideo

The following subtypes are valid:
  • MEDIASUBTYPE_MPEG1Packet
  • MEDIASUBTYPE_MPEG1Payload
Input Pin Interfaces | IPin, IMemInputPin
Output Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo or FORMAT_VideoInfo2

The following subtypes are possible:
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_UYVY
  • MEDIASUBTYPE_Y41P
  • MEDIASUBTYPE_YUY2
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_CMPEGVideoCodec
Property Page CLSID | CLSID_MpegVideoDecodePropertyPage
Executable | quartz.dll
Merit | 0x40000001
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

This filter can decode into a DirectDraw Surface. The filter uses MMX if the machine supports MMX.


MPEG-2 Demultiplexer

The MPEG-2 Demultiplexer ("demux") filter demultiplexes MPEG-2 transport and program streams that are delivered in push-mode. In Microsoft® Windows® XP, this filter also supports program streams in pull mode (file playback). On earlier platforms, use the MPEG-2 Splitter filter for program streams in pull mode. This filter can be used in any type of filter graph, including a BDA digital TV filter graph.

Note The MPEG-2 Demultiplexer does not support frame-accurate seeking.

Filter Interfaces IBaseFilter, ISpecifyPropertyPages

Push mode only: IAMFilterMiscFlags, IMpeg2Demultiplexer, IReferenceClock
Input Pin Media Types Major type: MEDIATYPE_STREAM

Subtype:

  • KSDATAFORMAT_SUBTYPE_BDA_MPEG2_TRANSPORT
  • MEDIASUBTYPE_MPEG2_PROGRAM
  • MEDIASUBTYPE_MPEG2_TRANSPORT
  • MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE

For more information, see MPEG-2 Demultiplexer Media Types.
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types Audio and video elementary streams must have a major type of MEDIATYPE_Audio or MEDIATYPE_Video.

For more information, see MPEG-2 Demultiplexer Media Types.
Output Pin Interfaces IPin, IQualityControl

Push mode only: IAMPushSource, IMPEG2PIDMap, IMPEG2StreamIdMap

Pull mode only: IMediaSeeking
Filter CLSID | CLSID_MPEG2Demultiplexer
Property Page CLSID | Available for testing only. Use the ISpecifyPropertyPages interface to access the propery pages.
Executable | mpg2splt.ax
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

To output audio and video elementary streams, the demux must receive the PCR and SCR streams. On the input side, this means a transport stream must contain the PAT and PMT tables that define the PID for the PCR stream; and program streams must contain at least one pack header.

See Also

  • Using the MPEG-2 Demultiplexer


MPEG-2 Sections and Tables Filter

The MPEG-2 Sections and Tables filter receives PSI tables from an MPEG-2 transport stream.

Filter Interfaces | IBaseFilter, IMpeg2Data
Input Pin Media Types | Major Type: MEDIATYPE_MPEG2_SECTIONS Subtype: MEDIASUBTYPE_MPEG2DATA Format block: None
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | Not applicable
Merit | MERIT_NORMAL
Filter Category | KSCATEGORY_BDA_TRANSPORT_INFORMATION

See Also

  • Getting MPEG-2 PSI Tables


MPEG-2 Splitter

In Microsoft® Windows® XP, the MPEG-2 Splitter filter is deprecated. Use the MPEG-2 Demultiplexer instead.

On earlier platforms, use the MPEG-2 Splitter for MPEG-2 program streams delivered in pull mode that contain at least one of the following stream types: MPEG-2 video; MPEG-2 audio; AC3 audio encoded as defined for DVD video; or PCM audio encoded as defined for DVD video. This filter parses the streams, creates an output pin for each stream, and outputs the compressed MPEG audio or video packets to an MPEG-2 decoder filter.

For program and transport streams delivered in push-mode, use the MPEG-2 Demultiplexer, on all platforms.

Note The MPEG-2 Splitter does not support frame-accurate seeking.

Filter Interfaces | IBaseFilter, ISpecifyPropertyPages, IAMParse, IAMStreamSelect
Input Pin Media Types
  • MEDIATYPE_Stream, MEDIASUBTYPE_MPEG2_PROGRAM
  • MEDIATYPE_Stream, MEDIASUBTYPE_MPEG1_Video
  • MEDIATYPE_Stream, MEDIASUBTYPE_NULL
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | Depends on the stream type. See MPEG-2 Splitter Media Types.
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_MMSPLITTER
Property Page CLSID | Not applicable
Executable | mpg2splt.ax
Merit | MERIT_NORMAL + 1
Filter Category | CLSID_AudioInputDeviceCategory

See Also

  • Using the MPEG-2 Splitter


MSDV Driver

MSDV is the Microsoft® Windows® Driver Model (WDM) driver for DV camcorders. It is exposed to applications as the WDM Video Capture filter. MSDV supports a subset of the interfaces described on the filter's reference page. If a DV camcorder is available on the user's system, it appears in both the "Video Capture Sources" category (CLSID_VideoInputDeviceCategory) and the "WDM Streaming Rendering Devices" category (AM_KSCATEGORY_RENDER). The friendly name is "Microsoft DV Camera and VCR," or a localized equivalant. To add this filter to a filter graph, use the ICreateDevEnum interface. For more information, see Enumerating Devices and Filters.

MSDV exposes the IAMExtDevice, IAMExtTransport, and IAMTimecodeReader interfaces for controlling the camcorder.

MSDV has two output pins. One output pin delivers interleaved audio-video data, and the other delivers video data without audio. Only one output pin can be rendered at a time. It has one input pin, which transmits data from the computer to the camcorder. MSDV will not accept simultaneous input and output connections, because a camcorder cannot capture and transmit at the same time. For information about which DV formats are supported, see DV Video Subtypes.

Some tips on using MSDV:

  • The IGraphBuilder::Render method will not render an output pin on MSDV, because the Filter Graph Manager tries to connect the pin to MSDV's own input pin. Because MSDV rejects the connection, the method fails. Instead, use IGraphBuilder::Connect or ICaptureGraphBuilder2::RenderStream.
  • When a filter graph contains MSDV, MSDV should supply the reference clock for the graph. As of DirectX 8.0, the Filter Graph Manager will automatically choose MSDV as the reference clock. With earlier versions, you should call the IMediaFilter::SetSyncSource method on the Filter Graph Manager. For more information about clocks, see Time and Clocks in DirectShow.
  • Depending on the device, some methods in IAMExtDevice, IAMExtTransport, and IAMTimeCodeReader might return WIN32 error codes instead of HRESULT values. Possible error codes include the following:
Error Code | Description
ERROR_TIMEOUT | An external device command has timed out.
ERROR_REQ_NOT_ACCEP | The device did not accept this external device command.
ERROR_NOT_SUPPORTED | The device does not support this external device command.
ERROR_REQUEST_ABORTED | An external device command was aborted. Possbly the device was removed or a bus reset occurred.

Device Information

In Windows Millennium Edition and Windows XP, the DV filter's device moniker supports a "Description" property in addition to the "FriendlyName" property. This property returns a description of the device, taken from the INF file, which usually contains the brand name of the device. This property is not supported for all device models, however.

For more information about device monikers, see Using the System Device Enumerator.

Clock Times

The MSDV driver uses the 1394 bus clock that is contained in the 1394 data packets to derive the clock. It uses these values to time stamp the DV media samples. Because this source clock is not the computer system clock, the times will eventually drift from the computer system clock. As noted above, however, by default the Filter Graph Manager will select MSDV as the graph reference clock.

The IAMDroppedFrame interface reports the driver's current measure of dropped frames; this value may not be perfectly synchronized with the actual number of dropped frames at a given time. If frames are dropped, it indicates the system is not balanced (data production exceeds data consumption). For example, the user's hard disk may not be fast enough to support DV capture rates.

See Also

  • Controlling a DV Camcorder
  • Digital Video in DirectShow


MSTape Driver

This topic applies to Windows XP only.

The MSTape driver supports D-VHS and MPEG camcorder devices. It is exposed to applications as the WDM Video Capture filter. Its functionality is similar to that of MSDV, the DV camcorder driver:

  • It appears in the "Video Capture Sources" (CLSID_VideoInputDeviceCategory) and "WDM Streaming Rendering Devices" (AM_KSCATEGORY_RENDER) filter categories.
  • An application can create an instance of the filter using the ICreateDevEnum interface.
  • It has an output pin for capture and transport from the device, and an input pin for transport to the device. Only one pin can be connected at time.

Media Types

The input pin supports one media type.

Major Type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE
Sample Size | 192 x 256
Format Block | MPEG2_TRANSPORT_STRIDE

The output pin supports two media types.

Major Type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE
Sample Size | 192 x 256
Format Block | MPEG2_TRANSPORT_STRIDE

Major Type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE
Sample Size | 188 x 256
Format Block | NULL

Device Information

The driver dynamically reads information from the device configuration ROM. The application can retrieve this information by binding the device moniker to a property bag and calling the IPropertyBag::Read method.

Property | Description
UniqueID_Low | Unique ID of the device (low DWORD).
UniqueID_High | Unique ID of the device (high DWORD)
VendorID | Vendor ID.
ModelID | Model ID.
VendorText | Vendor name.
ModelText | Device model name.
UnitModelText | Unit model name; may be the same as ModelText.
DeviceOPcr0Payload | oPCR (Output Plug Control) payload. Example: 146 quadlets.
DeviceOPcr0DataRate | oPCR data rate. Examples: 0 (S100), 1 (S200), or 2 (S400).
DeviceClassGUID | GUID that identifies the device driver. For MSTape, this value is {8C0F6AF2-0EDB-44C1-8AEB-59040BD830ED}. This GUID is defined as MSTapeDeviceGUID in the header file Xprtdefs.h.
Description | A description of the device, taken from the INF file. This string usually contains the brand name of the device.

The device ID is a 64-bit integer. The low DWORD is stored in the UniqueID_Low property, and the high DWORD is stored in the UniqueID_High property.

For more information about device monikers, see Using the System Device Enumerator.

See Also

  • Controlling a DV Camcorder


MSYUV Color Space Converter Codec

MSYUV is a YUV-to-RGB color space converter codec. It enables playback of video source data in YUV formats on clients whose video display adapter cannot be used for YUV-to-RGB conversions in hardware. The codec participates in filter graphs through the AVI Decompressor wrapper filter.

Digital conferencing cameras with 1394 or USB interfaces can produce image data in various YUV formats. If the display hardware does not support on-board YUV-to-RGB conversion, or if the hardware conversion capability cannot be used for some other reason, then the YUV image data must be converted to RGB format before it is sent to the Video Renderer.

Because of the Video Renderer's requirement for an RGB input type at connection time, this filter might be inserted into a graph upstream from the Video Renderer during automatic graph building. Specifically, if the Graph Builder detects a YUV format in the media type of the upstream filter's output pin, the Graph Builder will insert the AVI Decompressor, which will then load the MSYUV codec and configure it initially to perform the conversion to RGB. After the graph first transitions to a run or paused state, the Video Renderer filter can detect whether the video display adapter can perform the conversion in hardware. If it can, then the AVI Decompressor is notified and it reconfigures MSYUV to operate in "pass-through mode," which causes the codec to skip the conversion and copy the YUV image data directly onto a DirectDraw overlay surface in video memory.

Because the Video Mixing Renderers (VMR-7 and VMR-9) never use GDI, they do not require an RGB type at connect time, and the MSYUV Color Space Converter is never inserted before the VMR in a graph.

MSYUV converts packed YUV formats to RGB, as shown in the following list:

  • Input formats: UYVY, YUY2, YVYU
  • Output formats: RGB 8, RGB 16, RGB 24, RGB 32

For filter details, see AVI Decompressor.


Multi-File Parser Filter

The Multi-File Parser filter parses a simple file format that enables multiple file names to be specified as though they were one file. These files have the format shown in the following example:

;MULTI
http://server/share/video.mpg
http://server/share/captions.smi

The use of this filter is deprecated. To render multiple files within the same filter graph, the application should simply call RenderFile or AddSourceFilter multiple times.

Filter interfaces | IBaseFilter
Input pin media types
  • Major type: MEDIATYPE_Stream
  • Subtype: CLSID_MultFile
  • Format type: GUID_NULL
Input pin interfaces | IPin, IQualityControl
Output pin media types
  • Major type: MEDIATYPE_File
  • Subtype: GUID_NULL
  • Format type: MEDIATYPE_File
Output pin interfaces | IPin, IQualityControl
Filter CLSID | CLSID_MultFile
Executable | Quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The filter creates one ouput pin for each file listed in the source file. The output type is MEDIATYPE_File, and the format block for the output type is a wide-character string that contains the file name. Each pin connects to an instance of the File Stream Renderer filter. The File Stream Renderer filter creates one ouput pin, which exposes the IStreamBuilder interface. The output pin renders the specified file. No media data travels between the Multi-File Parser and the File Stream Renderer.

The filter's CLSID is not defined in Uuids.h. Use this macro in your own header file:

// {D51BD5A3-7548-11cf-A520-0080C77EF58A}
DEFINE_GUID(CLSID_MultFile,
0xd51bd5a3, 0x7548, 0x11cf, 0xa5, 0x20, 0x0, 0x80, 0xc7, 0x7e, 0xf5, 0x8a);


NABTS/FEC VBI Codec Filter

The NABTS/FEC VBI codec decodes NABTS (North American Broadcast Teletext Specification) teletext from data in the vertical blanking interval (VBI). It also accepts hardware-decoded NABTS data. The codec delivers forward-error-corrected (FEC) SLIP packets.

Connect this filter to the BDA SLIP Deframer filter, and connect the BDA SLIP deframer to the BDA IP Sink filter. The BDA IP Sink filter delivers IP data to Winsock.

The NABTS/FEC VBI codec has two input pins:

  • The VBI pin accepts raw VBI data
  • The HWNABTS pin accepts hardward-decoded NABTS data. The filter simply passes the data to the BDA SLIP Deframer.

There are no application-callable interfaces on this filter.

This filter appears in the "WDM Streaming VBI Codecs" filter category (AM_KSCATEGORY_VBICODEC). Because this is a kernel-mode filter, applications cannot create it directly using CoCreateInstance. Instead, use the System Device Enumerator. For more information, see Creating Kernel-Mode Filters.


Null Renderer Filter

This filter is a renderer that discards every sample it receives, without displaying or rendering the sample data.

Filter interfaces | IBaseFilter, IMediaPosition, IMediaSeeking
Input pin media types | Any media type
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | Not applicable.
Output pin interfaces | Not applicable.
Filter CLSID | CLSID_NullRenderer
Property Page CLSID | No property page.
Executable | Qedit.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

Use this filter when an output pin in the graph requires a downstream connection, but you do not wish to render the data from that pin. By connecting the output pin to the Null Renderer, you complete the connection without rendering the data.

Even though this filter does not render any samples, it does wait for each sample's presentation time before discarding the sample. Therefore, the graph will run at the normal rate. If you want the graph the run as quickly as possible, set the reference clock to NULL. For more information, see Setting the Graph Clock.


Overlay Mixer Filter

The Overlay Mixer filter is a video renderer designed specifically for DVD playback and broadcast video streams with line-21 closed captioning. The Overlay Mixer also supports Video Port Extensions (VPEs), enabling it to work with hardware MPEG-2 decoders or analog TV tuners that send video directly to the graphics card, rather than over the PCI bus.

Note The Video Mixing Renderer 9 is now preferred over the Overlay Mixer filter, except in VPE scenarios.

The Overlay Mixer uses Microsoft® DirectDraw® for rendering. It requires an overlay surface on the graphics card. The primary video stream should be connected to pin 0. Secondary streams (closed caption graphics or DVD subpictures) are connected to pins 1 and higher. The Overlay Mixer blits the secondary streams directly onto the primary suface; it does not mix or alpha blend them.

The Overlay Mixer uses the Video Renderer for window management. The Video Renderer connects to the Overlay Mixer's output pin.

This filter is added to the filter graph automatically when applications use the IDvdGraphBuilder and ICaptureGraphBuilder2 interfaces to create the graph. The Filter Graph Manager will not automatically add the Overlay Mixer to the graph.

Note In the following table, the media subtypes accepted on input pin 0 are hardware dependent. The Overlay Mixer cannot determine whether a particular subtype is supported until it creates the DirectDraw surface. Therefore, the only way for an upstream filter to determine whether a subtype is supported is to attempt a connection with that subtype.

Filter Interfaces | IAMOverlayFX, IAMVideoDecimationProperties, IBaseFilter, IDDrawExclModeVideo, IKsPropertySet, IMediaPosition, IMediaSeeking, IMixerOCX, IQualProp, IVPNotify, IVPNotify2
Input Pin Media Types Major Type: MEDIATYPE_Video
Subtypes:
  • MEDIASUBTYPE_Overlay (pin 0 only)
  • DirectDraw YUV formats: MEDIASUBTYPE_YUVxx (pin 0 only)
  • DirectDraw Video Acceleration formats: MEDIASUBTYPE_DVAxxx (pin 0 only)
  • Microsoft® DirectDraw® RGB formats: MEDIASUBTYPE_RGBxx (all input pins)

    Format Type: Format_VIDEOINFO, Format_VIDEOINFO2

Input Pin Interfaces | IAMVideoAccelerator, IKsPin, IKsPropertySet, IMemInputPin, IMixerPinConfig, IMixerPinConfig2, IOverlay (pin 0 only), IPin, IPinConnection, IQualityControl, IVPNotify, IVPNotify2
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_Overlay
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_OverlayMixer
Property Page CLSID | No property page.
Executable | qdvd.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The Overlay Mixer uses destination color keying to mix video surfaces with overlays. It blits the color key and the secondary video to the primary surface, and sends the primary video to the overlay surface. The graphics card then composites the two surfaces into its frame buffer.

Applications can control some behaviors on the Overlay Mixer through the IMixerPinConfig2 interface. Game developers can use the Overlay Mixer to display video in DirectDraw Exclusive Mode, as described later in this section. The Video Mixing Renderer Filter 9 (VMR-9) now provides better support for video in games, however. For more information, see Using the Video Mixing Renderer.

The following information is provided for the benefit of filter developers, and game developers who want to use the Overlay Mixer in DirectDraw Exclusive Mode.

Overlay Mixer Internal Operations

The Overlay Mixer exposes an input pin for each incoming stream. Typically, there are three input pins: pin 0 for video data, and pins 1 and 2 for line 21 and DVD subpicture data. Internally, the Overlay Mixer creates a DirectDraw object with a primary surface comprising the entire desktop, plus an overlay surface whose rectangle is defined by the size of the video stream on Pin 0. If the decoder does not specify a color key, the Overlay Mixer uses default color keys: dark gray for more recent graphics cards and magenta for older 256-color cards.

Note The results are undefined if the decoder delivers two secondary video streams simultaneously in the same place on the overlay surface. (This sometimes occurs with DVDs that contain subpicture and line 21 streams.) The video might flicker, or display only one of the streams.

On Windows 98SE and Windows 2000, the Overlay Mixer does not support video port connections on secondary monitors. The pin connection will fail in this case. This limitation does not exist on Windows Me or Windows XP.

Upstream Connection with the Video Decoder

Typically the Overlay Mixer's input pins connect to an upstream video decoder. The primary video stream must connect to the pin 0. The line 21 or subpicture streams connect to pin 1 or greater. If the decoder is a software decoder that uses the host CPU exclusively, the connection between the decoder and the Pin 0 is an IMemInputPin connection. If the decoder uses hardware acceleration, the connection to Pin 0 must use the IAMVideoAccelerator inferface. These two types of connections are mutually exclusive.

If the decoder draws directly onto the overlay surface, it should use the IOverlay interface on pin 0 and implement the IOverlayNotify interface.

Filters that wrap a hardware decoder and connect to the Overlay Mixer through a video port must implement the IVPConfig inteface. The Overlay Mixer implements the IVPNotify interface. These two interfaces enable the decoder to specify the overlay surfaces it requires, and they enable the Overlay Mixer to inform the decoder of the location of those surfaces in video memory.

The Overlay Mixer also ensures that the video rectangle is scaled correctly. Video capture involves certain issues with respect to scaling the preview image and capturing interleaved video frames. If you are developing a filter or WDM driver for a hardware video capture device, refer to the IVPConfig and IVPNotify reference pages for more information on these topics.

The Overlay Mixer is not used in 1394 or USB capture scenarios. It is used in video capture over the PCI bus.

Downstream Connection with the Video Renderer

The Overlay Mixer has an output pin that connects to the Video Renderer filter. The Video Renderer in this case does not render the video; it simply manages the video window.

The pin connection uses the IOverlay interface rather than the IMemInputPin interface. The Video Renderer passes its window handle through the Overlay Mixer to DirectDraw, which manages the rectangle clipping. Applications can control the Video Renderer through the IVideoWindow and IBasicVideo2 interfaces on the Filter Graph Manager.

DirectDraw Exclusive Mode

The Overlay Mixer's DirectDraw exclusive mode enables games to display video on some part of the screen. In this mode, the Overlay Mixer renders the video directly to a DirectDraw surface created by the game application, rather than to a window provided by the Video Renderer. This enables games to control the color key. The Overlay Mixer exposes only one input pin in DirectDraw exclusive mode, which means that no mixing of Line 21 or DVD subpicture can be performed in this mode.

To use the Overlay Mixer in DirectDraw exclusive mode, create an instance of the Overlay Mixer and query it for the IDDrawExclModeVideo interface before building the filter graph. Then call IDDrawExclModeVideo::SetDDrawSurface to specify the DirectDraw surface for rendering. One significant limitation of this mode is that the game does not get access to the actual video bits. If you use IDDrawExclModeVideo, your application creates the primary surface, and the Overlay Mixer creates the overlay surface.

You can also use DirectDraw exclusive mode to perform windowless rendering—for example, in a Web page—but this is not recommended, because the Overlay Mixer does not perform any mixing in this mode. This means that no line 21 or subpicture data can be displayed. To write a DVD playback application in windowless mode, the recommended approach is to use the MSWebDVD ActiveX Control.


Overlay Mixer 2 Filter

The Overlay Mixer 2 filter is identical to the Overlay Mixer filter, except:

  • It supports only VIDEOINFOHEADER2 formats.
  • It has a higher merit, which enables it to be added to a filter graph automatically.

The Overlay Mixer 2 is provided so that the Filter Graph Manager will add it to the graph when it renders non-DVD MPEG-2 video. The choice of whether to use the Overlay Mixer or the Overlay Mixer 2 is handled by the component that builds the graph, either the Filter Graph Manager, the Capture Graph Builder, or the DVD Graph Builder. From an application perspective, they are the same filter, with the same interfaces and functionality.

The following table contains information specific to the Overlay Mixer 2. For all other filter data, refer to the documentation for the Overlay Mixer.

Input Pin Media Types | Format Type: Format_VIDEOINFO2
Filter CLSID | CLSID_OverlayMixer2
Merit | MERIT_UNLIKELY


QT Decompressor Filter

The QT Decompressor filter decompresses Apple® QuickTime® 2.0 video. This format is typically used in older QuickTime files.

Filter Interfaces | IBaseFilter
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo

The following subtypes are valid:
  • MEDIASUBTYPE_QTRpza
  • MEDIASUBTYPE_QTSmc
  • MEDIASUBTYPE_QTRle
  • MEDIASUBTYPE_QTJpeg
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_QTDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory


QuickTime Movie Parser Filter

The QuickTime Movie Parser filter splits Apple® QuickTime® data into audio and video streams. It supports QuickTime 2.0 and earlier. The input pin connects to a source filter such as the Async File Source filter or the URL File Source filter. The Parser uses the AVI Decompressor or QT Decompressor filter to decompress QuickTime files. The filter creates one output pin for the video stream and one output pin for the audio stream.

Filter Interfaces | IAMMediaContent, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_QTMovie;
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types
  • MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
  • MEDIATYPE_Audio, MEDIASUBTYPE_NULL, FORMAT_WaveFormatEx
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_QuickTimeParser
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory


SAMI (CC) Parser Filter

Parses captioning data from Synchronized Accessible Media Interchange (SAMI) files.

SAMI is a text format similar to HTML, and is used for encoding time-based captions. This filter converts SAMI data into a text stream. Each sample in the stream contains one caption entry, along with format information. The time stamps on the samples are generated from the time information in the SAMI file.

This filter is designed to be used with the Internal Script Command Renderer filter. The Internal Script Command Renderer receives the text samples and sends them to the application, in the form of event notifications. For more information, see the Remarks section.

Filter Interfaces | IAMStreamSelect, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Text, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaSeeking, IPin, IQualityControl
Filter CLSID | {33FACFE0-A9BE-11D0-A520-00A0D10129C0}
Property Page CLSID | No property page
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The following is a simple SAMI file:

<SAMI>
<Head>
<STYLE TYPE="text/css"> <!--
    .ENCC {Name: English; lang:en-US; SAMI_TYPE: CC;}
    .FRCC {Name: French; lang:fr-FR; SAMI_TYPE: CC;}
    #NORMAL {Name: Normal; font-family: arial;}
    #GREENTEXT {Name: GreenText; color:green; font-family: verdana;}
-->
</STYLE>
</Head>
<BODY>
<Sync Start=1000>
    <P CLASS="ENCC">One
    <P CLASS="FRCC">Un

<Sync Start=2000>
    <P CLASS="ENCC">Two
    <P CLASS="FRCC">Deux

<Sync Start=3000>
    <P CLASS="ENCC">Three
    <P CLASS="FRCC">Trois
</BODY>
</SAMI>

The STYLE tag defines two language settings, English (.ENCC) and French (.FRCC). It also defines two styles, #NORMAL and #GREENTEXT. Each SYNC tag defines the start time for a caption, in milliseconds. The P tags contain the caption text, while the CLASS attribute specifies the language setting to which the caption applies.

For each language and style, the filter creates a logical stream. At any time, exactly one language stream and one style stream are enabled. When the filter generates a sample, it selects the caption for the current language and applies the current style. By default, the first language and style declared in the file are enabled. An application can use the IAMStreamSelect::Enable method to enable a different stream.

With the default settings, the first caption in the example file produces the following output:

<P STYLE=" Name: English; lang:en-US; SAMI_TYPE: CC; Name: Normal; font-family: arial;">One

If the output goes to the Internal Script Command Renderer, that filter sends an EC_OLE_EVENT event notification. The second event parameter is a BSTR with the caption text. The application can retrieve the event and display the caption.

The following example shows how to render a SAMI file, retrieve stream information, enable streams, and display caption text. The example assumes that the previous SAMI file is saved as C:\Sami_test_file.sami.

For brevity, this example used hard-coded stream indexes when it calls the IAMStreamSelect::Enable method. It also performs minimal error checking.

void __cdecl main()
{
    HRESULT hr;
    IGraphBuilder *pGraph;
    IMediaControl *pMediaControl;
    IMediaEventEx *pEv;
    IBaseFilter   *pSAMI;

    CoInitialize(NULL);

    // Create the filter graph manager.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
                        IID_IGraphBuilder, (void **)&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pGraph->QueryInterface(IID_IMediaEventEx, (void**)&pEv);

    // Create the graph and find the SAMI parser.
    pGraph->RenderFile(L"C:\\Sami_test_file.sami", NULL);
    hr = pGraph->FindFilterByName(L"SAMI (CC) Parser", &pSAMI);
    if (SUCCEEDED(hr))
    {
        IAMStreamSelect *pStrm = NULL;
        hr = pSAMI->QueryInterface(IID_IAMStreamSelect, (void**)&pStrm);
        if (SUCCEEDED(hr))
        {
            DWORD dwStreams = 0;
            pStrm->Count(&dwStreams);
            printf("Stream count: %d\n", dwStreams);

            // Select French and "GreenText"
            hr = pStrm->Enable(1, AMSTREAMSELECTENABLE_ENABLE);
            hr = pStrm->Enable(3, AMSTREAMSELECTENABLE_ENABLE);

            // Print the name of each logical stream.
            for (DWORD index = 0; index < dwStreams; index++)
            {
                DWORD dwFlags;
                WCHAR *wszName;
                hr = pStrm->Info(index, NULL, &dwFlags, NULL, NULL,
                    &wszName, NULL, NULL);
                if (hr == S_OK)
                {
                    wprintf(L"Stream %d: %s [%s]\n", index, wszName,
                        (dwFlags ?  L"ENABLED" : L"DISABLED"));
                    CoTaskMemFree(wszName);
                }
            }
            pStrm->Release();
        }
        pSAMI->Release();
    }

    // Run the graph and display the captions.
    pMediaControl->Run();
    while (1)
    {
        long evCode, lParam1, lParam2;
        pEv->GetEvent(&evCode, &lParam1, &lParam2, 100);

        if (evCode == EC_OLE_EVENT) {
            wprintf(L"%s\n", (BSTR)lParam2);
        }
        pEv->FreeEventParams(evCode, lParam1, lParam2);

        if (evCode == EC_USERABORT || evCode == EC_COMPLETE || evCode == EC_ERRORABORT)
            break;
    }

    // Clean up.
    pMediaControl->Release();
    pEv->Release();
    pGraph->Release();
    CoUninitialize();
}

This filter uses the IAsyncReader interface to pull samples from the source filter. Therefore, it does not support the IMemInputPin interface on its input pin.


Sample Grabber Filter

The Sample Grabber filter provides a way to retrieve samples as they pass through the filter graph. It is a transform filter with one input pin and one output pin. It passes all samples downstream unchanged, so you can insert it into a filter graph without altering the data stream. Your application can then retrieve individual samples from the filter by calling methods on the ISampleGrabber interface.

If you want to retrieve samples without rendering the data, connect the Sample Grabber filter to the Null Renderer filter.

Filter interfaces | IBaseFilter, ISampleGrabber
Input pin media types | Any media type.
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | Any media type. Matches input media type.
Output pin interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_SampleGrabber
Property Page CLSID | No property page.
Executable | Qedit.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

To use this filter, add it to the filter graph and call ISampleGrabber::SetMediaType with the desired media type. This method specifies the media type for the filter's input and output pin connections. Then connect the filter to other filters in the graph.

If you call ISampleGrabber::SetBufferSamples with the value TRUE, the filter buffers each sample that it receives before passing it downstream. Call the ISampleGrabber::GetCurrentBuffer method to retrieve the current contents of the buffer. Alternatively, you can call ISampleGrabber::SetCallback to have the filter invoke a callback function whenever it receives a sample.

The filter does not support video types with top-down orientation (negative biHeight) or with format type FORMAT_VideoInfo2. Also, it rejects any video type where the surface stride does not match the video width. This means that for some video types, the Sample Grabber will not connect to the Video Mixing Renderer (VMR).

See Also

  • Using the Sample Grabber


Smart Tee Filter

The Smart Tee filter is used in video capture graphs to split the video stream into a preview stream and a capture stream. This is done without any additional data copying. The output pins support whatever media types are supported on the downstream connection.

The Smart Tee filter is useful when a video capture filter does not provide separate pins for capture and preview. The Smart Tee filter delivers preview data only if doing so does not hurt capture performance. It also removes the time stamps from the preview stream. The capture graph builder automatically inserts the Smart Tee filter when needed. For more information, see Combining Video Capture and Preview.

The following illustration shows a typical capture graph that uses the Smart Tee filter.

Using the Smart Tee Filter

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMStreamControl, IPin, IQualityControl
Filter CLSID | CLSID_SmartTee
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory


Tee/Sink-to-Sink Converter

The Tee/Sink-to-Sink Converter is a kernel-mode, KsProxy-based filter. It is used in analog video television filter graphs where VBI data is being rendered or captured. The filter is connected upstream to the WDM Video Capture Filter and provides an efficient means to duplicate streams of data within kernel mode without the expensive transitions between kernel and user mode. It delivers each received data block to all output pins, and the downstream codec is responsible for finding the specific VBI data to decode.

The other important function of the Tee/Sink-to-Sink Converter is not really relevant for application programmers, but is mentioned here for completeness. The "Sink-to-Sink" capability was required for the Microsoft® Windows 98® platform to enabled the connection of two drivers that each supported only incoming IRPs. This functionality is now performed by other components in the WDM architecture.

The Tee/Sink-to-Sink Converter appears in the "WDM Streaming Tee/Splitter Devices" filter category (AM_KSCATEGORY_SPLITTER).

Because this is a kernel-mode filter, applications cannot create it directly using CoCreateInstance. Instead, use the System Device Enumerator. For more information, see Creating Kernel-Mode Filters.


TV Audio Filter

The TV Audio filter provides control of television audio decoding, stereo or monoaural selection, and secondary audio program (SAP) selection.

Filter Interfaces | IAMTVAudio, IPersistPropertyBag, ISpecifyPropertyPages, IKsPropertySet
Input Pin Media Types | MEDIATYPE_AnalogAudio
Input Pin Interfaces | IKsPropertySet
Output Pin Media Types | MEDIATYPE_AnalogAudio
Output Pin Interfaces | IKsPropertySet
Filter CLSID | CLSID_TVAudioFilter
Property Page CLSID | AM_KSCATEGORY_TVAUDIO
Executable |
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_AudioInputDeviceCategory


TV Tuner Filter

The TV Tuner filter selects an analog broadcast or cable channel to be viewed. The single output stream is a hardware path for analog baseband video. This output should connect to the Analog Video Crossbar filter. The input pins include an input for cable and an antenna input.

Filter Interfaces | IBaseFilter, IAMTVTuner, ISpecifyPropertyPages, IPersistPropertyBag, IKsObject, IKsPropertySet
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | Video: MEDIATYPE_AnalogVideo, KSDATAFORMAT_SUBTYPE_NONE Audio: MEDIATYPE_AnalogAudio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IPin
Filter CLSID | CLSID_TVTunerFilter
Property Page CLSID | CLSID_TVTunerFilterPropertyPage
Executable | KSTVTune.ax
Merit | MERIT_DO_NOT_USE
Filter Category | AM_KSCATEGORY_TVTUNER


VBI Surface Allocator

The VBI Surface Allocator controls the allocation of VBI buffers in analog television graphs with hardware video port capture scenarios. With devices such as the Bt829 decoder, the frame buffer may contain multiple VBI capture buffers that are accessed via a proprietary hardware-based mechanism known generically as a Video Port. The VBI Surface Allocator filter connects downstream from the capture filter and has no output pin. The filter works closely with the Overlay Mixer (via DirectDraw) to perform coordinated operations on the hardware video port, utilizing the same limited SVGA frame buffer memory.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_VPVBI
Input Pin Interfaces | IKsPropertySet
Output Pin Media Types | MEDIATYPE_NULL, MEDIASUBTYPE_NULL. (Nothing is ever connected to the output pin.)
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_VBISurfaces
Property Page CLSID | No property page.
Executable | vbisurf.ax
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

On Windows 98SE and Windows 2000, the VBI Surface Allocator does not support video port connections on secondary monitors. The pin connection will fail in this case. This limitation does not exist on Windows Me or Windows XP.


VFW Capture Filter

This filter works with older video capture hardware that uses Video For Windows.

This filter has two output pins. One is called Capture, and the other is called either Preview or Overlay.

Filter Interfaces | IPersistPropertyBag, IAMVfwCaptureDialogs, IAMFilterMiscFlags, IBaseFilter, ISpecifyPropertyPages, IOverlayNotify
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | Capture: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo Overlay: MEDIATYPE_Video, MEDIASUBTYPE_Overlay, FORMAT_VideoInfo Preview: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | Capture: IAMBufferNegotiation, IAMDroppedFrames, IAMPushSource, IAMStreamConfig, IAMStreamControl, IAMVideoCompression, IKsPropertySet, IPin, IQualityControl Overlay: IAMStreamControl, IKsPropertySet, IPin, IQualityControl Preview: IAMPushSource, IAMStreamControl, IKsPropertySet, IPin, IQualityControl
Filter CLSID | CLSID_VfwCapture
Property Page CLSID | CLSID_CaptureProperties
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_VideoInputDeviceCategory

See Also

  • Video Capture


VGA 16 Color Ditherer Filter

The VGA 16 Color Ditherer filter converts from an RGB color type to a 4-bit color display so that AVI and MPEG video streams may be displayed on older 16-color monitors. This filter is inserted in the graph between a decompressor filter and a video renderer filter.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_RGB8
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_RGB4
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_Dither
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory


Video Mixing Renderer Filter 7

This topic applies to Windows XP only.

In Microsoft® Windows® XP, the Video Mixing Renderer 7 (VMR-7) is the default video renderer. It is called the VMR-7 because internally it uses DirectDraw 7. In DirectX 9, a similar but separate filter, the VMR-9, is available for redistribution on non-XP systems. The VMR-9 uses Direct3D 9.

Note The VMR is available only on Windows XP. It is not available through the DirectX redistributable, or on previous versions of Windows. For most scenarios, application developers are encouraged to use the Video Mixing Renderer 9.

Features of the VMR include:

  • True alpha blending of up to 16 input streams
  • Access to the composited image before it is rendered
  • A plug-in model that enables third-parties to implement custom video effects.

During graph building on Windows XP, the Filter Graph Manager will not use the older Video Renderer or Overlay Mixer filters, unless the application explicitly creates them and adds to the graph.

For more information, see Using the Video Mixing Renderer.

Filter Interfaces | IAMVideoAccelerator, IBaseFilter, IBasicVideo, IBasicVideo2, IQualProp, IVideoWindow, IVMRAspectRatioControl, IVMRDeinterlaceControl, IVMRFilterConfig, IVMRImageCompositor, IVMRImagePresenter, IVMRImagePresenterConfig, IVMRMixerBitmap, IVMRMixerControl, IVMRSurfaceAllocator, IVMRSurfaceAllocatorNotify, IVMRWindowlessControl
Input Pin Media Types | Any type with a major type of MEDIATYPE_Video.
Input Pin Interfaces | IAMVideoAccelerator, IMemInputPin, IOverlay (see Remarks), IPin, IPinConnection, IQualityControl, IVMRVideoStreamControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID There are two CLSIDs associated with this filter:
  • CLSID_VideoMixingRenderer: Creates the VMR-7. If there are not enough system resources to create the VMR-7, the call to CoCreateInstance fails.
  • CLSID_VideoRendererDefault: Creates the VMR-7 if system resources are available, or else creates the old Video Renderer filter.

Use CLSID_VideoMixingRenderer if you need the specific capabilities of the VMR-7. Otherwise, use CLSID_VideoRendererDefault, which is almost certain not to fail, because it falls back to the old Video Renderer filter.

Property Page CLSID | N/A
Executable | Quartz.dll
Merit | MERIT_PREFERRED + 1
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The input pin exposes the IOverlay interface only when the VMR-7 filter is in windowed mode. The only IOverlay method that the pin implements is GetWindowHandle, which enables an application to obtain a handle to the filter's video window. All other IOverlay methods return E_NOTIMPL. In windowless mode, the filter does not create a video window, so the pin does not expose the interface.


Video Mixing Renderer Filter 9

In DirectX 9, the Video Mixing Renderer 9 (VMR-9) filter offers advanced video rendering capabilities on all platforms supported by DirectX. It is fully integrated with DirectX 9 3D capabilities. For example, that you can easily add video to games and other 3D environments or transform video images using the Direct3D pixel shaders and other effects.

This filter does not support video ports.

To maintain backward compatibility, the VMR-9 is not the default renderer on any system. To use this filter, add it to the filter graph explicitly and configure it before connecting any of its input pins. The VMR-9 uses its own set of interfaces, structures, and enumerations, which are not always identical to the corresponding data types used with the VMR-7. For more information, see Using the Video Mixing Renderer.

Filter Interfaces | IAMVideoAccelerator, IBaseFilter, IBasicVideo, IBasicVideo2, IQualProp, IVideoWindow, IVMRAspectRatioControl9, IVMRDeinterlaceControl9, IVMRFilterConfig9, IVMRImageCompositor9, IVMRImagePresenter9, IVMRImagePresenterConfig9, IVMRMixerBitmap9, IVMRMixerControl9, IVMRMonitorConfig9, IVMRSurface9, IVMRSurfaceAllocator9, IVMRSurfaceAllocatorNotify9, IVMRWindowlessControl9
Input Pin Media Types | The input pins will connect with any type supported by the underlying video hardware.
Input Pin Interfaces | IAMVideoAccelerator, IMemInputPin, IOverlay, IQualityControl, IPin, IPinConnection, IVMRVideoStreamControl9
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_VideoMixingRenderer9
Property Page CLSID | N/A
Executable | Quartz.dll
Merit | MERIT_DO_NOT_USE
Filter Category | CLSID_LegacyAmFilterCategory


Video Port Manager

The Video Port Manager filter (VPM) enables the Video Mixing Renderer Filter 7 (VMR-7) to work with video capture devices or hardware decoders that use a video port. A video port is a direct hardware connection to the graphics chip. It enables video to be transferred directly to the graphics chip without going over the system bus.

Note The Video Port Manager is not compatible with the VMR-9, because the VMR-9 does not support video ports.

Filter Interfaces | IAMVideoDecimationProperties, IBaseFilter, IKsPropertySet, IQualProp, IVPManager
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_VPVideo or MEDIASUBTYPE_VPVBI, FORMAT_None
Input Pin Interfaces | IKsPin, IKsPropertySet, IMemInputPin, IPin, IPinConnection, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, FORMAT_VideoInfo2
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_VideoPortManager
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The Video Port Manager combines the video port functionality of the Overlay Mixer Filter and the functionality of the VBI Surface Allocator. The VPM allocates video ports and surfaces, and synchronizes data capture from the video port. It allows video port-based capture that is independent of rendering. If preview is desired, the VPM coordinates with the VMR-7 to display captured video port data. When a video port is present on the system, the capture filter requires additional buffers to extract VBI data from the video stream. These buffers are provided by the VPM. Once the capture filter has extracted the VBI data, it delivers it on a separate pin to filters such as the CC Decoder. The following illustration shows the VPM and its connections in a filter graph.

Video Port Manager filter graph segment

The DVD Graph Builder adds the VPM to the filter graph automatically when a video port is detected on the system. Once added to the graph, the VPM uses a DirectDraw object provided by the Video Mixing Renderer to allocate two or three surfaces. These surfaces receive the digitized frames from the upstream capture filter. In response to user-mode event notifications sent when data is present in the surface, the VPM performs an automatic blit to an offscreen surface provided by the VMR.

The fact that the VPM uses multiple surfaces for its input buffers means that it requires more VRAM than the previous DirectShow video port implementation. The extra blit from the VPM to the VMR-7 requires additional video memory bandwidth. And since hardware auto-flipping is not used any longer, there is a theoretical potential for dropped frames, but the empirical evidence suggests that this does not occur.

See Also

  • IVPManager Interface


Video Renderer Filter

The Video Renderer filter is a robust, all-purpose video renderer.

Note In Microsoft Windows XP, the default video renderer is the Video Mixing Renderer (VMR). The VMR and the Video Renderer both have the friendly name "Video Renderer." On all other platforms, the Video Renderer is the default renderer, although applications can use the VMR-9 for advanced rendering capabilities.

The Video Renderer uses Microsoft® DirectDraw® and overlay surfaces, if the video card supports them. The Filter Graph Manager exposes the IVideoWindow interface, which enables applications to set and retrieve properties on the Video Renderer. With newer video cards, the Video Renderer supports full-screen rendering. Otherwise, the Filter Graph Manager automatically switches to the Full Screen Renderer filter for full-screen mode. See IVideoWindow::put_FullScreenMode for more information.

Important Normally, this filter's video window processes messages on a worker thread created by the Filter Graph Manager. Howerver, if an application directly creates the filter using CoCreateInstance, the video window processes messages on the application thread. In that case, the application thread must have a message loop, to dispatch messages to the video window. Also, the thread must not exit until the final Release call to the Video Renderer, which occurs when the Filter Graph Manager shuts down. Otherwise, the application might deadlock.

Filter Interfaces | IBaseFilter, IBasicVideo, IBasicVideo2, IDirectDrawVideo, IKsPropertySet, IMediaPosition, IMediaSeeking, IQualityControl, IQualProp, IVideoWindow
Input Pin Media Types | MEDIATYPE_Video
Input Pin Interfaces | IMemInputPin, IOverlay, IPin, IPinConnection, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_VideoRenderer
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | Windows 98, Me, NT, 2000: MERIT_PREFERRED Windows XP: MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

In the debug version of Quartz.dll, if the LOG_TRACE debug level is set to 5 or higher, the Video Renderer displays each frame's time stamps on the video window. These numbers do not appear in the retail version of the DLL. For more information, see Debug Output Functions.

The following remarks are intended for filter developers:

The Video Renderer accepts YUV formats if the video graphics card supports YUV overlay surfaces. When it first connects to the upstream filter, however, the Video Renderer requires an RGB format that matches the color depth of the current monitor settings. For example, if the current display setting is 24-bit color, the upstream filter must be able to provide 24-bit RGB video. When the filter graph switches to a runing state, the Video Renderer negotiates a dynamic format change to the appropriate YUV color space.

By connecting with an RGB type, the Video Renderer ensures that it can use GDI in case DirectDraw is not available. It will switch to GDI if another application is using the video memory, if the video rectangle straddles two monitors on a multi-monitor system, or if the video rectangle is completely obscured by another window.

Note The Video Mixing Renderer does not perform this type of dynamic format change, and does not require an RGB media type, because it never uses GDI for rendering.

To negotiate a format change, the Video Renderer calls IPin::QueryAccept with the new media type. If the upstream filter returns S_OK, the Video Renderer attaches the new media to the next sample. The upstream filter should call IMediaSample::GetMediaType on each sample. If GetMediaType returns a non-NULL value, it indicates a format change, and the upstream filter should respond by switching output types. (Do not switch types in the QueryAccept method.) The upstream filter should accept at least the major RGB types, and ideally should support the common YUV types. During streaming, the Video Renderer might switch back and forth between YUV and RGB types any number of times. The Video Renderer does not accept dynamic format changes initiated by the upstream filter.

When the Video Renderer draws to a DirectDraw overlay surface, it allocates a single buffer for its input pin. If the upstream filter attempts to force a connection using multiple buffers, the Video Renderer will be unable to use the overlay surface.


WAVE Parser Filter

The WAVE Parser filter parses WAV-format audio data from .wav, .au, or .aif files. The upstream filter must be the Async File Source filter, URL File Source filter, or a compatible third-party asynchronous source filter that contains WAV audio data. The output stream is audio data, which you can connect directly to an audio rendering filter or to an intervening audio transform filter.

Filter Interfaces | IAMMediaContent, IBaseFilter, IPersistMediaPropertyBag
Input Pin Media Types MEDIATYPE_Stream

The following subtypes are valid:
  • MEDIASUBTYPE_AIFF
  • MEDIASUBTYPE_AU
  • MEDIASUBTYPE_WAVE
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_WAVEParser
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory


WDM Video Capture Filter

The WDM Video Capture filter controls analog capture devices that use Windows Driver Model (WDM) drivers.

This filter is actually a kernel-mode KsProxy plug-in. It provides property pages and the COM interfaces for WDM drivers that control analog capture devices (also called analog video decoders). An application can treat it simply as a filter. To add this filter to a filter graph, use the System Device Enumerator. It returns a unique moniker for each device that uses this plug-in. For more information, see Enumerating Devices and Filters and How Hardware Devices Participate in the Filter Graph. As with any filter based on KsProxy, the friendly name of the filter will depend on the underlying driver.

Not all devices that are exposed through the WDM Video Capture Filter will implement all of the interfaces listed below. The application can use QueryInterface to determine which interfaces are supported by a particular device.

Filter Interfaces | The WDM driver for the device may support one or more of the following: IAMAnalogVideoDecoder, IAMCameraControl, IAMDroppedFrames, IAMExtDevice, IAMExtTransport, IAMFilterMiscFlags, IAMTimecodeReader, IAMVideoCompression, IAMVideoControl, IAMVideoProcAmp, IBaseFilter, IKsPropertySet, IMediaSeeking, IReferenceClock, ISpecifyPropertyPages.
Input Pin Media Types | Driver-dependent.
Input Pin Interfaces | Driver-dependent.
Output Pin Media Types | Driver-dependent.
Output Pin Interfaces | The driver may support one or more of the following: IAMBufferNegotiation, IAMStreamConfig, IAMStreamControl, IKsPin, IKsPropertySet, IStreamBuilder, IMediaSeeking, IPin, IQualityControl, ISpecifyPropertyPages
Filter CLSID | Not applicable.
Property Page CLSID | Driver-dependent.
Plug-in Executable | kswdmcap.ax
Merit | Driver-dependent.
Filter Category | CLSID_VideoInputDeviceCategory

See Also

  • Video Capture


Windows Media Source Filter

This filter is the legacy source filter for Windows Media® content. It is used by Windows Media Player 6.4. In general, the simplest and most reliable way to use this filter is to use the Windows Media Player 6.4 ActiveX control. Many of the methods exposed by this filter are also exposed through the ActiveX control. See the Windows Media Player SDK for more information.

When this filter is given the name of a local ASF file or a URL for a remote file, it reads the file, parses the compressed streams, and creates an output pin for each one. This filter does not use the Windows Media Format SDK. It uses the installable codec versions of the Windows Media decoders, not the DMO versions. The audio output pin always connects to the ASF ACM Handler filter, and the video pin always connects to the ASF ICM Handler. (ICM in this case refers to the original name of the Video Compression Manager.) The filter does not support seeking.

The following diagram shows a filter graph with this filter.

Windows Media Source Filter Graph

To maintain backward compatibility with Windows Media Player 6.4, this filter is the default source filter for files with .wma, .wmv, and .asf file extensions. For file playback, newer applications should use the WM ASF Reader filter. However, the WM ASF Reader does not support playback of streamed content.

The simplest way for an application to play streamed Windows Media-based content is to use the Windows Media Player SDK. Another option is to use the Windows Media Format SDK. Attempting to create a custom player based on the Windows Media Source Filter is not recommended.

Filter interfaces | IBaseFilter, IAMChannelInfo, IAMExtendedSeeking, IAMMediaContent, IAMOpenProgress, IAMNetShowConfig, IAMNetShowExProps, IAMNetShowPreroll, IAMNetworkStatus, IFileSourceFilter
Input pin media types | Not applicable.
Input pin interfaces | Not applicable.
Output pin media types | Varies depending on the streams within the ASF file.
Output pin interfaces | IMediaSeeking
Filter CLSID | See Remarks
Executable | dxmasf.dll
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

Remarks

The filter's CLSID is not defined in qnetwork.h. Use this macro in your own header file:

//  {6B6D0800-9ADA-11d0-A520-00A0D10129C0}
DEFINE_GUID(CLSID_NetShowSource,
0x6b6d0800, 0x9ada, 0x11d0, 0xa5, 0x20, 0x0, 0xa0, 0xd1, 0x1, 0x29, 0xc0);

See Also

  • Reading ASF Files in DirectShow
  • WM ASF Reader Filter


WM ASF Reader Filter

The WM ASF Reader is a wrapper filter for the reader object provided with the Microsoft Windows Media™ Format SDK and is the recommended source filter for file playback of Windows Media-based content and content created with any of the Microsoft MPEG-4 Encoder DMOs. In DirectX 9.x and DirectX 8.x, this filter is never used by IGraphBuilder::RenderFile. It must be explicitly added to a filter graph using its CLSID.

Note The most recent version of this filter will become available in the Windows Media Format 9 Series SDK. The new version of the WM ASF Reader is the default source filter for Windows Media-based content and it is used by RenderFile.

In general, this version of the WM ASF Reader is the one that applications should use to play ASF content, including Windows Media Audio and Windows Media Video as well as MPEG-4 content authored with the Microsoft MPEG-4 Encoder. Seeking performance is much better than with the Windows Media Source Filter. However, only ASF files that have been authored with an index are seekable.

When given the name of an ASF file or a URL, the WM ASF Reader reads the compressed content, parses the compressed streams, and exposes an output pin for each one. This filter connects downstream to audio and/or video codecs filters, which do the decompression. Seeking is supported if the ASF file is seekable. The ASF Reader time stamps the samples before sending them downstream, but it does not modify the time stamps in any way.

To use this filter you must install the Microsoft® Windows Media™ Format (SDK).

Filter interfaces | IBaseFilter, IFileSourceFilter, IAMExtendedSeeking, IServiceProvider Windows Media Format SDK interfaces exposed through the filter: IWMHeaderInfo, IWMReaderAdvanced, IWMReaderAdvanced2
Input pin media types | Not applicable.
Input pin interfaces | Not applicable.
Output pin media types | Varies depending on the streams within the ASF file.
Output pin interfaces | IMediaSeeking
Filter CLSID | CLSID_WMAsfReader {187463A0-5BB7-11d3-ACBE-0080C75E246E}
Property Page CLSID | No property page.
Executable | Qasf.dll
Merit | MERIT_UNLIKELY
Filter Category | CLSID_LegacyAmFilterCategory

See Also

  • Reading ASF Files in DirectShow
  • Windows Media Source Filter


WM ASF Writer Filter

The WM ASF Writer is a wrapper filter for the writer object provided with the Windows Media™ Format SDK. The filter accepts a variable number of input streams and creates an Advanced Systems Format (ASF) file. The filter handles all compression and multiplexing (although the compression mechanism can be bypassed). You can use the WM ASF Writer in various scenarios including digital video (DV) capture, audio recompression, and conversion of Audio-Video Interleaved (AVI) or MPEG multimedia files for network streaming. This filter provides the only way to create Microsoft® Windows Media™ Audio and Windows Media Video files in Microsoft DirectShow.

For more information, see Creating ASF Files in DirectShow.

Filter interfaces | IAMFilterMiscFlags, IBaseFilter, IConfigAsfWriter, IFileSinkFilter2, IMediaSeeking, IPersistStream, IServiceProvider, ISpecifyPropertyPages
Input pin media types | Depends on the ASF profile. Typically uncompressed audio and video types, although the filter will accept compressed types if they match the ASF profile.
Input pin interfaces | IPin, IMemInputPin, IAMStreamConfig
Output pin media types | Not applicable.
Output pin interfaces | Not applicable.
Filter CLSID | CLSID_WMAsfWriter
Property page CLSID | CLSID_AsfWriterProperties
Executable | Qasf.dll
Merit | MERIT_DO_NOT_USE
Filter Category | Not specified

Remarks

The filter requires the Windows Media Format Software Development Kit (SDK) and its underlying dependencies.

The number of input pins on the filter dependings on the profile or profile identifier of the ASF stream.

The input pins support one method from the IAMStreamConfig interface: IAMStreamConfig::GetFormat. All other methods return E_NOTIMPL. Call the GetFormat method to query the pin's destination compression format, which is defined by the current ASF profile. Use the IConfigAsfWriter interface to set the profile.

The filter's IServiceProvider interface enable applications to retrieve the IWMWriterAdvanced2 interface, which is defined in the Windows Media Format SDK. This interface can only be obtained after the filter has been added to the filter graph. The IWMWriterAdvanced2 interface controls video deinterlacing, and is useful if the input is an interlaced source, such as DV video. Use the GetInputSetting and SetInputSetting methods to control deinterlacing. It is not recommended that clients use any of the other methods on this interface. The following example shows how to query for this interface:

// Assume that m_pGraph is a valid IGraphBuilder interface pointer
// and that pAsfWriter points to the IBaseFilter interface
// on the WM ASF Writer filter

IServiceProvider *pProvider = NULL;
IWMWriterAdvanced2 *pWMWA2 = NULL;

hr = m_pGraph->AddFilter(pAsfWriter, L"WM ASF Writer");
...
hr = pAsfWriter->QueryInterface(IID_IServiceProvider, (void**)&pProvider)
if (SUCCEEDED(hr))
{
    hr = pProvider->QueryService(IID_IWMWriterAdvanced2,
        IID_IWMWriterAdvanced2, (void**)&pWMWA2);
    pProvider->Release();
}


WST Codec Filter

World Standard Teletext (WST) is the European standard for data transmission using VBI on PAL analog television signals. Both captioning and data services are provided using this standard. The WST Codec is a kernel-mode filter that receives raw VBI samples and, optionally, decoded Teletext samples from the Capture Filter via the Tee/Sink-to-Sink Converter filter. This codec decodes and/or duplicates the decoded and forward-error-corrected Teletext data for the WST Decoder filter. The WST Codec corresponds to the CC Decoder filter for NTSC transmissions. The WST Decoder corresponds to the Line 21 Decoder for NTSC; these filters create the bitmaps that are sent to the Overlay Mixer or the Video Mixing Renderer.

This filter has two input pins, VBI and HWCC. The VBI pin is used for raw VBI data, and the HWCC pin is used when the VBI decoding is performed in hardware by the capture filter. When the data is received on the HWCC pin, the WST Codec operates in "pass-through" mode, and sends the data directly to the WST Decoder without processing it in any way. If the capture filter exposes an HWCC pin, it must be connected directly to the corresponding pin on the WST Codec.

The WST Codec filter appears in the "WDM Streaming VBI Codecs" filter category (AM_KSCATEGORY_VBICODEC).

Because this is a kernel-mode filter, applications cannot create it directly using CoCreateInstance. Instead, use the System Device Enumerator. For more information, see Creating Kernel-Mode Filters.

See Also

  • Viewing World Standard Teletext


WST Decoder Filter

The WST Decoder is a kernel-mode filter that accepts decoded World Standard Teletext data from the WST Codec and delivers the bitmaps to Pin 2 on the Overlay Mixer using fonts supplied by Microsoft. Only Western European languages are supported at this time; no Unicode fonts are currently provided.

This filter can be added to the graph automatically by calling ICaptureGraphBuilder2::RenderStream, using the output pin of the WST Codec.

Filter Interfaces | ISpecifyPropertyPages, IAMWstDecoder
Input Pin Media Types | MEDIATYPE_VBI, MEDIASUBTYPE_TELETEXT
Input Pin Interfaces | IPin
Output Pin Media Types | MEDIATYPE_Video
Output Pin Interfaces | IPin
Filter CLSID | CLSID_WSTDecoder
Property Page CLSID | CLSID_WstDecoderPropertyPage
Executable | Wstdecod.DLL
Merit | MERIT_NORMAL
Filter Category | CLSID_LegacyAmFilterCategory

See Also

  • Viewing World Standard Teletext


Interfaces

This topic contains reference information for the Microsoft® DirectShow® core interfaces. To provide broad support for various types of hardware, file formats, and stream operations, implements a large number of interfaces. Some are used by applications; others are used internally by filters and other DirectShow components.

Any particular application will use only a small subset of these interfaces, depending on the nature of the application.

  • Interfaces for Building Filter Graphs
  • Interfaces for Controlling a Filter Graph
  • Audio Capture and Rendering Interfaces
  • DVD Interfaces
  • Video Capture Interfaces
  • File Encoding and Decoding Interfaces
  • Interfaces for Video Rendering and Overlay
  • Analog TV Tuning Interfaces
  • External Device Control Interfaces
  • Alphabetical List of DirectShow Interfaces

See Also

  • DirectShow Objects
  • DirectShow Filters
  • DirectShow Editing Services C++ Reference


Interfaces for Building Filter Graphs

Applications use these interfaces to build various types of filter graphs.

Interface | Description
IAMFilterGraphCallback | Receive callback notifications if a pin cannot be rendered.
IAMGraphBuilderCallback | Provides a callback mechanism during graph building.
ICaptureGraphBuilder2 | Build filter graphs for video capture.
ICreateDevEnum | Enumerate system devices, such as capture devices.
IDvdGraphBuilder | Build filter graphs for DVD navigation and playback.
IEnumFilters | Enumerate the filters in the graph.
IFilterGraph2 | Add, remove, or connect filters.
IFilterMapper2 | Enumerate the filters registered on the user's system.
IGraphBuilder | Build filter graphs for file playback or for custom uses.
IGraphConfig | Dynamically reconfigure a filter graph.
IGraphVersion | Determine when the graph changes.


Interfaces for Controlling a Filter Graph

These interfaces provide methods for controlling a filter graph.

Interface | Description
IAMClockAdjust | Adjust the graph clock.
IAMGraphStreams | Synchronize live streams in a filter graph.
IFilterChain | Control chains of filters.
IMediaControl | Run, pause, and stop the filter graph. (Also provides Automation-compatible methods for building graphs.)
IMediaEventEx | Respond to events in the graph.
IMediaSeeking | Seek within a file.
IQueueCommand | Queue commands to run at a later time.
IVideoFrameStep | Frame-step through a video stream.


Audio Capture and Rendering Interfaces

These interfaces support capture and rendering of audio.

Interface | Description
IAMAudioInputMixer | Access the analog inputs on the system's sound card and adjust characteristics, such as mono or stereo, mix level, pan level, loudness, treble, and bass.
IAMAudioRendererStats | Get statistical performance information about audio renderering.
IAMBufferNegotiation | Control how the audio capture filter allocates buffers.
IAMClockSlave | Control the tolerance of an audio renderer when it matches rates with another clock.
IAMDirectSound | Enables an application to specify which widow has focus for controlling DirectSound audio playback.
IAMResourceControl | Hold an audio device resource before it is needed.
IAMStreamConfig | Query and set the capture filter's output format.
IBasicAudio | Set audio output volume and balance.


DVD Interfaces

These interfaces support DVD playback and navigation.

Interface | Description
IAMDecoderCaps | Implemented by decoders to indicate various capabilities.
IDvdCmd | Block the DVD Navigator Filter until a command starts or completes.
IDvdControl2 | Navigate and play DVD-Video titles, including karaoke titles.
IDvdGraphBuilder | Build a filter graph for DVD-Video playback from the available software and hardware on the system.
IDvdInfo2 | Query for various attributes of a DVD disc or the DVD Navigator's state.
IDvdState | Save the state of the user's session to disk, including playback location, parental level, and region.


Video Capture Interfaces

These interfaces support video capture, using Microsoft® Windows® Driver Model (WDM) devices or legacy Microsoft® Video for Windows® (VFW) devices.

Interface | Description
IAMAnalogVideoDecoder | Control video digitization on a WDM video capture card.
IAMBufferNegotiation | Control how a pin allocates buffers.
IAMCopyCaptureFileProgress | Callback interface to receive the progress of a file copy operation.
IAMCrossbar | Create a hardware connection between a WDM audio or video source and a WDM capture device.
IAMDroppedFrames | Query a capture filter about capture performance.
IAMStreamControl | Control the start and stop times of individual streams.
IAMStreamConfig | Query and set the capture filter's output format.
IAMVfwCaptureDialogs | Display the dialog boxes provided by VFW capture drivers.
IAMVideoControl | Control the picture from a capture device.
IAMVideoProcAmp | Adjust the qualities of a video signal, such as brightness, contrast, hue, saturation, gamma, and sharpness.
ICaptureGraphBuilder2 | Build filter graphs for video capture.
IFileSinkFilter2 | Specify the name and attributes of an output file.

See Also

  • External Device Control Interfaces
  • Video Capture


File Encoding and Decoding Interfaces

These interfaces support file encoding and decoding.

Interface | Description
IAMMediaContent | Retrieve meta-data from a stream, such as the author and title.
IAMOpenProgress | Determine the progress of a file-open operation.
IAMParse | Query and set the parse time for the current position in an MPEG stream.
IAMStreamSelect | Control which logical streams are played, and retrieve information about them.
IAMVfwCompressDialogs | Display dialog boxes provided by VFW codecs.
IAMVideoCompression | Set video compression parameters.
IConfigAsfWriter | Control how the WM ASF Writer filter writes Advanced Systems Format (ASF) files.
IConfigAviMux | Control how the AVI Mux filter writes AVI files.
IConfigInterleaving | Configure interleaving when the AVI Mux filter writes AVI files.
IDVEnc | Set the encoding resolution on the DV Video Encoder filter.
IDVSplitter | Downgrade the frame rate on a digital video (DV) stream
IIPDVDec | Set the decoding resolution on the DV Video Decoder filter.
IPersistMediaPropertyBag | Set and retrieve INFO and DISP chunks in AVI streams.


Interfaces for Video Rendering and Overlay

These interfaces support application control over video rendering. Note that some of these interfaces are now deprecated, because the Video Mixing Renderer filter provides superior rendering and overlay control.

Interface | Description
IAMLine21Decoder | Provides access to closed-captioned information and settings.
IAMOverlayFX | Apply overlay effects to the video surface. (Deprecated.)
IAMVideoDecimationProperties | Control how DirectShow scales a video image if the video window is smaller than the native size of the video. (Deprecated.)
IBasicVideo2 | Set video properties.
IDDrawExclModeVideo | Render video in Microsoft DirectDraw exclusive full-screen mode. (Deprecated.)
IDDrawExclModeVideoCallback | Callback interface to receive notification about changes to the overlay position, size, and visibility. (Deprecated.)
IDirectDrawVideo | Disable specified DirectDraw capabilities. (Deprecated.)
IDirectDrawMediaSample | Access a DirectDraw surface allocated by the Overlay Mixer filter.(Deprecated.)
IMixerOCX | Implemented on the Overlay Mixer. Enables windowless clients such as ActiveX® controls to get and set properties of the video rectangle and advise the filter of events.
IMixerOCXNotify | Implemented by windowless clients and called by the Overlay Mixer to send notifications of events affecting the video display rectangle.
IMixerPinConfig2 | Set video color controls on the Overlay Mixer filter when mixing multiple video streams. (Deprecated.)
IQualProp | Query a video renderer for performance information.
IVideoWindow | Set video window properties.
IVMRAspectRatioControl9, IVMRDeinterlaceControl9, IVMRFilterConfig9, IVMRImageCompositor9, IVMRImagePresenter9, IVMRImagePresenterConfig9, IVMRMixerBitmap9, IVMRMixerControl9, IVMRMonitorConfig9, IVMRSurface9, IVMRSurfaceAllocator9, IVMRSurfaceAllocatorNotify9, IVMRWindowlessControl9 | Video Mixing Renderer 9 interfaces.
IVMRAspectRatioControl, IVMRDeinterlaceControl, IVMRFilterConfig, IVMRImageCompositor, IVMRImagePresenter, IVMRImagePresenterConfig, IVMRMixerBitmap, IVMRMixerControl, IVMRSurfaceAllocator, IVMRSurfaceAllocatorNotify, IVMRWindowlessControl | Video Mixing Renderer 7 interfaces.

See Also

  • Using the Video Mixing Renderer


Analog TV Tuning Interfaces

These interfaces support analog TV tuning.

Note In Windows XP, applications should use the interfaces defined in Microsoft TV Technologies.

Interface | Description
IAMTVTuner | Control a TV tuner device.
IAMTVAudio | Control the audio from a TV tuner.
IAMAnalogVideoDecoder | Contains methods for selecting the digitization format, indicating the horizontal lock status, and controlling the time constant on the digitizer phase lock loop (PLL).
IAMLine21Decoder | Used to control the display of closed captioning.
IAMWstDecoder | Used to control the dislay of World Standard Teletext (WST).

See Also

  • Analog Television
  • Video Capture


External Device Control Interfaces

These interfaces support application control over external devices, such as DV camcorders.

Interface | Description
IAMCameraControl | Control a camera.
IAMExtDevice | Control an external device such as a VCR or camcorder.
IAMExtTransport | Control VCR transport functions, such as play, pause, record, fast-forward, and rewind.
IAMTimecodeDisplay | Set properties on a device that displays SMPTE timecode.
IAMTimecodeGenerator | Set properties on a device that generates SMPTE timecode.
IAMTimecodeReader | Read SMPTE timecode from an external device.

See Also

  • Controlling a DV Camcorder


Alphabetical List of DirectShow Interfaces

The following is an alphabetical list of the core DirectShow interfaces.

  • IAMAnalogVideoDecoder
  • IAMAudioInputMixer
  • IAMAudioRendererStats
  • IAMBufferNegotiation
  • IAMCameraControl
  • IAMChannelInfo
  • IAMClockAdjust
  • IAMClockSlave
  • IAMCopyCaptureFileProgress
  • IAMCrossbar
  • IAMDecoderCaps
  • IAMDirectSound
  • IAMDroppedFrames
  • IAMExtDevice
  • IAMExtTransport
  • IAMExtendedErrorInfo
  • IAMExtendedSeeking
  • IAMFilterGraphCallback
  • IAMFilterMiscFlags
  • IAMGraphBuilderCallback
  • IAMGraphStreams
  • IAMLatency
  • IAMLine21Decoder
  • IAMMediaContent
  • IAMMediaContent2
  • IAMNetShowConfig
  • IAMNetShowExProps
  • IAMNetShowPreroll
  • IAMNetworkStatus
  • IAMOpenProgress
  • IAMOverlayFX
  • IAMParse
  • IAMPushSource
  • IAMResourceControl
  • IAMStats
  • IAMStreamConfig
  • IAMStreamControl
  • IAMStreamSelect
  • IAMTimecodeDisplay
  • IAMTimecodeGenerator
  • IAMTimecodeReader
  • IAMTuner
  • IAMTVAudio
  • IAMTVTuner
  • IAMVfwCaptureDialogs
  • IAMVfwCompressDialogs
  • IAMVideoAccelerator
  • IAMVideoAcceleratorNotify
  • IAMVideoCompression
  • IAMVideoControl
  • IAMVideoDecimationProperties
  • IAMVideoProcAmp
  • IAMWstDecoder
  • IAsyncReader
  • IBaseFilter
  • IBasicAudio
  • IBasicVideo
  • IBasicVideo2
  • ICaptureGraphBuilder2
  • ICodecAPI
  • IConfigAsfWriter
  • IConfigAviMux
  • IConfigInterleaving
  • ICreateDevEnum
  • IDDrawExclModeVideo
  • IDDrawExclModeVideoCallback
  • IDecimateVideoImage
  • IDeferredCommand
  • IDirectDrawVideo
  • IDirectDrawMediaSample
  • IDirectDrawMediaSampleAllocator
  • IDistributorNotify
  • IDMOWrapperFilter
  • IDShowPlugin
  • IDvdCmd
  • IDvdControl2
  • IDvdGraphBuilder
  • IDvdInfo2
  • IDvdState
  • IDVEnc
  • IDVRGB219
  • IDVSplitter
  • IEncoderAPI
  • IEnumFilters
  • IEnumMediaTypes
  • IEnumPIDMap
  • IEnumPins
  • IEnumStreamIdMap
  • IFileSinkFilter
  • IFileSinkFilter2
  • IFileSourceFilter
  • IFilterChain
  • IFilterGraph
  • IFilterGraph2
  • IFilterMapper2
  • IFullScreenVideoEx
  • IGetCapabilitiesKey
  • IGraphBuilder
  • IGraphConfig
  • IGraphConfigCallback
  • IGraphVersion
  • IIPDVDec
  • IKsPin
  • IKsPropertySet
  • IMediaControl
  • IMediaEvent
  • IMediaEventEx
  • IMediaEventSink
  • IMediaFilter
  • IMediaPosition
  • IMediaPropertyBag
  • IMediaSample
  • IMediaSample2
  • IMediaSeeking
  • IMemAllocator
  • IMemAllocatorCallbackTemp
  • IMemAllocatorNotifyCallbackTemp
  • IMemInputPin
  • IMixerOCX
  • IMixerOCXNotify
  • IMixerPinConfig
  • IMixerPinConfig2
  • IMpeg2Demultiplexer
  • IMPEG2PIDMap
  • IMPEG2StreamIdMap
  • IOverlay
  • IOverlayNotify
  • IOverlayNotify2
  • IPersistMediaPropertyBag
  • IPin
  • IPinConnection
  • IPinFlowControl
  • IQualityControl
  • IQualProp
  • IQueueCommand
  • IReferenceClock
  • IRegisterServiceProvider
  • IResourceConsumer
  • IResourceManager
  • ISampleGrabber
  • ISampleGrabberCB
  • ISeekingPassThru
  • IStreamBuilder
  • IVideoFrameStep
  • IVideoWindow
  • IVMRAspectRatioControl
  • IVMRAspectRatioControl9
  • IVMRDeinterlaceControl
  • IVMRDeinterlaceControl9
  • IVMRFilterConfig
  • IVMRFilterConfig9
  • IVMRImageCompositor
  • IVMRImageCompositor9
  • IVMRImagePresenter
  • IVMRImagePresenter9
  • IVMRImagePresenterConfig
  • IVMRImagePresenterConfig9
  • IVMRImagePresenterExclModeConfig
  • IVMRMixerBitmap
  • IVMRMixerBitmap9
  • IVMRMixerControl
  • IVMRMixerControl9
  • IVMRMonitorConfig
  • IVMRMonitorConfig9
  • IVMRSurface
  • IVMRSurface9
  • IVMRSurfaceAllocator
  • IVMRSurfaceAllocator9
  • IVMRSurfaceAllocatorNotify
  • IVMRSurfaceAllocatorNotify9
  • IVMRVideoStreamControl
  • IVMRVideoStreamControl9
  • IVMRWindowlessControl
  • IVMRWindowlessControl9
  • IVPBaseConfig
  • IVPBaseNotify
  • IVPConfig
  • IVPManager
  • IVPNotify
  • IVPNotify2

See Also

  • Deprecated Interfaces


IAMAnalogVideoDecoder Interface

The IAMAnalogVideoDecoder interface sets and retrieves information about the analog-to-digital conversion process in a video capture filter.

The WDM Video Capture filter exposes this interface if the device is an analog video capture device. Applications can use this interface to control aspects of the analog decoding process, such as the analog video format and the horizontal sync lock.

In addition to the methods inherited from IUnknown, the IAMAnalogVideoDecoder interface exposes the following methods.

Method | Description
get_AvailableTVFormats | Retrieves the analog video formats that the decoder supports.
get_HorizontalLocked | Determines whether the horizontal sync is locked.
get_NumberOfLines | Retrieves the number of scan lines in the video signal.
get_OutputEnable | Determines whether the video port bus is enabled.
get_TVFormat | Retrieves the current analog video format.
get_VCRHorizontalLocking | Indicates whether the decoder is expecting video from a tape source or a broadcast source
put_OutputEnable | Enables or disables the video port bus.
put_TVFormat | Sets the analog video format.
put_VCRHorizontalLocking | Specifies whether the video is a tape source or a broadcast source.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_VIDEODECODER property set. For more information, see the Windows DDK documenation.


IAMAnalogVideoDecoder::get_AvailableTVFormats

The get_AvailableTVFormats method retrieves the analog video formats that the decoder supports.

Syntax

HRESULT get_AvailableTVFormats(
  long *lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard

[out] Pointer to a variable that receives a bitwise OR of zero or more flags from the AnalogVideoStandard enumeration.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::get_HorizontalLocked

The get_HorizontalLocked method determines whether the horizontal sync is locked.

Syntax

HRESULT get_HorizontalLocked(
  long *plLocked
);

Parameters

plLocked

[out] Pointer to a variable that receives one of the following values.

Value | Description
0 | Horizontal sync is not locked.
1 | Horizontal sync is locked

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::get_NumberOfLines

The get_NumberOfLInes method retrieves the number of scan lines in the video signal.

Syntax

HRESULT get_NumberOfLines(
  long *plNumberOfLines
);

Parameters

plNumberOfLines

[out] Pointer to a variable that receives the number of scan lines in the video signal. This is generally by 525 lines for NTSC and 625 lines for PAL or SECAM.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::get_OutputEnable

The get_OutputEnable method determines whether the video port bus is enabled.

Syntax

HRESULT get_OutputEnable(
  long *plOutputEnable
);

Parameters

plOutputEnable

[out] Pointer to a variable that receives one of the following values.

Value | Description
0 | Video port bus is disabled.
1 | Video port bus is enabled.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

Remarks

This method applies only to devices that use a shared video port bus. If the returned value is 1, the device is actively driving the video port bus. If the value is zero, the device is tri-stated.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::get_TVFormat

The get_TVFormat method retrieves the current analog video format.

Syntax

HRESULT get_TVFormat(
  long *plAnalogVideoStandard
);

Parameters

plAnalogVideoStandard

[out] Pointer to a variable that receives a member of the AnalogVideoStandard enumeration, indicating the analog video format.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::get_VCRHorizontalLocking

The get_VCRHorizontalLocking method indicates whether the decoder is expecting video from a tape source or a broadcast source.

Syntax

HRESULT get_VCRHorizontalLocking(
  long *plVCRHorizontalLocking
);

Parameters

plVCRHorizontalLocking

[out] Pointer to a variable that receives one of the following values.

Value | Description
0 | The decoder is expecting video from a broadcast source.
1 | The decoder is expecting video from a tape source.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

Remarks

The timing accuracy of synchronization pulses is typically poorer from a tape source than from a broadcast source. If the returned value is 1, the decoder might relax its sync timing standards.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::put_OutputEnable

The put_OutputEnable method enables or disables the video port bus.

Syntax

HRESULT put_OutputEnable(
  long lOutputEnable
);

Parameters

lOutputEnable

[in] Specifies whether the bus is enabled. Use one of the following values.

Value | Description
0 | Disable the video port bus.
1 | Enable the video port bus.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

Remarks

This method applies only to devices that use a shared video port bus. If the value is 1, the device will actively drive the video port bus. If the value is zero, the device will be tri-stated.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::put_TVFormat

The put_TVFormat method sets the analog video format.

Syntax

HRESULT put_TVFormat(
  long lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard

[in] Specifies the video format as a member of the AnalogVideoStandard enumeration.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAnalogVideoDecoder::put_VCRHorizontalLocking

The put_VCRHorizontalLocking method specifies whether the video is a tape source or a broadcast source.

Syntax

HRESULT put_VCRHorizontalLocking(
  long lVCRHorizontalLocking
);

Parameters

lVCRHorizontalLocking

[in] Specifies one of the following values.

Value | Description
0 | The video is from a broadcast source.
1 | The video is from a tape source.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_PROP_ID_UNSUPPORTED | The device does not support this method.
S_OK | Success.

Remarks

The timing accuracy of synchronization pulses is typically poorer from a tape source than from a broadcast source. Setting the value to 1 tells the decoder to relax its standards, which leads to a better chance of maintaining sync.

See Also

  • Error and Success Codes
  • IAMAnalogVideoDecoder Interface


IAMAudioInputMixer Interface

The IAMAudioInputMixer interface controls audio capture properties, such as panning and loudness; and enables or disables specific audio inputs, such as the line in or the microphone.

The Audio Capture filter exposes this interface on each input pin, as well as on the filter itself. The input pins on the Audio Capture Filter represent physical hardware connections; they are not connected to other DirectShow filters. The pin name indicates the input type; for example, "Line In" or "Microphone." Use the IAMAudioInputMixer interface as follows:

  • To control the settings on a particular input, use the interface on the pin.
  • To set the overall properties when multiple inputs are enabled, use the interface on the filter.
  • To enable or disable an input, call that pin's IAMAudioInputMixer::put_Enable method.

Some methods on this interface might fail, depening on the capabilities of the underlying hardware.

Filter Developers: Implement this interface on each input pin of an audio capture filter. You can also implement this interface on the audio capture filter itself to control the overall audio settings after mixing.

In addition to the methods inherited from IUnknown, the IAMAudioInputMixer interface exposes the following methods.

Method | Description
put_Enable | Enables or disables an input.
get_Enable | Queries whether an input is enabled.
put_Mono | Combines all channels of an input into a mono signal.
get_Mono | Queries whether all the channels of an input are combined into a mono signal.
put_MixLevel | Sets the recording level.
get_MixLevel | Retrieves the recording level.
put_Pan | Sets the pan level.
get_Pan | Retrieves the pan level.
put_Loudness | Sets the loudness control.
get_Loudness | Retrieves the loudness control setting.
put_Treble | Sets the treble equalization.
get_Treble | Retrieves the treble equalization.
get_TrebleRange | Retrieves the treble range.
put_Bass | Sets the bass equalization.
get_Bass | Retrieves the bass equalization.
get_BassRange | Retrieves the bass range.


IAMAudioInputMixer::get_Bass

The get_Bass method retrieves the bass equalization.

Syntax

HRESULT get_Bass(
  double *pBass
);

Parameters

pBass

[in] Pointer to a variable that receives the bass gain, in decibels. A negative value indicates attenuation.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Bass


IAMAudioInputMixer::get_BassRange

The get_BassRange method retrieves the bass range.

Syntax

HRESULT get_BassRange(
  double *pRange
);

Parameters

pRange

[out] Pointer to a variable that receives the largest valid value for the IAMAudioInputMixer::put_Bass method. For example, 6.0 means that any value between –6.0 and 6.0 is valid.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Bass


IAMAudioInputMixer::get_Enable

The get_Enable method retrieves whether the input is enabled.

Syntax

HRESULT get_Enable(
  BOOL *pfEnable
);

Parameters

pfEnable

[in] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | Input is enabled.
FALSE | Input is disabled.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method applies to specific input pins on the Audio Capture Filter, so the filter itself returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Enable


IAMAudioInputMixer::get_Loudness

The get_Loudness method retrieves the loudness control setting.

Syntax

HRESULT get_Loudness(
  BOOL *pfLoudness
);

Parameters

pfLoudness

[in] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | Loudness is on.
FALSE | Loudness is off.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Loudness


IAMAudioInputMixer::get_MixLevel

The get_MixLevel methiod retrieves the recording level.

Syntax

HRESULT get_MixLevel(
  double *pLevel
);

Parameters

pLevel

[out] Pointer to a variable that receives the recording level. The following values are possible.

Value | Description
0.0 to 1.0 | Zero indicates that the recording level is off; the value 1.0 indicates that the recording level is at full volume. Intermediate values are also allowed.
AMF_AUTOMATICGAIN | Automatic adjustment of the recording level is enabled.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_MixLevel


IAMAudioInputMixer::get_Mono

The get_Mono method queries whether all channels are combined into a mono signal.

Syntax

HRESULT get_Mono(
  BOOL *pfMono
);

Parameters

pfMono

[in] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | Mono
FALSE | Multichannel

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Mono


IAMAudioInputMixer::get_Pan

The get_Pan method retrieves the pan level.

Syntax

HRESULT get_Pan(
  double *pPan
);

Parameters

pPan

[in] Pointer to a variable that receives the pan level. Possible values range from from –1.0 to 1.0, as follows:

Value | Description
-1 | Full left
0 | Center
1 | Full right

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Pan


IAMAudioInputMixer::get_Treble

The get_Treble method retrieves the treble equalization.

Syntax

HRESULT get_Treble(
  double *pTreble
);

Parameters

pTreble

[in] Pointer to a variable that receives the treble gain, in decibels. A negative value indicates attenuation.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Treble


IAMAudioInputMixer::get_TrebleRange

The get_TrebleRange method retrieves the treble range for this input.

Syntax

HRESULT get_TrebleRange(
  double *pRange
);

Parameters

pRange

[out] Pointer to a variable that receives the largest valid value for the IAMAudioInputMixer::put_Treble. For example, 6.0 means that any value between –6.0 and 6.0 is valid.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::put_Treble


IAMAudioInputMixer::put_Bass

The put_Bass method sets the bass equalization.

Syntax

HRESULT put_Bass(
  double Bass
);

Parameters

Bass

[in] Specifies the gain, in decibels. A negative value specifies attenuation.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument. Must be in range given by IAMAudioInputMixer::get_BassRange.

Remarks

This method boosts or cuts the signal's bass before it is recorded, by the number of decibels specified in the Bass parameter.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Bass


IAMAudioInputMixer::put_Enable

The put_Enable method enables or disables an input.

Syntax

HRESULT put_Enable(
  BOOL fEnable
);

Parameters

fEnable

[in] Specifies whether to enable or disable the input. Use one of the following values.

Value | Description
TRUE | Enable the input.
FALSE | Disable the input.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

If an input is enabled, it is mixed into the recorded signal.

This method applies to specific input pins on the Audio Capture Filter, so the filter itself returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Enable


IAMAudioInputMixer::put_Loudness

The put_Loudness method enables or disables the loudness control.

Syntax

HRESULT put_Loudness(
  BOOL fLoudness
);

Parameters

fLoudness

[in] Specifies whether loudness is on or off. Use one of the following values.

Value | Description
TRUE | Sets loudness on.
FALSE | Sets loudness off.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Loudness boosts the bass of low volume signals before they are recorded, to compensate for the fact that the ear does not hear quiet bass sounds as well as other sounds.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Loudness


IAMAudioInputMixer::put_MixLevel

The put_MixLevel method sets the recording level for this input.

Syntax

HRESULT put_MixLevel(
  double Level
);

Parameters

Level

[in] Specifies the recording level. The following values are possible.

Value | Description
0.0 to 1.0 | Zero indicates that the recording level is off; the value 1.0 indicates that the recording level is at full volume. Intermediate values are also allowed.
AMF_AUTOMATICGAIN | Enable automatic adjustment of the recording level.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | This filter does not support the AMF_AUTOMATICGAIN flag.
E_INVALIDARG | Invalid argument.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_MixLevel


IAMAudioInputMixer::put_Mono

The put_Mono method combines all channels into a mono signal.

Syntax

HRESULT put_Mono(
  BOOL fMono
);

Parameters

fMono

[in] Specifies mono or multichannel. Use one of the following values.

Value | Description
TRUE | Mono
FALSE | Multichannel

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_FAIL | Error setting mono control.
S_OK | Success.

Remarks

In mono mode, a stereo recording of this input will have the same data in both channels. The result will be a mixture of the left and right signals.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Mono


IAMAudioInputMixer::put_Pan

The put_Pan method sets the pan level.

Syntax

HRESULT put_Pan(
  double Pan
);

Parameters

Pan

[in] Specifies the pan level. Possible values range from –1.0 to 1.0, as follows.

Value | Description
-1 | Full left
0 | Center
1 | Full right

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

In a stereo recording, setting the pan level to -1.0 or 1.0 sends the entire signal to one channel. The other channel records silence. Panning has no effect for a mono recording.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Pan


IAMAudioInputMixer::put_Treble

The put_Treble method sets the treble equalization for this input.

Syntax

HRESULT put_Treble(
  double Treble
);

Parameters

Treble

[in] Specifies the gain, in decibels. A negative value specifies attenuation.

Return Values

Returns an HRESULT value. The following are possible values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid. Must be in range given by IAMAudioInputMixer::get_TrebleRange.

Remarks

This method boosts or cuts the signal's treble by a specified number of decibels before it is recorded.

See Also

  • Error and Success Codes
  • IAMAudioInputMixer Interface
  • IAMAudioInputMixer::get_Treble


IAMAudioRendererStats Interface

The IAMAudioRendererStats interface retrieves statistical performance information from an audio renderer filter.

This interface is intended for use during development, to log performance data from the audio renderer. There is probably no reason for an application to use it in a retail build. The Audio Renderer (WaveOut) filter and the DirectSound Renderer filter both expose this interface.

Filter Developers: It is not expected that other filters will implement this interface.

In addition to the methods inherited from IUnknown, the IAMAudioRendererStats interface exposes the following method.

Method | Description
GetStatParam | Retrieves performance information from the filter.


IAMAudioRendererStats::GetStatParam

The GetStatParam method retrieves performance information from the audio renderer.

Syntax

HRESULT GetStatParam(
    DWORD dwParam,
    DWORD *pdwParam1,
    DWORD *pdwParam2
);

Parameters

dwParam

[in] Specifies a member of the _AM_AUDIO_RENDERER_STAT_PARAM enumeration, indicating which information to retrieve.

pdwParam1

[out] Pointer to a variable that receives performance information. The meaning of the returned value depends on the value of dwParam.

pdwParam2

[out] Pointer to a variable that receives performance information. The meaning of the returned value depends on the value of dwParam.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | The renderer does not track the specified information.
E_POINTER | NULL pointer argument.
S_OK | Success.

Example Code

The following example retrieves the number of breaks in the audio stream:

IBaseFilter *pAudioRenderer;
// Assume pAudioRenderer is a valid pointer to an audio renderer filter.
IAMAudioRendererStats *pStats = 0;
HRESULT hr = pAudioRenderer->QueryInterface(IID_IAMAudioRendererStats,
    (void**)&pStats);
if (SUCCEEDED(hr))
{
    DWORD dwBreakCount = 0, dwNotUsed = 0;
    hr = pStats->GetStatParam(AM_AUDREND_STAT_PARAM_BREAK_COUNT,
        &dwBreakCount, &dwNotUsed);
    if (SUCCEEDED(hr))
    {
        // dwBreakCount contains the cumulative number of audio breaks.
    }
    pStats->Release();
}

See Also

  • IAMAudioRendererStats Interface


IAMBufferNegotiation Interface

The IAMBufferNegotiation interface enables an application to request how many buffers a filter creates and the buffer size. This interface can be exposed by any pin that connects using the IMemInputPin pin interface, but is typically exposed on the output pins of capture filters.

When two pins connect through IMemInputPin, they agree on an allocator object that is responsible for creating buffers. Normally this process is transparent to the application, but in some situations the application needs more control. If a pin exposes IAMBufferNegotiation, the application can suggest how many buffers to create, the size of the buffers, and other properties. If your application performs preview of captured audio, you can specify a smaller buffer size to reduce latency. Teleconferencing applications should specify a minimal number of buffers.

To use this interface, call the SuggestAllocatorProperties method before the pins connect. After the pins connect, call the GetAllocatorProperties method to determine whether the pin honored the request.

Filter developers: Capture filters should always support this interface when possible.

In addition to the methods inherited from IUnknown, the IAMBufferNegotiation interface exposes the following methods.

Method | Description
GetAllocatorProperties | Retrieves the allocator properties that the pin is using.
SuggestAllocatorProperties | Informs the pin of the application's preferred allocator properties


IAMBufferNegotiation::GetAllocatorProperties

The GetAllocatorProperties method retrieves the allocator properties that the pin is using.

Syntax

HRESULT GetAllocatorProperties(
  ALLOCATOR_PROPERTIES *pprop
);

Parameters

pprop

[out] Pointer to an ALLOCATOR_PROPERTIES structure, allocated by the caller, that receives the allocator properties.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

Call this method after the pins connect, to find out the allocator properties that were chosen.

See Also

  • Error and Success Codes
  • IAMBufferNegotiation Interface


IAMBufferNegotiation::SuggestAllocatorProperties

The SuggestAllocatorProperties method informs the pin of the application's preferred allocator properties. Call this method before the pin connects.

Syntax

HRESULT SuggestAllocatorProperties(
  const ALLOCATOR_PROPERTIES *pprop
);

Parameters

pprop

[in] Pointer to an ALLOCATOR_PROPERTIES structure that contains the requested properties. A negative value for any member indicates that the pin should use its default setting for that property.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_CONNECTED | Pin is already connected.

Remarks

If both pins in the connection expose the IAMBufferNegotiation interface, call this method on each pin, to ensure that one pin does not override the other.

To request a particular number of buffers, set the cBuffers member of the ALLOCATOR_PROPERTIES structure. To request a particular buffer size, set the cbBuffer member. An application typically should not specify the alignment or prefix. If the number of buffers or size of each buffer is too small, the filter graph might drop samples.

Example Code

ALLOCATOR_PROPERTIES AllocProp;
AllocProp.cbAlign = -1;  // -1 means no preference.
AllocProp.cbBuffer = dwBytesPerSec *  dwLatencyInMilliseconds / 1000;
AllocProp.cbPrefix = -1;
AllocProp.cBuffers = -1;
pIAMBufferNegotiation->SuggestAllocatorProperties(&AllocProp);

See Also

  • Error and Success Codes
  • IAMBufferNegotiation Interface


IAMCameraControl Interface

The IAMCameraControl interface provides local or remote control over a camera. Applications can use this interface to control camera settings such as zoom, pan, aperture adjustment, or shutter speed. To obtain this interface, query the filter that controls the camera.

In addition to the methods inherited from IUnknown, the IAMCameraControl interface exposes the following methods.

Method | Description
Get | Retrieves the current setting of a camera property.
GetRange | retrieves the range and default value of a specified camera property.
Set | Sets a specified property on the camera.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_CAMERACONTROL property set. For more information, see the Windows DDK documenation.

See Also

  • IAMVideoProcAmp Interface


IAMCameraControl::Get

The Get method retrieves the current setting of a camera property.

Syntax

HRESULT Get (
  long Property,
  long *lValue,
  long *Flags
);

Parameters

Property

[in] Specifies the property to retrieve, as a value from the CameraControlProperty enumeration.

lValue

[out] Pointer to a variable that receives the value of the property.

Flags

[out] Pointer to a variable that receives a member of the CameraControlFlags enumeration. The returned value indicates whether the setting is controlled manually or automatically.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMCameraControl Interface
  • IAMCameraControl::Set


IAMCameraControl::GetRange

The GetRange method retrieves the range and default value of a specified camera property.

Syntax

HRESULT GetRange (
  long property,
  long *pMin,
  long *pMax,
  long *pSteppingDelta,
  long *pDefault,
  long *pCapsFlags
);

Parameters

property

[in] Specifies the property to query, as a value from the CameraControlProperty enumeration.

pMin

[out] Pointer to a variable that receives the minimum value of the property.

pMax

[out] Pointer to a variable that receives the maximum value of the property.

pSteppingDelta

[out] Pointer to a variable that receives the step size for the property. The step size is the smallest increment by which the property can change.

pDefault

[out] Pointer to a variable that receives the default value of the property.

pCapsFlags

[out] Pointer to a variable that receives a member of the CameraControlFlags enumeration, indicating whether the property is controlled automatically or manually.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMCameraControl Interface


IAMCameraControl::Set

The Set method sets a specified property on the camera.

Syntax

HRESULT Set (
  long Property,
  long lValue,
  long Flags
);

Parameters

Property

[in] Specifies the property to set, as a value from the CameraControlProperty enumeration.

lValue

[in] Specifes the new value of the property.

Flags

[in] Specifies the desired control setting, as a member of the CameraControlFlags enumeration.

Return Values

If method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

If the Flags parameter is CameraControl_Flags_Auto, the method ignores the lValue parameter.

See Also

  • Error and Success Codes
  • IAMCameraControl Interface
  • IAMCameraControl::Get


IAMChannelInfo Interface

The IAMChannelInfo interface contains methods to get and set channel information. It is exposed on the Windows Media Source filter only when the filter is reading Windows Media Station (.nsc) files. The Windows Media Source filter uses .nsc files to get the information it needs to receive multicast content over the Internet. These files contain information such as stream location and rollover URL, as well as descriptive information about the station.

In addition to the methods inherited from IDispatch, the IAMChannelInfo interface exposes the following methods.

Method | Description
get_ChannelDescription | Retrieves the description of the channel.
get_ChannelName | Retrieves the channel name.
get_ChannelURL | Retrieves the channel URL.
get_ContactAddress | Retrieves the contact address.
get_ContactEmail | Retrieves the contact e-mail address.
get_ContactPhone | Retrieves the contact phone number.

Requirements

Requires Qnetwork.h. To define the interface identifier, include Initguid.h before Qnetwork.h, but after Dshow.h:

#include <dshow.h>
#include <initguid.h>
#include <qnetwork.h>

Note Make sure that Initguid.h is included only once in your project.


IAMChannelInfo::get_ChannelDescription

The get_ChannelDescription method retrieves the description of the channel.

Syntax

HRESULT get_ChannelDescription(
  BSTR *pbstrChannelDescription
);

Parameters

pbstrChannelDescription

[out] Pointer to a variable that receives the channel description.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMChannelInfo::get_ChannelName

The get_ChannelName method retrieves the channel name.

Syntax

HRESULT get_ChannelName(
  BSTR *pbstrChannelName
);

Parameters

pbstrChannelName

[out] Pointer to a variable that receives a string containing the channel name.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMChannelInfo::get_ChannelURL

The get_ChannelURL method retrieves the channel URL.

Syntax

HRESULT get_ChannelURL(
  BSTR *pbstrChannelURL
);

Parameters

pbstrChannelURL

[out] Pointer to a variable that receives the URL.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMChannelInfo::get_ContactAddress

The get_ContactAddress method retrieves the contact address.

Syntax

HRESULT get_ContactAddress(
  BSTR *pbstrContactAddress
);

Parameters

pbstrContactAddress

[out] Pointer to a variable that receives the contact address.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMChannelInfo::get_ContactEmail

The get_ContactEmail method retrieves the e-mail address of the contact.

Syntax

HRESULT get_ContactEmail(
  BSTR *pbstrContactEmail
);

Parameters

pbstrContactEmail

[out] Pointer to a variable that receives the contact e-mail.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMChannelInfo::get_ContactPhone

The get_ContactPhone method retrieves the phone number of the contact.

Syntax

HRESULT get_ContactPhone(
  BSTR *pbstrContactPhone
);

Parameters

pbstrContactPhone

[out] Pointer to a variable that receives the contact's phone number.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMChannelInfo Interface


IAMClockAdjust Interface

The IAMClockAdjust interface provides a method to adjust a reference clock. The System Reference Clock exposes this interface.

In addition to the methods inherited from IUnknown, the IAMClockAdjust interface exposes the following method.

Method | Description
SetClockDelta | Adjusts the clock time.


IAMClockAdjust::SetClockDelta

The SetClockDelta method adjusts the clock time.

Syntax

HRESULT SetClockDelta(
  REFERENCE_TIME rtDelta
);

Parameters

rtDelta

[in] Specifies the amount by which to adjust the clock, as a REFERENCE_TIME value. A positive value moves the clock forward, and a negative value moves the clock backward.

Return Values

Returns S_OK or an HRESULT error code.

Remarks

The time values returned by IReferenceClock::GetTime are monotonically increasing. If you set the clock back, GetTime continues to report the old time until the internal clock catches up.

See Also

  • Error and Success Codes
  • IAMClockAdjust Interface


IAMClockSlave Interface

The IAMClockSlave interface controls the tolerance of an audio renderer when it is matching rates with another clock.

If the audio renderer is matching rates with another clock, it allows the audio to drift up to the amount of the specified tolerance. If the audio drifts too far ahead, the renderer drops samples; if it drifts too far behind, the renderer inserts silent gaps. This interface enables an application to change the tolerance from the default.

Setting a larger tolerance is likely to result in the audio stream becoming out of sync with the video stream. Setting a smaller tolerance can cause audio jitter. Therefore, changing the tolerance setting is not recommended, unless you have a specific reason to do so.

In addition to the methods inherited from IUnknown, the IAMClockSlave interface exposes the following methods.

Method | Description
GetErrorTolerance | Retrieves the current tolerance.
SetErrorTolerance | Sets the tolerance.

See Also

  • Live Sources


IAMClockSlave::GetErrorTolerance

The GetErrorTolerance method retrieves the audio renderer's rate-matching tolerance.

Syntax

HRESULT GetErrorTolerance(
  DWORD *pdwTolerance
);

Parameters

pdwTolerance

[out] Pointer to a variable that receives the maximum tolerance, in milliseconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMClockSlave Interface


IAMClockSlave::SetErrorTolerance

The SetErrorTolerance method sets the audio renderer's rate-matching tolerance.

Syntax

HRESULT SetErrorTolerance(
  DWORD dwTolerance
);

Parameters

dwTolerance

[in] Specifies the maximum tolerance, in milliseconds. The value must be from 1 to 1000, inclusive.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter graph is not stopped.

Remarks

Changing the tolerance has no effect unless the audio renderer is matching rates with a different clock. If the audio renderer is the reference clock, the audio is always synchronized to the clock (by definition).

This method fails unless the filter graph is stopped.

See Also

  • Error and Success Codes
  • IAMClockSlave Interface


IAMCopyCaptureFileProgress Interface

The IAMCopyCaptureFileProgress is a callback interface used by the ICaptureGraphBuilder2::CopyCaptureFile method.

Because the CopyCaptureFile method can take a long time to complete, an application can implement this interface to receive periodic notifications about the progress of the copy operation. If the application does not need to receive this information, there is no need to implement the interface.

In addition to the methods inherited from IUnknown, the IAMCopyCaptureFileProgress interface exposes the following method.

Method | Description
Progress | Called periodically by the ICaptureGraphBuilder2::CopyCaptureFile method during capture operations.

Remarks

To use this interface, implement a class that inherits the interface and implements all of its methods, including the methods in IUnknown. In your application, create an instance of the class and pass it to the CopyCaptureFile method. You do not have to implement COM reference counting in your class, as long as the object is guaranteed not to be deleted before the CopyCaptureFile method returns.

The following example shows a class that implements the interface:

class CProgress : public IAMCopyCaptureFileProgress
{
public:
    STDMETHODIMP_(ULONG) AddRef() { return 1; }
    STDMETHODIMP_(ULONG) Release() { return 0; }
    STDMETHODIMP QueryInterface(REFIID iid, void **ppv)
    {
        if  (ppv == NULL) return E_POINTER;
        if (iid == __uuidof(IUnknown))
        {
            *ppv = static_cast<IUnknown*>(this);
            return S_OK;
        }
        if (iid == IID_IAMCopyCaptureFileProgress)
        {
            *ppv = static_cast<IAMCopyCaptureFileProgress*>(this);
            return S_OK;
        }
        return E_NOINTERFACE;
        }
    }
    STDMETHODIMP Progress(int iPercent)
    {
        if (i < 0 || i > 100) return E_INVALIDARG;
        TCHAR szMsg[32];
        wsprintf(szMsg, TEXT("Progress: %d%%"), i);
        // Assume g_hwndStatus is a valid HWND.
        SetWindowText(g_hwndStatus, szMsg);
        return S_OK;
    };
};

The following example uses this class in the CopyCaptureFile method:

// Scope for CProgress object
{
    CProgress Prog;
    // Assume pBuilder is an initialized ICaptureGraphBuilder2 pointer.
    hr = pBuilder->CopyCaptureFile(szCaptureFile, szDestFile, TRUE,
        static_cast<IAMCopyCaptureFileProgress*>(&Prog));
}


IAMCopyCaptureFileProgress::Progress

The Progress method is called periodically by the ICaptureGraphBuilder2::CopyCaptureFile method while it copies the file.

Syntax

HRESULT Progress(
  int iProgress
);

Parameters

iProgress

[in] Specifies the percentage of the copy operation that has completed, as a value between 0 and 100.

Return Values

Returns S_OK or an HRESULT error code.

Remarks

Applications typically use the value of iProgress to update a progress bar on the user interface.

See Also

  • Error and Success Codes
  • IAMCopyCaptureFileProgress Interface


IAMCrossbar Interface

The IAMCrossbar interface is implemented by the Analog Video Crossbar Filter.

The Analog Video Crossbar filter routes signals from an analog or digital source to a video capture filter. The filter is modeled after a general switching matrix, with n inputs and m outputs. For example, a video card might have two external connectors: a coaxial connector for TV, and an S-video input. These would be represented as input pins on the filter. To select one of the inputs, an application would use the IAMCrossbar interface to "route" an input pin to the filter's output pin, by calling the IAMCrossbar::Route method.

In addition to the methods inherited from IUnknown, the IAMCrossbar interface exposes the following methods.

Method | Description
CanRoute | Queries whether a specified input pin can be routed to a specified output pin.
get_CrossbarPinInfo | Retrieves information about a specified pin.
get_IsRoutedTo | Retrieves the input pin that is currently routed to the specified output pin.
get_PinCounts | Retrieves the number of input and output pins on the crossbar filter.
Route | Routes an input pin to an output pin.

See Also

  • Working with Crossbars


IAMCrossbar::CanRoute

The CanRoute method queries whether a specified input pin can be routed to a specified output pin.

Syntax

HRESULT CanRoute (
  long OutputPinIndex,
  long InputPinIndex
);

Parameters

OutputPinIndex

[in] Specifes the index of the output pin.

InputPinIndex

[in] Specifies the index of input pin.

Return Values

Returns an HRESULT values. Possible values include the following.

Return code | Description
S_OK | These two pins can be routed.
S_FALSE | These two pins cannot be routed.

Remarks

To route the pins, call the IAMCrossbar::Route method. Output pins and input pins are both indexed from zero. To determine the number of output and input pins, call the IAMCrossbar::get_PinCounts method.

See Also

  • Error and Success Codes
  • IAMCrossbar Interface
  • Working with Crossbars


IAMCrossbar::get_CrossbarPinInfo

The get_CrossbarPinInfo method retrieves information about a specified pin.

Syntax

HRESULT get_CrossbarPinInfo (
  BOOL IsInputPin,
  long PinIndex,
  long *PinIndexRelated,
  long *PhysicalType
);

Parameters

IsInputPin

[in] Specifies the direction of the pin. Use one of the following values.

Value | Description
TRUE | Input pin
FALSE | Output pin

PinIndex

[in] Specifies the index of the pin.

PinIndexRelated

[out] Pointer to a variable that receives the index of the related pin, or -1 if no pin is related to this pin. The related pin is a pin on the same filter, with the same direction; it typically represents the same physical jack or connector. For example, a video tuner and an audio tuner might be related pins. Typically, if two pins are related, you should route them together.

PhysicalType

[out] Pointer to a variable that receives a member of the PhysicalConnectorType enumeration, indicating the pin's physical type.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Unknown physical type.
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

Output pins and input pins are both indexed from zero. To determine the number of output and input pins, call the IAMCrossbar::get_PinCounts method.

See Also

  • Error and Success Codes
  • IAMCrossbar Interface
  • Working with Crossbars


IAMCrossbar::get_IsRoutedTo

The get_IsRoutedTo method retrieves the input pin that is currently routed to the specified output pin.

Syntax

HRESULT get_IsRoutedTo (
  long OutputPinIndex,
  long *InputPinIndex
);

Parameters

OutputPinIndex

[in] Specifes the index of the output pin.

InputPinIndex

[out] Pointer to a variable that receives the index of the input pin, or -1 if no input pin is routed to this output pin.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | No input pin is routed to this output pin.
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

Output pins and input pins are both indexed from zero. To determine the number of output and input pins, call the IAMCrossbar::get_PinCounts method.

See Also

  • Error and Success Codes
  • IAMCrossbar Interface
  • Working with Crossbars


IAMCrossbar::get_PinCounts

The get_PinCounts method retrieves the number of input and output pins on the crossbar filter.

Syntax

HRESULT get_PinCounts(
  long *OutputPinCount,
  long *InputPinCount
);

Parameters

OutputPinCount

[out] Pointer to variable that receives the number of output pins.

InputPinCount

[out] Pointer to variable that receives the number of input pins.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The other IAMCrossbar methods take parameters that specify pins by index number. For these methods, output pins and input pins are both indexed from zero. Use the get_PinCounts method to determine the upper bounds for each.

See Also

  • Error and Success Codes
  • IAMCrossbar Interface
  • Working with Crossbars


IAMCrossbar::Route

The Route method routes an input pin to an output pin.

Syntax

HRESULT Route (
  long OutputPinIndex,
  long InputPinIndex
);

Parameters

OutputPinIndex

[in] Specifies the index of the output pin.

InputPinIndex

[in] Specifies the index of the input pin.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Cannot route these two pins.
S_OK | Success.

Remarks

Routing two pins causes the output pin to deliver data from that input pin. Only one input pin at a time can be routed to a given output pin.

Output pins and input pins are both indexed from zero. To determine the number of output and input pins, call the IAMCrossbar::get_PinCounts method.

See Also

  • Error and Success Codes
  • IAMCrossbar Interface
  • Working with Crossbars


IAMDecoderCaps Interface

The IAMDecoderCaps interface should be implemented by MPEG decoder filters to inform other components about their capabilities. The capabilities reported through this interface include whether the decoder supports the Video Mixing Renderer filter and whether it supports DirectX Video Acceleration.

Some DirectShow components, such as the DVD Graph Builder, use this interface to determine the correct filter graph to build. Applications might use this interface to query the decoder's capabilities.

In addition to the methods inherited from IUnknown, the IAMDecoderCaps interface exposes the following method.

Method | Description
GetDecoderCaps | Queries the decoder for its capabilities.

See Also

  • Using the Video Mixing Renderer


IAMDecoderCaps::GetDecoderCaps

The GetDecoderCaps method queries the decoder for its capabilities.

Syntax

HRESULT GetDecoderCaps(
  DWORD dwCapIndex,
  DWORD* lpdwCap
);

Parameters

dwCapIndex

[in] Specifies the capability being queried for.

Constant | Value | Description
AM_QUERY_DECODER_VMR_SUPPORT | 0x00000001 | Video Mixing Renderer Filter 7 (VMR-7) support
AM_QUERY_DECODER_DXVA_1_SUPPORT | 0x00000002 | DirectX Video Acceleration support
AM_QUERY_DECODER_DVD_SUPPORT | 0x00000003 | DVD Video support
AM_QUERY_DECODER_ATSC_SD_SUPPORT | 0x00000004 | Standard-definition (SD) ATSC video support
AM_QUERY_DECODER_ATSC_HD_SUPPORT | 0x00000005 | High-definition (HD) ATSC video support
AM_GETDECODERCAP_QUERY_VMR9_SUPPORT | 0x00000006 | Video Mixing Renderer Filter 9 (VMR-9) support

lpdwCap

[out] Specifies a pointer to a variable that receives one of the following values.

Value | Description
DECODER_CAP_NOTSUPPORTED | The decoder does not support this capability.
DECODER_CAP_SUPPORTED | The decoder supports this capability.

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The DVD Graph Builder uses this method when it builds a DVD graph. If the decoder does not support the Video Mixing Renderer filter, then the DVD Graph Builder uses the Overlay Mixer filter instead.

See Also

  • Building the DVD Filter Graph
  • Error and Success Codes
  • IAMDecoderCaps Interface


IAMDirectSound Interface

The IAMDirectSound interface enables an application to specify which widow has focus for controlling DirectSound audio playback. Currently DirectShow provides limited support for this interface:

  • The DirectSound Renderer implements the GetWindowFocus and SetWindowFocus methods. It does not implement the other methods on the interface.
  • The Audio Renderer (WaveOut) exposes the interface but does not implement any of its methods.

In addition to the methods inherited from IUnknown, the IAMDirectSound interface exposes the following methods.

Method | Description
GetDirectSoundInterface | Not implemented.
GetFocusWindow | Retrieves the window that is handling sound playback for the current media file.
GetPrimaryBufferInterface | Not implemented.
GetSecondaryBufferInterface | Not implemented.
ReleaseDirectSoundInterface | Not implemented.
ReleasePrimaryBufferInterface | Not implemented.
ReleaseSecondaryBufferInterface | Not implemented.
SetWindowFocus | Sets the window that will handle sound playback for the current media file.


IAMDirectSound::GetDirectSoundInterface

The GetDirectSoundInterface method is not implemented.

Syntax

HRESULT GetDirectSoundInterface(
  LPDIRECTSOUND *lplpds
);

Parameters

lplpds

[out] Specifies a variable that receives an IDirectSound interface pointer.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::GetPrimaryBufferInterface

The GetPrimaryBufferInterface method is not implemented.

Syntax

HRESULT GetDirectSoundInterface(
  LPDIRECTSOUNDBUFFER *lplpdsb
);

Parameters

lplpdsb

[out] Specifies a variable that receives an IDirectSoundBuffer interface pointer.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::GetSecondaryBufferInterface

The GetSecondaryBufferInterface method is not implemented.

Syntax

HRESULT GetSecondaryBufferInterface(
  LPDIRECTSOUNDBUFFER *lplpdsb
);

Parameters

lplpdsb

[out] Specifies a variable that receives an IDirectSoundBuffer interface pointer.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::GetFocusWindow

The GetWindowFocus method retrieves the window that is handling sound playback.

Syntax

HRESULT GetFocusWindow(
  HWND* hWnd,
  BOOL* bMixingOnOrOff
);

Parameters

hWnd

[out] Pointer to a variable that receives a handle to the window. If sound playback is not associated with a window, the returned value is NULL.

Note Windows NT 4.0 does not support windowless sound playback.

bMixingOnOrOff

[out] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | The sound is audible when the window loses focus.
FALSE | The sound is not audible when the windows loses focus.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::ReleaseDirectSoundInterface

The ReleaseDirectSoundInterface method is not implemented.

Syntax

HRESULT ReleaseDirectSoundInterface(
  LPDIRECTSOUND lpds
);

Parameters

lpds

[in] Specifies a pointer to the IDirectSound interface.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::ReleasePrimaryBufferInterface

The ReleasePrimaryBufferInterface method is not implemented.

Syntax

HRESULT ReleasePrimaryBufferInterface(
  LPDIRECTSOUNDBUFFER lpdsb
);

Parameters

lpdsb

[in] Specifies a pointer to the IDirectSoundBuffer interface.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::ReleaseSecondaryBufferInterface

The ReleaseSecondaryBufferInterface method is not implemented.

Syntax

HRESULT ReleaseSecondaryBufferInterface(
  LPDIRECTSOUNDBUFFER lpdsb
);

Parameters

lpdsb

[in] Specifies a pointer to the IDirectSoundBuffer interface.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDirectSound::SetWindowFocus

The SetWindowFocus method specifies a window to handle sound playback.

Syntax

HRESULT SetWindowFocus(
  HWND hWnd,
  BOOL bMixingOnOrOff
);

Parameters

hWnd

[in] Specifies a handle to the window. If this value is NULL, the sound will not be associated with any window.

Note Windows NT 4.0 does not support windowless sound playback.

bMixingOnOrOff

[in] Specifies whether to mix the sound when the window loses focus.

Value | Description
TRUE | The sound is audible when the window loses focus.
FALSE | The sound is not audible when the windows loses focus.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_FAIL | Failure.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMDirectSound Interface


IAMDroppedFrames Interface

The IAMDroppedFrames interface retrieves performance information from a video capture filter, such as how many frames were dropped and how many frames were delivered. Applications can use this interface to determine capture performance at run-time.

In addition to the methods inherited from IUnknown, the IAMDroppedFrames interface exposes the following methods.

Method | Description
GetAverageFrameSize | Retrieves the average size of the frames that the filter has captured.
GetDroppedInfo | Retrieves an array of frame numbers that were dropped.
GetNumDropped | Retrieves the total number of frames that the filter has dropped since it started streaming.
GetNumNotDropped | Retrieves the total number of frames that the filter has delivered since it started streaming.

Remarks

Some filters that expose this interface do not implement the GetDroppedInfo or GetAverageFrameSize method.

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_DROPPEDFRAMES property set. For more information, see the Windows DDK documenation.


IAMDroppedFrames::GetAverageFrameSize

The GetAverageFrameSize method retrieves the average size of the frames that the filter has captured.

Syntax

HRESULT GetAverageFrameSize(
  long *plAverageSize
);

Parameters

plAverageSize

[out] Pointer to a variable that receives the average frame size, in bytes, since the filter began streaming.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

If the device does not report a value, the method might succeed but return zero in the plAverageSize parameter.

See Also

  • Error and Success Codes
  • IAMDroppedFrames Interface


IAMDroppedFrames::GetDroppedInfo

The GetDroppedInfo method retrieves an array of frame numbers that were dropped.

Syntax

HRESULT GetDroppedInfo(
  long lSize,
  long *plArray,
  long *plNumCopied
);

Parameters

lSize

[in] Specifies the size of the array.

plArray

[out] Pointer to an array of size lSize, allocated by the caller. The method fills the array with the frame numbers of the first lSize frames that were dropped, up to a maximum number that is device-depedent.

plNumCopied

[outl] Pointer to a variable that receives the number of items returned in plArray. This number might be less than the value of lSize.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument; the lSize parameter must by greater than zero.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.
E_PROP_ID_UNSUPPORTED | Not supported by this device.

See Also

  • Error and Success Codes
  • IAMDroppedFrames Interface


IAMDroppedFrames::GetNumDropped

The GetNumDropped method retrieves the total number of frames that the filter has dropped since it started streaming.

Syntax

HRESULT GetNumDropped(
  long *plDropped
);

Parameters

plDropped

[out] Pointer to a variable that receives the number of dropped frames.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The filter resets the count to zero when it transitions from stopped to paused.

If your application uses the IAMStreamControl interface to control a pin, the driver might continue to count dropped and non-dropped frames while the pin is off. To get an accurate count, call this method once when you turn on the pin, and again when you turn off the pin. The difference is the total number of dropped frames. (If the start time occurs later than the call to IAMStreamControl::StartAt, the application should listen for the EC_STREAM_CONTROL_STARTED event.) These remarks also apply if your application uses the ICaptureGraphBuilder2::ControlStream method.

See Also

  • Error and Success Codes
  • IAMDroppedFrames Interface


IAMDroppedFrames::GetNumNotDropped

The GetNumNotDropped method retrieves the total number of frames that the filter has delivered since it started streaming.

Syntax

HRESULT GetNumNotDropped(
  long *plNotDropped
);

Parameters

plNotDropped

[out] Pointer to a variable that receives the number of delivered frames.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The filter resets the count to zero when it transitions from stopped to paused.

If your application uses the IAMStreamControl interface to control a pin, the driver might continue to count dropped and non-dropped frames while the pin is off. To get an accurate count, call this method once when you turn on the pin, and again when you turn off the pin. The difference is the total number of dropped frames. (If the start time occurs later than the call to IAMStreamControl::StartAt, the application should listen for the EC_STREAM_CONTROL_STARTED event.) These remarks also apply if your application uses the ICaptureGraphBuilder2::ControlStream method.

See Also

  • Error and Success Codes
  • IAMDroppedFrames Interface


IAMExtDevice Interface

The IAMExtDevice interface enables an application to control an external device, such as a VCR, through the filter graph.

This interface controls basic device functions. Several other interfaces exist for controlling more specific functionality in a device:

  • IAMExtTransport
  • IAMTimecodeReader
  • IAMTimecodeGenerator
  • IAMTimecodeDisplay

Requirements

The DV camcorder driver, MSDV, requires some additional constants that are defined in the header file Xprtdefs.h.

Hardware Requirements

To control an external VCR, certain hardware requirements are recommended. VCRs with an RS-422 serial interface require a special serial port card or an external RS-232-to-RS-422 adapter. In addition, for best performance, your computer should have a serial port card built with a 16550 high-performance UART (Universal Asynchronous Receiver/Transmitter) to sustain higher baud rates, such as 38.4 baud.

In addition to the methods inherited from IUnknown, the IAMExtDevice interface exposes the following methods.

Method | Description
GetCapability | Retrieves the capabilities of the device.
get_ExternalDeviceID | Retrieves the model number of the device.
get_ExternalDeviceVersion | Retrieves the version number of the device's operating software.
put_DevicePort | Specifies the communication port to which the device is connected.
get_DevicePower | Retrieves the device's power mode.
put_DevicePower | Sets the device's power mode.
Calibrate | Calibrates the device's transport mechanism.
get_DevicePort | Retrieves the communication port to which the device is connected.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_EXT_DEVICE property set. For more information, see the DirectX DDK documenation.


IAMExtDevice::Calibrate

The Calibrate method calibrates an external device's transport mechanism.

Syntax

HRESULT Calibrate(
  HEVENT hEvent,
  long Mode,
  long *pStatus
);

Parameters

hEvent

[in] Handle to an event. The event is signaled when the action is complete.

Mode

[in] Specifies a value that activates or deactivates the calibration process:

Value | Description
ED_ACTIVE | Activates the calibration process.
ED_INACTIVE | Deactivates the calibration process.
NULL | No action; return the calibration status in pStatus.

pStatus

[out] Pointer to a long integer that receives one of the following values:

Value | Description
OATRUE | Calibration is active.
OAFALSE | Calibration is inactive.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Use this method on certain external devices that require calibration; for example, rewinding a tape and resetting the counter, or computing the frame offset for a timecode reader.

Filters for various external devices can implement this method differently, depending on the calibration that the device needs. This method assumes the IMediaEventSink interface has already established an event sink, or that another event signaling method has been established.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface


IAMExtDevice::GetCapability

The GetCapability method retrieves the capabilities of the external device.

Syntax

HRESULT GetCapability(
  long Capability,
  long *pValue,
  double *pdblValue
);

Parameters

Capability

[in] Specifies the capability to check. See Remarks for more information.

pValue

[out] Pointer to a variable that receives a long integer. See Remarks for more information.

pdblValue

[out] Pointer to a variable that receives a double. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The Capability parameter is a flag that specifies which capability to check. The method returns the result either in the pValue parameter or in the pdblValue parameter, depending on the capability flag.

For the following flags, the method returns the value OATRUE or OAFALSE in the pValue parameter. The value OATRUE indicates that the capability is present, while the value OAFALSE indicates it is absent.

Capability flag | Description
ED_DEVCAP_AUDIO_INPUTS | Device accepts audio input.
ED_DEVCAP_CAN_MONITOR_SOURCES | Device can send any input to the monitored output, regardless of the input that is currently selected.
ED_DEVCAP_CAN_PREVIEW | Device can preview.
ED_DEVCAP_CAN_RECORD | Device can record.
ED_DEVCAP_CAN_RECORD_STROBE | Device can strobe record. This capability applies to multitrack devices that can record to selected tracks.
ED_DEVCAP_CAN_SAVE | Device can save data.
ED_DEVCAP_CTLTRK_READ | Device can read control tracks.
ED_DEVCAP_HAS_AUDIO | Device has audio.
ED_DEVCAP_HAS_VIDEO | Device has video.
ED_DEVCAP_INDEX_READ | Device can read index marks.
ED_DEVCAP_NEEDS_CALIBRATING | Device needs calibrating. See IAMExtDevice::Calibrate.
ED_DEVCAP_TIMECODE_READ | Device can read SMPTE time code.
ED_DEVCAP_TIMECODE_WRITE | Device can set SMPTE time code.
ED_DEVCAP_USES_FILES | Device has a built-in file system.
ED_DEVCAP_VIDEO_INPUTS | Device accepts video input.

For the following flags, the method returns a defined constant in the pValue parameter.

  • ED_DEVCAP_DEVICE_TYPE: Returns the device type.
Returned Constant | Description
ED_DEVTYPE_ATR | Audio tape recorder
ED_DEVTYPE_CG | Character generator
ED_DEVTYPE_DDR | Digital disk recorder
ED_DEVTYPE_DVE | Digital video effects unit
ED_DEVTYPE_GPI | General purpose interface trigger
ED_DEVTYPE_KEYER | Video keyer
ED_DEVTYPE_LASERDISK | Laserdisc
ED_DEVTYPE_MIXER_AUDIO | Audio mixer
ED_DEVTYPE_MIXER_VIDEO | Video mixer
ED_DEVTYPE_ROUTER | Video router
ED_DEVTYPE_TBC | Timebase corrector
ED_DEVTYPE_TCG | Timecode generator/reader
ED_DEVTYPE_VCR | VCR, or camcorder with full VCR capabilities
ED_DEVTYPE_WIPEGEN | Video wipe generator
ED_DEVTYPE_JOYSTICK | Joystick
ED_DEVTYPE_KEYBOARD | Keyboard

  • ED_DEVCAP_SYNC_ACCURACY: Returns an indication of the device's synchronization accuracy.
Returned Constant | Description
ED_SYNCACC_PRECISE | Device has precise accuracy.
ED_SYNCACC_FRAME | Device is frame accurate.
ED_SYNCACC_ROUGH | Device is less than frame accurate.

  • ED_DEVCAP_NORMAL_RATE: Returns the device's normal frame rate.
Returned Constant | Description
ED_RATE_24 | 24 frames per second (fps)
ED_RATE_25 | 25 fps
ED_RATE_2997 | 29.997 fps
ED_RATE_30 | 30 fps

  • ED_DEVCAP_SEEK_TYPE: Returns an indication of the device's seeking accuracy.
Returned Constant | Description
ED_SEEK_PERFECT | Device can seek within one video frame without a signal break.
ED_SEEK_FAST | Device can seek quickly, with a short break in the signal.
ED_SEEK_SLOW | Device seeks slowly; such as tape transport.

For the following flags, the method returns a numeric value in the pValue parameter.

Capability Flag | Returned Value
ED_DEVCAP_EXTERNAL_DEVICE_ID | Manufacturer-specific identifier.
ED_DEVCAP_PREROLL | Device preroll time.
ED_DEVCAP_POSTROLL | Device postroll time.

DV Implementation

MSDV supports the following behaviors.

  • The ED_DEVCAP_DEVICE_TYPE flag returns the device type.
Returned Constant | Description
ED_DEVTYPE_CAMERA | Simple camera that can record or pause-record, but lacks full VCR capabilities.
ED_DEVTYPE_DVHS | Device supports D-VHS format.
ED_DEVTYPE_UNKNOWN | Unknown device type.
ED_DEVTYPE_VCR | Device has full VCR capabilities.

  • The ED_DEVCAP_NORMAL_RATE flag returns the camcorder's frame rate.
Returned Constant | Description
ED_RATE_25 | 25 fps (default NTSC frame rate)
ED_RATE_2997 | 29.997 fps (default PAL frame rate)

See Also

  • Error and Success Codes
  • IAMExtDevice Interface


IAMExtDevice::get_DevicePort

The get_DevicePort method retrieves the communication port to which the external device is connected.

Syntax

HRESULT get_DevicePort(
  long *pDevicePort
);

Parameters

pDevicePort

[out] Pointer to a long integer that receives one of the following values, indicating the port to which the device is connected:

Value | Description
DEV_PORT_1394 | IEEE 1394 Bus
DEV_PORT_ARTI | ARTI driver
DEV_PORT_COM1 | COM1
DEV_PORT_COM2 | COM2
DEV_PORT_COM3 | COM3
DEV_PORT_COM4 | COM4
DEV_PORT_DIAQ | Diaquest driver
DEV_PORT_SIM | Simulation port
DEV_PORT_USB | Universal Serial Bus

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

For DV camcorders, the method returns the value DEV_PORT_1394.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface
  • IAMExtDevice::put_DevicePort


IAMExtDevice::get_DevicePower

The get_DevicePower method retrieves the external device's power mode: on, off, or standby.

Syntax

HRESULT get_DevicePower(
  long *pPowerMode
);

Parameters

pPowerMode

[out] Pointer to a long integer that receives one of the following values, indicating the device's power mode.

Value | Description
ED_POWER_OFF | Off
ED_POWER_ON | On
ED_POWER_STANDBY | Standby

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV and MPEG Camcorder Implementation

MSDV returns the ED_POWER_ON flag when the camcorder is on. If the camcorder is off or in standby mode, the DV driver is not loaded, so this method is not available. If the camcorder is removed unexpectedly, the method can return ERROR_GEN_FAILURE.

MSTape supports both ED_POWER_OFF and ED_POWER_ON, but not ED_POWER_STANDBY.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface
  • IAMExtDevice::put_DevicePower


IAMExtDevice::get_ExternalDeviceID

The get_ExternalDeviceID method retrieves the model number of the external device.

Syntax

HRESULT get_ExternalDeviceID(
  LPOLESTR *ppszData
);

Parameters

ppszData

[out] Pointer to an LPOLESTR that receives the manufacturer-specific identification as a string. The caller must release the string by calling CoTaskMemFree.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV returns the device's 64-bit unique identifier, as defined by IEEE 1394. This identifier is guaranteed to be unique, even for two identical device models connected simultaneously to the IEEE 1394 bus.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface


IAMExtDevice::get_ExternalDeviceVersion

The get_ExternalDeviceVersion retrieves the version number of the external device's operating software.

Syntax

HRESULT get_ExternalDeviceVersion(
  LPOLESTR *ppszData
);

Parameters

ppszData

[out] Pointer to an LPOLESTR that receives the manufacturer-specific operating software version number as a string. The caller must release the string by calling CoTaskMemFree.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

The method returns the version of the IEEE AV/C Digital Interface Command Set (VCR Subunit Specification) that the device supports.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface


IAMExtDevice::put_DevicePort

The put_DevicePort method assigns the communication port to which the external device is connected.

Syntax

HRESULT put_DevicePort(
  long DevicePort
);

Parameters

DevicePort

[in] Specifies the port to which the device will connect. Use one of the following values.

Value | Description
DEV_PORT_1394 | IEEE 1394 Bus
DEV_PORT_ARTI | ARTI driver
DEV_PORT_COM1 | COM1
DEV_PORT_COM2 | COM2
DEV_PORT_COM3 | COM3
DEV_PORT_COM4 | COM4
DEV_PORT_DIAQ | Diaquest driver
DEV_PORT_MIN | DEV_PORT_SIM
DEV_PORT_SIM | Simulation port (used for "no hardware" simulation)
DEV_PORT_USB | Universal serial bus

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface
  • IAMExtDevice::get_DevicePort


IAMExtDevice::put_DevicePower

The put_DevicePower method assigns the external device's power mode to either on, off, or standby.

Syntax

HRESULT put_DevicePower(
  long PowerMode
);

Parameters

PowerMode

[in] Specifies the device's power mode. Use one of the following values.

Value | Description
ED_POWER_OFF | Off
ED_POWER_ON | On
ED_POWER_STANDBY | Standby

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV and MPEG Camcorder Implementation

MSDV does not support this method. It returns E_NOTIMPL.

MSTape supports both ED_POWER_OFF and ED_POWER_ON, but not ED_POWER_STANDBY. When the driver is loaded, it detects the power state. If the power is off, the driver will attempt to turn the device on. An application can use this method to set the power mode.

See Also

  • Error and Success Codes
  • IAMExtDevice Interface
  • IAMExtDevice::get_DevicePower


IAMExtTransport Interface

The IAMExtTransport interface controls the transport on a VCR or camcorder. Applications can use this interface to play, record, or stop the transport; determine whether the transport contains media; and other transport-related functions. The implementation of this interface can vary, depending on the device. Some methods might return E_NOTIMPL if the device does not support them.

This interface also contains methods for non-linear editing through edit events and edit property sets. Currently, DirectShow does not provide any filters or drivers that implement this part of the interface.

Filter Developers: Implement this interface if you are writing a filter that controls an external device with a transport, such as a VCR. If you implement this interface, you should implement the IAMExtDevice interface as well.

Requirements

The DV camcorder driver, MSDV, requires some additional constants that are defined in the header file Xprtdefs.h.

Hardware Requirements

To control an external VCR, certain hardware requirements are recommended. VCRs with an RS-422 serial interface require a special serial port card or an external RS-232-to-RS-422 adapter. In addition, for best performance, your computer should have a serial port card built with a 16550 high-performance UART to sustain higher baud rates, such as 38.4 baud.

In addition to the methods inherited from IUnknown, the IAMExtTransport interface exposes the following methods.

Method | Description
GetCapability | Retrieves the general capabilities of an external transport.
put_MediaState | Sets the current state of the media.
get_MediaState | Retrieves the current state of the media.
put_LocalControl | Sets the state of the device to local or remote control.
get_LocalControl | Retrieves the state of the device.
GetStatus | Determines the status of the transport.
GetTransportBasicParameters | Retrieves the transport's basic parameter settings.
SetTransportBasicParameters | Sets the transport's basic parameters.
GetTransportVideoParameters | Retrieves the transport's video parameter settings.
SetTransportVideoParameters | Sets the video parameters for the transport.
GetTransportAudioParameters | Retrieves the transport's audio parameter settings.
SetTransportAudioParameters | Sets audio parameter settings for the transport.
put_Mode | Sets the movement of the transport to a new mode, such as play, stop, or record.
get_Mode | Retrieves the mode of the transport.
put_Rate | Sets the playback rate for variable-speed external devices.
get_Rate | Retrieves the playback rate.
GetChase | Retrieves the status of chase mode.
SetChase | Enables or disables chase mode.
GetBump | Retrieves status of bump mode.
SetBump | Temporarily changes the speed of playback for synchronization of multiple external devices.
get_AntiClogControl | Determines if the anti-headclog control is enabled or disabled.
put_AntiClogControl | Enables or disables the transport's anti-headclog control.
GetEditPropertySet | Retrieves the current state of an edit property set.
SetEditPropertySet | Registers an edit property set that describes a group of edit properties.
GetEditProperty | Retrieves individual parameters and values associated with a particular edit property set.
SetEditProperty | Defines individual parameters and values associated with a particular edit property set.
get_EditStart | Determines whether edit control is active.
put_EditStart | Activates edit control.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_EXT_TRANSPORT property set. For more information, see the DirectX DDK documenation.


IAMExtTransport::get_AntiClogControl

The get_AntiClogControl method determines whether the anti-headclog control is enabled or disabled.

Syntax

HRESULT get_AntiClogControl(
  long *pEnabled
);

Parameters

pEnabled

[out] Pointer to a long integer that receives one of the following values:

Value | Description
OATRUE | Anti-headclog is enabled.
OAFALSE | Anti-headclog is disabled.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::put_AntiClogControl


IAMExtTransport::GetBump

The GetBump method retrieves the status of bump mode.

Syntax

HRESULT GetBump(
  long *pSpeed,
  long *pDuration
);

Parameters

pSpeed

[out] Pointer to a long integer that receives the temporary bump speed, as a multiple of normal speed.

pDuration

[out] Pointer to a long integer that receives the duration of a bump. The duration is given in the current time format; see IAMExtTransport::SetTransportBasicParameters for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

This method returns the temporary speed and remaining duration for an active "bump."

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::SetBump


IAMExtTransport::GetCapability

The GetCapability method retrieves the general capabilities of the transport.

Syntax

HRESULT GetCapability(
  long Capability,
  long *pValue,
  double *pdblValue
);

Parameters

Capability

[in] Specifies the capability to check. See Remarks for more information.

pValue

[out] Pointer to a variable that receives a long integer. See Remarks for more information.

pdblValue

[out] Pointer to a variable that receives a double. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The Capability parameter is a flag that specifies which capability to check. The method returns the result either in the pValue parameter or in the pdblValue parameter, depending on the capability flag.

For the following flags, the method returns the value OATRUE or OAFALSE in the pValue parameter. The value OATRUE indicates that the capability is present, while the value OAFALSE indicates it is absent.

Capability Flag | Description
ED_TRANSCAP_CAN_ASSEMBLE | Transport can use assemble record mode (record new tracks that link seamlessly to the control track from the previously recorded segment).
ED_TRANSCAP_CAN_BUMP_PLAY | Transport can synchronize by varying speed.
ED_TRANSCAP_CAN_DELAY_AUDIO_IN | Transport can perform delayed-in audio edits.
ED_TRANSCAP_CAN_DELAY_AUDIO_OUT | Transport can perform delayed-out audio edits.
ED_TRANSCAP_CAN_DELAY_VIDEO_IN | Transport can perform delayed-in video edits.
ED_TRANSCAP_CAN_DELAY_VIDEO_OUT | Transport can perform delayed-out video edits.
ED_TRANSCAP_CAN_DETECT_LENGTH | Transport can detect the length of the media.
ED_TRANSCAP_CAN_EJECT | Transport can eject the media.
ED_TRANSCAP_CAN_FREEZE | Transport can freeze/pause.
ED_TRANSCAP_CAN_INSERT | Transport can use insert record mode (record individual tracks while locked to a prerecorded control track).
ED_TRANSCAP_CAN_PLAY_BACKWARDS | Transport can play backwards.
ED_TRANSCAP_CAN_SET_EE | Transport can show the device's input on its output.
ED_TRANSCAP_CAN_SET_PB | Transport can show media playback on its output.
ED_TRANSCAP_FIELD_STEP | Transport responds to a frame advance command by advancing one field.
ED_TRANSCAP_HAS_CLOCK | Device has a clock.
ED_TRANSCAP_HAS_DT | Device has dynamic tracking.
ED_TRANSCAP_HAS_TIMER | Device has a timer.
ED_TRANSCAP_HAS_TUNER | Device has a tuner.
ED_TRANSCAP_IS_MASTER | Device is the master clock for synchronizing.
ED_TRANSCAP_MULTIPLE_EDITS | Device supports multiple edit events.
ED_TRANSCAP_NEEDS_CUEING | Device must be cued before it performs an edit.
ED_TRANSCAP_NEEDS_TBC | Device needs to be calibrated.

For the following flags, the method returns a numeric value in the pValue parameter.

Capability Flag | Returned Value
ED_TRANSCAP_LTC_TRACK | Returns the track number of the LTC timecode track, or ED_ALL if there is no dedicated timecode track.
ED_TRANSCAP_NUM_AUDIO_TRACKS | Returns the number of audio tracks.

For the following flags, the method returns a value in the pdblValue parameter.

Capability Flag | Returned Value
ED_TRANSCAP_FWD_SHUTTLE_MAX | Maximum forward speed in shuttle mode, as a multiple of play speed.
ED_TRANSCAP_FWD_SHUTTLE_MIN | Minimum forward speed in shuttle mode, as a multiple of play speed.
ED_TRANSCAP_FWD_VARIABLE_MAX | Maximum forward speed, as a multiple of play speed.
ED_TRANSCAP_FWD_VARIABLE_MIN | Minimum forward speed, as a multiple of play speed.
ED_TRANSCAP_REV_SHUTTLE_MAX | Maximum reverse speed in shuttle mode, as a multiple of play speed.
ED_TRANSCAP_REV_SHUTTLE_MIN | Minimum reverse speed in shuttle mode, as a multiple of play speed.
ED_TRANSCAP_REV_VARIABLE_MAX | Maximum reverse speed, as a multiple of play speed.
ED_TRANSCAP_REV_VARIABLE_MIN | Minimum reverse speed, as a multiple of play speed.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::GetChase

The GetChase method retrieves the status of chase mode.

Syntax

HRESULT GetChase(
  long *pEnabled,
  long *pOffset,
  HEVENT *phEvent
);

Parameters

pEnabled

[out] Pointer to a long integer that receives one of the following values:

Value | Description
OATRUE | Chase enabled.
OAFALSE | Chase disabled.

pOffset

[out] Pointer to a long integer that receives an offset from the present time, indicating the offset that the transport will maintain while playing. The offset is given in the current time format; see IAMExtTransport::SetTransportBasicParameters for more information.

phEvent

[out] Pointer to a variable that receives an event handle. The event is signaled when the chase offset is established.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::SetChase


IAMExtTransport::GetEditProperty

The GetEditProperty method retrieves parameters and values associated with an edit event.

Syntax

HRESULT GetEditProperty(
  long EditID,
  long Param,
  long *pValue
);

Parameters

EditID

[in] Specifes the edit property set. Use the identifier returned by the IAMExtTransport::SetEditPropertySet method.

Param

[in] Specifies the edit event parameter to retrieve.

pValue

[out] pointer to a variable that receives the parameter value.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

For a list of edit event parameters and their possible values, see IAMExtTransport::SetEditProperty. In addition, this method supports ED_EDIT_TEST, which determines whether the device can perform the edit. If the device filter estimates that the device can perform the edit, it returns the value OATRUE in the pValue parameter. If not, it returns the value OAFALSE.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::SetEditProperty


IAMExtTransport::GetEditPropertySet

The GetEditPropertySet method retrieves the state of an edit event.

Syntax

HRESULT GetEditPropertySet(
  long EditID,
  long *pState
);

Parameters

EditID

[in] Specifies the edit property set. Use the identifier returned by the IAMExtTransport::SetEditPropertySet method.

pState

[out] Pointer to a long integer that receives the state of the edit property set:

Value | Description
ED_ACTIVE | The edit property set is active.
ED_DELETE | The edit property set was deleted.
ED_INACTIVE | The edit property set is inactive.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::SetEditPropertySet


IAMExtTransport::get_EditStart

The get_EditStart method determines whether the external transport's edit control is active.

Syntax

HRESULT get_EditStart(
  long *pValue
);

Parameters

pValue

[out] Specifies a pointer to a to a long integer to receive a value indicating whether the external transport's edit control is active.

Value | Description
OATRUE | Edit control is active.
OAFALSE | Edit control is inactive.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::put_EditStart


IAMExtTransport::get_LocalControl

The get_LocalControl method determines whether the transport is under local control or remote control.

Syntax

HRESULT get_LocalControl(
  long *pState
);

Parameters

pState

[out] Pointer to a long integer that receives one of the following values:

Value | Description
OATRUE | Local control.
OAFALSE | Remote control.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

To control an external device from an application, the device must be in remote mode.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::put_LocalControl


IAMExtTransport::get_MediaState

The get_MediaState method retrieves the current state of the media.

Syntax

HRESULT get_MediaState(
  long *pState
);

Parameters

pState

[out] Pointer to a long integer that receives one of the following values.

Value | Description
ED_MEDIA_SPIN_DOWN | For disk media: Stopped spinning. For tape media: Tape is unthreaded.
ED_MEDIA_SPIN_UP | For disk media: Started spinning, but not at full speed. For tape media: Threading the tape.
ED_MEDIA_UNLOAD | Media is ejected from the drive.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::get_Mode

The get_Mode method retrieves the current transport mode, such as play, stop, or record.

Syntax

HRESULT get_Mode(
  long *pMode
);

Parameters

pMode

[out] Pointer to a long integer that receives the current transport mode. For possible values, see IAMExtTransport::put_Mode.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

For a list of transport modes supported by MSDV, see IAMExtTransport::put_Mode. In addition, MSDV supports the following flags for the get_Mode method, but not the put_Mode method.

Value | Description
ED_MODE_REW_FASTEST | High-speed rewind.
ED_MODE_REV_PLAY | Reverse play, at normal speed.

These flags are defined in the header file Xprtdefs.h.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::get_Rate

The get_Rate method retrieves the playback rate for variable-speed external devices.

Syntax

HRESULT get_Rate(
  double *pdblRate
);

Parameters

pdblRate

[out] Pointer to a double to receive the playback rate that was set using IAMExtTransport::put_Rate.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::GetStatus

The GetStatus method returns information about the transport's status.

Syntax

HRESULT GetStatus(
  long StatusItem,
  long *pValue
);

Parameters

StatusItem

[in] Specifies the status information to retrieve. See Remarks for more information.

pValue

[out] Pointer to variable that either specifies or receives a long integer, whose meaning depends on the value of StatusItem. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The StatusItem parameter is a flag that specifies which status information to retrieve. The method returns in the information in the pValue parameter. Not every device supports every status flag. The following flags are defined:

  • ED_MODE: Returns the current transport mode, such as pause or play. See IAMExtTransport::put_Mode for a list of constants that define the transport modes. As an alternative, you can set StatusItem equal to one of these constants, and pValue will receive the value OATRUE if the transport is currently in that mode, or OAFALSE otherwise.
  • ED_MEDIA_TYPE: Indicates the format of the media for this transport. Returns one of the following constants.
    Constant | Description
    ED_MEDIA_VHS | VHS
    ED_MEDIA_SVHS | S-VHS
    ED_MEDIA_HI8 | Hi-8
    ED_MEDIA_UMATIC | Umatic
    ED_MEDIA_DVC | DV tape (DVC)
    ED_MEDIA_1_INCH | 1-inch tape
    ED_MEDIA_D1 | D1 format
    ED_MEDIA_D2 | D2 format
    ED_MEDIA_D3 | D3 format
    ED_MEDIA_D5 | D5 format
    ED_MEDIA_DBETA | Digital Betacam
    ED_MEDIA_BETA | Betacam
    ED_MEDIA_8MM | 8-millimeter
    ED_MEDIA_DDR | Digital disk recorder
    ED_MEDIA_SX | Betacam SX
    ED_MEDIA_OTHER | Other
    ED_MEDIA_CLV | CLV (Constant Linear Velocity, or "standard play") laserdisc
    ED_MEDIA_CAV | CAV (Constant Angular Velocity, or "extended play") laserdisc

  • ED_LINK_MODE: Returns OATRUE if the transport's controls are linked to the filter graph's Run, Stop, and Pause methods, and OAFALSE otherwise. See IAMExtTransport::put_Mode for more information.
  • ED_MEDIA_PRESENT: Returns OATRUE if the transport's media is present, or OAFALSE otherwise.
  • ED_MEDIA_LENGTH: Returns the length of the media, in units of the current time format (see IAMExtTransport::SetTransportBasicParameters).
  • ED_MEDIA_TRACK_COUNT: Returns the track count.
  • ED_MEDIA_TRACK_LENGTH: Returns the track length, in units of the current time format.
  • ED_MEDIA_SIDE: Indicates which side of the media is active.

DV Implementation

MSDV supports the following status flags:

  • ED_MODE: See previous remarks.
  • ED_MEDIA_TYPE: Returns one of the following values.
    Constant | Description
    ED_MEDIA_VHS | VHS tape.
    ED_MEDIA_DVC | DV tape.
    ED_MEDIA_UNKNOWN | Unknown type.
    ED_MEDIA_NOT_PRESENT | The transport is empty.

  • ED_DEV_REMOVED_HEVENT_GET. Returns a handle to an event. The driver signals the event if the device is physically removed from the system.
  • ED_DEV_REMOVED_HEVENT_RELEASE. Releases the event handle obtained through the ED_DEV_REMOVED_HEVENT_GET flag. Specify the address of the handle in the pValue parameter.
  • ED_MODE_CHANGE_NOTIFY. Returns the device state in pValue. If the method returns E_PENDING, a state change is pending. You can use the ED_NOTIFY_HEVENT_GET flag to get notification when the state change is complete.
  • ED_NOTIFY_HEVENT_GET. Returns a handle to an event. The driver signals the event when the device completes a mode change.
  • ED_NOTIFY_HEVENT_RELEASE. Releases the event handle obtained through the ED_NOTIFY_HEVENT_GET flag. Specify the address of the handle in the pValue parameter.

MPEG Camcorder Implementation

MSTape supports an additional media format for the ED_MEDIA_TYPE flag.

Constant | Description
ED_MEDIA_NEO | Mini digital tape for MPEG-2 transport stream (D-VHS).

Some of these flags are defined in the header file Xptrdefs.h.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::GetTransportAudioParameters

The GetTransportAudioParameters method retrieves audio parameter setting for external transport.

Syntax

HRESULT GetTransportAudioParameters(
  long Param,
  long *pValue
);

Parameters

Param

[in] Specifies the audio parameter, whose value you want receive, as a long integer containing one of the following values.

Value | Description
ED_TRANSAUDIO_ENABLE_OUTPUT | Audio output channel(s)
ED_TRANSAUDIO_ENABLE_RECORD | Audio recording channel(s)
ED_TRANSAUDIO_ENABLE_SELSYNC | Audio selsync recording channel(s)
ED_TRANSAUDIO_SET_MONITOR | Monitor output audio channel(s)
ED_TRANSAUDIO_SET_SOURCE | Audio source channel(s)

pValue

[out] Specifies a pointer to a long integer to receive the channel or channels set in the IAMExtTransport::SetTransportAudioParameters method.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::GetTransportBasicParameters

The GetTransportBasicParameters method retrieves general properties of the external transport.

Syntax

HRESULT GetTransportBasicParameters(
  long Param,
  long *pValue,
  LPOLESTR *ppszData
);

Parameters

Param

[in] Specifies which property to receive.

pValue

[out] Pointer to a variable that receives a long integer value. See Remarks for more information.

ppszData

[out] Pointer to a variable of type LPOLESTR that receives a string. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The Param parameter is a flag that specifies which property to retrieve. Some properties are numeric; these are returned in the pValue parameter. Other properties are string values; these are returned in the ppszData parameter. For a list of flags and expected values, see IAMExtTransport::SetTransportBasicParameters.

If the method returns a string, the caller must free the string, using the CoTaskMemFree function.

DV and MPEG Camcorder Implementation

MSDV supports the following additional flags:

  • ED_RAW_EXT_DEV_CMD: Invokes a raw AV/C command. Specify the AV/C command as an array of bytes in the ppszData parameter. Specify the size of the command, in bytes, in the pValue parameter. When the method returns, ppszData contains the response from the device, and pValue contains the size of the response, in bytes. The AV/C command is passed directly to the device with no validation or error checking.

    The response payload might be larger than the command. It is the caller's responsibility to allocate enough space in the buffer for the response. The maximum payload size is 512 bytes.

    For more information, see Issuing Raw AV/C Commands.

  • ED_TRANSBASIC_INPUT_SIGNAL: Retrieves the signal format that the DV camcorder is designed to accept. Returns one of the following constants in pValue.
    Constant | Description
    ED_TRANSBASIC_SIGNAL_525_60_SD | NTSC SD signal.
    ED_TRANSBASIC_SIGNAL_525_60_SDL | NTSC SDL (long-play) signal.
    ED_TRANSBASIC_SIGNAL_625_50_SD | PAL SD signal.
    ED_TRANSBASIC_SIGNAL_625_50_SDL | PAL SDL (long-play) signal.
    ED_TRANSBASIC_SIGNAL_MPEG2TS | D-VHS signal.

  • ED_TRANSBASIC_OUTPUT_SIGNAL: Retrieves the signal format that the DV camcorder is designed to transmit. Returns one of the constants listed for the ED_TRANSBASIC_INPUT_SIGNAL flag.

MSTape supports additional values for ED_TRANSBASIC_INPUT_SIGNAL and ED_TRANSBASIC_INPUT_SIGNAL.

Constant | Description
ED_TRANSBASIC_SIGNAL_2500_60_MPEG | 25-Mbps/60 MPEG stream.
ED_TRANSBASIC_SIGNAL_1250_60_MPEG | 12.5-Mbps/60 MPEG stream.
ED_TRANSBASIC_SIGNAL_0625_60_MPEG | 6.25-Mbps/60 MPEG stream.
ED_TRANSBASIC_SIGNAL_2500_50_MPEG | 25-Mbps/50 MPEG stream.
ED_TRANSBASIC_SIGNAL_1250_50_MPEG | 12.5-Mbps/50 MPEG stream.
ED_TRANSBASIC_SIGNAL_0625_50_MPEG | 6.25-Mbps/50 MPEG stream.
ED_TRANSBASIC_SIGNAL_UNKNOWN | Unknown signal format.

These flags are defined in the header file Xprtdefs.h.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface


IAMExtTransport::GetTransportVideoParameters

The GetTransportVideoParameters retrieves video parameter settings for external transport.

Syntax

HRESULT GetTransportVideoParameters(
  long Param,
  long *pValue
);

Parameters

Param

[in] Specifies the video parameter to retrieve. Must be one of the following values.

Value | Description
ED_TRANSVIDEO_SET_OUTPUT | Retrieves the output mode.
ED_TRANSVIDEO_SET_SOURCE | Retrieves the input pin.

pValue

[out] Specifies a pointer to a long integer to receive the video parameter. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

If Param equals ED_TRANSVIDEO_SET_OUTPUT, pValue receives one of the following constants.

Value | Description
ED_E2E | Input video is displayed on the device's output regardless of the transport mode.
ED_OFF | Video output is disabled.
ED_PLAYBACK | Video playing from media is displayed on the device's output.

If Param equals ED_TRANSVIDEO_SET_SOURCE, pValue receives the index of the input pin used for the video input. The pin index is zero-based.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::SetTransportVideoParameters


IAMExtTransport::put_AntiClogControl

The put_AntiClogControl method enables or disables anti-headclog control on the transport.

Syntax

HRESULT put_AntiClogControl(
  long Enable
);

Parameters

Enable

[in] Specifies whether to enable anti-headclog control.

Value | Description
OATRUE | Enable transport anti-headclog control.
OAFALSE | Disable transport anti-headclog control.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Use this method to unclog video heads on VCRs that have an automatic head-cleaning feature.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_AntiClogControl


IAMExtTransport::put_EditStart

The put_EditStart method activates the edit control on a capable transport.

Syntax

HRESULT put_EditStart(
  long Value
);

Parameters

Value

[in] Specifies whether to active the edit control.

Value | Description
OATRUE | Activates the edit control.
OAFALSE | Deactivates the edit control.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Use this method to manually enable edit control. Edit control is defined as the precise enabling of individual, or a set of, record tracks on a VCR; for example, a video-only insert edit, where only the video record head is enabled and a new video signal is recorded—the audio signal is left as is. Use this method to control "on the fly" editing on machines that have this feature.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_EditStart


IAMExtTransport::put_LocalControl

The put_LocalControl method switches the device between local and remote control.

Syntax

HRESULT put_LocalControl(
  long State
);

Parameters

State

[in] Specifies the state of the device.

Value | Description
OATRUE | Local control
OAFALSE | Remote control

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_LocalControl


IAMExtTransport::put_MediaState

The put_MediaState method sets the current state of the media.

Syntax

HRESULT put_MediaState(
  long State
);

Parameters

State

[in] Specifies the media state as a long integer. Use one of the following:

Value | Description
ED_MEDIA_SPIN_DOWN | For disk media: Stop spinning. For tape media: Unthread the tape.
ED_MEDIA_SPIN_UP | For disk media: Start spinning. For tape media: Thread the tape.
ED_MEDIA_UNLOAD | Eject the media from the drive.

These constants are for disk and tape media. Other devices might need to define new constants.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_MediaState


IAMExtTransport::put_Mode

The put_Mode method sets the transport mode; for example, play, stop, or record.

Syntax

HRESULT put_Mode(
  long Mode
);

Parameters

Mode

[in] Specifies the transport mode as a long integer. Use one of the following values.

Value | Description
ED_MODE_PLAY | Play.
ED_MODE_STOP | Stop.
ED_MODE_FREEZE | Pause.
ED_MODE_THAW | Resume.
ED_MODE_FF | Fast forward.
ED_MODE_REW | Rewind.
ED_MODE_RECORD | Record.
ED_MODE_RECORD_FREEZE | Pause recording.
ED_MODE_RECORD_STROBE | Record single frame.
ED_MODE_STEP_FWD | Single step forward.
ED_MODE_STEP_REV | Single step backward.
ED_MODE_SHUTTLE | Shuttle (high-speed movement with visible picture). Use with IAMExtTransport::put_Rate to set the transport speed.
ED_MODE_EDIT_CUE | Position transport to the cue point for an active edit event.
ED_MODE_LINK_ON | Link this method to the graph's IMediaControl::Run, IMediaControl::Stop, and IMediaControl::Pause methods.
ED_MODE_LINK_OFF | Disengage this method from the graph's IMediaControl methods.

Return Values

Returns an HRESULT. Possible errors include the following.

Value | Description
HRESULT_FROM_WIN32(ERROR_REQ_NOT_ACCEP) | The device did not accept the command.
S_OK | Success.

DV Implementation

Of the constants listed previously, MSDV supports the following:

  • ED_MODE_PLAY
  • ED_MODE_STOP
  • ED_MODE_FREEZE
  • ED_MODE_FF
  • ED_MODE_REW
  • ED_MODE_RECORD
  • ED_MODE_RECORD_FREEZE
  • ED_MODE_STEP_FW
  • ED_MODE_STEP_REV

MSDV supports some additional modes that are defined in the header file Xprtdefs.h.

Value | Description
ED_MODE_PLAY_FASTEST_FWD | Fastest forward.
ED_MODE_PLAY_SLOWEST_FWD | Slowest forward.
ED_MODE_PLAY_FASTEST_REV | Fastest reverse.
ED_MODE_PLAY_SLOWEST_REV | Slowest reverse.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_Mode


IAMExtTransport::put_Rate

The put_Rate method sets the playback rate for variable-speed external devices.

Syntax

HRESULT put_Rate(
  double dblRate
);

Parameters

dblRate

[in] Specifies the rate as a multiple of normal playback rate. For example, 0.5 specifies half speed, and 2.0 specifies double speed.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::get_Rate


IAMExtTransport::SetBump

The SetBump method temporarily changes the playback, for synchronization of multiple external devices.

Syntax

HRESULT SetBump(
  long Speed,
  long Duration
);

Parameters

Speed

[in] Specifies the temporary speed (a multiple of normal speed) as a long integer.

Duration

[in] Specifies the duration of a bump as a long integer. The duration is given in the current time format; see IAMExtTransport::SetTransportBasicParameters for more information.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method causes a temporary speed variation of the transport. The transport operates at the new speed until the specified duration elapses. Then it returns to its previous speed.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetBump


IAMExtTransport::SetChase

The SetChase method enables or disables chase mode.

Syntax

HRESULT SetChase(
  long Enable,
  long Offset,
  HEVENT hEvent
);

Parameters

Enable

[in] Specifies whether chase is enabled as a long integer.

Value | Description
OATRUE | Enable chase.
OAFALSE | Disable chase.

Offset

[in] Specifies the offset that the transport will maintain from a reference time. The offset is given in the current time format; see IAMExtTransport::SetTransportBasicParameters for more information.

hEvent

[in] Specifies a handle to an event. The device signals the event after it has established the signal offset.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Use this method when you want an external transport to follow a timecode signal by a fixed offset. For example, if a VCR supports chasing, it can switch to play mode and keep the tape at a fixed offset from a reference timecode.

Chase mode remains in effect until it completes or is canceled. The filter must verify that the transport is maintaining the fixed offset, by periodically reading the transport's timecode.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetChase


IAMExtTransport::SetEditProperty

The SetEditProperty method defines parameters and values associated with an edit event.

Syntax

HRESULT SetEditProperty(
  long EditID,
  long Param,
  long Value
);

Parameters

EditID

[in] Specifes the edit property set. Use the identifier returned by the IAMExtTransport::SetEditPropertySet method.

Param

[in] Specifies the edit event parameter. See Remarks for more information.

Value

[in] Specifies the value of the parameter. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

An edit event consists of one or more edit event parameters. Use the SetEditPropertySet method to create an edit event, and then use this method to specify the edit event parameters for that edit event.

The Param parameter is a flag that specifies the edit event parameter. The Value parameter specifies the value of that parameter. The meaning of Value depends on the flag used in Param:

  • ED_EDIT_HEVENT: Handle to an event. The device will signal the event when the edit event has completed.
  • ED_EDIT_IMMEDIATE: If the value is OATRUE, the application can switch the device into edit mode by calling IAMExtTransport::put_Mode with the value ED_MODE_EDIT_CUE.
  • ED_EDIT_MODE: Specifies the editing mode. Use one of the following constants.
    Constant | Description
    ED_EDIT_MODE_ASSEMBLE | Assemble edit mode.
    ED_EDIT_MODE_INSERT | Insert edit mode.
    ED_EDIT_MODE_CRASH_RECORD | Crash record mode.

  • ED_EDIT_TRACK: Specifies which track to edit. Use one or more of the following constants. You can combine constants with a bitwise OR.
    Constant | Description
    ED_VIDEO | Video track
    ED_AUDIO_1 through ED_AUDIO_24 | Audio tracks 1 through 24
    ED_AUDIO_ALL | All audio track

  • ED_EDIT_SRC_INPOINT: Specifies the inpoint on the source, in units of the current time format.
  • ED_EDIT_SRC_OUTPOINT: Specifies the outpoint on the source, in units of the current time format.
  • ED_EDIT_REC_INPOINT: Specifies the inpoint on the record device, in units of the current time format.
  • ED_EDIT_REC_OUTPOINT: Specifies the outpoint on the record device, in units of the current time format.
  • ED_EDIT_REHEARSE_MODE: Specifies the preview mode. Use one of the following constants.
    Constant | Description
    ED_EDIT_BVB | Black-video-black (BVB). Display black, then inserted video, then black.
    ED_EDIT_VBV | Video-black-video (VBV). Display recorded video, then black, then recorded video.
    ED_EDIT_VVV | Video-video-video (VVV). Display recorded video, then inserted video, then recorded video.
    ED_EDIT_PERFORM | Do not preview.

  • ED_EDIT_ABORT: With the value OATRUE, the method halts the edit if it is currently in progress.
  • ED_EDIT_TIMEOUT: Specifies how long the device will wait for the edit to complete, before timing out.
  • ED_EDIT_SEEK: With the value OATRUE, the method seeks to a specified point. First call this method with the ED_EDIT_SEEK_MODE flag, to specify the seek point.
  • ED_EDIT_SEEK_MODE: Specifies a seek point. Use one of the following constants.
    Constant | Description
    ED_EDIT_SEEK_EDIT_IN | Seek to the inpoint.
    ED_EDIT_SEEK_EDIT_OUT | Seek to the outpoint.
    ED_EDIT_SEEK_PREROLL | Seek to the inpoint preroll.
    ED_EDIT_SEEK_PREROLL_CT | Seek to the inpoint using timecode, then seek back to the preroll point using the control track.
    ED_EDIT_SEEK_BOOKMARK | Seek to the next bookmark.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetEditProperty


IAMExtTransport::SetEditPropertySet

The SetEditPropertySet method registers an edit property set that describes a group of edit properties.

Syntax

HRESULT SetEditPropertySet(
  long *pEditID,
  long State
);

Parameters

pEditID

[in, out] Pointer to a long integer that specifies or receives an identifier for the edit property set.

State

[in] Specifies the state of the edit property set.

Value | Description
ED_ACTIVE | Activates the edit property set.
ED_DELETE | Deletes the edit property set.
ED_INACTIVE | Inactivates edit property set.
ED_REGISTER | Registers the edit property set.

If the value is ED_REGISTER, the pEditID parameter receives an identifier for the edit property set. For the other flags, use the pEditID parameter to specify the identifier.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

An edit event is a set of parameters that define a recording sequence. For example, the parameters can specify editing modes, inpoints and outpoints, or seek positions. Each edit event consists of one or more parameters, called edit properties. The collection of properties is called an edit property set. Each edit property set is identified by a long integer, assigned by the device filter.

To create and execute an edit event, the application must do the following:

  • Register an edit property set. Call the SetEditPropertySet method with the value ED_REGISTER in the State parameter. When the method returns, the pEditID parameter contains the identifer for the edit property set. Use this number to identify the edit property set in subsequent method calls.
  • Specify the edit properties using the IAMExtTransport::SetEditProperty method.
  • Activate the edit event by calling SetEditPropertySet with the value ED_ACTIVE.
  • Cue the transport by calling SetEditProperty with the value ED_EDIT_SEEK.
  • Run the filter graph.

For example, the following code configures an insert edit on all tracks:

// Register an edit property set ID. (Causes memory to be allocated.)
long EditId;
SetEditPropertySet(&EditId, ED_REGISTER);

// Set the edit mode.
SetEditProperty(EditId, ED_EDIT_MODE, ED_EDIT_MODE_INSERT);
// Set the particulars about the event.
SetEditProperty(EditId, ED_EDIT_TRACK, ED_VIDEO | ED_AUDIO_ALL);
SetEditProperty(EditId, ED_REHEARSE_MODE, ED_EDIT_PERFORM);

// Set the source and record times.
SetEditProperty(EditId, ED_EDIT_SRC_INPOINT, 200)
SetEditProperty(EditId, ED_EDIT_SRC_OUTPOINT, 500)
SetEditProperty(EditId, ED_EDIT_REC_INPOINT, 100)
SetEditProperty(EditId, ED_EDIT_REC_OUTPOINT, 400)

// Activate the edit event.
SetEditPropertySet(&EditId, ED_ACTIVE);
// Cue up the machine.
SetEditProperty(EditId, ED_EDIT_SEEK, OATRUE);

// Run the graph. (Not shown.)

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetEditPropertySet


IAMExtTransport::SetTransportAudioParameters

The SetTransportAudioParameters assigns audio parameter settings for external transport.

Syntax

HRESULT SetTransportAudioParameters(
  long Param,
  long Value
);

Parameters

Param

[in] Specifies the audio parameter you want to set as a long integer.

Value | Description
ED_TRANSAUDIO_ENABLE_OUTPUT | Enable audio channel(s) for output.
ED_TRANSAUDIO_ENABLE_RECORD | Enable audio channel(s) for recording.
ED_TRANSAUDIO_ENABLE_SELSYNC | Enable audio channel(s) for selsync recording.
ED_TRANSAUDIO_SET_MONITOR | Set the monitor output source.
ED_TRANSAUDIO_SET_SOURCE | Set the active audio input.

Value

[in] Specifies which audio channel or channels is assigned the parameter as a long integer.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Specify an exact channel or channels in Value by selecting ED_AUDIO_1 through ED_AUDIO_24 (use a bitwise OR to combine), or all channels by selecting ED_AUDIO_ALL.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetTransportAudioParameters


IAMExtTransport::SetTransportBasicParameters

The SetTransportBasicParameters method sets general properties of the transport.

Syntax

HRESULT SetTransportBasicParameters(
  long Param,
  long Value,
  LPCOLESTR pszData
);

Parameters

Param

[in] Specifies which property to set. See Remarks for more information.

Value

[in] Specifies the value of the property as a long integer. See Remarks for more information.

pszData

[in] Specifies the value of the property as an LPOLESTR. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code. Possible error codes include the following.

Return code | Description
E_NOTIMPL | Device does not support setting this property.
ERROR_DEVICE_REMOVED | Device was removed.

Remarks

The Param parameter is a flag that specifies which property to set. For some flags, the property is numeric; use the Value parameter to specify the value. For other flags, the property is a string; use the pszData parameter to specify the value. In either case, the method ignores the other parameter.

For the following flags, the Value parameter takes a defined constant.

  • ED_TRANSBASIC_TIME_FORMAT: Specifies the time format.
    Constant | Description
    ED_FORMAT_MILLISECONDS | Milliseconds.
    ED_FORMAT_FRAMES | Frames.
    ED_FORMAT_REFERENCE_TIME | Reference time.
    ED_FORMAT_HMSF | Binary coded decimal, representing hours, minutes, seconds, and frames.
    ED_FORMAT_TMSF | Binary coded decimal, representing tracks, minutes, seconds, and frames.

  • ED_TRANSBASIC_TIME_REFERENCE: Specifies the reference time in use by the device.
    Constant | Description
    ED_TIMEREF_TIMECODE | Time code.
    ED_TIMEREF_CONTROL_TRACK | Control track.
    ED_TIMEREF_INDEX | Index.
    ED_TIMEREF_ATN | Absolute track number. This constant is defined in the header file Xprtdefs.h.

  • ED_TRANSBASIC_END_STOP_ACTION: Specifies the action the device takes when it reaches the end of the transport medium.
    Constant | Description
    ED_MODE_STOP | Stop.
    ED_MODE_REWIND | Rewind.
    ED_MODE_FREEZE | Freeze/pause.

  • ED_TRANSBASIC_RECORD_FORMAT: Specifies the recording speed.
    Constant | Description
    ED_RECORD_FORMAT_SP | Standard play.
    ED_RECORD_FORMAT_LP | Long play.
    ED_RECORD_FORMAT_EP | Extended play.

  • ED_TRANSBASIC_SUPERIMPOSE: Specifies whether the on-screen display is enabled or disabled.
    Constant | Description
    OATRUE | On-screen display is enabled.
    OAFALSE | On-screen display is disabled.

  • ED_TRANSBASIC_STEP_UNIT: Specifies the step unit.
    Constant | Description
    ED_STEP_FIELD | Fields.
    ED_STEP_FRAME | Frames.
    ED_STEP_3_2 | 3/2 Pulldown.

  • ED_TRANSBASIC_SET_COUNTER_FORMAT: Sets the time format for the counter. See the ED_TRANSBASIC_TIME_FORMAT flag for possible values.

For the following flags, use a numeric value in the Value parameter.

Flag | Description
ED_TRANSBASIC_STEP_COUNT | Specifies the step count, in units defined by the ED_TRANSBASIC_STEP_UNIT flag.
ED_TRANSBASIC_SET_FREEZE_TIMEOUT | Specifies the timeout for freeze mode, in units of the current time format.
ED_TRANSBASIC_SETCLOCK | Sets the clock time.
ED_TRANSBASIC_SET_COUNTER_VALUE | Sets the value of the counter.

For the following flags, use a string in the pszData parameter.

Flag | Description
ED_TRANSBASIC_VOLUME_NAME | Specifies the volume name.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetTransportBasicParameters


IAMExtTransport::SetTransportVideoParameters

The SetTransportVideoParameters method assigns video parameters for external transport.

Syntax

HRESULT SetTransportVideoParameters(
  long Param,
  long Value
);

Parameters

Param

[in] Specifies the video parameter to set. Must be one of the following values.

Value | Description
ED_TRANSVIDEO_SET_OUTPUT | Sets the output mode.
ED_TRANSVIDEO_SET_SOURCE | Sets the input pin.

Value

[in] Specifies the value of the video parameter. See Remarks for more information.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

If Param equals ED_TRANSVIDEO_SET_OUTPUT, Value must be one of the following constants.

Constant | Description
ED_E2E | Input video is displayed on the device's output regardless of the transport mode.
ED_OFF | Video output is disabled.
ED_PLAYBACK | Video playing from media is displayed on the device's output.

If Param equals ED_TRANSVIDEO_SET_SOURCE, Value specifies the index of the input pin to use for the video input. The pin index is zero-based.

DV Implementation

MSDV does not support this method. It returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMExtTransport Interface
  • IAMExtTransport::GetTransportVideoParameters


IAMExtendedErrorInfo Interface

The IAMExtendedErrorInfo interface is used to obtain error information.

In addition to the methods inherited from IDispatch, the IAMExtendedErrorInfo interface exposes the following methods.

Method | Description
get_ErrorCode | Retrieves the current error code.
get_ErrorDescription | Retrieves the error description.
get_HasError | Queries whether an error occurred.

Requirements

Requires Qnetwork.h. To define the interface identifier, include Initguid.h before Qnetwork.h, but after Dshow.h:

#include <dshow.h>
#include <initguid.h>
#include <qnetwork.h>

Make sure that Initguid.h gets included only once in your project.


IAMExtendedErrorInfo::get_ErrorCode

The get_ErrorCode method retrieves the current error code.

Syntax

HRESULT get_ErrorCode(
  long *  pErrorCode
);

Parameters

pErrorCode

[out] Pointer to a variable that receives the error code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMExtendedErrorInfo Interface


IAMExtendedErrorInfo::get_ErrorDescription

The get_ErrorDescription method retrieves the extended error description.

Syntax

HRESULT get_ErrorDescription(
  BSTR *pbstrErrorDescription
);

Parameters

pbstrErrorDescription

[out] Pointer to a variable that that receives the error description.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMExtendedErrorInfo Interface


IAMExtendedErrorInfo::get_HasError

The get_HasError method queries whether an error occurred.

Syntax

HRESULT get_HasError(
  VARIANT_BOOL *pHasError
);

Parameters

pHasError

Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_FALSE | No error.
VARIANT_TRUE | An error occurred.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

If pHasError is true, you can call the get_ErrorCode and get_ErrorDescription methods to determine the nature of the error.

See Also

  • IAMExtendedErrorInfo Interface


IAMExtendedSeeking Interface

The IAMExtendedSeeking interface provides methods for seeking to markers in a Windows Media stream and for modifying the playback speed. It is implemented on the Windows Media Source filter and the WM ASF Reader filter.

In addition to the methods inherited from IDispatch, the IAMExtendedSeeking interface exposes the following methods.

Method | Description
get_CurrentMarker | Retrieves the current marker.
get_ExSeekCapabilities | Retrieves the extended seeking capabilities of the filter.
get_MarkerCount | Retrieves the number of markers in the current stream.
get_PlaybackSpeed | Retrieves the current playback speed.
GetMarkerName | Retrieves the name associated with the specified marker.
GetMarkerTime | Retrieves the presentation time associated with the specified marker.
put_PlaybackSpeed | Sets the playback speed.

Requirements

Requires Qnetwork.h. To define the interface identifier, include Initguid.h before Qnetwork.h, but after Dshow.h:

#include <dshow.h>
#include <initguid.h>
#include <qnetwork.h>

Make sure that Initguid.h is included only once in your project.


IAMExtendedSeeking::get_CurrentMarker

The get_CurrentMarker method retrieves the current marker.

Syntax

HRESULT get_CurrentMarker(
  long *pCurrentMarker
);

Parameters

pCurrentMarker

[out] Pointer to a variable that receives the current marker.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMExtendedSeeking Interface


IAMExtendedSeeking::get_ExSeekCapabilities

The get_ExSeekCapabilities method retrieves the extended seeking capabilities of the filter.

Syntax

HRESULT get_ExSeekCapabilities(
  long *pExCapabilities
);

Parameters

pExCapabilities

[out] Pointer to a variable that receives a bitwise OR of AMExtendedSeekingCapabilities flags.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The Windows Media Source filter sets the extended seeking flags as follows.

Flag | Condition
AM_EXSEEK_BUFFERING | Always.
AM_EXSEEK_NOSTANDARDREPAINT | Always.
AM_EXSEEK_SENDS_VIDEOFRAMEREADY | If the video pin has been created.
AM_EXSEEK_CANSCAN, AM_EXSEEK_SCANWITHOUTCLOCK | If the stream supports rates other than 1.0.
AM_EXSEEK_CANSEEK | If the stream has been authored to be seekable.
AM_EXSEEK_MARKERSEEK | If the stream contains markers.

See Also

  • IAMExtendedSeeking Interface


IAMExtendedSeeking::get_MarkerCount

The get_MarkerCount method retrieves the number of markers in the current stream.

Syntax

HRESULT get_MarkerCount(
  long *pMarkerCount
);

Parameters

pMarkerCount

[out] Pointer to a variable that receives the marker count.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMExtendedSeeking Interface


IAMExtendedSeeking::get_PlaybackSpeed

The get_PlaybackSpeed method retrieves the playback speed.

Syntax

HRESULT get_PlaybackSpeed(
  double *pSpeed
);

Parameters

pSpeed

[out] Pointer to a variable that receives the playback speed.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMExtendedSeeking Interface
  • IAMExtendedSeeking::put_PlaybackSpeed


IAMExtendedSeeking::GetMarkerName

The GetMarkerName method retrieves the name associated with the specified marker.

Syntax

HRESULT GetMarkerName(
  long  MarkerNum,
  BSTR *pbstrMarkerName
);

Parameters

MarkerNum

[in] Specifies the marker number.

pbstrMarkerName

[out] Pointer to a variable that receives the marker name.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMExtendedSeeking Interface
  • IAMExtendedSeeking::GetMarkerTime


IAMExtendedSeeking::GetMarkerTime

The GetMarkerTime method retrieves the presentation time associated with the specified marker.

Syntax

HRESULT GetMarkerTime(
  long  MarkerNum,
  double *pMarkerTime
);

Parameters

MarkerNum

[in] Specifies the marker number.

pMarkerTime

[out] Pointer to a variable that receives the marker time.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

None.

See Also

  • IAMExtendedSeeking Interface
  • IAMExtendedSeeking::GetMarkerName


IAMExtendedSeeking::put_PlaybackSpeed

The put_PlaybackSpeed method specifies the playback speed.

Syntax

HRESULT put_PlaybackSpeed(
  double  Speed
);

Parameters

Speed

[in] Specifies the playback speed. The value may be positive or negative, but not zero.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMExtendedSeeking Interface
  • IAMExtendedSeeking::get_PlaybackSpeed


IAMFilterGraphCallback Interface

The IAMFilterGraphCallback interface provides a callback mechanism during graph building.

To use this interface, implement the interface in your application or client object. Query the Filter Graph Manager for the IObjectWithSite interface and call the IObjectWithSite::SetSite method with a pointer to your implementation of the interface. During graph building, if the Filter Graph Manager fails to render a pin, it calls the UnabletoRender method. The client can then take appropriate action, such as providing an error message for the user or registering a new filter.

In addition to the methods inherited from IUnknown, the IAMFilterGraphCallback interface exposes the following method.

Method | Description
UnableToRender | Informs the client that no combination of filters could be found to render the specified pin.

See Also

  • IAMGraphBuilderCallback Interface


IAMFilterGraphCallback::UnableToRender

The UnableToRender method is called by the Filter Graph Manager if it cannot find any combination of filters to render the specified pin.

Syntax

HRESULT UnableToRender(
  IPin *pPin
);

Parameters

pPin

Specifies the IPin interface of the pin that could not be rendered.

Return Values

If the return value is S_OK, this Filter Graph Manager attempts to render the pin again. For any other return value, including S_FALSE and other success codes, the Filter Graph Manager continues to build the graph as normal. Typically it will reject the current filter and attempt to use a different filter.

Remarks

The Filter Graph Manager holds a graph-wide critical section while it calls this method. Therefore, the callback method should avoid calling any methods on the Filter Graph Manager, or any methods on filters that might change the graph state (such as disconnecting pins). Doing so might cause a deadlock or other unexpected behaviors. However, it is safe to query the pin for an interface or check the pin's preferred media type. The main use for this method would be to register a new filter, such as a decoder.

This method uses the thiscall calling convention, rather than __stdcall.

See Also

  • IAMFilterGraphCallback Interface
  • Intelligent Connect


IAMFilterMiscFlags Interface

The IAMFilterMiscFlags interface indicates whether a filter is a source filter or a renderer. Source and renderer filters can implement this interface.

Applications do not use this interface. The Filter Graph Manager uses this interface to determine how many EC_COMPLETE events it will receive when playback completes.

In addition to the methods inherited from IUnknown, the IAMFilterMiscFlags interface exposes the following methods.

Method | Description
GetMiscFlags | Returns the filter's type, either source or renderer.


IAMFilterMiscFlags::GetMiscFlags

The GetMiscFlags method returns the filter's type, either source or renderer.

Syntax

ULONG GetMiscFlags(void);

Parameters

This method takes no parameters.

Return Values

This method returns a member of the _AM_FILTER_MISC_FLAGS enumeration.

See Also

  • Error and Success Codes
  • IAMFilterMiscFlags Interface


IAMGraphBuilderCallback Interface

The IAMGraphBuilderCallback interface provides a callback mechanism during graph building.

To use this interface, implement the interface in your application or client object. Query the Filter Graph Manager for the IObjectWithSite interface and call the IObjectWithSite::SetSite method with a pointer to your implementation of the interface. The Filter Graph Manager calls the methods on this interface while it builds the graph, which gives the client the opportunity to modify the graph-building process.

The primary use for this interface is to configure the Video Mixing Renderer filter before it is connected. You can also use it reject a specific filter during graph building, such as a decoder filter.

In addition to the methods inherited from IUnknown, the IAMGraphBuilderCallback interface exposes the following methods.

Method | Description
SelectedFilter | Called when the Filter Graph Manager finds a candidate filter, but before it creates the filter.
CreatedFilter | Called after the Filter Graph Manager creates a filter, but before it tries to connect the filter.

See Also

  • IAMFilterGraphCallback Interface


IAMGraphBuilderCallback::SelectedFilter

The Filter Graph Manager calls this method when it finds a candidate filter for the graph, but before it creates the filter.

Syntax

HRESULT SelectedFilter(
  IMoniker *pMon
);

Parameters

pMon

Pointer to a moniker that contains information about the filter.

Return Values

If the method returns a success code, the Filter Graph Manager creates the filter and tries to connect it. If the method returns a failure code, the Filter Graph Manager rejects the filter.

Remarks

This method enables the client to examine a filter to determine whether it is acceptable for the current filter graph.

The Filter Graph Manager holds a graph-wide critical section while it calls this method. Therefore, the callback method should avoid calling any methods on the Filter Graph Manager, or any methods on filters that might change the graph state (such as disconnecting pins). Doing so might cause a deadlock or other unexpected behaviors.

See Also

  • IAMGraphBuilderCallback Interface


IAMGraphBuilderCallback::CreatedFilter

The Filter Graph Manager calls this method after it has created a filter, but before it attempts to connect the filter.

Syntax

HRESULT CreatedFilter(
  IBaseFilter *pFil
);

Parameters

pFil

Pointer to the IBaseFilter interface of the filter.

Return Values

If the method returns a success code, the Filter Graph Manager tries to connect the filter. If the method returns a failure code, the Filter Graph Manager rejects the filter.

Remarks

This method enables the client to configure the filter immediately after it has been created. The Video Mixing Renderer is the primary example of a filter that requires configuration before it is connected. Most other DirectShow filters can be configured after they are connected.

The Filter Graph Manager holds a graph-wide critical section while it calls this method. Therefore, the callback method should avoid calling any methods on the Filter Graph Manager, or any methods on filters that might change the graph state (such as disconnecting pins). Doing so might cause a deadlock or other unexpected behaviors.

See Also

  • IAMGraphBuilderCallback Interface


IAMGraphStreams Interface

This interface provides methods for controlling a filter graph that renders a live source. A live source is one that streams data in real time, such as a capture device or a network broadcast. The Filter Graph Manager implements this interface.

Applications can use this interface to specify how the graph handles latency and synchronization when it renders a live source. For more information, see Live Sources.

In addition to the methods inherited from IUnknown, the IAMGraphStreams interface exposes the following methods.

Method | Description
FindUpstreamInterface | Searches the filter graph for a specified interface, upstream from a specified pin.
SyncUsingStreamOffset | Enables or disables synchronization using time-stamp offsets.
SetMaxGraphLatency | Sets the maximum latency for the graph.


IAMGraphStreams::FindUpstreamInterface

The FindUpstreamInterface method searches the filter graph for a specified interface, upstream from a specified pin.

Syntax

HRESULT FindUpstreamInterface(
  IPin *pPin,
  REFIID riid,
  void **ppvInterface,
  DWORD dwFlags
);

Parameters

pPin

[in] Pointer to the IPin interface of a pin. The pin must belong to a filter in the filter graph.

riid

[in] Reference to an interface identifier (IID) that specifies the interface to find.

ppvInterface

[out] Address of a void pointer. If the method succeeds, this variable receives a pointer to the interface specified by riid.

dwFlags

[in] Combination of flags from the AM_INTF_SEARCH_FLAGS enumeration, specifying what to search (pins or filters).

Return Values

Returns one of the following HRESULT values.

Return code | Description
E_NOINTERFACE | Interface not found.
E_POINTER | Invalid pointer.
S_OK | Success.

Remarks

If dwFlags is zero, this method searches for the interface in the following order:

  1. It queries the pin specified by pPin.
  2. If pPin is an input pin, it calls FindUpstreamInterface recursively on the output pin that is connected to pPin, if any.

    If pPin is an output pin, it queries the filter that owns pPin. Then it creates a list of input pins on the filter that have internal connections to pPin, and calls FindUpstreamInterface recursively on those input pins.

    To create a list of input pins with internal connections, the method does the following:

    • Calls IPin::QueryInternalConnections.
    • If that fails, calls IBaseFilter::EnumPins and looks for input pins.

It stops at the first object it finds that supports the interface. You can limit the objects that are searched (filters, input pin, or output pins) by setting dwFlags to a non-zero value.

Note The ICaptureGraphBuilder2::FindInterface method implements a more general approach to this problem, and in most situations is preferred.

See Also

  • Error and Success Codes
  • IAMGraphStreams Interface


IAMGraphStreams::SetMaxGraphLatency

The SetMaxGraphLatency method sets the maximum latency for the graph. You must call the IAMGraphStreams::SyncUsingStreamOffset method before calling this method.

Syntax

HRESULT SetMaxGraphLatency(
  REFERENCE_TIME rtMaxGraphLatency
);

Parameters

rtMaxGraphLatency

[in] Specifies the maximum latency in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure
S_OK | Success

Remarks

At connection time, some live source filters use the maximum latency to determine the size of buffer to allocate. Calling this method before constructing the graph can help to ensure that sufficient buffers are allocated for the expected latency.

If you call this method beforing calling SyncUsingStreamOffset, the method returns E_FAIL.

See Also

  • Error and Success Codes
  • IAMGraphStreams Interface


IAMGraphStreams::SyncUsingStreamOffset

The SyncUsingStreamOffset method enables or disables synchronization using time-stamp offsets.

Syntax

HRESULT SyncUsingStreamOffset(
  BOOL bUseStreamOffset
);

Parameters

bUseStreamOffset

[in] Boolean value indicating whether to use a time-stamp offset. If TRUE, live sources will use a time-stamp offset to synchronize streams.

Return Values

Returns S_OK if successsful, or an error code otherwise.

Remarks

By default, the filter graph does not attempt to synchronize live streams by means of time-stamp offsets. Call this method with a value of TRUE if you want the filter graph to determine the maximum latency in the graph and adjust time stamps accordingly. For more information, see IAMPushSource::SetStreamOffset.

See Also

  • Error and Success Codes
  • IAMGraphStreams Interface


IAMLatency Interface

The IAMLatency interface provides a method for a filter to report the amount of latency that it introduces into the graph. Latency is defined as the time that it takes the filter to process a sample. For a source filter, latency is the filter's maximum buffer size, measured in time. For example, a video capture filter that buffers one frame at 30 frames per second introduces a latency of about 33 milliseconds.

Currently, there is no support for using this interface by itself. A source filter that streams live or real-time data should implement the IAMPushSource interface, which inherits from this interface.

In addition to the methods inherited from IUnknown, the IAMLatency interface exposes the following method.

Method | Description
GetLatency | Retrieves the expected latency associated with this filter.


IAMLatency::GetLatency

The GetLatency method retrieves the expected latency associated with this filter.

Syntax

HRESULT GetLatency(
  REFERENCE_TIME *prtLatency
);

Parameters

prtLatency

[in] Pointer to a variable that receives the latency in 100-nanosecond units.

Return Values

Returns S_OK if successsful, or an error code otherwise.

See Also

  • Error and Success Codes
  • IAMLatency Interface


IAMLine21Decoder Interface

The IAMLine21Decoder interface provides access to closed-captioned information and settings. The Line 21 Decoder filter exposes this interface. Applications can use this interface to enable or disable closed captions, select the closed captioning service, and set other closed captioning properties.

Closed-captioned information is transmitted on line 21 of field 1 in the vertical blanking interval (VBI) of television signals. Video cassette recorders record this information on video tape, and you can use the Line21 Decoder and other Microsoft® DirectShow® filters to capture the line 21 data and save it on disk in a media file format such as Audio-Video Interleaved (AVI). The closed-captioned information appears as a separate stream within the media file.

Closed-captioned text is used in television programming and DVD movies. DVD movies contain line 21 data as part of the user data section of each Group of Pictures (GOP) in the video stream. Television receiver cards with Windows Driver Model (WDM) drivers provide line 21 data.

Requirements

Requires Il21dec.h.

In addition to the methods inherited from IUnknown, the IAMLine21Decoder interface exposes the following methods.

Method | Description
GetBackgroundColor | Retrieves the background color used by the Line 21 Decoder filter for overlay.
GetCurrentService | Retrieves the current closed captioning service.
GetDecoderLevel | Retrieves the closed-captioned decoder level.
GetDrawBackgroundMode | Indicates whether the filter draws the captions on a transparent background or an opaque background.
GetOutputFormat | Retrieves the Line 21 Decoder filter's output format.
GetRedrawAlways | Indicates whether the filter redraws the entire output bitmap for each sample.
GetServiceState | Indicates whether closed captioning is on or off.
SetBackgroundColor | Sets the background color that the filter uses for overlay.
SetCurrentService | Sets the closed captioning service.
SetDrawBackgroundMode | Specifies whether the filter draws the captions on a transparent background or an opaque background.
SetOutputFormat | Sets the filter's output format. (Not implemented)
SetRedrawAlways | Specifies whether the filter redraws the entire output bitmap for each sample.
SetServiceState | Enables or disables closed captions.


IAMLine21Decoder::GetBackgroundColor

The GetBackgroundColor method retrieves the background color used by the Line 21 Decoder filter for overlay. The default background color is magenta.

Syntax

HRESULT GetBackgroundColor(
  DWORD *pdwPhysColor
);

Parameters

pdwPhysColor

Pointer to a variable that receives the background color as a pixel color value. The meaning of the pixel value is defined by the bit depth of the filter's current output format.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::SetBackgroundColor


IAMLine21Decoder::GetCurrentService

The GetCurrentService method retrieves the current closed captioning service.

Syntax

HRESULT GetCurrentService(
  AM_LINE21_CCSERVICE *lpService
);

Parameters

lpService

Pointer to a variable that receives a member of the AM_LINE21_CCSERVICE enumeration. The default service is CC1.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::SetCurrentService


IAMLine21Decoder::GetDecoderLevel

The GetDecoderLevel method retrieves the closed-captioned decoder level.

Syntax

HRESULT GetDecoderLevel(
  AM_LINE21_CCLEVEL *lpLevel
);

Parameters

lpLevel

Pointer to a variable that receives a member of the AM_LINE21_CCLEVEL enumeration. The retruend value is always AM_L21_CCLEVEL_TC2 (TeleCaption II).

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

TeleCaption I and TeleCaption II are standards for closed caption decoders. The Line 21 Decoder filter supports TeleCaption II, which is backward compatible with TeleCaption I.

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface


IAMLine21Decoder::GetDrawBackgroundMode

The GetDrawBackgroundMode method indicates whether the Line 21 Decoder filter draws the captions on a transparent background or an opaque background. By default, the caption background is opaque.

Syntax

HRESULT GetDrawBackgroundMode(
  AM_LINE21_DRAWBGMODE *lpMode
);

Parameters

lpMode

Pointer a variable that receives a member of the AM_LINE21_DRAWBGMODE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::SetDrawBackgroundMode


IAMLine21Decoder::GetOutputFormat

The GetOutputFormat method retrieves the Line 21 Decoder filter's output format.

Syntax

HRESULT GetOutputFormat(
  LPBITMAPINFOHEADER lpbmih
);

Parameters

lpbmih

Pointer to a caller-allocated BITMAPINFOHEADER structure.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success
S_FALSE | The output format has not been set.

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface


IAMLine21Decoder::GetRedrawAlways

The GetRedrawAlways method indicates whether the Line 21 Decoder filter redraws the entire output bitmap for each sample.

Syntax

HRESULT GetRedrawAlways(
  LPBOOL lpbOption
);

Parameters

lpbOption

Pointer to a variable that receives one of the following values.

Value | Description
TRUE | The filter always redraws the entire bitmap.
FALSE | The filter does not always redraw the entire bitmap. (Default)

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::SetRedrawAlways


IAMLine21Decoder::GetServiceState

The GetServiceState method indicates whether closed captioning is on or off.

Syntax

HRESULT GetServiceState(
  AM_LINE21_CCSTATE *lpState
);

Parameters

lpState

Pointer to a variable that receives a member of the AM_LINE21_CCSTATE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

By default, the Line 21 Decoder enables closed captioning.

See Also

  • Error and Success Codes
  • IAMLine21Decoder::SetServiceState


IAMLine21Decoder::SetBackgroundColor

The SetBackgroundColor method sets the background color that the Line 21 Decoder filter uses for overlay. The default background color is magenta.

Generally, applications should not call this method. The background color must match the overlay color key, which is defined by the downstream rendering filter.

Syntax

HRESULT SetBackgroundColor(
  DWORD dwPhysColor
);

Parameters

dwPhysColor

Sets the background color as a pixel color value. The meaning of the pixel value is defined by the bit depth of the filter's current output format.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::GetBackgroundColor


IAMLine21Decoder::SetCurrentService

The SetCurrentService method sets the closed captioning service.

Syntax

HRESULT SetCurrentService(
  AM_LINE21_CCSERVICE Service
);

Parameters

Service

Member of the AM_LINE21_CCSERVICE enumeration that specifies the closed captioning service. The default service is CC1.

Return Values

Value | Description
E_INVALIDARG | Invalid argument
E_NOTIMPL | The requested service is not implemented.
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::GetCurrentService


IAMLine21Decoder::SetDrawBackgroundMode

The SetDrawBackgroundMode method specifies whether the Line 21 Decoder filter draws the captions on a transparent background or an opaque background. By default, the caption background is opaque.

Syntax

HRESULT SetDrawBackgroundMode(
  AM_LINE21_DRAWBGMODE Mode
);

Parameters

Mode

Specifies a member of the AM_LINE21_DRAWBGMODE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder::GetDrawBackgroundMode


IAMLine21Decoder::SetOutputFormat

The SetOutputFormat method sets the Line 21 Decoder filter's output format.

This method is currently not implemented.

Syntax

HRESULT SetOutputFormat(
  LPBITMAPINFO lpbmi
);

Parameters

lpbmi

Pointer to a BITMAPINFO structure that describes the output format.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::GetOutputFormat


IAMLine21Decoder::SetRedrawAlways

The SetRedrawAlways method specifies whether the Line 21 Decoder filter redraws the entire output bitmap for each sample.

Syntax

HRESULT SetRedrawAlways(
  BOOL bOption
);

Parameters

bOption

Specifies one of the following values.

Value | Description
TRUE | The filter always redraws the entire bitmap.
FALSE | The filter does not always redraw the entire bitmap. (Default)

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

Generally, applications should not call this method. The downstream mixer or renderer filter should call this method with the value TRUE if it writes into the buffers that it receives from the Line 21 Decoder filter. Redrawing degrades performance and increases CPU load, because it negates any potential optimizations.

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::GetRedrawAlways


IAMLine21Decoder::SetServiceState

The SetServiceState method enables or disables closed captions.

Syntax

HRESULT SetServiceState(
  AM_LINE21_CCSTATE State
);

Parameters

State

Member of the AM_LINE21_CCSTATE enumeration, specify whether to enable or disable closed captions.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IAMLine21Decoder Interface
  • IAMLine21Decoder::GetServiceState


IAMMediaContent Interface

The IAMMediaContent interface provides methods for retrieving metadata from a stream. Applications can use this interface to retrieve information encoded into a stream, such as the author, title, and copyright. This interface is typically exposed by parser filters, such as the AVI Splitter filter and the MPEG-1 Stream Splitter filter.

Depending on the stream type, a filter might support a subset of the methods on this interface. For example, the AVI Splitter retrieves the copyright, author name, and title from INFO chunks in the AVI file. The remaining methods return E_NOTIMPL.

Note Microsoft® Windows Media™ Player does not use this interface to display metadata.

exposes the following methods.

Method | Description
get_AuthorName | Retrieves the author name.
get_Title | Retrieves the title.
get_Rating | Retrieves the rating.
get_Description | Retrieves a description of the content.
get_Copyright | Retrieves copyright information.
get_BaseURL | Retrieves a base URL for the related Web content.
get_LogoURL | Retrieves a URL for the logo.
get_LogoIconURL | Retrieves a URL for the logo icon.
get_WatermarkURL | Retrieves a URL for the watermark.
get_MoreInfoURL | Retrieves a URL for additional information about the content.
get_MoreInfoBannerImage | Retrieves an image for a related-information banner.
get_MoreInfoBannerURL | Retrieves a URL for a related-information banner.
get_MoreInfoText | Retrieves additional information as text.

Requirements

Requires Qnetwork.h. To define the interface identifier, include Initguid.h before Qnetwork.h, but after Dshow.h:

#include <dshow.h>
#include <initguid.h>
#include <qnetwork.h>

Note Make sure that Initguid.h is included only once in your project.


IAMMediaContent::get_AuthorName

The get_AuthorName method retrieves the author name.

Syntax

HRESULT get_AuthorName(
  BSTR *pbstrAuthorName
);

Parameters

pbstrAuthorName

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_BaseURL

The get_BaseURL method retrieves a base URL for the related Web content.

Syntax

HRESULT get_BaseURL(
  BSTR *pbstrBaseURL
);

Parameters

pbstrBaseURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_Copyright

The get_Copyright method retrieves copyright information.

Syntax

HRESULT get_Copyright(
  BSTR *pbstrCopyright
);

Parameters

pbstrCopyright

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_Description

The get_Description method retrieves a description of the content.

Syntax

HRESULT get_Description(
  BSTR *pbstrDescription
);

Parameters

pbstrDescription

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_LogoIconURL

The get_LogoIconURL method retrieves a URL for the logo icon.

Syntax

HRESULT get_LogoIconURL(
  BSTR *pbstrLogoURL
);

Parameters

pbstrLogoURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_LogoURL

The get_LogoURL method retrieves a URL for the logo.

Syntax

HRESULT get_LogoURL(
  BSTR *pbstrLogoURL
);

Parameters

pbstrLogoURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_MoreInfoBannerImage

The get_MoreInfoBannerImage method retrieves an image for a related-information banner.

Syntax

HRESULT get_MoreInfoBannerImage(
  BSTR *pbstrMoreInfoBannerImage
);

Parameters

pbstrMoreInfoBannerImage

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_MoreInfoBannerURL

The get_MoreInfoBannerURL method retrieves a URL for a related-information banner.

Syntax

HRESULT get_MoreInfoBannerURL(
  BSTR *pbstrMoreInfoBannerURL
);

Parameters

pbstrMoreInfoBannerURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_MoreInfoText

The get_MoreInfoText method retrieves additional information as text.

Syntax

HRESULT get_MoreInfoText(
  BSTR *pbstrMoreInfoText
);

Parameters

pbstrMoreInfoText

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_MoreInfoURL

The get_MoreInfoURL method retrieves a URL for additional information about the content.

Syntax

HRESULT get_MoreInfoURL(
  BSTR *pbstrMoreInfoURL
);

Parameters

pbstrMoreInfoURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_Rating

The get_Rating method retrieves the rating.

Syntax

HRESULT get_Rating(
  BSTR *pbstrRating
);

Parameters

pbstrRating

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_Title

The get_Title method retrieves the title.

Syntax

HRESULT get_Title(
  BSTR *pbstrTitle
);

Parameters

pbstrTitle

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent::get_WatermarkURL

The get_WatermarkURL method retrieves a URL for the watermark.

Syntax

HRESULT get_WatermarkURL(
  BSTR *pbstrWatermarkURL
);

Parameters

pbstrWatermarkURL

Pointer to a variable that receives a BSTR with the information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMMediaContent Interface


IAMMediaContent2 Interface

The IAMMediaContent2 interface is used to retrieve custom parameters and playlists from ASX files.

In addition to the methods inherited from IDispatch, the IAMMediaContent2 interface exposes the following methods.

Method | Description
get_MediaParameter | Retrieves the value of a custom parameter.
get_MediaParameterName | Retrieves the name of a custom parameter.
get_PlaylistCount | Retrieves the number of playlist entries.

Requirements

Requires Qnetwork.h. To define the interface identifier, include Initguid.h before Qnetwork.h, but after Dshow.h:

#include <dshow.h>
#include <initguid.h>
#include <qnetwork.h>

Note Make sure that Initguid.h is included only once in your project.


IAMMediaContent2::get_MediaParameter

The get_MediaParameter method retrieves the value of a custom parameter in the ASX file.

Syntax

HRESULT get_MediaParameter(
  long  EntryNum,
  BSTR  bstrName,
  BSTR *pbstrValue
);

Parameters

EntryNum

Specifies the location of the parameter in the ASX file.

Value | Description
0 | The parameter is a direct child of the ASX node.
> 0 | The parameter is located inside an ENTRY tag; EntryNum specifies the entry, indexed from 1.

bstrName

Specifies the name of the parameter.

pbstrValue

Pointer to a variable that receives the value of the parameter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the BSTR returned in pbstrValue, by calling SysFreeString.

See Also

  • IAMMediaContent2 Interface


IAMMediaContent2::get_MediaParameterName

The get_MediaParameterName method retrieves the name of a custom parameter in an ASX file.

Syntax

HRESULT get_MediaParameterName(
  long  EntryNum,
  long  Index,
  BSTR *pbstrName
);

Parameters

EntryNum

Specifies the location of the parameter in the ASX file.

Value | Description
0 | The parameter is a direct child of the ASX node.
> 0 | The parameter is located inside an ENTRY tag; EntryNum specifies the entry, indexed from 1.

Index

Specifies the index of the parameter to retrieve, indexed from 1.

pbstrName

Pointer to a variable that receives the parameter name.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IAMMediaContent2 Interface


IAMMediaContent2::get_PlaylistCount

The get_PlaylistCount method retrieves the number of entries in an ASX file.

Syntax

HRESULT get_PlaylistCount(
  long FAR*  pNumberEntries
);

Parameters

pNumberEntries

Pointer to a variable that receives the number of entries.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMMediaContent2 Interface


IAMNetShowConfig Interface

The IAMNetShowConfig interface contains methods for configuring the Windows Media Source filter.

In addition to the methods inherited from IDispatch, the IAMNetShowConfig interface exposes the following methods.

Method | Description
get_BufferingTime | Retrieves the buffering time.
get_EnableAutoProxy | Queries whether the control or filter should use the browser's proxy settings.
get_EnableHTTP | Queries whether HTTP-type streaming is enabled.
get_EnableMulticast | Queries whether multicast-type streaming is enabled.
get_EnableTCP | Queries whether TCP-based streaming is enabled.
get_EnableUDP | Queries whether UDP-based streaming is enabled.
get_FixedUDPPort | Retrieves the fixed UDP port number.
get_HTTPProxyHost | Retrieves the HTTP address of the proxy host.
get_HTTPProxyPort | Retrieves the HTTP proxy port.
get_UseFixedUDPPort | Queries whether the filter should use the fixed UDP port.
get_UseHTTPProxy | Queries whether the filter should use the HTTP proxy server.
put_BufferingTime | Specifies the buffering time.
put_EnableAutoProxy | Specifies whether the control or filter should use the browser's proxy settings.
put_EnableHTTP | Enables or disables HTTP-based streaming.
put_EnableMulticast | Enables or disables multicast-based streaming.
put_EnableTCP | Enables or disables TCP-based streaming.
put_EnableUDP | Enables or disables UDP-based streaming.
put_FixedUDPPort | Specifies the fixed UDP port number.
put_HTTPProxyHost | Specifies the address of the HTTP proxy server.
put_HTTPProxyPort | Specifies the port for the HTTP proxy server.
put_UseFixedUDPPort | Specifies whether to use a fixed UDP port number.
put_UseHTTPProxy | Specifies whether to use an HTTP proxy server.


IAMNetShowConfig::get_BufferingTime

The get_BufferingTime method retrieves the buffering time.

Syntax

HRESULT get_BufferingTime(
  double *pBufferingTime
);

Parameters

pBufferingTime

Pointer that receives the buffering time, in seconds.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::get_EnableAutoProxy

The get_EnableAutoProxy method queries whether the control or filter should use the browser's proxy settings.

Syntax

HRESULT get_EnableAutoProxy(
  VARIANT_BOOL *pEnableAutoProxy
);

Parameters

pEnableAutoProxy

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

This flag is TRUE by default.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::get_EnableHTTP

The get_EnableHTTP method queries whether HTTP-type streaming is enabled.

Syntax

HRESULT get_EnableHTTP(
  VARIANT_BOOL *pEnableHTTP
);

Parameters

pEnableHTTP

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::get_EnableMulticast

The get_EnableMulticast method queries whether multicast-type streaming is enabled.

Syntax

HRESULT get_EnableMulticast(
  VARIANT_BOOL *pEnableMulticast
);

Parameters

pEnableMulticast

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::get_EnableTCP

The get_EnableTCP method queries whether TCP-based streaming is enabled.

Syntax

HRESULT get_EnableTCP(
  VARIANT_BOOL *pEnableTCP
);

Parameters

pEnableTCP

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

None.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_EnableUDP


IAMNetShowConfig::get_EnableUDP

The get_EnableUDP method queries whether UDP-based streaming is enabled.

Syntax

HRESULT get_EnableUDP(
  VARIANT_BOOL *pEnableUDP
);

Parameters

pEnableUDP

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_EnableTCP


IAMNetShowConfig::get_FixedUDPPort

The get_FixedUDPPort method gets the fixed UDP port number.

Syntax

HRESULT get_FixedUDPPort(
  long *pFixedUDPPort
);

Parameters

pFixedUDPPort

Pointer to a variable that receives the fixed UDP port number.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_UseFixedUDPPort


IAMNetShowConfig::get_HTTPProxyHost

The get_HTTPProxyHost method retrieves the HTTP address of the proxy host.

Syntax

HRESULT get_HTTPProxyHost(
  BSTR *pbstrHTTPProxyHost
);

Parameters

pbstrHTTPProxyHost

Pointer to a variable that receives the HTTP address.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_HTTPProxyPort


IAMNetShowConfig::get_HTTPProxyPort

The get_HTTPProxyPort method retrieves the HTTP proxy port.

Syntax

HRESULT get_HTTPProxyPort(
  long *pHTTPProxyPort
);

Parameters

pHTTPProxyPort

Pointer to a variable that receives the port number.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_HTTPProxyHost


IAMNetShowConfig::get_UseFixedUDPPort

The get_UseFixedUDPPort method queries whether the filter should use the fixed UDP port.

Syntax

HRESULT get_UseFixedUDPPort(
  VARIANT_BOOL *pUseFixedUDPPort
);

Parameters

pUseFixedUDPPort

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::get_FixedUDPPort


IAMNetShowConfig::get_UseHTTPProxy

The get_UseHTTPProxy method queries whether the filter should use the HTTP proxy server.

Syntax

HRESULT get_UseHTTPProxy(
  VARIANT_BOOL *pUseHTTPProxy
);

Parameters

pUseHTTPProxy

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::put_BufferingTime

The put_BufferingTime method specifies the buffering time.

Syntax

HRESULT put_BufferingTime(
  double  BufferingTime
);

Parameters

BufferingTime

Specifies the buffering time, in seconds.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::put_EnableAutoProxy

The put_EnableAutoProxy method enables or disables auto-proxy.

Syntax

HRESULT put_EnableAutoProxy(
  VARIANT_BOOL  EnableAutoProxy
);

Parameters

EnableAutoProxy

Specify one of the following values.

Value | Description
VARIANT_TRUE | Enable auto-proxy.
VARIANT_FALSE | Disable auto-proxy.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::put_EnableHTTP

The put_EnableHTTP method enables or disables HTTP-based streaming.

Syntax

HRESULT put_EnableHTTP(
  VARIANT_BOOL  EnableHTTP
);

Parameters

EnableHTTP

Specify one of the following values.

Value | Description
VARIANT_TRUE | Enable HTTP-based streaming.
VARIANT_FALSE | Disable HTTP-based streaming.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::put_EnableMulticast

The put_EnableMulticast method enables or disables multicast-based streaming.

Syntax

HRESULT put_EnableMulticast(
  VARIANT_BOOL  EnableMulticast
);

Parameters

EnableMulticast

Specify one of the following values.

Value | Description
VARIANT_TRUE | Enable multicast-based streaming.
VARIANT_FALSE | Disable multicast-based streaming.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowConfig::put_EnableTCP

The put_EnableTCP method enables or disables TCP-based streaming.

Syntax

HRESULT put_EnableTCP(
  VARIANT_BOOL  EnableTCP
);

Parameters

EnableTCP

Specify one of the following values.

Value | Description
VARIANT_TRUE | Enable TCP-based streaming.
VARIANT_FALSE | Disable TCP-based streaming.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_EnableUDP


IAMNetShowConfig::put_EnableUDP

The put_EnableUDP method enables or disablles UDP-based streaming.

Syntax

HRESULT put_EnableUDP(
  VARIANT_BOOL  EnableUDP
);

Parameters

EnableUDP

Specify one of the following values.

Value | Description
VARIANT_TRUE | Enable UDP-based streaming.
VARIANT_FALSE | Disable UDP-based streaming.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_EnableTCP


IAMNetShowConfig::put_FixedUDPPort

The put_FixedUDPPort method specifies the fixed UDP port.

Syntax

HRESULT put_FixedUDPPort(
  long  FixedUDPPort
);

Parameters

FixedUDPPort

Specifies the fixed UDP port number.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_UseFixedUDPPort


IAMNetShowConfig::put_HTTPProxyHost

The put_HTTPProxyHost method specifies the address of the HTTP proxy server.

Syntax

HRESULT put_HTTPProxyHost(
  BSTR  bstrHTTPProxyHost
);

Parameters

bstrHTTPProxyHost

Specifies the proxy's address.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_HTTPProxyPort


IAMNetShowConfig::put_HTTPProxyPort

The put_HTTPProxyPort method specifies the port for the HTTP proxy server.

Syntax

HRESULT put_HTTPProxyPort(
  long  HTTPProxyPort
);

Parameters

HTTPProxyPort

Specifies the HTTP proxy port.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_HTTPProxyHost


IAMNetShowConfig::put_UseFixedUDPPort

The put_UseFixedUDPPort method specifies whether to use a fixed UDP port number.

Syntax

HRESULT put_UseFixedUDPPort(
  VARIANT_BOOL  UseFixedUDPPort
);

Parameters

UseFixedUDPPort

Specify one of the following values.

Value | Description
VARIANT_TRUE | Use a fixed UDP port.
VARIANT_FALSE | Use a dynamic UDP port.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface
  • IAMNetShowConfig::put_FixedUDPPort


IAMNetShowConfig::put_UseHTTPProxy

The put_UseHTTPProxy method specifies whether to use an HTTP proxy server.

Syntax

HRESULT put_UseHTTPProxy(
  VARIANT_BOOL  UseHTTPProxy
);

Parameters

UseHTTPProxy

Specify one of the following values.

Value | Description
VARIANT_TRUE | Use an HTTP proxy server.
VARIANT_FALSE | Do not use an HTTP proxy server.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowConfig Interface


IAMNetShowExProps Interface

The IAMNetShowExProps interface contains methods to configure the Windows Media Source filter.

In addition to the methods inherited from IDispatch, the IAMNetShowExProps interface exposes the following methods.

Method | Description
get_Bandwidth | Retrieves the bandwidth.
get_CodecCount | Retrieves the number codecs needed to play the file.
get_CreationDate | Retrieves the creation date.
get_ErrorCorrection | Retrieves the error correction method.
get_SourceLink | Retrieves the source link.
get_SourceProtocol | Retrieves the source protocol.
GetCodecDescription | Retrieves the user-friendly description of a codec.
GetCodecInstalled | Queries whether a specified codec is installed on the local system.
GetCodecURL | Retrieves the URL from which the codec may be downloaded.


IAMNetShowExProps::get_Bandwidth

The get_Bandwidth method retrieves the bandwidth.

Syntax

HRESULT get_Bandwidth(
  long *pBandwidth
);

Parameters

pBandwidth

Pointer to a variable that receives the bandwidth.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::get_CodecCount

The get_CodecCount method retrieves the number codecs needed to play the file.

Syntax

HRESULT get_CodecCount(
  long *pCodecCount
);

Parameters

pCodecCount

Pointer to a variable that receives the number of codecs.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::get_CreationDate

The get_CreationDate method retrieves the creation date of the source file.

Syntax

HRESULT get_CreationDate(
  DATE *pCreationDate
);

Parameters

pCreationDate

Pointer to a variable that receives the date.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::get_ErrorCorrection

The get_ErrorCorrection method retrieves the current error correction method.

Syntax

HRESULT get_ErrorCorrection(
  BSTR *pbstrErrorCorrection
);

Parameters

pbstrErrorCorrection

Pointer to a variable that receives a string describing the error correction method.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::get_SourceLink

The get_SourceLink method retrieves the source link.

Syntax

HRESULT get_SourceLink(
  BSTR *pbstrSourceLink
);

Parameters

pbstrSourceLink

Pointer to a variable that receives the source link.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::get_SourceProtocol

The get_SourceProtocol method retrieves the source protocol.

Syntax

HRESULT get_SourceProtocol(
  long *pSourceProtocol
);

Parameters

pSourceProtocol

Pointer to a variable that receives one of the following values.

Value | Description
0 | Unknown protocol
1 | Multicast
2 | Multisession bridge
3 | UDP
4 | TCP
5 | Media Streaming Broadcast Distribution (MSBD)
6 | HTTP
7 | File

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowExProps Interface


IAMNetShowExProps::GetCodecDescription

The GetCodecDescription method retrieves a user-friendly description of a specified codec.

Syntax

HRESULT GetCodecDescription(
  long  CodecNum,
  BSTR *pbstrCodecDescription
);

Parameters

CodecNum

Specifies the codec to query, indexed from zero. Call get_CodecCount to obtain the number of codecs.

pbstrCodecDescription

Pointer to a variable that receives the description.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IAMNetShowExProps Interface
  • IAMNetShowExProps::get_CodecCount


IAMNetShowExProps::GetCodecInstalled

The GetCodecInstalled method queries whether a specified codec is installed on the local system.

Syntax

HRESULT GetCodecInstalled(
  long  CodecNum,
  VARIANT_BOOL *pCodecInstalled
);

Parameters

CodecNum

Specifies the codec to query, indexed from zero. Call get_CodecCount to obtain the number of codecs.

pCodecInstalled

Pointer that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowExProps Interface
  • IAMNetShowExProps::get_CodecCount


IAMNetShowExProps::GetCodecURL

The GetCodecURL method retrieves the URL where the codec may be downloaded.

Syntax

HRESULT GetCodecURL(
  long  CodecNum,
  BSTR FAR*  pbstrCodecURL
);

Parameters

CodecNum

Specifies the codec to query, indexed from zero. Call get_CodecCount to obtain the number of codecs.

pbstrCodecURL

Pointer that receives the URL.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IAMNetShowExProps Interface
  • IAMNetShowExProps::get_CodecCount


IAMNetShowPreroll Interface

The IAMNetShowPreroll interface enables clients to retrieve and modify the preroll settings on the Windows Media Source filter. The default preroll time is five seconds.

In addition to the methods inherited from IDispatch, the IAMNetShowPreroll interface exposes the following methods.

Method | Description
get_Preroll | Queries whether the filter is currently prerolling.
put_Preroll | Specifies whether the filter should start prerolling.


IAMNetShowPreroll::get_Preroll

The get_Preroll method queries whether the filter is currently prerolling.

Syntax

HRESULT get_Preroll(
  VARIANT_BOOL *pfPreroll
);

Parameters

pfPreroll

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowPreroll Interface


IAMNetShowPreroll::put_Preroll

The put_Preroll method specifies whether the filter should start prerolling.

Syntax

HRESULT put_Preroll(
  VARIANT_BOOL fPreroll
);

Parameters

fPreroll

Specifies one of the following values:

Value | Description
VARIANT_TRUE | Begin prerolling.
VARIANT_FALSE | Stop prerolling.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetShowPreroll Interface


IAMNetworkStatus Interface

The IAMNetworkStatus interface is exposed by the Windows Media Source filter. It enables clients to retrieve information about the quality of the network connection.

In addition to the methods inherited from IDispatch, the IAMNetworkStatus interface exposes the following methods.

Method | Description
get_BufferingCount | Retrieves the number of times the network source has buffered the data.
get_BufferingProgress | Retrieves the buffering progress.
get_IsBroadcast | Retrieves a value indicating whether the current clip is a broadcast clip.
get_LostPackets | Retrieves the number of lost packets.
get_ReceivedPackets | Retrieves the number of received packets.
get_ReceptionQuality | Retrieves a value indicating the reception quality.
get_RecoveredPackets | Retrieves the number of recovered packets.


IAMNetworkStatus::get_BufferingCount

The get_BufferingCount method retrieves the number of times the network source has buffered the data.

Syntax

HRESULT get_BufferingCount(
  long *pBufferingCount
);

Parameters

pBufferingCount

Pointer to a variable that receives the buffering count.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_BufferingProgress

The get_BufferingProgress method retrieves a value indicating the buffering progress.

Syntax

HRESULT get_BufferingProgress(
  long *pBufferingProgress
);

Parameters

pBufferingProgress

Pointer to a variable that receives a value from 0 to 100, indicating what percentage has completed.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_IsBroadcast

The get_IsBroadcast method retrieves a value indicating whether the current stream is a broadcast stream.

Syntax

HRESULT get_IsBroadcast(
  VARIANT_BOOL *pIsBroadcast
);

Parameters

pIsBroadcast

Pointer to a variable that receives a Boolean value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

A broadcast stream can be unicast or multicast. In a broadcast connection, the client is passive and does not control when the stream starts or stops. In an on-demand connection, the client is active and controls when the stream is started and stopped.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_LostPackets

The get_LostPackets method retrieves the number of packets that have been lost.

Syntax

HRESULT get_LostPackets(
  long *pLostPackets
);

Parameters

pLostPackets

Pointer to a variable that receives the number of lost packets.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

This property is only valid for streaming media, and will equal zero when using the HTTP protocol, which is lossless. Packets may be lost for a number of reasons, such as the type and quality of the network connection.

Whenever playback is stopped and restarted, this property is set to zero. It is not reset if playback is paused and restarted.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_ReceivedPackets

The get_ReceivedPackets method retrieves the number of packets that have been received.

Syntax

HRESULT get_ReceivedPackets(
  long *pReceivedPackets
);

Parameters

pReceivedPackets

Pointer to a variable that receives the number of received packets.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_ReceptionQuality

The get_ReceptionQuality method retrieves a value indicating the reception quality.

Syntax

HRESULT get_ReceptionQuality(
  long *pReceptionQuality
);

Parameters

pReceptionQuality

Pointer to a variable that receives a value from 0 to 100, indicating the reception quality. This value is percentage of packets that the filter received without requiring resending or error correction.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetworkStatus Interface


IAMNetworkStatus::get_RecoveredPackets

The get_RecoveredPackets method retrieves the number of recovered packets.

Syntax

HRESULT get_RecoveredPackets(
  long *pRecoveredPackets
);

Parameters

pRecoveredPackets

Pointer to a variable that receives the number of recovered packets.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • IAMNetworkStatus Interface


IAMOpenProgress Interface

The IAMOpenProgress interface provides methods that report the progress of a file-open operation and enable the application to cancel the operation.

Filters that open files over a network can expose this interface. An application can use it to query the progress of the download, or to cancel the download. If the network is not responsive, a method such as IGraphBuilder::RenderFile might block for an indefinite period. To prevent your application from blocking, create a worker thread that uses IAMOpenProgress to monitor the progress. The worker thread can cancel the operation if a predefined timeout occurs, or in response to a command from the user.

The File Source (URL) filter supports this interface.

In addition to the methods inherited from IUnknown, the IAMOpenProgress interface exposes the following methods.

Method | Description
QueryProgress | Retrieves the progress of the file-open operation.
AbortOperation | Cancels the file-open operation.


IAMOpenProgress::AbortOperation

The AbortOperation method cancels the file-open operation.

Syntax

HRESULT AbortOperation(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

See Also

  • Error and Success Codes
  • IAMOpenProgress Interface


IAMOpenProgress::QueryProgress

The QueryProgress method retrieves the progress of the file-open operation.

Syntax

HRESULT QueryProgress(
  LONGLONG *pllTotal,
  LONGLONG *pllCurrent
);

Parameters

pllTotal

[out] Pointer to a variable that receives the length of the entire file, in bytes.

pllCurrent

[out] Pointer to a variable that receives the length of the downloaded portion of the file, in bytes.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
VFW_S_ESTIMATED | The returned values are estimates.
E_UNEXPECTED | Unexpected error.

See Also

  • Error and Success Codes
  • IAMOpenProgress Interface


IAMOverlayFX Interface

The IAMOverlayFX interface is implemented on the Overlay Mixer filter. This interface enables applications to control how the video overlay appears on the user's screen.

In addition to the methods inherited from IUnknown, the IAMOverlayFX interface exposes the following methods.

Method | Description
QueryOverlayFXCaps | Retrieves information about which overlay effects are available to the Overlay Mixer filter.
SetOverlayFX | Applies the specified effects to the overlay surface.
GetOverlayFX | Retrieves the effects currently applied to the overlay surface, if any.


IAMOverlayFX::GetOverlayFX

The GetOverlayFX method retrieves the effects currently applied to the overlay surface, if any. The application can call this method while the filter graph is running.

Syntax

HRESULT GetOverlayFX(
  DWORD *lpdwOverlayFX
);

Parameters

lpdwOverlayFX

[out] Pointer a variable that receives a value indicating which effects, if any, are currently applied to the overlay surface. The value is a logical combination of flags from the AMOVERLAYFX enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns S_OK if successful, or E_POINTER to indicate a NULL pointer argument.

See Also

  • Error and Success Codes
  • IAMOverlayFX Interface


IAMOverlayFX::SetOverlayFX

The SetOverlayFX method applies the specified effects to the overlay surface.

Syntax

HRESULT SetOverlayFX(
  DWORD dwOverlayFX
);

Parameters

dwOverlayFX

[in] Value specifying which effects to apply. The value must be a logical combination of flags from the AMOVERLAYFX enumeration, or the method returns E_INVALIDARG.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation may return one of the following values, or others not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

The application must call this method while the filter graph is running. The effects are applied immediately.

See Also

  • Error and Success Codes
  • IAMOverlayFX Interface


IAMOverlayFX::QueryOverlayFXCaps

The QueryOverlayFXCaps method retrieves information about which overlay effects are available to the Overlay Mixer filter.

Syntax

HRESULT QueryOverlayFXCaps(
  DWORD *lpdwOverlayFXCaps
);

Parameters

lpdwOverlayFXCaps

[out] Pointer to a variable that receives a value indicating the overlay effects capabilities of the overlay surface. The value is a logical combination of flags from the AMOVERLAYFX enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns one of the following values.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMOverlayFX Interface


IAMParse Interface

The IAMParse interface is implemented on the MPEG-2 Splitter filter. The interface enables an application to query and set the parse time—a notional time associated with the current position in the stream of bytes supplied to the parser filter. This time is also tied to the origin of the time stamps in that time stamp zero corresponds to parse time zero.

Use this interface to retrieve or set the current stream parse time or to clear the data buffer of its current data.

Requirements

Requires Amparse.h.

In addition to the methods inherited from IUnknown, the IAMParse interface exposes the following methods.

Method | Description
Flush | Empties the current file buffer.
GetParseTime | Retrieves the current stream parse time.
SetParseTime | Sets the current stream parse time.


IAMParse::Flush

The Flush method clears the current file data to allow for a more rapid switch to a new file.

Syntax

HRESULT Flush(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

Although this method can make transitions much more immediate, it can also make them appear less seamless.

See Also

  • Error and Success Codes
  • IAMParse Interface


IAMParse::GetParseTime

The GetParseTime method retrieves the current stream parse time. For MPEG-2, this corresponds to the system clock time computed for the current stream position.

Syntax

HRESULT GetParseTime(
  REFERENCE_TIME *ptrParseTime
);

Parameters

ptrParseTime

[out] Pointer to the current parse time.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The parse time is not available, because the input pin is not connected

Remarks

The parse time for the MPEG-2 Splitter filter is the current stream position in system clock units. The initial value of the parse time is zero.

See Also

  • Error and Success Codes
  • IAMParse Interface


IAMParse::SetParseTime

The SetParseTime method sets the current stream parse time. For MPEG-2, this corresponds to the system clock time computed for the current stream position.

Syntax

HRESULT SetParseTime(
  REFERENCE_TIME rtPosition
);

Parameters

rtPosition

[in] Current stream parse time.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The parse time is not available, because the input pin is not connected

Remarks

The parse time for the MPEG-2 Splitter filter is the current stream position in system clock units. The initial value of the parse time is zero.

See Also

  • Error and Success Codes
  • IAMParse Interface


IAMPushSource Interface

The IAMPushSource interface provides methods for synchronizing a filter graph that renders a live source (that is, a source that streams data in real time, such as a capture device or a network broadcast). It inherits the IAMLatency interface.

Source filters that stream live data should expose this interface on their output pins.

Generally, applications should not call the methods on this interface; instead, use the IAMGraphStreams interface. The filter graph manager uses the methods on this interface to address two problems that commonly occur when rendering live sources:

  • Latency: When a filter graph includes more than one live source, the sources often have different latencies, which can cause them to be out of sync. For example, if audio capture has a longer latency time than video capture, the audio will lag behind the video unless the graph compensates for the difference.
  • Rate Matching: When a renderer filter is connected to a live source, it must adjust its data consumption rate to match the source filter's production rate. Otherwise, there might be gaps in the data (if the renderer runs faster than the source) or data might get dropped (if the source runs faster).

To correct for latency, the filter graph calls IAMLatency::GetLatency on each output pin that exposes the IAMPushSource interface, and determines the maximum latency in the graph. It then calls IAMPushSource::SetStreamOffset on any filters with less than the maximum latency, so that they will adjust the time stamps they generate by the correct offset.

To perform rate matching, the filter graph needs to determine whether the renderer filter can match clock rates with the source filter. The IAMPushSource::GetPushSourceFlags method returns a set of flags indicating whether it is safe for the renderer to match rates with the source.

These issues do not affect capturing to a file. The File Writer filter relies on time stamps on the incoming samples to write the file correctly; the streams are then synchronized during playback. As for rate matching, the data is always written to the file as fast as possible.

In addition to the methods inherited from IAMLatency, the IAMGraphStreams interface exposes the following methods.

Method | Description
GetMaxStreamOffset | Retrieves the maximum stream offset the filter can support.
GetPushSourceFlags | Retrieves a combination of flags describing the behavior of the filter.
GetStreamOffset | Retrieves the offset that the filter uses when generating time stamps.
SetMaxStreamOffset | Reference time specifying the maximum stream offset.
SetPushSourceFlags | Sets flags that specify the behavior of the filter.
SetStreamOffset | Sets the offset for time stamps generated by this filter.


IAMPushSource::GetMaxStreamOffset

The GetMaxStreamOffset method retrieves the maximum stream offset the filter can support.

Syntax

HRESULT GetMaxStreamOffset(
  REFERENCE_TIME *prtMaxOffset
);

Parameters

prtMaxOffset

[out] Pointer to a variable that receives a reference time indicating the maximum offset the filter can support.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns E_POINTER or S_OK.

Remarks

If the stream offset is set to a value larger than the maximum supported offset, the filter is not guaranteed to have a buffer large enough to hold data for the entire amount of the offset. Unless there is another buffer downstream, data might be lost.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMPushSource::GetPushSourceFlags

The GetPushSourceFlags method retrieves a combination of flags describing the behavior of the filter.

Syntax

HRESULT GetPushSourceFlags(
  ULONG *pFlags
);

Parameters

pFlags

[out] Pointer to a variable that receives a combination of flags from the AM_PUSHSOURCE_FLAGS enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Call this method to determine whether a renderer filter can safely match clock rates with this source filter.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMPushSource::GetStreamOffset

The GetStreamOffset method retrieves the offset that the filter uses when generating time stamps.

Syntax

HRESULT GetStreamOffset(
  REFERENCE_TIME *prtOffset
);

Parameters

prtOffset

[out] Pointer to a variable that receives a reference time indicating the current stream offset.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMPushSource::SetMaxStreamOffset

The SetMaxStreamOffset method specifies the stream offset that will be allowed in the filter graph.

Syntax

HRESULT SetMaxStreamOffset(
  REFERENCE_TIME rtMaxOffset
);

Parameters

rtMaxOffset

[in] Reference time specifying the maximum stream offset.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

If this method is called prior to connecting the filter, the filter can allocate an appropriately sized buffer.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMPushSource::SetPushSourceFlags

The SetPushSourceFlags method sets flags that specify the behavior of the filter. Currently, applications should not call this method, because request flags are not supported and an application should not override the flags set by the filter.

Syntax

HRESULT SetPushSourceFlags(
  ULONG Flags
);

Parameters

Flags

[in] Combination of flags from the AM_PUSHSOURCE_FLAGS enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMPushSource::SetStreamOffset

The SetStreamOffset method sets the offset for time stamps generated by this filter.

Syntax

HRESULT SetStreamOffset(
  REFERENCE_TIME rtOffset
);

Parameters

rtOffset

[in] New stream offset for the filter.

Return Values

Returns S_FALSE if the specified offset is larger than the filter's maximum preferred offset. Otherwise, returns S_OK if successful or an HRESULT value indicating the cause of the error.

Remarks

The filter graph calls this method to adjust a filter's stream offset, in order to synchronize streams with different latency values.

If the return value is S_FALSE, the filter might not support a buffer large enough for the requested offset. Unless there is another buffer downstream, data might be lost. To retrieve the filter's maximum preferred offset, call the IAMPushSource::GetMaxStreamOffset method.

See Also

  • Error and Success Codes
  • IAMPushSource Interface


IAMResourceControl Interface

The IAMResourceControl interface enables an application to open and hold an audio device resource before it's actually needed, so that playback can be guaranteed, or so that the application can learn in advance that a device is not available.

A filter can implement IAMResourceControl for use with a resource that might sometimes be unavailable. The Audio Capture, DirectSound Renderer, and the Audio Renderer (WaveOut) filters implement this interface.

In addition to the methods inherited from IUnknown, the IAMResourceControl interface exposes the following method.

Method | Description
Reserve | Reserves or unreserves a device resource.


IAMResourceControl::Reserve

The Reserve method reserves or unreserves a device resource.

Syntax

HRESULT Reserve(
  DWORD dwFlags,
  PVOID pvReserved
);

Parameters

dwFlags

[in] Flag indicating whether to reserve or unreserve this device. The value must be a member of the AMRESCTL_RESERVEFLAGS enumeration.

pvReserved

[in] Must be NULL.

Return Values

Returns S_OK if the device was successfully reserved or unreserved, S_FALSE if the device is currently reserved and will continue to be held, or an HRESULT error code if the device can't be reserved.

Remarks

A resource can be reserved multiple times. If the method returns S_OK, the filter increments an internal reserve count. For every call to reserve a device that returns S_OK, the caller must make a matching call to unreserve the device.

See Also

  • Error and Success Codes
  • IAMResourceControl Interface


IAMStats Interface

The IAMStats interface enables an application to retrieve performance data from the Filter Graph Manager. Filters can use this interface to record performance data.

Filter developers: As with all Filter Graph Manager interfaces, a filter must not hold a reference count on this interface, or it will cause a circular reference count. For more information, see IBaseFilter::JoinFilterGraph.

In addition to the methods inherited from IDispatch, the IAMStats interface exposes the following methods.

Method | Description
AddValue | Records a new value.
get_Count | Retrieves the number of values that were collected for a given statistic.
GetIndex | Retrieves the index for a named statistic, or creates a new statistic.
GetValueByIndex | Retrieves a statistic by index.
GetValueByName | Retrieves a statistic by name.
Reset | Resets all statistics to zero.

Remarks

Each statistic is defined by a name and an index. Use the GetIndex method to find the index from the name. Values are always double types. The following statistics are predefined.

Name | Description
RenderFile | Measures the time taken by each call to IGraphBuilder::RenderFile.
ConnectDirectInternal | Measures the time taken to connect two filters.
Build Mapper Cache | Measures the time taken to cache information about registered filters (used by the Filter Mapper object).
Process Category CategoryName | Measures the time taken to cache information about filters in a particular category, where CategoryName is the friendly name of the filter category. (See Filter Categories.)

For each of these statistics, the values represent time in milliseconds.


IAMStats::AddValue

The AddValue method records a new value.

Syntax

HRESULT AddValue(
  long lIndex
  double dValue
);

Parameters

lIndex

[in] Specifies the index of the statistic.

dValue

[in] Specifies the value to record.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Index out of range.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStats::get_Count

The get_Count method retrieves the number of values that were collected for a given statistic.

Syntax

HRESULT get_Count(
  LONG *plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the count.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStats::GetIndex

The GetIndex method retrieves the index for a named statistic, or creates a new statistic.

Syntax

HRESULT GetIndex(
  BSTR szName
  long lCreate
  long plIndex
);

Parameters

szName

[in] Specifies the name of the statistic.

lCreate

[in] Specifies whether to create the statistic, if it is not defined already. If the value is TRUE, the method creates a new index for the statistic when it cannot find an existing entry with that name. If the value is FALSE, the method fails when the statistic does not already exist.

plIndex

[out] Pointer to a variable that receives the index.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
HRESULT_FROM_WIN32(ERROR_NOT_FOUND) | No match for this name.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStats::GetValueByIndex

The GetValueByIndex method retrieves a statistic, by index.

Syntax

HRESULT GetValueByIndex(
  long lIndex
  BSTR *szName
  long *lCount
  double *dLast
  double *dAverage
  double *dStdDev
  double *dMin
  double *dMax
);

Parameters

lIndex

[in] Specifies the index of the statistic.

szName

[out] Pointer to a variable that receives the name of the statistic.

lCount

[out] Pointer to a variable that receives the number of values that were recorded.

dLast

[out] Pointer to a variable that receives the most recent value that was recorded.

dAverage

[out] Pointer to a variable that receives the average value.

dStdDev

[out] Pointer to a variable that receives the standard deviation of the values. If the count is less than two, the standard deviation is zero.

dMin

[out] Pointer to a variable that receives the minimum value that was recorded.

dMax

[out] Pointer to a variable that receives the maximum value that was recorded.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Index out of range.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The caller must free the string returned in szName, by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStats::GetValueByName

The GetValueByName method retrieves a statistic, by name.

Syntax

HRESULT GetValueByIndex(
  BSTR szName
  long *lIndex
  long *lCount
  double *dLast
  double *dAverage
  double *dStdDev
  double *dMin
  double *dMax
);

Parameters

szName

[in] Specifies the name of the statistic.

lIndex

[out] Pointer to a variable that receives the index of this statistic.

lCount

[out] Pointer to a variable that receives the number of values that were recorded.

dLast

[out] Pointer to a variable that receives the most recent value that was recorded.

dAverage

[out] Pointer to a variable that receives the average value.

dStdDev

[out] Pointer to a variable that receives the standard deviation of the values. If the count is less than two, the standard deviation is zero.

dMin

[out] Pointer to a variable that receives the minimum value that was recorded.

dMax

[out] Pointer to a variable that receives the maximum value that was recorded.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | No match for this name.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStats::Reset

The Reset method resets all statistics to zero.

Syntax

HRESULT Reset(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful, or an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMStats Interface


IAMStreamConfig Interface

The IAMStreamConfig interface enables an application to set the output format on certain capture and compression filters, for both audio and video.

Use this interface to set format properties, such as the output dimensions and frame rate (for video) or the sample rate and number of channels (for audio).

Filters expose this interface on their output pins. To use the interface, enumerate the filter's pins and query for IAMStreamConfig. Or, if you are using the Capture Graph Builder object to build the filter graph, you can call the ICaptureGraphBuilder2::FindInterface method. Note that a capture filter might have separate pins for capture and preview.

Filter developers: If you are writing a capture filter or compression filter, implement this interface on the video or audio output pin. For more information, see Exposing Capture and Compression Formats.

In addition to the methods inherited from IUnknown, the IAMStreamConfig interface exposes the following methods.

Method | Description
GetFormat | Retrieves the current or preferred output format.
GetNumberOfCapabilities | Retrieves the number of format capabilities that this pin supports.
GetStreamCaps | Retrieves a set of format capabilities.
SetFormat | Sets the output format on the pin.


IAMStreamConfig::GetFormat

The GetFormat method retrieves the current or preferred output format.

Syntax

HRESULT GetFormat(
  AM_MEDIA_TYPE **pmt
);

Parameters

pmt

[out] Address of a pointer to an AM_MEDIA_TYPE structure.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer value.
VFW_E_NOT_CONNECTED | The input pin is not connected.

Remarks

If the pin is connected, this method returns the format that the pin is currently using. Otherwise, the method returns the pin's preferred format for the next pin connection. If you have already called the IAMStreamConfig::SetFormat method to set the format, GetFormat returns the same format. If not, it returns the first format in the pin's list of preferred formats, as determined by the IPin::EnumMediaTypes method.

The method allocates the memory for the AM_MEDIA_TYPE structure, fills in the structure, and returns it in the pmt parameter. The caller must release the memory, including the format block. You can use the DeleteMediaType helper function in the base class library.

On some compression filters, the method fails if the filter's input pin is not connected.

Example Code

IAMStreamConfig *pConfig = NULL;
// Query the output pin for IAMStreamConfig (not shown).
AM_MEDIA_TYPE *pmt = NULL;
hr = pConfig->GetFormat(&pmt);
if (SUCCEEDED(hr))
{
    /* Examine the media type for any information you need. */
    DeleteMediaType(pmt);
}
pConfig->Release();

See Also

  • Error and Success Codes
  • IAMStreamConfig Interface


IAMStreamConfig::GetNumberOfCapabilities

The GetNumberOfCapabilities method retrieves the number of format capabilities that this pin supports.

Syntax

HRESULT GetNumberOfCapabilities(
  int *piCount,
  int *piSize
);

Parameters

piCount

[out] Pointer to a variable that receives the number of format capabilities.

piSize

[out] Pointer to a variable that receives the size of the configuration structure in bytes. See Remarks for more information.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer value.
VFW_E_NOT_CONNECTED | The input pin is not connected.

Remarks

An output pin can support more than one set of format capabilities. This method returns the total number of capabilities that the pin supports; the number is returned in the piCount parameter. To retrieve a particular set of capabilities, call the IAMStreamConfig::GetStreamCaps method. Format capabilities are indexed from zero, so the value returned in piCount is one more than the upper bound.

Depending on the pin's format type, the GetStreamCaps method returns either a VIDEO_STREAM_CONFIG_CAPS structure (for video) or an AUDIO_STREAM_CONFIG_CAPS structure (for audio). The piSize parameter receives the size of the structure, in bytes.

On some compression filters, this method fails if the filter's input pin is not connected.

See Also

  • Error and Success Codes
  • IAMStreamConfig Interface


IAMStreamConfig::GetStreamCaps

The GetStreamCaps method retrieves a set of format capabilities.

Syntax

HRESULT GetStreamCaps(
  int iIndex,
  AM_MEDIA_TYPE **pmt,
  BYTE *pSCC
);

Parameters

iIndex

[in] Specifies the format capability to retrieve, indexed from zero. To determine the number of capabilities that the pin supports, call the IAMStreamConfig::GetNumberOfCapabilities method.

pmt

[out] Address of a pointer to an AM_MEDIA_TYPE structure. The method allocates the structure and fills it with a media type.

pSCC

[out] Pointer to a byte array allocated by the caller. For video, use the VIDEO_STREAM_CONFIG_CAPS structure. For audio, use the AUDIO_STREAM_CONFIG_CAPS structure. To determine the required size of the array, call the GetNumberOfCapabilities method.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Specified index is too high.
S_OK | Success.
E_INVALIDARG | Invalid index.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer value.
VFW_E_NOT_CONNECTED | The input pin is not connected.

Remarks

This method returns two pieces of information:

  • The pmt parameter receives a filled-in AM_MEDIA_TYPE structure, which describes one supported output format.
  • The pSCC parameter receives a structure that contains additional format information. For video, pSCC receives a VIDEO_STREAM_CONFIG_CAPS structure. For audio, it receives an AUDIO_STREAM_CONFIG_CAPS structure.

To configure the output pin so that it uses this format, call the IAMStreamConfig::SetFormat method and pass in the value of pmt.

Before calling SetFormat, you can modify the AM_MEDIA_TYPE structure in pmt, using the information in pSCC. For example, an audio pin might return a default media type of 44-kHz, 16-bit stereo in the pmt parameter. Based on the values returned in the AUDIO_STREAM_CONFIG_CAPS structure, you might change this format to 8-bit mono before calling SetFormat.

The method allocates the memory for the AM_MEDIA_TYPE structure that is returned in the pmt parameter. The caller must release the memory, including the format block. You can use the DeleteMediaType helper function in the base class library. The caller must allocate the memory for the pSCC parameter.

On some compression filters, this method fails if the filter's input pin is not connected.

Filter Developers: For more information on implementing this method, see Exposing Capture and Compression Formats.

Example Code

The following example retrieves the first supported format (index zero) on a video output pin. Then it configures the pin to use the smallest output size for that format. To do so, it modifies the format block's BITMAPINFOHEADER structure with the new width and height; and sets the lSampleSize member of the AM_MEDIA_TYPE structure to the new sample size. The sample size depends partly on the bit depth, which can be determined from the media subtype. (For brevity, this example shows only the case for UYVY format. Also, it assumes that the caller already knows the pin produces video output.)

int iCount, iSize;
VIDEO_STREAM_CONFIG_CAPS scc;
AM_MEDIA_TYPE *pmt;

hr = pConfig->GetNumberOfCapabilities(&iCount, &iSize);
if (sizeof(scc) != iSize)
{
    // This is not the structure we were expecting.
    return E_FAIL;
}
// Get the first format.
hr = pConfig->GetStreamCaps(0, &pmt, reinterpret_cast<BYTE*>(&scc));
if (hr == S_OK)
{
    // Is it VIDEOINFOHEADER and UYVY?
    if (pmt->formattype == FORMAT_VideoInfo &&
        pmt->subtype == MEDIASUBTYPE_UYVY)
    {
        // Find the smallest output size.
        LONG width = scc.MinOutputSize.cx;
        LONG height = scc.MinOutputSize.cy;
        LONG cbPixel = 2;  // Bytes per pixel in UYVY

        // Modify the format block.
        VIDEOINFOHEADER *pVih =
            reinterpret_cast<VIDEOINFOHEADER*>(pmt->pbFormat);
        pVih->bmiHeader.biWidth = width;
        pVih->bmiHeader.biHeight = height;

        // Set the sample size and image size.
        // (Round the image width up to a DWORD boundary.)
        pmt->lSampleSize = pVih->bmiHeader.biSizeImage =
            ((width + 3) & ~3) * height * cbPixel;

        // Now set the format.
        hr = pConfig->SetFormat(pmt);
        if (FAILED(hr))
        {
            MessageBox(NULL, TEXT("SetFormat Failed\n"), NULL, MB_OK);
        }
        DeleteMediaType(pmt);
    }
}

See Also

  • Error and Success Codes
  • IAMStreamConfig Interface


IAMStreamConfig::SetFormat

The SetFormat method sets the output format on the pin.

Syntax

HRESULT SetFormat(
  AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the new format.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer value.
VFW_E_INVALIDMEDIATYPE | This media type is not valid.
VFW_E_NOT_CONNECTED | The input pin is not connected.
VFW_E_NOT_STOPPED | Cannot set the type; the filter is not stopped.
VFW_E_WRONG_STATE | Cannot set the type; the filter is not stopped.

Remarks

This method specifies the format for the output pin. If the pin is not connected, it will use this format for its next connection. If the pin is already connected, it will attempt to reconnect with this format. The method might fail if the other pin rejects the new type.

If this method succeeds, subsequent calls to the IPin::EnumMediaTypes method will return the new type, and no others.

On most filters, this method fails if the filter is paused or running. On some compression filters, the method fails if the filter's input pin is not connected.

With some filters, you can call this method with the value NULL to reset the pin to its default format.

Filter Developers: The following remarks describe how to implement this method:

If the output pin is not connected, and the pin supports the specified media type, return S_OK. Store the media type and offer it as format number zero in the CBasePin::GetMediaType method. Do not offer other formats, and reject other formats in the CBasePin::CheckMediaType method.

If the pin is already connected, and the pin supports the media type, reconnect the pin with that type. If the other pin rejects the new type, return VFW_E_INVALIDMEDIATYPE and restore the original connection.

See Also

  • Error and Success Codes
  • IAMStreamConfig Interface


IAMStreamControl Interface

The IAMStreamControl interface provides methods for controlling individual streams on a filter. Pins on some filters expose this interface. For example, the AVI Mux Filter supports this interface on its input pins, and the Audio Capture Filter and WDM Video Capture Filter support it on their output pins.

This interface enables an application to turn streams on and off at specified times. For example, an application might turn off an audio stream to mute the audio during video preview. Capture applications can use this interface to specify exact start and stop times for capture, and to control capture and preview streams independently of each other.

To use this interface, call the IAMStreamControl::StartAt method to specify when the pin will start delivering data, and the IAMStreamControl::StopAt method to specify when it will stop delivering data. Then call IMediaControl::Run on the Filter Graph Manager to run the filter graph. All times are relative to when the graph starts running.

When you use this interface, be aware of the following limitations:

  • There must be a reference clock in the filter graph.
  • Preview pins on capture cards with hardware overlay do not support this interface.
  • If you are capturing audio and video to an interleaved AVI file, the AVI Mux filter requires data both streams. If you stop one stream, the filter cannot interleave the data. For more information, see IConfigInterleaving Interface.

Depending on the application, you might find the ICaptureGraphBuilder2::ControlStream method more convenient, because it supports stream control at the graph level, so that you do not have to enumerate individual filters and pins.

Filter developers: The CBaseStreamControl base class implements this interface.

In addition to the methods inherited from IUnknown, the IAMStreamControl interface exposes the following methods.

Method | Description
StartAt | Informs the pin when to start sending streaming data.
StopAt | Informs the pin when to suspend processing and supplying data.
GetInfo | Retrieves information about the current streaming settings.

See Also

  • CBaseStreamControl Class
  • Error and Success Codes


IAMStreamControl::GetInfo

The GetInfo method retrieves information about the current stream-control settings, including the start and stop times.

Syntax

HRESULT GetInfo(
  AM_STREAM_INFO *pInfo
);

Parameters

pInfo

[out] Pointer to an AM_STREAM_INFO structure, allocated by the caller, that receives the current stream-control settings.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer value.

See Also

  • Error and Success Codes
  • IAMStreamControl Interface


IAMStreamControl::StartAt

The StartAt method informs the pin when to start delivering data.

Syntax

HRESULT StartAt(
  const REFERENCE_TIME *ptStart,
  DWORD dwCookie
);

Parameters

ptStart

[in] Pointer to a REFERENCE_TIME value that specifies when the pin should start delivering data. If the value is MAXLONGLONG (0x7FFFFFFFFFFFFFFF), the method cancels the previous start request. If psStart is NULL, the pin starts immediately when the graph runs.

For preview pins, only the values NULL and MAXLONGLONG are valid, because preview pins do not time stamp the samples they deliver.

dwCookie

[in] Specifies a value to send along with the start notification. See Remarks.

Return Values

If the method succeeds, the return value is S_OK. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

By default, the pin delivers data as soon as the filter graph runs. The StartAt method causes the pin to wait until a specified time after the graph runs, before the pin begins delivering data.

If the dwCookie parameter is non-zero, the pin will send an EC_STREAM_CONTROL_STARTED event when it starts to deliver data. The first event parameter is a pointer to the pin's IPin interface, and the second is the value of dwCookie.

This method implements the following special cases:

  • If ptStart is NULL, the pin starts as soon as the graph runs. No event is sent, and the value of dwCookie is ignored.
  • If ptStart contains the value MAXLONGLONG, and there is a pending stop request, the pin starts when the graph runs. If there is no pending stop request, the pin remains stopped. In either case, no start event is sent, and the value of dwCookie is ignored.

This method also handles the following boundary conditions:

  • If the start time falls between the start and stop times of a sample, the pin delivers that sample.
  • If the start time equals the stop time, the pin delivers one sample.

MAXLONGLONG is the largest possible REFERENCE_TIME value. In the base class library, it is also defined as the constant MAX_TIME.

See Also

  • Error and Success Codes
  • IAMStreamControl Interface


IAMStreamControl::StopAt

The StopAt method informs the pin when to stop delivering data.

Syntax

HRESULT StopAt(
  const REFERENCE_TIME *ptStop,
  BOOL bSendExtra,
  DWORD dwCookie
);

Parameters

ptStop

[in] Pointer to a REFERENCE_TIME value that specifies when the pin should stop delivering data. If the value is MAXLONGLONG (0x7FFFFFFFFFFFFFFF), the method cancels any previous stop request. If psStop is NULL, the pin stops immediately.

For preview pins, only the values NULL and MAXLONGLONG are valid, because preview pins do not time stamp the samples they deliver.

bSendExtra

[in] Specifies a Boolean value that indicates whether to send an extra sample after the scheduled stop time. If TRUE, the pin sends one extra sample.

dwCookie

[in] Specifies a value to send along with the start notification. See Remarks.

Return Values

If the method succeeds, the return value is S_OK. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

If the dwCookie parameter is non-zero, the pin will send an EC_STREAM_CONTROL_STOPPED event when it stops delivering data. The first event parameter is a pointer to the pin's IPin interface, and the second is the value of dwCookie. If ptStop is NULL or MAXLONGLONG, no event is sent, and the value of dwCookie is ignored.

In video capture, you would typically call this method on the capture filter's output pin and the multiplexer's input pin. The application should wait for the stop event from the multiplexer. This ensures that the capture filter sends the right number of frames, while guaranteeing that all frames reach the multiplexer. Also, set the bSendExtra parameter to TRUE for the capture pin, but FALSE for the multiplexer pin. This causes the capture filter to send one additional frame. The multiplexer relies on the time stamps from the capture pin, so if the extra frame is not sent, the multiplexer will wait indefinitely for the stop time. When the multiplexer receives the extra frame, it will discard it.

This method handles the following boundary conditions:

  • If the stop time falls between the start and stop times of a sample, the pin delivers that sample.
  • If the start time equals the stop time, the pin delivers one sample.

MAXLONGLONG is the largest possible REFERENCE_TIME value. In the base class library, it is also defined as the constant MAX_TIME.

See Also

  • Error and Success Codes
  • IAMStreamControl Interface


IAMStreamSelect Interface

The IAMStreamSelect interface controls which logical streams are played and retrieves information about them. An example of logical stream selection is selection from a set of audio streams that encode different national languages. For example, the client might be able to choose from a set of logical audio streams that included English, German, and French.

In addition to the methods inherited from IUnknown, the IAMStreamSelect interface exposes the following methods.

Method | Description
Count | Retrieves the number of available streams.
Enable | Enables or disables a given stream.
Info | Retrieves information about a given stream.


IAMStreamSelect::Count

The Count method retrieves the number of available streams.

Syntax

HRESULT Count(
  DWORD *pcStreams
);

Parameters

pcStreams

[out] Pointer to a variable that receives the number of streams.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

See Also

  • Error and Success Codes
  • IAMStreamSelect Interface


IAMStreamSelect::Enable

The Enable method enables or disables a given stream.

Syntax

HRESULT Enable(
  long lIndex,
  DWORD dwFlags
);

Parameters

lIndex

[in] Zero-based index of the stream.

dwFlags

[in] Flag indicating whether to enable or disable the stream. Use one of the following values.

Value | Description
Zero | Disable all streams in the group containing this stream.
AMSTREAMSELECTENABLE_ENABLE | Enable only this stream within the given group and disable all others.
AMSTREAMSELECTENABLE_ENABLEALL | Enable all streams in the group containing this stream.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid stream ID.
E_NOTIMPL | The filter does not support the specified flag.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

See Also

  • Error and Success Codes
  • IAMStreamSelect Interface


IAMStreamSelect::Info

The Info method retrieves information about a given stream.

Syntax

HRESULT Info(
  long lIndex,
  AM_MEDIA_TYPE **ppmt,
  DWORD *pdwFlags,
  LCID *plcid,
  DWORD *pdwGroup,
  WCHAR **ppszName,
  IUnknown **ppObject,
  IUnknown **ppUnk
);

Parameters

lIndex

[in] Zero-based index of the stream.

ppmt

[out] Address of a variable that receives a pointer to the stream's media type. This parameter is optional and can be NULL. If the value is non-NULL, the method returns a pointer to an AM_MEDIA_TYPE structure. The caller must delete the structure, including the format block. (You can use the DeleteMediaType function from the DirectShow base-class library.)

pdwFlags

[out] Pointer to a variable that receives one of the following values:

Value | Description
Zero | This stream is disabled.
AMSTREAMSELECTINFO_ENABLED | The stream is enabled, and others in this group might be enabled too.
AMSTREAMSELECTINFO_EXCLUSIVE | This stream is the only enabled stream in the group.

This parameter is optional and can be NULL.

plcid

[out] Pointer to a variable that receives a locale context (LCID) value. If the stream is associated with a particular locale, the LCID is returned in this variable. Otherwise, the variable receives the value zero. This parameter is optional and can be NULL.

pdwGroup

[out] Pointer to a variable that receives the logical group with which the stream is associated. This parameter is optional and can be NULL.

ppszName

[out] Address of a variable that receives a pointer to the stream name. The caller must free the returned string by calling the CoTaskMemFree function. This parameter is optional and can be NULL.

ppObject

[out] Address of a variable that receives an IUnknown interface pointer. The method might return a pointer to a pin or filter associated with the stream, or it might return the value NULL. If the method returns a non-NULL value, the caller must release the IUnknown pointer.

Calling the IAMStreamSelect::Enable method might invalidate the object returned by this method.

This parameter is optional and can be NULL.

ppUnk

[out] Address of a variable that receives an IUnknown interface pointer. The method might return a pointer to an interface that is specific to the stream, or it might return the value NULL. If the method returns a non-NULL value, the caller must release the IUnknown pointer. This parameter is optional and can be NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
S_FALSE | The index is out of range.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMStreamSelect Interface


IAMTimecodeDisplay Interface

The IAMTimecodeDisplay interface defines the behavior of an external SMPTE/MIDI timecode display device.

DirectShow currently does not provide any filters that implement this interface. Third parties should implement this interface on any filter that controls the timecode display of an external timecode reader or generator. Timecode readers or generators can be built into a VCR or can be separate external devices.

This interface is not intended for rendering in a Microsoft® DirectShow® filter graph; it is purely for use on external device displays.

Hardware Requirements

See the IAMExtTransport interface for hardware requirements.

In addition to the methods inherited from IUnknown, the IAMTimecodeDisplay interface exposes the following methods.

Method | Description
GetTCDisplayEnable | Determines whether an external device's timecode character generator output is enabled or disabled.
SetTCDisplayEnable | Enables or disables an external device's timecode character output generator.
GetTCDisplay | Retrieves current settings of the timecode character generator output.
SetTCDisplay | Sets the timecode character generator output characteristics.


IAMTimecodeDisplay::GetTCDisplay

The GetTCDisplay method retrieves current settings of the timecode character generator output.

Syntax

HRESULT GetTCDisplay(
  long Param,
  long *pValue
);

Parameters

Param

[in] Timecode display characteristic. Specify one of the following items you want to get settings for.

Value | Description
ED_TCD_BORDER | White border for black characters, black border for white characters.
ED_TCD_INTENSITY | Intensity (brightness) of characters.
ED_TCD_INVERT | Black characters on white background or white characters on black background.
ED_TCD_POSITION | Position of characters.
ED_TCD_SIZE | Size of characters.
ED_TCD_SOURCE | Source of display's data.
ED_TCD_TRANSPARENCY | Transparency of characters.

pValue

[out] Pointer to the current setting of the parameter specified in Param. This parameter retrieves one of the following values.

If ED_TCD_SOURCE specified in Param, will return one of the following.

Value | Description
ED_TCG | Timecode generator
ED_TCR | Timecode reader

If ED_TCD_SIZE specified in Param, will return one of the following.

Value | Description
ED_LARGE | Large
ED_MED | Medium
ED_SMALL | Small

If ED_TCD_POSITION specified in Param, will return one of the following.

Value | Description
ED_BOTTOM | Bottom
ED_MIDDLE | Middle
ED_TOP | Top

in combination with one of the following.

Value | Description
ED_CENTER | Center
ED_LEFT | Left
ED_RIGHT | Right

If ED_TCD_INTENSITY specified in Param, will return one of the following.

Value | Description
ED_HIGH | High
ED_LOW | Low

If ED_TCD_TRANSPARENCY is specified in Param, will return a value from 0 to 4, 0 being completely opaque.

If ED_TCD_INVERT is specified in Param, will return one of the following.

Value | Description
OAFALSE | Black characters on white background
OATRUE | White characters on black background

If ED_TCD_BORDER specified in Param, will return one of the following.

Value | Description
OAFALSE | Black characters for white border
OATRUE | White border for black characters

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTimecodeDisplay Interface
  • IAMTimecodeDisplay::SetTCDisplay


IAMTimecodeDisplay::GetTCDisplayEnable

The GetTCDisplayEnable method determines whether an external device's timecode character generator output is enabled or disabled.

Syntax

HRESULT GetTCDisplayEnable(
  long *pState
);

Parameters

pState

[out] Pointer to a value indicating whether timecode character generator output is enabled. OATRUE indicates enabled; OAFALSE indicates disabled.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method is not intended for character rendering inside a filter graph, it is purely intended for hardware displays. Ensure that your external timecode reader or generator has display capability before trying to use this method.

See Also

  • Error and Success Codes
  • IAMTimecodeDisplay Interface
  • IAMTimecodeDisplay::SetTCDisplayEnable


IAMTimecodeDisplay::SetTCDisplay

The SetTCDisplay method sets the timecode character generator output characteristics.

Syntax

HRESULT SetTCDisplay(
  long Param,
  long Value
);

Parameters

Param

[in] Timecode display characteristic. Specify one of the following properties you want to set properties for.

Value | Description
ED_TCD_BORDER | White border for black characters, black border for white characters
ED_TCD_INTENSITY | Intensity (brightness) of characters
ED_TCD_INVERT | Black characters on white background or white characters on black background
ED_TCD_POSITION | Position of characters
ED_TCD_SIZE | Size of characters
ED_TCD_SOURCE | Source of the display's data
ED_TCD_TRANSPARENCY | Transparency of characters

Value

[in] Setting of the parameter specified in Param. Must be one of the following:

If ED_TCD_SOURCE specified in Param, set one of the following.

Value | Description
ED_TCG | Timecode generator
ED_TCR | Timecode reader

If ED_TCD_SIZE is specified in Param, set one of the following.

Value | Description
ED_LARGE | Large
ED_MED | Medium
ED_SMALL | Small

If ED_TCD_POSITION specified in Param, set one of the following.

Value | Description
ED_BOTTOM | Bottom
ED_MIDDLE | Middle
ED_TOP | Top

in combination with one of the following.

Value | Description
ED_CENTER | Center
ED_LEFT | Left
ED_RIGHT | Right

If ED_TCD_INTENSITY is specified in Param, set one of the following.

Value | Description
ED_HIGH | High
ED_LOW | Low

If ED_TCD_TRANSPARENCY is specified in Param, set a value from 0 to 4, 0 being completely opaque, 4 being as dark as possible.

If ED_TCD_INVERT is specified in Param, set one of the following.

Value | Description
OAFALSE | Black on white
OATRUE | White on black

If ED_TCD_BORDER is specified in Param, set one of the following.

Value | Description
OAFALSE | Black characters for white border
OATRUE | White border for black characters

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTimecodeDisplay Interface
  • IAMTimecodeDisplay::GetTCDisplay


IAMTimecodeDisplay::SetTCDisplayEnable

The SetTCDisplayEnable method enables or disables an external device's timecode character output generator.

Syntax

HRESULT SetTCDisplayEnable(
  long State
);

Parameters

State

[in] Value specifying whether to enable or disable the timecode character output generator. Specify OATRUE to enable or OAFALSE to disable.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method is not intended for rendering characters inside a filter graph, it is purely intended for hardware displays. Ensure that your external timecode reader or generator has display capability before trying to use this method.

See Also

  • Error and Success Codes
  • IAMTimecodeDisplay Interface
  • IAMTimecodeDisplay::GetTCDisplayEnable


IAMTimecodeGenerator Interface

The IAMTimecodeGenerator interface controls how an external SMPTE/MIDI timecode generator supplies data to the filter graph.

DirectShow currently does not provide any filters that implement this interface. Third parties should implement this interface on any filter that controls an external timecode generator. Timecode generators can be built into a VCR or can be separate external devices. The device must be able to read timecode and send it to the computer over its control interface. If not, the user must have a timecode reader card in the computer, or you can write a software decoder that converts VITC embedded in captured video frames or LTC captured as an audio signal into DirectShow timecode samples.

SMPTE timecode is a frame addressing system that identifies video and audio sources, makes automatic track synchronization possible, and provides a container for additional data related to the production. SMPTE timecode's main purpose is to provide a machine-readable address for video and audio. It is displayed in hh:mm:ss:ff format and is thoroughly defined in ANSI/SMPTE 12-1986.

Optionally, you can enable applications to convert timecode to reference time by supporting the IMediaSeeking::ConvertTimeFormat method on the filter.

Hardware Requirements

For hardware requirements, see the IAMExtTransport interface.

In addition to the methods inherited from IUnknown, the IAMTimecodeGenerator interface exposes the following methods.

Method | Description
GetTCGMode | Retrieves the SMPTE timecode generator properties.
SetTCGMode | Sets the SMPTE timecode generator properties.
put_VITCLine | Specifies which line(s) to insert the vertical interval timecode information into.
get_VITCLine | Retrieves which line(s) the vertical interval timecode information has been inserted into.
SetTimecode | Sets the timecode, userbit value, or both.
GetTimecode | Retrieves the most recent timecode and/or userbit value available in the stream.

See Also

  • IAMTimecodeReader Interface


IAMTimecodeGenerator::GetTCGMode

The GetTCGMode method retrieves the SMPTE timecode generator properties.

Syntax

HRESULT GetTCGMode(
  long Param,
  long *pValue
);

Parameters

Param

[in] Timecode generator mode. Specify one of the following modes you want to get settings for.

Value | Description
ED_TCG_FRAMERATE | Frame rate
ED_TCG_REFERENCE_SOURCE | Source of the count value
ED_TCG_SYNC_SOURCE | Source of the hardware clock reference
ED_TCG_TIMECODE_TYPE | SMPTE timecode format of the generator

pValue

[out] Pointer to the current setting of the mode specified in Param.

If you specify ED_TCG_FRAMERATE in Param, this parameter retrieves one of the following.

Value | Description
ED_FORMAT_SMPTE_24 | 24 frames per second.
ED_FORMAT_SMPTE_25 | 25 frames per second.
ED_FORMAT_SMPTE_30 | 30 frames per second. Nondrop frame.
ED_FORMAT_SMPTE_30DROP | 30 frames per second. Drop frame (actually 29.97 fps).

If you specify ED_TCG_REFERENCE_SOURCE in Param, this parameter retrieves one of the following.

Value | Description
ED_TCG_FREE | No count reference source.
ED_TCG_READER | Synchronize to reader value (jamsync).

If you specify ED_TCG_SYNC_SOURCE in Param, this parameter retrieves one of the following.

Value | Description
ED_TCG_FREE | Lock to nothing (freerun).
ED_TCG_READER | Lock to timecode reader.
ED_TCG_VIDEO | Lock to incoming video.

If you specify ED_TCG_TIMECODE_TYPE in Param, this parameter retrieves one of the following.

Value | Description
ED_TCG_MIDI_FULL | MIDI full frame timecode
ED_TCG_MIDI_QF | MIDI quarter frame timecode
ED_TCG_SMPTE_LTC | Linear timecode
ED_TCG_SMPTE_VITC | Vertical interval timecode

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method returns various settings of the timecode generator. For more information on ED_TCG_TIMECODE_TYPE, see IAMTimecodeReader::SetTCRMode.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface


IAMTimecodeGenerator::GetTimecode

The GetTimecode method retrieves the most recent timecode and/or userbit value available in the stream.

Syntax

HRESULT GetTimecode(
  PTIMECODE_SAMPLE pTimecodeSample
);

Parameters

pTimecodeSample

[out] Pointer to a TIMECODE_SAMPLE structure.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to obtain the most recent timecode value available in the stream. The application can use this to monitor the timecode and verify the generator is working properly.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface
  • IAMTimecodeGenerator::SetTimecode


IAMTimecodeGenerator::get_VITCLine

The get_VITCLine method retrieves which line(s) the vertical interval timecode information has been inserted into.

Syntax

HRESULT get_VITCLine(
  long *pLine
);

Parameters

pLine

[out] Pointer to the vertical line(s) containing the timecode information (valid lines are 11-20).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To get VITC information from multiple lines, make successive calls to this method, once for each line desired, with the hi bit set for each line.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface
  • IAMTimecodeGenerator::put_VITCLine


IAMTimecodeGenerator::put_VITCLine

The put_VITCLine method specifies which line to insert the vertical interval timecode information into.

Syntax

HRESULT put_VITCLine(
  long Line
);

Parameters

Line

[in] Vertical line to contain the timecode information (valid lines are 11-20; 0 means autoselect).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To generate VITC on specific multiple lines, make successive calls to this method, once for each line desired.

Set the high bit to add to this line to any previously set lines.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface
  • IAMTimecodeGenerator::get_VITCLine


IAMTimecodeGenerator::SetTCGMode

The SetTCGMode method sets the SMPTE timecode generator properties.

Syntax

HRESULT SetTCGMode(
  long Param,
  long Value
);

Parameters

Param

[in] Timecode generator mode. Specify one of the following modes.

Value | Description
ED_TCG_FRAMERATE | Frame rate
ED_TCG_REFERENCE_SOURCE | Source of the count value
ED_TCG_SYNC_SOURCE | Source of the hardware clock reference
ED_TCG_TIMECODE_TYPE | SMPTE timecode format of the generator

Value

[in] Setting of the mode specified in Param.

If ED_TCG_FRAMERATE is specified in Param, this parameter is set to one of the following.

Value | Description
ED_FORMAT_SMPTE_24 | 24 frames per second.
ED_FORMAT_SMPTE_25 | 25 frames per second.
ED_FORMAT_SMPTE_30 | 30 frames per second. Nondrop frame.
ED_FORMAT_SMPTE_30DROP | 30 frames per second. Drop frame (actually 29.97 frames per second).

If ED_TCG_REFERENCE_SOURCE is specified in Param, set one of the following.

Value | Description
ED_TCG_FREE | No count reference source.
ED_TCG_READER | Sync to reader value (jamsync).

If ED_TCG_SYNC_SOURCE is specified in Param, set one of the following.

Value | Description
ED_TCG_FREE | Lock to nothing (freerun).
ED_TCG_READER | Lock to timecode reader.
ED_TCG_VIDEO | Lock to incoming video.

If ED_TCG_TIMECODE_TYPE is specified in Param, set one of the following.

Value | Description
ED_TCG_MIDI_FULL | MIDI Full Frame timecode
ED_TCG_MIDI_QF | MIDI quarter frame timecode
ED_TCG_SMPTE_LTC | Linear timecode
ED_TCG_SMPTE_VITC | Vertical interval timecode

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For more information on ED_TCG_TIMECODE_TYPE, see the IAMTimecodeReader::SetTCRMode method.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface
  • IAMTimecodeGenerator::GetTCGMode


IAMTimecodeGenerator::SetTimecode

The SetTimecode method sets the timecode, userbit value, or both.

Syntax

HRESULT SetTimecode(
  PTIMECODE_SAMPLE pTimecodeSample
);

Parameters

pTimecodeSample

[in] Pointer to a TIMECODE_SAMPLE structure.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To set only timecode, set userbit value to NULL, and vice versa. If generator is running, these values will take effect immediately.

See Also

  • Error and Success Codes
  • IAMTimecodeGenerator Interface
  • IAMTimecodeGenerator::GetTimecode


IAMTimecodeReader Interface

The IAMTimecodeReader interface enables an application to read SMPTE or MIDI timecode from an external device. The MSDV and MSTape drivers support this interface for reading timecode from an external DV or MPEG-2 camcorder.

Hardware Requirements

See the IAMExtTransport interface for hardware requirements.

In addition to the methods inherited from IUnknown, the IAMTimecodeReader interface exposes the following methods.

Method | Description
GetTCRMode | Retrieves properties of the timecode reader.
SetTCRMode | Sets the timecode reader properties.
put_VITCLine | Specifies the vertical interval line that the timecode reader will use to read timecode.
get_VITCLine | Retrieves the vertical interval line that the timecode reader is using to read timecode.
GetTimecode | Retrieves the most recent timecode, userbits, and flag values available in the stream.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_TIMECODE_READER property set. For more information, see the DirectX DDK documenation.

SMPTE timecode is a frame addressing system that identifies video and audio sources, makes automatic track synchronization possible, and provides a container for additional data related to the source material. SMPTE timecode's main purpose is to provide a machine-readable address for video and audio. It is displayed in hh:mm:ss:ff (hours, minutes, seconds, frames) format and is thoroughly defined in ANSI/SMPTE 12-1986.

Applications generally save timecode in one of two ways. It is either written to the capture file as an additional stream or as a discontinuity table stored in the extended AVI file index. It is commonly used to trigger capture or playback and to create edit decision lists that describes how source material is organized into a finished product.

If you intend to capture timecode, treat it as a separate stream that has its own media type. It can be consumed by an appropriate file-writing multiplexer filter. However, sometimes there are errors in reading the timecode off the tape because of dropouts and other mechanical tape problems. In such cases, the timecode source filter should simply drop samples and mark the next valid one with the discontinuity property.

If you intend to use timecodes to trigger capture or playback from a timecoded (or "striped") videotape, the sequence of events goes as follows:

  1. Build a capture graph, open a target AVI file, and preallocate disk space if necessary. If the captured material will be appended to an existing AVI file, seek to the end of the file before writing. The capture graph is paused at this point.
  2. Search the VCR to the capture start point and note the timecode. You can either enter this value manually into your program, or the application can automatically read it. Automatic reading requires that the graph is running but the stream control interfaces on the file multiplexer's input pins are discarding incoming samples, effectively gating the capture.
  3. Cue the VCR to preroll position, usually five seconds before the target point.
  4. Start the VCR and the graph. When the trigger point is reached (or the trigger point minus the file writer's preroll), the stream control interfaces release the file multiplexer and it begins streaming media samples to the file writer.
  5. You can stop the capture process manually or by setting a duration property on the stream control interface.

You must consider discontinuous timecode, both during preroll and during the capture process; it is reasonable to demand that the timecode be continuous and monotonically increasing throughout the preroll and capture start point. This prevents a potentially ambiguous calculation of relative stream times by the IMediaSeeking::ConvertTimeFormat method. Also, the timecode need not be the only gating signal for triggered capture. Any time-stamped data stored in the vertical blanking interval, such as Intercast or closed-captioned data (XDS), can be used to start the streaming of video and audio data to disk.

Filter Developers: Implement this interface on an external device filter when you want to specify how an external device should read SMPTE/MIDI timecode information. Expose the IMediaSeeking interface on your filter so that applications can convert timecode to reference time, using the IMediaSeeking::ConvertTimeFormat method.

The external device must be able to read timecode and send it to the computer over its control interface. If this is not the case, you must either have a timecode reader card in your computer, or you can write a software decoder that converts VITC (Vertical Interval Timecode) in captured video frames or LTC (Linear Timecode) captured as an audio signal into DirectShow timecode samples.


IAMTimecodeReader::GetTCRMode

The GetTCRMode method retrieves the timecode reader's properties.

Syntax

HRESULT GetTCRMode(
  long Param,
  long *pValue
);

Parameters

Param

[in] Timecode reader property to get (either ED_TCR_SOURCE or ED_TCR_NOTIFY_ENABLE).

pValue

[out] Pointer to the value of the requested timecode reader property. If Param is set to ED_TCR_NOTIFY_ENABLE, then this parameter will return OATRUE—meaning that notifications are enabled—or OAFALSE. If Param is set to ED_TCR_SOURCE, then this value must be one of the following.

Value | Description
ED_TCR_CT | Control track
ED_TCR_LTC | Linear timecode
ED_TCR_VITC | Vertical interval timecode
ED_TCR_LAST_VALUE | Last read value

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Linear timecode is recorded on an analog audio track as a bi-phase mark -encoded signal. Each timecode frame is one video frame time in duration.

Vertical timecode is usually stored in two lines of a video signal's vertical interval, somewhere between lines 11 and 20.

Control track is a once-per-frame signal recorded on a special track on a tape. The head and drive servo mechanisms use it to keep everything locked. It is also used to drive the counter on machines without timecode capability, and can optionally be used on machines equipped with a timecode reader.

Note that ED_TCR_LAST_VALUE is used when implementing timecode notification because the application does not want to initiate another timecode request to the external device. This method is not recommended for frame-accurate applications because of multithreading issues.

See Also

  • Error and Success Codes
  • IAMTimecodeReader Interface
  • IAMTimecodeReader::SetTCRMode


IAMTimecodeReader::GetTimecode

The GetTimecode method retrieves the most recent timecode, userbit, and flag values available in the stream.

Syntax

HRESULT GetTimecode(
  TIMECODE_SAMPLE *pTimecodeSample
);

Parameters

pTimecodeSample

[out] Pointer to a TIMECODE_SAMPLE structure.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to monitor the timecode and to parse duplicates and discontinuities.

The timecode contains undefined bits, called userbits. Applications can use these bits to store synchronization information or other custom information.

DV and MPEG Camcorder Implementation

The MSDV driver supports reading SMPTE timecode or absolute track numbers (ATN). The MSTape driver supports reading the relative time counter (RTC). To read time information on these devices, do the following:

Set the dwFlags member of the TIMECODE_SAMPLE structure to one of the following values.

Constant | Description
ED_DEVCAP_TIMECODE_READ | Timecode (DV)
ED_DEVCAP_ATN_READ | Absolute track number (DV)
ED_DEVCAP_RTC_READ | Relative time counter (MPEG tape)

The timecode member of the TIMECODE_SAMPLE structure is a TIMECODE structure. Initialize that structure's dwFrames member to zero.

All other structure members are ignored.

When the method returns, the dwFrames member contains the time information, in the following format.

Time Information | Format
Timecode | Hours, minutes, seconds, and frames, as a binary coded decimal (BCD) value: 0xhhmmssff.
ATN | Track number.
RTC | Hours, minutes, seconds, and frames, as a BCD value: 0xhhmmssff. The most significant bit of the frames byte is a sign bit. If the frame count is not available, the remaining frame bits are set to 0x7F.

Also, the dwUser member receives the blank flag bit from the device, which has one of the following values.

Value | Description
0x00 | Not a discontinuity.
0x01 | Discontinuity.

See Also

  • Getting Timecode from the Device
  • Error and Success Codes
  • IAMTimecodeReader Interface


IAMTimecodeReader::get_VITCLine

The get_VITCLine method retrieves the vertical interval line that the timecode reader is using to read timecode.

Syntax

HRESULT get_VITCLine(
  long *pLine
);

Parameters

pLine

[out] Pointer to the vertical line containing timecode information (valid lines are from 11 through 20).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The high bit indicates that multiple lines are used and successive calls will cycle through the line numbers.

See Also

  • Error and Success Codes
  • IAMTimecodeReader Interface
  • IAMTimecodeReader::put_VITCLine


IAMTimecodeReader::put_VITCLine

The put_VITCLine method specifies the vertical interval line that the timecode reader will use to read timecode.

Syntax

HRESULT put_VITCLine(
  long Line
);

Parameters

Line

[in] Vertical line containing timecode information (valid lines are 11-20; 0 means autoselect).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

If VITC mode is specified in the IAMTimecodeReader::SetTCRMode method, you must specify which line or lines will contain timecode information. To read VITC on specific multiple lines, the caller would make successive calls to IAMTimecodeReader::put_VITCLine, once for each line desired.

Set the high bit to add to the list of lines for readers that test across multiple lines.

See Also

  • Error and Success Codes
  • IAMTimecodeReader Interface
  • IAMTimecodeReader::get_VITCLine


IAMTimecodeReader::SetTCRMode

The SetTCRMode method sets the timecode reader properties.

Syntax

HRESULT SetTCRMode(
  long Param,
  long Value
);

Parameters

Param

[in] Property you want to set (use ED_TCR_SOURCE or ED_TCR_NOTIFY_ENABLE).

Value

[in] Value of the specified property; If Param returns ED_TCR_NOTIFY_ENABLE, then this value will return OATRUE or OAFALSE. IfParam returns ED_TCR_SOURCE, then this value must be one of the following.

Value | Description
ED_TCR_CT | Control Track.
ED_TCR_LTC | Linear Timecode.
ED_TCR_VITC | Vertical Interval Timecode.
ED_TCR_LAST_VALUE | Return last read value.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Linear timecode is recorded on an analog audio track as an NRZ bi-phase mark-encoded signal. Each timecode frame is one video frame time in duration.

Vertical timecode is usually stored in two lines of a video signal's vertical interval, somewhere between 10 and 20.

Control track is a once-per-frame signal recorded on a special track on a tape. The head and drive servo mechanisms use it to keep everything locked. It is also used to drive the counter on machines without timecode capability, and can optionally be used on machines equipped with a timecode reader.

Note that ED_TCR_LAST_VALUE is used when implementing timecode notification because the application does not want to initiate another timecode request to the external device. This method is not recommended for frame-accurate applications because of multithreading issues.

See Also

  • Error and Success Codes
  • IAMTimecodeReader Interface
  • IAMTimecodeReader::GetTCRMode


IAMTuner Interface

The IAMTuner interface is the base class for the IAMTVTuner interface, which inherits all the IAMTuner methods. For more information on controlling a TV tuner using Microsoft DirectShow, see the IAMTVTuner documentation.

In addition to the methods inherited from IUnknown, the IAMTuner interface exposes the following methods.

Method | Description
ChannelMinMax | Retrieves the minimum and maximum channel available.
GetAvailableModes | Retrieves the tuner's supported modes.
get_Channel | Retrieves the TV channel that the tuner is set to.
get_CountryCode | Retrieves the country/region code.
get_Mode | Retrieves the current mode on a multifunction tuner.
get_TuningSpace | Retrieves the storage index for regional fine tuning.
Logon | Logs a user onto the system.
Logout | Logs a user off the system.
put_Channel | Sets the TV channel.
put_CountryCode | Sets the country/region code to establish the frequency to use.
put_Mode | Sets a multifunction tuner to the specified mode.
put_TuningSpace | Sets a storage index for regional channel-to-frequency mappings.
RegisterNotificationCallBack | Allows an object that implements the IAMTunerNotification interface to receive event notifications when the tuner changes state. (Not implemented.)
SignalPresent | Retrieves the strength of the signal on a given channel.
UnRegisterNotificationCallBack | Unregisters an object for event notifications. (Not implemented.)


IAMTuner::ChannelMinMax

The ChannelMinMax method retrieves the highest and lowest channels available.

Syntax

HRESULT ChannelMinMax(
  long *lChannelMin,
  long *lChannelMax
);

Parameters

lChannelMin

[out] Pointer to a variable that receives the lowest channel.

lChannelMax

[out] Pointer to a variable that receives the highest channel.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • International Analog TV Tuning
  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::get_Channel

The get_Channel method retrieves the channel to which the tuner is set.

Syntax

HRESULT get_Channel (
  long *plChannel,
  long *plVideoSubChannel,
  long *plAudioSubChannel
);

Parameters

plChannel

[out] Pointer to a variable that receives the channel. For frequencies, see International Analog TV Tuning

plVideoSubChannel

[out] Pointer to a variable that receives either the video subchannel, or one of the following flags:

Value | Description
AMTUNER_SUBCHAN_DEFAULT | Default subchannel
AMTUNER_SUBCHAN_NO_TUNE | No subchannel tuning

plAudioSubChannel

[out] Pointer to a variable that receives either the audio subchannel, or one of the following flags:

Value | Description
AMTUNER_SUBCHAN_DEFAULT | Default subchannel
AMTUNER_SUBCHAN_NO_TUNE | No subchannel tuning

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::get_CountryCode

The get_CountryCode method retrieves the country/region code that establishes the current channel-to-frequency mapping.

Syntax

HRESULT get_CountryCode(
  long *plCountryCode
);

Parameters

plCountryCode

[out] Pointer to a variable that receives the country/region code currently in use by the TV Tuner filter.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The IAMTuner::put_CountryCode method determines which channel-to-frequency mapping table to use. This establishes the base frequencies for the given country/region. Use the IAMTVTuner::AutoTune method to determine the exact frequencies for specific regions.

Override the country/region code when a country/region wants to receive broadcast video from a different national source. For a list of country/region codes, see International Analog TV Tuning.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::get_Mode

The get_Mode method retrieves the current mode on a multifunction tuner.

Syntax

HRESULT get_Mode(
  AMTunerModeType *plMode
);

Parameters

plMode

[out] Pointer to a variable that receives a flag indicating the current mode setting. The possible values are defined in the AMTunerModeType enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::get_TuningSpace

The get_TuningSpace method retrieves the tuning space.

Syntax

HRESULT get_TuningSpace(
  long *plTuningSpace
);

Parameters

plTuningSpace

[out] Pointer to a variable that receives the current tuning space.

Return Values

Returns an HRESULT value.

Remarks

The application defines the value retrieved by this method; it is set through a call to IAMTuner::put_TuningSpace.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::GetAvailableModes

The GetAvailableModes method retrieves the tuner's supported modes.

Syntax

HRESULT GetAvailableModes(
  long *plModes
);

Parameters

plModes

[out] Pointer to a variable that receives any combination of the values as specified in the AMTunerModeType enumeration.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::Logon

The Logon method logs a user onto the system.

Syntax

HRESULT Logon(
  HANDLE hCurrentUser
);

Parameters

hCurrentUser

[in] Handle to an application-defined data structure that identifies the current user.

Return Values

Returns an HRESULT value.

Remarks

The Logon and Logout methods enable you to implement selective user access.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::Logout

The Logout method logs out the current user.

Syntax

HRESULT Logout(void);

Parameters

This methods takes no parameters.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::put_Channel

The put_Channel method sets the TV channel.

Syntax

HRESULT put_Channel(
  long lChannel,
  long lVideoSubChannel,
  long lAudioSubChannel
);

Parameters

lChannel

[in] TV channel number.

lVideoSubChannel

Predefined video subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel. Meaningful only for satellite broadcasts.

lAudioSubChannel

Predefined audio subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel. Meaningful only for satellite broadcasts.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method handles the channel-to-frequency function call that converts the TV channel to a TV frequency. For a list of frequencies for channels, see International Analog TV Tuning.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::put_CountryCode

The put_CountryCode method sets the country/region code to establish the frequency to use.

Syntax

HRESULT put_CountryCode(
  long lCountryCode
);

Parameters

lCountryCode

[in] Value indicating the country/region code.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method establishes the base frequencies for the given country/region. Use the IAMTVTuner::AutoTune method to determine the exact frequencies for specific regions, unless there are previously cached settings for the new country/region.

Because channels in different countries/regions map to different frequencies, worldwide mapping tables are provided in the appendix International Analog TV Tuning. Override the existing country/region code by selecting the new value from the appendix and passing it in as the parameter for the put_CountryCode method. This is useful when a country/region wants to receive broadcast video from a different national source.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::put_Mode

The put_Mode method sets a multifunction tuner to the specified mode.

Syntax

HRESULT put_Mode(
  AMTunerModeType lMode
);

Parameters

lMode

[in] Flag indicating which mode to switch to. Possible values are defined in the AMTunerModeType enumeration.

You can also set the mode to digital TV if the card supports it. To do this, define AMTUNER_MODE_DTV with a value of 0x0010.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTuner::GetAvailableModes


IAMTuner::put_TuningSpace

The put_TuningSpace method sets a storage index for regional channel-to-frequency mappings.

Syntax

HRESULT put_TuningSpace(
  long lTuningSpace
);

Parameters

lTuningSpace

[in] Value indicating the current locale.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

As TV tuners move into portable systems, you must retain locale-specific mappings of available channels and their actual frequencies. Formulating different lTuningSpace values for each locale provides a way of switching the channel-to-frequency mappings when moving from region to region.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::RegisterNotificationCallBack

The RegisterNotificationCallBack method enables an object to receive event notifications when the tuner changes state.

This method is not implemented.

Syntax

HRESULT RegisterNotificationCallBack(
  IAMTunerNotification *pNotify,
  long lEvents
);

Parameters

pNotify

[in] Pointer to the IAMTunerNotification interface that will receive the event notifications.

lEvents

[in] Flag indicating that an event has occurred.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::SignalPresent

The SignalPresent method retrieves the strength of the signal on a given channel.

Syntax

HRESULT SignalPresent(
  long *plSignalStrength
);

Parameters

plSignalStrength

[out] Pointer to a variable that receives a value indicating whether a signal is present on the current channel. Can be one of the following values.

Value | Description
AMTUNER_HASNOSIGNALSTRENGTH | -1
AMTUNER_NOSIGNAL | 0
AMTUNER_SIGNALPRESENT | 1

A value of AMTUNER_HASNOSIGNALSTRENGTH means the signal strength cannot be determined at this time.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTuner::UnRegisterNotificationCallBack

The UnRegisterNotificationCallBack method unregisters an object for event notifications.

This method is not implemented.

Syntax

HRESULT UnRegisterNotificationCallBack(
  IAMTunerNotification *pNotify
);

Parameters

pNotify

[in] Pointer to the IAMTunerNotification interface that was specified in a previous call to RegisterNotificationCallBack.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMTuner Interface


IAMTVAudio Interface

The IAMTVAudio interface is implemented on the TV Audio filter. This interface enables applications to control settings unique to audio from television sources, including secondary audio program (SAP), and stereo or mono selection. These controls are generally found on devices external to the system audio mixer.

In addition to the methods inherited from IUnknown, the IAMTVAudio interface exposes the following methods.

Method | Description
get_TVAudioMode | Retrieves the current TV audio mode.
GetAvailableTVAudioModes | Retrieves a bitmask of the possible modes.
GetHardwareSupportedTVAudioModes | Retrieves a bitmask of the formats available in the hardware.
put_TVAudioMode | Sets the current TV audio mode.
RegisterNotificationCallBack | Not implemented.
UnRegisterNotificationCallBack | Not implemented.

See Also

  • Analog Television


IAMTVAudio::GetHardwareSupportedTVAudioModes

The GetHardwareSupportedTVAudioModes method retrieves a bitmask of the formats available in the hardware.

Syntax

HRESULT GetHardwareSupportedTVAudioModes(
  long *plModes
);

Parameters

plModes

[out] Pointer to a TVAudioMode enumeration value that identifies the audio mode.

Return Values

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVAudio::GetAvailableTVAudioModes

The GetAvailableTVAudioModes method retrieves a bitmask of the possible modes.

Syntax

HRESULT GetAvailableTVAudioModes(
  long *plModes
);

Parameters

plModes

[out] Pointer to a TVAudioMode enumeration type, identifying the audio mode.

Return Values

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVAudio::get_TVAudioMode

The get_TVAudioMode method retrieves the current TV audio mode.

Syntax

HRESULT get_TVAudioMode(
  long *plModes
);

Parameters

plModes

[out] Pointer to a TVAudioMode enumeration type, identifying the audio mode.

Return Values

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVAudio::put_TVAudioMode

The put_TVAudioMode method sets the current TV audio mode.

Syntax

HRESULT put_TVAudioMode(
  long plModes
);

Parameters

plModes

[in] A TVAudioMode enumeration value that identifies the audio mode.

Return Values

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVAudio::RegisterNotificationCallBack

The RegisterNotificationCallBack method enables an object that implements the IAMTunerNotification interface to receive event notifications when the tuner changes state.

This method is not implemented.

Syntax

HRESULT RegisterNotificationCallBack(
  IAMTunerNotification *pNotify,
  long lEvents
);

Parameters

pNotify

[in] Pointer to the IAMTunerNotification interface that will receive the event notifications.

lEvents

[in] Flag indicating that an event has occurred.

Return Values

Returns a E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVAudio::UnRegisterNotificationCallBack

The UnRegisterNotificationCallBack method unregisters an object for event notifications.

This method is not implemented.

Syntax

HRESULT UnRegisterNotificationCallBack(
  IAMTunerNotification *pNotify
);

Parameters

pNotify

[in] Pointer to the IAMTunerNotification interface that was specified in a previous call to RegisterNotificationCallBack.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IAMTVAudio Interface


IAMTVTuner Interface

The IAMTVTuner interface is implemented on the TV Tuner filter. This interface inherits the IAMTuner interface and provides methods that enable an application to control a TV tuner device. The interface supports tuners for analog broadcast television and AM/FM radio.

IAMTVTuner supports tuners with multiple input pins, to allow for multiple devices and multiple transmission types.

IAMTVTuner maps TV channels to specific frequencies through the IAMTuner::put_Channel and IAMTVTuner::AutoTune methods. These methods handle the details of the conversion so that the hardware driver receives an exact frequency. The TV Tuner filter supports worldwide tuning coverage.

Use this interface from an application to set TV channels and to get or set information about their frequencies, and to determine what analog video standards your TV tuner card supports.

In addition to the methods inherited from IAMTuner, the IAMTVTuner interface exposes the following methods.

Method | Description
get_AvailableTVFormats | Retrieves all the analog video TV standards that the tuner supports.
get_TVFormat | Retrieves the current analog video TV standard in use.
AutoTune | Scans for a precise signal on the channel's frequency.
StoreAutoTune | Saves the fine-tuning information for all channels.
get_NumInputConnections | Retrieves the number of TV sources plugged into the tuner filter.
put_InputType | Sets the tuner input type (cable or antenna).
get_InputType | Retrieves the input type.
put_ConnectInput | Sets the hardware tuner input connection.
get_ConnectInput | Retrieves the hardware tuner input connection.
get_VideoFrequency | Retrieves the current video frequency.
get_AudioFrequency | Retrieves the current audio frequency.

See Also

  • Analog Television


IAMTVTuner::AutoTune

The AutoTune method scans for a precise signal on the channel's frequency.

Syntax

HRESULT AutoTune(
  long lChannel,
  long *plFoundSignal
);

Parameters

lChannel

[in] TV channel number.

plFoundSignal

[out] Pointer to a variable indicating whether the channel's frequency was found; nonzero indicates found, zero indicates not found.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

TV channels generally map to a unique frequency depending on regional variances. To avoid interference between multiple transmitters that are assigned the same channel when they are in close geographic proximity, small frequency offsets are introduced at each transmitter. In the United States, this offset ranges up to +/– 26.25 kilohertz (kHz).

This method handles the channel-to-frequency conversion and scans for the most precise frequency. Store these values by calling the IAMTVTuner::StoreAutoTune method. You can find base frequencies for channels in the appendix International Analog TV Tuning.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_AudioFrequency

The get_AudioFrequency method retrieves the currently tuned audio frequency.

Syntax

HRESULT get_AudioFrequency(
  long *lFreq
);

Parameters

lFreq

[out] Pointer to a variable that receives the audio frequency, in hertz (Hz).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This is a diagnostic method that enables you to examine the exact frequency being used for a given channel.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_AvailableTVFormats

The get_AvailableTVFormats method retrieves all the analog video TV standards that the tuner supports.

Syntax

HRESULT get_AvailableTVFormats(
  long *lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard

[out] Pointer to a variable that receives a bitwise combination of values from the AnalogVideoStandard enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_ConnectInput

The get_ConnectInput method retrieves the hardware tuner input connection.

Syntax

HRESULT get_ConnectInput (
  long *plIndex
);

Parameters

plIndex

[out] Pointer to the input pin to get the connection for.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_InputType

The get_InputType method retrieves the input type set in IAMTVTuner::put_InputType.

Syntax

HRESULT get_InputType (
  long lIndex,
  TunerInputType *pInputType
);

Parameters

lIndex

[in] Index value that specifies the input pin that will be set.

pInputType

[out] Pointer to a variable the receives a member of the TunerInputType enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_NumInputConnections

The get_NumInputConnections method retrieves the number of TV sources plugged into the tuner filter.

Syntax

HRESULT get_NumInputConnections(
  long *plNumInputConnections
);

Parameters

plNumInputConnections

[out] Pointer to a variable that receives the number of TV sources plugged into the tuner filter.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_TVFormat

The get_TVFormat method retrieves the current analog video TV standard in use.

Syntax

HRESULT get_TVFormat(
  long *plAnalogVideoStandard
);

Parameters

plAnalogVideoStandard

[out] Pointer to a variable that receives a member of the AnalogVideoStandard enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::get_VideoFrequency

The get_VideoFrequency method retrieves the current video frequency.

Syntax

HRESULT get_VideoFrequency(
  long *lFreq
);

Parameters

lFreq

[out] Pointer to a variable that receives the video frequency, in hertz (Hz).

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

This is a diagnostic method that enables you to examine the exact frequency being used for a given channel.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::put_ConnectInput

The put_ConnectInput method sets the hardware tuner input connection.

Syntax

HRESULT put_ConnectInput(
  long lIndex
);

Parameters

lIndex

[in] Index value of the input pin to set connection for.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::put_InputType

The put_InputType method sets the tuner input type (cable or antenna).

Syntax

HRESULT put_InputType(
  long lIndex,
  TunerInputType InputType
);

Parameters

lIndex

[in] Index value that specifies the input pin to be set.

InputType

[in] Value indicating the connection type, as specified in the TunerInputType enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTuner Interface
  • IAMTVTuner Interface


IAMTVTuner::StoreAutoTune

The StoreAutoTune method saves the fine-tuning information for all channels.

Syntax

HRESULT StoreAutoTune(void);

Paremeters

This method takes no parameters.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Override the channel-to-frequency information stored by this method by setting a new country/region code in the IAMTuner::put_CountryCode method. For a listing of country/region codes, see International Analog TV Tuning.

See Also

  • Error and Success Codes
  • IAMTVTuner Interface
  • IAMTuner Interface


IAMVfwCaptureDialogs Interface

The IAMVfwCaptureDialogs interface is implemented on the VFW Capture filter. This interface enables an application to display one of the three dialog boxes (Source, Format, or Display) provided by Microsoft® Video for Windows® capture drivers. Any application that enables the user to change settings in a Video for Windows capture driver-supplied dialog box should use this interface.

In addition to the methods inherited from IUnknown, the IAMVfwCaptureDialogs interface exposes the following methods.

Method | Description
HasDialog | Determines if the specified dialog box exists in the driver.
ShowDialog | Displays the specified dialog box.
SendDriverMessage | Sends a driver-specific message.


IAMVfwCaptureDialogs::HasDialog

The HasDialog method determines if the specified dialog box exists in the driver.

Syntax

HRESULT HasDialog(
  int iDialog
);

Parameters

iDialog

[in] Desired dialog box. This is a member of the VfwCaptureDialogs enumeration.

Return Values

Returns S_OK if the driver contains the dialog box or S_FALSE otherwise.

Remarks

This method calls the Video for Windows videoDialog function to query for the existence of the appropriate dialog box.

See Also

  • Error and Success Codes
  • IAMVfwCaptureDialogs Interface


IAMVfwCaptureDialogs::SendDriverMessage

The SendDriverMessage method sends a driver-specific message.

Syntax

HRESULT SendDriverMessage(
  int iDialog,
  int uMsg,
  long dw1,
  long dw2
);

Parameters

iDialog

[in] Handle of the driver dialog box. This is a member of the VfwCaptureDialogs enumeration.

uMsg

[in] Message to send to the driver.

dw1

[in] Message data.

dw2

[in] Message data.

Return Values

Return value varies depending on the implementation within each driver.

Remarks

You should never need to use this method. This method can send any private message to the capture driver. Behavior might be undetermined in response to arbitrary messages; use this method at your own risk.

This method calls the Video for Windows videoMessage function to send the driver message.

See Also

  • Error and Success Codes
  • IAMVfwCaptureDialogs Interface


IAMVfwCaptureDialogs::ShowDialog

The ShowDialog method displays the specified VFW dialog box.

Syntax

HRESULT ShowDialog(
  int iDialog,
  HWND hwnd
);

Parameters

iDialog

[in] Dialog box to display. This is a member of the VfwCaptureDialogs enumeration.

hwnd

[in] Handle of the dialog box's parent window.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_CANNOT_CONNECT | Could not reconnect with the new format.
VFW_E_NOT_STOPPED | The filter graph is not stopped.

Remarks

Stop the filter graph before calling this method. Otherwise, the method fails and returns VFW_E_NOT_STOPPED.

The Video Format dialog (VfwCaptureDialog_Format) may change the video format. If so, the method tries to reconnect the capture filter. If the downstream filter rejects the new format, the method returns VFW_E_CANNOT_CONNECT.

See Also

  • Error and Success Codes
  • IAMVfwCaptureDialogs Interface


IAMVfwCompressDialogs Interface

The IAMVfwCompressDialogs interface is implemented on the AVI Compressor filter. The interface enables an application to display a Video for Windows codec "Configure" or "About" dialog box and to set and retrieve compressor status.

In addition to the methods inherited from IUnknown, the IAMVfwCompressDialogs interface exposes the following methods.

Method | Description
ShowDialog | Displays the specified dialog box.
GetState | Retrieves the current configuration settings for the VCM codec currently being used.
SetState | Sets configuration for the VCM codec.
SendDriverMessage | Sends a driver-specific message.


IAMVfwCompressDialogs::GetState

The GetState method retrieves the current configuration settings for the VCM codec currently being used.

Syntax

HRESULT GetState(
  LPVOID pState,
  int *pcbState
);

Parameters

pState

[out] State of the VCM codec.

pcbState

[in, out] Pointer to the size of the state.

Return Values

Return value varies depending on the implementation within each driver.

Remarks

This method calls the COM ICGetState macro.

See Also

  • Error and Success Codes
  • IAMVfwCompressDialogs Interface


IAMVfwCompressDialogs::SendDriverMessage

The SendDriverMessage method sends a driver-specific message.

Syntax

HRESULT SendDriverMessage(
  int uMsg,
  long dw1,
  long dw2
);

Parameters

uMsg

[in] Message to send to the driver.

dw1

[in] Message data.

dw2

[in] Message data.

Return Values

Return value varies depending on the implementation within each driver.

Remarks

You should never need to use this method. This method can send any private message to the video compressor (codec). Behavior might be undetermined in response to arbitrary messages; use this method at your own risk.

This method calls the Video for Windows video compression manager (VCM) ICSendMessage function to send the message.

See Also

  • Error and Success Codes
  • IAMVfwCompressDialogs Interface


IAMVfwCompressDialogs::SetState

The SetState method sets configuration for the VCM codec.

Syntax

HRESULT SetState(
  LPVOID pState,
  int cbState
);

Parameters

pState

[in] State of the VCM codec.

cbState

[in] Size of the state.

Return Values

Return value varies depending on the implementation within each driver.

Remarks

This method calls the COM ICSetState macro, which notifies a video compression driver to set the state of the compressor.

See Also

  • Error and Success Codes
  • IAMVfwCompressDialogs Interface


IAMVfwCompressDialogs::ShowDialog

The ShowDialog method displays the specified dialog box.

Syntax

HRESULT ShowDialog(
  int iDialog,
  HWND hwnd
);

Parameters

iDialog

[in] Dialog box to display. This is a member of the VfwCompressDialogs enumeration.

hwnd

[in] Handle of the dialog box's parent window.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method returns an error when asked to display a dialog box while the driver is streaming or displaying another dialog box. While the driver displays the dialog box you can't stream (pause or run) the filter.

IAMVfwCompressDialogs::ShowDialog calls the Video for Windows video compression manager (VCM) functions ICConfigure, ICAbout, ICQueryConfigure, and ICQueryAbout to display the appropriate dialog box or determine if one exists.

The VfwCompressDialog_QueryConfig and VfwCompressDialog_QueryAbout members of the VfwCompressDialogs enumeration tell you whether or not the configure dialog or about dialog is available. If passed one of these flags, the filter will return S_OK if the dialog exists, and S_FALSE if it does not. If a dialog is available, you call ShowDialog with the value VfwCompressDialog_Config or VfwCompressDialog_About to bring up the dialog.

See Also

  • Error and Success Codes
  • IAMVfwCompressDialogs Interface


IAMVideoAccelerator Interface

The IAMVideoAccelerator interface enables a video decoder filter to access video accelerator functionality, including the functionality provided by DirectX Video Acceleration. The Video Mixing Renderer filter's input pins support this interface, and so does pin 0 on the Overlay Mixer. If a video decoder filter calls methods on this interface, the decoder should support the IAMVideoAcceleratorNotify interface on its output pin. Applications should not call methods on this interface. For more information on how to use this interface, see How Decoders Use IAMVideoAccelerator.

Note This interface is available in Microsoft® Windows® 2000 and later.

Requirements

Requires Videoacc.h.

In addition to the methods inherited from IUnknown, the IAMVideoAccelerator interface exposes the following methods.

Method | Description
GetVideoAcceleratorGUIDs | Retrieves a list of the GUIDs for the video accelerator formats accepted.
GetUncompFormatsSupported | Retrieves a list of pixel formats that can be used to render a specified video accelerator format.
GetInternalMemInfo | Retrieves information about the uncompressed data memory requirements, based on the video accelerator GUID, the uncompressed size, and the pixel format.
GetCompBufferInfo | Retrieves compressed buffer information.
GetInternalCompBufferInfo | Called after the pins are connected, retrieving compressed buffer information given the connected type.
BeginFrame | Begins frame processing.
EndFrame | Ends frame processing and passes miscellaneous data to the video accelerator driver.
GetBuffer | Retrieves the compressed buffer of a specified index and type.
ReleaseBuffer | Releases a compressed buffer after processing.
Execute | Performs a decompression operation.
QueryRenderStatus | Queries the processing status of a data buffer.
DisplayFrame | Displays a decoded frame.


IAMVideoAccelerator::GetVideoAcceleratorGUIDs

The GetVideoAcceleratorGUIDs method retrieves a list of the GUIDs for the video accelerator formats accepted.

Syntax

HRESULT GetVideoAcceleratorGUIDs(
  LPDWORD pdwNumGuidsSupported,
  LPGUID pGuidsSupported
);

Parameters

pdwNumGuidsSupported

[in] [out] If pGuidsSupported is NULL, pdwNumGuidsSupported returns with the number of video accelerator format GUIDs supported. Otherwise, this parameter is a pointer to the maximum number of GUIDs to return in pGuidsSupported. If fewer than this number are supported, pdwNumGuidsSupported is updated to be the number of GUIDs actually returned.

pGuidsSupported

[in] [out] If this parameter is not NULL, the GUIDs supported are returned in this array, whose size in bytes is at least sizeof(GUID) * (*pdwNumGuidsSupported).

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::GetUncompFormatsSupported

The GetUncompFormatsSupported method retrieves a list of pixel formats that can be used to render a specified video accelerator format.

Syntax

HRESULT GetUncompFormatsSupported(
  const GUID *pGuid,
  LPDWORD pdwNumFormatsSupported,
  LPDDPIXELFORMAT pFormatsSupported
);

Parameters

pGuid

[in] Pointer to a video accelerator GUID.

pdwNumFormatsSupported

[in] [out] If pFormatsSupported is NULL, pdwNumFormatsSupported returns with the number of pixel formats to which the video accelerator format, defined by pGuid, can be converted. Otherwise, this parameter is the number of pixel formats to return in pFormatsSupported. When the method returns, this parameter is the actual number of pixel formats returned.

pFormatsSupported

[in] [out] Pointer to a DDPIXELFORMAT structure. If this parameter is not NULL, up to *pdwNumFormatsSupported pixel formats are copied into this array. The size of the buffer should be at least *pdwNumFormatsSupported * sizeof(DDPIXELFORMAT).

Return Values

Returns S_OK when successful. Otherwise an error code is returned.

Note:The driver can return DDERR_MOREDATA if fewer than the total number of formats are requested. DDERR_MOREDATA is technically a failing HRESULT which will be caught by SUCCEEDED() or FAILED() macros but it isn't really a failure. The decoder must handle this result specially.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::GetInternalMemInfo

The GetInternalMemInfo method retrieves information about the uncompressed data memory requirements, based on the video accelerator GUID, the uncompressed size, and the pixel format.

Syntax

HRESULT GetInternalMemInfo(
  const GUID *pGuid,
  const AMVAUncompDataInfo *pamvaUncompDataInfo,
  LPAMVAInternalMemInfo pamvaInternalMemInfo
);

Parameters

pGuid

[in] Pointer to a video accelerator GUID.

pamvaUncompDataInfo

[in] Pointer to an AMVAUncompDataInfo structure containing the size and pixel format of the uncompressed data.

pamvaInternalMemInfo

[in, out] Pointer to an AMVAInternalMemInfo structure containing information on the scratch memory requirement.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::GetCompBufferInfo

The GetCompBufferInfo method retrieves compressed buffer information.

Syntax

HRESULT GetCompBufferInfo(
  const GUID *pGuid,
  const AMVAUncompDataInfo *pamvaUncompDataInfo,
  LPDWORD pdwNumTypesCompBuffers,
  LPAMVACompBufferInfo pamvaCompBufferInfo
);

Parameters

pGuid

[in] Pointer to a video accelerator format GUID.

pamvaUncompDataInfo

[in] Pointer to an AMVAUncompDataInfo structure containing the size and pixel format of the uncompressed data.

pdwNumTypesCompBuffers

[in] [out] Pointer to a variable of type DWORD. If pamvaCompBufferInfo is not NULL, this parameter receives the number of uncompressed buffer types. Otherwise, on input this parameter specifies the maximum number of compressed buffer types to return, and on output receives the actual number of compressed buffer types.

pamvaCompBufferInfo

[out] If non-NULL, then up to pdwNumTypesCompBuffers AMVACompBufferInfo structures are returned. This data includes the width, height, pixel format, and DirectDraw capabilities to be used to create the surface and the size in bytes the surface will occupy.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method returns the information necessary to create a video accelerator surface of the required type using DirectDraw. A video accelerator driver may support multiple compressed buffer types (for instance, video accelerator data and Inverse Discrete Cosine Transfer [IDCT] data).

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface
  • AMVACompBufferInfo Structure


IAMVideoAccelerator::GetInternalCompBufferInfo

The GetInternalCompBufferInfo method called after the pins are connected, retrieving compressed buffer information given the connected type.

Syntax

HRESULT GetInternalCompBufferInfo(
  LPDWORD pdwNumTypesCompBuffers,
  LPAMVACompBufferInfo pamvaCompBufferInfo
);

Parameters

pdwNumTypesCompBuffers

[in] [out] Pointer to a variable of type DWORD. If pamvaCompBufferInfo is not NULL, this parameter receives the number of uncompressed buffer types. Otherwise, on input this parameter specifies the maximum number of compressed buffer types to return, and on output receives the actual number of compressed buffer types.

pamvaCompBufferInfo

[out] If non-NULL, then up to pdwNumTypesCompBuffers AMVACompBufferInfo structures are returned. This data includes the width, height, pixel format, and DirectDraw capabilities to be used to create the surface and the size in bytes the surface will occupy.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

A video accelerator driver may support multiple compressed buffer types (for instance, video accelerator data and Inverse Discrete Cosine Transfer [IDCT] data.)

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface
  • AMVACompBufferInfo Structure


IAMVideoAccelerator::BeginFrame

The BeginFrame method begins frame processing.

Syntax

HRESULT BeginFrame(
  const AMVABeginFrameInfo *pamvaBeginFrameInfo
);

Parameters

pamvaBeginFrameInfo

[in] Pointer to an AMVABeginFrameInfo structure containing the information needed to begin processing the frame.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method can only be called after the pins are connected.

The AMVABeginFrameInfo structure contains an index to the destination buffer. Valid index values are from zero to dwActualUncompSurfacesAllocated–1), obtained by calling IAMVideoAcceleratorNotify::SetUncompSurfacesInfo.

The decoder should not make any assumption about the initial contents of the frame, as the frame memory used might not be the same as the memory last used with this frame index.

A call to this method might block operation processing if no non-busy frame buffer is available.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::EndFrame

The EndFrame method ends frame processing and passes miscellaneous data to the video accelerator driver.

Syntax

HRESULT EndFrame(
  const AMVAEndFrameInfo *pEndFrameInfo
);

Parameters

pEndFrameInfo

[in] Pointer to an AMVAEndFrameInfo structure containing miscellaneous data for the video accelerator driver.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

See Remarks for BeginFrame.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::GetBuffer

The GetBuffer method retrieves the compressed buffer of a specified index and type.

Syntax

HRESULT GetBuffer(
  DWORD dwTypeIndex,
  DWORD dwBufferIndex,
  BOOL bReadOnly,
  LPVOID *ppBuffer,
  LONG *lpStride
);

Parameters

dwTypeIndex

[in] Zero-based index into the surface types supported by the video accelerator driver, or 0xFFFFFFFF. See Remarks.

dwBufferIndex

[in] Buffer index within the type. The valid range is from zero to the value of the dwNumCompBuffers member of the AMVACompBufferInfo structure.

bReadOnly

[in] Boolean value indicating whether the buffer will be updated. If TRUE, the buffer will not be updated, allowing access to busy reference frames.

ppBuffer

[out] Pointer to the buffer that will contain the compressed data. The size of this buffer is determined by the dwBytesToAllocate member of the AMVACompBufferInfo structure returned for the dwSurfaceTypeIndex entry from the IAMVideoAccelerator::GetInternalCompBufferInfo method.

lpStride

[out] Stride compatible with the compression type. Generally, this will be equal to the dwWidthToCreate member of the AMVACompBufferInfo structure. Note that this might not be equal to dwWidthToCreate for output display buffers or other uncompressed types.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method locks and obtains access to a single buffer. Buffers are identified by type and by index within that type. The IAMVideoAccelerator::GetInternalCompBufferInfo method returns the number of types in its pdwNumTypesCompBuffers parameter, which defines the valid range for dwTypeIndex. For each type, the dwNumCompBuffers member of the AMVACompBufferInfo structure gives the number of buffers, which defines the valid range for dwBufferIndex. Note that dwTypeIndex and dwBufferIndex both specify zero-based offsets.

Alternatively, use a type index of 0xFFFFFFFF to retrieve a pointer to an output buffer. Currently, this is only valid between calls to IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame. In this case the buffer index must equal the dwDestSurfaceIndex member of the AMVABeginFrameInfo structure that was passed to the last BeginFrame call.

This method will fail if the filter's pins are not connected.

Until all compressed buffers are released, it is possible that this thread will hold the Win16 lock or the DirectDraw lock.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::ReleaseBuffer

The ReleaseBuffer method releases a compressed buffer after processing.

Syntax

HRESULT ReleaseBuffer(
  DWORD dwTypeIndex,
  DWORD dwBufferIndex
);

Parameters

dwTypeIndex

[in] Zero-based index into the surface types supported by the video accelerator driver, or 0xFFFFFFFF.

dwBufferIndex

[in] Buffer index within the type. The valid range is from zero to the value of the dwNumCompBuffers member of the AMVACompBufferInfo structure.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after the pins are connected. Calling this method unlocks a single buffer. The video decoder calls this method when the buffer is no longer required and after any calls to Execute have been made. Note that the buffer pointer is no longer valid after this call.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::Execute

The Execute method performs a decompression operation.

Syntax

HRESULT Execute(
  DWORD dwFunction,
  LPVOID lpPrivateInputData,
  DWORD cbPrivateInputData,
  LPVOID lpPrivateOutputData,
  DWORD cbPrivateOutputData,
  DWORD dwNumBuffers,
  const AMVABUFFERINFO *pamvaBufferInfo
);

Parameters

dwFunction

[in] Function number. This can be zero if this argument is the default or is ignored.

lpPrivateInputData

[in] Pointer to private input data passed to the driver.

cbPrivateInputData

[in] Length of private input data.

lpPrivateOutputData

[in] Pointer to private output data passed to the driver.

cbPrivateOutputData

[in] Length of private data buffer.

dwNumBuffers

[in] Number of AMVABUFFERINFO structures.

pamvaBufferInfo

[in] Pointer to a list of AMVABUFFERINFO structures to be passed.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after the pins are connected.

The associated buffer list is passed along with a function number (defaulting to zero) and any necessary private data describing the decompression operation. For example, decompressed reference frame information is passed in the buffer list. The buffer list order is important and is defined by the particular decompression operation being performed.

Private data can be passed to and from a driver.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface
  • AMVABUFFERINFO Structure


IAMVideoAccelerator::QueryRenderStatus

The QueryRenderStatus method queries the processing status of a data buffer.

Syntax

HRESULT QueryRenderStatus(
  DWORD dwTypeIndex,
  DWORD dwBufferIndex,
  DWORD dwFlags
);

Parameters

dwTypeIndex

[in] Type index for buffer to be tested.

dwBufferIndex

[in] Buffer index for buffer to be tested.

dwFlags

[in] Flag indicating the type of query to perform. If zero, this method tests whether the surface is safe to use for updates. If AMVA_QUERYRENDERSTATUSF_READ, this method tests whether the surface is safe to use for reading.

Return Values

Returns an HRESULT value. Returns S_OK if the operation is complete; returns E_PENDING if the operation is still in progress. If the operation failed, this method returns another failure code, which can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method will report progress and failures.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAccelerator::DisplayFrame

The DisplayFrame method displays a decoded frame.

Syntax

HRESULT DisplayFrame(
  DWORD dwFlipToIndex,
  IMediaSample *pMediaSample
);

Parameters

dwFlipToIndex

[in] The surface index of the decompressed frame to display.

pMediaSample

[in] Pointer to an IMediaSample interface containing start and stop time stamps.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after all pins are connected. This call is non-blocking.

The video decoder invokes this method after calling IAMVideoAccelerator::EndFrame for the surface whose index is dwFlipToIndex. This index must have previously been the value of the dwDestSurfaceIndex member in the AMVABeginFrameInfo structure passed in a call to IAMVideoAccelerator::BeginFrame.

See Also

  • Error and Success Codes
  • IAMVideoAccelerator Interface


IAMVideoAcceleratorNotify Interface

The IAMVideoAcceleratorNotify interface is supported by the video decoder's output pin. The methods are called during pin connection with the downstream Video Mixing Renderer or Overlay Mixer filter to set up the IAMVideoAccelerator interface.

Note This interface is available in Microsoft® Windows® 2000.

Requirements

Requires Videoacc.h.

In addition to the methods inherited from IUnknown, the IAMVideoAcceleratorNotify interface exposes the following methods.

Method | Description
GetUncompSurfacesInfo | Retrieves the decompressed buffer information for a given video accelerator GUID.
SetUncompSurfacesInfo | Sets the uncompressed buffer information.
GetCreateVideoAcceleratorData | Retrieves the information needed to create a video accelerator object.


IAMVideoAcceleratorNotify::GetUncompSurfacesInfo

The GetUncompSurfacesInfo method retrieves the decompressed buffer information for a given video accelerator GUID.

Syntax

HRESULT GetUncompSurfacesInfo(
  const GUID *pGuid,
  LPAMVAUncompBufferInfo pUncompBufferInfo
);

Parameters

pGuid

[in] Pointer to a GUID identifying the video accelerator for which information is returned.

pUncompBufferInfo

[in, out] Pointer to a AMVAUncompBufferInfo structure containing uncompressed surface information.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method returns the video decoder's requirements for the minimum and maximum number of surfaces, as well as the pixel format. This method provides information necessary to allocate uncompressed data buffers.

See Also

  • Error and Success Codes
  • IAMVideoAcceleratorNotify Interface


IAMVideoAcceleratorNotify::SetUncompSurfacesInfo

The SetUncompSurfacesInfo method sets the uncompressed buffer information.

Syntax

HRESULT SetUncompSurfacesInfo(
  DWORD  dwActualUncompSurfacesAllocated
);

Parameters

dwActualUncompSurfacesAllocated

[in] The number of surfaces allocated.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method tells the video decoder how many decompressed surfaces are actually allocated.

See Also

  • Error and Success Codes
  • IAMVideoAcceleratorNotify Interface


IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData

The GetCreateVideoAcceleratorData method retrieves the information needed to create a video accelerator object.

Syntax

HRESULT GetCreateVideoAcceleratorData(
  const GUID *pGuid,
  LPWDORD pdwSizeMiscData,
  LPVOID *ppMiscData
);

Parameters

pGuid

[in] Pointer to a GUID identifying the video accelerator.

pdwSizeMiscData

[out] Pointer to a variable that receives the size of the data returned in ppMiscData, in bytes.

ppMiscData

[out] Address to a pointer of type void that receives the miscellaneous data (or NULL if pdwSizeMiscData is 0). This pointer should be allocated with CoTaskMemAlloc, a helper function from the COM library. It is freed by the caller. See Remarks.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method retrieves a pointer to any miscellaneous data that the video decoder needs to send to the video accelerator driver when the video accelerator is initialized. It is the caller's responsibility to call CoTaskMemFree on ppMiscData.

See Also

  • Error and Success Codes
  • IAMVideoAcceleratorNotify Interface


IAMVideoCompression Interface

The IAMVideoCompression interface sets and retrieves video compression properties. It is supported by some video compression filters, and also by some video capture filters that output compressed video. Filters that support this interface expose it through their output pins.

An application can use this interface to control how video is compressed, including characteristics such as the key-frame rate or the compression quality.

A filter that supports this interface might not support every method. Use the IAMVideoCompression::GetInfo method to determine which methods the filter supports.

Note To use this interface on a capture filter, you might need to connect the filter to another filter in the graph.

In addition to the methods inherited from IUnknown, the IAMVideoCompression interface exposes the following methods.

Method | Description
put_KeyFrameRate | Sets the key-frame rate.
get_KeyFrameRate | Retrieves the key-frame rate.
put_PFramesPerKeyFrame | Sets the predicted (P) frame frequency.
get_PFramesPerKeyFrame | Retrieves the P frame frequency.
put_Quality | Sets the compression quality.
get_Quality | Retrieves the compression quality.
put_WindowSize | Sets the number of frames over which the compressor must maintain an average data rate.
get_WindowSize | Retrieves the number of frames over which the compressor must maintain an average data rate.
GetInfo | Retrieves information about the filter's compression properties, including capabilities and default values.
OverrideKeyFrame | Forces a particular frame to be a key frame.
OverrideFrameSize | Overrides a particular frame's data rate.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_VIDEOCOMPRESSION property set. For more information, see the Windows DDK documenation.


IAMVideoCompression::GetInfo

The GetInfo method retrieves information about the filter's compression properties, including capabilities and default values.

Syntax

HRESULT GetInfo(
  WCHAR *pszVersion,
  int *pcbVersion,
  LPWSTR pszDescription,
  int *pcbDescription,
  long *pDefaultKeyFrameRate,
  long *pDefaultPFramesPerKey,
  double *pDefaultQuality,
  long *pCapabilities
) PURE;

Parameters

pszVersion

[out] Pointer to a buffer that receives a version string, such as "Version 2.1.0."

pcbVersion

[in, out] Pointer to a variable that receives the size of the version string, in bytes.

pszDescription

[out] Pointer to a buffer that receives a description string, such as "My Video Compressor."

pcbDescription

[in, out] Pointer to a variable that receives the size of the description string.

pDefaultKeyFrameRate

[out] Pointer to a variable that receives the default key-frame rate.

pDefaultPFramesPerKey

[out] Pointer to a variable that receives the default rate of predicted (P) frames per key frame.

pDefaultQuality

[out] Pointer to a variable that receives the default quality.

pCapabilities

[out] Pointer to a variable that receives the compression capabilities, as a bitwise combination of zero or more CompressionCaps flags.

Return Values

Returns an HRESULT value.

Remarks

Any of the listed parameters can be NULL, in which case the method ignores that parameter.

The application must allocate the buffers for the version and description strings. To determine the required size of the buffers, call this method with NULL for the pszVersion and pszDescription parameters. Use the values returned in pcbVersion and pcbDescription to allocate the buffers and then call the method again, as shown in the following code:

int cbVersion, cbDesc; // Size in bytes, not characters!
hr = pCompress->GetInfo(0, &cbVersion, 0, &cbDesc, 0, 0, 0, 0);
if (SUCCEEDED(hr))
{
    WCHAR *pszVersion = new WCHAR[cbVersion/2];  // Wide character = 2 bytes
    WCHAR *pszDesc = new WCHAR[cbDesc/2];
    if (pszVersion && pszDesc)
    {
        hr = pCompress->GetInfo(pszVersion, 0, pszDesc, 0, 0, 0, 0, 0);
    }
    delete [] pszVersion;
    delete [] pszDesc;
}

Note that the strings are wide-character strings, and the returned sizes are in bytes, not number of characters. Also, one or both strings might be zero-length.

The pCapabilities parameter receives a set of flags indicating which compression properties are supported, and thus which IAMVideoCompression methods are supported. For example, if the CompressionCaps_CanKeyFrame flag is returned, it the filter supports the IAMVideoCompression::get_KeyFrameRate and IAMVideoCompression::put_KeyFrameRate methods.

The remaining parameters receive default values for the compression properties. For unsupported properties (as determined by the flags returned in pCapabilities), you should ignore the corresponding default value, as it may not be correct or meaningful.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface


IAMVideoCompression::get_KeyFrameRate

The get_KeyFrameRate method retrieves the current key-frame rate.

Syntax

get_KeyFrameRate(
  long *pKeyFrameRate
);

Parameters

pKeyFrameRate

[out] Pointer to a variable that receives the current key-frame rate. If the value is negative, the filter will use the default key-frame rate. If the value is zero, only the first frame is a key frame.

Return Values

Returns an HRESULT value.

Remarks

The key-frame rate is the number of frames per key frame. For example, if the rate is 15, then a key frame occurs every 15 frames.

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanKeyFrame flag in the pCapabilities parameter. The GetInfo method also returns the default key-frame rate.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::put_KeyFrameRate


IAMVideoCompression::get_PFramesPerKeyFrame

The get_PFramesPerKeyFrame method retrieves the rate of predicted (P) frames per key frame.

Syntax

HRESULT get_PFramesPerKeyFrame(
  long *pPFramesPerKeyFrame
);

Parameters

pPFramesPerKeyFrame

[out] Pointer to a variable that receives the number of P frames per key frame. If the value is negative, the filter will use the default rate.

Return Values

Returns an HRESULT value.

Remarks

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanBFrame flag in the pCapabilities parameter. The GetInfo method also returns the default P-frame rate.

P frames are used in MPEG compression; in general, this property does not apply to other compression formats. For example, suppose a key frame occurs once every 10 frames, and there are three P frames per key frame. The P frames will be spaced evenly between the key frames. The remaining six frames are bidirectional (B) frames.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::put_KeyFrameRate


IAMVideoCompression::get_Quality

The get_Quality method retrieves the current compression quality.

Syntax

HRESULT get_Quality(
  double *pQuality
);

Parameters

pQuality

[out] Pointer to a variable that receives the relative compression quality. The quality is expressed as a value between 0.0 and 1.0, where 1.0 indicates the best quality and 0.0 indicates the worst quality. If the value is negative, the filter will use the default quality.

Return Values

Returns an HRESULT value.

Remarks

The exact meaning of the quality setting depends on the filter.

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanQuality flag in the pCapabilities parameter. The GetInfo method also returns the default quality.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::put_Quality


IAMVideoCompression::get_WindowSize

The get_WindowSize method retrieves the number of frames over which the compressor will maintain the average data rate.

For example, assuming a data rate of 100K/sec and a frame rate of 10 frames per second, if the window size is 1, then every frame will be 10K or less. If the window size is 5, then every five consecutive frames will average 10K per frame, but individual frames may exceed this size.

The default window size is 1.

Syntax

HRESULT get_WindowSize(
  DWORDLONG *pWindowSize
);

Parameters

pWindowSize

[out] Pointer to a variable that receives the window size, expressed as a number of frames.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::put_WindowSize


IAMVideoCompression::OverrideFrameSize

The OverrideFrameSize method overrides the frame size of a specified frame.

Syntax

HRESULT OverrideFrameSize(
  long FrameNumber,
  long Size
);

Parameters

FrameNumber

[in] Specifies the frame number. The first frame that the filter delivers is numbered zero.

Size

[in] Specifies the maximum size of the specified frame, in bytes.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

If the filter supports this method, the IAMVideoCompression::GetInfo method will return the CompressionCaps_CanCrunch flag in the pCapabilities parameter. However, this flag can also indicate that the filter supports setting the bit rate, so it does not guarantee that the OverrideFrameSize method is supported.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • CompressionCaps Enumeration


IAMVideoCompression::OverrideKeyFrame

The OverrideKeyFrame method instructs the filter to compress a particular frame as a key frame.

Syntax

HRESULT OverrideKeyFrame(
  long FrameNumber
);

Parameters

FrameNumber

[in] Specifies the frame number. The first frame that the filter delivers is numbered zero.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

If the filter supports this method, you can use it to override the normal key-frame distribution for a particular frame. After the filter creates a key frame, it might reset its count to determine when the next key frame should occur. For example, if the key-frame rate is 10, and an application uses this method to force frame 5 as a key frame, the filter might wait another 10 frames (until frame 15) before it creates the next key frame.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface


IAMVideoCompression::put_KeyFrameRate

The put_KeyFrameRate method sets the key-frame rate.

Syntax

HRESULT put_KeyFrameRate(
  long KeyFrameRate
);

Parameters

KeyFrameRate

[in] Desired key-frame rate. If the value is negative, the filter will use the default key-frame rate. If the value is zero, only the first frame will be a key frame.

Return Values

Returns an HRESULT value.

Remarks

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanKeyFrame flag in the pCapabilities parameter. The GetInfo method also returns the default key-frame rate.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::get_KeyFrameRate


IAMVideoCompression::put_PFramesPerKeyFrame

The put_PFramesPerKeyFrame method sets the rate of predicted (P) frames per key frame.

Syntax

HRESULT put_PFramesPerKeyFrame(
  long PFramesPerKeyFrame
);

Parameters

PFramesPerKeyFrame

[in] Specifies the number of P frames per key frame. If the value is negative, the filter will use the default rate.

Return Values

Returns an HRESULT value.

Remarks

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanBFrame flag in the pCapabilities parameter. The GetInfo method also returns the default P-frame rate.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::get_PFramesPerKeyFrame


IAMVideoCompression::put_Quality

The put_Quality method sets the compression quality.

Syntax

HRESULT put_Quality(
  double Quality
);

Parameters

Quality

[in] Specifies the quality as a value between 0.0 and 1.0, where 1.0 indicates the best quality and 0.0 indicates the worst quality. If the value is negative, the filter will use the default quality.

Return Values

Returns an HRESULT value.

Remarks

To determine if the filter supports this method, call the IAMVideoCompression::GetInfo method and check for the CompressionCaps_CanQuality flag in the pCapabilities parameter. The GetInfo method also returns the default quality.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::get_Quality


IAMVideoCompression::put_WindowSize

The put_WindowSize method sets the number of frames over which the compressor must maintain an average data rate.

For example, assuming a data rate of 100K/sec and a frame rate of 10 frames per second, if the window size is 1, then every frame will be 10K or less. If the window size is 5, then every five consecutive frames must average 10K per frame, but individual frames may exceed this size.

Syntax

HRESULT put_WindowSize(
  DWORDLONG WindowSize
);

Parameters

WindowSize

[in] Specifies the window size, expressed as a number of frames. .

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IAMVideoCompression Interface
  • IAMVideoCompression::get_WindowSize


IAMVideoControl Interface

The IAMVideoControl interface enables you to flip a picture horizontally and/or vertically, set up a stream so it can capture from an external trigger (such as a camera button that the user pushes), simulate an external trigger in software, and list the available frame rates.

Use this interface when your application runs on hardware that is capable of flipping and external triggering.

In addition to the methods inherited from IUnknown, the IAMVideoControl interface exposes the following methods.

Method | Description
GetCaps | Retrieves the capabilities of the underlying hardware.
SetMode | Sets the video control mode of operation.
GetMode | Retrieves the video control mode of operation.
GetCurrentActualFrameRate | Retrieves the actual frame rate at which the device is streaming. This method is used with devices, such as the Universal Serial Bus (USB) or cameras that use the IEEE 1394 serial standard, where the maximum frame rate can be limited by bandwidth availability. This is only available during video streaming.
GetMaxAvailableFrameRate | Retrieves the maximum frame rate currently available based on bus bandwidth usage for connections such as USB and IEEE 1394 camera devices where the maximum frame rate can be limited by bandwidth availability.
GetFrameRateList | Retrieves a list of available frame rates.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_VIDEOCONTROL property set. For more information, see the Windows DDK documenation.


IAMVideoControl::GetCaps

The GetCaps method retrieves the capabilities of the underlying hardware.

Syntax

HRESULT GetCaps (
  IPin *pPin,
  long *pCapsFlags
);

Parameters

pPin

[in] Pointer to the pin to query capabilities from.

pCapsFlags

[out] Pointer to a value representing a combination of the flags from the VideoControlFlags enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible capabilities include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface


IAMVideoControl::GetCurrentActualFrameRate

The GetCurrentActualFrameRate method retrieves the actual frame rate, expressed as a frame duration in 100-nanosecond units. USB (Universal Serial Bus) and IEEE 1394 cameras may provide lower frame rates than requested because of bandwidth availability. This is only available during video streaming.

Syntax

HRESULT GetCurrentActualFrameRate (
  IPin *pPin,
  LONGLONG *ActualFrameRate
);

Parameters

pPin

[in] Pointer to the pin to retrieve the frame rate from.

ActualFrameRate

[out] Pointer to the frame rate in frame duration in 100-nanosecond units.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface


IAMVideoControl::GetFrameRateList

The GetFrameRateList method retrieves a list of available frame rates.

Syntax

HRESULT GetFrameRateList (
  IPin *pPin,
  long iIndex,
  SIZE Dimensions,
  long *ListSize,
  LONGLONG **FrameRates
);

Parameters

pPin

[in] Pointer to the pin to query for the list of frame rates.

iIndex

[in] Index of the format to query for frame rates. This index corresponds to the order in which formats are enumerated by IAMStreamConfig::GetStreamCaps. The value must range between zero and the number of supported VIDEO_STREAM_CONFIG_CAPS structures returned by IAMStreamConfig::GetNumberOfCapabilities) minus one.

Dimensions

[in] Frame image size (width and height) in pixels.

ListSize

[out] Pointer to the number of elements in the list of frame rates.

FrameRates

[out] Address of a pointer to an array of frame rates in 100-nanosecond units. Can be NULL if you only need ListSize.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The caller is responsible for freeing the memory through a call to CoTaskMemFree.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface
  • VIDEO_STREAM_CONFIG_CAPS Structure


IAMVideoControl::GetMaxAvailableFrameRate

The GetMaxAvailableFrameRate method retrieves the maximum frame rate currently available, based on bus bandwidth usage for connections, such as USB and IEEE 1394, where the maximum frame rate may be limited by bandwidth availability.

Syntax

HRESULT GetMaxAvailableFrameRate(
  IPin *pPin,
  long iIndex,
  SIZE Dimensions,
  LONGLONG *MaxAvailableFrameRate
);

Parameters

pPin

[in] Pointer to the pin to retrieve the maximum frame rate from.

iIndex

[in] Index of the format to query for maximum frame rate. This index corresponds to the order in which formats are enumerated by IAMStreamConfig::GetStreamCaps. The value must range between zero and the number of supported VIDEO_STREAM_CONFIG_CAPS structures returned by IAMStreamConfig::GetNumberOfCapabilities) minus one.

Dimensions

[in] Frame image size (width and height) in pixels.

MaxAvailableFrameRate

[out] Pointer to the maximum available frame rate. The frame rate is expressed as frame duration in 100-nanosecond units.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface
  • VIDEO_STREAM_CONFIG_CAPS Structure


IAMVideoControl::GetMode

The GetMode method retrieves the video control mode of operation.

Syntax

HRESULT GetMode (
  IPin *pPin,
  long *Mode
);

Parameters

pPin

[in] Pointer to the pin to retrieve the video control mode from.

Mode

[out] Pointer to a value representing a combination of the flags from the VideoControlFlags enumeration, which specify the video control mode.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible modes of operation include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface


IAMVideoControl::SetMode

The SetMode method sets the video control mode of operation.

Syntax

HRESULT SetMode (
  IPin *pPin,
  long Mode
);

Parameters

pPin

[in] Pointer to the pin to set the video control mode on.

Mode

[in] Value specifying a combination of the flags from the VideoControlFlags enumeration to set the video control mode.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible modes of operation include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.

See Also

  • Error and Success Codes
  • IAMVideoControl Interface


IAMVideoDecimationProperties Interface

The IAMVideoDecimationProperties interface enables an application to control where video decimation occurs. The Overlay Mixer filter implements this interface.

If a video window is smaller than the native size of the video being displayed, the video renderer must decimate the incoming video—that is, scale the video down to the smaller size. Decimation can be performed in one of the following places.

  • The overlay hardware on the VGA chip.
  • The scaler built in to the video port (if the connection is through a video port).
  • The decoder supplying video to the renderer.

An application can call methods on this interface to select a particular decimation strategy, in order to optimize performance. However, most applications will have no occasion to use this interface. Unless your application is designed to support particular hardware, there is no reason to modify the Overlay Mixer filter's default behavior for decimation.

In addition to the methods inherited from IUnknown, the IAMVideoDecimationProperties interface exposes the following methods.

Method | Description
QueryDecimationUsage | Retrieves the current decimation strategy.
SetDecimationUsage | Sets the decimation strategy.


IAMVideoDecimationProperties::QueryDecimationUsage

The QueryDecimationUsage method retrieves the current decimation strategy.

Syntax

HRESULT QueryDecimationUsage(
  DECIMATION_USAGE *lpUsage
);

Parameters

lpUsage

[out] Pointer to a variable of type DECIMATION_USAGE that receives the decimation setting.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns S_OK if successful, or E_FAIL or another error code otherwise.

See Also

  • Error and Success Codes
  • IAMVideoDecimationProperties Interface


IAMVideoDecimationProperties::SetDecimationUsage

The SetDecimationUsage method sets the decimation strategy.

Syntax

HRESULT SetDecimationUsage(
  DECIMATION_USAGE Usage
);

Parameters

Usage

[in] Member of the DECIMATION_USAGE enumeration that specifies the decimation strategy.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns S_OK if successful, or E_INVALIDARG otherwise.

See Also

  • Error and Success Codes
  • IAMVideoDecimationProperties Interface


IAMVideoProcAmp Interface

The IAMVideoProcAmp interface enables an application to adjust the qualities of an incoming video signal, such as brightness, contrast, hue, saturation, gamma, and sharpness.

The WDM Video Capture filter exposes this interface if the hardware supports image adjustment.

In addition to the methods inherited from IUnknown, the IAMVideoProcAmp interface exposes the following methods.

Method | Description
GetRange | Retrieves minimum, maximum, and default values for setting properties.
Set | Sets video quality for a specified property.
Get | Retrieves video quality for a specified property.

Remarks

For Windows Driver Model (WDM) devices, the WDM Video Capture Filter automatically exposes this interface if the WDM driver supports the PROPSETID_VIDCAP_VIDEOPROCAMP property set. For more information, see the Windows DDK documenation.


IAMVideoProcAmp::Get

The Get method retrieves retrieves the current setting of a video property.

Syntax

HRESULT Get(
  long Property,
  long *lValue,
  long *Flags
);

Parameters

Property

[in] Specifies the property to retrieve, as a value from the VideoProcAmpProperty enumeration.

lValue

[out] Pointer to a variable that receives the value of the property.

Flags

[out] Pointer to a variable that receives a member of the VideoProcAmpFlags enumeration. The returned value indicates whether the setting is controlled manually or automatically.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | No error.
E_POINTER | Null pointer argument.

See Also

  • Error and Success Codes
  • IAMVideoProcAmp Interface
  • IAMVideoProcAmp::Set


IAMVideoProcAmp::GetRange

The GetRange method retrieves retrieves the range and default value of a specified video property.

Syntax

HRESULT GetRange(
  long Property,
  long *pMin,
  long *pMax,
  long *pSteppingDelta,
  long *pDefault,
  long *pCapsFlags
);

Parameters

Property

[in] Specifies the property to query, as a value from the VideoProcAmpProperty enumeration.

pMin

[out] Pointer to a variable that receives the minimum value of the property.

pMax

[out] Pointer to a variable that receives the maximum value of the property.

pSteppingDelta

[out] Pointer to a variable that receives the step size for the property. The step size is the smallest increment by which the property can change.

pDefault

[out] Pointer to a variable that receives the default value of the property.

pCapsFlags

[out] Pointer to a variable that receives a member of the VideoProcAmpFlags enumeration, indicating whether the property is controlled automatically or manually.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
E_PROP_ID_UNSUPPORTED | The device does not support this property.
S_OK | No error.

See Also

  • Error and Success Codes
  • IAMVideoProcAmp Interface


IAMVideoProcAmp::Set

The Set method sets video quality for a specified property.

Syntax

HRESULT Set(
  long Property,
  long lValue,
  long Flags
);

Parameters

Property

[in] Specifies the property to set, as a value from the VideoProcAmpProperty enumeration.

lValue

[in] Specifes the new value of the property.

Flags

[in] Specifies the desired control setting, as a member of the VideoProcAmpFlags enumeration

Return Values

If the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

If the pCapsFlags parameter is VideoProcAmp_Flags_Auto, the method ignores the lValue parameter.

See Also

  • Error and Success Codes
  • IAMVideoProcAmp Interface
  • IAMVideoProcAmp::Get


IAMWstDecoder Interface

Use the IAMWstDecoder interface to work with the World Standard Teletext (WST) decoder.

In addition to the methods inherited from IUnknown, the IAMWstDecoder interface exposes the following methods.

Method | Description
GetAnswerMode | Retrieves whether hidden text is exposed or not.
GetBackgroundColor | Retrieves the current physical color used in color keying the background for overlay mixing.
GetCurrentPage | Retrieves the current WST page.
GetCurrentService | Retrieves the current WST service.
GetDecoderLevel | Retrieves the WST decoder level.
GetDrawBackgroundMode | Determines whether the caption text background is opaque or transparent.
GetHoldPage | Determines whether the current WST page is held by the WST decoder.
GetOutputFormat | Retrieves the current output video format.
GetRedrawAlways | Retrieves whether the whole output bitmap should be redrawn for each sample.
GetServiceState | Retrieves whether closed captioning is on or off.
SetAnswerMode | Assigns whether hidden text is exposed or not.
SetBackgroundColor | Assigns the current physical color used in color keying the background for overlay mixing.
SetCurrentPage | Assigns the current WST page.
SetDrawBackgroundMode | Assigns the caption text background to be opaque or transparent.
SetHoldPage | Instructs the WST decoder to hold the current page.
SetOutputFormat | Assigns an output video format.
SetRedrawAlways | Sets whether the whole output bitmap should be redrawn for each sample.
SetServiceState | Sets closed captioning on or off.


IAMWstDecoder::GetAnswerMode

Downstream filters use the GetAnswerMode method to retrieve the current answer mode.

Syntax

HRESULT GetAnswerMode(
  BOOL*  pbAnswer
);

Parameters

pbAnswer

[out] Specifies a pointer to a BOOL to receive the current answer mode.

Value | Description
TRUE | Hidden text exposed.
FALSE | Hidden text not exposed.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetBackgroundColor

Downstream filters use the GetBackgroundColor method to retrieve the current physical color used in color keying the background for overlay mixing.

Syntax

HRESULT GetBackgroundColor(
  DWORD*  pdwPhysColor
);

Parameters

pdwPhysColor

[out] Specifies a pointer to a DWORD to receive the physical color as an RGB value.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetCurrentPage

Downstream filters use the GetCurrentPage method to retrieve the current WST page.

Syntax

HRESULT GetCurrentPage(
  AM_WST_PAGE  *pWstPage
);

Parameters

pWstPage

[out] Specifies a pointer to an AM_WST_PAGE structure to receive the current page.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetCurrentService

Applications use the GetCurrentService method to retrieve the current WST service.

Syntax

HRESULT GetCurrentService(
  AM_WST_SERVICE*  lpService
);

Parameters

lpService

[out] Specifies a pointer to an AM_WST_SERVICE enumeration to receive the service currently being used.

Value | Description
AM_WST_SERVICE_None | No service is currently available.
AM_WST_SERVICE_Text | The service is providing text.
AM_WST_SERVICE_IDS | The service is providing IDS data.
AM_WST_SERVICE_Invalid | The service is invalid.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetDecoderLevel

Applications use the GetDecoderLevel method to retrieve the WST decoder level. This method is not implemented and always returns AM_WST_LEVEL_1_5.

Syntax

HRESULT GetDecoderLevel(
  AM_WST_LEVEL*  lpLevel
);

Parameters

lpLevel

[out] Address of a variable that receives a member of the AM_WST_LEVEL enumeration, indicting the decoder level.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetDrawBackgroundMode

Downstream filters use the GetDrawBackgroundMode method to determine whether the caption text background is opaque or transparent.

Syntax

HRESULT GetDrawBackgroundMode(
  AM_WST_DRAWBGMODE*  lpMode
);

Parameters

lpMode

[out] Pointer to a variable that receives a member of the AM_WST_DRAWBGMODE enumeration. This parameter receives one of the following values.

Value | Description
AM_WST_DRAWBGMODE_Opaque | Caption text background is opaque.
AM_WST_DRAWBGMODE_Transparent | Caption text background is transparent.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetHoldPage

Downstream filters use the GetHoldPage method to determine whether the current WST page is held. When the WST decoder holds a page, any updates from the TV stream are turned off. It is though the page was paused in real time.

Syntax

HRESULT GetHoldPage(
  BOOL*  pbHoldPage
);

Parameters

pbHoldPage

[out] Pointer to a BOOL to receive the status of the WST page.

Value | Description
TRUE | The current page is held.
FALSE | The current page is not held.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetOutputFormat

Downstream filters use the GetOutputFormat method to retrieve the size, bit depth, and other parameters of the output video.

Syntax

HRESULT GetOutputFormat(
  LPBITMAPINFOHEADER  lpbmih
);

Parameters

lpbmih

[out] Specifies a LPBITMAPINFOHEADER structure to receive the size, bit depth, and other properties of the output video.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetRedrawAlways

Downstream filters use the GetRedrawAlways method to retrieve a value that indicates whether the whole output bitmap is redrawn for each sample.

Syntax

HRESULT GetRedrawAlways(
  LPBOOL  lpbOption
);

Parameters

lpbOption

[out] Pointer to a BOOL to receive the redraw-always value.

Value | Description
TRUE | Redraw the whole output bitmap for each sample.
FALSE | Do not redraw the whole output bitmap for each sample.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::GetServiceState

Applications use the GetServiceState method to retrieve the current service state.

Syntax

HRESULT GetServiceState
  AM_WST_STATE*  lpState
);

Parameters

lpState

[out] Pointer to a variable that receives the state, specified as a member of the AM_WST_STATE enumeration. The following values are possible.

Value | Description
AM_WST_STATE_On | The WST service is on.
AM_WST_STATE_Off | The WST service is off.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetAnswerMode

Downstream filters use the SetAnswerMode method to assign the current answer mode.

Syntax

HRESULT SetAnswerMode(
  BOOL  bAnswer
);

Parameters

bAnswer

[in] Specifies a BOOL to assign the current answer mode.

Value | Description
TRUE | Hidden text exposed.
FALSE | Hidden text not exposed.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetBackgroundColor

Downstream filters use the SetBackgroundColor method to assign the physical color to be used in color keying the background for overlay mixing.

Syntax

HRESULT SetBackgroundColor(
  DWORD  dwPhysColor
);

Parameters

dwPhysColor

[in] Specifies a DWORD containing the physical color.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetCurrentPage

Downstream filters use the SetCurrentPage method to assign the current page.

Syntax

HRESULT SetCurrentPage(
  AM_WST_PAGE  WstPage
);

Parameters

WstPage

[in] Specifies an AM_WST_PAGE structure that is used to assign the current page.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetDrawBackgroundMode

Downstream filters use the SetDrawBackgroundMode method to assign whether the caption text background is to be opaque or transparent.

Syntax

HRESULT SetDrawBackgroundMode(
  AM_WST_DRAWBGMODE  Mode
);

Parameters

Mode

[in] Specifies an AM_WST_DRAWBGMODE enumeration to assign whether the caption text background is to be opaque or transparent.

Value | Description
AM_WST_DRAWBGMODE_Opaque | Caption text background is opaque.
AM_WST_DRAWBGMODE_Transparent | Caption text background is transparent.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetHoldPage

Downstream filters use the SetHoldPage method to tell the WST decoder to hold the current WST page. When the WST decoder holds a page, any updates from the TV stream are turned off. It is as though the page was paused in real time.

Syntax

HRESULT SetHoldPage(
  BOOL  bHoldPage
);

Parameters

bHoldPage

[in] Specifies whether to hold the current page.

Value | Description
TRUE | Hold the current page.
FALSE | Release the current page.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetOutputFormat

Downstream filters use the SetOutputFormat method to define an output video format.

Syntax

HRESULT SetOutputFormat(
  LPBITMAPINFO  lpbmi
);

Parameters

lpbmi

[in] Specifies a LPBITMAPINFO containing the output video format, such as size, bit depth, and other properties.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Return code | Description
S_FALSE | So far, downstream filters have defined no output format.
S_OK | Downstream filters have already defined an output format.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetRedrawAlways

Downstream filters use the SetRedrawAlways method to determine whether the whole output bitmap should be redrawn for each sample.

Syntax

HRESULT SetRedrawAlways(
  BOOL  bOption
);

Parameters

bOption

[in] Specifies a BOOL to assign whether the whole output bitmap should be redrawn for each sample.

Value | Description
TRUE | Redraw the whole output bitmap for each sample.
FALSE | Do not redraw the whole output bitmap for each sample.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAMWstDecoder::SetServiceState

Applications use the SetServiceState method to assign the service state.

Syntax

HRESULT SetServiceState(
  AM_WST_STATE  State
);

Parameters

State

[in] Specifies a member of an AM_WST_STATE enumeration to assign the service state.

Value | Description
AM_WST_STATE_On | Closed captioning on.
AM_WST_STATE_Off | Closed captioning off.

Return Values

When the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMWstDecoder Interface


IAsyncReader Interface

The IAsyncReader interface is exposed by output pins that perform asynchronous read operations. The interface is used by the input pin on the downstream filter. Applications do not use this interface.

The Async File Source filter exposes this interface on its output pin.

Filter developers: Implement this interface if your output pin delivers data in the form of a byte stream (MEDIATYPE_Stream) and supports the pull model. During the connection process, check whether the downstream pin queries for the IAsyncReader interface. If it does not, your pin should either fail the connection or establish some other transport. (If your pin derives from CBasePin, perform this check in the CBasePin::CheckConnect method.)

For more information about using this interface, see the following topics:

  • Negotiating Allocators
  • Data Flow for Filter Developers
  • CPullPin Class

In addition to the methods inherited from IUnknown, the IAsyncReader interface exposes the following methods.

Method | Description
BeginFlush | Causes all outstanding reads to return.
EndFlush | Ends the flushing operation.
Length | Retrieves the total length of the stream, and the currently available length.
RequestAllocator | Retrieves the actual allocator to be used.
Request | Queues a request for data.
SyncReadAligned | Performs an aligned synchronized read.
SyncRead | Performs a synchronized read.
WaitForNext | Blocks until the next sample is completed or the time-out occurs.


IAsyncReader::BeginFlush

The BeginFlush method begins a flush operation.

Syntax

HRESULT BeginFlush(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful, or S_FALSE otherwise.

Remarks

This method interrupts all pending read requests. While the pin is flushing, the IAsyncReader::Request method fails and the IAsyncReader::WaitForNext method returns immediately, possibly with the return code VFW_E_TIMEOUT.

The downstream input pin should call this method whenever the downstream filter flushes the filter graph. After calling this method, call the WaitForNext method until it returns NULL in the ppSample parameter, to clear out the queue of pending samples. Ignore error codes, and release each sample. Then call the IAsyncReader::EndFlush method to end the flush operation.

For more information, see Flushing.

Example Code

The following example shows how a downstream input pin should call this method:

m_pReader->BeginFlush();
while (1) {
    IMediaSample *pSample;
    DWORD_PTR dwUnused;
    m_pReader->WaitForNext(0, &pSample, &dwUnused);
    if(pSample) {
        pSample->Release();
    }
    else {  // No more samples.
        break;
    }
}
m_pReader->EndFlush();

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::EndFlush

The EndFlush method ends a flush operation.

Syntax

HRESULT EndFlush(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful, or S_FALSE otherwise.

Remarks

While the pin is flushing, the IAsyncReader::Request method fails and the IAsyncReader::WaitForNext method returns immediately. Call the EndFlush method at the end of a flush operation, to reenable the Request method.

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::Length

The Length method retrieves the total length of the stream.

Syntax

HRESULT Length(
  LONGLONG *pTotal,
  LONGLONG *pAvailable
);

Parameters

pTotal

Pointer to a variable that receives the length of the stream, in bytes.

pAvailable

Pointer to a variable that receives the portion of the stream that is currently available, in bytes.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_S_ESTIMATED | The returned values are estimates; for example, if the file is being read over a network.
E_UNEXPECTED | The file is not open or no longer exists.

Remarks

For streams retrieved over a network, the entire stream may not be available at first. Read operations beyond the available length might block for a long period of time, until that portion of the stream becomes available.

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::Request

The Request method queues an asynchronous request for data.

Syntax

HRESULT Request(
  IMediaSample *pSample,
  DWORD_PTR dwUser
);

Parameters

pSample

Pointer to the IMediaSample interface of a media sample provided by the caller.

dwUser

[in] Specifies an arbitrary value that is returned when the request completes.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_BADALIGN | The buffer is not aligned correctly.
VFW_E_SAMPLE_TIME_NOT_SET | The sample was not time stamped.
VFW_E_WRONG_STATE | The pin is flushing.
HRESULT_FROM_WIN32(ERROR_HANDLE_EOF) | The requested start position is past the end of the file.
E_OUTOFMEMORY | Insufficient memory.

Remarks

Before calling this method, retrieve a media sample from the pin's allocator. Time stamp the sample with the byte offsets you are requesting, first and last inclusive, multiplied by 10,000,000. Byte offsets are relative to the start of the stream.

The start and stop positions should match the alignment that was decided when the pins connected. Otherwise, the method might return VFW_E_BADALIGN. If the agreed alignment is coarser than the actual alignment of the stream, the stop position might exceed the real duration. If so, the method rounds the stop position down to the actual alignment.

Although it is technically a violation of COM rules, the caller must leave an outstanding reference count on the sample. The Request method does not call AddRef or Release, so the reference count is needed to keep the sample active.

The method returns before the request completes. Call the IAsyncReader::WaitForNext method to wait for the request. Do not reuse the original media sample while the request is pending. The WaitForNext method returns a pointer to the original sample. If the request succeeded, the sample contains the requested data. The WaitForNext method also returns whatever value is specified in the dwUser parameter. The caller can use this value to identify the sample.

Example Code

The following example shows a possible helper function for an input pin, to queue requests:

CMyPin::QueueSample(long cbFirst, long cbLast, DWORD dwuser)
{
    IMediaSample* pSample;
    HRESULT hr = m_pAlloc->GetBuffer(&pSample, NULL, NULL, 0);
    if (FAILED(hr)) { return hr; }

    LONGLONG tStart = cbFirst * 10000000, tStop = cbLast * 10000000;
    pSample->SetTime(&tCurrent, &tStopThis);
    hr = m_pReader->Request(pSample, dwuser);
    if (FAILED(hr))
    {
        pSample->Release();
    }
    return hr;
}

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::RequestAllocator

The RequestAllocator method requests an allocator during the pin connection.

Syntax

HRESULT RequestAllocator(
  IMemAllocator *pPreferred,
  ALLOCATOR_PROPERTIES *pProps,
  IMemAllocator **ppActual
);

Parameters

pPreferred

[in] Pointer to the IMemAllocator interface on the input pin's preferred allocator, or NULL.

pProps

[in] Specifies the address of an ALLOCATOR_PROPERTIES structure, allocated by the caller. The caller should fill in any allocator properties that the input pin requires, and set the remaining members to zero.

ppActual

[out] Address of a variable that receives an IMemAllocator interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_FAIL | Failure to initialize an allocator.
VFW_E_BADALIGN | An invalid alignment was specified.
S_OK | Allocator was returned.

Remarks

The downstream input pin should call this method during the connection process. If the pin has a preferred allocator, specify it in the pPreferred parameter. Specify any buffer requirements, such as buffer size or alignment, in the pProps parameter. The output pin chooses the allocator and returns a pointer to it in the ppActual parameter.

The output pin is not required to honor the input pin's requests. If the input pin has any absolute requirements, it should call the IMemAllocator::GetProperties method on the returned allocator. It can fail the connect if the allocator properties are not suitable. Once the connection is established, the input pin must use the allocator chosen by the output pin.

The input pin is responsible for committing and decommitting the allocator.

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::SyncRead

The SyncRead method performs a synchronous read. The method blocks until the request is completed. The file positions and the buffer address do not have to be aligned. If the request is not aligned, the method performs a buffered read operation.

Syntax

HRESULT SyncRead(
  LONGLONG llPosition,
  LONG lLength,
  BYTE *pBuffer
);

Parameters

llPosition

[in] Specifies the byte offset at which to begin reading. The method fails if this value is beyond the end of the file.

lLength

[in] Specifies the number of bytes to read.

pBuffer

[out] Pointer to a buffer that receives the data.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Retrieved fewer bytes than requested. (Probably the end of the file was reached.)
S_OK | Success.

Remarks

This method works even if the filter is stopped.

See Also

  • Error and Success Codes
  • IAsyncReader Interface
  • IAsyncReader::SyncReadAligned


IAsyncReader::SyncReadAligned

The SyncReadAligned method performs a synchronous read. The method blocks until the request is completed. The file positions and the buffer address must be aligned; check the allocator properties for the required alignment.

Syntax

HRESULT SyncReadAligned(
  IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface of a media sample provided by the caller.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
VFW_E_BADALIGN | Invalid alignment.
S_FALSE | Retrieved fewer bytes than requested. (Probably the end of the file was reached.)
S_OK | Success.

Remarks

Before calling this method, retrieve a media sample from the pin's allocator. Time stamp the sample with the byte offsets you are requesting, first and last inclusive, multiplied by 10,000,000. Byte offsets are relative to the start of the stream.

The start and stop positions should match the alignment that was decided when the pins connected. Otherwise, the method returns VFW_E_BADALIGN. If the agreed alignment is coarser than the actual alignment of the stream, the stop position might exceed the real duration. If so, the method rounds the stop position down to the actual alignment.

This method performs an unbuffered read, so it might be faster than the IAsyncReader::SyncRead method.

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IAsyncReader::WaitForNext

The WaitForNext method waits for the next pending read request to complete.

Syntax

HRESULT WaitForNext(
  DWORD dwTimeout,
  IMediaSample **ppSample,
  DWORD_PTR *pdwUser
);

Parameters

dwTimeout

[in] Specifies a time-out in milliseconds. Use the value INFINITE to wait indefinitely

ppSample

[out] Address of a variable that receives an IMediaSample interface pointer.

pdwUser

[out] Pointer to a variable that receives the value of the dwUser parameter specified in the IAsyncReader::Request method.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
VFW_E_TIMEOUT | The time-out expired, or the pin is flushing.
VFW_E_WRONG_STATE | The pin is flushing.
E_FAIL | A read error occurred.
S_OK | Success.
S_FALSE | Reached the end of the file; retrieved fewer bytes than requested.

Remarks

If the method succeeds, the ppSample parameter contains a pointer to a media sample, whose buffer holds the requested data. Call the IMediaSample::GetTime method and divide the results by 10,000,000 to determine the start and stop bytes. Samples may be returned out of order. Release the sample when you are finished processing the data.

The method fails if the pin is flushing. However, it may return an empty sample in ppSample. If *ppSample is non-NULL, release the sample and discard it. For more information, see IAsyncReader::BeginFlush.

If a read error occurs, the source filter sends an error event to the Filter Graph Manager; the caller does not have to signal an error.

See Also

  • Error and Success Codes
  • IAsyncReader Interface


IBaseFilter Interface

The IBaseFilter interface provides methods for controlling a filter. All DirectShow filters expose this interface. The Filter Graph Manager uses this interface to control filters. Applications can use this interface to enumerate pins and query for filter information, but should not use it to change the state of a filter. Instead, use the IMediaControl interface on the Filter Graph Manager.

Filter developers: Implement this interface on every DirectShow filter. The CBaseFilter base class implements this interface.

In addition to the methods inherited from IMediaFilter, the IBaseFilter interface exposes the following methods.

Method | Description
EnumPins | Enumerates the pins on this filter.
FindPin | Retrieves the pin with the specified identifier.
JoinFilterGraph | Notifies the filter that it has joined or left the filter graph.
QueryFilterInfo | Retrieves information about the filter.
QueryVendorInfo | Retrieves a string containing vendor information.


IBaseFilter::EnumPins

The EnumPins method enumerates the pins on this filter.

Syntax

HRESULT EnumPins(
  IEnumPins **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumPins interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | Null pointer argument

Remarks

This method returns an enumerator that supports the IEnumPins interface, which works like a standard COM enumerator. For more information, see Enumerating Pins.

If the method succeeds, the IEnumPins interface has an outstanding reference count. Be sure to release the interface when you are done.

See Also

  • Error and Success Codes
  • IBaseFilter Interface


IBaseFilter::FindPin

The FindPin method retrieves the pin with the specified identifier.

Syntax

HRESULT FindPin(
  LPCWSTR Id,
  IPin **ppPin
);

Parameters

Id

[in] Pointer to a constant wide-character string that identifies the pin. Call the IPin::QueryId method to retrieve a pin's identifier.

ppPin

[out] Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

This method supports graph persistence. Use the IPin::QueryId method to save a pin's state, and use this method to restore the state. The pin's identifier string is defined by the filter implementation. The identifier must be unique within the filter.

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release the interface when you are done.

See Also

  • Error and Success Codes
  • IBaseFilter Interface


IBaseFilter::JoinFilterGraph

The JoinFilterGraph method notifies the filter that it has joined or left the filter graph.

Syntax

HRESULT JoinFilterGraph(
  IFilterGraph *pGraph,
  LPCWSTR pName
);

Parameters

pGraph

[in] Pointer to the Filter Graph Manager's IFilterGraph interface, or NULL if the filter is leaving the graph.

pName

[in, string] Pointer to a wide-character string that specifies a name for the filter.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

When the Filter Graph Manager adds a filter to the filter graph, it calls this method with a pointer to itself. It assigns a name for this instance of the filter through the pName parameter. The name can be retrieved by calling the IBaseFilter::QueryFilterInfo method.

When the Filter Graph Manager removes the filter from the graph, it calls this method with a NULL pointer.

Applications should never call this method. To add a filter to the graph, call the IFilterGraph::AddFilter method on the filter graph manager.

Filter developers: The filter can store the IFilterGraph interface pointer and query it for other Filter Graph Manager interfaces. However, it must never hold a reference count on the Filter Graph Manager. Doing so creates a circular reference count, because the Filter Graph Manager keeps a reference count on the filter. A circular reference count prevents the interface from being released properly, which can lead to a deadlock. The IFilterGraph interface is guaranteed to be valid until the Filter Graph Manager calls this method again with the value NULL. For an implementation of this method, see the CBaseFilter::JoinFilterGraph method.

See Also

  • Error and Success Codes
  • IBaseFilter Interface


IBaseFilter::QueryFilterInfo

The QueryFilterInfo method retrieves information about the filter.

Syntax

HRESULT QueryFilterInfo(
  FILTER_INFO *pInfo
);

Parameters

pInfo

[out] Pointer to a FILTER_INFO structure.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success
E_POINTER | Null pointer argument

Remarks

This method fills the FILTER_INFO structure with the filter information. On return, if the pGraph member of the FILTER_INFO structure is non-NULL, the IFilterGraph interface has an outstanding reference count. Be sure to release the interface when you are done.

See Also

  • Error and Success Codes
  • IBaseFilter Interface


IBaseFilter::QueryVendorInfo

The QueryVendorInfo method retrieves a string containing vendor information.

Syntax

HRESULT QueryVendorInfo(
  LPWSTR *pVendorInfo
);

Parameters

pVendorInfo

[out] Address of a variable that receives a pointer to a wide-character string containing the vendor information.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.

Remarks

This method is optional; filters are not required to support it.

If the method is supported, it uses the CoTaskMemAlloc function to allocate memory for the string. Call the CoTaskMemFree function to free the memory.

See Also

  • Error and Success Codes
  • IBaseFilter Interface


IBasicAudio Interface

The IBasicAudio interface enables applications to control the volume and balance of the audio stream.

This interface is implemented on the Audio Renderer (WaveOut) filter and the DirectSound Renderer filter, but is exposed to applications through the Filter Graph Manager. Applications should always retrieve this interface from the Filter Graph Manager.

In addition to the methods inherited from IDispatch, the IBasicAudio interface exposes the following methods.

Method | Description
get_Balance | Retrieves the balance for the audio signal.
get_Volume | Retrieves the volume (amplitude) of the audio signal.
put_Balance | Sets the balance for the audio signal.
put_Volume | Sets the volume (amplitude) of the audio signal.


IBasicAudio::get_Balance

The get_Balance method retrieves the balance for the audio signal.

Syntax

HRESULT get_Balance(
  long *plBalance
);

Parameters

plBalance

[out] Pointer to a variable that receives the balance.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_NOTIMPL | The filter graph does not contain an audio renderer filter. (Possibly the source does not contain an audio stream.)
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

The balance ranges from -10,000 to 10,000. The value -10,000 means the right channel is attenuated by 100 dB and is effectively silent. The value 10,000 means the left channel is silent. The neutral value is 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

See Also

  • Error and Success Codes
  • IBasicAudio Interface


IBasicAudio::get_Volume

The get_Volume method retrieves the volume (amplitude) of the audio signal.

Syntax

HRESULT get_Volume(
  long *plVolume
);

Parameters

plVolume

[out] Pointer to a variable that receive the volume. Divide by 100 to get equivalent decibel value. For example, –10,000 is –100 dB.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_NOTIMPL | The filter graph does not contain an audio renderer filter. (Possibly the source does not contain an audio stream.)
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IBasicAudio Interface


IBasicAudio::put_Balance

The put_Balance method sets the balance of the audio signal.

Syntax

HRESULT put_Balance(
  long lBalance
);

Parameters

lBalance

[in] Specifies the balance. The value can range from -10,000 to 10,000. The value -10,000 means the right channel is attenuated by 100 dB and is effectively silent. The value 10,000 means the left channel is silent. The neutral value is 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | The underlying audio device returned an error.
E_INVALIDARG | The value of lBalance is invalid.
E_NOTIMPL | The filter graph does not contain an audio renderer filter. (Possibly the source does not contain an audio stream.)
S_OK | Success.

See Also

  • Error and Success Codes
  • IBasicAudio Interface


IBasicAudio::put_Volume

The put_Volume method sets the volume (amplitude) of the audio signal.

Syntax

HRESULT put_Volume(
  long lVolume
);

Parameters

lVolume

[in] Specifies the volume, as a number from –10,000 to 0, inclusive. Full volume is 0, and –10,000 is silence. Multiply the desired decibel level by 100. For example, –10,000 = –100 dB.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | The underlying audio device returned an error.
E_INVALIDARG | The value of lVolume is invalid.
E_NOTIMPL | The filter graph does not contain an audio renderer filter. (Possibly the source does not contain an audio stream.)
S_OK | Success.

See Also

  • Error and Success Codes
  • IBasicAudio Interface


IBasicVideo Interface

The IBasicVideo interface enables applications to set video properties such as the destination and source rectangles. This interface is implemented on the Video Renderer filter, but is exposed to applications through the Filter Graph Manager. Applications should always retrieve this interface from the Filter Graph Manager.

The methods on this interface require that the Video Renderer be connected. Otherwise, all methods return VFW_E_NOT_CONNECTED. Properties set on the Video Renderer persist between successive connections and disconnections.

The IBasicVideo interface manipulates the following rectangles associated with the video image:

The source rectangle is the portion of the original image that gets displayed.

The destination rectangle is the portion of the video window the receives the source rectangle.

The video rectangle is the original video image.

In other words, the video renderer crops the image to the source rectangle, and then stretches or shrinks the cropped image to the destination rectangle. All rectangle dimensions are given in pixels.

In addition to the methods inherited from IDispatch, the IBasicVideo interface exposes the following methods.

Method | Description
get_AvgTimePerFrame | Retrieves the average time between successive frames.
get_BitErrorRate | Retrieves the approximate bit error rate of the video stream.
get_BitRate | Retrieves the approximate bit rate of the video stream.
get_DestinationHeight | Retrieves the height of the destination rectangle.
get_DestinationLeft | Retrieves the x-coordinate of the destination rectangle.
get_DestinationTop | Retrieves the y-coordinate of the destination rectangle.
get_DestinationWidth | Retrieves the width of the destination rectangle.
get_SourceHeight | Retrieves the height of the source rectangle.
get_SourceLeft | Retrieves the x-coordinate of the source rectangle.
get_SourceTop | Retrieves the y-coordinate of the source rectangle.
get_SourceWidth | Retrieves the width of the source rectangle.
get_VideoHeight | Retrieves the video height.
get_VideoWidth | Retrieves the video width.
GetCurrentImage | Returns a copy of the current image that is waiting at the renderer.
GetDestinationPosition | Retrieves the destination rectangle.
GetSourcePosition | Retrieves the source rectangle.
GetVideoPaletteEntries | Retrieves the color palette entries required by the video.
GetVideoSize | Retrieves the native video dimensions.
IsUsingDefaultDestination | Queries whether the renderer is using the default destination rectangle.
IsUsingDefaultSource | Queries whether the renderer is using the default source rectangle.
put_DestinationHeight | Sets the height of the destination rectangle.
put_DestinationLeft | Sets the x-coordinate of the destination rectangle.
put_DestinationTop | Sets the y-coordinate of the destination rectangle.
put_DestinationWidth | Sets the width of the destination rectangle.
put_SourceHeight | Sets the height of the video rectangle.
put_SourceLeft | Sets the x-coordinate of the source rectangle.
put_SourceTop | Sets the y-coordinate of the source rectangle.
put_SourceWidth | Sets the width of the source rectangle.
SetDefaultDestinationPosition | Reverts to the default destination rectangle.
SetDefaultSourcePosition | Reverts to the default source rectangle.
SetDestinationPosition | Sets the destination rectangle.
SetSourcePosition | Sets the source rectangle.


IBasicVideo::get_AvgTimePerFrame

The get_AvgTimePerFrame method retrieves the average time between successive frames.

Syntax

HRESULT get_AvgTimePerFrame(
  REFTIME *pAvgTimePerFrame
);

Parameters

pAvgTimePerFrame

[out] Pointer to a variable of type REFTIME that receives the average frame time, in seconds.

Return Values

Returns an HRESULT value.

Remarks

This method returns the authored time per frame. This value is typically set by the source filter, which obtains it from information in the video stream itself. This value is not necessarily equal to the actual time per frame at which the video is rendered.

To retrieve the actual frame rate during playback, use the IQualProp::get_AvgFrameRate. For more information on actual versus authored frame rates, see the Remarks section for the VIDEOINFOHEADER structure.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_BitErrorRate

The get_BitErrorRate method retrieves the approximate bit error rate of the video stream

Syntax

HRESULT get_BitErrorRate(
  long *pBitErrorRate
);

Parameters

pBitErrorRate

[out] Pointer to a variable that receives the approximate number of bits per error.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_BitRate

The get_BitRate method retrieves the approximate bit rate of the video stream.

Syntax

HRESULT get_BitRate(
  long *pBitRate
);

Parameters

pBitRate

[out] Pointer to a variable that receives the approximate bit rate, in bits per second.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::GetCurrentImage

The GetCurrentImage method retrieves the current image waiting at the renderer.

Syntax

HRESULT GetCurrentImage(
  long *pBufferSize,
  long *pDIBImage
);

Parameters

pBufferSize

[in, out] Pointer to a variable that contains the size of the buffer that the caller is passing in. If pDIBImage is NULL, this parameter receives the required buffer size.

pDIBImage

[out] Pointer to a buffer where the complete image will be stored in device-independent bitmap (DIB) format. Cast the pointer to a long pointer type.

Return Values

Returns an HRESULT value.

Remarks

The Video Renderer filter and the Video Mixing Renderer (VMR) implement this method differently.

Video Renderer only:

This method fails if the renderer is using DirectDraw acceleration. Unfortunately, this depends on the end-user's hardware configuration, so in practice this method is not reliable.

Pause the Video Renderer before calling this method. Otherwise, the method returns VFW_E_NOT_PAUSED. Make sure that the pause operation has completed by calling IMediaControl::GetState; if the pause operation has not completed, the GetCurrentImage method returns E_UNEXPECTED. Depending on what data the source filter has available, the video renderer is not guaranteed to service this request. If no image is available, it returns E_FAIL.

Video Mixing Renderer only:

This method is reliable regardless of whether the VMR is using DirectDraw acceleration and regardless of the current graph state (running, stopped, or paused).

Both Video Renderer and Video Mixing Renderer:

To obtain the required buffer size to hold the image, call this method with a NULL pointer in the pDIBImage parameter. The method returns the required buffer size in the pBufferSize parameter. Allocate a buffer of that size and call the method again, with pDIBImage pointing to the buffer. On the second call, use pBufferSize to specify the buffer size. If the buffer is too small to hold the complete image, the method returns E_OUTOFMEMORY.

If the method succeeds, the buffer is filled with the entire DIB image, including the BITMAPINFOHEADER structure, plus any palette entries and bit masks as defined in the Win32 BITMAPINFO structure. The format of the image depends on the type provided by the source filter, and cannot be specified in advance.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_DestinationHeight

The get_DestinationHeight method retrieves the height of the destination rectangle.

Syntax

HRESULT get_DestinationHeight(
  long *pDestinationHeight
);

Parameters

pDestinationHeight

[out] Pointer to a variable that receives the height, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_DestinationLeft

The get_DestinationLeft method retrieves the x-coordinate of the destination rectangle.

Syntax

HRESULT get_DestinationLeft(
  long *pDestinationLeft
);

Parameters

pDestinationLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::GetDestinationPosition

The GetDestinationPosition method retrieves the position of the destination rectangle.

Syntax

HRESULT GetDestinationPosition(
  long *pLeft,
  long *pTop,
  long *pWidth,
  long *pHeight
);

Parameters

pLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

pTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

pWidth

[out] Pointer to a variable that receives the width, in pixels.

pHeight

[out] Pointer to a variable that receives the height, in pixels.

Return Values

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::get_DestinationLeft, IBasicVideo::get_DestinationTop, IBasicVideo::get_DestinationWidth, and IBasicVideo::get_DestinationHeight methods.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_DestinationTop

The get_DestinationTop method retrieves the y-coordinate of the destination rectangle.

Syntax

HRESULT get_DestinationTop(
  long *pDestinationTop
);

Parameters

pDestinationTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_DestinationWidth

The get_DestinationWidth method retrieves the width of the destination rectangle.

Syntax

HRESULT get_DestinationWidth(
  long *pDestinationWidth
);

Parameters

pDestinationWidth

[out] Pointer to a variable that receives the width, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_SourceHeight

The get_SourceHeight method retrieves the height of the source rectangle.

Syntax

HRESULT get_SourceHeight(
  long *pSourceHeight
);

Parameters

pSourceHeight

[out] Pointer to a variable that receives the current height, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_SourceLeft

The get_SourceLeft method retrieves the x-coordinate of the source rectangle.

Syntax

HRESULT get_SourceLeft(
  long *pSourceLeft
);

Parameters

pSourceLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::GetSourcePosition

The GetSourcePosition method retrieves the position of the source rectangle.

Syntax

HRESULT GetSourcePosition(
  long *pLeft,
  long *pTop,
  long *pWidth,
  long *pHeight
);

Parameters

pLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

pTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

pWidth

[out] Pointer to a variable that receives the width, in pixels.

pHeight

[out] Pointer to a variable that receives the height, in pixels.

Return Values

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::get_SourceLeft, IBasicVideo::get_SourceTop, IBasicVideo::get_SourceWidth, and IBasicVideo::get_SourceHeight methods.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_SourceTop

The get_SourceTop method retrieves the y-coordinate of the source rectangle.

Syntax

HRESULT get_SourceTop(
  long *pSourceTop
);

Parameters

pSourceTop

[out] Pointer a variable that receives the y-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_SourceWidth

The get_SourceWidth method retrieves the width of the source rectangle.

Syntax

HRESULT get_SourceWidth(
  long *pSourceWidth
);

Parameters

pSourceWidth

[out] Pointer to a variable that receives the width, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_VideoHeight

The get_VideoHeight method retrieves the native height of the video.

Syntax

HRESULT get_VideoHeight(
  long *pVideoHeight
);

Parameters

pVideoHeight

[out] Pointer to a variable that receives the height, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::GetVideoPaletteEntries

The GetVideoPaletteEntries method retrieves the palette colors for the video.

Syntax

HRESULT GetVideoPaletteEntries(
  long StartIndex,
  long Entries,
  long *pRetrieved,
  long *pPalette
);

Parameters

StartIndex

[in] Start index for the palette.

Entries

[in] Number of palette entries to retrieve.

pRetrieved

[out] Pointer to a variable that receives the number of entries returned in pPallette.

pPalette

[out] Pointer to an array of PALETTEENTRY structures of size Entries. Cast the pointer to a long pointer type. The method fills the array.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NO_PALETTE_AVAILABLE | No palette is available.
VFW_E_NOT_CONNECTED | The Video Renderer's input pin is not connected.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::GetVideoSize

The GetVideoSize method retrieves the native video dimensions.

Syntax

HRESULT GetVideoSize(
  long *pWidth,
  long *pHeight
);

Parameters

pWidth

[out] Pointer to a variable that receives the width of the video image, in pixels.

pHeight

[out] Pointer to a variable that receives the height of the video image, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::get_VideoWidth

The get_VideoWidth method retrieves the native width of the video.

Syntax

HRESULT get_VideoWidth(
  long *pVideoWidth
);

Parameters

pVideoWidth

[out] Pointer to a variable that receives the width of the video, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::IsUsingDefaultDestination

The IsUsingDefaultDestination method queries whether the renderer is using the default destination rectangle.

Syntax

HRESULT IsUsingDefaultDestination(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if the renderer is using the default destination rectangle, or S_FALSE otherwise.

See Also

  • Error and Success Codes
  • IBasicVideo Interface
  • IBasicVideo::SetDefaultDestinationPosition


IBasicVideo::IsUsingDefaultSource

The IsUsingDefaultSource method queries whether the renderer is using the default source rectangle.

Syntax

HRESULT IsUsingDefaultSource(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if the renderer is using the default source rectangle, or S_FALSE otherwise.

See Also

  • Error and Success Codes
  • IBasicVideo Interface
  • IBasicVideo::SetDefaultSourcePosition


IBasicVideo::put_DestinationHeight

The put_DestinationHeight method sets the height of the destination rectangle.

Syntax

HRESULT put_DestinationHeight(
  long DestinationHeight
);

Parameters

DestinationHeight

[in] Specifies the height, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_DestinationLeft

The put_DestinationLeft method sets the x-coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationLeft(
  long DestinationLeft
);

Parameters

DestinationLeft

[in] Specifies the x-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_DestinationTop

The put_DestinationTop method sets the y-coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationTop(
  long DestinationTop
);

Parameters

DestinationTop

[in] Specifies the y-coordinate, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_DestinationWidth

The put_DestinationWidth method sets the width of the destination rectangle.

Syntax

HRESULT put_DestinationWidth(
  long DestinationWidth
);

Parameters

DestinationWidth

[in] Specifies the width, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_SourceHeight

The put_SourceHeight method sets the height of the source rectangle.

Syntax

HRESULT put_SourceHeight(
  long SourceHeight
);

Parameters

SourceHeight

[in] Specifies the height, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_SourceLeft

The put_SourceLeft method sets the x-coordinate of the source rectangle.

Syntax

HRESULT put_SourceLeft(
  long SourceLeft
);

Parameters

SourceLeft

[in] Specifies the x-coordinate, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer's input pin is not connected.

Remarks

This method moves the entire source rectangle to the left or right. It does not change the width of the source rectangle. If the value of SourceLeft would place the right edge of the rectangle beyond the edge of the video frame, the method returns E_INVALIDARG. To crop the video, call put_SourceWidth to adjust the width, before calling put_SourceLeft. (Or call SetSourcePosition to set the entire source rectangle at once.)

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_SourceTop

The put_SourceTop method sets the y-coordinate of the source rectangle.

Syntax

HRESULT put_SourceTop(
  long SourceTop
);

Parameters

SourceTop

[in] Specifies the y-coordinate, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer's input pin is not connected.

Remarks

This method moves the entire source rectangle up or down. It does not change the height of the source rectangle. If the value of SourceTop would place the bottom edge of the rectangle beyond the edge of the video frame, the method returns E_INVALIDARG. To crop the video, call put_SourceHeight to adjust the width, before calling put_SourceTop. (Or call SetSourcePosition to set the entire source rectangle at once.)

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::put_SourceWidth

The put_SourceWidth method sets the width of the source rectangle.

Syntax

HRESULT put_SourceWidth(
  long SourceWidth
);

Parameters

SourceWidth

[in] Specifies the width, in pixels.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::SetDefaultDestinationPosition

The SetDefaultDestinationPosition method reverts to the default destination rectangle. After this method is called, the video renderer uses the entire window for playback.

Syntax

HRESULT SetDefaultDestinationPosition(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::SetDefaultSourcePosition

The SetDefaultSourcePosition method reverts to the default source rectangle. After this method is called, the video renderer uses the entire video image, without cropping.

Syntax

HRESULT SetDefaultSourcePosition(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::SetDestinationPosition

The SetDestinationPosition method sets the destination rectangle.

Syntax

HRESULT SetDestinationPosition(
  long Left,
  long Top,
  long Width,
  long Height
);

Parameters

Left

[in] Specifies the x-coordinate, in pixels.

Top

[in] Specifies the y-coordinate, in pixels.

Width

[in] Specifies the width, in pixels.

Height

[in] Specifies the height, in pixels.

Return Values

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::put_DestinationLeft, IBasicVideo::put_DestinationTop, IBasicVideo::put_DestinationWidth, and IBasicVideo::put_DestinationHeight methods.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo::SetSourcePosition

The SetSourcePosition method sets the source rectangle.

Syntax

HRESULT SetSourcePosition(
  long Left,
  long Top,
  long Width,
  long Height
);

Parameters

Left

[in] Specifies the x-coordinate, in pixels.

Top

[in] Specifies the y-coordinate, in pixels.

Width

[in] Specifies the width, in pixels.

Height

[in] Specifies the height, in pixels.

Return Values

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::put_SourceLeft, IBasicVideo::put_SourceTop, IBasicVideo::put_SourceWidth, and IBasicVideo::put_SourceHeight methods.

Setting this coordinate does not affect the destination rectangle height.

See Also

  • Error and Success Codes
  • IBasicVideo Interface


IBasicVideo2 Interface

The IBasicVideo2 interface derives from the IBasicVideo interface and provides an additional method for applications to retrieve the preferred aspect ratio of the video stream. The interface is implemented on the Video Renderer Filter, but is exposed to applications on the Filter Graph Manager.

In addition to the methods inherited from IDispatch and IBasicVideo, the IBasicVideo2 interface exposes the following method.

Method | Description
GetPreferredAspectRatio | Retrieves the movie's preferred aspect ratio.


IBasicVideo2::GetPreferredAspectRatio

The GetPreferredAspectRatio method retrieves a pair of dimensionless values whose ratio defines the movie's preferred aspect ratio.

Syntax

HRESULT GetPreferredAspectRatio (
  long *plAspectX,
  long *plAspectY
);

Parameters

plAspectX

[out] Pointer to a value that indicates the movie's x-axis aspect ratio.

plAspectY

[out] Pointer to a value that indicates the movie's y-axis aspect ratio.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | One or both of the parameters are invalid.
E_NOINTERFACE | The renderer does not implement IBasicVideo2.

See Also

  • Error and Success Codes
  • IBasicVideo2 Interface
  • VIDEOINFOHEADER2 Structure


ICaptureGraphBuilder2 Interface

The ICaptureGraphBuilder2 interface provides methods for building capture graphs, and other custom filter graphs. The Capture Graph Builder object implements this interface.

Note The ICaptureGraphBuilder2 interface does not use the Video Mixing Renderer (VMR) or Video Port Manager filters.

In addition to the methods inherited from IUnknown, the ICaptureGraphBuilder2 interface exposes the following methods.

Method | Description
AllocCapFile | Preallocates a capture file to a specified size.
ControlStream | Sets the start and stop times for one or more streams of captured data.
CopyCaptureFile | Copies the valid media data from a capture file.
FindInterface | Searches the graph for a specified interface, starting from a specified filter.
FindPin | Retrieves a particular pin on a filter, or determines whether a given pin matches the specified criteria.
GetFiltergraph | Retrieves the filter graph that the builder is using.
RenderStream | Connects an output pin on a source filter to a rendering filter, optionally through a compression filter.
SetFiltergraph | Specifies a filter graph for the capture graph builder to use.
SetOutputFileName | Creates the file writing section of the filter graph.

See Also

  • Building Graphs with the Capture Graph Builder
  • Recompressing an AVI File
  • Video Capture


ICaptureGraphBuilder2::AllocCapFile

The AllocCapFile method preallocates a capture file to a specified size. For best results, always capture to a defragmented, preallocated capture file that is larger than the size of the capture data.

Syntax

HRESULT AllocCapFile(
  LPCOLESTR lpwstr,
  DWORDLONG dwlSize
);

Parameters

lpwstr

[in] Pointer to a wide-character string that contains the name of the file to create or resize.

dwlSize

[in] Size of the file to allocate, in bytes.

Return Values

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method fails if the file is read-only.

It is best to allocate as much space as possible—ideally, more than needed. However, this can result in a very large file that contains relatively little data. For example, a 1-gigabyte (GB) capture file might contain a few megabytes of captured video. Use the ICaptureGraphBuilder2::CopyCaptureFile method to copy the data into a new file. That method copies only the data and ignores the empty portion of the original file.

Note The AllocCapFile method takes longer on Microsoft® Windows NT® 4.x or Microsoft® Windows® 2000 than it does on other Windows platforms, because the method must write over the entire preallocated file. However, it is still recommended that you use this method, because it results in better capture performance.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::ControlStream

The ControlStream method sets the start and stop times for one or more streams of captured data.

Syntax

HRESULT ControlStream(
  const GUID *pCategory,
  const GUID *pType,
  IBaseFilter *pFilter,
  REFERENCE_TIME *pstart,
  REFERENCE_TIME *pstop,
  WORD wStartCookie,
  WORD wStopCookie
);

Parameters

pCategory

[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY structure of the Pin Property Set property set, specifying the pin category. The value of this parameter cannot be NULL.

pType

[in] Pointer to a major type GUID that specifies the media type, or NULL. If this parameter is NULL, set the pFilter parameter to NULL as well. Otherwise, you might control the wrong pin and get unpredictable results.

pFilter

[in] Pointer to an IBaseFilter interface that specifies which filter to control. To control all the capture filters in the graph, set this parameter to NULL.

pstart

[in] Pointer to a variable that contains the start time. If the value is MAXLONGLONG (0x7FFFFFFFFFFFFFFF), the method cancels the previous start request. If the value is NULL, the pin starts immediately when the graph runs.

pstop

[in] Pointer to a variable that contains the stop time. If the value is MAXLONGLONG, the method cancels any previous stop request. If the value is NULL, the pin stops immediately.

wStartCookie

[in] Value that is sent as the second parameter of the EC_STREAM_CONTROL_STARTED event notification. See Remarks for more information.

wStopCookie

[in] Value that is sent as the second parameter of the EC_STREAM_CONTROL_STOPPED event notification. See Remarks for more information.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | At least one downstream renderer will not send a stop notification.
S_OK | Success.
E_FAIL | Could not find a matching pin, or the pin did not support stream control.
E_POINTER | NULL pointer argument.

Remarks

This method locates output pins on capture filters, using search criteria that you supply in the method call. Then it calls the IAMStreamControl methods on those pins. This method enables an application to control streams without the application needing to enumerate the filters and pins in the graph.

Use this method for frame-accurate capture, or for individual control of capture and preview. For example, you can stop capturing to disk but leave video preview running.

The first three parameters specify which pins to control. A capture graph can have more than one capture filter. For example, it might have filters for video, audio, and closed captioning data. Also, a capture filter can have more than one output pin. Some capture filters have separate pins for preview and capture, or separate pins for video-only data and audio-video interleaved data. To control video preview, for example, specify PIN_CATEGORY_PREVIEW for pCategory and MEDIATYPE_Video for pType.

Note If the pin category is PIN_CATEGORY_PREVIEW, you cannot set specific start and stop times, because the samples delivered by a preview pin have no time stamps (see Time Stamps). Instead, use the values NULL and MAXLONGLONG to start and stop the pin at the desired times.

Also, this method is not supported for preview if the device uses a video port pin, because in that case the device is delivering the preview samples directly over hardware.

To control a pin, this method calls the IAMStreamControl::StartAt and IAMStreamControl::StopAt methods. Each pin sends an EC_STREAM_CONTROL_STARTED event notification when it starts. The second parameter of the event notification is the value given in wStartCookie. When the pin stops, it sends an EC_STREAM_CONTROL_STOPPED event notification. The second parameter of that event notification is the value given in wStopCookie.

When this method locates a matching pin, it searches downstream for another filter that supports IAMStreamControl (typically a multiplexer). If it finds one, it also sets the start and stop times on that filter. This generates two pairs of stop notifications: one for the capture filter, and one for the downstream filter. Only the stop notification from the downstream filter uses the wStopCookie parameter. Waiting for this event guarantees that the downstream filter receives the last sample.

If no downstream filter supports IAMStreamControl, the method returns S_FALSE. In that case, you might receive the stop notification before the last sample is rendered.

MAXLONGLONG is the largest possible REFERENCE_TIME value. In the DirectShow base class library, it is also defined as the constant MAX_TIME.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::CopyCaptureFile

The CopyCaptureFile method copies the valid media data from a capture file.

Syntax

HRESULT CopyCaptureFile(
  LPOLESTR lpwstrOld,
  LPOLESTR lpwstrNew,
  int fAllowEscAbort,
  IAMCopyCaptureFileProgress *pCallback
);

Parameters

lpwstrOld

[in] Pointer to a wide-character string that contains the source file name.

lpwstrNew

[in] Pointer to a wide-character string that contains the destination file name. Valid data is copied to this file.

fAllowEscAbort

[in] Boolean value that specifies whether pressing the ESC key cancels the copy operation. If the value is TRUE and the user presses the ESC key, the operation halts. If the value is FALSE, the method ignores the ESC key.

pCallback

[in] Pointer to an IAMCopyCaptureFileProgress interface to display progress information, or NULL. See Remarks for more information.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | User canceled the operation before it completed.
S_OK | Success.
E_FAIL | Failure.
E_INVALIDARG | Could not open the source file or destination file.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Typically, you will first capture to a large preallocated file. This method copies just the valid data to a new file. As a result, the new file can be much smaller than the original file.

The source and destination files must be AVI files. Other file types are not supported.

To display the progress of the copy operation, implement the IAMCopyCaptureFileProgress interface and pass a pointer to the interface in the pCallback parameter. If pCallback is non-NULL, this method periodically calls the IAMCopyCaptureFileProgress::Progress method with an integer between 0 and 100 that specifies the percentage complete.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::FindInterface

The FindInterface method searches the graph for a specified interface, starting from a specified filter. You can restrict the search to a section of the graph upstream or downstream of the filter, or restrict it to a particular pin category or media type.

Syntax

HRESULT FindInterface(
  const GUID *pCategory,
  const GUID *pType,
  IBaseFilter *pf,
  REFIID riid,
  void **ppint
);

Parameters

pCategory

[in] Pointer to a GUID that specifies the search criteria. See Remarks for more information. The following values are possible:

  • &LOOK_UPSTREAM_ONLY
  • &LOOK_DOWNSTREAM_ONLY
  • Member of the AMPROPERTY_PIN_CATEGORY structure of the Pin Property Set property set, specifying a pin category.
  • NULL

See Remarks for more information.

pType

[in] Pointer to a GUID that specifies the major media type of an output pin, or NULL.

pf

[in] Pointer to the IBaseFilter interface of the filter. The method begins searching from this filter.

riid

[in] Interface identifier (IID) of the interface to locate.

ppint

[out] Address of a variable that receives the interface pointer. Be sure to release the retrieved interface pointer when you are done with the interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_FAIL | Failure.
E_NOINTERFACE | No such interface supported.
E_POINTER | NULL pointer argument.

Remarks

In a capture graph, various filters and pins might expose interfaces for setting properties such as compression parameters (IAMVideoCompression) or stream formats (IAMStreamConfig). Depending on the capture device, other useful interfaces might include IAMCrossbar, which routes analog signals, or IAMTVTuner, which controls a TV tuner device. You can use this method to find an interface, without writing special code that traverses the graph.

Important Do not call this method to obtain an IVideoWindow interface pointer. Always query the filter graph manager for this interface. Otherwise, the filter graph manager will not respond correctly to changes in screen resolution and other events.

If the pCategory parameter is NULL, this method searches the entire graph for the requested interface. Starting from the filter specified by the pf parameter, it queries the following objects in the graph.

  • The filter
  • The filter's pins
  • All the downstream filters, including their pins
  • All the upstream filters, including their pins

You can restrict the search by setting the pCategory and pType parameters, as follows:

  • If pCategory equals &LOOK_UPSTREAM_ONLY, the search starts from the filter's input pins and continues upstream. It does not include the filter or anything downstream from the filter. The pType parameter is ignored.
  • If pCategory equals &LOOK_DOWNSTREAM_ONLY, the search starts from the filter's output pins and continues downstream. It does not include the filter or anything upstream from the filter. The pType parameter is ignored.
  • If pCategory specifies a pin category, the downstream portion of the search is restricted to output pins on the filter that match both the pin category and the media type given in the pType parameter. In this case, the method also searches the filter and everything upstream from the filter.

Pin categories are useful for finding pin interfaces on capture filters. For example, a capture filter might have separate pins for capture and preview. If you specify a pin category, you should also specify the media type, to make certain the method selects the correct filter and pin.

Some video capture filters have a video port pin (PIN_CATEGORY_VIDEOPORT) instead of a preview pin. If you specify PIN_CATEGORY_PREVIEW and MEDIATYPE_Video, the method treats any video port pins as preview pins. Your application does not have to test for this possibility.

Supporting Filters. If a capture device uses a Windows Driver Model (WDM) driver, the graph may require certain filters upstream from the WDM Video Capture filter, such as a TV Tuner filter or an Analog Video Crossbar filter. If your graph requires any of these WDM filters, this method automatically inserts them into the graph. The method queries the input pins on the capture filter to determine what mediums they support, and connects them to matching filters.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::FindPin

The FindPin method retrieves a particular pin on a filter, or determines whether a given pin matches the specified criteria.

Syntax

HRESULT FindPin(
  IUnknown *pSource,
  PIN_DIRECTION pindir,
  const GUID *pCategory,
  const GUID *pType,
  BOOL fUnconnected,
  int num,
  IPin **ppPin
);

Parameters

pSource

[in] Pointer to an interface on a filter, or to an interface on a pin.

pindir

[in] Member of the PIN_DIRECTION enumeration that specifies the pin direction (input or output).

pCategory

[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY structure of the Pin Property Set property set, specifying a pin category. Use NULL to match any category.

pType

[in] Pointer to a major type GUID that specifies the media type. Use NULL to match any media type.

fUnconnected

[in] Boolean value that specifies whether the pin must be unconnected. If TRUE, the pin must be unconnected. If FALSE, the pin can be connected or unconnected.

num

[in] Zero-based index of the pin to retrieve, from the set of matching pins. If pSource is a pointer to a filter, and more than one pin matches the search criteria, this parameter specifies which pin to retrieve. If pSource is a pointer to a pin, this parameter is ignored.

ppPin

[out] Address of a pointer to receive the IPin interface of the matching pin.

Return Values

Returns S_OK if a matching pin is found, or E_FAIL otherwise.

Remarks

If pSource is a pointer to a filter, the method searches for the nth pin on that filter that matches the search criteria, where n is given by the num parameter. If the method finds a matching pin, it returns a pointer to the pin in the ppPin parameter.

If pSource is a pointer to a pin, the method tests that pin against the search criteria. If the pin matches the criteria, the method returns S_OK, and returns a pointer to the pin's IPin interface in the ppPin parameter. Otherwise, it returns E_FAIL.

In either case, if the method succeeds, the IPin interface returned in the ppPin parameter has an outstanding reference count. Be sure to release the interface when you are done using it.

Typically, an application will not need to use this method. It is provided for unusually complex tasks, when the ICaptureGraphBuilder2::RenderStream method cannot build the filter graph. Use this method to retrieve a desired pin from a capture filter, and then build the rest of the graph manually.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::GetFiltergraph

The GetFiltergraph method retrieves the filter graph that the capture graph builder is using.

Syntax

HRESULT GetFiltergraph(
  IGraphBuilder **ppfg
);

Parameters

ppfg

[out] Address of a variable that receives an IGraphBuilder interface pointer.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | No filter graph.

Remarks

Initially, the capture graph builder does not hold a pointer to a filter graph. This method returns E_UNEXPECTED until one of the following methods has been called:

  • ICaptureGraphBuilder2::RenderStream
  • ICaptureGraphBuilder2::SetFiltergraph
  • ICaptureGraphBuilder2::SetOutputFileName

This method increments the reference count on the IGraphBuilder interface. Be sure to release the interface when you are done with it.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::RenderStream

The RenderStream method connects an output pin on a source filter to a sink filter, optionally through an intermediate filter.

Syntax

HRESULT RenderStream(
  const GUID *pCategory,
  const GUID *pType,
  IUnknown *pSource,
  IBaseFilter *pIntermediate,
  IBaseFilter *pSink
);

Parameters

pCategory

[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY structure of the Pin Property Set property set, specifying a pin category; or NULL to use any pin, regardless of category. Typical values include the following.

  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW
  • PIN_CATEGORY_CC

pType

[in] Pointer to a major-type GUID that specifies the media type of the output pin; or NULL to use any pin, regardless of media type. For a list of possible values, see Major Types.

pSource

[in] Specifies a pointer to the starting filter for the connection, or to an output pin.

pIntermediate

[in] Pointer to the IBaseFilter interface of an intermediate filter, such as a compression filter. Can be NULL.

pSink

[in] Pointer to the IBaseFilter interface of a sink filter, such as a renderer or mux filter. If the value is NULL, the method uses a default renderer (see Remarks).

Return Values

Returns an HRESULT value. Possible return values include the following.

Return code | Description
S_OK | Success.
VFW_S_NOPREVIEWPIN | Preview was rendered through the Smart Tee Filter.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_NOT_IN_GRAPH | A filter is not in the filter graph. This error can occur if you did not call AddFilter to add pSource, pIntermediate, or pSink to the graph. It can also occur if you did not call SetFiltergraph to connect your graph to the Capture Graph Builder; in this case, the Capture Graph Builder object automatically creates its own filter graph. See About the Capture Graph Builder.

Remarks

This method renders a stream by connecting two or more filters together in a chain:

  • The pSource parameter specifies the start of the chain, either a filter or an output pin.
  • The pIntermediate parameter specifies an intermediate filter, typically a compression filter. This parameter can be NULL.
  • The pSink parameter specifies the filter at the end of the chain. Typically, this filter is either a renderer for preview, or a mux for file capture.

The method connects pSource to pIntermediate, and then connects pIntermediate to pSink. If pIntermediate is NULL, the method just connects pSource to pSink. All of the filters specified by pSource, pIntermediate, and pSink must be added to the graph prior to calling the method. The method uses Intelligent Connect, so additional filters such as decoders might be added to the graph.

If the pSink parameter is NULL, the method tries to use a default renderer. For video it uses the Video Renderer, and for audio it uses the DirectSound Renderer.

If pSource is a filter, the method searches for an output pin on that filter. In that case, use the pCategory and pType parameters to narrow the search. For example, if a filter has separate pins for preview and capture, you can specify either PIN_CATEGORY_CAPTURE or PIN_CATEGORY_PREVIEW. If pSource is an output pin, set the pCategory and pType to NULL.

In all cases, the method searches for unconnected pins. If more than one pin meets the specified criteria, the method uses the first such pin that it finds.

Note that for DV capture, if the media type is MEDIATYPE_Interleaved and the pSink parameter is NULL, the method splits the interleaved stream into an audio stream and a video stream, and renders both of those streams.

The RenderStream method handles many of the details required for capture graphs:

Smart Tee. Some capture filters have a capture pin but no preview pin. To preview, the capture pin must be connected to the Smart Tee Filter. This filter splits the data into two streams, a capture stream and a preview stream. When you specify PIN_CATEGORY_PREVIEW or PIN_CATEGORY_CAPTURE, the method inserts a Smart Tee filter if one is needed. Then it renders the specified stream on the Smart Tee filter. If you render a preview stream and the method uses a Smart Tee filter, it returns VFW_S_NOPREVIEWPIN.

Closed Captioning. You can use this method to capture or preview closed captioning. Some capture filters deliver Vertical Blanking Interval (VBI) data, others deliver closed captioning data. To handle either case, call the method twice, once using PIN_CATEGORY_VBI and once using PIN_CATEGORY_CC. The method inserts any filters needed to convert VBI data to closed captioning. To preview the data, set the pSink parameter to NULL. To capture the data to a file, use the multiplexer filter's IBaseFilter interface pointer. You can capture and preview the data in the same graph. Call the method once using NULL and again using the multiplexer. Set the pIntermediate parameter to NULL.

Video Port Pins. Filters that work with video port extension (VPE) video capture hardware might have video port pins (PIN_CATEGORY_VIDEOPORT) instead of preview pins. For preview or capture to work, a video port pin must connect to the Overlay Mixer Filter. The method handles this detail. You do not have to specify PIN_CATEGORY_VIDEOPORT. Specify PIN_CATEGORY_PREVIEW or PIN_CATEGORY_CAPTURE, and the method will connect the pin correctly. In a similar way, some filters deliver VBI data using video port pins (PIN_CATEGORY_VIDEOPORT_VBI). As with PIN_CATEGORY_VIDEOPORT, the method handles this detail. You do not have to specify PIN_CATEGORY_VIDEOPORT_VBI.

Supporting Filters. If a capture device uses a Windows Driver Model (WDM) driver, the graph may require certain filters upstream from the WDM Video Capture Filter, such as a TV Tuner Filter or an Analog Video Crossbar Filter. If this method successfully renders the stream, it also inserts any WDM filters that are required in your graph. The method queries the input pins on the capture filter to determine what mediums they support, and connects them to matching filters.

Example Code

For a typical capture graph, connect the preview pin to the default renderer, with no intermediate filter:

// Video:
pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
    pCaptureFilter, NULL, NULL);
// Audio:
pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Audio,
    pCaptureFilter, NULL, NULL);

Connect the capture pin to a mux filter or file writer filter, depending on what type of file you wish to output. For AVI files, use the AVI Mux filter. For ASF files, use the WM ASF Writer filter. Typically, you will get a pointer to this filter from the ppf parameter of the ICaptureGraphBuilder2::SetOutputFileName method.

pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi, L"C:\\Example.avi",
    &ppf, &pSink);
pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
    pCaptureFilter, NULL, ppf);

For more examples, see Video Capture.

File Sources. You can use this method to transcode or recompress a file. The following discussion assumes that the file has at most one video stream and one audio stream, or else a single interleaved stream. Otherwise, the method will not work correctly.

A file source has one output pin, so set pCategory and pType to NULL. Call the method twice—once to render the video stream, and once to render the audio stream. The first call connects the source filter to a parser filter and renders one of the parser filter's output pins. The second call renders the parser's remaining output pin. If you are compressing one stream but not the other, make sure to specify the compressor filter in the first call. The method will automatically pick the correct stream based on the compression type.

pBuilder->RenderStream(NULL, NULL, pSrc, pCompressor, pMux);
pBuilder->RenderStream(NULL, NULL, pSrc, NULL, pMux);

For a complete example, see Recompressing an AVI File.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::SetFiltergraph

The SetFiltergraph method specifies a filter graph for the capture graph builder to use.

Syntax

HRESULT SetFiltergraph(
  IGraphBuilder *pfg
);

Parameters

pfg

[in] Pointer to the filter graph's IGraphBuilder interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

If you do not call this method, the capture graph builder automatically creates a filter graph when it needs one. If the capture graph builder already has a filter graph, this method returns E_UNEXPECTED.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICaptureGraphBuilder2::SetOutputFileName

The SetOutputFileName method creates the file writing section of the filter graph.

Syntax

HRESULT SetOutputFileName(
  const GUID *pType,
  LPCOLESTR lpwstrFile,
  IBaseFilter **ppf,
  IFileSinkFilter **pSink
);

Parameters

pType

[in] Pointer to a GUID that represents either the media subtype of the output or the class identifier (CLSID) of a multiplexer filter or file writer filter. If you specify a media subtype, it must be one of the following:

Value | Description
MEDIASUBTYPE_Avi | Audio-Video Interleaved (AVI)
MEDIASUBTYPE_Asf | Advanced Systems Format (ASF)

lpwstrFile

[in] Pointer to a wide-character string that contains the output file name.

ppf

[out] Address of a pointer that receives the multiplexer's IBaseFilter interface.

pSink

[out] Address of a pointer that receives the file writer's IFileSinkFilter interface. Can be NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.

Remarks

This method creates a multiplexer filter based on the value of the pType parameter. For AVI, it creates the AVI Mux Filter. For ASF, it creates the WM ASF Writer. For other values, it creates the filter identified by the CLSID. It adds the multiplexer to the filter graph, and returns a pointer to its IBaseFilter interface in the ppf parameter.

If the multiplexer supports the IFileSinkFilter interface, the method calls IFileSinkFilter::SetFileName to set the output file name, using the value given in the lpwstrFile parameter. If the multiplexer does not support IFileSinkFilter interface, the method adds the File Writer Filter to the filter graph, connects the multiplexer to the file writer, and uses the file writer's IFileSinkFilter interface to call SetFileName. If the pSink parameter is not NULL, it receives a pointer to the IFileSinkFilter interface.

You can use the pointer to the multiplexer filter, returned in the ppf parameter, as the pSink parameter in the ICaptureGraphBuilder2::RenderStream method.

For custom multiplexer filters, the method fails if the filter does not support a connection on its output pin before its input pins are connected. For example, the WavDest Filter Sample included with the SDK has this limitation.

If the method succeeds, the IBaseFilter interface returned in the ppf parameter has an outstanding reference count. If the method succeeds and pSink is not NULL, the IFileSinkFilter interface also has an outstanding reference count. Be sure to release both interfaces when you are done using them.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder2 Interface


ICodecAPI Interface

The ICodecAPI interface defines a standard way for applications and drivers to communicate with third-party hardware or software encoders that implement the interface. For more information about this interface, see Encoder API.

Note This interface supersedes the IEncoderAPI interface, which has been deprecated.

It is expected that encoders will store profile and capability information in the system registry. This will enable applications to query the device during device enumeration. Default profiles are stored in HLKM\Software\Classes\CLSID\<category>\Profiles. Each profile is a registry key whose default string is a text description of the profile. Each value has a GUID name, followed by a string value containing the numeric GUID value. For example:

  HLKM\Software\Classes\CLSID\<category>\Profiles\DVD
    default "HQ DVD"
    REG_SZ {659e5ecc-b1b9-4d29-8304-86911fb33165} = "0"
    REG_SZ {3c2009e0-7598-4454-86ba-de8edc342645} = "1234"

where {...} is a property GUID that the application can map into its user interface. Microsoft is currently considering the definition of a set of standard profiles.

Default codec capabilities are stored under HLKM\Software\Classes\CLSID\<category>\Instance\<Filter CLSID>\Capabilities. Each value has a GUID name, followed by a string value containing the numeric GUID value. For example:

HLKM\Software\Classes\CLSID\<category>\Instance\<My DVD encoder>\Capabilities
     default "My DVD encoder"
     REG_SZ_MULTI {659e5ecc-b1b9-4d29-8304-86911fb33165}

where {...} is a property GUID that the application can map into its user interface.

In addition to the methods inherited from IUnknown, the ICodecAPI interface exposes the following methods.

Method | Description
GetAllSettings | Saves the current encoder settings to a stream.
GetDefaultValue | Retrieves the default value for a parameter, if one exists.
GetParameterRange | Returns the valid range of values for a parameter.
GetParameterValues | Returns the list of supported values for a given parameter.
GetValue | Retrieves the current value of a specified parameter.
IsModifiable | Queries whether a parameter can be changed.
IsSupported | Queries whether a given parameter is supported.
RegisterForEvent | Registers the application to receive a specified event from the encoder.
SetAllDefaults | Returns all parameters to their default values.
SetAllDefaultsWithNotify | Returns all parameters to their default values, and returns a list of the settings that have changed.
SetAllSettings | Loads encoder settings from a stream and sets them on the encoder.
SetAllSettingsWithNotify | Loads encoder settings from a stream, sets them on the encoder, and returns a list of the settings that have changed.
SetValue | Sets the value of a parameter.
SetValueWithNotify | Sets the value of a parameter, and returns a list of other settings that have changed as a result.
UnregisterForEvent | Unregisters the application for a specified encoder event.

Remarks

The IEncoderAPI interface defined a set of GUIDs that identify various encoder parameters. The ICodecAPI interface will also support these GUIDs, but it is expected that a broader list of supported GUIDs will be defined for use with this interface. Please refer to the IEncoderAPI documentation for the list of the previously defined GUIDs.

See Also

  • Encoder API


ICodecAPI::GetAllSettings

The GetAllSettings method saves the current encoder settings to a stream.

Syntax

HRESULT GetAllSettings(
    IStream *pStream
);

Parameters

pStream

[in] Pointer to the IStream interface of the stream.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::GetDefaultValue

The GetDefaultValue method retrieves the default value for a parameter, if one exists.

Syntax

HRESULT GetDefaultValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Pointer to a VARIANT type that receives the default value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

If there is no default value for the parameter, the method fails.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::GetParameterRange

The GetParameterRange method returns the valid range of values for a parameter. This method applies to parameters that support a stepped range of values, as opposed to a list of specific values.

Syntax

HRESULT GetParameterRange(
  const GUID*  Api,
  VARIANT*  ValueMin,
  VARIANT*  ValueMax,
  VARIANT*  SteppingDelta
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

ValueMin

[out] Pointer to a VARIANT type that receives the minimum value of the parameter.

ValueMax

[out] Pointer to a VARIANT type that receives the maximum value of the parameter.

SteppingDelta

[out] Pointer to a VARIANT type that receives the stepping delta, which defines the valid increments from ValueMin to ValueMax.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The valid range for the parameter is [ValueMin ... ValueMax], with increments of SteppingDelta. If a parameter supports a stepped range of values, it must use one of the following variant types:

  • Unsigned types: VT_UI8, VT_UI4, VT_UI2, VT_UI1
  • Signed types: VT_I8, VT_I4, VT_I2
  • Floating-point types: VT_R8, VT_R4

By definition, the parameter will return a specific type.

Any stepping value is valid. If the range has no stepping delta (that is, you can increment by any value), the encoder should return an empty value (VT_EMPTY) for SteppingDelta.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::GetParameterValues

The GetParameterValues method returns the list of supported values for a given parameter. This method applies to parameters that support a list of specific values, as opposed to a stepped range of values.

Syntax

HRESULT GetParameterValues(
  const GUID*  Api,
  VARIANT**  Values
  ULONG*  ValuesCount,

);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Values

[out] Address of a variable that receives a pointer to an array of VARIANT types. The array contains the list of values the encoder supports for this parameter. The caller must free the array by calling the CoTaskMemFree function.

ValuesCount

[out] Pointer to a variable that receives the number of elements in the array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::GetValue

The GetValue method retrieves the current value of a specified parameter.

Syntax

HRESULT GetValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Pointer to a VARIANT type that receives the value of the parameter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI Interface
  • ICodecAPI::SetValue
  • Encoder API


ICodecAPI::IsModifiable

The IsModifiable method queries whether a parameter can be changed, given the current configuration of the encoder.

Syntax

HRESULT IsModifiable(
  const GUID* Api
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Return Values

Returns an HRESULT value. Possible values are shown in the following table.

Return code | Description
S_FALSE | The parameter cannot be changed.
S_OK | The parameter can be changed.

Remarks

Any errors besides those in the previous table indicate an inability to process the call.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::IsSupported

The IsSupported method queries whether a given parameter is supported.

Syntax

HRESULT IsSupported(
  const GUID* Api
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Return Values

Returns an HRESULT value. Possible values are shown in the following table.

Return code | Description
E_NOTIMPL | The encoder does not support the parameter.
S_OK | The encoder supports the parameter.

Remarks

Any errors besides those in the previous table indicate an inability to process the call.

See Also

  • ICodecAPI Interface
  • Encoder API


ICodecAPI::RegisterForEvent

The RegisterForEvent method registers the application to receive a specified event from the encoder. The application will receive an EC_CODECAPI_EVENT event notification whenever the encoder driver sends the event.

Syntax

HRESULT RegisterForEvent(
  const GUID*  Api,
  LONG_PTR  userData
);

Parameters

Api

[in] Pointer to a GUID that specifies the event.

userData

[out] Pointer to caller-defined data. The application receives this pointer in the lParam1 event parameter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

Currently, the following GUID is defined.

Event GUID | Description
CODECAPI_CHANGELISTS | Notifies the client about which parameters have changed in the encoder.

For more information, see CodecAPIEventData Structure.

See Also

  • ICodecAPI::UnregisterForEvent
  • Encoder API


ICodecAPI::SetAllDefaults

The SetAllDefaults method returns all parameters to their default values.

Syntax

HRESULT SetAllDefaults();

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::SetAllDefaultsWithNotify

The SetAllDefaultsWithNotify method returns all parameters to their default values, and returns a list of the settings that have changed.

Syntax

HRESULT SetAllDefaultsWithNotify(
  GUID** ChangedParam,
  ULONG* ChangedParamCount
);

Parameters

[out] ChangedParam

Address of a variable that receives a pointer to an array of GUIDs, of size ChangedParamCount. The array contains the GUIDs of the parameters that have changed in the encoder as a result of this method call. The caller must free the array by calling the CoTaskMemFree function.

[out] ChangedParamCount

Pointer to a variable that receives the number of elements in the array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::SetAllSettings

The SetAllSettings method loads encoder settings from a stream and sets them on the encoder.

Syntax

HRESULT SetAllSettings(
    IStream *pStream
);

Parameters

pStream

[in] Pointer to the IStream interface of the stream.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::SetAllSettingsWithNotify

The SetAllSettingsWithNotify method loads encoder settings from a stream, sets them on the encoder, and returns a list of the settings that have changed.

Syntax

HRESULT SetAllSettingsWithNotify(
    IStream *pStream,
    GUID **ChangedParam,
    ULONG *ChangedParamCount
);

Parameters

pStream

[in] Pointer to the IStream interface of the stream.

ChangedParam

[out] Address of a variable that receives a pointer to an array of GUIDs, of size ChangedParamCount. The array contains the GUIDs of the parameters that have changed in the encoder as a result of this method call. The caller must free the array by calling the CoTaskMemFree function.

ChangedParamCount

[in] Pointer to a variable that receives the number of elements in the array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::SetValue

The SetValue method sets the value of a parameter.

Syntax

HRESULT SetValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Pointer to a VARIANT type that contains the new value for the parameter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::SetValueWithNotify

The SetValueWithNotify method sets the value of a parameter, and returns a list of other settings that have changed as a result.

Syntax

HRESULT SetValueWithNotify(
  const GUID* Api,
  VARIANT* Value,
  GUID** ChangedParam,
  ULONG* ChangedParamCount
);

Parameters

[in] Api

Pointer to a GUID that specifies the parameter.

[in] Value

Pointer to a VARIANT type that contains the new value for the parameter.

[out] ChangedParam

Address of a variable that receives a pointer to an array of GUIDs, of size ChangedParamCount. The array contains the GUIDs of the parameters that have changed in the encoder as a result of this method call. The caller must free the array by calling the CoTaskMemFree function.

[out] ChangedParamCount

Pointer to a variable that receives the number of elements in the array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::GetValue
  • Encoder API


ICodecAPI::UnregisterForEvent

The UnregisterForEvent method unregisters the application for a specified encoder event.

Syntax

HRESULT UnregisterForEvent(
  const GUID*  Api,
);

Parameters

Api

[in] Pointer to a GUID that specifies the event.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • ICodecAPI::RegisterForEvent
  • Encoder API


IConfigAsfWriter Interface

The IConfigAsfWriter interface is implemented by the WM ASF Writer filter and provides methods for getting and setting the Advanced Systems Format (ASF) profiles the filter will use to write files.

When the WM ASF Writer filter is created, it is configured automatically with a default ASF audio-visual profile based on the incoming streams. A profile describes various attributes of an ASF file such as bit rate, number and type of streams, compression quality, and so on. The filter uses the profile to determine what kind of ASF file to write, how many input pins to create, and what media types to accept. In most cases, the default profile should be suitable, but if it is not, an application can modify it using the IConfigAsfWriter interface. For details about ASF profiles, see the Microsoft® Windows Media™ Software Development Kit (SDK). For more information about writing ASF files, see Creating ASF Files in DirectShow.

Requirements

Requires Dshowasf.h, Windows Media Format SDK.

In addition to the methods inherited from IUnknown, the IConfigAsfWriter interface exposes the following methods.

Method | Description
ConfigureFilterUsingProfileGuid | Configures the filter to write an ASF file based on the specified predefined Windows Media Format SDK profile GUID.
ConfigureFilterUsingProfile | Configures the filter to write an ASF file based on the specified application-defined profile.
ConfigureFilterUsingProfileId | Configures the filter to write an ASF file with a profile identifier (ID) index from the system profile list. (For Windows Media Format 4.0 profiles only.)
GetCurrentProfileGuid | Retrieves the current ASF profile GUID defined by the Windows Media Format SDK.
GetCurrentProfile | Retrieves the application-defined ASF profile.
GetCurrentProfileId | Retrieves the current ASF profile ID. (For Windows Media Format 4.0 profiles only.)
GetIndexMode | Retrieves the current index mode.
SetIndexMode | Enables the application to control whether the file will be indexed and therefore seekable.


IConfigAsfWriter::ConfigureFilterUsingProfile

The ConfigureFilterUsingProfile method configures the filter to write an ASF file based on the specified application-defined profile.

Syntax

HRESULT ConfigureFilterUsingProfile(
  IWMProfile *pProfile
);

Parameters

pProfile

[in] IWMProfile interface pointer to the application-defined profile.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
VFW_E_WRONG_STATE | The graph is stopped.
E_POINTER | The IWMProfile interface pointer is invalid.

Remarks

IWMProfile is defined in the Windows Media Format SDK.

If successful, this method will cause an EC_GRAPH_CHANGED event to be sent to the application.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::ConfigureFilterUsingProfileGuid

The ConfigureFilterUsingProfileGuid method configures the filter to write an ASF file based on the specified predefined profile.

Syntax

HRESULT ConfigureFilterUsingProfileGuid(
  REFGUID guidProfile
);

Parameters

guidProfile

[in] Profile GUID as defined in the Windows Media Format SDK header file Wmsysprf.h.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_FAIL | The profile is invalid.
VFW_E_WRONG_STATE | The filter graph is stopped.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::ConfigureFilterUsingProfileId

The ConfigureFilterUsingProfileId method configures the filter to write an ASF file with a profile identifier (ID) index from the system profile list. (For Windows Media Format 4.0 profiles only.)

Syntax

HRESULT ConfigureFilterUsingProfileId(
  DWORD dwProfileId
);

Parameters

dwProfileId

[in] Profile ID as defined in the Windows Media Format SDK.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_FAIL | The profile is invalid.
VFW_E_WRONG_STATE | The filter graph is stopped.

Remarks

This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. To configure the filter for version 7.0 and later profiles, use ConfigureFilterUsingProfile or ConfigureFilterUsingProfileGuid.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::GetCurrentProfile

The GetCurrentProfile method retrieves the application-defined ASF profile.

Syntax

HRESULT GetCurrentProfile(
  IWMProfile **ppProfile
);

Parameters

ppProfile

[out] Address of a pointer that receives the IWMProfile interface of the application-defined profile.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

If the method succeeds, the IWMProfile pointer that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::GetCurrentProfileGuid

The GetCurrentProfileGuid method retrieves the current ASF profile ID.

Syntax

HRESULT GetCurrentProfileGuid(
  GUID *pProfileGuid
);

Parameters

pProfileGuid

[out] Pointer to a variable of type GUID that receives the profile ID.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::GetCurrentProfileId

The GetCurrentProfileId method retrieves the current ASF profile ID. (For Windows Media Format 4.0 profiles only.)

Syntax

HRESULT GetCurrentProfileId(
  DWORD *pdwProfileId
);

Parameters

pdwProfileId

[out] Pointer to a variable of type DWORD that receives the current profile ID.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. Use GetCurrentProfile or GetCurrentProfileGuid instead to correctly identify a profile for version 4.0, 7.0 and later.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::GetIndexMode

The GetIndexMode method retrieves the current index mode.

Syntax

HRESULT GetIndexMode(
  BOOL *pbIndexFile
);

Parameters

pbIndexFile

[out] Pointer to a variable of type BOOL that receives the index mode setting. A value of TRUE indicates that the WM ASF Writer is configured to write indexed files.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

Use this method to determine whether the WM ASF Writer is currently configured to write indexed ASF files. See the Remarks for SetIndexMode for more information.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAsfWriter::SetIndexMode

The SetIndexMode method enables the application to control whether the file will be indexed and therefore seekable.

Syntax

HRESULT SetIndexMode(
  BOOL bIndexFile
);

Parameters

bIndexFile

[in] Variable of type BOOL; TRUE specifies that the file will be indexed.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

By default, the WM ASF Writer creates indexed ASF files. It performs the indexing when the graph stops. You can disable this behavior if you want to do your own indexing as a post-processing step.

See Also

  • Error and Success Codes
  • IConfigAsfWriter Interface


IConfigAviMux Interface

The IConfigAviMux interface controls how the AVI Mux Filter writes files out to disk. DirectShow currently exposes this interface through the property page of the AVI multiplexer filter and you can use it to set the master stream and compatibility indexes.

IConfigAviMux provides backward compatibility with older Video for Windows® Audio-Video Interleaved (AVI) index formats (idx1) as well as extended AVI 2.0 index formats (indx) to allow for file sizes greater than 1 gigabyte (GB). Set and retrieve the compatibility indexes by using the IConfigAviMux::SetOutputCompatibilityIndex and IConfigAviMux::GetOutputCompatibilityIndex methods.

In addition to the methods inherited from IUnknown, the IConfigAviMux interface exposes the following methods.

Method | Description
GetMasterStream | Queries which stream will be used to synchronize the other streams in the file.
GetOutputCompatibilityIndex | Retrieves the setting for the AVI index format.
SetMasterStream | Specifies a stream that will be used to synchronize the other streams in the file.
SetOutputCompatibilityIndex | Sets the AVI index format.


IConfigAviMux::GetMasterStream

The GetMasterStream method queries which stream will be used to synchronize the other streams in the file.

Syntax

HRESULT GetMasterStream(
  LONG *pStream
);

Parameters

pStream

[out] Pointer to a variable that receives the index of the master stream, or -1 if no master stream was set.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IConfigAviMux Interface
  • IConfigAviMux::SetMasterStream


IConfigAviMux::GetOutputCompatibilityIndex

The GetOutputCompatibilityIndex method retrieves the setting for the AVI index format.

Syntax

HRESULT GetOutputCompatibilityIndex(
  BOOL *pfOldIndex
);

Parameters

pfOldIndex

[out] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | Create an AVI 1.0 index, as well as an AVI 2.0 index.
FALSE | Create an AVI 2.0 index, but not an AVI 1.0 index.

Remarks

The AVI Mux filter always creates an AVI 2.0 index ('indx' format). If the value returned in pfOldIndex is TRUE, the AVI Mux also creates an AVI 1.0 index ('idx1' format), for backward compatibility with Video for Windows.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IConfigAviMux Interface
  • IConfigAviMux::SetOutputCompatibilityIndex


IConfigAviMux::SetMasterStream

The SetMasterStream method specifies a stream that will be used to synchronize the other streams in the file.

Syntax

HRESULT SetMasterStream(
  LONG iStream
);

Parameters

iStream

[in] Specifies the index of the stream, or –1 to indicate no master stream. The AVI Mux writes one stream for each connected input pin. Stream numbers are indexed from zero.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

If you are capturing audio and video from two different sources, use this method to synchronize the streams. Streams coming from separate capture sources may be captured at slightly different rates. If you specify a master stream, the AVI Mux adjusts the playback rates for the other streams, to compensate for any drift that might occur.

It is recommended to use the audio stream as the master stream, because minor adjustments to the video playback rate are less noticeable than changes to the audio playback rate. Also, modifying the audio playback rate will cause the audio to be resampled by the audio driver.

This method works by adjusting the dwScale and dwRate values in the AVISTREAMHEADER structure.

See Also

  • AVI RIFF File Reference
  • Error and Success Codes
  • IConfigAviMux Interface


IConfigAviMux::SetOutputCompatibilityIndex

The SetOutputCompatibilityIndex method sets the AVI index format.

Syntax

HRESULT SetOutputCompatibilityIndex(
  BOOL fOldIndex
);

Parameters

fOldIndex

[in] Specifies one of the following values:

Value | Description
TRUE | Create an AVI 1.0 index, as well as an AVI 2.0 index.
FALSE | Create an AVI 2.0 index, but not an AVI 1.0 index.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

The AVI Mux filter always creates an AVI 2.0 index ('indx' format). If the value given in fOldIndex is TRUE, the AVI Mux also creates an AVI 1.0 index ('idx1' format), for backward compatibility with Video for Windows.

The AVI 2.0 index format allows for larger files, incremental growth of files, and minimized disk seeks.

See Also

  • Error and Success Codes
  • IConfigAviMux Interface


IConfigInterleaving Interface

The IConfigInterleaving interface is implemented on the AVI Mux Filter. The interface controls how files are written out to disk and sets interleaving configuration information such as frequency and preroll parameters.

This interface uses the InterleavingMode enumeration, which specifies how audio samples and video frames will be saved on a disk. Capture interleaving settings can range from INTERLEAVE_NONE to INTERLEAVE_FULL, depending on whether you will author immediately or later.

Video-authoring applications that handle capturing should use this interface when they need to control how audio samples and video frames will be saved on a disk.

In addition to the methods inherited from IUnknown, the IConfigInterleaving interface exposes the following methods.

Method | Description
get_Interleaving | Retrieves the audio preroll time and the frequency of the interleaving.
get_Mode | Retrieves the interleaving quality setting.
put_Interleaving | Sets the audio preroll time and the frequency of the interleaving.
put_Mode | Sets how audio samples and video frames will be saved on disk by specifying quality of interleaving.


IConfigInterleaving::get_Interleaving

The get_Interleaving method retrieves the audio preroll time and the frequency of the interleaving.

Syntax

HRESULT get_Interleaving(
  REFERENCE_TIME *prtInterleave,
  REFERENCE_TIME *prtPreroll
);

Parameters

prtInterleave

[out] Pointer to the frequency of the streams in the file, in 100-nanosecond units.

prtPreroll

[out] Pointer to the audio preroll, in 100-nanosecond units.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IConfigInterleaving Interface
  • IConfigInterleaving::put_Interleaving


IConfigInterleaving::get_Mode

The get_Mode method retrieves the interleaving quality setting.

Syntax

HRESULT get_Mode(
  InterleavingMode *pMode
);

Parameters

pMode

[out] Pointer to the interleaving quality setting specified in the InterleavingMode enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IConfigInterleaving Interface
  • IConfigInterleaving::put_Mode


IConfigInterleaving::put_Interleaving

The put_Interleaving method sets the audio preroll time and the frequency of the interleaving.

Syntax

HRESULT put_Interleaving(
  const REFERENCE_TIME *prtInterleave,
  const REFERENCE_TIME *prtPreroll
);

Parameters

prtInterleave

[in] Pointer to the frequency of the streams in the file, in 100-nanosecond units.

prtPreroll

[in] Pointer to the audio preroll, in 100-nanosecond units.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

An audio preroll of 750 milliseconds is recommended when authoring a file for distribution.

The default value for prtInterleave is 1000 milliseconds; however, you can adjust this. The smaller the number, the larger the file.

See Also

  • Error and Success Codes
  • IConfigInterleaving Interface
  • IConfigInterleaving::get_Interleaving


IConfigInterleaving::put_Mode

The put_Mode method sets how audio samples and video frames are to be written to disk, by specifying quality of interleaving.

Syntax

HRESULT put_Mode(
  InterleavingMode mode
);

Parameters

mode

[in] Interleaving quality setting specified in the InterleavingMode enumeration.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IConfigInterleaving Interface
  • IConfigInterleaving::get_Mode


ICreateDevEnum Interface

The ICreateDevEnum interface creates an enumerator for devices within a particular category, such as video capture devices, audio capture devices, video compressors, and so forth. The System Device Enumerator exposes this interface.

Applications can use this interface to enumerate devices and to create the DirectShow filter that manages each device. The CreateClassEnumerator method returns an enumerator object for a specific device category. The enumerator object supports the IEnumMoniker interface and returns a list of monikers, where each moniker represents a different device. In some cases, the same DirectShow filter manages an entire category of devices.

For more information on using this interface, see Using the System Device Enumerator. For more information on using enumerators, see the IEnumXXXX topic in the Platform SDK documentation.

In addition to the methods inherited from IUnknown, the ICreateDevEnum interface exposes the following method.

Method | Description
CreateClassEnumerator | Creates a class enumerator for a specified device category.


ICreateDevEnum::CreateClassEnumerator

The CreateClassEnumerator method creates an enumerator for a specified device category.

Syntax

HRESULT CreateClassEnumerator(
  REFCLSID clsidDeviceClass,
  IEnumMoniker **ppEnumMoniker,
  DWORD dwFlags
);

Parameters

clsidDeviceClass

[in] Specifies the class identifier (CLSID) of the device category. See Filter Categories.

ppEnumMoniker

[out] Address of a variable that receives an IEnumMoniker interface pointer.

dwFlags

[in] Bitwise combination of zero or more flags. If zero, the method enumerates every filter in the category. If any flags are set, the enumeration includes only filters that match the specified flags. The following flags are defined:

Flag | Description
CDEF_DEVMON_CMGR_DEVICE | Enumerate audio or video codecs, using the audio compression manager (ACM) or video compression manager (VCM).
CDEF_DEVMON_DMO | Enumerate DirectX Media Objects (DMOs).
CDEF_DEVMON_FILTER | Enumerate native DirectShow filters.
CDEF_DEVMON_PNP_DEVICE | Enumerate Plug and Play hardware devices.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_OUTOFMEMORY | There is not enough memory available to create a class enumerator.
S_FALSE | The category specified by clsidDeviceClass does not exist or is empty.
E_POINTER | NULL pointer argument.

Remarks

If the category does not exist or is empty, the return value is S_FALSE, and the ppEnumMoniker parameter receives the value NULL. Therefore, test for the return value S_OK instead of using the SUCCEEDED macro:

IEnumMoniker *pEnum = NULL;
hr = pSysDevEnum->CreateClassEnumerator(
    CLSID_VideoCompressorCategory, &pEnum, 0);
if (hr == S_OK)
{
    // Safe to dereference pEnum.
    pEnum->Release();
}

The returned IEnumMoniker interface has an outstanding reference count. The caller must release the interface.

See Also

  • Error and Success Codes
  • ICreateDevEnum Interface


IDDrawExclModeVideo Interface

The IDDrawExclModeVideo interface is implemented by the Overlay Mixer Filter. The interface enables video playback while in Microsoft® DirectDraw® exclusive full-screen mode. Game applications can use DirectDraw in exclusive full-screen mode and continue playing video. For example, the video can be in the background and graphics can be used on top of it. The application passes in a DirectDraw object and primary surface, and these are passed to the Overlay Mixer filter in the filter graph.

The DVD graph builder object uses IDDrawExclModeVideo to play DVD content while in DirectDraw exclusive full-screen mode. This interface can also be used alone to play MPEG-1 or AVI videos in games.

In addition to the methods inherited from IUnknown, the IDDrawExclModeVideo interface exposes the following methods.

Method | Description
GetDDrawObject | Retrieves the DirectDraw object being used by the Overlay Mixer.
GetDDrawSurface | Retrieves the DirectDraw surface being used by the Overlay Mixer.
GetNativeVideoProps | Retrieves the width, height, and aspect ratio of the Overlay Mixer's primary stream.
SetCallbackInterface | Specifies the callback interface to the Overlay Mixer so that the calling application can be notified about adjustments to the display during video playback.
SetDDrawObject | Sets the DirectDraw object to be used in subsequent drawing.
SetDDrawSurface | Sets the DirectDraw surface to be used in subsequent drawing.
SetDrawParameters | Specifies which part of the original video will appear at which position of the screen.


IDDrawExclModeVideo::GetDDrawObject

The GetDDrawObject method retrieves the DirectDraw object being used by the Overlay Mixer filter.

Syntax

HRESULT GetDDrawObject(
  LPDIRECTDRAW *pDDrawObject,
  BOOL *pbUsingExternal
);

Parameters

pDDrawObject

[out] Address of a pointer to the IDirectDraw interface that the Overlay Mixer is using.

pbUsingExternal

[out] Pointer to a variable that receives a Boolean value. It receives the value TRUE if the Overlay Mixer is using a DirectDraw object specified by IDDrawExclModeVideo::SetDDrawObject, or FALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

If the filter graph has not set a DirectDraw object and the Overlay Mixer has not yet allocated one, then pDDrawObject will be set to NULL and pbUsingExternal will be set to FALSE.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideo::GetDDrawSurface

The GetDDrawSurface method retrieves the DirectDraw surface being used by the Overlay Mixer.

Syntax

HRESULT GetDDrawSurface(
  LPDIRECTDRAWSURFACE *pDDrawSurface,
  BOOL *pdUsingExternal
);

Parameters

pDDrawSurface

[out] Address of a pointer to the IDirectDrawSurface interface that is being used by the Overlay Mixer.

pdUsingExternal

[out] Pointer to a variable that receives a Boolean value. It receives the value TRUE if the Overlay Mixer is using a DirectDraw surface specified by IDDrawExclModeVideo::SetDDrawSurface, or FALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

If the filter graph has not set a DirectDraw surface and the Overlay Mixer has not yet allocated one, then pDDrawSurface will be set to NULL and pdUsingExternal will be set to FALSE.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideo::GetNativeVideoProps

The GetNativeVideoProps method retrieves the current video size and picture aspect ratio of the Overlay Mixer's primary stream.

Syntax

HRESULT GetNativeVideoProps(
  DWORD *pdwVideoWidth,
  DWORD *pdwVideoHeight,
  DWORD *pdwPictAspectRatioX,
  DWORD *pdwPictAspectRatioY
);

Parameters

pdwVideoWidth

[out] Address of variable that receives the width of the video.

pdwVideoHeight

[out] Address of variable that receives the height of the video.

pdwPictAspectRatioX

[out] Address of variable that receives the x-axis aspect ratio.

pdwPictAspectRatioY

[out] Address of variable that receives the y-axis aspect ratio.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.

Remarks

The filter graph should look for the EC_VIDEO_SIZE_CHANGED event, and on its receipt call this method to adjust the aspect ratio and position.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideo::SetCallbackInterface

The SetCallbackInterface method retrieves a pointer to the callback interface of the Overlay Mixer so that the calling application can be notified about adjustments to the display during video playback.

Syntax

HRESULT SetCallbackInterface(
  IDDrawExclModeVideoCallback *pCallback,
  DWORD dwFlag
);

Parameters

pCallback

[out] Pointer to the object that implements the IDDrawExclModeVideoCallback interface. If pCallback is NULL, the callback interface is set to NULL and no more callbacks are made. If there was a previous callback interface, it is released and no more callbacks are made to it. If pCallback is not NULL and this method returns S_OK, then the reference count of the object pCallback points to is incremented.

dwFlag

[in] Must be zero.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.

Remarks

An application should use this method to get notification about the overlay size, position, or color key change happening, so that it can hide or show the video, or adjust the video at the start, end, or during playback. By calling this method, an application can access the IDDrawExclModeVideoCallback interface and pass the pointer to that interface to the Overlay Mixer.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideo::SetDDrawObject

The SetDDrawObject method sets the DirectDraw object to be used in subsequent drawing.

Syntax

HRESULT SetDDrawObject(
  LPDIRECTDRAW pDDrawObject
);

Parameters

pDDrawObject

[in] Pointer to the IDirectDraw interface on the object to use.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

A game application can use this method to share its DirectDraw object with the Overlay Mixer filter, so that the video can be drawn in a specified surface, as set in IDDrawExclModeVideo::SetDDrawSurface.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideo::SetDrawParameters

The SetDrawParameters method specifies which part of the original video will appear at which position of the screen.

Syntax

HRESULT SetDrawParameters(
  const RECT *pSrcRect,
  const RECT *pDestRect
);

Parameters

pSrcRect

[in] Pointer to the RECT structure of the original video.

pDestRect

[in] Pointer to the RECT that indicates where the video will appear on the screen.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface
  • IDDrawExclModeVideoCallback Interface


IDDrawExclModeVideo::SetDDrawSurface

The SetDDrawSurface method specifies the DirectDraw surface to be used in subsequent drawing.

Syntax

HRESULT SetDDrawSurface(
  LPDIRECTDRAWSURFACE pDDrawSurface
);

Parameters

pDDrawSurface

[in] Pointer to the IDirectDrawSurface interface on the surface to use.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

A game application can use this to share the DirectDraw surface it has created for itself to the Overlay Mixer filter so that the video can be drawn in a specified surface. This surface must be associated with the object specified in IDDrawExclModeVideo::SetDDrawObject.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideo Interface


IDDrawExclModeVideoCallback Interface

The IDDrawExclModeVideoCallback interface enables applications to get synchronous notification about changes to the overlay position, size, visibility, and so on, so that the application can adjust its video visibility, size, and position. This avoids any color key flash at the beginning, end, or during playback. The application must implement a COM object supporting this interface.

Implement this interface if you are using an IDDrawExclModeVideo interface and want the callback information. It is important that none of the methods block or slow down the video processing, because this will cause problems with playback. The DDrawXCL sample illustrates how to implement this interface.

Use this interface if you are writing a filter that supports IDDrawExclModeVideo or needs to generate callbacks to enable an application to draw color keys at the right time.

In addition to the methods inherited from IUnknown, the IDDrawExclModeVideoCallback interface exposes the following methods.

Method | Description
OnUpdateColorKey | Informs the application that the color key has changed so that the application can use the new color key to overlay graphics on the video.
OnUpdateOverlay | Informs the application when the overlay surface for the video is about to change.
OnUpdateSize | Informs the application when the size of the video rectangle is about to change.


IDDrawExclModeVideoCallback::OnUpdateColorKey

The OnUpdateColorKey method informs the application that the color key has changed so that the application can use the new color key to overlay graphics on the video.

Syntax

HRESULT OnUpdateColorKey (
  COLORKEY const *pKey,
  DWORD dwColor
);

Parameters

pKey

[out] Pointer to a COLORKEY structure that contains the key type and a palette index.

dwColor

[out] Value indicating the 8-bit palette index of the COLORKEY returned in pKey, if the current display mode is 8-bit palettized. Otherwise, it is a value representing the color key in the pixel format of the current display mode.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | One of the parameters is invalid.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideoCallback Interface


IDDrawExclModeVideoCallback::OnUpdateOverlay

The OnUpdateOverlay method informs the application when the overlay surface for the video is about to become visible, invisible, change size, or change position, so that the application can repaint its window appropriately.

Syntax

HRESULT OnUpdateOverlay(
  BOOL bBeforeChange,
  DWORD dwFlags,
  BOOL bOldVisible,
  const RECT *prcSrcOld,
  const RECT *prcDestOld,
  BOOL bNewVisible,
  const RECT *prcSrcNew,
  const RECT *prcDestNew,
);

Parameters

bBeforeChange

[in] Boolean value specifying whether the call is being made before or after the overlay-related change. TRUE specifies before, FALSE specifies after.

dwFlags

[in] Value from the AM_OVERLAY_NOTIFY_FLAGS enumeration that specifies what is about to change or what changed.

bOldVisible

[in] Boolean value specifying whether the old window is visible. TRUE means the old window is visible.

prcSrcOld

[in] Pointer to the rectangle representing the old source position of the DirectDraw surface.

prcDestOld

[in] Pointer to the rectangle representing the old destination position of the rectangle in the overlay surface.

bNewVisible

[in] Boolean specifying whether the new window is visible. TRUE means the new window is visible.

prcSrcNew

[in] Pointer to the rectangle representing the new source position of the DirectDraw surface.

prcDestNew

[in] Pointer to the rectangle representing the new destination position of the rectangle in the overlay surface.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid parameter.

Remarks

The application should call this method once before the overlay-related change occurs and once after the changes are done. In the call before the change, the overlay change doesn't happen until the application completes executing this method.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideoCallback Interface


IDDrawExclModeVideoCallback::OnUpdateSize

The OnUpdateSize method informs the application that the size of the video rectangle is about to change.

Syntax

HRESULT OnUpdateSize(
  DWORD dwWidth,  DWORD dwHeight,
  DWORD dwARWidth,
  DWORD dwARHeight
);

Parameters

dwWidth

[in] The new width, in pixels, of the video stream.

dwHeight

[in] The new height, in pixels, of the video stream.

dwARWidth

[in] The new horizontal value of the aspect ratio.

dwARHeight

[in] The new vertical value of the aspect ratio.

Return Value

Returns an HRESULT value.

Remarks

This method is called when the size of the rectangle in the video stream changes, for example from 704x480 to 640x480.

See Also

  • Error and Success Codes
  • IDDrawExclModeVideoCallback Interface


IDecimateVideoImage Interface

The IDecimateVideoImage interface specifies decimation on a decoder filter. The term decimation refers to scaling the video output down to a size smaller than the native size of the video.

Applications must not call methods on this interface. The Overlay Mixer filter uses this interface to decimate video at the video decoder.

Decoder filters that can decimate their video output should support this interface.

In addition to the methods inherited from IUnknown, the IDecimateVideoImage interface exposes the following methods.

Method | Description
ResetDecimationImageSize | Specifies that the decoder should no longer decimate its output image.
SetDecimationImageSize | Specifies the dimensions to which the decoder should decimate its output image.


IDecimateVideoImage::ResetDecimationImageSize

The ResetDecimationImageSize method specifies that the decoder should no longer decimate its output image.

Syntax

HRESULT ResetDecimationImageSize(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value indicating the success or failure of the call.

See Also

  • Error and Success Codes
  • IDecimateVideoImage Interface


IDecimateVideoImage::SetDecimationImageSize

The SetDecimationImageSize method specifies the dimensions to which the decoder should decimate its output image.

Syntax

HRESULT SetDecimationImageSize(
  long lWidth,
  long lHeight
);

Parameters

lWidth

[in] Specifies the width of the video image, in pixels.

lHeight

[in] Specifies the height of the video image, in pixels.

Return Values

Returns one of the following HRESULT values.

Return code | Description
E_FAIL | The decoder cannot perform any decimation, or needs to halt decimation it is currently performing.
S_OK | The decoder can decimate the video to the requested size.

See Also

  • Error and Success Codes
  • IDecimateVideoImage Interface


IDeferredCommand Interface

The IDeferredCommand interface enables an application to cancel or modify graph-control commands that the application previously queued using the IQueueCommand interface.

When an application calls an IQueueCommand method on the filter graph manager, it receives a pointer to the IDeferredCommand interface. The application can use the interface to cancel or postpone the command, or retrieve the return value from the command.

In addition to the methods inherited from IUnknown, the IDeferredCommand interface exposes the following methods.

Method | Description
Cancel | Cancels a command that the application previously queued.
Confidence | Retrieves a confidence value that indicates how likely it is for the command to be invoked at the requested time.
GetHResult | Retrieves the return value from the invoked command.
Postpone | Specifies a new invocation time for the command.


IDeferredCommand::Cancel

The Cancel method cancels a command that the application previously queued.

Syntax

HRESULT Cancel(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_ALREADY_CANCELLED | The request was already cancelled.

See Also

  • Error and Success Codes
  • IDeferredCommand Interface


IDeferredCommand::Confidence

The Confidence method retrieves a confidence value that indicates how likely it is for the command to be invoked at the requested time.

This method is not implemented and returns E_NOTIMPL.

Syntax

HRESULT Confidence(
  LONG *pConfidence
);

Parameters

pConfidence

Pointer to a variable that receives the confidence level, on a scale of 0 to 100.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IDeferredCommand Interface


IDeferredCommand::GetHResult

The GetHResult method retrieves the return value from the invoked command.

Syntax

HRESULT GetHResult(
  HRESULT *phrResult
);

Parameters

phrResult

Pointer to a variable that receives the HRESULT value.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_ABORT | Command has not yet been invoked.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IDeferredCommand Interface


IDeferredCommand::Postpone

The Postpone method specifies a new invocation time for the command.

Syntax

HRESULT Postpone(
  REFTIME newtime
);

Parameters

newtime

New time at which to invoke the command.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_TIME_ALREADY_PASSED | The specified time has already passed.

See Also

  • Error and Success Codes
  • IDeferredCommand Interface


IDirectDrawVideo Interface

The IDirectDrawVideo interface is implemented on the Video Renderer and provides applications with information about DirectDraw surfaces and hardware capabilities. Applications use this interface to control what DirectDraw features the Video Renderer will take advantage of. For example, if you are positive that you don't want the Video Renderer to use a hardware overlay you can disable its use via the SetSwitches method.

Note You can't use this interface to force the Video Renderer to use a particular DirectDraw feature; you can only stop it from using that feature.

There is some duplication in this interface with the IDirectDraw interface; however, this interface enables simple access to that information without calling the DirectDraw provider directly.

The Video Renderer doesn't load DirectDraw until it is connected, and likewise DirectDraw is unloaded only when the renderer is disconnected. When the renderer has allocated the DirectDraw surfaces it will use for video playback, an application can obtain a DDSURFACEDESC structure describing it. By passing in a pointer to a DDSURFACEDESC structure, the renderer will fill in the structure with the details of the current surface. If DirectDraw has not been loaded, the renderer will return E_FAIL. If the renderer is using DCI (the predecessor to DirectDraw), the DDSURFACEDESC structure is not filled in but the call will return S_FALSE. The only type of DCI surfaces the renderer uses are primary surfaces.

In addition to the methods inherited from IUnknown, the IDirectDrawVideo interface exposes the following methods.

Method | Description
CanUseOverlayStretch | Determines whether the renderer will check overlay restrictions.
CanUseScanLine | Determines whether the renderer will check the current scan line when drawing.
GetCaps | Retrieves a DirectDraw-defined DDCAPS structure containing the hardware capabilities.
GetDirectDraw | Retrieves the IDirectDraw interface.
GetEmulatedCaps | Retrieves a DirectDraw-defined DDCAPS structure containing the emulated capabilities.
GetFourCCCodes | Retrieves the multimedia format type FOURCC DWORD.
GetSurfaceDesc | Retrieves a description of the DirectDraw surface in use.
GetSurfaceType | Retrieves the actual surface type.
GetSwitches | Retrieves the surface types that the renderer is allowed to use.
SetDefault | Makes the current property settings the global default.
SetDirectDraw | Passes the IDirectDraw interface to a loaded driver.
SetSwitches | Sets the surface types that the renderer is allowed to use.
UseOverlayStretch | Determines whether the renderer should check overlay stretch limitations.
UseScanLine | Determines whether the renderer should check the current scan line when drawing a video.
UseWhenFullScreen | Determines whether DirectShow should change display mode when going to full-screen mode.
WillUseFullScreen | Determines whether DirectShow will change display mode when going to full-screen mode.


IDirectDrawVideo::CanUseOverlayStretch

The CanUseOverlayStretch method determines whether the renderer will check overlay restrictions.

Syntax

HRESULT CanUseOverlayStretch(
  long *UseOverlayStretch
);

Parameters

UseOverlayStretch

Pointer to a value indicating whether the renderer can use overlay restrictions. OATRUE indicates the renderer will check overlay restrictions; OAFALSE indicates it will not.

Return Values

Returns an HRESULT value.

Remarks

For a description of overlay stretching, see IDirectDrawVideo::UseOverlayStretch.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::CanUseScanLine

The CanUseScanLine method determines whether the renderer will check the current scan line when drawing.

Syntax

HRESULT CanUseScanLine(
  long *UseScanLine
);

Parameters

UseScanLine

Pointer to a value indicating whether the renderer will use scan line information. OATRUE indicates the renderer will check the current scan line when drawing; OAFALSE indicates it will not.

Return Values

Returns an HRESULT value.

Remarks

For a description of the use of scan line detection in the DirectShow video renderer, see IDirectDrawVideo::UseScanLine.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetCaps

The GetCaps method retrieves a DirectDraw-defined DDCAPS structure containing the hardware capabilities.

Syntax

HRESULT GetCaps(
  DDCAPS *pCaps
);

Parameters

pCaps

Pointer to a DDCAPS structure containing the hardware capabilities.

Return Values

Returns an HRESULT value.

Remarks

If the renderer has not loaded DirectDraw, this method returns E_FAIL.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetDirectDraw

The GetDirectDraw method retrieves the IDirectDraw interface.

Syntax

HRESULT GetDirectDraw(
  LPDIRECTDRAW *ppDirectDraw
);

Parameters

ppDirectDraw

Address of a pointer to the IDirectDraw interface.

Return Values

Returns an HRESULT value.

Remarks

If an application wants to load DirectDraw but allow the renderer to also allocate surfaces, it can let the renderer load DirectDraw and then obtain a reference-incremented interface to it through this method. The interface returned should be released by the application when it is finished with it.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetEmulatedCaps

The GetEmulatedCaps method retrieves a DirectDraw-defined DDCAPS structure containing the emulated capabilities.

Syntax

HRESULT GetEmulatedCaps(
  DDCAPS *pCaps
);

Parameters

pCaps

Pointer to a DDCAPS structure containing the emulated capabilities.

Return Values

Returns an HRESULT value. If the renderer has not loaded DirectDraw, this method returns E_FAIL.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetFourCCCodes

The GetFourCCCodes method retrieves the multimedia format type.

Syntax

HRESULT GetFourCCCodes(
  DWORD *pCount,
  DWORD *pCodes
);

Parameters

pCount

Pointer to the number of FOURCC codes in the pCodes array.

pCodes

Pointer to an array of DWORD media tags formerly used for Microsoft multimedia types.

Return Values

Returns an HRESULT value.

Remarks

In the original Microsoft® Windows® multimedia APIs, media types were tagged with 32-bit values created from four 8-bit characters and were known as FOURCC codes. Because FOURCC codes are unique, a one-to-one mapping has been made possible by allocating a range of 4 billion GUIDs representing FOURCCs.

This method retrieves the FOURCC codes that the current display driver can support. The number available is obtained by calling the method with a valid pCount pointer, but with pCodes set to NULL. In this case, the pCount variable will be filled in with the number of FOURCC codes available. An application can then allocate enough DWORD values for this many FOURCC codes and call the method again with the array pointer in pCodes.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetSurfaceDesc

The GetSurfaceDesc method retrieves a DDSURFACEDESC structure describing the current DirectDraw surface.

Syntax

HRESULT GetSurfaceDesc(
  DDSURFACEDESC *pSurfaceDesc
);

Parameters

pSurfaceDesc

Pointer to a DDSURFACEDESC structure describing the current DirectDraw surface.

Return Values

Returns an HRESULT value. If no surface has been allocated, this method will return E_FAIL. If a DCI primary surface is in use, the DDSURFACEDESC structure will not be filled in and the call will return S_FALSE.

Remarks

Surfaces are allocated only when the renderer is paused. After the renderer has been paused, it cannot release the surfaces when stopped.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetSurfaceType

The GetSurfaceType method retrieves the actual surface type as a DirectShow DirectDraw Surface (AMDDS) definition.

Syntax

HRESULT GetSurfaceType(
  DWORD *pSurfaceType
);

Parameters

pSurfaceType

Pointer to variable that receives a bitwise-OR of one or more of the following values.

Value | Description
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Values

Returns an HRESULT value.

Remarks

It is not always easy to discover which kind of surface is being used by looking at a DDSURFACEDESC structure. Therefore, an application can call GetSurfaceType to retrieve the surface type. The field will be filled in with one bit setting selected from the preceding list of AMDDS definitions.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::GetSwitches

The GetSwitches method retrieves the surface types that the renderer is allowed to use.

Syntax

HRESULT GetSwitches(
  DWORD *pSwitches
);

Parameters

pSwitches

Pointer to a bit mask containing one or more of the following DirectShow DirectDraw Surface (AMDDS) surface types.

Value | Description
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::SetDefault

The SetDefault method makes the current property settings the global default.

Syntax

HRESULT SetDefault(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

All properties set through IDirectDrawVideo are specific to that particular instance. Call this method to make properties set on this instance of IDirectDrawVideo the global default of all DirectShow instances of this interface. After it is called, the current property settings will persist between the subsequent starting of other DirectShow filter graphs and between any computer restarts.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::SetDirectDraw

The SetDirectDraw method passes the IDirectDraw interface to a loaded driver.

Syntax

HRESULT SetDirectDraw(
  LPDIRECTDRAW pDirectDraw
);

Parameters

pDirectDraw

Pointer to the IDirectDraw interface to be passed.

Return Values

Returns an HRESULT value.

Remarks

To have the renderer release a DirectDraw interface previously passed in through SetDirectDraw, an application can call SetDirectDraw and pass in NULL. However, the renderer will continue using that DirectDraw interface until it is disconnected. Therefore, calling SetDirectDraw with a null parameter does not make the renderer stop using it immediately.

This method was created because only one instance of IDirectDraw could be loaded per process in versions of DirectDraw prior to DirectX 7.0. If you are using DirectX 7.0 or later, you never need to call this method. If an application wanted to load IDirectDraw but allow the Video Renderer to also allocate surfaces, the application could open IDirectDraw itself and then pass the interface to the loaded driver through IDirectDrawVideo::SetDirectDraw. Alternatively, the application could let the renderer load DirectDraw and then obtain a reference-incremented interface to it through IDirectDrawVideo::GetDirectDraw. Because DirectShow ships with the most recently shipped version of DirectDraw, however, this method is not required unless the application wants to change display modes itself and pass in a DirectDraw object, which the renderer can then use to allocate surfaces.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::SetSwitches

The SetSwitches method sets the surface types that the renderer is allowed to use.

Syntax

HRESULT SetSwitches(
  DWORD Switches
);

Parameters

Switches

Bit mask containing one or more of the following DirectShow DirectDraw Surface (AMDDS) surface types.

Value | Description
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Values

Returns an HRESULT value.

Remarks

This method must be called before the Video Renderer is connected.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::UseOverlayStretch

The UseOverlayStretch method determines whether the renderer should check overlay stretch limitations.

Syntax

HRESULT UseOverlayStretch(
  long UseOverlayStretch
);

Parameters

UseOverlayStretch

Value specifying whether the renderer checks overlay stretching. Set to OATRUE for the renderer to check overlay stretching; otherwise, set to OAFALSE.

Return Values

Returns an HRESULT value.

Remarks

Some display cards provide the use of overlay surfaces through DirectDraw. An overlay surface is a block of video memory whose contents are overlaid onto the display during the monitor's vertical refresh. DirectShow uses all available overlay surfaces where possible because they typically offer higher-quality video and very fast performance. On some display cards set to relatively high bit depths, the overlay must be displayed on the screen larger than its real size (to accommodate certain display hardware bandwidth limitations). If the overlay is not displayed large enough, certain undesirable effects can be seen on the display (sometimes described as a "fleeting shimmering" effect).

If UseOverlayStretch is set to OATRUE (on, the default), DirectShow will ensure the overlay is adequately stretched before displaying it. If it is set to OAFALSE (off), DirectShow will not check that the overlay is adequately stretched, and the user is likely to experience artifacts on the screen (although it will also guarantee that the overlay will be used if possible).

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::UseScanLine

The UseScanLine method determines whether the renderer should check the current scan line when drawing a video.

Syntax

HRESULT UseScanLine(
  long UseScanLine
);

Parameters

UseScanLine

Long integer value that specifies whether or not to use the scan line information. Set to OATRUE to use scan line information or OAFALSE to ignore it.

Return Values

Returns E_INVALIDARG if the argument is invalid or S_OK otherwise.

Remarks

If you blit an image to the video memory while the monitor's scan line is scanning over a visible portion of the screen, the complete image will be a composite of the old and new images. This composite is known as a torn video image. You can avoid torn images by waiting until the previous image is complete before blitting the new image. Some video cards can retrieve the scan line's current position; if this information is available, you can have DirectShow try to reduce tearing by waiting until the scan line is off-screen before blitting the new image. Note that checking the scan line location increases load on the processor and can reduce the amount of video frames delivered to the screen. If scan line information is available, DirectShow uses it by default. Set UseScanLine to OAFALSE if you want to save processing time at the expense of minor image degradation.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::UseWhenFullScreen

The UseWhenFullScreen method determines whether DirectShow should change display mode when going to full-screen mode.

Syntax

HRESULT UseWhenFullScreen(
  long UseWhenFullScreen
);

Parameters

UseWhenFullScreen

Value specifying whether to change the display mode. Set to OATRUE to cause the renderer to use DirectShow in full-screen mode; otherwise, set to OAFALSE.

Return Values

Returns an HRESULT value.

Remarks

When asked to go to full-screen mode, DirectShow has a number of choices. The first choice is to determine if any filters in the graph can support full-screen playback directly; if one can, it will be asked to do so.

The second choice is to automatically add a special full-screen renderer to the filter graph that uses DirectDraw mode-changing services to play back the video. By changing display modes, the video effectively fills more (but not necessarily all) of the display. So, for example, if the current mode is 1024 x 768 pixels, a video might look relatively small, but when displayed in a 320 x 240 display mode it might look very presentable.

The third and final choice is to simply take any renderer supporting the IVideoWindow interface and have its window stretched full-screen. This will typically offer lower performance than the second option (swapping in a full-screen DirectDraw-enabled renderer). If the UseWhenFullScreen parameter is set to On (OATRUE), the window will always be stretched full-screen for full-screen playback; if set to Off (the default), the filter graph manager is free to swap in the DirectDraw-enabled full-screen renderer.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawVideo::WillUseFullScreen

The WillUseFullScreen method determines whether DirectShow will change display mode when going to full-screen mode.

Syntax

HRESULT WillUseFullScreen(
  long *UseWhenFullScreen
);

Parameters

UseWhenFullScreen

Pointer to a value indicating whether DirectShow will use DirectX in full-screen mode. OATRUE indicates it will use full-screen mode; OAFALSE indicates it will not.

Return Values

Returns an HRESULT value.

Remarks

For a description of this feature, see IDirectDrawVideo::UseWhenFullScreen.

See Also

  • Error and Success Codes
  • IDirectDrawVideo Interface


IDirectDrawMediaSample Interface

The IDirectDrawMediaSample interface is supported by media samples that use Microsoft® DirectDraw® surfaces. The allocator for the Overlay Mixer filter creates samples that expose this interface. These samples are used for connections between the Overlay Mixer and upstream decoder filters. Decoder filters can use this interface to unlock the DirectDraw surface while still holding it, so that other components can access the surface.

Samples that support this interface also support the IMediaSample interface.

The Overlay Mixer's allocator exposes the IDirectDrawMediaSampleAllocator.

In addition to the methods inherited from IUnknown, the IDirectDrawMediaSample interface exposes the following methods.

Method | Description
GetSurfaceAndReleaseLock | Retrieves and unlocks the surface that the sample represents.
LockMediaSamplePointer | Locks the surface that the sample represents.


IDirectDrawMediaSample::GetSurfaceAndReleaseLock

The GetSurfaceAndReleaseLock method retrieves and unlocks the surface that the sample represents.

Syntax

HRESULT GetSurfaceAndReleaseLock(
  IDirectDrawSurface **ppDirectDrawSurface,
  RECT *pRect
);

Parameters

ppDirectDrawSurface

[out] Address of a pointer to the sample's IDirectDrawSurface interface.

pRect

[out] Pointer to a variable that receives the address of the rectangle defining the part of the surface that the sample represents.

Return Values

Returns an HRESULT value.

Remarks

The caller should release the returned surface pointer, except when calling the Overlay Mixer filter's implementation of this interface.

See Also

  • Error and Success Codes
  • IDirectDrawMediaSample Interface


IDirectDrawMediaSample::LockMediaSamplePointer

The LockMediaSamplePointer method locks the surface that the sample represents.

Syntax

HRESULT LockMediaSamplePointer(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

Call this method only after calling IDirectDrawMediaSample::GetSurfaceAndReleaseLock.

See Also

  • Error and Success Codes
  • IDirectDrawMediaSample Interface


IDirectDrawMediaSampleAllocator Interface

The IDirectDrawMediaSampleAllocator interface is implemented on the allocator created by the Overlay Mixer for its upstream connection with a video decoder. This allocator allocates IDirectDrawMediaSample media samples that also support the IMediaSample interface.

Decoder filters should not have to use this interface to connect to the Overlay Mixer. Applications never use this interface.

In addition to the methods inherited from IUnknown, the IDirectDrawMediaSampleAllocator interface exposes the following method.

Method | Description
GetDirectDraw | Retrieves the DirectDraw instance used to allocate surfaces.


IDirectDrawMediaSampleAllocator::GetDirectDraw

The GetDirectDraw method retrieves a pointer to the DirectDraw instance used to allocate surfaces.

Syntax

HRESULT GetDirectDraw(
  IDirectDraw **ppDirectDraw
);

Parameters

ppDirectDraw

[out] Address of a pointer that receives the DirectDraw object's IDirectDraw interface.

Return Values

Returns an HRESULT value.

Remarks

The caller should release the returned IDirectDraw pointer, except when calling the Overlay Mixerfilter's implementation of this interface.

See Also

  • Error and Success Codes
  • IDirectDrawMediaSampleAllocator Interface


IDistributorNotify Interface

The IDistributorNotify interface is an optional interface that enables a plug-in distributor to be notified when the filter graph changes.

Applications never use this interface. Implement this interface if you are writing a plug-in distributor (PID) and want the PID to receive notifications of control and changes in the composition of filter graphs.

The Filter Graph Manager queries for this interface on any plug-in distributors that it aggregates. If a PID exposes this interface, the Filter Graph Manager notifies the PID of any state changes by calling IDistributorNotify methods before calling the equivalent IBaseFilter methods on the filters. The Filter Graph Manager also calls the IDistributorNotify::NotifyGraphChange method whenever it adds or removes a filter, or any pin connections change.

During a call to any IDistributorNotify method, do not hold any critical section that might be held by another code path that calls methods on the Filter Graph Manager. Doing so could result in a deadlock.

In addition to the methods inherited from IUnknown, the IDistributorNotify interface exposes the following methods.

Method | Description
NotifyGraphChange | Called when the set of filters in the filter graph change or their connections change.
Pause | Called when the filter graph is entering a paused state.
Run | Called when the filter graph is entering a running state.
SetSyncSource | Called when a new clock is registered.
Stop | Called when the filter graph is entering a stopped state.

See Also

  • Plug-in Distributors


IDistributorNotify::NotifyGraphChange

The NotifyGraphChange method is called when the set of filters in the filter graph changes or any pin connections change.

Syntax

HRESULT NotifyGraphChange(void);

Parameters

This methods takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

This method is called whenever the IFilterGraph::AddFilter, IFilterGraph::RemoveFilter, or IFilterGraph::ConnectDirect method is called or a method is called that will lead to one of these being called (such as IGraphBuilder::RenderFile).

Make sure you call Release on any held filters that have been removed at this point. For performance reasons, PIDs might choose not to rescan the filters until the PIDs actually need the interfaces, because there might be several separate notifications sent. However, it is important to release any cached interfaces immediately.

See Also

  • Error and Success Codes
  • IDistributorNotify Interface


IDistributorNotify::Pause

The Pause method is called when the filter graph is entering a paused state.

Syntax

HRESULT Pause(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Transition is not complete, but no error has occurred.
S_OK | Success.

Remarks

This method is called before the filters are notified.

See Also

  • Error and Success Codes
  • IDistributorNotify Interface


IDistributorNotify::Run

The Run method is called when the filter graph is entering a running state.

Syntax

HRESULT Run(
  REFERENCE_TIME tStart
);

Parameters

tStart

Stream-time offset that will be passed to every filter's IMediaFilter::Run method.

Return Values

Returns an HRESULT value.

Remarks

This method is called before the filters are notified.

See Also

  • Error and Success Codes
  • IDistributorNotify Interface


IDistributorNotify::SetSyncSource

The SetSyncSource method is called when a new clock is registered.

Syntax

HRESULT SetSyncSource(
  IReferenceClock *pClock
);

Parameters

pClock

[in] Pointer to the new clock's IReferenceClock interface.

Return Values

Returns an HRESULT value.

Remarks

This method is called before the filters are notified. Make sure to use AddRef on the pClock parameter if the plug-in distributor intends to hold it beyond this method call.

See Also

  • Error and Success Codes
  • IDistributorNotify Interface


IDistributorNotify::Stop

The Stop method is called when the filter graph is entering a stopped state.

Syntax

HRESULT Stop(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_FALSE | Transition is not complete, but no error has occurred.
S_OK | Success.

Remarks

This method is called before the filters are notified.

See Also

  • Error and Success Codes
  • IDistributorNotify Interface


IDMOWrapperFilter Interface

Enables applications to use a Microsoft® DirectX Media Object (DMO) in a filter graph. The DMO Wrapper filter exposes this interface.

To add a DMO to the filter graph, create an instance of the DMO Wrapper filter and query it for the IDMOWrapperFilter interface. Then call the IDMOWrapperFilter::Init method to initialize the filter with the DMO.

Requirements

Include Dmodshow.h. Link to Dmoguids.lib.

In addition to the methods inherited from IUnknown, the IDMOWrapperFilter interface exposes the following method.

Method | Description
Init | Initializes the DMO Wrapper filter with the specified DMO.


IDMOWrapperFilter::Init

The Init method initializes the DMO Wrapper filter with the specified DMO.

Syntax

HRESULT Init(
  REFCLSID clsidDMO,
  REFCLSID catDMO
);

Parameters

clsidDMO

Class identifier (CLSID) of the DMO.

catDMO

CLSID that specifies the category of the DMO.

Return Values

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

In some cases, the DMO Wrapper filter performs optimizations based on the category.

See Also

  • Error and Success Codes
  • IDMOWrapperFilter Interface


IDShowPlugin Interface

The IDShowPlugin interface enables the Windows Media Source filter to communicate with the Windows Media Player 6.4 Plug-in for Netscape Navigator. If Windows Media Player 6.4 is hosted in the Netscape Navigator browser, the Windows Media Source filter uses this interface to retrieve the URL and the User-Agent heading. This interface is not used when the player is hosted as an ActiveX control in Microsoft Internet Explorer.

Applications cannot access this interface. It is documented here for completeness, because it is defined in the header file Qnetwork.h.

In addition to the methods inherited from IUnknown, the IDShowPlugin interface exposes the following methods.

Method | Description
get_URL | Retrieves the URL of the current Web page.
get_UserAgent | Retrieves the User-Agent string.


IDShowPlugin::get_URL

The get_URL method retrieves the URL of the current Web page.

Syntax

HRESULT get_URL(
  BSTR *pURL
);

Parameters

pURL

Pointer to a variable that receives the URL.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IDShowPlugin Interface


IDShowPlugin::get_UserAgent

The get_UserAgent method retrieves the User-Agent field from the HTTP header.

Syntax

HRESULT get_UserAgent(
  BSTR *pUserAgent
);

Parameters

pUserAgent

Pointer to a variable that receives the User-Agent string.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

The caller must release the returned BSTR, by calling SysFreeString.

See Also

  • IDShowPlugin Interface


IDvdCmd Interface

The IDvdCmd interface is implemented on command synchronization objects allocated by the DVD Navigator. If instructed by an application in an IDvdControl2 "play" method call such as IDvdControl2::PlayTitle, IDvdControl2::PlayAtTimeInTitle, and so on, the DVD Navigator will allocate a command synchronization object and pass a pointer to its IDvdCmd back to the application. The command synchronization object stores the results of the command at both the start (when the command has begun processing) and the end after it has completed. The application can use the object to block the DVD Navigator until the command starts or completes.

For complete information on using command synchronization objects and the IDvdCmd interface, see Synchronizing DVD Commands. (This article also discusses alternate ways to synchronize commands without using command synchronization objects.)

Note Although the DVD Navigator allocates the command synchronization object, the application must call Release on the object when it is done with it.

In addition to the methods inherited from IUnknown, the IDvdCmd interface exposes the following methods.

Method | Description
WaitForStart | Blocks the DVD Navigator until the command associated with this object begins.
WaitForEnd | Blocks the DVD Navigator until the command associated with this object completes or is canceled.


IDvdCmd::WaitForEnd

The WaitForEnd method blocks the DVD Navigator until the command associated with this object completes or is canceled.

Syntax

HRESULT WaitForEnd(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful or an HRESULT error code otherwise.

See Also

  • Error and Success Codes
  • IDvdCmd Interface


IDvdCmd::WaitForStart

The WaitForStart method blocks the DVD Navigator until the command associated with this object begins.

Syntax

HRESULT WaitForStart(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful or an HRESULT error code otherwise.

See Also

  • Error and Success Codes
  • IDvdCmd Interface


IDvdControl2 Interface

The DirectShow DVD Navigator source filter exposes the IDvdControl2 interface to enable applications to navigate and play DVD-Video titles, including karaoke titles. After creating a DVD filter graph through the IDvdGraphBuilder interface, a DVD player application uses the methods of the IDvdControl2 and IDvdInfo2 interfaces to send DVD commands to and retrieve state information from the DVD Navigator.

IDvdControl2 provides the full functionality required by the DVD Annex J specification, as well as methods for playback, menu navigation, and parental control. For more information on writing a DVD player application using the DVD Navigator, including topics on the DVD filter graph, command synchronization, parental controls, menus, and karaoke support, see DVD Applications.

In addition to the methods inherited from IUnknown, the IDvdControl2 interface exposes the following methods. The methods are grouped by functional area.

Playback

Method | Description
Pause | Pauses or resumes playback at the current location.
PlayAtTime | Starts playback from the specified time in the current title.
PlayAtTimeInTitle | Starts playback from the specified time in the specified title.
PlayBackwards | Plays backward at the specified speed from the current location.
PlayChapter | Starts playback from the specified chapter in the current title.
PlayChapterInTitle | Starts playback from the beginning of the specified chapter of the specified title.
PlayChaptersAutoStop | Plays the number of chapters specified, starting at the specified chapter within the specified title.
PlayForwards | Plays forward at the specified speed from the current location.
PlayNextChapter | Starts playback from the beginning of the next chapter in the current title.
PlayPeriodInTitleAutoStop | Starts playback in the specified title from the specified start time until the specified end time.
PlayPrevChapter | Starts playback from the beginning of the previous chapter in the current title.
PlayTitle | Starts playback from the beginning of the specified title.
ReplayChapter | Starts playback from the beginning of the current chapter.
Stop | Stops playback of a title or menu by moving the DVD Navigator into the DVD Stop domain.

Menus

Method | Description
ActivateAtPosition | Activates the menu button under the mouse pointer position.
ActivateButton | Activates the selected menu button.
Resume | Leaves a menu and resumes playback.
ReturnFromSubmenu | Returns the display from a submenu to its parent menu.
SelectAtPosition | Highlights the menu button under the mouse pointer position.
SelectAndActivateButton | Selects and activates the specified menu button.
SelectButton | Selects the specified menu button.
SelectDefaultMenuLanguage | Sets the default language for all menus and menu buttons.
SelectRelativeButton | Selects the specified relative button (upper, lower, right, left).
ShowMenu | Displays the specified menu, if available.

Video Stream

Method | Description
SelectAngle | Sets the new angle when the DVD Navigator is in an angle block.
StillOff | Resumes playback, canceling still mode.
SelectVideoModePreference | Sets the video mode display for subsequent playback—wide screen, letterbox, or pan-scan.

Audio Stream

Method | Description
SelectAudioStream | Selects the audio stream to play.
SelectDefaultAudioLanguage | Sets the default audio language.
SelectKaraokeAudioPresentationMode | Sends karaoke auxiliary channels to the left or right speaker.

Subpicture Stream

Method | Description
SelectDefaultSubpictureLanguage | Sets the default language for subpicture text.
SelectSubpictureStream | Sets the subpicture stream to display.
SetSubpictureState | Turns the subpicture display on or off.

Parental Levels

Method | Description
AcceptParentalLevelChange | Accepts or rejects a request from the DVD Navigator to play content at a higher parental management level.
SelectParentalCountry | Sets the country/region for interpreting parental access levels and setting default languages.
SelectParentalLevel | Sets the parental access level for the logged-on user.

DVD Navigator Control

Method | Description
SetDVDDirectory | Sets the DVD drive that the DVD Navigator will read from.
SetOption | Enables or disables a DVD Navigator internal behavioral flag.
SetState | Saves the current disc position and state of the DVD Navigator for retrieval at a later time.
SetGPRM | Sets a general parameter register value.


IDvdControl2::AcceptParentalLevelChange

The AcceptParentalLevelChange method accepts or rejects a request from the DVD Navigator to play content at a higher parental management level.

Syntax

HRESULT AcceptParentalLevelChange(
  BOOL bAccept
);

Parameters

bAccept

[in] Flag that indicates whether the application accepts the parental management level change. Specify TRUE to accept the change and play the higher-level content, or FALSE to reject the change.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

A temporary parental management level (PML) command is a marker on the DVD disc indicating that the content that follows has a PML higher than the level specified for the title as a whole. This marker also contains instructions on where to branch depending on whether the change is accepted or rejected. If you specify FALSE, the DVD Navigator follows the rejected branch on the disc. If you specify TRUE, the DVD Navigator follows the branch to the higher-level content.

Use AcceptParentalLevelChange in conjunction with the SetOption method. The sequence of events is as follows: First, call SetOption(DVD_NotifyParentalLevelChange, TRUE) to tell the DVD Navigator to always wait after sending an EC_DVD_PARENTAL_LEVEL_CHANGE event notification to the application. In your event handler, implement code to determine whether to accept or reject the change, and then call AcceptParentalLevelChange to notify the DVD Navigator of the decision.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

  • Enforcing Parental Management Levels
  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::ActivateAtPosition

The ActivateAtPosition method activates the menu button under the mouse pointer position.

Syntax

HRESULT ActivateAtPosition(
  POINT point
);

Parameters

point

[in] Point on the client window area, in screen pixel coordinates.

Return Values

Returns one of the following values.

Return code | Description
S_OK | The click occurred in the highlighted button rectangle, and the button was successfully activated.
E_INVALIDARG | The point lies outside the valid video region.
E_UNEXPECTED | The button is present but is not working.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in a menu domain.
VFW_E_DVD_NO_BUTTON | There is no menu button under the mouse pointer position.
VFW_E_DVD_OPERATION_INHIBITED | The operation is inhibited by user operation (UOP) control.

Remarks

The mouse pointer coordinates are relative to the upper left of the client area, which isn't necessarily the video display area if the video is in letterbox format.

Use this method when the user is navigating through a menu by moving the mouse pointer directly over the menu buttons. If the user is using the relative buttons to navigate the menu, use ActivateButton rather than ActivateAtPosition.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::ActivateButton

The ActivateButton method activates the selected menu button.

Syntax

HRESULT ActivateButton(void);

Parameters

This method takes no parameters.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.
VFW_E_DVD_NO_BUTTON | No button is selected.

Remarks

An application might or might not have four relative buttons on the side of the video display to represent the buttons on a physical remote control. These enable a user to select menu buttons but not activate them. A fifth button is required to activate the selected button. Call ActivateButton in response to a mouse click on the fifth button.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Activate | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::Pause

The Pause method pauses or resumes playback at the current location.

Syntax

HRESULT Pause(
  BOOL bState
);

Parameters

bState

[in] Value of type Boolean that specifies whether to pause playback; TRUE means to pause.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.

Remarks

Putting the DVD Navigator into a paused state freezes playback and any internal timers, similar to IMediaControl::Pause. If the filter graph is not running, this method does nothing.

This method is demonstrated in the DVDSample application in CDvdCore::Pause.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
PauseOn/PauseOff | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::PlayAtTime

The PlayAtTime method starts playback from the specified time in the current title.

Syntax

HRESULT PlayAtTime(
  DVD_HMSF_TIMECODE *pTime,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

pTime

[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to start playback.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::PlayTime.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Time_Search | DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayAtTimeInTitle

The PlayAtTimeInTitle method starts playback from the specified time in the specified title.

Syntax

HRESULT PlayAtTimeInTitle(
  ULONG uiTitle,
  DVD_HMSF_TIMECODE *pTime,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

uiTitle

[in] Value that specifies the number of the title to play; this value must be from 1 through 99.

pTime

[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies where playback will begin.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd interface that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J command name | Valid domains
Time_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayBackwards

The PlayBackwards method plays backward at the specified speed from the current location.

Syntax

HRESULT PlayBackwards(
  double dwSpeed,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwSpeed

[in] Value that specifies the speed of backward play. This value is a multiplier, where 1.0 is the authored speed. So, a value of 2.5 plays backward at two and one-half times the authored speed, while a value of 0.5 plays backward at half the authored speed. The actual speed of playback depends on the video decoder's capabilities and might differ from the specified rate. For reverse play, audio is muted and no subpicture is displayed. Any speed below 0.00001 is converted to 0.00001.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd interface that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::Rewind. For playing backwards one frame at a time, use the IVideoFrameStep interface as demonstrated in the sample application in CDvdCore::FrameStep.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Backward_Scan | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::PlayChapter

The PlayChapter method starts playback from the specified chapter in the current title.

Syntax

HRESULT PlayChapter(
  ULONG ulChapter,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulChapter

[in] Value that specifies the chapter in the current title where the DVD Navigator will start playback; this value must be from 1 through 999.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd interface that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The DVD Navigator begins playback at the specified chapter and continues to the subsequent chapters. Use IDvdControl2::PlayChaptersAutoStop to play the current chapter only.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PlayChapter.

Annex J Command Name | Valid Domains
PTT_Search | DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayChapterInTitle

The PlayChapterInTitle method starts playback from the beginning of the specified chapter of the specified title.

Syntax

HRESULT PlayChapterInTitle(
  ULONG ulTitle,
  ULONG ulChapter,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulTitle

[in] Value that specifies the title in which the chapter is located; this value must be from 1 through 99.

ulChapter

[in] Value that specifies the chapter in the specified title where the DVD Navigator will start playback; this value must be from 1 through 999.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd interface that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PlayChapterInTitle.

Annex J Command Name | Valid Domains
PTT_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayChaptersAutoStop

The PlayChaptersAutoStop method plays the number of chapters specified, starting at the specified chapter within the specified title.

Syntax

HRESULT PlayChaptersAutoStop(
  ULONG ulTitle,
  ULONG ulChapter,
  ULONG ulChaptersToPlay,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulTitle

[in] Value that specifies the title in which the chapter is located; this value must be from 1 through 99.

ulChapter

[in] Value that specifies the chapter in the specified title where the DVD Navigator will start playback; this value must be from 1 through 999.

ulChaptersToPlay

[in] Number of chapters to play from the start chapter.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd interface object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_UNEXPECTED | The DVD Navigator is not initialized or the title is not a One Sequential PGC Title.
E_INVALIDARG | The ulTitle value does not exist or is greater than the number of titles, or ulChapter does not exist or is greater than the number of chapters, or ulChapter plus ulChaptersToPlay is greater than the number of chapters.
VFW_E_DVD_GRAPHNOTREADY | The graph is not in a running state.

Remarks

This method works only on One_Sequential_PGC_Titles. When the specified number of chapters have been played, the DVD Navigator sends the application an EC_DVD_CHAPTER_AUTOSTOP event notification.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None. | All.

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayForwards

The PlayForwards method plays forward at the specified speed from the current location.

Syntax

HRESULT PlayForwards(
  double dwSpeed,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwSpeed

[in] Value that specifies the playback speed. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 plays at two and one-half times the authored speed, while a value of 0.5 plays at half the authored speed. The actual speed of playback depends on the capabilities of the video decoder.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::FastForward.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Forward_Scan | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::PlayNextChapter

The PlayNextChapter method starts playback from the beginning of the next chapter in the current title.

Syntax

HRESULT PlayNextChapter(
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

After playing the next chapter, the DVD Navigator continues playing, following the branching instructions on the disc. To play only the next chapter, call IDvdControl2::PlayChaptersAutoStop.

This method is demonstrated in the DVDSample application in CDvdCore::NextChapter.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
NextPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayPeriodInTitleAutoStop

The PlayPeriodInTitleAutoStop method starts playback in the specified title from the specified start time until the specified end time.

Syntax

HRESULT PlayPeriodInTitleAutoStop(
  ULONG ulTitle,
  DVD_HMSF_TIMECODE *pStartTime,
  DVD_HMSF_TIMECODE *pEndTime,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulTitle

[in] Value that specifies the title; this value must be from 1 through 99.

pStartTime

[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to start playing.

pEndTime

[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to stop playing.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The actual start and end times are the times before or equal to the frame number specified in the DVD_HMSF_TIMECODE. The frame rate code is ignored on pStartTime and pEndTime.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayPrevChapter

The PlayPrevChapter method starts playback from the beginning of the previous chapter in the current title.

Syntax

HRESULT PlayPrevChapter(
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PrevChapter.

Annex J Command Name | Valid Domains
PrevPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::PlayTitle

The PlayTitle method starts playback from the beginning of the specified title.

Syntax

HRESULT PlayTitle(
  ULONG uiTitle,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

uiTitle

Value that specifies the title number; this value must be from 1 through 99.

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Title_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::ReplayChapter

The ReplayChapter method starts playback from the beginning of the current chapter.

Syntax

HRESULT ReplayChapter(
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
TopPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands


IDvdControl2::Resume

The Resume method leaves a menu and resumes playback.

Syntax

HRESULT Resume(
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_NO_RESUME_INFORMATION | Resume was called from the Video Manager Menu.

Remarks

This method returns to playback from the location where play left off.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::RootMenu and CDvdCore::TitleMenu.

Annex J Command Name | Valid Domains
Resume | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::ReturnFromSubmenu

The ReturnFromSubmenu method returns the display from a submenu to its parent menu.

Syntax

HRESULT ReturnFromSubmenu(
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

If the DVD Navigator is at the top-level menu, this method calls the IDvdControl2::Resume method so that play continues where it left off.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
GoUP | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Synchronizing DVD Commands
  • Working With DVD Menus


IDvdControl2::SelectAndActivateButton

The SelectAndActivateButton method selects and activates the specified menu button.

Syntax

HRESULT SelectAndActivateButton(
  ULONG ulButton
);

Parameters

ulButton

[in] Value from 1 through 36 that specifies the button to select and activate.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | ulButton is out of range.
E_UNEXPECTED | The ulButton value is valid, but the DVD Navigator filter couldn't activate it.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select_And_Activate | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::SelectAngle

The SelectAngle method sets the new angle when the DVD Navigator is in an angle block.

Syntax

HRESULT SelectAngle(
  ULONG ulAngle,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulAngle

[in] Value of the new angle, which must be from 1 through 9.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | ulAngle is out of range.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the First Play domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

Note that angle and menu button indexes are one-based while audio stream and subpicture stream indexes are zero-based.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Angle_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Domains


IDvdControl2::SelectAtPosition

The SelectAtPosition method highlights the menu button under the mouse pointer position.

Syntax

HRESULT SelectAtPosition(
  POINT point
);

Parameters

point

[in] Point on the screen, in screen pixel coordinates.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_NO_BUTTON | No button is present at the mouse pointer position.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the Stop domain.

Remarks

Note that angle and menu button indexes are one-based while audio stream and subpicture stream indexes are zero-based.

Call IDvdControl2::ActivateButton in response to a mouse click when the pointer is over a menu button.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::OnMouseEvent.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_FirstPlay

See Also

  • ActivateAtPosition
  • Domains
  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::SelectAudioStream

The SelectAudioStream method selects the audio stream to play.

Syntax

HRESULT SelectAudioStream(
  ULONG ulAudio,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulAudio

[in] Value that specifies the audio track to use, which must be an integral value from 0 through 7, or DVD_DEFAULT_AUDIO_STREAM to specify the default stream.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | ulAudio is out of range, or doesn't correspond to an audio stream.
E_UNEXPECTED | The ulAudio value is valid, but the DVD Navigator couldn't set it for some reason.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_STREAM_DISABLED | The specified stream is disabled.

Remarks

This method affects the audio of the current Video Title Set (VTS). When called from within a menu, this method sets the audio stream of the title from which the menu was called.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Audio_Stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectButton

The SelectButton method selects the specified menu button.

Syntax

HRESULT SelectButton(
  ULONG ulButton
);

Parameters

ulButton

[in] Value from 1 through 36 that specifies the button to select.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.
VFW_E_DVD_NO_BUTTON | No button is selected.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::SelectDefaultAudioLanguage

The SelectDefaultAudioLanguage method sets the default audio language.

Syntax

HRESULT SelectDefaultAudioLanguage(
  LCID Language,
  DVD_AUDIO_LANG_EXT audioExtension
);

Parameters

Language

[in] Locale identifier that specifies the default language.

audioExtension

[in] DVD_AUDIO_LANG_EXT enumeration that specifies the default audio language extension.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The audioExtension value is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the Stop domain.

Remarks

This method selects the default language and language extensions to use when the disc is played. For example, if Language is specified as 0x409 for English and audioExtension is specified as DVD_AUD_EXT_NotSpecified, the DVD Navigator will look for the basic audio stream in English. If audioExtension is specified as DVD_AUD_EXT_VisuallyImpaired, the DVD Navigator will first look for a special audio stream in English for people with low vision. If the default stream is not found on a disc, the DVD Navigator will select the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectDefaultMenuLanguage

The SelectDefaultMenuLanguage method sets the default language for all menus and menu buttons.

Syntax

HRESULT SelectDefaultMenuLanguage(
  LCID Language
);

Parameters

Language

Variable of type LCID that specifies the default language.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in a valid domain.

Remarks

This method selects the default text language to use for menus when the disc is played. For example, if Language is specified as 0x409 for U.S. English, the DVD Navigator tries to show U.S. English text in menus. If the default menu language is not found on a disc, the DVD Navigator selects the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectDefaultSubpictureLanguage

The SelectDefaultSubpictureLanguage method sets the default language for subpicture text.

Syntax

HRESULT SelectDefaultSubpictureLanguage(
  LCID Language,
  DVD_SUBPICTURE_LANG_EXT subpictureExtension
);

Parameters

Language

[in] Locale identifier that specifies the default language.

subpictureExtension

[in] DVD_SUBPICTURE_LANG_EXT enumeration that specifies the default subpicture extension.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | TLanguage is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.

Remarks

This method selects the default language and format to use for subpictures and menus when the disc is played. For example, if Language is specified as 0x409 for U.S. English and subpictureExtension is specified as DVD_SP_EXT_Caption_Big, the DVD Navigator tries to show U.S. English text in the "big caption" format in subpictures. If the default language or language extension is not found on a disc, the DVD Navigator selects the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectKaraokeAudioPresentationMode

The SelectKaraokeAudioPresentationMode method sends karaoke auxiliary channels to the left or right speakers.

Syntax

HRESULT SelectKaraokeAudioPresentationMode(
  ULONG ulMode
);

Parameters

ulMode

[in] Bitwise OR of DVD_KARAOKE_DOWNMIX enumeration indicating how to downmix the five karaoke channels to channels 0 and 1, which are usually output to the left and right speakers.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is in an invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the current operation.

Remarks

When the DVD Navigator enters karaoke mode, it queries the audio decoder to discover whether it supports karaoke downmixing. If the decoder supports it, then channels 2 through 4 (the karaoke auxiliary channels with the guide vocals, guide melodies, and sound effects) are muted. Use this method to turn individual channels on or off and direct them to channels 0 and 1.

This method is demonstrated in the DVDSample application in CKaraokeDlg::DoModal.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Karaoke_Audio_Presentation_Mode_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectParentalCountry

The SelectParentalCountry method sets the country/region for interpreting parental access levels and setting default languages.

Syntax

HRESULT SelectParentalCountry(
  BYTE country_region[2]
);

Parameters

country_region

[in] Array of values of type BYTE that specifies the current country/region according to ISO 3166.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.

Remarks

The parental country/region determines the meaning of the eight generic parental levels as well as the default language for the soundtrack and menus. For details, see Enforcing Parental Management Levels.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Country_Select | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • IDvdControl2::SelectParentalLevel


IDvdControl2::SelectParentalLevel

The SelectParentalLevel method sets the parental access level for the logged-on user.

Syntax

HRESULT SelectParentalLevel(
  ULONG ulParentalLevel
);

Parameters

ulParentalLevel

Value that specifies the parental access level for the current user. For details, see Remarks.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.

Remarks

There are eight generic parental levels defined in the DVD specification, numbered from 1 (most restrictive) through 8 (least restrictive). The meaning of these levels varies from region to region and depends on the current country/region (see IDvdControl2::SelectParentalCountry). For the United States and Canada (DVD Region 1), the suggested values are as follows:

Parental level | Meaning
1 | The rating is G, general.
3 | The rating is PG, parental guidance suggested.
4 | The rating is PG-13, parental guidance suggested, not recommended for those under 13.
6 | The rating is R, restricted.
7 | The rating is NC-17, not appropriate for those under 17.

This method sets the current user's access level; this access level determines what content the user can play. Higher levels can play lower-level content; lower levels can't play higher-level content. In other words, adults can watch child-safe content, but children can't watch adult content.

DVD player applications can enforce restrictions on the parental level setting, such as providing password protection for raising the current parental level. The application's user interface should have a way to set the level and to disable checking completely. Some discs might be authored to disallow even level 8, meaning that no level is valid and no one could watch the disc if parental management is enabled. On such discs, parental management must be disabled for the discs to be viewed. Parental management in the DVD Navigator filter is disabled by default.

To disable parental management after it has been enabled, pass 0xffffffff for ulParentalLevel.

This method is demonstrated in the DVDSample application in CDvdCore::SetParentalLevel.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Level_Select | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectRelativeButton

The SelectRelativeButton method sets the specified relative button (upper, lower, right, or left).

Syntax

HRESULT SelectRelativeButton(
  DVD_RELATIVE_BUTTON buttonDir
);

Parameters

buttonDir

DVD_RELATIVE_BUTTON enumeration value indicating the button to select.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
(Left/Right/Upper/Lower)_Button_Select | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • DVD_RELATIVE_BUTTON
  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::SelectSubpictureStream

The SelectSubpictureStream method sets the subpicture stream to display.

Syntax

HRESULT SelectSubpictureStream(
  ULONG ulSubPicture,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulSubPicture

Value that specifies the subpicture stream, which must be from 0 through 31, or 63.

Return code | Description
0-31 | The stream is valid.
63 | The stream is the dummy stream, which means it is a muted, low-bitrate stream.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | ulSubPicture is out of range or doesn't correspond to an SP stream.
E_UNEXPECTED | The ulSubPicture parameter is valid, but DVD Navigator cannot set it for some other reason.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_STREAM_DISABLED | The specified stream is disabled.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Sub-picture_Stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Audio and Subpicture Streams
  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SelectVideoModePreference

The SelectVideoModePreference method sets the specified video mode display (wide screen, letterbox, or pan-scan) for playback.

Syntax

HRESULT SelectVideoModePreference(
  ULONG ulPreferredDisplayMode
);

Parameters

ulPreferredDisplayMode

[in] Value that specifies the new display mode for DVD content. Member of the DVD_PREFERRED_DISPLAY_MODE enumeration.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method changes the default video window's aspect ratio and can also specify a default aspect ratio conversion mechanism.

For anamorphic 16 x 9 source video, formed by stretching the 720 x 480 source video to a 16 x 9 aspect ratio.

Widescreen The 16 x 9 source video should be placed and stretched into the largest 16 x 9 area of the client output window. The highlights are relative to the inside of the 16 x 9 area. Black bars should be added to either the top/bottom or to the sides to maintain a 16 x 9 area.

Pan Scan The video shown is computed by taking a 4 x 3 subwindow from the stretched 16 x 9 video (the horizontal offset is provided in the MPEG-2 video's window's offset). The 4 x 3 subwindow is placed into the largest 4 x 3 area of the output client window. The highlight's coordinates are relative to the 4 x 3 output window (and have no relationship to the source 16 x 9 video). Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area.

Letterbox A 4 x 3 display area is formed by taking the largest 4 x 3 area of the output client window. Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area. The source 16 x 9 video is placed in the largest 16 x 9 subwindow inside of the 4 x 3 subwindow. Black bars should be added to the top and bottom of the subwindow to maintain a 16 x 9 area. The highlight's coordinates are relative to the 4 x 3 subwindow (and have no relationship to the source 16 x 9 video). It is technically possible for a disk to specify a highlight that lies outside of the 16 x 9 area (but still in the 4 x 3 window).

For 4 x 3 video, the video is placed in the largest 4 x 3 output area of the output client window. Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Video_PresentationMode_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SetDVDDirectory

The SetDVDDirectory method sets the DVD drive that the DVD Navigator filter will read from.

Syntax

HRESULT SetDVDDirectory(
  LPCWSTR  pszwPath
);

Parameters

pszwPath

[in] Variable of type LPCWSTR that specifies the path of the root directory.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The pszwPath parameter points to an invalid DVD path, or a DVD drive is not found while enumerating.
E_UNEXPECTED | The DVD Navigator is not initialized.
S_FALSE | The pszwPath parameter is NULL and the DVD Navigator can't find any DVD volume.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain. For details, see Remarks.

Remarks

If pszwPath is NULL, the DVD Navigator tries to select a DVD volume on any available drive. On startup, the DVD Navigator automatically looks for a drive, starting at drive C, with a VIDEO_TS folder in the root folder. It is therefore only necessary to call SetDVDDirectory when you have more than one DVD drive on a machine, or if your DVD drive letter is A or B. When specifying the path, include the video_ts folder.

SetDVDDirectory(L"e:\\video_ts");

Some DVD volumes may have their video in a directory named something other than "video_ts." The general idea is that an additional "DVD volume" (the set of .IFO. VOB, and .BUP files that would normally be stored in the VIDEO_TS directory) can be placed in a subdirectory on the disc. By changing the root to point to this directory, MSWebDVD will operate on this separate DVD volume. A new set of menus, titles, and so on will be available, independent of the titles in the VIDEO_TS root, which will no longer be accessible. Such directories are called "hidden directories." The following example shows how to set a hidden directory as the root, where "hidden" is a placeholder for whatever name the disc authors have given to the directory.

SetDVDDirectory(L"d:\\webdvd\\hidden");

If the filter graph is running and the DVD Navigator finds a DVD in the directory specified by pszwPath, the DVD Navigator automatically begins playing the disc. This conforms with the DVD specification and ensures that the new disc is initialized properly. If you do not want the new disc to play automatically after SetDVDDirectory returns, you must set the DVD_ResetOnStop flag in IDvdControl2::SetOption to TRUE and stop the filter graph through a call to IMediaControl::Stop on the Filter Graph Manager. If DVD_ResetOnStop is set to FALSE, then SetDVDDirectory returns VFW_E_DVD_INVALIDDOMAIN.

This method is demonstrated in the DVDSample application in CDvdCore::SetDirectory.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SetGPRM

The SetGPRM method sets a general parameter register value.

Syntax

HRESULT SetGPRM(
  ULONG ulIndex,
  WORD wValue,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

ulIndex

[in] Register index; may be a value from zero through 15.

wValue

[in] A 16-bit value contained in the specified register.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The ulIndex parameter is greater than 15 or any other of the input parameters are invalid.

Remarks

A DVD disc uses general parameter registers to store various types of information. By manually setting one or more of these registers, an application might be able to provide certain custom functionality. This is an advanced command and should not be used unless you have a thorough understanding of the DVD specification.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
none | All

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • IDvdInfo2::GetAllGPRMs


IDvdControl2::SetOption

The SetOption method enables or disables an internal behavior flag on the DVD Navigator filter.

Syntax

HRESULT SetOption(
  DVD_OPTION_FLAG flag,
  BOOL bEnable
);

Parameters

flag

[in] Specifies which behavior to modify, as a member of the DVD_OPTION_FLAG enumeration type. For details, see the DVD_OPTION_FLAG reference page.

bEnable

[in] Boolean value that specifies whether to enable to disable the behavior flag given in the flag parameter.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid flag.

Remarks

The following flags are suppored. For more information, see the DVD_OPTION_FLAG Enumeration.

Flag | Description
DVD_AudioDuringFFwdRew | Specifies whether the DVD Navigator enables audio during fast forward and rewind.
DVD_HMSF_TimeCodeEvents | Specifies the format for timecode information.
DVD_NotifyParentalLevelChange | Specifies whether the DVD Navigator notifies the application when the parental level changes.
DVD_ResetOnStop | Specifies whether the DVD Navigator returns to the start of the disc when the graph stops.

Call SetOption with the desired flags immediately after creating an instance of the DVD Navigator and whenever you want to change any behaviors.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

  • DVD Command Flags
  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SetState

The SetState method saves the current disc position and state of the DVD Navigator filter.

Syntax

HRESULT SetState(
  IDvdState *pState,
  DWORD    dwFlags,
  IDvdCmd  **ppCmd
);

Parameters

pState

[in] Pointer to the IDvdState interface on the object that contains the state information.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns S_OK if successful, or an HRESULT value otherwise.

Remarks

The DVD Navigator uses the location information in the given state object to restore the playback position to a specific location on the disc.

This method is demonstrated in the DVDSample application in CDvdCore::RestoreBookmark.

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::SetSubpictureState

The SetSubpictureState method turns the subpicture display on or off.

Syntax

HRESULT SetSubpictureState(
  BOOL bState,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

bState

[in] Boolean value that specifies whether the subpicture display is on; TRUE sets subpicture display on for subsequent playback.

dwFlags

[in] Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the First Play domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

Subpicture streams are typically used in menus for button text and sometimes button graphics, and in video playback for subtitles, credits, or other overlaid graphics. Do not confuse subpictures with closed captions; the latter are encoded within the video stream. In general, this method is intended for controlling subpicture display over video while the DVD Navigator filter is playing video in the DVD Title domain.

This method corresponds to the second parameter of the Annex J "Sub-picture_Stream_Change" command.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Sub-picture_stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • SelectSubpictureStream


IDvdControl2::ShowMenu

The ShowMenu method displays the specified menu, if available.

Syntax

HRESULT ShowMenu(
  DVD_MENU_ID MenuID,
  DWORD dwFlags,
  IDvdCmd **ppCmd
);

Parameters

MenuID

[in] A DVD_MENU_ID enumeration value that specifies the menu to display.

dwFlags

Bit flag that contains one or more DVD_CMD_FLAGS enumeration specifying command synchronization options.

ppCmd

Address of a pointer to an IDvdCmd object that can be used to synchronize commands to the DVD Navigator filter.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The MenuID value is out of range.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The Video Manager Menu (VMGM) should be accessible from the Title or the Video Title Set domains. The Video Title Set menus (VTSMs) might only be accessible through the VMGM. Any submenus under each VTSM (for chapters, angles, and audio and subpicture streams) are only accessible through that VTSM.

This method is demonstrated in the DVDSample application application in CDvdCore::RootMenu and CDvdCore::TitleMenu.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Menu_Call | All.

See Also

  • Error and Success Codes
  • IDvdControl2 Interface
  • Working With DVD Menus


IDvdControl2::StillOff

The StillOff method resumes playback, canceling still mode.

Syntax

HRESULT StillOff(void);

Parameters

This method takes no parameters.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
E_UNEXPECTED | The DVD Navigator filter is in a menu domain and the menu has buttons.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

A still is a static image presented by the disc. It is not the same as the frozen display image that appears when the user clicks the Pause button. When the DVD Navigator encounters a still image, it sends the application an EC_DVD_STILL_ON message, goes into still-store mode displaying the image, and waits for StillOff to be called before resuming playback.

If the DVD Navigator is not in still-store mode, this method does nothing.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Still_Off | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdControl2::Stop

The Stop method stops playback of a title or menu by moving the DVD Navigator into the DVD Stop domain.

Syntax

HRESULT Stop(void);

Parameters

This method takes no parameters.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.

Remarks

Calling this method puts the DVD Navigator into the Stop domain, but the DVD filter graph as a whole remains in a running state, ready to play at any time. From the Stop, domain the user can display a menu or initiate playback directly through any "Play" method.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Stop | DVD_DOMAIN_FirstPlay DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • Error and Success Codes
  • IDvdControl2 Interface


IDvdGraphBuilder Interface

The IDvdGraphBuilder interface is implemented on the DVD Graph Builder object. The RenderDvdVideoVolume method automatically builds a filter graph for DVD-Video playback from the available software and hardware on the system. For information on how to build the DVD filter graph and obtain the pointers to all the necessary interfaces, see Building the DVD Filter Graph. The DVDSample application also demonstrates this process in DvdCore.cpp.

Note A DVD filter graph requires either a hardware or software MPEG-2 decoder, which DirectShow does not provide. You must install a DirectShow-compatible third-party decoder on your computer before attempting to build the DVD filter graph.

Generally, you should not add, remove, connect, disconnect, or access individual filters in the graph created by RenderDvdVideoVolume, because doing so might confuse the cleanup code. The purpose of the DvdGraphBuilder object is to simplify the developement of DVD-Video applications. If you need a specific type of graph for a particular solution, you should manually create the entire filter graph.

In addition to the methods inherited from IUnknown, the IDvdGraphBuilder interface exposes the following methods.

Method | Description
GetFiltergraph | Retrieves the IGraphBuilder interface for the filter graph used by the DVD-Video graph builder object.
GetDvdInterface | Retrieves specific interface pointers in the DVD-Video playback graph to make DVD-Video playback development easier.
RenderDvdVideoVolume | Completes building a filter graph according to user specifications for playing a DVD-Video volume.


IDvdGraphBuilder::GetDvdInterface

The GetDvdInterface method retrieves specific interface pointers in the DVD-Video playback graph to make DVD-Video playback development easier.

Syntax

HRESULT GetDvdInterface(
  REFIID riid,
  void **ppvIF
);

Parameters

riid

[in] IID of the required interface.

ppvIF

[out] Address of a pointer to the retrieved interface.

Return Values

Returns an HRESULT that depends on the implementation of the interface.

The DirectShow implementation return values include the following:

Return code | Description
E_INVALIDARG | The ppvIF parameter is invalid.
E_NOINTERFACE | The riid parameter value is not supported.
VFW_E_DVD_GRAPHNOTREADY | The graph has not been built through the IDvdGraphBuilder::RenderDvdVideoVolume method before retrieving this interface.

Remarks

Use this method to get the IDvdControl2 and IDvdInfo2 interfaces to control playback of a DVD-Video volume, and to get the IAMLine21Decoder interface to turn closed captioning on and off. You also use this method to get the IBasicVideo, IVideoWindow, and IBasicAudio interfaces. You only need a pointer to IBasicAudio if an audio renderer is used to render audio.

The returned interface pointer has an outstanding reference count. The caller must release the interface.

The IMixerPinConfig2 interface can be retrieved from the first input pin (primary video stream) of the Overlay Mixer filter in the DVD-Video playback graph using this interface. The IDDrawExclModeVideo interface can also be retrieved from the Overlay Mixer in the DVD-Video playback graph. This interface is required to playback video in DirectDraw exclusive mode, as some games require. Unlike other interfaces, it is not necessary to build the graph using the IDvdGraphBuilder::RenderDvdVideoVolume method before calling IDvdGraphBuilder::GetDvdInterface. This interface should be retrieved before using the IDvdGraphBuilder::RenderDvdVideoVolume method to build the graph.

See Also

  • Error and Success Codes
  • IDvdGraphBuilder Interface


IDvdGraphBuilder::GetFiltergraph

The GetFiltergraph method retrieves the IGraphBuilder interface for the filter graph used by the DVD-Video graph builder object.

Syntax

HRESULT GetFiltergraph(
  IGraphBuilder **ppGB
);

Parameters

ppGB

[out] Address of a pointer to the IGraphBuilder interface that the DVD-Video graph builder object is using.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if ppGB is invalid.

Remarks

The returned IGraphBuilder interface pointer has an outstanding reference count. The caller must release the interface.

See Also

  • Error and Success Codes
  • IDvdGraphBuilder Interface


IDvdGraphBuilder::RenderDvdVideoVolume

The RenderDvdVideoVolume method completes building a filter graph according to user specifications for playing a DVD-Video volume.

Syntax

HRESULT RenderDvdVideoVolume(
  LPCWSTR lpcwszPathName,
  DWORD dwFlags,
  AM_DVD_RENDERSTATUS *pStatus
);

Parameters

lpcwszPathName

[in] Pointer to the path for the DVD-Video volume to play. Can be NULL.

dwFlags

[in] Member of the AM_DVD_GRAPH_FLAGS enumeration indicating the type of decoder—hardware or software or a mix of hardware and software) to include in the filter graph. Maximum hardware decoding (AM_DVD_HWDEC_PREFER) is the default.

pStatus

[out] Pointer to the retrieved AM_DVD_RENDERSTATUS structure, which returns indication of any failure.

Return Values

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation return values include the following:

Return code | Description
E_INVALIDARG | The dwFlags parameter specifies conflicting options, or pStatus is a bad pointer.
S_FALSE | Graph has been built, but not perfectly. The pStatus parameter provides details of the problems.
S_OK | Success. Playback graph built successfully, all streams rendered, and the DVD-Video volume was specified or found.
VFW_E_DVD_DECNOTENOUGH | AM_DVD_HWDEC_ONLYor AM_DVD_SWDEC_ONLY was specified and there weren't enough hardware or software decoders to decode all streams.
VFW_E_DVD_RENDERFAIL | Some basic error occurred in building the graph. Possibilities include the DVD Navigator filter or the video or audio renderer not instantiating, a trivial connection or pin enumeration failing, or none of the streams rendering.

Remarks

The AM_DVD_RENDERSTATUS structure reflects failure codes for this method. Reasons for this method returning S_FALSE include the following:

  • The graph has been completely built, but one of the following is true.
    • Overlay mixing doesn't work—the application didn't use the AM_DVD_NOVPE flag and the video stream couldn't be put through the Overlay Mixer. In this case, if the video is decoded in software the application will have enough information to inform the user that the video won't be visible. Hardware-decoded video will be visible only on a TV connected to the NTSC out port of the hardware video decoder.
    • Video decoder doesn't produce line 21 data. The application can display a warning or informative message that closed captioning is not available because of the decoder.
    • No volume path is specified and DVD Navigator didn't locate any DVD-Video volume to be played. The application can ask the user to insert a DVD-Video disc if none is available in the drive when playback starts.
  • Some streams didn't render or didn't render completely. Volume can be partially played back. The application can indicate to the user that some streams can't be played.

This method builds the graph without any knowledge of the DVD-Video file or volume to play. The DVD-Video graph builder builds the graph even if lpcwszPathName is NULL or if the DVD Navigator filter does not find a default DVD-Video volume to play.

See Also

  • Error and Success Codes
  • IDvdGraphBuilder Interface


IDvdInfo2 Interface

The IDvdInfo2 interface is implemented by the DVD Navigator source filter and provides methods to query for various attributes of the disc or the DVD Navigator's state. IDvdInfo2 is the companion interface to IDvdControl2 interface. IDvdInfo2 groups the DVD Navigator's "get" methods and IDvdControl2 groups the "set" methods. Together they provide DVD navigation and playback functionality beyond the DVD Annex J specification.

Note The information provided by some of these methods can also be obtained through event notifications sent from the DVD Navigator to the application's message loop. For example, to get the current DVD domain, you can call IDvdInfo2::GetCurrentDomain or you can handle the EC_DVD_DOMAIN_CHANGE event in your application's message loop and extract the new domain from the event's lParam1 parameter.

In addition to the methods inherited from IUnknown, the IDvdInfo2 interface exposes the following methods.

Menus

Method | Description
GetButtonAtPosition | Retrieves the button located at the specified point within the display window.
GetButtonRect | Retrieves the rectangle coordinates of the specified button.
GetCurrentButton | Retrieves the number of available buttons and the number of the currently selected button.
GetDefaultMenuLanguage | Retrieves the default menu language.
GetMenuLanguages | Retrieves all the languages available for all menus on the disc.
GetVMGAttributes | Retrieves attributes of all video, audio, and subpicture streams for the video manager menu.

Titles

Method | Description
GetNumberOfChapters | Retrieves the number of chapters in a given title.
GetTitleAttributes | Retrieves attributes of all video, audio, and subpicture streams for the specified title and its menus.
GetTotalTitleTime | Retrieves the total playback time for the current title.

Disc Information

Method | Description
GetAllSPRMs | Retrieves the current contents of all system parameter registers (SPRMs).
GetAllGPRMs | Retrieves the current contents of all general parameter registers (GPRMs).
GetCurrentUOPS | Retrieves a set of flags indicating which navigation commands, if any, the content authors have explicitly disabled for the current disc location.
GetDiscID | Retrieves a system-generated 64-bit "unique" identification number for the specified DVD.
GetDVDVolumeInfo | Retrieves the current DVD volume information.

Video Stream

Method | Description
GetCurrentAngle | Retrieves the number of available angles in the current angle block and the currently selected angle number.
GetCurrentVideoAttributes | Retrieves the video attributes of the current title or menu.

Audio Stream

Method | Description
GetAudioAttributes | Retrieves the attributes of the specified audio stream in the current title or menu.
GetAudioLanguage | Retrieves the language of the specified audio stream within the current title.
GetCurrentAudio | Retrieves the number of available audio streams and the number of the currently selected audio stream.
GetDecoderCaps | Retrieves the DVD decoder's maximum data rate for video, audio, and subpicture (in forward and reverse) as well as support for various types of audio (Dolby AC-3, MPEG-2, DTS, SDDS, LPCM).
GetDefaultAudioLanguage | Retrieves the default audio language.
GetKaraokeAttributes | Retrieves the karaoke attributes of the specified audio stream in the current title or menu.
IsAudioStreamEnabled | Determines if the specified audio stream is enabled in the current title.

Subpicture Stream

Method | Description
GetCurrentSubpicture | Retrieves the number of available subpicture streams in the current title, the currently selected subpicture stream number, and the state of the subpicture.
GetDefaultSubpictureLanguage | Retrieves the default subpicture language.
GetSubpictureAttributes | Retrieves the attributes of the specified subpicture stream in the current title or menu.
GetSubpictureLanguage | Retrieves the language of the specified subpicture stream within the current title.
IsSubpictureStreamEnabled | Determines if the specified subpicture stream is enabled in the current title.

Parental Levels

Method | Description
GetPlayerParentalLevel | Retrieves the current parental level and ISO 3166 country/region code settings for the DVD Navigator.
GetTitleParentalLevels | Retrieves the parental levels that are defined for a particular title.

DVD Navigator State Information

Method | Description
GetCmdFromEvent | Retrieves an IDvdCmd object from an EC_DVD_CMD_START, EC_DVD_CMD_END, or VFW_E_DVD_CMD_CANCELLED event.
GetCurrentDomain | Retrieves the DVD domain in which the DVD Navigator is currently located.
GetCurrentLocation | Retrieves the current playback location.
GetDVDDirectory | Retrieves the root directory that is set in the DVD Navigator.
GetState | Retrieves a bookmark containing the disc location and DVD Navigator state information.

DVD Text Strings

Method | Description
GetDVDTextNumberOfLanguages | Retrieves the number of text languages for the current DVD or disc side.
GetDVDTextLanguageInfo | Retrieves the information for the specified text string language block.
GetDVDTextStringAsNative | Retrieves the text string for the specified language as an array of bytes.
GetDVDTextStringAsUnicode | Retrieves the text string for the specified language in Unicode™.


IDvdInfo2::GetAllGPRMs

The GetAllGPRMs method retrieves the current contents of all general parameter registers (GPRMs).

Syntax

HRESULT GetAllGPRMs(
  GPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray

[out] Pointer to a GPRMARRAY that receives all 16 current GPRM values. See Remarks.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.

Remarks

GPRMs are 16-bit registers that each disc can use in unique ways for temporary data storage. The file Dvdif.idl contains the following typedefs.

typedef WORD DVD_REGISTER;
typedef DVD_REGISTER    GPRMARRAY[16];
typedef DVD_REGISTER    SPRMARRAY[24];

Note A player application using the DVD Navigator filter does not need to access these registers for any Annex J playback or navigation control. This method is provided for player applications implementing advanced functionality. Do not attempt to modify the GPRMs directly unless you have a thorough knowledge of the DVD specification, and the ways in which the GPRMs are used on the particular discs to be played.

See Also

  • Error and Success Codes
  • IDvdControl2::SetGPRM
  • IDvdInfo2 Interface


IDvdInfo2::GetAllSPRMs

The GetAllSPRMs method retrieves the current contents of all system parameter registers (SPRMs).

Syntax

HRESULT GetAllSPRMs(
  SPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray

[out] Pointer to a variable of type SPRMARRAY that receives the address of an array of SPRMs. See Remarks.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.

Remarks

The 24 SPRMs are used to hold information on current language, subpicture, and other navigation data. The file Dvdif.idl contains the following typedefs.

typedef WORD DVD_REGISTER;
typedef DVD_REGISTER    GPRMARRAY[16];
typedef DVD_REGISTER    SPRMARRAY[24];

Note A player application doesn't need to access these read-only registers for any standard navigation functionality. To use these registers effectively, you will probably need a more detailed knowledge of the DVD navigation commands than is provided in this documentation. The following table lists the contents of each register. Bits within the word are referred to as b0 (low order bit) through b15 (high order bit).

Register | Contents
0 | ISO-639 language code (two lowercase ASCII letters). Default value is undefined.
1 | Low 4 bits (b0-b3) contain audio stream number (0 to 7) or 15 (none). Default value is 15.
2 | Low 6 bits (b0-b5) contain subpicture stream number (0 to 31) or 62 (none) or 63 (dummy stream for forced subpicture). 7th bit (b6) contains subpicture display flag (0 = don't display subpicture). Default value is 62.
3 | Low 4 bits (b0-b3) contain angle number (1 to 9). Default value is 1.
4 | Low 7 bits (b0-b6) contain title number (1 to 99). Default value is 1.
5 | Low 7 bits (b0-b6) contain title number within current VTS (1 to 99). Default value is 1.
6 | Low 15 bits (b0-b14) contain PGC number in current title (1 to 32767). Default value is undefined.
7 | Low 10 bits (b0-b9) contain chapter number (1 to 99). Default value is 1. Value undefined unless title is one_sequential_PGC_title.
8 | High 6 bits (b10-b15) contain button number (1 to 36). Default value is 1024 (button 1).
9 | Timer count, in seconds (0 to 65535). Default value is 0.
10 | Low 15 bits (b0-b14) contain PGC number in current title (1 to 32767). Default value is undefined.
11 | Six flags (b2: mix ch2 to ch1, b3: mix ch3 to ch1, b4: mix ch4 to ch1, b10 mix ch2 to ch0, b11: mix ch3 to ch0, b12: mix ch4 to ch0). Flag value of 0 means don't mix. Default value for all flags is 0. Value undefined if not playing Karaoke stream.
12 | ISO-3166 country/region code (two uppercase ASCII letters) or 65535 (not specified). Default value is undefined.
13 | Low 4 bits (b0-b3) contain parental level (1 to 8) or 15 (none). Default value is undefined.
14 | b8-b9 contain current video output mode (0 = normal [4:3 or 16:9], 1 = panscan, 2 = letterbox). b10-b11 contain preferred display mode (0 = 4:3, 3 = 16:9). Default value is undefined.
15 | Nine flags (b2: SDDS karaoke, b3: DTS karaoke, b4: MPEG karaoke, b6: Dolby Digital karaoke, b7: PCM karaoke, b10: SDDS playback, b11: DTS playback, b12: MPEG playback, b14: Dolby Digital playback). Flag value of 0 means incapable, 1 means capable. Default value is undefined.
16 | ISO-639 language code (two lowercase ASCII letters) or 65535 (not specified). Default value is 65535.
17 | Language extension code (0 = not specified, 1 = normal audio, 2 = audio for visually impaired, 3 = director comments #1, 4 = director comments #2). Default value is 0.
18 | ISO-639 language code (two lowercase ASCII letters) or 65535 (not specified). Default value is 65535.
19 | Language extension code (0 = not specified, 1 = normal subtitles, 2 = large subtitles, 3 = subtitles for children, 5 = normal Closed Captions, 6 = large Closed Captions, 7 = Closed Captions for children, 9 = forced subtitles, 13 = director comments, 14 = large director comments, 15 = director comments for children). Default value is 0.
20 | Low 8 bits (b0-b7) contain region code (1 to 8).

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetAudioAttributes

The GetAudioAttributes method retrieves the attributes of the specified audio stream in the current title or menu.

Syntax

HRESULT GetAudioAttributes(
  ULONG ulStream,
  DVD_AudioAttributes *pATR
);

Parameters

ulStream

[in] Variable of type ULONG specifying the audio stream whose attributes you wish to query. See Remarks.

pATR

[out] Pointer to a DVD_AudioAttributes structure that is filled with the attributes of the specified audio stream.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_NO_ATTRIBUTES | The stream's audio attributes are not available for some reason.
E_POINTER | Invalid argument.

Remarks

ulStream can be any index number from 0 through 7 or one of the following values:

Value | Description
DVD_DEFAULT_AUDIO_STREAM | To query for the attributes of the default audio stream.
DVD_STREAM_DATA_CURRENT | To query the current stream.
DVD_STREAM_DATA_VMGM | To query for the VMGM's audio attributes.
DVD_STREAM_DATA_VTSM | To query for the VTSM's audio attributes.

The use of this method is demonstrated in the DVDSample application in CDvdCore::GetAudioAttributes() and CAudioLangDlg::GetAudioLang.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetAudioLanguage

The GetAudioLanguage method retrieves the language of the specified audio stream within the current title.

Syntax

HRESULT GetAudioLanguage(
  ULONG ulStream,
  LCID *pLanguage
);

Parameters

ulStream

[in] Audio stream number for the language being retrieved.

pLanguage

[out] Pointer to an LCID that receives the language information.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

Remarks

This method does not return languages for menus. It sets the value pointed to by pLanguage to zero if the stream contains an unknown language. Call the Microsoft® Win32® GetLocaleInfo function to create a human-readable string name from pLanguage:

LCID Language;
hr = pDvdInfo->GetAudioLanguage(ulStream, &Language);
if (SUCCEEDED(hr))
{
    int cchSize = GetLocaleInfo(Language, LOCALE_SENGLANGUAGE, 0, 0);
    TCHAR *szString = new TCHAR[cchSize];
    if (szString)
    {
        GetLocaleInfo(Language, LOCALE_SENGLANGUAGE, szString, cchSize);
        /* ... */
        delete [] szString;
    }
}

See Also

  • Error and Success Codes
  • IDvdControl2::SelectAudioStream
  • IDvdInfo2 Interface


IDvdInfo2::GetButtonAtPosition

The GetButtonAtPosition method retrieves the button located at the specified point within the display window.

Syntax

HRESULT GetButtonAtPosition(
  POINT point,
  ULONG *puButtonIndex
);

Parameters

point

[in] Current mouse pointer position as retrieved through the Win32 WM_MOUSEMOVE message.

puButtonIndex

[out] Pointer to a variable of type ULONG that receives the index (from 1 through 36) of the button at the current mouse pointer position.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The puButtonIndex parameter is invalid.
VFW_E_DVD_NO_BUTTON | No button at point.

Remarks

This method is typically called in response to a mouse pointer move within a DVD menu display window. Be sure to check for success in the HRESULT before trying to retrieve the button number; this method only sets the value of puButtonIndex if a button is found at the specified point. DVD buttons do not necessarily have highlighted rectangles, button rectangles can overlap, and button rectangles do not always correspond to the visual representation of the buttons.

See Also

  • Error and Success Codes
  • IDvdControl2::ActivateButton
  • IDvdInfo2 Interface


IDvdInfo2::GetButtonRect

The GetButtonRect method retrieves the rectangle coordinates for the specified menu button. (This method is currently not implemented.)

Syntax

HRESULT GetButtonRect(
  ULONG ulButton,
  RECT *pRect
);

Parameters

ulButton

[in] Variable of type ULONG, from 1 through 36, that specifies the button.

pRect

[out] Pointer to a variable of type RECT that receives the coordinates of the button's rectangle.

Return Values

Returns one of the following HRESULT values.

Return code | Description
E_NOTIMPL | This method is currently not implemented

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetCmdFromEvent

The GetCmdFromEvent method retrieves an IDvdCmd object from an EC_DVD_CMD_START or EC_DVD_CMD_END event.

Syntax

HRESULT GetCmdFromEvent(
  LONG_PTR lParam1,
  IDvdCmd **ppCmdObj
);

Parameters

lParam1

[in] Event notification's lParam1 parameter.

ppCmdObj

[out] Address of a pointer to an IDvdCmd command object that is associated with the command that fired the event.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_FAIL | The command no longer exists.
E_POINTER | Invalid argument.

Remarks

This method maps the lParam1 parameter of an EC_DVD_CMD_START or EC_DVD_CMD_END event into an IDvdCmd object that is associated with the command that fired the event. You can then call WaitForStart or WaitForEnd to control the blocking behavior of the DVD Navigator with respect to that command. The IDvdCmd object is created by the DVD Navigator and the returned pointer has already had its reference count incremented, so you must release it after WaitForStart or WaitForEnd returns.

See Also

  • EC_DVD_CMD_END
  • EC_DVD_CMD_START
  • Error and Success Codes
  • IDvdInfo2 Interface
  • Synchronizing DVD Commands


IDvdInfo2::GetCurrentAngle

The GetCurrentAngle method retrieves the number of available angles in the current angle block and the currently selected angle number.

Syntax

HRESULT GetCurrentAngle(
  ULONG *pulAnglesAvailable,
  ULONG *pulCurrentAngle
);

Parameters

pulAnglesAvailable

[out] Pointer to a variable of type ULONG that receives the number of available angles. There are up to nine angles in an angle block, numbered 1 through 9. If the value equals 1, then the DVD Navigator is not in an angle block.

pulCurrentAngle

[out] Pointer to a variable of type ULONG that receives the current angle number.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not initialized or not in a valid domain.

Remarks

Note that angle and menu button indexes are 1-based, while audio and subpicture stream indexes are 0-based. When the DVD Navigator is about to enter an angle block, it sends the application an EC_DVD_ANGLES_AVAILABLE event notification with the lParam set to 1. Applications will typically call GetCurrentAngle and IDvdControl2::SelectAngle within their event handler for EC_DVD_ANGLES_AVAILABLE.

This method is demonstrated in the DVDSample application in CAngleDlg::MakeAngleList.

See Also

  • EC_DVD_ANGLE_CHANGE
  • EC_DVD_ANGLES_AVAILABLE
  • Error and Success Codes
  • IDvdControl2::SelectAngle
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentAudio

The GetCurrentAudio method retrieves the number of available audio streams and the number of the currently selected audio stream.

Syntax

HRESULT GetCurrentAudio(
  ULONG *pulStreamsAvailable,
  ULONG *pulCurrentStream
);

Parameters

pulStreamsAvailable

[out] Pointer to a variable of type ULONG that receives the number of available audio streams.

pulCurrentStream

[out] Pointer to a variable of type ULONG that receives the currently selected audio stream number in the current title.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Input arguments are invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in a valid domain.

Remarks

To get the available audio languages on the disc, call GetCurrentAudio and then call GetAudioLanguage for each stream, starting from zero through (pulStreamsAvailable - 1) to get the language content.

See Also

  • EC_DVD_AUDIO_STREAM_CHANGE
  • Error and Success Codes
  • IDvdControl2::SelectAudioStream
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentButton

The GetCurrentButton method retrieves the number of available buttons and the number of the currently selected button.

Syntax

HRESULT GetCurrentButton(
  ULONG *pulButtonsAvailable,
  ULONG *pulCurrentButton
);

Parameters

pulButtonsAvailable

[out] Pointer to a variable of type ULONG that receives the number of buttons available.

pulCurrentButton

[out] Pointer to a variable of type ULONG that receives the number (from 1 through 36) of the currently selected button.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | One of the pointer arguments is not valid.

Remarks

If buttons are not present, both pulButtonsAvailable and pulCurrentButton are set to zero.

See Also

  • EC_DVD_BUTTON_CHANGE
  • Error and Success Codes
  • IDvdControl2::ActivateButton
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentDomain

The GetCurrentDomain method retrieves the domain in which the DVD Navigator is currently located.

Syntax

HRESULT GetCurrentDomain(
  DVD_DOMAIN *pDomain
);

Parameters

pDomain

[out] Pointer to a variable of type DVD_DOMAIN that receives the current domain.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_UNEXPECTED | Unexpected error.
E_POINTER | Invalid argument.

Remarks

You can use this method to test whether the DVD Navigator is finished playing in a particular title domain. An application doesn't have to test for the current domain before calling an IDvdControl2 method such as PlayTitle, PlayForwards, and so on. The DVD Navigator tests for the domain and simply does nothing, returning VFW_E_DVD_INVALIDDOMAIN, if the current command is invalid for the domain.

See Also

  • Domains
  • EC_DVD_DOMAIN_CHANGE
  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentLocation

The GetCurrentLocation method retrieves the current playback location.

Syntax

HRESULT GetCurrentLocation(
  DVD_PLAYBACK_LOCATION2 *pLocation
);

Parameters

pLocation

[out] Pointer to a variable of type DVD_PLAYBACK_LOCATION2 that receives the playback location information.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLocation parameter is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.

Remarks

This method retrieves information sufficient to restart playback of a video from the current playback location in titles that don't explicitly disable seeking to the current location. After the disc has been ejected, the information returned by this method will not necessarily be sufficient to restart playback. To save the current location and state information to disc so that the user can return to the same location at any later time, use GetState.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentSubpicture

The GetCurrentSubpicture method retrieves the number of available subpicture streams in the current title, the currently selected subpicture stream number, and the state of the subpicture.

Syntax

HRESULT GetCurrentSubpicture(
  ULONG *pulStreamsAvailable,
  ULONG *pulCurrentStream,
  BOOL *pbIsDisabled
);

Parameters

pulStreamsAvailable

[out] Pointer to a variable of type ULONG that receives the number of available subpicture streams.

pulCurrentStream

[out] Pointer to a variable of type ULONG that receives the number of the currently selected subpicture stream.

pbIsDisabled

[out] Pointer to a variable of type BOOL that receives a value indicating whether the subpicture display is disabled; TRUE means it is disabled.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in the Title domain.

Remarks

DVD content authors can specify that any particular subpicture stream on a disc is forcedly activated, meaning that the DVD authors require this stream to display whether the viewer wants to watch it or not. The DVD Navigator complies with all such commands from the disc, meaning that forcedly activated streams are displayed even if the application has disabled subpicture display with the IDvdControl2::SetSubpictureState method.

See Also

  • EC_DVD_SUBPICTURE_STREAM_CHANGE
  • Error and Success Codes
  • IDvdControl2::SelectSubpictureStream
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentUOPS

The GetCurrentUOPS method retrieves a set of flags indicating which navigation commands, if any, the content authors have explicitly disabled for the current disc location.

Syntax

HRESULT GetCurrentUOPS(
  ULONG *pulUOPs
);

Parameters

pulUOPs

[out] Pointer to a variable of type ULONG that is a bitwise OR of VALID_UOP_FLAG values. Each bit represents the state (valid or not valid) of a user operation (UOP). If the bit is set, then that user operation is prohibited. See Remarks.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | pulUOPs is not a valid pointer.

Remarks

DVD authors can insert UOP commands at almost any place on the disc to disallow a navigation command that would otherwise be permitted within the current DVD domain. In other words, UOP commands enable disc authors to override the usual navigation permissions.

A DVD player application should normally never have to use this method because the DVD Navigator automatically checks all UOP permissions before proceeding with any command, and will return VFW_E_DVD_OPERATION_INHIBITED from any method if the command is invalid under the current UOP. If your application needs to track the current UOP permissions itself, you can call GetCurrentUOPS whenever the current UOP permissions are required, or you can handle the EC_DVD_VALID_UOPS_CHANGE event notification in your message loop and retrieve the UOP information from the lParam1 parameter. The latter approach is generally more efficient.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetCurrentVideoAttributes

The GetCurrentVideoAttributes method retrieves the video attributes of the current title or menu.

Syntax

HRESULT GetCurrentVideoAttributes(
  DVD_VideoAttributes *pATR
);

Parameters

pATR

[out] Pointer to a DVD_VideoAttributes structure that receives the attributes.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The use of this method is demonstrated in the DVDSample application in CDvdCore::GetVideoAttributes().

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetDecoderCaps

The GetDecoderCaps method retrieves the DVD decoder's maximum data rate for video, audio, and subpicture (in forward and reverse) as well as support for various types of audio (AC-3, MPEG-2, DTS, SDDS, LPCM).

Syntax

HRESULT GetDecoderCaps(
  DVD_DECODER_CAPS *pCaps
);

Parameters

pCaps

[out] Pointer to a variable of type DVD_DECODER_CAPS that receives the information about the decoder.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
VFW_E_WRONG_STATE | The filter graph has not been initialized.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetDefaultAudioLanguage

The GetDefaultAudioLanguage method retrieves the default audio language.

Syntax

HRESULT GetDefaultAudioLanguage(
  LCID *pLanguage,
  DVD_AUDIO_LANG_EXT *pAudioExtension
);

Parameters

pLanguage

[out] Pointer to an LCID that receives the default language information.

pAudioExtension

Pointer to a variable of type DVD_AUDIO_LANG_EXT that receives a value indicating the default DVD audio language extension.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

  • Error and Success Codes
  • IDvdControl2::SelectAudioStream
  • IDvdControl2::SelectDefaultAudioLanguage


IDvdInfo2::GetDefaultMenuLanguage

The GetDefaultMenuLanguage method retrieves the default menu language.

Syntax

HRESULT GetDefaultMenuLanguage(
  LCID *pLanguage
);

Parameters

pLanguage

[out] Pointer to an LCID that receives the language information.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

  • Error and Success Codes
  • IDvdControl2::SelectDefaultMenuLanguage
  • IDvdInfo2 Interface


IDvdInfo2::GetDefaultSubpictureLanguage

The GetDefaultSubpictureLanguage method retrieves the default subpicture language.

Syntax

HRESULT GetDefaultSubpictureLanguage(
  LCID *pLanguage,
  DVD_SUBPICTURE_LANG_EXT *pSubpictureExtension
);

Parameters

pLanguage

[out] Pointer to an LCID that receives the language information.

pSubpictureExtension

[out] Pointer to a variable of type DVD_SUBPICTURE_LANG_EXT that receives one of the allowable values indicating the default language extension.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

  • Error and Success Codes
  • IDvdControl2::SelectDefaultSubpictureLanguage
  • IDvdInfo2 Interface


IDvdInfo2::GetDiscID

The GetDiscID method retrieves a system-generated 64-bit identification number for the specified DVD.

Syntax

HRESULT GetDiscID(
  LPCWSTR pszwPath,
  ULONGLONG *pullDiscID
  );

Parameters

pszwPath

[in] Path of the volume to use for the disc ID. Specify NULL to use the current DVD volume.

pullDiscID

[out] Pointer to a variable of type ULONGLONG that receives the 64-bit disc ID.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The DVD Navigator calculates a "unique" ID based on file sizes, dates, and other information, and not the BCA value. This number is guaranteed to be the same each time the disc is played. The ID applies to all replicated copies of a disc. In other words, all copies of a specific movie will have the same ID. The odds that two separate titles will have the same ID is sufficiently remote that this ID can be considered "unique" for all practical purposes.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetDVDDirectory

The GetDVDDirectory method retrieves the root directory that is set in the DVD Navigator.

Syntax

HRESULT GetDVDDirectory(
  LPWSTR pszwPath,
  ULONG ulMaxSize,
  ULONG *pulActualSize
);

Parameters

pszwPath

[out, size_is(cbMaxSize)] Pointer to a buffer that receives the path string.

ulMaxSize

[in] Size of the buffer, in WCHARs.

pulActualSize

[out] Pointer to a variable that receives the size of actual data returned, in WCHARs.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The buffer is not large enough to hold the string.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in a valid domain.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::GetDriveLetter.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetDVDTextLanguageInfo

The GetDVDTextLanguageInfo method retrieves the information for the specified text string language block.

Syntax

HRESULT GetDVDTextLanguageInfo(
  ULONG ulLangIndex,
  ULONG *pulNumOfStrings,
  LCID pLangCode,
  DVD_TextCharSet *pbCharacterSet
);

Parameters

ulLangIndex

[in] Index specifying the language block. See Remarks.

pulNumOfStrings

[out] Pointer to a variable of type ULONG that receives the number of strings for the specified language block.

pLangCode

[out] Pointer to a variable of type LCID that represents the language in which the text is written.

pbCharacterSet

[out] Pointer to a DVD_TextCharSet enumeration that receives a value indicating which character set is used for the specified language.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

Call GetDVDTextNumberOfLanguages to set up the index of all the available text languages for menus and subpictures. Then, for each index entry, call GetDVDTextLanguageInfo to retrieve the information for that particular language (number of strings, language code, character set).

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface
  • Working with DVD Text Strings


IDvdInfo2::GetDVDTextNumberOfLanguages

The GetDVDTextNumberOfLanguages method retrieves the number of text languages for the current DVD or disc side.

Syntax

HRESULT GetDVDTextNumberOfLanguages(
  ULONG *pulNumOfLangs
);

Parameters

pulNumOfLangs

[out] Pointer to a variable of type ULONG that receives the number of text languages.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

Depending on how the disc is authored, the number of languages will be valid either for the entire disc, or for the current side only.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface
  • Working with DVD Text Strings


IDvdInfo2::GetDVDTextStringAsNative

The GetDVDTextStringAsNative method retrieves the text string for the specified language as an array of bytes.

Syntax

HRESULT GetDVDTextStringAsNative(
  ULONG ulLangIndex,
  ULONG ulStringIndex,
  BYTE *pchBuffer,
  ULONG ulMaxBufferSize,
  ULONG *pulActualSize,
  DVD_TextStringType *pType
);

Parameters

ulLangIndex

[in] Language index.

ulStringIndex

[in] String index of the given language.

pchBuffer

[out] Pointer to a buffer that receives the text string. If pchBuffer is NULL, then this method returns only the size of the string in pulActualSize.

ulMaxBufferSize

[in] Maximum string size allowed (size of pchBuffer).

pulActualSize

[out] Actual length, in bytes, of the string returned in pchBuffer, including the terminating NULL.

pType

[out] Pointer to a variable of type DVD_TextStringType enumeration receives the type of string data returned.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

In general, a robust application can handle Unicode™ strings. So, when getting a string, you generally first call IDvdInfo2::GetDVDTextStringAsUnicode. But because some strings might contain characters that cannot be represented in Unicode, if GetDVDTextStringAsUnicode fails, the application can try calling GetDVDTextStringAsNative.

A terminating NULL is appended to the returned string.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface
  • Working with DVD Text Strings


IDvdInfo2::GetDVDTextStringAsUnicode

The GetDVDTextStringAsUnicode method retrieves the text string for the specified language and string indexes in Unicode™.

Syntax

HRESULT GetDVDTextStringAsUnicode(
  ULONG ulLangIndex,
  ULONG ulStringIndex,
  TCHAR *pchBuffer,
  ULONG ulMaxBufferSize,
  ULONG *pulActualSize,
  enum DVD_TextStringType *pType
);

Parameters

ulLangIndex

[in] Language index.

ulStringIndex

[in] String index of the given language.

pchBuffer

[out] Pointer to a buffer that receives the text string. If pchBuffer is NULL, then this method returns only the size of the string in pulActualSize.

ulMaxBufferSize

[in] Maximum string size allowed, calculated as sizeof(pchBuffer)/sizeof(*pchBuffer).

pulActualSize

[out] Pointer to a variable of type ULONG that receives the actual length of the string returned in pchBuffer, including the terminating NULL.

pType

[out] Pointer to a variable of type DVD_TextStringType that receives the type of string data returned.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

In general, a robust application can handle Unicode™ strings. So, when getting a string, you generally first call GetDVDTextStringAsUnicode. But because some strings might contain characters that cannot be represented in Unicode, if GetDVDTextStringAsUnicode fails, the application can try calling GetDVDTextStringAsNative.

A terminating NULL is appended to the returned string.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface
  • Working with DVD Text Strings


IDvdInfo2::GetDVDVolumeInfo

The GetDVDVolumeInfo method retrieves the current DVD volume information.

Syntax

HRESULT GetDVDVolumeInfo(
  ULONG *pulNumOfVolumes,
  ULONG *pulVolume,
  DVD_DISC_SIDE *pSide,
  ULONG *pulNumOfTitles
);

Parameters

pulNumOfVolumes

[out] Pointer to a variable of type ULONG that receives the number of volumes in the volume set.

pulVolume

[out] Pointer to a variable of type ULONG that receives the volume number for this root directory.

pSide

[out] Pointer to a variable of type DVD_DISC_SIDE that receives the current disc side.

pulNumOfTitles

[out] Pointer to a variable of type ULONG that receives the number of titles available in this volume.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.

Remarks

Some discs can be distributed as part of multidisc set. "Volume" in this context can mean either "disc" or "disc side", depending on how the disc was authored.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetKaraokeAttributes

The GetKaraokeAttributes method retrieves the karaoke attributes of the specified audio stream in the current title or menu.

Syntax

HRESULT GetKaraokeAttributes(
  ULONG ulStream,
  DVD_KaraokeAttributes *pATR
);

Parameters

ulStream

[in] Variable of type ULONG specifying the index of the audio stream whose attributes you want to query. See Remarks.

pATR

[out] Pointer to a DVD_KaraokeAttributes structure that is filled with the karaoke attributes.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_NOT_IN_KARAOKE_MODE | The specified stream is not in karaoke format.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
VFW_E_DVD_NO_ATTRIBUTES | The karaoke attributes for the specified stream are not available for some reason.

Remarks

This method does not explicitly return the number of channels in the stream. You can obtain that information through a call to IDvdInfo2::GetAudioAttributes. This method is demonstrated in the DVDSample application in CKaraokeDlg::DoModal.

The ulStream parameter may be a value from 0 through 7, or one of the following:

Value | Description
DVD_STREAM_DATA_CURRENT (0x800) | To query the currently selected audio stream.
DVD_DEFAULT_AUDIO_STREAM | To query the default audio stream.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetMenuLanguages

The GetMenuLanguages method retrieves all the languages available for all menus on the disc.

Syntax

HRESULT GetMenuLanguages(
  LCID *pLanguages,
  ULONG ulMaxLanguages,
  ULONG *puActualLanguages
);

Parameters

pLanguages

[out] Pointer to an LCID array that receives the languages returned. To retrieve only the number of languages available for menus, and not the actual languages themselves, specify NULL for pLanguages.

ulMaxLanguages

[in] Maximum number of languages to retrieve.

puActualLanguages

[out] Pointer to a variable of type ULONG that receives the actual number of languages retrieved.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetNumberOfChapters

The GetNumberOfChapters method retrieves the number of chapters in a given title.

Syntax

HRESULT GetNumberOfChapters(
  ULONG ulTitle,
  ULONG *pulNumOfChapters
);

Parameters

ulTitle

[in] Variable of type ULONG that specifies the title.

pulNumOfChapters

[out] Pointer to a variable of type ULONG that receives the number of chapters for the specified title.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | A parameter is invalid.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

Call this method to get the number of chapters before calling IDvdControl2::PlayChapter, to ensure that you specify a valid chapter number.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetPlayerParentalLevel

The GetPlayerParentalLevel method retrieves the current parental level and ISO 3166 country/region code settings for the DVD Navigator.

Syntax

HRESULT GetPlayerParentalLevel(
  ULONG *pulParentalLevel,
  BYTE pulCountryCode[2]
);

Parameters

pulParentalLevel

[out] Pointer to a variable of type ULONG that receives a value indicating the current parental level. Valid parental levels are 1 through 8 if parental management is enabled, 0xFFFFFFFF if parental management is disabled.

pulCountryCode

[out] Address of a two-byte array that receives the current country/region code (ISO 3166 Alpha-2 Code).

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | A parameter is invalid.

Remarks

Parental management is disabled by default in the DVD Navigator. This method is demonstrated in the DVDSample application in CDvdCore::GetParentalLevel.

See Also

  • EC_DVD_PARENTAL_LEVEL_CHANGE
  • Enforcing Parental Management Levels
  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetState

The GetState method retrieves a bookmark containing the disc location and DVD Navigator state information.

Syntax

HRESULT GetState(
  IDvdState **pStateData
);

Parameters

pStateData

[out] Address of a pointer to the IDvdState interface of a DvdState object allocated by the DVD Navigator.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | DVD Navigator is not initialized.

Remarks

When this method is called, the DVD Navigator creates a new state object and saves the current location into it, as well as the current parental level and other state information. The DVDState object can be used to restore the DVD Navigator to the saved location at a later time through a call to IDvdControl2::SetState. This enables viewers to stop viewing in the middle of a disc, save the location, and come back at some later time to begin viewing where they left off, with all the internal settings restored as they were before.

The DVD Navigator calls AddRef on the DvdState object before returning it to the application. The application must call Release on the object when it is finished with it.

This method is demonstrated in the DVDSample application in CDvdCore::RestoreBookmark.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetSubpictureAttributes

The GetSubpictureAttributes method retrieves the attributes of the specified subpicture stream in the specified title or menu.

Syntax

HRESULT GetSubpictureAttributes(
  ULONG ulStream,
  DVD_SubpictureAttributes *pAttributes
);

Parameters

ulStream

[in] Index number, from 0 through 31, of the subpicture stream to query. See Remarks.

pAttributes

[out] Pointer to a DVD_SubpictureAttributes structure that receives the subpicture attributes.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_FAIL | No subpicture streams were found.
E_POINTER | Invalid argument.
VFW_E_ATTRIBUTES_DO_NOT_EXIST | The subpicture has no defined attributes.

Remarks

The index numbers 0-31 are valid only for titles. Menus have only one subpicture stream, which must be specified using one of the constants in the table below:

Value | Description
DVD_STREAM_DATA_CURRENT (0x800) | To query the currently selected subpicture stream.
DVD_STREAM_DATA_VMGM (0x400) | To query the subpicture attributes for the Video Manager or "Top" Menu.
DVD_STREAM_DATA_VTSM (0x401) | To query the subpicture attributes for the currently selected Video Title Set Menu.

This method is demonstrated in the DVDSample application in CDvdCore::GetSPAttributes() and CSPLangDlg::GetSPLang.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface
  • IsSubpictureStreamEnabled
  • Working With DVD Menus


IDvdInfo2::GetSubpictureLanguage

The GetSubpictureLanguage method retrieves the language of the specified subpicture stream within the current title.

Syntax

HRESULT GetSubpictureLanguage(
  ULONG ulStream,
  LCID *pLanguage
);

Parameters

ulStream

[in] Number of the subpicture stream for which the language is being retrieved.

pLanguage

[out] Pointer to an LCID that receives the locale information. The language information can then be extracted from the LCID by using the Win32 MAKELANGID macro.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in a valid domain.

Remarks

To get the text languages available for a menu, call GetMenuLanguages. GetSubpictureLanguage sets the value pointed to by pLanguage to zero if the stream contains an unknown language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage:

LCID Language;
hr = pDvdInfo->GetSubpictureLanguage(ulStream, &Language);
if (SUCCEEDED(hr))
{
    int cchSize = GetLocaleInfo(Language, LOCALE_SENGLANGUAGE, 0, 0);
    TCHAR *szString = new TCHAR[cchSize];
    if (szString)
    {
        GetLocaleInfo(Language, LOCALE_SENGLANGUAGE, szString, cchSize);
        /* ... */
        delete [] szString;
    }
}

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetTitleAttributes

The GetTitleAttributes method retrieves attributes of all video, audio, and subpicture streams for the specified title and its menus.

Syntax

HRESULT GetTitleAttributes(
  ULONG ulTitle,
  DVD_MenuAttributes *pMenu,
  DVD_TitleAttributes *pTitle
);

Parameters

ulTitle

[in] Variable of type ULONG, from 1 through 99, specifying the requested title number. Specify 0xFFFFFFFF for the current title.

pMenu

[out] Pointer to a DVD_MenuAttributes structure that receives the attributes of the menu associated with the specified title.

pTitle

[out] Pointer to a DVD_TitleAttributes structure that receives the attributes of the specified title.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | The nTitle parameter is invalid.
E_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
E_POINTER | The pMenu or pTitle parameter is invalid.
E_UNEXPECTED | DVD Navigator is not initialized or some other internal error occurred.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetTitleParentalLevels

The GetTitleParentalLevels method retrieves the parental levels that are defined for a particular title.

Syntax

HRESULT GetTitleParentalLevels(
  ULONG ulTitle,
  ULONG *pulParentalLevels
);

Parameters

ulTitle

[in] Title for which parental levels are requested. Specify 0xfffffff to return the parental levels for the current title.

pulParentalLevels

[out] Pointer to a variable of type ULONG that receives a bitwise OR combination of DVD_PARENTAL_LEVEL values defined for the title.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A title can contain different parental levels for different sections.

See Also

  • Enforcing Parental Management Levels
  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetTotalTitleTime

The GetTotalTitleTime method retrieves the total playback time for the current title.

Syntax

HRESULT GetTotalTitleTime(
  DVD_HMSF_TIMECODE *pTotalTime,
  ULONG *pulTimeCodeFlags
);

Parameters

pTotalTime

[out] Pointer to a variable of type DVD_HMSF_TIMECODE that receives the total time in hours, minutes, seconds, and frames.

pulTimeCodeFlags

[out] Pointer to a variable of type ULONG that receives a DVD_TIMECODE_FLAGS value indicating the frame rate at which the disc was authored to play. Specify NULL if you don't want to receive the timecode information.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
VFW_S_DVD_NON_ONE_SEQUENTIAL | The title is not a one sequential video title.

Remarks

The total title time is the time required to play the title sequentially, not counting any stills, pauses, and so on.

This method is for use only with one sequential video titles, which are titles such as movies in which each chapter automatically branches to the next chapter so that the entire title plays continuously without stopping. Nonsequential video titles are titles whose chapters do not automatically play one after another. Because of variations in how DVD authors encode time information on nonsequential video titles, do not use this method to determine the total time for such titles.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::GetVMGAttributes

The GetVMGAttributes method retrieves attributes of all video, audio, and subpicture streams for the Video Manager Menu.

Syntax

HRESULT GetVMGAttributes(
  DVD_MenuAttributes *pATR
);

Parameters

pATR

[out] Pointer to a DVD_MenuAttributes structure that receives the attributes.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The Video Manager Menu is not associated with any particular title number.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::IsAudioStreamEnabled

The IsAudioStreamEnabled method determines if the specified audio stream is enabled in the current title.

Syntax

HRESULT IsAudioStreamEnabled(
  ULONG ulStreamNum,
  BOOL *pbEnabled
);

Parameters

ulStreamNum

[in] Audio stream number to test.

pbEnabled

[out] Pointer to a variable of type BOOL that receives a value of TRUE if the audio stream is enabled, or FALSE otherwise.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A DVD can have up to eight separate audio streams, although typically not all the streams will be enabled for each title. Use IsAudioStreamEnabled to determine whether a particular stream is enabled for the current title, and then call IDvdControl2::SelectAudioStream to select one of the enabled streams.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdInfo2::IsSubpictureStreamEnabled

The IsSubpictureStreamEnabled method determines if the specified subpicture stream is enabled in the current title.

Syntax

HRESULT IsSubpictureStreamEnabled(
  ULONG ulStreamNum,
  BOOL *pbEnabled
);

Parameters

ulStreamNum

[in] Subpicture stream number to test.

pbEnabled

[out] Pointer to a variable of type BOOL that receives a value of TRUE if the audio stream is enabled, or FALSE otherwise.

Return Values

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A DVD can have up to 32 separate subpicture streams, although typically not all the streams will be enabled for each title. Use IsSubpictureStreamEnabled to determine whether a particular stream is enabled for the current title, and then call IDvdControl2::SelectSubpictureStream to select one of the enabled streams.

See Also

  • Error and Success Codes
  • IDvdInfo2 Interface


IDvdState Interface

The IDvdState interface is implemented by a DvdState object, which is created by the DVD Navigator filter when an application calls IDvdInfo2::GetState to save the state of the user's session to disk, including playback location, parental level, and region. An application can use the IDvdState methods to query for this information, which is saved in a DvdState object.

The DvdState objects implement IPersist to enable saving to disk. For sample code showing how to save bookmarks, see Saving and Restoring DvdState Objects.

The DVD Navigator initializes the DvdState object with the current playback location on the DVD, the user's parental level, and the DVD region. An alternative approach is for the application to create the state object by calling CoCreateInstance:

CoCreateInstance(CLSID_DVDState, NULL, CLSCTX_INPROC_SERVER,
    IID_IDvdState, (void **)ppState);

Call IDvdControl2::SetState to resume playback at a later time from the point where it left off when GetState was called, with the restored parental and region settings.

In addition to the methods inherited from IUnknown, the IDvdState interface exposes the following methods.

Method | Description
GetDiscID | Retrieves the unique identifier (ID) of the disc from which the bookmark was made.
GetParentalLevel | Retrieves the user's parental level as saved in the DvdState object.


IDvdState::GetDiscID

The GetDiscID method retrieves the unique ID of the disc from which the bookmark was made.

Syntax

HRESULT GetDiscID(
  ULONGLONG *pullUniqueID
);

Parameters

pullUniqueID

[out] Pointer to a variable of type ULONGLONG that receives the ID.

Return Values

Returns one of the values shown in the following table.

Return code | Description
S_OK | Success
E_POINTER | Invalid argument

See Also

  • Error and Success Codes
  • IDvdState Interface


IDvdState::GetParentalLevel

The GetParentalLevel method retrieves the user's parental level as saved in the DvdState object.

Syntax

HRESULT GetParentalLevel(
  ULONG *pulParentalLevel
);

Parameters

pulParentalLevel

[out] Pointer to a variable of type ULONG that receives the parental level.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success
E_POINTER | Invalid argument

See Also

  • Error and Success Codes
  • IDvdState Interface


IDVEnc Interface

The IDVEnc interface provides methods for setting and retrieving properties on the DV Video Encoder filter.

In addition to the methods inherited from IUnknown, the IDVEnc interface exposes the following methods.

Method | Description
get_IFormatResolution | Retrieves the encoding resolution.
put_IFormatResolution | Sets the encoding resolution.


IDVEnc::get_IFormatResolution

The get_IFormatResolution method retrieves the encoding resolution.

Syntax

HRESULT get_IFormatResolution(
  int *VideoFormat,
  int *DVFormat,
  int *Resolution,
  BYTE fDVInfo,
  DVINFO *sDVInfo
);

Parameters

VideoFormat

[out] Pointer to a variable that receives a member of the DVENCODERVIDEOFORMAT enumeration, specifying the video standard in use (NTSC or PAL).

[out] Pointer to a variable that receives a member of the DVENCODERFORMAT enumeration, specifying the digital video (DV) format.

Resolution

[out] Pointer to a variable that receives a member of the DVENCODERRESOLUTION enumeration, specifying the video resolution.

fDVInfo

[in] Boolean value specifying whether to retrieve the DVINFO structure that specifies the stream format. If TRUE, the stream format is returned in the sDVInfo parameter.

sDVInfo

[out] Pointer to a variable that receives a DVINFO structure containing the stream format. If fDVInfo is FALSE, this parameter is ignored.

Return Values

Returns S_OK if successful. Otherwise, returns E_FAIL or another error code.

See Also

  • Error and Success Codes
  • IDVEnc Interface


IDVEnc::put_IFormatResolution

The put_IFormatResolution method sets the encoding resolution.

Syntax

HRESULT put_IFormatResolution(
  int VideoFormat,
  int DVFormat,
  int Resolution,
  BYTE fDVInfo,
  DVINFO *sDVInfo
);

Parameters

VideoFormat

[in] Member of the DVENCODERVIDEOFORMAT enumeration, specifying the video standard to use (NTSC or PAL).

DVFormat

[in] Member of the DVENCODERFORMAT enumeration, specifying the DV format.

Resolution

[in] Member of the DVENCODERRESOLUTION enumeration, specifying the video resolution.

fDVInfo

[in] Boolean value specifying whether the sDVInfo parameter contains a valid DVINFO structure. To set the stream format, set this parameter to TRUE and specify the format chunk with the sDVInfo parameter.

sDVInfo

[in] If fDVInfo is TRUE, must point to a DVINFO structure that describes the stream format.

Return Values

Returns S_OK if successful. Otherwise, returns E_FAIL or another error code.

See Also

  • Error and Success Codes
  • IDVEnc Interface


IDVRGB219 Interface

The IDVRGB219 interface controls the dynamic range in the DV Video Encoder and DV Video Decoder filters.

In addition to the methods inherited from IUnknown, the IDVRGB219 interface exposes the following method.

Method | Description
SetRGB219 | Controls the dynamic range for DV encoding and decoding.


IDVRGB219::SetRGB219

The SetRGB219 method controls the dynamic range for DV encoding and decoding.

The DV video format has a dynamic range of 16–235. By default, when the DV Video Decoder decodes to 24-bit or 32-bit RGB, it stretches the color range from to 0–255. Similarly, the DV Video Encoder compresses 24-bit RGB into the 16-235 range. In RGB-219 mode, the decoder does not stretch the color range, and the encoder does not compress the color range. Use the SetRGB219 method to toggle between the default mode and RGB-219 mode.

Syntax

HRESULT SetRGB219(
  BOOL bState
);

Parameters

bState

[in] Boolean value that specifies the filter's encoding or decoder behavior.

Value | Description
TRUE | Enable RGB-219 mode.
FALSE | Disable RGB-219 mode. Use the default mode.

Return Values

Returns S_OK if successful. Otherwise, returns an HRESULT failure code.

Remarks

For the encoder, this method has no effect unless the input type is RGB-24. For the decoder, it has no effect unless the output type is RGB-24 or RGB-32.

See Also

  • Error and Success Codes
  • IDVRGB219 Interface


IDVSplitter Interface

Downgrades the frame rate on a digital video (DV) stream. The DV Splitter filter exposes this interface.

Applications can use this interface to reduce the frame rate on a DV stream, before the stream reaches the DV Video Decoder filter. This can be helpful for processor-intensive tasks, such as real-time transcoding.

In addition to the methods inherited from IUnknown, the IDVSplitter interface exposes the following method.

Method | Description
DiscardAlternateVideoFrames | Discards half of the frames in the video stream.


IDVSplitter::DiscardAlternateVideoFrames

The DiscardAlternateVideoFrames method discards half of the frames in the video stream. For NTSC, the frame rate is reduced from 30 frames per second (fps) to 15 fps. For PAL, the frame rate is reduced from 25 fps to 12.5 fps.

Syntax

HRESULT DiscardAlternateVideoFrames(
  int nDiscard
);

Parameters

nDiscard

[in] Flag that specifies whether to discard frames. If the value is non-zero, the filter discards alternate frames. If the value is zero, the filter delivers every frame.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Return code | Description
S_OK | Success.
E_UNEXPECTED | Filter is paused or running.

See Also

  • Error and Success Codes
  • IDVSplitter Interface


IEncoderAPI Interface

Note This interface is deprecated and is maintained for backward compatibility only. New applications and drivers should use the ICodecAPI interface.

The IEncoderAPI interface defines a standard way for applications and drivers to communicate with third-party hardware or software encoders that implement the interface. For more information on this interface, see Encoder API.

In addition to the methods inherited from IUnknown, the IEncoderAPI interface exposes the following methods.

Methods | Description
GetDefaultValue | Retrieves the default value for a parameter, if one exists.
GetParameterRange | Retrieves the valid range of values that the parameter supports, in cases where the parameter supports a stepped range as opposed to a list of specific values.
GetParameterValues | Retrieves the list of values supported by the given parameter.
GetValue | Retrieves the current value of a specified parameter.
IsAvailable | Queries whether a given parameter is available.
IsSupported | Queries whether a given parameter is supported.
SetValue | Sets the current value of a parameter.

Remarks

In the various interface methods, the following GUIDs, defined in uuids.h, are used to indicate which parameter is being set or retrieved.

Parameter | Description
ENCAPIPARAM_BITRATE | Specifies the bit rate, in bits per second. In constant bit rate (CBR) mode, the value gives the constant bitrate. In either variable bit rate mode, it gives the average bit rate. The value is a 32-bit unsigned long.
ENCAPIPARAM_PEAK_BITRATE | Secifies the peak bit rate. This parameter is relevant only when ENCAPIPARAM_BITRATE_MODE has been set to VariableBitRatePeak.
ENCAPIPARAM_BITRATE_MODE | Specifies the bit-rate mode, as a VIDEOENCODER_BITRATE_MODE enumeration value (32-bit signed long).

The following table describes an encoder's expected behavior under extremely high or low bitrate conditions in the two variable bitrate modes defined in VIDEOENCODER_BITRATE_MODE.

Condition | Mode | Behavior
Scene falls to black or there is zero motion | VariableBitRateAverage | Over a short period of time (several seconds) the bit rate will fall below the rate specified for the ENCAPIPARAM_BITRATE parameter. But over a four-minute period of time, the encoder will maintain the average rate, if necessary by adding "dummy" bits to the stream.
Scene falls to black or there is zero motion. | VariableBitRatePeak | The bitrate will fall below the expected rate as specified in the value for the ENCAPIPARAM_BITRATE parameter. The rate will stay at that level until a more complicated scene begins.
The scene is extremely complex. | VariableBitRateAverage | For a few seconds the rate will go up. If the scene stays complex, the rate will come back down and the picture will become blocky in order to maintain the average as specified in the value for the ENCAPIPARAM_BITRATE parameter.
The scene is extremely complex. | VariableBitRatePeak | The rate will go up and stay up, possibly above the expected rate as specified in the value for the ENCAPIPARAM_BITRATE parameter, but never above the peak as specified in the ENCAPIPARAM_PEAK_BITRATE parameter.

See Also

  • Encoder API


IEncoderAPI::GetDefaultValue

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The GetDefaultValue method retrieves the default value for a parameter, if one exists.

Syntax

HRESULT GetDefaultValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Receives the value for the parameter specified in Api. If Api was specified as ENCAPIPARAM_BITRATE_MODE, then Value will be one of the VIDEOENCODER_BITRATE_MODE constants.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::GetParameterRange

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The GetParameterRange method retrieves the valid range of values that the parameter supports, in cases where the parameter supports a stepped range as opposed to a list of specific values.

Syntax

HRESULT GetParameterRange(
  const GUID*  Api,
  VARIANT*  ValueMin,
  VARIANT*  ValueMax,
  VARIANT*  SteppingDelta
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

ValueMin

[out] Pointer to a VARIANT type that receives the minimum value of the parameter.

ValueMax

[out] Pointer to a VARIANT type that receives the maximum value of the parameter.

SteppingDelta

[out] Pointer to a VARIANT type that receives the stepping delta, which defines the valid increments from ValueMin to ValueMax.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

If Api equals ENCAPIPARAM_BITRATE_MODE, the method returns E_NOTIMPL, because the bitrate mode constants are a list of specific values.

The valid range for the parameter is [ValueMin ... ValueMax], with increments of SteppingDelta. If a parameter supports a stepped range of values, it must use one of the following variant types:

  • Unsigned types : VT_UI8, VT_UI4, VT_UI2, VT_UI1
  • Signed types : VT_I8, VT_I4, VT_I2
  • Float types : VT_R8, VT_R4

By definition, the parameter will return a specific type.

Any stepping value is valid. If the range has no stepping delta (that is, you can increment by any value), the encoder should return an empty value (VT_EMPTY) for SteppingDelta.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::GetParameterValues

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The GetParameterValues method retrieves the list of values supported by the given parameter.

Syntax

HRESULT GetParameterValues(
  const GUID*  Api,
  VARIANT**  Values
  ULONG*  ValuesCount,

);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Values

[out, size_is(*ValuesCount)] Address of a pointer to an array that receives the values.

ValuesCount

[out] Indicates the number of entries placed into the array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

This method returns an array of VARIANT types representing the individual values supported by the parameter. This array is allocated by the callee through CoTaskMemAlloc and placed into the Values parameter. On exit, ValuesCount contains the number of elements in the array. The caller must free the array by calling CoTaskMemFree.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::GetValue

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The GetValue method retrieves the current value of a specified parameter.

Syntax

HRESULT GetValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Receives the value for the parameter specified in Api. If Api was specified as ENCAPIPARAM_BITRATE_MODE, then Value will be one of the VIDEOENCODER_BITRATE_MODE constants.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::IsAvailable

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The IsAvailable method queries whether a given parameter can be read and modified.

Syntax

HRESULT IsSupported(
  const GUID* Api
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Values | Description
S_OK | The parameter can be read and modified. (Set and get operations are supported for this parameter.)
E_NOTIMPL | The parameter cannot be read or modified.

Remarks

Any errors besides those in the table above indicate an inability to process the call.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::IsSupported

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The IsSupported method queries whether a given parameter is supported.

Syntax

HRESULT IsSupported(
  const GUID* Api
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Values | Description
S_OK | The encoder supports the parameter.
E_NOTIMPL | The encoder does not support the parameter.

Remarks

The method returns S_OK if the encoder recognizes the GUID. To check whether the parameter can be read or modified, call the IEncoderAPI::IsAvailable method.

Any errors besides those in the table above indicate an inability to process the call.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEncoderAPI::SetValue

Note The IEncoderAPI interface is deprecated. Use ICodecAPI instead.

The SetValue method sets the current value of a parameter.

Syntax

HRESULT SetValue(
  const GUID*  Api,
  VARIANT*  Value
);

Parameters

Api

[in] Pointer to a GUID that specifies the parameter.

Value

[out] Pointer that specifies the value of Api. If Api was specified as ENCAPIPARAM_BITRATE_MODE, then Value must be one of the VIDEOENCODER_BITRATE_MODE constants.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

See Also

  • Encoder API
  • IEncoderAPI Interface


IEnumFilters Interface

The IEnumFilters interface enumerates the filters in a filter graph. To obtain this interface, call the IFilterGraph::EnumFilters method on the Filter Graph Manager. For more information, see Enumerating Objects in a Filter Graph.

This interface implements a standard Component Object Model (COM) collection object. For more information on COM collections, see the IEnumXXXX topic in the Platform SDK.

If the set of filters in the graph changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the IEnumFilters::Reset method to resynchronize the enumerator.

In addition to the methods inherited from IUnknown, the IEnumFilters interface exposes the following methods.

Method | Description
Clone | Makes a copy of the enumerator object.
Next | Retrieves the specified number of filters in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of filters.


IEnumFilters::Clone

The Clone method makes a copy of the enumerator object. The returned object starts with the same enumeration state as the original.

Syntax

HRESULT Clone(
  IEnumFilters **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumFilters interface of the new enumerator.

Return Values

Returns one of the following HRESULTs.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IEnumFilters Interface


IEnumFilters::Next

The Next method retrieves the specified number of filters in the enumeration sequence.

Syntax

HRESULT Next(
  ULONG cFilters,
  IBaseFilter **ppFilter,
  ULONG *pcFetched
);

Parameters

cFilters

[in] Number of filters to retrieve.

ppFilter

[out] Array of size cFilters that is filled with IBaseFilter interface pointers.

pcFetched

[out] Pointer to a variable that receives the number of filters retrieved. Can be NULL if cFilters is 1.

Return Values

Value | Description
S_FALSE | Did not retrieve as many filters as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The graph has changed and is now inconsistent with the enumerator.

Remarks

If the method succeeds, the IBaseFilter pointers all have outstanding reference counts. Be sure to release them when you are done.

If the filter graph changes (for example, the application removes a filter), the enumerator is no longer be consistent with the graph, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumFilters::Reset method. You can then call the Next method safely.

See Also

  • Error and Success Codes
  • IEnumFilters Interface


IEnumFilters::Reset

The Reset method resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK.

See Also

  • Error and Success Codes
  • IEnumFilters Interface


IEnumFilters::Skip

The Skip method skips over a specified number of filters.

Syntax

HRESULT Skip(
  ULONG cFilter
);

Parameters

cFilter

[in] Number of filters to skip.

Return Values

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The graph has changed and is now inconsistent with the enumerator.

Remarks

If the filter graph changes (for example, the application removes a filter), the enumerator is no longer be consistent with the graph, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumFilters::Reset method. You can then call the Skip method safely.

See Also

  • Error and Success Codes
  • IEnumFilters Interface


IEnumMediaTypes Interface

The IEnumMediaTypes interface enumerates a pin's preferred media types. To obtain this interface, call the IPin::EnumMediaTypes method on the pin. Filters use this interface when they connect to other filters. Applications can also use it to examine a pin's preferred media types. For more information, see Enumerating Objects in a Filter Graph.

This interface implements a standard Component Object Model (COM) collection object. For more information on COM collections, see the IEnumXXXX topic in the Platform SDK.

If a pin's set of preferred media types changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the IEnumMediaTypes::Reset method to resynchronize the enumerator.

In addition to the methods inherited from IUnknown, the IEnumMediaTypes interface exposes the following methods.

Method | Description
Clone | Makes a copy of the enumerator.
Next | Retrieves a specified number of media types.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of media types.


IEnumMediaTypes::Clone

The Clone method makes a copy of the enumerator. The returned object starts with the same enumeration state as the original.

Syntax

HRESULT Clone(
  IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumMediaTypes interface of the new enumerator.

Return Values

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the set of media types changes, the enumerator is no longer consistent with the pin, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Clone method safely.

See Also

  • Error and Success Codes
  • IEnumMediaTypes Interface


IEnumMediaTypes::Next

The Next method retrieves a specified number of media types.

Syntax

HRESULT Next(
  ULONG cMediaTypes,
  AM_MEDIA_TYPE **ppMediaTypes,
  ULONG *pcFetched
);

Parameters

cMediaTypes

[in] Number of media types to retrieve.

ppMediaTypes

[out] Array of AM_MEDIA_TYPE structure pointers, of size cPins.

pcFetched

[out] Pointer to a variable that receives the number of media types the method returned. Can be NULL if cMediaTypes is 1.

Return Values

Returns one of the following HRESULT values.

Value | Description
S_FALSE | Did not retrieve as many media types as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

The caller passes an array of AM_MEDIA_TYPE pointers in ppMediaTypes. The method allocates a number AM_MEDIA_TYPE structures equal to cMediaTypes or to the number of media types that remain in the enumeration, whichever is less. The number of structures allocated is returned in pcFetched. Delete each structure by calling the DeleteMediaType function.

If the set of media types changes, the enumerator becomes inconsistent with the owning pin. In that case, the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumMediaTypes::Reset method. You can then call the Next method safely.

See Also

  • Error and Success Codes
  • IEnumMediaTypes Interface


IEnumMediaTypes::Reset

The Reset method resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Values

Returns S_OK.

See Also

  • Error and Success Codes
  • IEnumMediaTypes Interface


IEnumMediaTypes::Skip

The Skip method skips over a specified number of media types.

Syntax

HRESULT Skip(
  ULONG cMediaTypes
);

Parameters

cMediaTypes

[in] Number of media types to skip.

Return Values

Returns one of the following HRESULT values.

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the set of media types changes, the enumerator is no longer consistent with the pin, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumMediaTypes::Reset method. You can then call the Skip method safely.

See Also

  • Error and Success Codes
  • IEnumMediaTypes Interface


IEnumPIDMap Interface

The IEnumPIDMap interface enumerates a collection of Packet ID (PID) maps. Each PID map describes how the MPEG-2 Demultiplexer filter maps a PID to an output pin on the filter. PID mappings are created by calling the IMPEG2PIDMap::MapPID method on the filter's output pin.

To obtain the IEnumPIDMap interface, call the IMPEG2PIDMap::EnumPIDMap method on the output pin. Typically, output pins for audio and video streams have at most one PID mapped at any given time.

This interface implements a standard Component Object Model (COM) collection object. For more information on COM collections, see the IEnumXXXX topic in the Platform SDK. The collection object represents a snapshot of the PID map when the collection is created. The collection is not updated automatically.

Requirements

Include Bdaiface.h.

In addition to the methods inherited from IUnknown, the IEnumPIDMap interface exposes the following methods.

MethodName | Description
Clone | Creates a copy of the collection.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips over the specified number of elements in the collection.


IEnumPIDMap::Clone

The Clone method creates a copy the collection.

Syntax

HRESULT Clone(
  IEnumPIDMap** ppIEnumPIDMap
);

Parameters

ppIEnumPIDMap

[out] Address of a variable that receives an IEnumPIDMap interface pointer, representing the new collection.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument; ppIEnumPIDMap cannot be NULL.
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

The caller must release the returned IEnumPIDMap interface.

See Also

  • Error and Success Codes
  • IEnumPIDMap Interface


IEnumPIDMap::Next

The Next method retrieves the next n elements in the collection.

Syntax

HRESULT Next(
  ULONG cRequest,
  PID_MAP* pPIDMap,
  ULONG* pcReceived
);

Parameters

cRequest

[in] The number of elements to retrieve.

pPIDMap

[in, out] Address of an array allocated by the caller, containing cRequest elements. The array is filled with PID_MAP structures that describe the PID mapping.

pcReceived

[out] Pointer to a variable that receives the number of elements actually retrieved. This parameter cannot be NULL. If cRequest equals zero, this parameter receives the total number of items in the collection.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument; pPidMap and pcReceived cannot be NULL.
S_FALSE | Reached the end of the collection.
S_OK | Success.

See Also

  • Error and Success Codes
  • IEnumPIDMap Interface


IEnumPIDMap::Reset

The Reset method moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Values

Returns S_OK if successful. If the method fails,an HRESULT error code is returned.

See Also

  • Error and Success Codes
  • IEnumPIDMap Interface


IEnumPIDMap::Skip

The Skip method skips the specified number of elements in the collection.

Syntax

HRESULT Skip(
  ULONG cRecords
);

Parameters

cRecords

[in] Specifies the number of elements to skip.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Reached the end of the collection.
S_OK | Success.

See Also

  • Error and Success Codes
  • IEnumPIDMap Interface


IEnumPins Interface

Enumerates pins on a filter.

The IBaseFilter::EnumPins method returns this interface. It is based on the standard Component Object Model (COM) enumerators. For more information, see the IEnumXXXX topic in the Platform SDK.

The filter graph manager uses this interface when it connects filters. Applications can use it to retrieve pins on a filter. For more information, see Enumerating Objects in a Filter Graph.

If the number of pins on the filter changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the IEnumPins::Reset method to resynchronize the enumerator.

In addition to the methods inherited from IUnknown, the IEnumPins interface exposes the following methods.

Method | Description
Next | Retrieves a specified number of pins.
Skip | Skips over a specified number of pins.
Reset | Resets the enumeration sequence to the beginning.
Clone | Makes a copy of the enumerator with the same enumeration state.


IEnumPins::Clone

The Clone method makes a copy of the enumerator with the same enumeration state.

Syntax

HRESULT Clone(
  IEnumPins **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumPins interface of the new enumerator.

Return Values

Returns one of the following HRESULT

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumPins::Reset method. You can then call the Clone method safely.

See Also

  • Error and Success Codes
  • IEnumPins Interface


IEnumPins::Next

The Next method retrieves a specified number of pins in the enumeration sequence.

Syntax

HRESULT Next(
  ULONG cPins,
  IPin **ppPins,
  ULONG *pcFetched
);

Parameters

cPins

[in] Number of pins to retrieve.

ppPins

[out] Array of size cPins that is filled with IPin pointers.

pcFetched

[out] Pointer to a variable that receives the number of pins retrieved. Can be NULL if cPins is 1.

Return Values

Returns one of the following HRESULT values.

Value | Description
S_FALSE | Did not retrieve as many pins as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

This method retrieves pointers to the specified number of pins, starting at the current position in the enumeration, and places them in the specified array.

If the method succeeds, the IPin pointers all have outstanding reference counts. Be sure to release them when you are done.

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumPins::Reset method. You can then call the Next method safely.

See Also

  • Error and Success Codes
  • IEnumPins Interface


IEnumPins::Reset

The Reset method resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Values

Returns S_OK.

See Also

  • Error and Success Codes
  • IEnumPins Interface


IEnumPins::Skip

The Skip method skips over a specified number of pins.

Syntax

HRESULT Skip(
  ULONG cPins
);

Parameters

cPins

[in] Number of pins to skip.

Return Values

Returns one of the following HRESULT

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the IEnumPins::Reset method. You can then call the Skip method safely.

See Also

  • Error and Success Codes
  • IEnumPins Interface


IEnumStreamIdMap Interface

The IEnumStreamIdMap interface is implemented on a standard COM collection of Stream ID maps that have been created by the MPEG-2 Demultiplexer's IMPEG2StreamIdMap::MapStreamId method. To obtain a pointer to this interface, use the IMPEG2StreamIdMap::EnumStreamIdMap method. Typically, an output pin will never have more than one stream ID mapped to it at any given time. This collection represents a snapshot of the Stream IDs mapped at the time the collection is created. The collection is not updated automatically.

In addition to the methods inherited from IUnknown, the IEnumStreamIdMap interface exposes the following methods.

Method | Description
Clone | Creates a new copy of the collection and all its sub-objects.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips over the specified element in the collection.


IEnumStreamIdMap::Clone

The Clone method copies the collection.

Syntax

HRESULT Clone(
  IEnumStreamIdMap** ppIEnumStreamIdMap
);

Parameters

ppIEnumStreamIdMap

[out] Address of an IEnumStreamIdMap interface pointer that will be set to the returned collection object.

Return Values

Returns S_OK if successful. If the method fails,an HRESULT error code is returned.

See Also

  • Error and Success Codes
  • IEnumStreamIdMap Interface


IEnumStreamIdMap::Next

The Next method retrieves the next n elements in the collection.

Syntax

HRESULT Next(
  ULONG cRequest,
  STREAM_ID_MAP* pStreamIdMap,
  ULONG* pcReceived
);

Parameters

cRequest

[in] The number of elements to retrieve.

pStreamIdMap

[in, out, size_is (cRequest)] Address of a user-allocated array containing cRequest elements that will receive the retrieved STREAM_ID_MAP structures.

pcReceived

[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Values

Returns S_OK if successful. If the method fails,an HRESULT error code is returned.

Remarks

If cRequest> = 0 and pcReceived is not NULL, upon return pcReceived contains the number of stream ID maps remaining in the collection.

See Also

  • Error and Success Codes
  • IEnumStreamIdMap Interface


IEnumStreamIdMap::Reset

The Reset method moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Values

Returns S_OK if successful. If the method fails,an HRESULT error code is returned.

See Also

  • Error and Success Codes
  • IEnumStreamIdMap Interface


IEnumStreamIdMap::Skip

The Skip method skip the element at the specified index.

Syntax

HRESULT Skip(
  ULONG cRecords
);

Parameters

cRecords

[in] Index of the element to skip.

Return Values

Returns S_OK if successful. If the method fails, an HRESULT error code is returned.

See Also

  • Error and Success Codes
  • IEnumStreamIdMap Interface


IFileSinkFilter Interface

The IFileSinkFilter interface is implemented on filters that write media streams to a file. A file sink filter in a video capture filter graph, for instance, writes the output of the video compression filter to a file. Typically, the application running this filter graph should enable the user to enter the name of the file to be written to. This interface enables the communication of this information.

IFileSinkFilter2 replaces this interface unless you need to maintain backward compatibility with Microsoft® ActiveMovie® 1.0.

If a filter needs the name of an output file, it should expose this interface to allow an application to set the file name. Note that there is currently no base class implementation of this interface.

Any application that must set the name of the file into which the file sink filter will write should use this interface to get and set the file name.

In addition to the methods inherited from IUnknown, the IFileSinkFilter interface exposes the following methods.

Method | Description
SetFileName | Sets the name of the file into which media samples will be written.
GetCurFile | Retrieves the name of the current file into which media samples will be written.


IFileSinkFilter::GetCurFile

The GetCurFile method retrieves the name and media type of the current file.

Syntax

HRESULT GetCurFile(
  LPOLESTR *ppszFileName,
  AM_MEDIA_TYPE *pmt
);

Parameters

ppszFileName

[out] Address of a pointer that receives the name of the file, as an OLESTR type.

pmt

[out] Pointer to an AM_MEDIA_TYPE structure that receives the media type. This parameter can by NULL, in which case the method does not return the media type.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_FAIL | No file is opened.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument in ppszFileName.

Remarks

If the filter has not opened a file, the method might succeed but return NULL in the ppszFileName parameter. Check the value when the method returns.

The method allocates the memory for the string returned in ppszFileName, and the memory for the format block in the media type (if any). The caller must free them by calling CoTaskMemFree. For the media type, you can use the FreeMediaType function in the base class library.

See Also

  • Error and Success Codes
  • IFileSinkFilter Interface


IFileSinkFilter::SetFileName

The SetFileName method sets the name of the file into which media samples will be written.

Syntax

HRESULT SetFileName(
  LPCOLESTR pszFileName,
  const AM_MEDIA_TYPE *pmt
);

Parameters

pszFileName

[in] Pointer to the name of the file to receive the media samples.

pmt

[in] Pointer to the type of media samples to be written to the file, and the media type of the sink filter's input pin.

Return Values

Returns an HRESULT value.

Remarks

If the pszFileName parameter names a nonexistent file, the file will be created. If it names an existing file, the sink filter will overwrite the file without first deleting it.

See Also

  • Error and Success Codes
  • IFileSinkFilter Interface


IFileSinkFilter2 Interface

The IFileSinkFilter2 interface derives from the IFileSinkFilter interface and replaces it. Like IFileSinkFilter, filters that write media streams to a file implement this interface. A file sink filter in a video capture filter graph, for instance, saves the output of the video compression filter to a file. Typically, the application running this filter graph should allow the user to enter the name of the file to which to save the data. This interface enables you to communicate this information. IFileSinkFilter2 adds the option to determine whether the file it writes should destroy an existing file of the same name. In the video capture case, do not destroy a file you've already created, because preallocating file space takes valuable time. By default, the new file does not destroy the old one. Otherwise, destroy the original file to make sure the file you author doesn't contain garbage.

A filter should implement this interface when it needs the name of an output file or needs to set options for that file. Implement the older IFileSinkFilter interface if you need to make your filter compatible with ActiveMovie 1.0. Note that there is currently no base class implementation of this interface.

When an application must set the name of the file into which the file sink filter will write, it should use this interface to get and set the file name or change options. Use the older IFileSinkFilter interface if you need to make your application compatible with ActiveMovie 1.0.

In addition to the methods inherited from IFileSinkFilter, the IFileSinkFilter interface exposes the following methods.

Method | Description
SetMode | Determines whether the file writer destroys the file when it creates the new one.
GetMode | Retrieves whether the file writer destroys the file when it creates the new one.


IFileSinkFilter2::GetMode

The GetMode method retrieves whether the file writer destroys the file when it creates the new one.

Syntax

HRESULT GetMode(
  DWORD *dwFlags
);

Parameters

dwFlags

[out] Pointer to the retrieved flags. Currently, the only defined flag is AM_FILE_OVERWRITE, which indicates that the file should be destroyed; zero indicates that the file will be left alone.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IFileSinkFilter2 Interface


IFileSinkFilter2::SetMode

The SetMode method determines whether the file writer destroys the file when it creates the new one.

Syntax

HRESULT SetMode(
  DWORD dwFlags
);

Parameters

dwFlags

[in] Currently, the only defined flag is AM_FILE_OVERWRITE, which indicates that the file writer should destroy the file. Specify zero for dwFlags to leave the file alone.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IFileSinkFilter2 Interface


IFileSourceFilter Interface

The IFileSourceFilter interface is exposed by source filters to set the file name and media type of the media file that they are to render. It is an abbreviated version@@@ of the COM IPersistFile interface. If the file has a type that can be determined by the algorithm described in Registering a Custom File Type, the recommended file source filter CLSID is used when the filter graph manager attempts to render the filter graph.

If a filter needs the name of a file to open, it should expose this interface to allow an application to set the file name. Note that there is no base class implementation of this interface.

An application that inserts file source filters directly must query for this interface and set the file name. Normally, the filter graph manager uses this interface when an application calls IGraphBuilder::RenderFile. The Graphedt.exe tool queries for the IFileSourceFilter interface and prompts for a file name if it finds it.

In addition to the methods inherited from IUnknown, the IFileSourceFilter interface exposes the following methods.

Method | Description
Load | Loads the source filter with the file.
GetCurFile | Retrieves the current file.


IFileSourceFilter::GetCurFile

The GetCurFile method retrieves the name and media type of the current file.

Syntax

HRESULT GetCurFile(
  LPOLESTR *ppszFileName,
  AM_MEDIA_TYPE *pmt
);

Parameters

ppszFileName

[out] Address of a pointer that receives the name of the file, as an OLESTR type.

pmt

[out] Pointer to an AM_MEDIA_TYPE structure that receives the media type. This parameter can by NULL, in which case the method does not return the media type.

Return Values

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_FAIL | No file is opened.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument in ppszFileName.

See Also

  • Error and Success Codes
  • IFileSourceFilter Interface

Remarks

If the filter has not opened a file, the method might succeed but return NULL in the ppszFileName parameter. Check the value when the method returns.

The method allocates the memory for the string returned in ppszFileName, and the memory for the format block in the media type (if any). The caller must free them by calling CoTaskMemFree. For the media type, you can use the FreeMediaType function in the base class library.


IFileSourceFilter::Load

The Load method causes a source filter to load a media file.

Syntax

HRESULT Load(
  LPCOLESTR pszFileName,
  const AM_MEDIA_TYPE *pmt
);

Parameters

pszFileName

[in] Pointer to the name of the file to open.

pmt

[in] Pointer to the media type of the file. This can be NULL.

Return Values

Returns an HRESULT value.

Remarks

This method initializates the interface. It is not designed to load multiple files, and any calls to this method after the first call will fail.

Depending on the filter, the pszFileName parameter should specify the absolute path to a file on disk (File Source (Async) filter, WM ASF Reader filter) or the URL of a file to download (File Source (URL) filter).

See Also

  • Error and Success Codes
  • IFileSourceFilter Interface


IFilterChain Interface

The IFilterChain interface provides methods for starting, stopping, or removing chains of filters in a filter graph. The filter graph manager exposes this interface.

A filter chain is a sequence of filters, each with at most one connected input pin and one connected output pin, that forms an unbroken line of filters. A filter chain is defined by the filter at the start of the chain and the filter at the end of the chain. (These can be the same filter, making a chain of one filter.) By definition, there is a single stream path going from the start of the chain downstream to the end of the chain.

The methods on this interface are useful in situations where an entire stream of data can appear or disappear, such as a video conferencing application that receives multiple streams over a network. For more information, see Dynamic Graph Building. To control individual streams on a capture filter, use the IAMStreamControl interface instead.

In addition to the methods inherited from IUnknown, the IFilterChain interface exposes the following methods.

Method | Description
StartChain | Switches all the filters in a filter chain into a running state.
StopChain | Switches all the filters in a filter chain into a stopped state.
RemoveChain | Removes every filter in a filter chain from the filter graph.
PauseChain | Switches all the filters in a filter chain into a paused state.


IFilterChain::PauseChain

The PauseChain method switches all the filters in a filter chain into a paused state.

Syntax

HRESULT PauseChain(
  IBaseFilter *pStartFilter,
  IBaseFilter *pEndFilter
);

Parameters

pStartFilter

[in] Pointer to the filter at the start of the chain.

pEndFilter

[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Values

Returns S_OK if successful. If the method fails, the return value may be VFW_E_NOT_PAUSED or another HRESULT value.

Remarks

If this method cannot switch a given filter into a paused state, it stops all of the filters in chain. The filter graph must be paused when you call this method.

See Also

  • Error and Success Codes
  • IFilterChain Interface


IFilterChain::RemoveChain

The RemoveChain method removes every filter in a filter chain from the filter graph.

Syntax

HRESULT RemoveChain(
  IBaseFilter *pStartFilter,
  IBaseFilter *pEndFilter
);

Parameters

pStartFilter

[in] Pointer to the filter at the start of the chain.

pEndFilter

[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure otherwise.

Remarks

You can call this method while the graph is running; the method stops the filters in the chain before removing them from the graph.

See Also

  • Error and Success Codes
  • IFilterChain Interface


IFilterChain::StartChain

The StartChain method switches all the filters in a filter chain into a running state.

Syntax

HRESULT StartChain(
  IBaseFilter *pStartFilter,
  IBaseFilter *pEndFilter
);

Parameters

pStartFilter

[in] Pointer to the filter at the start of the chain.

pEndFilter

[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Values

Returns S_OK if successful. If the method fails, the return value may be VFW_E_NOT_RUNNING or another HRESULT value.

Remarks

If this method cannot switch a given filter into a running state, it leaves all the filters in a stopped state. The filter graph must be running when you call this method.

See Also

  • Error and Success Codes
  • IFilterChain Interface


IFilterChain::StopChain

The StopChain method switches all the filters in a filter chain into a stopped state.

Syntax

HRESULT StopChain(
  IBaseFilter *pStartFilter,
  IBaseFilter *pEndFilter
);

Parameters

pStartFilter

[in] Pointer to the filter at the start of the chain.

pEndFilter

[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure otherwise.

See Also

  • Error and Success Codes
  • IFilterChain Interface


IFilterGraph Interface

The IFilterGraph interface provides methods for building a filter graph. An application can use it to add filters to the graph, connect or disconnect filters, remove filters, and perform other basic operations. However, the IGraphBuilder interface inherits from this interface and provides additional methods that are more sophisticated. Therefore, applications should use IGraphBuilder rather than using IFilterGraph directly.

The filter graph manager implements this interface.

In addition to the methods inherited from IUnknown, the IFilterGraph interface exposes the following methods.

Method | Description
AddFilter | Adds a filter to the graph.
RemoveFilter | Removes a filter from the graph.
EnumFilters | Provides an enumerator for all filters in the graph.
FindFilterByName | Finds a filter that was added with a specified name.
ConnectDirect | Connects two pins directly (without intervening filters).
Reconnect | Breaks the existing pin connection and reconnects it to the same pin.
Disconnect | Disconnects a specified pin.
SetDefaultSyncSource | Sets the reference clock to the default clock.


IFilterGraph::AddFilter

The AddFilter method adds a filter to the graph.

Syntax

HRESULT AddFilter(
  IBaseFilter *pFilter,
  LPCWSTR pName
);

Parameters

pFilter

[in] Pointer to the IBaseFilter interface of the filter to add.

pName

[in] Pointer to a wide-character string containing a name for filter.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_DUPLICATE_NAME | Successfully added a filter with a duplicate name.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.
VFW_E_CERTIFICATION_FAILURE | Use of this filter is restricted by a software key.
VFW_E_DUPLICATE_NAME | Failed to add a filter with a duplicate name.

Remarks

The name of the filter can be NULL, in which case the filter graph manager will generate a name. If the name is not NULL and is not unique, this method will modify the name in an attempt to generate a new unique name. If this is successful, this method returns VFW_S_DUPLICATE_NAME. If it cannot generate a unique name, it returns VFW_E_DUPLICATE_NAME.

AddFilter calls the filter's IBaseFilter::JoinFilterGraph method to inform the filter that it has been added. AddFilter must be called before attempting to use the IGraphBuilder::Connect, IFilterGraph::ConnectDirect, or IGraphBuilder::Render method to connect or render pins belonging to the added filter.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::ConnectDirect

The ConnectDirect method connects the two pins directly (without intervening filters).

Syntax

HRESULT ConnectDirect(
  IPin *ppinOut,
  IPin *ppinIn,
  const AM_MEDIA_TYPE *pmt
);

Parameters

ppinOut

[in] Pointer to the output pin.

ppinIn

[in] Pointer to the input pin.

pmt

[in] Pointer to the media type to use for the connection (optional; can be NULL).

Return Values

Returns one of the following values, or an error value returned by IPin::Connect.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_IN_GRAPH | One of the specified pins is not in the graph.
VFW_E_CIRCULAR_GRAPH | The input pin is upstream of the output pin, which would result in a circular graph.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::Disconnect

The Disconnect method disconnects this pin.

Syntax

HRESULT Disconnect(
  IPin *ppin
);

Parameters

ppin

[in] Pointer to the pin to disconnect.

Return Values

Returns one of the following values.

Value | Description
S_OK | Success.
S_FALSE | Pin was not connected. No error.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_STOPPED | The filter is not stopped, but does not support reconnection while in a running state.

Remarks

This method does not completely break the connection. To completely break the connection, both ends must be disconnected.

To remove a filter from the filter graph entirely, call the IFilterGraph::RemoveFilter method.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::EnumFilters

The EnumFilters method provides an enumerator for all filters in the graph.

Syntax

HRESULT EnumFilters(
  IEnumFilters **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumFilters interface. Use this interface to enumerate the filters. The caller must release the interface.

Return Values

Returns one of the following values.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory to create the enumerator.
E_POINTER | Null pointer argument.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::FindFilterByName

The FindFilterByName method finds a filter that was added to the filter graph with a specific name.

Syntax

HRESULT FindFilterByName(
  LPCWSTR pName,
  IBaseFilter **ppFilter
);

Parameters

pName

[in, string] Pointer to the name to search for.

ppFilter

[out] Address of a variable that receives a pointer to the filter's IBaseFilter interface.

Return Values

Returns one of the following values.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_FOUND | No filter was found with the specified name.

Remarks

If no filter is found, the method returns a NULL pointer in the ppFilter parameter.

The returned IBaseFilter interface has an outstanding reference count. The caller must release the interface.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::Reconnect

The Reconnect method disconnects a pin and then reconnects it to the same pin.

Applications should not call this method. It is called by filters during the graph building process.

Syntax

HRESULT Reconnect(
  IPin *ppin
);

Parameters

ppin

[in] Pointer to IPin interface of the pin to reconnect.

Return Values

Returns one of the following values.

Value | Description
S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.
VFW_E_WRONG_STATE | Filter is not stopped.

Remarks

This method is obsolete; use the IFilterGraph2::ReconnectEx method instead.

Filters can call this method in order to renegotiate a pin connection. The method executes on a separate thread. Before calling this method, call IPin::QueryAccept on the other pin to ensure that the reconnnection attempt will succeed. Do not call this method unless QueryAccept returns S_OK. Otherwise, because the reconnection is performed asynchronously, the reconnection might fail even though the Reconnect method succeeds, leaving the filter graph in an inconsistent state.

See Also

  • Error and Success Codes
  • IFilterGraph Interface
  • Reconnecting Pins


IFilterGraph::RemoveFilter

The RemoveFilter method removes a filter from the graph.

Syntax

HRESULT RemoveFilter(
  IBaseFilter *pFilter
);

Parameters

pFilter

[in] Pointer to the filter to be removed from the graph.

Return Values

Returns one of the following values.

Value | Description
S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.

Remarks

The Filter Graph Manager notifies the filter that it is being removed by calling the filter's IBaseFilter::JoinFilterGraph method with a NULL argument. It is not necessary to disconnect the filter's pins before calling RemoveFilter, but the filter graph should be in the Stopped state. If the filters are not stopped, RemoveFilter may fail to disconnect the pins and then fail to remove the filter from the graph. IGraphConfig::RemoveFilterEx enables an application to remove a filter without disconnecting the pins automatically, which improves performance if you want to move groups of connected filters into a new graph.

See Also

  • Error and Success Codes
  • IFilterGraph Interface


IFilterGraph::SetDefaultSyncSource

The SetDefaultSyncSource method sets the reference clock to the default clock.

Syntax

HRESULT SetDefaultSyncSource(void);

Return Values

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_STOPPED | The filter graph is not stopped.

Remarks

This method instructs the Filter Graph Manager to choose a reference clock using its default algorithm. For more information about the algorithm that it uses, see Reference Clocks.

Usually you do not need to call this method, because the Filter Graph Manager automatically selects a clock. However, if you call IMediaFilter::SetSyncSource to override the clock, you can use SetDefaultSyncSource to restore the default clock.

This method fails if the filter graph is running or paused.

See Also

  • Error and Success Codes
  • IFilterGraph Interface
  • Time and Clocks in DirectShow


IFilterGraph2 Interface

The IFilterGraph2 interface extends the IFilterGraph and IGraphBuilder interfaces, which contain methods for building filter graphs.

The filter graph manager implements this interface. Applications can use it when building graphs, to take advantage of the additional methods it provides.

IFilterGraph2 adds two methods to IFilterGraph and IGraphBuilder.

  • The IFilterGraph2::AddSourceFilterForMoniker method creates a source filter based on a moniker, and adds it to the graph.
  • The IFilterGraph2::ReconnectEx method improves the IFilterGraph::Reconnect method by specifying a media type for the reconnection.

In addition to the methods inherited from IGraphBuilder, the IFilterGraph2 interface exposes the following methods.

Method | Description
AddSourceFilterForMoniker | Adds a source filter based on a moniker.
ReconnectEx | Breaks the existing pin connection and reconnects it to the same pin, using a specified media type.
RenderEx | Renders an output pin, with an option to use existing renderers only.


IFilterGraph2::AddSourceFilterForMoniker

The AddSourceFilterForMoniker method adds a source filter based on a moniker. For example, you can obtain a moniker for a system device, such as a video capture device, and add a video capture filter for that device. (For more information about system device monikers, see the ICreateDevEnuminterface.)

Syntax

HRESULT AddSourceFilterForMoniker(
  IMoniker *pMoniker,
  IBindCtx *pCtx,
  LPCWSTR lpcwstrFilterName,
  IBaseFilter **ppFilter
);

Parameters

pMoniker

[in] Pointer to an IMoniker interface.

pCtx

[in] Pointer to an IBindCtx bind context interface.

lpcwstrFilterName

[in] Pointer to the filter's name.

ppFilter

[out] Address of a variable that receives an IBaseFilter interface pointer.

Return Values

Returns and HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_DUPLICATE_NAME | Success; but the specified name was a duplicate, so the Filter Graph Manager modified the name.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_DUPLICATE_NAME | Failed to add a filter with a duplicate name.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for could not be loaded.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.

Remarks

When adding a source filter for the given moniker to the graph, the COM IMoniker::BindToStorage member function will query for an IStream interface. If this fails, IMoniker::BindToObject will try to retrieve an IBaseFilter interface.

See Also

  • Error and Success Codes
  • IFilterGraph2 Interface


IFilterGraph2::ReconnectEx

The ReconnectEx method breaks the existing pin connection and reconnects it to the same pin, using a specified media type.

Applications should not call this method. It is called by filters during the graph building process.

Syntax

HRESULT ReconnectEx(
  IPin *ppin,
  const AM_MEDIA_TYPE *pmt
);

Parameters

ppin

[in] Pointer to the pin to disconnect and reconnect.

pmt

[in] Pointer to the media type to reconnect with. Specify NULL to use the existing media type.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
S_FALSE | Pin was not connected. No error.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_STOPPED | The filter is not stopped, but it does not support reconnection while in a running state.

Remarks

Filters can call this method in order to renegotiate a pin connection. The method executes on a separate thread. Before calling this method, call IPin::QueryAccept on the other pin to ensure that the reconnnection attempt will succeed. Do not call this method unless QueryAccept returns S_OK. Otherwise, because the reconnection is performed asynchronously, the reconnection might fail even though the ReconnectEx method succeeds, leaving the filter graph in an inconsistent state.

This method improves on the IFilterGraph::Reconnect method by specifying a media type. This makes the reconnection more likely to succeed.

See Also

  • Error and Success Codes
  • IFilterGraph2 Interface
  • Reconnecting Pins


IFilterGraph2::RenderEx

The RenderEx method renders an output pin, with an option to use existing renderers only.

Syntax

HRESULT RenderEx(
  IPin *pPinOut,
  DWORD dwFlags,
  DWORD *pvContext
);

Parameters

pPinOut

[in] Pointer to the IPin interface of the output pin.

dwFlags

[in] Flag that specifies how to render the pin. If the value is AM_RENDEREX_RENDERTOEXISTINGRENDERERS, the method attempts to use renderers already in the filter graph. It will not add new renderers to the graph. (It will add intermediate transform filters, if needed.) For the method to succeed, the graph must contain the appropriate renderers, and they must have unconnected input pins. If the value is zero, the method behaves identically to the IGraphBuilder::Render method.

pvContext

[in, out] Reserved. Must be NULL.

Return Values

Returns an HRESULT.

See Also

  • Error and Success Codes
  • IFilterGraph2 Interface


IFilterMapper2 Interface

Registers and unregisters filters, and locates filters in the registry. The Filter Mapper helper object implements this interface.

Filters use this interface to register and unregister themselves. When the filter graph manager builds a filter graph, it uses this interface to look up filters and determine their characteristics. Applications can also use this interface to look up filters. For more information, see Using the Filter Mapper and How to Register DirectShow Filters.

In addition to the methods inherited from IUnknown, the IFilterMapper2 interface exposes the following methods.

Method | Description
CreateCategory | Adds a new filter category to the registry.
UnregisterFilter | Removes filter information from the registry.
RegisterFilter | Adds filter information to the registry.
EnumMatchingFilters | Enumerates registered filters that meet specified requirements.


IFilterMapper2::CreateCategory

The CreateCategory method adds a new filter category to the registry.

Syntax

HRESULT CreateCategory(
  REFCLSID clsidCategory,
  DWORD dwCategoryMerit,
  LPCWSTR Description
);

Parameters

clsidCategory

[in] Class identifier (CLSID) of the new filter category.

dwCategoryMerit

[in] Merit of the category. Categories with higher merit are enumerated first.

Description

[in] Descriptive name for the category.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

The filter graph manager initially skips all categories with a merit value less than or equal to MERIT_DO_NOT_USE, to speed up the graph-building process. Filter categories that should not be considered for playback should have a merit of MERIT_DO_NOT_USE or less.

A filter can appear in one or more categories (for example, Video Compressors) to restrict the search space.

See Also

  • Error and Success Codes
  • IFilterMapper2 Interface


IFilterMapper2::EnumMatchingFilters

The EnumMatchingFilters method enumerates registered filters that meet specified requirements.

Syntax

HRESULT EnumMatchingFilters(
  IEnumMoniker **ppEnum,
  DWORD dwFlags,
  BOOL bExactMatch,
  DWORD dwMerit,
  BOOL bInputNeeded,
  DWORD cInputTypes,
  const GUID *pInputTypes,
  const REGPINMEDIUM *pMedIn,
  const CLSID *pPinCategoryIn,
  BOOL bRender,
  BOOL bOutputNeeded,
  DWORD cOutputTypes,
  const GUID *pOutputTypes,
  const REGPINMEDIUM *pMedOut,
  const CLSID *pPinCategoryOut
);

Parameters

ppEnum

[out] Address of a variablle that receives a pointer to the IEnumMoniker interface. Use this interface pointer to retrieve filter monikers from the enumeration. The caller must release the interface.

dwFlags

[in] Reserved, must be zero.

bExactMatch

[in] Boolean value indicating whether an exact match is required. See Remarks for more information.

dwMerit

[in] Minimum merit value. The enumeration exludes filters with a lesser merit value. If dwMerit is higher than MERIT_DO_NOT_USE, the enumeration also excludes filters whose category has a merit less than or equal to MERIT_DO_NOT_USE. (See Filter Categories.)

bInputNeeded

[in] Boolean value indicating whether the filter must have an input pin. If the value is TRUE, the filter must have at least one input pin.

cInputTypes

[in] Number of input media types specified in pInputTypes.

pInputTypes

[in] Pointer to an array of GUID pairs that specify major types and subtypes, for the input pins to match. The size of the array is 2 * cInputTypes. The array can be NULL. Individual array members can be GUID_NULL, which matches any type. (See Media Types.)

pMedIn

[in] Pointer to a REGPINMEDIUM structure specifying the medium for the input pins. Set to NULL if not needed.

pPinCategoryIn

[in] Pointer to a GUID that specifies the input pin category. (See Pin Property Set.) Set to NULL if not needed.

bRender

[in] Boolean value that specifies whether the filter must render its input. If TRUE, the specified filter must render input.

bOutputNeeded

[in] Boolean value specifying whether the filter must have an output pin. If TRUE, the filter must have at least one output pin.

cOutputTypes

[in] Number of input media types specified in pOutputTypes.

pOutputTypes

[in] Pointer to an array of GUID pairs that specify major types and subtypes, for the output pins to match. The size of the array is 2 * cOutputTypes. The array can be NULL. Individual array members can be GUID_NULL, which matches any type.

pMedOut

[in] Pointer to a REGPINMEDIUM structure specifying the medium for the output pins. Set to NULL if not needed.

pPinCategoryOut

[in] Pointer to a GUID that specifies the output pin category. (See Pin Property Set.) Set to NULL if not needed.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

To find filters whose input pins match a given set of media types, declare an array with major-type GUIDs and subtype GUIDs ordered in pairs. Pass the array address in the pInputTypes parameter, and set the cInputTypes parameter equal to the number of pairs (that is, half the array size):

GUID arrayInTypes[2];
arrayInTypes[0] = MEDIATYPE_Video;
arrayInTypes[1] = GUID_NULL;

DWORD cInTypes = 1;

For output pins, pass a similar array in the pOutputTypes parameter, and specify the number of GUID pairs in the cOutputTypes parameter.

If the value of the bExactMatch parameter is TRUE, this method looks for filters that exactly match the values you specify for media type, pin category, and pin medium. If the value is FALSE, filters that register a value of NULL for any of these items are considered a match. (In effect, a NULL value in the registry acts as a wildcard.)

If you specify NULL for media type, pin category, or pin medium, any filter is considered a match for that parameter.

If a pin did not register any media types, this method will not consider it a match for the media type.

See Also

  • Error and Success Codes
  • IFilterMapper2 Interface


IFilterMapper2::RegisterFilter

The RegisterFilter method adds filter information to the registry.

Syntax

HRESULT RegisterFilter(
  REFCLSID clsidFilter,
  LPCWSTR Name,
  IMoniker **ppMoniker,
  const CLSID *pclsidCategory,
  const OLECHAR *szInstance,
  const REGFILTER2 *prf2
);

Parameters

clsidFilter

[in] Class identifier (CLSID) of the filter.

Name

[in] Descriptive name for the filter.

ppMoniker

[in, out] Address of a pointer to a device moniker that determines where this filter's data will be written. Can be NULL.

pclsidCategory

[in] Pointer to the filter category of the filter. If NULL, the default category is CLSID_ActiveMovieFilters. (See Filter Categories.)

szInstance

[in] Instance data for constructing the device moniker's display name. Can be the friendly name, or the string representation of the filter CLSID. If NULL, defaults to the filter CLSID.

prf2

[in] Pointer to a REGFILTER2 structure containing filter information.

Return Values

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_BAD_KEY | Could not get registry key.

Remarks

This method adds information about the filter to the registry, under the registry entry for the specified filter category. It does not register the in-process server that creates the filter (usually a DLL). To register the server, you can call the AMovieDllRegisterServer2 function.

For the ppMoniker parameter, use one of the following:

  • The address of an IMoniker interface pointer for an existing device moniker
  • The address of a NULL IMoniker interface pointer
  • NULL

If you are registering a filter for a Windows Driver Model (WDM) or Plug and Play device, pass the address of the existing device moniker. The filter will be registered using this moniker. When the method returns, *ppMoniker is set to NULL.

Otherwise, the method creates a new moniker. If ppMoniker is non-NULL, the method sets *ppMoniker to point to the new moniker. The application can use this moniker to write additional private values in the property bag. Be sure to release the interface.

Set ppMoniker to NULL if you don't want to provide or receive the moniker.

See Also

  • Error and Success Codes
  • IFilterMapper2 Interface


IFilterMapper2::UnregisterFilter

The UnregisterFilter method removes filter information from the registry.

Syntax

HRESULT UnregisterFilter(
  const CLSID *pclsidCategory,
  const OLECHAR *szInstance,
  REFCLSID Filter
);

Parameters

pclsidCategory

[in] Address of a GUID that specifies the filter category from which to remove the filter. For a list of categories, see Filter Categories.

szInstance

[in] Instance data used to construct the device moniker's display name. Use the value that was originally passed to the RegisterFilter method.

Filter

[in] Class identifier (CLSID) of the filter.

Return Values

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

If the filter was not registered, the method might return an error.

See Also

  • Error and Success Codes
  • IFilterMapper2 Interface


IFullScreenVideoEx Interface

The IFullScreenVideoEx interface is implemented on the Full Screen Renderer filter, which provides full-screen video rendering on older hardware. Newer video cards can stretch the video efficiently enough that the Full Screen Renderer is not required. Therefore, both the filter and this interface are now deprecated.

In addition to the methods inherited from IUnknown, the IFullScreenVideoEx interface exposes the following methods.

Method | Description
CountModes | Retrieves the number of display modes that the Full Screen Renderer supports.
GetAcceleratorTable | Retrieves the accelerator table currently being used to translate keyboard messages. (Not supported.)
GetCaption | Retrieves the caption associated with the full-screen window.
GetClipFactor | Retrieves the clip factor, which determines how much of the video the Full Screen Renderer is allowed to clip.
GetCurrentMode | Retrieves the current display mode.
GetMessageDrain | Retrieves the window that receives mouse and keyboard messages.
GetModeInfo | Retrieves information about a specified display mode.
GetMonitor | Queries which monitor the Full Screen Renderer is using. (Not supported.)
HideOnDeactivate | Specifies the behavior when the user switches to another application.
IsHideOnDeactivate | Indicates the behavior when the user switches to another application.
IsKeepPixelAspectRatio | Queries whether the pixel aspect ratio is maintained. (Not supported.)
IsModeAvailable | Queries whether a specified display mode is available.
IsModeEnabled | Queries whether a specified display mode is enabled.
KeepPixelAspectRatio | Specifies whether to maintain the pixel aspect ratio. (Not supported.)
SetAcceleratorTable | Specifies an accelerator table that will be used to translate keyboard messages. (Not supported.)
SetCaption | Sets the caption associated with the full-screen window.
SetClipFactor | Specifies the clip factor.
SetDefault | Saves the current settings.
SetEnabled | Enables or disables a specified display mode.
SetMessageDrain | Specifies a window to receive mouse and keyboard messages from the video window.
SetMonitor | Specifies which monitor to use. (Not supported.)


IFullScreenVideoEx::CountModes

The CountModes method retrieves the number of display modes that the Full Screen Renderer supports.

Syntax

HRESULT CountModes(
  long *pModes
);

Parameters

pModes

[out] Pointer to the returned mode count.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetAcceleratorTable

The GetAcceleratorTable method retrieves the accelerator table currently being used to translate keyboard messages. The Full Screen Renderer filter does not support this method.

Syntax

HRESULT GetAcceleratorTable(
    HWND *phwnd,
    HACCEL *phAccel
);

Parameters

phwnd

[out] Pointer to a variable that receives a window handle. The window receives translated messages.

phAccelr

[out] Pointer to a variable that receives a handle to the accelerator table.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetCaption

The GetCaption method retrieves the caption associated with the full-screen window.

Syntax

HRESULT GetCaption(
  BSTR *pstrCaption
);

Parameters

pstrCaption

[out] Pointer to a BSTR that receives the caption.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The caption is visible when the window is minimized.

The caller must release the returned string, by calling the SysFreeString function.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetClipFactor

The GetClipFactor method retrieves the clip factor, which determines how much of the video the Full Screen Renderer is allowed to clip. For example, if the clip factor is 25, the Full Screen Renderer can clip up to 25% of the video.

Syntax

HRESULT GetClipFactor(
  long *pClipFactor
);

Parameters

pClipFactor

[out] Pointer to a variable the receives the clip factor.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetCurrentMode

The GetCurrentMode method retrieves the current display mode.

Syntax

HRESULT GetCurrentMode(
  long *pMode
);

Parameters

pMode

[out] Pointer to a variable that receives the index of the current video mode. Pass this index to the IFullScreenVideoEx::GetModeInfo method to obtain information about this mode, including the width, height, and bit depth.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The filter did not load DirectDraw.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetMessageDrain

The GetMessageDrain method retrieves the window that receives mouse and keyboard messages, if any.

Syntax

HRESULT GetMessageDrain(
  HWND *hwnd
);

Parameters

hwnd

[out] Pointer to a variable that receives the handle of the window. If no window has been designated to receive messages, this parameter receives the value NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

This method is equivalent to the IVideoWindow::get_MessageDrain method.

The Full Screen video renderer posts all mouse and keyboard messages to the window designated as a message drain. The exact list of messages that are posted is the same as the list given in IVideoWindow::put_MessageDrain.

Applications do not need to use this method. Use the IVideoWindow::get_MessageDrain method on the Filter Graph Manager instead.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetModeInfo

The GetModeInfo method retrieves information about a specified display mode supported by the Full Screen Renderer filter.

Syntax

HRESULT GetModeInfo(
  long Mode,
  long *pWidth,
  long *pHeight,
  long *pDepth
);

Parameters

Mode

[in] Index of the display mode.

pWidth

[out] Pointer to a variable that receives the width of the display mode, in pixels.

pHeight

[out] Pointer to a variable that receives the height of the display mode, in pixels.

pDepth

[out] Pointer to a variable that receives the bit depth of the display mode.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.
S_FALSE | The specified display mode is not available and is disabled.
S_OK | Success.

Remarks

Display modes are indexed from zero. The IFullScreenVideoEx::CountModes method returns the number of modes.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::GetMonitor

The GetMonitor method queries which monitor the Full Screen Renderer is using. The Full Screen Renderer only supports the primary monitor, so the returned value is always zero.

Syntax

HRESULT GetMonitor(
  long *Monitor
);

Parameters

Monitor

[out] Pointer to a variable that receives the index of the monitor.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::HideOnDeactivate

The HideOnDeactivate method . Depending on the setting, the full-screen video window is either minimized or hidden. If it is minimized, it appears as an icon in the task bar; otherwise, it does not.

Syntax

HRESULT HideOnDeactivate(
  long Hide
);

Parameters

Hide

[in] Value that specifies the behavior when the application is deactivated. Set to OATRUE to hide the icon; set to OAFALSE to display the icon.

Value | Description
OATRUE | Hide the video window.
OAFALSE | Minimize the video window. (Default)

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::IsHideOnDeactivate

The IsHideOnDeactivate method indicates the behavior when the user switches to another application. Depending on the setting, the full-screen video window is either minimized or hidden. If it is minimized, it appears as an icon in the task bar; otherwise, it does not.

Syntax

HRESULT IsHideOnDeactivate(void);

Return Values

Returns one of the following values.

Value | Description
S_FALSE | The video window is minimized. (Default)
S_OK | The video window is hidden.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::IsKeepPixelAspectRatio

The IsKeepPixelAspectRatio method queries whether the pixel aspect ratio is maintained. The Full Screen Renderer filter does not support this method; it always maintains the pixel aspect ratio.

Syntax

HRESULT GetAcceleratorTable(
    long *pKeepAspect
);

Parameters

pKeepAspect

[in] Pointer to a variable that receives the value OATRUE or OAFALSE.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::IsModeAvailable

The IsModeAvailable method queries whether a specified display mode is available.

Syntax

HRESULT IsModeAvailable(
  long Mode
);

Parameters

Mode

[in] Index of the display mode.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Index out of range.
S_FALSE | The display mode is not available.
S_OK | The display mode is available.

Remarks

The Full Screen Renderer supports a static set of display modes. However, the video card on the user's system might not support every mode. If a particular display mode is not supported by the video card, this method returns S_FALSE. Even if a particular mode is available, it will not necessarily be used for video playback. The mode must also be compatible with the filters in the filter graph.

You can disable a display mode by calling the IFullScreenVideoEx::SetEnabled method. The Full Screen Renderer will not use a disabled mode, even if the video card supports it.

Display modes are indexed from zero. The IFullScreenVideoEx::CountModes method returns the number of modes.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::IsModeEnabled

The IsModeEnabled method queries whether a specified display mode is enabled.

Syntax

HRESULT IsModeEnabled(
  long Mode
);

Parameters

Mode

[in] Index of the display mode to query.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Index out of range.
S_FALSE | The display mode is disabled.
S_OK | The display mode is enabled.

Remarks

The Full Screen Renderer supports a static set of display modes. By default, every mode is enabled. You can enable or disable a display mode by calling the IFullScreenVideoEx::SetEnabled. The IsEnabled method retrieves the current setting for the specified mode.

The video card on the user's system might not support every mode. The Full Screen Renderer will not use a mode that the video card does not support, even if that mode is enabled. To determine whether the card supports a particular mode, call the IFullScreenVideoEx::IsModeAvailable method. If a mode is disabled, the Full Screen Renderer will not use it, even if the card supports it.

Display modes are indexed from zero. The IFullScreenVideoEx::CountModes method returns the number of modes.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::KeepPixelAspectRatio

The KeepPixelAspectRatio method specifies whether to maintain the pixel aspect ratio. The Full Screen Renderer filter does not support this method; it always maintains the pixel aspect ratio.

Syntax

HRESULT GetAcceleratorTable(
    long KeepAspect
);

Parameters

KeepAspect

[in] Specifies whether to maintain the aspect ratio. The value must be OATRUE or OAFALSE.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetAcceleratorTable

The SetAcceleratorTable method specifies an accelerator table that will be used to translate keyboard messages. The Full Screen Renderer filter does not support this method.

Syntax

HRESULT SetAcceleratorTable(
    HWND hwnd,
    HACCEL hAccel
);

Parameters

hwnd

[in] Handle of the window that will receive the translated messages.

hAccel

[in] Handle to the accelerator table.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetCaption

The SetCaption method sets the caption associated with the full-screen window.

Syntax

HRESULT SetCaption(
  BSTR strCaption
);

Parameters

strCaption

[in] String containing the caption.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

The caption is visible when the window is minimized.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetClipFactor

The SetClipFactor method specifies the clip factor, which determines how much of the video the Full Screen Renderer is allowed to clip.

For example, suppose the display mode is 320 x 200 and the video is 352 x 288 pixels. Assuming the decoder cannot shrink the video, the display will clip about 25 percent of the image. The clip factor specifies the upper range that is permitted. The default value is 25%.

Syntax

HRESULT SetClipFactor(
  long ClipFactor
);

Parameters

ClipFactor

[in] Specifies the maximum allowable amount of the image to clip. The value is expressed as a percentage from 0 to 100.

Return Values

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetDefault

The SetDefault method saves the current settings.

Syntax

HRESULT SetDefault(void);

Return Values

Returns an HRESULT value.

Remarks

Normally, the properties set through this interface apply only to the current instance of the Full Screen Renderer. Calling this method saves the current values as the global default. This method persists the following information:

  • The clip factor.
  • The enabled flag for each display mode.

It does not persist the caption or the hide-when-deactivated flag.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface
  • IFullScreenVideoEx::HideOnDeactivate
  • IFullScreenVideoEx::SetClipFactor
  • IFullScreenVideoEx::SetCaption
  • IFullScreenVideoEx::SetEnabled


IFullScreenVideoEx::SetEnabled

The SetEnabled method enables or disables a specified display mode.

Syntax

HRESULT SetEnabled(
  long Mode,
  long bEnabled
);

Parameters

Mode

[in] Index of the display mode to enable or disable.

bEnabled

[out] Specifies one of the following Boolean values:

Value | Description
OATRUE | Enable the specified display mode.
OAFALSE | Disable the specified display mode.

Return Values

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

The Full Screen Renderer supports a static set of display modes. By default, every mode is enabled. You can use this method to enable or disable a particular display mode. The video card on the user's system might not support every mode. The Full Screen Renderer will not use a mode that the video card does not support, even if that mode is enabled. To determine whether the card supports a particular mode, call the IFullScreenVideoEx::IsModeAvailable method. If a mode is disabled, the Full Screen Renderer will not use it, even if the card supports it.

Display modes are indexed from zero. The IFullScreenVideoEx::CountModes method returns the number of modes. To retrieve the width, height, and bit depth of a particular display mode, call the IFullScreenVideoEx::GetModeInfo method.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetMessageDrain

The SetMessageDrain method specifies a window to receive mouse and keyboard messages from the video window.

Syntax

HRESULT SetMessageDrain(
  HWND hwnd
);

Parameters

hwnd

[in] Specifies a handle to the message-drain window.

Return Values

Returns an HRESULT value.

Remarks

This method is equivalent to the IVideoWindow::put_MessageDrain method.

The Full Screen video renderer posts all mouse and keyboard messages to the window designated as a message drain. The exact list of messages that are posted is the same as the list given in put_MessageDrain.

Applications do not need to use this method. Instead, call the Filter Graph Manager's put_MessageDrain method before switching to full-screen mode. The Filter Graph Manager automatically sets the same message drain on the renderer that it selects for full-screen mode.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IFullScreenVideoEx::SetMonitor

The SetMonitor method specifies which monitor to use. The Full Screen Renderer only supports the primary monitor, however, so this method is not useful in the current implementation.

Syntax

HRESULT SetMonitor(
  long Monitor
);

Parameters

Monitor

[in] Specifies the index of the monitor to use. Must be zero in the current implementation.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IFullScreenVideoEx Interface


IGetCapabilitiesKey Interface

The IGetCapabilitiesKey interface enables an application to retrieve the capabilities of a software or hardware encoder from the registry, without creating an instance of the encoder filter. The moniker for the encoder filter exposes this interface. For more information, see Encoder API.

In addition to the methods inherited from IUnknown, the IGetCapabilitiesKey interface exposes the following method.

Method | Description
GetCapabilitiesKey | Returns a registry key that contains the capabilities information for the encoder.


IGetCapabilitiesKey::GetCapabilitiesKey

The GetCapabilitiesKey method returns a registry key that contains capability information for the encoder.

Syntax

HRESULT GetCapabilitiesKey(
    HKEY *pKey
);

Parameters

pKey

[out] Pointer to a variable that receives a handle to the registry key. Call RegEnumValue to enumerate the values for the returned key.

Return Values

Returns an HRESULT value.

See Also

  • Encoder API
  • Error and Success Codes
  • IGetCapabilitiesKey Interface


IGraphBuilder Interface

This interface provides methods that enable an application to build a filter graph. The Filter Graph Manager implements this interface.

IGraphBuilder inherits from the IFilterGraph interface. IFilterGraph provides basic operations, such as adding a filter to the graph or connecting two pins. IGraphBuilder adds further methods that construct graphs from partial information. For example, the IGraphBuilder::RenderFile method builds a graph for file playback, given the name of the file. The IGraphBuilder::Render method renders data from an output pin by connecting new filters to the pin.

Using these methods, an application does not need to specify every filter and pin connection in the graph. Instead, the Filter Graph Manager selects filters that are registered on the user's system, adds them to the graph, and connects them. For more information, see Intelligent Connect.

In addition to the methods inherited from IFilterGraph, the IGraphBuilder interface exposes the following methods.

Method | Description
Connect | Connects two pins. If they will not connect directly, this method connects them with intervening transforms.
Render | Adds a chain of filters to a specified output pin to render it.
RenderFile | Builds a filter graph that renders the specified file.
AddSourceFilter | Adds a source filter to the filter graph for a specific file.
SetLogFile | Sets the file for logging actions taken when attempting to perform an operation.
Abort | Requests that the graph builder return as soon as possible from its current task.
ShouldOperationContinue | Queries whether the current operation should continue.


IGraphBuilder::Abort

The Abort method requests the Filter Graph Manager to halt its current task as quickly as possible.

The current task may or may not fail to complete. Possibly the fastest option for the Filter Graph Manager is to complete the task.

Syntax

HRESULT Abort(void);

Return Value

Returns S_OK.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::AddSourceFilter

The AddSourceFilter method adds a source filter for a specified file to the filter graph.

Syntax

HRESULT AddSourceFilter(
  LPCWSTR lpwstrFileName,
  LPCWSTR lpwstrFilterName,
  IBaseFilter **ppFilter
);

Parameters

lpwstrFileName

[in] Specifies the name of the file to load.

lpwstrFilterName

[in] Specifies a name for the source filter.

ppFilter

[out] Pointer to a variable that receives the IBaseFilter interface pointer of the source filter.

Return Value

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | Success.
E_NOINTERFACE | The source filter does not support the IFileSourceFilter interface.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_NOT_FOUND | File or object not found.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file was not recognized.

Remarks

This method searches for an installed filter that can read the specified file. If it finds one, the method adds it to the filter graph and returns a pointer to the filter's IBaseFilter interface. To determine the media type and compression scheme of the file, the Filter Graph Manager reads the first few bytes of the file, looking for specific patterns of bytes, as documented in the article Registering a Custom File Type.

The application is responsible for building the rest of the filter graph. To do so, call IBaseFilter::EnumPins to enumerate the output pins on the source filter. Then use either the IGraphBuilder::Connect method or the IGraphBuilder::Render method.

If the method succeeds, the IBaseFilter interface has an outstanding reference count. The caller must release the interface.

To render a file for default playback, use the IGraphBuilder::RenderFile method.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::Connect

The Connect method connects the two pins, using intermediates if necessary.

Syntax

HRESULT Connect(
  IPin *ppinOut,
  IPin *ppinIn
);

Parameters

ppinOut

[in] Pointer to the IPin interface on the output pin.

ppinIn

[in] Pointer to the IPin interface on the input pin.

Return Value

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_PARTIAL_RENDER | Partial success; some of the streams from this pin use an unsupported format.
E_ABORT | Operation aborted.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_NOT_IN_GRAPH | At least one of the filters is not in the filter graph.

Remarks

This method connects two pins directly or indirectly, adding intermediate filters if necessary. The method starts by attempting a direct connection. If that fails, it tries to use any filters that are already in the filter graph and have unconnected input pins. (It enumerates these in an arbitrary order.) If that fails, it searches for filters in the registry, and tries them in order of merit. For more information, see Intelligent Connect.

During the connection process, the Filter Graph Manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::Render

The Render method builds a filter graph that renders the data from a specified output pin.

Syntax

HRESULT Render(
  IPin *ppinOut
);

Parameters

ppinOut

[in] Pointer to the IPin interface on an output pin.

Return Value

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Partial success; the audio was not rendered.
VFW_S_DUPLICATE_NAME | Success; the Filter Graph Manager modified a filter name to avoid duplication.
VFW_S_PARTIAL_RENDER | Partial success; some of the streams in this movie are in an unsupported format.
VFW_S_VIDEO_NOT_RENDERED | Partial success; the video was not rendered.
E_ABORT | Operation aborted.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream.
VFW_E_NO_ACCEPTABLE_TYPES | There is no common media type between these pins.
VFW_E_NOT_IN_GRAPH | The filter to which this pin belongs is not in the filter graph.

Remarks

This method renders the data from a specified output pin, adding new filters to the graph as needed. Filters are tried in the same order as for the IGraphBuilder::Connect method. For more information, see Intelligent Connect.

During the connection process, the Filter Graph Manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::RenderFile

The RenderFile method builds a filter graph that renders the specified file.

Syntax

HRESULT RenderFile(
  LPCWSTR lpwstrFile,
  LPCWSTR lpwstrPlayList
);

Parameters

lpwstrFile

[in] Specifies a wide-character string that contains the name of a media file.

lpwstrPlayList

[in] Reserved. Must be NULL.

Return Value

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Partial success; the audio was not rendered.
VFW_S_DUPLICATE_NAME | Success; the Filter Graph Manager modified the filter name to avoid duplication.
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format.
VFW_S_VIDEO_NOT_RENDERED | Partial success; some of the streams in this movie are in an unsupported format.
E_ABORT | Operation aborted.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream.
VFW_E_INVALID_FILE_FORMAT | The file format is invalid.
VFW_E_NOT_FOUND | An object or name was not found.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.
VFW_E_UNSUPPORTED_STREAM | Cannot play back the file: the format is not supported.

Remarks

If the lpwstrFile parameter specifies a media file, the method builds a filter graph for default playback. First it adds a source filter that can read the file, using the same process as the IGraphBuilder::AddSourceFilter method. Then it renders the output pins on the source filter, adding intermediate filters if necessary. It tries filters in the same order as the IGraphBuilder::Connect method.

During the connection process, the Filter Graph Manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

Note that the RenderFile method does not remove any filters from the graph. If you call RenderFile twice, the second call simply adds more filters to the graph. When you run the graph, both sources will play at the same time.

Example Code

The following example renders an AVI file for default playback:

hr = pGraph->RenderFile(L"C:\\Media\\Example.avi", 0);

The following example downloads an AVI file over HTTP, using the File Source (URL) filter:

hr = pGraph->RenderFile(L"http://example.microsoft.com/Example.avi", 0);

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::SetLogFile

The SetLogFile method sets the file for logging actions taken when attempting to perform an operation.

Syntax

HRESULT SetLogFile(
  DWORD_PTR hFile
);

Parameters

hFile

Handle to the log file.

Return Value

Returns S_OK.

Remarks

This method is for use in debugging; it is intended to help you determine the cause of any failure to automatically build a filter graph.

The hFile parameter must be an open file handle. Your application is responsible for opening the file and for closing it when you are done logging. Before closing the file handle, call SetLogFile with a NULL file handle. This will ensure that the component does not attempt to use the file handle after you have closed it.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphBuilder::ShouldOperationContinue

The ShouldOperationContinue method queries whether the current operation should continue. A filter that is performing some operation at the request of the graph can call this method to determine whether it should continue. Applications will not normally call this method.

Syntax

HRESULT ShouldOperationContinue(void);

Return Value

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The current operation should continue.
S_FALSE | The current operation should not continue.
E_UNEXPECTED | Unexpected error.

See Also

  • Error and Success Codes
  • IGraphBuilder Interface


IGraphConfig Interface

The Filter Graph Manager exposes IGraphConfig to support dynamic graph building. This interface enables applications and filters to reconfigure the filter graph while the graph is in a running state, and without losing data from the stream.

The most straightforward way to rebuild the graph dynamically is to call the IGraphConfig::Reconnect method. This method handles most of the details of dynamically rebuilding the graph. If a situation ever arises where you want to implement your own technique, IGraphConfig also provides the IGraphConfig::Reconfigure method. This method obtains a lock on the filter graph and then calls a callback function in your application, which reconfigures the graph. With this method, most of the work is shifted to your application. For more information, see Dynamic Graph Building.

To optimize the process of adding and removing filters, the filter graph maintains a cache of filters. During a call to the Reconnect method, you can specify that any filters removed from the graph get added to the cache. You can also add a filter to the cache directly, if you know it is likely to be needed, by calling IGraphConfig::AddFilterToCache. The IGraphBuilder::Render, IGraphBuilder::RenderFile, and IGraphBuilder::Connect methods automatically try to use filters in the cache before using other filters. Also, in the Reconnect method you can specify that only cached filters will be used for the reconnection. Note that filters held in the cache are not actually part of the graph. They are disconnected from any pins and are kept in a stopped state.

In addition to the methods inherited from IUnknown, the IGraphConfig interface exposes the following methods.

Method | Description
Reconnect | Performs a dynamic reconnection between two pins.
Reconfigure | Locks the filter graph and calls a callback function in the application or filter to perform a dynamic reconfiguration.
AddFilterToCache | Adds a filter to the filter cache.
RemoveFilterFromCache | Removes a filter from the filter cache.
EnumCacheFilter | Enumerates the filters in the filter cache.
GetStartTime | Retrieves the reference time used when the filter graph was last put into a running state.
PushThroughData | Pushes data through the filter graph to the specified pin.
SetFilterFlags | Sets a filter's configuration information.
GetFilterFlags | Retrieves a filter's configuration information.
RemoveFilterEx | Removes a filter from the filter graph.


IGraphConfig::AddFilterToCache

The AddFilterToCache method adds a filter to the filter cache.

Syntax

HRESULT AddFilterToCache(
  IBaseFilter *pFilter
);

Parameters

pFilter

[in] Pointer to the IBaseFilter interface of the filter.

Return Value

Returns one of the following HRESULT values.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
S_FALSE | Filter is already in the cache.
S_OK | Filter was added to the cache.

Remarks

You must disconnect all of the filter's pins before calling this method, or the method will fail. If the filter is in the filter graph, this method will remove it. This method will also put the filter into a stopped state, if it is not already.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::EnumCacheFilter

The EnumCacheFilter method enumerates the filters in the filter cache.

Syntax

HRESULT EnumCacheFilter(
  IEnumFilters **pEnum
);

Parameters

pEnum

[out] Address of a pointer to the IEnumFilters interface on the filter enumerator.

Return Value

Returns one of the following HRESULT values.

Value | Description
E_OUTOFMEMORY | Failed to allocate necessary memory.
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::GetFilterFlags

The GetFilterFlags method retrieves a filter's configuration information.

Syntax

HRESULT GetFilterFlags(
  IBaseFilter *pFilter,
  DWORD *pdwFlags
);

Parameters

pFilter

[in] Pointer to a filter in the filter graph.

pdwFlags

[out] Pointer to a variable of type DWORD that receives the current configuration flags.

Return Value

Returns one of the following HRESULT values.

Value | Description
E_POINTER | Null pointer argument.
S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in the graph.

See Also

  • Error and Success Codes
  • IGraphConfig Interface
  • IGraphConfig::SetFilterFlags


IGraphConfig::GetStartTime

The GetStartTime method retrieves the reference time that was used when the filter graph was last put into a running state.

Syntax

HRESULT GetStartTime(
  REFERENCE_TIME *prtStart
);

Parameters

prtStart

[out] Pointer to a variable that receives the start time.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
VFW_E_WRONG_STATE | Filter graph is not in a running state.

Remarks

The filter graph must currently be in a running state or this method will fail.


IGraphConfig::PushThroughData

The PushThroughData method pushes data through the filter graph to the specified pin.

Syntax

HRESULT PushThroughData(
  IPin *pOutputPin,
  IPinConnection *pConnection,
  HANDLE hEventAbort
);

Parameters

pOutputPin

[in] Pointer to an output pin in the filter graph.

pConnection

[in] Pointer to an input pin in the filter graph, or NULL.

hEventAbort

[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.

Return Value

Returns S_OK if successful. Otherwise, returns an error code that may be one of the following values, or others not listed.

Value | Description
E_OUTOFMEMORY | Failed to allocate necessary memory.
VFW_E_NOT_FOUND | Could not find a candidate input pin.
VFW_E_STATE_CHANGED | Filter state changed during the operation.

Remarks

This method pushes through any pending data, from a specified output pin down to a specified input pin. Optionally, you can leave the input pin unspecified and let the method search the filter graph for the best candidate. Do not call this method from the thread that is pushing data.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by the filter. The filter should signal the event if it receives a call to its Stop method.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::Reconfigure

The Reconfigure method locks the filter graph and calls a callback function in the application or filter to perform a dynamic reconfiguration.

Syntax

HRESULT Reconfigure(
  IGraphConfigCallback *pCallback,
  PVOID pvContext,
  DWORD dwFlags,
  HANDLE hAbortEvent
);

Parameters

pCallback

[in] Pointer to the IGraphConfigCallback callback interface on the application or filter.

pvContext

[in] Pointer to a variable of type PVOID that is passed to the callback routine.

dwFlags

[in] Application-defined flags that are passed to the callback routine.

hAbortEvent

[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.

Return Value

Returns S_OK if successful, or an error code otherwise. Possible errors include VFW_E_WRONG_STATE, if the method could not obtain a lock on the filter graph; whatever HRESULT was returned by the callback routine; or an error code indicating that the graph could not put the filters into a running state.

Remarks

This method is provided so that an application or filter can implement specialized dynamic graph building. In most cases, however, the IGraphConfig::Reconnect method is adequate, and should be preferred because it handles most of the implementation details.

Before calling this method, block any streams as needed and push the data through the graph (see IPinFlowControl::Block and IGraphConfig::PushThroughData). If the callback method succeeds, IGraphConfig::Reconfigure attempts to put all the filters into a running state. (The caller must then unblock the data flow.) Otherwise, it returns whatever error code the callback method returned.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by filter. The filter should signal the event if it receives a call to its Stop method.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::Reconnect

The Reconnect method performs a dynamic reconnection between two pins.

Syntax

HRESULT Reconnect(
  IPin *pOutputPin,
  IPin *pInputPin,
  const AM_MEDIA_TYPE *pmtFirstConnection,
  IBaseFilter *pUsingFilter,
  HANDLE hAbortEvent,
  DWORD dwFlags
);

Parameters

pOutputPin

[in] Pointer to an output pin. Can be NULL, in which case pInputPin must not be NULL.

pInputPin

[in] Pointer to an input pin. Can be NULL, in which case pOutputPin must not be NULL.

pmtFirstConnection

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the first pin connection made during the reconnection. If this parameter is NULL, the first connection can have any media type.

pUsingFilter

[in] Pointer to an optional filter to use in the reconnection. The filter must already be in the graph. Can be NULL.

hAbortEvent

[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.

dwFlags

[in] Combination of flags from the AM_GRAPH_CONFIG_RECONNECT_FLAGS enumeration, specifying how to perform the reconnection.

Return Value

Returns S_OK if successful. Otherwise, returns an error code that may be one of the following values, or others not listed.

E_INVALIDARG | Invalid argument. (For example, both pInputPin and pOutputPin are NULL.)
E_NOINTERFACE | Input pin does not support IPinConnection.
VFW_E_CANNOT_CONNECT | Unable to connect filter.
VFW_E_STATE_CHANGED | The state of the filter changed. Unable to complete the operation.

Remarks

If you specify only one pin, the method will search for the other pin. By default, however, the search fails if it reaches a filter that was added to the graph by means of the IFilterGraph::AddFilter method. To override this behavior, call IGraphConfig::SetFilterFlags and set the AM_FILTER_FLAGS_REMOVABLE flag on the filter.

The reconnection process involves several steps, most of them handled inside this method:

  1. First, before calling the method, make sure to block the flow of data along the path that is being reconfigured. Applications should call the IPinFlowControl::Block method to do this. If the caller is a filter, rather than an application, possibly the filter can control the data flow internally.
  2. The specified output and input pins define the starting and ending points for the reconnection. The input pin must support the IPinConnection interface. If you leave one of these pins unspecified (by passing a NULL parameter), the method searches the filter graph to find a candidate pin for reconnection. (To find an input pin, it searches downstream from the output pin; to find an output pin, it searches upstream from the input pin.)
  3. The method pushes any pending data through the filter graph (through an internal call to IGraphConfig::PushThroughData).
  4. If you have specified a filter to insert into the graph, the method connects the starting output pin to the filter's input pin, and connects the filter's output pin to the final input pin. If you do not specify a filter, the method simply connects the output pin to the input pin. In either case, the method inserts any transform filters required to complete the connections. (However, you can override this behavior by setting the appropriate flag; for more information see the description of the dwFlags parameter.)
  5. Finally, the method places the new filters into a running state. It is up to the caller to restart the data flow. Applications can do this by calling IPinFlowControl::Block with no flags.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by filter. The filter should signal the event if it receives a call to its Stop method.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::RemoveFilterEx

The RemoveFilterEx method removes a filter from the filter graph.

Syntax

HRESULT RemoveFilterEx(
  IBaseFilter *pFilter,
  DWORD Flags
);

Parameters

pFilter

[in] Pointer to the filter to remove from the graph.

Flags

[in] Combination of flags from the REM_FILTER_FLAGS enumerated type.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method extends the IFilterGraph::RemoveFilter method by accepting a flag that specifies the behavior of the method. This flag enables an application to remove a filter without disconnecting the pins automatically, which improves performance when moving groups of connected filters into a new graph.

By default, this method disconnects the filter before removing it from the graph. Use the REMFILTERF_LEAVECONNECTED flag to leave the filter connected.

RemoveFilterEx

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfig::RemoveFilterFromCache

The RemoveFilterFromCache method removes a filter from the filter cache.

Syntax

HRESULT RemoveFilterFromCache(
  IBaseFilter *pFilter
);

Parameters

pFilter

[in] Pointer to the filter to remove from the cache.

Return Value

Returns one of the following HRESULT values.

Value | Description
E_POINTER | Null pointer argument.
S_FALSE | Filter was not in the cache.
S_OK | Filter was successfully removed from the cache.


IGraphConfig::SetFilterFlags

The SetFilterFlags method sets a filter's configuration information.

Syntax

HRESULT SetFilterFlags(
  IBaseFilter *pFilter,
  DWORD dwFlags
);

Parameters

pFilter

[in] Pointer to a filter in the filter graph.

dwFlags

[in] Value specifying the new configuration flags. Must be one of the following values.

Value | Description
Zero | No flags set.
AM_FILTER_FLAGS_REMOVABLE | The filter is removable during a dynamic reconnection. For more information, see Remarks.

Return Value

Returns one of the following HRESULT values.

Value | Description
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in the graph.

Remarks

The AM_FILTER_FLAGS_REMOVABLE flag changes the behavior of the IGraphConfig::Reconnect method. The Reconnect method performs a dynamic reconnection between two pins. If the caller specifies one pin, but leaves the other pin unspecified, Reconnect searches upstream or downstream from the specified pin to find a suitable match. By default, however, the search fails if it reaches a filter that was added to the graph by means of the IFilterGraph::AddFilter method. To override this behavior, call SetFilterFlags and set the AM_FILTER_FLAGS_REMOVABLE flag on the filter.

See Also

  • Error and Success Codes
  • IGraphConfig Interface


IGraphConfigCallback Interface

The IGraphConfigCallback interface contains the callback method passed to IGraphConfig::Reconfigure. The caller (an application or filter) implements this interface. For more information, see IGraphConfig.

In addition to the methods inherited from IUnknown, the IGraphConfigCallback interface exposes the following method.

Method | Description
Reconfigure | Callback method passed to IGraphConfig::Reconfigure.


IGraphConfigCallback::Reconfigure

The Reconfigure method is a callback method passed to IGraphConfig::Reconfigure.

Syntax

HRESULT Reconfigure(
  PVOID pvContext,
  DWORD dwFlags
);

Parameters

pvContext

Value passed in the IGraphConfig::Reconfigure method's pvContext parameter.

dwFlags

Value passed in the IGraphConfig::Reconfigure method's dwFlags parameter.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

If your application or filter calls IGraphConfig::Reconfigure, you must implement this method and pass it as a callback. The IGraphConfig::Reconfigure method obtains a lock on the filter graph before calling your Reconfigure method. Your method then handles all the other details of dynamic graph building.

If this method succeeds, IGraphConfig::Reconfigure tries to put all the filters in the graph back into a running state. If the method fails, IGraphConfig::Reconfigure returns whatever error code this method returned.

This method allows for specialized graph rebuilding. For a more straightforward approach to dynamic graph building, see IGraphConfig::Reconnect.

See Also

  • Error and Success Codes
  • IGraphConfigCallback Interface


IGraphVersion Interface

The IGraphVersion interface is implemented on the Filter Graph Manager to provide a way for plug-in distributors and applications to know when the graph has changed. If the graph has changed, and the application or plug-in distributor has an interface on a particular filter or pin, it should requery the graph to see if its pointers are still valid, or if there are new ones it should use.

In addition to the methods inherited from IUnknown, the IGraphVersion interface exposes the following method.

Method | Description
QueryVersion | Retrieves the current graph version number.


IGraphVersion::QueryVersion

The QueryVersion method retrieves the current graph version number.

Syntax

HRESULT QueryVersion(
  LONG *pVersion
);

Parameters

pVersion

Pointer to the current graph version.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The version number is incremented every time there is a change in the set of filters in the graph or in their connections. If the version number has changed since the last enumeration, the graph must be re-enumerated.

See Also

  • Error and Success Codes
  • IGraphVersion Interface


IIPDVDec Interface

The IIPDVDec interface provides methods for setting and retrieving properties on the DV Video Decoder filter.

In addition to the methods inherited from IUnknown, the IIPDVDec interface exposes the following methods.

Method | Description
get_IPDisplay | Retrieves the decoding resolution.
put_IPDisplay | Sets the decoding resolution.


IIPDVDec::get_IPDisplay

The get_IPDisplay method retrieves the decoding resolution.

Syntax

HRESULT get_IPDisplay(
  int *displayPix
);

Parameters

displayPix

Pointer to a variable that receives a member of the DVDECODERRESOLUTION enumerated type, specifying the decoding resolution.

Return Value

Returns S_OK.

See Also

  • Error and Success Codes
  • IIPDVDec Interface


IIPDVDec::put_IPDisplay

The put_IPDisplay method sets the decoding resolution.

Syntax

HRESULT put_IPDisplay(
  int displayPix
);

Parameters

displayPix

[in] Member of the DVDECODERRESOLUTION enumerated type, specifying the decoding resolution. The meaning of this value depends on whether the current format is NTSC or PAL. The filter determines at run time which format applies, based on the media type.

Return Value

Returns S_OK if successful; otherwise, returns E_FAIL or another error code.

Remarks

This method will fail if the filter is already streaming media data.

See Also

  • Error and Success Codes
  • IIPDVDec Interface


IKsPin Interface

The IKsPin interface provides a method to retrieve the mediums supported by a pin on a kernel-mode filter. IKsPin has additional methods besides the one shown here, but they are not supported for DirectShow.

Requirements

Requires Ks.h and Ksproxy.h. Include Ks.h before Ksproxy.h.

In addition to the methods inherited from IUnknown, the IKsPin interface exposes the following method.

Method | Description
KsQueryMediums | Retrieves the mediums supported by a pin.


IKsPin::KsQueryMediums

The KsQueryMediums method retrieves the mediums supported by a pin.

Syntax

HRESULT KsQueryMediums(
  KSMULTIPLE_ITEM **ppmi
);

Parameters

ppmi

[out] Address of a pointer to a KSMULTIPLE_ITEM structure.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an HRESULT error code.

Remarks

This method returns a task-allocated KSMULTIPLE_ITEM structure, which is followed by zero or more REGPINMEDIUM structures. The Count member of the KSMULTIPLE_ITEM structure specifies the number of REGPINMEDIUM structures. Each REGPINMEDIUM structure defines a medium supported by the pin.

The caller must free the returned structures, using the CoTaskMemFree function.

Example Code

The following helper function attempts to match a pin against a specified medium.

HRESULT FindMatchingMedium(
    IPin *pPin,
    REGPINMEDIUM *pMedium,
    bool *pfMatch)
{
    IKsPin* pKsPin = NULL;
    KSMULTIPLE_ITEM *pmi;

    *pfMatch = false;
    HRESULT hr = pPin->QueryInterface(IID_IKsPin, (void **)&pKsPin);
    if (FAILED(hr))
        return hr;  // Pin does not support IKsPin.

    hr = pKsPin->KsQueryMediums(&pmi);
    pKsPin->Release();
    if (FAILED(hr))
        return hr;  // Pin does not support mediums.

    if (pmi->Count)
    {
        // Use pointer arithmetic to reference the first medium structure.
        REGPINMEDIUM *pTemp = (REGPINMEDIUM*)(pmi + 1);
        for (ULONG i = 0; i < pmi->Count; i++, pTemp++)
        {
            if (pMedium->clsMedium == pTemp->clsMedium)
            {
                *pfMatch = true;
                break;
            }
        }
    }
    CoTaskMemFree(pmi);
    return S_OK;
}

See Also

  • Error and Success Codes
  • IKsPin Interface
  • WDM Class Driver Filters


IKsPropertySet Interface

The IKsPropertySet interface was originally designed as an efficient way to set and retrieve device properties on WDM drivers, using KSProxy to translate the user-mode COM method calls into the kernel-mode property sets used by WDM streaming class drivers. This interface is now also used to pass information strictly between software components.

In some cases, software components must implement either this interface, or else the IKsControl interface (documented in the DirectShow DDK). For example, if you are writing a software MPEG-2 decoder for use with the Microsoft® DVD Navigator, you must implement one of these interfaces and also support the DVD-related property sets that the Navigator will send to the decoder. Pins may support one of these interfaces to allow other pins or filters to set or retrieve their properties.

Note Another interface by this name exists in the dsound.h header file. The two interfaces are not compatible. The IKsControl interface, documented in the DirectShow DDK, is now the recommended interface for passing property sets between WDM drivers and user mode components.

Methods in Vtable Order

In addition to the methods inherited from IUnknown, the interface exposes the following methods.

Method | Description
Set | Sets a property identified by a property set GUID and a property ID.
Get | Retrieves a property identified by a property set GUID and a property ID.
QuerySupported | Determines whether an object supports a specified property set.


IKsPropertySet::Get

The Get method retrieves a property identified by a property set GUID and a property ID.

Syntax

HRESULT Get(
  REFGUID guidPropSet,
  DWORD dwPropID,
  LPVOID pInstanceData,
  DWORD cbInstanceData,
  LPVOID pPropData,
  DWORD cbPropData,
  DWORD *pcbReturned
);

Parameters

guidPropSet

[in] Specifies the GUID of the property set .

dwPropID

[in] Specifies the identifier of the property within the property set.

pInstanceData

[in] Pointer to an array of bytes that contains instance data for the property.

cbInstanceData

[in] Specifies the size of the array given in pInstanceData.

pPropData

[out] Pointer to an array of bytes that receives the property data.

cbPropData

[in] Specifies the size of the array given in pPropData.

pcbReturned

[out] Pointer to a variable that receives the number of bytes the method returned in the pPropData array.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_PROP_SET_UNSUPPORTED | The property set is not supported.
E_PROP_ID_UNSUPPORTED | The property ID is not supported for the specified property set.

Remarks

Note Another interface by this name exists in the dsound.h header file. The two interfaces are not compatible. The IKsControl interface, documented in the DirectShow DDK, is now the recommended interface for passing property sets between WDM drivers and user mode components.

To retrieve a property, allocate a buffer which this method will then fill in. To determine the necessary buffer size, specify NULL for pPropData and zero (0) for cbPropData. This method returns the necessary buffer size in pcbReturned.

Example Code

The following example queries a pin for its pin category, by retrieving the AMPROPERTY_PIN_CATEGORY property. (See Pin Property Set.)

IKsPropertySet *pKs;
GUID guid;
DWORD cbBytes;
/* Query the pin for IKsProperty Set (not shown.) */
pKs->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0, &guid,
    sizeof(GUID), &cbBytes);
pKs->Release();

See Also

  • Error and Success Codes
  • IKsPropertySet Interface


IKsPropertySet::QuerySupported

The QuerySupported method determines whether an object supports a specified property set.

Syntax

HRESULT QuerySupported(
  REFGUID guidPropSet,
  DWORD dwPropID,
  DWORD *pTypeSupport
);

Parameters

guidPropSet

[in] Property set GUID.

dwPropID

[in] Identifier of the property within the property set.

pTypeSupport

[out] Pointer to a value in which to store flags indicating the support provided by the driver. Supported flags include the following:

Value | Description
KSPROPERTY_SUPPORT_GET | You can retrieve the property by calling the IKsPropertySet::Get method.
KSPROPERTY_SUPPORT_SET | You can change the property by calling IKsPropertySet::Set.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | The specified property set and property ID combination is supported.
E_NOTIMPL | Property set is not supported.
E_PROP_ID_UNSUPPORTED | Property ID is not supported for the specified property set.
E_PROP_SET_UNSUPPORTED | Property set is not supported.

Remarks

Note Another interface by this name exists in the dsound.h header file. The two interfaces are not compatible. The IKsControl interface, documented in the DirectShow DDK, is now the recommended interface for passing property sets between WDM drivers and user mode components.

See Also

  • Error and Success Codes
  • IKsPropertySet Interface


IKsPropertySet::Set

The Set method sets a property identified by a property set GUID and a property ID.

Syntax

HRESULT Set(
  REFGUID guidPropSet,
  DWORD dwPropID,
  LPVOID pInstanceData,
  DWORD cbInstanceData,
  LPVOID pPropData,
  DWORD cbPropData
);

Parameters

guidPropSet

[in] Property set GUID.

dwPropID

[in] Identifier of the property within the property set.

pInstanceData

[out, size_is(cbInstanceData)] Pointer to instance data for the property.

cbInstanceData

[in] Number of bytes in the buffer to which pInstanceData points.

pPropData

[out, size_is(cbPropData)] Pointer to the retrieved buffer, which contains the value of the property.

cbPropData

[in] Number of bytes in the buffer to which pPropData points.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_PROP_SET_UNSUPPORTED | The property set is not supported.
E_PROP_ID_UNSUPPORTED | The property ID is not supported for the specified property set.

Remarks

Note Another interface by this name exists in the dsound.h header file. The two interfaces are not compatible. The IKsControl interface, documented in the DirectShow DDK, is now the recommended interface for passing property sets between WDM drivers and user mode components.

See Also

  • Error and Success Codes
  • IKsPropertySet Interface


IMediaControl Interface

The IMediaControl interface provides methods for controlling the flow of data through the filter graph. It includes methods for running, pausing, and stopping the graph. The Filter Graph Manager implements this interface. For more information on filter graph states, see Data Flow in the Filter Graph.

IMediaControl also provides some Automation-compatible methods for building graphs. These are intended for applications written in Microsoft® Visual Basic® and are documented in the section Using DirectShow with Visual Basic.

In addition to the methods inherited from IDispatch, the IMediaControl interface exposes the following methods.

Method | Description
Run | Runs all the filters in the filter graph.
Pause | Pauses all filters in the filter graph.
Stop | Stops all the filters in the filter graph.
StopWhenReady | Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.
GetState | Retrieves the state of the filter graph.
RenderFile | Intended for Visual Basic; not documented here.
AddSourceFilter | Intended for Visual Basic; not documented here.
get_FilterCollection | Intended for Visual Basic; not documented here.
get_RegFilterCollection | Intended for Visual Basic; not documented here.


IMediaControl::AddSourceFilter

The AddSourceFilter method adds a source filter to the filter graph.

This method is intended for use by Visual Basic applications. It is documented for Visual Basic as the FilgraphManager.AddSourceFilter method. C++ applications should use the IGraphBuilder::AddSourceFilter method instead.

Syntax

HRESULT AddSourceFilter(
  BSTR strFilename,
  IDispatch **ppUnk
);

See Also

  • IMediaControl Interface


IMediaControl::get_FilterCollection

The get_FilterCollection method retrieves a collection of the filters in the filter graph.

This method is intended for use by Visual Basic applications. It is documented for Visual Basic as the FilgraphManager.FilterCollection property. C++ applications should use the IFilterGraph::EnumFilters method instead.

Syntax

HRESULT get_FilterCollection(
  IDispatch **ppUnk
);

See Also

  • IMediaControl Interface


IMediaControl::get_RegFilterCollection

The get_RegFilterCollection method retrieves a collection of all the filters listed in the registry.

This method is intended for use by Visual Basic applications. It is documented for Visual Basic as the FilgraphManager.RegFilterCollection property. C++ applications should use the IFilterMapper2::EnumMatchingFilters method instead.

Syntax

HRESULT get_RegFilterCollection(
  IDispatch **ppUnk
);

See Also

  • IMediaControl Interface


IMediaControl::GetState

The GetState method retrieves the state of the filter graph—paused, running, or stopped.

State transitions are not necessarily synchronous. Therefore, when you call this method, the filter graph might be in transition to a new state. In that case, the method blocks until the transition completes or until the specified time-out elapses.

Syntax

HRESULT GetState(
  LONG msTimeout,
  OAFilterState *pfs
);

Parameters

msTimeout

[in] Duration of the time-out, in milliseconds, or INFINITE to specify an infinite time-out.

pfs

[out] Pointer to a variable that receives a member of the FILTER_STATE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_S_STATE_INTERMEDIATE | The filter graph is still in transition to the indicated state.
VFW_S_CANT_CUE | The filter graph is paused, but cannot cue data.
E_FAIL | Failure.

Remarks

Applications can use this method to determine whether playback has started after a call to IMediaControl::Run. Generally, applications should have their own mechanism for tracking which state they have put the filter graph into. Applications typically use the current state to determine which user interface controls are enabled or disabled. For example, once the graph goes into the running state, the application might disable a "Play" button and enable "Stop" and "Pause" buttons.

If the filter graph is in a transition to a new state, the returned state is the new state, not the previous state.

This method returns an error if there is a call on another thread to change the state while this method is blocked.

Avoid specifying a time-out of INFINITE, because threads cannot process messages while waiting in GetState. If you call GetState from the thread that processes Windows messages, specify small wait times on the call in order to remain responsive to user input. This is especially important when the source is streaming over a network or from the Internet because state transitions in these environments can take significantly more time to complete.

For more information about filter graph states, see Data Flow in the Filter Graph.

See Also

  • Error and Success Codes
  • IMediaControl Interface


IMediaControl::Pause

The Pause method pauses all the filters in the filter graph.

Syntax

HRESULT Pause(void);

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The graph paused successfully, but some filters have not completed the state transition.
S_OK | All filters in the graph completed the transition to a paused state.

Remarks

Pausing the filter graph cues the graph for immediate rendering when the graph is next run. While the graph is paused, filters process data but do not render it. Data is pushed through the graph and processed by transform filters as far as buffering permits, but renderer filters do not render the data. However, video renderers display a static poster frame of the first sample.

If the method returns S_FALSE, call the IMediaControl::GetState method to wait for the state transition to complete, or to check if the transition has completed. When you call Pause to display the first frame of a video file, always follow it immediately with a call to GetState to ensure that the state transition has completed. Failure to do this can result in the video rectangle being painted black.

If the method fails, it stops the graph before returning.

See Also

  • Error and Success Codes
  • IMediaControl Interface
  • IMediaControl::StopWhenReady


IMediaControl::RenderFile

The RenderFile method builds a filter graph that renders the specified file.

This method is intended for use by Visual Basic applications. It is documented for Visual Basic as the FilgraphManager.RenderFile method. C++ applications should use the IGraphBuilder::RenderFile method instead.

Syntax

HRESULT RenderFile(
 BSTR strFilename
);

See Also

  • IMediaControl Interface


IMediaControl::Run

The Run method runs all the filters in the filter graph. While the graph is running, data moves through the graph and is rendered.

Syntax

HRESULT Run(void);

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The graph is preparing to run, but some filters have not completed the transition to a running state.
S_OK | All filters in the graph completed the transition to a running state.

Remarks

If the filter graph is stopped, this method pauses the graph before running. If the graph is already running, the method returns S_OK but has no effect.

The graph runs until the application calls the IMediaControl::Pause or IMediaControl::Stop method. When playback reaches the end of the stream, the graph continues to run, but the filters do not stream any more data. At that point, the application can pause or stop the graph. For information about the end-of-stream event, see IMediaControl::Pause and EC_COMPLETE.

This method does not seek to the beginning of the stream. Therefore, if you run the graph, pause it, and then run it again, playback resumes from the paused position. If you run the graph after it has reached the end of the stream, nothing is rendered. To seek the graph, use the IMediaSeeking interface.

If the return value is S_FALSE, you can wait for the transition to complete by calling the IMediaControl::GetState method. If the method fails, some filters might be in a running state. In a multistream graph, entire streams might be playing successfully. The application must determine whether to stop the graph.

See Also

  • Error and Success Codes
  • IMediaControl Interface


IMediaControl::Stop

The Stop method stops all the filters in the graph.

Syntax

HRESULT Stop(void);

Return Values

Returns S_OK if successful, or an HRESULT value that indicates the cause of the error.

Remarks

If the graph is running, this method pauses the graph before stopping it. While paused, video renderers can copy the current frame to display as a poster frame.

This method does not seek to the beginning of the stream. If you call this method and then call the IMediaControl::Run method, playback resumes from the stopped position. To seek, use the IMediaSeeking interface.

The Filter Graph Manager pauses all the filters in the graph, and then calls the IMediaFilter::Stop method on all filters, without waiting for the pause operations to complete. Therefore, some filters might have their Stop method called before they complete their pause operation. If you develop a custom rendering filter, you might need to handle this case by pausing the filter if it receives a stop command while in a running state. However, most filters do not need to take any special action in this regard.

See Also

  • StopWhenReady
  • Error and Success Codes
  • IMediaControl Interface


IMediaControl::StopWhenReady

The StopWhenReady method pauses the filter graph, allowing filters to queue data, and then stops the filter graph.

Syntax

HRESULT StopWhenReady(void);

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
S_FALSE | The graph was still transitioning to the paused state when the method returned.

Remarks

This method is useful if you want to seek the filter graph while the graph is stopped. As long as the filter graph is stopped, changes in the current position do not repaint the video window with a new frame. Therefore, calling IMediaSeeking::SetPositions does not update the video window. To update the window after the seek operation, call StopWhenReady. This method transitions the graph to a paused state, waits for the pause operation to complete, and then transitions the graph back to stopped. The pause operation queues data in the graph, so that the video renderer receives and displays the new frame.

This method is asynchronous. It waits on a separate thread for the pause to complete. The calling thread does not block, which enables the application to respond to user input. When the method returns, the logical state of the graph is stopped, even before the pause operation completes. If you call the IMediaControl::GetState method at this point, it returns State_Stopped.

If the application issues another state-change command (such as pause, run, or seek) before the pause operation completes, the new command cancels the pending stop command. The pause operation completes, but the graph does not stop.

See Also

  • Error and Success Codes
  • IMediaControl Interface


IMediaEvent Interface

The IMediaEvent interface contains methods for retrieving event notifications and for overriding the Filter Graph Manager's default handling of events. The IMediaEventEx interface inherits this interface and extends it.

The Filter Graph Manager implements this interface. Applications can use it to respond to events that occur in the filter graph, such as the end of a stream or a rendering error. Filters post events to the filter graph using the IMediaEventSink interface.

For more information about event notification, see Event Notification in DirectShow. For a list of system-defined event notifications, see Event Notification Codes.

In addition to the methods inherited from IDispatch, the IMediaEvent interface exposes the following methods.

Method | Description
CancelDefaultHandling | Cancels the Filter Graph Manager's default handling for a specified event.
FreeEventParams | Frees resources associated with the parameters of an event.
GetEvent | Retrieves the next event notification from the event queue.
GetEventHandle | Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.
RestoreDefaultHandling | Restores the Filter Graph Manager's default handling for a specified event.
WaitForCompletion | Waits for the filter graph to render all available data.


IMediaEvent::CancelDefaultHandling

The CancelDefaultHandling method cancels the Filter Graph Manager's default handling for a specified event. The event notification is passed to the application.

Syntax

HRESULT CancelDefaultHandling(
  long lEvCode
);

Parameters

lEvCode

Event code for which to cancel default handling.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_INVALIDARG | No default handling for this event.

Remarks

To restore the default handling for an event, call the IMediaEvent::RestoreDefaultHandling method with the event code.

See Also

  • Error and Success Codes
  • IMediaEvent Interface


IMediaEvent::FreeEventParams

The FreeEventParams method frees resources associated with the parameters of an event.

Syntax

HRESULT FreeEventParams(
  long lEventCode,
  long lParam1,
  long lParam2
);

Parameters

lEventCode

[in] Event code.

lParam1

[in] First event parameter.

lParam2

[in] Second event parameter.

Return Value

Returns S_OK.

Remarks

After you call the IMediaEvent::GetEvent method to retrieve an event notification, you must call FreeEventParams. This method frees any resources that were allocated for the event parameters. Pass in the same variables used for the GetEvent call.

Example Code

hr = pEvent->GetEvent(&evCode, &param1, &param2, 0);
// Handle the event (not shown).
hr = pEvent->FreeEventParams(evCode, param1, param2);

See Also

  • Error and Success Codes
  • IMediaEvent Interface


IMediaEvent::GetEvent

The GetEvent method retrieves the next event notification from the event queue.

Syntax

HRESULT GetEvent(
  long *lEventCode,
  long *lParam1,
  long *lParam2,
  long msTimeout
);

Parameters

lEventCode

[out] Pointer to a variable that receives the event code.

lParam1

[out] Pointer to a variable that receives the first event parameter.

lParam2

[out] Pointer to a variable that receives the second event parameter.

msTimeout

[in] Time-out interval, in milliseconds. Use INFINITE to block until there is an event.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_ABORT | Timeout expired.

Remarks

If no event is on the queue, this method waits up to msTimeout milliseconds for an event to arrive. Avoid using a time-out interval of INFINITE, because threads cannot process any messages while waiting in GetEvent. If you call GetEvent from the same thread that processes Windows messages, specify only small wait times, in order to remain responsive to user input.

After calling GetEvent, call the IMediaEvent::FreeEventParams method to release any resources allocated for the event parameters.

For a list of notification codes and event parameter values, see Event Notification Codes.

Because this method removes the event from the filter graph event queue, there is no way for multiple clients to monitor events from the same graph.

See Also

  • Error and Success Codes
  • IMediaEvent Interface


IMediaEvent::GetEventHandle

The GetEventHandle method retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.

Syntax

HRESULT GetEventHandle(
  OAEVENT *hEvent
);

Parameters

hEvent

[out] Pointer to a variable that receives the event handle.

Return Value

Returns S_OK.

Remarks

The Filter Graph Manager keeps a manual-reset event that reflects the state of the event queue. If the queue contains event notifications, the manual-reset event is signaled. If the queue is empty, the IMediaEvent::GetEvent method resets the event.

An application can use this event to determine the state of the queue. First call GetEventHandle to obtain a handle to the event. Wait for the event to be signaled, using a Microsoft® Windows® function such as WaitForSingleObject. When the event is signaled, call the IMediaEvent::GetEvent method to retrieve the next event notification from the queue. The Filter Graph Manager keeps the event signaled until the queue is empty; then it resets the event.

Do not close the event handle returned by this method, because the event handle is used internally by the filter graph. Also, do not use the handle after you release the Filter Graph Manager, because the handle becomes invalid after the Filter Graph Manager is destroyed. (To avoid this error, it is a good idea to duplicate the handle by calling DuplicateHandle, and use the duplicate instead of the original handle. Close the duplicate handle when you are finished.)

For Automation compatibility, this method takes a pointer to an OAEVENT type. In C++, declare a variable of type HANDLE and cast it an OAEVENT pointer, as follows:

HANDLE hEvent;
GetEventHandle( (OAEVENT*) &hEvent );

Another way for applications to monitor the event queue is by calling the IMediaEventEx::SetNotifyWindow method.

See Also

  • Error and Success Codes
  • IMediaEvent Interface


IMediaEvent::RestoreDefaultHandling

The RestoreDefaultHandling method restores the Filter Graph Manager's default handling for a specified event.

Syntax

HRESULT RestoreDefaultHandling(
  long lEvCode
);

Parameters

lEvCode

[in] Event code for which to restore default handling.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | No default handling for this event.

Remarks

By default, the Filter Graph Manager handles some events (such as EC_REPAINT) without passing them to the application. If you call the IMediaEvent::CancelDefaultHandling method to override the default handling for an event, you can restore the default behavior by calling RestoreDefaultHandling with the same event code.

See Also

  • 0Error and Success Codes
  • IMediaEvent Interface


IMediaEvent::WaitForCompletion

The WaitForCompletion method waits for the filter graph to render all available data. The filter graph must be running or the method fails.

Syntax

HRESULT WaitForCompletion(
  long msTimeout,
  long *pEvCode
);

Parameters

msTimeout

[in] Time-out interval, in milliseconds. Pass zero to return immediately. Pass the value INFINITE to block indefinitely.

pEvCode

[out] Pointer to a variable that receives an event code. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ABORT | Time-out expired.
VFW_E_WRONG_STATE | The filter graph is not running.

Remarks

This method blocks until the time-out expires, or one of the following events occurs:

  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_USERABORT

During the wait, the method discards all other event notifications.

If the return value is S_OK, the pEvCode parameter receives the event code that ended the wait. When the method returns, the filter graph is still running. The application can pause or stop the graph, as appropriate.

See Also

  • Error and Success Codes
  • IMediaEvent Interface


IMediaEventEx Interface

The IMediaEventEx interface inherits the IMediaEvent interface, which contains methods for retrieving event notifications and for overriding the filter graph's default handling of events. IMediaEventEx adds methods that enable an application window to receive messages when events occur. Unlike IMediaEvent, this interface is not available through Automation, and therefore cannot be called directly from Microsoft® Visual Basic®.

The Filter Graph Manager implements this interface.

For more information about event notification, see Event Notification in DirectShow. For a list of system-defined event notifications, see Event Notification Codes.

In addition to the methods inherited from IMediaEvent, the IMediaEventEx interface exposes the following methods.

Method | Description
SetNotifyWindow | Registers a window to process event notifications.
SetNotifyFlags | Enables or disables event notifications.
GetNotifyFlags | Determines whether event notifications are enabled.


IMediaEventEx::GetNotifyFlags

The GetNotifyFlags method determines whether event notifications are enabled.

Syntax

HRESULT GetNotifyFlags(
  long *lplNoNotifyFlags
);

Parameters

lplNoNotifyFlags

[out] Pointer to a variable that receives one of the following values:

Value | Description
Zero | Event notifications are enabled.
AM_MEDIAEVENT_NONOTIFY | Event notifications are disabled.

Return Value

Returns S_OK if successful, or E_POINTER if the lplNoNotifyFlags parameter is NULL.

Remarks

By default, the Filter Graph Manager posts event notifications for the application. To disable event notification, call the IMediaEventEx::SetNotifyFlags method with the value AM_MEDIAEVENT_NONOTIFY.

If event notifications are disabled, the handle returned by the IMediaEvent::GetEventHandle method is signaled at the end of each stream—that is, whenever the Filter Graph Manager receives an EC_COMPLETE event.

See Also

  • Error and Success Codes
  • IMediaEventEx Interface


IMediaEventEx::SetNotifyFlags

The SetNotifyFlags method enables or disables event notifications.

Syntax

HRESULT SetNotifyFlags(
  long lNoNotifyFlags
);

Parameters

lNoNotifyFlags

[in] Value indicating whether to enable or disable event notifications. Must be one of the following values:

Value | Description
Zero | Enable event notifications.
AM_MEDIAEVENT_NONOTIFY | Disable event notifications.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the lNoNotifyFlags parameter is invalid.

Remarks

By default, the Filter Graph Manager posts event notifications for the application. If the lNoNotifyFlags parameter is AM_MEDIAEVENT_NONOTIFY, the Filter Graph Manager clears any pending event notifications from the queue, and does not post any new ones.

If event notifications are disabled, the handle returned by the IMediaEvent::GetEventHandle method is signaled at the end of each stream—that is, whenever the Filter Graph Manager receives an EC_COMPLETE event.

See Also

  • Error and Success Codes
  • IMediaEventEx Interface


IMediaEventEx::SetNotifyWindow

The SetNotifyWindow method registers a window to process event notifications.

Syntax

HRESULT SetNotifyWindow(
  OAHWND hwnd,
  long lMsg,
  long lInstanceData
);

Parameters

hwnd

[in] Handle to the window, or NULL to stop receiving event messages.

lMsg

[in] Window message to be passed as the notification.

lInstanceData

[in] Value to be passed as the lParam parameter for the lMsg message.

Return Value

Returns S_OK if successful or E_INVALIDARG if the hwnd parameter is not a valid handle to a window.

Remarks

This method designates a window that will process event notifications. Whenever the Filter Graph Manager puts an event in the event queue, it will also post a message to the designated window. The hwnd parameter specifies the window, and the lMsg parameter specifies the message. The application should define a private window message for this purpose. The message's lParam parameter is set to the value of lInstanceData, and the wParam parameter is set to zero.

When the window receives the message, it should call the IMediaEvent::GetEvent method to retrieve the event. Events are asynchronous, so the queue might contain several events (or none). Call GetEvent repeatedly, until it returns an error code.

See Also

  • Error and Success Codes
  • IMediaEventEx Interface


IMediaEventSink Interface

Notifies the Filter Graph Manager of events that occur within the filter graph. Filters use this interface to report events. The Filter Graph Manager exposes this interface.

Applications do not use IMediaEventSink. To retrieve events, applications use the IMediaEventEx interface.

In addition to the methods inherited from IUnknown, the IMediaEventSink interface exposes the following method.

Method | Description
Notify | Notifies the Filter Graph Manager of an event.


IMediaEventSink::Notify

The Notify method notifies the Filter Graph Manager of an event.

Syntax

HRESULT Notify(
  long EventCode,
  LONG_PTR EventParam1,
  LONG_PTR EventParam2
);

Parameters

EventCode

[in] Identifier of the event.

EventParam1

[in] First event parameter.

EventParam2

[in] Second event parameter.

Return Value

Returns an HRESULT value.

Remarks

The event is queued but not delivered to the application on this thread. For a list of notification codes and event parameter values, see Event Notification Codes.

See Also

  • Error and Success Codes
  • IMediaEventSink Interface


IMediaFilter Interface

The IMediaFilter interface controls the streaming state of a filter.

All DirectShow filters implement this interface. It provides methods for switching the filter between states (stopped, paused, and running); for retrieving the filter's current state; and for setting a reference clock. Applications should not call IMediaFilter methods on filters.

The Filter Graph Manager also exposes this interface. Applications can use the SetSyncSource method to set the graph reference clock, and GetSyncSource to retrieve the clock. Applications should not call the other methods on this interface. Instead, use the corresponding methods on the IMediaControl interface.

The IBaseFilter interface inherits from IMediaFilter.

In addition to the methods inherited from IPersist, the IMediaFilter interface exposes the following methods.

Method | Description
Stop | Stops the filter.
Pause | Pauses the filter.
Run | Runs the filter.
GetState | Retrieves the state of the filter (running, stopped, or paused).
SetSyncSource | Sets the reference clock for the filter or the filter graph.
GetSyncSource | Retrieves the current reference clock.


IMediaFilter::GetState

The GetState method retrieves the filters's state (running, stopped, or paused).

Syntax

HRESULT GetState(
  DWORD dwMilliSecsTimeout,
  FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout

[in] Time-out interval, in milliseconds. To block indefinitely, use the value INFINITE.

State

[out] Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_S_STATE_INTERMEDIATE | Intermediate state.
VFW_S_CANT_CUE | The filter is active, but cannot deliver data.

Remarks

State transitions can be asynchronous. If the filter is transitioning to a new state, and the method times out before the transition completes, the method returns VFW_S_STATE_INTERMEDIATE.

If a filter cannot deliver data for some reason, it returns VFW_S_CANT_CUE. Live capture filters return this value while paused, because they do not deliver data in the paused state.

For more information, see Data Flow in the Filter Graph.

See Also

  • Error and Success Codes
  • IMediaFilter Interface


IMediaFilter::GetSyncSource

The GetSyncSource method retrieves the current reference clock.

Syntax

HRESULT GetSyncSource(
  IReferenceClock **pClock
);

Parameters

pClock

[out] Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer argument

Remarks

This method returns the same reference clock as the last call to IMediaFilter::SetSyncSource. If there is no reference clock, pClock receives the value NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

You can also call this method on the Filter Graph Manager to determine the current reference clock.

See Also

  • Error and Success Codes
  • IMediaFilter Interface


IMediaFilter::Pause

The Pause method pauses the filter.

Syntax

HRESULT Pause(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is paused, it can receive, process, and deliver samples. However, a renderer filter will only accept one sample while paused. Therefore, when the filter graph is paused, samples move through the graph until the first sample reaches the renderer. At that point, streaming is paused until the IMediaFilter::Run method is called. Video renderers display the first sample as a still frame.

Live capture filters do not deliver any samples while paused, only while running.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE. Renderer filters do not complete the state transition until they receive one sample.

See Also

  • Error and Success Codes
  • IMediaFilter Interface


IMediaFilter::Run

The Run method runs the filter.

Syntax

HRESULT Run(
  REFERENCE_TIME tStart
);

Parameters

tStart

Reference time corresponding to stream time 0.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is running, it can receive, process, and deliver samples. Source filters generate new samples, and renderer filters render them.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE.

Stream time is calculated as the current reference time minus tStart. To calculate when a media sample should be rendered, the renderer compares the time stamp with the current stream time. Thus, a media sample with a time stamp of zero should be rendered at time tStart. For more information, see Time and Clocks in DirectShow.

When an application calls the IMediaControl::Run method, the Filter Graph Manager calls IMediaFilter::Run on each filter. It sets the value of tStart slightly in the future, to account for graph latency.

See Also

  • Error and Success Codes
  • IMediaFilter Interface


IMediaFilter::SetSyncSource

The SetSyncSource method sets the reference clock.

Syntax

HRESULT SetSyncSource(
  IReferenceClock *pClock
);

Parameters

pClock

[in] Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

All the filters in the filter graph share the same reference clock, in order to stay synchronized. Stream time is calculated from the reference clock. Renderer filters use the reference clock to schedule when they render samples. If there is no reference clock, a renderer filter renders every sample as soon as it arrives.

This method is implemented by all DirectShow filters, and also by the Filter Graph Manager.

Filter Implementation

When the graph runs, the Filter Graph manager calls this method on every filter in the graph, to notify them of the graph reference clock. Use this method to store the IReferenceClock pointer. Increment the reference count on the stored pointer. Before the filter is removed from the graph, the Filter Graph Manager calls SetSyncSource again with the value NULL. Release the stored pointer and set it to NULL.

The CBaseFilter class implements this method; see CBaseFilter::SetSyncSource.

Note that filters cannot use this method to select the graph clock. In filters, the only function of this method is to inform the filter of the clock that the graph is using. A filter can provide a reference clock by exposing the IReferenceClock interface. For more information, see Time and Clocks in DirectShow.

Application Use

An application can override the default clock by calling SetSyncSource on the Filter Graph Manager. Do not do this unless you have a particular reason to prefer another clock. You can also set the graph not to use any reference clock, by calling SetSyncSource with the value NULL. You might do this to process samples as quickly as possible. For more information, see Setting the Graph Clock.

Applications should never call this method on filters.

See Also

  • Error and Success Codes
  • IMediaFilter Interface
  • IFilterGraph::SetDefaultSyncSource


IMediaFilter::Stop

The Stop method stops the filter.

Syntax

HRESULT Stop(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is stopped, it does not process or deliver any samples, and it rejects samples from upstream filters.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE.

This method always sets the filter's state to State_Stopped, even if the method returns an error code.

See Also

  • Error and Success Codes
  • IMediaFilter Interface
  • FILTER_STATE Enumeration


IMediaPosition Interface

Contains methods for seeking to a position within a stream.

The IMediaSeeking interface improves on this interface. Applications written in C/C++ should use IMediaSeeking instead of IMediaPosition. However, IMediaSeeking is not compatible with Automation, so applications written in Microsoft® Visual Basic® must use IMediaPosition instead.

This interface is exposed by the Filter Graph Manager as well as by individual filters. Applications should obtain an IMediaPosition interface pointer from the Filter Graph Manager, not from a filter. The Filter Graph Manager distributes method calls to all of the renderer filters. The renderer filters propagate the calls upstream to the source filters. This sequence of events ensures that all streams remain synchronized.

If one of the distributed calls returns an error, the Filter Graph Manager returns the first error value it received. Some of the distributed calls may have succeeded in this case. However, the filter graph does not return E_NOTIMPL unless all the distributed calls return E_NOTIMPL. If at least one filter in the graph implements the method, the Filter Graph Manager does not return E_NOTIMPL.

Filter developers: Do not implement this method. Implement IMediaSeeking instead. If your filter supports IMediaSeeking, the Filter Graph Manager automatically handles calls to IMediaPosition.

In addition to the methods inherited from IDispatch, the IMediaPosition interface exposes the following methods.

Method | Description
get_Duration | Retrieves the duration of the stream.
put_CurrentPosition | Sets the current position, relative to the total duration of the stream.
get_CurrentPosition | Retrieves the current position, relative to the total duration of the stream.
get_StopTime | Retrieves the time at which the playback will stop, relative to the duration of the stream.
put_StopTime | Sets the time at which the playback will stop, relative to the duration of the stream.
get_PrerollTime | Retrieves the amount of data that will be queued before the start position.
put_PrerollTime | Sets the amount of data that will be queued before the start position.
put_Rate | Sets the playback rate.
get_Rate | Retrieves the playback rate.
CanSeekForward | Determines whether the filter graph can seek forward in the stream.
CanSeekBackward | Determines whether the filter graph can seek backward in the stream.


IMediaPosition::CanSeekBackward

The CanSeekBackward method determines whether the filter graph can seek backward in the stream.

Syntax

HRESULT CanSeekBackward(
  LONG *pCanSeekBackward
);

Parameters

pCanSeekBackward

[out] Pointer to a variable that receives the value OATRUE if the graph can seek backward, or OAFALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::CanSeekForward

The CanSeekForward method determines whether the filter graph can seek forward in the stream.

Syntax

HRESULT CanSeekForward(
  LONG *pCanSeekForward
);

Parameters

pCanSeekForward

[out] Pointer to a variable that receives the value OATRUE if the graph can seek forward, or OAFALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::get_CurrentPosition

The get_CurrentPosition method retrieves the current position, relative to the total duration of the stream.

Syntax

HRESULT get_CurrentPosition(
  REFTIME *pllTime
);

Parameters

pllTime

[out] Pointer to a variable that receives the current position, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method returns the current position that playback has reached. The value ignores the playback rate and start time. For example, if you set the rate to 2.0 and the start time to five seconds, running the graph for four seconds yields a current position of 9.0 seconds (5 + 4 x 2.0).

If the graph is paused or stopped, the current position is the point at which playback will resume.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::get_Duration

The get_Duration method retrieves the duration of the stream.

Syntax

HRESULT get_Duration(
  REFTIME *plength
);

Parameters

plength

[out] Pointer to a variable that receives the total stream length, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the duration of the stream at normal playback speed. Changing the playback rate does not affect the duration.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::get_PrerollTime

The get_PrerollTime method retrieves the amount of data that will be queued before the start position.

Syntax

HRESULT get_PrerollTime(
  REFTIME *pllTime
);

Parameters

pllTime

[out] Pointer to a variable that receives the preroll time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

If no filter in the graph implements this method, the Filter Graph Manager sets the value of *pllTime to zero and returns S_OK.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::get_Rate

The get_Rate method retrieves the playback rate.

Syntax

HRESULT get_Rate(
  double *pdRate
);

Parameters

pdRate

[out] Pointer to a variable that receives the playback rate.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed.


IMediaPosition::get_StopTime

The get_StopTime method retrieves the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT get_StopTime(
  REFTIME *pllTime
);

Parameters

pllTime

[out] Pointer to a variable that receives the stop time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The playback rate does not affect the value returned by this method.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::put_CurrentPosition

The put_CurrentPosition method sets the current position, relative to the total duration of the stream.

Syntax

HRESULT put_CurrentPosition(
  REFTIME llTime
);

Parameters

llTime

[in] New position, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | Graph was paused and is in transition back to a running state.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The position specified by the llTime parameter is relative to the total duration, ignoring playback rate. For example, if a source file is 10 seconds long, setting the position to 5.0 causes the graph to seek to the middle of the file, regardless of playback rate.

If the filter graph is running, the Filter Graph Manager pauses the graph, issues the seek command, and then runs the graph again. If the method returns while the graph is still transitioning to a running state, the return value is S_FALSE.

If a filter is paused when it receives a seek command, it must flush existing data before it introduces the data from the new position. See IPin::BeginFlush and IPin::EndFlush.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::put_PrerollTime

The put_PrerollTime method sets the amount of data that will be queued before the start position.

Syntax

HRESULT put_PrerollTime(
  REFTIME llTime
);

Parameters

llTime

[in] Preroll time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::put_Rate

The put_Rate method sets the playback rate.

Syntax

HRESULT put_Rate(
  double dRate
);

Parameters

dRate

[in] Playback rate. Must not be zero.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed. For audio streams, changing the rate also changes the pitch.

For more information, see the remarks in IMediaSeeking::SetRate.

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPosition::put_StopTime

The put_StopTime method sets the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT put_StopTime(
  REFTIME llTime
);

Parameters

llTime

[in] Stop time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The stop time ignores the start time and the playback rate. For example, if the start time is 2 seconds, the stop time is 12 seconds, and the playback rate is 2.0, playback will stop after 5 seconds (real time).

See Also

  • Error and Success Codes
  • IMediaPosition Interface


IMediaPropertyBag Interface

The IMediaPropertyBag interface is exposed by the Media Property Bag object. The Media Property Bag is a specialized version of the standard COM property bag, designed for setting and retrieving INFO and DISP chunks in Audio-Video Interleaved (AVI) files.

An INFO chunk contains meta-information about a file, such as author and copyright information. A DISP chunk contains data in Clipboard format. For more information, refer to the resource interchange file format (RIFF) specification.

The media property bag stores the chunks as name/value pairs, as follows:

  • INFO chunks: The name is a string with the form INFO/XXXX, where XXXX is the four-character code that defines the type of meta-information—for example, ICOP for copyright information and IART for author name. The value is any string.
  • DISP chunks: The name is a string with the form DISP/0000000000, where 0000000000 is the 10-character decimal equivalent of a standard Clipboard format—for example, 0000000008 for CF_DIB. The value is an array of bytes that contains the display data.

This interface inherits the IPropertyBag interface. Use this interface with the IPersistMediaPropertyBag interface to retrieve INFO and DISP chunks from an AVI file.

In addition to the methods inherited from IPropertyBag, the IMediaPropertyBag interface exposes the following method.

Method | Description
EnumProperty | Retrieves a property/value pair.


IMediaPropertyBag::EnumProperty

The EnumProperty method retrieves a property/value pair.

Syntax

HRESULT EnumProperty(
  ULONG iProperty,
  VARIANT *pvarPropertyName,
  VARIANT *pvarPropertyValue
);

Parameters

iProperty

[in] Index value of the pair.

pvarPropertyName

[in, out] Pointer to a VARIANT that receives the property's name.

pvarPropertyValue

[in, out] Pointer to a VARIANT that receives the property's value.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) | Index out of range.

Remarks

The name is always a string. Set the variant type of the pvarPropertyName parameter to VT_EMPTY or VT_BSTR before calling this method.

The value can be a string (for INFO chunks) or an array of bytes (for DISP chunks). Set the variant type of the pvarPropertyName parameter to VT_EMPTY, VT_BSTR, or (VT_ARRAY | VT_UI1).

See Also

  • Error and Success Codes
  • IMediaPropertyBag Interface


IMediaSample Interface

The IMediaSample interface sets and retrieves properties on media samples. A media sample is a COM object that contains a block of media data. Media samples support the use of shared memory buffers among filters.

Typically, applications do not call methods on this interface. Filters use this interface to set properties on samples, and deliver the samples to a downstream filter. The downstream filter uses the interface to retrieve the properties and read the data. The filter can modify the data in place, or it can copy the sample, modify the copy, and pass the copy downstream.

The IMediaSample2 interface inherits this interface.

In addition to the methods inherited from IUnknown, the IMediaSample interface exposes the following methods.

Method | Description
GetActualDataLength | Retrieves the length of the valid data in the buffer.
GetMediaTime | Retrieves the media times for this sample.
GetMediaType | Retrieves the media type, if the media type differs from the previous sample.
GetPointer | Retrieves a read/write pointer to this buffer's memory.
GetSize | Retrieves the size of the buffer.
GetTime | Retrieves the stream times at which this sample should begin and finish.
IsDiscontinuity | Determines if this sample represents a break in the data stream.
IsPreroll | Determines if this sample is a preroll sample.
IsSyncPoint | Determines if the beginning of this sample is a synchronization point.
SetActualDataLength | Sets the length of the valid data in the buffer.
SetDiscontinuity | Specifies whether this sample represents a break in the data stream.
SetMediaTime | Sets the media times for this sample.
SetMediaType | Sets the media type for the sample.
SetPreroll | Specifies whether this sample is a preroll sample.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
SetTime | Sets the stream time when this sample should begin and finish.


IMediaSample::GetActualDataLength

The GetActualDataLength method retrieves the length of the valid data in the buffer.

Syntax

LONG GetActualDataLength(void);

Return Value

Returns the length of the valid data, in bytes.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::GetMediaTime

The GetMediaTime method retrieves the media times for this sample.

Syntax

HRESULT GetMediaTime(
  LONGLONG *pTimeStart,
  LONGLONG *pTimeEnd
);

Parameters

pTimeStart

[out] Pointer to a variable that receives the media start time.

pTimeEnd

[out] Pointer to a variable that receives the media stop time.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | Media times are not set on this sample.

Remarks

For more information about media times, see Time and Clocks in DirectShow.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::GetMediaType

The GetMediaType method retrieves the media type, if the media type differs from the previous sample.

Syntax

HRESULT GetMediaType(
  AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType

Address of a variable that receives a pointer to an AM_MEDIA_TYPE structure. If the media type has not changed from the previous sample, *ppMediaType is set to NULL.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | The media type has not changed from the previous sample.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

Remarks

This method enables a filter to make limited changes to the media type, such as changing the palette. To make a significant change to the media type, the pins might need to reconnect and renegotiate the media type.

If the method returns S_OK, the caller must free the memory for the media type, including the format block. You can use the DeleteMediaType function in the DirectShow base class library.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::GetPointer

The GetPointer method retrieves a read/write pointer to this buffer's memory.

Syntax

HRESULT GetPointer(
  BYTE **ppBuffer
);

Parameters

ppBuffer

[out] Address of a pointer to the buffer.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.


IMediaSample::GetSize

The GetSize method retrieves the size of the buffer.

Syntax

long GetSize(void);

Return Value

Returns the size of the buffer, in bytes. The size does not include the prefix bytes, if any.

See Also

  • Error and Success Codes
  • IMediaSample Interface
  • ALLOCATOR_PROPERTIES


IMediaSample::GetTime

The GetTime method retrieves the stream times at which this sample should begin and finish.

Syntax

HRESULT GetTime(
  REFERENCE_TIME *pTimeStart,
  REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

[out] Pointer to a variable that receives the start time.

pTimeEnd

[out] Pointer to a variable that receives the stop time. If the sample has no stop time, the value is set to the start time plus one.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success. The sample has valid start and stop times.
VFW_S_NO_STOP_TIME | The sample has a valid start time, but no stop time.
VFW_E_SAMPLE_TIME_NOT_SET | The sample is not time-stamped.

Remarks

Both time values are relative to the stream time. For more information, see Time and Clocks in DirectShow.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::IsDiscontinuity

The IsDiscontinuity method determines if this sample represents a break in the data stream.

Syntax

HRESULT IsDiscontinuity(void);

Return Value

Returns S_OK if the sample is a break in the data stream. Otherwise, returns S_FALSE.

Remarks

A discontinuity occurs when a filter seeks to a different place in the stream, or when a filter drops samples for quality control.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::IsPreroll

The IsPreroll method determines if this sample is a preroll sample. A preroll sample should not be displayed.

Syntax

HRESULT IsPreroll(void);

Return Value

Returns S_OK if the sample is a preroll sample. Otherwise, returns S_FALSE.

Remarks

Preroll samples are processed but not displayed. They are located in the media stream before the displayable samples.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::IsSyncPoint

The IsSyncPoint method determines if the beginning of this sample is a synchronization point.

Syntax

HRESULT IsSyncPoint(void);

Return Value

Returns S_OK if the sample is a synchronization point. Otherwise, returns S_FALSE.

Remarks

A filter can begin a stream at any synchronization point. With some compression types, streaming can begin only at certain points in the stream; for example, on key frames. If the bTemporalCompression member of the AM_MEDIA_TYPE structure is FALSE, all samples are synchronization points.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::SetActualDataLength

The SetActualDataLength method sets the length of the valid data in the buffer.

Syntax

HRESULT SetActualDataLength(
  long lLen
);

Parameters

lLen

Length of the data in the media sample, in bytes.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_BUFFER_OVERFLOW. | Length specified in lLen is larger than the buffer size.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::SetDiscontinuity

The SetDiscontinuity method specifies whether this sample represents a break in the data stream.

Syntax

HRESULT SetDiscontinuity(
  BOOL bIsDiscontinuity
);

Parameters

bIsDiscontinuity

[in] Boolean value that specifies whether this sample is a discontinuity. If TRUE, the media sample is discontinuous with the previous sample.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

See Also

  • Error and Success Codes
  • IMediaSample Interface
  • IMediaSample::IsDiscontinuity


IMediaSample::SetMediaTime

The SetMediaTime method sets the media times for this sample.

Syntax

HRESULT SetMediaTime(
  LONGLONG *pTimeStart,
  LONGLONG *pTimeEnd
);

Parameters

pTimeStart

[in] Pointer to the beginning media time.

pTimeEnd

[in] Pointer to the ending media time.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

Remarks

To invalidate the media time, set pTimeStart and pTimeEnd to NULL. This will cause the IMediaSample::GetMediaTime method to return VFW_E_MEDIA_TIME_NOT_SET.

For more information about media times, see Time and Clocks in DirectShow.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::SetMediaType

The SetMediaType method sets the media type for the sample.

Syntax

HRESULT SetMediaType(
  AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

By default, every sample has the same media type as the previous sample. (The pin connection determines the original media type.) Call this method to make limited changes to the media type, such as changing the palette. To make a significant change to the media type, the pins might need to reconnect and renegotiate the media type.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample::SetPreroll

The SetPreroll method specifies whether this sample is a preroll sample.

Syntax

HRESULT SetPreroll(
  BOOL bIsPreroll
);

Parameters

bIsPreroll

Boolean value that specifies whether this is a preroll sample. If TRUE, this is a preroll sample.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

See Also

  • Error and Success Codes
  • IMediaSample Interface
  • IMediaSample::IsPreroll


IMediaSample::SetSyncPoint

The SetSyncPoint method specifies whether the beginning of this sample is a synchronization point.

Syntax

HRESULT SetSyncPoint(
  BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint

[in] Boolean value that specifies whether this is a synchronization point. If TRUE, this is a synchronization point.

Return Value

Returns S_OK or an HRESULT value indicating the cause of the error.

Remarks

The filter that first generates the data in the sample should set this flag to TRUE or FALSE, as appropriate. For uncompressed video and PCM audio, set every sample to TRUE. For compressed video, set key frames to TRUE and delta frames to FALSE.

This flag is purely informational. Other filters downstream might check this flag; for example, a filter might need to skip to the next key frame.

See Also

  • Error and Success Codes
  • IMediaSample Interface
  • IMediaSample::IsSyncPoint


IMediaSample::SetTime

The SetTime method sets the stream times when this sample should begin and finish.

Syntax

HRESULT SetTime(
  REFERENCE_TIME *pTimeStart,
  REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

[in] Pointer to a variable that contains the start time of the sample.

pTimeEnd

[in] Pointer to a variable that contains the stop time of the sample.

Return Value

Returns S_OK, or HRESULT value indicating the cause of the error.

Remarks

Both time values are relative to the stream time. For more information, see Time and Clocks in DirectShow.

To invalidate the stream times, set pTimeStart and pTimeEnd to NULL. This will cause the IMediaSample::GetTime method to return VFW_E_SAMPLE_TIME_NOT_SET.

For more information about stream times, see Time and Clocks in DirectShow.

See Also

  • Error and Success Codes
  • IMediaSample Interface


IMediaSample2 Interface

The IMediaSample2 interface sets and retrieves properties on media samples.

This interface inherits the IMediaSample interface. Whereas the IMediaSample interface requires separate method calls for each sample property, the IMediaSample2 interface has methods for setting and retrieving multiple properties at once.

Media samples are not guaranteed to support IMediaSample2. However, if an allocator creates samples that support IMediaSample2, all of the samples that it creates must support the interface. For any given media sample, the IMediaSample2::GetProperties method returns the same values as the individual IMediaSample methods. Therefore, you can use whichever version you prefer.

In addition to the methods inherited from IMediaSample, the IMediaSample2 interface exposes the following methods.

Method | Description
GetProperties | Retrieves the properties of a media sample.
SetProperties | Sets the properties of a media sample.


IMediaSample2::GetProperties

The GetProperties method retrieves the properties of a media sample.

Syntax

HRESULT GetProperties(
  DWORD cbProperties,
  BYTE *pbProperties
);

Parameters

cbProperties

[in] Length of property data to retrieve, in bytes.

pbProperties

[out] Pointer to a buffer of size cbProperties.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The retrieved data conforms to the format of the AM_SAMPLE2_PROPERTIES structure. You can retrieve a subset of the sample properties by setting cbProperties to a value less than the size of the AM_SAMPLE2_PROPERTIES structure.

For efficiency, the pMediaType member returned in AM_SAMPLE2_PROPERTIES is a pointer to the data stored in the media sample, not a copy of that data. The pointer may become invalid after the sample is passed to another filter, or after the input pin's IMemInputPin::Receive method has completed. Also, do not free the pointer or delete the media type.

See Also

  • Error and Success Codes
  • IMediaSample2 Interface


IMediaSample2::SetProperties

The SetProperties method sets the properties of a media sample.

Syntax

HRESULT SetProperties(
  DWORD cbProperties,
  const BYTE *pbProperties
);

Parameters

cbProperties

[in] Length of property data to set, in bytes.

pbProperties

[in] Pointer to a buffer of size cbProperties.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The data contained in pbProperties must conform to the format of the AM_SAMPLE2_PROPERTIES structure. You can specify a subset of the sample properties by setting cbProperties to a value less than the size of the AM_SAMPLE2_PROPERTIES structure.

See Also

  • Error and Success Codes
  • IMediaSample2 Interface


IMediaSeeking Interface

The IMediaSeeking interface contains methods for seeking to a position within a stream, and for setting the playback rate. The Filter Graph Manager exposes this interface, and so do individual filters. Applications should query the Filter Graph Manager for the interface.

The Filter Graph Manager distributes any IMediaSeeking call to each of the renderer filters in the graph. The renderer filters send the call upstream to the source filters. This sequence of events ensures that all streams remain synchronized. If any of the distributed calls returns an error, the Filter Graph Manager returns the first error value it received, even if some of the distributed calls succeed. An exception is E_NOTIMPL: the Filter Graph Manager does not return E_NOTIMPL unless it was returned by all of the distributed calls.

An application can seek the graph while the graph is in any state (running, paused or stopped). If the graph is running, the Filter Graph Manager pauses the graph before it issues the seek command. Then it runs the graph again. All seeking operations are independent of the current playback rate. Seeking operations cause any pending media data to be flushed from the graph.

For all IMediaSeeking parameters that specify time, the unit of time depends on the current time format. To set the time format, call the IMediaSeeking::SetTimeFormat method. Time formats are globally unique identifiers (GUIDs) defined in uuids.h. For more information, see Time Format GUIDs.

In addition to the methods inherited from IUnknown, the IMediaSeeking interface exposes the following methods.

Method | Description
GetCapabilities | Retrieves all the seeking capabilities of the stream.
CheckCapabilities | Queries whether a stream has specified seeking capabilities.
IsFormatSupported | Determines whether a specified time format is supported for seek operations.
QueryPreferredFormat | Retrieves the preferred time format for seeking.
GetTimeFormat | Retrieves the time format that is currently being used for seek operations.
IsUsingTimeFormat | Determines whether seek operations are currently using a specified time format.
SetTimeFormat | Sets the time format for subsequent seek operations.
GetDuration | Retrieves the duration of the stream.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
ConvertTimeFormat | Converts from one time format to another.
SetPositions | Sets the current position and the stop position.
GetPositions | Retrieves the current position and the stop position, relative to the total duration of the stream.
GetAvailable | Retrieves the range of times in which seeking is efficient.
SetRate | Sets the playback rate.
GetRate | Retrieves the playback rate.
GetPreroll | Retrieves the amount of data that will be queued before the start position.

See Also

  • Seeking the Filter Graph


IMediaSeeking::CheckCapabilities

The CheckCapabilities method queries whether a stream has specified seeking capabilities.

Syntax

HRESULT CheckCapabilities(
  DWORD *pCapabilities
);

Parameters

pCapabilities

[in, out] Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes. When the method returns, the value indicates which of those attributes are available.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Not all of the capabilities in pCapabilities are present.
S_OK | All capabilities in pCapabilities are present.
E_FAIL | No capabilities in pCapabilities are present.
E_POINTER | NULL pointer argument.

Remarks

If you are only interested in a few specific capabilities, calling this method is more efficient than calling IMediaSeeking::GetCapabilities, which checks all the stream's seeking capabilities.

Declare a DWORD value equal to the bitwise-OR combination of the AM_SEEKING_SEEKING_CAPABILITIES attributes that you want to test. Pass a pointer to this value in the pCapabilities parameter. When the method returns, pCapabilities contains a subset of the original bits, indicating which capabilities are present. The return value indicates whether some, none, or all of the requested capabilities are present.

The following code example shows how to find out whether the stream supports forward seeking, backward seeking, and absolute seeking.

// Set flags for the capabilities you want to check.
DWORD dwCaps = AM_SEEKING_CanSeekAbsolute |
             AM_SEEKING_CanSeekForwards |
             AM_SEEKING_CanSeekBackwards;

HRESULT hr = pMediaSeeking->CheckCapabilities(&dwCaps);
if(FAILED(hr))
{
    // The stream cannot seek.
}
else if (hr == S_OK)
{
    // The stream can seek forward, backward, and to an absolute position.
}
else if (hr == S_FALSE) // The stream might have some of the capabilities.
{
    if (dwCaps & AM_SEEKING_CanSeekAbsolute)
        // The stream can seek to an absolute position.
    if (dwCaps & AM_SEEKING_CanSeekAbsolute)
        // The stream can seek forward.
    if (dwCaps & AM_SEEKING_CanSeekBackwards)
        // The stream can seek backward.
}

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::ConvertTimeFormat

The ConvertTimeFormat method converts from one time format to another.

Syntax

HRESULT ConvertTimeFormat(
  LONGLONG *pTarget,
  const GUID *pTargetFormat,
  LONGLONG Source,
  const GUID *pSourceFormat
);

Parameters

pTarget

[out] Pointer to a variable that receives the converted time.

pTargetFormat

[in] Pointer to a GUID that specifies the target format. If NULL, the current format is used. See Time Format GUIDs.

Source

[in] Time value to be converted.

pSourceFormat

[in] Pointer to a GUID that specifies the format to convert. If NULL, the current format is used. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Conversion between these types is not supported.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetAvailable

The GetAvailable method retrieves the range of times in which seeking is efficient.

Syntax

HRESULT GetAvailable(
  LONGLONG *pEarliest,
  LONGLONG *pLatest
);

Parameters

pEarliest

[out] Pointer to a variable that receives the earliest time for efficient seeking.

pLatest

[out] Pointer to a variable that receives the latest time for efficient seeking.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method is intended primarily for seeking in media streams that might have excessive latency, such as streams being sent over a network. The returned values indicate cached data that has already arrived, which can be easily seeked. It is assumed that seeking to values beyond these returned parameters will cause a delay while the application waits for the data to arrive.

All time values are expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetCapabilities

The GetCapabilities method retrieves all the seeking capabilities of the stream.

Syntax

HRESULT GetCapabilities(
  DWORD *pCapabilities
);

Parameters

pCapabilities

[out] Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

This method returns information on all the seeking capabilities of the stream. Examine pCapabilities by performing a separate bitwise-AND operation on each AM_SEEKING_SEEKING_CAPABILITIES value you are interested in.

DWORD dwCaps = 0;
pMediaSeeking->GetCapabilities(&dwCaps);

if (dwCaps & AM_SEEKING_CanGetCurrentPos)
{
    // The stream can seek to the current position.
}
if (dwCaps & AM_SEEKING_CanPlayBackwards)
{
    // The stream can play backward.
}

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetCurrentPosition

The GetCurrentPosition method retrieves the current position, relative to the total duration of the stream.

Syntax

HRESULT GetCurrentPosition(
  LONGLONG *pCurrent
);

Parameters

pCurrent

[out] Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method returns the current position that playback has reached. The value ignores the playback rate and start time. For example, if you set the rate to 2.0 and the start time to five seconds, running the graph for four seconds yields a current position of nine seconds (5 + 4 x 2.0). The returned value is expressed in units of the current time format. To determine the current time format, call the GetTimeFormat method.

If the graph is paused or stopped, the current position is the point at which playback will resume.

The Filter Graph Manager calculates the position from the current stream time; it does not query the filters in the graph. For file playback, this yields an accurate result, because playback is synchronized to the stream time. For file writing, the results are not accurate. To get the current position in a file-writing graph, query the multiplexer filter. (Position is not relevant for live capture, however.)

The returned value is expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetDuration

The GetDuration method retrieves the duration of the stream.

Syntax

HRESULT GetDuration(
  LONGLONG *pDuration
);

Parameters

pDuration

[out] Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the duration of the stream at normal playback speed. Changing the playback rate does not affect the duration.

The returned value is expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetPositions

The GetPositions method retrieves the current position and the stop position, relative to the total duration of the stream.

Syntax

HRESULT GetPositions(
  LONGLONG *pCurrent,
  LONGLONG *pStop
);

Parameters

pCurrent

[out] Pointer to a variable that receives the current position, in units of the current time format.

pStop

[out] Pointer to a variable that receives the stop position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The current position and the stop position are both relative to the original stream, and are independent of the playback rate.

The returned values are expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetPreroll

The GetPreroll method retrieves the amount of data that will be queued before the start position.

Syntax

HRESULT GetPreroll(
  LONGLONG *pllPreroll
);

Parameters

pllPreroll

[out] Pointer to a variable that receives the preroll time, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

The returned value is expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetRate

The GetRate method retrieves the playback rate.

Syntax

HRESULT GetRate(
  double *dRate
);

Parameters

dRate

[out] Pointer to a variable that receives the playback rate.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::GetStopPosition

The GetStopPosition method retrieves the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT GetStopPosition(
  LONGLONG *pStop
);

Parameters

pStop

[out] Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The playback rate does not affect the value returned by this method.

The returned value is expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method.


IMediaSeeking::GetTimeFormat

The GetTimeFormat method retrieves the time format that is currently being used for seek operations.

Syntax

HRESULT GetTimeFormat(
  GUID *pFormat
);

Parameters

pFormat

[out] Pointer to a variable that receives a GUID specifying the time format. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface
  • IMediaSeeking::SetTimeFormat


IMediaSeeking::IsFormatSupported

The IsFormatSupported method determines whether a specified time format is supported for seek operations.

Syntax

HRESULT IsFormatSupported(
  const GUID *pFormat
);

Parameters

pFormat

[in] Pointer to a GUID that specifies the time format. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The format is not supported.
S_OK | The format is supported.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface
  • IMediaSeeking::SetTimeFormat


IMediaSeeking::IsUsingTimeFormat

The IsUsingTimeFormat method determines whether seek operations are currently using a specified time format.

Syntax

HRESULT IsUsingTimeFormat(
  const GUID *pFormat
);

Parameters

pFormat

[in] Pointer to a GUID that specifies the time format. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The specified format is not the current format.
S_OK | The specified format is the current format.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method is slightly more efficient than the IMediaSeeking::GetTimeFormat method, because it does not require copying the GUID.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface
  • IMediaSeeking::SetTimeFormat


IMediaSeeking::QueryPreferredFormat

The QueryPreferredFormat method retrieves the preferred time format for seeking.

Syntax

HRESULT QueryPreferredFormat(
  GUID *pFormat
);

Parameters

pFormat

[out] Pointer to a variable that receives a GUID specifying the time format. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface
  • IMediaSeeking::SetTimeFormat


IMediaSeeking::SetPositions

The SetPositions method sets the current position and the stop position.

Syntax

HRESULT SetPositions(
  LONGLONG *pCurrent,
  DWORD dwCurrentFlags,
  LONGLONG *pStop,
  DWORD dwStopFlags
);

Parameters

pCurrent

[in,out] Pointer to a variable that specifies the current position, in units of the current time format.

dwCurrentFlags

[in] Bitwise combination of flags. See Remarks.

pStop

[in,out] Pointer to a variable that specifies the stop time, in units of the current time format.

dwStopFlags

[in] Bitwise combination of flags. See Remarks.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | No position change. (Both flags specify no seeking.)
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The dwCurrentFlags and dwStopFlags parameters define the type of seek. The following flags are defined:

Positioning Flags | Description
AM_SEEKING_NoPositioning | No change in position. (The time parameter can be NULL.)
AM_SEEKING_AbsolutePositioning | The specified position is absolute.
AM_SEEKING_RelativePositioning | The specified position is relative to the previous value.
AM_SEEKING_IncrementalPositioning | The stop position (pStop) is relative to the current position (pCurrent).
Modifier Flags | Description
AM_SEEKING_SeekToKeyFrame | Seek to the nearest key frame. This might be faster, but less accurate.
AM_SEEKING_ReturnTime | Return the equivalent reference times.
AM_SEEKING_Segment | Use segment seeking.
AM_SEEKING_NoFlush | Do not flush.

For each parameter, use one positioning flag. Optionally, include one or more modifier flags.

If the AM_SEEKING_ReturnTime flag is specified, the method converts the position value to a reference time and returns it in the pCurrent or pStop variable. This flag is useful if you are using another time format, such as frames.

The AM_SEEKING_Segment and AM_SEEKING_NoFlush flags support seamless looping:

  • If the AM_SEEKING_Segment flag is present, the source filter sends an EC_END_OF_SEGMENT event when it reaches the stop position, instead of calling IPin::EndOfStream. The application can wait for this event and then issue another seek command.
  • If the AM_SEEKING_NoFlush flag is present, the graph does not flush data during the seek. Use this flag with AM_SEEKING_Segment.

To perform looping, the graph must report AM_SEEKING_CanDoSegments in the IMediaSeeking::GetCapabilities method. Currently, only the WAVE Parser Filter supports this feature.

The incoming values of pCurrent and pStop are expressed in the current time format. The default time format is REFERENCE_TIME units (100 nanoseconds). To change time formats, use the IMediaSeeking::SetTimeFormat method. If the AM_SEEKING_ReturnTime flag is present, the method converts the outgoing value to REFERENCE_TIME units.

Filter Developers

If you implement this method, you can check whether the caller is requesting a change in the current or stop position, by using the value AM_SEEKING_PositioningBitsMask to mask out the modifier flags. For example:

DWORD dwCurrentPos = dwCurrentFlags & AM_SEEKING_PositioningBitsMask
if (dwCurrentPos == AM_SEEKING_AbsolutePositioning)
{
    // Set new position to pCurrent.
    m_rtStart = *pCurrent;
}
else if (dwCurrentPos == AM_SEEKING_RelativePositioning)
{
    // Increment current position by pCurrent.
    m_rtStart += *pCurrent;
}

For more information, see the source code for the CSourceSeeking::SetPositions method in the base class library.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::SetRate

The SetRate method sets the playback rate.

Syntax

HRESULT SetRate(
  double dRate
);

Parameters

dRate

[in] Playback rate. Must not be zero.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | The specified rate was zero or a negative value. (See Remarks.)
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.
VFW_E_UNSUPPORTED_AUDIO | Audio device or filter does not support this rate.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed. For audio streams, changing the rate also changes the pitch.

Negative values indicate reverse playback. Most filters do not support negative playback, but instead return an error code if the dRate parameter is negative.

When an application calls this method on the Filter Graph Manager, the Filter Graph Manager does the following:

  1. Calls the IMediaSeeking::GetCurrentPosition method. This call returns the current position as calculated by the Filter Graph Manager.
  2. Stops the filter graph (if the graph is paused or running).
  3. Calls the IMediaSeeking::SetPositions method on the filters, with the current position as the start time. This has the effect of resetting the stream time to zero.
  4. Calls the SetRate method on the filters, with the new rate.
  5. Resumes the filter graph, if it was paused or running.

If an error occurs in step 4, the Filter Graph Manager tries to restore the previous rate.

Filters should repond to rate changes as follows:

Parser and source filters: The filter that originates the time stamps responds to the SetRate call. This is usually a parser filter, such as the AVI Splitter Filter, but it might be a source filter. After any seek or rate change, the filter should call the IPin::NewSegment method with the new settings. After a rate change, it should adjust its time stamps accordingly. Because a rate change is preceded by a seek, time stamps restart from zero, so the filter can simply divide by the rate to calculate the new time stamps.

Decoder filters: Decoders should not act on SetRate calls other than to pass them upstream. Instead, they should respond to the NewSegment call that the upstream parser issues. When a decoder filter receives new segment information, it should store the values and pass the NewSegment call downstream. Some decoders need to generate extra time stamps by interpolating their input; they should take rate changes into account when doing so.

Renderers: Video renderers can typically ignore rate changes, because the incoming frames already have the correct time stamp. Audio renderers must modify their playback rate, because audio decoders typically do not make rate-change conversions.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface


IMediaSeeking::SetTimeFormat

The SetTimeFormat method sets the time format for subsequent seek operations.

Syntax

HRESULT SetTimeFormat(
  const GUID *pFormat
);

Parameters

pFormat

[in] Pointer to a GUID that specifies the time format. See Time Format GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.
VFW_E_WRONG_STATE | Filter graph is not stopped.

Remarks

This method specifies the time units used by other IMediaSeeking methods, such as IMediaSeeking::GetPositions and IMediaSeeking::SetPositions. Whenever you call one of these other methods, any parameters that express time values are given in units of the current time format.

The default time format is REFERENCE_TIME units (100 nanoseconds). Other time formats include frames, samples, and bytes. To determine if a given format is supported, call the IMediaSeeking::IsFormatSupported method. If a format is supported, you can switch to that format by calling SetTimeFormat. Only one time format is active at any one time.

See Also

  • Error and Success Codes
  • IMediaSeeking Interface
  • IMediaSeeking::GetTimeFormat
  • IMediaSeeking::QueryPreferredFormat


IMemAllocator Interface

Allocates media samples, for moving data between pins.

This interface is used by pins that share allocators, when the input pin exposes the IMemInputPin interface. The pins negotiate which pin will provide the allocator. The allocator is used to allocate memory buffers, retrieve empty buffers, and release buffers. Not every filter creates its own allocator, so one allocator might be used by several filters. For more information, see How Filters Connect.

Applications typically do not use this interface.

To use an allocator, perform the following steps:

  1. Call the IMemAllocator::SetProperties method to specify the buffer requirements, including the number of buffers and the size of each buffer.
  2. Call the IMemAllocator::Commit method to allocate the buffers.
  3. Call the IMemAllocator::GetBuffer method to retrieve media samples. This method blocks until the next sample becomes available.
  4. When you are done with each sample, call the IUnknown::Release method on the sample. The sample is not deleted when its reference count reaches zero. Instead, the sample returns to the allocator's free list.
  5. When you are done using the allocator, call the IMemAllocator::Decommit method to release the memory for the buffers.

Methods in Vtable Order

In addition to the methods inherited from IUnknown, the interface exposes the following methods.

Method | Description
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.
GetProperties | Retrieves the number of buffers that the allocator will create, and the buffer properties.
Commit | Allocates the buffer memory.
Decommit | Releases the buffer memory.
GetBuffer | Retrieves a media sample that contains an empty buffer.
ReleaseBuffer | Releases a media sample.


IMemAllocator::Commit

The Commit method allocates the buffer memory.

Syntax

HRESULT Commit(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

Before calling this method, call the IMemAllocator::SetProperties method to specify the buffer requirements.

You must call this method before calling the IMemAllocator::GetBuffer method.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocator::Decommit

The Decommit method releases the buffer memory.

Syntax

HRESULT Decommit(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Any threads waiting in the IMemAllocator::GetBuffer method return with an error. Further calls to GetBuffer fail, until the IMemAllocator::Commit method is called.

The purpose of the Decommit method is to prevent filters from getting any more samples from the allocator. Filters that already hold a reference count on a sample are not affected. After a filter releases a sample and the reference count goes to zero, however, the sample is no longer available.

The allocator may free the memory belonging to any sample with a reference count of zero. Thus, the Decommit method "releases" the memory in the sense that filters stop having access to it. Whether the memory actually returns to the heap depends on the implementation of the allocator. Some allocators wait until their own destructor method. However, an allocator must not leave any allocated memory behind when it deletes itself. Therefore, an allocator's destructor must wait until all of its samples are released.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocator::GetBuffer

The GetBuffer method retrieves a media sample that contains an empty buffer.

Syntax

HRESULT GetBuffer(
  IMediaSample **ppBuffer,
  REFERENCE_TIME *pStartTime,
  REFERENCE_TIME *pEndTime,
  DWORD dwFlags
);

Parameters

ppBuffer

[out] Address of a variable that receives a pointer to the buffer's IMediaSample interface.

pStartTime

[in] Pointer to the start time of the sample, or NULL.

pEndTime

[in] Pointer to the ending time of the sample, or NULL.

dwFlags

[in] Bitwise combination of zero or more of the following flags:

Flag | Description
AM_GBF_NOTASYNCPOINT | This sample is not a synchronization point. Dynamic format changes are not allowed on this sample. When called on the Overlay Mixer or VMR, this flag implies that the buffer returned will contain an image that is identical to the last image delivered.
AM_GBF_PREVFRAMESKIPPED | This sample is the first after a discontinuity. (Only the video renderer uses this flag.)
AM_GBF_NOWAIT | Do not wait for a buffer to become available.
AM_GBF_NODDSURFACELOCK | Used with the Video Mixing Renderer Filter 7 (Microsoft® Windows® XP only) to request an unlocked DirectDraw surface. For more information, see Working with Direct3D Render Targets.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_COMMITTED | Allocator is decommitted.
VFW_E_TIMEOUT | Timed out.

Remarks

By default, this method blocks until a free sample is available or the allocator is decommitted. If the caller specifies the AM_GBF_NOWAIT flag and no sample is available, the allocator can return immediately with a return value of VFW_E_TIMEOUT. However, allocators are not required to support this flag.

The sample returned in ppBuffer has a valid buffer pointer. The caller is responsible for setting any other properties on the sample, such as the time stamps, the media times, or the sync-point property. (For more information, see IMediaSample.)

The pStartTime and pEndTime parameters are not applied to the sample. The allocator might use these values to determine which buffer it retrieves. For example, the Video Renderer filter uses these values to synchronize switching between Microsoft® DirectDraw® surfaces. To set the time stamp on the sample, call the IMediaSample::SetTime method.

You must call the IMemAllocator::Commit method before calling this method. This method fails after the IMemAllocator::Decommit method is called. If the method succeeds, the IMediaSample interface that it returns has an outstanding reference count. Be sure to release the interface when you are done using it.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocator::GetProperties

The GetProperties method retrieves the number of buffers that the allocator will create, and the buffer properties.

Syntax

HRESULT GetProperties(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

[out] Pointer to an ALLOCATOR_PROPERTIES structure that receives the allocator properties.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Calls to this method might not succeed until the IMemAllocator::Commit method is called.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocator::ReleaseBuffer

The ReleaseBuffer method releases a media sample.

Syntax

HRESULT ReleaseBuffer(
  IMediaSample *pBuffer
);

Parameters

pBuffer

[in] Pointer to the media sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

When a media sample's reference count reaches zero, it calls this method with itself as the pBuffer parameter. This method releases the sample back to the allocator's list of available samples.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocator::SetProperties

The SetProperties method specifies the number of buffers to allocate and the size of each buffer.

Syntax

HRESULT SetProperties(
  ALLOCATOR_PROPERTIES *pRequest,
  ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.

pActual

Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method specifies the buffer requirements, but does not allocate any buffers. Call the IMemAllocator::Commit method to allocate buffers.

The caller allocates two ALLOCATOR_PROPERTIES structures. The pRequest parameter contains the caller's buffer requirements, including the number of buffers and the size of each buffer. When the method returns, the pActual parameter contains the actual buffer properties, as set by the allocator.

When this method is called, the allocator must not be committed or have outstanding buffers.

See Also

  • Error and Success Codes
  • IMemAllocator Interface


IMemAllocatorCallbackTemp Interface

The IMemAllocatorCallbackTemp interface enables a filter to receive a callback notification from an allocator whenever a sample is returned to the allocator's free list.

The use of this interface is deprecated.

In addition to the methods inherited from IMemAllocator, the IMemAllocatorCallbackTemp interface exposes the following methods.

Method | Description
GetFreeCount | Retrieves the number of free media samples.
SetNotify | Sets or removes a callback on the allocator.


IMemAllocatorCallbackTemp::GetFreeCount

The GetFreeCount method returns the number of free media samples. This number equals the total number of media samples minus the number of samples that are currently held by filters.

Syntax

HRESULT GetFreeCount(
    LONG *plBuffersFree
);

Parameters

plBuffersFree

[out] Pointer to a variable that receives the number of free media samples.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

A filter holds a sample by keeping a reference count on it. It releases the sample by releasing the reference count.

Until the allocator is committed, the samples are not guaranteed to be allocated.

See Also

  • Error and Success Codes
  • IMemAllocatorCallbackTemp Interface


IMemAllocatorCallbackTemp::SetNotify

The SetNotify method sets or removes a callback on the allocator. The allocator calls the callback method whenever the allocator's IMemAllocator::ReleaseBuffer method is called.

Syntax

HRESULT SetNotify(
    IMemAllocatorNotifyCallbackTemp *pNotify
);

Parameters

pNotify

Pointer to the IMemAllocatorNotifyCallbackTemp interface that will be used for the callback. The caller must implement the interface. Use the value NULL to remove the callback.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

Whenever the allocator's ReleaseBuffer method is called, the allocator calls the NotifyRelease method on the interface provided in pNotify. The ReleaseBuffer method returns a media sample to the allocator's free list. Samples call this method when their reference counts reach zero.

The allocator holds a reference count on the caller's IMemAllocatorNotifyCallbackTemp interface. This can create circular reference counts, thereby preventing objects in the graph from being released correctly. Therefore, when the caller no longer needs callback notifications, it should call this method again with the value NULL. An appropriate time to do this is when the graph stops, or else when the pins are disconnected.

See Also

  • Error and Success Codes
  • IMemAllocatorCallbackTemp Interface


IMemAllocatorNotifyCallbackTemp Interface

The IMemAllocatorNotifyCallbackTemp interface enables a filter to receive a callback notification from an allocator whenever a sample is returned to the allocator's free list. To receive callbacks, the filter must implement this interface. For more information, see IMemAllocatorCallbackTemp Interface.

The use of this interface is deprecated.

In addition to the methods inherited from IUnknown, the IMemAllocatorNotifyCallbackTemp interface exposes the following method.

Method | Description
NotifyRelease | Called when a sample returns to the allocator's free list.


IMemAllocatorNotifyCallbackTemp::NotifyRelease

The NotifyRelease method is called whenever the allocator's IMemAllocator::ReleaseBuffer method is called. The ReleaseBuffer method returns a media sample to the allocator's free list. Samples call this method when their reference counts reach zero.

Syntax

HRESULT NotifyRelease();

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

In general, this call can occur on any thread, and the caller may be holding critical sections. Therefore, this method should not do anything that could cause a deadlock. Instead, the method should set an event or post a message to another thread, and the other thread should take any required actions.

See Also

  • Error and Success Codes
  • IMemAllocatorNotifyCallbackTemp Interface


IMemInputPin Interface

The IMemInputPin interface is used to delivers media data to an input pin. Input pins expose this interface if they use the IMemAllocator interface to allocate buffers. When an output pin connects to an input pin, the output pin uses this interface to negotiate allocator requirements and deliver samples to the input pin.

Applications typically do not use this interface.

Filter developers: The CBaseInputPin class implements this interface.

In addition to the methods inherited from IUnknown, the IMemInputPin interface exposes the following methods.

Method | Description
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves allocator properties that are requested by the input pin.
Receive | Receives the next media sample in the stream.
ReceiveMultiple | Receives multiple samples in the stream.
ReceiveCanBlock | Determines whether calls to the Receive method might block.


IMemInputPin::GetAllocator

The GetAllocator method retrieves the memory allocator proposed by this pin. After the allocator has been selected, this method returns a pointer to the selected allocator.

Syntax

HRESULT GetAllocator(
  IMemAllocator **ppAllocator
);

Parameters

ppAllocator

[out] Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ALLOCATOR | No allocator is available.

Remarks

When an output pin connects to an input pin, it negotiates with the input pin to decide on a memory allocator. The output pin calls this method to retrieve the input pin's proposed allocator. It calls the IMemInputPin::NotifyAllocator method to specify which allocator it selected.

If this method succeeds, the IMemAllocator interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMemInputPin::GetAllocatorRequirements

The GetAllocatorRequirements method retrieves the allocator properties requested by the input pin.

Syntax

HRESULT GetAllocatorRequirements(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

[in] Pointer to an ALLOCATOR_PROPERTIES, structure which is filled in with the requirements.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_NOTIMPL | Not implemented
E_POINTER | NULL pointer argument

Remarks

When an output pin initializes a memory allocator, it can call this method to determine whether the input pin has any buffer requirements. The input pin is not required to implement this method. If the filter has specific alignment or prefix requirements, it should implement this method.

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMemInputPin::NotifyAllocator

The NotifyAllocator method specifies an allocator for the connection.

Syntax

HRESULT NotifyAllocator(
  IMemAllocator *pAllocator,
  BOOL bReadOnly
);

Parameters

pAllocator

[in] Pointer to the allocator's IMemAllocator interface.

bReadOnly

[out] Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

During the pin connection, the output pin chooses an allocator and calls this method to notify the input pin. The output pin might use the allocator that the input pin proposed in the IMemInputPin::GetAllocator method, or it might provide its own allocator.

If the bReadOnly parameter is TRUE, all samples in the allocator are read-only. The filter must copy them to modify the data.

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMemInputPin::Receive

The Receive method receives the next media sample in the stream.

Syntax

HRESULT Receive(
  IMediaSample *pSample
);

Parameters

pSample

[in] Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
S_FALSE | The sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method is synchronous and possibly blocking. The pin does one of the following:

  • Rejects the sample.
  • Returns immediately and processes the sample in a worker thread.
  • Processes the sample before returning.

In the last case, the method might block indefinitely. If this might happen, the IMemInputPin::ReceiveCanBlock method returns S_OK.

If the pin uses a worker thread to process the sample, it holds a reference count on the sample. In any case, the output pin cannot directly re-use this sample. It must call the IMemAllocator::GetBuffer method to obtain a new sample.

If this method returns S_FALSE or an error code, the upstream filter should stop sending samples until the graph stops or completes a flush operation. Typical reasons for an S_FALSE return value include:

  • The downstream pin is flushing; that is, it received a BeginFlush call and has not yet received an EndFlush call.
  • The downstream filter detected the end of the stream. (See End-of-Stream Notifications.)

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMemInputPin::ReceiveCanBlock

The ReceiveCanBlock method determines whether calls to the IMemInputPin::Receive method might block.

Syntax

HRESULT ReceiveCanBlock(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | The pin will not block on a call to Receive
S_OK | The pin might block on a call to Receive.

Remarks

If this method returns S_FALSE, calls to the Receive method are guaranteed not to block. Otherwise, they might block. An upstream filter can use this method to determine its threading strategy. If calls to Receive can block, the upstream filter might decide to use a worker thread that buffers data.

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMemInputPin::ReceiveMultiple

The ReceiveMultiple method receives multiple samples in the stream.

Syntax

HRESULT ReceiveMultiple(
  IMediaSample **pSamples,
  long nSamples,
  long *nSamplesProcessed
);

Parameters

pSamples

[in] Address of an array of IMediaSample interface pointers, of size nSamples.

nSamples

[in] Number of samples to process.

nSamplesProcessed

[out] Pointer to a variable that receives the number of samples that were processed.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method behaves like the IMemInputPin::Receive method, but receives an array of samples.

See Also

  • Error and Success Codes
  • IMemInputPin Interface


IMixerOCX Interface

The IMixerOCX interface is implemented on the Overlay Mixer. This interface enables clients that do not own their own windows, such as an ActiveX control, to set properties of the video rectangle and advise the filter of events.

Note Applications should generally use the Video Mixing Renderer Filter 9 (VMR-9) and not the Overlay Mixer. The only scenario that requires the Overlay Mixer is when the video capture or decoder hardware uses video ports to transfer video data to the graphics card. The VMR-9 does not support video ports.

In addition to the methods inherited from IUnknown, the IMixerOCX interface exposes the following methods.

Methods | Description
Advise | Provides the Overlay Mixer with a pointer to the client's IMixerOCXNotify interface for callback notifications.
GetAspectRatio | Not implemented.
GetStatus | Not implemented.
GetVideoSize | Retrieves the current size of the video rectangle.
OnDisplayChange | Not implemented.
OnDraw | Instructs the Overlay Mixer to draw the video rectangle.
SetDrawRegion | Specifies the location and dimensions of the video and clipping rectangles in screen coordinates.
UnAdvise | Instructs the Overlay Mixer to release its pointer to the client's IMixerOCXNotify interface.


IMixerOCX::Advise

The Advise method provides the Overlay Mixer with a pointer to the client's IMixerOCXNotify interface for callback notifications.

Syntax

HRESULT Advise(
  IMixerOCXNotify*  pmdns
);

Parameters

pmdns

[in] Specifies the client's IMixerOCXNotify interface.

Return Values

If the method succeeds, it returns S_OK.

Remarks

Call this method if you wish to receive callbacks from the Overlay Mixer.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::GetAspectRatio

The GetAspectRatio method returns the current aspect ratio setting on the Overlay Mixer. (Currently not implemented.)

Syntax

HRESULT GetAspectRatio(
  LPDWORD  pdwPictAspectRatioX,
  LPDWORD  pdwPictAspectRatioY
);

Parameters

pdwPictAspectRatioX

[out] Pointer that receives the value of the X dimension.

pdwPictAspectRatioY

[out] Pointer that receives the value of the Y dimension.

Return Values

Return E_NOTIMPL.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::GetStatus

The GetStatus method returns the current status of the Overlay Mixer. (Not implemented.)

Syntax

HRESULT GetStatus(
  LPDWORD*  pdwStatus
);

Parameters

pdwStatus

[out] Pointer that receives the current status of the Overlay Mixer.

Return Values

Returns E_NOTIMPL.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::GetVideoSize

The GetVideoSize method retrieves the current size of the video rectangle.

Syntax

HRESULT GetVideoSize(
  LPDWORD  pdwVideoWidth,
  LPDWORD  pdwVideoHeight
);

Parameters

pdwVideoWidth

[out] Pointer that receives the video width in pixels.

pdwVideoHeight

[out] Pointer that receives the video height in pixels.

Return Values

If the method succeeds, it returns S_OK.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::OnDisplayChange

The OnDisplayChange method informs the Overlay Mixer that the monitor's display settings have changed. (Not implemented.)

Syntax

HRESULT OnDisplayChange(
  ULONG  ulBitsPerPixel,
  ULONG  ulScreenWidth,
  ULONG  ulScreenHeight
);

Parameters

ulBitsPerPixel

[in] Specifies the new bits per pixel setting.

ulScreenWidth

[in] Specifies the new screen width in pixels.

ulScreenHeight

[in] Specifies the new screen height in pixels.

Return Values

Returns E_NOTIMPL.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::OnDraw

The OnDraw method instructs the Overlay Mixer to draw the video rectangle.

Syntax

HRESULT OnDraw(
  HDC  hdcDraw,
  LPCRECT  prcDraw
);

Parameters

hdcDraw

[in] Specifies the device context associated with the parent window.

prcDraw

[in] Specifies the rectangle coordinates of the video rectangle.

Return Values

If the method succeeds, it returns S_OK.

Remarks

The HDC provided here should not be cached. If an application has set a device context using SetDrawInfo, do not provide a non-NULL argument here.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::SetDrawRegion

The SetDrawRegion method specifies the location and dimensions of the video and clipping rectangles in screen coordinates.

Syntax

HRESULT SetDrawRegion(
  LPPOINT  lpptTopLeftSC,
  LPCRECT  prcDrawCC,
  LPCRECT  lprcClip
);

Parameters

lpptTopLeftSC

[in] Specifies the top left of the video rectangle in screen coordinates.

prcDrawCC

[in] Specifies the video rectangle in screen coordinates.

lprcClip

[in] Specifies the clipping rectangle in screen coordinates.

Return Values

The method returns an HRESULT value. Possible values include those in the following table.

Values | Description
S_OK | The method succeeded.
E_INVALIDARG | Either prcDrawCC or lprcClip are NULL.

Remarks

The lpptTopLeftSC parameter should be NULL unless the MIXER_DRAW_DC_ONSCREEN flag is set to TRUE.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCX::UnAdvise

The UnAdvise method instructs the Overlay Mixer to release its pointer to the client's IMixerOCXNotify interface.

Syntax

HRESULT UnAdvise();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK.

See Also

  • IMixerOCX Interface
  • Overlay Mixer


IMixerOCXNotify Interface

The IMixerOCXNotify interface is implemented by clients and called by the Overlay Mixer to send notifications of events affecting the video display rectangle.

In addition to the methods inherited from IUnknown, the IMixerOCXNotify interface exposes the following methods.

Methods | Description
OnDataChange | Notifies the client when the video rectangle's aspect ratio or size, or the display palette, has changed.
OnInvalidateRect | Notifies the client that the video rectangle has been invalidated.
OnStatusChange | Notifies the client that a status change has occurred.

See Also

  • IMixerOCX Interface


IMixerOCXNotify::OnDataChange

The OnDataChange method notifies the client when the video rectangle's aspect ratio or size, or the display palette, has changed.

Syntax

HRESULT OnDataChange(
  ULONG  ulDataFlags
);

Parameters

ulDataFlags

[in] Flag indicating which set of data has changed. The following flags are defined.

Flags | Description
MIXER_DATA_ASPECT_RATIO (0x00000001) | Picture aspect ratio.
MIXER_DATA_NATIVE_SIZE (0x00000002) | The video stream's native size changed.
MIXER_DATA_PALETTE (0x00000004) | The video palette changed.

Return Values

If the method succeeds, it returns S_OK.

See Also

  • IMixerOCX Interface
  • IMixerOCXNotify Interface


IMixerOCXNotify::OnInvalidateRect

The OnInvalidateRect method notifies the client that the video rectangle has been invalidated.

Syntax

HRESULT OnInvalidateRect(
  LPCRECT  lpcRect
);

Parameters

lpcRect

[in] Specifies the rectangle that has been invalidated, in screen coordinates.

Return Values

If the method succeeds, it returns S_OK.

See Also

  • IMixerOCX Interface
  • IMixerOCXNotify Interface


IMixerOCXNotify::OnStatusChange

The OnStatusChange method informs the client that a status change has occurred.

Syntax

HRESULT OnStatusChange(
  ULONG  ulStatusFlags
);

Parameters

ulStatusFlags

[in] Bitwise OR of one or more of the following status flags.

Flag | Description
MIXER_STATE_UNCONNECTED (0x00000000) | The Overlay Mixer is unconnected and stopped.
MIXER_STATE_CONNECTED_STOPPED (0x00000001) | The Overlay Mixer is connected and stopped.
MIXER_STATE_CONNECTED_PAUSED (0x00000002) | The Overlay Mixer is connected and paused.
MIXER_STATE_CONNECTED_PLAYING (0x00000003) | The Overlay Mixer is connected and playing.

Return Values

If the method succeeds, it returns S_OK.

See Also

  • IMixerOCX Interface
  • IMixerOCXNotify Interface
  • Overlay Mixer


IMixerPinConfig Interface

The IMixerPinConfig interface is exposed on the input pins of the Overlay Mixer filter and contains methods that manipulate video streams in various ways. The Overlay Mixer contains multiple input pins that are dynamically created as video input streams are added. The video stream on the first pin is known as the primary stream and subsequent streams are known as secondary streams.

Use this interface to manipulate the parameters involved in mixing various video streams. These parameters include getting and setting position, z-order, blending and transparency levels, aspect ratio correction, and color keys of streams.

When setting the position of video streams in the display window, the default relative position of all secondary streams is {0, 0, 0, 0}. Therefore, use the IMixerPinConfig::SetRelativePosition method on secondary streams to ensure that all video streams are placed properly.

Applications use this interface to get and set attributes when mixing multiple video streams.

In addition to the methods inherited from IUnknown, the IMixerPinConfig interface exposes the following methods.

Method | Description
SetRelativePosition | Sets the position of the stream in the display window.
GetRelativePosition | Retrieves the position of the stream in the display window.
SetZOrder | Sets the z-order of a particular video stream.
GetZOrder | Retrieves the z-order of a particular video stream.
SetColorKey | Sets the color key being used by a video stream.
GetColorKey | Retrieves the color key being used by a video stream.
SetBlendingParameter | Sets the blending parameter that defines how a secondary stream is blended with a primary stream.
GetBlendingParameter | Retrieves the value of the blending parameter that defines how a secondary stream is blended with a primary stream.
SetAspectRatioMode | Sets the aspect ratio correction mode for window resizing.
GetAspectRatioMode | Retrieves the aspect ratio correction mode for window resizing.
SetStreamTransparent | Sets the stream to transparent.
SetStreamTransparent | Determines whether a stream is transparent.

Requirements

Requires Mpconfig.h.


IMixerPinConfig::GetAspectRatioMode

The GetAspectRatioMode method retrieves the aspect ratio correction mode for window resizing.

Syntax

HRESULT GetAspectRatioMode(
  AM_ASPECT_RATIO_MODE *pamAspectRatioMode
);

Parameters

pamAspectRatioMode

[out] Pointer to an AM_ASPECT_RATIO_MODE enumerated type member.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_NOTIMPL | Method called on secondary stream.
E_INVALIDARG | Value invalid or NULL.
S_OK | Success.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetAspectRatioMode


IMixerPinConfig::GetBlendingParameter

The GetBlendingParameter method retrieves the value of the blending parameter that defines how a secondary stream is blended with a primary stream.

Syntax

HRESULT GetBlendingParameter(
  DWORD *pdwBlendingParameter
);

Parameters

pdwBlendingParameter

[out] Pointer to a value between 0 and 255 that indicates the amount of blending between a primary stream and a secondary stream.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_UNEXPECTED | Method called on primary stream.
E_INVALIDARG | Value outside of possible range (0-255).
S_OK | Success.

Remarks

A value of zero indicates that the secondary stream is invisible; a value of 255 indicates the primary stream is invisible in the area that the secondary stream occupies.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetBlendingParameter


IMixerPinConfig::GetColorKey

The GetColorKey method retrieves the color key being used by a video stream.

Syntax

HRESULT GetColorKey(
  COLORKEY *pColorKey,
  DWORD *pColor
);

Parameters

pColorKey

[out] Pointer to a COLORKEY structure that contains the key type and a palette index.

pColor

[out] Pointer to a value indicating the 8-bit palette index of the COLORKEY returned if the current display mode is 8-bit palettized. Otherwise it is a value representing the color key in the pixel format of the current display mode.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_INVALIDARG | Invalid arguments, both parameters are NULL.
E_FAIL | GetColorKey failed because the color key isn't known.
NOERROR | Success.

Remarks

Getting the value on the primary stream will retrieve the destination color key being used by the overlay surface. Getting this value on the secondary pin returns the color key being used by that particular stream.

Current DirectShow implementation of this interface can return NULL for either the pColorKey or the pColor parameters; however, the method will fail and return E_INVALIDARG if both parameters are NULL.

Note The DWORD value returned by the pColor parameter is the actual color being used. So, if the bit depth of the display is 8, 16, 24, 32 the last 8, 16, 24 or 32 bits of the DWORD specify the actual value of the color key.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetColorKey


IMixerPinConfig::GetStreamTransparent

The GetStreamTransparent method determines whether a stream is transparent.

Syntax

HRESULT GetStreamTransparent(
  BOOL *pbStreamTransparent
);

Parameters

pbStreamTransparent

[out] Pointer to a value indicating whether the stream is transparent. TRUE indicates transparent stream; FALSE indicates not a transparent stream.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_NOTIMPL | Method is not supported.
S_OK | Success.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetStreamTransparent


IMixerPinConfig::GetRelativePosition

The GetRelativePosition method retrieves the position of the stream in the display window.

Syntax

HRESULT GetRelativePosition(
  DWORD *pdwLeft,
  DWORD *pdwTop,
  DWORD *pdwRight,
  DWORD *pdwBottom
);

Parameters

pdwLeft

[out] Pointer to a value indicating the x-coordinate in the top-left corner of the display window.

pdwTop

[out] Pointer to a value indicating the y-coordinate in the top-left corner of the display window.

pdwRight

[out] Pointer to a value indicating the x-coordinate in the bottom-right corner of the display window.

pdwBottom

[out] Pointer to a value indicating the y-coordinate in the bottom-right corner of the display window.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_INVALIDARG | Coordinates not in the {0, 0, 10,000, 10,000} range.
S_OK | Success.

Remarks

This method assumes window coordinates of {0, 0, 10,000, 10,000}. If the video stream is being rendered in the bottom right quarter of the display window, this method would return {5,000, 5,000, 10,000, 10,000}.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetRelativePosition


IMixerPinConfig::GetZOrder

The GetZOrder method retrieves the z-order of a particular video stream.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetZOrder(
  DWORD *pdwZOrder
);

Parameters

pdwZOrder

[out] Pointer to a value indicating the order in which streams will clip each other.

Return Value

Returns E_NOTIMPL.

Remarks

Images with larger z-values are always in front of images with smaller z-values.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::SetZOrder


IMixerPinConfig::SetAspectRatioMode

The SetAspectRatioMode method sets the aspect ratio correction mode for window resizing.

Syntax

HRESULT SetAspectRatioMode(
  AM_ASPECT_RATIO_MODE amAspectRatioMode
);

Parameters

amAspectRatioMode

[in] Value specifying one of the AM_ASPECT_RATIO_MODE enumerated type members.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_NOTIMPL | Method called on secondary stream.
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

Currently this function is implemented only on the primary pin of the Overlay Mixer filter. Calling it on a secondary pin will result in an error.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetAspectRatioMode


IMixerPinConfig::SetBlendingParameter

The SetBlendingParameter method sets the blending parameter that defines how a secondary stream is blended with a primary stream.

Syntax

HRESULT SetBlendingParameter(
  DWORD dwBlendingParameter
);

Parameters

dwBlendingParameter

[in] Value between 0 and 255 that indicates the amount of blending between a primary stream and a secondary stream.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_UNEXPECTED | Method called on primary stream.
E_INVALIDARG | Value outside of possible range (0 to 255).
S_OK | Success.

Remarks

The value of the dwBlendingParameter parameter must be between 0 and 255, where 0 makes the secondary stream invisible and 255 makes the primary stream invisible in the area that the secondary stream occupies. If no value is set the default is 255.

This method is not intended to be called on the primary stream.

Note Current DirectShow implementation of this interface allows only values of 0 or 255 for the dwBlendingParameter parameter. Any other values are invalid.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetBlendingParameter


IMixerPinConfig::SetColorKey

The SetColorKey method sets the color key being used by a video stream.

Syntax

HRESULT SetColorKey(
  COLORKEY *pColorKey
);

Parameters

pColorKey

[in] Pointer to a COLORKEY structure.

Return Value

Returns an HRESULT value.

Remarks

The term color key has different meanings depending on which stream it is referring to. The color key of the primary stream refers to the destination color key being used by the overlay surface. The color key of the secondary stream refers to the source color key used, when blitting from an offscreen surface to the primary surface.

Applications should set the color key of the primary pin to an obscure color (some color which, in all probability, will not be present on the desktop). Overlay mixer filters will try to pick an obscure color, but if the application knows that the specified color is part of some other content, then the application should change it.

Setting the color key on the secondary stream can be used to make the stream transparent and enable nonrectangular images. For example, if the secondary stream is closed-captioned text, then the closed-captioned text decoder should paint a solid color in the background and then set the color key on the corresponding pin to that color. This ensures that all pixels are transferred except those specified by the color key. If possible, applications should set the color key of the secondary stream to the same as that of the primary stream to give a slight performance advantage.

Setting this value on the primary stream sets the destination color key being used by the overlay surface. By default, the destination color key is used as the color key for all transparent (secondary) streams.

Valid arguments for the pColorKey parameter include CK_INDEX when video display mode is set to 256 colors, and CK_RGB when video display mode is set to a higher color depth such as hi-color, 24-bit, or 32-bit. The CK_RGB flag must be specified along with the CK_INDEX. If CK_INDEX flag is set then the index will be used as palette index in 256 color mode. But you must provide a COLORREF with a valid true color so that if the display mode is changed on the fly, DirectShow can switch to using the specified true color. This is because a number of true colors can be mapped to a single palette index, but going the other way from the palette index to a true color is not one-to-one.

Note Currently, this method is implemented only for the primary input pin.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetColorKey


IMixerPinConfig::SetStreamTransparent

The SetStreamTransparent method sets the stream to transparent.

Syntax

HRESULT SetStreamTransparent(
  BOOL bStreamTransparent
);

Parameters

bStreamTransparent

[in] Value specifying the transparency of the stream. Pass in TRUE to indicate stream is transparent; FALSE to indicate not a transparent stream.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetStreamTransparent


IMixerPinConfig::SetRelativePosition

The SetRelativePosition method sets the position of the stream in the display window.

Syntax

HRESULT SetRelativePosition(
  DWORD dwLeft,
  DWORD dwTop,
  DWORD dwRight,
  DWORD dwBottom
);

Parameters

dwLeft

[in] Value specifying the x-coordinate in the upper-left corner of the display window.

dwTop

[in] Value specifying the y-coordinate in the upper-left corner of the display window.

dwRight

[in] Value specifying the x-coordinate in the bottom-right corner of the display window.

dwBottom

[in] Value specifying the y-coordinate in the bottom-right corner of the display window.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_INVALIDARG | Coordinates not in the {0, 0, 10,000, 10,000} range.
S_OK | Success.

Remarks

This method assumes window coordinates of {0, 0, 10,000, 10,000}. Therefore, if you want your video stream to be rendered in the bottom right quarter of the display window, you would call this method with the parameters {5,000, 5,000, 10,000, 10,000}.

Note Values greater than 10,000 are invalid and will cause an error.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetRelativePosition


IMixerPinConfig::SetZOrder

The SetZOrder method sets the z-order of a particular video stream.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT SetZOrder(
  DWORD dwZOrder
);

Parameters

dwZOrder

[in] Value indicating the order in which streams will clip each other.

Return Value

Returns E_NOTIMPL.

Remarks

The z-order indicates which streams can clip other streams. Images with larger z-values are always in front of images with smaller z-values.

The relative order of multiple streams is significant only if the video images overlap.

Specifying the same z-order for two overlapping streams can cause strange video artifacts.

See Also

  • Error and Success Codes
  • IMixerPinConfig Interface
  • IMixerPinConfig::GetZOrder


IMixerPinConfig2 Interface

The IMixerPinConfig2 interface is exposed on the input pins of the Overlay Mixer and contains methods that manipulate video color controls, if the VGA chip supports it.

This interface derives from the IMixerPinConfig interface.

Applications use this interface to get and set video color controls when mixing multiple video streams.

Requirements

Requires Mpconfig.h.

In addition to the methods inherited from IMixerPinConfig, the IMixerPinConfig2 interface exposes the following methods.

Method | Description
SetOverlaySurfaceColorControls | Sets the color control settings associated with the specified overlay surface.
GetOverlaySurfaceColorControls | Retrieves the color control settings currently associated with the specified overlay surface.


IMixerPinConfig2::GetOverlaySurfaceColorControls

The GetOverlaySurfaceColorControls method retrieves the color control settings associated with the specified overlay surface.

Syntax

HRESULT GetOverlaySurfaceColorControls(
  LPDDCOLORCONTROL pColorControl
);

Parameters

pColorControl

[out] Address of a pointer to the DDCOLORCONTROL structure containing the color values currently applied to the specified surface.

Return Value

Returns an HRESULT value. If the allocator on the pin is not using an overlay surface, the method returns E_FAIL.

See Also

  • Error and Success Codes
  • IMixerPinConfig2 Interface


IMixerPinConfig2::SetOverlaySurfaceColorControls

Sets the color control settings associated with the specified overlay surface.

Syntax

HRESULT SetOverlaySurfaceColorControls(
  LPDDCOLORCONTROL pColorControl
);

Parameters

pColorControl

[in] Address of a pointer to the DDCOLORCONTROL structure containing the new values to be applied to the specified surface.

Return Value

Returns an HRESULT value. If the allocator on the pin is not using an overlay surface, the method returns E_FAIL.

See Also

  • Error and Success Codes
  • IMixerPinConfig2 Interface


IMpeg2Demultiplexer Interface

This interface is implemented on the MPEG-2 Demultiplexer filter (Demux) and is used in both program stream mode and transport stream mode. It is called by applications or other filters to create, configure and delete output pins on the Demux. This interface is not exposed when the filter is playing back a file (pull-mode).

In addition to the methods inherited from IUnknown, the IMpeg2Demultiplexer interface exposes the following methods.

Method | Description
CreateOutputPin | Creates a new output pin on the Demux.
SetOutputPinMediaType | Updates the media type of the specified output pin. (DirectX® 9.0 and later.)
DeleteOutputPin | Deletes the specified output pin.


IMpeg2Demultiplexer::CreateOutputPin

The CreateOutputPin method creates a new output pin on the Demux.

Syntax

HRESULT CreateOutputPin(
  AM_MEDIA_TYPE* pMediaType,
  LPWSTR pszPinName,
  IPin** ppIPin
);

Parameters

pMediaType

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type information for the new pin.

pszPinName

[in] Pointer to a wide character string that specifies a name for the new pin. The maximum length is 128 characters, including the NULL terminator.

ppIPin

[out] Address of a variable that receives a pointer to the pin's IPin interface.

Return Value

Returns an HRESULT value. Possible return values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_DUPLICATE_NAME | Duplicate pin name.

Remarks

Duplicate pin names are not allowed. To configure the pin, query the returned IPin interface for the IMPEG2StreamIdMap interface (for program streams) or for the IMPEG2PIDMap interface (for transport streams). Depending on which interface is queried for on the first output pin, the Demux configures itself for either transport or program stream mode. Once the Demux is configured, any calls to QueryInterface to retrieve the other interface will fail.

See Also

  • Error and Success Codes
  • IMpeg2Demultiplexer Interface


IMpeg2Demultiplexer::SetOutputPinMediaType

The SetOutputPinMediaType method updates the media type of the specified output pin. (DirectX® 9.0 and later.)

Syntax

HRESULT SetOutputPinMediaType(
  LPWSTR pszPinName,
  AM_MEDIA_TYPE* pMediaType
);

Parameters

pszPinName

[in] The friendly name of the pin as specified when the pin was created in a call to CreateOutputPin.

pMediaType

in] Pointer to an AM_MEDIA_TYPE structure that specifies the new media type information for the pin.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

The pin must be assigned the media type at the time it is created. The media type cannot be modified later.

Pins can be reconfigured at any time with a new media type. If no connection exists, the media type is simply updated. If the pin is connected, the success or failure of the call will depend on the downstream input pin's acceptance or rejection of the specified media type.

The media type is not interpreted in any way by the Demultiplexer filter. It is used only during connection negotiation by the output pin. It has no effect on the content of the media samples. Media sample content is defined when a PID is mapped via the MEDIA_SAMPLE_CONTENT parameter in the IMPEG2PIDMap::MapPID method, or via the defined values in an IMPEG2StreamIdMap::MapStreamId call.

See Also

  • Error and Success Codes
  • IMpeg2Demultiplexer Interface


IMpeg2Demultiplexer::DeleteOutputPin

The DeleteOutputPin method deletes the specified output pin.

Syntax

HRESULT DeleteOutputPin(
  LPWSTR pszPinName
);

Parameters

pszPinName

[in] The friendly name of the pin as specified when the pin was created in a call to CreateOutputPin.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

Call this method only when you need to delete a pin while keeping the filter alive. When the filter is released, it will perform all necessary cleanup on the output pins.

See Also

  • Error and Success Codes
  • IMpeg2Demultiplexer Interface


IMPEG2PIDMap Interface

This interface is implemented on each output pin of the MPEG-2 Demultiplexer filter (Demux) and is used in transport stream mode only. It is called by applications or other filters to associate the pin with one or more Packet IDs (PID). Once a PID has been mapped, the Demux will deliver all packets with that ID to the output pin. This interface is not exposed when the filter is playing back a file (pull-mode).

For program streams, use the IMPEG2StreamIdMap interface.

Requirements

Include Bdaiface.h.

In addition to the methods inherited from IUnknown, the IMPEG2PIDMap interface exposes the following methods.

Method | Description
MapPID | Maps the packets of a specified PID to the pin.
UnmapPID | Unmaps the PID mapping created in a previous call to MapPID.
EnumPIDMap | Returns a collection of all the currently mapped PIDs on this pin.


IMPEG2PIDMap::MapPID

The MapPID method maps one or more PIDs to the pin.

Syntax

HRESULT MapPID(
  ULONG culPID,
  ULONG* pulPID,
  MEDIA_SAMPLE_CONTENT MediaSampleContent
);

Parameters

culPID

[in] Specifies the number of elements in the pulPID array.

pulPID

[in] Pointer to an array of size culPID, allocated by the caller. Each element in the array contains a PID to be mapped.

MediaSampleContent

[in] Variable of type MEDIA_SAMPLE_CONTENT that specifies the contents of the stream.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

There may be no more than 255 distinct PIDs mapped at any given time. This includes the PIDs that the Demux maps internally for its own use; this number varies depending on the transport stream. This limitation should not present a problem in practice, because applications will typically map no more than a dozen PIDs on any given transport stream.

See Also

  • Error and Success Codes
  • IMPEG2PIDMap Interface


IMPEG2PIDMap::UnmapPID

The UnmapPID method unmaps one or more PIDs.

Syntax

HRESULT UnmapPID(
  ULONG culPID,
  ULONG* pulPID
);

Parameters

culPID

[in] Specifies the number of elements in the pulPID array.

pulPID

[in] Pointer to an array of size culPID, allocated by the caller. Each element in the array contains a PID to be unmapped

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

On output pins for audio and video streams, there will typically be only one PID mapped at any given time. On an output pin such as one delivering the PSI stream to the Transport Information Filter, there may be multiple PIDs mapped to a single pin. Use the IEnumPIDMap methods to determine which PIDs are mapped to the pin, and then fill in the pulPID array with those values.

See Also

  • Error and Success Codes
  • IMPEG2PIDMap Interface


IMPEG2PIDMap::EnumPIDMap

The EnumPIDMap method returns a collection of all the currently mapped PIDs on this pin.

Syntax

HRESULT EnumPIDMap(
  IEnumPIDMap** ppIEnumPIDMap
);

Parameters

ppIEnumPIDMap

[in] Address of a variable that receives an IEnumPIDMap pointer. Use this interface to enumerate the mapped PIDs. The caller must release the interface.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IMPEG2PIDMap Interface


IMPEG2StreamIdMap Interface

This interface is implemented on each output pin of the MPEG-2 Demultiplexer filter (Demux) and is used in program stream mode only. It is called by applications or other filters to associate the pin with a specified Stream ID and to inform the pin whether substream filtering is required on the stream. This interface is not exposed when the filter is playing back a file (pull-mode).

For transport streams, use the IMPEG2PIDMap interface.

In addition to the methods inherited from IUnknown, the IMPEG2StreamIdMap interface exposes the following methods.

Method | Description
MapStreamId | Maps the Stream ID of an elementary stream within an MPEG-2 program stream to a media content type and substream filtering information.
UnmapStreamId | Unmaps the Stream ID mapping created in a previous call to MapStreamId.
EnumStreamIdMap | Returns a collection of all the mapped Stream IDs on this pin.


IMPEG2StreamIdMap::MapStreamId

The MapStreamId method maps the Stream ID of an elementary stream within an MPEG-2 program stream to a media content type and substream filtering information.

Syntax

HRESULT MapStreamId(
  ULONG ulStreamId,
  DWORD MediaSampleContent,
  ULONG ulSubstreamFilterValue,
  int iDataOffset
);

Parameters

ulStreamId

[in] Variable of type ULONG that specifies the stream ID of the PES stream.

MediaSampleContent

[in] Variable of type ULONG that specifies the contents of the stream. Currently the only value supported is MPEG2_PROGRAM_ELEMENTARY_STREAM (defined as 0x00000001 in axextend.idl).

ulSubstreamFilterValue

[in] Variable of type ULONG that specifies which substream within this elementary stream to pass on to the downstream decoder. Only the low-order byte can contain a valid filter value. If iDataOffset = 0, this parameter is ignored.

iDataOffset

[in] Variable of type int that specifies the byte offset into the payload at which the substream begins.

Return Value

Returns S_OK if successful. If the method fails, an error code is returned. If a Stream ID of MEDIA_PROGRAM_STREAM_MAP, MEDIA_PROGRAM_DIRECTORY_PES_PACKET or MEDIA_PROGRAM_PACK_HEADER is attempted, this method returns E_NOTIMPL.

Remarks

The Stream ID mapped by this method is the stream ID in the PES header. Substream filtering is most commonly used to provide multiple channels on a single audio stream.

See Also

  • Error and Success Codes
  • IMPEG2StreamIdMap Interface


IMPEG2StreamIdMap::UnmapStreamId

The UnmapStreamId method unmaps the Stream ID mapping created in a previous call to MapStreamId.

Syntax

HRESULT UnmapStreamId(
  ULONG culStreamId,
  ULONG* pulStreamID
);

Parameters

culStreamId

[in] Variable of type ULONG that specifies the number of elements in the pulStreamID array.

pulStreamID

[in] Array of Stream IDs mapped for this pin.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

There is typically only one stream ID mapped to a given pin, therefore pulStreamID will typically contain a single element.

See Also

  • Error and Success Codes
  • IMPEG2StreamIdMap Interface


IMPEG2StreamIdMap::EnumStreamIdMap

The EnumStreamIdMap method returns a collection of all the mapped Stream IDs on this pin.

Syntax

HRESULT EnumStreamIdMap(
  IEnumStreamIdMap** ppIEnumStreamIdMap
);

Parameters

ppIEnumStreamIdMap

[in] IEnumStreamIdMap interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

Currently, there is only one stream ID mapped to a given pin, therefore this collection will contain a single item.

See Also

  • Error and Success Codes
  • IMPEG2StreamIdMap Interface


IOverlay Interface

The IOverlay interface provides information so that a filter can write directly to video memory while placing the video in the correct window position. It is implemented on the input pin of the video renderer and communicates with an upstream filter (typically a video decompressor) by calling that filter's IOverlayNotify methods to notify it of changes to the video window.

This interface has no relationship to the DirectDraw® overlay capability. The Microsoft video renderer draws data it receives through the IMemInputPin interface, using DirectDraw overlays when available. This interface, used in place of IMemInputPin, is intended to provide notification support for any upstream filter that bypasses the renderer's drawing capabilities, but needs notifications of other display properties.

See the IOverlayNotify reference page for more information on how the IOverlay and IOverlayNotify interfaces work together.

See the IOverlayNotify2 interface for more information on asynchronous notifications of changes to the rendering window.

This interface is implemented on the Microsoft® DirectShow® video renderer filter. It can also be implemented on replacement video renderer filters if desired. If doing so, implement this interface so that filters writing directly to the frame buffer or trying to position an overlay know where to display their video. To implement this interface, the renderer must be prepared to use methods on the IOverlayNotify interface or the IOverlayNotify2 interface of the filter doing the drawing, with notifications of video property changes.

The window-based renderer in DirectShow supports both IMemInputPin and IOverlay interfaces. These two interfaces are mutually exclusive. A filter chooses to use the IOverlay transport by providing a media type during connection that has a subtype of MEDIASUBTYPE_Overlay. After connection, it will be able to get and use successfully the IOverlay interface. If it connects with any other video formats (such as MEDIASUBTYPE_RGB8), trying to call through IOverlay returns VFW_E_NOT_OVERLAY_CONNECTION.

Use the methods on this function from an upstream filter that must control video overlay properties and intends to handle the displaying of the video data itself. This typically is used by hardware video decoders that have an alternate connection to the video hardware.

In addition to the methods inherited from IUnknown, the IOverlay interface exposes the following methods.

Method | Description
GetPalette | Retrieves the current palette.
SetPalette | Sets the palette.
GetDefaultColorKey | Retrieves the default color key.
GetColorKey | Returns the identifier of the currently active color key.
SetColorKey | Changes the color key.
GetWindowHandle | Returns the window handle.
GetClipList | Retrieves the clipping list.
GetVideoPosition | Retrieves the current video source and destination rectangles.
Advise | Sets up an advise link for the overlay events.
Unadvise | Terminates the advise link.


IOverlay::Advise

The Advise method sets up an advise link for the overlay events specified by the dwInterests parameter.

Syntax

HRESULT Advise(
  IOverlayNotify *pOverlayNotify,
  DWORD dwInterests
);

Parameters

pOverlayNotify

[in] Pointer to the notification interface.

dwInterests

[in] Callbacks of interest, which can be any subset of the following events.

Event | Description
ADVISE_NONE | No changes.
ADVISE_CLIPPING | Change in clipping region (synchronized with the window).
ADVISE_PALETTE | Change in palette.
ADVISE_COLORKEY | Change of chroma key value.
ADVISE_POSITION | Change in position of video window (not synchronized with the window).
ADVISE_DISPLAY_CHANGE | Called on WM_DISPLAYCHANGE. The WM_DISPLAYCHANGE message is sent to all windows when the display resolution has changed.
ADVISE_ALL2 | All of the above.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

This method sets up an advise link for the IOverlayNotify interface to receive notifications. If one of these events occurs, the appropriate entry point in the pOverlayNotify parameter passed in is called (IOverlayNotify::OnClipChange, IOverlayNotify::OnColorKeyChange, IOverlayNotify::OnPaletteChange, or IOverlayNotify::OnPositionChange).

Only one advise link can be set on any given IOverlay interface. Trying to set another notification interface on second and subsequent calls returns VFW_E_ADVISE_ALREADY_SET. You can cancel an advise link by using IOverlay::Unadvise.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetClipList

The GetClipList method retrieves the clipping list.

Syntax

HRESULT GetClipList(
  RECT *pSourceRect,
  RECT *pDestinationRect,
  RGNDATA **ppRgnData
);

Parameters

pSourceRect

[out] Pointer to the bounding client rectangle.

pDestinationRect

[in] Pointer to the destination rectangle.

ppRgnData

[out] Address of a pointer to the header and data describing clipping. If successful, the Microsoft® Win32® CoTaskMemFree function should free memory.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

The IOverlay implementation allocates the memory for the clipping rectangles, because it can vary in length. The filter calling this method should free the memory (using CoTaskMemFree) when it is finished with it.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetColorKey

The GetColorKey method retrieves the current color key used for chroma keying.

Syntax

HRESULT GetColorKey(
  COLORKEY *pColorKey
);

Parameters

pColorKey

[out] Pointer to a variable that receives the current color key for chroma keying.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

If you change the color key by using the IOverlay::SetColorKey method, all the advise links receive an IOverlayNotify::OnColorKeyChange callback method with the new color.

If no color key is currently being used, this method returns VFW_E_NO_COLOR_KEY_SET.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetDefaultColorKey

The GetDefaultColorKey method retrieves the default color key used for a chroma key overlay.

Syntax

HRESULT GetDefaultColorKey(
  COLORKEY *pColorKey
);

Parameters

pColorKey

[out] Pointer to a variable that receives the default color key.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

A filter using color keys can get a default color from the video renderer. The default color key can then be installed into the window using IOverlay::SetColorKey. The colors returned through this method vary depending on the current display mode. If the colors are 8-bit palettized, they will be bright system colors (such as magenta). If the display is in a true-color mode, they will be shades of black.

The IOverlay interface is used to ensure that separate instances of the renderer on the same computer get different color keys so that overlays do not conflict.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetPalette

The GetPalette method retrieves the current system palette.

Syntax

HRESULT GetPalette(
  DWORD *pdwColors,
  PALETTEENTRY **ppPalette
);

Parameters

pdwColors

[out] Pointer to a variable that receives the number of colors present.

ppPalette

[out] Address of a variable that receives a pointer to a PALETTEENTRY structure describing the palette.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetVideoPosition

The GetVideoPosition method retrieves the current video source and destination rectangles.

Syntax

HRESULT GetVideoPosition(
  RECT *pSourceRect,
  RECT *pDestinationRect
);

Parameters

pSourceRect

[out] Pointer to a RECT structure that receives the source rectangle.

pDestinationRect

[in] Pointer to to a RECT structure that receives the destination rectangle.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::GetWindowHandle

The GetWindowHandle method retrieves the current window handle.

Syntax

HRESULT GetWindowHandle(
  HWND *pHwnd
);

Parameters

pHwnd

[out] Pointer to a variable that receives the window handle.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::SetColorKey

The SetColorKey method changes the color key.

Syntax

HRESULT SetColorKey(
  COLORKEY *pColorKey
);

Parameters

pColorKey

[in, out] Pointer to the color key value to be set. If successful, the actual color key value selected is copied to this parameter.

Return Value

Returns S_OK if successful, E_POINTER if pColorKey is NULL, or E_INVALIDARG if the value of pColorKey is invalid for the current palette or pixel format.

Remarks

If you change the color key using the SetColorKey method, all the advise links will receive an IOverlayNotify::OnColorKeyChange callback method with the new color.

When using IOverlay::Advise on a palettized display, a filter can either install a color key (using SetColorKey) or install a palette (using IOverlay::SetPalette), but not both. This is because color keys in this mode require a palette to be realized that would conflict with SetPalette. Color keys can be uninstalled by requesting a color key with the CK_NOCOLORKEY flag. Likewise, any palette installed through SetPalette can be uninstalled by calling SetPalette and passing in null parameters (that is, SetPalette(0,NULL)).

Trying to set a palette when a color key is installed returns a VFW_E_PALETTE_SET error. Trying to set a color key when a palette is installed returns VFW_E_COLOR_KEY_SET.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::SetPalette

The SetPalette method sets the palette.

Syntax

HRESULT SetPalette(
  DWORD dwColors,
  PALETTEENTRY *pPalette
);

Parameters

dwColors

[in] Number of colors present.

pPalette

[in] Pointer to colors to use for the palette.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

This method sets a logical palette for the window. The window is not guaranteed to always have the colors requested in the actual system device palette. The Microsoft® Windows® operating system only guarantees those colors when the window is the foreground active window. The current device palette can be obtained by calling IOverlay::GetPalette.

If the device does not have a palette, it returns VFW_E_NO_DISPLAY_PALETTE.

The Overlay Mixer filter returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlay::Unadvise

The Unadvise method terminates the advise link established with the IOverlayNotify interface.

Syntax

HRESULT Unadvise(void);

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

This method terminates the advise link established by using the IOverlay::Advise method. Only one advise link can be maintained at any one time.

See Also

  • Error and Success Codes
  • IOverlay Interface


IOverlayNotify Interface

The IOverlayNotify interface provides an upstream filter, such as a decoder, with notifications of changes to the rendering window. This includes notifications of changes to the palette, color key, and window position, and visible region (clipping) changes.

Most software video decoders let the video renderer draw the decompressed images they produce by passing the media samples to the IMemInputPin interface on the renderer's input pin.

However, some video decoding filters (typically hardware decompression boards) handle the drawing of the images themselves, perhaps by using a VGA connector. These filters do not need to use IMemInputPin, but can instead use the IOverlay interface provided by the renderer input pin. Through this interface, the decoder can be notified when the window position or size changes, or when the current system palette changes in order to install and change color keys and palettes.

Decoders that do their own drawing should implement the IOverlayNotify and IOverlayNotify2 interfaces. The renderer uses this interface to notify the decoder whenever the window size or position changes, the system palette changes, or a different color key is used. The decoder should call the IOverlay::Advise method on the renderer's input pin, to set up the callback. Once the callback is established, the renderer calls the decoder's IOverlayNotify methods when the appropriate events occur. To cancel the callback, use the IOverlay::Unadvise method.

The video renderer is the only filter that calls the methods on this interface. This is done automatically by the default video renderer. If you are writing a replacement video renderer, you will need to use the methods on this interface if your filter supports IOverlay and this interface is passed to your filter in an IOverlay::Advise call.

In addition to the methods inherited from IUnknown, the IOverlayNotify interface exposes the following methods.

Method | Description
OnPaletteChange | Provides notification that the palette of the window has changed.
OnClipChange | Provides notification that the window's visible region has changed.
OnColorKeyChange | Provides notification that the chroma key has changed.
OnPositionChange | Provides notification that the position has changed.


IOverlayNotify::OnClipChange

The OnClipChange method provides notification that the window's visible region has changed. It is essential that any overlay hardware be updated to reflect the change to the visible region before returning from this method.

Syntax

HRESULT OnClipChange(
  const RECT *pSourceRect,
  const RECT *pDestinationRect,
  const RGNDATA *pRgnData
);

Parameters

pSourceRect

[in] Pointer to the region of the video to use.

pDestinationRect

[in] Pointer to the video destination.

pRgnData

[in] Pointer to the clipping information.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

The calls to OnClipChange happen in synchronization with the window. It is called with an empty clip list to freeze the video before the window moves, and then called again when the window has stabilized with the new clip list.

If the window rectangle is all zeros, the window is invisible. As is the case for AVI decoders, the decoder should save the image if it relies on the current image to decode the next one.

See Also

  • Error and Success Codes
  • IOverlayNotify Interface


IOverlayNotify::OnColorKeyChange

The OnColorKeyChange method provides notification that the window's color key has changed.

Syntax

HRESULT OnColorKeyChange(
  const COLORKEY *pColorKey
);

Parameters

pColorKey

[in] Pointer to the new chroma key.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.


IOverlayNotify::OnPaletteChange

The OnPaletteChange method provides notification that the palette of the window has changed.

Syntax

HRESULT OnPaletteChange(
  DWORD dwColors,
  const PALETTEENTRY *pPalette
);

Parameters

dwColors

[in] Number of colors present.

pPalette

[in] Pointer to the array of palette colors.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

Before returning, the filter should copy the array of RGBQUAD values, if necessary.

See Also

  • Error and Success Codes
  • IOverlayNotify Interface


IOverlayNotify::OnPositionChange

The OnPositionChange method provides notification that the position has changed.

Syntax

HRESULT OnPositionChange(
  const RECT *pSourceRect,
  const RECT *pDestinationRect
);

Parameters

pSourceRect

[in] Pointer to the source video rectangle.

pDestinationRect

[in] Pointer to the destination video rectangle. Note that this is not clipped to the visible display area.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

Remarks

This method is a callback intended for use by hardware overlay cards that do not want the expense of synchronous clipping updates, and just want to know when the source or destination video positions change.

Unlike the IOverlayNotify::OnClipChange method, this method is not called in synchronization with the window changing but, rather, at some point after the window has changed (basically in time with WM_SIZE messages received). This is therefore suitable for overlay cards that do not inlay their data to the frame buffer.

See Also

  • Error and Success Codes
  • IOverlayNotify Interface


IOverlayNotify2 Interface

The IOverlayNotify2 interface derives from the IOverlayNotify interface. IOverlayNotify2 gives asynchronous notifications of changes to the rendering window, identifying changes to the exposed window area. The advise link optionally supports this for the purpose of accepting IOverlayNotify2::OnDisplayChange notification.

To get notifications that the exposed window area has changed, decoders that do their own drawing should implement an IOverlayNotify2 interface.

The video renderer is the only filter that calls the method on this interface. This is done automatically by the default video renderer.

In addition to the methods inherited from IOverlayNotify, the IOverlayNotify2 interface exposes the following method.

Method | Description
OnDisplayChange | Provides notification that the exposed window area has changed.


IOverlayNotify2::OnDisplayChange

The OnDisplayChange method provides notification that the exposed window area has changed.

Syntax

HRESULT OnDisplayChange(
  HMONITOR hMonitor
);

Parameters

hMonitor

[in] Handle to the monitor used for displaying the overlay.

Return Value

Returns S_OK if successful. If the method fails, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IOverlayNotify2 Interface


IPersistMediaPropertyBag Interface

The IPersistMediaPropertyBag interface sets and retrieves INFO and DISP chunks in Audio-Video Interleaved (AVI) streams. It uses the IMediaPropertyBag interface to store the chunks as name/value pairs.

The AVI Splitter filter and the WAVE Parser filter support this interface for reading INFO and DISP chunks from an AVI or WAV file. The AVI Mux filter supports the interface for writing these chunks into a file.

IPersistMediaPropertyBag is modeled after, but does not inherit from, the IPersistPropertyBag interface. For more information on IPersistPropertyBag, see the Platform SDK.

In addition to the methods inherited from IUnknown, the IPersistMediaPropertyBag interface exposes the following methods.

Method | Description
InitNew | Initializes a new property bag that will hold the media file header information.
Load | Retrieves the properties from the media file and stores them in the property bag.
Save | Saves the media file properties.


IPersistMediaPropertyBag::InitNew

The InitNew method initializes the object to receive new properties.

Syntax

HRESULT InitNew(void);

Return Value

Returns S_OK.

Remarks

Calling this method on the AVI Mux filter clears any properties that were previously set using the Load method.

Calling this method on the AVI Splitter filter or the WAVE Parser filter has no effect.

See Also

  • Error and Success Codes
  • IPersistMediaPropertyBag Interface


IPersistMediaPropertyBag::Load

The Load method loads properties from the media property bag into the filter.

Syntax

HRESULT Load(
  IMediaPropertyBag *pPropBag,
  IErrorLog *pErrorLog
);

Parameters

pPropBag

[in] Pointer to the IMediaPropertyBag interface of a media property bag created by the caller.

pErrorLog

[in] Reserved. Set the value to NULL.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
STG_E_ACCESSDENIED | Access denied.
VFW_E_WRONG_STATE | Filter graph is not in a stopped state.

Remarks

Call this method on the AVI Mux filter to write the properties into the AVI stream. The following code example writes an IART (author name) INFO chunk to the stream.

IPersistMediaPropertyBag *pPersist = NULL;
IMediaPropertyBag *pBag = NULL;
VARIANT val;

// Query the AVI Mux filter for IPersistMediaPropertyBag (not shown).

CoCreateInstance(CLSID_MediaPropertyBag, NULL, CLSCTX_INPROC,
        IID_IMediaPropertyBag, (LPVOID *)&pBag);

val.vt = VT_BSTR;
val.bstrVal = SysAllocString(OLESTR("Author Name"));
pBag->Write(OLESTR("INFO/IART"), &val);
pPersist->Load(pBag, NULL);
VariantClear(&val);

The AVI Splitter filter and the WAVE Parser do not support this method.

See Also

  • Error and Success Codes
  • IPersistMediaPropertyBag Interface


IPersistMediaPropertyBag::Save

The Save method saves properties from the filter into the media property bag.

Syntax

HRESULT Save(
  IMediaPropertyBag *pPropBag,
  BOOL fClearDirty,
  BOOL fSaveAllProperties
);

Parameters

pPropBag

[in] Pointer to the IMediaPropertyBag interface of a media property bag created by the caller.

fClearDirty

[in] Reserved. Can be any value.

fSaveAllProperties

[in] Reserved. Can be any value.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
HRESULT_FROM_WIN32(ERROR_INVALID_DATA) | Invalid data.

Remarks

If you call this method on the AVI Splitter filter or the WAVE Parser, the filter reads any INFO and DISP chunks from the file and stores them in the media property bag. You can use the IMediaPropertyBag::Read or IMediaPropertyBag::EnumProperty method to retrieve the chunks.

The AVI Muxfilter does not implement this method.

See Also

  • Error and Success Codes
  • IPersistMediaPropertyBag Interface


IPin Interface

This interface is exposed by all input and output pins.

The filter graph manager uses this interface to connect pins and perform flushing operations. Applications can use this interface to query the pin for information. Applications should never call IPin methods that change a pin's state, such as Connect, Disconnect, BeginFlush, or EndFlush. To connect pins, an application must use the methods in IGraphBuilder.

Filter developers: The CBasePin, CBaseInputPin, and CBaseOutputPin classes implement this interface. Other base classes derive from these three classes.

In addition to the methods inherited from IUnknown, the IPin interface exposes the following methods.

Method | Description
Connect | Connects the pin to another pin.
ReceiveConnection | Accepts a connection from another pin.
Disconnect | Breaks the current pin connection.
ConnectedTo | Retrieves the pin connected to this pin.
ConnectionMediaType | Retrieves the media type for the current pin connection.
QueryPinInfo | Retrieves information about the pin, such as the name, the owning filter, and the direction.
QueryId | Retrieves the pin identifier.
QueryAccept | Determines whether the pin accepts a specified media type.
EnumMediaTypes | Enumerates the pin's preferred media types.
QueryInternalConnections | Retrieves the pins that are connected internally to this pin (within the filter).
EndOfStream | Notifies the pin that no additional data is expected.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
QueryDirection | Retrieves the direction of the pin (input or output).


IPin::BeginFlush

The BeginFlush method begins a flush operation.

Applications should not call this method. This method is called by other filters, to flush data from the graph.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | The pin is an output pin.

Remarks

Call this method only on input pins. Output pins return E_UNEXPECTED.

In a flush operation, a filter discards whatever data it was processing. It rejects new data until the flush is completed. The flush is completed when the upstream pin calls the IPin::EndFlush method. Flushing enables the filter graph to be more responsive when events alter the normal data flow. For example, flushing occurs during a seek.

When BeginFlush is called, the filter performs the following steps:

  1. Passes the IPin::BeginFlush call downstream.
  2. Sets an internal flag that causes all data-streaming methods to fail, such as IMemInputPin::Receive.
  3. Returns from any blocked calls to the Receive method.

When the BeginFlush notification reaches a renderer filter, the renderer frees any samples that it holds.

After BeginFlush is called, the pin rejects all samples from upstream, with a return value of S_FALSE, until the IPin::EndFlush method is called.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::Connect

The Connect method connects the pin to another pin.

Applications should not call this method. Use IGraphBuilder methods instead. This method is called by the Filter Graph Manager to connect pins.

Syntax

HRESULT Connect(
  IPin *pReceivePin,
  const AM_MEDIA_TYPE *pmt
);

Parameters

pReceivePin

[in] Pointer to the receiving pin's IPin interface.

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection. Can be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NO_ACCEPTABLE_TYPES | Cannot find an acceptable media type.
VFW_E_NO_TRANSPORT | Pins cannot agree on a transport, or there is no allocator for the connection.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pmt parameter can be NULL. It can also specify a partial media type, with a value of GUID_NULL for the major type, subtype, or format.

This method verifies that the connection is possible. If the pin rejects the connection, the method fails. The connecting pin proposes media types by calling IPin::ReceiveConnection on the receiving pin.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::ConnectedTo

The ConnectedTo method retrieves a pointer to the connected pin, if any.

Syntax

HRESULT ConnectedTo(
  IPin **ppPin
);

Parameters

ppPin

[out] Address of a variable that receives a pointer to the IPin interface of the other pin. Cannot be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release it when you are done.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::ConnectionMediaType

The ConnectionMediaType method retrieves the media type for the current pin connection, if any.

Syntax

HRESULT ConnectionMediaType(
  AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[out] Pointer to an AM_MEDIA_TYPE structure that receives the media type.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the pin is connected, this method copies the media type into the AM_MEDIA_TYPE structure specified by pmt. The caller must free the media type's format block. You can use the Microsoft® Win32® CoTaskMemFree function, or the FreeMediaType helper function.

If the pin is not connected, this method clears the media type specified by pmt and returns an error code.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::Disconnect

The Disconnect method breaks the current pin connection.

The Filter Graph Manager calls this method when it disconnects two filters. Applications and filters should not call this method. Instead, call the IFilterGraph::Disconnect method on the Filter Graph Manager.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active.

Remarks

This method fails if the filter is paused or running. If the pin supports the IPinConnection interface, call IPinConnection::DynamicDisconnect to disconnect the pin when the filter is paused or running.

This method does not disconnect the other pin in the pin connection.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::EndFlush

The EndFlush method ends a flush operation.

Applications should not call this method. This method is called by other filters, to flush data from the graph.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | The pin is an output pin.

Remarks

Call this method only on input pins. Output pins return E_UNEXPECTED.

When this method is called, the filter performs the following actions:

  1. Waits for all queued samples to be discarded.
  2. Frees any buffered data, including any pending end-of-stream notifications.
  3. Clears any pending EC_COMPLETE notifications.
  4. Calls EndFlush downstream.

When the method returns, the pin can accept new samples.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected, until a new run command is issued to the filter.

Applications should not call this method. This method is called by other filters to signal the end of the stream.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | The pin is an output pin.

Remarks

Call this method only on input pins. Output pins return E_UNEXPECTED.

This method sends an end-of-stream notification to the pin. The pin delivers the notification downstream. It must serialize end-of-stream notifications with IMemInputPin::Receive calls. If the pin queues media samples for delivery, it should queue end-of-stream notifications as well. The IPin::BeginFlush method flushes any queued end-of-stream notifications.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::EnumMediaTypes

The EnumMediaTypes method enumerates the pin's preferred media types.

Syntax

HRESULT EnumMediaTypes(
  IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

[out] Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The IEnumMediaTypes interface works like a standard COM enumerator. For more information, see Enumerating Objects in a Filter Graph. If the method succeeds, the IEnumMediaTypes interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::NewSegment

The NewSegment method notifies the pin that media samples received after this call are grouped as a segment, with a common start time, stop time, and rate.

Applications should not call this method. This method is called by other filters.

Syntax

HRESULT NewSegment(
  REFERENCE_TIME tStart,
  REFERENCE_TIME tStop,
  double dRate
);

Parameters

tStart

Start time of the segment, relative to the original source, in 100-nanosecond units.

tStop

End time of the segment, relative to the original source, in 100-nanosecond units.

dRate

Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

A source filter (or parser filter) calls this method at the start of each new stream and after each seek operation. It calls the method on the input pin of the downstream filter, after delivering the previous batch of data and before calling IMemInputPin::Receive with any new data. The downstream filter propagates the NewSegment call downstream.

Filters can use segment information to process samples. For example, with some formats it is impossible to reconstruct a delta frame without the next key frame. Therefore, if the stop time occurs on a delta frame, the source filter must send some additional frames. The decoder filter determines the final frame based on the segment information. The segment rate is used to render continuous data sources, such as audio data. For example, the audio renderer uses the sampling rate and the segment rate to render the audio data correctly.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::QueryAccept

The QueryAccept method determines whether the pin accepts a specified media type.

Syntax

HRESULT QueryAccept(
  const AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns one of the following values:

Value | Description
S_FALSE | The pin rejects the media type.
S_OK | The pin accepts the media type.

Remarks

A return value of S_OK indicates that the pin will accept the media type, either on the next sample, or after a pin reconnection. The implementation should take into account the current state of the filter, including connections on other pins, and any properties that can be set on the filter.

Any other return value, including S_FALSE, means that the pin rejects the media type. Therefore, test for S_OK explicitly; do not use the SUCCEEDED macro.

If the filter is running, a return value of S_OK is ambiguous. The pin might accept a format change on the next media sample, without reconnecting; or it might need to reconnect. If the pin supports the IPinConnection interface, call the IPinConnection::DynamicQueryAccept method, which specifically tests whether the pin can accept the new type without reconnecting.

See Also

  • Data Flow in the Filter Graph
  • Dynamic Format Changes
  • Error and Success Codes
  • IPin Interface


IPin::QueryDirection

The QueryDirection method retrieves the direction of the pin (input or output).

Syntax

HRESULT QueryDirection(
  PIN_DIRECTION *pPinDir
);

Parameters

pPinDir

[out] Pointer to a variable that receives a member of the PIN_DIRECTION enumerated type.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.


IPin::QueryId

The QueryId method retrieves an identifier for the pin.

Syntax

HRESULT QueryId(
  LPWSTR *Id
);

Parameters

Id

[out] Address of a variable that receives a string containing the pin identifier.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.

Remarks

This method supports graph persistence. Use this method to save a pin's state, and the IBaseFilter::FindPin method to restore the state. The pin's identifier string is defined by the filter implementation. The identifier must be unique within the filter.

Note The pin identifier is not necessarily the same as the pin name that the QueryPinInfo method returns.

The filter allocates the returned string using the Microsoft® Win32® CoTaskMemAlloc function. The caller must free it using CoTaskMemFree.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::QueryInternalConnections

The QueryInternalConnections method retrieves the pins that are connected internally to this pin (within the filter).

Syntax

HRESULT QueryInternalConnections(
  IPin **apPin,
  ULONG *nPin
);

Parameters

apPin

[out] Address of an array of IPin pointers.

nPin

[in, out] On input, specifies the size of the array. When the method returns, the value is set to the number of pointers returned in the array.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Insufficient array size.
S_OK | Success.
E_FAIL | Failure.
E_NOTIMPL | Not implemented.

Remarks

On some filters, input pins correspond to particular output pins. For each pin, this method fills an array with pointers to the corresponding pins. If every input pin provides data for every output pin, the pin returns E_NOTIMPL.

If the method succeeds and returns a value of *nPin greater than zero, the array contains pointers to IPin interfaces. Be sure to release each interface pointer when you are done.


IPin::QueryPinInfo

The QueryPinInfo method retrieves information about the pin.

Syntax

HRESULT QueryPinInfo(
  PIN_INFO *pInfo
);

Parameters

pInfo

[out] Pointer to a PIN_INFO structure that receives the pin information.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.

Remarks

When the method returns, if the pFilter member of the PIN_INFO structure is non-NULL, it has an outstanding reference count. Be sure to release the interface when you are done.

See Also

  • Data Flow in the Filter Graph
  • Error and Success Codes
  • IPin Interface


IPin::ReceiveConnection

The ReceiveConnection method accepts a connection from another pin.

Applications should not call this method. This method is called by other filters during the pin connection process.

Syntax

HRESULT ReceiveConnection(
  IPin *pConnector,
  const AM_MEDIA_TYPE *pmt
);

Parameters

pConnector

[in] Pointer to the connecting pin's IPin interface.

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NOT_STOPPED | Cannot connect while filter is active.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

When an output pin connects, it calls this method on the input pin. The input pin should verify that the specified media type is acceptable. It may also need to check for other connection requirements specific to the owning filter. If the connection is suitable, the input pin should return S_OK, and also do the following:

  • store the media type, and return the same type in the IPin::ConnectionMediaType method.
  • store the output pin's IPin interface (pConnector), and return this pointer in the IPin::ConnectedTo method

If the connection is unsuitable, the pin should return an error code.

The CBasePin class implements the basic framework for this method, including storing the media type and IPin pointers.

See Also

  • Error and Success Codes
  • How Filters Connect
  • IPin Interface


IPinConnection Interface

This interface provides methods for reconnecting an input pin while the filter is still running. The Filter Graph Manager calls methods on this interface when it performs dynamic reconnections (see the IGraphConfig interface). Applications might also use this interface to perform dynamic pin reconnections.

Filter developers: Implement this interface on any input pin that allows dynamic reconnection or dynamic changes in format.

In addition to the methods inherited from IUnknown, the IPinConnection interface exposes the following methods.

Method | Description
DynamicQueryAccept | Queries whether the pin can accept the specified media type while the graph is running with the current connection to this pin.
NotifyEndOfStream | Requests notification from the pin when the next end-of-stream condition occurs.
IsEndPin | Indicates whether a reconnection search should end at this pin.
DynamicDisconnect | Disconnects the pin when the filter is running.

See Also

  • Dynamic Graph Building
  • Dynamic Reconnection


IPinConnection::DynamicDisconnect

The DynamicDisconnect method disconnects the pin when the filter is active (paused or running). Call this method instead of IPin::Disconnect to disconnect a pin when the graph is running or paused.

The caller must ensure that no data is flowing to the pin when it calls this method. Call the IPinFlowControl::Block method on an upstream pin to block the data flow, or use some other mechanism to make sure that no samples are delivered until this pin is reconnected.

Syntax

HRESULT DynamicDisconnect(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The pin is already disconnected.
S_OK | Success.

See Also

  • Dynamic Reconnection
  • Error and Success Codes
  • IPinConnection Interface


IPinConnection::DynamicQueryAccept

The DynamicQueryAccept method queries whether the pin can accept the specified media type while the graph is running with the current connection to this pin.

Syntax

HRESULT DynamicQueryAccept(
  const AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Media type is acceptable.
VFW_E_TYPE_NOT_ACCEPTED | Media type is not acceptable.

Remarks

If this method succeeds, the pin can accept the media type on the next sample or in a call to IPin::ReceiveConnection.

An application or filter can call this method to determine whether the filter graph must be reconfigured. If the pin can accept the specified media type, there is no need to reconfigure the graph.

Although the IPin::QueryAccept method also determines whether a pin can accept a format type, it does not guarantee that the pin can switch to that format while the filter is running. If you need to switch formats while the filter is running, call DynamicQueryAccept instead.

See Also

  • Dynamic Format Changes
  • Error and Success Codes
  • IPinConnection Interface


IPinConnection::IsEndPin

The IsEndPin method indicates whether a reconnection search should end at this pin.

Syntax

HRESULT IsEndPin(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Media type is not acceptable.
S_OK | Media type is acceptable.

Remarks

A filter or application can call this method to determine whether the pin is a candidate for dynamic reconnection.

Generally, a sink filter or a filter that splits or merges data should return S_OK. Other filters (for example, simple transform filters) should return S_FALSE.

See Also

  • Dynamic Reconnection
  • Error and Success Codes
  • IPinConnection Interface


IPinConnection::NotifyEndOfStream

The NotifyEndOfStream method requests notification from the pin when the next end-of-stream condition occurs.

Syntax

HRESULT NotifyEndOfStream(
  HANDLE hNotifyEvent
);

Parameters

hNotifyEvent

[in] Handle to an event object that the pin will signal.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Event handle was NULL, but there was no existing event handle to reset.
S_OK | Event handle was set. (If event handle was NULL, event notification was canceled.)

Remarks

This method enables the caller to push data through a portion of the filter graph ending with this pin.

For example, suppose the caller is pushing data from an output pin called "A" on one filter, to an input pin called "B" on another filter, possibly with intermediate filters connecting them. The following sequence of events would take place.

  1. The caller blocks the data flow at pin A.
  2. It calls NotifyEndOfStream on pin B.
  3. It calls IPin::EndOfStream on the input pin connected to pin A.
  4. As the remaining data travels downstream through any intermediate filters, those filters propagate the end-of-stream notification.
  5. When pin B receives the end-of-stream notification, it signals the event given in the hNotifyEvent parameter. At that point, the caller can safely reconfigure the graph between pin A and pin B.

Because the purpose of this method is to enable the caller to rebuild the graph dynamically and then restart the connection, the end-of-stream notification does not represent the actual end of the stream. Therefore, pin B does not propagate the end-of-stream condition or signal EC_COMPLETE. This is an exception to the usual rules for data flow in the filter graph.

It is the caller's responsibility to cancel notification by calling this method again with a NULL event handle.

The filter graph calls this method inside the IGraphConfig::Reconnect method. If an application or filter does any specialized dynamic reconfiguration to the graph (using the IGraphConfig::Reconfigure method), it might call this method first in order to push data through the portion of the graph that is being reconfigured.

See Also

  • Dynamic Reconnection
  • Error and Success Codes
  • IPinConnection Interface


IPinFlowControl Interface

Blocks data flow from an active output pin. This interface is exposed by output pins that can reconnect dynamically. Use this interface to start a dynamic reconnection within the filter graph. For more information, see Dynamic Graph Building.

Filter developers: Parser and capture filters that support dynamic reconnection should support this interface on their output pins. Generally, other types of filters do not need to implement this interface.

In addition to the methods inherited from IUnknown, the IPinFlowControl interface exposes the following method.

Method | Description
Block | Blocks or unblocks the flow of data from the pin.


IPinFlowControl::Block

The Block method blocks or unblocks the flow of data from the pin.

Syntax

HRESULT Block(
  DWORD dwBlockFlags,
  HANDLE hEvent
);

Parameters

dwBlockFlags

[in] Flag that indicates whether to block or unblock the pin. Must be one of the following values:

  • Zero: Unblock data flow from the pin.
  • AM_PIN_FLOW_CONTROL_BLOCK: Block data flow from the pin.

hEvent

[in] Handle to an event object, or NULL. If this parameter is non-NULL, the method is asynchronous and returns immediately. The event is signaled when the operation completes. If this parameter is NULL, the method is synchronous and does not complete until the pin is blocked. If dwBlockFlags is zero, this parameter must be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Pin is already unblocked.
S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

This method can be synchronous or asynchronous:

  • To call it asynchronously, use the CreateEvent function to create an event object. Pass the event handle in the hEvent parameter. The method returns immediately and signals the event when the operation has completed. Call a wait function such as WaitForSingleObject to wait for the event.
  • To call this method synchronously, set the hEvent parameter to NULL. The method blocks until it completes. The method might not complete until the pin is ready to deliver a sample. If the filter is paused, the method might block indefinitely. Therefore, you should not call this method synchronously from your main application thread.

See Also

  • Dynamic Reconnection
  • Error and Success Codes
  • IPinFlowControl Interface


IQualityControl Interface

The IQualityControl interface provides support for quality control. An object exposes this interface if it can generate or receive quality-control messages. This includes renderer filters (which typically generate quality control messages), pins (which receive them), and external quality managers (which also receive them).

A renderer filter generates a quality-control message by calling the IQualityControl::Notify method on the output pin of the upstream filter. The upstream filter either handles the message or passes it upstream.

An application can implement its own quality-control manager. Call IQualityControl::SetSink on the renderer to designate the quality-control manager as the recipient for quality-control messages. Calling this method overrides the default handling of quality-control messages.

However, most applications will not implement their own quality-control managers; and aside from this special case, applications typically do not use this interface. For more information, see Quality-Control Management

In addition to the methods inherited from IUnknown, the IQualityControl interface exposes the following methods.

Method | Description
Notify | Notifies the recipient that a quality change is requested.
SetSink | Sets the IQualityControl object that will receive quality messages.


IQualityControl::Notify

The Notify method notifies the filter that a quality change is requested.

Syntax

HRESULT Notify(
  IBaseFilter *pSelf,
  Quality q
);

Parameters

pSelf

[in] Pointer to the filter that is sending the quality notification.

q

[in] Quality notification structure.

Return Value

Returns S_OK if the method succeeds; otherwise, returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IQualityControl Interface


IQualityControl::SetSink

The SetSink method sets the IQualityControl object that will receive quality messages.

Syntax

HRESULT SetSink(
  IQualityControl *piqc
);

Parameters

piqc

Pointer to the IQualityControl object to which the notifications should be sent.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The filter that receives a call to this method should record the piqc but should not add a reference count to it. The object pointed to will be a quality manager and will be a part of the filter graph (for example, a plug-in distributor). Adding a reference count to this could cause circular reference problems.

The reference to the object specified in piqc is guaranteed to be valid until this method is called with a null value.

See Also

  • Error and Success Codes
  • IQualityControl Interface


IQualProp Interface

The IQualProp interface provides methods for retrieving performance information from video renderers. The values returned through the interface are reset each time the filter is stopped. The Video Renderer filter and the Full Screen Renderer filter expose this interface.

Applications can use this interface to retrieve video performance information.

In addition to the methods inherited from IUnknown, the IQualProp interface exposes the following methods.

Method | Description
get_AvgFrameRate | Retrieves the average frame rate achieved.
get_AvgSyncOffset | Retrieves the average time difference between when a frame was due for rendering and when rendering actually began (this is returned as a value in milliseconds).
get_DevSyncOffset | Retrieves the average time difference between when a frame was due for rendering and when rendering actually began (this is returned as a standard deviation).
get_FramesDrawn | Retrieves the number of frames drawn since streaming started.
get_FramesDroppedInRenderer | Retrieves the number of frames dropped by the renderer.
get_Jitter | Expresses the average time between successive frames delivered to the video renderer.


IQualProp::get_AvgFrameRate

The get_AvgFrameRate method retrieves the actual average frame rate since streaming started.

Syntax

HRESULT get_AvgFrameRate(
  int *piAvgFrameRate
) PURE;

Parameters

piAvgFrameRate

Pointer to a variable that receives the actual number of frames per second, multiplied by 100. For example, an average frame rate of 30 frames per second will be represented as 3000.

Return Value

Returns an HRESULT value.

Remarks

The actual frame rate during playback might be less than the authored frame rate. For more information on actual versus authored frame rates, see the Remarks section for the VIDEOINFOHEADER structure.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQualProp::get_AvgSyncOffset

The get_AvgSyncOffset method retrieves the average time difference between when the video frames should have been displayed and when they actually were.

Syntax

HRESULT get_AvgSyncOffset(
  int *piAvg
);

Parameters

piAvg

Pointer to the time difference, expressed in milliseconds.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQualProp::get_DevSyncOffset

The get_DevSyncOffset method retrieves the average time difference between when the video frames should have been displayed and when they actually were. This method is the same as the IQualProp::get_AvgSyncOffset method except that the value returned is calculated as a standard deviation rather than as a simple average.

Syntax

HRESULT get_DevSyncOffset(
  int *piDev
);

Parameters

piDev

Pointer to a value denoting the accuracy of the video frames displayed.

Return Value

Returns an HRESULT value.

Remarks

When playing video from networks, the presentation can often be disrupted by network glitches. For this reason, expressing the accuracy of video frames by a simple average is inappropriate. Looking at a standard deviation provides a better idea of the overall accuracy.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQualProp::get_FramesDrawn

The get_FramesDrawn method retrieves the number of frames actually drawn since streaming started.

Syntax

HRESULT get_FramesDrawn(
  int *pcFramesDrawn
);

Parameters

pcFramesDrawn

Pointer to the number of frames drawn since streaming started.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQualProp::get_FramesDroppedInRenderer

The get_FramesDroppedInRenderer method retrieves the number of frames dropped by the renderer.

Syntax

HRESULT get_FramesDroppedInRenderer(
  int *pcFrames
);

Parameters

pcFrames

Pointer to the number of frames dropped by the renderer.

Return Value

Returns an HRESULT value.

Remarks

The property page uses this method to retrieve data from the renderer.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQualProp::get_Jitter

The get_Jitter method expresses the average time between successive frames delivered to the video renderer.

Syntax

HRESULT get_Jitter(
  int *piJitter
);

Parameters

piJitter

Pointer to the standard deviation of the interframe time, in milliseconds.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IQualProp Interface


IQueueCommand Interface

The IQueueCommand interface queues a command for processing at a designated time. The Filter Graph Manager exposes this interface. Applications can use it to queue graph-control commands in advance.

The methods in IQueueCommand are modeled after the IDispatch::InvokeAt method. The application specifies an interface, a method on the interface, parameters to the method, and a reference time. The Filter Graph Manager queues this information and then invokes the method at the specified time. The requested interface must inherit IDispatch and must be exposed by the Filter Graph Manager. Examples include IMediaControl, IMediaEventEx, and IMediaPosition.

When the command is queued, the filter graph manager returns a pointer to the IDeferredCommand interface. The application can use this interface to cancel or modify the command.

Note The two methods in IQueueCommand refer to stream time and presentation time, respectively. In the context of the Filter Graph Manager, stream time and presentation time are identical, so there is no functional difference between the two methods. Other objects could implement IQueueCommand differently. For more information about stream time and presentation time, see Time and Clocks in DirectShow.

In addition to the methods inherited from IUnknown, the IQueueCommand interface exposes the following methods.

Method | Description
InvokeAtPresentationTime | Queues a method to be invoked at the specified presentation time.
InvokeAtStreamTime | Queues a method to be invoked at the specified stream time.


IQueueCommand::InvokeAtPresentationTime

The InvokeAtPresentationTime method queues a method to be invoked at the specified presentation time.

Syntax

HRESULT InvokeAtPresentationTime(
  IDeferredCommand **pCmd,
  REFTIME time,
  GUID *iid,
  long dispidMember,
  short wFlags,
  long cArgs,
  VARIANT *pDispParams,
  VARIANT *pvarResult,
  short *puArgErr
);

Parameters

pCmd

[out] Address of a variable that receives an IDeferredCommand interface pointer.

time

[in] Time at which to invoke the command.

iid

[in] Pointer to the interface identifier (IID) of interface.

dispidMember

[in] Dispatch identifier (DISPID) of a method or property on the interface. Equivalent to the dispIdMember parameter of the IDispatch::InvokeAt method.

wFlags

[in] Flags describing the context of the call. Equivalent to the wFlags parameter of the IDispatch::InvokeAt method.

cArgs

[in] Number of arguments in pDispParams. Equivalent to the cArgs member of the DISPPARAMS structure.

pDispParams

[in] Pointer to an array that contains the arguments. Equivalent to the rgvarg member of the DISPPARAMS structure.

pvarResult

[in, out] Pointer a VARIANT that receives the result. Equivalent to the pVarResult parameter of the IDispatch::InvokeAt method.

puArgErr

[out] Pointer to a variable that receives the index of the first argument that has an error. Equivalent to the puArgErr parameter of the IDispatch::InvokeAt method.

Return Value

Returns an HRESULT value.

Remarks

Use the IDispatch::GetIDsOfNames method to retrieve the DISPID for the dispidMember parameter.

For a code example, see IQueueCommand::InvokeAtStreamTime.

See Also

  • Error and Success Codes
  • IQueueCommand Interface


IQueueCommand::InvokeAtStreamTime

The InvokeAtStreamTime method queues a method or property change for execution at a specified stream time (that is, presentation time relative to the current stream time offset).

Syntax

HRESULT InvokeAtStreamTime(
  IDeferredCommand **pCmd,
  REFTIME time,
  GUID *iid,
  long dispidMember,
  short wFlags,
  long cArgs,
  VARIANT *pDispParams,
  VARIANT *pvarResult,
  short *puArgErr
);

Parameters

pCmd

[out] Address of a variable that receives an IDeferredCommand interface pointer.

time

[in] Time at which to invoke the command.

iid

[in] Pointer to the interface identifier (IID) of interface.

dispidMember

[in] Dispatch identifier (DISPID) of a method or property on the interface. Equivalent to the dispIdMember parameter of the IDispatch::InvokeAt method.

wFlags

[in] Flags describing the context of the call. Equivalent to the wFlags parameter of the IDispatch::InvokeAt method.

cArgs

[in] Number of arguments in pDispParams. Equivalent to the cArgs member of the DISPPARAMS structure.

pDispParams

[in] Pointer to an array that contains the arguments. Equivalent to the rgvarg member of the DISPPARAMS structure.

pvarResult

[in, out] Pointer to a VARIANT that receives the result. Equivalent to the pVarResult parameter of the IDispatch::InvokeAt method.

puArgErr

[out] Pointer to a variable that receives the index of the first argument that has an error. Equivalent to the puArgErr parameter of the IDispatch::InvokeAt method.

Return Value

Returns an HRESULT value.

Remarks

Use the IDispatch::GetIDsOfNames method to retrieve the DISPID for the dispidMember parameter.

Example Code

The following example queues an IMediaControl::Stop command for 3.0 seconds.

IQueueCommand *pQ = 0;
IMediaControl *pControl = 0;

// Query for IQueueCommand.
pGraph->QueryInterface(IID_IQueueCommand, reinterpret_cast<void**>(&pQ));

// Query for IMediaControl.
pGraph->QueryInterface(IID_IMediaControl, reinterpret_cast<void**>(&pControl));

// Find the DISPID of the IMediaControl::Stop method.
OLECHAR *szMethod = OLESTR("Stop");

long dispid;
hr = pControl->GetIDsOfNames(IID_NULL, &szMethod, 1, 0, &dispid);

// Invoke the command.
IDeferredCommand *pCmd = 0;
hr = pQ->InvokeAtPresentationTime(&pCmd, 3.0,
    const_cast<GUID*>(&IID_IMediaControl), dispid, DISPATCH_METHOD,
    0, 0, 0, 0);
if (SUCCEEDED(hr))
{
    pControl->Run();
    pCmd->Release();
}

See Also

  • Error and Success Codes
  • IQueueCommand Interface


IRegisterServiceProvider Interface

The IRegisterServiceProvider interface registers an object as a service. For more information, see IRegisterServiceProvider::RegisterService.

In addition to the methods inherited from IUnknown, the IRegisterServiceProvider interface exposes the following method.

Method | Description
RegisterService | Registers an object as a service.


IRegisterServiceProvider::RegisterService

The RegisterService method registers an object as a service.

Syntax

HRESULT RegisterService(
  REFGUID guidService,
  IUnknown *pUnkObject
);

Parameters

guidService

[in] Service identifier (SID) of the service.

pUnkObject

[in] Pointer to the IUnknown interface of the service object, or NULL to unregister the service.

Return Value

Returns an HRESULT value.

Remarks

A service is an interface that a client discovers through the COM IServiceProvider::QueryService method, instead of through the usual IUnknown::QueryInterface method. The difference between the two methods is that QueryInterface returns an interface on the original object, whereas QueryService may return an interface on another object. (More precisely, QueryInterface guarantees that you can query the original interface and the returned interface for IUnknown, and you will get back identical pointers. QueryService does not have this guarantee.)

The RegisterService method enables you to register a service with the Filter Graph Manager. Other objects can then use the IServiceProvider interface to retrieve your object. This facilitates communication between separate COM objects, using the Filter Graph Manager as the central communication point.

A service is identified by a GUID, called the service identifier (SID). One service can support multiple interfaces. To register the service, call RegisterService, as shown in the following code:

DEFINE_GUID(SID_MyService, ....);
IRegisterServiceProvider *pRSP;
hr = pGraph->QueryInterface(IID_IRegisterServiceProvider, (void**)&pRSP);
if (SUCCEEDED(hr))
{
    IUnknown pServiceObj;
    MyCreateServiceHelper(SID_MyService, &pServiceObj);
    pRSP->RegisterService(SID_MyService, pServiceObj);
    pRSP->Release();
    pServiceObj->Release();
}

This example assumes that MyCreateServiceHelper is a helper function that creates the service object. A client could get a pointer to the service object by calling IServiceProvider::QueryService:

IServiceProvider *pSP;
hr = pGraph->QueryInterface(IID_IServiceProvider, (void**)&pSP);
if (SUCCEEDED(hr))
{
    ISomeInterface *pService;
    hr = pSP->QueryService(SID_MyService, IID_ISomeInterface, (void**)&pService);
    pSP->Release();
    if (SUCCEEDED(hr))
    {
        pService->SomeMethod();
        pService->Release();
    }
};

To unregister the service, call RegisterService with a NULL pointer in the second parameter:

pRSP->RegisterService(SID_MyService, NULL);

When the Filter Graph Manager is released, it unregisters all services.

The Filter Graph Manager keeps a reference count on the service object until the service is unregistered. To prevent circular reference counts, the service object should not hold a reference count on the Filter Graph Manager. For example, you cannot use the service object's destructor method to unregister the service, because as long as the service holds a reference count on the Filter Graph Manager, the destructor will never be called. One solution is to create a separate object that registers and unregisters the service. Or, you can simply release the service object after you register it and let the Filter Graph Manager control its lifetime.

See Also

  • Error and Success Codes
  • IRegisterServiceProvider Interface


IResourceConsumer Interface

The IResourceConsumer interface provides a callback mechanism for objects using the IResourceManager interface.

An object must implement IResourceConsumer if it uses the IResourceManager interface to request resources from the filter graph manager. The filter graph manager calls methods on IResourceConsumer to notify the object when a resource becomes available, or when the object should release a resource that it acquired.

Applications typically do not use or implement this interface.

In addition to the methods inherited from IUnknown, the IResourceConsumer interface exposes the following methods.

Method | Description
AcquireResource | Notifies the resource consumer that a resource might be acquired.
ReleaseResource | Requests the resource consumer to release the specified resource.

See Also

  • IResourceConsumer Interface


IResourceConsumer::AcquireResource

The AcquireResource method notifies the resource consumer that a resource might be acquired.

Syntax

HRESULT AcquireResource(
  LONG idResource
);

Parameters

idResource

[in] Resource identifier of the resource to be acquired.

Return Value

Returns an HRESULT value. Possible values include the following:

Return code | Description
S_OK | Consumer has successfully acquired the resource.
S_FALSE | Consumer has not acquired the resource but will use IResourceManager::NotifyAcquire when it does.
VFW_S_RESOURCE_NOT_NEEDED | Consumer no longer needs the resource.

The method may return some other error code, if the consumer fails to acquire the resource.

See Also

  • Error and Success Codes
  • IResourceConsumer Interface


IResourceConsumer::ReleaseResource

The ReleaseResource method requests the resource consumer to release the specified resource.

Syntax

HRESULT ReleaseResource(
  LONG idResource
);

Parameters

idResource

[in] Resource identifier to be released.

Return Value

Returns S_OK if the consumer has released it and requires it again when it becomes available, or S_FALSE if the consumer has not released it but will use IResourceManager::NotifyRelease when it does.

See Also

  • Error and Success Codes
  • IResourceConsumer Interface


IResourceManager Interface

The IResourceManager interface resolves contentions for system resources.

The filter graph manager exposes this interface. Filters can use this interface to request resources that other objects are likely to use. For example, audio renderers use this interface to resolve contentions for the wave-output device, to enable sound to follow focus.

Applications will typically not use this interface.

An object can use this interface to resolve possible contentions between existing resources. The object registers the resource with the interface and then requests it whenever needed. The object should notify the filter graph manager whenever the user focus changes. The filter graph manager can then switch contended resources to the objects that have the focus of the user.

An object that uses this interface must implement the IResourceConsumer interface. IResourceConsumer provides a callback mechanism for the filter graph manager to notify the object when a resource becomes available, or when the object should release a resource that it acquired.

In addition to the methods inherited from IUnknown, the IResourceConsumer interface exposes the following methods.

Method | Description
Register | Registers a single named resource with the resource manager.
RegisterGroup | Registers a named resource group with the resource manager.
RequestResource | Requests the use of a given registered resource.
NotifyAcquire | Notifies the resource manager that an attempt to acquire a resource has completed.
NotifyRelease | Notifies the resource manager that a resource consumer has released a resource.
CancelRequest | Cancels the request for a resource.
SetFocus | Notifies the resource manager that a specified object has been given the focus of the user.
ReleaseFocus | Sets the focus object to NULL in the resource manager if the object of the current focus object is the one specified in this method.


IResourceManager::CancelRequest

The CancelRequest method cancels the request for a resource.

Syntax

HRESULT CancelRequest(
  LONG idResource,
  IResourceConsumer *pConsumer
);

Parameters

idResource

[in] Resource identifier of a pending request.

pConsumer

[in] Pointer to the IResourceConsumer interface that made the request.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method should be called when the IResourceConsumer object that requested the resource has not received it and no longer requires it. If it has already received the resource, it should use the IResourceManager::NotifyRelease method.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::NotifyAcquire

The NotifyAcquire method notifies the resource manager that an attempt to acquire a resource has completed.

Syntax

HRESULT NotifyAcquire(
  LONG idResource,
  IResourceConsumer *pConsumer,
  HRESULT hr
);

Parameters

idResource

[in] Token for the registered resource.

pConsumer

[in] Pointer to the IResourceConsumer interface of the object requesting the resource.

hr

[in] Value indicating the success of the acquisition; S_OK if the resource was acquired, or an error value if not.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method after an IResourceConsumer::AcquireResource method returns an S_FALSE value, indicating that the acquisition will be asynchronous (that is, handled by a callback mechanism). If the hr parameter is S_OK, the resource manager will assume that the resource is now held by the caller. If the hr parameter is anything other than S_OK, the resource manager will assume that the attempt to acquire the resource failed and will reassign the resource elsewhere.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::NotifyRelease

The NotifyRelease method notifies the resource manager that IResourceConsumer has released a resource.

Syntax

HRESULT NotifyRelease (
  LONG idResource,
  IResourceConsumer *pConsumer,
  BOOL bStillWant
);

Parameters

idResource

[in] Resource token.

pConsumer

[in] Pointer to the object releasing the resource.

bStillWant

[in] Flag that specifies whether the resource is still required. Set to TRUE to indicate that you still want the resource when it is next available, or FALSE if you no longer want the resource.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method in response to an IResourceConsumer::ReleaseResource method, or when you have finished using the resource.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::Register

The Register method registers a single named resource with the resource manager.

Syntax

HRESULT Register(
  LPCWSTR pName,
  LONG cResource,
  LONG *plToken
);

Parameters

pName

[in] Named resource.

cResource

[in] Number of resources.

plToken

[out] Pointer to the returned token identifying the resource to be used in additional calls.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method registers a named resource, which can contain a number of resources, and returns a token to be used when requesting this resource. It is not an error if the resource is already registered; if the number in the cResource parameter is less than what is already registered, resources will be deallocated to the new count. To unregister the resource, pass a count of zero in cResource.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::RegisterGroup

The RegisterGroup method registers a named resource group with the resource manager.

Syntax

HRESULT RegisterGroup(
  LPCWSTR pName,
  LONG cResource,
  LONG *palTokens,
  LONG *plToken
);

Parameters

pName

[in] Named resource group.

cResource

[in] Number of resources in the group.

palTokens

[in, size_is(cResource)] Pointer to an array of resources in the group.

plToken

[out] Pointer to the returned group resource identifier.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::ReleaseFocus

The ReleaseFocus method sets the focus object to NULL in the resource manager if the current focus object is the one specified in this method.

Syntax

HRESULT ReleaseFocus(
  IUnknown *pFocusObject
);

Parameters

pFocusObject

[in] Pointer to the focus object.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method when the object of focus is about to be destroyed to ensure that the focus is not still being referenced.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::RequestResource

The RequestResource method requests the use of a given registered resource.

Syntax

HRESULT RequestResource(
  LONG idResource,
  IUnknown *pFocusObject,
  IResourceConsumer *pConsumer
);

Parameters

idResource

[in] Resource token retrieved when the resource was registered.

pFocusObject

[in] Pointer to the IUnknown interface of a focus object associated with a request (typically the filter's IUnknown interface).

pConsumer

[in] Pointer to the IResourceConsumer interface on the object requesting the resource.

Return Value

Returns an HRESULT value. Returns S_OK if the requested resource is returned, or S_FALSE if the resource is not available, in which case the resource manager will call the requesting object back when the resource becomes available. Any other return is an error.

Remarks

When there is more than one request for the resource, the resource manager will decide the priority by using the object of focus passed with each request and comparing it to the object of focus passed in the most recent IResourceManager::SetFocus method.

Requests will be filled in the following order of priority:

  1. Requests made with exactly the same object of focus as the last SetFocus method.
  2. Requests whose object of focus shares a common source filter whose object of focus shares a common filter graph.
  3. Requests in the same process as the focus.

While checking this priority, the resource manager will use QueryInterface on the focus object for IID_IFilter. If found, the resource manager will use IBaseFilter methods to check the filter graph and look for common source filters with the current focus object.

A filter should pass the IUnknown interface of the filter in the pFocusObject parameter. The filter graph manager matches filters to the filter graph and will attempt to trace filters to common source filters when checking objects of focus.

The focus object must be valid for the entire lifetime of the request—until either the IResourceManager::CancelRequest method is called, or the IResourceManager::NotifyRelease method is called with the bStillWant parameter set to FALSE.

See Also

  • Error and Success Codes
  • IResourceManager Interface


IResourceManager::SetFocus

The SetFocus method notifies the resource manager that a specified object has been given the focus of the user.

Syntax

HRESULT SetFocus(
  IUnknown *pFocusObject
);

Parameters

pFocusObject

[in] Pointer to the object that has been given the user's focus.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

Return code | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

In DirectShow, the object given the user's focus is typically a video renderer whose window has received the focus. The resource manager gives priority to requests for resources in the following order:

  1. Requests made with the focus object specified in the pFocusObject parameter.
  2. Requests whose focus object shares a common source filter.
  3. Requests whose focus object shares a common filter graph.
  4. Requests in the same process as the focus.

After a focus has been set, the resource manager must maintain a focus object until ReleaseFocus is called. That is, after calling this method, you must use ReleaseFocus before the IUnknown interface of the focus object becomes invalid, unless you can guarantee that SetFocus is called by a different object in the meantime. No reference count is held on the focus object.

The resource manager will hold this pointer until replaced or canceled, and will use it to resolve resource contention. It will use QueryInterface for the IBaseFilter interface at least and, if found, will use methods on that interface. It calls methods on IBaseFilter to decide which audio renderer to use if there are two (it will choose the one with a source filter common to the focus object), and also to determine if the two objects are within the same filter graph.

See Also

  • Error and Success Codes
  • IResourceManager Interface


ISampleGrabber Interface

The ISampleGrabber interface is exposed by the Sample Grabber Filter. It enables an application to retrieve individual media samples as they move through the filter graph.

In addition to the methods inherited from IUnknown, the ISampleGrabber interface exposes the following methods.

Method | Description
SetOneShot | Specifies whether the filter should stop the graph after receiving one sample.
SetMediaType | Specifies the media type for the connection on the Sample Grabber's input pin.
GetConnectedMediaType | Retrieves the media type for the connection on the Sample Grabber's input pin.
SetBufferSamples | Specifies whether to copy sample data into a buffer as it goes through the filter.
GetCurrentBuffer | Retrieves a copy of the sample that the filter received most recently.
GetCurrentSample | Not currently implemented.
SetCallback | Specifies a callback method to call on incoming samples.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Using the Sample Grabber


ISampleGrabber::GetConnectedMediaType

The GetConnectedMediaType method retrieves the media type for the connection on the Sample Grabber's input pin.

Syntax

HRESULT GetConnectedMediaType(
  AM_MEDIA_TYPE *pType
);

Parameters

pType

Pointer to an AM_MEDIA_TYPE structure allocated by the caller.

Return Value

Returns one of the following values.

Return code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The filter is not connected.

Remarks

This method copies the media type into the AM_MEDIA_TYPE structure specified by pType. The caller must free the media type's format block. You can use the CoTaskMemFree function, or the FreeMediaType function in the base-class library.

See Also

  • ISampleGrabber Interface


ISampleGrabber::GetCurrentBuffer

The GetCurrentBuffer method retrieves a copy of the buffer associated with the most recent sample.

Syntax

HRESULT GetCurrentBuffer(
  long *pBufferSize,
  long *pBuffer
);

Parameters

pBufferSize

[in, out] Pointer to the size of the buffer. If pBuffer is NULL, this parameter receives the required buffer size. If pBuffer is not NULL, set this parameter to the size of the buffer. On output, the parameter receives the size of the data copied into the buffer. This might be smaller than the size of the buffer.

pBuffer

[out] Pointer to a buffer to receive a copy of the sample, or NULL.

Return Value

Returns one of the following values.

Return code | Description
E_INVALIDARG | Samples are not being buffered.
E_OUTOFMEMORY | The specified buffer is not large enough.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The filter is not connected.
VFW_E_WRONG_STATE | The filter has not received any samples yet. To deliver a sample, run or pause the graph.

Remarks

To activate buffering, call ISampleGrabber::SetBufferSamples with a value of TRUE.

Call this method twice. On the first call, set pBuffer to NULL. The size of the buffer is returned in pBufferSize. Then allocate the buffer and call the method again. On the second call, pass the size of you buffer in pBufferSize, and pass the address of the buffer in pBuffer. If the buffer that you provide is not large enough, the method returns E_OUTOFMEMORY.

The filter does not buffer preroll samples, or samples in which the dwStreamId member of the AM_SAMPLE2_PROPERTIES structure is anything other than AM_STREAM_MEDIA.

See Also

  • ISampleGrabber Interface


ISampleGrabber::GetCurrentSample

The GetCurrentSample method is not currently implemented.

Syntax

HRESULT GetCurrentSample(
  IMediaSample **ppSample
);


ISampleGrabber::SetBufferSamples

The SetBufferSamples method specifies whether to copy sample data into a buffer as it goes through the filter.

Syntax

HRESULT SetBufferSamples(
  BOOL BufferThem
);

Parameters

BufferThem

Boolean value specifying whether to buffer sample data. If TRUE, the filter copies sample data into an internal buffer.

Return Value

Returns S_OK.

See Also

  • ISampleGrabber Interface


ISampleGrabber::SetCallback

The SetCallback method specifies a callback method to call on incoming samples.

Syntax

HRESULT SetCallback(
  ISampleGrabberCB *pCallback,
  long WhichMethodToCallback
);

Parameters

pCallback

Pointer to an ISampleGrabberCB interface containing the callback method, or NULL to cancel the callback.

WhichMethodToCallback

Index specifying the callback method. Must be one of the following values.

Value | Description
0 | Call the ISampleGrabberCB::SampleCB method.
1 | Call the ISampleGrabberCB::BufferCB method.

Return Value

Returns one of the following values.

Return code | Description
E_INVALIDARG | Samples are not being buffered.
S_OK | Success.

Remarks

If the sample is a Microsoft® DirectDraw® surface, the surface is locked during the callback. The Win16 lock (also called Win16Mutex) might be locked as well. Both of these locks create the potential for deadlock. If the callback thread waits for a thread that is trying to call a DirectDraw API, it can cause deadlock. In addition, if the Win16 lock is being held, deadlock can result if the callback holds a critical section or waits for another thread to complete any activity.

Therefore, the callback should not perform any actions with the potential to block, such as holding a critical section or waiting on another thread. Also, do not call any GDI or USER32.DLL APIs that might cause a window to move. For more information about the Win16 lock, see Knowledge Base article Q125867, Understanding Win16Mutex.

The data processing thread blocks until the callback method returns. If the callback does not return quickly, it can interfere with playback.

Modifying the contents of the sample is not recommended. Either make a copy of the sample, or write a custom filter instead of using the Sample Grabber.

The filter does not invoke the callback function for preroll samples, or for samples in which the dwStreamId member of the AM_SAMPLE2_PROPERTIES structure is anything other than AM_STREAM_MEDIA.

See Also

  • ISampleGrabber Interface


ISampleGrabber::SetMediaType

The SetMediaType method specifies the media type for the connection on the Sample Grabber's input pin.

Syntax

HRESULT SetMediaType(
  const AM_MEDIA_TYPE *pType
);

Parameters

pType

Pointer to an AM_MEDIA_TYPE structure specifies the required media type. It is not necessary to set all the structure members; see Remarks for details.

Return Value

Returns S_OK.

Remarks

By default, the Sample Grabber has no preferred media type. To ensure that the Sample Grabber connects to the correct filter, call this method before building the filter graph.

This method restricts the range of media types that the filter will accept. When the filter connects, it tries to match the media type given in pType. To do so, it compares the major type, subtype, and format type GUIDs, in that order. For each of these GUIDs, if pType has the value GUID_NULL, the Sample Grabber accepts the media type without any further checks. If pType has any other value, the Sample Grabber compares it to the GUID in the connection type. Unless the two GUIDs match exactly, the Sample Grabber rejects the connection.

Example 1:

  • Major type: MEDIATYPE_Video
  • Subtype: GUID_NULL
  • Format type: GUID_NULL

The Sample Grabber will accept any video type where the major type equals MEDIATYPE_Video. It will not check the subtype.

Example 2:

  • Major type: MEDIATYPE_Video
  • Subtype: MEDIASUBTYPE_RGB24
  • Format type: GUID_NULL

Now the Sample Grabber will check the subtype, and accept only RGB 24 video.

Limitations: Regardless of what type you set, the Sample Grabber Filter rejects any video types with top-down orientation (negative biHeight), or with a format type of FORMAT_VideoInfo2. In this case, although the SetMediaType method succeeds, the filter will not connect.

See Also

  • ISampleGrabber Interface


ISampleGrabber::SetOneShot

The SetOneShot method specifies whether the filter should stop the graph after receiving one sample.

Syntax

HRESULT SetOneShot(
  BOOL OneShot
);

Parameters

OneShot

Boolean value specifying whether the filter should stop the graph after receiving one sample. If TRUE, the filter graph stops when the Sample Grabber receives the first sample and signals EC_COMPLETE. If FALSE, the filter graph continues to run normally.

Return Value

Returns S_OK.

Remarks

You can retrieve a sample at a particular time by calling this method with a value of TRUE, seeking to the desired time, and running the graph.

The Sample Grabber implements one-shot mode by calling IPin::EndOfStream on the downstream filter and returning S_FALSE from it's IMemInputPin::Receive method.

See Also

  • ISampleGrabber Interface


ISampleGrabberCB Interface

The ISampleGrabberCB interface provides callback methods for the ISampleGrabber::SetCallback method. If your application calls that method, it must implement this interface. For more information, see ISampleGrabber.

In addition to the methods inherited from IUnknown, the ISampleGrabber interface exposes the following methods.

Method | Description
BufferCB | Callback method that receives a pointer to the sample buffer.
SampleCB | Callback method that receives a pointer to the media sample.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


ISampleGrabberCB::BufferCB

The BufferCB method is a callback method that receives a pointer to the sample buffer.

Syntax

HRESULT BufferCB(
  double SampleTime,
  BYTE *pBuffer,
  long BufferLen
);

Parameters

SampleTime

Starting time of the sample, in seconds.

pBuffer

Pointer to a buffer that contains the sample data.

BufferLen

Length of the buffer pointed to by pBuffer, in bytes.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

Call the ISampleGrabber::SetBufferSamples method to activate sample buffering. Otherwise, the buffer will be empty.

See Also

  • Error and Success Codes
  • ISampleGrabberCB Interface


ISampleGrabberCB::SampleCB

The SampleCB method is a callback method that receives a pointer to the media sample.

Syntax

HRESULT SampleCB(
  double SampleTime,
  IMediaSample *pSample
);

Parameters

SampleTime

Starting time of the sample, in seconds.

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

See Also

  • Error and Success Codes
  • ISampleGrabberCB Interface


ISeekingPassThru Interface

The ISeekingPassThru interface creates a helper object that implements seeking for one-input filters. Filters can use this interface to implement the IMediaSeeking and IMediaPosition interfaces. For more information, see CPosPassThru.

Applications do not use this interface.

In addition to the methods inherited from IUnknown, the ISeekingPassThru interface exposes the following method.

Method | Description
Init | Initializes the seeking helper object.

Remarks

To obtain this interface, call CoCreateInstance with CLSID_SeekingPassThru. You can also use the CreatePosPassThru function in the base class library.


ISeekingPassThru::Init

The Init method initializes the seeking helper object.

Syntax

HRESULT Init(
  BOOL bSupportRendering,
  IPin *pPin
);

Parameters

bSupportRendering

[in] Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise.

pPin

[in] Pointer to the IPin interface on the filter's input pin..

Return Value

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_FAIL | Object was already initialized.
E_OUTOFMEMORY | Not enough memory to create the object.

See Also

  • Error and Success Codes
  • ISeekingPassThru Interface


IStreamBuilder Interface

The IStreamBuilder interface enables an output pin to notify the filter graph manager that the pin itself will build the downstream section of the filter graph. Output pins with special connection needs can implement this interface to override the default pin connection process used by the filter graph manager.

In addition to the methods inherited from IUnknown, the IStreamBuilder interface exposes the following methods.

Method | Description
Render | Completes rendering of the stream originating with this pin. This can involve adding filters to the filter graph and connecting them.
Backout | Undoes steps taken in Render. This includes disconnecting and removing any filters that were added inside Render.


IStreamBuilder::Backout

The Backout method undoes steps taken in the IStreamBuilder::Render method. This includes disconnecting and removing any filters that were added inside Render.

Syntax

HRESULT Backout(
  IPin *ppinOut,
  IGraphBuilder *pGraph
)

Parameters

ppinOut

[in] Pointer to this pin's IPin interface.

pGraph

[in] Pointer to the filter graph manager's IGraphBuilder interface.

Return Value

Returns an HRESULT value. A return code of S_OK indicates to the graph builder that the disconnect was successful.

Remarks

The following example shows how a filter would reverse the steps that are shown in the code example for the IStreamBuilder::Render method:

STDMETHODIMP CMyOutputPin::BackOut(IPin *pPin, IGraphBuilder *pGraph)
{
    CheckPointer(pPin, E_POINTER);
    CheckPointer(pGraph, E_POINTER);

    HRESULT hr = S_OK;
    if (m_Connected != NULL) // Pointer to the pin we're connected to.
    {
        // Find the filter that owns the pin connected to us.
        FILTER_INFO fi;
        hr = m_Connected->QueryFilterInfo(&fi);
        if (SUCCEEDED(hr))
        {
            if (fi.pFilter != NULL)
            {
                //  Disconnect the pins.
                pGraph->Disconnect(m_Connected);
                pGraph->Disconnect(pPin);
                // Remove the filter from the graph.
                pGraph->RemoveFilter(fi.pFilter);
                fi.pFilter->Release();
            }
            else
            {
                hr = E_UNEXPECTED;
            }
        }
    }
    return hr;
}

See Also

  • Error and Success Codes
  • IStreamBuilder Interface


IStreamBuilder::Render

The Render method completes rendering of the stream originating with this pin. This can involve adding filters to the filter graph and connecting them.

Syntax

HRESULT Render(
  IPin *ppinOut,
  IGraphBuilder *pGraph
);

Parameters

ppinOut

[in] Pointer to this pin's IPin interface.

pGraph

[in] Pointer to the filter graph manager's IGraphBuilder interface.

Return Value

Returns an HRESULT value. A return code of S_OK indicates that the stream was successfully rendered.

Remarks

The following code illustrates how to implement this method on an output pin. This example assumes that the filter requires a custom renderer downstream from it.

STDMETHODIMP CMyOutputPin::Render(IPin *pPin, IGraphBuilder *pGraph)
{
    CheckPointer(pPin, E_POINTER);
    CheckPointer(pGraph, E_POINTER);

    // This filter needs a special renderer connected to it.
    IBaseFilter *pMyRenderer = NULL;

    // Create the renderer.
    HRESULT hr = CoCreateInstance(CLSID_MyRenderer, NULL, CLSCTX_INPROC,
        IID_IBaseFilter, (void **)&pMyRenderer);
    if (FAILED(hr))
    {
        return hr;
    }

    // Add my renderer to the filter graph.
    hr = pGraph->AddFilter(pMyRenderer, L"My Renderer");
    if (FAILED(hr))
    {
        pMyRenderer->Release();
        return hr;
    }

    IEnumPins *pEnumPins;
    IPin *pMyRendererInputPin = NULL;
    hr = pMyRenderer->EnumPins(&pEnumPins);
    if (SUCCEEDED(hr))
    {
        if (S_OK != pEnumPins->Next(1, &pMyRendererInputPin, 0))
        {
            hr = E_UNEXPECTED;
         }
    }
    if (SUCCEEDED(hr))
    {
        // Connect my renderer to my output pin.
        hr = pGraph->ConnectDirect(pPin, pMyRendererInputPin);
        pMyRendererInputPin->Release();
    }
    if (FAILED(hr))
    {
        // Could not connect to my renderer. Remove it from the graph.
        pGraph->RemoveFilter(pMyRenderer);
    }
    pMyRenderer->Release();
    return hr;
}

See Also

  • Error and Success Codes
  • IStreamBuilder Interface


IVideoFrameStep Interface

The IVideoFrameStep interface steps through a video stream. This interface enables Microsoft® DirectShow® applications, including DVD players, to step through a video stream as slowly as one frame at a time. Obtain the interface through the filter graph manager, which controls the frame stepping process in conjunction with the Overlay Mixer Filter or the Video Renderer Filter. Backward frame stepping is not supported.

Note For frame stepping to work with a hardware decoder, the decoder must support the Frame Stepping Property Set property set.

In addition to the methods inherited from IUnknown, the IVideoFrameStep interface exposes the following methods.

Method | Description
Step | Causes the filter graph to step forward by the specified number of frames.
CanStep | Determines the stepping capabilities of the specified filter.
CancelStep | Cancels the previous step operation.


IVideoFrameStep::CancelStep

The CancelStep method cancels the previous IVideoFrameStep::Step operation.

Syntax

HRESULT CancelStep();

Return Values

Returns S_OK if the Step operation was successfully canceled, or E_FAIL otherwise.

See Also

  • Error and Success Codes
  • IVideoFrameStep Interface


IVideoFrameStep::CanStep

The CanStep method determines the stepping capabilities of the specified filter.

Syntax

HRESULT CanStep(
  long bMultiple,
  IUnknown *pStepObject
);

Parameters

bMultiple

If bMultiple is zero and the method returns S_OK, the graph can step one frame at a time. If bMultiple if greater than zero and the method returns S_OK, the graph can step bMultiple frames at a time.

pStepObject

Pointer to an interface on the filter that will control the stepping operation. Specify NULL to perform frame stepping using the renderer filter in the graph. If the graph includes a custom filter that implements the frame stepping, then pStepObject should specify that filter's IBaseFilter interface.

Return Values

Returns S_OK if the object can step or E_INVALIDARG if pStepObject is invalid.

See Also

  • Error and Success Codes
  • IVideoFrameStep Interface


IVideoFrameStep::Step

The Step method causes the filter graph to step forward by the specified number of frames.

Syntax

HRESULT Step(
  DWORD dwFrames,
  IUnknown *pStepObject
);

Parameters

dwFrames

Specifies the number of frames to skip. If dwFrames is 1, the graph steps forward one frame. If dwFrames is a number n greater than 1, the graph skips n - 1 frames and shows the nth frame.

pStepObject

Pointer to an interface on the filter that will control the stepping operation. Specify NULL to perform the frame stepping using the renderer filter in the graph. If the graph includes a custom filter that implements the frame stepping, then pStepObject should specify that filter's IBaseFilter interface.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
S_OK | Success.
VFW_E_FRAME_STEP_UNSUPPORTED | Frame stepping is not supported.
E_INVALIDARG | The pStepObject parameter is invalid.

Remarks

When the step operation is complete, this method sends an EC_STEP_COMPLETE event notification to the filter graph manager, which will pass it to the application's event loop and set the filter graph to a paused state.

The frames step in real time, which means that if the movie is playing at 30 frames per second, calling IVideoFrameStep::Step with bMultiple set to 60 would take 2 seconds to execute. All methods in this interface are asynchronous, so control returns to the application immediately.

See Also

  • Error and Success Codes
  • IVideoFrameStep Interface


IVideoWindow Interface

The IVideoWindow interface sets properties on the video window. Applications can use it to set the window owner, the position and dimensions of the window, and other properties.

Both the Video Renderer Filter and the Filter Graph Manager expose this interface. Applications should use the Filter Graph Manager's version of this interface. The Filter Graph Manager forwards all method calls to the Video Renderer. It also forwards certain window messages, such as WM_DISPLAYCHANGE, that the Video Renderer requires in order to update itself. If you make the video window into a child window, the window no longer receives these messages directly. Thus, it relies on the Filter Graph Manager to forward them.

However, if the filter graph contains more than one Video Renderer, the Filter Graph Manager only communicates with one of them (selected arbitrarily). Therefore, to work with multiple video windows, an application must use the IVideoWindow interface directly on the filters themselves. In that case, you must be sure to forward window messages to each Video Renderer, using the IVideoWindow::NotifyOwnerMessage method.

MFC applications which place the video window in a child window must define an empty WM_ERASEBKGND message handler, or the video display area will not repaint correctly.

If the video renderer is not connected, all the methods on this interface return the error code VFW_E_NOT_CONNECTED. Properties set on a video renderer persist between successive connections and disconnections. Because this interface is Automation-compatible, Boolean values are OAFALSE (0) or OATRUE (–1).

Filter Developers: You can use the CBaseVideoWindow class to help implement this interface.

In addition to the methods inherited from IDispatch, the IVideoWindow interface exposes the following methods.

Method | Description
get_AutoShow | Queries whether the video renderer automatically shows the video window when it receives video data.
get_BackgroundPalette | Queries whether the video window realizes its palette in the background.
get_BorderColor | Retrieves the color that appears around the edges of the destination rectangle.
get_Caption | Retrieves the video window caption.
get_FullScreenMode | Queries whether the video renderer is in full-screen mode.
get_Height | Retrieves the height of the video window.
get_Left | Retrieves the video window's x-coordinate.
get_MessageDrain | Retrieves the window that receives mouse and keyboard messages from the video window, if any.
get_Owner | Retrieves the video window's parent window, if any.
get_Top | Retrieves the video window's y-coordinate.
get_Visible | Queries whether the video window is visible.
get_Width | Retrieves the width of the video window.
get_WindowState | Queries whether the video window is visible, hidden, minimized, or maximized.
get_WindowStyle | Retrieves the window style on the video window.
get_WindowStyleEx | Retrieves the extended window style on the video window.
GetMaxIdealImageSize | Retrieves the maximum ideal size for the video image.
GetMinIdealImageSize | Retrieves the minimum ideal size for the video image.
GetRestorePosition | Retrieves the restored window position.
GetWindowPosition | Retrieves the position of the video window.
HideCursor | Hides the cursor.
IsCursorHidden | Queries whether the cursor is hidden.
NotifyOwnerMessage | Forwards a message to the video window.
put_AutoShow | Specifies whether the video renderer automatically shows the video window when it receives video data.
put_BackgroundPalette | Specifies whether the video window realizes its palette in the background.
put_BorderColor | Sets the color that appears around the edges of the destination rectangle.
put_Caption | Sets the video window caption.
put_FullScreenMode | Enables or disables full-screen mode.
put_Height | Sets the height of the video window.
put_Left | Sets the video window's x-coordinate.
put_MessageDrain | Specifies a window to receive mouse and keyboard messages from the video window.
put_Owner | Specifies a parent window for the video window.
put_Top | Sets the video window's y-coordinate.
put_Visible | Shows or hides the video window.
put_Width | Sets the width of the video window.
put_WindowState | Shows, hides, minimizes, or maximizes the video window.
put_WindowStyle | Sets the window style on the video window.
put_WindowStyleEx | Sets the extended window style on the video window.
SetWindowForeground | Places the video window at the top of the Z order.
SetWindowPosition | Sets the position of the video window.


IVideoWindow::get_AutoShow

The get_AutoShow method queries whether the video renderer automatically shows the video window when it receives video data.

Syntax

HRESULT get_AutoShow(
    long *AutoShow
);

Parameters

AutoShow

[out] Pointer to a variable that receives one of the following values.

Value | Description
OATRUE | If the video renderer pauses or runs, it will automatically show the video window.
OAFALSE | The video renderer will not automatically show the video window.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVideoWindow::get_BackgroundPalette

The get_BackgroundPalette method queries whether the video window realizes its palette in the background..

Syntax

HRESULT get_BackgroundPalette(
    long *pBackgroundPalette
);

Parameters

pBackgroundPalette

[out] Pointer to a variable that receives one of the following values.

Value | Description
OATRUE | The video window realizes the palette in the background.
OAFALSE | The video window does not realize the palette in the background.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_BackgroundPalette


IVideoWindow::get_BorderColor

The get_BorderColor method retrieves the color that appears around the edges of the destination rectangle.

Syntax

HRESULT get_BorderColor(
    long *pColor
);

Parameters

pColor

[out] Pointer to a variable that receives a Microsoft Win32® COLORREF value.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_BorderColor


IVideoWindow::get_Caption

The get_Caption method retrieves the video window caption.

Syntax

HRESULT get_Caption(
    BSTR *strCaption
);

Parameters

strCaption

[out] Pointer to a BSTR that receives the caption.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

The caller must free the returned string, using the SysFreeString function.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Caption


IVideoWindow::get_FullScreenMode

The get_FullScreenMode method queries whether the video renderer is in full-screen mode.

Syntax

HRESULT get_FullScreenMode(
    long *FullScreenMode
);

Parameters

FullScreenMode

[out] Pointer to a variable that receives the value OATRUE if the video renderer is in full-screen mode, or OAFALSE otherwise.

Return Values

Possible return values include the following:

Value | Description
E_NOTIMPL | This filter does not support full-screen mode.
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

When the Filter Graph Manager is switching to full-screen mode, it calls this method to determine whether the current video renderer supports this mode. If the renderer does not have inherent support for full-screen playback, it should return E_NOTIMPL. If if does, it should return S_OK, and also return the correct value in the FullScreenMode parameter.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_FullScreenMode


IVideoWindow::get_Height

The get_Height method retrieves the height of the video window.

Syntax

HRESULT get_Height(
    long *pHeight
);

Parameters

pHeight

[out] Pointer to a variable that receives the height, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Height


IVideoWindow::get_Left

The get_Left method retrieves the video window's x-axis coordinate.

Syntax

HRESULT get_Left(
    long *pLeft
);

Parameters

pLeft

[out] Pointer to a variable that receives the x-axis coordinate, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Left


IVideoWindow::GetMaxIdealImageSize

The GetMaxIdealImageSize method retrieves the maximum ideal image size for the video image.

Syntax

HRESULT GetMaxIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth

[out] Pointer to a variable that receives the maximum ideal width, in pixels.

pHeight

[out] Pointer to a variable that receives the maximum ideal height, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_FALSE | Could not retrieve a maximum image size.
S_OK | Success.
VFW_E_WRONG_STATE | Filter is stopped.

Remarks

The maximum ideal size may differ from the native video size, because the video hardware might have specific stretching requirements.

This method returns S_FALSE under various circumstances:

  • The filter is using an IOverlay transport.
  • UseWhenFullScreen mode is on. (See IDirectDrawVideo::UseWhenFullScreen.)
  • The video surface has no maximum overlay stretch. (The dwMaxOverlayStretch member of the DDCAPS structure is zero. See IDirectDrawVideo::GetCaps.)

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::GetMinIdealImageSize


IVideoWindow::get_MessageDrain

The get_MessageDrain method retrieves the window that receives mouse and keyboard messages from the video window, if any.

Syntax

HRESULT get_MessageDrain(
    OAHWND *Drain
);

Parameters

Drain

[in] Pointer to a variable that receives a handle to the window, as an OAHWND type. If no message drain was set, this parameter receives the value NULL.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_MessageDrain


IVideoWindow::GetMinIdealImageSize

The GetMinIdealImageSize method retrieves the minimum ideal size for the video image.

Syntax

HRESULT GetMinIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth

[out] Pointer to a variable that receives the minimum ideal width, in pixels.

pHeight

[out] Pointer to a variable that receives the minimum ideal height, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_FALSE | Could not retrieve a minimum image size.
S_OK | Success.
VFW_E_WRONG_STATE | Filter is stopped.

Remarks

The maximum ideal size may differ from the native video size, because the video hardware might have specific stretching requirements.

This method returns S_FALSE under various circumstances:

  • The filter is using an IOverlay transport.
  • UseWhenFullScreen mode is on. (See IDirectDrawVideo::UseWhenFullScreen.)
  • Video playback is using a stretchable offscreen surface. (The dwCaps member of the DDCAPS structure includes the DDCAPS_BLTSTRETCH flag. See IDirectDrawVideo::GetCaps.)
  • The video surface has no minimum overlay stretch. (The dwMinOverlayStretch member of the DDCAPS structure is zero. See IDirectDrawVideo::GetCaps.)

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::GetMaxIdealImageSize


IVideoWindow::get_Owner

The get_Owner method retrieves the video window's parent window, if any.

Syntax

HRESULT get_Owner(
    OAHWND *pOwner
);

Parameters

pOwner

[out] Pointer to a variable that receives a handle to the window, as an OAHWND type. If the video window has no parent, this parameter receives the value NULL.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVideoWindow::GetRestorePosition

The GetRestorePosition method retrieves the restored window position.

Syntax

HRESULT GetRestorePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

pTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

pWidth

[out] Pointer to a variable that receives the width of the window, in pixels.

pHeight

[out] Pointer to a variable that receives the height of the window, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

If the video window is minimized or maximized, you can use this method to get the window's restored position.

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVideoWindow::get_Top

The get_Top method retrieves the video window's y-coordinate.

Syntax

HRESULT get_Top(
    long *pTop
);

Parameters

pTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Top


IVideoWindow::get_Visible

The get_Visible method queries whether the video window is visible.

Syntax

HRESULT get_Visible(
    long *pVisible
);

Parameters

pVisible

[out] Pointer to a variable that receives the value OATRUE if the window is visible, or OAFALSE if the window is hidden.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method checks for the WS_VISIBLE style bit, by calling the Windows IsWindowVisible method.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Visible


IVideoWindow::get_Width

The get_Width method retrieves the width of the video window.

Syntax

HRESULT get_Width(
    long *pWidth
);

Parameters

pWidth

[out] Pointer a variable that receives the width, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_Width


IVideoWindow::GetWindowPosition

The GetWindowPosition method retrieves the position of the video window.

Syntax

HRESULT GetWindowPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

[out] Pointer to a variable that receives the x-coordinate, in pixels.

pTop

[out] Pointer to a variable that receives the y-coordinate, in pixels.

pWidth

[out] Pointer to a variable that receives the width of the window, in pixels.

pHeight

[out] Pointer to a variable that receives the height of the window, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method has the same effect as calling the IVideoWindow::get_Left, IVideoWindow::get_Top, IVideoWindow::get_Width, and IVideoWindow::get_Height methods.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::SetWindowPosition


IVideoWindow::get_WindowState

The get_WindowState method queries whether the video window is visible, hidden, minimized, or maximized.

Syntax

HRESULT get_WindowState(
    long *WindowState
);

Parameters

WindowState

[out] Pointer to a variable that receives one of the following flags:

  • SW_HIDE
  • SW_MAXIMIZE
  • SW_MINIMIZE
  • SW_SHOW

The meanings of these flags are defined by the Windows ShowWindow function.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_WindowState


IVideoWindow::get_WindowStyle

The get_WindowStyle method retrieves the window styles on the video window.

Syntax

HRESULT get_WindowStyle(
    long *pWindowStyle
);

Parameters

pWindowStyle

[out] Pointer to a variable that receives the window style flags.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method calls the Windows GetWindowLong function with the value GWL_STYLE.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_WindowStyle
  • IVideoWindow::get_WindowStyleEx


IVideoWindow::get_WindowStyleEx

The get_WindowStyleEx method retrieves the extended window styles on the video window.

Syntax

HRESULT get_WindowStyleEx(
    long *pWindowStyleEx
);

Parameters

pWindowStyleEx

[out, retval] Pointer to a variable that receives the window style flags.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method calls the Windows GetWindowLong function with the value GWL_EXSTYLE.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::put_WindowStyleEx
  • IVideoWindow::get_WindowStyle


IVideoWindow::HideCursor

The HideCursor method shows or hides the cursor when the mouse is positioned over the video window.

Syntax

HRESULT HideCursor(
    long HideCursor
);

Parameters

HideCursor

[in] Specifies whether to show or hide the cursor. Must be one of the following values:

Value | Description
OATRUE | Hide the cursor.
OAFALSE | Show the cursor.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::IsCursorHidden


IVideoWindow::IsCursorHidden

The IsCursorHidden method queries whether the cursor is hidden.

Syntax

HRESULT IsCursorHidden(
    long *CursorHidden
);

Parameters

CursorHidden

[out] Pointer to a variable that receives the value OATRUE if the cursor is hidden, or OAFALSE if the cursor is displayed.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::HideCursor


IVideoWindow::NotifyOwnerMessage

The NotifyOwnerMessage method forwards a message to the video window.

Syntax

HRESULT NotifyOwnerMessage(
    long hwnd,
    long uMsg,
    long wParam,
    long lParam
);

Parameters

hwnd

[in] Handle to the window.

uMsg

[in] Specifies the message.

wParam

[in] Message parameter.

lParam

[in] Message parameter.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

The Filter Graph Manager calls this method to pass various messages to the renderer, including the following:

  • WM_ACTIVATEAPP
  • WM_DEVMODECHANGE
  • WM_DISPLAYCHANGE
  • WM_PALETTECHANGED
  • WM_PALETTEISCHANGING
  • WM_QUERYNEWPALETTE
  • WM_SYSCOLORCHANGE

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVideoWindow::put_AutoShow

The put_AutoShow method specifies whether the video renderer automatically shows the video window when it receives video data.

Syntax

HRESULT put_AutoShow(
    long AutoShow
);

Parameters

AutoShow

[in] Specifies whether the video renderer automatically shows the video windoe. Must be one of the following values:

Value | Description
OATRUE | If the video renderer pauses or runs, it will automatically show the video window. (Default.)
OAFALSE | The video renderer will not automatically show the video window.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

By default, when the filter graph changes state to paused or running, the video renderer shows the video window and moves it to the foreground. If the user closes the window, it will not automatically reappear.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_AutoShow


IVideoWindow::put_BackgroundPalette

The put_BackgroundPalette method specifies whether the video window realizes its palette in the background.

Syntax

HRESULT put_BackgroundPalette(
    long BackgroundPalette
);

Parameters

BackgroundPalette

[in] Value that specifies whether the video renderer realizes it palette in the background. Must be one of the following values:

Value | Description
OATRUE | The video renderer realizes the palette in the background.
OAFALSE | The video renderer does not realize the palette in the background. (Default.)

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

If BackgroundPalette is OATRUE and the video image requires a pallette, the video renderer will realize that palette in the background. Any colors that the palette uses will change to their closest match in the display palette prior to drawing. This ensures that an application will not have its palette disturbed. However, it imposes severe performance penalties on the video.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_BackgroundPalette


IVideoWindow::put_BorderColor

The put_BorderColor method sets the color that appears around the edges of the destination rectangle.

Syntax

HRESULT put_BorderColor(
    long Color
);

Parameters

Color

[in] Specifies the border color as a COLORREF value.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

If the destination rectangle is smaller than the client area of the video window, a border is exposed around the edges of the video. The default color is black. Use this method to override the default color. If a palette is in use, a nonsystem color is converted to its closest match.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_BorderColor
  • IBasicVideo::SetDestinationPosition


IVideoWindow::put_Caption

The put_Caption method sets the video window caption.

Syntax

HRESULT put_Caption(
    BSTR strCaption
);

Parameters

strCaption

[in] Specifies the caption.

Return Values

Possible return values include the following:

Value | Description
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Caption


IVideoWindow::put_FullScreenMode

The put_FullScreenMode method enables or disables full-screen video rendering.

Syntax

HRESULT put_FullScreenMode(
    long FullScreenMode
);

Parameters

FullScreenMode

[in] Boolean value that specifies whether to enable or disable full-screen mode. Must be one of the following values:

Value | Description
OATRUE | Switch to full-screen mode.
OAFALSE | Disable full-screen mode. (Default.)

Return Values

Possible return values include the following:

Value | Description
E_NOTIMPL | Filter does not support full-screen mode.
S_FALSE | Already in the requested mode.
S_OK | Success.
VFW_E_NO_FULLSCREEN | Could not find any filter that supports full-screen mode.

Remarks

Depending on the video renderer, the switch to full-screen mode may not be visible until the application runs or pauses the graph. In full-screen mode, if the user switches away from the application (for example, using ALT + TAB), the Filter Graph Manager sends an EC_FULLSCREEN_LOST event.

The following remarks describe how the Filter Graph Manager implements full-screen mode. Application developers can probably ignore this information, but it may be useful if you are writing a custom video renderer.

When an application switches to full-screen mode, the Filter Graph Manager searches for a video renderer that will function most efficiently. In order of preference, these are:

  1. Any video renderer in the filter graph that natively supports full-screen mode.
  2. Any video renderer in the filter graph that can stretch the video to full-screen without a significant performance cost.
  3. The Full Screen Renderer filter.
  4. Any video renderer in the filter graph that supports IVideoWindow.

For the first option, the Filter Graph Manager calls IVideoWindow::get_FullScreenMode on every video renderer in the graph. Most renderers return E_NOTIMPL, indicating the filter does not natively support full-screen mode. If any renderer returns a value not equal to E_NOTIMPL, the Filter Graph Manager uses that one.

For the second option, the Filter Graph Manager calls IVideoWindow::GetMaxIdealImageSize and GetMinIdealImageSize on every video renderer in the graph. If the size of the display falls within the filter's reported range, it indicates that the filter can stretch the video without a significant performance cost.

Note If the graph is stopped, the Filter Graph Manager pauses each renderer before calling these methods. This gives the renderer an opportunity to initialize any resources it needs, because many renderers cannot determine these values while they are stopped.

Except on older hardware, the second option will generally succeed. The third option is to use the Full Screen Renderer filter, adding it to the graph if necessary. The fourth option is simply to find the first renderer in the graph that supports IVideoWindow, and stretch the video regardless of performance.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_FullScreenMode


IVideoWindow::put_Height

The put_Height method sets the height of the video window.

Syntax

HRESULT put_Height(
    long Height
);

Parameters

Height

[in] Specifies the height, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Height


IVideoWindow::put_Left

The put_Left method sets the x-coordinate of the video window.

Syntax

HRESULT put_Left(
    long Left
);

Parameters

Left

[in] Specifies the x-coordinate, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Left


IVideoWindow::put_MessageDrain

The put_MessageDrain method specifies a window to receive mouse and keyboard messages from the video window.

Syntax

HRESULT put_MessageDrain(
  OAHWND Drain
);

Parameters

Drain

[in] Specifies a handle to the window, as an OAHWND value.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method enables an application to respond to mouse and keyboard events generated within the video window.

If Drain is non-NULL, the video renderer forwards certain messages to the specified window, using the PostMessage function. Which messages are forwarded might depend on the video renderer in use. The Video Renderer and Video Mixing Renderer (VMR) filters forward the following messages:

  • WM_CHAR
  • WM_DEADCHAR
  • WM_KEYDOWN
  • WM_KEYUP
  • WM_LBUTTONDBLCLK
  • WM_LBUTTONDOWN
  • WM_LBUTTONUP
  • WM_MBUTTONDBLCLK
  • WM_MBUTTONDOWN
  • WM_MBUTTONUP
  • WM_MOUSEACTIVATE
  • WM_MOUSEMOVE
  • WM_NCLBUTTONDBLCLK
  • WM_NCLBUTTONDOWN
  • WM_NCLBUTTONUP
  • WM_NCMBUTTONDBLCLK
  • WM_NCMBUTTONDOWN
  • WM_NCMBUTTONUP
  • WM_NCMOUSEMOVE
  • WM_NCRBUTTONDBLCLK
  • WM_NCRBUTTONDOWN
  • WM_NCRBUTTONUP
  • WM_RBUTTONDBLCLK
  • WM_RBUTTONDOWN
  • WM_RBUTTONUP
  • WM_SYSCHAR
  • WM_SYSDEADCHAR
  • WM_SYSKEYDOWN
  • WM_SYSKEYUP

The message drain window does not need to be a parent of the video window, so full-screen applications can use this method.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_MessageDrain


IVideoWindow::put_Owner

The put_Owner method specifies a parent window for the video window.

Syntax

HRESULT put_Owner(
  OAHWND Owner
);

Parameters

Owner

[in] Specifies a handle to the parent window, as an OAHWND value, or NULL to remove the existing parent.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

Use this method to display videos in a compound document. This method changes the parent of the video window and sets the WS_CHILD style for the video window.

Reset the owner to NULL before releasing the Filter Graph Manager. Otherwise, messages will continue to be sent to this window and errors will likely occur when the application is terminated.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Owner


IVideoWindow::put_Top

The put_Top method specifies the y-coordinate of the video window.

Syntax

HRESULT put_Top(
  long Top
);

Parameters

Top

[in] Specifies the y-coordinate, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Top


IVideoWindow::put_Visible

The put_Visible method shows or hides the video window.

Syntax

HRESULT put_Visible(
  long Visible
);

Parameters

Visible

[in] Value that specifies whether to show or hide the window. Must be one of the following values:

Value | Description
OATRUE | Show the window.
OAFALSE | Hide the window.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Visible


IVideoWindow::put_Width

The put_Width method specifies the width of the video window.

Syntax

HRESULT put_Width(
  long Width
);

Parameters

Width

[in] Specifies the width, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_Width


IVideoWindow::put_WindowState

The put_WindowState method shows, hides, minimizes, or maximizes the video window.

Syntax

HRESULT put_WindowState(
  long WindowState
);

Parameters

WindowState

[in] Flag that specifies how the window is to be shown. The value can be any constant defined for the nCmdShow parameter of the Microsoft® Windows® ShowWindow function. For more information, see the Platform SDK.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_WindowState


IVideoWindow::put_WindowStyle

The put_WindowStyle method sets the window styles on the video window.

Syntax

HRESULT put_WindowStyle(
  long WindowStyle
);

Parameters

WindowStyle

[in] Specifies one or more flags from the GWL_STYLE value of the Windows SetWindowLong function.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method is a thin wrapper over the SetWindowLong function and must be treated with care. In particular, you should retrieve the current styles and then add or remove flags. With some exceptions, flags allowed by the Windows CreateWindow function are acceptable. However, do not use this method to change the window size, and do not use the following flags:

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_WindowStyle
  • IVideoWindow::put_WindowStyleEx


IVideoWindow::put_WindowStyleEx

The put_WindowStyleEx method sets the extended window styles on the video window.

Syntax

HRESULT put_WindowStyleEx(
  long WindowStyleEx
);

Parameters

WindowStyleEx

[in] Specifies one or more flags from the GWL_EXSTYLE value of the Windows SetWindowLong function.

Return Values

Possible return values include the following:

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method is a thin wrapper over the SetWindowLong function and must be treated with care. In particular, you should retrieve the current styles and then add or remove flags. With some exceptions, flags allowed by the Windows CreateWindow function are acceptable. However, do not use this method to change the window size.

See Also

  • Error and Success Codes
  • IVideoWindow Interface
  • IVideoWindow::get_WindowStyleEx
  • IVideoWindow::put_WindowStyle


IVideoWindow::SetWindowForeground

The SetWindowForeground method places the video window at the top of the Z order.

Syntax

HRESULT SetWindowForeground(
  long Focus
);

Parameters

Focus

Value that specifies whether to give the window focus. Must be one of the following values:

Value | Description
OATRUE | Give the window focus.
OAFALSE | Do not give the window focus.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVideoWindow::SetWindowPosition

The SetWindowPosition method sets the position of the video window.

Syntax

HRESULT SetWindowPosition(
  long Left,
  long Top,
  long Width,
  long Height
);

Parameters

Left

[in] Specifies the x-coordinate, in pixels.

Top

[in] Specifies the y-coordinate, in pixels.

Width

[in] Specifies the width, in pixels.

Height

[in] Specifies the height, in pixels.

Return Values

Possible return values include the following:

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The video renderer filter is not connected.

Remarks

This method has the same effect as calling the IVideoWindow::put_Left, IVideoWindow::put_Top, IVideoWindow::put_Width, and IVideoWindow::put_Height methods.

If resizing the window to the specified dimensions is impossible, this method modifies the window's size and location to make the window fit. Call the IVideoWindow::GetWindowPosition method to determine the result.

See Also

  • Error and Success Codes
  • IVideoWindow Interface


IVMRAspectRatioControl Interface

The IVMRAspectRatioControl interface controls whether the Video Mixing Renderer Filter 7 (VMR-7) preserves the aspect ratio of the source video. This interface is available when the VMR-7 is operating in either windowed or windowless modes. In windowless mode, the same functionality is provided by the IVMRWindowlessControl interface.

In addition to the methods inherited from IUnknown, the IVMRAspectRatioControl interface exposes the following methods.

Method | Description
GetAspectRatioMode | Queries whether the VMR will preserve the aspect ratio of the source video.
SetAspectRatioMode | Specifies whether the VMR will preserve the aspect ratio of the source video.


IVMRAspectRatioControl::GetAspectRatioMode

The GetAspectRatioMode method queries whether the VMR will preserve the aspect ratio of the source video.

Syntax

HRESULT GetAspectRatioMode(
  DWORD* lpAspectRatioMode
);

Parameters

lpAspectRatioMode

[out] Pointer to a variable that receives a VMR_ASPECT_RATIO_MODE value indicating the aspect ratio mode.

Return Values

Returns an HRESULT value. Possible values include the following:

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • Error and Success Codes
  • IVMRAspectRatioControl Interface


IVMRAspectRatioControl::SetAspectRatioMode

The SetAspectRatioMode method specifies whether the VMR will preserve the aspect ratio of the source video.

Syntax

HRESULT SetAspectRatioMode(
  DWORD AspectRatioMode
);

Parameters

AspectRatioMode

[in] Specifies a member of the VMR_ASPECT_RATIO_MODE enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following:

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • Error and Success Codes
  • IVMRAspectRatioControl Interface


IVMRAspectRatioControl9 Interface

The IVMRAspectRatioControl9 interface controls whether the Video Mixing Renderer Filter 9 (VMR-9) preserves the aspect ratio of the source video. This interface is available when the VMR is operating in either windowed or windowless modes. In windowless mode, the same functionality is provided by the IVMRWindowlessControl interface.

In addition to the methods inherited from IUnknown, the IVMRAspectRatioControl9 interface exposes the following methods.

Method | Description
GetAspectRatioMode | Queries whether the VMR will preserve the aspect ratio of the source video.
SetAspectRatioMode | Specifies whether the VMR will preserve the aspect ratio of the source video.

Requirements

Include D3d9.h, Vmr9.h.


IVMRAspectRatioControl9::GetAspectRatioMode

The GetAspectRatioMode method queries whether the VMR preserves the aspect ratio of the source video.

Syntax

HRESULT GetAspectRatioMode(
  DWORD* lpAspectRatioMode
);

Parameters

lpAspectRatioMode

[out] Pointer to a variable that receives a member of the VMR_ASPECT_RATIO_MODE enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRAspectRatioControl9 Interface


IVMRAspectRatioControl9::SetAspectRatioMode

The SetAspectRatioMode method specifies whether the VMR preserves the aspect ratio of the source video.

Syntax

HRESULT SetAspectRatioMode(
  DWORD AspectRatioMode
);

Parameters

AspectRatioMode

[in] Specifies a member of the VMR_ASPECT_RATIO_MODE enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRAspectRatioControl9 Interface


IVMRDeinterlaceControl Interface

This topic applies to Windows XP Service Pack 1 only.

The IVMRDeinterlaceControl interface provides support for advanced hardware-accelerated deinterlacing using the Video Mixing Renderer filter (VMR-7 only). This interface enables applications or other filters to control how the VMR manages DirectX Video Acceleration (DirectX VA) hardware deinterlacing.

In addition to the methods inherited from IUnknown, the IVMRDeinterlaceControl interface exposes the following methods.

Method | Description
GetActualDeinterlaceMode | Returns the deinterlacing mode that the VMR is using for a specified stream.
GetDeinterlaceMode | Retrieves the deinterlacing mode for the specified video stream.
GetDeinterlaceModeCaps | Retrieves the capabilities of a specific deinterlacing mode supported by the graphics device driver.
GetDeinterlacePrefs | Queries how the VMR will select a deinterlacing mode if it cannot use the preferred mode.
GetNumberOfDeinterlaceModes | Retrieves the deinterlacing modes available to the VMR for the specified video format.
SetDeinterlaceMode | Sets the deinterlacing mode for the specified video stream.
SetDeinterlacePrefs | Specifies how the VMR will select a deinterlacing mode if it cannot use the preferred mode.

Remarks

This interface is applicable only when the VMR is in mixer mode. All methods in this interface return VFW_E_VMR_NOT_IN_MIXER_MODE if the VMR is not in mixer mode.

Deinterlacing modes are identified by GUIDs. The graphics device driver returns an array of GUIDs for the modes that it supports. The array is sorted in order of quality, from best quality to lowest quality. To retrieve the list of GUIDs, call the GetNumberOfDeinterlaceModes method. To obtain more information about a particular mode, pass this GUID to the GetDeinterlaceModeCaps method. To configure the VMR to use a particular mode, call the SetDeinterlaceMode method.

See Also

  • Setting Deinterlace Preferences


IVMRDeinterlaceControl::GetActualDeinterlaceMode

This topic applies to Windows XP Service Pack 1 only.

The GetActualDeinterlaceMode method returns the deinterlacing mode that the VMR is using for a specified stream.

Syntax

HRESULT GetActualDeinterlaceMode(
    DWORD dwStreamID,
    GUID *lpDeinterlaceMode
);

Parameters

dwStreamID

[in] Index of the video stream.

lpDeinterlaceMode

[out] Pointer to a variable that receives a GUID value that identifies the deinterlacing mode. The method returns GUID_NULL if the VMR has not initialized the deinterlacing hardware, or if the VMR determines that this stream should not be deinterlaced.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface


IVMRDeinterlaceControl::GetDeinterlaceMode

This topic applies to Windows XP Service Pack 1 only.

The GetDeinterlaceMode method retrieves the deinterlacing mode for the specified video stream.

Syntax

HRESULT GetDeinterlaceMode(
  DWORD  dwStreamID,
  GUID  *lpDeinterlaceMode,
);

Parameters

dwStreamID

[in] Index of the video stream to check.

lpDeinterlaceMode

[out] Pointer to a variable that receives a GUID. The GUID identifies the deinterlacing mode currently in use. If no deinterlacing mode was set, the value is GUID_NULL.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_FALSE | No deinterlacing mode was set.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

The VMR may not be able to use the requested mode, in which case it falls back to another deinterlace mode, as specified in the IVMRDeinterlaceControl::SetDeinterlacePrefs method.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface
  • IVMRDeinterlaceControl::SetDeinterlaceMode


IVMRDeinterlaceControl::GetDeinterlaceModeCaps

This topic applies to Windows XP Service Pack 1 only.

The GetDeinterlaceModeCaps method retrieves the capabilities of a specific deinterlacing mode supported by the graphics device driver.

Syntax

HRESULT GetDeinterlaceModeCaps(
  GUID  *lpDeinterlaceMode,
  VMRVideoDesc* lpVideoDescription,
  VMRDeinterlaceCaps* lpDeinterlaceCaps
);

Parameters

lpDeinterlaceMode

[in] Pointer to a GUID that identifies the deinterlacing mode. Call the GetNumberOfDeinterlaceModes method to obtain a list of GUIDs supported by the driver.

lpVideoDescription

[in] Pointer to a VMRVideoDesc structure describing the video to deinterlace.

lpDeinterlaceCaps

[out] Pointer to a VMRDeinterlaceCaps structure. The method fills this structure with information about the specified deinterlacing mode.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_DDRAW_CAPS_NOT_SUITABLE | The video card does not support hardware deinterlacing.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface


IVMRDeinterlaceControl::GetDeinterlacePrefs

This topic applies to Windows XP Service Pack 1 only.

The GetDeinterlacePrefs method queries how the VMR will select a deinterlacing mode if it cannot use the preferred deinterlacing mode.

Syntax

HRESULT GetDeinterlacePrefs(
  DWORD *lpdwDeinterlacePrefs
);

Parameters

lpdwDeinterlacePrefs

[in] Pointer to a variable that receives a member of the VMRDeinterlacePrefs enumeration.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

By default, the preferred deinterlacing mode is the first mode reported by the driver. The application can set the preferred mode by calling the IVMRDeinterlaceControl::SetDeinterlaceMode method. If the VMR cannot use the preferred mode, it will fall back to another mode as specified by the dwDeinterlacePrefs parameter.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface
  • IVMRDeinterlaceControl::SetDeinterlacePrefs


IVMRDeinterlaceControl::GetNumberOfDeinterlaceModes

This topic applies to Windows XP Service Pack 1 only.

The GetNumberOfDeinterlaceModes method retrieves the deinterlacing modes available to the VMR for the specified video format.

Syntax

HRESULT GetNumberOfDeinterlaceModes(
  VMRVideoDesc*  lpVideoDescription,
  DWORD *lpdwNumDeinterlaceModes,
  GUID *lpDeinterlaceModes
);

Parameters

lpVideoDescription

[in] Pointer to a VMRVideoDesc structure that describes the video.

lpdwNumDeinterlaceModes

[in, out] Pointer to a DWORD value. On input, this value specifies the size of the array given in lpDeinterlaceModes. On output, it receives number of GUIDs the method copied into the array.

lpDeinterlaceModes

[out] Address of an array allocated by caller. The method fills the array with GUID values. To determine the size of the array that is needed, set this parameter to NULL and check the value returned in lpdwNumDeinterlaceModes.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.
VFW_E_DDRAW_CAPS_NOT_SUITABLE | The video card does not support hardware deinterlacing.

Remarks

This method returns an array of GUIDs, where each GUID represents a deinterlacing mode that is supported in hardware by the graphics device driver. The array is sorted by quality, so the first entry represents the best quality, the second entry represents the next best quality, and so forth.

All drivers are required to support the following mode:

GUID | Description
DXVA_DeinterlaceBobDevice | Bob mode

Drivers can support additional modes and should define their own GUIDs to identify them. For each returned mode, call the IVMRDeinterlaceControl::GetDeinterlaceModeCaps method to get information about that mode.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface


IVMRDeinterlaceControl::SetDeinterlaceMode

This topic applies to Windows XP Service Pack 1 only.

The SetDeinterlaceMode method sets the deinterlacing mode for the specified video stream.

Syntax

HRESULT SetDeinterlaceMode(
  DWORD  dwStreamID,
  GUID  *lpDeinterlaceMode,
);

Parameters

dwStreamID

[in] Index of the video stream to set. To set all streams, use the value 0xFFFFFFFF.

lpDeinterlaceMode

[in] Pointer to a GUID that specifies the deinterlacing mode. To turn off deinterlacing, use the value GUID_NULL.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

If the application does not specify the mode, the VMR defaults to the first mode reported by the driver. In either case, if the VMR cannot use the preferred mode, it falls back to another mode as specified in the IVMRDeinterlaceControl::SetDeinterlacePrefs method.

The SetDeinterlaceMode method is effective only for new connections made to the VMR. Some deinterlacing mode require that additional reference samples be available; the exact number depends on the mode. The VMR allocates surfaces for these additional samples. The client must set the deinterlace mode before the surfaces have been allocated. Surface allocation occurs after any of the following:

  • Pin connections, including dynamic reconnections
  • Dynamic format changes (the upstream filter calls IPin::ReceiveConnection to specify a new format)
  • Resolution changes
  • Monitor changes

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface
  • IVMRDeinterlaceControl::GetDeinterlaceMode


IVMRDeinterlaceControl::SetDeinterlacePrefs

This topic applies to Windows XP Service Pack 1 only.

The SetDeinterlacePrefs method specifies how the VMR will select a deinterlacing mode if it cannot use the preferred deinterlacing mode.

Syntax

HRESULT SetDeinterlacePrefs(
  DWORD dwDeinterlacePrefs
);

Parameters

lpdwDeinterlacePrefs

[in] Specifies a member of the VMRDeinterlacePrefs enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

By default, the preferred deinterlacing mode is the first mode reported by the driver. The application can set the preferred mode by calling the IVMRDeinterlaceControl::SetDeinterlaceMode method. If the VMR cannot use the preferred mode, it will fall back to another mode as specified by the dwDeinterlacePrefs parameter.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface
  • IVMRDeinterlaceControl::GetDeinterlacePrefs


IVMRDeinterlaceControl9 Interface

The IVMRDeinterlaceControl9 interface supports hardware-accelerated deinterlacing using the Video Mixing Renderer Filter 9 (VMR-9). This interface enables applications or other filters to control how the VMR manages DirectX Video Acceleration (DirectX VA) hardware deinterlacing.

In addition to the methods inherited from IUnknown, the IVMRDeinterlaceControl9 interface exposes the following methods.

Method | Description
GetActualDeinterlaceMode | Returns the deinterlacing mode that the VMR is using for a specified stream.
GetDeinterlaceMode | Retrieves the deinterlacing mode for the specified video stream.
GetDeinterlaceModeCaps | Retrieves the capabilities of a specific deinterlacing mode supported by the graphics device driver.
GetDeinterlacePrefs | Queries how the VMR will select a deinterlacing mode if it cannot use the preferred mode.
GetNumberOfDeinterlaceModes | Retrieves the deinterlacing modes available to the VMR for the specified video format.
SetDeinterlaceMode | Sets the deinterlacing mode for the specified video stream.
SetDeinterlacePrefs | Specifies how the VMR will select a deinterlacing mode if it cannot use the preferred mode.

Remarks

Deinterlacing modes are identified by GUIDs. The graphics device driver returns an array of GUIDs for the modes that it supports. The array is sorted in order of quality, from best quality to lowest quality. To retrieve the list of GUIDs, call the GetNumberOfDeinterlaceModes method. To obtain more information about a particular mode, pass this GUID to the GetDeinterlaceModeCaps method. To configure the VMR to use a particular mode, call the SetDeinterlaceMode method.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Setting Deinterlace Preferences


IVMRDeinterlaceControl9::GetActualDeinterlaceMode

The GetActualDeinterlaceMode method returns the deinterlacing mode that the VMR is using for a specified stream.

Syntax

HRESULT GetActualDeinterlaceMode(
    DWORD dwStreamID,
    GUID *lpDeinterlaceMode
);

Parameters

dwStreamID

[in] Index of the video stream.

lpDeinterlaceMode

[out] Pointer to a variable that receives a GUID value that identifies the deinterlacing mode. The method returns GUID_NULL if the VMR has not initialized the deinterlacing hardware, or if the VMR determines that this stream should not be deinterlaced.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::GetDeinterlaceMode

The GetDeinterlaceMode method retrieves the deinterlacing mode for the specified video stream.

Syntax

HRESULT GetDeinterlaceMode(
  DWORD  dwStreamID,
  GUID  *lpDeinterlaceMode,
);

Parameters

dwStreamID

[in] Index of the video stream to check.

lpDeinterlaceMode

[out] Pointer to a variable that receives a GUID. The GUID identifies the deinterlacing mode currently in use. If no deinterlacing mode was set, the value is GUID_NULL.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_FALSE | No deinterlacing mode was set.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

The VMR may not be able to use the requested mode, in which case it falls back to another deinterlace mode, as specified in the IVMRDeinterlaceControl9::SetDeinterlacePrefs method.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::GetDeinterlaceModeCaps

The GetDeinterlaceModeCaps method retrieves the capabilities of a specific deinterlacing mode supported by the graphics device driver.

Syntax

HRESULT GetDeinterlaceModeCaps(
  GUID  *lpDeinterlaceMode,
  VMR9VideoDesc* lpVideoDescription,
  VMR9DeinterlaceCaps* lpDeinterlaceCaps
);

Parameters

lpDeinterlaceMode

[in] Pointer to a GUID that identifies the deinterlacing mode. Call the IVMRDeinterlaceControl9::GetNumberOfDeinterlaceModes method to obtain a list of GUIDs supported by the driver.

lpVideoDescription

[in] Pointer to a VMR9VideoDesc structure describing the video to deinterlace.

lpDeinterlaceCaps

[out] Pointer to a VMR9DeinterlaceCaps structure. The method fills this structure with information about the specified deinterlacing mode.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_DDRAW_CAPS_NOT_SUITABLE | The video card does not support hardware deinterlacing.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::GetDeinterlacePrefs

The GetDeinterlacePrefs method queries how the VMR will select a deinterlacing mode if it cannot use the preferred deinterlacing mode.

Syntax

HRESULT GetDeinterlacePrefs(
  DWORD *lpdwDeinterlacePrefs
);

Parameters

lpdwDeinterlacePrefs

[in] Pointer to a variable that receives a member of the VMR9DeinterlacePrefs enumeration.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

By default, the preferred deinterlacing mode is the first mode reported by the driver. The application can set the preferred mode by calling the IVMRDeinterlaceControl9::SetDeinterlaceMode method. If the VMR cannot use the preferred mode, it will fall back to another mode as specified by the dwDeinterlacePrefs parameter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::GetNumberOfDeinterlaceModes

The GetNumberOfDeinterlaceModes method retrieves the deinterlacing modes available to the VMR for the specified video format.

Syntax

HRESULT GetNumberOfDeinterlaceModes(
  VMR9VideoDesc*  lpVideoDescription,
  DWORD *lpdwNumDeinterlaceModes,
  GUID *lpDeinterlaceModes
);

Parameters

lpVideoDescription

[in] Pointer to a VMR9VideoDesc structure that describes the video.

lpdwNumDeinterlaceModes

[in, out] Pointer to a DWORD value. On input, this value specifies the size of the array given in lpDeinterlaceModes. On output, it receives number of GUIDs the method copied into the array.

lpDeinterlaceModes

[out] Address of an array allocated by caller. The method fills the array with GUID values. To determine the size of the array that is needed, set this parameter to NULL and check the value returned in lpdwNumDeinterlaceModes.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.
VFW_E_DDRAW_CAPS_NOT_SUITABLE | The video card does not support hardware deinterlacing.

Remarks

This method returns an array of GUIDs, where each GUID represents a deinterlacing mode that is supported in hardware by the graphics device driver. The array is sorted by quality, so the first entry represents the best quality, the second entry represents the next best quality, and so forth.

All drivers are required to support the following mode:

GUID | Description
DXVA_DeinterlaceBobDevice | Bob mode

Drivers can support additional modes and should define their own GUIDs to identify them. For each returned mode, call the IVMRDeinterlaceControl9::GetDeinterlaceModeCaps method to get information about that mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::SetDeinterlaceMode

The SetDeinterlaceMode method sets the deinterlacing mode for the specified video stream.

Syntax

HRESULT SetDeinterlaceMode(
  DWORD  dwStreamID,
  GUID  *lpDeinterlaceMode,
);

Parameters

dwStreamID

[in] Index of the video stream to set. To set all streams, use the value 0xFFFFFFFF.

lpDeinterlaceMode

[in] Pointer to a GUID that specifies the deinterlacing mode. To turn off deinterlacing, use the value GUID_NULL.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

If the application does not specify the mode, the VMR defaults to the first mode reported by the driver. In either case, if the VMR cannot use the preferred mode, it falls back to another mode as specified in the IVMRDeinterlaceControl9::SetDeinterlacePrefs method.

The SetDeinterlaceMode method is effective only for new connections made to the VMR. Some deinterlacing mode require that additional reference samples be available; the exact number depends on the mode. The VMR allocates surfaces for these additional samples. The client must set the deinterlace mode before the surfaces have been allocated. Surface allocation occurs after any of the following:

  • Pin connections, including dynamic reconnections
  • Dynamic format changes (the upstream filter calls IPin::ReceiveConnection to specify a new format)
  • Resolution changes
  • Monitor changes

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl Interface
  • IVMRDeinterlaceControl9 Interface


IVMRDeinterlaceControl9::SetDeinterlacePrefs

The SetDeinterlacePrefs method specifies how the VMR will select a deinterlacing mode if it cannot use the preferred deinterlacing mode.

Syntax

HRESULT SetDeinterlacePrefs(
  DWORD dwDeinterlacePrefs
);

Parameters

lpdwDeinterlacePrefs

[in] Specifies a member of the VMR9DeinterlacePrefs enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following:

Return Code | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_VMR_NOT_IN_MIXER_MODE | The VMR is not in mixer mode.

Remarks

By default, the preferred deinterlacing mode is the first mode reported by the driver. The application can set the preferred mode by calling the IVMRDeinterlaceControl9::SetDeinterlaceMode method. If the VMR cannot use the preferred mode, it will fall back to another mode as specified by the dwDeinterlacePrefs parameter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • Error and Success Codes
  • IVMRDeinterlaceControl9 Interface


IVMRFilterConfig Interface

The IVMRFilterConfig interface is used to configure the operating mode and video rendering mechanisms of the Video Mixing Renderer Filter 7 (VMR-7). For the VMR-9, use the IVMRFilterConfig9 interface.

Applications must add the VMR to the graph and configure it before connecting it to any upstream filters (for example, in a call to IGraphBuilder::RenderFile). Once a filter has been connected to the VMR, the VMR's configuration is locked and all future attempts to alter it fail.

In addition to the methods inherited from IUnknown, the IVMRFilterConfig interface exposes the following methods.

Method | Description
GetNumberOfStreams | Retrieves the number of input streams being mixed.
GetRenderingMode | Retrieves the rendering mode currently being used by the VMR.
GetRenderingPrefs | Retrieves the current set of rendering preferences being used by the VMR.
SetImageCompositor | Installs an application-provided image compositor object.
SetNumberOfStreams | Sets the number of streams to be mixed and instructs the VMR to go into mixer mode.
SetRenderingMode | Sets the rendering mode used by the VMR.
SetRenderingPrefs | Sets various application preferences related to video rendering.


IVMRFilterConfig::GetNumberOfStreams

The GetNumberOfStreams method retrieves the number of input streams being mixed.

Syntax

HRESULT GetNumberOfStreams(
  DWORD*  pdwMaxStreams
);

Parameters

pdwMaxStreams

[out] Pointer to a double word that receives the number of streams being mixed, which is equal to the number of input pins on the VMR.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Return Code | Description
E_POINTER | PdwMaxStreams is invalid

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::SetNumberOfStreams


IVMRFilterConfig::GetRenderingMode

The GetRenderingMode method retrieves the rendering mode currently being used by the VMR.

Syntax

HRESULT GetRenderingMode(
  DWORD*  pMode
);

Parameters

pMode

[out] Pointer to a DWORD that receives a VMRMode value indicating the current rendering mode.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pMode is invalid

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::SetRenderingMode


IVMRFilterConfig::GetRenderingPrefs

The GetRenderingPrefs method retrieves the current set of rendering preferences being used by the VMR.

Syntax

HRESULT GetRenderingPrefs(
  DWORD*  pdwRenderFlags
);

Parameters

pdwRenderFlags

[out] Pointer to DWORD that receives a VMRRenderPrefs value indicating the current rendering preferences.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pdwRenderingPrefs is invalid
VFW_E_WRONG_STATE | No allocator-presenter object is currently loaded.

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::SetRenderingPrefs


IVMRFilterConfig::SetImageCompositor

The SetImageCompositor method installs an application-provided image compositor object.

Syntax

HRESULT SetImageCompositor(
  IVMRImageCompositor*  lpVMRImgCompositor
);

Parameters

lpVMRImgCompositor

[in] Pointer to the image compositor object provided by the application.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The mixer is not currently loaded.

Remarks

Use this method to replace the VMR's default compositor with a custom compositor provided by the application. The image compositor is a sub-component of the mixer. The mixer must be loaded, through a call to IVMRFilterConfig::SetNumberOfStreams, before the compositor can be specified. The VMR manages all reference counting on the IVMRImageCompositor interface.

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface


IVMRFilterConfig::SetNumberOfStreams

The SetNumberOfStreams method sets the number of streams to be mixed and instructs the VMR to go into mixer mode.

Syntax

HRESULT SetNumberOfStreams(
  DWORD  dwMaxStreams
);

Parameters

dwMaxStreams

[in] Double word containing the maximum number of input streams that the VMR will be required to mix. Must not be greater than MAX_MIXER_STREAMS (16).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_FAIL | The mixer is already configured.
E_INVALIDARG | An attempt was made to configure the mixer for more than 16 input streams.
E_OUTOFMEMORY | Memory to manage the streams could not be allocated.

Remarks

dwMaxStreams should be equal to the number of input pins required. Pins cannot be added or removed after the VMR has been connected. If you do not know in advance how many input streams will be required, set dxMaxStreams to the maximum number that might be required. A value of 1 is valid for dwMaxStreams. This value does not cause any extra pins to be created, but it does force the VMR to go into "mixer mode." Therefore, once this method has been called, you cannot call SetRenderingMode to set the mode to VMRMode_Renderless

The VMR creates as many input pins as are specified without attempting to determine whether there is enough video memory to support them all. This is because it has no way of knowing the media type or rectangle dimensions at this time. Later, when an upstream filter attempts to connect to a pin, at that point the media type is known and the VMR will examine the video memory and fail the connection if there is not enough to process the stream.

Note Although the VMR supports multiple streams, they all share a single clock, and therefore you cannot seek one stream independently of the others. If you need to seek the input streams independently, you must use a different technique. See the VMRMulti sample for more information.

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::GetNumberOfStreams


IVMRFilterConfig::SetRenderingMode

The SetRenderingMode method sets the rendering mode used by the VMR.

Syntax

HRESULT SetRenderingMode(
  DWORD  Mode
);

Parameters

Mode

[in] Specifies the rendering mode as a VMRMode value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_INVALIDARG | An invalid rendering mode was specified.
VFW_E_WRONG_STATE | The mode cannot be changed for some reason. See Remarks.

Remarks

The VMR is in VMRMode_Windowed by default. Use this method only if you are putting the VMR into VMRMode_Windowless or VMRMode_Renderless mode. You cannot change the mode after any pin has been connected and you cannot change the mode from windowless or renderless back to windowed, even before any pins are connected. Therefore, specifying VMRMode_Windowed for Mode has no effect under any circumstances.

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::GetRenderingMode


IVMRFilterConfig::SetRenderingPrefs

The SetRenderingPrefs method sets various application preferences related to video rendering.

Syntax

HRESULT SetRenderingPrefs(
  DWORD  dwRenderFlags
);

Parameters

dwRenderFlags

[in] Double word containing a bitwise OR of VMRRenderPrefs values specifying the rendering preferences.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | No allocator-presenter is present.
E_INVALIDARG | dwRenderFlags is invalid.

See Also

  • Error and Success Codes
  • IVMRFilterConfig Interface
  • IVMRFilterConfig::GetRenderingPrefs


IVMRFilterConfig9 Interface

The IVMRFilterConfig9 interface is implemented by the Video Mixing Renderer Filter 9. Applications use this interface to configure the VMR's operating mode and video rendering mechanisms. Applications must add the VMR to the graph and configure it before it is connected to any upstream filters (for example, in a call to IGraphBuilder::RenderFile). Once a filter has been connected to the VMR, the VMR's configuration is locked and all future attempts to alter it fail.

In addition to the methods inherited from IUnknown, the IVMRFilterConfig9 interface exposes the following methods.

Method | Description
GetNumberOfStreams | Retrieves the number of input streams being mixed.
GetRenderingMode | Retrieves the rendering mode currently being used by the VMR.
GetRenderingPrefs | Retrieves the current set of rendering preferences being used by the VMR.
SetImageCompositor | Installs an application-provided image compositor object.
SetNumberOfStreams | Sets the number of streams to be mixed and instructs the VMR to go into mixer mode.
SetRenderingMode | Sets the rendering mode used by the VMR.
SetRenderingPrefs | Sets various application preferences related to video rendering.

Requirements

Include D3d9.h, Vmr9.h.


IVMRFilterConfig9::GetNumberOfStreams

The GetNumberOfStreams method retrieves the number of input streams being mixed.

Syntax

HRESULT GetNumberOfStreams(
  DWORD*  pdwMaxStreams
);

Parameters

pdwMaxStreams

[out] Pointer to a double word that receives the number of streams being mixed, which is equal to the number of input pins on the VMR.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | PdwMaxStreams is invalid

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::GetRenderingMode

The GetRenderingMode method retrieves the rendering mode currently being used by the VMR.

Syntax

HRESULT GetRenderingMode(
  DWORD*  pMode
);

Parameters

pMode

[out] Pointer to a double word that receives the number of streams being mixed, which is equal to the number of input pins on the VMR.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pMode is invalid

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::GetRenderingPrefs

The GetRenderingPrefs method retrieves the current set of rendering preferences being used by the VMR.

Syntax

HRESULT GetRenderingPrefs(
  DWORD*  pdwRenderFlags
);

Parameters

pdwRenderFlags

[out] Pointer to DWORD that receives a VMR9RenderPrefs value indicating the current rendering preferences.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pdwRenderingPrefs is invalid.
VFW_E_WRONG_STATE | No allocator-presenter object is currently loaded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::SetImageCompositor

The SetImageCompositor method installs an application-provided image compositor object.

Syntax

HRESULT SetImageCompositor(
  IVMRImageCompositor9*  lpVMRImgCompositor
);

Parameters

lpVMRImgCompositor

[in] Pointer to the image compositor object provided by the application.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The mixer is not currently loaded.

Remarks

Use this method to replace the VMR's default compositor with a custom compositor provided by the application. The image compositor is a sub-component of the mixer. The mixer must be loaded, through a call to IVMRFilterConfig9::SetNumberOfStreams,

before the compositor can be specified. The VMR manages all reference counting on the IVMRImageCompositor9 interface.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::SetNumberOfStreams

The SetNumberOfStreams method sets the number of streams to be mixed and instructs the VMR to go into mixer mode.

Syntax

HRESULT SetNumberOfStreams(
  DWORD  dwMaxStreams
);

Parameters

dwMaxStreams

[in] Double word containing the maximum number of input streams that the VMR will be required to mix.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The mixer is already configured.
E_INVALIDARG | An attempt was made to configure the mixer for more than 16 input streams.
E_OUTOFMEMORY | Memory to manage the streams could not be allocated.

Remarks

dwMaxStreams should be equal to the number of input pins required. Pins cannot be added or removed after the VMR has been connected. If you do not know in advance how many input streams will be required, set dxMaxStreams to the maximum number that might be required. A value of 1 is valid for dwMaxStreams. This value does not cause any extra pins to be created, but it does force the VMR to go into "mixer mode."

The VMR creates as many input pins as are specified without attempting to determine whether there is enough video memory to support them all. This is because it has no way of knowing the media type or rectangle dimensions at this time. Later, when an upstream filter attempts to connect to a pin, at that point the media type is known and the VMR will examine the video memory and fail the connection if there is not enough memory to process the stream.

Note Although the VMR supports multiple streams, they all share a single clock, and therefore you cannot seek one stream independently of the others. If you need to seek the input streams independently, you must use a different technique. See the VMRMulti sample for more information.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::SetRenderingMode

The SetRenderingMode method sets the rendering mode used by the VMR.

Syntax

HRESULT SetRenderingMode(
  DWORD  Mode
);

Parameters

Mode

[in] Specifies the rendering mode as a VMR9Mode value.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_INVALIDARG | An invalid rendering mode was specified.
VFW_E_WRONG_STATE | The mode cannot be changed for some reason. See Remarks.

Remarks

The VMR is in VMRMode_Windowed by default. Use this method only if you are putting the VMR into VMRMode_Windowless or VMRMode_Renderless mode. You cannot change the mode after any pin has been connected and you cannot change the mode from windowless or renderless back to windowed, even before any pins are connected. Therefore, specifying VMRMode_Windowed for Mode has no effect under any circumstances.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRFilterConfig9::SetRenderingPrefs

The SetRenderingPrefs method sets various application preferences related to video rendering.

Syntax

HRESULT SetRenderingPrefs(
  DWORD  dwRenderFlags
);

Parameters

dwRenderFlags

[in] Double word containing a bitwise OR of VMR9RenderPrefs values specifying the rendering preferences.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | No allocator-presenter is present.
E_INVALIDARG | dwRenderFlags is invalid.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRFilterConfig9 Interface


IVMRImageCompositor Interface

The IVMRImageCompositor interface is implemented by the default compositor for the Video Mixing Renderer Filter 7 (VMR-7). It must also be implemented by any plug-in compositor that an application provides for the VMR-7. The VMR07 calls the methods on this interface to inform the Compositor that it should composite the incoming video frames into a single output frame. Applications do not use this interface.

For the VMR-9, use the IVMRImageCompositor9 interface.

In addition to the methods inherited from IUnknown, the IVMRImageCompositor interface exposes the following methods.

Method | Description
CompositeImage | Composites the current frames available in each input stream.
InitCompositionTarget | Informs the compositor that a new composition target has been created.
SetStreamMediaType | Sets the media type for the input stream.
TermCompositionTarget | Informs the compositor that the current composition target is being replaced.


IVMRImageCompositor::CompositeImage

The CompositeImage method composites the current frames available in each input stream.

Syntax

HRESULT CompositeImage(
  IUnknown*  pD3DDevice,
  LPDIRECTDRAWSURFACE7  pddsRenderTarget,
  AM_MEDIA_TYPE*  pmtRenderTarget,
  REFERENCE_TIME  rtStart,
  REFERENCE_TIME  rtEnd,
  DWORD  clrBkgnd,
  VMRVIDEOSTREAMINFO*  pVideoStreamInfo,
  UINT  cStreams
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device. The compositor must cast this to a LPDIRECT3DDEVICE7 type.

pddsRenderTarget

[in] Specifies the DirectDraw surface that all drawing should be performed on.

pmtRenderTarget

[in] Specifies the media type of the DirectDraw surface.

rtStart

[in] Specifies the start time.

rtEnd

[in] Specifies the end time.

clrBkgnd

[in] Specifies the background color.

pVideoStreamInfo

[in] Pointer to an array of video stream info objects.

cStreams

[in] Specifies the number of streams to be mixed, which is equal to the size of the pVideoStreamInfo array.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRImageCompositor Interface


IVMRImageCompositor::InitCompositionTarget

The InitCompositionTarget method informs the compositor that a new composition target has been created. The compositor should perform any necessary configuration work in this method. This could include attaching a a Z or stencil buffer buffer for the new render target

Syntax

HRESULT InitCompositionTarget(
  IUnknown*  pD3DDevice,
  LPDIRECTDRAWSURFACE7  pddsRenderTarget
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device object.

pddsRenderTarget

[in] Specifies the DirectDraw surface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRImageCompositor Interface


IVMRImageCompositor::SetStreamMediaType

The SetStreamMediaType method sets the media type for the input stream.

Syntax

HRESULT SetStreamMediaType(
  DWORD dwStrmID,
  AM_MEDIA_TYPE* pmt,
  BOOL fTexture
);

Parameters

dwStrmID

Specifies the input stream. The value must be from 1 through 16.

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

fTexture

If true, specifies that the target surface is a Direct3D texture surface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes


IVMRImageCompositor::TermCompositionTarget

The TermCompositionTarget method informs the compositor that the current composition target is being replaced. Compositors should perform any necessary cleanup of the composition target in this method.

HRESULT TermCompositionTarget(
  IUnknown*  pD3DDevice,
  LPDIRECTDRAWSURFACE7  pddsRenderTarget
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device object.

pddsRenderTarget

[in] Specifies the DirectDraw surface

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRImageCompositor Interface


IVMRImageCompositor9 Interface

The IVMRImageCompositor9 interface is implemented by the default compositor for the Video Mixing Renderer Filter 9 (VMR-9). It must also be implemented by any plug-in compositor that an application provides for the VMR-9. The VMR-9 calls the methods on this interface to inform the compositor that it should composite the incoming video frames into a single output frame. Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IVMRImageCompositor9 interface exposes the following methods.

Method | Description
CompositeImage | Composites the current frames available in each input stream.
InitCompositionDevice | Informs the compositor that a new composition target has been created.
SetStreamMediaType | Sets the media type for the input stream.
TermCompositionDevice | Informs the compositor that the current composition target is being replaced.

Requirements

Include D3d9.h, Vmr9.h.


IVMRImageCompositor9::CompositeImage

The CompositeImage method composites the current frames available in each input stream.

Syntax

HRESULT CompositeImage(
  IUnknown*  pD3DDevice,
  IDirect3DSurface9*  pddsRenderTarget,
  AM_MEDIA_TYPE*  pmtRenderTarget,
  REFERENCE_TIME  rtStart,
  REFERENCE_TIME  rtEnd,
  D3DCOLOR  dwClrBkGnd,
  VMR9VideoStreamInfo*  pVideoStreamInfo,
  UINT  cStreams
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device object.

pddsRenderTarget

[in] Specifies the Direct3D surface that all drawing should be performed on.

pmtRenderTarget

[in] Pointer to an AM_MEDIA_TYPE structure that contains the media type of the target surface.

rtStart

[in] Specifies the start time.

rtEnd

[in] Specifies the end time.

dwClrBkGnd

[in] Specifies the background color, as a D3DCOLOR type.

pVideoStreamInfo

[in] Pointer to an array of VMR9VideoStreamInfo structures, which descibe each video stream.

cStreams

[in] Specifies the number of streams to mix, which is also the size of the pVideoStreamInfo array.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImageCompositor9 Interface


IVMRImageCompositor9::InitCompositionDevice

The InitCompositionDevice method informs the compositor that a new composition target has been created. The compositor should perform any necessary configuration work in this method. This could include attaching a Z or stencil buffer for the new render target.

Syntax

HRESULT InitCompositionDevice(
  IUnknown*  pD3DDevice
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device object.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImageCompositor9 Interface


IVMRImageCompositor9::SetStreamMediaType

The SetStreamMediaType method sets the media type for the input stream.

Syntax

HRESULT SetStreamMediaType(
  DWORD  dwStrmID,
  AM_MEDIA_TYPE*  pmt,
  BOOL  fTexture
);

Parameters

dwStrmID

[in] Specifies the input stream; must be from 1 through 16.

pmt

[in] Pointer to the AM_MEDIA_TYPE struct that specifies the media type.

fTexture

[in] If true, specifies that the target surface is a Direct3D texture surface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImageCompositor9 Interface


IVMRImageCompositor9::TermCompositionDevice

The TermCompositionDevice method informs the compositor that the current composition target is being replaced. Compositors should perform any necessary cleanup of the composition target in this method.

Syntax

HRESULT TermCompositionDevice(
  IUnknown*  pD3DDevice
);

Parameters

pD3DDevice

[in] Pointer to the IUnknown interface of the Direct3D device object.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImageCompositor9 Interface


IVMRImagePresenter Interface

The IVMRImagePresenter interface is implemented by the default Allocator-Presenter for the Video Mixing Renderer Filter 7 (VMR-7). It must also be implemented by any plug-in Allocator-Presenter that an application provides for the VMR-7. The VMR-7 uses the methods on this interface to inform the Allocator-Presenter that it should present the video frame contained in the supplied Direct Draw surface. Applications do not use this interface.

For the VMR-9, use the IVMRImagePresenter9 interface.

In addition to the methods inherited from IUnknown, the IVMRImagePresenter interface exposes the following methods.

IVMRImagePresenter Methods | Description
PresentImage | Called at precisely the moment this video frame should be presented.
StartPresenting | Called just before the video starts playing.
StopPresenting | Called just after the video stops playing.


IVMRImagePresenter::PresentImage

The PresentImage method is called at precisely the moment this video frame should be presented.

Syntax

HRESULT PresentImage(
  DWORD_PTR  dwUserID,
  VMRPRESENTATIONINFO*  lpPresInfo
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR that uniquely identifies this instance of the VMR in scenarios when multiple instances of the VMR are being used with a single instance of an Allocator-Presenter. See Remarks

lpPresInfo

[in] Specifies the VMRPRESENTATIONINFO structure.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

PresentImage can be called when the filter is in either a running or a paused state. StartPresenting and StopPresenting can be called only in a running state. Therefore, if the graph is paused before it is run, PresentImage will be called before StartPresenting.

Applications can create custom blending effects by using a single instance of an Allocator-Presenter with multiple instances of the VMR either in a single filter graph or in multiple filter graphs. Using the allocator presenter in this way enables applications to blend streams from different filter graphs, or blend different streams within the same filter graph. If you are using a single instance of the VMR, set this value to zero.

See Also

  • Error and Success Codes
  • IVMRImagePresenter Interface


IVMRImagePresenter::StartPresenting

The StartPresenting method is called just before the video starts playing. The allocator-presenter should perform any necessary configuration in this method.

Syntax

HRESULT StartPresenting(
  DWORD_PTR  dwUserID
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

PresentImage can be called when the filter is in either a running or a paused state. StartPresenting and StopPresenting can be called only in a running state. Therefore, if the graph is paused before it is run, PresentImage will be called before StartPresenting.

See Also

  • IVMRImagePresenter Interface
  • IVMRImagePresenter::StopPresenting


IVMRImagePresenter::StopPresenting

The StopPresenting method is called just after the video stops playing. The allocator-presenter should perform any necessary cleanup in this method.

Syntax

HRESULT StopPresenting(
  DWORD_PTR  dwUserID
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

StopPresenting can be called only when the VMR is in a running state.

See Also

  • IVMRImagePresenter Interface
  • IVMRImagePresenter::StartPresenting


IVMRImagePresenter9 Interface

The IVMRImagePresenter9 interface is implemented by the default allocator-presenter for the Video Mixing Renderer Filter 9 (VMR-9). It must also be implemented by any plug-in allocator-presenter that an application provides for the VMR-9. The VMR-9 uses this interface to inform the allocator-presenter that it should present the video frame contained in the supplied Direct3D surface. Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IVMRImagePresenter9 interface exposes the following methods.

Method | Description
PresentImage | Called at precisely the moment this video frame should be presented.
StartPresenting | Called just before the video starts playing.
StopPresenting | Called just after the video stops playing.

Requirements

Include D3d9.h, Vmr9.h.


IVMRImagePresenter9::PresentImage

The PresentImage method is called at precisely the moment this video frame should be presented.

Syntax

HRESULT PresentImage(
  DWORD_PTR  dwUserID,
  VMR9PresentationInfo*  lpPresInfo
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR that uniquely identifies this instance of the VMR in scenarios when multiple instances of the VMR are being used with a single instance of an allocator-presenter. See Remarks.

lpPresInfo

[in] Specifies a VMR9PresentationInfo structure that contains information about the video frame.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

PresentImage can be called when the filter is in either a running or a paused state. StartPresenting and StopPresenting can be called only in a running state. Therefore, if the graph is paused before it is run, PresentImage will be called before StartPresenting.

Applications can create custom blending effects by using a single instance of an allocator-presenter with multiple instances of the VMR either in a single filter graph or in multiple filter graphs. Using the allocator presenter in this way enables applications to blend streams from different filter graphs, or blend different streams within the same filter graph. If you are using a single instance of the VMR, set this value to zero.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImagePresenter9 Interface


IVMRImagePresenter9::StartPresenting

The StartPresenting method is called just before the video starts playing. The allocator-presenter should perform any necessary configuration in this method.

Syntax

HRESULT StartPresenting(
  DWORD_PTR  dwUserID
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

PresentImage can be called when the filter is in either a running or a paused state. StartPresenting and StopPresenting can be called only in a running state. Therefore, if the graph is paused before it is run, PresentImage will be called before StartPresenting.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImagePresenter9 Interface
  • StopPresenting


IVMRImagePresenter9::StopPresenting

The StopPresenting method is called just after the video stops playing. The allocator-presenter should perform any necessary cleanup in this method.

Syntax

HRESULT StopPresenting(
  DWORD_PTR  dwUserID
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

StopPresenting can be called only when the VMR is in a running state.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImagePresenter9 Interface
  • StartPresenting


IVMRImagePresenterConfig Interface

The IVMRImagePresenterConfig interface provides methods for setting the renderering preferences on the image presenter used by the Video Mixing Renderer Filter 7 (VMR-7). This interface allows applications to configure the default allocator-presenter, in order to simplify the implementation of their own allocator-presenter plug-in. The default allocator-presenter implements this interface.

For the VMR-9, use the IVMRImagePresenterConfig9 interface.

In additions to the methods inherited from IUnknown, the IVMRImagePresenterConfig interface exposes the following methods.

Method | Description
SetRenderingPrefs | Sets the rendering preferences.
GetRenderingPrefs | Gets the rendering preferences.


IVMRImagePresenterConfig::SetRenderingPrefs

The SetRenderingPrefs method sets the rendering preferences on the VMR's allocator-presenter.

Syntax

HRESULT SetRenderingPrefs(
  DWORD dwRenderFlags
);

Parameters

dwRenderFlags

[in] A bitwise OR combination of VMRRenderPrefs flags that will be used to configure the allocator-presenter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRImagePresenterConfig Interface


IVMRImagePresenterConfig::GetRenderingPrefs

The GetRenderingPrefs method retrieves the current rendering preferences on the VMR's allocator-presenter.

Syntax

HRESULT GetRenderingPrefs(
  DWORD* dwRenderFlags
);

Parameters

dwRenderFlags

[out] Pointer that receives a bitwise OR combination of VMRRenderPrefs flags that indicate the current rendering settings on the allocator-presenter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRImagePresenterConfig Interface


IVMRImagePresenterConfig9 Interface

The IVMRImagePresenterConfig9 interface provides methods for setting the rendering preferences on the image presenter used by the Video Mixing Renderer Filter 9 (VMR-9). This interface allows applications to configure the default allocator-presenter, in order to simplify the implementation of their own allocator-presenter plug-in. The default allocator-presenter implements this interface.

In addition to the methods inherited from IUnknown, the IVMRImagePresenterConfig9 interface exposes the following methods.

Method | Description
GetRenderingPrefs | Sets the rendering preferences.
SetRenderingPrefs | Gets the rendering preferences.

Requirements

Include D3d9.h, Vmr9.h.


IVMRImagePresenterConfig9::GetRenderingPrefs

The GetRenderingPrefs method retrieves the current rendering preferences on the VMR's allocator-presenter.

Syntax

HRESULT GetRenderingPrefs(
  DWORD*  dwRenderFlags
);

Parameters

dwRenderFlags

[out] Pointer that receives a bitwise OR combination of VMR9RenderPrefs flags that indicate the current rendering settings on the allocator-presenter.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImagePresenterConfig9 Interface


IVMRImagePresenterConfig9::SetRenderingPrefs

The SetRenderingPrefs method sets the rendering preferences.

Syntax

HRESULT SetRenderingPrefs(
  DWORD  dwRenderFlags
);

Parameters

dwRenderFlags

[in] A bitwise OR combination of VMR9RenderPrefs flags that will be used to configure the allocator-presenter.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRImagePresenterConfig9 Interface


IVMRImagePresenterExclModeConfig Interface

The IVMRImagePresenterExclModeConfig interface inherits from IVMRImagePresenterConfig and provides methods for setting and retrieving the renderering preferences on the Exclusive Mode Allocator-Presenter. This interface is exposed on the DirectDraw Exclusive Mode Allocator-Presenter object. When applications run in DirectDraw Exclusive Mode, they must create their own DirectDraw object, configure the VMR to use the Exclusive Mode Allocator-Presenter, and use this interface to inform the VMR about the DirectDraw object and the primary surface associated with it. For more information, see DirectDraw Exclusive Mode.

In additions to the methods inherited from IVMRImagePresenterConfig, the IVMRImagePresenterExclModeConfig interface exposes the following methods.

Method | Description
SetXlcModeDDObjAndPrimarySurface | Informs the VMR of the DirectDraw object and primary surface that were created by the application.
GetXlcModeDDObjAndPrimarySurface | Retrieves the DirectDraw object and primary surface currently being used by a VMR that has been configured for DirectDraw Exclusive Mode using the SetXlcModeDDObjAndPrimarySurface method.


IVMRImagePresenterExclModeConfig::SetXlcModeDDObjAndPrimarySurface

The SetXlcModeDDObjAndPrimarySurface method informs the VMR of the DirectDraw object and primary surface that were created by the application.

Syntax

HRESULT SetXlcModeDDObjAndPrimarySurface(
  LPDIRECTDRAW7 lpDDObj,
  LPDIRECTDRAWSURFACE7 lpPrimarySurf
);

Parameters

lpDDObj

[in] Specifies the Exclusive Mode DirectDraw object created by the application.

lpPrimarySurf

[in] Specifies the primary surface associated with the DirectDraw object.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The procedure for configuring and using an application-defined DirectDraw Exclusive Mode object is described in DirectDraw Exclusive Mode.

See Also

  • IVMRImagePresenterExclModeConfig Interface
  • IVMRImagePresenterExclModeConfig::GetXlcModeDDObjAndPrimarySurface


IVMRImagePresenterExclModeConfig::GetXlcModeDDObjAndPrimarySurface

The GetXlcModeDDObjAndPrimarySurface method retrieves the DirectDraw object and primary surface currently being used by a VMR that has been configured for DirectDraw Exclusive Mode using the SetXlcModeDDObjAndPrimarySurface method.

Syntax

HRESULT GetXlcModeDDObjAndPrimarySurface(
  LPDIRECTDRAW7* lpDDObj,
   LPDIRECTDRAWSURFACE7* lpPrimarySurf
);

Parameters

lpDDObj

[out] Retrieves the Exclusive Mode DirectDraw object created by the application.

lpPrimarySurf

[out] Retrieves the primary surface associated with the DirectDraw object.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The procedure for configuring and using an application-defined DirectDraw Exclusive Mode object is described in DirectDraw Exclusive Mode.

See Also

  • IVMRImagePresenterExclModeConfig Interface
  • IVMRImagePresenterExclModeConfig::SetXlcModeDDObjAndPrimarySurface


IVMRMixerBitmap Interface

The IVMRMixerBitmap interface enables an application to blend a static image from a bitmap or DirectDraw surface onto the video stream, when using the Video Mixing Renderer Filter 7 (VMR-7). For the VMR-9, use the IVMRMixerBitmap9 interface.

You can pass images to the VMR as frequently as you like, but changing the image several times per second may impact the performance and smoothness of the video being rendered. The new image will be blended with the next and all subsequent video frames rendered by the VMR.

Internally, the VMR uses its mixer component to perform the blending operation. Therefore the VMR must be configured correctly prior to commencing video playback. Even if only a single video stream is present, applications should call IVMRFilterConfig::SetNumberOfStreams with a value of "1" to cause the VMR to load the mixer and compositor. The image can contain embedded per pixel alpha information; this allows the image to contain regions that are transparent. Transparent areas can also be identified by a color key value. Changes in the image are only shown on the screen while the filter graph is running.

In addition to the methods inherited from IUnknown, the IVMRMixerBitmap interface exposes the following methods.

IVMRMixerBitmap Methods | Description
GetAlphaBitmapParameters | Retrieves a copy of the current image and related blending parameters.
SetAlphaBitmap | Specifies a new bitmap image and the source location of the bitmap and how and where it should be rendered on the destination rectangle.
UpdateAlphaBitmapParameters | Changes the bitmap location, size and blending value.


IVMRMixerBitmap::GetAlphaBitmapParameters

The GetAlphaBitmapParameters method retrieves a copy of the current image and related blending parameters.

Syntax

HRESULT GetAlphaBitmapParameters(
  PVMRALPHABITMAP  pBmpParms
);

Parameters

pBmpParms

[out] Pointer to a VMRALPHABITMAP structure that receives the bitmap, information about the blending values, and the location to blend it.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pBmpParms is invalid.
VFW_E_WRONG_STATE | The mixer has not been loaded.

See Also

  • Error and Success Codes
  • IVMRMixerBitmap Interface
  • IVMRMixerBitmap::SetAlphaBitmap


IVMRMixerBitmap::SetAlphaBitmap

The SetAlphaBitmap method specifies a new bitmap image and the source location of the bitmap and how and where it should be rendered on the destination rectangle.

Syntax

HRESULT SetAlphaBitmap(
  const VMRALPHABITMAP*  pBmpParms
);

Parameters

pBmpParms

[in] Pointer to a VMRALPHABITMAP structure that contains information about the bitmap.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pBmpParms is NULL.
E_INVALIDARG | Indicates a problem with the dwFlags member of the VMRALPHABITMAP structure or failure to specify a valid HDC or DirectDraw surface in the structure, or an invalid value for fAlpha.
E_OUTOFMEMORY | Could not create a destination DC or DIBSection for the bitmap.
E_FAIL | BitBlt to bitmap surface failed.

See Also

  • Error and Success Codes
  • IVMRMixerBitmap Interface
  • IVMRMixerBitmap::GetAlphaBitmapParameters


IVMRMixerBitmap::UpdateAlphaBitmapParameters

The UpdateAlphaBitmapParameters method changes the bitmap location, size and blending value.

Syntax

HRESULT UpdateAlphaBitmapParameters(
  PVMRALPHABITMAP  pBmpParms
);

Parameters

pBmpParms

[in] A PVMRALPHABITMAP, which is defined as a pointer to a VMRALPHABITMAP structure.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The filter graph must be running for the changes to take effect. This method does not change the bitmap image. If you specify a VMRALPHABITMAP structure with no destination or color key set, the bitmap disappears. This behavior is by design for backward compatibility and cannot be changed.

See Also

  • IVMRMixerBitmap Interface


IVMRMixerBitmap9 Interface

The IVMRMixerBitmap9 interface enables an application to blend a static image from a bitmap or Direct3D surface onto the video stream, when using the Video Mixing Renderer Filter 9 (VMR-9).

You can pass images to the VMR as frequently as you like, but changing the image several times per second may impact the performance and smoothness of the video being rendered. The new image will be blended with the next and all subsequent video frames rendered by the VMR.

Internally, the VMR uses its mixer component to perform the blending operation. In the VMR-9, the mixer is always present by default except in "renderless" mode in which the application is performing its own rendering. The image can contain embedded per pixel alpha information; this allows the image to contain regions that are transparent. Transparent areas can also be identified by a color key value. Changes in the image are only shown on the screen while the filter graph is running.

In addition to the methods inherited from IUnknown, the IVMRMixerBitmap9 interface exposes the following methods.

Method | Description
GetAlphaBitmapParameters | Retrieves a copy of the current image and related blending parameters.
SetAlphaBitmap | Specifies a new bitmap image and the source location of the bitmap and how and where it should be rendered on the destination rectangle.
UpdateAlphaBitmapParameters | Changes the bitmap location, size and blending value.

Requirements

Include D3d9.h, Vmr9.h.


IVMRMixerBitmap9::GetAlphaBitmapParameters

The GetAlphaBitmapParameters method retrieves a copy of the current image and related blending parameters.

Syntax

HRESULT GetAlphaBitmapParameters(
  VMR9AlphaBitmap*  pBmpParms
);

Parameters

pBmpParms

[out] Pointer to a VMR9AlphaBitmap structure that receives the bitmap, information about the blending values, and the location to blend it.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pBmpParms is invalid.
VFW_E_WRONG_STATE | The mixer has not been loaded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerBitmap9 Interface


IVMRMixerBitmap9::SetAlphaBitmap

The SetAlphaBitmap method specifies a new bitmap image and the source location of the bitmap and how and where it should be rendered on the destination rectangle.

Syntax

HRESULT SetAlphaBitmap(
  const VMR9AlphaBitmap*  pBmpParms
);

Parameters

pBmpParms

[in] Pointer to a VMR9AlphaBitmap structure that contains information about the bitmap.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pBmpParms is NULL.
E_INVALIDARG | Indicates a problem with the dwFlags member of the VMR9ALPHABITMAP structure or failure to specify a valid HDC or Direct3D surface in the structure, or an invalid value for fAlpha.
E_OUTOFMEMORY | Could not create a destination DC or DIBSection for the bitmap.
E_FAIL | BitBlt to bitmap surface failed.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • GetAlphaBitmapParameters
  • IVMRMixerBitmap9 Interface


IVMRMixerBitmap9::UpdateAlphaBitmapParameters

The UpdateAlphaBitmapParameters method changes the bitmap location, size and blending value.

Syntax

HRESULT UpdateAlphaBitmapParameters(
  const VMR9AlphaBitmap*  pBmpParms
);

Parameters

pBmpParms

[in] Pointer to a VMR9AlphaBitmap structure.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The filter graph must be running for the changes to take effect. This method does not change the bitmap image. If you specify a VMR9AlphaBitmap structure with no destination or color key set, the bitmap disappears. This behavior is by design for backward compatibility and cannot be changed.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerBitmap9 Interface


IVMRMixerControl Interface

The IVMRMixerControl interface is enables an application to manipulate the incoming video streams on the Video Mixing Renderer Filter 7 (VMR-7). Although this interface is implemented on the filter, it is actually the mixer component that is being configured. For this reason, this interface is only available when the mixer has been loaded through a call to IVMRFilterConfig::SetNumberOfStreams. This interface is intended for use by applications only; it should not be used by upstream filters.

For the VMR-9, use the IVMRMixerControl9 interface.

In addition to the methods inherited from IUnknown, the IVMRMixerControl interface exposes the following methods:

Method | Description
GetAlpha | Retrieves the constant alpha value that is applie to this video stream.
GetBackgroundClr | Retrieves the background color of the output rectangle.
GetMixingPrefs | Retrieves the mixing preferences for the stream.
GetOutputRect | Retrieves the position of this stream's video rectangle within the composition rectangle.
GetZOrder | Retrieves this video stream's position in the Z order.
SetAlpha | Sets a constant alpha value that is applied to this video stream.
SetBackgroundClr | Sets the background color of the output rectangle.
SetMixingPrefs | Sets the mixing preferences for the stream.
SetOutputRect | Sets the position of this stream within the composition rectangle.
SetZOrder | Sets this video stream's position in the Z-order.


IVMRMixerControl::GetAlpha

The GetAlpha method retrieves the constant alpha value that is applied to this video stream.

Syntax

HRESULT GetAlpha(
  DWORD dwStreamID,
  float*  pAlpha
);

Parameters

dwStreamID

[in] Specifies the input stream.

pAlpha

[out] Pointer to a variable of type float that receives the current alpha value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pAlpha is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface
  • IVMRMixerControl::SetAlpha


IVMRMixerControl::GetBackgroundClr

Gets the current background color on the output rectangle.

Syntax

HRESULT GetBackgroundClr(
  COLORREF* ClrBkg
);

Parameters

ClrBkg

[in] Address of a variable that receives the background color.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface


IVMRMixerControl::GetMixingPrefs

Retrieves the mixing preferences for the stream.

Syntax

HRESULT GetMixingPrefs(
   DWORD* dwMixerPrefs
);

Parameters

dwMixerPrefs

[in] Address of a variable that receives a bitwise OR combination of VMRMixerPrefs flags.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface


IVMRMixerControl::GetOutputRect

The GetOutputRect method retrieves the position of this stream's video rectangle within the composition rectangle.

Syntax

HRESULT GetOutputRect(
  DWORD dwStreamID,
  NORMALIZEDRECT*  pRect
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[out] Pointer to a NORMALIZEDRECT structure that receives the destination rectangle in composition space.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pRect is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Because this rectangle exists in compositional space, there is no such thing as an "invalid" rectangle. For example, if left is greater than right, it means the video is mirrored in the x direction. An empty rectangle turns off this stream.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface
  • IVMRMixerControl::SetOutputRect


IVMRMixerControl::GetZOrder

The GetZOrder method retrieves this video stream's position in the Z order.

Syntax

HRESULT GetZOrder(
  DWORD dwStreamID,
  DWORD*  pZOrder
);

Parameters

dwStreamID

[in] Specifies the input stream.

pZOrder

[out] Pointer to a DWORD that receives the current position in the Z-order.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pZ is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

The default Z-order is the order in which the pins were created.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface
  • IVMRMixerControl::SetZOrder


IVMRMixerControl::SetAlpha

The SetAlpha method sets a constant alpha value that is applied to this video stream.

Syntax

HRESULT SetAlpha(
  DWORD dwStreamID,
  float  Alpha
);

Parameters

dwStreamID

[in] Specifies the input stream.

Alpha

[in] Specifies the alpha blending value to be applied to all the pixels in this stream.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

The alpha value specified can be between 0.0 (fully transparent) and 1.0 (full opaque).

See Also

  • Error and Success Codes
  • IVMRMixerControl::GetAlpha
  • IVMRMixerControl Interface


IVMRMixerControl::SetBackgroundClr

Sets the background color on the output rectangle.

Syntax

HRESULT SetBackgroundClr(
  COLORREF ClrBkg
);

Parameters

ClrBkg

[in] Specifies the background color.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

Error and Success Codes

IVMRMixerControl Interface


IVMRMixerControl::SetOutputRect

The SetOutputRect method sets the position of this stream within the composition rectangle.

Syntax

HRESULT SetOutputRect(
  DWORD dwStreamID,
  const NORMALIZEDRECT*  pRect
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[in] Pointer to a NORMALIZEDRECT structure that specifies the position of the rectangle with composition space.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | pRect is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Because this rectangle exists in compositional space, there is no such thing as an "invalid" rectangle. For example, set left greater than right to mirror the video in the x direction. Specifying an empty rectangle turns off this stream.

See Also

  • Error and Success Codes
  • IVMRMixerControl::GetOutputRect
  • IVMRMixerControl Interface


IVMRMixerControl::SetMixingPrefs

Sets the mixing preferences for the stream.

Syntax

  HRESULT SetMixingPrefs(
  DWORD dwMixerPrefs
);

Parameters

dwMixerPrefs

[in] Bitwise OR combination of VMRMixerPrefs flags.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRMixerControl Interface


IVMRMixerControl::SetZOrder

The SetZOrder method sets this video stream's position in the Z-order; larger values are further away.

Syntax

HRESULT SetZOrder(
  DWORD dwStreamID,
  DWORD  dwZOrder
);

Parameters

dwStreamID

[in] Specifies the input stream.

dwZOrder

[in] Double word containing the stream's position within the Z-order.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

The default Z-order is the order in which the pins were created. You only need to use this method if you wish to modify the default Z-order.

See Also

  • Error and Success Codes
  • IVMRMixerControl::GetZOrder
  • IVMRMixerControl Interface


IVMRMixerControl9 Interface

The IVMRMixerControl9 interface enables an application to manipulate the incoming video streams on the Video Mixing Renderer Filter 9 (VMR-9). This interface is intended for use by applications only; it should not be used by upstream filters.

In addition to the methods inherited from IUnknown, the IVMRMixerControl9 interface exposes the following methods.

Method | Description
GetAlpha | Retrieves the constant alpha value that is applied to this video stream.
GetBackgroundClr | Retrieves the background color of the output rectangle.
GetMixingPrefs | Retrieves the mixing preferences for the stream.
GetOutputRect | Retrieves the position of this stream's video rectangle within the composition rectangle.
GetProcAmpControl | Retrieves the current image adjustment settings, such as brightness, contrast, hue, and saturation.
GetProcAmpControlRange | Retrieves the range of values for an image adjustment setting.
GetZOrder | Retrieves this video stream's position in the Z-order.
SetAlpha | Sets a constant alpha value that is applied to this video stream.
SetBackgroundClr | Sets the background color of the output rectangle.
SetMixingPrefs | Sets the mixing preferences for the stream.
SetOutputRect | Sets the position of this stream within the composition rectangle.
SetProcAmpControl | Sets the image adjustment.
SetZOrder | Sets this video stream's position in the Z-order.

Requirements

Include D3d9.h, Vmr9.h.


IVMRMixerControl9::GetAlpha

The GetAlpha method retrieves the constant alpha value that is applied to this video stream.

Syntax

HRESULT GetAlpha(
  DWORD  dwStreamID,
  float*  pAlpha
);

Parameters

dwStreamID

[in] Specifies the input stream.

pAlpha

[out] Pointer to a variable that receives the current alpha value.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pAlpha is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::GetBackgroundClr

The GetBackgroundClr method gets the current background color on the output rectangle.

Syntax

HRESULT GetBackgroundClr(
  COLORREF*  lpClrBkg
);

Parameters

lpClrBkg

[in] Address of a variable that receives the background color.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

See Also

  • IVMRMixerControl9 Interface
  • SetBackgroundClr


IVMRMixerControl9::GetMixingPrefs

The GetMixingPrefs method retrieves the mixing preferences for the stream.

Syntax

HRESULT GetMixingPrefs(
  DWORD*  pdwMixerPrefs
);

Parameters

pdwMixerPrefs

[out] Address of a variable that receives a bitwise OR combination of VMR9MixerPrefs flags.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::GetOutputRect

The GetOutputRect method retrieves the position of this stream's video rectangle within the composition rectangle.

Syntax

HRESULT GetOutputRect(
  DWORD  dwStreamID,
  VMR9NormalizedRect*  pRect
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[out] Pointer to a NORMALIZEDRECT structure that receives the destination rectangle in composition space.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pRect is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Because this rectangle exists in compositional space, there is no such thing as an "invalid" rectangle. For example, if left is greater than right, it means the video is mirrored in the x direction. An empty rectangle turns off this stream.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::GetProcAmpControl

The GetProcAmpControl method retrieves the current image adjustment settings for the VMR-9. Image adjustment includes brightness, contrast, hue, and saturation, and is performed by the graphics device. If the graphics driver does not support hardware image adjustment, this method fails.

Syntax

HRESULT GetProcAmpControl(
  DWORD  dwStreamID,
  VMR9ProcAmpControl*  lpClrControl
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[in, out] Pointer to a VMR9ProcAmpControl structure that receives the image adjustment settings. The dwFlags field indicates which properties are supported by the graphics driver.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pin is not connected.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::GetProcAmpControlRange

The GetProcAmpControlRange method retrieves the range of values for an image adjustment setting, such as brightness, contrast, hue, or saturation. Image adjustment is performed by the graphics device, so the valid range depends on the graphics driver. If the driver does not support hardware image adjustment, this method fails.

Syntax

HRESULT GetProcAmpControlRange(
  DWORD  dwStreamID,
  VMR9ProcAmpControlRange*  lpClrControl
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[in, out] Pointer to a VMR9ProcAmpControlRange structure that receives the range. The caller must set the dwSize and dwProperty fields.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pin is not connected.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::GetZOrder

The GetZOrder method retrieves this video stream's position in the Z-order.

Syntax

HRESULT GetZOrder(
  DWORD  dwStreamID,
  DWORD*  pZ
);

Parameters

dwStreamID

[in] Specifies the input stream.

pZ

[out] Pointer that receives the current position in the Z-order.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pZ is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

The default Z-order is the order in which the pins were created.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetAlpha

The SetAlpha method sets a constant alpha value that is applied to this video stream.

Syntax

HRESULT SetAlpha(
  DWORD  dwStreamID,
  float  Alpha
);

Parameters

dwStreamID

[in] Specifies the input stream.

Alpha

[in] Specifies the alpha blending value to be applied to all the pixels in this stream.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

The alpha value specified can range from 0.0 (fully transparent) to 1.0 (full opaque).

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetBackgroundClr

The SetBackgroundClr method sets the background color on the output rectangle.

Syntax

HRESULT SetBackgroundClr(
  COLORREF  ClrBkg
);

Parameters

ClrBkg

[in] Specifies the background color.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetColorControl

The SetMixingPrefs method sets the mixing preferences for the stream.

Syntax

HRESULT SetMixingPrefs(
  DWORD  dwStreamID,
  DWORD  dwMixerPrefs
);

Parameters

dwStreamID

[in] Specifies the input stream.

dwMixerPrefs

[in] Bitwise OR combination of VMR9MixerPrefs flags.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetMixingPrefs

The SetMixingPrefs method sets the mixing preferences for the stream.

Syntax

HRESULT SetMixingPrefs(
  DWORD  dwMixerPrefs
);

Parameters

dwMixerPrefs

[in] Bitwise OR combination of VMR9MixerPrefs flags.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetOutputRect

The SetOutputRect method sets the position of this stream within the composition rectangle.

Syntax

HRESULT SetOutputRect(
  DWORD  dwStreamID,
  const VMR9NormalizedRect*  pRect
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[in] Pointer to a NORMALIZEDRECT structure that specifies the position of the rectangle with composition space.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | pRect is invalid.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Because this rectangle exists in compositional space, there is no such thing as an "invalid" rectangle. For example, set left greater than right to mirror the video in the x direction. Specifying an empty rectangle turns off this stream.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetProcAmpControl

The SetProcAmpControl method sets the image adjustment for the VMR-9. Image adjustment includes brightness, contrast, hue, and saturation, and is performed by the graphics device. If the graphics driver does not support hardware image adjustment, this method fails.

Syntax

HRESULT SetProcAmpControl(
  DWORD  dwStreamID,
  VMR9ProcAmpControl*  lpClrControl
);

Parameters

dwStreamID

[in] Specifies the input stream.

pRect

[in] Pointer to a VMR9ProcAmpControl structure that contains the image adjustment settings.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid stream number.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pin is not connected.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMixerControl9::SetZOrder

The SetZOrder method sets this video stream's position in the Z-order; larger values are further away.

Syntax

HRESULT SetZOrder(
  DWORD  dwStreamID,
  DWORD  dwZ
);

Parameters

dwStreamID

[in] Specifies the input stream.

dwZ

[in] Double word containing the stream's position within the Z-order.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_NOT_CONNECTED | The pin is not connected.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMixerControl9 Interface


IVMRMonitorConfig Interface

The IVMRMonitorConfig interface is implemented by the Video Mixing Renderer Filter 7 (VMR-7). Applications use this interface to determine the capabilities of the display devices on the system and to control which device is used to display the output. For example, if the system contains a hardware DVD decoder and the VMR is rendering the output from that decoder, then on a multi-monitor system, an application must use this interface to specify the display device that is connected to the decoder.

The VMR supports a maximum of four display devices.

It is the responsibility of the application to ensure that the playback window is positioned on the desired monitor before the window is displayed. Otherwise the playback window will be displayed at a location chosen by the Windows Shell (Explorer) which may not be on the desired monitor.

For the VMR-9, use the IVMRMonitorConfig9 interface.

In addition to the methods inherited from IUnknown, the IVMRMonitorConfig interface exposes the following methods:

Method | Description
GetAvailableMonitors | Retrieves information about the monitors currently available on the system.
GetDefaultMonitor | Retrieves the default monitor that all future instances of the VMR will use for video playback.
GetMonitor | Retrieves the monitor that this instance of the VMR is using for video playback.
SetDefaultMonitor | Specifies the default monitor that all future instances of the VMR should use for video playback.
SetMonitor | On a multi-monitor system, specifies the monitor that this instance of the VMR should use for video playback.


IVMRMonitorConfig::GetAvailableMonitors

The GetAvailableMonitors method retrieves information about the monitors currently available on the system.

Syntax

Parameters
HRESULT GetAvailableMonitors(
  VMRMONITORINFO*  pInfo,
  DWORD  dwMaxInfoArraySize,
  DWORD*  pdwNumDevices
);

pInfo

[out] Pointer to an array of VMRMONITORINFO structures that contain information about each monitor on the system.

dwMaxInfoArraySize

[in] Specifies the maximum number of members in the array.

pdwNumDevices

[out] Pointer to a variable that receives the number of devices retrieved.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument; dwMaxInfoArraySize must be greater than zero.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Use this method to get a list of DirectDraw device GUIDs and their associated monitor information that the VMR can use when connecting to an upstream decoder filter. To return the required array size in the pdwNumDevices parameter, specify NULL for pInfo.

See Also

  • Error and Success Codes
  • IVMRMonitorConfig Interface


IVMRMonitorConfig::GetDefaultMonitor

The GetDefaultMonitor method retrieves the default monitor that all future instances of the VMR will use for video playback.

Syntax

HRESULT GetDefaultMonitor(
  VMRGUID*  pGUID
);

Parameters

pGUID

[out] Pointer to a VMRGUID structure that identifies the default monitor on the system.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to determine which is the default DirectDraw device the VMR will use when connecting to an upstream filter.

See Also

  • Error and Success Codes
  • IVMRMonitorConfig Interface
  • IVMRMonitorConfig::SetDefaultMonitor


IVMRMonitorConfig::GetMonitor

The GetMonitor method retrieves the monitor that this instance of the VMR is using for video playback.

Syntax

HRESULT GetMonitor(
  VMRGUID*  pGUID
);

Parameters

pGUID

[out] Pointer to a VMRGUID structure allocated by the caller. The method fills this structure with a GUID that identifies the monitor.

Return Values

Returns an HRESULT value. Possible values include the following.

Error Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

See Also

  • Error and Success Codes
  • IVMRMonitorConfig Interface
  • IVMRMonitorConfig::SetMonitor


IVMRMonitorConfig::SetDefaultMonitor

The SetDefaultMonitor method specifies the default monitor that all future instances of the VMR should use for video playback.

Syntax

HRESULT SetDefaultMonitor(
  const VMRGUID*  pGUID
);

Parameters

pGUID

[in] Pointer to a VMRGUID structure that identifies the monitor.

Return Values

Returns an HRESULT value. Possible values include the following.

Error Code | Description
E_FAIL | Could not set the specified monitor as the default.
E_INVALIDARG | Invalid argument. The specified monitor does not exist, or the pGUID parameter was not formatted correctly.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to specify to the VMR the default DirectDraw device to use when connecting to an upstream filter. The default DirectDraw device can be overriden for a particular connection by the SetMonitor method.

The pGUID member of the VMRGUID structure must be either NULL, indicating the default DirectDraw device, or equal to the address of the GUID member of the VMRGUID structure. Otherwise, the method returns E_INVALIDARG.

If the specified GUID does not correspond to any monitor, the method return E_INVALIDARG.

See Also

  • Error and Success Codes
  • IVMRMonitorConfig::GetDefaultMonitor
  • IVMRMonitorConfig Interface


IVMRMonitorConfig::SetMonitor

On a multi-monitor system, the SetMonitor method specifies the monitor that this instance of the VMR should use for video playback.

Syntax

HRESULT SetMonitor(
  const VMRGUID*  pGUID
);

Parameters

pGUID

[in] Pointer to a VMRGUID structure that identifies the monitor.

Return Values

Returns an HRESULT value. Possible values include the following.

Error Code | Description
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to specify to the VMR which DirectDraw driver should be used when connecting to an upstream decoder filter.

The pGUID member of the VMRGUID structure must be either NULL, indicating the default DirectDraw device, or equal to the address of the GUID member of the VMRGUID structure. Otherwise, the method returns E_INVALIDARG.

If the specified GUID does not correspond to any monitor, the method return E_INVALIDARG.

See Also

  • Error and Success Codes
  • IVMRMonitorConfig::GetMonitor
  • IVMRMonitorConfig Interface


IVMRMonitorConfig9 Interface

The IVMRMonitorConfig9 interface is implemented by the Video Mixing Renderer Filter 9 (VMR-9). Applications use this interface to determine the capabilities of the display devices on the system and to control which device is used to display the output. For example, if the system contains a hardware DVD decoder and the VMR is rendering the output from that decoder, then on a multi-monitor system, an application must use this interface to specify the display device that is connected to the decoder.

In addition to the methods inherited from IUnknown, the IVMRMonitorConfig9 interface exposes the following methods.

Method | Description
GetAvailableMonitors | Retrieves information about the monitors currently available on the system.
GetDefaultMonitor | Retrieves the default monitor that all future instances of the VMR will use for video playback.
GetMonitor | Retrieves the monitor that this instance of the VMR is using for video playback.
SetDefaultMonitor | Specifies the default monitor that all future instances of the VMR should use for video playback.
SetMonitor | On a multi-monitor system, specifies the monitor that this instance of the VMR should use for video playback.

Requirements

Include D3d9.h, Vmr9.h.


IVMRMonitorConfig9::GetAvailableMonitors

The GetAvailableMonitors method retrieves information about the monitors currently available on the system.

Syntax

HRESULT GetAvailableMonitors(
  VMR9MonitorInfo*  pInfo,
  DWORD  dwMaxInfoArraySize,
  DWORD*  pdwNumDevices
);

Parameters

pInfo

[out] Pointer to an array of VMR9MonitorInfo structures that contain information about each monitor on the system.

dwMaxInfoArraySize

[in] Specifies the maximum number of members in the array.

pdwNumDevices

[out] If pInfo is NULL, this parameter receives the required array size. Otherwise, it receives the actual number of devices retrieved.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument; dwMaxInfoArraySize must be greater than zero.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

Use this method to get a list of Direct Draw device identifiers and their associated monitor information that the mixer can use when connecting to an upstream decoder filter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMonitorConfig9 Interface


IVMRMonitorConfig9::GetDefaultMonitor

The GetDefaultMonitor method retrieves the default monitor that all future instances of the VMR will use for video playback.

Syntax

HRESULT GetDefaultMonitor(
  UINT*  puDev
);

Parameters

puDev

[out] Pointer that receives an index that identifies the default monitor on the system.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to determine which is the default DirectDraw device the overlay mixer filter will use when connecting to an upstream filter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMonitorConfig9 Interface
  • IVMRMonitorConfig9::SetDefaultMonitor


IVMRMonitorConfig9::GetMonitor

The GetMonitor method retrieves the monitor that this instance of the VMR is using for video playback.

Syntax

HRESULT GetMonitor(
  UINT*  puDev
);

Parameters

puDev

[out] Pointer that receives an index that identifies the monitor currently in use.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method to determine the DirectDraw object that will be used when connecting the mixer filter to an upstream decoder filter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMonitorConfig9 Interface
  • IVMRMonitorConfig9::SetMonitor


IVMRMonitorConfig9::SetDefaultMonitor

The SetDefaultMonitor method specifies the default monitor that all future instances of the VMR should use for video playback.

Syntax

HRESULT SetDefaultMonitor(
  UINT  uDev
);

Parameters

uDev

[in] Index that specifies the default monitor.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_FAIL | Could not set the specified monitor as the default.
E_INVALIDARG | Invalid argument; uDev does not correspond to a valid monitor.
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to specify to the VMR the default Direct3D device to use when connecting to an upstream filter. The default Direct3D device can be overridden for a particular connection by the SetMonitor method.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMonitorConfig9 Interface
  • IVMRMonitorConfig9::GetDefaultMonitor


IVMRMonitorConfig9::SetMonitor

On a multi-monitor system, the SetMonitor method specifies the monitor that this instance of the VMR should use for video playback.

Syntax

HRESULT SetMonitor(
  UINT  uDev
);

Parameters

uDev

[in] Index that specifies the monitor.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument; uDev does not correspond to a valid monitor.
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The allocator-presenter has not been loaded.

Remarks

Use this method on a multi-monitor system to specify to the VMR which Direct3D device should be used when connecting to an upstream decoder filter.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRMonitorConfig9 Interface
  • IVMRMonitorConfig9::GetMonitor


IVMRSurface Interface

The IVMRSurface interface is implemented on the media samples used by the Video Mixing Renderer Filter 7 (VMR-7). Filters can use this interface to access the underlying DirectDraw surface on which the media sample is based. Filters must always lock and unlock the surface using the methods available on this interface. Filters must never call lock or unlock directly on the DirectDraw surface interface returned from the GetSurface method. Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IVMRSurface interface exposes the following methods:

Method | Description
GetSurface | Retrieves the attached DirectDraw surface interface.
IsSurfaceLocked | Indicates whether the DirectDraw surface attached to this media sample is locked.
LockSurface | Locks the attached DirectDraw surface.
UnlockSurface | Unlocks the attached DirectDraw surface.


IVMRSurface::GetSurface

The GetSurface method retrieves the attached DirectDraw surface interface.

Syntax

HRESULT GetSurface(
  LPDIRECTDRAWSURFACE7*  lplpSurface
);

Parameters

lplpSurface

[out] Address of a variable that receives a pointer to the IDirectDrawSurface7 interface. The caller must release the interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | NULL pointer argument.
E_FAIL | No DirectDraw surface is attached to this sample.

See Also

  • Error and Success Codes
  • IVMRSurface Interface


IVMRSurface::IsSurfaceLocked

The IsSurfaceLocked method indicates whether the DirectDraw surface attached to this media sample is locked.

Syntax

HRESULT IsSurfaceLocked();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRSurface Interface


IVMRSurface::LockSurface

The LockSurface method locks the attached DirectDraw surface.

Syntax

HRESULT LockSurface(
  BYTE**  lpSurface
);

Parameters

lpSurface

[out] Address of a variable that receives a pointer to the locked bits.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | lpSurface is invalid.
E_FAIL | No DirectDraw surface is attached to this sample.

See Also

  • Error and Success Codes
  • IVMRSurface Interface


IVMRSurface::UnlockSurface

The UnlockSurface method unlocks the attached DirectDraw surface.

Syntax

HRESULT UnlockSurface();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_FAIL | No DirectDraw surface is attached to this sample.

See Also

  • Error and Success Codes
  • IVMRSurface Interface


IVMRSurface9 Interface

The IVMRSurface9 interface is implemented on the media samples used by the Video Mixing Renderer Filter 9. Filters can use this interface to access the underlying DirectDraw surface on which the media sample is based. Filters must always lock and unlock the surface using the methods available on this interface. Filters must never call lock or unlock directly on the DirectDraw surface interface returned from the GetSurface method. Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IVMRSurface9 interface exposes the following methods.

Method | Description
GetSurface | Retrieves the attached Direct3D surface interface.
IsSurfaceLocked | Indicates whether the Direct3D surface attached to this media sample is locked.
LockSurface | Locks the attached Direct3D surface.
UnlockSurface | Unlocks the attached Direct3D surface.

Requirements

Include D3d9.h, Vmr9.h.


IVMRSurface9::GetSurface

The GetSurface method retrieves the attached DirectDraw surface.

Syntax

HRESULT GetSurface(
  IDirect3DSurface9**  lplpSurface
);

Parameters

lplpSurface

[out] Address of a variable that receives an IDirect3DSurface9 interface pointer. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | lplpSurface is invalid.
E_FAIL | No Direct3D surface is attached to this sample.

Remarks

The media sample object increments the reference count on the returned interface. The caller must call Release on the interface.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurface9 Interface


IVMRSurface9::IsSurfaceLocked

The IsSurfaceLocked method indicates whether the Direct3D surface attached to this media sample is locked.

Syntax

HRESULT IsSurfaceLocked();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurface9 Interface


IVMRSurface9::LockSurface

The LockSurface method locks the attached Direct3D surface.

Syntax

HRESULT LockSurface(
  BYTE**  lpSurface
);

Parameters

lpSurface

[out] Address of a variable that receives a pointer to the locked bits.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | lpSurface is invalid.
E_FAIL | No Direct3D surface is attached to this sample.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurface9 Interface


IVMRSurface9::UnlockSurface

The UnlockSurface method unlocks the attached DirectDraw surface.

Syntax

HRESULT UnlockSurface();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | No Direct3D surface is attached to this sample.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurface9 Interface


IVMRSurfaceAllocator Interface

The IVMRSurfaceAllocator interface is implemented by the default allocator-presenter for the Video Mixing Renderer Filter 7 (VMR-7). It must also be implemented by any plug-in allocator-presenter that an application provides to the VMR-7. The VMR-7 uses the methods on this interface to allocate, prepare and free DirectDraw surfaces. Applications do not use this interface.

For the VMR-9, use the IVMRSurfaceAllocator9 interface.

In addition to the methods inherited from IUnknown, the IVMRSurfaceAllocator interface exposes the following methods:

Method | Description
AdviseNotify | Called by the VMR to provide the allocator-presenter with an interface pointer for notification callbacks.
AllocateSurface | Allocates a DirectDraw surface.
FreeSurface | Frees the allocated DirectDraw surface.
PrepareSurface | Prepares the DirectDraw surface to have the next video frame decoded into it.


IVMRSurfaceAllocator::AdviseNotify

The AdviseNotify method is called by the VMR to provide the allocator-presenter with an interface pointer for notification callbacks.

Syntax

HRESULT AdviseNotify(
  IVMRSurfaceAllocatorNotify*  lpIVMRSurfAllocNotify
);

Parameters

lpIVMRSurfAllocNotify

[in] Specifies the IVMRSurfaceAllocatorNotify interface pointer that the allocator-presenter will use to pass notifications back to the VMR.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRSurfaceAllocator Interface
  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocator::AllocateSurface

The AllocateSurface method allocates a DirectDraw surface.

Syntax

HRESULT AllocateSurface(
  DWORD_PTR  dwUserID,
  VMRALLOCATIONINFO*  lpAllocInfo,
  DWORD* lpdwActualBuffers,
  LPDIRECTDRAWSURFACE7*  lplpSurface
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

lpAllocInfo

[in] Specifies the VMRALLOCATIONINFO structure. See Remarks.

lpdwActualBuffers

[in] [out] On input this parameter is used to request the number of buffers desired. On output it receives the actual number of buffers created.

lplpSurface

[out] Address of a pointer that receives the Direct3D surface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | One of the pointers is invalid.
E_INVALIDARG | In dwFlags, the AMAP_3D_TARGET was combined with AMAP_FORCE_SYSMEM or AMAP_ALLOW_SYSMEM.
E_FAIL | One or more members of the BITMAPINFOHEADER structure specified by lpAllocInfo->lpHdr is incorrect.

Remarks

Before calling AllocateSurface explicitly, a client application should call IVMRSurfaceAllocator::FreeSurface to be sure that the DirectDraw decoding surface front buffer is NULL. If it is not NULL at the time an application calls AllocateSurface, the debug version of quartz.dll will cause an assertion.

When implementing this method in a custom allocator-presenter, you must examine the value of lpAllocInfo->lpHdr->biBitCount. If biBitCount is zero, then you must set it to the pixel depth for the current display. If BiBitCount is left at zero, the surface allocation will fail and a new (default) VMR will be created.

See Also

  • Error and Success Codes
  • IVMRSurfaceAllocator Interface


IVMRSurfaceAllocator::FreeSurface

The FreeSurface method frees the allocated DirectDraw surface.

Syntax

HRESULT FreeSurface(
  DWORD_PTR  dwID
);

Parameters

dwID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRSurfaceAllocator Interface


IVMRSurfaceAllocator::PrepareSurface

The PrepareSurface method prepares the DirectDraw surface to have the next video frame decoded into it.

Syntax

HRESULT PrepareSurface(
  DWORD_PTR  dwUserID,
  LPDIRECTDRAWSURFACE7  lpSurface,
  DWORD  dwSurfaceFlags
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR cookie that uniquely identifies this instance of the VMR for use in scenarios when one instance of the allocator-presenter is used with multiple VMR instances.

lpSurface

[in] Specifies the DirectDraw surface

dwSurfaceFlags

[in] Double word containing the surface flags. See Remarks.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The only flag that the VMR currently checks here is AM_GBF_NOTASYNCPOINT (0x00000002), which indicates that you are not going to fill this buffer with a sync point (keyframe).

See Also

  • IVMRSurfaceAllocator Interface


IVMRSurfaceAllocator9 Interface

The IVMRSurfaceAllocator9 interface is implemented by the default allocator-presenter for the Video Mixing Renderer Filter 9 (VMR-9). It must also be implemented by any plug-in allocator-presenter object that an application provides to the VMR-9. The VMR-9 uses the methods on this interface to allocate, prepare and free Direct3D surfaces. Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IVMRSurfaceAllocator9 interface exposes the following methods.

Method | Description
AdviseNotify | Called by the VMR to provide the allocator-presenter with an interface pointer for notification callbacks.
GetSurface | Retrieves a Direct3D surface.
InitializeDevice | Initializes the Direct3D device.
TerminateDevice | Releases the Direct3D device.

Requirements

Include D3d9.h, Vmr9.h.


IVMRSurfaceAllocator9::AdviseNotify

The AdviseNotify method is called by the VMR to provide the allocator-presenter with an interface pointer for notification callbacks.

Syntax

HRESULT AdviseNotify(
  IVMRSurfaceAllocatorNotify9*  lpIVMRSurfAllocNotify
);

Parameters

lpIVMRSurfAllocNotify

[in] Specifies the IVMRSurfaceAllocatorNotify9 interface that the allocator-presenter will use to pass notifications back to the VMR.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocator9 Interface


IVMRSurfaceAllocator9::GetSurface

The GetSurface method retrieves a Direct3D surface.

Syntax

HRESULT GetSurface(
  DWORD_PTR  dwUserID,
  DWORD  SurfaceIndex,
  DWORD  SurfaceFlags,
  IDirect3DSurface9**  lplpSurface
);

Parameters

dwUserID

[in] Identifies this instance of the VMR.

SurfaceIndex

[in] Specifies the index of the surface to retrieve.

SurfaceFlags

[in] Specifies surface flags.

lplpSurface

[out] Address of a variable that receives an IDirect3DSurface9 interface pointer. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocator9 Interface


IVMRSurfaceAllocator9::InitializeDevice

The InitializeDevice method initializes the Direct3D device.

Syntax

HRESULT InitializeDevice(
  DWORD_PTR  dwUserID,
  VMR9AllocationInfo*  lpAllocInfo,
  DWORD*  lpNumBuffers
);

Parameters

dwUserID

[in] Specifies this instance of the VMR.

lpAllocInfo

[in] Specifies a VMR9AllocationInfo structure that contains the initialization parameters.

lpNumBuffers

[in, out] On input, specifies the number of buffers to create. When the method returns, this parameter contains the number of buffers that were actually allocated.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocator9 Interface


IVMRSurfaceAllocator9::TerminateDevice

The TerminateDevice method releases the Direct3D device.

Syntax

HRESULT TerminateDevice(
  DWORD_PTR  dwID
);

Parameters

dwID

[in] Specifies the ID that idientifies this instance of the VMR.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

See Also

Requirements

Include D3d9.h, Vmr9.h.

  • IVMRSurfaceAllocator9 Interface


IVMRSurfaceAllocatorNotify Interface

The IVMRSurfaceAllocatorNotify interface is implemented by the Video Mixing Renderer Filter 7 (VMR-7). Applications use this interface to set a custom allocator-presenter and the allocator-presenter uses this interface to inform the VMR-7 of changes to the system environment that affect the DirectDraw surfaces.

In order for an application to obtain this interface, the VMR must be in renderless mode.

For the VMR-9, use the IVMRSurfaceAllocatorNotify9 interface.

In addition to the methods inherited from IUnknown, the IVMRSurfaceAllocatorNotify interface exposes the following methods:

Method | Description
AdviseSurfaceAllocator | Called by an application to instruct the VMR to use a custom allocator-presenter.
ChangeDDrawDevice | Notifies the VMR that the DirectDraw playback device has changed.
NotifyEvent | Called by the allocator-presenter to inform the VMR of any significant DirectShow events during the allocation or presentation processes.
RestoreDDrawSurfaces | Notifies the VMR that a DirectDraw surface "loss" has been detected.
SetBorderColor | Specifies to the VMR which color to use in areas of the display rectangle which are not being used for video, for example when the video is letterboxed.
SetDDrawDevice | Sets the initial DirectDraw device and monitor to be used for video playback.


IVMRSurfaceAllocatorNotify::AdviseSurfaceAllocator

The AdviseSurfaceAllocator method is called by an application to instruct the VMR to use a custom allocator-presenter.

Syntax

HRESULT AdviseSurfaceAllocator(
  DWORD_PTR  dwUserID,
  IVMRSurfaceAllocator*  lpIVRMSurfaceAllocator
);

Parameters

dwUserID

[in] An application-defined DWORD_PTR that uniquely identifies this instance of the VMR in scenarios when multiple instances of the VMR are being used with a single instance of an allocator-presenter.

lpIVMRSurfaceAllocator

[in] Specifies the IVMRSurfaceAllocator interface on the new allocator-presenter. If this value is NULL, then the VMR will release the client allocator-presenter and restore its default allocator-presenter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The method will cause the default allocator-presenter to be uninstalled and destroyed, and replaced with the specified new component. The new component must also support the IVMRImagePresenter interface.

This method can be called only once in the lifetime of the VMR. The VMR continues to use the allocator-presenter until the VMR is itself deleted. When the VMR is finally released, it releases its reference count on the custom allocator-presenter object, which allows that object to be freed.

See Also

  • Error and Success Codes
  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify::ChangeDDrawDevice

The ChangeDDrawDevice method notifies the VMR that the DirectDraw playback device has changed. For example, on a multi-monitor system, the user has moved the video rectangle from one monitor to another.

Syntax

HRESULT ChangeDDrawDevice(
  LPDIRECTDRAW7  lpDirectDrawDevice,
  HMONITOR  hMonitor
);

Parameters

lpDirectDrawDevice

[in] Specifies the DirectDraw device.

hMonitor

[in] Specifies the handle to the monitor associated with the DirectDraw device.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The VMR needs to know which DirectDraw device is being used at any given time in order to associate the Direct3D surfaces being created in the mixer component with that device.

See Also

  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify::NotifyEvent

The NotifyEvent method is called by the allocator-presenter to inform the VMR of any significant DirectShow events during the allocation or presentation processes.

Syntax

HRESULT NotifyEvent(
  LONG  EventCode,
  LONG_PTR  Param1,
  LONG_PTR  Param2
);

Parameters

EventCode

[in] Specifies the event code.

Param1

[in] Specifies Param1 of the event code.

Param2

[in] Specifies Param2 of the event code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The VMR provides the allocator-presenter with a pointer to this interface in a call to IVMRSurfaceAllocator::AdviseNotify. When the allocator-presenter calls this method and specifies some regular DirectShow event, such as EC_ERRORABORT or EC_VMR_RENDERDEVICE_SET, the VMR will pass the event to the filter graph manager.

See Also

  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify::RestoreDDrawSurfaces

The RestoreDDrawSurfaces method notifies the VMR that a DirectDraw surface "loss" has been detected.

Syntax

HRESULT RestoreDDrawSurfaces();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify::SetBorderColor

The SetBorderColor method specifies to the VMR which color to use in areas of the display rectangle which are not being used for video, for example when the video is letterboxed.

Syntax

HRESULT SetBorderColor(
  COLORREF  clrBorder
);

Parameters

clrBorder

[in] Specifies the border color.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify::SetDDrawDevice

The SetDDrawDevice method sets the initial DirectDraw device and monitor to be used for video playback.

Syntax

HRESULT SetDDrawDevice(
  LPDIRECTDRAW7  lpDirectDrawDevice,
  HMONITOR  hMonitor
);

Parameters

lpDirectDrawDevice

[in] Specifies the DirectDraw device.

hMonitor

[in] Handle to the monitor associated with the DirectDraw device.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The VMR needs to know which DirectDraw device is being used at any given time in order to associate the Direct3D surfaces being created in the mixer component with that device.

See Also

  • IVMRSurfaceAllocatorNotify Interface


IVMRSurfaceAllocatorNotify9 Interface

The IVMRSurfaceAllocatorNotify9 interface is implemented by the Video Mixing Renderer Filter 9 (VMR-9). Applications use this interface to set a custom allocator-presenter and the allocator-presenter uses this interface to inform the VMR of changes to the system environment that affect the Direct3D surfaces.

In addition to the methods inherited from IUnknown, the IVMRSurfaceAllocatorNotify9 interface exposes the following methods.

Method | Description
AdviseSurfaceAllocator | Called by an application to instruct the VMR to use a custom allocator-presenter.
AllocateSurfaceHelper | Allocates a Direct3D surface based on specified parameters.
ChangeD3DDevice | Notifies the VMR that the Direct3D playback device has changed.
NotifyEvent | Called by the allocator-presenter to inform the VMR of any significant DirectShow events during the allocation or presentation processes.
SetD3DDevice | Sets the initial Direct3D device and monitor to be used for video playback.

Requirements

Include D3d9.h, Vmr9.h.


IVMRSurfaceAllocatorNotify9::AdviseSurfaceAllocator

The AdviseSurfaceAllocator method is called by an application to instruct the VMR-9 to use a custom allocator-presenter.

Syntax

HRESULT AdviseSurfaceAllocator(
  DWORD_PTR  dwUserID,
  IVMRSurfaceAllocator9*  lpIVRMSurfaceAllocator
);

Parameters

dwUserID

[in] Identifies this instance of the VMR-9.

lpIVRMSurfaceAllocator

[in] Pointer to the IVMRSurfaceAllocator9 interface on the custom surface allocator object.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

This method can be called only once in the lifetime of the VMR. The VMR continues to use the allocator-presenter until the VMR is itself deleted. When the VMR is finally released, it releases its reference count on the custom allocator-presenter object, which allows that object to be freed.

The custom allocator-presenter must also support the IVMRImagePresenter9 interface.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocatorNotify9 Interface


IVMRSurfaceAllocatorNotify9::AllocateSurfaceHelper

The AllocateSurfaceHelper method allocates a Direct3D surface based on application-specified parameters.

Syntax

HRESULT AllocateSurfaceHelper(
  VMR9AllocationInfo*  lpAllocInfo,
  DWORD*  lpNumBuffers,
  IDirect3DSurface9**  lplpSurface
);

Parameters

lpAllocInfo

[in] Pointer to a VMR9AllocationInfo structure that contains initialization information for the new surface.

lpNumBuffers

[in, out] Specifies the number of buffers to use.

lplpSurface

[out] Address of a variable that receives an IDirect3DSurface9 interface pointer. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocatorNotify9 Interface


IVMRSurfaceAllocatorNotify9::ChangeD3DDevice

The ChangeD3DDevice method notifies the VMR that the Direct3D device has changed.

Syntax

HRESULT ChangeD3DDevice(
  IDirect3DDevice9*  lpD3DDevice,
  HMONITOR  hMonitor
);

Parameters

lpD3DDevice

[in] Pointer to the IDirect3DDevice9 interface of the new device.

hMonitor

[in] Handle to the monitor associated with the new device.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocatorNotify9 Interface


IVMRSurfaceAllocatorNotify9::NotifyEvent

The NotifyEvent method is called by the allocator-presenter to inform the VMR of any significant DirectShow events that it (the allocator presenter) generates during the allocation or presentation processes.

Syntax

HRESULT NotifyEvent(
  LONG  EventCode,
  LONG_PTR  Param1,
  LONG_PTR  Param2
);

Parameters

EventCode

[in] Specifies the DirectShow event code.

Param1

[in] Specifies the first event parameter. The meaning depends on the event code. See Event Notification Codes.

Param2

[in] Specifies the second event parameter. The meaning depends on the event code.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The VMR provides the allocator-presenter with a pointer to this interface in a call to IVMRSurfaceAllocator9::AdviseNotify. When the allocator-presenter calls this method and specifies some regular DirectShow event, such as EC_ERRORABORT or EC_VMR_RENDERDEVICE_SET, the VMR will pass the event to the filter graph manager.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocatorNotify9 Interface


IVMRSurfaceAllocatorNotify9::SetD3DDevice

The SetD3DDevice method .

Syntax

HRESULT SetD3DDevice(
  IDirect3DDevice9*  lpD3DDevice,
  HMONITOR  hMonitor
);

Parameters

lpD3DDevice

[in] Pointer to the IDirect3DDevice9 interface of the device.

hMonitor

[in] Handle to a monitor.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRSurfaceAllocatorNotify9 Interface


IVMRVideoStreamControl Interface

The IVMRVideoStreamControl interface is implemented on each input pin of the Video Mixing Renderer Filter 7 (VMR-7). The interface operates on the input stream represented by the pin. This interface is used by upstream filters (typically decoders) to get or set the active state of individual streams, or the source color key for the composited image. Applications in general should not use this interface.

The VMR-9 input pins expose the IVMRVideoStreamControl9 interface.

In addition to the methods inherited from IUnknown, the IVMRVideoStreamControl interface exposes the following methods:

Method | Description
GetColorKey | Retrieves the source color key currently set for this stream.
GetStreamActiveState | Retrieves the state of the stream.
SetColorKey | Sets the source color key that the VMR will use when compositing the video image.
SetStreamActiveState | Activates or inactivates an input stream.


IVMRVideoStreamControl::GetColorKey

The GetColorKey method retrieves the source color key currently set for this stream.

Syntax

HRESULT GetColorKey(
  DDCOLORKEY*  pclr
);

Parameters

pclr

[out] Address of a DDCOLORKEY structure that receives the source color key.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IVMRVideoStreamControl Interface
  • IVMRVideoStreamControl::SetColorKey


IVMRVideoStreamControl::GetStreamActiveState

The GetStreamActiveState method retrieves the state of the stream.

Syntax

HRESULT GetStreamActiveState(
  BOOL*  lpfActive
);

Parameters

lpfActive

[out] Receives the current state of the stream. TRUE means the stream is active; FALSE means that it is inactive.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

None.

See Also

  • IVMRVideoStreamControl Interface
  • IVMRVideoStreamControl::SetStreamActiveState


IVMRVideoStreamControl::SetColorKey

The SetColorKey method sets the source color key that the VMR will use when compositing the video image.

Syntax

HRESULT SetColorKey(
  DDCOLORKEY  clr
);

Parameters

clr

[in] Specifies the source color key as a DDCOLORKEY type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRVideoStreamControl::GetColorKey
  • IVMRVideoStreamControl Interface


IVMRVideoStreamControl::SetStreamActiveState

The SetStreamActiveState method activates or inactivates an input stream.

Syntax

HRESULT SetStreamActiveState(
  BOOL  fActive
);

Parameters

fActive

[in] Specifies the state of the stream. TRUE means active; FALSE means inactive.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IVMRVideoStreamControl::GetStreamActiveState
  • IVMRVideoStreamControl Interface


IVMRVideoStreamControl9 Interface

The IVMRVideoStreamControl9 interface is implemented on each input pin of the Video Mixing Renderer Filter 9. The interface operates on the input stream represented by the pin. This interface is used by upstream filters (typically decoders) to get or set the active state of individual streams. Applications in general should not use this interface.

In addition to the methods inherited from IUnknown, the IVMRVideoStreamControl9 interface exposes the following methods:

Method | Description
GetStreamActiveState | Retrieves the state of the stream.
SetStreamActiveState | Activates or inactivates an input stream.

Requirements

Include D3d9.h, Vmr9.h.


IVMRVideoStreamControl9::GetStreamActiveState

The GetStreamActiveState method retrieves the state of the stream.

Syntax

HRESULT GetStreamActiveState(
  BOOL*  lpfActive
);

Parameters

lpfActive

[out] Receives the current state of the stream. TRUE means the stream is active; FALSE means that it is inactive.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRVideoStreamControl9 Interface


IVMRVideoStreamControl9::SetStreamActiveState

The SetStreamActiveState method activates or inactivates an input stream.

Syntax

HRESULT SetStreamActiveState(
  BOOL  fActive
);

Parameters

fActive

[in] Specifies the state of the stream. TRUE means active; FALSE means inactive.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRVideoStreamControl9 Interface


IVMRWindowlessControl Interface

The IVMRWindowlessControl interface controls how the Video Mixing Renderer Filter 7 (VMR-7) renders a video stream within a container window. Applications must first put the VMR-7 into windowless mode before using this interface.

For the VMR-9, use the IVMRWindowlessControl9 interface.

In addition to the methods inherited from IUnknown, the IVMRWindowlessControl interface exposes the following methods:

Method | Description
DisplayModeChanged | Informs the VMR that a WM_DISPLAYCHANGE message has been received by the application.
GetAspectRatioMode | Queries whether the VMR will preserve the aspect ratio of the source video.
GetBorderColor | Retrieves the current border color used by the VMR.
GetColorKey | Retrieves the current source color key value used by the VMR.
GetCurrentImage | Retrieves a copy of the current image being displayed by the VMR.
GetMaxIdealVideoSize | Retrieves the maximum video size that the VMR can display without incurring significant performance or image quality degradation.
GetMinIdealVideoSize | Retrieves the minimum video size that the VMR can display without incurring significant performance or image quality degradation.
GetNativeVideoSize | Retrieves the un-stretched video size and aspect ratio of the video.
GetVideoPosition | Retrieves the current source and destination rectangles used to display the video.
RepaintVideo | Repaints the current video frame.
SetAspectRatioMode | Specifies whether the VMR will preserve the aspect ratio of the source video.
SetBorderColor | Sets the border color to be used by the VMR.
SetColorKey | Sets the source color key value that the VMR should use
SetVideoClippingWindow | Specifies the container window that video should be clipped to.
SetVideoPosition | Sets the source and destination rectangles for the video.


IVMRWindowlessControl::DisplayModeChanged

The DisplayModeChanged method informs the VMR that a WM_DISPLAYCHANGE message has been received by the application.

Syntax

HRESULT DisplayModeChanged();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

An application must call this method whenever it receives a WM_DISPLAYCHANGE window message, but only if the VMR is currently in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::GetAspectRatioMode

The GetAspectRatioMode method queries whether the VMR will preserve the aspect ratio of the source video.

Syntax

HRESULT GetAspectRatioMode(
  DWORD*  lpAspectRatioMode
);

Parameters

lpAspectRatioMode

[out] Pointer to a variable that receives a VMR_ASPECT_RATIO_MODE value indicating the aspect ratio mode.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface
  • IVMRWindowlessControl::SetAspectRatioMode


IVMRWindowlessControl::GetBorderColor

The GetBorderColor method retrieves the current border color used by the VMR.

Syntax

HRESULT GetBorderColor(
  COLORREF*  lpClr
);

Parameters

lpClr

[out] Pointer to a COLORREF variable that receives the current border color.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface
  • IVMRWindowlessControl::SetBorderColor


IVMRWindowlessControl::GetColorKey

The GetColorKey method retrieves the current source color key value used by the VMR.

Syntax

HRESULT GetColorKey(
  COLORREF*  lpClr
);

Parameters

lpClr

[out] Pointer to a COLORREF variable that receives the current color key value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface
  • IVMRWindowlessControl::SetColorKey


IVMRWindowlessControl::GetCurrentImage

The GetCurrentImage method retrieves a copy of the current image being displayed by the VMR.

Syntax

HRESULT GetCurrentImage(
  BYTE**  lpDib
);

Parameters

lpDib

[out] Address of a pointer to a BYTE that will receive the DIB.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

GetCurrentImage returns the current image being displayed. This image is returned in the form of packed Windows DIB. GetCurrentImage can be called at any time, no matter what state the filter is in, whether running, stopped or paused.

The caller is responsible for freeing the returned memory by calling the COM runtime method CoTaskMemFree.

Excessive use of this function will degrade video playback performance.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::GetMaxIdealVideoSize

The GetMaxIdealVideoSize method retrieves the maximum video size that the VMR can display without incurring significant performance or image quality degradation.

Syntax

HRESULT GetMaxIdealVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight
);

Parameters

lpWidth

[out] Pointer that receives the maximum ideal width.

lpHeight

[out] Pointer that receives the maximum ideal height.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetMinIdealVideoSize
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::GetMinIdealVideoSize

The GetMinIdealVideoSize method retrieves the minimum video size that the VMR can display without incurring significant performance or image quality degradation.

Syntax

HRESULT GetMinIdealVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight
);

Parameters

lpWidth

[out] Pointer to a LONG value that receives the minimum ideal width.

lpHeight

[out] Pointer to a LONG value that receives the minimum ideal height.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetMaxIdealVideoSize
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::GetNativeVideoSize

The GetNativeVideoSize method retrieves the un-stretched video size and aspect ratio of the video.

Syntax

HRESULT GetNativeVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight,
  LONG*  lpARWidth,
  LONG*  lpARHeight
);

Parameters

lpWidth

[out] Pointer that receives the width of the native video rectangle.

lpHeight

[out] Pointer that receives the height of the native video rectangle.

lpARWidth

[out] Pointer that receives the aspect ratio width of the native video rectangle.

lpARHeight

[out] Pointer that receives the aspect ratio height of the native video rectangle.

Return Values

If the method succeeds, it returns S_OK. Returns E_POINTER if all four input parameters are NULL.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

If the VMR is not connected to an upstream filter, this method will succeed but all parameters will be set to zero.

If lpWidth is 640 and lpHeight is 480, then lpARWidth will be 4 and lpARHeight will be 3.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::GetVideoPosition

The GetVideoPosition method retrieves the current source and destination rectangles used to display the video.

Syntax

HRESULT GetVideoPosition(
  LPRECT  lpSRCRect,
  LPRECT  lpDSTRect
);

Parameters

lpSRCRect

[out] Pointer that receives the current source rectangle.

lpDSTRect

[out] Pointer that receives the current destination rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface
  • IVMRWindowlessControl::SetVideoPosition


IVMRWindowlessControl::RepaintVideo

The RepaintVideo method repaints the current video frame.

Syntax

HRESULT RepaintVideo(
  HWND  hwnd,
  HDC  hdc
);

Parameters

hwnd

[in] Specifies the handle of the window in which the repainting should occur.

hdc

[in] Specifies the handle to the device context for the window.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::SetAspectRatioMode

The SetAspectRatioMode method specifies whether the VMR will preserve the aspect ratio of the source video.

Syntax

HRESULT SetAspectRatioMode(
  DWORD  AspectRatioMode
);

Parameters

AspectRatioMode

[in] Specifies a member of the VMR_ASPECT_RATIO_MODE enumeration type.

Return Values

Returns an HRESULT value. Possible values include the following:

Error Code | Description
E_INVALIDARG | Invalid argument
S_OK | Success
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetAspectRatioMode
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::SetBorderColor

The SetBorderColor method sets the border color to be used by the VMR.

Syntax

HRESULT SetBorderColor(
  COLORREF  Clr
);

Parameters

Clr

[in] Specifies the border color.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

The border color is color used to fill any area of the destination rectangle that does not contain video. It is typically used in two instances: (1) when the video straddles two monitors and (2) when the VMR is trying to maintain the aspect ratio of the movie by letter boxing the video to fit within the specified destination rectangle. See the IVMRWindowlessControl::SetAspectRatioMode method.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetBorderColor
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::SetColorKey

The SetColorKey method sets the source color key value that the VMR should use.

Syntax

HRESULT SetColorKey(
  COLORREF  Clr
);

Parameters

Clr

[in] Specifies the source color key.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

Color key control is only meaningful when the VMR is using an overlay surface.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetColorKey
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::SetVideoClippingWindow

The SetVideoClippingWindow method specifies the container window that video should be clipped to.

Syntax

HRESULT SetVideoClippingWindow(
  HWND  hwnd
);

Parameters

hwnd

[in] Specifies the window to which the video should be clipped.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl Interface


IVMRWindowlessControl::SetVideoPosition

The SetVideoPosition method sets the source and destination rectangles for the video.

Syntax

HRESULT SetVideoPosition(
  const LPRECT  lpSRCRect,
  const LPRECT  lpDSTRect
);

Parameters

lpSRCRect

[in] Specifies the source rectangle.

lpDSTRect

[in] Specifies the destination rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Error Code | Description
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

See Also

  • Error and Success Codes
  • IVMRWindowlessControl::GetVideoPosition
  • IVMRWindowlessControl Interface


IVMRWindowlessControl9 Interface

The IVMRWindowlessControl9 interface controls how the Video Mixing Renderer Filter 9 (VMR-9) renders a video stream within a container window. Applications must first put the VMR-9 into windowless mode before using the methods on this interface.

In addition to the methods inherited from IUnknown, the IVMRWindowlessControl9 interface exposes the following methods.

Method | Description
DisplayModeChanged | Informs the VMR that a WM_DISPLAYCHANGE message has been received by the application.
GetAspectRatioMode | Retrieves the current aspect ratio display mode.
GetBorderColor | Retrieves the current border color used by the VMR.
GetCurrentImage | Retrieves a copy of the current image being displayed by the VMR.
GetMaxIdealVideoSize | Retrieves the maximum video size that the VMR can display without incurring significant performance or image quality degradation.
GetMinIdealVideoSize | Retrieves the minimum video size that the VMR can display without incurring significant performance or image quality degradation.
GetNativeVideoSize | Retrieves the un-stretched video size and aspect ratio of the video.
GetVideoPosition | Retrieves the current source and destination rectangles used to display the video.
RepaintVideo | Repaints the current video frame.
SetAspectRatioMode | Sets the current aspect ratio display mode.
SetBorderColor | Sets the border color to be used by the VMR.
SetVideoClippingWindow | Specifies the container window that video should be clipped to.
SetVideoPosition | Sets the source and destination rectangles for the video.

Requirements

Include D3d9.h, Vmr9.h.


IVMRWindowlessControl9::DisplayModeChanged

The DisplayModeChanged method informs the VMR that a WM_DISPLAYCHANGE message has been received by the application.

Syntax

HRESULT DisplayModeChanged();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

An application must call this method whenever it receives a WM_DISPLAYCHANGE window message, but only if the VMR is currently in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::GetAspectRatioMode

The GetAspectRatioMode method retrieves the current aspect ratio display mode.

Syntax

HRESULT GetAspectRatioMode(
  DWORD*  lpAspectRatioMode
);

Parameters

lpAspectRatioMode

[out] Pointer to a DWORD that receives a VMR9AspectRatioMode value that indicates the current aspect ratio mode.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_POINTER | lpAspectRatioMode is invalid

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface
  • SetAspectRatioMode


IVMRWindowlessControl9::GetBorderColor

The GetBorderColor method retrieves the current border color used by the VMR.

Syntax

HRESULT GetBorderColor(
  COLORREF*  lpClr
);

Parameters

lpClr

[out] Pointer to a COLORREF variable that receives the current border color.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface
  • SetBorderColor


IVMRWindowlessControl9::GetCurrentImage

The GetCurrentImage method retrieves a copy of the current image being displayed by the VMR.

Syntax

HRESULT GetCurrentImage(
  BYTE**  lpDib
);

Parameters

lpDib

[out] Address of a pointer to a BYTE that will receive the DIB.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

This image is returned in the form of packed Windows DIB. The GetCurrentImage method can be called at any time, regardless of whether the filter is running, stopped, or paused. The caller must free the returned memory by calling CoTaskMemFree. Excessive use of this function will degrade video playback performance.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::GetMaxIdealVideoSize

The GetMaxIdealVideoSize method retrieves the maximum video size that the VMR can display without incurring significant performance or image quality degradation.

Syntax

HRESULT GetMaxIdealVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight
);

Parameters

lpWidth

[out] Pointer that receives the maximum ideal width.

lpHeight

[out] Pointer that receives the maximum ideal height.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • GetMinIdealVideoSize
  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::GetMinIdealVideoSize

The GetMinIdealVideoSize method retrieves the minimum video size that the VMR can display without incurring significant performance or image quality degradation.

Syntax

HRESULT GetMinIdealVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight
);

Parameters

lpWidth

[out] Pointer that receives the minimum ideal width.

lpHeight

[out] Pointer that receives the minimum ideal height.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • GetMaxIdealVideoSize
  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::GetNativeVideoSize

The GetNativeVideoSize method retrieves the un-stretched video size and aspect ratio of the video.

Syntax

HRESULT GetNativeVideoSize(
  LONG*  lpWidth,
  LONG*  lpHeight,
  LONG*  lpARWidth,
  LONG*  lpARHeight
);

Parameters

lpWidth

[out] Pointer that receives the width of the native video rectangle.

lpHeight

[out] Pointer that receives the height of the native video rectangle.

lpARWidth

[out] Pointer that receives the aspect ratio width of the native video rectangle.

lpARHeight

[out] Pointer that receives the aspect ratio height of the native video rectangle.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Remarks

If the VMR is not connected to an upstream filter, this method will succeed but all parameters will be set to zero.

If lpWidth is 640 and lpHeight is 480, then lpARWidth will be 4 and lpARHeight will be 3.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::GetVideoPosition

The GetVideoPosition method retrieves the current source and destination rectangles used to display the video.

Syntax

HRESULT GetVideoPosition(
  LPRECT  lpSRCRect,
  LPRECT  lpDSTRect
);

Parameters

lpSRCRect

[out] Pointer that receives the current source rectangle.

lpDSTRect

[out] Pointer that receives the current destination rectangle.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface
  • SetVideoPosition


IVMRWindowlessControl9::RepaintVideo

The RepaintVideo method repaints the current video frame.

Syntax

HRESULT RepaintVideo(
  HWND  hwnd,
  HDC  hdc
);

Parameters

hwnd

[in] Specifies the handle of the window in which the repainting should occur.

hdc

[in] Specifies the handle to the device context for the window.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::SetAspectRatioMode

The SetAspectRatioMode method sets the current aspect ratio display mode.

Syntax

HRESULT SetAspectRatioMode(
  DWORD  AspectRatioMode
);

Parameters

AspectRatioMode

[in] A VMR9AspectRatioMode value that specifies the aspect ratio mode.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • GetAspectRatioMode
  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::SetBorderColor

The SetBorderColor method sets the border color to be used by the VMR.

Syntax

HRESULT SetBorderColor(
  COLORREF  Clr
);

Parameters

Clr

[in] Specifies the color as a COLORREF value.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The border color is used to fill any area of the destination rectangle that does not contain video. It is typically used in two situations:

  • When the video straddles two monitors
  • When the VMR is trying to maintain the aspect ratio of the movies by letter-boxing the video to fit within the specified destination rectangle. See SetAspectRatioMode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::SetVideoClippingWindow

The SetVideoClippingWindow method specifies the container window that video should be clipped to.

Syntax

HRESULT SetVideoClippingWindow(
  HWND  hwnd
);

Parameters

hwnd

[in] Specifies the window to which the video should be clipped.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVMRWindowlessControl9::SetVideoPosition

The SetVideoPosition method sets the source and destination rectangles for the video.

Syntax

HRESULT SetVideoPosition(
  const LPRECT  lpSRCRect,
  const LPRECT  lpDSTRect
);

Parameters

lpSRCRect

[in] Specifies the source rectangle.

lpDSTRect

[in] Specifies the destination rectangle.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
VFW_E_WRONG_STATE | The VMR is not in windowless mode.

Requirements

Include D3d9.h, Vmr9.h.

See Also

  • IVMRWindowlessControl9 Interface


IVPBaseConfig Interface

IVPBaseConfig is implemented on a filter that wraps a hardware device such as a decoder or capture device, if the device has a video port to the graphics adapter. This interface allows the video port to communicate with the Overlay Mixer filter regarding configuration information. The IVPConfig interface derives from this interface.

Applications never use this interface.

Requirements

Requires Dvp.h, Vptype.h, Vpconfig.h.

In addition to the methods inherited from IUnknown, the IVPBaseConfig interface exposes the following methods.

Method | Description
GetConnectInfo | Retrieves information about the connections supported by the VPE object.
GetMaxPixelRate | Retrieves the maximum pixel rate the device will output for a given width and height.
GetOverlaySurface | Queries whether the caller should use the driver's overlay surface, and if so, returns a pointer to the surface.
GetVideoFormats | Retrieves the video formats the driver supports.
GetVPDataInfo | Retrieves the current video port data information.
InformVPInputFormats | Informs the device what video formats the video port supports.
SetConnectInfo | Sets the video port connection parameters.
SetDDSurfaceKernelHandles | Specifies the kernel-mode handles of the DirectDraw surfaces to be used for the overlay suface.
SetDirectDrawKernelHandle | Sets the kernel-mode handle to the DirectDraw object.
SetInvertPolarity | Reverses the current polarity the driver uses.
SetSurfaceParameters | Informs the device of the layout of the overlay surface.
SetVideoFormat | Sets the video format.
SetVideoPortID | Specifies the ID of the hardware video port to use.

See Also

  • IVPNotify


IVPBaseConfig::GetConnectInfo

The GetConnectInfo method retrieves information about the connections supported by the VPE object.

Syntax

HRESULT GetConnectInfo(
  DWORD *pdwNumConnectInfo,
  DDVIDEOPORTCONNECT *pddVPConnectInfo
);

Parameters

pdwNumConnectInfo

[in, out] Pointer to a variable that specifies the number of DDVIDEOPORTCONNECT structures in the pddVPConnectInfo array. On input, specifies the size of the array (in number of array elements). On ouput, contains the actual number of DDVIDEOPORTCONNECT structures that were copied into the array. If pddVPConnectInfo is NULL, the method returns the required array size.

pddVPConnectInfo

[in, out] Pointer to an array of DDVIDEOPORTCONNECT structures, allocated by the caller. The device fills in the array with the connection information.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

The client first calls this method with the value NULL for the pddVPConnectInfo parameter. The device returns the number of DDVIDEOPORTCONNECT structures in the pdwNumConnectInfo parameter. The client allocates an array of that size, and calls the method again, passing the address of the array in the pddVPConnectInfo parameter. The device copies the connection information into the buffer, and returns the actual number of copied structures in the pdwNumConnectInfo parameter.

The DDVIDEOPORTCONNECT structure is documented in the Windows DDK. The device can translate this method directly into an DdVideoPortGetConnectInfo call.

The client sets the connection information by calling the IVPBaseConfig::SetConnectInfo method with an index number, which references one of the connection structures returned by this method.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::GetMaxPixelRate

The GetMaxPixelRate method retrieves the maximum pixel rate the device will output for a given width and height.

Syntax

HRESULT GetMaxPixelRate(
  LPAMVPSIZE pamvpSize,
  LPDWORD pdwMaxPixelsPerSecond
);

Parameters

pamvpSize

[in, out] Pointer to an AMVPSIZE structure containing the desired width and height.

pdwMaxPixelsPerSecond

[out] Pointer to a variable that receives the maximum pixel rate, in pixels per second.

Return Values

Returns an HRESULT value.

Remarks

This method retrieves the maximum pixels per second expected for a given size. If the device does not support this size, then it returns the rate and the size that it supports.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::GetOverlaySurface

The GetOverlaySurface method queries whether the caller should use the driver's overlay surface. If so, the method returns a pointer to the surface.

Syntax

HRESULT GetOverlaySurface(
  LPDIRECTDRAWSURFACE *ppddOverlaySurface
);

Parameters

ppddOverlaySurface

[out] Address of a pointer to the IDirectDrawSurface interface. If the caller should use the driver's overlay surface, it sets this variable equal to the IDirectDrawSurface interface for the overlay surface.

Return Values

Returns S_OK if the overlay surface object was returned.

Remarks

The Overlay Mixer uses this function to determine if the driver requires the Overlay Mixer to use the driver's overlay surface. If this function returns NULL, then the Overlay Mixer allocates its own surface.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::GetVideoFormats

The GetVideoFormats method retrieves the video formats the driver supports.

Syntax

HRESULT GetVideoFormats(
  LPDWORD pdwNumFormats,
  LPDDPIXELFORMAT pddPixelFormats
);

Parameters

pdwNumFormats

[in, out] Pointer to a variable that specifies the number of DDPIXELFORMAT structures in the pddPixelFormats array. On input, specifies the size of the array (in number of array elements). On output, contains the actual number of DDPIXELFORMAT structures that were copied into the array. If pddPixelFormat is NULL, the method returns the required array size.

pddPixelFormats

[in, out] Pointer to an array of DDPIXELFORMAT structures, allocated by the caller. The device fills in the array with the format information.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

The client first calls this method with the value NULL for the pddPixelFormats parameter. The device returns the number of DDPIXELFORMAT structures in the pddPixelFormatso parameter. The client allocates an array of that size, and calls the method again, passing the address of the array in the pddPixelFormats parameter. The device copies the format information into the buffer, and returns the actual number of copied structures in the pddPixelFormats parameter.

The DDPIXELFORMAT structure is documented in the Windows DDK.

The client sets the format by calling the IVPBaseConfig::SetVideoFormat method with an index number, which references one of the format structures returned by this method.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::GetVPDataInfo

The GetVPDataInfo method retrieves the current video port data information.

Syntax

HRESULT GetVPDataInfo(
  LPAMVPDATAINFO pamvpDataInfo
);

Parameters

pamvpDataInfo

[in, out] Pointer to an AMVPDATAINFO structure allocated by the caller. The device fills in the structure with information about the video port.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::InformVPInputFormats

The InformVPInputFormats method informs the device what video formats the video port supports.

Syntax

HRESULT InformVPInputFormats(
  DWORD dwNumFormats,
  LPDDPIXELFORMAT pDDPixelFormats
);

Parameters

dwNumFormats

[in] Number of video formats contained in the pDDPixelFormats parameter.

pDDPixelFormats

[in] Pointer to an array of pixel format structures (DDPIXELFORMAT) to send to the device.

Return Values

Returns S_FALSE if failure, or S_OK otherwise.

Remarks

The supplied array of supported video port formats might determine what formats the device, in turn, proposes.

The DDPIXELFORMAT structure is documented in the Windows DDK.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetConnectInfo

The SetConnectInfo method sets the video port connection parameters.

Syntax

HRESULT SetConnectInfo(
  DWORD dwChosenEntry
);

Parameters

dwChosenEntry

[in] Specifies the index of connect information to pass to the driver. The value is a zero-based index into the array returned by the IVPBaseConfig::GetConnectInfo method.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetDDSurfaceKernelHandles

The SetDDSurfaceKernelHandles method specifies the kernel-mode handles of the DirectDraw surfaces to be used for the overlay suface.

Syntax

HRESULT SetDDSurfaceKernelHandle(
    DWORD cHandles,
    ULONG_PTR *rgDDKernelHandles
);

Parameters

cHandles

[in] Specifies the number of handles in the rgDDKernelHandles array.

rgDDKernelHandles

[in] Address of an array of kernel-mode handles.

Return Values

Returns an HRESULT value.

Remarks

This method sets the DirectDraw handles for the overlay surface. There may be more than one attached surface, so the array may contain more than one surface handle.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetDirectDrawKernelHandle

The SetDirectDrawKernelHandle method sets the kernel-mode handle to the DirectDraw object. This handle enables the device's mini-driver to communicate with DirectDraw.

Syntax

HRESULT SetDirectDrawKernelHandle(
  ULONG_PTR dwDDKernelHandle
);

Parameters

dwDDKernelHandle

[in] Specifies the kernel-mode handle of the DirectDraw object.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetInvertPolarity

The SetInvertPolarity method reverses the current polarity the device uses.

Syntax

HRESULT SetInvertPolarity(void);

Return Values

Returns an HRESULT value.

Remarks

Reversing polarity means asking the decoder or capture device to treat even fields as odd fields and vice versa.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetSurfaceParameters

The SetSurfaceParameters method informs the device of the layout of the overlay surface. The downstream filter (the Overlay Mixer, VBI Surface Allocator, or Video Port Manager) calls this method after it creates the overlay surface.

Syntax

HRESULT SetSurfaceParameters(
  DWORD dwPitch,
  DWORD dwXOrigin,
  DWORD dwYOrigin
) PURE;

Parameters

dwPitch

[in] Specifies the stride of the surface (also called the pitch), in pixels.

dwXOrigin

[in] Specifies the X-coordinate of the pixel at which valid data starts.

dwYOrigin

[in] Specifies the Y-coordinate of the pixel at which valid data starts.

Return Values

Returns S_OK if successful, or E_NOTIMPL.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetVideoFormat

The SetVideoFormat method sets the video format.

Syntax

HRESULT SetVideoFormat(
  DWORD dwChosenEntry
);

Parameters

dwChosenEntry

[in] Value specifying the index (zero-based) of the video pixel format to use.

Return Values

Returns an HRESULT value.

Remarks

Retrieve the video formats by using IVPBaseConfig::GetVideoFormats.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseConfig::SetVideoPortID

The SetVideoPortID method specifies the ID of the hardware video port to use.

Syntax

HRESULT SetVideoPortID (
  DWORD dwVideoPortID
);

Parameters

dwVideoPortID

[in] Specifies the video port ID. This value corresponds to the dwVideoPortID member of the DDVIDEOPORTDESC structure, which is documented in the Windows DDK.

Return Values

Returns an HRESULT value.

Remarks

This method sets the DirectDraw video port ID on the mini driver to enable it to communicate with the video port directly.

See Also

  • Error and Success Codes
  • IVPBaseConfig Interface


IVPBaseNotify Interface

Enables the Overlay Mixer to control the properties of a hardware device such as a decoder that uses a video port. The IVPNotify interface derives from this interface.

Applications should never use this interface.

Requirements

Requires Vptype.h, Vpnotify.h.

In addition to the methods inherited from IUnknown, the IVPBaseNotify interface exposes the following method.

Method | Description
RenegotiateVPParameters | Initializes the connection to the decoder.

See Also

  • IVPBaseConfig
  • IVPConfig


IVPBaseNotify::RenegotiateVPParameters

The RenegotiateVPParameters method initializes the connection to the decoder.

Syntax

HRESULT RenegotiateVPParameters(void);

Return Values

Returns an HRESULT value.

Remarks

The Overlay Mixer filter negotiates various parameters (by using the IVPBaseConfig interface) with the decoder or driver. Call this method if any of those parameters (such as the video format or size) change. Currently, the Overlay Mixer repeats the whole connection process. You can call this method even while the graph is playing.

See Also

  • Error and Success Codes
  • IVPBaseNotify Interface


IVPConfig Interface

IVPConfig must be implemented by any filter that wraps a hardware decoder with a video port. This enables the Overlay Mixer, through its IVPNotify interface, to set and retrieve configuration information on the video port regarding the video memory on the display adapter. This interface derives from IVPBaseConfig.

Applications never use this interface.

Requirements

Requires Dvp.h, Vptype.h, Vpconfig.h.

In addition to the methods inherited from IVPBaseConfig, the IVPConfig interface exposes the following methods.

Method | Description
IsVPDecimationAllowed | Given the context, retrieves whether scaling at the video port is possible.
SetScalingFactors | Sets the factors by which the decoder should scale the video stream.

See Also

  • IVPBaseNotify
  • IVPNotify2


IVPConfig::IsVPDecimationAllowed

The IsVPDecimationAllowed method, given the context, retrieves whether scaling at the video port is possible.

Syntax

HRESULT IsVPDecimationAllowed(
  AMVP_CONTEXT amvpContext,
  LPBOOL pbIsDecimationAllowed
);

Parameters

amvpContext

[in] Context (video or VBI) in which to query the VP decimation capability.

pbIsDecimationAllowed

[out] Pointer to the retrieved value indicating whether decimation is allowed.

Return Values

Returns an HRESULT value.

Remarks

The Overlay Mixer filter uses this function to determine whether the driver needs the mixer to decimate video data at its own discretion. This function can be especially useful in a capture with preview situation in which you would not want the VP mixer filter to perform any scaling at the video port.

See Also

  • Error and Success Codes
  • IVPConfig Interface


IVPConfig::SetScalingFactors

The SetScalingFactors method sets the factors by which the decoder should scale the video stream.

Syntax

HRESULT SetScalingFactors(
  LPAMVPSIZE pamvpSize
);

Parameters

pamvpSize

[in] Pointer to the new scaling size structure (AMVPSIZE) to use to specify the width and height.

Return Values

Returns an HRESULT value.

Remarks

If the decoder does not support the specified scaling factors, then it sets the values to the nearest factors it can support.

See Also

  • Error and Success Codes
  • IVPConfig Interface


IVPNotify Interface

Supports a private communication mechanism between the Overlay Mixer filter and a VPE decoder filter that represents a hardware decoder. This interface derives from IVPBaseNotify.

Only the Overlay Mixer filter implements this interface. Applications should never use it.

Requirements

Requires Vptype.h, Vpnotify.h.

In addition to the methods inherited from IVPBaseNotify, the IVPNotify interface exposes the following methods.

Method | Description
SetDeinterlaceMode | Sets the deinterlacing mode (such as bob or weave).
GetDeinterlaceMode | Retrieves the deinterlacing mode (such as bob or weave).

See Also

  • IVPBaseConfig
  • IVPConfig


IVPManager Interface

The IVPManager interface is implemented on the Video Port Manager (VPM). The interface provides methods for applications to specify and retrieve indexes for ports when there are multiple video ports on a system, and to specify and retrieve the rectangle used by the video port. Currently, only the two index-related methods are implemented.

In addition to the methods inherited from IUnknown, the IVPManager interface exposes the following methods:

Method | Description
GetVideoPortIndex | Returns the current video port index being used by the Video Port Manager.
GetVideoPortRects | Currently not implemented. An optional method that is useful in some very specific cases and may be implemented by the Video Port Manager at a later date.
SetVideoPortIndex | Instructs the Video Port Manager to connect to the specified video port.
SetVideoPortRects | Specifies the source and destination rectangles for the currently selected video port.


IVPManager::GetVideoPortIndex

The GetVideoPortIndex method returns the current video port index being used by the Video Port Manager (VPM).

Syntax

HRESULT GetVideoPortIndex(
  DWORD*  pdwVideoPortIndex
);

Parameters

pdwVideoPortIndex

[out] Pointer to a double word containing the index of the video port that the VPM is currently connected to.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method returns the current video port index being used by the Video Port Manager (VPM).

See Also

  • Error and Success Codes
  • IVPManager Interface
  • SetVideoPortIndex


IVPManager::GetVideoPortRects

The GetVideoPortRects method is an optional method that is useful in some very specific cases and may be implemented by the Video Port Manager (VPM) at a later date.

Syntax

HRESULT GetVideoPortRects(
  RECT*  pSrc,
  RECT*  pDest
);

Parameters

pSrc

[out] Pointer to a RECT structure that receives the source rectangle.

pDest

[out Pointer to a RECT structure that receives the destination rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Currently not implemented.

See Also

  • Error and Success Codes
  • IVPManager Interface
  • IVPManager::SetVideoPortRects


IVPManager::SetVideoPortIndex

The SetVideoPortIndex method instructs the Video Port Manager (VPM) to connect to the specified video port.

Syntax

HRESULT SetVideoPortIndex(
  DWORD  dwVideoPortIndex
);

Parameters

dwVideoPortIndex

[in] Double word containing the video port index.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Use this method on a multi-monitor system to specify to the Video Port Manager which video port index is being used.

See Also

  • Error and Success Codes
  • IVPManager::GetVideoPortIndex
  • IVPManager Interface


IVPManager::SetVideoPortRects

The SetVideoPortRects method specifies the source and destination rectangles for the currently selected video port.

Syntax

HRESULT SetVideoPortRects(
  const RECT*  pSrc,
  const RECT*  pDest
);

Parameters

pSrc

[in] Pointer to a RECT that specifies the source rectangle.

pDest

[in] Pointer to a RECT that specifies the destination rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

For both pSrc and pDest, specify NULL to indicate the entire image.

See Also

  • Error and Success Codes
  • IVPManager::GetVideoPortRects
  • IVPManager Interface


IVPNotify::GetDeinterlaceMode

The GetDeinterlaceMode method retrieves the mode (such as bob or weave).

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetDeinterlaceMode(
  AMVP_MODE *pmode
) PURE;

Parameters

pmode

[out] Pointer to the retrieved mode. This value is a member of the AMVP_MODE enumerated data type.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IVPNotify Interface


IVPNotify::SetDeinterlaceMode

Sets the mode (such as bob or weave).

Syntax

HRESULT SetDeinterlaceMode(
  AMVP_MODE mode
) PURE;

Parameters

mode

[in] Specified mode. This value is a member of the AMVP_MODE enumerated data type.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPNotify Interface


IVPNotify2 Interface

The IVPNotify2 interface inherits from IVPNotify and is implemented by the Overlay Mixer filter. This interface enables the Overlay Mixer to communicate with a video port (on a hardware device such as a decoder) that implements IVPConfig.

Applications should never use this interface.

Requirements

Requires Vptype.h, Vpnotify.h.

In addition to the methods inherited from IVPNotify, the IVPNotify2 interface exposes the following methods.

Method | Description
SetVPSyncMaster | Sets whether the video port controls vertical synchronization of the VGA.
GetVPSyncMaster | Checks whether the video port controls the synchronization of the VGA.


IVPNotify2::GetVPSyncMaster

The GetVPSyncMaster method checks whether the video port controls the synchronization of the VGA.

Syntax

HRESULT GetVPSyncMaster(
  BOOL *pbVPSyncMaster
) PURE;

Parameters

pbVPSyncMaster

[out] Pointer to a value indicating whether the video port controls the vertical synchronization of the VGA monitor. TRUE if the port controls the monitor's synchronization; FALSE otherwise.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPNotify2 Interface


IVPNotify2::SetVPSyncMaster

The SetVPSyncMaster method sets whether the video port controls vertical synchronization of the VGA.

Syntax

HRESULT GetVPSyncMaster(
  BOOL bVPSyncMaster
) PURE;

Parameters

bVPSyncMaster

[in] Value specifying whether the video port controls the vertical synchronization of the VGA monitor. TRUE if the port controls the monitor's synchronization; FALSE otherwise.

Return Values

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IVPNotify2 Interface


DirectShow Structures

This section describes the Microsoft® DirectShow® structures.

Structure | Description
ALLOCATOR_PROPERTIES | Contains the allocator's count, size, alignment, and prefix properties.
AM_MEDIA_TYPE | Describes a media type.
AM_SAMPLE2_PROPERTIES | Describes the properties of a generic media sample.
AM_STREAM_INFO | Contains start and stop information given to a pin.
AM_WMT_EVENT_DATA | Contains information pertaining to a WMT_STATUS event and the associated status code returned by the Windows Media Format SDK.
AM_WST_PAGE | Describes a page of WST text.
AMOVIESETUP_FILTER | Contains filter information for registering a filter.
AMOVIESETUP_MEDIATYPE | Contains media type information for registering a filter.
AMOVIESETUP_PIN | Contains pin information for registering a filter.
AMVABeginFrameInfo | Specifies information needed to begin processing the frame.
AMVABUFFERINFO | Describes buffer information.
AMVACompBufferInfo | Describes the allocated surfaces and compressed buffer information.
AMVAEndFrameInfo | Specifies information to finish processing the frame.
AMVAInternalMemInfo | Specifies the amount of scratch memory the hardware abstraction layer (HAL) will allocate for its private use.
AMVAUncompBufferInfo | Describes the surfaces to be allocated.
AMVAUncompDataInfo | Specifies the pixel format and dimensional characteristics of the data input stream.
AMVPDATAINFO | Specifies the data-specific characteristics of the VP input stream.
AMVPDIMINFO | Specifies the dimensional characteristics of the VP input stream.
AMVPSIZE | Specifies the width and height for a VP image.
ANALOGVIDEOINFO | Maintains information about the format of the analog video signal.
AUDIO_STREAM_CONFIG_CAPS | Contains information about all possible audio formats supported.
AVIMAINHEADER | Defines global information in an AVI file.
AVIOLDINDEX | Describes an AVI 1.0 index ('idx1' format).
AVIPALCHANGE | Defines a palette change in an AVI file.
AVISTREAMHEADER | Contains information about one stream in an AVI file.
BITMAPINFOHEADER | Contains information about the dimensions and color format of a device-independent bitmap (DIB).
CodecAPIEventData | Describes the event data that an encoder forwards along with an EC_CODECAPI_EVENT event.
COLORKEY | Communicates color key information between the renderer and another filter.
DVINFO | Describes the format of a digital video (DV) stream.
FILTER_INFO | Contains information about a filter.
MPEG1VIDEOINFO | Defines the format of MPEG-1 video data.
MPEG1WAVEFORMAT | Defines the format of MPEG-1 audio data.
MPEG2VIDEOINFO | Contains additional MPEG-2 video system information.
PIN_INFO | Contains information about a pin.
Quality | Defines a quality-control message.
REGFILTER2 | Describes a filter for registration through the IFilterMapper2 interface.
REGFILTERPINS | Contains pin information for registering a filter.
REGFILTERPINS2 | Contains information for registering a filter through the IFilterMapper2 interface.
REGPINMEDIUM | Describes a pin medium for registration through the IFilterMapper2 interface.
REGPINTYPES | Contains media type information for registering a filter.
STREAM_ID_MAP | Contains information about an elementary stream within an MPEG-2 program stream.
TIMECODE | Contains basic timecode frame count information.
TIMECODE_SAMPLE | Contains complete timecode information.
TRUECOLORINFO | Maintains color information.
VIDEO_STREAM_CONFIG_CAPS | Contains information about possible connections.
VIDEOINFO | Contains information that specifies a video image and its color palette and bitmasks.
VIDEOINFOHEADER | Describes the bitmap and color information for a video image.
VIDEOINFOHEADER2 | Describes the bitmap and color information for a video image, including interlace, copy protection, and pixel aspect ratio information.
WAVEFORMATEX | Defines the format of waveform-audio data.
WAVEFORMATEXTENSIBLE | Defines the format of waveform-audio data for formats having more than two channels.

The following structures relate to DVD navigation and playback:

Structure Description

AM_DVD_RENDERSTATUS | Contains codes indicating the status of DVD-Video playback. These codes are used in the IDvdGraphBuilder::RenderDvdVideoVolume method.
DVD_DECODER_CAPS | Contains information about the audio decoder's capabilities.
DVD_HMSF_TIMECODE | Encapsulates timecode information.
DVD_KaraokeAttributes | Contains information about karaoke audio streams on a DVD disc.
DVD_MenuAttributes | Contains information about the menus on a DVD disc.
DVD_MUA_Coeff | Contains information about surround sound mixing coefficients for multichannel audio on DVD.
DVD_MUA_MixingInfo | Contains information about surround sound mixing information on a DVD disc.
DVD_MultichannelAudioAttributes | Contains information about multichannel audio streams on a DVD disc.
DVD_PLAYBACK_LOCATION | Contains the DVD playback location.
DVD_PLAYBACK_LOCATION2 | Contains the DVD playback location.
DVD_SubpictureAttributes | Contains information about a subpicture stream on a DVD disc.
DVD_TIMECODE | Contains DVD timecode in hours, minutes, seconds, and frames.
DVD_TitleAttributes | Contains information about a title on a DVD disc.
DVD_VideoAttributes | Contains information about the video stream on a DVD disc.

The following structures are used with the Video Mixing Renderer Filter 7. These structures are available only on Microsoft® Windows® XP.

Structure | Description
DDCOLORKEY | Describes a color key as a range of values.
VMRALLOCATIONINFO | Used to allocate a new bitmap surface by the AllocateSurface method.
VMRALPHABITMAP | Provides a static alpha-blended bitmap to be displayed on the composited video frame supplied by the GetAlphaBitmapParameters method on the IVMRMixerBitmap interface.
VMRGUID | Used to identify a monitor on the system.
VMRMONITORINFO | Used to set and retrieve information about monitors on the system.
VMRPRESENTATIONINFO | Used to present video frame information.
VMRVIDEOSTREAMINFO | Contains video stream information that is used in the Video Mixing Renderer filter call to the IVMRImageCompositor::CompositeImage method.

The following structures are used with the Video Mixing Renderer Filter 9.

Structure | Description
DDCOLORKEY | Describes a color key as a range of values.
VMR9AllocationInfo | Used to allocate a new bitmap surface by the AllocateSurface method.
VMR9AlphaBitmap | Provides a static alpha-blended bitmap to be displayed on the composited video frame supplied by the GetAlphaBitmapParameters method on the IVMRMixerBitmap9 interface.
VMR9DeinterlaceCaps | Describes the capabilities of a deinterlacing mode.
VMR9Frequency | Describes the frequency of a video stream.
VMR9MonitorInfo | Used to set and retrieve information about monitors on the system.
VMR9NormalizedRect | Used to specify or retrieve the location of a video rectangle in composition space.
VMR9PresentationInfo | Used to present video frame information.
VMR9ProcAmpControl | Specifies the image adjustments to be performed on a video stream.
VMR9ProcAmpControlRange | Specifies the valid range for an image adjustment property.
VMR9VideoDesc | Sescribes a video stream to be deinterlaced.
VMR9VideoStreamInfo | Contains video stream information that is used by the VMR-9.


ALLOCATOR_PROPERTIES Structure

The ALLOCATOR_PROPERTIES structure describes an allocator's count, size, alignment, and prefix properties.

Syntax

typedef struct _AllocatorProperties {
    long cBuffers;
    long cbBuffer;
    long cbAlign;
    long cbPrefix;
} ALLOCATOR_PROPERTIES;

Members

cBuffers

Number of buffers created by the allocator.

cbBuffer

Size of each buffer in bytes, excluding any prefix.

cbAlign

Alignment of the buffer; buffer start will be aligned on a multiple of this value.

cbPrefix

Each buffer is preceded by a prefix of this many bytes.

Remarks

The IMediaSample::GetPointer method returns a pointer to the beginning of the buffer, not including the prefix bytes designated by cbPrefix.

The alignment is applied to the prefix data, if any. If a nonzero prefix is used, the beginning of the prefix is aligned according to cbAlign.

See Also

  • DirectShow Structures


AM_DVD_RENDERSTATUS Structure

The AM_DVD_RENDERSTATUS structure contains codes indicating the status of DVD-Video playback. These codes are used in the IDvdGraphBuilder::RenderDvdVideoVolume method.

Syntax

typedef struct {
    HRESULT hrVPEStatus;
    BOOL    bDVDVolInvalid;
    BOOL    bDVDVolUnknown;
    BOOL    bNoLine21In;
    BOOL    bNoLine21Out;
    int     iNumStreams;
    int     iNumStreamsFailed;
    DWORD   dwFailedStreamsFlag;
} AM_DVD_RENDERSTATUS;

Members

hrVPEStatus

Overlay/VPE error code. Zero indicates success; any other value is failure.

bDVDVolInvalid

TRUE if the specified DVD volume to be played does not exist; FALSE otherwise.

bDVDVolUnknown

TRUE if no DVD volume is specified or if it isn't found; FALSE otherwise.

bNoLine21In

TRUE if the video decoder doesn't produce line 21 (closed captioning) data; FALSE otherwise.

bNoLine21Out

TRUE if the video decoder can't be shown as closed captioning on video due to a problem with graph building; FALSE otherwise.

iNumStreams

Number of DVD streams to render.

iNumStreamsFailed

Number of streams that failed to render.

dwFailedStreamsFlag

Combination of AM_DVD_STREAM_FLAGS flags indicating which streams failed.

See Also

  • DirectShow Structures
  • IDvdGraphBuilder::RenderDvdVideoVolume


AM_MEDIA_TYPE Structure

The AM_MEDIA_TYPE structure describes the format of a media sample.

Syntax

typedef struct  _MediaType {
    GUID      majortype;
    GUID      subtype;
    BOOL      bFixedSizeSamples;
    BOOL      bTemporalCompression;
    ULONG     lSampleSize;
    GUID      formattype;
    IUnknown  *pUnk;
    ULONG     cbFormat;
    [size_is(cbFormat)] BYTE *pbFormat;
} AM_MEDIA_TYPE;

Members

majortype

Globally unique identifier (GUID) that specifies the major type of the media sample. For a list of possible major types, see Media Types.

subtype

GUID that specifies the subtype of the media sample. For a list of possible subtypes, see Media Types. For some formats, the value might be MEDIASUBTYPE_None, which means the format does not require a subtype.

bFixedSizeSamples

If TRUE, samples are of a fixed size. This field is informational only. For audio, it is generally set to TRUE. For video, it is usually TRUE for uncompressed video and FALSE for compressed video.

bTemporalCompression

If TRUE, samples are compressed using temporal (interframe) compression. A value of TRUE indicates that not all frames are key frames. This field is informational only.

lSampleSize

Size of the sample in bytes. For compressed data, the value can be zero.

formattype

GUID that specifies the structure used for the format block. The pbFormat member points to the corresponding format structure. Format types include the following:

Format type | Format structure
FORMAT_None | None.
FORMAT_DvInfo | DVINFO
FORMAT_MPEGVideo | MPEG1VIDEOINFO
FORMAT_MPEG2Video | MPEG2VIDEOINFO
FORMAT_VideoInfo | VIDEOINFOHEADER
FORMAT_VideoInfo2 | VIDEOINFOHEADER2
FORMAT_WaveFormatEx | WAVEFORMATEX
GUID_NULL | None

pUnk

Not used.

cbFormat

Size of the format block, in bytes.

pbFormat

Pointer to the format block. The structure type is specified by the formattype member. The format structure must be present, unless formattype is GUID_NULL or FORMAT_None.

Remarks

When two pins connect, they negotiate a media type, which is defined by an AM_MEDIA_TYPE structure. The media type describes the format of the data that the filters will exchange. If the filters do not agree on a media type, they cannot connect.

The stream type is specified by two GUIDs, called the major type and the subtype. The major type defines the general category, such as video, audio, or byte stream. The subtype defines a narrower category within the major type. For example, video subtypes include 8-bit, 16-bit, 24-bit, and 32-bit RGB.

The AM_MEDIA_TYPE structure is followed by a variable-length block of data that contains format-specific information. The pbFormat member points to this block, called the format block. The layout of the format block depends on the type of data in the stream, and is specified by the formattype member. The format block might be NULL. Check the cbFormat member to determine the size. Cast the pbFormat member to access the format block. For example:

if (pmt->formattype == FORMAT_VideoInfo)
{
    // Check the buffer size.
    if (pmt->cbFormat >= sizeof(VIDEOINFOHEADER))
    {
        VIDEOINFOHEADER *pVih =
            reinterpret_cast<VIDEOINFOHEADER*>(pmt->pbFormat);
        /* Access VIDEOINFOHEADER members through pVih. */
    }
}

In some situations, you can set the format block to NULL and the format type to GUID_NULL, resulting in a partial media type. This enables you to specify a range of possible formats. For example, you can specify 24-bit RGB (MEDIASUBTYPE_RGB24) without giving an exact width or height.

To obtain detailed information about a specified media type for debugging purposes, use the DisplayType method.

See Also

  • About Media Types
  • DirectShow Structures
  • Media Types
  • Media Type Functions


AM_SAMPLE2_PROPERTIES Structure

The AM_SAMPLE2_PROPERTIES structure describes the properties of a media sample. The IMediaSample2 interface uses this structure.

Syntax

typedef struct tagAM_SAMPLE2_PROPERTIES {
    DWORD           cbData;
    DWORD           dwTypeSpecificFlags;
    DWORD           dwSampleFlags;
    LONG            lActual;
    REFERENCE_TIME  tStart;
    REFERENCE_TIME  tStop;
    DWORD           dwStreamId;
    AM_MEDIA_TYPE   *pMediaType;
    BYTE            *pbBuffer;
    LONG            cbBuffer;
} AM_SAMPLE2_PROPERTIES;

Members

cbData

Length of property data, in bytes. This structure member is for extensibility.

dwTypeSpecificFlags

Type-specific flags. Flags are defined separately for each media type. Default value is AM_VIDEO_FLAG_INTERLEAVED_FRAME (zero). The following flags are used for video streams.

Flag | Value | Description
AM_VIDEO_FLAG_FIELD_MASK | 0x0003 | Use this mask to check whether the sample is a field or a frame.
AM_VIDEO_FLAG_INTERLEAVED_FRAME | 0x0000 | The sample is a frame. (Use the AM_VIDEO_FLAG_FIELD_MASK bitmask to test for this value.)
AM_VIDEO_FLAG_FIELD1 | 0x0001 | The sample is field 1. (Use the AM_VIDEO_FLAG_FIELD_MASK bitmask to test for this value.)
AM_VIDEO_FLAG_FIELD2 | 0x0002 | The sample is the field 2. (Use the AM_VIDEO_FLAG_FIELD_MASK bitmask to test for this value.)
AM_VIDEO_FLAG_FIELD1FIRST | 0x0004 | If this flag is set, display field 1 first. Otherwise, display field 2 first. (Applies only when there are two fields per sample.)
AM_VIDEO_FLAG_WEAVE | 0x0008 | If this flag is set, use weave mode (that is, do not deinterlace the sample). Otherwise, use bob mode. This flag applies only when there are two fields per sample.
AM_VIDEO_FLAG_REPEAT_FIELD | 0x0040 | If this flag is set, display the first field again after displaying the second field. (Applies only when there are two fields per sample.)

Other flags are defined but not currently used. See dvdmedia.h.

dwSampleFlags

Bitwise combination of flags the AM_SAMPLE_PROPERTY_FLAGS enumerated data type. Undefined bits are reserved and must be zero.

lActual

Length of the valid data in the buffer.

tStart

Start time, if valid. The dwSampleFlags member specifies whether this member is valid.

tStop

Stop time, if valid. The dwSampleFlags member specifies whether this member is valid.

dwStreamId

Stream identifier. If the value is AM_STREAM_MEDIA, the stream contains media data. If the value is AM_STREAM_CONTROL, the stream contains control information. Applications can define values of 0x80000000 or greater for their own use. (See AM_SAMPLE_PROPERTY_FLAGS Enumeration.)

pMediaType

Pointer to an AM_MEDIA_TYPE structure that specifies the media type if the format has changed. If this format has not changed, this member is NULL.

pbBuffer

Pointer to the sample buffer.

cbBuffer

Size of the sample buffer, in bytes.

See Also

  • DirectShow Structures


AM_STREAM_INFO Structure

The AM_STREAM_INFO structure contains stream-control information.

Syntax

typedef struct {
    REFERENCE_TIME tStart;
    REFERENCE_TIME tStop;
    DWORD dwStartCookie;
    DWORD dwStopCookie;
    DWORD dwFlags;
} AM_STREAM_INFO;

Members

tStart

Time when the pin will start streaming data.

tStop

Time when the pin will stop streaming data.

dwStartCookie

Value that will be sent with the event notification when the pin starts.

dwStopCookie

Value that will be sent with the event notification when the pin stops.

dwFlags

Bitwise combination of zero or more flags from the AM_STREAM_INFO_FLAGS enumeration.

See Also

  • DirectShow Structures
  • IAMStreamControl::GetInfo


AM_WMT_EVENT_DATA Structure

The AM_WMT_EVENT_DATA structure contains information pertaining to a EC_WMT_EVENT and the associated status code returned by the Windows Media Format SDK.

Syntax

typedef struct {
    HRESULT hrStatus;
    void * pData;            // event data
} AM_WMT_EVENT_DATA;

Members

hrStatus

The status code returned by the Windows Media Format SDK.

pData

Pointer whose data is dependent on the value of the WMT_STATUS message in lParam1 of the EC_WMT_EVENT event. For more information, see EC_WMT_EVENT.

Remarks

This structure is relevant when using the WM ASF Reader filter to read files protected with Digital Rights Management.

See Also

  • DirectShow Structures


AM_WST_PAGE Structure

The AM_WST_PAGE structure identifies a WST page.

Syntax

typedef struct _AM_WST_PAGE {
    DWORD    dwPageNr ;
    DWORD    dwSubPageNr ;
    BYTE*    pucPageData;
} AM_WST_PAGE, *PAM_WST_PAGE ;

Members

dwPageNr

The page number.

dwSubPageNr

The sub-page number.

pucPageData

A pointer to the page data.

See Also

  • DirectShow Structures


AMOVIESETUP_FILTER Structure

The AMOVIESETUP_FILTER structure contains information for registering a filter.

Syntax

typedef struct _AMOVIESETUP_FILTER {
    const CLSID           *clsID;
    const WCHAR           *strName;
    DWORD                 dwMerit;
    UINT                  nPins;
    const AMOVIESETUP_PIN *lpPin;
} AMOVIESETUP_FILTER, * PAMOVIESETUP_FILTER, * FAR LPAMOVIESETUP_FILTER;

Members

clsID

Class identifier of the filter.

strName

Name of the filter.

dwMerit

Filter merit. Used by the IGraphBuilder interface when constructing a filter graph.

nPins

Number of pins on the filter.

lpPin

Pointer to an array of AMOVIESETUP_PIN structures, of size nPins.


AMOVIESETUP_MEDIATYPE Structure

See REGPINTYPES.


AMOVIESETUP_PIN Structure

See REGFILTERPINS.


AMVABeginFrameInfo Structure

The AMVABeginFrameInfo structure specifies information needed to begin processing the frame.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVABeginFrameInfo{
    DWORD  dwDestSurfaceIndex;
    LPVOID pInputData;
    DWORD  dwSizeInputData;
    LPVOID pOutputData;
    DWORD  dwSizeOutputData;
 } AMVABeginFrameInfo, *LPAMVABeginFrameInfo;

Members

dwDestSurfaceIndex

Destination buffer in which to decode this frame.

pInputData

Pointer to miscellaneous data.

dwSizeInputData

Size of miscellaneous data to begin processing frame.

pOutputData

Pointer to data which the video graphics array (VGA) is going to fill.

dwSizeOutputData

Size of data which the VGA is going to fill.

Remarks

Note that you can't store pointers in pInputData, because their addresses will not be valid in kernel mode, where the frame processing occurs.

See Also

  • DirectShow Structures


AMVABUFFERINFO Structure

The AMVABUFFERINFO structure describes buffer information.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVABUFFERINFO{
    DWORD dwTypeIndex;
    DWORD dwBufferIndex;
    DWORD dwDataOffset;
    DWORD dwDataSize;
 } AMVABUFFERINFO, *LPAMVABUFFERINFO;

Members

dwTypeIndex

Type of buffer.

dwBufferIndex

Buffer index.

dwDataOffset

Offset of relevant data from the beginning of buffer.

dwDataSize

Size of relevant data.

See Also

  • DirectShow Structures


AMVACompBufferInfo Structure

The AMVACompBufferInfo structure describes the allocated surfaces and compressed buffer information.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVACompBufferInfo{
    DWORD dwNumCompBuffers;
    DWORD dwWidthToCreate;
    DWORD dwHeightToCreate;
    DWORD dwBytesToAllocate;
    DDSCAPS2 ddCompCaps;
    DDPIXELFORMAT ddPixelFormat;
 } AMVACompBufferInfo, *LPAMVACompBufferInfo;

Members

dwNumCompBuffers

Number of buffers requested for compressed data.

dwWidthToCreate

Width of surface to create.

dwHeightToCreate

Height of surface to create.

dwBytesToAllocate

Total number of bytes used by each surface.

ddCompCaps

DDSCAPS2 structure defining the capabilities of the DirectDrawSurface object created to store compressed data.

ddPixelFormat

DDPIXELFORMAT structure, describing the pixel format used to create surfaces to store compressed data.

See Also

  • DirectShow Structures


AMVAEndFrameInfo Structure

The AMVAEndFrameInfo structure specifies information to finish processing the frame.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVAEndFrameInfo{
    DWORD dwSizeMiscData;
    LPVOID pMiscData;
 } AMVAEndFrameInfo, *LPAMVAEndFrameInfo;

Members

dwSizeMiscData

Size of other miscellaneous data to begin frame.

pMiscData

Pointer to miscellaneous data.

Remarks

Note that you are not allowed to store a pointer in pMiscData.

See Also

  • DirectShow Structures


AMVAInternalMemInfo Structure

The AMVAInternalMemInfo structure specifies the amount of scratch memory the hardware abstraction layer (HAL) will allocate for its private use.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVAInternalMemInfo{
    DWORD dwScratchMemAlloc;
 } AMVAInternalMemInfo, *LPAMVAInternalMemInfo;

Members

dwScratchMemAlloc

Amount of scratch memory the HAL will allocate for its private use.

See Also

  • DirectShow Structures


AMVAUncompBufferInfo Structure

The AMVAUncompBufferInfo structure describes the surfaces to be allocated.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVAUncompBufferInfo{
    DWORD dwMinNumSurfaces;
    DWORD dwMaxNumSurfaces;
    DDPIXELFORMAT ddUncompPixelFormat;
 } AMVAUncompBufferInfo, *LPAMVAUncompBufferInfo;

Members

dwMinNumSurfaces

Minimum number of surfaces to be allocated.

dwMaxNumSurfaces

Maximum number of surfaces to be allocated.

ddUncompPixelFormat

DDPIXELFORMAT structure, describing the pixel format of surfaces to be allocated.

See Also

  • DirectShow Structures


AMVAUncompDataInfo Structure

The AMVAUncompDataInfo structure specifies the pixel format and dimensional characteristics of the data input stream.

Note This structure is available in Microsoft® Windows® 98 Second Edition, Windows 2000, and later operating systems.

Syntax

typedef struct _tag_AMVAUncompDataInfo{
    DWORD dwUncompWidth;
    DWORD dwUncompHeight;
    DDPIXELFORMAT ddUncompPixelFormat;
 } AMVAUncompDataInfo, *LPAMVAUncompDataInfo;

Members

dwUncompWidth

Width of uncompressed data.

dwUncompHeight

Height of uncompressed data.

ddUncompPixelFormat

DDPIXELFORMAT structure, describing the pixel format of uncompressed data.

See Also

  • DirectShow Structures


AMVPDATAINFO Structure

The AMVPDATAINFO structure specifies the data-specific characteristics of the VP input stream.

Syntax

typedef struct _AMVPDATAINFO{
    DWORD dwSize;
    DWORD dwMicrosecondsPerField;
    AMVPDIMINFO amvpDimInfo;
    DWORD dwPictAspectRatioX;
    DWORD dwPictAspectRatioY;
    BOOL bEnableDoubleClock;
    BOOL bEnableVACT;
    BOOL bDataIsInterlaced;
    LONG lHalfLinesOdd;
    BOOL bFieldPolarityInverted;
    DWORD dwNumLinesInVREF;
    LONG lHalfLinesEven;
    DWORD dwReserved1;
} AMVPDATAINFO, *LPAMVPDATAINFO;

Members

dwSize

Size of the structure, in bytes.

dwMicrosecondsPerField

Time taken by each field.

amvpDimInfo

Dimensional information.

dwPictAspectRatioX

The X dimension of picture aspect ratio.

dwPictAspectRatioY

The Y dimension of picture aspect ratio.

bEnableDoubleClock

Video port should enable double clocking.

bEnableVACT

Video port should use an external VACT signal.

bDataIsInterlaced

Indicates that the signal is interlaced.

lHalfLinesOdd

Number of half lines in the odd field.

bFieldPolarityInverted

Video port should invert the field polarity.

dwNumLinesInVREF

Number of lines of data in VREF.

lHalfLinesEven

Number of half lines in the even field.

dwReserved1

Reserved for future use.

See Also

  • DirectShow Structures


AMVPDIMINFO Structure

The AMVPDIMINFO structure specifies the dimensional characteristics of a video port (VP) input stream.

Syntax

typedef struct _AMVPDIMINFO{
    DWORD dwFieldWidth;
    DWORD dwFieldHeight;
    DWORD dwVBIWidth;
    DWORD dwVBIHeight;
    RECT rcValidRegion;
} AMVPDIMINFO, *LPAMVPDIMINFO;

Members

dwFieldWidth

Field width of the data.

dwFieldHeight

Field height of the data.

dwVBIWidth

Width of the VBI data.

dwVBIHeight

Height of the VBI data.

rcValidRegion

Valid rectangle, used for cropping.

See Also

  • DirectShow Structures


AMVPSIZE Structure

The AMVPSIZE structure specifies the width and height for a VP image.

Syntax

typedef struct _AMVPSIZE{
    DWORD dwWidth;
    DWORD dwHeight;
} AMVPSIZE, *LPAMVPSIZE;

Members

dwWidth

Width, in pixels.

dwHeight

Height.

Remarks

The context could be anything such as scaling, cropping, and so on.

See Also

  • DirectShow Structures


ANALOGVIDEOINFO Structure

The ANALOGVIDEOINFO structure maintains information about the format of the analog video signal.

Syntax

typedef struct tagAnalogVideoInfo {
    RECT            rcSource;
    RECT            rcTarget;
    DWORD           dwActiveWidth;
    DWORD           dwActiveHeight;
    REFERENCE_TIME  AvgTimePerFrame;
} ANALOGVIDEOINFO;

Members

rcSource

Source video rectangle.

rcTarget

Destination target rectangle.

dwActiveWidth

Source video width.

dwActiveHeight

Source video height (483 for NTSC, 575 for PAL/SECAM).

AvgTimePerFrame

Average time per frame in 100-nanosecond units.

Remarks

Filters using this format usually pass the video signal using a hardware-based connection rather than using memory-based transports.

An example of a definition of an analog video media type connection would be a connection of NTSC video using "M" color encoding. This would use a major media type of MEDIATYPE_AnalogVideo, a subtype of MEDIASUBTYPE_AnalogVideo_NTSC_M, and a format type of FORMAT_AnalogVideo.

See Also

  • DirectShow Structures


AUDIO_STREAM_CONFIG_CAPS Structure

The AUDIO_STREAM_CONFIG_CAPS structure describes a range of audio formats. Audio compression and capture filters use this structure to describe the formats they can produce.

Syntax

typedef struct _AUDIO_STREAM_CONFIG_CAPS {
    GUID guid;
    ULONG MinimumChannels;
    ULONG MaximumChannels;
    ULONG ChannelsGranularity;
    ULONG MinimumBitsPerSample;
    ULONG MaximumBitsPerSample;
    ULONG BitsPerSampleGranularity;
    ULONG MinimumSampleFrequency;
    ULONG MaximumSampleFrequency;
    ULONG SampleFrequencyGranularity;
} AUDIO_STREAM_CONFIG_CAPS;

Members

guid

Will be set to MEDIATYPE_Audio to indicate an audio sample.

MinimumChannels

Minimum number of channels.

MaximumChannels

Maximum number of channels.

ChannelsGranularity

Granularity of the channels. For example, the filter might specify channels 2 through 4, in steps of 2.

MinimumBitsPerSample

Minimum bits per sample.

MaximumBitsPerSample

Maximum bits per sample.

BitsPerSampleGranularity

Granularity of the bits per sample. For example, the filter might specify 8 bits per sample through 32 bits per sample, in steps of 8.

MinimumSampleFrequency

Minimum sample frequency.

MaximumSampleFrequency

Maximum sample frequency.

SampleFrequencyGranularity

Granularity of the frequency. For example, the filter might specify 11025 Hz to 44100 Hz, in steps of 11025 Hz.

See Also

  • IAMStreamConfig::GetStreamCaps
  • DirectShow Structures


AVIMAINHEADER Structure

The AVIMAINHEADER structure defines global information in an AVI file.

Syntax

typedef struct _avimainheader {
    FOURCC fcc;
    DWORD  cb;
    DWORD  dwMicroSecPerFrame;
    DWORD  dwMaxBytesPerSec;
    DWORD  dwPaddingGranularity;
    DWORD  dwFlags;
    DWORD  dwTotalFrames;
    DWORD  dwInitialFrames;
    DWORD  dwStreams;
    DWORD  dwSuggestedBufferSize;
    DWORD  dwWidth;
    DWORD  dwHeight;
    DWORD  dwReserved[4];
} AVIMAINHEADER;

Members

fcc

Specifies a FOURCC code. The value must be 'avih'.

cb

Specifies the size of the structure, not including the initial 8 bytes.

dwMicroSecPerFrame

Specifies the number of microseconds between frames. This value indicates the overall timing for the file.

dwMaxBytesPerSec

Specifies the approximate maximum data rate of the file. This value indicates the number of bytes per second the system must handle to present an AVI sequence as specified by the other parameters contained in the main header and stream header chunks.

dwPaddingGranularity

Specifies the alignment for data, in bytes. Pad the data to multiples of this value.

dwFlags

Contains a bitwise combination of zero or more of the following flags:

Value | Description
AVIF_HASINDEX | Indicates the AVI file has an index.
AVIF_MUSTUSEINDEX | Indicates that application should use the index, rather than the physical ordering of the chunks in the file, to determine the order of presentation of the data. For example, this flag could be used to create a list of frames for editing.
AVIF_ISINTERLEAVED | Indicates the AVI file is interleaved.
AVIF_WASCAPTUREFILE | Indicates the AVI file is a specially allocated file used for capturing real-time video. Applications should warn the user before writing over a file with this flag set because the user probably defragmented this file.
AVIF_COPYRIGHTED | Indicates the AVI file contains copyrighted data and software. When this flag is used, software should not permit the data to be duplicated.

dwTotalFrames

Specifies the total number of frames of data in the file.

dwInitialFrames

Specifies the initial frame for interleaved files. Noninterleaved files should specify zero. If you are creating interleaved files, specify the number of frames in the file prior to the initial frame of the AVI sequence in this member. For more information about the contents of this member, see "Special Information for Interleaved Files" in the Video for Windows Programmer's Guide.

dwStreams

Specifies the number of streams in the file. For example, a file with audio and video has two streams.

dwSuggestedBufferSize

Specifies the suggested buffer size for reading the file. Generally, this size should be large enough to contain the largest chunk in the file. If set to zero, or if it is too small, the playback software will have to reallocate memory during playback, which will reduce performance. For an interleaved file, the buffer size should be large enough to read an entire record, and not just a chunk.

dwWidth

Specifies the width of the AVI file in pixels.

dwHeight

Specifies the height of the AVI file in pixels.

dwReserved

Reserved. Set this array to zero.

Requirements

Include Aviriff.h

See Also

  • AVI RIFF File Reference
  • DirectShow Structures


AVIOLDINDEX Structure

The AVIOLDINDEX structure describes an AVI 1.0 index ('idx1' format). New AVI files should use an AVI 2.0 index ('indx' format).

Syntax

typedef struct _avioldindex {
   FOURCC  fcc;
   DWORD   cb;
   struct _avioldindex_entry {
      DWORD   dwChunkId;
      DWORD   dwFlags;
      DWORD   dwOffset;
      DWORD   dwSize;
  } aIndex[];
} AVIOLDINDEX;

Members

fcc

Specifies a FOURCC code. The value must be 'idx1'.

cb

Specifies the size of the structure, not including the initial 8 bytes.

dwChunkId

Specifies a FOURCC that identifies a stream in the AVI file. The FOURCC must have the form 'xxyy' where xx is the stream number and yy is a two-character code that identifies the contents of the stream:

Two-character code | Description
db | Uncompressed video frame
dc | Compressed video frame
pc | Palette change
wb | Audio data

dwFlags

Specifies a bitwise combination of zero or more of the following flags:

Value | Description
AVIIF_KEYFRAME | The data chunk is a key frame.
AVIIF_LIST | The data chunk is a 'rec ' list.
AVIIF_NO_TIME | The data chunk does not affect the timing of the stream. For example, this flag should be set for palette changes.

dwOffset

Specifies the location of the data chunk in the file. The value should be specified as an offset, in bytes, from the start of the 'movi' list; however, in some AVI files it is given as an offset from the start of the file.

dwSize

Specifies the size of the data chunk, in bytes.

Remarks

This structure consists of the initial RIFF chunk (the fcc and cb members) followed by one index entry for each data chunk in the 'movi' list.

Requirements

Include Aviriff.h.

See Also

  • AVI RIFF File Reference
  • DirectShow Structures


AVIPALCHANGE Structure

The AVIPALCHANGE structure defines a palette change in an AVI file.

Syntax

typedef struct
{
    BYTE          bFirstEntry;
    BYTE          bNumEntries;
    WORD          wFlags;
    PALETTEENTRY  peNew[];
} AVIPALCHANGE;

Members

bFirstEntry

Specifies the index of the first palette entry to change.

bNumEntries

Specifies the number of palette entries to change, or zero to change all 256 palette entries.

wFlags

Reserved.

peNew

Specifies an array of PALETTEENTRY structures, of size bNumEntries.

Requirements

Include Avifmt.h.

See Also

  • AVI RIFF File Reference
  • DirectShow Structures


AVISTREAMHEADER Structure

The AVISTREAMHEADER structure contains information about one stream in an AVI file.

Syntax

typedef struct _avistreamheader {
     FOURCC fcc;
     DWORD  cb;
     FOURCC fccType;
     FOURCC fccHandler;
     DWORD  dwFlags;
     WORD   wPriority;
     WORD   wLanguage;
     DWORD  dwInitialFrames;
     DWORD  dwScale;
     DWORD  dwRate;
     DWORD  dwStart;
     DWORD  dwLength;
     DWORD  dwSuggestedBufferSize;
     DWORD  dwQuality;
     DWORD  dwSampleSize;
     struct {
         short int left;
         short int top;
         short int right;
         short int bottom;
     }  rcFrame;
} AVISTREAMHEADER;

Members

fcc

Specifies a FOURCC code. The value must be 'strh'.

cb

Specifies the size of the structure, not including the initial 8 bytes.

fccType

Contains a FOURCC that specifies the type of the data contained in the stream. The following standard AVI values for video and audio are defined.

FOURCC | Description
'auds' | Audio stream
'mids' | MIDI stream
'txts' | Text stream
'vids' | Video stream

fccHandler

Optionally, contains a FOURCC that identifies a specific data handler. The data handler is the preferred handler for the stream. For audio and video streams, this specifies the codec for decoding the stream.

dwFlags

Contains any flags for the data stream. The bits in the high-order word of these flags are specific to the type of data contained in the stream. The following standard flags are defined.

Value | Description
AVISF_DISABLED | Indicates this stream should not be enabled by default.
AVISF_VIDEO_PALCHANGES | Indicates this video stream contains palette changes. This flag warns the playback software that it will need to animate the palette.

dwPriority

Specifies priority of a stream type. For example, in a file with multiple audio streams, the one with the highest priority might be the default stream.

dwInitialFrames

Specifies how far audio data is skewed ahead of the video frames in interleaved files. Typically, this is about 0.75 seconds. If you are creating interleaved files, specify the number of frames in the file prior to the initial frame of the AVI sequence in this member. For more information about the contents of this member, see "Special Information for Interleaved Files" in the Video for Windows Programmer's Guide.

dwScale

Used with dwRate to specify the time scale that this stream will use. Dividing dwRate by dwScale gives the number of samples per second. For video streams, this is the frame rate. For audio streams, this rate corresponds to the time needed to play nBlockAlign bytes of audio, which for PCM audio is the just the sample rate.

dwRate

See dwScale.

dwStart

Specifies the starting time for this stream. The units are defined by the dwRate and dwScale members in the main file header. Usually, this is zero, but it can specify a delay time for a stream that does not start concurrently with the file.

dwLength

Specifies the length of this stream. The units are defined by the dwRate and dwScale members of the stream's header.

dwSuggestedBufferSize

Specifies how large a buffer should be used to read this stream. Typically, this contains a value corresponding to the largest chunk present in the stream. Using the correct buffer size makes playback more efficient. Use zero if you do not know the correct buffer size.

dwQuality

Specifies an indicator of the quality of the data in the stream. Quality is represented as a number between 0 and 10,000. For compressed data, this typically represents the value of the quality parameter passed to the compression software. If set to –1, drivers use the default quality value.

dwSampleSize

Specifies the size of a single sample of data. This is set to zero if the samples can vary in size. If this number is nonzero, then multiple samples of data can be grouped into a single chunk within the file. If it is zero, each sample of data (such as a video frame) must be in a separate chunk. For video streams, this number is typically zero, although it can be nonzero if all video frames are the same size. For audio streams, this number should be the same as the nBlockAlign member of the WAVEFORMATEX structure describing the audio.

rcFrame

Specifies the destination rectangle for a text or video stream within the movie rectangle specified by the dwWidth and dwHeight members of the AVI main header structure. The rcFrame member is typically used in support of multiple video streams. Set this rectangle to the coordinates corresponding to the movie rectangle to update the whole movie rectangle. Units for this member are pixels. The upper-left corner of the destination rectangle is relative to the upper-left corner of the movie rectangle.

Remarks

Some of the members of this structure are also present in the AVIMAINHEADER structure. The data in the AVIMAINHEADER structure applies to the whole file, while the data in the AVISTREAMHEADER structure applies to one stream.

Requirements

Include Aviriff.h

See Also

  • AVI RIFF File Reference
  • DirectShow Structures


BITMAPINFOHEADER Structure

The BITMAPINFOHEADER structure contains information about the dimensions and color format of a device-independent bitmap (DIB).

Note This structure is fully described in the Microsoft® Platform SDK. This entry is included in the DirectShow documentation for quick reference.

Syntax

typedef struct tagBITMAPINFOHEADER {
    DWORD  biSize;
    LONG   biWidth;
    LONG   biHeight;
    WORD   biPlanes;
    WORD   biBitCount;
    DWORD  biCompression;
    DWORD  biSizeImage;
    LONG   biXPelsPerMeter;
    LONG   biYPelsPerMeter;
    DWORD  biClrUsed;
    DWORD  biClrImportant;
} BITMAPINFOHEADER;

Members

biSize

Specifies the number of bytes required by the structure.

biWidth

Specifies the width of the bitmap.

  • For RGB formats, the width is specified in pixels.
  • The same is true for YUV formats if the bitdepth is an even power of 2.
  • For YUV formats where the bitdepth is not an even power of 2, however, the width is specified in bytes.

Decoders and video sources should propose formats where biWidth is the width of the image. If the video renderer is using DirectDraw, it modifies the format so that biWidth equals the stride of the surface, and the rcTarget member of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure specifies the image width. Then it proposes the modified format using IPin::QueryAccept.

For RGB and even-power-of-2 YUV formats, if the video renderer does not specify the stride, then round the width up to the nearst DWORD boundardy to find the stride.

biHeight

Specifies the height of the bitmap, in pixels.

  • For uncompressed RGB bitmaps, if biHeight is positive, the bitmap is a bottom-up DIB with the origin at the lower left corner. If biHeight is negative, the bitmap is a top-down DIB with the origin at the upper left corner.
  • For YUV bitmaps, the bitmap is always top-down, regardless of the sign of biHeight. Decoders should offer YUV formats with postive biHeight, but for backward compatibility they should accept YUV formats with either positive or negative biHeight.
  • For compressed formats, biHeight must be positive, regardless of image orientation.

biPlanes

Specifies the number of planes for the target device. This value must be set to 1.

biBitCount

Specifies the number of bits per pixel.

biCompression

If the bitmap is compressed, this member is a FOURCC the specifies the compression. For uncompressed formats, the following values are possible:

Value | Description
BI_RGB | Uncompressed RGB.
BI_BITFIELDS | Uncompressed RGB with color masks. Valid for 16-bpp and 32-bpp bitmaps.

See Remarks for more information.

biSizeImage

Specifies the size, in bytes, of the image. This can be set to 0 for uncompressed RGB bitmaps.

biXPelsPerMeter

Specifies the horizontal resolution, in pixels per meter, of the target device for the bitmap.

biYPelsPerMeter

Specifies the vertical resolution, in pixels per meter, of the target device for the bitmap.

biClrUsed

Specifies the number of color indices in the color table that are actually used by the bitmap.

biClrImportant

Specifies the number of color indices that are considered important for displaying the bitmap. If this value is zero, all colors are important.

Remarks

If the bitmap is 8-bpp or less, the bitmap uses a color table, which immediately follows the BITMAPINFOHEADER. The color table consists of an array of RGBQUAD values. The size of the array is given by the biClrUsed member. If biClrUsed is zero, the array contains the maximum number of colors for the given bitdepth; that is, 2^biBitCount colors.

If biCompression equals BI_BITFIELDS, bitmap uses three DWORD color masks (red, green, and blue, respectively), which specify the byte layout of the pixels. The 1 bits in each mask indicate the bits for that color within the pixel.

For 16-bpp bitmaps, if biCompression equals BI_RGB, the format is RGB 555. If biCompression equals BI_BITFIELDS, the format is either RGB 555 or RGB 565. Use the subtype GUID in the AM_MEDIA_TYPE structure to determine the specific RGB type.

For compressed or YUV types the FOURCC value is specified as a DWORD in little-endian order. For example, YUYV would be 'VYUY' or 0x56595559. For more information, see FOURCC Codes.

In cases where the BITMAPINFOHEADER is followed by a color table or a set of color masks, you can use the BITMAPINFO structure to reference the color table of the color masks. The BITMAPINFO structure is defined as follows:

typedef struct tagBITMAPINFO {
    BITMAPINFOHEADER bmiHeader;
    RGBQUAD          bmiColors[1];
} BITMAPINFO;

If you cast the BITMAPINFOHEADER to a BITMAPINFO, the bmiHeader member refers to the BITMAPINFOHEADER and the bmiColors member refers to the first entry in the color table, or the first color mask.

Be aware that if the bitmap uses a color table or color masks, then the size of the entire format structure (the BITMAPINFOHEADER plus the color information) is not equal to sizeof(BITMAPINFOHEADER) or sizeof(BITMAPINFO). You must calculate the actual size for each instance.

See Also

  • DirectShow Structures
  • VIDEOINFOHEADER Structure
  • VIDEOINFOHEADER2 Structure
  • Working with DIBs


CodecAPIEventData Structure

The CodecAPIEventData structure describes the event data that an encoder forwards along with an EC_CODECAPI_EVENT event.

Syntax

struct CodecAPIEventData
{
    GUID    guid;
    DWORD   dataLength;
    DWORD   reserved[3];
    // A block of data of size dataLength follows this structure.
};

Members

guid

GUID value that identifies the encoder event.

dataLength

Specifies the length of the event data that follows this structure, in bytes.

reserved

Reserved; do not use.

Remarks

The lParam2 parameter in the EC_CODECAPI_EVENT event is a pointer to a block of data that starts with a CodecAPIEventData structure. The rest of the block contains the event data. The size of the event data is given by the dataLength member.

If guid equals CODECAPI_CHANGELISTS, the data is an array of GUIDs, indicating which parameters have changed following a call to set one or more parameter values. The size of the array is equal to dataLength / sizeof(GUID). The driver may send multiple CODECAPI_CHANGELISTS messages for one call.

See Also

  • DirectShow Structures
  • ICodecAPI::RegisterForEvent


COLORKEY Structure

The COLORKEY structure communicates color key information between the renderer and another filter.

Syntax

typedef struct tagCOLORKEY {
    DWORD     KeyType;
    DWORD     PaletteIndex;
    COLORREF  LowColorValue;
    COLORREF  HighColorValue;
} COLORKEY;

Members

KeyType

Key type. Can be CK_NOCOLORKEY, CK_INDEX, or CK_RGB. CK_INDEX and CK_RGB can be logically combined.

PaletteIndex

Palette index.

LowColorValue

Lowest RGB color value.

HighColorValue

Highest RGB color value.

Remarks

The video renderer supports a data transport accessed through the IOverlay interface. This will typically be used by hardware decoder filters that need the renderer to communicate where to put the data rather than requiring the renderer to draw the data. One mechanism for communicating where to put the images is by using a color key. This structure is used by a filter (typically a hardware decoder) to describe color key requirements to the video renderer.

See Also

  • DirectShow Structures


DDCOLORKEY Structure

Describes a color key as a range of values.

Requirements

Requires Microsoft® Windows® XP.

Syntax

typedef struct {
  DWORD dw1;
  DWORD dw2;
} DDCOLORKEY;

Members

dw1

Specifies the lower bound of the color key range.

dw2

Specifies the upper bound of the color key range.

Remarks

This structure is used by the Video Mixing Renderer (VMR) filter, which is available only on Windows XP. The VMR uses this structure to support the DirectDraw capability of specifying a range of values for a color key by using two DWORDs. The VMR and the graphics card automatically determine whether the two DWORDs are interpreted as RGB or YUV color space values. Not all hardware may support this capability. To ensure compatibility with all hardware, set dw1 and dw2 to the same value.


DVD_AudioAttributes Structure

The DVD_AudioAttributes structure is used in IDvdInfo2::GetAudioAttributes to receive the various audio attributes of the disc.

Syntax

typedef struct tagDVD_AudioAttributes {
    DVD_AUDIO_APPMODE   AppMode;
    DVD_AUDIO_FORMAT    AudioFormat;
    LCID                Language;
    DVD_AUDIO_LANG_EXT  LanguageExtension;
    BOOL                fHasMultichannelInfo;
    DWORD               dwFrequency;
    BYTE                bQuantization;
    BYTE                bNumberOfChannels;
    DWORD               dwReserved[2];
} DVD_AudioAttributes;

Members

AppMode

Indicates the current audio mode. If the mode returned is DVD_AudioMode_Karaoke, call IDvdInfo2::GetKaraokeAttributes to get more info.

AudioFormat

Describes the format (encoding mode) of the audio stream.

Language

An LCID value indicating the language of the audio stream. Is zero if no language is present.

LanguageExtension

A DVD_AUDIO_LANG_EXT enumeration that will be filled in if any information is available on the disc.

fHasMultichannelInfo

Indicates whether multichannel attributes are present. If TRUE, it means there is additional mixing information available, such as for SurroundSound. Call IDvdInfo2::GetTitleAttributes to retrieve the multichannel information.

dwFrequency

The frequency in hertz (48k, 96k) of the audio stream.

bQuantization

The resolution of the audio stream (16, 20, 24 bits, or other) Zero indicates the resolution is unknown.

bNumberOfChannels

The number of channels. For example, 5.1 Dolby AC-3 has six channels.

dwReserved

Currently not used.

See Also

  • DirectShow Structures


DVD_DECODER_CAPS Structure

The DVD_DECODER_CAPS structure indicates the capabilities of a DVD decoder.

Syntax

typedef struct tagDVD_DECODER_CAPS {
    DWORD   dwSize ;
    DWORD   dwAudioCaps ;
    double  dFwdMaxRateVideo ;
    double  dFwdMaxRateAudio ;
    double  dFwdMaxRateSP ;
    double  dBwdMaxRateVideo ;
    double  dBwdMaxRateAudio ;
    double  dBwdMaxRateSP ;
    DWORD   dwRes1 ;
    DWORD   dwRes2 ;
    DWORD   dwRes3 ;
    DWORD   dwRes4 ;
} DVD_DECODER_CAPS ;

Members

dwSize

Size of this structure.

dwAudioCaps

Bitwise OR indicating which audio formats are supported. Possible values are:

  • DVD_AUDIO_CAPS_AC3 = 0x00000001
  • DVD_AUDIO_CAPS_MPEG2 = 0x00000002
  • DVD_AUDIO_CAPS_LPCM = 0x00000004
  • DVD_AUDIO_CAPS_DTS = 0x00000008
  • DVD_AUDIO_CAPS_SDDS = 0x00000010

dFwdMaxRateVideo

Maximum video data rate in forward direction.

dFwdMaxRateAudio

Maximum audio data rate in forward direction.

dFwdMaxRateSP

Maximum subpicture data rate in forward direction.

dBwdMaxRateVideo

Maximum video data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)

dBwdMaxRateAudio

Maximum audio data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)

dBwdMaxRateSP

Maximum subpicture data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)

dwRes1

Reserved for future use.

dwRes2

Reserved for future use.

dwRes3

Reserved for future use.

dwRes4

Reserved for future use.

See Also

  • DirectShow Structures
  • IDvdInfo2::GetDecoderCaps


DVD_HMSF_TIMECODE Structure

The DVD_HMSF_TIMECODE structure encapsulates the hours, minutes, seconds, and frames in a DVD timecode.

Syntax

typedef struct tagDVD_HMSF_TIMECODE {
    BYTE    bHours;
    BYTE    bMinutes;
    BYTE    bSeconds;
    BYTE    bFrames;
} DVD_HMSF_TIMECODE;

Members

bHours

Hours.

bMinutes

Minutes.

bSeconds

Minutes.

bFrames

Frames.

Remarks

A DVD_HMSF_TIMECODE structure is for use with IDvdControl2 and IDvdInfo2. A DVD_HMSF_TIMECODE structure can be cast to or from a ULONG value. This means that if you need to use the old BCD time format for backward compatibility, you can do so in place of a DVD_HMSF_TIMECODE structure.

See Also

  • DirectShow Structures


DVD_KaraokeAttributes Structure

The DVD_KaraokeAttributes structure contains information about a karaoke audio stream. The IDvdInfo2::GetKaraokeAttributes method fills in a DVD_KaraokeAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_KaraokeAttributes {
    BYTE  bVersion;
    BOOL  fMasterOfCeremoniesInGuideVocal1;
    BOOL  fDuet;
    DVD_KARAOKE_ASSIGNMENT  ChannelAssignment;
    WORD  wChannelContents[8];
} DVD_KaraokeAttributes;

Members

bVersion

The current karaoke version is 1.0.

fMasterOfCeremoniesInGuideVocal1

TRUE means that the "Guide Vocal 1" channel contains the "Master of Ceremonies" content.

fDuet

A BOOLEAN value indicating whether the song is intended to be sung as a duet.

ChannelAssignment

A DVD_KARAOKE_ASSIGNMENT value indicating the speaker configuration into which all the channels will be mixed.

wChannelContents

An array of valid DVD_KARAOKE_CONTENTS values that identifies the content on each channel.

See Also

  • DirectShow Structures


DVD_MenuAttributes Structure

The DVD_MenuAttributes structure contains information about a DVD menu. The IDvdInfo2::GetTitleAttributes method fills in a DVD_MenuAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_MenuAttributes {
    BOOL                        fCompatibleRegion[8];
    DVD_VideoAttributes         VideoAttributes;
    BOOL                        fAudioPresent;
    DVD_AudioAttributes         AudioAttributes;
    BOOL                        fSubpicturePresent;
    DVD_SubpictureAttributes    SubpictureAttributes;
} DVD_MenuAttributes;

Members

fCompatibleRegion

An array of TRUE/FALSE values indicating with which DVD regions the disc's authored region is compatible. The eight array indexes (numbered 0-7) correspond to the eight DVD regions (numbered 1-8). This array is only filled in when the menu being queried is the Video Manager Menu (the main menu for the entire disc).

Important: A value of 0 (FALSE) indicates that the region is compatible (permitted). A value of 1 (TRUE) indicates that the region is not compatible. This member should have been named fIncompatibleRegion.

VideoAttributes

A DVD_VideoAttributes structure containing the video attributes of the menu. This applies to both a VMGM and VTSM.

fAudioPresent

A variable of type BOOL indicating whether the menu has an audio stream.

AudioAttributes

A DVD_AudioAttributes structure containing information about the menu's audio stream. This structure will only be filled in if fAudioPresent is true.

fSubpicturePresent

A variable of type BOOL indicating whether the menu has a subpicture stream.

SubpictureAttributes

A DVD_SubpictureAttributes structure containing information about the menu's subpicture stream. This structure will only be filled in if fSubpicturePresent is true.

See Also

  • DirectShow Structures


DVD_MUA_Coeff Structure

The DVD_MUA_Coeff structure defines the mixing coefficients for one channel in a multichannel audio stream. The DVD_MultichannelAudioAttributes structure contains an array of eight DVD_MUA_Coeff structures, one for each channel in the stream.

Syntax

typedef struct tagDVD_MUA_Coeff {
    double   log2_alpha;
    double   log2_beta;
} DVD_MUA_Coeff;

Members

log2_alpha

Variable of type double indicating the mixing coefficient for this channel to channel 0.

log2_beta

Variable of type double indicating the mixing coefficient for this channel to channel 1.

Remarks

The information contained in this structure reflects the mixing coefficients as authored on the digital video disc (DVD). An application cannot modify these values or otherwise use them unless it is also decoding the audio. In the typical DVD filter graph, the DVD Navigator filter does not send this information to the decoder.

The alpha coefficient is used to mix to audio channel 0 and the beta coefficient is used to mix to audio channel 1. In general, the following formula calculates the mixing coefficients.

Audio channel 0 = coeff[0].alpha * value[0] + coeff[1].alpha * value[1] + ...
Audio channel 1 = coeff[0].beta * value[0]  + coeff[1].beta * value[1] + ...

See Also

  • DirectShow Structures
  • DVD_AudioAttributes
  • DVD_MUA_MixingInfo


DVD_MUA_MixingInfo Structure

The DVD_MUA_MixingInfo structure describes the surround sound mixing information for the channels in one audio stream in a specified title.

Syntax

typedef struct tagDVD_MUA_MixingInfo {
    BOOL    fMixTo0;
    BOOL    fMixTo1;
    BOOL    fMix0InPhase;
    BOOL    fMix1InPhase;
    DWORD   dwSpeakerPosition;
} DVD_MUA_MixingInfo;

Members

fMixTo0

Variable of type BOOL; TRUE means the channel is mixed to channel 0.

fMixTo1

Variable of type BOOL; TRUE means the channel is mixed to channel 1.

fMix0InPhase

Variable of type BOOL; TRUE means the channel is mixed in phase to channel 0.

fMix1InPhase

Variable of type BOOL; TRUE means the channel is mixed in phase to channel 1.

dwSpeakerPosition

Variable of type DWORD indicating the speaker for which this channel is intended. See Remarks.

Remarks

Applications cannot use the information contained in this structure to change the mixing unless they have a way to communicate with a custom audio decoder that has been inserted manually into the filter graph. The default audio decoder handles Linear Pulse Code Modulated (LPCM) audio using the mixing information on the digital video disc (DVD), but applications have no way to instruct the decoder to modify the mixing values. This means that current DVD playback applications should have no need to access the multichannel-related data structures.

The DVD_MultichannelAudioAttributes structure contains information about one audio stream in a specified title. An array of up to eight DVD_MUA_MixingInfo structures will be populated in this structure, if the following conditions are true.

  • DVD_AudioAttributes.AppMode = DVD_AudioMode_Surround
  • DVD_AudioAttributes.AudioFormat = DVD_AudioFormat_LPCM
  • DVD_AudioAttributes.fHasMultichannelInfo = 1

Possible values for dwSpeakerPosition are defined in Ksmedia.h as follows:

Define | Value
KSAUDIO_SPEAKER_LEFT | 0x1
KSAUDIO_SPEAKER_RIGHT | 0x2
KSAUDIO_SPEAKER_CENTER | 0x4
KSAUDIO_SPEAKER_SURROUND_LEFT | 0x8
KSAUDIO_SPEAKER_SURROUND_RIGHT | 0x10
KSAUDIO_SPEAKER_SUBWOOFER | 0x20
KSAUDIO_SPEAKER_LEFT_OF_CENTER | 0x40
KSAUDIO_SPEAKER_RIGHT_OF_CENTER | 0x80
KSAUDIO_SPEAKER_SURROUND_MONO | 0x100
KSAUDIO_SPEAKER_SIDE_LEFT | 0x200
KSAUDIO_SPEAKER_SIDE_RIGHT | 0x400
KSAUDIO_SPEAKER_TOP | 0x800

See Also

  • DirectShow Structures
  • DVD_AudioAttributes


DVD_MultichannelAudioAttributes Structure

The DVD_MultichannelAudioAttributes structure describes the multichannel attributes of one audio stream within a specified title.

Syntax

typedef struct tagDVD_MultichannelAudioAttributes {
    DVD_MUA_MixingInfo  Info[8];
    DVD_MUA_Coeff       Coeff[8];
} DVD_MultichannelAudioAttributes;

Members

Info

Array of eight DVD_MUA_MixingInfo structures, which contain the mixing information for each channel in the audio stream.

Coeff

Array of eight DVD_MUA_Coeff structures, which contain the mixing coefficients for each channel in the audio stream.

Remarks

The DVD_TitleAttributes structure contains an array of up to eight DVD_MultichannelAudioAttributes structures. When DVD_TitleAttributes is filled by a call to the IDvdInfo2::GetTitleAttributes method, the array will be populated with one DVD_MultichannelAudioAttributes structure for each available audio stream in the title.

See Also

  • DirectShow Structures


DVD_PLAYBACK_LOCATION Structure

The DVD_PLAYBACK_LOCATION structure indicates DVD playback location.

Syntax

typedef struct tagDVD_PLAYBACK_LOCATION {
    ULONG   TitleNum;
    ULONG   ChapterNum;
    ULONG   TimeCode;
} DVD_PLAYBACK_LOCATION;

Members

TitleNum

Title number for the whole disc; Title Track Number (TTN) not Video Title Set_Title Track Number (VTS_TTN).

ChapterNum

Part-of-title number with title. 0xffffffff if not a simple linear movie.

TimeCode

Timecode. Use DVD_TIMECODE for current playback time. 0xFFFFFFFF if not a simple linear movie.

Remarks

TitleNum and ChapterNum or TitleNum and TimeCode are sufficient to save the playback location for simple linear movies.

See Also

  • DirectShow Structures


DVD_PLAYBACK_LOCATION2 Structure

The DVD_PLAYBACK_LOCATION2 structure indicates DVD playback location.

Syntax

typedef struct tagDVD_PLAYBACK_LOCATION2 {
    ULONG   TitleNum;
    ULONG   ChapterNum;
    DVD_HMSF_TIMECODE   TimeCode;
    ULONG   TimeCodeFlags;
} DVD_PLAYBACK_LOCATION2;

Members

TitleNum

Title number for the whole disc (not the track number of the Video Title Set).

ChapterNum

Part-of-title number with title. 0xffffffff if not a simple linear movie.

TimeCode

Timecode. Use DVD_HMSF_TIMECODE for current playback time. 0xffffffff if not a simple linear movie.

TimeCodeFlags

A union of DVD_TIMECODE_EVENT_FLAGS.

Remarks

TitleNum and ChapterNum or TitleNum and TimeCode are sufficient to save the playback location for simple linear movies.

See Also

  • DirectShow Structures


DVD_SubpictureAttributes Structure

The DVD_SubpictureAttributes structure contains information about the DVD subpicture. The IDvdInfo2::GetSubpictureAttributes method fills in a DVD_SubpictureAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_SubpictureAttributes {
    DVD_SUBPICTURE_TYPE     Type;
    DVD_SUBPICTURE_CODING   CodingMode;
    LCID                    Language;
    DVD_SUBPICTURE_LANG_EXT LanguageExtension;
} DVD_SubpictureAttributes;

Members

Type

Variable of type DVD_SUBPICTURE_TYPE that indicates whether the subpicture contains language-related content.

CodingMode

Variable of type DVD_SUBPICTURE_CODING that indicates how the subpicture graphics stream is encoded.

Language

Variable of type LCID that identifies the subpicture language if Type equals DVD_SPType_Language.

LanguageExtension

Variable of type DVD_SUBPICTURE_LANG_EXT that identifies the subpicture language extension if Type equals DVD_SPType_Language.

See Also

  • DirectShow Structures


DVD_TIMECODE Structure

The DVD_TIMECODE structure contains DVD timecode in hours, minutes, seconds, and frames.

Syntax

typedef struct tagDVD_TIMECODE {
   ULONG Hours1:4;
   ULONG Hours10:4;
   ULONG Minutes1:4;
   ULONG Minutes10:4;
   ULONG Seconds1:4;
   ULONG Seconds10:4;
   ULONG Frames1:4;
   ULONG Frames10:2;
   ULONG FrameRateCode:2;
} DVD_TIMECODE;

Members

Hours1

Hours.

Hours10

Tens of hours.

Minutes1

Minutes.

Minutes10

Tens of minutes.

Seconds1

Seconds.

Seconds10

Tens of seconds.

Frames1

Frames.

Frames10

Tens of frames.

FrameRateCode

Frames per second dropped and not dropped as indicated by DVD_FRAMERATE.

Remarks

DVD timecode is binary coded decimal (BCD) encoded in the format 0xHhMmSsFf, where:

  • H is tens of hours
  • h is hours
  • M is tens of minutes
  • m is minutes
  • S is tens of seconds
  • s is seconds
  • F is tens of frames
  • f is frames

See Also

  • DirectShow Structures


DVD_TitleAttributes Structure

The DVD_TitleAttributes structure contains information about a DVD title. The IDvdInfo2::GetTitleAttributes method fills in a DVD_TitleAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_TitleMainAttributes {
    DVD_TITLE_APPMODE                   AppMode;
    DVD_VideoAttributes                 VideoAttributes;
    ULONG                               ulNumberOfAudioStreams;
    DVD_AudioAttributes                 AudioAttributes[8];
    DVD_MultichannelAudioAttributes     MultichannelAudioAttributes[8];
    ULONG                               ulNumberOfSubpictureStreams;
    DVD_SubpictureAttributes            SubpictureAttributes[32];
} DVD_TitleAttributes;

Members

AppMode

A variable of type DVD_TITLE_APPMODE indicating whether the Navigator is in "karaoke" mode or some other mode.

VideoAttributes

A DVD_VideoAttributes structure containing information about the "main" video of the current menu or title.

ulNumberOfAudioStreams

A variable of type ULONG indicating the number of audio streams available in the title.

AudioAttributes

An array of DVD_AudioAttributes structures containing information about each available audio stream in the current title.

MultichannelAudioAttributes

An array of DVD_MultichannelAudioAttributes structures containing additional information about any available audio stream that is in a multichannel format. This structure will be filled in for the corresponding audio stream if the multichannel bit is set in that stream's DVD_AudioAttributes structure.

ulNumberOfSubpictureStreams

A variable of type ULONG indicating the number of subpicture streams available in the title.

SubpictureAttributes

An array of DVD_SubpictureAttributes structures that contain information about each subpicture stream in the title.DVD_SubpictureAttributes structures containing information about each available subpicture stream in the title.

See Also

  • DirectShow Structures


DVD_VideoAttributes Structure

The DVD_VideoAttributes structure describes the attributes of the video stream for the current title or menu.

Syntax

typedef struct tagDVD_VideoAttributes {
    BOOL                     fPanscanPermitted;
    BOOL                     fLetterboxPermitted;
    ULONG                    ulAspectX;
    ULONG                    ulAspectY;
    ULONG                    ulFrameRate;
    ULONG                    ulFrameHeight;
    DVD_VIDEO_COMPRESSION    Compression;
    BOOL                     fLine21Field1InGOP;
    BOOL                     fLine21Field2InGOP;
    ULONG                    ulSourceResolutionX;
    ULONG                    ulSourceResolutionY;
    BOOL                     fIsSourceLetterboxed;
    BOOL                     fIsFilmMode;
} DVD_VideoAttributes;

Members

fPanscanPermitted

TRUE means the picture can be shown as pan-scan if the display aspect ratio is 4 x 3.

fLetterboxPermitted

TRUE means the picture can be shown as letterbox if the display aspect ratio is 4 x 3.

ulAspectX

The video stream's X aspect (4 or 16).

ulAspectY

The video stream's Y aspect (3 or 9).

ulFrameRate

The frame rate in hertz (Hz), either 50 or 60.

ulFrameHeight

The frame height in lines (525 for a frame rate of 60 Hz or 625 for 50 Hz).

Compression

Variable of type DVD_VIDEO_COMPRESSION indicating the MPEG compression type used on the disc.

fLine21Field1InGOP

TRUE means there is user data in line 21, field 1.

fLine21Field2InGOP

TRUE means there is user data in line 21, field 2.

ulSourceResolutionX

The x-axis source resolution (352, 704, or 720).

ulSourceResolutionY

The y-axis source resolution (240, 480, 288, or 576).

fIsSourceLetterboxed

TRUE means the source video is in letterbox format. Subpictures and menu buttons can only be displayed in the active video area.

fIsFilmMode

For 625/50 Hz systems, TRUE means "film mode" and FALSE means "camera mode."

Remarks

This structure is filled when an application calls the IDvdInfo2::GetCurrentVideoAttributes method.

See Also

  • DirectShow Structures


DVINFO Structure

The DVINFO structure describes the format of a digital video (DV) stream.

Syntax

typedef struct tag_DVINFO {
    DWORD dwDVAAuxSrc;
    DWORD dwDVAAuxCtl;
    DWORD dwDVAAuxSrc1;
    DWORD dwDVAAuxCtl1;
    DWORD dwDVVAuxSrc;
    DWORD dwDVVAuxCtl;
    DWORD dwDVReserved[2];
} DVINFO, *PDVINFO;

Members

dwDVAAuxSrc

Specifies the Audio Auxiliary Data Source Pack for the first audio block (first 5 DV DIF sequences for 525-60 systems or 6 DV DIF sequences for 625-50 systems) of a frame. A DIF sequence is a data block that contains 150 DIF blocks. A DIF block consists of 80 bytes. The Audio Auxiliary Data Source Pack is defined in section D.7.1 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.

dwDVAAuxCtl

Specifies the Audio Auxiliary Data Source Control Pack for the first audio block of a frame. The Audio Auxiliary Data Control Pack is defined in section D.7.2 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.

dwDVAAuxSrc1

Specifies the Audio Auxiliary Data Source Pack for the second audio block (second 5 DV DIF sequences for 525-60 systems or 6 DV DIF sequences for 625-50 systems) of a frame.

dwDVAAuxCtl1

Specifies the Audio Auxiliary Data Source Control Pack for the second audio block of a frame.

dwDVVAuxSrc

Specifies the Video Auxiliary Data Source Pack as defined in section D.8.1 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.

dwDVVAuxCtl

Specifies the Video Auxiliary Data Source Control Pack as defined in section D.8.2 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.

DwDVReserved

Reserved. Set this array to zero.

See Also

  • DV Data in the AVI File Format


FILTER_INFO Structure

The FILTER_INFO structure contains information about a filter.

Syntax

typedef struct _FilterInfo {
    WCHAR        achName[MAX_FILTER_NAME];
    IFilterGraph *pGraph;
} FILTER_INFO;

Members

achName

Null-terminated string containing the name of the filter.

pGraph

If the filter is member of a filter graph, contains a pointer to the filter graph's IFilterGraph interface. If the filter is not a member of a filter graph, this value of this member is NULL.

Remarks

If the pGraph member is not NULL, the application should release the IFilterGraph interface when it is finished using it.

See Also

  • DirectShow Structures


KSMULTIPLE_ITEM Structure

The KSMULTIPLE_ITEM structure describes the size and count of variable-length properties on kernel-mode pins.

Syntax

typedef struct {
    ULONG    Size;
    ULONG    Count;
} KSMULTIPLE_ITEM, *PKSMULTIPLE_ITEM;

Members

Size

Size of the returned memory block, in bytes. The size includes the KSMULTIPLE_ITEM structure and the items that follow it.

Count

Specifies the total number of items that follow this structure.

See Also

  • REGPINMEDIUM
  • IKsPin::KsQueryMediums
  • DirectShow Structures


MPEG1VIDEOINFO Structure

The MPEG1VIDEOINFO structure describes an MPEG-1 video stream.

Syntax

typedef struct tagMPEG1VIDEOINFO {
    VIDEOINFOHEADER hdr;
    DWORD           dwStartTimeCode;
    DWORD           cbSequenceHeader;
    BYTE            bSequenceHeader[1];
} MPEG1VIDEOINFO;

Members

hdr

VIDEOINFOHEADER structure.

dwStartTimeCode

25-bit group-of-pictures (GOP) time code at start of data.

cbSequenceHeader

Length of the bSequenceHeader member, in bytes.

bSequenceHeader

Sequence header including quantization matrices, if any.

See Also

  • DirectShow Structures


MPEG1WAVEFORMAT

The MPEG1WAVEFORMAT structure describes the format of MPEG-1 audio data.

Syntax

typedef struct mpeg1waveformat_tag {
    WAVEFORMATEX    wfx;
    WORD            fwHeadLayer;
    DWORD           dwHeadBitrate;
    WORD            fwHeadMode;
    WORD            fwHeadModeExt;
    WORD            wHeadEmphasis;
    WORD            fwHeadFlags;
    DWORD           dwPTSLow;
    DWORD           dwPTSHigh;
} MPEG1WAVEFORMAT;

Members

wfx

WAVEFORMATEX structure that contains information about the audio format. See Remarks.

fwHeadLayer

Specifies the MPEG audio layer, as defined by the following constants:

Value | Description
ACM_MPEG_LAYER1 | Layer 1
ACM_MPEG_LAYER2 | Layer 2
ACM_MPEG_LAYER3 | Layer 3

Some MPEG stream may contain frames from more than one layer. If so, combine the flags with a bitwise OR.

dwHeadBitrate

Specifies the bitrate, in bits per second. This value gives the actual bitrate, not the MPEG frame header code. If the bitrate is variable, or is a non-standard bitrate, set this field to zero.

fwHeadMode

Specifies the stream mode, as defined by the following constants:

Value | Description
ACM_MPEG_STEREO | Stereo
ACM_MPEG_JOINTSTEREO | Joint stereo
ACM_MPEG_DUALCHANNEL | Dual channel
ACM_MPEG_SINGLECHANNEL | Single channel

Some MPEG streams may contain frames with different modes. If so, combine the flags with a bitwise OR.

fwHeadModeExt

Specifies the mode extension for joint-stereo encoding:

Value | MPEG Frame Header Code | Layers 1 and 2 | Layer 3
0x01 | '00' | Intensity stereo in bands 4 to 31 | Intensity stereo off; Middle/Side (MS) stereo off
0x02 | '01' | Intensity stereo in bands 8 to 31 | Intensity stereo on; MS stereo off
0x04 | '10' | Intensity stereo in bands 12 to 31 | Intensity stereo off; MS stereo on
0x08 | '11' | Intensity stereo in bands 16 to 31 | Intensity stereo off; MS stereo on

These values may be combined with a bitwise OR. In general, encoders will dynamically switch between extension modes according to the characteristics of the signal. Therefore, for normal joint-stereo encoding, set this field to 0x0F (the bitwise OR of all the flags). However, you can use this field to limit the encoder to a set of allowable encoding types.

This field applies only when fwHeadMode includes ACM_MPEG_JOINTSTEREO. For other modes, set this field to zero.

wHeadEmphasis

Sepecifies the de-emphasis required by the decoder:

Value | MPEG Frame Header Code | De-emphasis Required
1 | '00' | None
2 | '01' | 50/15 ms emphasis
3 | '10' | Reserved
4 | '11' | CCITT J.17

fwHeadFlags

Specifies a bitwise combination of zero or more of the following flags:

Value | Description
ACM_MPEG_PRIVATEBIT | Set the private bit.
ACM_MPEG_COPYRIGHT | Set the copyright bit.
ACM_MPEG_ORIGINALHOME | Set the original/home bit.
ACM_MPEG_PROTECTIONBIT | Set the protection bit, and insert a 16-bit error protection code into each frame.
ACM_MPEG_ID_MPEG1 | Set the ID bit to 1, defining the stream as an MPEG-1 audio stream.

An encoder will use these flags to set the corresponding bits in the MPEG audio frame headers.

dwPTSLow

Specifies the least signifcant 32 bits of the presentation time stamp (PTS) of the first frame of the audio stream.

dwPTSHigh

Specifies the most significant bit of the PTS. The dwPTSLow and dwPTSHigh fields can be treated as a single 64-bit value.

Remarks

For MPEG-1 audio, the WAVEFORMATEX structure defined in the wfx member must have the following values.

WAVEFORMATEX Member | Description
wFormatTag | Must be WAVE_FORMAT_MPEG
nChannels | 1 for mono, 2 for stereo
nSamplesPerSec | Specifies the sampling frequency, if the sampling frequency is fixed. If it is variable, set this field to zero.
nAvgBytesPerSec | Specifies the average data rate. If variable bitrate encoding is used under layer 3, the value might not be a legal MPEG-1 bit rate.
nBlockAlign For audio streams with a fixed audio frame length, this field specifies the length of the audio frame. If the frame length is variable, set this field to 1.

If the sampling frequency is 32 kHz or 48 kHz and the bit rate is constant, the audio frame size is constant. In that case, calculate nBlockAlign as follows:

  • Layer 1: 4 * (int)(12 * bitrate / sampling frequency)
  • Layers 2 and 3: (int)(144 * bitrate / sampling frequency)

If the bit rate is variable or the sampling frequency is 44.1 kHz, the audio frame size is not constant and nBlockAlign should be 1.
wBitsPerSample | Not used; set to zero.
cbSize | Specifies the size of the format data after the WAVEFORMATEX structure, in bytes. For the standard MPEG1WAVEFORMAT structure, this value is 22 bytes.

See Also

  • DirectShow Structures
  • MPEG-1 Media Types


MPEG2_TRANSPORT_STRIDE

The MPEG2_TRANSPORT_STRIDE structure describes the format of MPEG-2 transport stream (TS) packets. This structure allows for transports streams in which the 188-byte transport packets are not contiguous. For the purpose of this documentation, such packets are referred to as stride packets.

Stride packets are identified by the following media type:

Major Type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE
Format Type | FORMAT_None

The format block (pbFormat) is optional. If the format block is included, it must begin with an MPEG2_TRANSPORT_STRIDE structure. This structure defines the layout of the transport packet within the stride packet. If the format block is NULL, the packets are assumed to use a set of default values; see the Remarks section for details.

Syntax

struct MPEG2_TRANSPORT_STRIDE {
    DWORD   dwOffset
    DWORD   dwPacketLength
    DWORD   dwStride
};

Members

dwOffset

Specifies the offset, in bytes, from the beginning of the packet to the first byte of the embedded transport packet. The value must range from zero to (dwStride - dwPacketLength), inclusive.

dwPacketLength

Specifies the length of the embedded transport packet, in bytes. For standard MPEG-2 transport packets, the value must be 188 bytes.

dwStride

Specifies the length of the entire stride packet, in bytes. The value must be at least (dwOffset + dwPacketLength).

Remarks

The following diagram illustrates the relations between the structure members.

MPEG-2 stride packet

Input buffers that contain multiplexed stride packets have some restrictions:

  • Stride packets must be packed contiguously within the buffer.
  • No bytes may precede the first stride packet or follow the last stride packet.
  • An integral number of stride packets must fit in the buffer; that is, buffer length % dwStride equals zero.

There is no restriction on the number of stride packets per buffer.

If the media type does not contain a format block (pbFormat is NULL), the following default values are used:

  • dwOffset: 0
  • dwPacketLength: 188
  • dwStride: 188

See Also

  • DirectShow Structures
  • MPEG-2 Media Types


MPEG2VIDEOINFO Structure

The MPEG2VIDEOINFO structure describes an MPEG-2 video stream.

Syntax

typedef struct tagMPEG2VIDEOINFO {
    VIDEOINFOHEADER2    hdr;
    DWORD               dwStartTimeCode;
    DWORD               cbSequenceHeader;
    DWORD               dwProfile;
    DWORD               dwLevel;
    DWORD               dwFlags;
    DWORD               dwSequenceHeader[1];
} MPEG2VIDEOINFO;

Members

hdr

VIDEOINFOHEADER2 structure.

dwStartTimeCode

25-bit group-of-pictures (GOP) time code at start of data. This field is not used for DVD.

cbSequenceHeader

Length of the sequence header, in bytes. For DVD, set this field to zero. The sequence header is given in the dwSequenceHeader field.

dwProfile

Specifies the MPEG-2 profile as an AM_MPEG2Profile enumeration type.

dwLevel

Specifies the MPEG-2 level as an AM_MPEG2Level enumeration type.

dwFlags

Flag indicating preferences. Set one or a combination of the following values.

Flag | Description
AMMPEG2_DoPanScan (0x00000001) | If this flag is set, the MPEG-2 video decoder should crop the output image based on pan-scan vectors in picture_display_extension and change the picture aspect ratio to 4x3. The VMR should not receive a 16x9 sample with this flag. A simple implementation might alter the source rectangle to indicate a 540 wide source region with a left edge equal to the display offset in the picture_display_extension.
AMMPEG2_DVDLine21Field1 (0x00000002) | If set, the MPEG-2 decoder must be able to produce an output pin for DVD style closed-captioned data found in the Group Of Pictures (GOP) layer of field 1.
AMMPEG2_DVDLine21Field2 (0x00000004) | If set, the MPEG-2 decoder must be able to produce an output pin for DVD style closed-captioned data found in the GOP layer of field 2.
AMMPEG2_SourceIsLetterboxed (0x00000008) | If set, indicates that black bars have been encoded in the top and bottom of the video.
AMMPEG2_FilmCameraMode (0x00000010) | If set, indicates "film mode" used for the 625/50 (line/field) content. If cleared, indicates that "camera mode" was used.
AMMPEG2_LetterboxAnalogOut (0x00000020) | If set and this stream is sent to an analog output, it should be letterboxed. Streams sent to VGA should be letterboxed only by renderers.
AMMPEG2_DSS_UserData (0x00000040) | If set, the MPEG-2 decoder must process DSS style user data.
AMMPEG2_DVB_UserData (0x00000080) | If set, the MPEG-2 decoder must process DVB style user data.
AMMPEG2_27MhzTimebase (0x00000100) | If set, the PTS, DTS timestamps advance at 27MHz rather than 90KHz.
AMMPEG2_WidescreenAnalogOut (0x00000200) | If set and this stream is sent to an analog output, it should be in widescreen format (4x3 content should be centered on a 16x9 output). Streams sent to VGA should be widescreened only by renderers.

Set undefined flags to zero or connection will be rejected. For more information on how to use these flags, see MPEG Decoder Preprocessing Transformations.

dwSequenceHeader

Address of a buffer that contains the sequence header, including quantization matrices and the sequence extension, if required. This field is typed as DWORD array to preserve the 32-bit alignment.

Requirements

Include Dvdmedia.h

See Also

  • DirectShow Structures


NORMALIZEDRECT

The NORMALIZEDRECT structure is used with the VMR filter in mixing operations to specify or retrieve the location of a video rectangle in composition space.

Syntax

typedef struct _NORMALIZEDRECT {
    float  left;
    float  top;
    float  right;
    float  bottom;
} NORMALIZEDRECT;
typedef struct _NORMALIZEDRECT *PNORMALIZEDRECT;

Members

left

Specifies left.

top

Specifies top.

right

Specifies right.

bottom

Specifies bottom.

Remarks

This structure is used in methods involving "composition space," which refers to the visible video rectangle, as well as the "offscreen" space necessary to contain rectangles from secondary streams. See Using the Video Mixing Renderer for more information.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Structures


PID_MAP Structure

The PID_MAP structure contains identifies the contents of an MPEG-2 transport stream packet ID.

Syntax

typedef struct {
    ULONG                   ulPID;
    MEDIA_SAMPLE_CONTENT    MediaSampleContent ;
} PID_MAP;

Members

ulPID

Specifies the packet ID (PID)

MediaSampleContent

Specifies the contents of the packet payload, as a MEDIA_SAMPLE_CONTENT enumeration type.

See Also

  • DirectShow Structures
  • IEnumPIDMap Interface


PIN_INFO Structure

The PIN_INFO structure contains information about a pin.

Syntax

typedef struct _PinInfo {
    IBaseFilter *pFilter;
    PIN_DIRECTION dir;
    WCHAR achName[MAX_PIN_NAME];
} PIN_INFO;

Members

pFilter

Pointer to the IBaseFilter interface of the owning filter.

dir

Direction of the pin (input or output).

achName

Name of the pin.

Remarks

If the name of an output pin begins with a tilde (~), the filter graph manager ignores the pin when it builds a graph. During a call to IGraphBuilder::Connect, IGraphBuilder::Render, or IGraphBuilder::RenderFile, if the pin appears on an intermediate filter, the filter graph manager does not render the pin. However, it renders the pin if you explicitly pass the pin to the Connect or Render method.

Use a tilde if the pin delivers a secondary stream that should not be rendered by default, or if the pin requires special code to render correctly. For example, DVD filters should use it for pins that deliver subpicture or closed captioning data. Video capture filters should use it for capture pins (but not preview pins).

The pFilter member has an outstanding reference count. The application must release the interface.

See Also

  • DirectShow Structures
  • IPin::QueryPinInfo


Quality Structure

The Quality structure describes a quality message by indicating Flood or Famine in the renderer and specifying the percentage of frames to drop or add to optimize the renderer's performance.

Syntax

typedef struct{
    QualityMessageType  Type;
    long                Proportion;
    REFERENCE_TIME      Late;
    REFERENCE_TIME      TimeStamp;
} Quality;

Members

Type

Value from the QualityMessageType enumeration, indicating whether the downstream filter needs more or less data.

Proportion

Value that specifies the rate at which Microsoft® DirectShow® should continue to send media samples. The base value is 1000, which indicates there should be no change. A percentage increase or decrease from 1000 indicates the percentage of frames to add or drop. If this value is 800, for example, DirectShow will drop 20 percent of the incoming frames to match the renderer's speed.

Late

If a famine exists downstream, this is the amount of time by which the stream is lagging.

TimeStamp

Value that specifies the time when DirectShow created this structure, which is usually the start time on a video sample.

See Also

  • DirectShow Structures


REGFILTER2 Structure

The REGFILTER2 structure contains information for registering a filter.

Syntax

typedef struct {
    DWORD dwVersion;
    DWORD dwMerit;
    union
    {
        struct {
            ULONG cPins;
            const REGFILTERPINS *rgPins;
        };
        struct {
            ULONG cPins2;
            const REGFILTERPINS2 *rgPins2;
        };
    };
} REGFILTER2;

Members

dwVersion

Filter registration format. If the value is 1, the union contains the first unnamed structure. If the value is 2, the union contains the second unnamed structure.

dwMerit

Filter merit. Filters with higher merit are enumerated first. See Merit.

cPins

Number of pins. (Defined only if dwVersion is 1.)

rgPins

Pointer to an array of REGFILTERPINS structures, of size cPins. (Defined only if dwVersion is 1.)

cPins2

Number of pins. (Defined only if dwVersion is 2.)

rgPins2

Pointer to an array of REGFILTERPINS2 structures, of size cPins2. (Defined only if dwVersion is 2.)

Remarks

This structure is passed to the IFilterMapper2::RegisterFilter method.

If you need to register pin mediums or pin categories, set dwVersion to 2 and use the REGFILTERPINS2 structure.

See Also

  • DirectShow Structures


REGFILTERPINS Structure

The REGFILTERPINS structure contains pin information for registering a filter.

Syntax

typedef struct {
    LPWSTR            strName;
    BOOL              bRendered;
    BOOL              bOutput;
    BOOL              bZero;
    BOOL              bMany;
    const CLSID       *clsConnectsToFilter;
    const WCHAR       *strConnectsToPin;
    UINT              nMediaTypes;
    const REGPINTYPES *lpMediaType;
} REGFILTERPINS;

typedef REGFILTERPINS AMOVIESETUP_PIN,
    * PAMOVIESETUP_PIN,
    * LPAMOVIESETUP_PIN;

Members

strName

Name of the pin. (Obsolete.)

bRendered

If TRUE, the filter renders the input from this pin. (Applies only to input pins. For output pins, the value is always FALSE.)

bOutput

If TRUE, this pin is an output pin. Otherwise, the pin is an input pin.

bZero

If TRUE, the filter can have zero instances of this pin.

bMany

If TRUE, the filter can create more than one instance of this type of pin.

clsConnectsToFilter

Class identifier (CLSID) of the filter to which this pin connects. (Obsolete.)

strConnectsToPin

Name of the pin to which this pin connects. (Obsolete.)

nMediaTypes

Number of media types supported by this pin.

lpMediaType

Pointer to an array of REGPINTYPES structures, of size nMediaTypes.

Remarks

This structure is used in the IFilterMapper2 interface for filter registration. If you use this stucture, set the dwVersion member of the REGFILTER2 structure to 1. If you need to register a medium or pin category for the pin, use the REGFILTERPINS2 structure instead. In that case, set the REGFILTER2 structure's dwVersion member to 2.

The equivalent AMOVIESETUP_PIN type is used in class factory templates (CFactoryTemplate).

The strName, clsConnectsToFilter, and strConnectsToPin members are obsolete. Their values are not added to the registry.

For more information, see How to Register DirectShow Filters.

See Also

  • DirectShow Structures


REGFILTERPINS2 Structure

The REGFILTERPINS2 structure contains information for registering a filter through the IFilterMapper2 interface.

Syntax

typedef struct {
    DWORD dwFlags;
    UINT cInstances;
    UINT nMediaTypes;
    [size_is(nMediaTypes)] const REGPINTYPES *lpMediaType;
    UINT nMediums;
    [size_is(nMediums)] const REGPINMEDIUM *lpMedium;
    const CLSID *clsPinCategory;
} REGFILTERPINS2;

Members

dwFlags

Bitwise combination of zero or more REG_PINFLAG flags.

cInstances

Number of instances of this pin.

nMediaTypes

Number of media types supported by this pin.

lpMediaType

Pointer to an array of REGPINTYPES structures, of size nMediaTypes.

nMediums

Number of mediums. Can be zero.

lpMedium

Pointer to an array of REGPINMEDIUM structures, of size nMediums.

clsPinCategory

Optional pin category, from the Pin Property Set.

Remarks

If you use this stucture, set the dwVersion member of the REGFILTER2 structure to 2.

See Also

  • DirectShow Structures


REGPINMEDIUM Structure

The REGPINMEDIUM structure describes a pin medium for registration through the IFilterMapper2 interface.

Syntax

typedef struct {
    CLSID clsMedium;
    DWORD dw1;
    DWORD dw2;
} REGPINMEDIUM;

Members

clsMedium

GUID that specifies the medium.

dw1

Variable of type DWORD that specifies the instance of this medium. This is necessary when two identical devices are present on the host system.

dw2

Not used.

Remarks

A medium identifies a hardware path of communication that exists within a single hardware device or between two devices. Register mediums if your filter is built on kernel streaming pins and needs to connect to other such filters.

This structure is equivalent to the KSPIN_MEDIUM structure, which is used by kernel streaming drivers. For more information, see the Microsoft® Windows® Driver Development Kit (DDK).

See Also

  • KSMULTIPLE_ITEM
  • DirectShow Structures


REGPINTYPES Structure

The REGPINTYPES structure contains media type information for registering a filter.

Syntax

typedef struct
{
    const CLSID *clsMajorType;
    const CLSID *clsMinorType;
} REGPINTYPES;

typedef REGPINTYPES AMOVIESETUP_MEDIATYPE,
    * PAMOVIESETUP_MEDIATYPE,
    * LPAMOVIESETUP_MEDIATYPE;

Members

clsMajorType

Major type GUID of the media type.

clsMinorType

Sub type GUID of the media type. Can be MEDIASUBTYPE_NULL.

Remarks

This structure is used by the IFilterMapper2 interface to identify the media types that a pin supports. The equivalent AMOVIESETUP_MEDIATYPE type is used in class factory templates (CFactoryTemplate).

To register a range of subtypes within the same major type, use the value MEDIASUBTYPE_NULL.

For more information, see How to Register DirectShow Filters.

See Also

  • DirectShow Structures
  • Media Types


STREAM_ID_MAP Structure

The STREAM_ID_MAP structure describes an elementary stream within an MPEG-2 program stream. Used with the IEnumStreamIdMap interface methods.

Syntax

typedef struct {
    ULONG   stream_id;
    DWORD   dwMediaSampleContent;
    ULONG   ulSubstreamFilterValue;
    int     iDataOffset;
} STREAM_ID_MAP;

Members

stream_id

Specifies the ID of the PES stream.

dwMediaSampleContent

Specifies the media contents of the stream. May be one of the following values defined in axextend.idl:

Define | Value
MPEG2_PROGRAM_STREAM_MAP | 0x00000000
MPEG2_PROGRAM_ELEMENTARY_STREAM | 0x00000001
MPEG2_PROGRAM_DIRECTORY_PES_PACKET | 0x00000002
MPEG2_PROGRAM_PACK_HEADER | 0x00000003
MPEG2_PROGRAM_PES_STREAM | 0x00000004
MPEG2_PROGRAM_SYSTEM_HEADER | 0x00000005

ulSubstreamFilterValue

Specifies the substream within the elementary stream. If no substream filtering is required, use SUBSTREAM_FILTER_VAL_NONE (0x10000000).

iDataOffset

Specifies the offset in bytes for the substream. If no filtering is required, specify 0.

See Also

  • DirectShow Structures


TIMECODE Structure

The TIMECODE structure contains basic timecode frame count information.

Syntax

typedef struct tagTIMECODE {
    WORD   wFrameRate;
    WORD   wFrameFract;
    DWORD  dwFrames;
} TIMECODE;

Members

wFrameRate

Number of frames per second. Specify with one of the following values:

Value | Description
ED_FORMAT_SMPTE_30 | 30 frames per second.
ED_FORMAT_SMPTE_30DROP | 30 frames per second drop frame (actual rate 29.97 fps).
ED_FORMAT_SMPTE_25 | 25 frames per second.
ED_FORMAT_SMPTE_24 | 24 frames per second.

wFrameFract

Fractional frame. Full scale is 0x1000.

dwFrames

Timecode value as a binary framecount.

Remarks

Fractional frame can be used to indicate temporal offset into frame when timecode was actually read from an external device; for example, wFrameFract=0x7ff means the timecode value was read from the device at the end of the first video field.

See Also

  • DirectShow Structures


TIMECODE_SAMPLE Structure

The TIMECODE_SAMPLE structure contains complete timecode information.

Syntax

typedef struct tagTIMECODE_SAMPLE {
    LONGLONG  qwTick;
    TIMECODE  timecode;
    DWORD     dwUser;
    DWORD     dwFlags;
} TIMECODE_SAMPLE;

Members

qwTick

Reference time, in 100-nanosecond units.

timecode

TIMECODE structure.

dwUser

Packed SMPTE userbits.

dwFlags

Timecode flag masks. Specify one or more of the following values.

Value | Description
AM_TIMECODE_FLAG_FCM | Frame code mode; 0 = nondrop; 1 = drop.
AM_TIMECODE_FLAG_CF | Color frame flag.
AM_TIMECODE_FLAG_FIELD | Field flag.
AM_TIMECODE_FLAG_DF | Drop frame flag (from flags in actual timecode on external media).
AM_TIMECODE_COLORFRAME | Specifies frame in color sequence.
AM_TIMECODE_COLORSEQUENCE | Duration in frames of complete sequence.
AM_TIMECODE_FILMSEQUENCE_TYPE | One of the FILM_SEQUENCE_XXX defines.
ED_DEVCAP_TIMECODE_READ | Read SMPTE timecode; applies to DV camcorders.
ED_DEVCAP_ATN_READ | Read the absolute track number (ATN); applies to DV camcorders. This constant is defined in the header file Xprtdefs.h.
ED_DEVCAP_RTC_READ | Read the relative time counter (RTC); applies to MPEG camcorders. This constant is defined in the header file Xprtdefs.h.

Remarks

The upper 16 bits in dwFlags are reserved for future use; set to zero.

See Also

  • IAMTimecodeReader::GetTimecode
  • DirectShow Structures


TRUECOLORINFO Structure

The TRUECOLORINFO structure contains color palette and bitmask information for a video image.

Syntax

typedef struct tag_TRUECOLORINFO {
    DWORD dwBitMasks[iMASK_COLORS];
    RGBQUAD bmiColors[iPALETTE_COLORS];
} TRUECOLORINFO;

Members

dwBitMasks

Array of color masks (one per color element).

bmiColors

Array of palette colors.

Remarks

This structure is not used for some RGB formats. For more information about which fields are valid under different circumstances, see the Platform SDK documentation for BITMAPINFO.

See Also

  • DirectShow Structures
  • VIDEOINFO


VIDEO_STREAM_CONFIG_CAPS Structure

The VIDEO_STREAM_CONFIG_CAPS structure describes a range of video formats. Video compression and video capture filters use this structure to describe what formats they can produce.

Syntax

typedef struct _VIDEO_STREAM_CONFIG_CAPS {
    GUID guid;
    ULONG VideoStandard;
    SIZE InputSize;
    SIZE MinCroppingSize;
    SIZE MaxCroppingSize;
    int CropGranularityX;
    int CropGranularityY;
    int CropAlignX;
    int CropAlignY;
    SIZE MinOutputSize;
    SIZE MaxOutputSize;
    int OutputGranularityX;
    int OutputGranularityY;
    int StretchTapsX;
    int StretchTapsY;
    int ShrinkTapsX;
    int ShrinkTapsY;
    LONGLONG MinFrameInterval;
    LONGLONG MaxFrameInterval;
    LONG MinBitsPerSecond;
    LONG MaxBitsPerSecond;
} VIDEO_STREAM_CONFIG_CAPS;

Members

guid

GUID that identifies the format type. For example, FORMAT_VideoInfo or FORMAT_VideoInfo2. For more information, see the formattype member of the AM_MEDIA_TYPE structure.

VideoStandard

The analog video standard supported. The value is a bitwise combination of flags from the AnalogVideoStandard enumeration type, or zero.

InputSize

Native size of the incoming video signal. For a compressor, the size is taken from the input pin. For a capture filter, the size is the largest signal the filter can digitize with every pixel remaining unique.

MinCroppingSize

Smallest source rectangle allowed. The source rectangle is defined in the rcSource member of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure.

MaxCroppingSize

Largest source rectangle allowed.

CropGranularityX

Horizontal granularity of the source rectangle. This value specifies the increments that are valid between MinCroppingSize and MaxCroppingSize.

CropGranularityY

Vertical granularity of the source rectangle. This value specifies the increments that are valid between MinCroppingSize and MaxCroppingSize.

CropAlignX

Required horizontal alignment of the source rectangle.

CropAlignY

Required vertical alignment of the source rectangle.

MinOutputSize

Minimum output size.

MaxOutputSize

Maximum output size.

OutputGranularityX

Granularity of the output width. This value specifies the increments that are valid between MinOutputSize and MaxOutputSize.

OutputGranularityY

Granularity of output height. This value specifies the increments that are valid between MinOutputSize and MaxOutputSize.

StretchTapsX

Indicates how well the filter can stretch the image horizontally.

StretchTapsY

Indicates how well the filter can stretch the image vertically.

ShrinkTapsX

Indicates how well the filter can shrink the image horizontally.

ShrinkTapsY

Indicates how well the filter can shrink the image vertically.

The previous four structure members use the following values:

Value | Description
0 | Does not support stretching/shrinking.
1 | Uses pixel doubling (stretching) or eliminates pixels (shrinking)
2 | Uses interpolation (2 taps)
3 and higher | Uses interpolation (>2 taps)

MinFrameInterval

The minimum frame duration, in 100-nanosecond units. This value applies only to capture filters.

MaxFrameInterval

The maximum frame duration, in 100-nanosecond units. This value applies only to capture filters.

MinBitsPerSecond

Minimum data rate this pin can produce.

MaxBitsPerSecond

Maximum data rate this pin can produce.

Remarks

The IAMStreamConfig::GetStreamCaps method returns this structure. An application can use this information to modify the output format on a video compression filter or video capture filter.

For example, assume that filter returns the following values for the source rectangle:

  • MinCroppingSize = (160, 120)
  • MaxCroppingSize = (320, 240)
  • CropGranularityX = 4
  • CropGranularityY = 8
  • CropAlignX = 2
  • CropAlignY = 4

These numbers define the set of rectangles that are valid for the rcSource member of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure. In this example, the minimum source rectangle is 160 pixels wide x 120 pixels high. The width can be increased in steps of 4 pixels, to a maximum of 320. The height can be increased in steps of 8 pixels, to a maximum of 240. In other words, the valid widths are 160, 164, 168 ... 320; and the valid heights are 120, 128, 136 ... 240.

The CropAlignX and CropAlignY members define where the top-left corner of the source rectangle can sit. For example, the following rectangles are valid, given the previous values:

  • (0, 0, 160, 120)
  • (2, 0, 162, 120)
  • (2, 8, 162, 128)

In a similar way, the MinOutputSize, MaxOutputSize, OutputGranularityX, and OutputGranularityY members define what values are supported for the biWidth and biHeight members of the BITMAPINFOHEADER structure.

For capture filters, the MinFrameInterval and MaxFrameInterval members define the minimum and maximum duration of each frame, as given in the AvgTimePerFrame member of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure. The filter may not support every frame rate that falls between these two values. The IAMStreamConfig::SetFormat method will set the frame rate to the closest value that the filter supports. If SetFormat succeeds, call IAMStreamConfig::GetFormat to determine the actual frame rate.

See Also

  • DirectShow Structures


VIDEOINFO Structure

The VIDEOINFO structure describes the bitmap and color information for a video image.

Syntax

typedef struct tagVIDEOINFO {
    RECT              rcSource,
    RECT              rcTarget,
    DWORD             dwBitRate,
    DWORD             dwBitErrorRate,
    REFERENCE_TIME    AvgTimePerFrame;
    BITMAPINFOHEADER  bmiHeader;
    union {
        RGBQUAD         bmiColors[iPALETTE_COLORS];
        DWORD           dwBitMasks[iMASK_COLORS];
        TRUECOLORINFO   TrueColorInfo;
    };
} VIDEOINFO;

Members

rcSource

Portion of the input video to use.

rcTarget

Where the video should be displayed.

dwBitRate

Approximate data rate in bits per second.

dwBitErrorRate

Bit error rate for this stream.

AvgTimePerFrame

The desired average time per frame, in 100-nanosecond units. For more information, see the Remarks section for the VIDEOINFOHEADER structure.

bmiHeader

BITMAPINFOHEADER structure that contains color and dimension information for a device-independent bitmap.

bmiColors

Array of Win32 RGBQUAD structures that specifies the video's color palette. Each structure represents a single color, which is a combination of red, green, and blue intensities.

dwBitMasks

Array of DWORD values that specify true-color bitmasks.

TrueColorInfo

TRUECOLORINFO structure that contains both a color palette and an array of color bitmasks.

Remarks

Never use this structure unless you are sure that you will use it only to store standard RGB formats. If you store anything other than standard RGB, the variable size of the bmiHeader structure will almost certainly cause problems, and you should use the VIDEOINFOHEADER structure instead. If you find it absolutely necessary to use the VIDEOINFO structure, do not access the TrueColorInfo, dwBitMasks, or bmiColors members directly. Instead, use the TRUECOLOR, COLORS, and BITMASKS macros to return the pointers to the color information. Which of these members is valid depends on the contents of the BITMAPINFOHEADER structure.

The first five data members are equivalent to a VIDEOINFOHEADER structure. They are expanded in full simply to reduce the amount of dereferencing needed when dealing with a pointer to a VIDEOINFO structure.

For information about using the rcSource and rcTarget members, see Source and Target Rectangles in Video Renderers.

See Also

  • DirectShow Structures


VIDEOINFOHEADER Structure

The VIDEOINFOHEADER structure describes the bitmap and color information for a video image.

Syntax

typedef struct tagVIDEOINFOHEADER {
    RECT                rcSource,
    RECT                rcTarget;
    DWORD               dwBitRate;
    DWORD               dwBitErrorRate;
    REFERENCE_TIME      AvgTimePerFrame;
    BITMAPINFOHEADER    bmiHeader;
} VIDEOINFOHEADER;

Members

rcSource

RECT structure that specifies the source video window. This structure can be a clipping rectangle, to select a portion of the source video stream.

rcTarget

RECT structure that specifies the destination video window.

dwBitRate

Approximate data rate of the video stream, in bits per second.

dwBitErrorRate

Data error rate, in bit errors per second.

AvgTimePerFrame

The desired average display time of the video frames, in 100-nanosecond units. The actual time per frame may be longer. See Remarks.

bmiHeader

BITMAPINFOHEADER structure that contains color and dimension information for the video image bitmap. If the format block contains a color table or color masks, they immediately follow the bmiHeader member. You can get the first color entry by casting the address of member to a BITMAPINFO pointer.

Remarks

For information about using the rcSource and rcTarget members, see Source and Target Rectangles in Video Renderers.

Frame Rates

The value of AvgTimePerFrame is usually set by the source filter, which obtains the value from the media stream. This value can be used to calculate the authored frame rate, which is the intended frame rate for the video to be rendered. During playback, the system may not be able to render the stream at the authored rate, so the actual frame rate may be less. This can happen if the machine's resources become over-committed. Also, the monitor's refresh rate can interfere with the playback rate of the video. For example, if the intended rate is 60,000/1001 (NTSC TV) and the monitor's refresh rate is 60Hz, the intended rate and the actual rate will never match. To retrieve the actual frame rate achieved during playback, use the IQualProp::get_AvgFrameRate method on the video renderer.

During playback, applications can retrieve the authored frame rate as follows:

  • If the old Video Renderer filter is rendering, call the IBasicVideo::get_AvgTimePerFrame method.
  • If the Video Mixing Renderer (VMR) is rendering, call IPin::ConnectionMediaType on the input pin and examine the format block. The VMR supports multiple input streams, and they are not required to have the same frame rates.

To obtain the authored frame rate of a video file without rendering it, use IMediaDet::get_FrameRate.

See Also

  • DirectShow Structures


VIDEOINFOHEADER2 Structure

The VIDEOINFOHEADER2 structure describes the bitmap and color information for a video image, including interlace, copy protection, and pixel aspect ratio information.

Syntax

typedef struct tagVIDEOINFOHEADER2 {
    RECT                rcSource;
    RECT                rcTarget;
    DWORD               dwBitRate;
    DWORD               dwBitErrorRate;
    REFERENCE_TIME      AvgTimePerFrame;
    DWORD               dwInterlaceFlags;
    DWORD               dwCopyProtectFlags;
    DWORD               dwPictAspectRatioX;
    DWORD               dwPictAspectRatioY;
    union {
        DWORD           dwControlFlags;
        DWORD           dwReserved1;
    };
    DWORD               dwReserved2;
    BITMAPINFOHEADER    bmiHeader;
} VIDEOINFOHEADER2;

Members

rcSource

RECT structure that specifies what part of the source stream should be used to fill the destination buffer. Renderers can use this field to ask the decoders to stretch or clip. For more information, see Source and Target Rectangles in Video Renderers

rcTarget

RECT structure that specifies that specifies what part of the destination buffer should be used

dwBitRate

Approximate data rate of the video stream, in bits per second.

dwBitErrorRate

Data error rate of the video stream, in bits per second.

AvgTimePerFrame

The video frame's average display time, in 100-nanosecond units. For more information, see the Remarks section for the VIDEOINFOHEADER structure.

dwInterlaceFlags

Flags that specify how the video is interlaced. This member is a bit-wise combination of zero or more of the following flags. The flags in Group 2 are mutually exclusive, and so are the flags in Group 3. (The flags in Group 2 are not recommended.) The flags in Group 1 may be combined with each other, and with one flag each from Group 2 and Group 3. See the table at the bottom of this page for more information about flag combinations.

Flag | Description
Group 1 |
AMINTERLACE_IsInterlaced | The stream is interlaced. If this flag is absent, the video is progressive and the other bits are irrelevant.
AMINTERLACE_1FieldPerSample | Each media sample contains one field. If this flag is absent, each media sample contains two fields.
AMINTERLACE_Field1First | Field 1 is first. If this flag is absent, field 2 is first. (The top field in PAL is field 1, and the top field in NTSC is field 2.)
Group 2 |
AMINTERLACE_FieldPatField1Only | The stream never contains a field 2.
AMINTERLACE_FieldPatField2Only | The stream never contains a field 1.
AMINTERLACE_FieldPatBothRegular | There is one field 2 for every field 1.
AMINTERLACE_FieldPatBothIrregular | The stream contains an irregular pattern of field 1 and field 2.
Group 3 |
AMINTERLACE_DisplayModeBobOnly | Bob display mode only.
AMINTERLACE_DisplayModeWeaveOnly | Weave display mode only.
AMINTERLACE_DisplayModeBobOrWeave | Either bob or weave mode.

Set undefined flags to zero, or the connection will be rejected.

dwCopyProtectFlags

Flag set with the AMCOPYPROTECT_RestrictDuplication value (0x00000001) to indicate that the duplication of the stream should be restricted. If undefined, specify zero or else the connection will be rejected.

dwPictAspectRatioX

The X dimension of picture aspect ratio. For example, 16 for a 16-inch x 9-inch display.

dwPictAspectRatioY

The Y dimension of picture aspect ratio. For example, 9 for a 16-inch x 9-inch display.

dwControlFlags, dwReserved1

This field was originally named dwReserved, and was required to be zero. The field was renamed to dwControlFlags, and must now contain a bitwise OR of zero or more of the following flags:

AMCONTROL_USED | 0x00000001
AMCONTROL_PAD_TO_4x3 | 0x00000002
AMCONTROL_PAD_TO_16x9 | 0x00000004

These flags are used by decoders to determine the aspect ratio of the output rectangle. The AMCONTROL_USED flag is used to test whether these flags are supported. A source filter should set the AMCONTROL_USED flag and see if QueryAccept succeeds on the downstream pin. If it is rejected, then the AMCONTROL flags cannot be used, and the field must be set to zero. The AMCONTROL_PAD_TO_4x3 flag indicates that the image should be padded and displayed in a 4x3 area. The AMCONTROL_PAD_TO_16x9 flag indicates that the image should be padded and displayed in a 16x9 area. For more information on the use of these flags, see MPEG Decoder Preprocessing Transformations.

dwReserved2

Reserved for future use. Must be zero.

bmiHeader

BITMAPINFOHEADER structure that contains color and dimension information for the video image bitmap.

Remarks

The dwInterlaceFlags field indicates whether the video is interlaced, and if so, the format of the fields within the media samples. The following table shows the valid interlace modes for the Overlay Mixer and Video Mixing Renderer filters.

Display Mode | Interlace Flags | Description
Progressive frames | None | The video stream is not interlaced.
Non-interleaved bob | AMINTERLACE_IsInterlaced | AMINTERLACE_1FieldPerSample | AMINTERLACE_DisplayModeBobOnly | The entire video stream is interlaced, and each media sample contains a single video field.
Interleaved bob | AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOnly | The entire video stream is interlaced. Each media sample contains two video fields. Flags on the media sample indicate which field to display first.
Weave | AMINTERLACE_IsInterlaced | AMINTERLACE_FieldPatBothRegular | AMINTERLACE_DisplayModeWeaveOnly | The video stream is interlaced, and each sample contains two video fields. The fields should not be deinterlaced.
Bob or weave | AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOrWeave | The video stream varies between progressive and interlaced content. Each media sample contains either a progressive frame or two video fields. Flags on the media sample indicate the correct way to display the contents.

If the video is interlaced, the media samples may carry flags that describe the contents of the sample (such as field 1 or field 2), along with the rendering requirements. These are specified by setting the dwTypeSpecificFlags member of each media sample's AM_SAMPLE2_PROPERTIES structure. The following table shows the valid media sample flags for each of the display modes listed in the previous table.

Display Mode |  | Media Sample Properties
Progressive frames |  | None
Non-interleaved bob |  | AM_VIDEO_FLAG_FIELD1 or AM_VIDEO_FLAG_FIELD2
Interleaved bob | Field 1 first | AM_VIDEO_FLAG_FIELD1FIRST
 | Field 2 First | None
Weave |  | AM_VIDEO_FLAG_WEAVE
Bob or weave | Bob, field 1 first | AM_VIDEO_FLAG_FIELD1FIRST
 | Bob, field 2 first | None
 | Weave | AM_VIDEO_FLAG_WEAVE
Use the bit mask AMINTERLACE_FieldPatternMask to check the field pattern flags in dwInterlaceFlags:

switch (dwInterlaceFlags & AMINTERLACE_FieldPatternMask)
{
case AMINTERLACE_FieldPatField1Only:
    // Stream never contains a Field 2.

case AMINTERLACE_FieldPatField2Only:
    // Stream never contains a Field 1.

case AMINTERLACE_FieldPatBothRegular:
    // One Field 2 for every Field 1.

case AMINTERLACE_FieldPatBothIrregular:
    // Random pattern of Field 1 and Field 2.
}

Use the bit mask AMINTERLACE_DisplayModeMask to check the display mode flags in dwInterlaceFlags:

switch (dwInterlaceFlags & AMINTERLACE_DisplayModeMask)
{
case AMINTERLACE_DisplayModeBobOnly:
    // Bob display mode only.

case AMINTERLACE_DisplayModeWeaveOnly:
    // Weave display mode only.

case AMINTERLACE_DisplayModeBobOrWeave:
    // Either bob or weave mode.
}

Requirements

Include Dvdmedia.h.


VMR9AllocationInfo

The VMR9AllocationInfo structure describes the Direct3D surfaces that a VMR-9 Allocator-Presenter object should allocate.

Syntax

typedef struct VMR9AllocationInfo{
  DWORD  dwFlags;
  DWORD  dwWidth;
  DWORD  dwHeight;
  D3DFORMAT  Format;
  D3DPOOL  Pool;
  DWORD  MinBuffers;
  SIZE  szAspectRatio;
  SIZE  szNativeSize;
};

Members

dwFlags

Specifies a bitwise combination of flags from the VMR9SurfaceAllocationFlags enumeration type.

dwWidth

Specifies the width of the surfaces.

dwHeight

Specifies the height of the surfaces.

Format

Specifies the surface format, as a D3DFORMAT type. The value 0 indicates that the surface format should be compatible with the display.

Pool

Specifies the Direct3D memory pool to use for the surfaces, as a D3DPOOL type.

MinBuffers

Specifies the minimum number of buffers to create.

szAspectRatio

Specifies the video aspect ratio as a SIZE structure.

szNativeSize

Specifies the native video size as a SIZE structure.

See Also

  • DirectShow Structures
  • IVMRSurfaceAllocator9::InitializeDevice
  • IVMRSurfaceAllocatorNotify9::AllocateSurfaceHelper


VMR9AlphaBitmap

The VMR9AlphaBitmap structure is used in the VMR-9's IVMRMixerBitmap9 methods when the application is providing a static alpha-blended bitmap to be displayed on the composited video frame.

Syntax

typedef struct VMR9AlphaBitmap{
  DWORD              dwFlags;
  HDC                hdc;
  IDirect3DSurface9* pDDS;
  RECT               rSrc;
  VMR9NormalizedRect rDest;
  FLOAT              fAlpha;
  COLORREF           clrSrcKey;
  DWORD              dwFilterMode;
};

Members

dwFlags

Bitwise combination of flags from the VMR9AlphaBitmapFlags enumeration type.

hdc

Specifies the handle to the device context for the bitmap. Specify NULL if the bitmap is located in a Direct3D surface.

pDDS

Direct3D surface to copy.

rSrc

Specifies the source rectangle in either the GDI device context or the DirectDraw surface.

rDest

Specifies the destination rectangle in composition space.

fAlpha

Specifies the alpha blending value; must be a value from 0.0 to 1.0 (inclusive).

clrSrcKey

Specifies the source color key.

dwFilterMode

Specifies flags from the VMRMixerPrefs enumeration, which control how the VMR mixes the image. The MixerPref_PointFiltering flag is particularly useful for images that contain text and do not need to be stretched prior to mixing.

See Also

  • DirectShow Structures


VMR9DeinterlaceCaps Structure

The VMR9DeinterlaceCaps structure describes the capabilities of a deinterlacing mode.

Syntax

typedef struct _VMR9DeinterlaceCaps {
    DWORD               dwSize;
    DWORD               dwNumPreviousOutputFrames;
    DWORD               dwNumForwardRefSamples;
    DWORD               dwNumBackwardRefSamples;
    VMRDeinterlaceTech  DeinterlaceTechnology;
} VMR9DeinterlaceCaps;

Members

dwSize

Size of the structure, in bytes.

dwNumPreviousOutputFrames

Number of previously de-interlaced frames that must be fed back to the hardware to deinterlace the next field. (Used by recursive deinterlacing algorithms.)

dwNumForwardRefSamples

Number of future samples needed to deinterlace the current field.

dwNumBackwardRefSamples

Number of past samples needed to deinterlace the current field.

DeinterlaceTechnology

Bitwise combination of flags from the VMR9DeinterlaceTech enumeration type. These flags are used to describe the deinterlacing algorithm.

See Also

  • DirectShow Structures


VMR9Frequency Structure

The VMR9Frequency structure describes the frequency of a video stream. Frequencies are described as ratios. For example, the NTSC frame rate of 29.97 fps is expressed as 30,000:1001.

Syntax

typedef struct _VMR9Frequency {
    DWORD dwNumerator;
    DWORD dwDenominator;
} VMR9Frequency;

Members

dwNumerator

Numerator of the frequency ratio.

dwDenominator

Denominator of the frequency ratio.

See Also

  • DirectShow Structures


VMR9MonitorInfo

The VMR9MonitorInfo structure is used with the VMR-9 in the IVMRMonitorConfig9::GetAvailableMonitors method to set and retrieve information about monitors on the system.

Syntax

typedef struct VMR9MonitorInfo{
  UINT  uDevID;
  RECT  rcMonitor;
  HMONITOR  hMon;
  DWORD  dwFlags;
  wchar_t  szDevice[VMR9DEVICENAMELEN];
  wchar_t  szDescription[VMR9DEVICEDESCRIPTIONLEN]
  LARGE_INTEGER  liDriverVersion;
  DWORD  dwVendorId;
  DWORD  dwDeviceId;
  DWORD  dwSubSysId;
  DWORD  dwRevision;
};

Members

uDevID

Integer index that specifies the monitor device.

rcMonitor

Specifies the monitor's rectangle.

hMon

Handle to the monitor.

dwFlags

Described in MONITORINFOEX, currently only MONITORINFOF_PRIMARY.

szDevice

Null-terminated string containing the device name.

szDescription

Null-terminated string containing a description of the device.

liDriverVersion

Specifies the driver version.

dwVendorId

Specifies the vendor.

dwDeviceId

Specifies the device ID.

dwSubSysId

Specifies the device subsystem.

dwRevision

Specifies the revision number.

Remarks

This structure is used to configure monitors on multi-monitor systems.

See Also

  • DirectShow Structures


VMR9NormalizedRect

The VMR9NormalizedRect structure is used with the VMR-9 filter in mixing operations to specify or retrieve the location of a video rectangle in composition space.

Syntax

typedef struct VMR9NormalizedRect{
  float  left;
  float  top;
  float  right;
  float  bottom;
};

Members

left

Specifies left.

top

Specifies top.

right

Specifies right.

bottom

Specifies bottom.

Remarks

This structure is used in methods involving "composition space," which refers to the visible video rectangle, as well as the "offscreen" space necessary to contain rectangles from secondary streams. See Using the Video Mixing Renderer for more information.

See Also

  • DirectShow Structures


VMR9PresentationInfo

The VMR9PresentationInfo structure is used with the VMR-9 in the IVMRImagePresenter9::PresentImage method.

Syntax

typedef struct VMR9PresentationInfo{
  DWORD  dwFlags;
  IDirect3DSurface9*  lpSurf;
  REFERENCE_TIME  rtStart;
  REFERENCE_TIME  rtEnd;
  SIZE  szAspectRatio;
  RECT  rcSrc;
  RECT  rcDst;
  DWORD  dwReserved1;
  DWORD  dwReserved2;
};

Members

dwFlags

Contains a bitwise combintation of flags from the VMR9PresentationFlags enumeration type. These flags describe the status of the video sample with respect to its presentation time.

lpSurf

Pointer to the DirectDraw surface that contains the video frame.

rtStart

Specifies the start time for the video frame.

rtEnd

Specifies the end time for the video frame

szAspectRatio

Specifies the aspect ratio of the video, as a SIZE structure.

rcSrc

Specifies the source rectangle.

rcDst

Specifies the destination rectangle.

dwReserved1

Reserved.

dwReserved2

Reserved.

See Also

  • DirectShow Structures


VMR9ProcAmpControl Structure

The VMR9ProcAmpControl structure specifies the image adjustments to be performed on a video stream. This structure is used with the Video Mixing Renderer Filter 9 (VMR-9).

Syntax

typedef struct _VMR9ProcAmpControl
{
    DWORD  dwSize;
    DWORD  dwFlags;
    float  Contrast;
    float  Brightness;
    float  Hue;
    float  Saturation;
} VMR9ProcAmpControl;

Members

dwSize

Size of the structure, in bytes.

dwFlags

Bitwise combination of flags from the VMR9ProcAmpControlFlags enumeration, indicating which properties the driver supports.

Contrast

Specifies the image contrast. Contrast alters the relative light-to-dark values in a picture. Functionally it maps the range of input values to a smaller or larger range of output values.

Brightness

Specifies the image brightness. Brightness, also called black-level setup, specifies the viewing black level. Functionally, it adds or subtracts the same number of quantizing steps (bits) from all the luminance words in a picture.

Hue

Specifies the image hue. Perceptually, hue corresponds approximately to "color." Functionally, hue is a phase relationship of the chrominance components. It is specified in degrees, with a nominal valid range from –180 to 180 degrees and a default value of 0.

Saturation

Specifies the image saturation. Saturation alters the color intensity of the image. Functionally it is similar to contrast, but operates on the chroma components of the image.

Remarks

The valid range of values for each property depends on the graphics device driver. Call the IVMRMixerControl9::GetProcAmpControlRange method to get the range for each property.

See Also

  • DirectShow Structures


VMR9ProcAmpControlRange Structure

The VMR9ProcAmpControlRange structure specifies the valid range for an image adjustment property. The range depends on the graphics device driver. This structure is used with the Video Mixing Renderer 9 Filter (VMR-9).

Syntax

typedef struct _VMR9ProcAmpControlRange
{
    DWORD                    dwSize;
    VMR9ProcAmpControlFlags  dwProperty;
    float                    MinValue;
    float                    MaxValue;
    float                    DefaultValue;
    float                    StepSize;
} VMR9ProcAmpControlRange;

Members

dwSize

Size of the structure, in bytes. The caller must set this field.

dwFlags

Specifies the image adjustment property to query, as a member of the VMR9ProcAmpControlFlags enumeration. The caller should set this field.

MaxValue

Specifies the maximum value for the property. The driver sets this field.

MinValue

Specifies the minimum value for the property. The driver sets this field.

DefaultValue

Specifies the default value for the property. The default value is the value that does not alter the image. The driver sets this field.

StepSize

Specifies the valid increments from MinValue to MaxValue. The driver sets this field.

See Also

  • DirectShow Structures
  • IVMRMixerControl9::GetProcAmpControlRange


VMR9VideoDesc Structure

The VMR9VideoDesc structure describes a video stream to be deinterlaced.

Syntax

typedef struct _VMR9VideoDesc {
    DWORD             dwSize;
    DWORD             dwSampleWidth;
    DWORD             dwSampleHeight;
    VMR9_SampleFormat SampleFormat;
    DWORD             dwFourCC;
    VMR9Frequency     InputSampleFreq;
    VMR9Frequency     OutputFrameFreq;
} VMR9VideoDesc;

Members

dwSize

Size of the structure, in bytes.

dwSampleWidth

Width of the video to be deinterlaced, in pixels.

dwSampleHeight

Height of the video to be deinterlaced, in pixels.

SampleFormat

Specifies the interlacing format of the sample, as a member of the VMR9_SampleFormat enumeration.

dwFourCC

Specifies the FOURCC code. Valid values include NV12, YV12, YUY2, UYVY, IMC1, IMC2, IMC3 and IMC4

InputSampleFreq

VMR9Frequency structure that specifies the input frequency. For NTSC TV, the frequency would be expressed as 30,000:1001.

OutputFrameFreq

VMRFrequency structure that specifies the output frequency. For NTSC TV, the frequency would be expressed as 60,000:1001.

See Also

  • DirectShow Structures
  • Setting Deinterlace Preferences


VMR9VideoStreamInfo

The VMR9VideoStreamInfo structure describes the rendering parameters for a video compositing operation in the VRM-9 filter. This structure is used in the IVMRImageCompositor9::CompositeImage method.

Syntax

typedef struct VMR9VideoStreamInfo{
    IDirect3DSurface9*  pddsVideoSurface;
    DWORD               dwWidth;
    DWORD               dwHeight;
    DWORD               dwStrmID;
    FLOAT               fAlpha;
    VMR9NormalizedRect  rNormal;
    REFERENCE_TIME      rtStart;
    REFERENCE_TIME      rtEnd;
    VMR9_SampleFormat   SampleFormat;
};

Members

pddsVideoSurface

Specifies the Direct3D surface that contains the video to be composited.

dwWidth

Specifies the width of the video rectangle.

dwHeight

Specifies the height of the video rectangle.

dwStrmID

Specifies the input stream. This value corresponds to the input pin.

fAlpha

Specifies the alpha value for this stream. (Not per-pixel alpha.)

rNormal

Specifies the position of the image in composition space, as a VMR9NormalizedRect structure.

rtStart

Specifies the start time of the video frame.

rtEnd

Specifies the end time of the video frame.

SampleFormat

Specifies the video interlacing format, as a member of the VMR9_SampleFormat enumeration type.

See Also

  • DirectShow Structures


VMRALLOCATIONINFO Structure

This topic applies to Windows XP only.

The VMRALLOCATIONINFO structure is used in the VMR-7 filter's IVMRSurfaceAllocator::AllocateSurface method.

Syntax

typedef struct tagVMRALLOCATIONINFO {
    DWORD dwFlags;
    LPBITMAPINFOHEADER lpHdr;
    LPDDPIXELFORMAT lpPixFmt;
    SIZE szAspectRatio;
    DWORD dwMinBuffers;
    DWORD dwMaxBuffers;
    DWORD dwInterlaceFlags;
    SIZE szNativeSize;
} VMRALLOCATIONINFO;

Members

dwFlags

Double word containing a bitwise OR of flags from the VMRSurfaceAllocationFlags enumeration.

lpHdr

Pointer to the BITMAPINFOHEADER structure associated with the surface.

lpPixFmt

Pointer to the DDPIXELFORMAT structure associated with the surface.

szAspectRatio

A SIZE structure that specifies the aspect ratio of the new surface.

dwMinBuffers

Specifies the minimum number of buffers to create for this surface.

dwMaxBuffers

Specifies the maximum number of buffers to create for this surface.

dwInterlaceFlags

These are the same flags that are used in the VIDEOINFOHEADER2 structure.

szNativeSize

Specifies the size of the native video rectangle.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Structures


VMRALPHABITMAP Structure

This topic applies to Windows XP only.

The VMRALPHABITMAP structure is used in the VMR-7 filter's IVMRMixerBitmap methods when the application is providing a static alpha-blended bitmap to be displayed on the composited video frame.

Syntax

typedef struct _VMRALPHABITMAP {
    DWORD dwFlags;
    HDC hdc;
    LPDIRECTDRAWSURFACE7 pDDS;
    RECT rSrc;
    NORMALIZEDRECT rDest;
    FLOAT fAlpha;
    COLORREF clrSrcKey;
} VMRALPHABITMAP;

typedef struct _VMRALPHABITMAP *PVMRALPHABITMAP;

Members

dwFlags

Flags that instruct the mixer where to find the bitmap. The following values are defined.

Value | Description
VMRBITMAP_DISABLE (0x00000001) | Disable the bitmap for now.
VMRBITMAP_HDC (0x00000002) | Obtain the bitmap from the HDC.
VMRBITMAP_ENTIREDDS (0x00000004) | Take the entire DirectDraw surface. When this flag is specified, rSrc is ignored.
VMRBITMAP_SRCCOLORKEY (0x00000008) | The clrSrcKey value is valid and should be used when blending.
VMRBITMAP_SRCRECT (0x00000010) | Indicates that the rSrc rectangle is valid and specifies a sub-rectangle of the original app image to be blended. Use of this parameter enables "Image Strips." This flag is only valid on UpdateAlphaBitmapParameters. When the VMRALPHABITMAP struct is specified in SetAlphaBitmap, rSrc must refer to the entire bitmap.

hdc

Specifies the handle to the device context for the bitmap. Specify NULL if the bitmap is located in a DirectDraw surface.

pDDS

Pointer to a DirectDraw surface that contains the bitmap. Specify NULL if the bitmap is to be obtained from a GDI device context.

rSrc

Specifies the source rectangle in either the GDI device context or the DirectDraw surface.

rDest

Specifies the destination rectangle in composition space.

fAlpha

Specifies the alpha blending value; must be a value from 0.0 to 1.0 (inclusive).

clrSrcKey

Specifies the source color key.

Requirements

Requires Microsoft Windows XP.

See Also

  • DirectShow Structures


VMRDeinterlaceCaps Structure

This topic applies to Windows XP Service Pack 1 only.

The VMRDeinterlaceCaps structure describes the capabilities of a deinterlacing mode.

Syntax

typedef struct _VMRDeinterlaceCaps {
    DWORD               dwSize;
    DWORD               dwNumPreviousOutputFrames;
    DWORD               dwNumForwardRefSamples;
    DWORD               dwNumBackwardRefSamples;
    VMRDeinterlaceTech  DeinterlaceTechnology;
} VMRDeinterlaceCaps;

Members

dwSize

Size of the structure, in bytes.

dwNumPreviousOutputFrames

Number of previously de-interlaced frames that must be fed back to the hardware to deinterlace the next field. (Used by recursive deinterlacing algorithms.)

dwNumForwardRefSamples

Number of future samples needed to deinterlace the current field.

dwNumBackwardRefSamples

Number of past samples needed to deinterlace the current field.

DeinterlaceTechnology

Bitwise combination of flags from the VMRDeinterlaceTech enumeration type. These flags are used to describe the deinterlacing algorithm.

Requirements

Requires Microsoft® Windows® XP Service Pack 1.

See Also

  • DirectShow Structures
  • IVMRDeinterlaceControl Interface


VMRFrequency Structure

This topic applies to Windows XP Service Pack 1 only.

The VMRFrequency structure describes the frequency of a video stream. Frequencies are described as ratios. For example, the NTSC frame rate of 29.97 fps is expressed as 30,000:1001.

Syntax

typedef struct _VMRFrequency {
    DWORD dwNumerator;
    DWORD dwDenominator;
} VMRFrequency;

Members

dwNumerator

Numerator of the frequency ratio.

dwDenominator

Denominator of the frequency ratio.

Requirements

Requires Microsoft® Windows® XP Service Pack 1.

See Also

  • DirectShow Structures


VMRGUID Structure

The VMRGUID structure is a member of the VMRMONITORINFO structure and is used to identify a monitor on the system (VMR-7 only).

Syntax

typedef struct tagVMRGUID {
    GUID *pGUID;
    GUID GUID;
}  VMRGUID;

Members

pGUID

Pointer to the GUID member of the structure. pGUID is NULL if the monitor is the default DirectDraw device.

GUID

Specifies the GUID for the monitor.

Remarks

In DirectX 9.0 and later, the monitor is identified by an integer index, not by a GUID.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Structures


VMRMONITORINFO Structure

This topic applies to Windows XP only.

The VMRMONITORINFO structure is used in the IVMRMonitorConfig::GetAvailableMonitors method to set and retrieve information about monitors on the system (VMR-7 only).

Syntax

typedef struct tagVMRMONITORINFO {
    VMRGUID guid;
    RECT rcMonitor;
    HMONITOR hMon;
    DWORD dwFlags;
    wchar_t szDevice[VMRDEVICENAMELEN];
    wchar_t szDescription[VMRDEVICEDESCRIPTIONLEN];
}  VMRMONITORINFO;

Members

guid

VMRGUID structure that specifies the monitor.

rcMonitor

Specifies the monitor's rectangle.

hMon

Handle to the monitor.

dwFlags

Flags as defined for the MONITORINFOEX structure in GDI. Currently the only valid flag is MONITORINFOF_PRIMARY, which indicates the primary display monitor.

szDevice

Null-terminated string containing the device name.

szDescription

Null-terminated string containing the device description.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Structures


VMRPRESENTATIONINFO Structure

This topic applies to Windows XP only.

The VMRPRESENTATIONINFO structure is used in the IVMRImagePresenter::PresentImage method (VMR-7 only).

Syntax

typedef struct tagVMRPRESENTATIONINFO {
    DWORD dwFlags;
    LPDIRECTDRAWSURFACE7 lpSurf;
    REFERENCE_TIME rtStart;
    REFERENCE_TIME rtEnd;
    SIZE szAspectRatio;
    RECT rcSrc;
    RECT rcDst;
    DWORD dwTypeSpecificFlags;
    DWORD dwInterlaceFlags;
} VMRPRESENTATIONINFO;

Members

dwFlags

A bitwise combination of flags from the VMRPresentationFlags enumeration, which describe the status of the video sample with respect to its presentation time.

lpSurf

Pointer to the DirectDraw surface that contains the video frame to be presented.

rtStart

Specifies the start time for the current frame.

rtEnd

Specifies the end time for the current frame.

szAspectRatio

Specifies the aspect ratio of the rectangle.

rcSrc

Specifies the source rectangle.

rcDst

Specifies the destination rectangle.

dwTypeSpecificFlags

Bitwise combination of flags, as defined for the dwTypeSpecificFlags member of the AM_SAMPLE2_PROPERTIES structure.

dwInterlaceFlags

Bitwise combination of flags, as defined for the dwInterlaceFlags member of the VIDEOINFOHEADER2 structure.

Requirements

Requires Microsoft® Windows® XP.

See Also

See Also

  • DirectShow Structures
  • VIDEOINFOHEADER2


VMRVideoDesc Structure

This topic applies to Windows XP Service Pack 1 only.

The VMRVideoDesc structure describes a video stream to be deinterlaced.

Syntax

typedef struct _VMRVideoDesc {
    DWORD         dwSize;
    DWORD         dwSampleWidth;
    DWORD         dwSampleHeight;
    BOOL          SingleFieldPerSample;
    DWORD         dwFourCC;
    VMRFrequency  InputSampleFreq;
    VMRFrequency  OutputFrameFreq;
} VMRVideoDesc;

Members

dwSize

Size of the structure, in bytes.

dwSampleWidth

Width of the video to be deinterlaced, in pixels.

dwSampleHeight

Height of the video to be deinterlaced, in pixels.

SingleFieldPerSample

Specifies one of the following values.

Value | Description
TRUE | Pairs of fields are combined into single samples.
FALSE | Each fields is delivered as a separate sample.

dwFourCC

Specifies a FOURCC code. Valid values include NV12, YV12, YUY2, UYVY, IMC1, IMC2, IMC3 and IMC4

InputSampleFreq

VMRFrequency structure that specifies the input frequency. For NTSC TV, the frequency would be expressed as 30,000:1001.

OutputFrameFreq

VMRFrequency structure that specifies the output frequency. For NTSC TV, the frequency would be expressed as 60,000:1001.

Requirements

Requires Microsoft® Windows® XP Service Pack 1.

See Also

  • DirectShow Structures


VMRVIDEOSTREAMINFO Structure

This topic applies to Windows XP only.

The VMRVIDEOSTREAMINFO structure is used in the VMR-7 filter's call to IVMRImageCompositor::CompositeImage on the image compositor.

Syntax

typedef struct _VMRVIDEOSTREAMINFO {
    LPDIRECTDRAWSURFACE7 pddsVideoSurface;
    DWORD dwWidth;
    DWORD dwHeight;
    DWORD dwStrmID;
    FLOAT fAlpha;
    DDCOLORKEY ddClrKey;
    NORMALIZEDRECT rNormal;
}  VMRVIDEOSTREAMINFO;

Members

pddsVideoSurface

Specifies the DirectDraw surface that contains the video to be composited.

dwWidth

Specifies the width of the video rectangle.

dwHeight

Specifies the height of the video rectangle.

dwStrmID

Specifies the input stream. This value corresponds to the input pin.

fAlpha

Specifies the alpha value for this stream. (Not per-pixel alpha.)

ddClrKey

Specifies the source color key value or -1 if color keying is not to be used for this stream.

rNormal

Specifies the position of the image in composition space.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Structures


WAVEFORMATEX Structure

The WAVEFORMATEX structure defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

This structure is part of the Platform SDK and is declared in Mmreg.h. It is documented here for convenience.

Syntax

typedef struct {
  WORD  wFormatTag;
  WORD  nChannels;
  DWORD nSamplesPerSec;
  DWORD nAvgBytesPerSec;
  WORD  nBlockAlign;
  WORD  wBitsPerSample;
  WORD  cbSize;
} WAVEFORMATEX;

Members

wFormatTag

Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the Mmreg.h header file. For one- or two-channel Pulse Code Modulation (PCM) data, this value should be WAVE_FORMAT_PCM.

nChannels

Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.

nSamplesPerSec

Sample rate, in samples per second (hertz). If wFormatTag is WAVE_FORMAT_PCM, then common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nAvgBytesPerSec

Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nBlockAlign

Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE, nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Software must process a multiple of nBlockAlign bytes of data at a time. Data written to and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample

Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. If wFormatTag is WAVE_FORMAT_EXTENSIBLE, this value can be any integer multiple of 8. Some compression schemes cannot define a value for wBitsPerSample, so this member can be zero.

cbSize

Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats (and only WAVE_FORMAT_PCM formats), this member is ignored.

See Also

  • DirectShow Structures
  • WAVEFORMATEXTENSIBLE Structure


WAVEFORMATEXTENSIBLE Structure

The WAVEFORMATEXTENSIBLE structure defines the format of waveform-audio data for formats having more than two channels.

This structure is part of the Platform SDK and is declared in Mmreg.h. It is documented here for convenience.

Syntax

typedef struct {
  WAVEFORMATEX  Format;
  union {
    WORD  wValidBitsPerSample;
    WORD  wSamplesPerBlock;
    WORD  wReserved;
  } Samples;
  DWORD   dwChannelMask;
  GUID    SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;

Members

Format

WAVEFORMATEX structure that specifies the basic format. The wFormatTag member must be WAVE_FORMAT_EXTENSIBLE, defined in Mmreg.h. The cbSize member must be at least 22.

wValidBitsPerSample

Number of bits of precision in the signal. Usually equal to WAVEFORMATEX.wBitsPerSample.

wSamplesPerBlock

Number of samples contained in one compressed block of audio data. This value is used in buffer estimation. This value is used with compressed formats that have a fixed number of samples within each block. This value can be set to zero if a variable number of samples is contained in each block of compressed audio data. In this case, buffer estimation and position information needs to be obtained in other ways.

wReserved

Reserved for internal use by operating system. Set to zero.

dwChannelMask

Bitmask specifying the assignment of channels in the stream to speaker positions. See Remarks.

SubFormat

Subformat of the data, such as KSDATAFORMAT_SUBTYPE_PCM. The subformat information is similar to that provided by the tag in the WAVEFORMATEX structure's wFormatTag member.

Remarks

The dwChannelMask member specifies which channels are present in the multichannel stream. The least significant bit corresponds with the front left speaker, the next least significant bit corresponds to the front right speaker, and so on. The bits, in order of significance, are defined in Ksmedia.h and Mmreg.h as follows:

Speaker position | Flag bit
SPEAKER_FRONT_LEFT | 0x1
SPEAKER_FRONT_RIGHT | 0x2
SPEAKER_FRONT_CENTER | 0x4
SPEAKER_LOW_FREQUENCY | 0x8
SPEAKER_BACK_LEFT | 0x10
SPEAKER_BACK_RIGHT | 0x20
SPEAKER_FRONT_LEFT_OF_CENTER | 0x40
SPEAKER_FRONT_RIGHT_OF_CENTER | 0x80
SPEAKER_BACK_CENTER | 0x100
SPEAKER_SIDE_LEFT | 0x200
SPEAKER_SIDE_RIGHT | 0x400
SPEAKER_TOP_CENTER | 0x800
SPEAKER_TOP_FRONT_LEFT | 0x1000
SPEAKER_TOP_FRONT_CENTER | 0x2000
SPEAKER_TOP_FRONT_RIGHT | 0x4000
SPEAKER_TOP_BACK_LEFT | 0x8000
SPEAKER_TOP_BACK_CENTER | 0x10000
SPEAKER_TOP_BACK_RIGHT | 0x20000

For more information on this structure, see the document Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.


DirectShow Enumerated Types

This section describes the Microsoft® DirectShow® enumerated types. Closed captioning, DVD, VMR-7, VMR-9 and Video Port Extension (VPE) enumerated types are grouped by functionality below the primary list.

Enumerated Type | Description
AM_ASPECT_RATIO_MODE | Specifies the aspect ratio of a video image in a display window.
_AM_AUDIO_RENDERER_STAT_PARAM | Specifies which performance information to retrieve from the audio renderer.
_AM_FILTER_MISC_FLAGS | Contains the source or renderer filter flags.
AM_GRAPH_CONFIG_RECONNECT_FLAGS | Specifies how to reconnect filters when dynamically rebuilding the filter graph.
AM_INTF_SEARCH_FLAGS | Specifies the types of object to search, when attempting to find an interface on the filter graph.
AM_MPEG2Level | Indicates the MPEG-2 video level as specified in the MPEG-2 video standard.
AM_MPEG2Profile | Indicates the MPEG-2 video profile as specified in the MPEG-2 video standard.
AM_OVERLAY_NOTIFY_FLAGS | Contains information on what the overlay has changed or what the overlay is about to change.
AM_PIN_CONNECTION_BLOCK_FLAGS | Defines flags that specify how to block data flow from an output pin.
AM_PUSHSOURCE_FLAGS | Indicates the behavior of a live source filter.
AMRESCTL_RESERVEFLAGS | Contains flags specifying whether to increment or decrement the number of resources currently being reserved.
AM_SAMPLE_PROPERTY_FLAGS | Specifies values for the dwSampleFlagsand dwStreamId members of the AM_SAMPLE2_PROPERTIES structure. These values describe the properties of media samples.
AM_SEEKING_SEEKING_CAPABILITIES | Specifies the seeking capabilities of a media stream.
AM_STREAM_INFO_FLAGS | Indicates whether various components of the AM_STREAM_INFO structure have been set.
AMExtendedSeekingCapabilities | Specifies the seeking capabilities of a filter. Used with IAMExtendedSeeking::get_ExSeekCapabilities.
AMOVERLAYFX | Specifies effects on a Microsoft® DirectDraw® hardware overlay surface.
AMTunerModeType | Specifies the frequency of a TV tuner (cable or antenna).
AnalogVideoStandard | Specifies the format of the baseband analog video signal.
CameraControlFlags | Specifies whether a particular camera function is set automatically or manually.
CameraControlProperty | Specifies what part of the camera DirectShow is controlling.
CompressionCaps | Indicates video compression capabilities.
DECIMATION_USAGE | Describes the decimation strategy used by the overlay mixer filter.
DVDECODERRESOLUTION | Indicates the digital video (DV) decoding resolution.
DVENCODERFORMAT | Indicates the DV format.
DVENCODERRESOLUTION | Indicates the DV encoding resolution.
DVENCODERVIDEOFORMAT | Indicates the video standard (NTSC or PAL) for DV encoding.
FILTER_STATE | Specifies a filter's state.
InterleavingMode | Specifies how video frames and audio samples will be written to disk.
MEDIA_SAMPLE_CONTENT | Describes the contents of an elementary stream within an MPEG-2 transport stream.
PhysicalConnectorType | Specifies the physical type of pin.
PIN_DIRECTION | Indicates a pin's direction.
QualityMessageType | Describes a quality message.
REG_PINFLAG | Defines flags for the REGFILTERPINS2 structure.
REM_FILTER_FLAGS | Specifies how to remove a filter from the filter graph.
SNDDEV_ERR | Specifies how the audio device was being accessed when a failure occurred.
TunerInputType | Specifies the frequency of a TV tuner (cable or antenna).
TVAudioMode | Specifies the mode of a TV audio control.
VfwCaptureDialogs | Specifies a dialog box for a Microsoft Video for Windows® capture driver.
VfwCompressDialogs | Specifies a dialog box for a Video for Windows codec.
VideoControlFlags | Specifies a mode of operation for a video device, such as horizontal or vertical flip, external trigger enable, and trigger simulate.
VIDEOENCODER_BITRATE_MODE | Defines the three types of bitrates supported by the IEncoderAPI interface methods.
VideoProcAmpFlags | Specifies how to set video properties.
VideoProcAmpProperty | Specifies video properties on a video capture device.

The following enumerated types are specific to Line21 and WST closed captioning.

Enumerated Type | Description
AM_LINE21_CCLEVEL | Indicates the closed captioning capability level.
AM_LINE21_CCSERVICE | Indicates the closed captioning decoder service.
AM_LINE21_CCSTATE | Indicates the closed captioning state (on or off).
AM_LINE21_DRAWBGMODE | Indicates the closed-captioned text background mode.
AM_WST_DRAWBGMODE | Specifies whether the background of a WST closed captioning window is opaque or transparent.
AM_WST_LEVEL | Not supported.
AM_WST_SERVICE | Specifies the type of WST service.
AM_WST_STATE | Specifies whether WST closed captioning is on or off.
AM_WST_STYLE | Not supported.

The following enumerated types are specific to DVD.

DVD enumerated type | Description
AM_DVD_GRAPH_FLAGS | Specifies the type of decoder to use in a DVD filter graph.
AM_DVD_STREAM_FLAGS | Describes a DVD stream type (video, audio, or subpicture).
DVD_AUDIO_APPMODE | Indicates the current audio mode.
DVD_AUDIO_FORMAT | Indicates the audio format of a DVD.
DVD_AUDIO_LANG_EXT | Defines flags that indicate whether an audio stream contains audio language extensions.
DVD_CMD_FLAGS | Defines flags that control how the DVD Navigator filter handles command synchronization.
DVD_DISC_SIDE | Indicates the sides of a DVD disc.
DVD_DOMAIN | Specifies DVD domains.
DVD_ERROR | Specifies DVD error conditions.
DVD_FRAMERATE | Indicates whether the DVD is authored to play at 25 or 30 frames per second.
DVD_KARAOKE_ASSIGNMENT | Defines the speaker configuration for an audio stream.
DVD_KARAOKE_CONTENTS | Specifies flags that, when used in a bitwise OR operation, describe the contents of each channel of an audio stream in a karaoke title.
DVD_KARAOKE_DOWNMIX | Defines flags used by the IDvdControl2::SelectKaraokeAudioPresentationMode method to control which speakers, if any, each auxiliary channel is downmixed to.
DVD_MENU_ID | Specifies DVD Video Title Set (VTS) menu identifiers.
DVD_OPTION_FLAG | Defines flags that control aspects of the DVD Navigator filter's behavior related to playback of DVD content.
DVD_PARENTAL_LEVEL | Identifies flags for the generic parental levels defined in the DVD specification.
DVD_PREFERRED_DISPLAY_MODE | Indicates the user's preferred window aspect ratio and conversion method.
DVD_RELATIVE_BUTTON | Identifies the four directional buttons used for DVD menu navigation and other operations.
DVD_SUBPICTURE_CODING | Indicates what kind of content the subpicture stream contains.
DVD_SUBPICTURE_LANG_EXT | Defines the possible language extensions in a specified subpicture stream.
DVD_SUBPICTURE_TYPE | Defines flags used to determine what kind of content the subpicture stream contains.
DVD_TextCharSet | Defines which ISO character set a specified string is encoded with.
DVD_TextStringType | Defines a subset of the DVD text string types.
DVD_TIMECODE_FLAGS | Indicates the frame rate at which a DVD has been authored to play.
DVD_TITLE_APPMODE | Indicates whether a DVD title is a karaoke title.
DVD_VIDEO_COMPRESSION | Defines the possible DVD video compression types.
DVD_WARNING | Specifies DVD warning conditions.
VALID_UOP_FLAG | Indicates which user operation (UOP) commands are currently allowed by the DVD.

The following enumerated types are specific to the VMR-7.

VMR-7 Enumerated Type | Description
VMR_ASPECT_RATIO_MODE | Used with the IVMRWindowlessControl::GetAspectRatioMode and IVMRWindowlessControl::SetAspectRatioMode methods to set and retrieve the aspect ratio mode
VMRDeinterlacePrefs | Used to describe the deinterlacing preference policy for the VMR.
VMRDeinterlaceTech | Used to describe the algorithm used for deinterlacing a stream. Flags are not mutually exclusive.
VMRMixerPrefs | Contains flags that specify decimation, filtering, and color space information that will be used when the video image is created on the DirectDraw surface.
VMRMode | Used in calls to the IVMRFilterConfig::GetRenderingMode and IVMRFilterConfig::SetRenderingMode methods to retrieve or specify the VMR-7's rendering mode.
VMRPresentationFlags | Member of the VMRPRESENTATIONINFO structure
VMRRenderPrefs | Used with the IVMRFilterConfig::GetRenderingPrefs and IVMRFilterConfig::SetRenderingPrefs methods to get and set basic rendering preferences.
VMRSurfaceAllocationFlags | used with the IVMRSurfaceAllocator::AllocateSurface method to specify surface creation parameters.

The following enumerated types are specific to the VMR-9.

VMR-9 Enumerated Type | Description
VMR9_SampleFormat | Describes the interlacing of a video stream.
VMR9AlphaBitmapFlags | Defines the possible values for the dwFlags member of the VMR9AlphaBitmap structure.
VMR9AspectRatioMode | Used with the IVMRWindowlessControl9::GetAspectRatioMode and SetAspectRatioMode methods to set and retrieve the aspect ratio mode.
VMR9DeinterlacePrefs | Describes the deinterlacing method that the VMR-9 uses if the method set by the application cannot be used.
VMR9DeinterlaceTech | Describes the algorithm used for deinterlacing a video stream.
VMR9MixerPrefs | Contains flags that specify decimation, filtering, and color space information that will be used when the video image is created on the Direct3D surface
VMR9Mode | Used in calls to the IVMRFilterConfig9::GetRenderingMode and SetRenderingMode methods to retrieve or specify the VMR-9's rendering mode.
VMR9PresentationFlags | Member of the VMR9PresentationInfo structure.
VMR9ProcAmpControlFlags | Specifies image adjustment properties.
VMR9RenderPrefs | Specifies basic rendering preferences for the VMR-9.
VMR9SurfaceAllocationFlags | Used with the IVMRSurfaceAllocator9::InitializeDevice method to specify surface creation parameters.

The following enumerated types are specific to Video Port Extensions.

VPE Enumerated Type | Description
AMVP_MODE | Specifies the various modes for video ports (VP).
AMVP_SELECT_FORMAT_BY | Specifies the criteria that the VP mixer should use to select the video format.


AM_ASPECT_RATIO_MODE Enumeration

Specifies the aspect ratio of a video image in a display window.

Syntax

typedef enum _AM_ASPECT_RATIO_MODE
{
    AM_ARMODE_STRETCHED,
    AM_ARMODE_LETTER_BOX,
    AM_ARMODE_CROP,
    AM_ARMODE_STRETCHED_AS_PRIMARY
} AM_ASPECT_RATIO_MODE;

Elements

AM_ARMODE_STRETCHED

No aspect ratio correction.

AM_ARMODE_LETTER_BOX

Put the video in letterbox format. Paint background color in the excess region so the video is not distorted.

AM_ARMODE_CROP

Crop the video to the correct aspect ratio.

AM_ARMODE_STRETCHED_AS_PRIMARY

Use whatever mode is currently set for the primary stream. This value is valid only for secondary streams.

Remarks

The AM_ARMODE_STRETCHED member causes a video stream to occupy the entire region of the display window when the window is resized, possibly stretching the video. The AM_ARMODE_LETTER_BOX member eliminates video stretching and distortions by keeping the aspect ratio consistent and painting the excess areas of the window a background color. The AM_ARMODE_CROP member also prevents stretching, by cropping the image if necessary.

See Also

  • IMixerPinConfig::GetAspectRatioMode
  • IMixerPinConfig::SetAspectRatioMode
  • DirectShow Enumerated Types


_AM_AUDIO_RENDERER_STAT_PARAM Enumeration

The _AM_AUDIO_RENDERER_STAT_PARAM enumeration specifies which performance information to retrieve from the audio renderer.

Syntax

enum _AM_AUDIO_RENDERER_STAT_PARAM {
    AM_AUDREND_STAT_PARAM_BREAK_COUNT = 1,
    AM_AUDREND_STAT_PARAM_SLAVE_MODE,
    AM_AUDREND_STAT_PARAM_SILENCE_DUR,
    AM_AUDREND_STAT_PARAM_LAST_BUFFER_DUR,
    AM_AUDREND_STAT_PARAM_DISCONTINUITIES,
    AM_AUDREND_STAT_PARAM_SLAVE_RATE,
    AM_AUDREND_STAT_PARAM_SLAVE_DROPWRITE_DUR,
    AM_AUDREND_STAT_PARAM_SLAVE_HIGHLOWERROR,
    AM_AUDREND_STAT_PARAM_SLAVE_LASTHIGHLOWERROR,
    AM_AUDREND_STAT_PARAM_SLAVE_ACCUMERROR,
    AM_AUDREND_STAT_PARAM_BUFFERFULLNESS,
    AM_AUDREND_STAT_PARAM_JITTER
};

Elements

This enumeration type is used in the IAMAudioRendererStats::GetStatParam method. Each enumeration member defines the meaning of the values that are returned in the pdwParam1 and pdwParam2 parameters of GetStatParam.

The following tables describe each enumeration member.

Enumeration Value | AM_AUDREND_STAT_PARAM_BREAK_COUNT
Param1 | The cumulative number of breaks in the audio stream.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_BUFFERFULLNESS
Param1 | How much audio data is in the audio buffer, as a percentage.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_DISCONTINUITIES
Param1 | The cumulative number of discontinuities in the audio stream.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_JITTER
Remarks | Not implemented.

Enumeration Value | AM_AUDREND_STAT_PARAM_LAST_BUFFER_DUR
Param1 | The duration of the most recent audio buffer, in milliseconds.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_SILENCE_DUR
Param1 | The cumulative amount of silence the audio renderer has inserted, due to gaps in the time stamps of the incoming samples. The value is given in milliseconds.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_ACCUMERROR
Param1 | The accumulated difference between the audio renderer and the master clock, including adjustments made by dropping samples or inserting gaps.
Param2 | Not used.
Remarks | Valid only when the audio renderer is matching rates to another clock or a live source.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_DROPWRITE_DUR
Param1 | The amount of data dropped to stay in sync, in milliseconds.
Param2 | The amount of silence added to stay in sync, in milliseconds. (Currently not implemented.)
Remarks | Applies only when the Audio Renderer (WaveOut) filter is matching rates to a master clock.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_HIGHLOWERROR
Param1 | The highest difference noted between the audio renderer's clock and the clock it is trying to match.
Param2 | The lowest difference noted between the audio renderer's clock and the clock it is trying to match.
Remarks | Valid only when the audio renderer is matching rates to a master clock.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_LASTHIGHLOWERROR
Param1 | The last high error, in milliseconds. A high error occurs when the audio renderer falls behind the clock.
Param2 | The last low error, in milliseconds. A low error occurs when the audio renderer runs ahead of the clock.
Remarks | Valid only when the audio renderer is matching rates to a master clock.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_MODE
Param1 | Indicates the current rate-matching mode. The value is a bitwise combination of the following: 0x00: No rate matching. 0x01: Match rates to a live source. 0x02: Match rates based on the rate of the incoming audio data. 0x04: Match rates with the filter graph's reference clock (when the clock is not provided by the audio renderer). 0x10: Match rates based on the time stamps of the audio samples.
Param2 | Not used.

Enumeration Value | AM_AUDREND_STAT_PARAM_SLAVE_RATE
Param1 | The sample rate that the audio renderer is matching, in samples per second.
Param2 | Not used.
Remarks | Valid only when the DirectSound Renderer is matching rates to another clock or a live source.

See Also

  • DirectShow Enumerated Types
  • IAMAudioRendererStats Interface


AM_DVD_GRAPH_FLAGS Enumeration

The AM_DVD_GRAPH_FLAGS enumeration specifies the type of decoder to use in a DVD filter graph.

Syntax

enum {
    AM_DVD_HWDEC_PREFER =  0x01,
    AM_DVD_HWDEC_ONLY   =  0x02,
    AM_DVD_SWDEC_PREFER =  0x04,
    AM_DVD_SWDEC_ONLY   =  0x08,
    AM_DVD_NOVPE        = 0x100,
    AM_DVD_VMR9_ONLY    = 0x800
} AM_DVD_GRAPH_FLAGS;

Elements

AM_DVD_HWDEC_PREFER

Maximum hardware decoding. Default.

AM_DVD_HWDEC_ONLY

Hardware decoding only.

AM_DVD_SWDEC_PREFER

Maximum software decoding.

AM_DVD_SWDEC_ONLY

Software decoding only.

AM_DVD_NOVPE

Do not show video on computer monitor. Use of this flag should be limited only to the combination of a hardware DVD-Video decoder and a display device with a port that can connect to a TV. A set-top box type of device that can play back DVD-Video could play DVD titles to be viewed on a TV set rather than a computer monitor.

AM_DVD_VMR9_ONLY

Use the Video Mixing Renderer Filter 9 (VMR-9) for rendering; fail if the VMR-9 is not available.

Remarks

Do not combine any of the hardware flags (AM_DVD_HWDEC_*) with any of the software flags (AM_DVD_SWDEC_*). However, you can combine AM_DVD_NOVPE with any of the hardware flags.

See Also

  • DirectShow Enumerated Types
  • IDvdGraphBuilder::RenderDvdVideoVolume


AM_DVD_STREAM_FLAGS Enumeration

Describes a DVD stream type (video, audio, or subpicture).

Syntax

enum {
    AM_DVD_STREAM_VIDEO  = 0x01,
    AM_DVD_STREAM_AUDIO  = 0x02,
    AM_DVD_STREAM_SUBPIC = 0x04
} AM_DVD_STREAM_FLAGS;

Elements

AM_DVD_STREAM_VIDEO

DVD video stream.

AM_DVD_STREAM_AUDIO

DVD audio stream.

AM_DVD_STREAM_SUBPIC

DVD subpicture stream.

See Also

  • AM_DVD_RENDERSTATUS Structure
  • DirectShow Enumerated Types


_AM_FILTER_MISC_FLAGS Enumeration

The _AM_FILTER_MISC_FLAGS enumeration contains flags that indicate whether a filter is a source filter or a renderer filter.

Syntax

typedef enum _AM_FILTER_MISC_FLAGS {
    AM_FILTER_MISC_FLAGS_IS_RENDERER = 0x00000001,
    AM_FILTER_MISC_FLAGS_IS_SOURCE   = 0x00000002
};

Elements

AM_FILTER_MISC_FLAGS_IS_RENDERER

The filter is a renderer and sends an EC_COMPLETE event at the end of the stream.

AM_FILTER_MISC_FLAGS_IS_SOURCE

The filter is a source filter.

See Also

  • DirectShow Enumerated Types
  • IAMFilterMiscFlags::GetMiscFlags


AM_GRAPH_CONFIG_RECONNECT_FLAGS Enumeration

Specifies how to reconnect filters when dynamically rebuilding the filter graph.

Syntax

typedef enum _AM_GRAPH_CONFIG_RECONNECT_FLAGS {
    AM_GRAPH_CONFIG_RECONNECT_DIRECTCONNECT = 0x00000001,
    AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS = 0x00000002,
    AM_GRAPH_CONFIG_RECONNECT_USE_ONLY_CACHED_FILTERS = 0x00000004
} AM_GRAPH_CONFIG_RECONNECT_FLAGS;

Elements

AM_GRAPH_CONFIG_RECONNECT_DIRECTCONNECT

Do not insert additional filters into the graph while reconnecting, aside from any filter explicitly requested.

AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS

Place filters removed from the graph into the filter cache.

AM_GRAPH_CONFIG_RECONNECT_USE_ONLY_CACHED_FILTERS

When inserting additional filters into the graph, use only filters currently in the filter cache.

See Also

  • IGraphConfig::Reconnect
  • IPinFlowControl::Block
  • DirectShow Enumerated Types


AM_INTF_SEARCH_FLAGS Enumeration

Specifies the types of object to search, when attempting to find an interface on the filter graph.

Syntax

enum _AM_INTF_SEARCH_FLAGS {
    AM_INTF_SEARCH_INPUT_PIN  = 0x00000001,
    AM_INTF_SEARCH_OUTPUT_PIN = 0x00000002,
    AM_INTF_SEARCH_FILTER     = 0x00000004
};

Elements

AM_INTF_SEARCH_INPUT_PIN

Search input pins.

AM_INTF_SEARCH_OUTPUT_PIN

Search output pins.

AM_INTF_SEARCH_FILTER

Search filters.

Remarks

If no flags are set (the default case), it is equivalent to the bitwise OR of all the flags. All filters and pins are searched.

See Also

  • DirectShow Enumerated Types
  • IAMGraphStreams::FindUpstreamInterface


AM_LINE21_CCLEVEL Enumeration

Indicates the closed caption decoder level.

Syntax

 typedef enum _AM_LINE21_CCLEVEL {
    AM_L21_CCLEVEL_TC2
} AM_LINE21_CCLEVEL, *PAM_LINE21_CCLEVEL ;

Elements

AM_L21_CCLEVEL_TC2

TeleCaption II.

See Also

  • DirectShow Enumerated Types
  • IAMLine21Decoder::GetDecoderLevel


AM_LINE21_CCSERVICE Enumeration

Indicates the closed captioning service.

Syntax

 typedef enum _AM_LINE21_CCSERVICE {
    AM_L21_CCSERVICE_None,
    AM_L21_CCSERVICE_Caption1,
    AM_L21_CCSERVICE_Caption2,
    AM_L21_CCSERVICE_Text1,
    AM_L21_CCSERVICE_Text2,
    AM_L21_CCSERVICE_XDS,
} AM_LINE21_CCSERVICE, *PAM_LINE21_CCSERVICE ;

Elements

AM_L21_CCSERVICE_None

No current service.

AM_L21_CCSERVICE_Caption1

CC1 (caption channel).

AM_L21_CCSERVICE_Caption2

CC2 (caption channel).

AM_L21_CCSERVICE_Text1

T1 (text channel).

AM_L21_CCSERVICE_Text2

T2 (text channel)

AM_L21_CCSERVICE_XDS

Extended Data Services (XDS or EDS).

Remarks

The Line 21 decoder supports CC1 and CC2 only.

See Also

  • DirectShow Enumerated Types
  • IAMLine21Decoder::GetCurrentService
  • IAMLine21Decoder::SetCurrentService


AM_LINE21_CCSTATE Enumeration

Indicates the closed captioning state (on or off).

Syntax

 typedef enum _AM_LINE21_CCSTATE {
    AM_L21_CCSTATE_Off,
    AM_L21_CCSTATE_On
} AM_LINE21_CCSTATE, *PAM_LINE21_CCSTATE ;

Elements

AM_L21_CCSTATE_Off

Closed captioning off.

AM_L21_CCSTATE_On

Closed captioning on.

See Also

  • DirectShow Enumerated Types
  • IAMLine21Decoder::GetServiceState
  • IAMLine21Decoder::SetServiceState


AM_LINE21_DRAWBGMODE Enumeration

Indicates the closed captioning text background mode.

Syntax

 typedef enum _AM_LINE21_DRAWBGMODE {
    AM_L21_DRAWBGMODE_Opaque,
    AM_L21_DRAWBGMODE_Transparent
} AM_LINE21_DRAWBGMODE, *PAM_LINE21_DRAWBGMODE ;

Elements

AM_L21_DRAWBGMODE_Opaque

Opaque background.

AM_L21_DRAWBGMODE_Transparent

Transparent background.

See Also

  • DirectShow Enumerated Types
  • IAMLine21Decoder::GetDrawBackgroundMode
  • IAMLine21Decoder::SetDrawBackgroundMode


AM_MPEG2Level Enumeration

Indicates an MPEG-2 video level as specified in the MPEG-2 video standard (ISO13818-2).

Syntax

enum AM_MPEG2Level {
    AM_MPEG2Level_Low = 1,
    AM_MPEG2Level_Main,
    AM_MPEG2Level_High1440,
    AM_MPEG2Level_High
};

Elements

AM_MPEG2Level_Low

Low level.

AM_MPEG2Level_Main

Main level.

AM_MPEG2Level_High1440

High 1440 level.

AM_MPEG2Level_High

High level.

Remarks

DVD MPEG-2 video decoders should support AM_MPEG2Level_Low or AM_MPEG2Level_Main.

Requirements

Include Dvdmedia.h

See Also

  • DirectShow Enumerated Types


AM_MPEG2Profile Enumeration

Indicates an MPEG-2 video profile as specified in the MPEG-2 video standard (ISO13818-2).

Syntax

enum AM_MPEG2Profile {
    AM_MPEG2Profile_Simple = 1,
    AM_MPEG2Profile_Main,
    AM_MPEG2Profile_SNRScalable,
    AM_MPEG2Profile_SpatiallyScalable,
    AM_MPEG2Profile_High
};

Elements

AM_MPEG2Profile_Simple

Simple profile.

AM_MPEG2Profile_Main

Main profile.

AM_MPEG2Profile_SNRScalable

Signal to Noise Ratio (SNR) scalable profile

AM_MPEG2Profile_SpatiallyScalable

Spatially scalable profile.

AM_MPEG2Profile_High

High profile.

Remarks

DVD video decoders should support AM_MPEG2Profile_Simple or AM_MPEG2Profile_Main.

Requirements

Include Dvdmedia.h

See Also

  • DirectShow Enumerated Types


AM_OVERLAY_NOTIFY_FLAGS Enumeration

The AM_OVERLAY_NOTIFY_FLAGS enumeration indicates what the overlay has changed, or is about to change.

Syntax

typedef enum _AM_OVERLAY_NOTIFY_FLAGS {
    AM_OVERLAY_NOTIFY_VISIBLE_CHANGE  = 0x00000001,
    AM_OVERLAY_NOTIFY_SOURCE_CHANGE   = 0x00000002,
    AM_OVERLAY_NOTIFY_DEST_CHANGE     = 0x00000004
};

Elements

AM_OVERLAY_NOTIFY_VISIBLE_CHANGE

The rectangle will be changed from visible to invisible, or vice-versa.

AM_OVERLAY_NOTIFY_SOURCE_CHANGE

Source rectangle changed or changing.

AM_OVERLAY_NOTIFY_DEST_CHANGE

Destination rectangle changed or changing.

Remarks

The IDDrawExclModeVideoCallback::OnUpdateOverlay method uses these flags to indicate how the overlay has changed, so that applications can take the necessary steps.

See Also

  • DirectShow Enumerated Types
  • IDDrawExclModeVideoCallback::OnUpdateOverlay


AM_PIN_CONNECTION_BLOCK_FLAGS Enumeration

Defines flags that specify how to block data flow from an output pin.

Syntax

typedef enum _AM_PIN_CONNECTION_BLOCK_FLAGS {
    AM_PIN_FLOW_CONTROL_BLOCK = 0x00000001,
    AM_PIN_PUSH_THROUGH_DATA = 0x00000002
};

Elements

AM_PIN_FLOW_CONTROL_BLOCK

Block the data flow.

AM_PIN_PUSH_THROUGH_DATA

Push the data through the filter graph.

See Also

  • DirectShow Enumerated Types
  • IPinFlowControl::Block


AM_PUSHSOURCE_FLAGS Enumeration

Indicates the behavior of a live source filter.

Syntax

enum _AM_PUSHSOURCE_FLAGS {
    AM_PUSHSOURCECAPS_INTERNAL_RM        = 0x00000001,
    AM_PUSHSOURCECAPS_NOT_LIVE           = 0x00000002,
    AM_PUSHSOURCECAPS_PRIVATE_CLOCK      = 0x00000004,
    AM_PUSHSOURCEREQS_USE_STREAM_CLOCK   = 0x00010000
};

Elements

AM_PUSHSOURCECAPS_INTERNAL_RM

The filter uses its own rate-matching mechanism; the renderer should therefore not attempt to match rates with this filter.

AM_PUSHSOURCECAPS_NOT_LIVE

The filter is not live. Do not treat it as a live source, even though it exposes the IAMPushSource interface.

AM_PUSHSOURCECAPS_PRIVATE_CLOCK

The filter time stamps the samples using a private clock. The clock is not available to the rest of the graph through IReferenceClock.

AM_PUSHSOURCEREQS_USE_STREAM_CLOCK

Reserved; do not use.

Remarks

If no flags are set (the default case), the source filter is assumed to be live and not to perform any rate matching on its own.

See Also

  • DirectShow Enumerated Types


AM_SAMPLE_PROPERTY_FLAGS Enumeration

Specifies values for the dwSampleFlags and dwStreamId members of the AM_SAMPLE2_PROPERTIES structure. These values describe the properties of media samples.

Syntax

enum tagAM_SAMPLE_PROPERTY_FLAGS {
    AM_SAMPLE_SPLICEPOINT        = 0x01,
    AM_SAMPLE_PREROLL            = 0x02,
    AM_SAMPLE_DATADISCONTINUITY  = 0x04,
    AM_SAMPLE_TYPECHANGED        = 0x08,
    AM_SAMPLE_TIMEVALID          = 0x10,
    AM_SAMPLE_TIMEDISCONTINUITY  = 0x40,
    AM_SAMPLE_FLUSH_ON_PAUSE     = 0x80,
    AM_SAMPLE_STOPVALID          = 0x100,
    AM_SAMPLE_ENDOFSTREAM        = 0x200,
    AM_STREAM_MEDIA              = 0,
    AM_STREAM_CONTROL            = 1
};

Elements

AM_SAMPLE_SPLICEPOINT

Sample is a splice point (it can be decoded without reference to previous data).

AM_SAMPLE_PREROLL

Sample is a preroll sample.

AM_SAMPLE_DATADISCONTINUITY

Initial data in this sample is a splice point. The data in the previous sample was not intended to be followed by data in this sample. For more information, see Remarks.

AM_SAMPLE_TYPECHANGED

Sample type changed.

AM_SAMPLE_TIMEVALID

Time is valid.

AM_SAMPLE_TIMEDISCONTINUITY

A time gap in the data starts after this sample. The pbBuffer member of the AM_SAMPLE2_PROPERTIES structure can be NULL in this case.

AM_SAMPLE_FLUSH_ON_PAUSE

For live data only; indicates discard in the paused state.

AM_SAMPLE_STOPVALID

Stop time is valid.

AM_SAMPLE_ENDOFSTREAM

End of stream occurs after this sample. This is reserved for kernel streaming and Microsoft® DirectShow® currently doesn't use it.

AM_STREAM_MEDIA

Normal data stream identifier.

AM_STREAM_CONTROL

Control stream identifier. A value greater than 0x7FFFFFFF indicates an application-defined stream.

Remarks

The AM_SAMPLE_DATADISCONTINUITY flag indicates that the data in the current media sample is not considered contiguous with the data in previous samples. A filter receiving a sample with the AM_SAMPLE_DATADISCONTINUITY flag set should not discard unprocessed data in its buffers. A filter waiting for incoming data before it can process buffered data should process the buffered data immediately; so, buffered data might be discarded if it is incomplete.

For example, a video decompressor filter might receive a media sample with the AM_SAMPLE_DATADISCONTINUITY flag set when it has two complete compressed video frames and one incomplete compressed video frame in its buffers. In this case, the filter decompresses the two complete frames and discards the incomplete third frame before beginning to process data from the current media sample.

The AM_SAMPLE_DATADISCONTINUITY flag is set on the first sample received following a flush or a stop. In addition, you should use the AM_SAMPLE_DATADISCONTINUITY flag when content is switched in the source, when a channel change occurs (when there might also be a format change), or when there is missing data because of stream interruptions.

The AM_SAMPLE_DATADISCONTINUITY flag is equivalent to the IMediaSample::IsDiscontinuity method returning S_OK.

See Also

  • DirectShow Enumerated Types


AM_SEEKING_SEEKING_CAPABILITIES Enumeration

Specifies the seeking capabilities of a media stream.

Syntax

typedef
enum AM_SEEKING_SeekingCapabilities {
    AM_SEEKING_CanSeekAbsolute        = 0x1,
    AM_SEEKING_CanSeekForwards        = 0x2,
    AM_SEEKING_CanSeekBackwards       = 0x4,
    AM_SEEKING_CanGetCurrentPos       = 0x8,
    AM_SEEKING_CanGetStopPos          = 0x10,
    AM_SEEKING_CanGetDuration         = 0x20,
    AM_SEEKING_CanPlayBackwards       = 0x40,
    AM_SEEKING_CanDoSegments          = 0x80,
    AM_SEEKING_Source                 = 0x100
}   AM_SEEKING_SEEKING_CAPABILITIES;

Elements

AM_SEEKING_CanSeekAbsolute

The stream can seek to an absolute position.

AM_SEEKING_CanSeekForwards

The stream can seek forward.

AM_SEEKING_CanSeekBackwards

The stream can seek backward.

AM_SEEKING_CanGetCurrentPos

The stream can report its current position.

AM_SEEKING_CanGetStopPos

The stream can report its stop position.

AM_SEEKING_CanGetDuration

The stream can report its duration.

AM_SEEKING_CanPlayBackwards

The stream can play backward.

AM_SEEKING_CanDoSegments

The stream can do seamless looping (see IMediaSeeking::SetPositions).

AM_SEEKING_Source

Reserved.

See Also

  • IMediaSeeking::GetCapabilities
  • IMediaSeeking::CheckCapabilities


AM_STREAM_INFO_FLAGS Enumeration

The AM_STREAM_INFO_FLAGS enumeration defines flags that indicate a pin's stream-control status.

Syntax

typedef enum {
    AM_STREAM_INFO_START_DEFINED = 0x00000001,
    AM_STREAM_INFO_STOP_DEFINED  = 0x00000002,
    AM_STREAM_INFO_DISCARDING    = 0x00000004,
    AM_STREAM_INFO_STOP_SEND_EXTRA = 0x00000010
} AM_STREAM_INFO_FLAGS;

Elements

AM_STREAM_INFO_START_DEFINED

Indicates that the pin's start time is set.

AM_STREAM_INFO_STOP_DEFINED

Indicates that the pin's stop time is been set.

AM_STREAM_INFO_DISCARDING

Indicates that the pin is currently discarding data.

AM_STREAM_INFO_STOP_SEND_EXTRA

Indicates that the pin will send one extra sample after it reaches the stop time.

See Also

  • AM_STREAM_INFO
  • IAMStreamControl::GetInfo


AM_WST_DRAWBGMODE Enumeration

The AM_WST_DRAWBGMODE enumeration specifies whether the background of the WST frame is opaque or transparent.

Syntax

typedef enum _AM_WST_DRAWBGMODE {
  AM_WST_DRAWBGMODE_Opaque,
  AM_WST_DRAWBGMODE_Transparent
} AM_WST_DRAWBGMODE, *PAM_WST_DRAWBGMODE ;

Elements

AM_WST_DRAWBGMODE_Opaque

The background is opaque.

AM_WST_DRAWBGMODE_Transparent

The background is transparent.

See Also

  • DirectShow Enumerated Types


AM_WST_LEVEL Enumeration

The AM_WST_LEVEL enumeration is currently not supported.

Syntax

typedef enum _AM_WST_LEVEL {
  AM_WST_LEVEL_1_5 = 0
} AM_WST_LEVEL, *PAM_WST_LEVEL ;

Elements

AM_WST_LEVEL_1_5

Not implemented.

See Also

  • DirectShow Enumerated Types


AM_WST_SERVICE Enumeration

The AM_WST_SERVICE enumeration specifies whether WST service is available and the type of service. This enumeration is currently not supported.

Syntax

typedef enum _AM_WST_SERVICE {
  AM_WST_SERVICE_None = 0,
  AM_WST_SERVICE_Text,
  AM_WST_SERVICE_IDS,
  AM_WST_SERVICE_Invalid
} AM_WST_SERVICE, *PAM_WST_SERVICE ;

Elements

AM_WST_SERVICE_None

There is no WST service

AM_WST_SERVICE_Text

The WST closed captioning service is text only

AM_WST_SERVICE_IDS

AM_WST_SERVICE_Invalid

See Also

  • DirectShow Enumerated Types


AM_WST_STATE Enumeration

The AM_WST_STATE enumeration specifies whether WST closed captioning is enabled or disabled.

Syntax

typedef enum _AM_WST_STATE {
  AM_WST_STATE_Off = 0,
  AM_WST_STATE_On
} AM_WST_STATE, *PAM_WST_STATE ;

Elements

AM_WST_STATE_Off

Specifies that WST closed captioning is enabled

AM_WST_STATE_On

Specifies that WST closed captioning is disabled.

See Also

  • DirectShow Enumerated Types


AM_WST_STYLE Enumeration

The AM_WST_STYLE enumeration is not supported.

Syntax

typedef enum _AM_WST_STYLE {
  AM_WST_STYLE_None = 0,
  AM_WST_STYLE_Invers
} AM_WST_STYLE, *PAM_WST_STYLE ;

Elements

AM_WST_STYLE_None

AM_WST_STYLE_Invers

See Also

  • DirectShow Enumerated Types


AMExtendedSeekingCapabilities Enumeration

The AMExtendedSeekingCapabilities enumeration contains flags that describe the extended seeking capabilities of a filter.

Syntax

typedef enum AMExtendedSeekingCapabilities{
  AM_EXSEEK_CANSEEK  =1,
  AM_EXSEEK_CANSCAN  =2,
  AM_EXSEEK_MARKERSEEK  =4,
  AM_EXSEEK_SCANWITHOUTCLOCK  =8,
  AM_EXSEEK_NOSTANDARDREPAINT  =16,
  AM_EXSEEK_BUFFERING  =32,
  AM_EXSEEK_SENDS_VIDEOFRAMEREADY  =64
};

Members

AM_EXSEEK_CANSEEK

Indicates that the stream is seekable.

AM_EXSEEK_CANSCAN

Indicates that the filter supports rates other than 1.0.

AM_EXSEEK_MARKERSEEK

Indicates that the stream contains markers.

AM_EXSEEK_SCANWITHOUTCLOCK

Indicates that the filter can play back at rates other than 1.0.

AM_EXSEEK_NOSTANDARDREPAINT

Indicates that the filter can seek to a new frame without displaying the new frame when it finds it.

AM_EXSEEK_BUFFERING

Indicates that the filter can seek while the stream is buffering.

AM_EXSEEK_SENDS_VIDEOFRAMEREADY

Indicates that the filter's video pin has been created.

Remarks

See IAMExtendedSeeking::get_ExSeekCapabilities for descriptions of how the Windows Media Source filter sets these flags.

See Also

  • DirectShow Enumerated Types


AMOVERLAYFX Enumeration

Specifies effects on a Microsoft® DirectDraw® hardware overlay surface.

Syntax

enum AMOVERLAYFX {
    AMOVERFX_NOFX =             0x00000000,
    AMOVERFX_MIRRORLEFTRIGHT =  0x00000002,
    AMOVERFX_MIRRORUPDOWN =     0x00000004,
    AMOVERFX_DEINTERLACE =      0x00000008
};

Elements

AMOVERFX_NOFX

Normal video (no effects).

AMOVERFX_MIRRORLEFTRIGHT

Mirror the overlay across the vertical axis.

AMOVERFX_MIRRORUPDOWN

Mirror the overlay across the horizontal axis.

AMOVERFX_DEINTERLACE

When used in IAMOverlayFX::QueryOverlayFXCaps, this flag specifies whether the hardware can support the DirectDraw 7 DDOVERFX_DEINTERLACE hint. When used with the IAMOverlayFX::GetOverlayFX or IAMOverlayFX::SetOverlayFX methods, this flag indicates that the overlay should be deinterlaced if possible.

See Also

  • IAMOverlayFX Interface
  • DirectShow Enumerated Types


AMRESCTL_RESERVEFLAGS Enumeration

Specifies whether to increment or decrement the number of resources currently being reserved.

Syntax

enum _AMRESCTL_RESERVEFLAGS{
    AMRESCTL_RESERVEFLAGS_RESERVE     = 0x00,
    AMRESCTL_RESERVEFLAGS_UNRESERVE   = 0x01
};

Elements

AMRESCTL_RESERVEFLAGS_RESERVE

Increment the reserved resource count.

AMRESCTL_RESERVEFLAGS_UNRESERVE

Decrement the reserved resource count.

See Also

  • DirectShow Enumerated Types


AMTunerModeType Enumeration

Specifies the frequency of a TV tuner (cable or antenna).

Syntax

typedef enum tagAMTunerModeType
    {
        AMTUNER_MODE_DEFAULT = 0x0000,
        AMTUNER_MODE_TV = 0x0001,
        AMTUNER_MODE_FM_RADIO = 0x0002,
        AMTUNER_MODE_AM_RADIO = 0x0004,
        AMTUNER_MODE_DSS = 0x0008
    } AMTunerModeType;

Elements

AMTUNER_MODE_DEFAULT

Indicates default tuner mode.

AMTUNER_MODE_TV

Indicates TV tuner mode.

AMTUNER_MODE_FM_RADIO

Indicates FM radio tuner mode.

AMTUNER_MODE_AM_RADIO

Indicates AM radio tuner mode.

AMTUNER_MODE_DSS

Indicates Digital Satellite Service (DSS) tuner mode.

See Also

  • DirectShow Enumerated Types


AMVP_MODE Enumeration

Specifies the various modes for video ports.

Syntax

typedef enum _AMVP_MODE{
AMVP_MODE_WEAVE,
AMVP_MODE_BOBINTERLEAVED,
AMVP_MODE_BOBNONINTERLEAVED,
AMVP_MODE_SKIPEVEN,
AMVP_MODE_SKIPODD
} AMVP_MODE;

Elements

AMVP_MODE_WEAVE

weave.

AMVP_MODE_BOBINTERLEAVED

Interleaved bob. Bob mode in which resources are allocated to switch to weave mode, for example, on the next frame.

MODE_BOBNONINTERLEAVED

Noninterleaved bob. Bob mode in which resources are not allocated to switch to weave mode.

AMVP_MODE_SKIPEVEN

Skip even fields.

AMVP_MODE_SKIPODD

Skip odd fields.

See Also

DirectShow Enumerated Types


AMVP_SELECT_FORMAT_BY Enumeration

Specifies the criteria that the Overlay Mixer Filter should use to select the video format.

Syntax

typedef enum _AMVP_SELECT_FORMAT_BY{
AMVP_DO_NOT_CARE,
AMVP_BEST_BANDWIDTH,
AMVP_INPUT_SAME_AS_OUTPUT
} AMVP_SELECT_FORMAT_BY;

Elements

AMVP_DO_NOT_CARE

Format doesn't matter.

AMVP_BEST_BANDWIDTH

Use the largest bandwidth.

AMVP_INPUT_SAME_AS_OUTPUT

Use the same input format as output format.

See Also

  • DirectShow Enumerated Types


AnalogVideoStandard Enumeration

The AnalogVideoStandard enumeration specifies the format of an analog television signal.

Syntax

typedef enum tagAnalogVideoStandard {
    AnalogVideo_None       = 0x00000000
    AnalogVideo_NTSC_M     = 0x00000001,
    AnalogVideo_NTSC_M_J   = 0x00000002,
    AnalogVideo_NTSC_433   = 0x00000004,
    AnalogVideo_PAL_B      = 0x00000010,
    AnalogVideo_PAL_D      = 0x00000020,
    AnalogVideo_PAL_H      = 0x00000080,
    AnalogVideo_PAL_I      = 0x00000100,
    AnalogVideo_PAL_M      = 0x00000200,
    AnalogVideo_PAL_N      = 0x00000400,
    AnalogVideo_PAL_60     = 0x00000800,
    AnalogVideo_SECAM_B    = 0x00001000,
    AnalogVideo_SECAM_D    = 0x00002000,
    AnalogVideo_SECAM_G    = 0x00004000,
    AnalogVideo_SECAM_H    = 0x00008000,
    AnalogVideo_SECAM_K    = 0x00010000,
    AnalogVideo_SECAM_K1   = 0x00020000,
    AnalogVideo_SECAM_L    = 0x00040000,
    AnalogVideo_SECAM_L1   = 0x00080000,
    AnalogVideo_PAL_N_COMBO = 0x00100000
} AnalogVideoStandard;

Elements

AnalogVideo_None

Digital sensor

AnalogVideo_NTSC_M

NTSC (M) standard, 7.5 IRE black

AnalogVideo_NTSC_M_J

NTSC (M) standard, 0 IRE black (Japan)

AnalogVideo_NTSC_433

NTSC-433

AnalogVideo_PAL_B

PAL-B standard

AnalogVideo_PAL_D

PAL (D) standard

AnalogVideo_PAL_H

PAL (H) standard

AnalogVideo_PAL_I

PAL (I) standard

AnalogVideo_PAL_M

PAL (M) standard

AnalogVideo_PAL_N

PAL (N) standard

AnalogVideo_PAL_60

PAL-60 standard

AnalogVideo_SECAM_B

SECAM (B) standard

AnalogVideo_SECAM_D

SECAM (D) standard

AnalogVideo_SECAM_G

SECAM (G) standard

AnalogVideo_SECAM_H

SECAM (H) standard

AnalogVideo_SECAM_K

SECAM (K) standard

AnalogVideo_SECAM_K1

SECAM (K1) standard

AnalogVideo_SECAM_L

SECAM (L) standard

AnalogVideo_SECAM_L1

SECAM (L1) standard

AnalogVideo_PAL_N_COMBO

Combination (N) PAL standard (Argentina)

See Also

  • DirectShow Enumerated Types


CameraControlFlags Enumeration

The CameraControlFlags enumeration indicates whether a particular camera setting is controlled manually or automatically.

Syntax

typedef enum{
    CameraControl_Flags_Auto   = 0x0001,
    CameraControl_Flags_Manual = 0x0002
} CameraControlFlags;

Elements

CameraControl_Flags_Auto

Indicates that the setting is controlled automatically.

CameraControl_Flags_Manual

Indicates that the setting is controlled manually.

See Also

  • DirectShow Enumerated Types
  • IAMCameraControl Interface


CameraControlProperty Enumeration

The CameraControlProperty enumeration specifies a setting on a camera.

Syntax

typedef enum {
    CameraControl_Pan = 1,
    CameraControl_Tilt,
    CameraControl_Roll,
    CameraControl_Zoom,
    CameraControl_Exposure,
    CameraControl_Iris,
    CameraControl_Focus
} CameraControlProperty;

Elements

CameraControl_Pan

Specifies the camera's pan setting, in degrees. Values range from –180 to +180, with the default set to zero. Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), and negative values are counterclockwise from the origin.

CameraControl_Tilt

Specifies the camera's tilt setting, in degrees. Values range from –180 to +180, with the default set to zero. Positive values point the imaging plane up, and negative values point the imaging plane down.

CameraControl_Roll

Specifies the camera's roll setting, in degrees. Values range from –180 to +180, with the default set to zero. Positive values cause a clockwise rotation of the camera along the image-viewing axis, and negative values cause a counterclockwise rotation of the camera.

CameraControl_Zoom

Specifies the camera's zoom setting, in millimeters. Values range from 10 to 600, and the default is specific to the device.

CameraControl_Exposure

Specifies the exposure setting, in log base 2 seconds. In other words, for values less than zero, the exposure time is 1/2n seconds, and for values zero or above, the exposure time is 2n seconds. For example:

Value | Seconds
-3 | 1/8
-2 | 1/4
-1 | 1/2
0 | 1
1 | 2
2 | 4

CameraControl_Iris

Specifies the camera's iris setting, in units of fstop * 10.

CameraControl_Focus

Specifies the camera's focus setting, as the distance to the optimally focused target, in millimeters. The range and default value are specific to the device.

Remarks

For a given property, a particular device might implement only a subset of the listed range.

See Also

  • DirectShow Enumerated Types
  • IAMCameraControl Interface


CompressionCaps Enumeration

Indicates video compression capabilities.

Syntax

typedef enum {
    CompressionCaps_CanQuality  = 0x01,
    CompressionCaps_CanCrunch   = 0x02,
    CompressionCaps_CanKeyFrame = 0x04,
    CompressionCaps_CanBFrame   = 0x08,
    CompressionCaps_CanWindow   = 0x10
} CompressionCaps;

Elements

CompressionCaps_CanQuality

Video compressor supports the IAMVideoCompression::put_Quality and IAMVideoCompression::get_Quality methods.

CompressionCaps_CanCrunch

Video compressor can compress video to a specified data rate. If the compressor has this capability then the output pins media type will contain the data rate in the VIDEOINFOHEADER structure's dwBitRate member. The only way to set the data rate is to set dwBitRate.

CompressionCaps_CanKeyFrame

Video compressor supports the IAMVideoCompression::put_KeyFrameRate and IAMVideoCompression::get_KeyFrameRate methods.

CompressionCaps_CanBFrame

Video compressor supports the IAMVideoCompression::put_PFramesPerKeyFrame and IAMVideoCompression::get_PFramesPerKeyFrame methods.

CompressionCaps_CanWindow

Video compressor supports the IAMVideoCompression::put_WindowSize and IAMVideoCompression::get_WindowSize methods.

See Also

  • IAMVideoCompression Interface
  • DirectShow Enumerated Types


DECIMATION_USAGE Enumeration

Describes the strategy that the Overlay Mixer Filter filter uses to scale the video image down to a smaller size.

Syntax

typedef enum {
    DECIMATION_LEGACY,
    DECIMATION_USE_DECODER_ONLY,
    DECIMATION_USE_VIDEOPORT_ONLY,
    DECIMATION_USE_OVERLAY_ONLY,
    DECIMATION_DEFAULT
} DECIMATION_USAGE;

Elements

DECIMATION_LEGACY

Decimate the video by taking the following steps, in the order listed, until one of them succeeds.

  1. Try to use the overlay scaler on the VGA chip.
  2. If the Overlay Mixer is connected through a video port, try to use the scaler on the video port.
  3. Crop the video image.

DECIMATION_USE_DECODER_ONLY

Decimate using the scaler on the video decoder. If that fails, crop the video image.

DECIMATION_USE_VIDEOPORT_ONLY

Decimate using the scaler on the video port. If that fails, crop the video image.

DECIMATION_USE_OVERLAY_ONLY

Decimate using the overlay scaler on the VGA chip. If that fails, crop the video image.

DECIMATION_DEFAULT

Decimate the video by taking the following steps, in the order listed, until one of them succeeds.

  1. Try to use the scaler on the video decoder.
  2. Try to use the overlay scaler on the VGA chip.
  3. If the Overlay Mixer is connected through a video port, try to use the scaler on the video port.
  4. Crop the video image.

    This mode is the default decimation strategy.

See Also

  • IAMVideoDecimationProperties
  • DirectShow Enumerated Types


DVD_AUDIO_APPMODE Enumeration

Indicates the current audio mode as retrieved in a call to IDvdInfo2::GetAudioAttributes.

Syntax

typedef enum tagDVD_AUDIO_APPMODE
{
    DVD_AudioMode_None     = 0,
    DVD_AudioMode_Karaoke  = 1,
    DVD_AudioMode_Surround = 2,
    DVD_AudioMode_Other    = 3,
} DVD_AUDIO_APPMODE;

Elements

DVD_AudioMode_None

No special audio mode. The DVD Navigator Filter will send the audio to the decoder with no special processing.

DVD_AudioMode_Karaoke

The current audio mode is karaoke content.

DVD_AudioMode_Surround

The current audio mode is surround sound.

DVD_AudioMode_Other

Unrecognized audio mode.

See Also

  • DirectShow Enumerated Types


DVD_AUDIO_FORMAT Enumeration

Indicates the audio format of a DVD.

Syntax

typedef enum tagDVD_AUDIO_FORMAT {
    DVD_AudioFormat_AC3       = 0,
    DVD_AudioFormat_MPEG1     = 1,
    DVD_AudioFormat_MPEG1_DRC = 2,
    DVD_AudioFormat_MPEG2     = 3,
    DVD_AudioFormat_MPEG2_DRC = 4,
    DVD_AudioFormat_LPCM      = 5,
    DVD_AudioFormat_DTS       = 6,
    DVD_AudioFormat_SDDS      = 7,
    DVD_AudioFormat_Other     = 8
} DVD_AUDIO_FORMAT;

Elements

DVD_AudioFormat_AC3

Audio format is Dolby AC-3.

DVD_AudioFormat_MPEG1

Audio format is MPEG-1.

DVD_AudioFormat_MPEG1_DRC

Audio format is MPEG-1 with dynamic range control.

DVD_AudioFormat_MPEG2

Audio format is MPEG-2.

DVD_AudioFormat_MPEG2_DRC

Audio format is MPEG-2 with dynamic range control.

DVD_AudioFormat_LPCM

Audio format is Linear Pulse Code Modulated (LPCM).

DVD_AudioFormat_DTS

Audio format is Digital Theater Systems (DTS).

DVD_AudioFormat_SDDS

Audio format is Sony Dynamic Digital Sound (SDDS).

DVD_AudioFormat_Other

Audio format is unrecognized.

Remarks

This enumeration is a member of the DVD_AudioAttributes structure.

See Also

  • DirectShow Enumerated Types


DVD_AUDIO_LANG_EXT Enumeration

Defines flags that indicate whether an audio stream contains audio language extensions.

Syntax

typedef enum tagDVD_AUDIO_LANG_EXT {
    DVD_AUD_EXT_NotSpecified        = 0,
    DVD_AUD_EXT_Captions            = 1,
    DVD_AUD_EXT_VisuallyImpaired    = 2,
    DVD_AUD_EXT_DirectorComments1   = 3,
    DVD_AUD_EXT_DirectorComments2   = 4
} DVD_AUDIO_LANG_EXT;

Elements

DVD_AUD_EXT_NotSpecified

The DVD doesn't specify an audio language extension for this audio stream.

DVD_AUD_EXT_Captions

The audio stream contains captions.

DVD_AUD_EXT_VisuallyImpaired

The audio stream contains content for people with low vision.

DVD_AUD_EXT_DirectorComments1

The audio stream contains "director comments 1."

DVD_AUD_EXT_DirectorComments2

The audio stream contains "director comments 2."

Remarks

This enumeration is used in the IDvdInfo2::GetAudioAttributes and IDvdInfo2::GetDefaultAudioLanguage methods.

See Also

  • DirectShow Enumerated Types


DVD_CMD_FLAGS Enumeration

Defines flags that control how the DVD Navigator Filter filter handles command synchronization.

Syntax

typedef enum {
    DVD_CMD_FLAG_None          = 0x00000000,
    DVD_CMD_FLAG_Flush         = 0x00000001,
    DVD_CMD_FLAG_SendEvents    = 0x00000002,
    DVD_CMD_FLAG_Block         = 0x00000004,
    DVD_CMD_FLAG_StartWhenRendered  = 0x00000008,
    DVD_CMD_FLAG_EndAfterRendered   = 0x00000010
} DVD_CMD_FLAGS;

Elements

DVD_CMD_FLAG_None

Tells the DVD Navigator not to flush the buffers when new commands are issued, not to send any events, and not to block the thread of execution on any method call.

DVD_CMD_FLAG_Flush

Tells the DVD Navigator, when it receives a new command such as IDvdControl2::PlayTitle or IDvdControl2::PlayForwards, to discard the approximately two seconds of video currently in the buffer and create an instance of the new command immediately.

DVD_CMD_FLAG_SendEvents

Tells the DVD Navigator to send events to the application when asynchronous operations are complete. The event parameters will contain the return value of the operation.

DVD_CMD_FLAG_Block

Tells the DVD Navigator to block on asynchronous operations until the operation completes or is canceled.

DVD_CMD_FLAG_StartWhenRendered

Currently unused.

DVD_CMD_FLAG_EndAfterRendered

Used with certain functions to cause the DVD Navigator to block until the specified action is actually being rendered. For example, when used with IDvdControl2::PlayChaptersAutoStop, this flag will cause the DVD Navigator to block until the specified chapters have all played. When used with IDvdControl2::SelectSubpictureStream, the flag will cause the Navigator to block until the new subpicture is actually appearing on the rendered display. Used with these functions: IDvdControl2::PlayChaptersAutoStop, IDvdControl2::PlayPeriodInTitleAutoStop, IDvdControl2::SelectSubpictureStream, and IDvdControl2::SetSubpictureState.

See Also

  • DirectShow Enumerated Types


DVD_DISC_SIDE Enumeration

Indicates the sides of a DVD disc.

Syntax

typedef enum tagDVD_DISC_SIDE {
    DVD_SIDE_A,
    DVD_SIDE_B
} DVD_DISC_SIDE;

Elements

DVD_SIDE_A

Side A.

DVD_SIDE_B

Side B.

Elements

This enumeration is used in the IDvdInfo2::GetDVDVolumeInfo method.

See Also

  • DirectShow Enumerated Types


DVD_DOMAIN Enumeration

Defines the DVD domains.

Syntax

typedef enum tagDVD_DOMAIN {
    DVD_DOMAIN_FirstPlay,
    DVD_DOMAIN_VideoManagerMenu,
    DVD_DOMAIN_VideoTitleSetMenu,
    DVD_DOMAIN_Title,
    DVD_DOMAIN_Stop
} DVD_DOMAIN;

Elements

DVD_DOMAIN_FirstPlay

Performing default initialization of a DVD disc.

DVD_DOMAIN_VideoManagerMenu

Displaying menus for whole disc.

DVD_DOMAIN_VideoTitleSetMenu

Displaying menus for current title set.

DVD_DOMAIN_Title

Displaying the current title.

DVD_DOMAIN_Stop

The DVD Navigator is in the DVD Stop domain.

Remarks

This enumeration is used in the IDvdInfo2::GetCurrentDomain method.

A domain is a logical space on a DVD disc. When the DVD Navigator is displaying the disc's main menu, it is said to be in the Video Manager domain. When it is displaying a menu specific to a title, it is in the Video Title Set domain. When it is playing video, it is the Title domain. When the user issues a Stop command, the Navigator goes into the Stop domain.

See Also

  • DirectShow Enumerated Types


DVD_ERROR Enumeration

Specifies DVD error conditions.

Syntax

typedef enum _tagDVD_ERROR {
    DVD_ERROR_Unexpected                          = 1,
    DVD_ERROR_CopyProtectFail                     = 2,
    DVD_ERROR_InvalidDVD1_0Disc                   = 3,
    DVD_ERROR_InvalidDiscRegion                   = 4,
    DVD_ERROR_LowParentalLevel                    = 5,
    DVD_ERROR_MacrovisionFail                     = 6,
    DVD_ERROR_IncompatibleSystemAndDecoderRegions = 7,
    DVD_ERROR_IncompatibleDiscAndDecoderRegions   = 8
} DVD_ERROR;

Elements

DVD_ERROR_Unexpected

Something unexpected happened; perhaps content is authored incorrectly. Playback is stopped.

DVD_ERROR_CopyProtectFail

Key exchange for DVD copy protection failed. Playback is stopped.

DVD_ERROR_InvalidDVD1_0Disc

DVD-Video disc is authored incorrectly for specification version 1.x. Playback is stopped.

DVD_ERROR_InvalidDiscRegion

DVD-Video disc cannot be played because the disc is not authored to play in the system region. Whis this value is returned in the lParam1 of the EC_DVD_ERROR event, lParam2 contains the disc region and the system region. See EC_DVD_ERROR for more information. You can try fixing the region mismatch by changing the system region with Dvdrgn.exe.

DVD_ERROR_LowParentalLevel

Player parental level is lower than the lowest parental level available in the DVD content. Playback is stopped.

DVD_ERROR_MacrovisionFail

Macrovision® distribution failed. Playback stopped.

DVD_ERROR_IncompatibleSystemAndDecoderRegions

No discs can be played because the system region does not match the decoder region.

DVD_ERROR_IncompatibleDiscAndDecoderRegions

The disc cannot be played because the disc is not authored to be played in the decoder's region.

Remarks

See Also

  • DVD Region Change Support in Windows
  • DirectShow Enumerated Types


DVD_FRAMERATE Enumeration

Indicates whether the DVD is authored to play at 25 or 30 frames per second.

Syntax

typedef enum tagDVD_FRAMERATE
{
    DVD_FPS_25 = 1,
    DVD_FPS_30NonDrop = 3
} DVD_FRAMERATE;

Elements

DVD_FPS_25

Twenty-five frames per second.

DVD_FPS_30NonDrop

Exactly 30 frames per second.

Remarks

You must know the frame rate to interpret the frame count as time.

See Also

  • DirectShow Enumerated Types


DVD_KARAOKE_ASSIGNMENT Enumeration

Defines the speaker configuration for an audio stream.

Syntax

typedef enum tagDVD_KARAOKE_ASSIGNMENT {
    DVD_Assignment_reserved0   = 0,
    DVD_Assignment_reserved1   = 1,
    DVD_Assignment_LR    = 2,
    DVD_Assignment_LRM   = 3,
    DVD_Assignment_LR1   = 4,
    DVD_Assignment_LRM1  = 5,
    DVD_Assignment_LR12  = 6,
    DVD_Assignment_LRM12 = 7
} DVD_KARAOKE_ASSIGNMENT;

Elements

DVD_Assignment_reserved0

Reserved.

DVD_Assignment_reserved1

Reserved.

DVD_Assignment_LR

The stream is assigned to the left and right speakers.

DVD_Assignment_LRM

The stream is assigned to the left, right, and middle speakers.

DVD_Assignment_LR1

The stream is assigned to the left, right, and audio1 speakers.

DVD_Assignment_LRM1

The stream is assigned to the left, right, middle, and audio1 speakers.

DVD_Assignment_LR12

The stream is assigned to the left, right, and audio2 speakers.

DVD_Assignment_LRM12

The stream is assigned to the left, right, middle, and audio2 speakers.

Remarks

All channels within a stream will use the same speaker configuration, although the channels can be sent to different speakers within this configuration.

See Also

  • DirectShow Enumerated Types
  • DVD_KaraokeAttributes Structure


DVD_KARAOKE_CONTENTS Enumeration

Specifies flags that, when used in a bitwise OR operation, describe the contents of each channel of an audio stream in a karaoke title.

Syntax

typedef enum tagDVD_KARAOKE_CONTENTS {
    DVD_Karaoke_GuideVocal1  = 0x0001,
    DVD_Karaoke_GuideVocal2  = 0x0002,
    DVD_Karaoke_GuideMelody1 = 0x0004,
    DVD_Karaoke_GuideMelody2 = 0x0008,
    DVD_Karaoke_GuideMelodyA = 0x0010,
    DVD_Karaoke_GuideMelodyB = 0x0020,
    DVD_Karaoke_SoundEffectA = 0x0040,
    DVD_Karaoke_SoundEffectB = 0x0080
} DVD_KARAOKE_CONTENTS;

Elements

DVD_Karaoke_GuideVocal1

The channel contains guide vocal 1.

DVD_Karaoke_GuideVocal2

The channel contains guide vocal 2.

DVD_Karaoke_GuideMelody1

The channel contains guide melody 1.

DVD_Karaoke_GuideMelody2

The channel contains guide melody 2.

DVD_Karaoke_GuideMelodyA

The channel contains guide melody A.

DVD_Karaoke_GuideMelodyB

The channel contains guide melody B.

DVD_Karaoke_SoundEffectA

The channel contains sound effect A.

DVD_Karaoke_SoundEffectB

The channel contains sound effect B.

Remarks

This enumeration is used in the DVD_KaraokeAttributes structure.

See Also

  • DirectShow Enumerated Types


DVD_KARAOKE_DOWNMIX Enumeration

Defines flags used by the IDvdControl2::SelectKaraokeAudioPresentationMode method to control which speakers, if any, each auxiliary channel is downmixed to.

Syntax

typedef enum tagDVD_KARAOKE_DOWNMIX {
    DVD_Mix_0to0 = 0x0001,
    DVD_Mix_1to0 = 0x0002,
    DVD_Mix_2to0 = 0x0004,
    DVD_Mix_3to0 = 0x0008,
    DVD_Mix_4to0 = 0x0010,
    DVD_Mix_Lto0 = 0x0020,
    DVD_Mix_Rto0 = 0x0040,

    DVD_Mix_0to1 = 0x0100,
    DVD_Mix_1to1 = 0x0200,
    DVD_Mix_2to1 = 0x0400,
    DVD_Mix_3to1 = 0x0800,
    DVD_Mix_4to1 = 0x1000,
    DVD_Mix_Lto1 = 0x2000,
    DVD_Mix_Rto1 = 0x4000,
} DVD_KARAOKE_DOWNMIX;

Elements

DVD_Mix_0to0

Unused. Reserved for future use.

DVD_Mix_1to0

Unused. Reserved for future use.

DVD_Mix_2to0

Downmix channel 2 to the left speaker.

DVD_Mix_3to0

Downmix channel 3 to the left speaker.

DVD_Mix_4to0

Downmix channel 4 to the left speaker.

DVD_Mix_Lto0

Unused. Reserved for future use.

DVD_Mix_Rto0

Unused. Reserved for future use.

DVD_Mix_0to1

Unused. Reserved for future use.

DVD_Mix_1to1

Unused. Reserved for future use.

DVD_Mix_2to1

Downmix channel 2 to the right speaker.

DVD_Mix_3to1

Downmix channel 3 to the right speaker.

DVD_Mix_4to1

Downmix channel 4 to the right speaker.

DVD_Mix_Lto1

Unused. Reserved for future use.

DVD_Mix_Rto1

Unused. Reserved for future use.

Remarks

Audio channels are zero-based, so channels 2 through 4 are the three auxiliary karaoke channels. Use bitwise OR operations to set the appropriate bit to send a channel to the left speaker (0), right speaker (1), both speakers, or to no speakers by turning both bits off. These bits are all off by default whenever the DVD Navigator Filter filter enters karaoke mode.

See Also

  • DirectShow Enumerated Types


DVD_MENU_ID Enumeration

Specifies the DVD menu in a call to IDvdControl2::ShowMenu.

Syntax

typedef enum tagDVD_MENU_ID {
    DVD_MENU_Title      = 2,
    DVD_MENU_Root       = 3,
    DVD_MENU_Subpicture = 4,
    DVD_MENU_Audio      = 5,
    DVD_MENU_Angle      = 6,
    DVD_MENU_Chapter    = 7
} DVD_MENU_ID;

Elements

DVD_MENU_Title

Specifies the top menu in a DVD-Video volume. This menu is also known as the Title Menu or Video Manager Menu and it provides access to all VTS (Video Title Set) menus on the disc.

DVD_MENU_Root

Specifies the root menu for a VTS.

DVD_MENU_Subpicture

Specifies the subpicture submenu in a VTS menu.

DVD_MENU_Audio

Specifies the audio submenu in a VTS menu.

DVD_MENU_Angle

Specifies the angle submenu in a VTS menu.

DVD_MENU_Chapter

Choose a chapter submenu in a VTS menu.

Remarks

The root menu always provides a means of getting to the subpicture, audio, angle and chapter menus if they exist.

See Also

  • DirectShow Enumerated Types


DVD_OPTION_FLAG Enumeration

The DVD_OPTION_FLAG enumeration type defines flags that control the behavior of the DVD Navigator Filter.

Syntax

typedef enum {
    DVD_ResetOnStop               = 1,
    DVD_NotifyParentalLevelChange = 2,
    DVD_HMSF_TimeCodeEvents       = 3,
    DVD_AudioDuringFFwdRew        = 4
} DVD_OPTION_FLAG;

Elements

DVD_ResetOnStop

If this flag is TRUE, the DVD Navigator enters the DVD Stop domain when the filter graph stops. When playback resumes, it starts at the beginning of the disc. This is the default behavior.

If this flag is FALSE, the DVD Navigator does not enter the DVD Stop domain when the filter graph stops. When the filter graph starts again, playback resumes from the point where it stopeed.

The default behavior is not always desirable, because the filter graph might be stopped unexpectedly. This can happen, for example, if the screen resolution changes, a screen saver starts, or the computer goes into suspended mode. In these situations, the user probably wants playback to restart from the same point. Typically, the application should set this flag to FALSE immediately before or after calling IMediaControl::Run. It should set the flag to TRUE before calling IMediaControl::Stop in resoponse to an explicit user to command to stop playback.

DVD_NotifyParentalLevelChange

This flag indicates whether the DVD Navigator notifies the application when the parental level changes on this disc.

When this flag is TRUE, if the DVD Navigator reaches a temporary parental management level command, it sends the application an EC_DVD_PARENTAL_LEVEL_CHANGE event. It blocks playback until it the application responds by calling IDvdControl2::AcceptParentalLevelChange.

If this flag is FALSE, when the DVD Navigator encounters a temporary parental management level command and the current parental level is too low, the Navigator automatically rejects the command and branches to whatever path the disc specifies. The Navigator sends an EC_DVD_PARENTAL_LEVEL_CHANGE event indicating the required level. The application can stop playback, put up a password dialog box, and restart playback so that it can succeed on the next attempt.

The default value for this flag is FALSE.

DVD_HMSF_TimeCodeEvents

If this flag is TRUE, the DVD Navigator sends all timecode information using the DVD_HMSF_TIMECODE structure instead of the old binary coded decimal (BCD) format, which is defined in the DVD_TIMECODE structure. The DVD_HMSF_TIMECODE format is easier to work with, but this flag defaults to FALSE for backward compatibility.

DVD_AudioDuringFFwdRew

If this flag is TRUE, the DVD Navigator enables audio during fast forward and rewind, as long as the audio rate does not exceed the maximum rate of the audio decoder. If this flag is FALSE, the Navigator disables audio during fast forward and rewind. The default value of this flag is FALSE.

You can also enable audio during fast forward and rewind by creating the following key in the Windows Registry:

DWORD HKLM\Software\Microsoft\DVDNavigator\AudioDuringFFwdRev = 1

This has the same effect as setting the DVD_AudioDuringFFwdRew flag to TRUE.

Remarks

The following table lists the default values for these flags.

Flag | Default value
DVD_ResetOnStop | TRUE
DVD_NotifyParentalLevelChange | FALSE
DVD_HMSF_TimeCodeEvents | FALSE
DVD_AudioDuringFFwdRew | FALSE

See Also

  • DirectShow Enumerated Types
  • IDvdControl2::SetOption


DVD_PARENTAL_LEVEL Enumeration

Identifies flags for the generic parental levels defined in the DVD specification.

Syntax

typedef enum tagDVD_PARENTAL_LEVEL {
    DVD_PARENTAL_LEVEL_8 = 0x8000,
    DVD_PARENTAL_LEVEL_7 = 0x4000,
    DVD_PARENTAL_LEVEL_6 = 0x2000,
    DVD_PARENTAL_LEVEL_5 = 0x1000,
    DVD_PARENTAL_LEVEL_4 = 0x0800,
    DVD_PARENTAL_LEVEL_3 = 0x0400,
    DVD_PARENTAL_LEVEL_2 = 0x0200,
    DVD_PARENTAL_LEVEL_1 = 0x0100
} DVD_PARENTAL_LEVEL;

Remarks

DVD_PARENTAL_LEVEL_8 is the most restrictive level and DVD_PARENTAL_LEVEL_1 is the least restrictive. The way in which the levels are interpreted or used varies from country/region to country/region. In the United States and Canada, the levels correspond to the Motion Picture Association of America (MPAA) rating levels as shown in the following table.

Parental level | Meaning
1 | The rating is G, General.
3 | The rating is PG, Parental Guidance Suggested.
4 | The rating is PG-13, Parental Guidance Suggested, not recommended for those under 13.
6 | The rating is R, Restricted.
7 | The rating is NC-17.

This enumeration is used in the IDvdInfo2::GetTitleParentalLevels method.

See Also

  • DirectShow Enumerated Types


DVD_PREFERRED_DISPLAY_MODE Enumeration

Indicates the user's preferred window aspect ratio and conversion method.

Syntax

typedef enum tagDVD_PREFERRED_DISPLAY_MODE {
    DISPLAY_CONTENT_DEFAULT = 0,
    DISPLAY_16x9 = 1,
    DISPLAY_4x3_PANSCAN_PREFERRED = 2,
    DISPLAY_4x3_LETTERBOX_PREFERRED = 3
} DVD_PREFERRED_DISPLAY_MODE;

Elements

DISPLAY_CONTENT_DEFAULT

Use the default window size and content type.

DISPLAY_16x9

Use a 16 x 9 window.

DISPLAY_4x3_PANSCAN_PREFERRED

Use a 4 x 3 window and convert to pan-scan, if possible.

DISPLAY_4x3_LETTERBOX_PREFERRED

Use a 4 x 3 window and convert to letterbox, if possible.

Remarks

DVD_PREFERRED_DISPLAY_MODE indicates the user's preferred window aspect ratio and preferred method of conversion of 16 x 9 content to a 4 x 3 window aspect ratio. Pan-scan and letterboxing are the two conversion methods. Displaying a video at the largest possible size inside the display window without any cropping or stretching is called displaying in letterbox format. Pan-scan is specifically cropping a 16 x 9 video for display in a 4 x 3 window using parameters defined by the video author.

This enumerated type indicates a preference of conversion mechanisms because some content can only be displayed using one of these methods. Content that is 4 x 3 is always converted to a 16 x 9 window by using sideboxing, where black bars are added to the right and left sides of the display instead of the top and bottom of the display as in the 16 x 9 to 4 x 3 conversion using letterboxing.

The following table shows the conversion method used between the actual content type listed in the first column, and the user display preference setting, indicated by one of the other columns.

Actual content type | 16 x 9 | 4 x 3 pan-scan | 4 x 3 letterbox
4 x 3 | Sideboxing | None | None
16 x 9 letterbox only | None | Letterbox | Letterbox
16 x 9 pan-scan only | None | Pan-scan | Pan-scan
16 x 9 pan-scan or letterbox | None | Pan-scan | Letterbox

The native window size used is always the user's preferred size.

See Also

  • DirectShow Enumerated Types


DVD_RELATIVE_BUTTON Enumeration

Identifies the four directional buttons used for DVD menu navigation and other operations.

Syntax

typedef enum tagDVD_RELATIVE_BUTTON {
    DVD_Relative_Upper = 1,
    DVD_Relative_Lower = 2,
    DVD_Relative_Left =  3,
    DVD_Relative_Rightt = 4
    } DVD_RELATIVE_BUTTON;

Elements

DVD_Relative_Upper

Upper button.

DVD_Relative_Lower

Lower button.

DVD_Relative_Left

Left button.

DVD_Relative_Right

Right button.

See Also

  • DirectShow Enumerated Types


DVD_SUBPICTURE_LANG_EXT Enumeration

Defines the possible language extensions in a specified subpicture stream.

Syntax

typedef enum tagDVD_SUBPICTURE_LANG_EXT {
    DVD_SP_EXT_NotSpecified     = 0,
    DVD_SP_EXT_Caption_Normal   = 1,
    DVD_SP_EXT_Caption_Big      = 2,
    DVD_SP_EXT_Caption_Children = 3,
    DVD_SP_EXT_CC_Normal        = 5,
    DVD_SP_EXT_CC_Big           = 6,
    DVD_SP_EXT_CC_Children      = 7,
    DVD_SP_EXT_Forced           = 9,
    DVD_SP_EXT_DirectorComments_Normal   =13,
    DVD_SP_EXT_DirectorComments_Big      =14,
    DVD_SP_EXT_DirectorComments_Children =15,
} DVD_SUBPICTURE_LANG_EXT;

Elements

DVD_SP_EXT_NotSpecified

Indicates that no language extensions are present.

DVD_SP_EXT_Caption_Normal

Indicates that the specified stream contains normal captions.

DVD_SP_EXT_Caption_Big

Indicates that the specified stream contains big captions.

DVD_SP_EXT_Caption_Children

Indicates that the specified stream contains captions for children.

DVD_SP_EXT_CC_Normal

Indicates that the specified stream contains normal closed captions.

DVD_SP_EXT_CC_Big

Indicates that the specified stream contains big closed captions.

DVD_SP_EXT_CC_Children

Indicates that the specified stream contains closed captions for children.

DVD_SP_EXT_Forced

Indicates that the subpicture stream is forcedly activated, meaning that the application will not be able to turn it off.

DVD_SP_EXT_DirectorComments_Normal

Indicates that the specified stream contains normal-sized director's comments.

DVD_SP_EXT_DirectorComments_Big

Indicates that the specified stream contains large-sized director's comments.

DVD_SP_EXT_DirectorComments_Children

Indicates that the specified stream contains director's comments for children.

See Also

  • DirectShow Enumerated Types


DVD_SUBPICTURE_TYPE Enumeration

Defines flags used to determine what kind of content the subpicture stream contains.

Syntax

typedef enum tagDVD_SUBPICTURE_TYPE
{
    DVD_SPType_NotSpecified = 0,
    DVD_SPType_Language     = 1,
    DVD_SPType_Other        = 2,
} DVD_SUBPICTURE_TYPE;

Elements

DVD_SPType_NotSpecified

The DVD does not specify the subpicture type.

DVD_SPType_Language

The subpicture contains language-related content such as movie subtitles or other text.

DVD_SPType_Other

The subpicture contains nonlanguage-related content such as a bouncing ball in karaoke titles.

See Also

  • DirectShow Enumerated Types


DVD_SUBPICTURE_CODING Enumeration

Indicates what kind of content the subpicture stream contains.

Syntax

typedef enum tagDVD_SUBPICTURE_CODING
{
    DVD_SPCoding_RunLength    = 0,
    DVD_SPCoding_Extended     = 1,
    DVD_SPCoding_Other        = 2,
} DVD_SUBPICTURE_CODING;

Elements

DVD_SPCoding_RunLength

Indicates that the subpicture uses run length encoding.

DVD_SPCoding_Extended

Indicates that subpicture uses extended encoding.

DVD_SPCoding_Other

Indicates that the subpicture uses some other encoding scheme.

Remarks

Most subpicture streams contain language-related content such as movie subtitles, but subpictures can also be used for the bouncing ball in karaoke or other non-language-related purposes.

See Also

  • DirectShow Enumerated Types


DVD_TextCharSet Enumeration

Defines which character set a specified string is encoded with.

Syntax

enum DVD_TextCharSet {
    DVD_CharSet_Unicode                       = 0,
    DVD_CharSet_ISO646                        = 1,
    DVD_CharSet_JIS_Roman_Kanji               = 2,
    DVD_CharSet_ISO8859_1                     = 3,
    DVD_CharSet_ShiftJIS_Kanji_Roman_Katakana = 4
};

Elements

DVD_CharSet_Unicode

Unicode™ character set.

DVD_CharSet_ISO646

ISO 646 character set.

DVD_CharSet_JIS_Roman_Kanji

JIS Roman Kanji character set.

DVD_CharSet_ISO8859_1

ISO 8859-1 character set.

DVD_CharSet_ShiftJIS_Kanji_Roman_Katakana

JIS Kanji-Roman-Katakana character set.

See Also

  • DirectShow Enumerated Types


DVD_TextStringType Enumeration

Defines a subset of the DVD text string types.

Syntax

enum DVD_TextStringType {
    // Disc structure identifiers (0x00..0x0f)
    // These are empty strings whose string type
    // is used to organize the content strings.
    DVD_Struct_Volume               = 0x01,
    DVD_Struct_Title                = 0x02,
    DVD_Struct_ParentalID           = 0x03,
    DVD_Struct_PartOfTitle          = 0x04,
    DVD_Struct_Cell                 = 0x05,
    // Stream (0x10..0x1f)
    DVD_Stream_Audio                = 0x10,
    DVD_Stream_Subpicture           = 0x11,
    DVD_Stream_Angle                = 0x12,
    // Channel in stream (0x20..0x2f)
    DVD_Channel_Audio               = 0x20,

    // Application information
    // General (0x30..0x37)
    // This is used to identify the name
    // for the current node, that is, volume title,
    // movie title, song title, and so on.
    DVD_General_Name                = 0x30,
    DVD_General_Comments            = 0x31,

    // Title (0x38..0x3f)
    DVD_Title_Series                = 0x38,
    DVD_Title_Movie                 = 0x39,
    DVD_Title_Video                 = 0x3a,
    DVD_Title_Album                 = 0x3b,
    DVD_Title_Song                  = 0x3c,
    DVD_Title_Other                 = 0x3f,

    // Title (sub) (0x40..0x47)
    DVD_Title_Sub_Series            = 0x40,
    DVD_Title_Sub_Movie             = 0x41,
    DVD_Title_Sub_Video             = 0x42,
    DVD_Title_Sub_Album             = 0x43,
    DVD_Title_Sub_Song              = 0x44,
    DVD_Title_Sub_Other             = 0x47,

    // Title (original) (0x48..0x4f)
    DVD_Title_Orig_Series           = 0x48,
    DVD_Title_Orig_Movie            = 0x49,
    DVD_Title_Orig_Video            = 0x4a,
    DVD_Title_Orig_Album            = 0x4b,
    DVD_Title_Orig_Song             = 0x4c,
    DVD_Title_Orig_Other            = 0x4f,

    // Other info (0x50..0x57)
    DVD_Other_Scene                 = 0x50,
    DVD_Other_Cut                   = 0x51,
    DVD_Other_Take                  = 0x52,

    //These less-used categories are defined in
    //the DVD specification but not in the
    //DVD_TextStringType enumeration.
    // Language     0x58..0x5b
    // Work         0x5c..0x6b
    // Character    0x6c..0x8f
    // Data         0x90..0x93
    // Karaoke      0x94..0x9b
    // Category     0x9c..0x9f
    // Lyrics       0xa0..0xa3
    // Document     0xa4..0xa7
    // Others       0xa8..0xab
    // Reserved     0xac..0xaf
    // Admin        0xb0..0xb7
    // more admin   0xb8..0xc0
    // Reserved     0xd0..0xdf
    // vendor       0xe0..0xef
    // extension    0xf0..0xf7
    // reserved     0xf8..0xff
};

Elements

DVD_Struct_Volume

Indicates the top-level of the logical hierarchy. Refers to the entire contents of a one-sided disc or one side of a two-sided disc.

DVD_Struct_Title

Indicates that all content strings, until the next DVD_Struct_Title, belong to one title.

DVD_Struct_ParentalID

Indicates the parental ID of the following strings.

DVD_Struct_PartOfTitle

Indicates that all content strings, until the next DVD_Struct_PartOfTitle, belong to one chapter.

DVD_Struct_Cell

Indicates that all content strings, until the next DVD_Struct_Cell, belong to one cell, which can be a scene from a chapter.

DVD_Stream_Audio

Indicates that the following content strings refer to the audio stream.

DVD_Stream_Subpicture

Indicates that the following content strings refer to the subpicture stream.

DVD_Stream_Angle

Indicates that the following content strings refer to the angle.

DVD_Channel_Audio

Indicates that the following content strings refer to the audio channel.

DVD_General_Name

Indicates the most important content string. Strings of this type contain the name of the volume, title, chapter, and so on, and can follow any structure identifiers.

DVD_General_Comments

Identifies a content string with additional information about the title, chapter, and so on, described by the DVD_General_Name string. The exact nature or structure of these comments is not defined.

DVD_Title_Series

Identifies a content string containing the name of a series to which the title belongs.

DVD_Title_Movie

Identifies a content string with the main movie title.

DVD_Title_Video

Identifies a content string containing the name of the video title.

DVD_Title_Album

Identifies a content string containing the name of the album title.

DVD_Title_Song

Identifies a content string containing the name of the song title.

DVD_Title_Other

Identifies a content string containing the name of the title of some other genre.

DVD_Title_Sub_Series

Identifies a content string with the name of the series localized to a particular country/region.

DVD_Title_Sub_Movie

Identifies a content string with the movie title localized to a particular country/region.

DVD_Title_Sub_Video

Identifies a content string with the video title localized to a particular country/region.

DVD_Title_Sub_Album

Identifies a content string with the album title localized to a particular country/region.

DVD_Title_Sub_Song

Identifies a content string with the song title localized to a particular country/region.

DVD_Title_Sub_Other

Identifies a content string with the title of some other genre localized to a particular country/region.

DVD_Title_Orig_Series

Identifies a content string with the original name of the series.

DVD_Title_Orig_Movie

Identifies a content string with the original name of the movie.

DVD_Title_Orig_Video

Identifies a content string with the original name of the video.

DVD_Title_Orig_Album

Identifies a content string with the original name of the album.

DVD_Title_Orig_Song

Identifies a content string with the original name of the song.

DVD_Title_Orig_Other

Identifies a content string with the original name of the content.

DVD_Other_Scene

Identifies a content string pertaining to a particular scene in a movie or video.

DVD_Other_Cut

Identifies a content string pertaining to a particular cut in a movie or video.

DVD_Other_Take

Identifies a content string pertaining to a particular take in a movie or video.

Remarks

A DVD_TextStringType is returned in the IDvdInfo2::GetDVDTextStringAsUnicode and IDvdInfo2::GetDVDTextStringAsNative methods to identify how the disc authors have categorized the specified text string. See Working with DVD Text Strings for general information on text strings.

One important text string type not defined in this enumeration is 0xF0, the extension sorting text string type. You can use this type of string in many ways to enable players to sort the string data. It can be a unique number or a repetition of a previous string with the word order changed. For example, a string type of 0x30 that has the name "The Greatest Hits" might be followed by a string of type 0xF0 that says "Greatest Hits, The." As with content strings, the use of the sorting string is not strictly defined.

See Also

  • DirectShow Enumerated Types


DVD_TIMECODE_FLAGS Enumeration

Indicates the frame rate at which a DVD has been authored to play.

Syntax

typedef enum tagDVD_TIMECODE_FLAGS {
    DVD_TC_FLAG_25fps         = 0x00000001,
    DVD_TC_FLAG_30fps         = 0x00000002,
    DVD_TC_FLAG_DropFrame     = 0x00000004,
    DVD_TC_FLAG_Interpolated  = 0x00000008,
} DVD_TIMECODE_FLAGS;

Elements

DVD_TC_FLAG_25fps

Disc is authored to play at 25 frames per second.

DVD_TC_FLAG_30fps

Disc is authored to play at 30 frames per second.

DVD_TC_FLAG_DropFrame

Disc is authored to play at 29.97 frames per second.

DVD_TC_FLAG_Interpolated

Value representing the DVD Navigator Filter filter's best estimate of the disc's frame rate.

See Also

  • DirectShow Enumerated Types


DVD_TITLE_APPMODE Enumeration

Indicates whether a DVD title is a karaoke title. This enumeration is a member of the DVD_TitleAttributes structure, which is filled when an application calls the IDvdInfo2::GetTitleAttributes method.

Syntax

typedef enum tagDVD_TITLE_APPMODE
{
    DVD_AppMode_Not_Specified = 0,
    DVD_AppMode_Karaoke  = 1,
    DVD_AppMode_Other    = 3,
} DVD_TITLE_APPMODE;

Elements

DVD_AppMode_Not_Specified

The disc does not provide any application mode information about this title.

DVD_AppMode_Karaoke

Title contains karaoke content.

DVD_AppMode_Other

Title contains a type of content that the DVD Navigator Filter does not recognize, so the application should treat the title as a regular DVD-Video title.

Remarks

When the DVD Navigator encounters a karaoke title on a disc, it goes into "karaoke mode" and informs the audio decoder. The decoder must respond by initially muting the three auxiliary channels. Applications can then selectively control the volume and mixing configuration of these channels using the karaoke-related methods in the IDvdControl2 interface For more information, see Playing Karaoke Audio Streams.

See Also

  • DirectShow Enumerated Types


DVD_VIDEO_COMPRESSION Enumeration

Defines the possible DVD video compression types.

Syntax

typedef enum tagDVD_VIDEO_COMPRESSION
{
    DVD_VideoCompression_Other  = 0,
    DVD_VideoCompression_MPEG1  = 1,
    DVD_VideoCompression_MPEG2  = 2,
} DVD_VIDEO_COMPRESSION;

Elements

DVD_VideoCompression_Other

Unrecognized compression type.

DVD_VideoCompression_MPEG1

MPEG-1 compression type.

DVD_VideoCompression_MPEG2

MPEG-2 compression type.

Remarks

This enumeration is a member of the DVD_VideoAttributes structure, which is filled by a call to the IDvdInfo2::GetCurrentVideoAttributes method.

See Also

  • DirectShow Enumerated Types


DVD_WARNING Enumeration

Specifies DVD warning conditions.

Syntax

typedef enum _tagDVD_WARNING {
    DVD_WARNING_InvalidDVD1_0Disc=1,
    DVD_WARNING_FormatNotSupported=2,
    DVD_WARNING_IllegalNavCommand=3,
    DVD_WARNING_Open = 4,
    DVD_WARNING_Seek = 5,
    DVD_WARNING_Read = 6
} DVD_WARNING;

Elements

DVD_WARNING_InvalidDVD1_0Disc

DVD-Video disc is authored incorrectly. Playback can continue, but unexpected behavior might occur.

DVD_WARNING_FormatNotSupported

A decoder would not support the current format. Playback of a stream (audio, video or subpicture) might not function. lParam2 of the EC_DVD_WARNING event notification code contains the stream type (see AM_DVD_STREAM_FLAGS).

DVD_WARNING_IllegalNavCommand

The internal DVD navigation command processor attempted to process an illegal command.

DVD_WARNING_Open

File Open failed.

DVD_WARNING_Seek

File Seek failed.

DVD_WARNING_Read

File Read failed.

See Also

  • DirectShow Enumerated Types


DVDECODERRESOLUTION Enumeration

Indicates the digital video (DV) decoding resolution.

Syntax

enum _DVDECODERRESOLUTION {
    DVDECODERRESOLUTION_720x480     = 1000,
    DVDECODERRESOLUTION_360x240     = 1001,
    DVDECODERRESOLUTION_180x120     = 1002,
    DVDECODERRESOLUTION_88x60       = 1003
};

enum _DVRESOLUTION {
    DVRESOLUTION_FULL    = 1000,
    DVRESOLUTION_HALF    = 1001,
    DVRESOLUTION_QUARTER = 1002,
    DVRESOLUTION_DC      = 1003
};

Elements

DVRESOLUTION_FULL

Decode at full size.

DVRESOLUTION_HALF

Decode at half size.

DVRESOLUTION_QUARTER

Decode at quarter size.

DVRESOLUTION_DC

Decode at one-eighth size.

Remarks

The DVDECODERRESOLUTION and DVRESOLUTION enumerations are equivalent; DVDECODERRESOLUTION is included for compatibility with existing applications.

The decoding resolution depends on whether the current format is NTSC or PAL:

Enumeration | NTSC | PAL
DVRESOLUTION_FULL | 720 x 480 | 720 x 576
DVRESOLUTION_HALF | 360 x 240 | 360 x 288
DVRESOLUTION_QUARTER | 180 x 120 | 180 x 144
DVRESOLUTION_DC | 88 x 60 | 88 x 72

See Also

  • IIPDVDec Interface
  • DirectShow Enumerated Types


DVENCODERFORMAT Enumeration

Indicates the digital video (DV) format.

Syntax

enum _DVENCODERFORMAT {
    DVENCODERFORMAT_DVSD        =   2007,
    DVENCODERFORMAT_DVHD        =   2008,
    DVENCODERFORMAT_DVSL        =   2009
};

Elements

DVENCODERFORMAT_DVSD

Use the 'dvsd' stream handler.

DVENCODERFORMAT_DVHD

Use the 'dvhd' stream handler.

DVENCODERFORMAT_DVSL

Use the 'dvsl' stream handler.

Remarks

This enumeration specifies the fccType member of the AVI stream header. For more information, see DV Data in the AVI File Format.

See Also

  • IDVEnc Interface
  • DirectShow Enumerated Types


DVENCODERRESOLUTION Enumeration

Indicates the digital video (DV) encoding resolution.

Syntax

enum _DVENCODERRESOLUTION {
    DVENCODERRESOLUTION_720x480     =   2012,
    DVENCODERRESOLUTION_360x240     =   2013,
    DVENCODERRESOLUTION_180x120     =   2014,
    DVENCODERRESOLUTION_88x60       =   2015
};

Elements

The meaning of the enumeration elements depends on whether the current format is NTSC or PAL:

Element | NTSC | PAL
DVENCODERRESOLUTION_720x480 | 720 x 480 | 720 x 576
DVENCODERRESOLUTION_360x240 | 360 x 240 | 360 x 288
DVENCODERRESOLUTION_180x120 | 180 x 120 | 180 x 144
DVENCODERRESOLUTION_88x60 | 88 x 66 | 88 x 72

See Also

  • IDVEnc Interface
  • DirectShow Enumerated Types


DVENCODERVIDEOFORMAT Enumeration

Indicates the video standard (NTSC or PAL) for digital video (DV) encoding.

Syntax

enum _DVENCODERVIDEOFORMAT {
    DVENCODERVIDEOFORMAT_NTSC = 2000,
    DVENCODERVIDEOFORMAT_PAL  = 2001
};

Elements

DVENCODERVIDEOFORMAT_NTSC

National Television Standards Committee (NTSC)

DVENCODERVIDEOFORMAT_PAL

Phase Alternating Line (PAL)

See Also

  • IDVEnc Interface
  • DirectShow Enumerated Types


FILTER_STATE Enumeration

Specifies a filter's state or the state of the filter graph.

Syntax

typedef enum _FilterState
{
    State_Stopped,
    State_Paused,
    State_Running
} FILTER_STATE;

Elements

State_Stopped

Stopped. The filter is not processing data.

State_Paused

Paused. The filter is processing data, but not rendering it.

State_Running

Running. The filter is processing and rendering data.

See Also

  • DirectShow Enumerated Types
  • IMediaFilter::GetState
  • IMediaControl::GetState
  • Data Flow in the Filter Graph


InterleavingMode Enumeration

Specifies how video frames and audio samples will be written to disk.

Syntax

typedef enum {
    INTERLEAVE_NONE,
    INTERLEAVE_CAPTURE,
    INTERLEAVE_FULL,
    INTERLEAVE_NONE_BUFFERED
} InterleavingMode;

Elements

INTERLEAVE_NONE

Noninterleaved. Frames are written in the order they arrive. Files must be interleaved for playback at a later time. In this mode, the AVI Mux filter attempts to use unbuffered, overlapped write operations, to increase throughput.

INTERLEAVE_CAPTURE

Approximate interleaving with less overhead than INTERLEAVE_FULL. This mode is suitable for video capture. The AVI Mux attempts to use unbuffered, overlapped write operations. Unless the interleaving parameters are configured properly, however, frames may be dropped if one stream blocks while it waits for data from another stream. In particular, audio buffers should be less than .5 second, or else the video stream will block for excessive periods of time.

INTERLEAVE_FULL

Full, precise interleaving of audio samples and video frames. Streams will block indefinitely, waiting for equal amounts of data before interleaving. This mode is suitable for authoring and playback.

INTERLEAVE_NONE_BUFFERED

Noninterleaved. This mode is equivalent to INTERLEAVE_NONE but uses less file space and system overhead.

See Also

  • DirectShow Enumerated Types


MEDIA_SAMPLE_CONTENT Enumeration

Describes the contents of an elementary stream within an MPEG-2 transport stream. This enumeration is used in the IMPEG2PIDMap interface, which is implemented on the output pins of the MPEG-2 Demultiplexer.

Syntax

typedef enum {
    MEDIA_TRANSPORT_PACKET,
    MEDIA_ELEMENTARY_STREAM,
    MEDIA_MPEG2_PSI,
    MEDIA_TRANSPORT_PAYLOAD
} MEDIA_SAMPLE_CONTENT ;

Members

MEDIA_TRANSPORT_PACKET

Specifies a complete transport stream packet to be passed through without processing.

MEDIA_ELEMENTARY_STREAM

Specifies an audio or video PES payload.

MEDIA_MPEG2_PSI

Specifies a PAT, PMT, CAT, or Private data stream. These are complete PSI sections which do not need to be reassembled.

MEDIA_TRANSPORT_PAYLOAD

Specifies gathered TS packet payloads, such as PES packets.

See Also

  • DirectShow Enumerated Types


PhysicalConnectorType Enumeration

Specifies the physical type of pin (audio or video).

Syntax

typedef enum
{
    PhysConn_Video_Tuner = 1,
    PhysConn_Video_Composite,
    PhysConn_Video_SVideo,
    PhysConn_Video_RGB,
    PhysConn_Video_YRYBY,
    PhysConn_Video_SerialDigital,
    PhysConn_Video_ParallelDigital,
    PhysConn_Video_SCSI,
    PhysConn_Video_AUX,
    PhysConn_Video_1394,
    PhysConn_Video_USB,
    PhysConn_Video_VideoDecoder,
    PhysConn_Video_VideoEncoder,
    PhysConn_Video_SCART,

    PhysConn_Audio_Tuner = 4096,
    PhysConn_Audio_Line,
    PhysConn_Audio_Mic,
    PhysConn_Audio_AESDigital,
    PhysConn_Audio_SPDIFDigital,
    PhysConn_Audio_SCSI,
    PhysConn_Audio_AUX,
    PhysConn_Audio_1394,
    PhysConn_Audio_USB,
    PhysConn_Audio_AudioDecoder,
} PhysicalConnectorType;

Elements

PhysConn_Video_Tuner

Specifies a tuner pin for video.

PhysConn_Video_Composite

Specifies a composite pin for video.

PhysConn_Video_SVideo

Specifies an S-Video (Y/C video) pin.

PhysConn_Video_RGB

Specifies an RGB pin for video.

PhysConn_Video_YRYBY

Specifies a YRYBY (Y, R–Y, B–Y) pin for video.

PhysConn_Video_SerialDigital

Specifies a serial digital pin for video.

PhysConn_Video_ParallelDigital

Specifies a parallel digital pin for video.

PhysConn_Video_SCSI

Specifies a SCSI (Small Computer System Interface) pin for video.

PhysConn_Video_AUX

Specifies an AUX (auxiliary) pin for video.

PhysConn_Video_1394

Specifies an IEEE 1394 pin for video.

PhysConn_Video_USB

Specifies a USB (Universal Serial Bus) pin for video.

PhysConn_Video_VideoDecoder

Specifies a video decoder pin.

PhysConn_Video_VideoEncoder

Specifies a video encoder pin.

PhysConn_Video_SCART

Specifies a SCART (Peritel) pin for video.

PhysConn_Audio_Tuner

Specifies a tuner pin for audio.

PhysConn_Audio_Line

Specifies a line pin for audio.

PhysConn_Audio_Mic

Specifies a microphone pin.

PhysConn_Audio_AESDigital

Specifies an AES/EBU (Audio Engineering Society/European Broadcast Union) digital pin for audio.

PhysConn_Audio_SPDIFDigital

Specifies an S/PDIF (Sony/Philips Digital Interface Format) digital pin for audio.

PhysConn_Audio_SCSI

Specifies a SCSI pin for audio.

PhysConn_Audio_AUX

Specifies an AUX pin for audio.

PhysConn_Audio_1394

Specifies an IEEE 1394 pin for audio.

PhysConn_Audio_USB

Specifies a USB pin for audio.

PhysConn_Audio_AudioDecoder

Specifies an audio decoder pin.

See Also

  • DirectShow Enumerated Types


PIN_DIRECTION Enumeration

Indicates a pin's direction.

Syntax

typedef enum _PinDirection {
    PINDIR_INPUT,
    PINDIR_OUTPUT
} PIN_DIRECTION;

Elements

PINDIR_INPUT

Input pin.

PINDIR_OUTPUT

Output pin.

See Also

  • DirectShow Enumerated Types


QualityMessageType Enumeration

Describes a quality message type.

Syntax

typedef enum {
    Famine,
    Flood
} QualityMessageType;

Elements

Famine

Downstream filter needs more data.

Flood

Downstream filter needs less data.

See Also

  • DirectShow Enumerated Types


REG_PINFLAG Enumeration

Defines flags for the dwFlags member in the REGFILTERPINS2 structure.

Syntax

enum
{
    REG_PINFLAG_B_ZERO     = 0x1,
    REG_PINFLAG_B_RENDERER = 0x2,
    REG_PINFLAG_B_MANY     = 0x4,
    REG_PINFLAG_B_OUTPUT   = 0x8
} REG_PINFLAG;

Elements

REG_PINFLAG_B_ZERO

The filter can have zero instances of this pin.

REG_PINFLAG_B_RENDERER

The filter renders the input from this pin. (Applies only to input pins. Output pins must not set this flag.)

REG_PINFLAG_B_MANY

The filter can create more than one instance of this pin.

REG_PINFLAG_B_OUTPUT

This pin is an output pin.

See Also

  • DirectShow Enumerated Types


REM_FILTER_FLAGS Enumeration

Specifies how to remove a filter from the filter graph.

Syntax

enum _REM_FILTER_FLAGS {
    REMFILTERF_LEAVECONNECTED = 0x00000001
};

Elements

REMFILTERF_LEAVECONNECTED

Leave the filter connected. By default, filters are disconnected when removed from the graph.

See Also

  • IGraphConfig::RemoveFilterEx

See Also

  • DirectShow Enumerated Types


SNDDEV_ERR Enumeration

Specifies how the audio device was being accessed when the failure occurred.

Syntax

typedef enum _tagSND_DEVICE_ERROR {
    SNDDEV_ERROR_Open             = 1,
    SNDDEV_ERROR_Close            = 2,
    SNDDEV_ERROR_GetCaps          = 3,
    SNDDEV_ERROR_PrepareHeader    = 4,
    SNDDEV_ERROR_UnprepareHeader  = 5,
    SNDDEV_ERROR_Reset            = 6,
    SNDDEV_ERROR_Restart          = 7,
    SNDDEV_ERROR_GetPosition      = 8,
    SNDDEV_ERROR_Write            = 9,
    SNDDEV_ERROR_Pause            = 10,
    SNDDEV_ERROR_Stop             = 11,
    SNDDEV_ERROR_Start            = 12,
    SNDDEV_ERROR_AddBuffer        = 13,
    SNDDEV_ERROR_Query            = 14,
} SNDDEV_ERR;

Elements

SNDDEV_ERROR_Open

The audio device attempted to open.

SNDDEV_ERROR_Close

The audio device attempted to close.

SNDDEV_ERROR_GetCaps

The capabilities of the underlying hardware were being retrieved.

SNDDEV_ERROR_PrepareHeader

The header for the audio device was being prepared.

SNDDEV_ERROR_UnprepareHeader

The header for the audio device was being unprepared.

SNDDEV_ERROR_Reset

The audio device attempted to reset.

SNDDEV_ERROR_Restart

The audio device attempted to restart.

SNDDEV_ERROR_GetPosition

The current and stop position settings were being retrieved.

SNDDEV_ERROR_Write

The audio device was being written to.

SNDDEV_ERROR_Pause

The audio device attempted to pause.

SNDDEV_ERROR_Stop

The audio device attempted to stop.

SNDDEV_ERROR_Start

The audio device attempted to start.

SNDDEV_ERROR_AddBuffer

A buffer was being added to the audio device.

SNDDEV_ERROR_Query

The audio device was being queried.

See Also

  • DirectShow Enumerated Types


TunerInputType Enumeration

Specifies the frequency of a TV tuner (cable or antenna).

Syntax

typedef enum {
    TunerInputCable,
    TunerInputAntenna
} TunerInputType;

Elements

TunerInputCable

Indicates cable frequency.

TunerInputAntenna

Indicates broadcast antenna frequency.

See Also

  • DirectShow Enumerated Types


TVAudioMode Enumeration

Specifies the mode of a TV audio control.

Syntax

typedef enum tagTVAudioMode {
    AMTVAUDIO_MODE_MONO   = 0x0001,
    AMTVAUDIO_MODE_STEREO = 0x0002,
    AMTVAUDIO_MODE_LANG_A = 0x0010,
    AMTVAUDIO_MODE_LANG_B = 0x0020,
    AMTVAUDIO_MODE_LANG_C = 0x0040,
} TVAudioMode;

Elements

AMTVAUDIO_MODE_MONO

Specifies the audio is in mono.

AMTVAUDIO_MODE_STEREO

Specifies the audio is in stereo.

AMTVAUDIO_MODE_LANG_A

Specifies the audio is an additional language. See Remarks.

AMTVAUDIO_MODE_LANG_B

Specifies the audio is an additional language. See Remarks.

AMTVAUDIO_MODE_LANG_C

Specifies the audio is an additional language. See Remarks.

Remarks

When using bilingual TV Audio in a specific country/region the elements are defined as follows.

Elements | Description
AMTVAUDIO_MODE_LANG_A | Main multilingual audio program.
AMTVAUDIO_MODE_LANG_B | Secondary multilingual audio program.
AMTVAUDIO_MODE_LANG_C | Either a third language, or the main multilingual audio program plus the secondary multilingual audio program. For example, use this element to get English from one speaker and Japanese from the other speaker.

See Also

  • DirectShow Enumerated Types


VALID_UOP_FLAG Enumeration

Indicates which user operation (UOP) commands are currently allowed by the DVD.

Syntax

typedef enum {
    UOP_FLAG_Play_Title_Or_AtTime           = 0x00000001,
    UOP_FLAG_Play_Chapter                   = 0x00000002,
    UOP_FLAG_Play_Title                     = 0x00000004,
    UOP_FLAG_Stop                           = 0x00000008,
    UOP_FLAG_ReturnFromSubMenu              = 0x00000010,
    UOP_FLAG_Play_Chapter_Or_AtTime         = 0x00000020,
    UOP_FLAG_PlayPrev_Or_Replay_Chapter     = 0x00000040,
    UOP_FLAG_PlayNext_Chapter               = 0x00000080,
    UOP_FLAG_Play_Forwards                  = 0x00000100,
    UOP_FLAG_Play_Backwards                 = 0x00000200,
    UOP_FLAG_ShowMenu_Title                 = 0x00000400,
    UOP_FLAG_ShowMenu_Root                  = 0x00000800,
    UOP_FLAG_ShowMenu_SubPic                = 0x00001000,
    UOP_FLAG_ShowMenu_Audio                 = 0x00002000,
    UOP_FLAG_ShowMenu_Angle                 = 0x00004000,
    UOP_FLAG_ShowMenu_Chapter               = 0x00008000,
    UOP_FLAG_Resume                         = 0x00010000,
    UOP_FLAG_Select_Or_Activate_Button      = 0x00020000,
    UOP_FLAG_Still_Off                      = 0x00040000,
    UOP_FLAG_Pause_On                       = 0x00080000,
    UOP_FLAG_Select_Audio_Stream            = 0x00100000,
    UOP_FLAG_Select_SubPic_Stream           = 0x00200000,
    UOP_FLAG_Select_Angle                   = 0x00400000,
    UOP_FLAG_Select_Karaoke_Audio_Presentation_Mode = 0x00800000,
    UOP_FLAG_Select_Video_Mode_Preference   = 0x01000000
} VALID_UOP_FLAG ;

Elements

UOP_FLAG_Play_Title_Or_AtTime

Annex J command name: Title_Or_Time_Play

UOP_FLAG_Play_Chapter

Annex J command name: Chapter_Search_Or_Play

UOP_FLAG_Play_Title

Annex J command name: Title_Play

UOP_FLAG_Stop

Annex J command name: Stop

UOP_FLAG_ReturnFromSubMenu

Annex J command name: GoUp

UOP_FLAG_ReturnFromSubMenu

Annex J command name: Time_Or_Chapter_Search

UOP_FLAG_PlayPrev_Or_Replay_Chapter

Annex J command name: Prev_Or_Top_PG_Search

UOP_FLAG_PlayNext_Chapter

Annex J command name: Next_PG_Search

UOP_FLAG_Play_Forwards

Annex J command name: Forward_Scan

UOP_FLAG_Play_Backwards

Annex J command name: Backward_Scan

UOP_FLAG_ShowMenu_Title

Annex J command name: Title_Menu_Call

UOP_FLAG_ShowMenu_Root

Annex J command name: Root_Menu_Call

UOP_FLAG_ShowMenu_SubPic

Annex J command name: SubPic_Menu_Call

UOP_FLAG_ShowMenu_Audio

Annex J command name: Audio_Menu_Call

UOP_FLAG_ShowMenu_Angle

Annex J command name: Angle_Menu_Call

UOP_FLAG_ShowMenu_Chapter

Annex J command name: Chapter_Menu_Call

UOP_FLAG_Resume

Annex J command name: Resume

UOP_FLAG_Select_Or_Activate_Button

Annex J command name: Button_Select_Or_Activate

UOP_FLAG_Still_Off

Annex J command name: Still_Off

UOP_FLAG_Pause_On

Annex J command name: Pause_On

UOP_FLAG_Select_Audio_Stream

Annex J command name: Audio_Stream_Change

UOP_FLAG_Select_SubPic_Stream

Annex J command name: SubPic_Stream_Change

UOP_FLAG_Select_Angle

Annex J command name: Angle_Change

UOP_FLAG_Select_Karaoke_Audio_Presentation_Mode

Annex J command name: Karaoke_Audio_Pres_Mode_Change

UOP_FLAG_Select_Video_Mode_Preference

Annex J command name: Video_Pres_Mode_Change

See Also

  • DirectShow Enumerated Types
  • IDvdInfo2::GetCurrentUOPS


VfwCaptureDialogs Enumeration

Specifies a dialog box that might exist in a Video for Windows capture driver.

Syntax

 typedef enum {
    VfwCaptureDialog_Source  = 0x01,
    VfwCaptureDialog_Format  = 0x02,
    VfwCaptureDialog_Display = 0x04
} VfwCaptureDialogs;

Elements

VfwCaptureDialog_Source

Video source dialog box.

VfwCaptureDialog_Format

Video format dialog box.

VfwCaptureDialog_Display

Video display dialog box.

See Also

  • DirectShow Enumerated Types
  • IAMVfwCaptureDialogs Interface


VfwCompressDialogs Enumeration

Specifies a dialog box that might exist in a Video for Windows compression (codec) driver.

Syntax

typedef enum {
    VfwCompressDialog_Config      = 0x01,
    VfwCompressDialog_About       = 0x02,
    VfwCompressDialog_QueryConfig = 0x04,
    VfwCompressDialog_QueryAbout  = 0x08
} VfwCompressDialogs;

Elements

VfwCompressDialog_Config

Configure dialog box.

VfwCompressDialog_About

About dialog box.

VfwCompressDialog_QueryConfig

Specifies whether the Configure dialog box is available.

VfwCompressDialog_QueryAbout

Specifies whether the About dialog box is available.

See Also

  • DirectShow Enumerated Types
  • IAMVfwCaptureDialogs Interface


VideoControlFlags Enumeration

Specifies the video mode of operation for a video device.

Syntax

typedef enum tagVideoControlFlags
{
    VideoControlFlag_FlipHorizontal        = 0x0001,
    VideoControlFlag_FlipVertical          = 0x0002,
    VideoControlFlag_ExternalTriggerEnable = 0x0004,
    VideoControlFlag_Trigger               = 0x0008
} VideoControlFlags;

Elements

VideoControlFlag_FlipHorizontal

Specifies that the picture is flipped horizontally.

VideoControlFlag_FlipVertical

Specifies that the picture is flipped vertically.

VideoControlFlag_ExternalTriggerEnable

Sets up a stream to capture a trigger from an external source, for example, a push button on a camera. Buffers can be queued to the driver but will not be passed up from the WDM capture driver (for compression, display, or writing to a file) until the external event happens. See Remarks.

VideoControlFlag_Trigger

In software, simulates an external trigger when the stream has the VideoControlFlag_ExternalTriggerEnable flag set.

Remarks

The IAMVideoControl interface uses this enumerated data type.

Multiple capture buffers are queued to a capture driver and are filled at a fixed rate once the stream is put into the "run" state. If the VideoControlFlag_ExternalTriggerEnable flag is set, a filled buffer is not passed up from the WDM capture driver for compression, display, or writing to a file until the external event happens.

See Also

  • DirectShow Enumerated Types


VIDEOENCODER_BITRATE_MODE Enumeration

The VIDEOENCODER_BITRATE_MODE enumeration type defines the three types of bitrates supported by the IEncoderAPI interface.

Syntax

typedef enum VIDEOENCODER_BITRATE_MODE {
  ConstantBitRate = 0,
  VariableBitRateAverage,
  VariableBitRatePeak
};

Members

ConstantBitRate

Indicates that the bit rate used for encoding is constant.

VariableBitRateAverage

Indicates that the bit rate used for encoding is variable with the specified bitrate used as a guaranteed average over a specified window. The default window size is considered to be five minutes.

VariableBitRatePeak

Specifies that the ENCAPIPARAM_BITRATE value is the expected (not guaranteed) average bit rate over a given time period and that the ENCAPIPARAM_PEAK_BITRATE value is the peak which the bit rate must not exceed. The default window size is considered to be 500ms (which is traditionally equal to one GOP).

See Also

  • IEncoderAPI Interface


VideoProcAmpFlags Enumeration

The VideoProcAmpFlags enumeration indicates whether a particular video property is controlled manually or automatically.

Syntax

typedef enum tagVideoProcAmpFlags {
VideoProcAmp_Flags_Auto   = 0x0001,
VideoProcAmp_Flags_Manual = 0x0002,
} VideoProcAmpFlags;

Elements

VideoProcAmp_Flags_Auto

Indicates that the property is controlled manually.

VideoProcAmp_Flags_Manual

Indicates that the property is controlled automatically.

See Also

  • DirectShow Enumerated Types
  • IAMVideoProcAmp Interface


VideoProcAmpProperty Enumeration

The VideoProcAmpProperty enumeration specifies video properties on a video capture device.

Syntax

typedef enum tagVideoProcAmpProperty
{
    VideoProcAmp_Brightness,
    VideoProcAmp_Contrast,
    VideoProcAmp_Hue,
    VideoProcAmp_Saturation,
    VideoProcAmp_Sharpness,
    VideoProcAmp_Gamma,
    VideoProcAmp_ColorEnable,
    VideoProcAmp_WhiteBalance,
    VideoProcAmp_BacklightCompensation,
    VideoProcAmp_Gain
} VideoProcAmpProperty;

Elements

VideoProcAmp_Brightness

Specifies the brightness, also called the black level. For NTSC, the value is expressed in IRE units * 100. For non-NTSC sources, the units are arbitrary, with zero representing blanking and 10,000 representing pure white. Values range from –10,000 to 10,000.

VideoProcAmp_Contrast

Specifies the contrast, expressed as gain factor * 100. Values range from zero to 10,000.

VideoProcAmp_Hue

Specifies the hue, in degrees * 100. Values range from -180,000 to 180,000 (-180 to +180 degrees).

VideoProcAmp_Saturation

Specifies the saturation. Values range from 0 to 10,000.

VideoProcAmp_Sharpness

Specifies the sharpness. Values range from 0 to 100.

VideoProcAmp_Gamma

Specifies the gamma, as gamma * 100. Values range from 1 to 500.

VideoProcAmp_ColorEnable

Specifies the color enable setting. The possible values are 0 (off) and 1 (on).

VideoProcAmp_WhiteBalance

Specifies the white balance, as a color temperature in degrees Kelvin. The range of values depends on the device.

VideoProcAmp_BacklightCompensation

Specifies the backlight compensation setting. Possible values are 0 (off) and 1 (on).

VideoProcAmp_Gain

Specifies the gain adjustment. Zero is normal. Positive values are brighter and negative values are darker. The range of values depends on the device.

See Also

  • DirectShow Enumerated Types
  • IAMVideoProcAmp


VMR_ASPECT_RATIO_MODE Enumeration

The VMR_ASPECT_RATIO_MODE enumeration type describes whether the Video Mixing Renderer preserves the aspect ratio of the source video.

Requirements

Requires Microsoft® Windows® XP.

Syntax

enum VMR_ASPECT_RATIO_MODE{
  VMR_ARMODE_NONE,
  VMR_ARMODE_LETTER_BOX
};

Elements

VMR_ARMODE_NONE

Indicates that the VMR will not try to maintain the aspect ratio of the source video.

VMR_ARMODE_LETTER_BOX

Indicates that the VMR will maintain the aspect ratio of the source video by letterboxing within the output rectangle.

See Also

  • DirectShow Enumerated Types
  • IVMRAspectRatioControl Interface
  • IVMRWindowlessControl Interface


VMR9_SampleFormat Enumeration

The VMR9_SampleFormat enumeration type describes the interlacing of a video stream.

Syntax

typedef enum _VMR9_SampleFormat {
    VMR9_SampleReserved                  = 1,
    VMR9_SampleProgressiveFrame          = 2,
    VMR9_SampleFieldInterleavedEvenFirst = 3,
    VMR9_SampleFieldInterleavedOddFirst  = 4,
    VMR9_SampleFieldSingleEven           = 5,
    VMR9_SampleFieldSingleOdd            = 6
} VMR9_SampleFormat;

Members

VMR9_SampleReserved

Reserved; do not use.

VMR9_SampleProgressiveFrame

Progressive frame; no interleaving

VMR9_SampleFieldInterleavedEvenFirst

Each sample contains two interleaved fields, with the even field first.

VMR9_SampleFieldInterleavedOddFirst

Each sample contains two interleaved fields, with the odd field first.

VMR9_SampleFieldSingleEven

The sample contains a single field, and each line in the sample corresponds to the even lines in a deinterlaced frame. That is, lines 0, 1, 2,... in the sample correspond to lines 0, 2, 4,... in the deinterlaced frame. The missing lines must be constructed when the frame is deinterlaced.

VMR9_SampleFieldSingleOdd

The sample contains a single field, and each line in the sample corresponds to the odd lines in a de-interlaced frame.

See Also

  • DirectShow Enumerated Types


VMR9AlphaBitmapFlags Enumeration

The VMR9AlphaBitmapFlags enumeration type defines the possible values for the dwFlags member of the VMR9AlphaBitmap structure.

Syntax

typedef enum VMR9AlphaBitmapFlags{
  VMR9AlphaBitmap_Disable  = 0x00000001,
  VMR9AlphaBitmap_hDC  = 0x00000002,
  VMR9AlphaBitmap_EntireDDS  = 0x00000004,
  VMR9AlphaBitmap_SrcColorKey  = 0x00000008,
  VMR9AlphaBitmap_SrcRect  = 0x00000010,
  VMR9AlphaBitmap_FilterMode  = 0x00000020
};

Members

VMR9AlphaBitmap_Disable

Disable the alpha bitmap.

VMR9AlphaBitmap_hDC

Take the bitmap from the HDC rather than the Direct3D surface.

VMR9AlphaBitmap_EntireDDS

Take the entire Direct3D surface. The rSrc member of the VMR9AlphaBitmap structure is ignored.

VMR9AlphaBitmap_SrcColorKey

Indicates that the srcClrKey member is valid and should be used when blending.

VMR9AlphaBitmap_SrcRect

Indicates that the rSrc member is valid and specifies a sub-rectangle of the original image to be blended. This flag is only valid for the IVMRMixerBitmap9::UpdateAlphaBitmapParameters method; it enables the application to create "image strips." For the IVMRMixerBitmap9::SetAlphaBitmap method, rSrc must refer to the entire bitmap.

VMR9AlphaBitmap_FilterMode

Indicates that the dwFilterMode member is valid and should be used to overide the VMR filter's default filtering method.

See Also

  • DirectShow Enumerated Types


VMR9AspectRatioMode Enumeration

The VMR9AspectRatioMode enumeration type is used with the IVMRWindowlessControl9::GetAspectRatioMode and IVMRWindowlessControl9::SetAspectRatioMode methods to set and retrieve the aspect ratio mode (VMR-9 only).

Syntax

typedef enum {
  VMR9ARMode_None,
  VMR9ARMode_LetterBox
} VMR9AspectRatioMode;

Members

VMR9ARMode_None

Indicates that the VMR is not attempting to maintain the aspect ratio of the source video.

VMR9ARMode_LetterBox

Indicates that the VMR will maintain the aspect ratio of the source video by letterboxing within the output rectangle.

See Also

  • DirectShow Enumerated Types


VMR9DeinterlacePrefs Enumeration

The VMR9DeinterlacePrefs enumeration type describes the deinterlacing method that the Video Mixing Renderer Filter 9 (VMR-9) uses if the method set by the application cannot be used.

Syntax

typedef enum {
    DeinterlacePref9_NextBest = 0x01,
    DeinterlacePref9_BOB      = 0x02,
    DeinterlacePref9_Weave    = 0x04,
    DeinterlacePref9_Mask     = 0x07
} VMR9DeinterlacePrefs;

Elements

DeinterlacePref9_NextBest

Use the next best mode offered by the driver.

DeinterlacePref9_BOB

Use the bob method.

DeinterlacePref9_Weave

Use the weave method (that is, no deinterlacing).

DeinterlacePref9_Mask

Bitwise OR of the previous flags. This value is used internally by the VMR, and is not a valid flag.

See Also

  • DirectShow Enumerated Types
  • IVMRDeinterlaceControl9 Interface


VMR9DeinterlaceTech Enumeration

The VMR9DeinterlaceTech enumeration type describes the algorithm used for deinterlacing a video stream. The flags are not mutually exclusive; drivers can set a combination of flags.

Syntax

typedef enum {
    DeinterlaceTech9_Unknown             = 0x0000,
    DeinterlaceTech9_BOBLineReplicate    = 0x0001,
    DeinterlaceTech9_BOBVerticalStretch  = 0x0002,
    DeinterlaceTech9_MedianFiltering     = 0x0004,
    DeinterlaceTech9_EdgeFiltering       = 0x0010,
    DeinterlaceTech9_FieldAdaptive       = 0x0020,
    DeinterlaceTech9_PixelAdaptive       = 0x0040,
    DeinterlaceTech9_MotionVectorSteered = 0x0080
} VMR9DeinterlacePrefs;

Elements

DeinterlaceTech9_Unknown

The algorithm is unknown or proprietary.

DeinterlaceTech9_BOBLineReplicate

The algorithm creates each missing line by repeating the line above it or below it. This method creates jagged artifacts and is not recommended.

DeinterlaceTech9_BOBVerticalStretch

The algorithm creates the missing lines by vertically stretching each video field by a factor of two. For example, it might average two lines or use a (-1, 9, 9, -1)/16 filter across four lines. Slight vertical adjustments are made to ensure that the resulting image does not "bob" up and down

DeinterlaceTech9_MedianFiltering

The algorithm uses median filtering to recreate the pixels in the missing lines.

DeinterlaceTech9_EdgeFiltering

The algorithm uses an edge filter to create the missing lines. In this process, spatial directional filters are applied to determine the orientation of edges in the picture content. Missing pixels are created by filtering along (rather than across) the detected edges.

DeinterlaceTech9_FieldAdaptive

The algorithm uses spatial or temporal interpolation, switching between the two on a field-by-field basis, depending on the amount of motion.

DeinterlaceTech9_PixelAdaptive

The algorithm uses spatial or temporal interpolation, switching between the two on a pixel-by-pixel basis, depending on the amount of motion.

DeinterlaceTech9_MotionVectorSteered

The algorithm identifies objects within a sequence of video fields. Before it recreates the missing pixels, it aligns the movement axes of the individual objects in the scene to make them parallel with the time axis.

See Also

  • DirectShow Enumerated Types
  • VMR9DeinterlaceCaps Structure


VMR9MixerPrefs Enumeration

The VMR9MixerPrefs enumeration type contains flags that specify decimation, filtering, and color space information that will be used when the video image is created on the Direct3D surface (VMR-9 only).

Syntax

typedef enum {
  MixerPref9_NoDecimation  = 0x00000001,
  MixerPref9_DecimateOutput  = 0x00000002,
  MixerPref9_DecimationReserved  = 0x0000000C,
  MixerPref9_DecimateMask  = 0x0000000F,
  MixerPref9_BiLinearFiltering  = 0x00000010,
  MixerPref9_PointFiltering  = 0x00000020,
  MixerPref9_AnisotropicFiltering  = 0x00000040,
  MixerPref9_PyramidalQuadFiltering   = 0x00000080, // 4-sample tent
  MixerPref9_GaussianQuadFiltering    = 0x00000100, // 4-sample gaussian
  MixerPref9_FilteringReserved  = 0x00000F80,
  MixerPref9_FilteringMask  = 0x00000FF0,
  MixerPref9_RenderTargetRGB  = 0x00001000,
  MixerPref9_RenderTargetReserved  = 0x000FE000,
  MixerPref9_RenderTargetMask  = 0x000FF000
} VMR9MixerPrefs;

Members

MixerPref9_NoDecimation

No decimation.

MixerPref9_DecimateOutput

Decimate output by 2 in the x and y directions.

MixerPref9_DecimationReserved

Reserved for future use.

MixerPref9_DecimateMask

Bitwise OR of all decimation flags; used internally by VMR, not by applications.

MixerPref9_BiLinearFiltering

Use bi-linear filtering.

MixerPref9_PointFiltering

Use point filtering.

MixerPref9_AnisotropicFiltering

Use anisotropic filtering.

MixerPref9_PyramidalQuadFiltering

Use 4-sample tent filtering.

MixerPref9_GaussianQuadFiltering

Use 4-sample Gaussian filterng.

MixerPref9_FilteringReserved

Reserved for future use.

MixerPref9_FilteringMask

Bitwise OR of all filtering flags; not used by applications.

MixerPref9_RenderTargetRGB

Use an RGB render target.

MixerPref9_RenderTargetReserved

Reserved for future use.

MixerPref9_RenderTargetMask

Bitwise OR of all render target flags; not used by applications.

See Also

  • DirectShow Enumerated Types


VMR9Mode Enumeration

The VMR9Mode enumeration type is used in calls to the IVMRFilterConfig9::GetRenderingMode and IVMRFilterConfig9::SetRenderingMode methods to retrieve or specify the VMR-9's rendering mode.

Syntax

typedef enum VMR9Mode{
  VMR9Mode_Windowed  = 0x00000001,
  VMR9Mode_Windowless  = 0x00000002,
  VMR9Mode_Renderless  = 0x00000004,
  VMR9Mode_Mask  = 0x00000007,
};

Members

VMR9Mode_Windowed

Indicates windowed mode.

VMR9Mode_Windowless

Indicates windowless mode.

VMR9Mode_Renderless

Indicates renderless mode.

VMR9Mode_Mask

Bitwise OR of all above flags; not used by applications

See Also

  • DirectShow Enumerated Types


VMR9PresentationFlags Enumeration

The VMR9PresentationFlags enumeration type contains flags that describe the status of a video sample. These flags are used in the VMR9PresentationInfo structure.

Syntax

typedef enum VMR9PresentationFlags{
  VMR9Sample_SyncPoint  = 0x00000001,
  VMR9Sample_Preroll  = 0x00000002,
  VMR9Sample_Discontinuity  = 0x00000004,
  VMR9Sample_TimeValid  = 0x00000008
};

Members

VMR9Sample_SyncPoint

Indicates that the sample is a sync point.

VMR9Sample_Preroll

Indicates that the sample is part of the preroll.

VMR9Sample_Discontinuity

Indicates that the sample is a discontinuity.

VMR9Sample_TimeValid

Indicates that the time stamp on the sample is valid.

See Also

  • DirectShow Enumerated Types


VMR9ProcAmpControlFlags Enumeration

The VMR9ProcAmpControlFlags enumeration type specifies image adjustment properties, for use with the Video Mixing Render Filter 9 (VMR-9).

Syntax

typedef enum {
    ProcAmpControl9_Contrast   = 0x00000001,
    ProcAmpControl9_Brightness = 0x00000002,
    ProcAmpControl9_Hue        = 0x00000004,
    ProcAmpControl9_Saturation = 0x00000008,
    ProcAmpControl9_Mask       = 0x0000000F
} VMR9ProcAmpControlFlags;

Members

ProcAmpControl9_Contrast

Contrast adjustment.

ProcAmpControl9_Brightness

Brightness adjustment.

ProcAmpControl9_Hue

Hue adjustment.

ProcAmpControl9_Saturation

Saturation adjustment.

ProcAmpControl9_Mask

Bitwise OR of all the previous flags. This value is used internally by the VMR-9, and is not a valid flag.

See Also

  • DirectShow Enumerated Types
  • VMR9ProcAmpControl Structure
  • VMR9ProcAmpControlRange Structure


VMR9RenderPrefs Enumeration

The VMR9RenderPrefs enumeration type specifies basic rendering preferences for the VMR-9. It is used with the IVMRFilterConfig9::GetRenderingPrefs and IVMRFilterConfig9::SetRenderingPrefs methods.

Syntax

typedef enum VMR9RenderPrefs{
  RenderPrefs9_DoNotRenderBorder         = 0x00000001,
  RenderPrefs9_Mask                      = 0x00000001,
};

Members

RenderPrefs9_DoNotRenderBorder

Indicates that the application paints the color keyed areas.

RenderPrefs9_Mask

Bitwise OR of all flags; not used by applications.

See Also

  • DirectShow Enumerated Types


VMR9SurfaceAllocationFlags Enumeration

The VMR9SurfaceAllocationFlags enumeration type is used with the IVMRSurfaceAllocator9::InitializeDevice method to specify surface creation parameters (VMR-9 only).

Syntax

typedef enum VMR9SurfaceAllocationFlags{
  VMR9AllocFlag_3DRenderTarget  = 0x0001,
  VMR9AllocFlag_DXVATarget  = 0x0002,
  VMR9AllocFlag_TextureSurface  = 0x0004,
  VMR9AllocFlag_OffscreenSurface  = 0x0008,
  VMR9AllocFlag_UsageReserved  = 0x00F0,
  VMR9AllocFlag_UsageMask  = 0x00FF
};

Members

VMR9AllocFlag_3DRenderTarget

Indicates that the surface is a Direct3D render target.

VMR9AllocFlag_DXVATarget

Indicates that the render target supports DXVA.

VMR9AllocFlag_TextureSurface

Indicates that the target is a Direct3D texture surface.

VMR9AllocFlag_OffscreenSurface

Indicates an offscreen surface.

VMR9AllocFlag_UsageReserved

Reserved for future use.

VMR9AllocFlag_UsageMask

OR of all flags; not used by applications

Remarks

VMR9AllocFlag_TextureSurface can be combined with DXVATarget and 3DRenderTarget flags.

See Also

  • DirectShow Enumerated Types


VMRDeinterlacePrefs Enumeration

This topic applies to Windows XP Service Pack 1 only.

The VMRDeinterlacePrefs enumeration type describes the deinterlacing method that the Video Mixing Renderer (VMR) uses if the method set by the application cannot be used.

Syntax

typedef enum {
    DeinterlacePref_NextBest = 0x01,
    DeinterlacePref_BOB      = 0x02,
    DeinterlacePref_Weave    = 0x04,
    DeinterlacePref_Mask     = 0x07
} VMRDeinterlacePrefs;

Elements

DeinterlacePref_NextBest

Use the next best mode offered by the driver.

DeinterlacePref_BOB

Use the bob method.

DeinterlacePref_Weave

Use the weave method (that is, no deinterlacing).

DeinterlacePref_Mask

Bitwise OR of the previous flags. This value is used internally by the VMR, and is not a valid flag.

Requirements

Requires Microsoft® Windows® XP Service Pack 1.

See Also

  • DirectShow Enumerated Types
  • IVMRDeinterlaceControl Interface


VMRDeinterlaceTech Enumeration

This topic applies to Windows XP Service Pack 1 only.

The VMRDeinterlaceTech enumeration type describes the algorithm used for deinterlacing a video stream. The flags are not mutually exclusive; drivers can set a combination of flags.

Syntax

typedef enum {
    DeinterlaceTech_Unknown             = 0x0000,
    DeinterlaceTech_BOBLineReplicate    = 0x0001,
    DeinterlaceTech_BOBVerticalStretch  = 0x0002,
    DeinterlaceTech_MedianFiltering     = 0x0004,
    DeinterlaceTech_EdgeFiltering       = 0x0010,
    DeinterlaceTech_FieldAdaptive       = 0x0020,
    DeinterlaceTech_PixelAdaptive       = 0x0040,
    DeinterlaceTech_MotionVectorSteered = 0x0080
} VMRDeinterlacePrefs;

Elements

DeinterlaceTech_Unknown

The algorithm is unknown or proprietary.

DeinterlaceTech_BOBLineReplicate

The algorithm creates each missing line by repeating the line above it or below it. This method creates jagged artifacts and is not recommended.

DeinterlaceTech_BOBVerticalStretch

The algorithm creates the missing lines by vertically stretching each video field by a factor of two. For example, it might average two lines or use a (-1, 9, 9, -1)/16 filter across four lines. Slight vertical adjustments are made to ensure that the resulting image does not "bob" up and down

DeinterlaceTech_MedianFiltering

The algorithm uses median filtering to recreate the pixels in the missing lines.

DeinterlaceTech_EdgeFiltering

The algorithm uses an edge filter to create the missing lines. In this process, spatial directional filters are applied to determine the orientation of edges in the picture content. Missing pixels are created by filtering along (rather than across) the detected edges.

DeinterlaceTech_FieldAdaptive

The algorithm uses spatial or temporal interpolation, switching between the two on a field-by-field basis, depending on the amount of motion.

DeinterlaceTech_PixelAdaptive

The algorithm uses spatial or temporal interpolation, switching between the two on a pixel-by-pixel basis, depending on the amount of motion.

DeinterlaceTech_MotionVectorSteered

The algorithm identifies objects within a sequence of video fields. Before it recreates the missing pixels, it aligns the movement axes of the individual objects in the scene to make them parallel with the time axis.

Requirements

Requires Microsoft® Windows® XP Service Pack 1.

See Also

  • DirectShow Enumerated Types
  • VMRDeinterlaceCaps Structure


VMRMixerPrefs Enumeration

The VMRMixerPrefs enumeration contains flags that specify decimation, filtering, and color space information that will be used when the video image is created on the DirectDraw surface.

Syntax

typedef enum {
    MixerPref_NoDecimation          = 0x00000001,
    MixerPref_DecimateOutput        = 0x00000002,
    MixerPref_DecimateMask          = 0x0000000F,
    MixerPref_BiLinearFiltering     = 0x00000010,
    MixerPref_PointFiltering        = 0x00000020,
    MixerPref_FilteringMask         = 0x000000F0,
    MixerPref_RenderTargetRGB       = 0x00000100,
    MixerPref_RenderTargetYUV420    = 0x00000200,
    MixerPref_RenderTargetYUV422    = 0x00000400,
    MixerPref_RenderTargetYUV444    = 0x00000800,
    MixerPref_RenderTargetReserved  = 0x0000F000,
    MixerPref_RenderTargetMask      = 0x0000FF00
} VMRMixerPrefs;

Members

MixerPref_NoDecimation

Indicates that the video will be rendered onto the surface in its native size.

MixerPref_DecimateOutput

Indicates that the native video will be decimated by a factor of 2 in both x and y directions.

MixerPref_DecimateMask

Used internally by the VMR to isolate the fields relevant to each parameter being set. Should not be used by applications.

MixerPref_BiLinearFiltering

Indicates that bi-linear filtering will be used. This is the default type of filtering, but not all cards can support it.

MixerPref_PointFiltering

Indicates that point filtering will be used.

MixerPref_FilteringMask

Used internally by the VMR to isolate the fields relevant to each parameter being set. Should not be used by applications.

MixerPref_RenderTargetRGB

Indicates that the render target is an RGB surface.

MixerPref_RenderTargetYUV420

Indicates that the render target is a YUV 4:2:0 surface.

MixerPref_RenderTargetYUV422

Indicates that the render target is a YUV 4:2:2 surface.

MixerPref_RenderTargetYUV444

Indicates that the render target is a YUV 4:4:4 surface.

MixerPref_RenderTargetReserved

Reserved for future use.

MixerPref_RenderTargetMask

Used internally by the VMR to isolate the fields relevant to each parameter being set. Should not be used by applications.

See Also

  • DirectShow Enumerated Types
  • IVMRMixerControl::SetMixingPrefs
  • IVMRMixerControl::GetMixingPrefs


VMRMode Enumeration

The VMRMode enumeration type is used in calls to the IVMRFilterConfig::GetRenderingMode and IVMRFilterConfig::SetRenderingMode methods to retrieve or specify the VMR-7's rendering mode.

Syntax

enum VMRMode{
  VMRMode_Windowed  = 0x00000001,
  VMRMode_Windowless  = 0x00000002,
  VMRMode_Renderless  = 0x00000004,
  VMRMode_Mask  = 0x00000007
};

Elements

VMRMode_Windowed

Indicates windowed mode.

VMRMode_Windowless

Indicates windowless mode.

VMRMode_Renderless

Indicates renderless mode.

VMRMode_Mask

Bitwise OR of all above flags; this is not a valid value to pass to SetRenderingMode.

Remarks

These modes are mutually exclusive. VMRMode_Renderless means that the application is providing its own allocator-presenter, which is responsible for all drawing to the screen. VMRMode_Windowed is the default mode of the VMR. See VMR Modes of Operation for more information on the rendering modes.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Enumerated Types


VMRPresentationFlags Enumeration

The VMRPresentationFlags enumeration type is a member of the VMRPRESENTATIONINFO structure .

Syntax

typedef enum {
  VMRSample_SyncPoint  = 0x00000001,
  VMRSample_Preroll  = 0x00000002,
  VMRSample_Discontinuity  = 0x00000004,
  VMRSample_TimeValid  = 0x00000008
} VMRPresentationFlags;

Elements

VMRSample_SyncPoint

Indicates that the sample is a sync point.

VMRSample_Preroll

Indicates that the sample is part of the preroll.

VMRSample_Discontinuity

Indicates that the sample is a discontinuity.

VMRSample_TimeValid

Indicates that the time stamp on the sample is valid.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Enumerated Types


VMRRenderPrefs Enumeration

The VMRRenderPrefs enumeration type is used with the IVMRFilterConfig::GetRenderingPrefs and IVMRFilterConfig::SetRenderingPrefs methods to get and set basic rendering preferences.

Syntax

typedef enum {
  RenderPrefs_ForceOffscreen               = 0x00000001,
  RenderPrefs_ForceOverlays                = 0x00000002,
  RenderPrefs_AllowOverlays                = 0x00000000,
  RenderPrefs_AllowOffscreen               = 0x00000000,
  RenderPrefs_DoNotRenderColorKeyAndBorder = 0x00000008,
  RenderPrefs_RestrictToInitialMonitor     = 0x00000010,
  RenderPrefs_PreferAGPMemWhenMixing       = 0x00000020,
  RenderPrefs_Mask                         = 0x0000003f
} VMRRenderPrefs;

Elements

RenderPrefs_ForceOffscreen

Indicates that the VMR should use only offscreen surfaces for rendering.

RenderPrefs_ForceOverlays

Indicates that the VMR should fail if no overlay surfaces are available.

RenderPrefs_AllowOverlays

Indicates that the VMR should use overlays if they are available. Should not be used by new applications.

RenderPrefs_AllowOffscreen

Indicates that the VMR should use offscreen surfaces if no overlays are available. Should not be used by new applications.

RenderPrefs_DoNotRenderColorKeyAndBorder

Indicates that the application is responsible for painting the color keys.

RenderPrefs_RestrictToInitialMonitor

Indicates that the VMR should output only to the initial monitor.

RenderPrefs_PreferAGPMemWhenMixing

Indicates that the VMR should attempt to use AGP memory when allocating texture surfaces.

RenderPrefs_Mask

Bitwise OR of all of the above flags

Remarks

By default the VMR tries to allocate DirectDraw texture surfaces from Video Memory and falls back to AGP memory if there is no Video Memory remaining to fulfill the allocation. In order for the VMR to use AGP memory, the graphics card must have some basic support for blitting from AGP memory to Video Memory.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Enumerated Types


VMRSurfaceAllocationFlags Enumeration

The VMRSurfaceAllocationFlags enumeration is used with the IVMRSurfaceAllocator::AllocateSurface method to specify surface creation parameters.

Syntax

typedef enum {
  AMAP_PIXELFORMAT_VALID  = 0x01,
  AMAP_3D_TARGET  = 0x02,
  AMAP_ALLOW_SYSMEM  = 0x04,
  AMAP_FORCE_SYSMEM  = 0x08,
  AMAP_DIRECTED_FLIP  = 0x10,
  AMAP_DXVA_TARGET = 0x20
} VMRSurfaceAllocationFlags;

Elements

AMAP_PIXELFORMAT_VALID

Indicates that the lpPxFmt field contains valid data that should be used to create the DirectDraw surface.

AMAP_3D_TARGET

Indicates that the DirectDraw surface created should also be a Direct3D render target that is created with the DDSCAPS_3DDEVICE flag set.

AMAP_ALLOW_SYSMEM

Indicates that if you can't allocate the DirectDraw surface in video memory you will try to allocate a system memory DirectDraw surface. (Note you should never allocate an AGP memory surface.)

AMAP_FORCE_SYSMEM

Force the surface to be created in system memory. Specify this if you will use GDI to process the image before it is renderered. The surface must match the current monitor display format (pixel depth).

AMAP_DIRECTED_FLIP

Means that when Flip is called you should Flip to the specified DirectDraw Surface passed as a parameter to the PresentImage function in the IVMRImagePresenter interface. Correct support for this flag is crucial in order to keep DXVA buffers seen by a video decoder in sync with the DXVA buffers seen by the graphics driver.

AMAP_DXVA_TARGET

Indicates that this surface will be used as a DXVA target.

Remarks

AMAP_3D_TARGET cannot be combined with AMAP_FORCE_SYSMEM or AMAP_ALLOW_SYSMEM because 3D surfaces cannot be created in system memory.

Requirements

Requires Microsoft® Windows® XP.

See Also

  • DirectShow Enumerated Types
  • IVMRSurfaceAllocator::AllocateSurface


Constants and GUIDs

This section describes constants and globally unique identifiers (GUIDs) that are defined in Microsoft® DirectShow®.

  • DVD Event Notification Codes
  • Error and Success Codes
  • Event Notification Codes
  • Filter Categories
  • Media Types
  • Merit
  • Time Format GUIDs

See Also

  • Filter class identifiers (CLSIDs): See DirectShow Filters.
  • Other component CLSIDs: See DirectShow Objects.
  • Interface identifiers (IIDs): Except where noted, all DirectShow IIDs have the form IID_InterfaceName. For example, the IID for the IGraphBuilder interface is IID_IGraphBuilder.


DVD Event Notification Codes

Note This introductory material applies only to C++ developers.

Microsoft® DirectShow® supports system-defined events, which filters in the filter graph pass to the filter graph manager. Filters pass these events to the filter graph manager by using the IMediaEventSink::Notify method, and the application retrieves them with the IMediaEvent::GetEvent method.

When you retrieve an event by calling GetEvent, the event can contain interface pointers or pointers to allocated memory. Code that uses GetEvent should, therefore, call IMediaEvent::FreeEventParams to free any resources associated with the event's parameters after it handles the event.

The DVD event notification codes are listed in Dvdevcod.h. See Event Notification Codes for non-DVD event notification codes. The following list shows the available DVD event notification codes in alphabetical order.

DVD event notification code | Description
EC_DVD_ANGLE_CHANGE | Signals that either the number of available angles changed or that the current angle number changed.
EC_DVD_ANGLES_AVAILABLE | Indicates whether an angle block is being played and angle changes can be performed.
EC_DVD_AUDIO_STREAM_CHANGE | Signals that the current audio stream number changed for the main title.
EC_DVD_BUTTON_AUTO_ACTIVATED | Signals that a menu button has been automatically activated per instructions on the disc.
EC_DVD_BUTTON_CHANGE | Signals that either the number of available buttons changed or that the currently selected button number changed.
EC_DVD_CHAPTER_AUTOSTOP | Indicates that playback stopped as the result of a call to the IDvdControl2::PlayChaptersAutoStop method.
EC_DVD_CHAPTER_START | Signals that the DVD Navigator started playback of a new chapter in the current title.
EC_DVD_CMD_START | Signals that a particular command has begun.
EC_DVD_CMD_END | Signals that a particular command has completed.
EC_DVD_CURRENT_HMSF_TIME | Signals the current time in DVD_HMSF_TIMECODE format at the beginning of every VOBU, which occurs every .4 to 1.0 sec.
EC_DVD_CURRENT_TIME | Signals the beginning of every video object unit (VOBU), a video segment which is 0.4 to 1.0 seconds in length.
EC_DVD_DISC_EJECTED | Signals that a disc has been ejected from the drive.
EC_DVD_DISC_INSERTED | Signals that a disc has been inserted into the drive.
EC_DVD_DOMAIN_CHANGE | Indicates the DVD Navigator's new domain.
EC_DVD_ERROR | Signals a DVD error condition.
EC_DVD_KARAOKE_MODE | Indicates that the Navigator has either begun playing or finished playing karaoke data.
EC_DVD_NO_FP_PGC | Indicates that the DVD disc does not have a FP_PGC (First Play Program Chain).
EC_DVD_PARENTAL_LEVEL_CHANGE | Signals that the parental level of the authored content is about to change.
EC_DVD_PLAYBACK_RATE_CHANGE | Indicates that a playback rate change has been initiated and the new rate is in the parameter.
EC_DVD_PLAYBACK_STOPPED | Indicates that playback has been stopped. The DVD Navigator has completed playback of the title and did not find any other branching instruction for subsequent playback.
EC_DVD_PLAYPERIOD_AUTOSTOP | Indicates that the Navigator has finished playing the segment specified in a call to PlayPeriodInTitleAutoStop.
EC_DVD_STILL_OFF | Signals the end of any still.
EC_DVD_STILL_ON | Signals the beginning of any still.
EC_DVD_SUBPICTURE_STREAM_CHANGE | Signals that the current subpicture stream number changed for the main title.
EC_DVD_TITLE_CHANGE | Indicates when the current title number changes.
EC_DVD_VALID_UOPS_CHANGE | Signals that the available set of IDvdControl2 interface methods has changed.
EC_DVD_WARNING | Signals a DVD warning condition.


EC_DVD_ANGLE_CHANGE

Signals that either the number of available angles changed or that the current angle number changed.

Parameters

lParam1

DWORD value indicating the number of available angles. When the number of available angles is 1, the current video is not multiangle.

lParam2

DWORD value indicating the current angle number.

Remarks

Angle numbers range from 1 to 9.

The current angle number can change automatically with a navigation command authored on the disc as well as through application control by using the IDvdControl2 interface.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_ANGLES_AVAILABLE

Indicates whether an angle block is being played and angle changes can be performed.

Parameters

lParam1

Boolean (BOOL) value that indicates if an angle block is being played back. Zero (0) indicates that playback is not in an angle block and angles are not available, One (1) indicates that an angle block is being played back and angle changes can be performed.

lParam2

Zero.

Remarks

Angle changes are not restricted to angle blocks and the manifestation of the angle change can be seen only in an angle block.

See Also

  • DVD Event Notification Codes


EC_DVD_AUDIO_STREAM_CHANGE

Signals that the current audio stream number changed for the main title.

Parameters

lParam1

DWORD value indicating the new user audio stream number. Audio stream numbers range from 0 to 7. Stream 0xFFFFFFFF indicates that no stream is selected.

lParam2

Zero.

Remarks

The current audio stream can change automatically with a navigation command authored on the disc as well as through application control by using the IDvdControl2 interface.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_BUTTON_AUTO_ACTIVATED

Signals that a menu button has been automatically activated per instructions on the disc. This occurs when a menu times out and the disc has specified a button to be automatically activated.

Parameters

lParam1

DWORD value indicating the button that was activated.

lParam2

Zero.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_BUTTON_CHANGE

Signals that either the number of available buttons changed or that the currently selected button number changed.

Parameters

lParam1

DWORD value indicating the number of available buttons.

lParam2

DWORD value indicating the currently selected button number. Selected button number zero implies that no button is selected.

Remarks

Button numbers range from 1 to 36.

The currently selected button can change automatically with a navigation command authored on the disc as well as through application control by using IDvdControl2 interface.

This event can signal any of the available button numbers. These numbers do not always correspond to button numbers used for IDvdControl2::SelectAndActivateButton because that method can activate only a subset of buttons.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_CHAPTER_AUTOSTOP

Indicates that playback stopped as the result of a call to the IDvdControl2::PlayChaptersAutoStop method.

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_CHAPTER_START

Signals that the DVD player started playback of a new program in the DVD_DOMAIN_Title domain.

Parameters

lParam1

DWORD value indicating the new chapter (program) number.

lParam2

Zero.

Remarks

Only simple linear movies signal this event.

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes
  • DVD_DOMAIN Enumeration


EC_DVD_CMD_START

Signals that a particular command has begun.

Parameters

lParam1

The Command ID and the HRESULT return value.

lParam2

Zero.

Remarks

This event is only fired if your application has expressed interest in it by setting the DVD_CMD_FLAG_SendEvents flag in any of the IDvdControl2::Play... methods. See Synchronizing DVD Commands for more details.

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_CMD_END

Signals that a particular command has completed.

Parameters

lParam1

The Command ID and the completion result.

lParam2

Zero.

Remarks

This event is only fired if your application has expressed interest in it by setting the DVD_CMD_FLAG_SendEvents flag in any of the IDvdControl2::Play... methods. See Synchronizing DVD Commands for more details.

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_CURRENT_HMSF_TIME

Signals the current time, in DVD_HMSF_TIMECODE format, relative to the start of the title. This event is triggered at the beginning of every VOBU, which occurs every 0.4 to 1.0 seconds.

Parameters

lParam1

A ULONG value that contains the DVD_HMSF_TIMECODE structure. Assign lParam1 to a ULONG variable and then cast that variable to a DVD_HMSF_TIMECODE to access its values.

lParam2

A ULONG value containing a union of DVD_TIMECODE_FLAGS.

Remarks

The DVD_HMSF_TIMECODE format is intended to replace the old BCD format that is returned in EC_DVD_CURRENT_TIME events. The HMSF timecodes are easier to work with. To have the Navigator send EC_DVD_CURRENT_HMSF_TIME events instead of EC_DVD_CURRENT_TIME events, an application must call IDvdControl2::SetOption(DVD_HMSF_TimeCodeEvents, TRUE). When this flag is set, the Navigator will also expect all time parameters in the IDvdControl2 and IDvdInfo2 methods to be passed as DVD_HMSF_TIMECODEs.

This event is raised in the title domains.

See Also

  • DVD Event Notification Codes


EC_DVD_CURRENT_TIME

Signals the beginning of every video object unit (VOBU), a video segment which is 0.4 to 1.0 seconds in length.

Parameters

lParam1

DWORD value indicating the current playback timecode in a binary coded decimal (BCD) hours, minutes, seconds, frames (HH:MM:SS:FF) format. Member of the DVD_TIMECODE structure.

lParam2

Boolean (BOOL) value indicating the timecode. Zero (0) indicates 25 frames per second while 1 indicates 30 frames per second (nondropped). A value of 2 indicates the playback time cannot be determined.

Remarks

Only simple linear movies signal this event.

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_DISC_EJECTED

Signals that a disc was ejected.

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

Playback automatically stops when a disc is ejected. The application does not have to take any special action in response to this event.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_DISC_INSERTED

Signals that a disc was inserted into the drive.

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

Playback automatically begins when a disc is ejected. The application does not have to take any special action in response to this event.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_DOMAIN_CHANGE

Indicates the DVD player's new domain.

Parameters

lParam1

DWORD value indicating the new domain. Member of the DVD_DOMAIN enumerated data type.

lParam2

Zero unless lParam1 == DVD_ERROR_LowParentalLevel. In that case lParam2 will be set to the minimum parental level required to play the title, or to DWORD_PTR(-1) if parental controls must be disabled in order to play the title.

Remarks

The DVD player signals this event whenever it changes domains.

This event is raised in all DVD domains.

See Also

  • DVD Event Notification Codes


EC_DVD_ERROR

Signals a DVD error condition.

Parameters

lParam1

DWORD value indicating the error condition. Member of the DVD_ERROR enumerated data type.

lParam2

DWORD value whose HIWORD contains the decoder region as a reversed set of bits and whose LOWORD contains the drive/system region as a reversed set of bits. See Remarks.

Remarks

This event is raised in all domains.

If lParam1 == DVD_ERROR_IncompatibleSystemAndDecoderRegion, it indicates that (1) the decoder has a region specified and (2) the drive and decoder region do not match. lParam2 contains the system region in the LOWORD and the HIWORD contains the decoder region.

If lParam1 == DVD_ERROR_IncompatibleDiscAndDecoderRegion, it indicates that (1) the decoder has a region specified and (2) the disc and decoder region do not match. lParam2 contains the disc region in the LOWORD and the decoder region in the HIWORD.

If lParam1 == DVD_ERROR_InvalidDiscRegion, it means that the disc region is invalid. lParam2 contains the disc region in the LOWORD and the system region in the HIWORD

The disc region is encoded exactly as it is on the disc: as a reversed set of bits in the LOWORD of lParam2. If a disc is allowed in a region, that bit will be OFF. For example, for a Region 2 disc the returned value will be 253 (1111 1101) which has the second least significant bit turned off. A multi-region disc will have more than one such bit turned off.

The decoder or system region in the HIWORD of lParam2 is encoded in the same way.

See Also

  • DVD Event Notification Codes


EC_DVD_KARAOKE_MODE

Indicates that the Navigator has either begun playing or finished playing karaoke data.

Parameters

lParam1

BOOL value. TRUE means that a karaoke track is being played and FALSE means that no karaoke data is being played.

lParam2

Reserved.

Remarks

The DVD player signals this event whenever it changes domains.

This event is raised in all DVD domains.

See Also

  • DVD Event Notification Codes


EC_DVD_NO_FP_PGC

Signals that the DVD disc does not have a FP_PGC (First Play Program Chain) and that the DVD Navigator will not automatically load any PGC and start playback.

Remarks

This event is raised from the First Play domain.

See Also

  • DVD Event Notification Codes


EC_DVD_PARENTAL_LEVEL_CHANGE

Signals that the parental level of the authored content is about to change.

Parameters

lParam1

LONG value representing the new parental level set in the player.

lParam2

Zero.

Remarks

The DVD Navigator source filter does not currently support "on the fly" parental level changes in response to SetTmpPML commands on a DVD disc.

See Also

  • DVD Event Notification Codes


EC_DVD_PLAYBACK_RATE_CHANGE

Signals that a rate change in the playback has been initiated; the parameter lParam1 indicates the new playback rate being used.

Parameters

lParam1

LONG indicating the new playback rate. lParam1 < 0 indicates reverse playback mode. lParam1 > 0 indicates forward playback mode. The value of lParam1 is the actual playback rate multiplied by 10,000, that is, lParam1 = playback_rate * 10000.

lParam2

Zero.

Remarks

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_PLAYBACK_STOPPED

Indicates that playback has been stopped. The DVD Navigator has completed playback of the title or chapter and did not find any other branching instruction for subsequent playback.

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

This event is raised in the title domain, but it is not raised on user initiated Stop.

See Also

  • DVD Event Notification Codes


EC_DVD_STILL_OFF

Signals the end of any still (PGC, Cell, or VOBU).

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

This event indicates that any currently active still has been released.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_PLAYPERIOD_AUTOSTOP

Indicates that the Navigator has finished playing the segment specified in a call to PlayPeriodInTitleAutoStop.

Parameters

lParam1

Zero.

lParam2

Zero.

Remarks

This event is raised in the Title domain.

This event is also sent when playback is cancelled before the Navigator finishes playing the specified segment.

See Also

  • DVD Event Notification Codes


EC_DVD_STILL_ON

Signals the beginning of any still (PGC, Cell, or VOBU).

Parameters

lParam1

Boolean (BOOL) value indicating whether buttons are available. Zero (0) indicates buttons are available so the IDvdControl2::StillOff method won't work. One (1) indicates no buttons are available, so IDvdControl2::StillOff will work.

lParam2

DWORD value indicating the number of seconds the still will last. 0xFFFFFFFF indicates an infinite still, meaning wait until the user presses a button or until the application calls IDvdControl2::StillOff.

Remarks

All combinations of buttons and still are possible (buttons on with still on, buttons on with still off, button off with still on, button off with still off).

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_SUBPICTURE_STREAM_CHANGE

Signals that the current subpicture stream number changed for the main title.

Parameters

lParam1

DWORD value indicating the new user subpicture stream number. Subpicture stream numbers range from 0 to 31. Stream 0xFFFFFFFF indicates that no stream is selected.

lParam2

Boolean value that indicates the subpicture's on/off state.

Remarks

The subpicture can change automatically with a navigation command authored on disc as well as through application control using IDvdControl2.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_TITLE_CHANGE

Indicates when the current title number changes.

Parameters

lParam1

DWORD value indicating the new title number.

lParam2

Zero.

Remarks

Title numbers range from 1 to 99. This number indicates the TTN, which is the title number with respect to the whole disc, not the VTS_TTN which is the title number with respect to just a current VTS.

This event is raised in the title domain.

See Also

  • DVD Event Notification Codes


EC_DVD_VALID_UOPS_CHANGE

Signals that the available set of IDvdControl2 interface methods has changed.

Parameters

lParam1

DWORD value that contains a combination of zero or more flags from the VALID_UOP_FLAG enumeration. The bits indicate which IDvdControl2 commands were explicitly disabled by the DVD disc.

lParam2

Zero.

Remarks

This event indicates only which operations are explicitly disabled by the content on the DVD disc. It does not guarantee that it is valid to call methods that are not disabled. For example, if no buttons are present, the IDvdControl2::ActivateButton method won't work, even though the method is not explicitly disabled.

This event is raised in all domains.

See Also

  • DVD Event Notification Codes


EC_DVD_WARNING

Signals a DVD warning condition.

Parameters

lParam1

DWORD value indicating the warning condition. Member of the DVD_WARNING enumerated data type.

lParam2

If pParam1 is DVD_WARNING_Open, then lParam2 contains the dwFileOpenError code returned from GetLastError. If lParam1 is DVD_WARNING_Seek or DVD_WARNING_Read, then lParam2 contains the dwError code returned from GetLastError.

See Also

  • DVD Event Notification Codes


Error and Success Codes

Microsoft® DirectShow® returns error and success notifications (return codes) to applications in the form of HRESULT values. A return code's LOWORD portion is the return code itself, in hexadecimal format.

This article contains the following sections:

  • HRESULT Values Specific to DirectShow
  • HRESULT Values Specific to DirectShow Editing Services

See Also

  • AMGetErrorText

HRESULT Values Specific to DirectShow

The following table contains DirectShow-specific error and success codes in numerical order. Return codes beginning with VFW_S_ indicate success. An operation might partially succeed and still have a successful return value. For example, VFW_S_SOME_DATA_IGNORED indicates that a file was rendered by ignoring some of its property settings. Return codes beginning with VFW_E_ indicate an error.

C/C++ applications receive error codes as 32-bit integer values. Microsoft Visual Basic® applications, on the other hand, receive only the first 16-bit portion of the error code. This value appears in the Err object as a run-time error.

Return code | Description | Hexadecimal value | Decimal value (LOWORD)
VFW_E_INVALIDMEDIATYPE | The specified media type is invalid. | 0x80040200 | 512
VFW_E_INVALIDSUBTYPE | The specified media subtype is invalid. | 0x80040201 | 513
VFW_E_NEED_OWNER | This object can only be created as an aggregated object. | 0x80040202 | 514
VFW_E_ENUM_OUT_OF_SYNC | The state of the enumerated object has changed and is now inconsistent with the state of the enumerator. Discard any data obtained from previous calls to the enumerator and then update the enumerator by calling the enumerator's Reset method. | 0x80040203 | 515
VFW_E_ALREADY_CONNECTED | At least one of the pins involved in the operation is already connected. | 0x80040204 | 516
VFW_E_FILTER_ACTIVE | This operation cannot be performed because the filter is active. | 0x80040205 | 517
VFW_E_NO_TYPES | One of the specified pins supports no media types. | 0x80040206 | 518
VFW_E_NO_ACCEPTABLE_TYPES | There is no common media type between these pins. | 0x80040207 | 519
VFW_E_INVALID_DIRECTION | Two pins of the same direction cannot be connected. | 0x80040208 | 520
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected. | 0x80040209 | 521
VFW_E_NO_ALLOCATOR | No sample buffer allocator is available. | 0x8004020A | 522
VFW_E_RUNTIME_ERROR | A run-time error occurred. | 0x8004020B | 523
VFW_E_BUFFER_NOTSET | No buffer space has been set. | 0x8004020C | 524
VFW_E_BUFFER_OVERFLOW | The buffer is not big enough. | 0x8004020D | 525
VFW_E_BADALIGN | An invalid alignment was specified. | 0x8004020E | 526
VFW_E_ALREADY_COMMITTED | The allocator was not committed. See IMemAllocator::Commit. | 0x8004020F | 527
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active. | 0x80040210 | 528
VFW_E_NOT_COMMITTED | Cannot allocate a sample when the allocator is not active. | 0x80040211 | 529
VFW_E_SIZENOTSET | Cannot allocate memory because no size has been set. | 0x80040212 | 530
VFW_E_NO_CLOCK | Cannot lock for synchronization because no clock has been defined. | 0x80040213 | 531
VFW_E_NO_SINK | Quality messages could not be sent because no quality sink has been defined. | 0x80040214 | 532
VFW_E_NO_INTERFACE | A required interface has not been implemented. | 0x80040215 | 533
VFW_E_NOT_FOUND | An object or name was not found. | 0x80040216 | 534
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection. | 0x80040217 | 535
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream. | 0x80040218 | 536
VFW_E_CHANGING_FORMAT | Could not change formats dynamically. | 0x80040219 | 537
VFW_E_NO_COLOR_KEY_SET | No color key has been set. | 0x8004021A | 538
VFW_E_NOT_OVERLAY_CONNECTION | Current pin connection is not using the IOverlay transport. | 0x8004021B | 539
VFW_E_NOT_SAMPLE_CONNECTION | Current pin connection is not using the IMemInputPin transport. | 0x8004021C | 540
VFW_E_PALETTE_SET | Setting a color key would conflict with the palette already set. | 0x8004021D | 541
VFW_E_COLOR_KEY_SET | Setting a palette would conflict with the color key already set. | 0x8004021E | 542
VFW_E_NO_COLOR_KEY_FOUND | No matching color key is available. | 0x8004021F | 543
VFW_E_NO_PALETTE_AVAILABLE | No palette is available. | 0x80040220 | 544
VFW_E_NO_DISPLAY_PALETTE | Display does not use a palette. | 0x80040221 | 545
VFW_E_TOO_MANY_COLORS | Too many colors for the current display settings. | 0x80040222 | 546
VFW_E_STATE_CHANGED | The state changed while waiting to process the sample. | 0x80040223 | 547
VFW_E_NOT_STOPPED | The operation could not be performed because the filter is not stopped. | 0x80040224 | 548
VFW_E_NOT_PAUSED | The operation could not be performed because the filter is not paused. | 0x80040225 | 549
VFW_E_NOT_RUNNING | The operation could not be performed because the filter is not running. | 0x80040226 | 550
VFW_E_WRONG_STATE | The operation could not be performed because the filter is in the wrong state. | 0x80040227 | 551
VFW_E_START_TIME_AFTER_END | The sample start time is after the sample end time. | 0x80040228 | 552
VFW_E_INVALID_RECT | The supplied rectangle is invalid. | 0x80040229 | 553
VFW_E_TYPE_NOT_ACCEPTED | This pin cannot use the supplied media type. | 0x8004022A | 554
VFW_E_SAMPLE_REJECTED | This sample cannot be rendered. | 0x8004022B | 555
VFW_E_SAMPLE_REJECTED_EOS | This sample cannot be rendered because the end of the stream has been reached. | 0x8004022C | 556
VFW_E_DUPLICATE_NAME | An attempt to add a filter with a duplicate name failed. | 0x8004022D | 557
VFW_S_DUPLICATE_NAME | An attempt to add a filter with a duplicate name succeeded with a modified name. | 0x0004022D | 557
VFW_E_TIMEOUT | A time-out has expired. | 0x8004022E | 558
VFW_E_INVALID_FILE_FORMAT | The file format is invalid. | 0x8004022F | 559
VFW_E_ENUM_OUT_OF_RANGE | The list has already been exhausted. | 0x80040230 | 560
VFW_E_CIRCULAR_GRAPH | The filter graph is circular. | 0x80040231 | 561
VFW_E_NOT_ALLOWED_TO_SAVE | Updates are not allowed in this state. | 0x80040232 | 562
VFW_E_TIME_ALREADY_PASSED | An attempt was made to queue a command for a time in the past. | 0x80040233 | 563
VFW_E_ALREADY_CANCELLED | The queued command was already canceled. | 0x80040234 | 564
VFW_E_CORRUPT_GRAPH_FILE | Cannot render the file because it is corrupt. | 0x80040235 | 565
VFW_E_ADVISE_ALREADY_SET | An IOverlay advise link already exists. | 0x80040236 | 566
VFW_S_STATE_INTERMEDIATE | The state transition is not complete. | 0x00040237 | 567
VFW_E_NO_MODEX_AVAILABLE | No full-screen modes are available. | 0x80040238 | 568
VFW_E_NO_ADVISE_SET | This advise cannot be canceled because it was not successfully set. | 0x80040239 | 569
VFW_E_NO_FULLSCREEN | Full-screen mode is not available. | 0x8004023A | 570
VFW_E_IN_FULLSCREEN_MODE | Cannot call IVideoWindow methods while in full-screen mode. | 0x8004023B | 571
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized. | 0x80040240 | 576
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded. | 0x80040241 | 577
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format. | 0x00040242 | 578
VFW_E_FILE_TOO_SHORT | A file appeared to be incomplete. | 0x80040243 | 579
VFW_E_INVALID_FILE_VERSION | The file's version number is invalid. | 0x80040244 | 580
VFW_S_SOME_DATA_IGNORED | The file contained some property settings that were not used. | 0x00040245 | 581
VFW_S_CONNECTIONS_DEFERRED | Some connections failed and were deferred. | 0x00040246 | 582
VFW_E_INVALID_CLSID | This file is corrupt: it contains an invalid class identifier. | 0x80040247 | 583
VFW_E_INVALID_MEDIA_TYPE | This file is corrupt: it contains an invalid media type. | 0x80040248 | 584
VFW_E_SAMPLE_TIME_NOT_SET | No time stamp has been set for this sample. | 0x80040249 | 585
VFW_S_RESOURCE_NOT_NEEDED | The resource specified is no longer needed. | 0x00040250 | 592
VFW_E_MEDIA_TIME_NOT_SET | No media time was set for this sample. | 0x80040251 | 593
VFW_E_NO_TIME_FORMAT_SET | No media time format was selected. | 0x80040252 | 594
VFW_E_MONO_AUDIO_HW | Cannot change balance because audio device is monoaural only. | 0x80040253 | 595
VFW_S_MEDIA_TYPE_IGNORED | Could not connect with the media type in the persistent graph. | 0x00040254 | 596
VFW_E_NO_DECOMPRESSOR | Cannot play back the video stream: could not find a suitable decompressor. | 0x80040255 | 597
VFW_E_NO_AUDIO_HARDWARE | Cannot play back the audio stream: no audio hardware is available, or the hardware is not supported. | 0x80040256 | 598
VFW_S_VIDEO_NOT_RENDERED | Cannot play back the video stream: could not find a suitable renderer. | 0x00040257 | 599
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream: could not find a suitable renderer. | 0x00040258 | 600
VFW_E_RPZA | Cannot play back the video stream: format 'RPZA' is not supported. | 0x80040259 | 601
VFW_S_RPZA | Cannot play back the video stream: format 'RPZA' is not supported. | 0x0004025A | 602
VFW_E_PROCESSOR_NOT_SUITABLE | DirectShow cannot play MPEG movies on this processor. | 0x8004025B | 603
VFW_E_UNSUPPORTED_AUDIO | Cannot play back the audio stream: the audio format is not supported. | 0x8004025C | 604
VFW_E_UNSUPPORTED_VIDEO | Cannot play back the video stream: the video format is not supported. | 0x8004025D | 605
VFW_E_MPEG_NOT_CONSTRAINED | DirectShow cannot play this video stream because it falls outside the constrained standard. | 0x8004025E | 606
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph. | 0x8004025F | 607
VFW_S_ESTIMATED | The value returned had to be estimated. Its accuracy can't be guaranteed. | 0x00040260 | 608
VFW_E_NO_TIME_FORMAT | Cannot access the time format on an object. | 0x80040261 | 609
VFW_E_READ_ONLY | Could not make the connection because the stream is read-only and the filter alters the data. | 0x80040262 | 610
VFW_S_RESERVED | This success code is reserved for internal purposes within DirectShow. | 0x00040263 | 611
VFW_E_BUFFER_UNDERFLOW | The buffer is not full enough. | 0x80040264 | 612
VFW_E_UNSUPPORTED_STREAM | Cannot play back the file: the format is not supported. | 0x80040265 | 613
VFW_E_NO_TRANSPORT | Pins cannot connect because they don't support the same transport. | 0x80040266 | 614
VFW_S_STREAM_OFF | The stream was turned off. | 0x00040267 | 615
VFW_S_CANT_CUE | The filter is active, but cannot deliver data. See IMediaFilter::GetState. | 0x00040268 | 616
VFW_E_BAD_VIDEOCD | The Video CD can't be read correctly by the device or the data is corrupt. | 0x80040269 | 617
VFW_S_NO_STOP_TIME | The sample had a start time but not a stop time. In this case, the stop time that is returned is set to the start time plus one. | 0x80040270 | 624
VFW_E_OUT_OF_VIDEO_MEMORY | There is not enough video memory at this display resolution and number of colors. Reducing resolution might help. | 0x80040271 | 625
VFW_E_VP_NEGOTIATION_FAILED | The video port connection negotiation process has failed. | 0x80040272 | 626
VFW_E_DDRAW_CAPS_NOT_SUITABLE | Either Microsoft® DirectDraw® has not been installed or the video card capabilities are not suitable. Make sure the display is not in 16-color mode. | 0x80040273 | 627
VFW_E_NO_VP_HARDWARE | No video port hardware is available, or the hardware is not responding. | 0x80040274 | 628
VFW_E_NO_CAPTURE_HARDWARE | No capture hardware is available, or the hardware is not responding. | 0x80040275 | 629
VFW_E_DVD_OPERATION_INHIBITED | This user operation is inhibited by DVD content at this time. | 0x80040276 | 630
VFW_E_DVD_INVALIDDOMAIN | This operation is not permitted in the current domain. | 0x80040277 | 631
VFW_E_DVD_NO_BUTTON | Requested button is not available. | 0x80040278 | 632
VFW_E_DVD_GRAPHNOTREADY | DVD-Video playback graph has not been built yet. | 0x80040279 | 633
VFW_E_DVD_RENDERFAIL | DVD-Video playback graph building failed. | 0x8004027A | 634
VFW_E_DVD_DECNOTENOUGH | DVD-Video playback graph could not be built due to insufficient decoders. | 0x8004027B | 635
VFW_E_DVD_NOT_IN_KARAOKE_MODE | The DVD Navigator is not in karaoke mode. | 0x8004028B | 651
VFW_E_FRAME_STEP_UNSUPPORTED | Frame stepping is not supported. | 0x8004028E | 654
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread. | 0x80040293 | 659
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread. | 0x80040294 | 660
VFW_E_CERTIFICATION_FAILURE | Use of this filter is restricted by a software key. The application must unlock the filter. | 0x80040295 | 661
VFW_E_BAD_KEY | A registry entry is corrupt. | 0x800403F2 | 1010

HRESULT Values Specific to DirectShow Editing Services

In addition to the values listed previously, DirectShow Editing Services defines the following HRESULT values.

Return code | Description | Hexadecimal value | Decimal value (LOWORD)
S_WARN_OUTPUTRESET | The rendering portion of the graph was deleted. The application must rebuild it. | 0x00009DD4 | 40404
E_NOTINTREE | The object is not contained in the timeline. | 0x80040400 | 1024
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully. | 0x80040401 | 1025
E_MUST_INIT_RENDERER | Render engine has not been initialized. | 0x80040402 | 1026
E_NOTDETERMINED | Cannot determine requested value. | 0x80040403 | 1027
E_NO_TIMELINE | There is no timeline object. | 0x80040404 | 1028


Event Notification Codes

This sections lists the DirectShow events that are not specific to DVD. For events specific to DVD, see DVD Event Notification Codes.

Filters send events to the Filter Graph Manager by calling the IMediaEventSink::Notify method. The Filter Graph Manager handles some events and queues others for the application. The application retrieves them by calling the IMediaEvent::GetEvent method.

In the sections that follow, each entry lists the event code, the meaning of the event parameters, and the Filter Graph Manager's default action for the event, if any. To override the default action, call IMediaEvent::CancelDefaultHandling. Event codes are defined in the header files Evcode.h and Audevcod.h. If there is no default action, the Filter Graph Manager automatically forwards the event to the application (through the event queue).

Custom Events

Filters can define custom events with event codes in the range EC_USER and higher. The Filter Graph Manager will place these directly in the event queue. However, the following caveats apply:

  • The Filter Graph Manager cannot free the event parameters using the normal IMediaEvent::FreeEventParams method. The application must free any memory or reference counts associated with the event parameters.
  • The filter should only send the event from within an application that is prepared to handle the event. (Possibly the application can set a custom property on the filter to indicate that it is safe to send the event.)
Event notification code | Description
EC_ACTIVATE | A video window is being activated or deactivated.
EC_BUFFERING_DATA | The graph is buffering data, or has stopped buffering data.
EC_BUILT | Send by the Video Control when a graph has been built. Not forwarded to applications.
EC_CLOCK_CHANGED | The reference clock has changed.
EC_CLOCK_UNSET | The clock provider was disconnected.
EC_CODECAPI_EVENT | Sent by an encoder to signal an encoding event.
EC_COMPLETE | All data from a particular stream has been rendered.
EC_DEVICE_LOST | A Plug and Play device was removed or has become available again.
EC_DISPLAY_CHANGED | The display mode has changed.
EC_END_OF_SEGMENT | The end of a segment has been reached.
EC_ERROR_STILLPLAYING | An asynchronous command to run the graph has failed.
EC_ERRORABORT | An operation was aborted because of an error.
EC_EXTDEVICE_MODE_CHANGE | Not supported.
EC_FULLSCREEN_LOST | The video renderer is switching out of full-screen mode.
EC_GRAPH_CHANGED | The filter graph has changed.
EC_LENGTH_CHANGED | The length of a source has changed.
EC_NEED_RESTART | A filter is requesting that the graph be restarted.
EC_NOTIFY_WINDOW | Notifies a filter of the video renderer's window.
EC_OLE_EVENT | A filter is passing a text string to the application.
EC_OPENING_FILE | The graph is opening a file, or has finished opening a file.
EC_PALETTE_CHANGED | The video palette has changed.
EC_PAUSED | A pause request has completed.
EC_QUALITY_CHANGE | The graph is dropping samples, for quality control.
EC_REPAINT | A video renderer requires a repaint.
EC_SEGMENT_STARTED | A new segment has started.
EC_SHUTTING_DOWN | The filter graph is shutting down, prior to being destroyed.
EC_SNDDEV_IN_ERROR | An audio device error has occurred on an input pin.
EC_SNDDEV_OUT_ERROR | An audio device error has occurred on an output pin.
EC_STARVATION | A filter is not receiving enough data.
EC_STATE_CHANGE | The filter graph has changed state.
EC_STEP_COMPLETE | A filter performing frame stepping has stepped the specified number of frames.
EC_STREAM_CONTROL_STARTED | A stream-control start command has taken effect.
EC_STREAM_CONTROL_STOPPED | A stream-control start command has taken effect.
EC_STREAM_ERROR_STILLPLAYING | An error has occurred in a stream. The stream is still playing.
EC_STREAM_ERROR_STOPPED | A stream has stopped because of an error.
EC_TIMECODE_AVAILABLE | Not supported.
EC_UNBUILT | Send by the Video Control when a graph has been torn down. Not forwarded to applications.
EC_USERABORT | The user has terminated playback.
EC_VIDEO_SIZE_CHANGED | The native video size has changed.
EC_VMR_RENDERDEVICE_SET | Sent when the VMR has selected its rendering mechanism.
EC_VMR_SURFACE_FLIPPED | Sent when the VMR-7's allocator presenter has called the DirectDraw Flip method on the surface being presented.
EC_VMR_RECONNECTION_FAILED | Sent by the VMR-7 and the VMR-9 when it was unable to accept a dynamic format change request from the upstream decoder.
EC_WINDOW_DESTROYED | The video renderer was destroyed or removed from the graph.
EC_WMT_EVENT | Sent by the Windows Media Format SDK when an application uses the ASF Reader filter to play ASF files protected by digital rights management (DRM).
EC_WMT_INDEX_EVENT | Sent by the Windows Media Format SDK when an application uses the ASF Writer to index Windows Media Video files.

See Also

  • Event Notification in DirectShow


EC_ACTIVATE

A video window is being activated or deactivated.

Parameters

lParam1

TRUE if the window is activated, or FALSE if the window is deactivated.

lParam2

Pointer to the renderer's IBaseFilter interface.

Default Action

The filter graph manager sets the focus, through the IResourceManager interface. It does not send the event notification to the application.

Remarks

A video renderer sends this event whenever its window is activated or deactivated (that is, when it receives a WM_ACTIVATEAPP message). Window activation or deactivation can occur because the window has gained or lost focus, or because the renderer has switched between full-screen mode and windowed mode.

This event enables the filter graph manager to allocate resources that depend on window focus, such as audio devices.

See Also

  • Event Notification Codes


EC_BUFFERING_DATA

The graph is buffering data, or has stopped buffering data.

Parameters

lParam1

TRUE if the graph is starting to buffer, or FALSE if the graph has stopped buffering.

lParam2

Zero.

Default Action

None.

Remarks

A filter can send this event if it needs to buffer data from an external source. (For example, it might be loading data from a network.) The application can use this event to adjust its user interface.

See Also

  • Event Notification Codes


EC_BUILT

The EC_BUILT event is sent by the Video Control when a graph has been completely built. This event is not forwarded to applications.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

See Also

  • Event Notification Codes


EC_CLOCK_CHANGED

The reference clock has changed.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

Remarks

The filter graph manager sends this event when its IMediaFilter::SetSyncSource method is called.

See Also

  • Event Notification Codes


EC_CLOCK_UNSET

The clock provider was disconnected.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

The Filter Graph Manager chooses a new reference clock on the next pause or run command. It also forwards the event to the application.

Remarks

KSProxy signals this event when the pin of a clock-providing filter is disconnected.

See Also

  • Event Notification Codes


EC_CODECAPI_EVENT

The EC_CODECAPI_EVENT event is sent by an encoder to signal an encoding event. The client registers for encoder event by calling the ICodecAPI::RegisterForEvent method.

Parameters

lParam1

User data. The value of this parameter is the pointer that the caller specified in the userData parameter of the RegisterForEvent method.

lParam2

Pointer to the event data. This data is allocated by the encoder and must be freed by the application, using the CoTaskMemFree function. The data block starts with a CodecAPIEventData structure; cast the lParam2 parameter to a pointer to this structure.

Default Action

No default action.

See Also

  • Event Notification Codes


EC_COMPLETE

All data from a particular stream has been rendered.

Parameters

lParam1

HRESULT value; can be S_OK.

lParam2

Zero, or a pointer to the renderer's IBaseFilter interface.

Default Action

By default, the filter graph manager does not forward this event to the application. However, after all the streams in the graph report EC_COMPLETE, the filter graph manager posts a separate EC_COMPLETE event to the application.

If the default action is disabled for this event, the application receives all of the EC_COMPLETE events from the renderers.

Remarks

A renderer filter sends this event when it receives an end-of-stream notice. (End-of-stream is signaled through the IPin::EndOfStream method.) The filter sends exactly one EC_COMPLETE event for each stream. The filter must process any pending samples before it sends the event. Stopping a renderer resets any end-of-stream state that was cached.

Filters set the lParam2 parameter to an IBaseFilter pointer. If the default action is enabled, the filter graph manager sets this parameter to zero.

See Also

  • Event Notification Codes


EC_DEVICE_LOST

A Plug and Play device was removed or became available again.

Parameters

lParam1

Pointer to the IUnknown interface of the filter that represents the device.

lParam2

Zero if the device was removed, or 1 if the device is available again.

Default Action

None.

Remarks

When the device becomes available again, the previous state of the device filter is no longer valid. The application must rebuild the graph in order to use the device.

See Also

  • Event Notification Codes


EC_DISPLAY_CHANGED

The display mode has changed.

Parameters

lParam1

Pointer to the IPin interface of the video renderer's input pin, or zero.

lParam2

Zero.

Default Action

The filter graph manager temporarily stops the graph, and then disconnects and reconnects the video renderer. It does not pass the event to the application.

Remarks

Video renderers can send this event in response to a WM_DISPLAYCHANGE message. The WM_DISPLAYCHANGE message indicates that the user has changed the display resolution.

During pin connection, most video renderers pick a format based on the current display mode. If the display mode changes, the video renderer might need to choose another format. By sending this message, the renderer signals to the filter graph manager that it needs to be reconnected. During the reconnection, the renderer can select a new format. If the reconnection fails, the filter graph manager sends an EC_ERRORABORT event to the application.

See Also

  • Event Notification Codes


EC_END_OF_SEGMENT

The end of a segment was reached.

Parameters

lParam1

Pointer to a REFERENCE_TIME value that specifies the accumulated stream time since the start of the segment.

lParam2

DWORD value indicating the segment number (zero-based).

Default Action

The filter graph manager checks the number of EC_END_OF_SEGMENT events against the number of EC_SEGMENT_STARTED events. If they match, it forwards the EC_END_OF_SEGMENT event to the application. Applications cannot override the default action for this event.

Remarks

This event code supports seamless looping. When a call to the IMediaSeeking::SetPositions method includes the AM_SEEKING_Segment flag, the source filter sends this event code instead of calling IPin::EndOfStream.

See Also

  • Event Notification Codes


EC_ERROR_STILLPLAYING

An asynchronous command to run the graph has failed.

Parameters

lParam1

HRESULT value of the operation that failed.

lParam2

Zero.

Default Action

None.

Remarks

If the filter graph manager issues an asynchronous run command that fails, it sends this event to the application. The graph remains in a running state. The state of the underlying filters is indeterminate. Some filters might be running, others might not.

See Also

  • Event Notification Codes


EC_ERRORABORT

An operation was aborted because of an error.

Parameters

lParam1

HRESULT value of the operation that failed.

lParam2

Zero.

Default Action

None.

See Also

  • Event Notification Codes


EC_EXTDEVICE_MODE_CHANGE

Not supported.

See Also

  • Event Notification Codes


EC_FULLSCREEN_LOST

The video renderer is switching out of full-screen mode.

Parameters

lParam1

Zero.

lParam2

Pointer to the video renderer's IBaseFilter interface, or NULL.

Default Action

None.

Remarks

When the Full Screen Renderer loses activation, it sends this event. When another video renderer switches out of full-screen mode, the filter graph manager sends this event, in response to an EC_ACTIVATE event from the renderer.

See Also

  • Event Notification Codes


EC_GRAPH_CHANGED

The filter graph has changed.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

Remarks

This event code is intended for debugging. It is not sent for all graph changes.

See Also

  • Event Notification Codes


EC_LENGTH_CHANGED

The length of a source has changed.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

The Filter Graph Manager stores the new stop time.

See Also

  • Event Notification Codes


EC_NEED_RESTART

A filter is requesting that the graph be restarted.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

The filter graph manager pauses and restarts the graph. It does not pass the event to the application.

Remarks

If a filter rejects a sample in the middle of a stream, the upstream pin will stop delivering samples. The filter can restart the stream by sending this event. For example, the audio renderer might lose access to the sound device, because a video window has lost focus. At that point, the audio renderer starts rejecting samples. When it regains access to the sound device, it sends this event to restart the audio stream.

See Also

  • Event Notification Codes


EC_NOTIFY_WINDOW

Notifies a filter of the video renderer's window.

Parameters

lParam1

Handle to the window.

lParam2

Zero.

Default Action

This event is used internally by DirectShow. The filter graph manager does not pass this event to the application. Applications cannot override the default action for this event.

Remarks

When a video renderer is connected, it checks whether the upstream output pin supports the IMediaEventSink interface. If so, the renderer sends this event to the upstream filter.

See Also

  • Event Notification Codes


EC_OLE_EVENT

A filter is passing a text string to the application.

Parameters

lParam1

String of type BSTR.

lParam2

String of type BSTR.

Default Action

None.

Remarks

By convention, the first parameter contains type information (for example, Text) and the second parameter contains the text string.

See Also

  • Event Notification Codes


EC_OPENING_FILE

The graph is opening a file, or has finished opening a file.

Parameters

lParam1

TRUE if the graph is starting to open a file, or FALSE if the graph is no longer opening the file.

lParam2

Zero.

Default Action

None.

Remarks

A filter can send this event if it spends significant time opening a file. (For example, the file might be located on a network.) The application can use this event to adjust its user interface.

See Also

  • Event Notification Codes


EC_PALETTE_CHANGED

The video palette has changed.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

Remarks

Video renderers send this event if they detect a palette change in the stream.

See Also

  • Event Notification Codes


EC_PAUSED

A pause request has completed.

Parameters

lParam1

HRESULT value that indicates the result of the transition. If the value is S_OK, the filter graph is now in a paused state.

lParam2

Zero.

Default Action

None.

Remarks

The filter graph manager sends this event when it completes an asynchronous pause command.

See Also

  • Event Notification Codes


EC_QUALITY_CHANGE

The graph is dropping samples, for quality control.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

Remarks

A filter sends this event if it drops samples in response to a quality control message. It sends the event only when it adjusts the quality level, not for each sample that it drops. For more information, see Quality-Control Management.

See Also

  • Event Notification Codes


EC_REPAINT

A video renderer requires a repaint.

Parameters

lParam1

Pointer to the IPin interface of the video renderer's input pin, or NULL.

lParam2

Zero.

Default Action

The lParam1 parameter might specify the video renderer's input pin. If so, the filter graph manager finds the output pin connected to that pin and queries it for the IMediaEventSink interface. If the output pin supports IMediaEventSink, the filter graph manager calls IMediaEventSink::Notify with the EC_REPAINT event code. This gives the upstream filter the opportunity to re-send the last sample.

If lParam1 is NULL, or if the pin does not support IMediaEventSink, or if the Notify method fails, the filter graph manager handles the EC_REPAINT event by itself. Its behavior depends on the state of the graph:

  • Running: Ignores the event. (The renderer will receive the next sample in the stream.)
  • Paused: Seeks the graph to its current location, thereby flushing the filter and re-queuing the data.
  • Stopped: Pauses and stops the graph, thereby re-queuing the data.

By default, the filter graph manager does not pass this event to the application.

Remarks

Video renderers send this message when they receive a WM_PAINT message and have no data to display.

See Also

  • Event Notification Codes


EC_SEGMENT_STARTED

A new segment has started.

Parameters

lParam1

Pointer to a REFERENCE_TIME value that specifies the accumulated stream time since the start of the segment.

lParam2

DWORD value indicating the segment number (zero-based).

Default Action

This event is not sent to the application. Applications cannot override the default action for this event.

Remarks

If a filter will send an EC_END_OF_SEGMENT at the end of a segment, it sends this event at the start of the segment. The filter graph manager uses this event notification to compute how many EC_END_OF_SEGMENT notifications it should expect at the end of the segment.

By default, filters do not send EC_END_OF_SEGMENT events at the end of segments, and therefore should not send this event. For more information, see IMediaSeeking::SetPositions.

See Also

  • Event Notification Codes


EC_SHUTTING_DOWN

The filter graph is shutting down, prior to being destroyed.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

This event is not sent to the application. The filter graph manager sends it to plug-in distributors, to notify them that the graph is shutting down. Applications cannot override the default action of this event.

See Also

  • Event Notification Codes


EC_SNDDEV_IN_ERROR

An audio device error occurred on an input pin.

Parameters

lParam1

DWORD value from the SNDDEV_ERR enumerated type, indicating how the device was being accessed when the failure occurred.

lParam2

DWORD value indicating the error returned from the sound device call.

Default Action

None.

See Also

  • Event Notification Codes


EC_SNDDEV_OUT_ERROR

An audio device error occurred on an output pin.

Parameters

lParam1

DWORD value from the SNDDEV_ERR enumerated type, indicating how the device was being accessed when the failure occurred.

lParam2

DWORD value indicating the error returned from the sound device call.

Default Action

None.

See Also

  • Event Notification Codes


EC_STARVATION

A filter is not receiving enough data.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

The event is not sent to the application. If the filter graph is running, the filter graph manager pauses the graph and waits for the pause to complete. Then it runs the graph again. The filter sending the event should not complete its transition to paused until it has enough data to resume. If the filter graph is not running, the filter graph manager ignores this event.

Remarks

A parser or source filter can send this event if too little data is arriving.

See Also

  • Event Notification Codes


EC_STATE_CHANGE

The filter graph has changed state.

Parameters

lParam1

Member of the FILTER_STATE enumerated type, indicating the new graph state.

lParam2

Zero.

Default Action

No default action. The event is not sent to the application.

Note This event can occur when the graph shuts down. If you override the default action and listen for this event, you must be especially careful not to process events after releasing the Filter Graph Manager. Otherwise, your application might reference an invalid IMediaEvent pointer and crash. For more information, see Responding to Events.

See Also

  • Event Notification Codes


EC_STEP_COMPLETE

A filter has completed frame stepping.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

The filter graph manager pauses the graph and passes the event to the application.

See Also

  • Event Notification Codes
  • IVideoFrameStep::Step


EC_STREAM_CONTROL_STARTED

A stream-control start command has taken effect.

Parameters

pSender

Pointer to the IPin interface of the pin that started the stream.

dwCookie

User-defined DWORD value.

Default Action

None.

Remarks

Filters send this event in response to the IAMStreamControl::StartAt method. This method specifies a reference time for a pin to begin streaming. When streaming does begin, the filter sends this event.

The pSender parameter specifies the pin that executes the start command. Depending on the implementation, it might not be the pin that received the StartAt call.

The dwCookie parameter is specified by the application in the StartAt method. This parameter enables the application to track multiple calls to the method.

See Also

  • Event Notification Codes


EC_STREAM_CONTROL_STOPPED

A stream-control start command has taken effect.

Parameters

pSender

Pointer to the IPin interface of the pin that stopped the stream.

dwCookie

User-defined DWORD value.

Default Action

None.

Remarks

Filters send this event in response to the IAMStreamControl::StopAt method. This method specifies a reference time for a pin to stop streaming. When streaming does halt, the filter sends this event.

The pSender parameter specifies the pin that executes the stop command. Depending on the implementation, it might not be the pin that received the StopAt call.

The dwCookie parameter is specified by the application in the StopAt method. This parameter enables the application to track multiple calls to the method.

See Also

  • Event Notification Codes


EC_STREAM_ERROR_STILLPLAYING

An error occurred in a stream, but the stream is still playing.

Parameters

lParam1

HRESULT of the operation that failed.

lParam2

DWORD value, generally zero.

Default Action

None. The application must decide whether to stop the graph.

See Also

  • Event Notification Codes


EC_STREAM_ERROR_STOPPED

A stream has stopped because of an error.

Parameters

lParam1

HRESULT of the operation that failed.

lParam2

DWORD value, generally zero.

Default Action

None.

See Also

  • Event Notification Codes


EC_TIMECODE_AVAILABLE

Not supported.

See Also

  • Event Notification Codes


EC_UNBUILT

The EC_UNBUILT event is sent by the Video Control when a graph has been torn down. This event is not forwarded to applications.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None.

See Also

  • Event Notification Codes


EC_USERABORT

The user has terminated playback.

Parameters

lParam1

Zero.

lParam2

Zero.

Default Action

None. The application must decide whether to stop the graph.

Remarks

This event code signals that the user has terminated normal graph playback. For example, video renderers send this event if the user closes the video window.

After sending this event, the filter should reject all samples and not send any EC_REPAINT events, until the filter stops and is reset.

See Also

  • Event Notification Codes


EC_VIDEO_SIZE_CHANGED

The native video size has changed.

Parameters

lParam1

Low-order WORD specifies the new width, in pixels; high-order WORD specifies the new height, in pixels.

lParam2

Zero.

Default Action

None.

Remarks

Video renderers send this event if they detect a change in the native video size.

See Also

  • Event Notification Codes


EC_VMR_RENDERDEVICE_SET

Sent when the VMR has selected its rendering mechanism.

lParam1

May be one of the following values:

Value | Meaning
VMR_RENDER_DEVICE_OVERLAY | The VMR will render to the overlay surface (VMR-7 only).
VMR_RENDER_DEVICE_VIDMEM | The VMR will render to video memory.
VMR_RENDER_DEVICE_SYSMEM | The VMR will render to system memory (VMR-7 only).

lParam2

Not used.

Remarks

This event is sent by both the VMR-7 and the VMR-9 and it is forwarded to applications. Note that the VMR-9 only supports video memory render targets.

See Also

  • Event Notification Codes


EC_VMR_SURFACE_FLIPPED

Sent when the VMR-7's allocator presenter has called the DirectDraw Flip method on the surface being presented. This allows the VMR to keep its DirectXVA table of surfaces synchronized with DirectDraw's flipping chain.

lParam1

HRESULT code returned from the DirectDraw Flip method.

lParam2

Not used.

Remarks

Custom allocator-presenters for the VMR-7 should send this event. This event is not forwarded to applications and it is not used with allocator-presenters for the VMR-9.

See Also

  • Event Notification Codes


EC_VMR_RECONNECTION_FAILED

Sent by the VMR-7 and the VMR-9 when it was unable to accept a dynamic format change request from the upstream decoder.

lParam1

HRESULT code returned from ReceiveConnection on the VMR's input pin that failed the reconnection.

lParam2

Not used.

Remarks

This event is forwarded to applications.

See Also

  • Event Notification Codes


EC_WINDOW_DESTROYED

The video renderer was destroyed or removed from the graph.

Parameters

lParam1

Pointer to the video renderer's IBaseFilter interface.

lParam2

Zero.

Default Action

The filter graph manager releases this window as the focus, through the IResourceManager interface. It does not send the event notification to the application.

Remarks

The video renderer sends this event when it leaves the filter graph, in its IBaseFilter::JoinFilterGraph method. (Sending the event when the filter is destroyed might be too late, because at that point the filter graph manager might also be destroyed.)

This event enables other filters to acquire resources that depend on window focus, such as audio devices.

See Also

  • Event Notification Codes


EC_WMT_EVENT

This event is sent when an application uses the ASF Reader filter to play ASF files protected by digital rights management (DRM).

Parameters

lParam1

Can be one of the following WMT_STATUS values:

WMT_STATUS Message | Description
WMT_NO_RIGHTS | The application has no rights to perform he requested action on a file protected by DRM version 1.
WMT_ACQUIRE_LICENSE | Sent when the DRM component has completed the license acquisition process, either successfully or unsuccessfully.
WMT_NO_RIGHTS_EX | The application has no rights to perform he requested action on a file protected by DRM version 7.
WMT_NEEDS_INDIVIDUALIZATION | The file requires that an application receive a security upgrade before performing the requested action.
WMT_INDIVIDUALIZE | The security upgrade process has completed, either successfully or unsuccessfully.

lParam2

Optional pointer to an AM_WMT_EVENT_DATA structure that contains information about the event. The pData member of this structure points to additional data, whose type depends on the value of lParam1, as shown in the following table.

lParam1 | AM_WMT_EVENT_DATA.pData
WMT_NO_RIGHTS | Pointer to a wide-character string containing a challenge URL.
WMT_ACQUIRE_LICENSE | Pointer to a WM_GET_LICENSE_DATA structure (defined in the Windows Media Format SDK).
WMT_NO_RIGHTS_EX | Pointer to a WM_GET_LICENSE_DATA structure (defined in the Windows Media Format SDK).
WMT_NEEDS_INDIVIDUALIZATION | NULL.
WMT_INDIVIDUALIZE | Pointer to a WM_INDIVIDUALIZE_STATUS structure (defined in the Windows Media Format SDK).

The value of lParam2 might be NULL. Check the value before dereferencing the pointer.

Remarks

See the Windows Media Format SDK documentation for more information on enabling playback of DRM-protected files.

See Also

  • Event Notification Codes


EC_WMT_INDEX_EVENT

Sent by the Windows Media Format SDK when an application uses the ASF Writer to index Windows Media Video files.

Parameters

lParam1

Can be one of the following WMT_STATUS messages.

Message | Description
WMT_STARTED | Indexing has begun. lParam2 is zero.
WMT_CLOSED | Indexing has completed. lParam2 is zero.
WMT_INDEX_PROGRESS | Indexing is in progress.

lParam2

If lParam1 is WMT_CLOSED or WMT_STARTED, then lParam2 is zero. If lParam1 is WMT_INDEX_PROGRESS, then lParam2 is a DWORD that expresses the amount of progress as a percentage.

See Also

  • Event Notification Codes


Filter Categories

The following tables list the CLSIDs for the standard DirectShow filter categories. To enumerate the filters in a given category, pass the corresponding CLSID to the ICreateDevEnum::CreateClassEnumerator method. These categories also appear in GraphEdit when you choose Insert Filters from the Graph menu.

The following categories are defined in Uuids.h. They are defiined when you include Dshow.h.

Friendly Name | CLSID | Merit
Audio Capture Sources | CLSID_AudioInputDeviceCategory | MERIT_DO_NOT_USE
Audio Compressors | CLSID_AudioCompressorCategory | MERIT_DO_NOT_USE
Audio Renderers | CLSID_AudioRendererCategory | MERIT_NORMAL
Device Control Filters | CLSID_DeviceControlCategory | MERIT_DO_NOT_USE
DirectShow Filters | CLSID_LegacyAmFilterCategory | MERIT_NORMAL
External Renderers | CLSID_TransmitCategory | MERIT_DO_NOT_USE
Midi Renderers | CLSID_MidiRendererCategory | MERIT_NORMAL
Video Capture Sources | CLSID_VideoInputDeviceCategory | MERIT_DO_NOT_USE
Video Compressors | CLSID_VideoCompressorCategory | MERIT_DO_NOT_USE
Video Effects (1 input) | CLSID_VideoEffects1Category | MERIT_DO_NOT_USE
Video Effects (2 inputs) | CLSID_VideoEffects2Category | MERIT_DO_NOT_USE
WDM Streaming Capture Devices | AM_KSCATEGORY_CAPTURE | MERIT_DO_NOT_USE
WDM Streaming Crossbar Devices | AM_KSCATEGORY_CROSSBAR | MERIT_DO_NOT_USE
WDM Streaming Rendering Devices | AM_KSCATEGORY_RENDER | MERIT_DO_NOT_USE
WDM Streaming Tee/Splitter Devices | AM_KSCATEGORY_SPLITTER | MERIT_DO_NOT_USE
WDM Streaming TV Audio Devices | AM_KSCATEGORY_TVAUDIO | MERIT_DO_NOT_USE
WDM Streaming TV Tuner Devices | AM_KSCATEGORY_TVTUNER | MERIT_DO_NOT_USE
WDM Streaming VBI Codecs | AM_KSCATEGORY_VBICODEC | MERIT_DO_NOT_USE
ActiveMovie Filter Categories | CLSID_ActiveMovieCategories | Not applicable

The following categories are defined in the header file Ks.h:

Friendly Name | CLSID | Merit
WDM Streaming Communication Transforms | KSCATEGORY_COMMUNICATIONSTRANSFORM | MERIT_DO_NOT_USE
WDM Streaming Data Transforms | KSCATEGORY_DATATRANSFORM | MERIT_DO_NOT_USE
WDM Streaming Interface Transforms | KSCATEGORY_INTERFACETRANSFORM | MERIT_DO_NOT_USE
WDM Streaming Mixer Devices | KSCATEGORY_MIXER | MERIT_DO_NOT_USE

The following categories are defined in the header file Ksmedia.h. Include these header files, in the order listed:

#include <ks.h>
#include <ksmedia.h>

Friendly Name | CLSID | Merit
WDM Streaming System Audio Devices | KSCATEGORY_AUDIO_DEVICE | MERIT_DO_NOT_USE

The following categories are defined in the header file Bdamedia.h. Include these header files, in the order listed:

#include <ks.h>
#include <ksmedia.h>
#include <bdamedia.h>
Friendly Name | CLSID | Merit
BDA CP/CA Filters Category | CLSID_CPCAFiltersCategory | MERIT_NORMAL
BDA Network Providers | KSCATEGORY_BDA_NETWORK_PROVIDER | MERIT_NORMAL
BDA Receiver Components | KSCATEGORY_BDA_RECEIVER_COMPONENT | MERIT_NORMAL
BDA Rendering Filters | KSCATEGORY_IP_SINK | MERIT_DO_NOT_USE
BDA Source Filters | KSCATEGORY_BDA_NETWORK_TUNER | MERIT_DO_NOT_USE
BDA Transport Information Renderers | KSCATEGORY_BDA_TRANSPORT_INFORMATION | MERIT_NORMAL

Remarks

The "DirectShow Filters" category contains miscellaneous filters, including decoders.

The "Video Effects (1 input)" and "Video Effects (2 inputs)" categories contain video effects and transitions for DirectShow Editing Services.

"ActiveMove Filter Cateories" is a meta-category; the other filter categories are registered under this category. For more information, see Layout of the Registry Keys.

See Also

  • Enumerating Devices and Filters
  • Intelligent Connect


Media Types

Microsoft® DirectShow® uses the AM_MEDIA_TYPE structure to describe media samples. This structure includes GUID members for major type, subtype, and format type. This section summarizes the major type and subtype GUIDs that are defined for DirectShow. Third-party filters may define their own media type GUIDs.

  • Major Types
  • Audio Subtypes
  • BDA Media Types
  • DVD Media Types
  • Line 21 Media Types
  • MPEG-1 Media Types
  • MPEG-2 Media Types
  • Stream Subtypes
  • Video Subtypes


Major Types

The following table describes the major media types.

GUID | Description
MEDIATYPE_AnalogAudio | Analog audio.
MEDIATYPE_AnalogVideo | Analog video.
MEDIATYPE_Audio | Audio.
MEDIATYPE_AUXLine21Data | Line 21 data. Used by closed captions.
MEDIATYPE_File | File. (Obsolete)
MEDIATYPE_Interleaved | Interleaved audio and video. Used for Digital Video (DV).
MEDIATYPE_LMRT | Obsolete. Do not use.
MEDIATYPE_Midi | MIDI format.
MEDIATYPE_MPEG2_PES | MPEG-2 PES packets.
MEDIATYPE_MPEG2_SECTION | MPEG-2 section data
MEDIATYPE_ScriptCommand | Data is a script command, used by closed captions.
MEDIATYPE_Stream | Byte stream with no time stamps.
MEDIATYPE_Text | Text.
MEDIATYPE_Timecode | Timecode data.
MEDIATYPE_URL_STREAM | Obsolete. Do not use.
MEDIATYPE_Video | Video.

The subtype GUID further defines the format. For some formats, the subtype GUID might be MEDIASUBTYPE_None, which means the format does not require a subtype.


Audio Subtypes

The following table describes the audio media subtypes.

GUID | Description
MEDIASUBTYPE_PCM | PCM audio.
MEDIASUBTYPE_PCMAudioObsolete | Obsolete. Do not use.
MEDIASUBTYPE_MPEG1Packet | MPEG1 Audio packet.
MEDIASUBTYPE_MPEG1Payload | MPEG1 Audio Payload.
MEDIASUBTYPE_MPEG2_AUDIO | MPEG-2 audio data
MEDIASUBTYPE_DVD_LPCM_AUDIO | DVD audio data
MEDIASUBTYPE_MPEG2_AUDIO | MPEG-2 audio data
MEDIASUBTYPE_DRM_Audio | Corresponds to WAVE_FORMAT_DRM.
MEDIASUBTYPE_IEEE_FLOAT | Corresponds to WAVE_FORMAT_IEEE_FLOAT
MEDIASUBTYPE_DOLBY_AC3 | Dolby data
MEDIASUBTYPE_DOLBY_AC3_SPDIF | Dolby AC3 over SPDIF.
MEDIASUBTYPE_RAW_SPORT | Equivalent to MEDIASUBTYPE_DOLBY_AC3_SPDIF.
MEDIASUBTYPE_SPDIF_TAG_241h | Equivalent to MEDIASUBTYPE_DOLBY_AC3_SPDIF.

The wFormatTag field in the WAVEFORMATEX structure specifies the audio format type. The format type is generally FORMAT_WaveFormatEx. Media samples are generally whole number of samples as specified in the wBitsPerSample field in the WAVEFORMATEX structure. This is not necessarily true for MPEG audio samples that can come from packetized streams and are therefore not necessarily packaged on sample / frame boundaries. For MPEG audio the time stamp in a media sample is the time stamp for the first frame whose first byte is contained in the media sample.

Media subtypes are defined for each wFormatTag as follows:

  • The Data1 subfield of the Media Subtype is the same as the wFormatTag value.
  • The Data 2 field is 0.
  • The Data 3 field is 0x0010.
  • The Data 4 field is 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71.

Thus, for PCM audio the subtype GUID (defined in uuids.h as MEDIASUBTYPE_PCM) is:

{00000001-0000-0010-8000-00AA00389B71}

To specify padded AC3 use 0x0092 for the wFormatTag and the corresponding subtype MEDIASUBTYPE_DOLBY_AC3_SPDIF. The values 0x240 and 0x241 have also been used to indicate padded AC3 but Microsoft encourages the use of 0x0092.

The CreateAudioMediaType function can be used to create an AM_MEDIA_TYPE structure from a WAVEFORMATEX structure.

See Also

  • Multiple Channel Audio Data and WAVE Files


BDA Media Types

The following tables describe the media types used for BDA digital television filters.

Antenna

This media type is used for the pin connection between the Network Provider filter and the tuner filter.

Major type | KSDATAFORMAT_TYPE_BDA_ANTENNA
Subtype | MEDIASUBTYPE_None
Format type | FORMAT_None

Intermediate Frequency (IF) Signal

This media type represents the IF signal that is sent from the tuner to the demodulator.

Major type | KSDATAFORMAT_TYPE_BDA_IF_SIGNAL
Subtype | MEDIASUBTYPE_None
Format type | FORMAT_None


DVD Media Types

The following tables describe the media types used for DVD.

Major Types

GUID | Description
MEDIATYPE_DVD_ENCRYPTED_PACK | Encrypted DVD data
MEDIATYPE_MPEG2_PES | MPEG-2 Packetized Elementary Stream (PES)

Subtypes

GUID | Description
MEDIASUBTYPE_MPEG2_VIDEO | MPEG-2 video
MEDIASUBTYPE_DOLBY_AC3 | Dolby AC3 audio
MEDIASUBTYPE_DVD_SUBPICTURE | DVD Subpicture


Line 21 Media Types

The following tablea describe the media types used for line 21 data.

Major Type

GUID | Description
MEDIATYPE_AUXLine21Data | Line 21 data

Subtypes

GUID | Description
MEDIASUBTYPE_Line21_BytePair | Line 21 data as byte pairs
MEDIASUBTYPE_Line21_GOPPacket | Line 21 data in DVD GOP Packet
MEDIASUBTYPE_Line21_VBIRawData | Line 21 data in raw VBI format


MPEG-1 Media Types

This section lists the media types used for MPEG-1 data.

MPEG-1 System Stream

Major type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG1System
Format Type | GUID_NULL
Format Structure | None
Media Sample Contents | Byte stream; no alignment

MPEG-1 System Stream from Video CD

Major type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_MPEG1VideoCD
Format Type | GUID_NULL
Format Structure | None
Media Sample Contents | Byte stream; no alignment.

MPEG-1 Audio Packet

Major type | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_MPEG1Packet
Format Type | FORMAT_WaveFormatEx
Format Structure | MPEG1WAVEFORMAT
Media Sample Contents | Single MPEG-1 packet, including packet header.

MPEG-1 Audio payload

Major type | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_MPEG1Payload
Format Type | FORMAT_WaveFormatEx
Format Structure | MPEG1WAVEFORMAT
Media Sample Contents | Byte-aligned MPEG-1 audio data.

MPEG-1 Video Packet

Major type | MEDIATYPE_Video
Subtype | MEDIASUBTYPE_MPEG1Packet
Format Type | FORMAT_MPEGVideo
Format Structure | MPEG1VIDEOINFO
Media Sample Contents | Single MPEG-1 packet, including packet header.

MPEG-1 Video payload

Major type | MEDIATYPE_Video
Subtype | MEDIASUBTYPE_MPEG1Payload
Format Type | FORMAT_MPEGVideo
Format Structure | MPEG1VIDEOINFO
Media Sample Contents | Byte-aligned MPEG-1 video data.

MPEG-1 Native Video Stream

Major type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_ MPEG1Video
Format Type | GUID_NULL
Format Structure | None
Media Sample Contents | Array of video stream bytes (no system layer).

MPEG-1 Native Audio Stream

Major type | MEDIATYPE_Stream
Subtype | MEDIASUBTYPE_ MPEG1Audio
Format Type | GUID_NULL
Format Structure | None
Media Sample Contents | Array of audio stream bytes (no system layer).

The DirectShow MPEG-1 filters support these types as follows.

Filter | Direction | Supported media types
MPEG-1 Splitter | Input | MPEG-1 system stream MPEG-1 system stream from Video CD
MPEG-1 Splitter | Output | MPEG-1 Audio packet MPEG-1 Audio payload MPEG-1 Video packet MPEG-1 Video payload
Software Audio Codec | Input | MPEG-1 Audio packet MPEG-1 Audio payload
Software Video Codec | Input | MPEG-1 Video packet MPEG-1 Video payload
Software Audio Codec | Output | PCM audio
Software Video Codec | Output | Uncompressed video (Y41P, YUY2, UYVY, RGB-24, RGB-32, RGB-565, RGB-555, RGB-8)

MPEG-1 Video packet and payload media types contain a complete sequence header so that data can be played from the middle of a file without needing a sequence header to initialize the video playback.

The video sequence header is appended to the video data type for MPEG video so that play can begin from the middle of a stream. The length of this field is up to 140 bytes; it includes the sequence header start code (0x000001B3) at the start, along with any quantization matrices found in the first sequence header encountered.


MPEG-2 Media Types

This section lists the media types used for MPEG-2 data.

  • MPEG-2 Splitter Media Types
  • MPEG-2 Demultiplexer Media Types
  • MPEG-2 Kernel Media Types

See Also

  • DVD Media Types


MPEG-2 Splitter Media Types

The MPEG-2 Splitter filter currently supports audio and video. Dolby AC-3 is supported as a substream as defined by DVD. The filter also supports MPEG-2 audio. The media types depend on whether the MPEG-2 splitter is delivering PES packets or PES payloads.

Video

For MPEG-2 video, the media types are as follows.

 | PES output | Payload output
Major Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Video
Subtype | MEDIASUBTYPE_MPEG2_VIDEO | MEDIASUBTYPE_MPEG2_VIDEO
Format Type | FORMAT_MPEG2Video | FORMAT_MPEG2Video
Format Structure | MPEG2VIDEOINFO | MPEG2VIDEOINFO

AC-3 Audio

For AC-3 audio, the media types are as follows.

 | PES output | Payload output
Major Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_DOLBY_AC3 | MEDIASUBTYPE_DOLBY_AC3
Format Type | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format Structure | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for AC-3 is currently WAVE_FORMAT_UNKNOWN, but this might change.

MPEG-2 Audio

For MPEG-2 audio, the media types are as follows.

 | PES output | Payload output
Major Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYE_MPEG2_AUDIO | MEDIASUBTYPE_MPEG2_AUDIO
Format Type | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format Structure | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for MPEG-2 Audio is currently WAVE_FORMAT_UNKNOWN, but this might change.

The MPEG-2 Splitter assumes that streams D0 through DF are used for the multichannel extension stream, as they are for DVD MPEG-2 audio. Therefore, whenever stream Cx is selected, the splitter forwards the packets for stream Dx as well.

LPCM Audio

For LPCM audio, the media types are as follows.

 | PES output | Payload output
Major Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_DVD_LPCM_AUDIO | MEDIASUBTYPE_DVD_LPCM_AUDIO
Format Type | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format Structure | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for LPCM audio is currently WAVE_FORMAT_UNKNOWN, but this might change.

See Also

  • MPEG-2 Media Types


MPEG-2 Demultiplexer Media Types

The MPEG-2 Demultiplexer filter recognizes the following media types.

Input Types

The major type is always MEDIATYPE_Stream. The subtype can be any of the following:

GUID | Description
KSDATAFORMAT_SUBTYPE_BDA_MPEG2_TRANSPORT | Transport stream from a Broadcast Driver Architecture (BDA) device filter. The MPEG-2 demultiplexer treats this subtype identically to MEDIASUBTYPE_MPEG2_TRANSPORT.
MEDIASUBTYPE_MPEG2_PROGRAM | Program stream
MEDIASUBTYPE_MPEG2_TRANSPORT | Transport stream (TS), with 188-byte packets
MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE | Transport stream with "strided" packets. This subtype indicates that the TS packets may be padded with extra bytes. For more information, see MPEG2_TRANSPORT_STRIDE.

For strided transport packets (MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE), each media sample must contain an integral number of transport packets, as described in MPEG2_TRANSPORT_STRIDE. For all other input types, there are no restrictions on sample boundaries; individual packets can span sample boundaries.

Output Types

The MPEG-2 Demultiplexer does not validate output types; the downstream filter is responsibe for parsing the data it receives from the demultiplexer. However, the following types are commonly accepted by downstream filters as output from the demultiplexer:

MPEG-2 Sections

Major Type | MEDIATYPE_MPEG2_SECTIONS
Subtype | MEDIASUBTYPE_ATSC_SI: ATSC Service Information MEDIASUBTYPE_DVB_SI: DVB Service Information MEDIASUBTYPE_MPEG2DATA: Used by the MPEG-2 Sections and Tables filter.
Format Type | None

MPEG-2 Video

Major type | MEDIATYPE_Video
Subtype | MEDIASUBTYPE_MPEG2_VIDEO
Format Type | FORMAT_MPEG2Video
Format Structure | MPEG2VIDEOINFO

MPEG-2 Audio

Major type | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_MPEG2_AUDIO
Format Type | FORMAT_WaveFormatEx
Format Structure | WAVEFORMATEX

Requirements

Some of these GUIDs are defined in the header file Bdamedia.h

See Also

  • MPEG-2 Media Types


MPEG-2 Kernel Media Types

For several MPEG-2 media type GUIDs, the Windows DDK defines names that differ from the names used in DirectShow. The following table shows the DirectShow names (defined in Ksuuids.h) and the corresponding kernel-mode names (defined in Ksmedia.h).

Name in Ksuuids.h | Name in Ksmedia.h
FORMAT_WaveFormatEx | KSDATAFORMAT_SPECIFIER_WAVEFORMATEX
FORMAT_MPEG2Video | KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO
MEDIASUBTYPE_ATSC_SI | KSDATAFORMAT_SUBTYPE_ATSC_SI
MEDIASUBTYPE_DOLBY_AC3 | KSDATAFORMAT_SUBTYPE_AC3_AUDIO
MEDIASUBTYPE_DVB_SI | KSDATAFORMAT_SUBTYPE_DVB_SI
MEDIASUBTYPE_DVD_LPCM_AUDIO | KSDATAFORMAT_SUBTYPE_LPCM_AUDIO
MEDIASUBTYPE_MPEG2_AUDIO | KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO
MEDIASUBTYPE_MPEG2_PROGRAM | STATIC_KSDATAFORMAT_TYPE_MPEG2_PROGRAM
MEDIASUBTYPE_MPEG2_TRANSPORT | KSDATAFORMAT_TYPE_MPEG2_TRANSPORT
MEDIASUBTYPE_MPEG2_VIDEO | KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO
MEDIATYPE_MPEG2_SECTIONS | KSDATAFORMAT_TYPE_MPEG2_SECTIONS
MEDIATYPE_Audio | KSDATAFORMAT_TYPE_AUDIO
MEDIATYPE_MPEG2_PES | KSDATAFORMAT_TYPE_MPEG2_PES
MEDIATYPE_Video | KSDATAFORMAT_TYPE_VIDEO

See Also

  • MPEG-2 Media Types


Stream Subtypes

The following table describes the stream media subtypes.

GUID | Description
MEDIASUBTYPE_AIFF | Data from AIFF file
MEDIASUBTYPE_Asf | Advanced Systems Format (ASF)
MEDIASUBTYPE_Avi | Data from AVI file
MEDIASUBTYPE_AU | Data from AU file
MEDIASUBTYPE_DssAudio | Dss Audio
MEDIASUBTYPE_DssVideo | Dss Video
MEDIASUBTYPE_MPEG1Audio | MPEG audio
MEDIASUBTYPE_MPEG1System | MPEG system
MEDIASUBTYPE_MPEG1SystemStream | Obsolete. Do not use.
MEDIASUBTYPE_MPEG1Video | MPEG video
MEDIASUBTYPE_MPEG1VideoCD | MPEG video CD
MEDIASUBTYPE_WAVE | Data from WAV file

Time stamps are byte positions * 10000000 (notionally 1 byte per second) rather than real times.


Video Subtypes

This section describes the video subtype GUIDs:

  • Analog Video Subtypes
  • DirectX Video Acceleration Video Subtypes
  • DV Video Subtypes
  • Uncompressed RGB Video Subtypes
  • Video Mixing Renderer Video Subtypes
  • YUV Video Subtypes
  • Miscellaneous Video Subtypes

See Also

  • FOURCC Codes
  • MPEG-1 Media Types
  • MPEG-2 Media Types


Analog Video Subtypes

The following analog video formats were introduced in Microsoft® ActiveMovie® 1.0 but are now obsolete. Use the AnalogVideoStandard enumeration instead.

GUID | Description
MEDIASUBTYPE_AnalogVideo_NTSC_M | (M) NSTC
MEDIASUBTYPE_AnalogVideo_PAL_B | (B) PAL
MEDIASUBTYPE_AnalogVideo_PAL_D | (D) PAL
MEDIASUBTYPE_AnalogVideo_PAL_G | (G) PAL
MEDIASUBTYPE_AnalogVideo_PAL_H | (H) PAL
MEDIASUBTYPE_AnalogVideo_PAL_I | (I) PAL
MEDIASUBTYPE_AnalogVideo_PAL_M | (M) PAL
MEDIASUBTYPE_AnalogVideo_PAL_N | (N) PAL
MEDIASUBTYPE_AnalogVideo_SECAM_B | (B) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_D | (D) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_G | (G) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_H | (H) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_K | (K) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_K1 | (K1) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_L | (L) SECAM

See Also

  • Video Subtypes


DirectX Video Acceleration Video Subtypes

The following subtypes are used by decoders that are using DirectX Video Acceleration (DXVA). AI44 and IA44 are surfaces with a bits-per-pixel value of 8. There are 4 bits of I and 4 bits of A. I represents an index into a 16-entry YUV palette. A represents 4 bits of transparency information (also known as per-pixel-alpha). Therefore, AI44 and IA44 surfaces allow for 16 different colors at 16 different transparency values, or 256 different pixel representations. With AI44 the alpha is stored in the hi-nibble, in IA44 the alpha is stored in the lo-nibble. Both formats are very useful for DVD sub-picture images and Line21 and Teletext images. Microsoft prefers the AI44 version because it is slightly easier to generate text using this format.

Subtype | Description
MEDIASUBTYPE_AI44 | For subpicture and text overlays. See previous description.
MEDIASUBTYPE_IA44 | For subpicture and text overlays. See previous description.

See Also

  • Video Subtypes


DV Video Subtypes

A number of subtypes are defined for DV video. Each has a FOURCC code and a corresponding GUID value. Not all of these formats are supported; see the Remarks section for more information.

Consumer Formats

FOURCC | GUID | Data Rate | Description
'dvsl' | MEDIASUBTYPE_dvsl | 12.5 Mbps | SD-DVCR 525-60 or SD-DVCR 625-50
'dvsd' | MEDIASUBTYPE_dvsd | 25 Mbps | SDL-DVCR 525-60 or SDL-DVCR 625-50
'dvhd' | MEDIASUBTYPE_dvhd | 50 Mbps | HD-DVCR 1125-60 or HD-DVCR 1250-50

Refer to IEC-61834 for more information about these formats.

Professional Formats

FOURCC | GUID | Data Rate | Description
'dv25' | MEDIASUBTYPE_dv25 | 25 Mbps | DVCPRO 25 (525-60 or 625-50)
'dv50' | MEDIASUBTYPE_dv50 | 50 Mbps | DVCPRO 50 (525-60 or 625-50)
'dvh1' | MEDIASUBTYPE_dvh1 | 100 Mbps | DVCPRO 100 (1080/60i, 1080/50i, or 720/60P)

Refer to SMPTE 314M for more information about dv25 and dv50, and SMPTE 370M for more information about dvh1.

Miscellaneous

Two additional DV subtypes are defined in the header file Uuids.h. These correspond to FOURCC codes that are produced by certain DV codecs; they do no correspond to any defined DV standards. These subtypes are obsolete and should not be used.

FOURCC | GUID
'DVCS' | MEDIASUBTYPE_DVCS
'DVSD' | MEDIASUBTYPE_DVSD

Remarks

When data is captured from an external DV device, the MSDV driver parses the transport data, while the DV Splitter and DV Video Decoder filters parse the contents of the data packets. Currently, these components provide the following support:

  • The MSDV driver supports data rates up to 25 Mbps. It does not support 50 Mbps or higher data rates. For 25-Mbps streams, the MSDV driver sets the media type to MEDIASUBTYPE_dvsd regardless of the source (SDL-DVCR or DVCPRO 25).
  • The DV Splitter and DV Video Decoder filters support MEDIASUBTYPE_dvsd only. The data can be PAL or NTSC. Third-party filters or codecs may be available that can parse other DV formats, as long as the data rate is supported by the MSDV driver.

In practice, this means applications can capture both 25-Mbps formats, SDL-DVCR and DVCPRO 25. Application can transmit both formats to tape, as long as the target device matches the capture device. In other words, if you capture DVCPRO 25 from a device, you can transmit it back to the same device, but not to an SDL-DVCR device.

See Also

  • Digital Video in DirectShow
  • MSDV Driver
  • Video Subtypes


Uncompressed RGB Video Subtypes

The following subtypes define uncompressed RGB formats.

GUID | Description
MEDIASUBTYPE_RGB1 | RGB, 1 bit per pixel (bpp), palettized
MEDIASUBTYPE_RGB4 | RGB, 4 bpp, palettized
MEDIASUBTYPE_RGB8 | RGB, 8 bpp
MEDIASUBTYPE_RGB565 | RGB 555, 16 bpp
MEDIASUBTYPE_RGB555 | RGB 565, 16 bpp
MEDIASUBTYPE_RGB24 | RGB, 24 bpp
MEDIASUBTYPE_RGB32 | RGB, 32 bpp, no alpha channel
MEDIASUBTYPE_ARGB32 | RGB, 32 bpp, alpha channel

For palettized formats, the color of each pixel is specified as an index into a palette. The palette must be included in the format block, following the BITMAPINFOHEADER structure. For non-palettized formats, the color of each pixel is specified directly; the memory layout depends on the bit depth:

  • RGB 555 uses the following memory layout:
High-order byte:    Low-order byte:
X R R R R R G G     G G G B B B B B

X = Don't care, R = Red, G = Green, B = Blue
  • RGB 565 uses the following memory layout:
High-order byte:    Low-order byte:
R R R R R G G G     G G G B B B B B
  • For 24-bit RGB, every pixel is an RGBTRIPLE. Each color is one byte, with a value from 0 to 255, inclusive. The memory layout is:
    Byte | 0 | 1 | 2
    Value | Blue | Green | Red

  • For 32-bit RGB, every pixel is an RGBQUAD. Each color is one byte, with a value from 0 to 255, inclusive. The memory layout is:
    Byte | 0 | 1 | 2 | 3
    Value | Blue | Green | Red | Alpha or Don't Care

If the subtype is MEDIASUBTYPE_ARGB32, byte 3 contains a value for the alpha channel. If the subtype is MEDIASUBTYPE_RGB32, byte 3 should be ignored.

See Also

  • Video Subtypes


Video Mixing Renderer Video Subtypes

Sybtype | Description
MEDIASUBTYPE_RGB32_D3D_DX7_RT | 32-bit RGB render target.
MEDIASUBTYPE_RGB16_D3D_DX7_RT | 16-bit RGB render target.
MEDIASUBTYPE_ARGB32_D3D_DX7_RT | 32-bit ARGB render target.
MEDIASUBTYPE_ARGB4444_D3D_DX7_RT | ARGB4444 render target (for subpicture graphics).
MEDIASUBTYPE_ARGB1555_D3D_DX7_RT | ARGB1555 render target (for subpicture graphics).

See Also

  • Video Subtypes


YUV Video Subtypes

YUV formats are divided into packed formats and planar formats. In a packed format, the Y, U, and V components are stored in a single array. Pixels are organized into groups of macropixels, whose layout depends on the format. In a planar format, the Y, U, and V components are stored separately, as three planes.

Packed YUV Formats

The following subtype GUIDs identify packed YUV formats.

GUID | Description
MEDIASUBTYPE_AYUV | 4:4:4 YUV format
MEDIASUBTYPE_UYVY | UYVY (packed 4:2:2)
MEDIASUBTYPE_Y411 | Same as Y41P
MEDIASUBTYPE_Y41P | Y41P (packed 4:1:1)
MEDIASUBTYPE_Y211 | Y211
MEDIASUBTYPE_YUY2 | YUY2 (packed 4:2:2)
MEDIASUBTYPE_YVYU | YVYU (packed 4:2:2)
MEDIASUBTYPE_YUYV | Same as YUY2. (Used by Canopus; FOURCC 'YUYV')

  • AYUV is a 4:4:4 YUV format with the following byte order:

    A0 Y0 U0 V0

    where A0 contains the alpha value.

  • UYVY format uses 2:1 horizontal downsampling and no vertical downsampling. Y is sampled at every pixel; U and V are sampled every 2 pixels horizontally. Each macropixel is 4 bytes and contains 2 pixels. It uses the following byte order:

    U0 Y0 V0 Y1

    Y41P format uses 4:1 horizontal downsampling and no vertical downsampling. Y is sampled at every pixel; U and V are sampled every 4 pixels horizontally. Each macropixel is 12 bytes and contains 8 pixels. It uses the following byte order:

    U0 Y0 V0 Y1   U4 Y2 V4 Y3   Y4 Y5 Y6 Y8

  • YUY2 is similar to UYVY but the byte order is different:

    Y0 U0 Y1 V0

  • YVYU is also similar to UYVY with a different byte order:

    Y0 V0 Y1 U0

  • In Y211 format, Y is sampled every 2 pixels horizontally, and U and V are sampled every 4 pixels horizontally. Each macropixel is 4 bytes and contains 4 pixels. It uses the following byte order:

    Y0 U0 Y2 V0

Planar YUV Formats

The following subtype GUIDs identify planar YUV formats.

GUID | Description
MEDIASUBTYPE_IF09 | Indeo YVU9
MEDIASUBTYPE_IYUV | IYUV
MEDIASUBTYPE_YV12 | YV12
MEDIASUBTYPE_YVU9 | YVU9

  • YVU9 format consists of an 8-bpp Y plane, followed by 8-bpp 4×4 U and V planes.
    Sampling Frequency | Horizontal | Vertical
    Y | 1 | 1
    U | 4 | 4
    V | 4 | 4

  • The Indeo YVU9 format (MEDIASUBTYPE_IF09) is a variation of YVU9 with additional delta-frame information after the U plane.
  • IYUV format consists of an 8-bpp Y plane, followed by 8-bpp 2×2 U and V planes.
    Sampling Frequency | Horizontal | Vertical
    Y | 1 | 1
    U | 2 | 2
    V | 2 | 2

  • YV12 format is identical to IYUV but the order of the U and V planes is switched, so the V plane comes before the U plane.

See Also

  • Video Subtypes


Miscellaneous Video Subtypes

The following table lists some additional video subtypes.

GUID | Description
MEDIASUBTYPE_CFCC | MJPG format produced by some cards. (FOURCC 'CFCC')
MEDIASUBTYPE_CLJR | Cirrus Logic CLJR format. (FOURCC 'CLJR')
MEDIASUBTYPE_CPLA | Cinepak UYVY format. (FOURCC 'CPLA')
MEDIASUBTYPE_CLPL | A YUV format supported by some Cirrus Logic drivers. (FOURCC 'CLPL')
MEDIASUBTYPE_IJPG | Intergraph JPEG format. (FOURCC 'IJPG')
MEDIASUBTYPE_MDVF | A DV encoding format. (FOURCC 'MDVF')
MEDIASUBTYPE_MJPG | Motion JPEG (MJPG) compressed video. (FOURCC 'MJPG')
MEDIASUBTYPE_MPEG1Packet | MPEG1 Video Packet.
MEDIASUBTYPE_MPEG1Payload | MPEG1 Video Payload.
MEDIASUBTYPE_Overlay | Video delivered using hardware overlay.
MEDIASUBTYPE_Plum | Plum MJPG format. (FOURCC 'Plum')
MEDIASUBTYPE_QTJpeg | QuickTime JPEG compressed data.
MEDIASUBTYPE_QTMovie | Apple® QuickTime® compression.
MEDIASUBTYPE_QTRle | QuickTime RLE compressed data.
MEDIASUBTYPE_QTRpza | QuickTime RPZA compressed data.
MEDIASUBTYPE_QTSmc | QuickTime SMC compressed data.
MEDIASUBTYPE_TVMJ | TrueVision MJPG format. (FOURCC 'TVMJ')
MEDIASUBTYPE_VideoPort | Video port data, used with DVD.
MEDIASUBTYPE_VPVBI | Video port vertical blanking interval (VBI) data.
MEDIASUBTYPE_VPVideo | Video port video data.
MEDIASUBTYPE_WAKE | MJPG format produced by some cards. (FOURCC 'WAKE')

See Also

  • Video Subtypes


Merit

Defines the order in which the filter graph manager tries filters during graph building.

Syntax

enum
{
    MERIT_PREFERRED     = 0x800000,
    MERIT_NORMAL        = 0x600000,
    MERIT_UNLIKELY      = 0x400000,
    MERIT_DO_NOT_USE    = 0x200000,
    MERIT_SW_COMPRESSOR = 0x100000,
    MERIT_HW_COMPRESSOR = 0x100050
};

Remarks

Each filter is registered with a merit value. When the filter graph manager builds a graph, it enumerates all the filters registered with the correct media type. Then it tries them in order of merit, from highest to lowest. (It uses additional criteria to choose between filters with equal merit.) It never tries filters with a merit value less than or equal to MERIT_DO_NOT_USE.

A filter that should never be considered for ordinary playback should have a merit of MERIT_DO_NOT_USE or less. Filters can be registered with intermediate values not defined by this enumeration, such as MERIT_NORMAL + 1.

See Also

  • Intelligent Connect
  • Guidelines for Registering Filters


Time Format GUIDs

The following globally unique identifiers (GUIDs) define different time formats.

Declaration: Uuids.h.

GUID | Description
TIME_FORMAT_NONE | No format.
TIME_FORMAT_FRAME | Video frames.
TIME_FORMAT_SAMPLE | Samples in the stream.
TIME_FORMAT_FIELD | Interlaced video fields.
TIME_FORMAT_BYTE | Byte offset within the stream.
TIME_FORMAT_MEDIA_TIME | Reference time (100-nanosecond units).

See Also

  • IMediaSeeking


Functions

Microsoft® DirectShow® provides the following function.

Function | Description
AMGetErrorText | Retrieves the error message text for a given message ID.


AMGetErrorText

The AMGetErrorText function retrieves the error message for a given return code, using the current language setting.

This function converts HRESULT return codes to error messages. The constant MAX_ERROR_TEXT_LEN specifies the maximum number of characters in an error message.

Requirements

Link to the library file Quartz.lib.

Syntax

DWORD AMGetErrorText(
    HRESULT hr,
    TCHAR* pBuffer,
    DWORD MaxLen
);

Parameters

hr

HRESULT value.

pBuffer

Pointer to a character buffer that receives the error message.

MaxLen

Number of characters in pBuffer.

Return Value

Returns the number of characters returned in the buffer, or zero if an error occurred.

Remarks

The DirectX SDK also provides the DXGetErrorString9 function, which returns error strings for all of the DirectX components, including DirectShow, plus standard Win32 errors.

Example Code

void ShowError(HRESULT hr)
{
    if (FAILED(hr))
    {
        TCHAR szErr[MAX_ERROR_TEXT_LEN];
        DWORD res = AMGetErrorText(hr, szErr, MAX_ERROR_TEXT_LEN);
        if (res == 0)
        {
            wsprintf(szErr, "Unknown Error: 0x%2x", hr);
        }
        MessageBox(0, szErr, TEXT("Error!"), MB_OK | MB_ICONERROR);
    }
}

See Also

  • Functions


DirectShow Data Types

Microsoft® DirectShow® provides the following type definitions.

Data Type | Description
OAEVENT | Defines an Automation-compatible event handle.
OAHWND | Defines an Automation-compatible window handle.
REFERENCE_TIME | Defines the data type for reference time.
REFTIME | Defines the data type used to express time in seconds.


OAEVENT

The OAEVENT data type defines an event handle that can be used by Automation clients.

Syntax

typedef LONG_PTR OAEVENT;

See Also

  • DirectShow Data Types
  • IMediaEvent::GetEventHandle


OAHWND

The OAHWND data type defines a window handle that can be used by Automation clients.

Syntax

typedef LONG_PTR OAHWND;

See Also

  • DirectShow Data Types
  • IMediaEventEx::SetNotifyWindow
  • IVideoWindow Interface


REFERENCE_TIME

The REFERENCE_TIME data type defines the units for reference time. Each unit of reference time is 100 nanoseconds.

Syntax

typedef LONGLONG REFERENCE_TIME;

Remarks

The REFERENCE_TIME data type is a 64-bit integer.

See Also

  • DirectShow Data Types


REFTIME

The REFTIME data type is used to express time in seconds.

Syntax

typedef double REFTIME;

See Also

  • DirectShow Data Types


MSWebDVD ActiveX Control

The Microsoft® MSWebDVD ActiveX® control can be used to create a script-based DVD application. It exposes the following objects and events to an application.

  • MSWebDVD
  • MSDVDAdm
  • DVDRect
  • MSWebDVD Events


MSWebDVD Object

The methods, properties, and events of the MSWebDVD object enable an application to control all aspects of DVD-Video navigation and playback, and to retrieve information from the disc. The MSWebDVD object does not perform the actual navigation work; rather, it passes the commands to the DVD Navigator filter, a Microsoft® DirectShow® component that reads DVD-Video discs.

The MSWebDVD methods and properties act on the current state of the DVD Navigator or the information on a disc, or both. To store and retrieve various types of application-specific information in the registry, such as user preferences for parental levels and default language, use the methods of the MSDVDAdm object. Use the DVDAdm property to access this object.

See Also

MSWebDVD Events
Writing a Script-Based DVD Application

Methods and Properties by Category

Playback
CanStep | Determines whether the MPEG-2 decoder on the local system can perform frame stepping in a specified direction.
Eject | Ejects or inserts a disc from or into the drive.
FramesPerSecond | Retrieves the video frame rate for the current DVD title.
Pause | Pauses playback at the current location.
Play | Plays the current DVD title.
PlayAtTime | Starts playback in the current title at the specified time.
PlayAtTimeInTitle | Starts playback at the specified time within the specified title.
PlayBackwards | Starts backward playback from the current location at the specified speed.
PlayChapter | Starts playback from the specified chapter in the current title.
PlayChapterInTitle | Plays the specified chapter in the specified title.
PlayChaptersAutoStop | Starts playback at the specified chapter in the specified title, for the number of chapters specified.
PlayForwards | Starts forward playback from the current location at the specified speed.
PlayNextChapter | Starts playback from the next chapter in the current title.
PlayPeriodInTitleAutoStop | Starts playback at the specified time in the specified title until the specified stop time.
PlayPrevChapter | Starts playback from the previous chapter in the current title.
PlayTitle | Starts playback at the beginning of the specified title.
ReplayChapter | Starts playback at the beginning of the current chapter.
Resume | Resumes playback after a menu has been displayed.
StillOff | Resumes playback, canceling still mode.
Step | Advances the DVD-Video stream by the specified number of frames.
Stop | Stops playback.
Menus
ActivateAtPosition | Activates the menu button at the specified position.
ActivateButton | Activates the selected menu button.
ButtonsAvailable | Retrieves the total number of buttons on the current menu.
CurrentButton | Retrieves the number of the selected button.
DefaultMenuLanguage | Retrieves the default menu language from the disc.
GetButtonAtPosition | Retrieves the number of the button at the specified coordinates without selecting or activating it.
GetButtonRect | Retrieves the rectangle for the specified button, in window coordinates.
ReturnFromSubmenu | Returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.
SelectAndActivateButton | Selects and activates the specified button.
SelectAtPosition | Selects the menu button at the specified position.
SelectLeftButton | Selects the left directional button from the displayed menu.
SelectLowerButton | Selects the lower directional button from the displayed menu.
SelectRightButton | Selects the right directional button from the displayed menu.
SelectUpperButton | Selects the upper directional button from the displayed menu.
ShowMenu | Displays the specified menu on the screen.
Audio Stream
AudioStreamsAvailable | Retrieves the number of audio streams available in the current title.
Balance | Sets or retrieves the speaker balance for the audio stream output.
CurrentAudioStream | Sets or retrieves the number of the enabled audio stream.
DefaultAudioLanguage | Retrieves the default audio language from the disc.
DefaultAudioLanguageExt | Retrieves the default audio language extension from the disc.
GetAudioLanguage | Retrieves a string indicating which language is available on the specified audio stream.
IsAudioStreamEnabled | Retrieves a value indicating whether the specified audio stream is enabled in the current title.
Mute | Turns the audio stream output on or off.
SelectDefaultAudioLanguage | Sets the current default audio language in the DVD Navigator.
Volume | Sets or retrieves the audio volume level.
Subpicture Stream
CurrentSubpictureStream | Retrieves the selected subpicture stream.
DefaultSubpictureLanguage | Retrieves the default subpicture language from the disc.
DefaultSubpictureLanguageExt | Retrieves the default subpicture language extension from the disc.
GetSubpictureLanguage | Retrieves the language for the specified subpicture stream.
IsSubpictureStreamEnabled | Retrieves a value indicating whether the specified subpicture stream is enabled in the current title.
PreferredSubpictureStream | Sets or retrieves the user's preferred subpicture stream for the current viewing session.
SelectDefaultSubpictureLanguage | Sets the current default subpicture language in the DVD Navigator.
SubpictureOn | Sets or retrieves the current subpicture state (on or off).
SubpictureStreamsAvailable | Retrieves the number of subpicture streams available in the current title.
Video Rectangle
AspectRatio | Retrieves the aspect ratio of the current video stream as authored on the disc.
BackColor | Sets or retrieves the color of the bars that appear around the edges of the video rectangle when the aspect ratio of the native video is not the same as that of the object's display area.
Capture | Captures a still image from the video frame when the MSWebDVD object is in windowless mode.
FullScreenMode | Sets or retrieves a value indicating whether the display is in full-screen mode.
GetClipVideoRect | Retrieves the clipping rectangle defined for the video display.
GetVideoSize | Retrieves the native video dimensions.
SetClipVideoRect | Sets the clipping rectangle occupied by the video display.
Zoom | Zooms the video display in or out, centered on a given set of screen coordinates.
Closed Captioning
CCActive | Sets or retrieves the current status of closed captioning.
ColorKey | Sets or retrieves the color key used in closed captioning.
CurrentCCService | Sets or retrieves the current closed-captioned service.
Angle Blocks
AnglesAvailable | Retrieves the number of angles available.
CurrentAngle | Sets or retrieves the current angle in an angle block.
Karaoke Audio
GetKaraokeChannelAssignment | Retrieves a value that indicates how the karaoke channels are assigned to the left and right speakers.
GetKaraokeChannelContent | Retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.
KaraokeAudioPresentationMode | Sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.
Text Strings
GetDVDTextLanguageLCID | Retrieves the locale identifier (LCID) for the specified text string block.
GetDVDTextNumberOfLanguages | Retrieves the number of text languages available in the current DVD directory.
GetDVDTextNumberOfStrings | Retrieves the number of text strings available for the specified language.
GetDVDTextString | Retrieves the specified text string from the disc.
GetDVDTextStringType | Retrieves a value that indicates the type of information contained in the specified DVD text string.
GetLangFromLangID | Retrieves a human-readable string when given a primary language identifier (ID).
Parental Management
AcceptParentalLevelChange | Instructs the DVD Navigator to accept or reject the new temporary parental management level.
GetPlayerParentalCountry | Retrieves the current country/region as set in the DVD Navigator.
GetPlayerParentalLevel | Retrieves the parental management level set in the DVD Navigator.
GetTitleParentalLevels | Retrieves the parental management levels for the specified title.
NotifyParentalLevelChange | Enables or disables the event handling for temporary parental management level commands.
SelectParentalCountry | Sets the specified parental country/region for subsequent playback.
SelectParentalLevel | Sets the specified parental level for subsequent playback.
Disc Information
CurrentChapter | Retrieves the number of the chapter currently playing.
CurrentDiscSide | Retrieves the current side of the DVD.
CurrentDomain | Retrieves the DVD domain that the DVD Navigator is in.
CurrentTime | Retrieves the current playback time.
CurrentTitle | Retrieves the number of the title currently playing.
CurrentVolume | Retrieves the volume number for the current root directory.
DVDDirectory | Retrieves or sets the root directory of the current DVD volume.
DVDTimeCode2bstr | Retrieves a String indicating the current time on the disc.
DVDUniqueID | Retrieves a system-generated number that uniquely identifies the current DVD.
GetNumberOfChapters | Retrieves the number of chapters in the specified title.
TitlesAvailable | Retrieves the number of titles available on the DVD.
TotalTitleTime | Retrieves the total playback time for the current title.
UOPValid | Retrieves a value that indicates whether the specified user operation is currently valid.
VolumesAvailable | Retrieves a value specifying the number of volumes in the disc set.
Object Initialization and Control
DisableAutoMouseProcessing | Enables or disables the object's mouse-processing functionality.
DVDAdm | Provides access to the MSDVDAdm object containing methods and properties for saving application and user information.
EnableResetOnStop | Sets or retrieves a value that determines how play will resume when the filter graph transitions out of a stopped state.
PlayState | Retrieves the current play state.
ReadyState | Retrieves the ReadyState of the MSWebDVD object.
RegionChange | Displays a system dialog box that enables the user to change the region associated with the DVD drive.
Render | Initializes the DVD filter graph.
WindowlessActivation | Initializes the MSWebDVD object at design time for either windowed or windowless mode.
Bookmarks
DeleteBookmark | Deletes the current bookmark.
RestoreBookmark | Moves the DVD Navigator to the point on the DVD as specified in the current bookmark, with all audio, video and subpicture settings restored.
SaveBookmark | Saves the current disc position and state of the DVD Navigator to disc so that the user can return to the same place later.
Cursors and ToolTips
CursorType | Sets or retrieves the current cursor type.
GetDelayTime | Retrieves the delay time for the ToolTip associated with the MSWebDVD object.
SetDelayTime | Sets the delay time for the ToolTip associated with the MSWebDVD object.
ShowCursor | Makes the mouse pointer visible when the DVD Navigator is in full-screen mode.
ToolTip | Sets the text for the ToolTip that will appear when the mouse pointer is over the MSWebDVD video rectangle.
ToolTipMaxWidth | Sets or retrieves the maximum width for the ToolTip associated with the MSWebDVD object.
GPRMs and SPRMs
GetGPRM | Retrieves the specified general parameter register.
GetSPRM | Retrieves the specified system parameter register.
SetGPRM | Sets the specified general parameter register to the specified value.


AcceptParentalLevelChange Method

The AcceptParentalLevelChange method accepts or rejects the new temporary parental management level.

Syntax

MSWebDVD.AcceptParentalLevelChange(bAccept);

Parameters

bAccept

Specifies the new parental level as a Boolean value.

Value | Description
true | Accept the new parental management level.
false | Reject the new parental management level.

Return Value

No return value.

Remarks

Call this method in response to an EC_DVD_PARENTAL_LEVEL_CHANGE event notification to specify whether the DVD Navigator should play the content with the new parental level, or branch to where the disc specifies if the new level is rejected.

See Also

  • Enforcing Parental Management Levels
  • GetPlayerParentalCountry
  • GetPlayerParentalLevel
  • GetTitleParentalLevels
  • NotifyParentalLevelChange
  • SelectParentalCountry
  • SelectParentalLevel


ActivateAtPosition Method

The ActivateAtPosition method activates the menu button at the specified position.

Syntax

MSWebDVD.ActivateAtPosition(xPos, yPos);

Parameters

xPos

Specifies x-coordinate as an Integer.

yPos

Specifies the y-coordinate as an Integer.

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

  • ButtonsAvailable
  • CurrentButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAndActivateButton
  • SelectAtPosition


ActivateButton Method

The ActivateButton method activates the selected menu button.

Syntax

MSWebDVD.ActivateButton();

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Use this method to activate a button that has been selected through the SelectLeftButton, SelectLowerButton, SelectUpperButton, or SelectRightButton method.


AnglesAvailable Property

The AnglesAvailable property retrieves the number of angles currently available.

Syntax

[ iAngles = ] MSWebDVD.AnglesAvailable

Return Values

Returns an integer value from 1 through 9 representing the number of angles currently available. If iAngles = 1, there is no angle block at the current location.

Remarks

This property is read-only with no default value. An angle block is a video segment that was shot from more than one camera angle. There can be up to nine angles in an angle block, numbered from 1 through 9. When the DVD Navigator first enters an angle block, it sends your application an EC_DVD_ANGLES_AVAILABLE event notification with the number of angles in lParam1. A disc can be authored to automatically show a menu for available angles when it enters an angle block, but generally an application must determine the number of angles available and offer the user a way to select one.

See Also

  • CurrentAngle


AspectRatio Property

The AspectRatio property retrieves the aspect ratio of the current video stream as authored on the disc.

Syntax

[ nAspectRatio = ] MSWebDVD.AspectRatio

Return Values

Returns a number representing the aspect ratio of the current video stream as authored on the disc (1.33 for a 4:3 aspect ratio or 1.78 for a 16:9 aspect ratio).

Remarks

This property is read-only with no default value.


AudioStreamsAvailable Property

The AudioStreamsAvailable property retrieves the number of audio streams available in the current title.

Syntax

[ iStreams = ] MSWebDVD.AudioStreamsAvailable

Return Values

Returns an integer value from 1 through 8 representing the number of audio streams available in the current title.

Remarks

This property is read-only with no default value. The primary use of multiple audio streams is to provide movie soundtracks in more than one language. Typically, not every title on a disc has all audio streams enabled. For example, the feature movie might have soundtracks in three different languages, but the trailers might have only an English soundtrack. Before a user can select a stream, the application must determine which streams are available within the current title. Note that particular streams are identified by an index from zero through 7.

Discs generally present a menu showing the available soundtracks, enabling the user to select the audio stream to enable.

See Also

  • GetAudioLanguage


BackColor Property

The BackColor property sets or retrieves the color of the bars that appear around the edges of the video rectangle when the aspect ratio of the native video is not the same as that of the object's display area.

Syntax

[ iBackColor = ] MSWebDVD.BackColor

Return Values

Returns an integer value representing the RGB values of the back color.

Remarks

This property is read/write with a default value of off-black (0x100010).


Balance Property

The Balance property sets or retrieves the speaker balance for the audio stream output.

Syntax

[ iBalance = ] MSWebDVD.Balance

Return Values

Returns and nteger value representing the balance levels. The allowable input range is -10,000 to 10,000. A value of 0 sets a neutral balance, that is both left and right speakers are given the same amplitude audio signal.

Remarks

This property is read/write with a default value of 0, meaning that both speakers receive equivalent audio signals. As with the Volume property, units correspond to .01 decibels (multiplied by -1 when iBalance is a positive value). For example, a value of 1000 indicates 10 dB on the right channel and 90 dB on the left channel.


ButtonsAvailable Property

The ButtonsAvailable property retrieves the total number of buttons on the current menu.

Syntax

[ iButtons = ] MSWebDVD.ButtonsAvailable

Return Values

Returns an integer value representing the number of buttons.

Remarks

This property is read-only with no default value. Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Call this method to retrieve the upper limit for the range of valid button numbers.

See Also

  • CurrentButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAndActivateButton
  • SelectAtPosition


CanStep Method

The CanStep method determines whether the MPEG-2 decoder on the local system can perform frame stepping in a specified direction.

Syntax

[ bCanStep = ] MSWebDVD.CanStep(bDirection);

Parameters

bDirection

Boolean used as a flag to specify the direction, forward or backward, of decoder's frame-stepping ability.

Value | Description
true | Can decoder step backward?
false | Can decoder step forward? This is the default value.

Return Value

Returns a Boolean value of true if the decoder can step in the specified direction, and false otherwise.

Remarks

Not all hardware MPEG-2 decoders support the new frame stepping capabilities in DirectShow® 8.0. This method queries the decoder for its frame stepping capabilities. If the decoder can perform frame stepping, an application can use the Step method to step through frames. This method will always return true if a software decoder is being used.


Capture Method

The Capture method captures a still image from the video frame when the MSWebDVD object is in windowless mode.

Syntax

MSWebDVD.Capture();

Remarks

This method captures the current frame from the DVD-Video image and pastes it into a window from which the user can save or edit the image. The MSWebDVD object must be in windowless mode for this method to succeed.


CCActive Property

The CCActive property sets or retrieves the current status of closed captioning.

Syntax

[ bCCActive = ] MSWebDVD.CCActive

Return Values

Returns a Boolean value indicating whether closed captioning is turned on.

Remarks

This property is read/write with a default value of false.

See Also

  • CurrentCCService


ColorKey Property

The ColorKey property sets or retrieves the color key used in closed captioning.

Syntax

[ iColorKey = ] MSWebDVD.ColorKey

Return Values

Returns an integer value representing the color to use as a transparent background for closed-captioned text. The default value in 256 colors is magenta, and off-black in any other color depth.

Remarks

This property is read/write. This property applies only to the closed-captions, if any exist, not to the subpicture stream.


CurrentAngle Property

The CurrentAngle property sets or retrieves the current angle in an angle block.

Syntax

[ iCurAngle = ] MSWebDVD.CurrentAngle

Return Values

Returns an integer value representing the angle. Must be a value from 1 through 9.

Remarks

This property is read/write with no default value.

See Also

  • AnglesAvailable


CurrentAudioStream Property

The CurrentAudioStream property sets or retrieves the number of the enabled audio stream.

Syntax

[ iStream = ] MSWebDVD.CurrentAudioStream

Return Values

Returns an integer value from 0 through 7 indicating the current audio stream.

Remarks

This property is read/write with no default value. Before attempting to set a new audio stream, call IsAudioStreamEnabled to verify that the stream is available.

See Also

  • AudioStreamsAvailable


CurrentButton Property

The CurrentButton property retrieves the number of the selected menu button.

Syntax

[ iButton = ] MSWebDVD.CurrentButton

Return Values

Returns an integer value representing the button.

Remarks

This property is read-only with no default value. Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

  • ActivateButton
  • ButtonsAvailable
  • CurrentButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAndActivateButton
  • SelectAtPosition


CurrentCCService Property

The CurrentCCService property sets or retrieves the current closed captioning service.

Syntax

[ iService = ] MSWebDVD.CurrentCCService

Return Values

Returns an integer value indicating the type of closed captioning service enabled.

Remarks

The possible values of this property are:

Value | Description
0x0 | No current service. This is the default value.
0x1 | True captioning, first field. Default service.
0x2 | Captioning for secondary language, second field. Generally not used.

This property is read/write.

See Also

  • CCActive


CurrentChapter Property

The CurrentChapter property retrieves the number of the chapter currently playing.

Syntax

[ iCurChapter = ] MSWebDVD.CurrentChapter

Return Values

Returns an integer value representing the current chapter in the current title.

Remarks

This property is read-only with no default value.


CurrentDiscSide Property

The CurrentDiscSide property retrieves the current side of the disc.

Syntax

[ iCurSide = ] MSWebDVD.CurrentDiscSide

Return Values

Returns an integer value representing the current side; Side A = 1 and Side B = 2.

Remarks

This property is read-only with no default value.


CurrentDomain Property

The CurrentDomain property retrieves the DVD domain that the MSWebDVD object is in.

Syntax

[ iDomain = ] MSWebDVD.CurrentDomain

Return Value

Returns an integer value representing the current domain.

Remarks

The possible values of the property are:

Value | Description
1 | First play
2 | Video Manager Menu
3 | Video Title Set Menu
4 | Title
5 | Stop

Call this method to ensure that the DVD Navigator is in a valid domain for the method you are about to call. For example, before calling PlayTitle, check the CurrentDomain property to make sure that the DVD Navigator is not in the Stop or First Play domain.


CurrentSubpictureStream Property

The CurrentSubpictureStream property sets or retrieves the current subpicture stream.

Syntax

[ iSPStream = ] MSWebDVD.CurrentSubpictureStream

Return Values

Returns an integer value representing the stream.

Remarks

The possible values of this property are:

Value | Description
0 to 31 | The subpicture stream
63 | Muted low-bitrate stream

This property is read/write with no default value. Before setting a new subpicture stream, call IsSubpictureStreamEnabled to verify that the stream is available.

Setting this property causes the SubpictureOn property to toggle to True.

See Also

  • SubpictureOn
  • SubpictureStreamsAvailable


CurrentTime Property

The CurrentTime property retrieves the current playback time.

Syntax

[ sCurTime = ] MSWebDVD.CurrentTime

Return Values

Returns an 11-character string representing the current playback time in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

Remarks

This property is read-only with no default value.

See Also

  • TotalTitleTime


CurrentTitle Property

The CurrentTitle property retrieves the number of the title currently playing.

Syntax

[ iCurTitle = ] MSWebDVD.CurrentTitle

Return Values

Returns an integer value from 1 through 99 representing the current disc title.

Remarks

This property is read-only with no default value.

See Also

  • TitlesAvailable


CurrentVolume Property

The CurrentVolume property retrieves the volume number for the current root directory.

Syntax

[ iCurVolume = ] MSWebDVD.CurrentVolume

Return Values

Returns an integer value representing the current DVD volume. If a disc is part of a multi-volume set, then the integer value should be greater than zero.

Remarks

This property is read-only with no default value.

See Also

  • VolumesAvailable


CursorType Property

The CursorType property sets or retrieves the current cursor type.

Syntax

[ iCursorType = ] MSWebDVD.CursorType

Return Values

Returns an integer value representing the cursor type.

Remarks

The possible values for this property are:

Value | Description
0 | Arrow
1 | Zoom In
2 | Zoom Out
3 | Hand
-1 | None

This property is read/write with a default value of zero. When the picture is zoomed in, setting CursorType to Hand (0x3) puts the application into drag mode, enabling the user to move the image inside the video display area.


DefaultAudioLanguage Property

The DefaultAudioLanguage property retrieves the default audio language.

Syntax

[ iLang = ] MSWebDVD.DefaultAudioLanguage

Return Values

Returns an LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Remarks

This property is read-only with no default value.

See Also

  • SelectDefaultAudioLanguage


DefaultAudioLanguageExt Property

The DefaultAudioLanguageExt property retrieves the default DVD audio language extension.

Syntax

[ iLangExt = ] MSWebDVD.DefaultAudioLanguageExt

Return Values

Returns an integer value indicating the default audio language extension. See Remarks for the possible values.

Remarks

This property is read-only with no default value. The following table shows the possible values for DVD audio language extensions.

Value | Description
0 | NotSpecified
1 | Captions
2 | VisuallyImpaired
3 | DirectorComments1
4 | DirectorComments2

See Also

SelectDefaultAudioLanguage


DefaultMenuLanguage Property

The DefaultMenuLanguage property retrieves the default menu language.

Syntax

[ iLang = ] MSWebDVD.DefaultMenuLanguage

Return Values

Returns an LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Remarks

This property is read-write with no default value.


DefaultSubpictureLanguage Property

The DefaultSubpictureLanguage property retrieves the default subpicture language.

Syntax

[ iLang = ] MSWebDVD.DefaultSubpictureLanguage

Return Values

Returrn an LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Remarks

This property is read-only with no default value.

See Also

  • SelectDefaultSubpictureLanguage


DefaultSubpictureLanguageExt Property

The DefaultSubpictureLanguageExt property retrieves the default DVD subpicture language extension.

Syntax

[ iLangExt = ] MSWebDVD.DefaultSubpictureLanguageExt

Return Values

Returns an Integer value indicating the default DVD subpicture language extension.

Remarks

This property is read-only with no default value. The following table shows the possible values.

Value | Description
0 | Extension Not Specified
1 | Normal Captions
2 | Big Captions
3 | Children's Captions
5 | Normal Closed Captions
6 | Big Closed Captions
7 | Children's Closed Captions
9 | Forced
13 | Normal Director's Comments
14 | Big Director's Comments
15 | Children's Director's Comments

See Also

  • SelectDefaultSubpictureLanguage


DeleteBookmark Method

The DeleteBookmark method deletes the saved bookmark.

Syntax

MSWebDVD.DeleteBookmark();

Return Value

No return value.

Remarks

There can only be one bookmark at a time.


DisableAutoMouseProcessing Property

The DisableAutoMouseProcessing property enables or disables the MSWebDVD object's mouse-processing functionality.

Syntax

[ bMouseProcessing = ] MSWebDVD.DisableAutoMouseProcessing

Return Values

Returns a boolean value indicating whether to disable the default mouse processing.

Remarks

This property is read/write with a default value of false. The MSWebDVD object automatically handles mouse actions for DVD on-screen menus by default; users can highlight and activate menu buttons without special programming by the application. An application can turn off this default mouse-handling functionality by setting this property to true. When the automatic mouse processing is turned off, an application must use the various button-related methods and properties to handle mouse moves and mouse clicks on the on-screen menus. Also, an application can use the button-related methods to override the automatic mouse handling even when when DisableAutoMouseProcessing is set to false.


DVDAdm Property

The DVDAdm property provides access to the MSDVDAdm object that contains methods and properties for saving application and user information.

Syntax

MSWebDVD.DVDAdm

Remarks

This property is read-only with no default value. There is no need to create a separate reference to the MSDVDAdm object. To access the methods and properties of the object, use the DVDAdm property as shown in the following example.

Example

DVD.DVDAdm.DisableScreenSaver = true;


DVDDirectory Property

The DVDDirectory property sets or retrieves the current directory of the current DVD volume.

Syntax

[ sDirPath = ] MSWebDVD.DVDDirectory

Return Values

Returns a string value indicating the path to the DVD root directory.

Remarks

This property is read/write with no default value. Use this method to set the root path when there is more than one DVD drive on a system. When there is only one drive on the system and its drive letter is higher than "C", the MSWebDVD object finds it automatically. For a standard DVD-Video disc, the root path should include the ts_video directory:

Example Code

MSWebDVD.DVDDirectory = "e:\\video_ts";

Some DVD volumes may have their video in a directory named something other than "video_ts." The general idea is that an additional "DVD volume" (the set of .IFO. VOB, and .BUP files that would normally be stored in the VIDEO_TS directory) can be placed in a subdirectory on the disc. By changing the root to point to this directory, MSWebDVD will operate on this separate DVD volume. A new set of menus, titles, and so on will be available, independent of the titles in the VIDEO_TS root, which will no longer be accessible. Such directories are called "hidden directories." The following example shows how to set a hidden directory as the root, where "hidden" is a placeholder for whatever name the disc authors have given to the directory.

Example Code

MSWebDVD.DVDDirectory = "d:\\webdvd\\hidden";


MSWebDVD.DVDTimeCode2bstr Method

The DVDTimeCode2bstr method retrieves a string indicating the current time on the disc.

Syntax

[ sTimeCode = ] MSWebDVD.DVDTimeCode2bstr(nTimeCode);

Parameters

sTimeCode

Specifies the current time on the disc relative to the start of the title as a Number obtained through the EC_DVD_CURRENT_HMSF_TIME event.

Return Value

Returns an 11-character String in the format "hh:mm:ss:ff" representing the hours, minutes, seconds and frames that define the current time.

Remarks

This method is read only.

See Also

  • Handling DVD Event Notifications


DVDUniqueID Property

The DVDUniqueID property retrieves a system-generated number that uniquely identifies the current disc.

Syntax

[ iDiscID = ] MSWebDVD.DVDUniqueID

Return Values

Returns an integer value that uniquely identifies the current disc.

Remarks

This property is read-only with no default value. The identifier (ID) number is not absolutely unique, but it is unique for all practical purposes. The ID applies to all replicated copies of a disc. In other words, all copies of a specific movie have the same ID. The ID is based on file sizes, dates, and other information, and not the BCA value.


Eject Method

The Eject method ejects or inserts a disc from or into the DVD drive.

Syntax

MSWebDVD.Eject();

Return Value

No return value.

Remarks

On some DVD drives, this method acts as a toggle, ejecting and inserting on alternate calls. This is hardware-dependent.


EnableResetOnStop Property

The EnableResetOnStop property sets or retrieves a value that determines how play will resume when the filter graph makes a transition from a stopped state.

Syntax

[ bEnableReset = ] MSWebDVD.EnableResetOnStop

Return Values

Returns a Boolean value indicating where the MSWebDVD object will start playing again after the filter graph is stopped.

Remarks

This property is read/write.

The possible values of this property are: with a default value of true.

Value | Description
true | DVD Navigator will reset and start play from the beginning of the disc. This is the default value
false | DVD Navigator will resume play where it left off.


FramesPerSecond Property

The FramesPerSecond property retrieves the video frame rate for the current DVD title.

Syntax

[ iFramesPerSec = ] MSWebDVD.FramesPerSecond

Return Values

Returns an integer value representing the video frame rate; either 25 or 30 frames per second.

Remarks

This property is read-only with no default value. NTSC video signals are displayed at 30 frames per second. PAL is displayed at 25 frames per second. A disc is encoded to play on either NTSC or PAL, but cannot play on both.


FullScreenMode Property

The FullScreenMode property sets or retrieves a value indicating whether the display is in full-screen mode.

Syntax

[ bFullScreen = ] MSWebDVD.FullScreenMode

Return Values

Returns a Boolean value indicating whether to enable or disable full-screen playback.

Remarks

This property is read/write with a default value of false.

Value | Description
true | Enable full-screen playback. This is the default value
false | Disable full-screen playback.

Remarks

Full screen mode is only available when the MSWebDVD control is running in windowed mode.

See Also

WindowlessActivation Property


GetAudioLanguage Method

The GetAudioLanguage method retrieves a string indicating which language is available on the specified audio stream.

Syntax

[ slang = ] MSWebDVD.GetAudioLanguage(iStream);

Parameters

iStream

Specifies the audio stream number in the current title as an Integer.

Return Values

Returns a human-readable string identifying the language of the audio stream in the current title.


GetButtonAtPosition Method

The GetButtonAtPosition method retrieves the number of the button at the specified coordinates without selecting or activating it.

Syntax

[ iButton = ] MSWebDVD.GetButtonAtPosition(xPos, yPos);

Parameters

xpos

Specifies the x-coordinate of the mouse pointer as an Integer.

yPos

Specifies the y-coordinate of the mouse pointer as an Integer.

Return Values

Returns an integer value specifying the button, if any, at the specified position.

Remarks

This method returns zero if no button is present at the given coordinates. Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

  • ActivateButton
  • ButtonsAvailable
  • CurrentButton
  • GetButtonRect
  • SelectAndActivateButton
  • SelectAtPosition


GetButtonRect Method

The GetButtonRect method retrieves the rectangle for the specified button, in window coordinates.

Syntax

[ oButton = ] MSWebDVD.GetButtonRect(iButton);

Parameters

oButton

Specifies the button number as an Integer.

Return Values

Returns a DVDRect object that defines the rectangle.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

  • ButtonsAvailable
  • CurrentButton
  • ActivateButton
  • SelectAndActivateButton
  • SelectAtPosition


GetClipVideoRect Method

The GetClipVideoRect method retrieves the clipping rectangle currently defined for the video display.

Syntax

[ oClipRect = ] MSWebDVD.GetClipVideoRect();

Return Values

Returns a DVDRect object that defines the rectangle.

See Also

  • SetClipVideoRect


GetDelayTime Method

The GetDelayTime method retrieves the delay time for the ToolTip associated with the MSWebDVD object.

Syntax

[ iDelay = ] MSWebDVD.GetDelayTime();

Return Values

Returns an integer value indicating the ToolTip delay time, in milliseconds.

See Also

  • SetDelayTime


GetDVDTextLanguageLCID Method

The GetDVDTextLanguageLCID method retrieves the locale identifier (LCID) for the specified text string block.

Syntax

[ iLCID = ] MSWebDVD.GetDVDTextLanguageLCID(iLangIndex);

Parameters

iLangIndex

Specifies the text language block on the disc as an Integer.

Return Values

Returns an LCID value that contains information specifying the language the strings are written in. See Working with LCIDs for information on extracting the primary language code from an LCID.

Remarks

Supplemental text strings are stored in contiguous blocks on the disc. Each language has one block of strings. An application specifies these blocks by an index, which must be less than the value returned by GetDVDTextNumberOfLanguages.

See Also

  • GetLangFromLangID
  • Working with DVD Text Strings


GetDVDTextNumberOfLanguages Method

The GetDVDTextNumberOfLanguages method retrieves the number of text languages available on the disc.

Syntax

[ iLanguages = ] MSWebDVD.GetDVDTextNumberOfLanguages();

Return Values

Returns an integer value specifying the number of text languages available.

See Also

  • Working with DVD Text Strings


GetDVDTextNumberOfStrings Method

The GetDVDTextNumberOfStrings method retrieves the number of text strings available for the specified language.

Syntax

[ iStrings = ] MSWebDVD.GetDVDTextNumberOfStrings(iLangIndex);

Parameters

iLangIndex

Specifies the language as an Integer. The value must range from zero through one less than the value returned by GetDVDTextNumberOfLanguages.

Return Values

Returns an integer value specifying how many strings the disc contains in the specified language.

See Also

  • Working with DVD Text Strings


GetDVDTextString Method

The GetDVDTextString method retrieves the specified text string.

Syntax

[ sText = ] MSWebDVD.GetDVDTextString(iLangIndex, iStringIndex);

Parameters

iLangIndex

Specifies the index of the language as an Integer.

iStringIndex

Specifies the index number of the text string as an Integer.

Return Values

Returns the String specified by iStringIndex.

See Also

  • GetDVDTextNumberOfLanguages
  • Working with DVD Text Strings


GetDVDTextStringType Method

The GetDVDTextStringType method retrieves a value that indicates the type of information contained in the specified DVD text string.

Syntax

[ iStringType = ] MSWebDVD.GetDVDTextStringType(iLangIndex, iStringIndex);

Parameters

iLangIndex

Specifies the language of the text string as an Integer.

iStringIndex

Specifies the index number of the text string as an Integer.

Return Values

Returns an integer value that indicates the type of information contained in the string.

Remarks

See Working with DVD Text Strings for a table of text string types and their meanings.


GetGPRM Method

The GetGPRM method retrieves the specified general parameter register.

Syntax

[ iGPRM = ] MSWebDVD.GetGPRM(iIndex);

Parameters

iIndex

Specifies the register to retrieve as an Integer. The value must range from 0 through 15.

Return Values

Returns an integer value representing the specified register.

Remarks

This method is not required for any DVD navigation or playback functionality using the MSWebDVD object. It is provided for those with a thorough understanding of the DVD specification who want to implement advanced features. GPRMs can be used to hold any values, so they can be freely set and read. But since GPRMs are used to store disc commands as well, changing their values using SetGPRM can result in unpredictable behavior.

See Also

  • SetGPRM


GetKaraokeChannelAssignment Method

The GetKaraokeChannelAssignment method retrieves a value that indicates how the karaoke channels are assigned to the speakers.

Syntax

[ iAssignment = ] MSWebDVD.GetKaraokeChannelAssignment( iStream );

Parameters

iStream

Specifies the audio stream as an Integer.

Return Values

Returns an integer indicating the speaker assignment for the specified stream.

Return code | Description
2 | The stream is assigned to the left and right speakers.
3 | The stream is assigned to the left, right, and middle speakers.
4 | The stream is assigned to the left, right, and audio1 speakers.
5 | The stream is assigned to the left, right, middle, and audio1 speakers.
6 | The stream is assigned to the left, right, and audio2 speakers.
7 | The stream is assigned to the left, right, middle, and audio2 speakers.

See Also

  • KaraokeAudioPresentationMode


GetKaraokeChannelContent Method

The GetKaraokeChannelContent method retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.

Syntax

[ iContent = ] MSWebDVD.GetKaraokeChannelContent(iStream, iChannel);

Parameters

iStream

Specifies the audio stream as an Integer.

iChannel

Specifies the channel as an Integer.

The possible values for each channel are:

Value | Description
0x0001 | Guide Vocal 1
0x0002 | Guide Vocal 2
0x0004 | Guide Melody 1
0x0008 | Guide Melody 2
0x0010 | Guide Melody A
0x0020 | Guide Melody B
0x0040 | Sound Effect A
0x0080 | Sound Effect B

Return Values

Returns an integer value whose individual bits specify the contents of the karaoke channel.

Remarks

DVD audio channel numbering is zero-based, so channels 2, 3, and 4 are the auxiliary karaoke channels. After the method returns, perform a bitwise AND operation on iContent to determine the contents of each channel. Because a single channel might have more than one type of content recorded on it, you should test for all the possible values even after a match is found.

The following code example demonstrates how to test iContents against each possible value.

        if(iContent & 0x0001)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Vocal 1.
            }
        if(iContent & 0x0002)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Vocal 2.
            }
        if(iContent & 0x0004)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Melody 1.
            }

        // Repeat for each possible value for each channel.

After the user knows the contents of each channel, he or she must be able to adjust the volume or turn the individual channels on or off as needed. Implement this functionality in your application by using the KaraokeAudioPresentationMode property.

Note: To play karaoke discs, the audio decoder on the user's system must be compatible with the DirectShow 8 karaoke implementation.


GetLangFromLangID Method

The GetLangFromLangID method retrieves a human-readable string when given a primary language ID.

Syntax

[ sLanguage = ] MSWebDVD.GetLangFromLangID(iPrimaryLangID)

Parameters

iPrimaryLangID

Specifies the primary language ID as an Integer. See Working with LCIDs for a table of some possible values.

Return Values

Returns a String representation of the language that can be displayed in the application's user interface.

Remarks

Although this method is named GetLangFromLangID, the parameter that you pass is actually the primary language ID, not the language ID.

See Also

  • Working with LCIDs
  • GetAudioLanguage
  • GetDVDTextLanguageLCID


GetNumberOfChapters Method

The GetNumberOfChapters method retrieves the number of chapters in the specified title.

Syntax

[ iChapters = ] MSWebDVD.GetNumberOfChapters(iTitle);

Parameters

iTitle

Specifies the title as an Integer.

Return Values

Returns an integer value from 1 through 999 indicating the number of chapters.


GetPlayerParentalCountry Method

The GetPlayerParentalCountry method retrieves the current country/region as set in the MSWebDVD object.

Syntax

[ iCountryCode = ] MSWebDVD.GetPlayerParentalCountry();

Return Value

Returns an integer value with the country/region code.

See Also

  • Enforcing Parental Management Levels
  • GetPlayerParentalLevel
  • GetTitleParentalLevels
  • SelectParentalCountry
  • SelectParentalLevel


GetPlayerParentalLevel Method

The GetPlayerParentalLevel retrieves the parental management level set in the MSWebDVD object.

Syntax

[ iLevel = ] MSWebDVD.GetPlayerParentalLevel();

Return Values

Returns an integer value specifying the current parental level in the DVD Navigator, or -1 if parental management is disabled.

Remarks

A player application is responsible for enforcing parental controls. The player parental level is a value set by an application than can be used to indicate the highest parental level the current user can view. When the DVD Navigator encounters a new parental level, use this method to determine whether the new level is greater than the level that was set by the application through SelectParentalLevel.

See Also

  • Enforcing Parental Management Levels
  • GetTitleParentalLevels
  • GetPlayerParentalCountry
  • SelectParentalCountry
  • SelectParentalLevel


GetSPRM Method

The GetSPRM method retrieves the specified system parameter register.

Syntax

[ iSPRM = ] MSWebDVD.GetSPRM(iIndex);

Parameters

iIndex

Specifies the register whose value you want to retrieve as an Integer. The Integer must range from 0 through 23.

Return Values

Returns an integer value representing the contents of the specified register.

Remarks

The disc controls system parameter registers (SPRMs). A player application doesn't need to access these registers for any standard navigation functionality. SPRMs represent the status of the player. Each one has a meaning, set by user preferences, disc commands, and other occurrences that an application has no direct control over. An application can read these registers but cannot write to them. To use these registers effectively, you will probably need a more detailed knowledge of the DVD navigation commands than is provided in this documentation. The following table shows the contents of each register. For more detailed information on the register contents, see IDvdInfo2::GetAllSPRMs

Register | Contents
0 | Menu language code
1 | Audio stream number
2 | Subpicture stream number
3 | Current angle number
4 | Current title number
5 | Title number
6 | PGC number
7 | Current chapter number (PTT)
8 | Highlighted button number
9 | Navigation timer
10 | PGC jump for nav. timer
11 | Karaoke audio presentation mode
12 | PML country/region code
13 | PML
14 | Video setting
15 | Audio capability
16 | Audio language
17 | Audio language extension
18 | Subpicture language
19 | Subpicture language extension
20 | Player region code
21 | Reserved
22 | Reserved
23 | Reserved

See Also

  • GetGPRM
  • SetGPRM


GetSubpictureLanguage Method

The GetSubpictureLanguage method retrieves the language for the specified subpicture stream.

Syntax

[ sLang = ] MSWebDVD.GetSubpictureLanguage(iStream);

Parameters

iStream

Specifies the subpicture stream number whose text language you want to retrieve as an Integer.

Return Values

Returns a human-readable string identifying the language of the audio stream in the current title.


GetTitleParentalLevels Method

The GetTitleParentalLevels method retrieves the parental management levels for the specified title.

Syntax

[ iLevels = ] MSWebDVD.GetTitleParentalLevels(iTitle);

Parameters

iTitle

Specifies the title as an Integer.

Return Values

Returns an integer value whose individual bits indicate which parental management levels (PML) are set in the specified title.

Remarks

A title may have chapters or even short segments that have a PML different from the overall PML for the title. Use this method to determine all the PMLs that will be encountered when playing a specified title. The returned integer is a set of bit flags that are defined as shown in the table below. Perform a bitwise AND operation on iLevels and each possible value. If the operation returns true, it means that PML will be encountered at some point in this title.

Value | Description
0x100 | DVD Parental Level 1
0x200 | DVD Parental Level 2
0x400 | DVD Parental Level 3
0x800 | DVD Parental Level 4
0x1000 | DVD Parental Level 5
0x2000 | DVD Parental Level 6
0x4000 | DVD Parental Level 7
0x8000 | DVD Parental Level 8

Example Code

The following code snippet shows how to test for PMLs on Title 1. One use for this information is to compare the highest PML defined for the title to the PML assigned to the current user and determine whether to play the specified title or not.

iLevels = oDVD.GetTitleParentalLevels(1);
if(iLevels & 0x100)
 // PML 1 is defined for this title
if(iLvels & 0x200)
   // PML 2 is defined for this title
if(iLevels & 0x400)
  // PML 3 is defined for this title
...   //  and so on for all eight levels

See Also

  • Enforcing Parental Management Levels
  • SelectParentalLevel
  • GetPlayerParentalCountry
  • GetPlayerParentalLevel
  • SelectParentalCountry


IsAudioStreamEnabled Method

The IsAudioStreamEnabled method retrieves a value indicating whether the specified audio stream is enabled in the current title.

Syntax

[ bEnabled = ] MSWebDVD.IsAudioStreamEnabled(iStream)

Parameters

iStream

Specifies the audio stream as an Integer value from 0 through 7.

Return Values

Returns a Boolean value indicating whether the specified audio stream is available for the current title. True means it is available.

Remarks

Although a disc can contain up to eight independent audio streams, each stream is not necessarily available for each title. For example, a main movie title might have three audio streams for English, Spanish, and Japanese, but the "Coming Attractions" title might have only one audio stream in English. Always verify that a stream is available for a title before setting the CurrentAudioStream property.


IsSubpictureStreamEnabled Method

The IsSubpictureStreamEnabled method retrieves a value indicating whether the specified subpicture stream is enabled in the current title.

Syntax

[ bEnabled = ] MSWebDVD.IsSubpictureStreamEnabled(iStream)

Parameters

iStream

Specifies the subpicture stream as an Integer.

Value | Description
0 to 31 | subpicture stream
63 | muted low-bitrate stream

Return Values

Returns a Boolean value indicating whether the specified audio stream is available in the current title. True means it is available.

Remarks

Although a disc can contain up to 32 subpicture streams, each stream is not necessarily available for each title. Always verify that a stream is available for a title before setting the CurrentSubpictureStream property.


GetVideoSize Method

The GetVideoSize method retrieves the native video dimensions.

Syntax

[ oSizeRect = ] MSWebDVD.GetVideoSize();

Return Values

Returns a DVDRect object containing four read/write properties: (top left) x; (top left) y, Width, and Height. The x and y properties are set to zero and the other two properties reflect the width and height of the video rectangle as authored on the disc.


KaraokeAudioPresentationMode Property

The KaraokeAudioPresentationMode property sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.

Syntax

[iMode ] = MSWebDVD.KaraokeAudioPresentationMode

Return Values

Returns an integer value containing a set of bit flags indicating how the auxiliary karaoke channels are downmixed to the left and right speakers.

Remarks

This property is read/write with a default value of zero.

Audio channels are zero-based, so channels 0 and 1 generally represent the right and left speaker channels and channels 2 through 4 are the three auxiliary karaoke channels. When the MSWebDVD object enters karaoke mode, it automatically mutes channels 2 and higher. Use bitwise OR operations to set the appropriate bit in order to send an auxiliary channel to the left speaker, right speaker, both speakers (both bits on), or to no speakers (both bits off). These bits are all off by default whenever the DVD Navigator enters karaoke mode. The value of the bits and their corresponding action is given in the following table.

Value | Description
0x0004 | Downmix Channel 2 to the left speaker
0x0008 | Downmix Channel 3 to the left speaker
0x0010 | Downmix Channel 4 to the left speaker
0x0400 | Downmix Channel 2 to the right speaker
0x0800 | Downmix Channel 3 to the right speaker
0x1000 | Downmix Channel 4 to the right speaker

Example Code

The following code example shows how to send channel 2 to the left speaker and channels 3 and 4 to the right channel by using a bitwise OR operation.

  var iMode = 0;
  iMode = 0x0004 | 0x0800 | 0x1000 ;
  DVD.KaraokeAudioPresentationMode = iMode;

To retrieve the value of KaraokeAudioPresentationMode, use a bitwise AND operation against the possible values, as shown in the following code example.

  if (DVD.KaraokeAudioPresentationMode & 0x0004)
  {
     // Channel 2 is being sent to the left speaker
  }
  if (DVD.KaraokeAudioPresentationMode & 0x0008)
  {
     // Channel 3 is being sent to the left speaker
  }
  // And so on for all possible values


Mute Property

The Mute property turns the audio stream output on or off.

Syntax

[ bMute = ] MSWebDVD.Mute

Return Values

Returns a Boolean value indicating whether the audio stream should be muted.

Remarks

This property is read/write with a default value of false.


NotifyParentalLevelChange Method

The NotifyParentalLevelChange method enables or disables the event handling for temporary parental management level commands.

Syntax

MSWebDVD.NotifyParentalLevelChange(bNotify);

Parameters

bNotify

Specifies a Boolean value indicating whether or not the application is notified when the MSWebDVD object encounters video segments with a rating more restrictive than the overall rating for the disc.

Return Values

No return value.

Remarks

Parental management notifications are disabled by default. This means that temporary parental commands from the disc are allowed but ignored and disc will play without interruption. Call this method during initialization of your application if you need to handle temporary parental management level commands from the disc. To disable parental management after it is enabled, call this method with an argument of false. For more details on parental management, see AcceptParentalLevelChange.

See Also

  • Enforcing Parental Management Levels
  • SelectParentalLevel
  • GetTitleParentalLevels
  • GetPlayerParentalCountry
  • GetPlayerParentalLevel
  • SelectParentalCountry


Pause Method

The Pause method pauses playback at the current location.

Syntax

MSWebDVD.Pause();

Return Values

No return value.

Remarks

If playback is already paused, this method does nothing.


Play Method

The Play method plays the current DVD title.

Syntax

MSWebDVD.Play();

Return Values

No return value.

Remarks

If playback is paused or stopped and EnableResetOnStop is true, then calling Play will resume playback at normal speed at the current location. If playback is stopped and EnableResetOnStop is false, then calling Play will cause the disc to start playing at the beginning of the first title.

See Also

  • Resume


PlayAtTime Method

The PlayAtTime method starts playback in the current title at the specified time.

Syntax

MSWebDVD.PlayAtTime(sTime);

Parameters

sTime

Specifies the time at which to start playing as a string. The string must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).

Return Values

No return value.

See Also

  • PlayAtTimeInTitle


PlayAtTimeInTitle Method

The PlayAtTimeInTitle method starts playback at the specified time within the specified title.

Syntax

MSWebDVD.PlayAtTimeInTitle(sTime, iTitle);

Parameters

sTime

Specifies the time at which to start playback as a string. The string must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).

iTitle

Specifies the index of the title as an Integer.

Return Values

No return value.

See Also

  • CurrentTitle
  • PlayAtTime
  • TitlesAvailable


PlayBackwards Method

The PlayBackwards method starts backward playback from the current location at the specified speed.

Syntax

MSWebDVD.PlayBackwards(nSpeed);

Parameters

nSpeed

Specifies the speed at which to play as a number. This number is a multiplier—1.0 is normal playback speed; 2.0 is double speed, 0.5 is half speed, and so on. When nSpeed does not equal 1.0, audio is muted and the subpicture is turned off.

Return Values

No return value.

See Also

  • PlayForwards


PlayChapter Method

The PlayChapter method starts playback from the specified chapter within the current title.

Syntax

MSWebDVD.PlayChapter(iChapter);

Parameters

iChapter

Specifies the chapter index in the current title as an Integer.

Return Values

No return value.

Remarks

When the end of the specified chapter is reached, this method continues playing subsequent chapters, if any exist. If you want to play only a specified chapter, use PlayChaptersAutoStop.

See Also

  • PlayChapterInTitle


PlayChaptersAutoStop Method

The PlayChaptersAutoStop method starts playback at the specified chapter in the specified title and for the number of chapters specified.

Syntax

MSWebDVD.PlayChaptersAutoStop(iTitle, iChapter, iChapterCount);

Parameters

iTitle

Specifies the title as an Integer value.

iChapter

Specifies the start chapter as an Integer value.

iChapterCount

Specifies the number of chapters to play as an Integer value.

Return Values

No return value.

Remarks

When the last chapter has played, this method causes an EC_DVD_CHAPTER_AUTOSTOP event notification to be sent to the application.


PlayChapterInTitle Method

The PlayChapterInTitle method plays the specified chapter in the specified title.

Syntax

MSWebDVD.PlayChapterInTitle(iTitle, iChapter);

Parameters

iTitle

Specifies the title as an Integer value.

iChapter

Specifies the chapter as an Integer value.

Return Values

No return value.

Remarks

This method starts playback at the specified chapter and then continues playing indefinitely. If you want to play only a particular chapter, use PlayChaptersAutoStop.


PlayForwards Method

The PlayForwards method starts forward playback from the current location at the specified speed.

Syntax

MSWebDVD.PlayForwards(nSpeed);

Parameters

nSpeed

Specifies the speed at which to play as an Integer value. This value is a multiplier—1.0 is normal playback speed; 2.0 is double speed, 0.5 is half speed, and so on. When nSpeed does not equal 1.0, audio is muted and the subpicture is turned off.

Return Values

No return value.

See Also

  • PlayBackwards


PlayNextChapter Method

The PlayNextChapter method starts playback from the next chapter in the current title.

Syntax

MSWebDVD.PlayNextChapter();

Return Values

No return value.

See Also

  • PlayPrevChapter


PlayPeriodInTitleAutoStop Method

The PlayPeriodInTitleAutoStop method starts playback at the specified time in the specified title until the specified stop time.

Syntax

MSWebDVD.PlayPeriodInTitleAutoStop(iTitle, sStartTime, sEndTime);

Parameters

iTitle

Specifies the title as an Integer.

sStartTime

Specifies the start time as a string in "hh:mm:ss:ff" format (specifying hours, minutes, seconds, frames).

sEndTime

Specifies the end time as a String in "hh:mm:ss:ff" format.

Return Values

No return value.

See Also

  • PlayChaptersAutoStop


PlayPrevChapter Method

The PlayPrevChapter method starts playback from the previous chapter in the current title.

Syntax

MSWebDVD.PlayPrevChapter();

Return Values

No return value.

See Also

  • PlayNextChapter


PlayState Property

The PlayState property retrieves the current state of the MSWebDVD object.

Syntax

[ iState = ] MSWebDVD.PlayState

Return Values

Returns an Integer value representing the current state of the DVD Navigator.

Return code | Description
-2 | Undefined
-1 | Uninitialized
0 | Stopped
1 | Paused
2 | Running

Remarks

This property is read-only with no default value.

The MSWebDVD object controls the DirectShow DVD Navigator filter, which does the actual work of DVD navigation. It is actually the state of the DVD Navigator that this property refers to. The DVD Navigator can be in one of several states, as described above. The PlayState property can be useful as a diagnostic tool, but generally there should be no reason for a scripting application to monitor the state of the DVD Navigator.


PlayTitle Method

The PlayTitle method starts playback at the beginning of the specified title.

Syntax

MSWebDVD.PlayTitle(iTitle);

Parameters

iTitle

Specifies the title as an Integer.

Return Values

No return value.

See Also

  • PlayPeriodInTitleAutoStop


PreferredSubpictureStream Property

The PreferredSubpictureStream property retrieves the preferred subpicture stream for the current viewing session.

Syntax

[ iStream = ] MSWebDVD.PreferredSubpictureStream

Return Values

Returns an Integer value representing the current preferred subpicture stream in the system registry.

Remarks

The preferred subpicture stream is set with MSDVDAdm object's DefaultSubpictureLCID.


ReadyState Property

The ReadyState property retrieves the ReadyState of the MSWebDVD object.

Syntax

[ iReadyState = ] MSWebDVD.ReadyState

Return Values

Returns an integer value representing the control's ReadyState

Return code | Description
0 | Default initialization state.
1 | Object is loading its properties.
2 | Object has been initialized.
3 | Object is interactive, but not all its data is available.
4 | Object has received all its data.

Remarks

This property is read-only with no default value.

Any object embedded in a Web page exposes the ReadyState property.


Render Method

The Render method initializes the DVD filter graph.

Syntax

MSWebDVD.Render(iRender = 0);

Parameters

iRender

Specifies an integer value indicating whether the filter graph will be destroyed and rebuilt.

Value | Description
0 | The filter graph will not be destroyed and rebuilt if it already exists. This is the default value.
1 | The filter graph will be destroyed and rebuilt if it already exists.

Return Values

No return value.

Remarks

The Render method enables the MSWebDVD object to fully initialize the underlying DirectShow filter graph on startup. This eliminates the slight delay that otherwise occurs when the user issues the first command to play a disc or show a menu. There is no case in which Render needs to be called before calling any other method. For example, if the application calls PlayTitle before the filter graph has been initialized, the MSWebDVD object calls Render automatically before attempting to play the disc.


ReplayChapter Method

The ReplayChapter method starts playback at the beginning of the current chapter.

Syntax

MSWebDVD.ReplayChapter();

Return Values

No return value.

See Also

  • PlayChapter
  • PlayChaptersAutoStop


RegionChange Method

The RegionChange method displays a system dialog box that enables the user to change the region associated with the DVD drive.

Syntax

MSWebDVD.RegionChange();

Return Values

No return value.

Remarks

The region for a DVD drive can be changed only five times.


RestoreBookmark Method

The RestoreBookmark method moves the MSWebDVD object to the point on the disc as specified in the current bookmark, with all audio, video, and subpicture settings restored.

Syntax

MSWebDVD.RestoreBookmark();

Return Values

No return value.


Resume Method

The Resume method resumes playback after a menu has been displayed.

Syntax

MSWebDVD.Resume();

Return Values

No return value.


ReturnFromSubmenu Method

The ReturnFromSubmenu method returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.

Syntax

MSWebDVD.ReturnFromSubmenu();

Return Values

No return value.


SaveBookmark Method

The SaveBookmark method saves the current disc position and state of the MSWebDVD object so the user can return to the same place later.

Syntax

MSWebDVD.SaveBookmark();

Return Values

No return value.

Remarks

A bookmark is a snapshot of the DVD Navigator's current state. This includes information such as where it is playing on the disc, and which audio and subpictures streams are selected. By saving a bookmark, the user can close the application, shut down the computer, and come back later to continue viewing the disc right where he or she left off, with all settings just as they were before. Only one bookmark can be saved at any given time. When you call SaveBookmark, the old bookmark is overwritten.

See Also

  • RestoreBookmark
  • Saving and Restoring Bookmarks


SelectAndActivateButton Method

The SelectAndActivateButton method selects and activates the specified button.

Syntax

MSWebDVD.SelectAndActivateButton(iButton);

Parameters

iButton

Specifies the button as an Integer.

Return Values

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

This method highlights the specified button and activate it automatically.

See Also

  • ButtonsAvailable
  • CurrentButton
  • ActivateButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAtPosition


SelectAtPosition Method

The SelectAtPosition method selects the menu button at the specified mouse pointer coordinates.

Syntax

MSWebDVD.SelectAtPosition(xPos, yPos);

Parameters

xPos

Specifies the x-coordinate as an Integer.

yPos

Specifies the y-coordinate as an Integer.

Return Values

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Selecting merely highlights the button. To send the command associated with a button that has been selected, call ActivateButton.

See Also

  • ButtonsAvailable
  • CurrentButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAndActivateButton


SelectDefaultAudioLanguage Method

The SelectDefaultAudioLanguage method sets the current default audio language in the MSWebDVD object.

Syntax

MSWebDVD.SelectDefaultAudioLanguage(iLang, iExt);

Parameters

iLang

Specifies the language as an Integer LCID value. See the table under Working with LCIDs for possible values.

iExt

Specifies the DVD audio language extension as an integer value.

Value | Description
0 | NotSpecified
1 | Captions
2 | VisuallyImpaired
3 | DirectorComments1
4 | DirectorComments2

Return Values

No return value.


SelectDefaultSubpictureLanguage Method

The SelectDefaultSubpictureLanguage method sets the current default subpicture language in the MSWebDVD object.

Syntax

MSWebDVD.SelectDefaultSubpictureLanguage(iLang,iExt);

Parameters

iLang

Specifies the language as an Integer.

iExt

Specifies the subpicture language extension as an Integer.

Value | Description
0 | Extension Not Specified
1 | Normal Captions
2 | Big Captions
3 | Children's Captions
5 | Normal Closed Captions
6 | Big Closed Captions
7 | Children's Closed Captions
9 | Forced
13 | Normal Director's Comments
14 | Big Director's Comments
15 | Children's Director's Comments

Return Values

No return value.

Remarks

The subpicture language extension provides further information about the subpicture.


SelectLeftButton Method

The SelectLeftButton method selects the left directional button from the displayed menu.

Syntax

MSWebDVD.SelectLeftButton();

Return Values

No return value.

See Also

  • ActivateButton
  • SelectLowerButton
  • SelectRightButton
  • SelectUpperButton


SelectLowerButton Method

The SelectLowerButton method selects the lower directional button from the displayed menu.

Syntax

MSWebDVD.SelectLowerButton();

Return Values

No return value.

See Also

  • ActivateButton
  • SelectLeftButton
  • SelectRightButton
  • SelectUpperButton


SelectParentalCountry Method

The SelectParentalCountry method sets the specified parental country/region for subsequent playback.

Syntax

MSWebDVD.SelectParentalCountry(iCountry, sUserName, sPassword);

Parameters

iCountry

Specifies the country/region as an Integer.

sUserName

Specifies the current logged-on user as a String. (Currently ignored.)

sPassword

Specifies the application password String.

Return Values

No return value.

Remarks

The parental country/region determines how the parental levels are interpreted.

See Also

  • Enforcing Parental Management Levels
  • SelectParentalLevel
  • NotifyParentalLevelChange
  • GetTitleParentalLevels
  • GetPlayerParentalCountry
  • GetPlayerParentalLevel
  • AcceptParentalLevelChange


SelectParentalLevel Method

The SelectParentalLevel method sets the specified parental level for subsequent playback.

Syntax

MSWebDVD.SelectParentalLevel(iLevel, sUserName, sPassword);

Parameters

iLevel

Specifies the parental management level as an Integer. To enable the parental management, the iLevel must range from 1 through 8. To disable the parental management, set iLevel to -1.

sUserName

Specifies the current user as a String. (Currently ignored.)

sPassword

Specifies the password currently stored in the registry as a String.

Return Values

No return value.

Remarks

This method sets the access level in the MSWebDVD object, which determines what content the user can play back. Higher levels can play lower-level content but lower levels can't play higher-level content. The exact meaning of the eight DVD parental management levels varies depending on the country/region. In the United States and Canada, the levels are mapped to the Motion Picture Association of America (MPAA) rating categories. Parental management in the DVD Navigator is disabled by default.

See Also

  • Enforcing Parental Management Levels
  • SelectParentalCountry
  • NotifyParentalLevelChange
  • GetTitleParentalLevels
  • GetPlayerParentalCountry
  • GetPlayerParentalLevel
  • AcceptParentalLevelChange


SelectRightButton Method

The SelectRightButton method selects the right directional button from the displayed menu.

Syntax

MSWebDVD.SelectRightButton();

Return Values

No return value.

See Also

  • ActivateButton
  • SelectLeftButton
  • SelectLowerButton
  • SelectUpperButton


SelectUpperButton Method

The SelectUpperButton method selects the upper directional button from the displayed menu.

Syntax

MSWebDVD.SelectUpperButton();

Return Values

No return value.

See Also

  • ButtonsAvailable
  • CurrentButton
  • ActivateButton
  • GetButtonAtPosition
  • GetButtonRect
  • SelectAndActivateButton
  • SelectAtPosition
  • SelectLeftButton
  • SelectLowerButton
  • SelectRightButton


SetClipVideoRect Method

The SetClipVideoRect method zooms the video display to the specified subrectangle.

Syntax

MSWebDVD.SetClipVideoRect(oRect);

Parameters

oRect

Specifies a DVDRect object, which contains the clipping rectangle.

Return Values

No return value.

Remarks

When you set a new clipping rectangle, the object enlarges that area to fit within the application's overall display dimensions. This creates the effect zooming in on a particular area of the screen. To specify the rectangle, create a new DVDRect object and fill in its properties.

The most common rectangle for video display is 720 x 540.

See Also

  • GetClipVideoRect


SetDelayTime

The SetDelayTime method sets the delay time for the ToolTip associated with the MSWebDVD object.

Syntax

MSWebDVD.SetDelayTime(iDelayType, iNewVal)

Parameters

iDelayType

Specifies the type of delay as an Integer.

Value | Description
-1 | To reset the autopop delay time to its default value, set iNewVal to -1.
0 | Set the length of time a ToolTip window remains visible if the pointer is stationary within a tool's bounding rectangle.
1 | Set the length of time a pointer must remain stationary within a tool's bounding rectangle before the ToolTip window appears.
2 | Set the length of time it takes for subsequent ToolTip windows to appear as the pointer moves from one tool to another.
3 | Set all delay times to default proportions. The autopop time is ten times the initial time and the reshow time is one-fifth the initial time. If this flag is set, use a positive value of iNewVal to specify the initial time, in milliseconds.

iNewVal

Specifies the delay, in milliseconds, as an Integer.

Value | Description
-1 | Sets the delay specified in iDelayType to its default value
any other negative value | Sets all delay types to their default value.

Return Values

No return value.


SetGPRM Method

The SetGPRM method sets the specified general parameter register to the specified value.

Syntax

MSWebDVD.SetGPRM(iIndex, nValue);

Parameters

iIndex

Specifies the general parameter register to set as an Integer. The Integer value must range from 0 through 15.

nValue

Specifies the new value for the register as an Integer.

Remarks

General parameter registers, or GPRMs, are 16-bit registers that each disc can use in unique ways for temporary data storage. A player application does not need to access these registers for any standard playback or navigation control using the MSWebDVD object. This method is provided for player applications implementing advanced functionality. Do not attempt to modify the GPRMs directly unless you have a thorough knowledge of the DVD specification and the ways in which the GPRMs are used on the particular disc to be played. Changing these values can result in unpredictable behavior.


ShowCursor Method

The ShowCursor method makes the cursor visible when the MSWebDVD object is in full-screen mode.

Syntax

MSWebDVD.ShowCursor(bShow);

Parameters

bShow

Specifies whether to show the cursor as a Boolean.

Value | Description
true | Show the cursor
false | Do not show the cursor

Return Values

No return value.

Remarks

When the DVD display goes into full-screen mode, the cursor disappears within 3 to 5 seconds. Use this method to make the cursor visible again if your application's control buttons are visible in full-screen mode.


ShowMenu Method

The ShowMenu method displays the specified menu on the screen.

Syntax

MSWebDVD.ShowMenu(iMenuID);

Parameters

iMenuID

Specifies the menu ID as an Integer.

Value | Description
2 | Title (Top)
3 | Root
4 | Subpicture
5 | Audio
6 | Angle
7 | Chapter

Return Values

No return value.

Remarks

DVD menu names can be somewhat confusing. The title menu is another name for the Video Manager Menu, the main menu for the entire disc; it generally lists all the video title sets available on the disc. The root menu is the menu for one video title set, which can contain one title or a group of titles. All the titles in a title set share the same Subpicture, Audio, and Angle menus.


Step Method

The Step method advances the DVD-Video stream by the specified number of frames.

Syntax

MSWebDVD.Step(iFrames);

Parameters

iFrames

Specifies the number of frames to step as an Integer.

Return Values

No return value.

Remarks

Before calling this method, call CanStep to determine whether the decoder supports frame stepping.

If the DVD-Video is playing in reverse mode when this method is called, and the decoder supports reverse frame stepping, then the frame stepping is done in reverse.


StillOff Method

The StillOff method resumes playback, canceling still mode.

Syntax

MSWebDVD.StillOff();

Return Values

No return value.

Remarks

The DVD Navigator goes into still mode when it encounters a still frame authored on the disc. It notifies your application by sending an EC_DVD_STILL_ON event. Still mode is different from the DVD Navigator being in a paused state because of a user operation. Calling StillOff resumes playback from still mode but does not restart the DVD Navigator when it is in a paused state.


Stop Method

The Stop method stops playback.

Syntax

MSWebDVD.Stop();

Return Values

No return value.

Remarks

If EnableResetOnStop is set to true, calling Stop puts the DVD Navigator, along with the rest of the filter graph, into a stopped state, which means that the next time the user presses the Play button, playback starts at the beginning of the disc. If EnableResetOnStop is set to true, playback resumes where it left off when the user issues the next Play command.


SubpictureOn Property

The SubpictureOn property sets or retrieves the current subpicture state (on or off).

Syntax

[ bState = ] MSWebDVD.SubpictureOn

Return Values

Returns a Boolean value indicating whether the subpicture is displayed.

Remarks

This property does not affect display of Closed Captions. Closed Captions are embedded within the video stream. DVD subpictures are transported on a separate stream.

When the subpicture stream is changed using CurrentSubpictureStream, the SubpictureOn property toggles to True.

This property is read/write with a default value of false.


SubpictureStreamsAvailable Property

The SubpictureStreamsAvailable property retrieves the number of subpicture streams available in the current title.

Syntax

[ iStreams = ] MSWebDVD.SubpictureStreamsAvailable

Return Values

Returns the number of available streams as an Integer.

Remarks

This property is read-only with no default value. To query each stream for its language attribute, first call this method to get the upper bound.

Stream numbering is zero-based.


TitlesAvailable Property

The TitlesAvailable property retrieves the number of titles available on the disc.

Syntax

[ iTitles = ] MSWebDVD.TitlesAvailable

Return Values

Returns the number of available titles as an Integer value from 1 through 99.

Remarks

This property is read-only with no default value.


ToolTip Property

The ToolTip property sets the text for the ToolTip that appears when the mouse pointer is over the MSWebDVD video rectangle.

Syntax

[ sToolTip = ] MSWebDVD.ToolTip

Return Values

Returns the ToolTip text as a String.

Remarks

This property is read/write with no default value. If the string is empty, no ToolTip appears.


ToolTipMaxWidth Property

The ToolTipMaxWidth property sets or retrieves the maximum width for the ToolTip associated with the MSWebDVD object.

Syntax

[ iMaxWidth = ] MSWebDVD.ToolTipMaxWidth

Return Values

Returns the maximum width for the application's ToolTip as an Integer.

Remarks

This property is read/write with a default value of 200 pixels.


TotalTitleTime Property

The TotalTitleTime property retrieves the total playback time for the current title.

Syntax

[ sTotalTime = ] MSWebDVD.TotalTitleTime

Return Values

Returns the total playing time of the current title as a String in the format "hh:mm:ss:ff".

Remarks

This property is read-only with no default value. The returned string will be 11 characters long in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

See Also

  • PlayAtTime
  • PlayAtTimeInTitle


UOPValid Method

The UOPValid method retrieves a value that indicates whether the specified user operation (UOP) is currently valid.

Syntax

[ bIsValid = ] MSWebDVD.UOPValid(iUOP);

Parameters

iUOP

Specifies the user operation (UOP) as an Integer.

Value | Description
0 | PlayTitle, PlayAtTime PlayAtTimeInTitle
1 | PlayChapter
2 | PlayTitle
3 | Stop
4 | ReturnFromSubmenu
5 | PlayChapter
6 | PlayPrevChapter, ReplayChapter
7 | PlayNextChapter
8 | PlayForwards
9 | PlayBackwards
10 | ShowMenu with a parameter value of 2 (DVD_MENU_Title)
11 | ShowMenu with a parameter value of 3 (DVD_MENU_Root)
12 | ShowMenu with a parameter value of 4 (DVD_MENU_Subpicture)
13 | ShowMenu with a parameter value of 5 (DVD_MENU_Audio)
14 | ShowMenu with a parameter value of 6 (DVD_MENU_Angle)
15 | ShowMenu with a parameter value of 7 (DVD_MENU_Chapter)
16 | Resume
17 | SelectLeftButton, SelectRightButton,SelectUpperButton,SelectLowerButton
18 | StillOff
19 | Pause
20 | CurrentAudioStream
21 | CurrentSubpictureStream
22 | CurrentAngle, SelectParentalLevel
23 | KaraokeAudioPresentationMode
24 | Select video mode preference.

Return Values

Returns a Boolean value indicating whether the specified operation is permitted by UOP control.


Volume Property

The Volume property sets or retrieves the speaker volume for the audio stream output.

Syntax

[ iVolume = ] MSWebDVD.Volume

Return Values

Returns the volume level as attenuation in decibels as an Integer.

Remarks

This property is read/write with a default value of 0. Full volume is 0, and 10,000 is silence; the scale is logarithmic. Multiply the desired decibel level by 100 (for example 10,000 = 100 dB).


VolumesAvailable Property

The VolumesAvailable property retrieves the number of volumes in a multivolume set.

Syntax

[ iVolumes = ] MSWebDVD.VolumesAvailable

Return Values

Returns the number of volumes in the set as an Integer.

Remarks

This property is read-only with no default value. Some DVD titles might be released as a multidisc set or series. Use this method to determine the volume number for the current disc.


WindowlessActivation Property

The WindowlessActivation property initializes the MSWebDVD object at design time for either windowed or windowless mode.

Syntax

[ bWindowless = ] MSWebDVD.WindowlessActivation

Return Values

Returns whether the object is in windowed mode as a Boolean.

Remarks

This property is read/write with a default value of true. Therefore, you only need to set this property if you are running the MSWebDVD object in a windowed container. When contained in a Web page in Microsoft® Internet Explorer, MSWebDVD is always in windowless mode, and you don't need to set this property.


Zoom Method

The Zoom method zooms the video display in or out, centered on a given set of screen coordinates.

Syntax

MSWebDVD.Zoom(iXPos, iYPos, iZoomRatio);

Parameters

iXPos

Specifies the x-coordinate at the center of the rectangular zoom area as an Integer.

iYPos

Specifies the y-coordinate at the center of the rectangle to be zoomed as an Integer.

iZoomRatio

Specifies the magnification factor applied to the current zoom value as an Integer. The total maximum value depends on what the hardware overlay can support; this is typically a factor of 32 to 64 times the original size.

Return Values

No return value.

Remarks

The new zoom ratio stays in effect until it is restored to the original size or changed again. In other words, two calls to this method specifying an iZoomRatio of two will result in a zoom ratio four times larger than the original video size. If the user tries to zoom beyond what the hardware can support, this method will succeed but do nothing.

The SetClipVideoRect method is another way to zoom in; the only difference between the two methods is the way in which the zoom rectangle is specified.


MSDVDAdm Object

The methods and properties of the MSDVDAdm "administration" object enable a scripting application to modify its default settings in the Microsoft® Windows® registry. The registry is a database on all Windows systems where applications can store information about themselves to be used on initialization or during run time.

Most of these methods and properties do not set or retrieve the current values in the MSWebDVD object itself. This means, for example, that when you call GetParentalLevel the returned value is not the current parental level stored in the object. Rather, it is the default parental level stored in the registry. To get the current parental level, call the MSWebDVD method GetPlayerParentalLevel. Calling SaveParentalLevel simply writes a new default parental access level to the registry; you still need to call the MSWebDVD method SelectParentalLevel to make the change take effect immediately in the MSWebDVD object. The default locale identifier (LCID) methods work in a similar way.

On the other hand, the BookmarkOnStop and BookmarkOnClose methods take effect immediately because the MSWebDVD object checks these settings just before the user stops playback or closes the application, rather than during initialization.

You access the MSDVDAdm object through the DVDAdm property of MSWebDVD. So, for example, if the MSWebDVD object is named "DVD," call ChangePassword as shown in the following code example.

DVD.DVDAdm.ChangePassword(sUserName, sOld, sNew);

Methods and Properties

The following table lists the methods and properties exposed by the MSDVDAdm object methods and properties.

Method | Description
ChangePassword | Saves a new application password in the registry.
SaveParentalLevel | Saves a new default parental level to the registry.
SaveParentalCountry | Saves the application's new parental country/region to the registry.
ConfirmPassword | Tests whether the specified password matches the previously saved password.
GetParentalLevel | Retrieves the parental level that was last saved to the registry.
GetParentalCountry | Retrieves the parental country/region that was last saved to the registry.
RestoreScreenSaver | Restores the system screen saver settings.
Properties | Description
DisableScreenSaver | Turns the system screen saver on or off.
DefaultAudioLCID | Sets or retrieves the registry setting for the user-specified default LCID for the audio stream.
DefaultSubpictureLCID | Sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.
DefaultMenuLCID | Sets or retrieves the registry setting for the user-specified default LCID for menus.
BookmarkOnStop | Sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.
BookmarkOnClose | Sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user closes the application.


BookmarkOnClose Property

The DVDAdm.BookmarkOnClose property sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user closes the application.

Syntax

[ bBookmarkOnClose = ] DVD.DVDAdm.BookmarkOnClose

Return Values

Returns a Boolean value, which if true, indicates that the MSDVDAdm control will save a bookmark of all DVD settings, including position on disc, parental level, and parental country/region when the user closes the DVD player application.

Remarks

This property is read/write with a default value of true.

See Also

  • BookmarkOnStop
  • Saving and Restoring Bookmarks
  • MSDVDAdm Object


BookmarkOnStop Property

The DVDAdm.BookmarkOnStop property sets or retrieves a value that tells the MSWebDVD object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.

Syntax

[ bBookmarkOnStop = ] DVD.DVDAdm.BookmarkOnStop

Return Values

Returns a Boolean value indicating whether the MSDVDAdm object will save a bookmark of all DVD settings including position on disc, parental level and parental country/region.

Remarks

This property is read/write with a default value of false.

Bookmarks are valid only for a particular machine. A user cannot save a bookmark and then send it to someone else to read on a different machine.

See Also

  • BookmarkOnClose
  • MSDVDAdm Object


ChangePassword Method

The DVDAdm.ChangePassword method saves a new application password in the registry.

Syntax

DVD.DVDAdm.ChangePassword(sUserName, sOld, sNew);

Parameters

SUserName

Specifies the current user's logon name as a String. The MSDVDAdm object ignores this parameter. See Remarks.

sOld

Specifies the user's old password as a String.

sNew

Specifies the user's new password as a String. Cannot be an empty string.

Return Values

No return value.

Remarks

Currently, the sUserName parameter is ignored on this and all related methods. This means that whoever knows the password can set the parental level. There is only one password and one parental level for the application. There is no support for individual user logon names or multiple password management. To enforce parental management levels, parents should set the password and then set the parental level appropriate for younger members of the family. When parents want to view a disc with adult-rated content, they can change the level, and then change it back when they are done viewing. As long as the children do not know the password, they can only watch content at or below the level set for them.

See Also

  • ConfirmPassword
  • MSDVDAdm Object


ConfirmPassword Method

The DVDAdm.ConfirmPassword method tests whether the specified password matches the previously saved password.

Syntax

[ bIsConfirmed = ] DVD.DVDAdm.ConfirmPassword(sUserName, sPassword);

Parameters

sUserName

Specifies the user's name as a String.

sPassword

Specifies the new password as a String.

Return Values

Returns true if the specified password matches the existing password, false otherwise.

Remarks

Currently, the sUserName parameter is ignored on this and all related methods.

See Also

  • ChangePassword
  • MSDVDAdm Object


DefaultAudioLCID Property

The DVDAdm.DefaultAudioLCID property sets or retrieves the registry setting for the user-specified default LCID for the audio stream.

Syntax

[ iAudioLCID = ] DVD.DVDAdm.DefaultAudioLCID

Return Values

Returns an Integer value representing the user-specified default audio LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default audio stream as authored on the DVD. For the range of valid LCIDs, see the Microsoft® Win32® documentation in the Platform SDK.

Remarks

This property is read/write with no default value. If no default audio LCID is specified, the MSDVDAdm object will play the audio stream that is marked as the default stream on the disc.

See Also

  • MSDVDAdm Object


DefaultMenuLCID Property

The DVDAdm.DefaultMenuLCID property sets or retrieves the registry setting for the user-specified default LCID for menus.

Syntax

[ iMenuLCID = ] DVD.DVDAdm.DefaultMenuLCID

Return Values

Returns an Integer value representing the LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default menu language as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

Remarks

This property is read/write with no default value. If no default menu LCID is specified, the MSDVDAdm object will use the language that is marked as the default menu language on the disc.

See Also

  • MSDVDAdm Object


DefaultSubpictureLCID Property

The DVDAdm.DefaultSubpictureLCID property sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.

Syntax

[ iSubpictureLCID = ] DVD.DVDAdm.DefaultSubpictureLCID

Return Values

Returns an Integer value representing the user-specified default subpicture LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default subpicture stream as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

Remarks

This property is read/write with no default value. If no default subpicture LCID is specified, the MSDVDAdm object will play the subpicture stream that is marked as the default stream on the disc.

See Also

  • MSDVDAdm Object


DisableScreenSaver Property

The DVDAdm.DisableScreenSaver property turns the system screen saver on or off.

Syntax

[ bDisabled = ] DVD.DVDAdm.DisableScreenSaver

Return Values

Returns a Boolean value indicating whether the system's screen saver settings are disabled for the DVD player application; TRUE means the settings are disabled.

Remarks

This property is read/write with a default value of true. When viewing a DVD-Video disc, a user typically does not use the mouse or keyboard for extended periods of time. The MSWebDVD ActiveX® control therefore disables the system screen saver by default. Object

See Also

  • RestoreScreenSaver
  • MSDVDAdm Object


GetParentalCountry Method

The DVDAdm.GetParentalCountry method retrieves the parental country/region that was last saved to the registry.

Syntax

[ iParentalCountry = ] DVD.DVDAdm.GetParentalCountry();

Return Values

Returns an Integer indicating the default country/region code stored in the registry.

Remarks

The parental country/region this method retrieves is not necessarily the same country/region currently stored in the MSWebDVD object.

See Also

  • MSDVDAdm Object


GetParentalLevel Method

The DVDAdm.GetParentalLevel method retrieves the parental level that was last saved to the registry.

Syntax

[ iParentalLevel = ] DVD.DVDAdm.GetParentalLevel();

Return Values

Returns an Integer from 1 through 8 indicating the default parental level.

Remarks

The parental level this method retrieves is not necessarily the same level currently stored in the MSWebDVD control; to get the level currently stored in the control, call the GetPlayerParentalLevel method. A value of -1 indicates that parental management is disabled.

See Also

  • MSDVDAdm Object


RestoreScreenSaver Method

The DVDAdm.RestoreScreenSaver method restores the system screen saver settings.

Syntax

DVD.DVDAdm.RestoreScreenSaver();

Return Values

No return value.

Remarks

Generally, a DVD application will disable the system's screen saver on startup by setting the DisableScreenSaver property to true, and then re-enable the screen saver again when the DVD application is closed by calling RestoreScreenSaver. If an application does not use the system's screen saver settings, it does not have to call this method or set the DisableScreenSaver property.

See Also

  • MSDVDAdm Object


SaveParentalCountry Method

The DVDAdm.SaveParentalCountry method saves the application's new parental country/region to the registry.

Syntax

DVD.DVDAdm.SaveParentalCountry( iCountry, sUserName, sPassword);

Parameters

iCountry

Specifies the parental country/region as an Integer.

sUserName

Specifies the user name as a String. (Currently ignored.)

sPassword

Specifies the password as a String.

Return value

No return value.

Remarks

This method enables a user who knows the current password to save a new parental country/region setting to the registry. As with all the methods of MSDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSWebDVD object is created, it will open with the new country/region. To change the parental country/region in the player, call SelectParentalCountry, which does not change the registry setting.

See Also

  • SaveParentalLevel
  • MSDVDAdm Object


SaveParentalLevel Method

The DVDAdm.SaveParentalLevel method saves a new default parental level to the registry.

Syntax

DVD.DVDAdm.SaveParentalLevel( iLevel, sUserName, sPassword);

Parameters

iLevel

Specifies the parental level as anInteger value from 1 through 8.

sUserName

Specifies the user name as a String. (Currently ignored.)

sPassword

Specifies the password as a String.

Return Values

No return value.

Remarks

This method enables a user who knows the current password to save a new parental level setting to the registry. As with all the methods of MSDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSWebDVD object is started, it will open with the new level. Specify -1 to disable parental management. To change the parental level in the player, call SelectParentalLevel, which does not change the registry setting.

See Also

  • MSDVDAdm Object


DVDRect Object

The properties of the DVDRect object enable a scripting application to specify and receive rectangle coordinates in MSWebDVD methods such as GetButtonRect, GetClipVideoRect, GetVideoSize and SetClipVideoRect.

Properties | Description
x | Sets or retrieves the x position of the rectangle's upper-left corner.
y | Sets or retrieves the y position of the rectangle's upper-left corner.
Width | Sets or retrieves the width of the rectangle, in pixels.
Height | Sets or retrieves the height of the rectangle, in pixels.


Height Property

The Height property sets or retrieves the height of the rectangle.

Syntax

[ iHeight = ] DVDRect.Height

Return Values

Returns the height, in pixels, of the rectangle as an Integer.

Remarks

This property is read/write with no default value.


Width Property

The Width property sets or retrieves the width of the rectangle.

Syntax

[ iWidth = ] DVDRect.Width

Return Values

Returns the width, in pixels, of the rectangle as an Integer.

Remarks

This property is read/write with no default value.


x Property

The x property sets or retrieves the x position of the rectangle's upper-left corner.

Syntax

[ iXPos = ] DVDRect.x

Return Values

Returns the X position of the rectangle's upper-left corner as an Integer.

Remarks

This property is read/write with no default value.


y Property

The y property sets or retrieves the y position of the rectangle's upper-left corner.

Syntax

[ iYPos = ] DVDRect.y

Return Values

Returns the Y position of the rectangle's upper-left corner as an Integer.

Remarks

This property is read/write with no default value.


MSWebDVD Events

The MSWebDVD Microsoft® ActiveX® control notifies your application when various types of internal events occur or when certain information is encountered on the disc.

Most of the events relate to user operation (UOP) controls. DVD authors can encode the disc so that any DVD command (such as PlayForwards, Pause, ShowMenu, and so on) can be disabled at any time. For example, most discs will not allow users to fast forward or show a menu while the FBI warning is playing. After the warning is over, the disc permits these operations. By handling the UOP events, your application can update its user interface to show the user which commands are currently permitted by the disc. The most common way to do this is by disabling a button. For example, if your application received a PlayForwards event with bEnabled set to false, you could disable the Play button. When it received that event with bEnabled set to true, you could enable the button again.

There are three events that do not relate to UOP controls. The DVDNotify event notifies your application of many different types of DVD-related events, which are identified in the EventCode parameter. Some events have additional information in he Param1 and Param2 parameters. The ReadyStateChange event notifies your application of changes in the MSWebDVD ReadyState property, which is a property common to all ActiveX controls. The UpdateOverlay event is sent to applications only if they are hosting MSWebDVD in windowless mode. Applications need to respond to this event only if they are displaying floating buttons over the video rectangle in full screen mode.

See Also

  • Handling DVD Event Notifications.
  • MSWebDVD Object
Event | Description
ChangeCurrentAngle | Sent when the disc enables or disables changing the angle.
ChangeCurrentAudioStream | Sent when the disc enables or disables changing the audio stream.
ChangeCurrentSubpictureStream | Sent when the ChangeCurrentSubpictureStream command has been enabled or disabled.
DVDNotify | Notifies an application of many different DVD events and disc instructions.
PauseOn | Sent when the Pause command has been enabled or disabled.
PlayAtTime | Sent when the PlayAtTime command has been enabled or disabled.
PlayAtTimeInTitle | Sent when the PlayAtTimeInTitle command has been enabled or disabled.
PlayBackwards | Sent when the PlayBackwards command has been enabled or disabled.
PlayChapter | Sent when the PlayChapter command has been enabled or disabled.
PlayChapterInTitle | Sent when the PlayChapterInTitle command has been enabled or disabled.
PlayForwards | Sent when the PlayForwards command has been enabled or disabled.
PlayNextChapter | Sent when the PlayNextChapter command has been enabled or disabled.
PlayPrevChapter | Sent when the PlayPrevChapter command has been enabled or disabled.
PlayTitle | Sent when the PlayTitle command has been enabled or disabled.
ReadyStateChange | Sent when the ReadyState property of the MSWebDVD control has changed.
ReplayChapter | Sent when the ReplayChapter command has been enabled or disabled.
Resume | Sent when the Resume command has been enabled or disabled.
ReturnFromSubmenu | Sent when the ReturnFromSubmenu command has been enabled or disabled.
SelectOrActivatButton | Sent when the disc enables or disables the selection or activation of menu buttons.
ShowMenu | Sent when the disc enables or disables the showing of a menu.
StillOff | Sent when the StillOff command has been enabled or disabled.
Stop | Sent when the Stop command has been enabled or disabled.
UpdateOverlay | Sent when the overlay surface has been moved or resized or its color key has changed.


ChangeCurrentAngle

The ChangeCurrentAngle event is sent when the disc enables or disables changing the angle.

Syntax

ChangeCurrentAngle(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


ChangeCurrentAudioStream

The ChangeCurrentAudioStream event is sent when the disc enables or disables changing the audio stream.

Syntax

ChangeCurrentAudioStream(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


ChangeCurrentSubpictureStream

The ChangeCurrentSubpictureStream event is sent when the disc enables or disables changing the subpicture stream.

Syntax

ChangeCurrentSubpictureStream(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


DVDNotify

The DVDNotify event notifies an application of many different DVD events and disc instructions.

Syntax

DVDNotify(EventCode, Param1, Param2)

Parameters

EventCode

Specifies the DVD event notification code.

Param1

Can contain additional information related to the event.

Param2

Can contain additional information related to the event.

Remarks

DVD Event Notification Codes gives a full explanation of all DVD event notification codes and their parameters.


PauseOn

The PauseOn event is sent when the PauseOn command has been enabled or disabled.

Syntax

PauseOn(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayAtTime

The PlayAtTime event is sent when the PlayAtTime command has been enabled or disabled.

Syntax

PlayAtTime(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayAtTimeInTitle

The PlayAtTimeInTitle event is sent when the PlayAtTimeInTitle command has been enabled or disabled.

Syntax

PlayAtTimeInTitle(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayBackwards

The PlayBackwards event is sent when the PlayBackwards command has been enabled or disabled.

Syntax

PlayBackwards(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayChapter

The PlayChapter event is sent when the PlayChapter command has been enabled or disabled.

Syntax

PlayChapter(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayChapterInTitle

The PlayChapterInTitle event is sent when the PlayChapterInTitle command has been enabled or disabled.

Syntax

PlayChapterInTitle(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayForwards

The PlayForwards event is sent when the PlayForwards command has been enabled or disabled.

Syntax

PlayForwards(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayNextChapter

The PlayNextChapter event is sent when the PlayNextChapter command has been enabled or disabled.

Syntax

PlayNextChapter(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayPrevChapter

The PlayPrevChapter event is sent when the PlayPrevChapter command has been enabled or disabled.

Syntax

PlayPrevChapter(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


PlayTitle

The PlayTitle event is sent when the PlayTitle command has been enabled or disabled.

Syntax

PlayTitle(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


ReadyStateChange

The ReadyStateChange event is sent when the ReadyState property of the MSWebDVD control has changed.

Syntax

ReadyStateChange(ReadyState)

Parameters

ReadyState

Specifies the new value of the ReadyState property.

Value | Description
0 | READYSTATE_UNINITIALIZED
1 | READYSTATE_LOADING
2 | READYSTATE_LOADED
3 | READYSTATE_INTERACTIVE
4 | READYSTATE_COMPLETE


ReplayChapter

The ReplayChapter event is sent when the ReplayChapter command has been enabled or disabled.

Syntax

ReplayChapter(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


Resume

The Resume event is sent when the Resume command has been enabled or disabled.

Syntax

Resume(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


ReturnFromSubmenu

The ReturnFromSubmenu event is sent when the ReturnFromSubmenu command has been enabled or disabled.

Syntax

ReturnFromSubmenu(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


SelectOrActivatButton

The SelectOrActivatButton event is sent when the disc enables or disables the selection or activation of menu buttons.

Syntax

SelectOrActivatButton(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


ShowMenu

The ShowMenu event is sent when the disc enables or disables the showing of a menu.

Syntax

ShowMenu(DVDMenuIDConstants, bEnabled)

Parameters

DVDMenuIDConstants

Specifies which menu has been enabled or disabled as a Number value.

Value | Description
2 | Title
3 | Root
4 | Subpicture
5 | Audio
6 | Angle
7 | Chapter

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


StillOff

The StillOff event is sent when the StillOff command has been enabled or disabled.

Syntax

StillOff(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


Stop

The Stop event is sent when the Stop command has been enabled or disabled.

Syntax

Stop(bEnabled)

Parameters

bEnabled

Specifies whether the operation is enabled or disabled as a Boolean.


UpdateOverlay

The UpdateOverlay event is sent when the overlay surface has been moved or resized or its color key has changed.

Syntax

UpdateOverlay()

Remarks

Applications should never be concerned about the overlay surface being resized or moved. This is all handled internally. But this event is also sent when the color key changes. That means that if an application is hosting MSWebDVD as a windowless control and displaying floating buttons on top of the video surface in full-screen mode, it should respond to this event by getting the new value of the ColorKey property so that it can draw the buttons properly.


Property Sets

Microsoft® DirectShow® uses property sets to support extended services offered by hardware and its associated drivers and filters. Hardware and filter vendors can define new capabilities as properties, arrange them in property sets, and publish the specification for these property sets. As the application developer, you can use the methods of the IKsPropertySet interface to determine whether a driver or filter supports a particular set of properties, and retrieve or set those properties.

All the methods exposed by IKsPropertySet require a GUID that identifies the property set (the guidPropSet parameter) and a DWORD that identifies the property within the property set (the dwPropID parameter). The dwPropID parameter is typically a member of an enumerated data type.

Individual properties can have associated data that you specify in the pPropData parameter in the IKsPropertySet::Set and IKsPropertySet::Get methods. In these methods, the property data is typed as a pointer to void. The data type and the meaning of the data are specified in the definition of the property set.

Requirements

Include Dvdmedia.h.

The following sections provide information about the property sets supported in DirectShow.

  • DVD Copy Protection Property Set
  • DVD Karaoke Property Set
  • DVD Subpicture Property Set
  • Frame Stepping Property Set
  • Pin Property Set
  • Rate Change Property Set


DVD Copy Protection Property Set

The DVD Copy Protection property set provides authentication of copy protection information from hardware or software decrypters. Use this property set to prevent unauthorized copying from prerecorded DVD-Video.

Microsoft provides software that facilitates the authentication process required by the encryption scheme, thus enabling a DVD-ROM drive to authenticate and transfer keys with a DVD decrypter. Microsoft has no current plans to ship a DVD decrypter and, instead, is providing operating system code that will act as the agent to enable authentication of either hardware or software decrypters.

The DVD navigator initiates and controls the key exchange process. The DVD minidriver needs only to implement the following properties. Other components handle the rest.

Each DVD input stream will receive copy protection properties. This is true even if the same hardware controls all DVD streams.

The following information presents the necessary constants and data types to use for this property set in calls to IKsPropertySet methods. It provides values for the GUID (guidPropSet), property ID (dwPropID), and property data type (pPropData) parameters.

Property Set GUID AM_KSPROPSETID_CopyProt

Property ID | Description
AM_PROPERTY_COPY_MACROVISION | This is a set-only property. This property sets the Macrovision level for the NTSC encoder on the output end of the receiving pin. Uses AM_COPY_MACROVISION.
AM_PROPERTY_DVDCOPY_CHLG_KEY | Both get and set operations are supported on this property. A get operation requests the decoder to provide its bus challenge key. A set operation provides the decoder with the bus challenge key from the DVD drive. The data passed in this property will be a structure of type AM_DVDCOPY_CHLGKEY.
AM_PROPERTY_DVDCOPY_DEC_KEY2 | This is a get-only property. This property requests that the decoder's bus key 2 be transferred to the DVD drive. The data passed will be a structure of type AM_DVDCOPY_BUSKEY.
AM_PROPERTY_DVDCOPY_DISC_KEY | Set-only property. This provides disc key. The key is a structure of type AM_DVDCOPY_DISCKEY.
AM_PROPERTY_DVDCOPY_DVD_KEY1 | This is a set-only property. This property provides the DVD drive bus key 1 to the decoder. The data passed will be a structure of type AM_DVDCOPY_BUSKEY.
AM_PROPERTY_DVDCOPY_REGION | Region code requests the region definition that the decoder is allowed to play in as defined by the DVD consortium. This region is defined as a DVD_REGION structure.
AM_PROPERTY_DVDCOPY_SET_COPY_STATE | Both get and set are supported on this property. Get is called first to determine if authentication is required. The set properties are indications as to which phase of copy protection negotiation the filter is entering. The data passed will be a structure of type AM_DVDCOPY_SET_COPY_STATE.
AM_PROPERTY_DVDCOPY_TITLE_KEY | This is a set-only property. This provides title key from current content. The key is a structure of type AM_DVDCOPY_TITLEKEY.

See Also

  • Property Sets


AM_COPY_MACROVISION

Macrovision level for the NTSC encoder.

Syntax

typedef struct _AM_COPY_MACROVISION {
    ULONG MACROVISIONLevel;
} AM_COPY_MACROVISION, *PAM_COPY_MACROVISION;

Members

MACROVISIONLevel

Macrovision level for the NTSC encoder. Member of the AM_COPY_MACROVISION_LEVEL enumerated data type.

Remarks

The AM_PROPERTY_COPY_MACROVISION property of the DVD Copy Protection Property Set uses this structure.

See Also

  • DVD Copy Protection Property Set


AM_COPY_MACROVISION_LEVEL

Identifies the macrovision level.

Syntax

typedef enum {
    AM_MACROVISION_DISABLED,
    AM_MACROVISION_LEVEL1,
    AM_MACROVISION_LEVEL2,
    AM_MACROVISION_LEVEL3
} AM_COPY_MACROVISION_LEVEL, *PAM_COPY_MACROVISION_LEVEL;

Elements

AM_MACROVISION_DISABLED

Disabled.

AM_MACROVISION_LEVEL1

Level 1.

AM_MACROVISION_LEVEL2

Level 2.

AM_MACROVISION_LEVEL3

Level 3.

Remarks

The AM_COPY_MACROVISION structure uses this data type.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPY_BUSKEY

Identifies the DVD bus key.

Syntax

typedef struct _AM_DVDCOPY_BUSKEY {
    BYTE BusKey[5];
    BYTE Reserved[1];
} AM_DVDCOPY_BUSKEY, *PAM_DVDCOPY_BUSKEY;

Members

BusKey

DVD drive bus key.

Reserved

Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_DVD_KEY1 and AM_PROPERTY_DVDCOPY_DEC_KEY2 properties use this structure.

A bus key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPY_CHLGKEY

Identifies the DVD challenge key.

Syntax

typedef struct _AM_DVDCOPY_CHLGKEY {
    BYTE ChlgKey[10];
    BYTE Reserved[2];
} AM_DVDCOPY_CHLGKEY, *PAM_DVDCOPY_CHLGKEY;

Members

ChlgKey

Challenge key.

Reserved

Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_CHLG_KEY property uses this structure.

A challenge key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPY_DISCKEY

Specifies the DVD disc key.

Syntax

typedef struct _AM_DVDCOPY_DISCKEY {
    BYTE DiscKey[2048];
} AM_DVDCOPY_DISCKEY, *PAM_DVDCOPY_DISCKEY;

Members

DiscKey

DVD disc key.

Remarks

The AM_PROPERTY_DVDCOPY_DISC_KEY property uses this structure.

A disc key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPY_SET_COPY_STATE

Specifies the copy protection state of the filter.

Syntax

typedef struct AM_DVDCOPY_SET_COPY_STATE {
    ULONG DVDCopyState;
} AM_DVDCOPY_SET_COPY_STATE, *PAM_DVDCOPY_SET_COPY_STATE;

Members

DVDCopyState

Copy protection state of the filter. Member of the AM_DVDCOPYSTATE enumerated data type.

Remarks

Both the IKsPropertySet::Get and IKsPropertySet::Set methods are supported on this property. The Get method is called first to determine if authentication is required. If a filter provides multiple pins that use the same authenticator, such as a hardware DVD decoder, the decoder might respond with AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED on some pins to indicate that the key exchange algorithm only needs to be applied once. The filter should respond with AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED to get the copy protection state property on the first pin where this property is issued.

The Set method is used to indicate which phase of copy protection negotiation the filter is entering. Specify these by setting the required flag in the AM_DVDCOPYSTATE enumerated type.

The AM_PROPERTY_DVDCOPY_SET_COPY_STATE property uses this structure.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPYSTATE

Specifies the copy protection state.

Syntax

typedef enum {
    AM_DVDCOPYSTATE_INITIALIZE,
    AM_DVDCOPYSTATE_INITIALIZE_TITLE,
    AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED,
    AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED,
    AM_DVDCOPYSTATE_DONE
} AM_DVDCOPYSTATE;

Elements

AM_DVDCOPYSTATE_INITIALIZE

Starting a full key-exchange algorithm.

AM_DVDCOPYSTATE_INITIALIZE_TITLE

Starting a title key-exchange algorithm.

AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED

Authentication is not required.

AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED

Authentication required.

AM_DVDCOPYSTATE_DONE

Key exchange negotiation is complete.

Remarks

The AM_DVDCOPY_SET_COPY_STATE structure uses this data type.

See Also

  • DVD Copy Protection Property Set


AM_DVDCOPY_TITLEKEY

Specifies the DVD title key from the current content.

Syntax

typedef struct AM_DVDCOPY_TITLEKEY {
    ULONG KeyFlags;
    UCHAR TitleKey[6];
    UCHAR Reserved[2];
} AM_DVDCOPY_TITLEKEY, *PAM_DVDCOPY_TITLEKEY;

Members

KeyFlags

Key flags.

TitleKey

Title key.

Reserved

Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_TITLE_KEY property uses this structure.

A title key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS.

See Also

  • DVD Copy Protection Property Set


DVD_REGION

Identifies the DVD region as reported by the local system components.

Syntax

typedef struct _DVD_REGION {
   UCHAR CopySystem;
   UCHAR RegionData;
   UCHAR SystemRegion;
   UCHAR Reserved;
} DVD_REGION, *PDVD_REGION;

Members

CopySystem

Specifies whether the disk is copy protected.

RegionData

Contains information about the region from the decoder.

SystemRegion

Contains information about region from DVD drive.

Reserved

Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_REGION property uses this structure.

See Also

  • DVD Copy Protection Property Set


DVD Karaoke Property Set

When the DVD Navigator filter goes into karaoke mode, it informs the audio decoder through the AM_PROPERTY_DVDKARAOKE_ENABLE property. The decoder should then mute audio channels 2 through 5 until it receives from the DVD Navigator an AM_PROPERTY_DVDKARAOKE_DATA property with a pointer to an AM_DvdKaraokeData data structure indicating how the auxiliary channels are to be mixed.

Property Set GUID AM_KSPROPSETID_DvdKaraoke

Property ID | Description
AM_PROPERTY_DVDKARAOKE_ENABLE | BOOLEAN value. The DVD Navigator sends the decoder an AM_PROPERTY_DVDKARAOKE_ENABLE with a value of TRUE to enable karaoke downmixing or false to disable it.
AM_PROPERTY_DVDKARAOKE_DATA | The DVD Navigator sends the decoder an AM_PROPERTY_DVDKARAOKE_DATA property with a pointer to an AM_DvdKaraokeData structure to change the downmix configuration; that is, to turn certain karaoke channels on or off and direct them to the right or left output channel.

See Also

  • Property Sets


AM_DvdKaraokeData

Specifies how to mix the karaoke audio channels.

Syntax

typedef struct tagAM_DvdKaraokeData
{
    DWORD   dwDownmix;
    DWORD   dwSpeakerAssignment;
} AM_DvdKaraokeData;

Members

dwDownmix

A bitwise OR of DVD_KARAOKE_DOWNMIX flags telling the decoder which channels are downmixed to channels 0 or 1.

dwSpeakerAssignment

A valid DVD_KARAOKE_ASSIGNMENT value that indicates which speakers the output is going to.

Remarks

This structure is used for the AM_PROPERTY_DVDKARAOKE_DATA property.

See Also

  • DVD Karaoke Property Set
  • SelectKaraokeAudioPresentationMode


DVD Subpicture Property Set

DVD Subpicture properties control the color, contrast, and output of the subpicture display.

The following information presents the necessary constants and data types to use for this property set in calls to IKsPropertySet methods. It provides values for the GUID (guidPropSet), property ID (dwPropID), and property data type (pPropData) parameters.

Property Set GUID AM_KSPROPSETID_DvdSubPic

Property ID | Description
AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON | Set-only property that enables or disables subpicture display. Microsoft® DirectShow® defines the AM_PROPERTY_COMPOSIT_ON Boolean data type for this property, as well as PAM_PROPERTY_COMPOSIT_ON as a pointer to this data type. TRUE indicates display the subpicture, FALSE indicates disable it. See the WDM portion of the Windows 98 DDK for more information.
AM_PROPERTY_DVDSUBPIC_HLI | Set-only property that specifies a rectangle of subpicture or screen whose color or contrast will be changed. Data type is AM_PROPERTY_SPHLI. See Remarks.
AM_PROPERTY_DVDSUBPIC_PALETTE | Sets the palette for a subpicture. Data type is AM_PROPERTY_SPPAL.

Remarks

The AM_PROPERTY_DVDSUBPIC_HLI property is set-only. It specifies a rectangle of subpicture or screen whose color or contrast will be changed. This differs from the DVD-Video specification, in that the Microsoft DVD navigator parses all button and keyboard information and passes only one highlight rectangle to the subpicture decoder at any given time. As a result, highlight information is sent to the decoder more often than it is present in the DVD stream.

The highlight information arrives asynchronously to the data stream. The decoder uses the highlight Start and End time stamps to correlate the highlight information to the relevant subpicture information, if any. If the decoder has not received any subpicture stream information for the requested time stamps, the decoder assumes that the highlight information is stand-alone and does not apply to a subpicture. In this case, the decoder assumes the color and contrast information is all the same color.

The data is not entirely in DVD disc format. Microsoft provides an additional structure of type AM_PROPERTY_SPHLI that is passed as the parameter to this property. This structure describes the currently selected button from the DVD highlight information.

The DVD navigator processes all keystroke information and sends new highlight information each time a button state changes. The information describes only one mode of one button at a time. It includes a display rectangle in pixel coordinates of the screen, or a display of the subpicture, if present. The structure also contains color and contrast information, but only for the present state of the currently selected button. The format is defined in the DVD specification.

Highlight information contains Start and End time stamps. These are in the same units as other time stamps, with two exceptions: A Start time stamp of 0xFFFFFFFF means the highlight property is effective upon receipt, and an End time stamp of 0xFFFFFFFF means the highlight property is valid until next highlight received.

The HLISS field is as defined in the DVD specification. A value of zero indicates that all highlights are invalid and the decoder should disable all highlights.

See Also

  • Property Sets


AM_COLCON

Indicates the color contrast description from the DVD highlight (HLI) structure.

Syntax

 typedef struct _AM_COLCON {
    UCHAR emph1col:4;
    UCHAR emph2col:4;
    UCHAR backcol:4;
    UCHAR patcol:4;
    UCHAR emph1con:4;
    UCHAR emph2con:4;
    UCHAR backcon:4;
    UCHAR patcon:4;
} AM_COLCON, *PAM_COLCON;

Members

emph1col

Emphasis color 1.

emph2col

Emphasis color 2.

backcol

Background color.

patcol

Pattern color.

emph1con

Emphasis contrast 1.

emph2con

Emphasis contrast 2.

backcon

Background contrast.

patcon

Pattern contrast.

Remarks

This structure is contained within the AM_PROPERTY_SPHLI structure.

See Also

  • DVD Subpicture Property Set


AM_DVD_YUV

Contains DVD YUV subpicture data.

Syntax

typedef struct _AM_DVD_YUV {
    UCHAR   Reserved;
    UCHAR   Y;
    UCHAR   U;
    UCHAR   V;
} AM_DVD_YUV, *PAM_DVD_YUV;

Members

Reserved

Reserved.

Y

Y color data.

U

U color data.

V

V color data.

Remarks

This structure is contained within the AM_PROPERTY_SPPAL structure.

See Also

  • DVD Subpicture Property Set


AM_PROPERTY_SPHLI

Describes the currently selected button from the DVD highlight information.

Syntax

typedef struct _AM_PROPERTY_SPHLI {
    USHORT  HLISS;
    USHORT  Reserved;
    ULONG   StartPTM;
    ULONG   EndPTM;
    USHORT  StartX;
    USHORT  StartY;
    USHORT  StopX;
    USHORT  StopY;
    AM_COLCON  ColCon;
} AM_PROPERTY_SPHLI, *PAM_PROPERTY_SPHLI;

Members

HLISS

Highlight status of current selection.

Reserved

Reserved for internal use. Do not use or set.

StartPTM

Start presentation time divided by 90,000.

EndPTM

End presentation time divided by 90,000.

StartX

Start x-coordinate pixel of the current highlight button.

StartY

Start y-coordinate pixel of the current highlight button.

StopX

Ending x-coordinate pixel of the current highlight button.

StopY

Ending y-coordinate pixel of the current highlight button.

ColCon

Color contrast description of type AM_COLCON.

Remarks

The AM_PROPERTY_DVDSUBPIC_HLI property uses this structure.

See Also

  • DVD Subpicture Property Set


AM_PROPERTY_SPPAL

Specifies the DVD subpicture palette.

Syntax

typedef struct _AM_PROPERTY_SPPAL {
    AM_DVD_YUV sppal[16];
} AM_PROPERTY_SPPAL, *PAM_PROPERTY_SPPAL;

Members

sppal

Array of 16 YUV elements that correspond to the 4-bit color numbers requested within the subpicture command stream. The YUV elements are of type AM_DVD_YUV.

Remarks

The AM_PROPERTY_DVDSUBPIC_PALETTE property uses this structure.

See Also

  • DVD Subpicture Property Set


Frame Stepping Property Set

Decoders that implement frame-accurate seeking under Microsoft® DirectShow® must implement the AM_KSPROPSETID_FrameStep property set, which is used in conjunction with the IVideoFrameStep interface.

Property Set GUID AM_KSPROPSETID_FrameStep

Property ID | Description
AM_PROPERTY_FRAMESTEP_STEP | Instructs the decoder to begin a step operation and passes an AM_PROPERTY_FRAMESTEP structure that specifies the number of steps.
AM_PROPERTY_FRAMESTEP_CANCEL | Instructs the decoder to cancel the current step operation. No instance data is associated with this property.
AM_PROPERTY_FRAMESTEP_CANSTEP | The decoder returns S_OK on this instruction to indicate that it can perform frame stepping, S_FALSE otherwise. No instance data is passed when this property is set.
AM_PROPERTY_FRAMESTEP_CANSTEPMULTIPLE | The decoder returns S_OK on this instruction to indicate that it can step multiple frames at a time, S_FALSE otherwise. No instance data is passed when this property is set.

See Also

  • Property Sets


AM_PROPERTY_FRAMESTEP Structure

Specifies the number of frames to step.

Syntax

typedef struct _AM_FRAMESTEP_STEP {
    DWORD dwFramesToStep;
} AM_FRAMESTEP_STEP;

Members

dwFramesToStep

DWORD value specifying to the decoder the number of frames to step. Must be at least 1. If greater than 1, this instruction means to skip n - 1 frames and show the nth.

See Also

  • Frame Stepping Property Set


Pin Property Set

The pin property set returns the pin category for a pin on a filter. The category is set by the filter when it creates the pin; the category indicates what type of data the pin is delivered or receives by this pin.

Property Set GUID AMPROPSETID_Pin

Property ID | Descriptiom
AMPROPERTY_PIN_CATEGORY | The only property defined in this property set is the pin category property (AMPROPERTY_PIN_CATEGORY). The value of the property is a GUID data type.

DirectShow defines the following pin categories in the Uuids.h header file:

Category GUID | Description
PIN_CATEGORY_ANALOGVIDEOIN | Input pin of the capture filter that takes analog and digitizes it.
PIN_CATEGORY_CAPTURE | Capture pin.
PIN_CATEGORY_CC | Pin providing closed captioning data from Line 21.
PIN_CATEGORY_EDS | Pin providing Extended Data Services (Line 21, even fields).
PIN_CATEGORY_NABTS | Pin providing North American Videotext Standard data.
PIN_CATEGORY_PREVIEW | Preview pin.
PIN_CATEGORY_STILL | Pin that provides a still image. The filter's capture pin must be connected before the still-image pin is connected.
PIN_CATEGORY_TELETEXT | Pin providing teletext (a closed captioning variant).
PIN_CATEGORY_TIMECODE | Pin providing timecode data.
PIN_CATEGORY_VBI | Pin providing vertical blanking interval data.
PIN_CATEGORY_VIDEOPORT | Video output pin to be connected to input pin zero on the Overlay Mixer.
PIN_CATEGORY_VIDEOPORT_VBI | Pin to be connected to the VBI Surface Allocator, the VBI surface allocator filter that is needed to allocate the correct video memory for things like closed captioning overlays in scenarios where a video port is being used. PCI, IEEE 1394, and USB scenarios do not use this filter. For more information, see Microsoft TV Technologies.
PINNAME_VIDEO_CC_CAPTURE | Hardware slicing closed-captioning pin

This property is read-only.

Example Code

The following code shows how to check whether a pin supports this property set, and if so, how to obtain the pin category.

HRESULT GetPinCategory(IPin *pPin, GUID *pPinCategory)
{
    HRESULT hr;
    IKsPropertySet *pKs;
    hr = pPin->QueryInterface(IID_IKsPropertySet, (void **)&pKs);
    if (FAILED(hr))
    {
        // The pin does not support IKsPropertySet.
        return hr;
    }
    // Try to retrieve the pin category.
    DWORD cbReturned;
    hr = pKs->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0,
        pPinCategory, sizeof(GUID), &cbReturned);

    // If this succeeded, pPinCategory now contains the category GUID.

    pKs->Release();
    return hr;
}

See Also

  • Property Sets
  • Pin Requirements for Capture Filters


Rate Change Property Set

The Rate Change property set enables MPEG-2 source/parser filters to change the playback rate. MPEG-2 decoders should support this property set. The DVD Navigator and the Stream Buffer Engine both use this property set to control playback rates.

Property Set GUID AM_KSPROPSETID_TSRateChange

Property ID | Description
AM_RATE_CorrectTS | Informs the decoder that the Navigator is setting the correct time stamps. Earlier versions of the DVD Navigator did not set the correct time stamps when the playback rate was something other than 1.0. Many decoders work around this problem by ignoring the time stamps during rewind or fast forward, and estimating the correct presentation times. These problems have been corrected in the current version of the DVD Navigator. For backward compatibility with existing decoders, the DVD Navigator indicates that the time stamps are correct by setting the AM_RATE_CorrectTS property on the decoder with the value TRUE. When this property is set, the decoder should use the actual time stamps, instead of estimating the presentation times.
AM_RATE_ExactRateChange | Obsolete.
AM_RATE_MaxFullDataRate | The DVD Navigator uses this property to query the decoder for the maximum rate at which the decoder can process the data. The data type for this property is AM_MaxFullDataRate, which is a typedef for LONG. The value indicates the maximum rate x 10000. This property is read-only.
AM_RATE_QueryFullFrameRate | This property queries the decoder for the maximum full-frame rate that the decoder supports. The data type for this property is an AM_QueryRate structure. If the playback rate exceeds the decoder's maximum rate, the source filter sends groups of continuous samples separated by discontinuities. The time stamps jump across the discontinuities. The source filter might do this even if the playback rate is within the decoder's maximum rate, because there may be other factors, such as disk IO, that limit the full playback rate.
AM_RATE_QueryLastRateSegPTS | The source filter can use this property to synchronize rate changes across several audio and video streams. Queries the decoder for the effective PTS of the rate segment that was set most recently.This property queries the decoder for the start time of the rate change that was queued most recently. This property is defined for version 1.1 of this property set; see AM_RATE_UseRateVersion.
AM_RATE_SimpleRateChange | This property is used to send rate changes to the decoder. The data type for this property is an AM_SimpleRateChange structure, which gives the new playback rate and the presentation time when the new rate takes effect.
AM_RATE_Step | Obsolete. See Frame Stepping Property Set.
AM_RATE_UseRateVersion | This property is used to signal which version of the Rate Change property set the decoder should use. The value is a WORD type. The high-order byte contains the minor version number, and the low-order byte contains the low-order byte. Thus, version 1.1 is signaled with the value 0x0101. If the decoder does not support the specified version, it should fail the call to IKsPropertySet::Set. If the source filter does not set the version, the decoder should default to version 1.0.

Remarks

Rate is the inverse of playback speed; if playback speed is 2x, the rate is 0.5. The decoder scales the presentation times on the decoded samples to match the rate. For example, if the rate is 0.5, the presentation times increase at half the normal rate, which translates to a faster playback speed, because samples are rendered earlier than normal.

Samples are sent to the decoder with a time stamp equal to the presentation time at 1x rate. The decoder must scale the time stamps on the output samples to the correct presentation time for the current rate. Generally, only I frames have time stamps. The decoder must interpolate the time stamps for the B and P frames. Note that during reverse playback, time stamps continue to increase — time stamps never go backward.

Two versions of the Rate Change property set are defined, version 1.0 and version 1.1. The default behavior is given by version 1.0. Decoder vendors are encouraged to support version 1.1, because it provides a smoother playback experience.

Rate Change Version 1.0

Version 1.0 of the Rate Change property set defines the default behavior for MPEG-2 decoders. The DVD Navigator currently uses this version.

The source filter signals a rate change by setting the AM_RATE_SimpleRateChange property. The data for this property is the new rate, plus the start time on the input sample where the rate takes effect. The decoder maintains a queue of pending rate changes, sorted by start time.

Before the DVD Navigator changes to a non-1x speed, it delivers all pending samples, temporarily sets the rate to 1.0, and flushes the graph. Then it sets the new rate. All rate changes are scheduled for the end of the current VOBU (video object unit). Note that flushing the graph resets the presentation time to zero.

The DVD Navigator operates either in smooth mode or in scan mode. In smooth mode, it sends every frame to the decoder, including B frames and P frames. The DVD Navigator uses smooth mode whenever playback speed is greater than zero but less than the decoder's maxmimum data rate. If playback speed is less than zero (reverse playback), or exceeds the decoder's maximum data rate, the DVD Navigator uses scan mode, where it sends just the I frames to the decoder. At very high speeds, it may skip some I frames; for example, it may send every other I frame.

By default, the DVD Navigator mutes the audio stream for rates other than 1.0. You can change this by calling IDvdControl2::SetOption with the DVD_AudioDuringFFwdRew flag.

Rate Change Version 1.1

Version 1.1 of the Rate Change property set follows the same basic principles as version 1.0, with the following differences:

  • The source filter signals the decoder to use version 1.1 by setting the AM_RATE_UseRateVersion property. Otherwise, the decoder should use the version 1.0 behavior.
  • The source filter does not flush the graph between rate changes. Time stamps therefore increase monotonically across rate change boundaries, rather than resetting to zero.
  • Instead of queuing a rate change for a particular reference time, the source filter can specify that a rate change applies to the decoder's most forward sample, defined as the sample at the head of the decoder's outgoing queue. To do so, the source filter uses the AM_RATE_SimpleRateChange property but sets the start time equal to -1.
  • The source filter can query the decoder for the start time of the rate change that was queued most recently. It uses the AM_RATE_QueryLastRateSegPTS property for this purpose.
  • The source filter does not mute the audio stream, regardless of the audio decoder's maximum data rate. The audio decoder can drop samples if the playback speed exceeds the decoder's maximum rate. However, it should still maintain the queue of scheduled rate changes.

More details are given in the reference pages for the individual properties.

Calculating Rate Segments

In the following diagram, the output time stamp (y) is given by formula

y = r(x - xi)

where x is the input time stamp, r is the rate, and xi is the x-intercept for the current rate. This formula is obtained by solving for the equation y = mx + b at the point xi, where m is the slope (r) and b is the y-intercept. This gives b = -m(xi), which can then be substituted back into the equation y = mx + b.

The decoder can calculate the x-intercept as follows. Given:

r1 = previous rate

r2 = current rate

xi1 = x-intercept for the previous rate change

xi2 = x-intercept for the current rate change

x = start time for the current rate change

The unknown xi2 can be found by setting y = r2(x - xi2) = r1(x - xi1) and solving for xi2. (Refer to the diagram that follows.) This gives the following result:

xi2 = (r1 / r2)(xi - x) + x

In the special case where playback is 1x at time 0, r1 = 1 and xi1 = 0.

Calculating the rate change x-intercept.

Requirements

Include Dvdmedia.h.

See Also

  • Property Sets


AM_SimpleRateChange Structure

The AM_SimpleRateChange structure is used to change the playback rate for an MPEG-2 stream.

Syntax

 typedef struct {
   REFERENCE_TIME StartTime;
   LONG           Rate;
} AM_SimpleRateChange;

Members

StartTime

Specifies the time stamp on the input sample when the new rate takes effect. The new rate applies to all samples with a time stamp >= StartTime and less than the start time on the next queued rate segment.

Rate

Specifies the new rate x 10000.

Remarks

Rate is the inverse of speed. For example, if the playback speed is 2x, the rate is 1/2, so the Rate member is set to 5000.

Version 1.1 Semantics

For version 1.1 of this property set, the StartTime member can be -1. This value indicates that the rate change applies to the decoder's most forward sample, defined as the sample at the head of the decoder's outgoing queue. The decoder should adjust the time stamps on every queued sample to reflect the new rate. If the decoder does not keep an internal queue of samples, it should return VFW_E_BUFFER_UNDERFLOW from the IKsPropertySet::Set method.

Queued samples might be incompatible with the new rate, especially for audio decoders; if so, the decoder may simply drop the queued samples. After dropping samples, it should set the discontinuity flag on the first sample it delivers.

If the source filter schedules a rate change whose start time is earlier than previously queued rate changes, the later rate changes are no longer valid, and the decoder should flush them from its queue. If StartTime is -1, the decoder should flush all pending rate changes before queuing the new rate change.

Requirements

Include Dvdmedia.h.

See Also

  • Rate Change Property Set


AM_QueryRate Structure

The AM_QueryRate structure is used to query the decoder's maximum full-frame rate for forward and reverse playback.

Syntax

typedef struct {
    LONG lMaxForwardFullFrame;
    LONG lMaxReverseFullFrame;
} AM_QueryRate ;

Members

lMaxForwardFullFrame

Specifies the maximum forward full-frame rate, as rate x 10000.

lMaxReverseFullFrame

Specifies the maximum reverse full-frame rate, as rate x 10000.

Remarks

Rate is the inverse of speed. For example, if the playback speed is 2x, the rate is 1/2, so the Rate member is set to 5000. Reverse rates are negative.

Requirements

Include Dvdmedia.h.

See Also

  • Rate Change Property Set


DirectShow Objects

This topic contains reference entries for the core COM objects included with Microsoft® DirectShow®, other than filters. For a list of filters included with DirectShow, see DirectShow Filters.

Object | Description
Capture Graph Builder | Builds video capture graphs.
DVD Graph Builder | Builds DVD playback graphs.
Filter Graph Manager | Builds and controls filter graphs.
Filter Mapper | Searches the registry for registered filters.
Media Property Bag | Sets or retrieves INFO and DISP chunks in AVI files.
Memory Allocator | Allocates buffers for media samples.
System Reference Clock | Implements a reference clock.
System Device Enumerator | Enumerates filters and hardware devices installed on the system.


Capture Graph Builder

The Capture Graph Builder is a helper object for building video and audio capture graphs. Capture and editing applications can use this component to construct filter graphs. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_CaptureGraphBuilder2
Interfaces | ICaptureGraphBuilder2

See Also

  • Audio Capture
  • Video Capture


DVD Graph Builder

The DVD Graph Builder is a helper object for building DVD playback graphs. Applications can use this component to build filter graphs for DVD playback and navigation. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_DvdGraphBuilder
Interfaces | IDvdGraphBuilder

See Also

  • Writing a DVD Application in C++


Filter Graph Manager

The Filter Graph Manager builds and controls filter graphs. This object is the central component in DirectShow. Applications use it to build and control filter graphs. The Filter Graph Manager also handles synchronization, event notification, and other aspects of the controlling the filter graph. Create this object by calling CoCreateInstance.

Class Identifier

There are two CLSIDs for creating the Filter Graph Manager.

CLSID | Description
CLSID_FilterGraph | Creates the Filter Graph Manager on a shared worker thread.
CLSID_FilterGraphNoThread | Creates the Filter Graph Manager on the application thread.

Generally, applications should use CLSID_FilterGraph. Both CLSIDs create the same object, but they use different threading models:

  • CLSID_FilterGraph creates the Filter Graph Manager on a worker thread, which is shared by all CLSID_FilterGraph instances within the same process. The thread dispatches messages sent by filters, and controls the lifetime of any windows created by filters.
  • CLSID_FilterGraphNoThread creates the Filter Graph Manager on the application's thread. If you use this CLSID, the thread that calls CoCreateInstance must have a message loop that dispatches messages; otherwise, deadlocks can occur. Also, before the application thread exits, it must release the Filter Graph Manager and all graph objects (such as filters, pins, reference clocks, and so forth).

Interfaces

The Filter Graph Manager exposes the following interfaces:

  • IAMGraphStreams
  • IAMStats
  • IBasicAudio
  • IBasicVideo
  • IBasicVideo2
  • IFilterChain
  • IFilterGraph
  • IFilterGraph2
  • IFilterMapper2
  • IGraphBuilder
  • IGraphConfig
  • IGraphVersion
  • IMediaControl
  • IMediaEvent
  • IMediaEventEx
  • IMediaEventSink
  • IMediaFilter
  • IMediaPosition
  • IMediaSeeking
  • IQueueCommand
  • IRegisterServiceProvider
  • IResourceManager
  • IServiceProvider
  • IVideoFrameStep
  • IVideoWindow


Filter Mapper

The Filter Mapper searches the registry for registered filters. The Filter Graph Manager uses this component to build filter graphs. Applications can use it to find filters that match specified search criteria. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_FilterMapper2
Interfaces | IAMFilterData (deprecated), IFilterMapper2

See Also

  • Using the Filter Mapper


Media Property Bag

The Media Property Bag object sets or retrieves INFO and DISP chunks in AVI files. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_MediaPropertyBag
Interfaces | IMediaPropertyBag

See Also

  • IPersistMediaPropertyBag Interface


Memory Allocator

The Memory Allocator object allocates buffers for media samples. Filters can use this object to allocate shared memory buffers; however, a filter with special requirements can also implement its own memory allocator object. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_MemoryAllocator
Interfaces | IMemAllocator


System Reference Clock

The System Reference Clock object implements a reference clock that returns the system time. If none of the filters in the graph provides a reference clock, the filter graph manager uses this component to synchronize the graph. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_SystemClock
Interfaces | IAMClockAdjust, IReferenceClock

See Also

  • Time and Clocks in DirectShow


System Device Enumerator

The System Device Enumerator enumerates filters and hardware devices installed on the system. Applications can use this component to locate filters and devices in a given category. Create this object by calling CoCreateInstance.

Class Identifier | CLSID_SystemDeviceEnum
Interfaces | ICreateDevEnum

See Also

  • Enumerating Devices and Filters
  • Filter Categories


DirectShow Base Classes

The Microsoft® DirectShow® base classes are a set of C++ classes and utility functions designed for implementing DirectShow filters. Several of the helper classes are also useful for application developers.

This section describes the base classes. It contains the following sections:

  • Using the DirectShow Base Classes
  • Introduction to the Filter Base Classes
  • Base Class Reference
  • Utility Functions
  • Debugging Utilities


Using the DirectShow Base Classes

To use the base classes in Microsoft® DirectShow®, you must build and link the base class library, located in the following directory:

(SDK root)\Samples\C++\DirectShow\BaseClasses

The project workspace for the base classes is named BaseClasses.dsw. The project builds two versions of the library—a retail version, Strmbase.lib, and a debug version, Strmbasd.lib. In your own project, include the header file Streams.h. Link your project either to Strmbase.lib or to Strmbasd.lib, depending on whether you are making a retail build or a debug build.

The table that follows summarizes the files you need.

Workspace | BaseClasses.dsw
Retail Library | Strmbase.lib
Debug Library | Strmbasd.lib
Header File | Streams.h

For more information on setting up your build environment, see Setting Up the Build Environment.

Preprocessor Symbols

When you include the header file Streams.h, the following preprocessor symbols have special meaning:

  • PERF: Reserved. Do not use this preprocessor symbol.
  • VFWROBUST: Enables pointer validation in retail. For more information, see Pointer Validation Macros. In debug builds, it is not necessary to define VFWROBUST.


Introduction to the Filter Base Classes

This article describes the Microsoft DirectShow base class library. This library is intended for filter developers, but application writers might find some of the helper classes and debugging utilities useful. The base class library is not required for DirectShow programming, however.

The following sections summarize the most important base classes in the library.

COM Object Classes

The following classes support the creation of COM objects:

Class | Description
CBaseObject | Base object class.
CUnknown | Implements the IUnknown interface.

Most of the DirectShow classes derive from CBaseObject. This class provides debugging assistance by keeping a count of all the active objects in the DLL at run time. In debug builds, the DLL asserts if it is unloaded while the object count is greater than zero. This makes it easier to track down leaks caused by reference-counting problems.

All of the base classes that support COM interfaces derive from CUnknown, which inherits CBaseObject. The CUnknown class supports reference counting, QueryInterface, and aggregration. For more information, see How to Implement IUnknown.

Filter and Pin Classes

The following classes support the creation of DirectShow filter and pin objects:

Class | Description
CBaseFilter | Base class for filters. Implements the IBaseFilter interface.
CBasePin | Base class for pins. Implements the IPin and IQualityControl interfaces.
CBaseInputPin | Base class for input pins that use local memory transport. Implements the IMemInputPin interface. This class derives from CBasePin.
CBaseOutputPin | Base class for output pins that use IMemInputPin connections. This class derives from CBasePin.

The following classes are useful for creating more specialized types of filters:

Class | Description
CSource | Base class for source filters. This class is designed for creating push sources. It is not suitable for pull sources, such as file readers. To create output pins for this class, use the CSourceStream class.
CTransformFilter | Base class for transform filters. This class performs a copy on the data. The pins for this class are CTransformInputPin and CTransformOutputPin.
CTransInPlaceFilter | Base class for transform filters that do not copy data. This class performs the data processing directly on the input data before passing it downstream. The pins for this class are CTransInPlaceInputPin and CTransInPlaceOutputPin.
CVideoTransformFilter | Base class for video transform filters. This class derives from CTransformFilter and adds support for quality control.
CBaseRenderer | Base class for renderer filters. The input pin for this class is CRendererInputPin.
CBaseVideoRenderer | Base class for video renderers. This class derives from CBaseRenderer.

To use these classes, you must derive your own class and write code to support the functionality that is specific to your filter. The more specialized the base class, the less code you will need to write in your derived class.

Helper Objects

The following classes implement helper objects that are used by filters and pins. Most of these classes can be used without deriving new classes from them:

Class | Description
CPullPin | Helper object for input pins on parser filters. Supports IAsyncReader connections with pull sources.
COutputQueue | Helper object for output pins that queue samples for delivery on a worker thread.
CSourceSeeking | Help object for implementing seeking on a source filter with exactly one output pin. (This class is not designed for filters with multiple pins, such as parsers.)
CEnumPins | Enumerator object for enumerating pins on a filter. Implements the IEnumPins interface.
CEnumMediaTypes | Enumerator object for enumerating preferred media types on a pin. Implements the IEnumMediaTypes interface.
CMemAllocator | Memory allocator object. Implements the IMemAllocator interface.
CMediaSample | Media sample object. Implements the IMediaSample2 interface.
CBaseReferenceClock | Base class for reference clocks. Implements the IReferenceClock interface.
CMediaType | Helper object for manipulating AM_MEDIA_TYPE structures.


Base Class Reference

This section contains reference entries for all the Microsoft DirectShow C++ classes, their data members, and their functions.

Class | Description
CAggDirectDraw | Deprecated.
CAggDrawSurface | Deprecated.
CAMEvent | Wrapper class for manual- and auto-reset events.
CAMMsgEvent | Wrapper class for event objects that perform message processing.
CAMSchedule | Scheduler for reference clocks.
CAMThread | Bass class for managing worker threads.
CAutoLock | Holds a critical section for the scope of a block.
CAutoUsingOutputPin | Obtains and releases access to a CDynamicOutputPin object.
CBaseAllocator | Bass class for allocators.
CBaseBasicVideo | Handles the IDispatch component of the IBasicVideo interface.
CBaseControlVideo | Implements the IBasicVideo interface for a generic video window.
CBaseControlWindow | Implements the IVideoWindow interface.
CBaseDispatch | Base class for implementing the IDispatch interface.
CBaseFilter | Base class for filters.
CBaseInputPin | Base class for input pins.
CBaseList | Base class for generic lists.
CBaseMediaFilter | Implements the IMediaFilter interface.
CBaseObject | Base class for implementing DirectShow objects.
CBaseOutputPin | Base class for output pins.
CBasePin | Base class for pins.
CBasePropertyPage | Base class for implementing property pages.
CBaseReferenceClock | Implements a reference clock.
CBaseRenderer | Base class for implementing renderer filters.
CBaseStreamControl | Implements the IAMStreamControl interface.
CBaseVideoRenderer | Base class for video renderers.
CBaseVideoWindow | Handles the IDispatch component of the IVideoWindow interface.
CBaseWindow | Base class for managing windows.
CBasicAudio | Handles the IDispatch interface component of the IBasicAudio interface.
CCmdQueue | Helper class for implementing the IQueueCommand interface.
CCritSec | Provides a thread lock.
CDeferredCommand | Implements the IDeferredCommand interface.
CDispParams | Wrapper class for the DISPPARAMS structure.
CDrawImage | Helper class for drawing to a window.
CDynamicOutputPin | Output pin that supports dyanamic reconnections and format changes.
CEnumMediaTypes | Enumerator for preferred media types.
CEnumPins | Enumerator for pins.
CFactoryTemplate | Class that provides information for a class factory.
CGenericList | Class template that implements a type-specific list.
CImageAllocator | Allocator for DIB sections.
CImageDisplay | Helper class for managing image display formats.
CImagePalette | Helper class for managing palettes.
CImageSample | Media sample that uses DIB sections.
CLoadDirectDraw | Deprecated.
CMediaControl | Handles the IDispatch methods of the IMediaControl interface.
CMediaEvent | Handles the IDispatch methods of the IMediaEvent interface.
CMediaPosition | Handles the IDispatch methods of the IMediaPosition interface.
CMediaSample | Media sample.
CMediaType | Class for managing media types.
CMemAllocator | Memory allocator.
CMsg | Helper class for managing requests made to a CMsgThread object.
CMsgThread | Worker thread that queues requests to the queuing thread for asynchronous completion.
COARefTime | Converts reference times between seconds and 100-nanosecond units.
COutputQueue | Object that queues media samples for delivery.
CPersistStream | Base class for implementing the IPersistStream interface.
CPosPassThru | Handles seek commands for filters with one input pin.
CPullPin | Helper class that pulls data from an output pin that supports the IAsyncReader interface.
CQueue | Class template that implements a simple, statically sized queue.
CRefTime | Helper class to manage reference times.
CRenderedInputPin | Input pin for renderer filters that support multiple inputs.
CRendererInputPin | Input pin for the CBaseRenderer class.
CRendererPosPassThru | Handles seek commands for renderer filters.
CSeekingPassThru | Helper object that creates CPosPassThru and CRendererPosPassThru objects.
CSource | Base class for implementing source filters.
CSourcePosition | Abstract class for implementing the IMediaPosition interface. Obsolete.
CSourceSeeking | Abstract class for implementing seeking in source filters with one output pin.
CSourceStream | Output pin for the CSource class.
CSystemClock | System clock.
CTransformFilter | Base class for implementing transform filters.
CTransformInputPin | Input pin used by the CTransformFilter class.
CTransformOutputPin | Output pin used by the CTransformFilter class.
CTransInPlaceFilter | Class for implementing transform filters that do not copy data.
CTransInPlaceInputPin | Input pin for the CTransInPlaceFilter class.
CTransInPlaceOutputPin | Output pin for the CTransInPlaceFilter class.
CUnknown | Implements the IUnknown interface.
CVideoTransformFilter | Base class for video transform filters.
FOURCCMap | Helper class for converting between GUIDs and FOURCCs.


CAggDirectDraw Class

The CAggDirectDraw class is deprecated, although it is still provided with the DirectShow base-class library for backward compatibility.


CAggDrawSurface Class

The CAggDrawSurface class is deprecated, although it is still provided with the DirectShow base-class library for backward compatibility.


CAMEvent Class

CAMEvent Class Hierarchy

The CAMEvent class is a wrapper for manual-reset and auto-reset events.

This class provides a convenient way to manage events, rather than calling Microsoft® Win32® functions such as CreateEvent, WaitForSingleObject, and ResetEvent.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_hEvent | Event handle.

Public Methods |
CAMEvent | Constructor method.
~CAMEvent | Destructor method.
Check | Checks whether the event is set, without blocking.
Reset | Sets the state of the event to nonsignaled.
Set | Signals the event.
Wait | Blocks until the event is signaled, or until a time-out occurs.

Operators |
operator HANDLE | Retrieves the event handle.


CAMEvent::m_hEvent

Event handle.

Syntax

HANDLE m_hEvent;

See Also

  • CAMEvent Class


CAMEvent::CAMEvent

Constructor method.

Syntax

CAMEvent(
    BOOL fManualReset = FALSE
);

Parameters

fManualReset

Boolean value that specifies whether the object is a manual-reset event or an auto-reset event. If TRUE, the object is a manual-reset event. Otherwise, it is an auto-reset event.

Remarks

The event begins in a nonsignaled state.

With an auto-reset event, the CAMEvent::Wait method resets the event to nonsignaled when the method returns. With a manual-reset event, the event remains signaled until you call the CAMEvent::Reset method.

See Also

  • CAMEvent Class


CAMEvent::~CAMEvent

Destructor method.

Syntax

~CAMEvent(void);

See Also

  • CAMEvent Class


CAMEvent::Check

The Check method checks whether the event is set, without blocking.

Syntax

BOOL Check(void);

Remarks

Returns TRUE if the event is set, or FALSE otherwise.

Remarks

This method calls the CAMEvent::Wait method with a time-out of zero. If the object is an auto-reset event, this method resets the event.

See Also

  • CAMEvent Class


CAMEvent::Reset

The Reset method sets the state of the event to nonsignaled.

Syntax

void Reset(void);

See Also

  • CAMEvent Class


CAMEvent::Set

The Set method signals the event.

Syntax

void Set(void);

Remarks

The behavior depends on whether the object is an auto-reset event or a manual-reset event:

  • Auto-reset: If any threads are waiting on this event, one thread is released and the event is reset. If no threads are waiting on this event, the event remains signaled.
  • Manual-reset: All the threads waiting on this event are released. The event remains signaled.

See Also

  • CAMEvent Class


CAMEvent::Wait

The Wait method blocks until the event is signaled, or until a time-out occurs.

Syntax

BOOL Wait(
    DWORD dwTimeout = INFINITE
);

Parameters

dwTimeout

Optional time-out value, represented in milliseconds.

Return Value

Returns TRUE if the event is signaled. Otherwise, returns FALSE.

Remarks

For auto-reset events, the event is reset to a nonsignaled state when this method returns.

See Also

  • CAMEvent Class


CAMEvent::operator HANDLE

Retrieves the event handle. This operator is not supported as an L-value.

Syntax

operator HANDLE () const;

Return Value

Returns the CAMEvent::m_hEvent member variable.

See Also

  • CAMEvent Class


CAMMsgEvent Class

CAMMsgEvent Class Hierarchy

The CAMMsgEvent class is a wrapper for event objects that perform message processing.

This class derives from the CAMEvent object. It adds one method, CAMMsgEvent::WaitMsg, which dispatches incoming messages while waiting.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
WaitMsg | Waits for the event to be signaled, while dispatching sent messages.


CAMMsgEvent::WaitMsg

The WaitMsg method waits for the event to be signaled, while dispatching sent messages.

Syntax

BOOL WaitMsg(
    DWORD dwTimeOut = INFINITE
);

Parameters

dwTimeOut

Optional time-out value, in milliseconds.

Return Value

Returns TRUE if the event is signaled, or FALSE if the time-out occurred.

Remarks

This method calls the PeekMessage function to process messages. Call this method instead of CAMEvent::Wait if your thread needs to process messages while waiting for an event. If the thread does not process messages and another thread sends a message, deadlock could occur.

For example, suppose you create a thread and then block until the thread initializes. If the thread sends a message to your window by calling the SendMessage function, it will result in a deadlock. This is because SendMessage does not return until the message has been processed. Calling WaitMsg allows the SendMessage call to return, preventing the deadlock.

See Also

  • CAMMsgEvent Class


CAMSchedule Class

The CAMSchedule class implements a scheduler for reference clocks.

Requirements

Header: Declared in Dsschedule.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CAMSchedule | Constructor method.
~CAMSchedule | Destructor method. Virtual.
GetAdviseCount | Retrieves the number of pending advise requests.
GetNextAdviseTime | Retrieves the time of the next advise request.
AddAdvisePacket | Adds an advise request to the list of pending requests.
Unadvise | Removes an advise request.
Advise | Dispatches all requests that are scheduled for a specified time or earlier.
GetEvent | Retrieves an event handle, which is used to signal a change in the next advise time.

Remarks

This helper object maintains a list of advise requests for a reference clock. The CBaseReferenceClock class uses it to help schedule advise requests. Clocks use this object in the following manner:

  1. The clock creates a worker thread to handle scheduling.
  2. The worker thread calls the CAMSchedule::GetEvent method to retrieve an event handle from the scheduler. It waits on this event, initially with an infinite time-out.
  3. To shedule a new advise request, the clock calls the CAMSchedule::AddAdvisePacket method. An advise request can be one-shot or periodic. The scheduler keeps the list of requests in time order.
  4. If a request is added to the front of the list, the scheduler signals the event. (The list is empty at first, so the first request is guaranteed to signal the event.)
  5. When the event is signaled, the worker thread calls the CAMSchedule::Advise method, specifying the current reference time. If any pending requests have expired, the scheduler dispatches them.
  6. The Advise method returns the time of the next request. The worker thread uses this value to calculate a new time-out value.
  7. Steps 2–6 repeat indefinitely.
  8. To terminate the worker thread, the clock sets an internal flag and signals the event.

In step 2, either the event is signaled, or the wait times out. If the event is signaled, it means that a new request was added to the front of the list. The worker thread must calculate a new time-out value. On the other hand, if the wait times out, it means that an advise request has come due and must be dispatched. The call to Advise in step 5 handles both cases.


CAMSchedule::AddAdvisePacket

The AddAvisePacket method adds an advise request to the list of pending requests.

Syntax

DWORD AddAdvisePacket(
    const REFERENCE_TIME& time1,
    const REFERENCE_TIME& time2,
    HANDLE hNotify,
    BOOL bPeriodic
);

Parameters

time1

Requested time for the advise.

time2

For periodic advise requests, the time between notifications. This parameter is ignored if bPeriodic is FALSE.

hNotify

Handle to a semaphore if bPeriodic is TRUE, or handle to an event if bPeriodic is FALSE.

bPeriodic

Boolean value that specifies whether to add a periodic notification or a one-shot notification. If TRUE, the notification is periodic; the time2 parameter specifies the time between notifications. If FALSE, the notification occurs only once.

Return Value

Returns an identifier for the advise request (the "cookie"). If the method fails, the return value is zero.

See Also

  • CAMSchedule Class


CAMSchedule::Advise

The Advise method dispatches all requests that are scheduled for a specified time or earlier.

Syntax

REFERENCE_TIME Advise(
    const REFERENCE_TIME& rtTime
);

Parameters

rtTime

Value that specifies the current reference time.

Return Value

Returns the reference time of the next scheduled advise request, or MAX_TIME if there are none left.

Remarks

When the clock calls this method, it specifies the current reference time. The scheduler determines which advise requests have expired, if any, and dispatches them. If a one-shot request expires, the scheduler deletes it. If a periodic request expires, the scheduler re-schedules it for the next advise time. The method returns the time of the next pending request.

To dispatch an advise request, the scheduler signals the event or semaphore given in the hNotify parameter of the CAMSchedule::AddAdvisePacket method.

See Also

  • CAMSchedule Class


CAMSchedule::CAMSchedule

Constructor method.

Syntax

CAMSchedule(
    HANDLE hEvent
);

Parameters

hEvent

Handle to an auto-reset event.

See Also

  • CAMSchedule Class


CAMSchedule::~CAMSchedule

Destructor method.

Syntax

~CAMSchedule(void);

See Also

  • CAMSchedule Class


CAMSchedule::GetAdviseCount

The GetAdviseCount method retrieves the number of pending advise requests.

Syntax

DWORD GetAdviseCount(void);

Return Value

Returns the number of pending advise requests.

See Also

  • CAMSchedule Class


CAMSchedule::GetEvent

The GetEvent method retrieves an event handle, which is used to signal a change in the next advise time.

Syntax

HANDLE GetEvent(void);

Return Value

Returns a handle to an event.

Remarks

If the next advise time changes—in other words, if a new advise request is added to the front of the list—the scheduler signals this event. The clock should call the CAMSchedule::Advise method to determine the next advise time.

See Also

  • CAMSchedule Class


CAMSchedule::GetNextAdviseTime

The GetNextAdviseTime method retrieves the time of the next advise request.

Syntax

REFERENCE_TIME GetNextAdviseTime(void);

Return Value

Returns the reference time of the next advise request, or MAX_TIME no requests are scheduled.

See Also

  • CAMSchedule Class


CAMSchedule::Unadvise

The Unadvise method removes an advise request.

Syntax

HRESULT Unadvise(
    DWORD dwAdviseCookie
);

Parameters

dwAdviseCookie

Identifier of the advise request, returned by the CAMSchedule::AddAdvisePacket method.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Not found
S_OK | Success

See Also

  • CAMSchedule Class


CAMThread Class

The CAMThread class is an abstract class for managing worker threads.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_hThread | Handle to the thread.
Public Member Variables |
m_AccessLock | Critical section that locks the thread from being accessed by other threads.
m_WorkerLock | Critical section that locks data shared among threads.
Public Methods |
CAMThread | Constructor method.
~CAMThread | Destructor method. Virtual.
InitialThreadProc | Calls the ThreadProc method when the thread is created.
Create | Creates the thread.
CallWorker | Signals the thread with a request.
Close | Waits for the thread to exit, then releases its resources.
ThreadExists | Queries whether the thread exists.
GetRequest | Waits for the next request.
CheckRequest | Checks if there is a request, without blocking.
Reply | Replies to a request.
GetRequestHandle | Retrieves a handle to the event signaled by the CallWorker method.
GetRequestParam | Retrieves the latest request.
CoInitializeHelper | Calls CoInitializeEx at the start of the thread.
Pure Virtual Methods |
ThreadProc | Thread procedure.

Remarks

This class provides methods for creating a worker thread, passing requests to the thread, and waiting for the thread to exit. To use this class, do the following:

  • Derive a class from CAMThread and override the pure virtual method CAMThread::ThreadProc. This method is the thread procedure that gets called at the start of the thread.
  • In your application, create an instance of your derived class. Creating the object does not create the thread. To create the thread, call the CAMThread::Create method.
  • To send requests to the thread, call the CAMThread::CallWorker method. This method takes a DWORD parameter, whose meaning is defined by your class. The method blocks until the thread responds (see below).
  • In your thread procedure, respond to requests by calling either CAMThread::GetRequest or CAMThread::CheckRequest. The GetRequest method blocks until another thread calls CallWorker. The CheckRequest method is non-blocking, which enables the thread to check for new requests while working asynchronously.
  • When the thread receives a request, call CAMThread::Reply to unblock the calling thread. The Reply method takes a DWORD parameter, which is passed to the calling thread as the return value for CallWorker.

When you are done with the thread, call the CAMThread::Close method. This method waits for the thread to exit, and then closes the thread handle. Your ThreadProc message must be guaranteed to exit, either on its own or in response to a CallWorker request. The destructor method also calls Close.

The following example illustrates these steps:

class MyThread : public CAMThread
{
protected:
    DWORD ThreadProc(void);
};

DWORD MyThread::ThreadProc()
{
    BOOL bShutDown = FALSE;
    while (!bShutDown)
    {
        DWORD req = GetRequest();
        printf("Request: %d\n", req);
        bShutDown = (req == 0);
        Reply(bShutDown ? S_FALSE : S_OK);
    }
    printf("Quitting Thread\n");
    return 1;
}

void main()
{
    MyThread thread;
    DWORD reply;

    thread.Create();
    reply = thread.CallWorker(3);
    reply = thread.CallWorker(0); // Thread exits.
}

In your derived class, you can also define member functions that validate the parameters to CallWorker. The following example shows a typical way to do this:

enum Command {CMD_INIT, CMD_RUN, CMD_STOP, CMD_EXIT};

HRESULT Init(void)  { return CallWorker(CMD_INIT); }
HRESULT Run(void)   { return CallWorker(CMD_RUN); }
HRESULT Stop(void)  { return CallWorker(CMD_STOP); }
HRESULT Exit(void)  { return CallWorker(CMD_EXIT); }

The CAMThread class provides two critical sections as public member variables. Use CAMThread::m_AccessLock to lock the thread from being accessed by other threads. (For example, the Create and CallWorker methods hold this lock, to serialize operations on the thread.) Use CAMThread::m_WorkerLock to lock data that is shared among threads.


CAMThread::m_AccessLock

Critical section that locks the thread from being accessed by other threads.

Syntax

CCritSec m_AccessLock;

Remarks

The CAMThread::Create and CAMThread::CallWorker methods hold this lock, to serialize operations on the thread.

See Also

  • CAMThread Class


CAMThread::m_WorkerLock

Critical section that locks data shared among threads.

Syntax

CCritSec m_WorkerLock;

See Also

  • CAMThread Class


CAMThread::m_hThread

Handle to the thread.

Syntax

HANDLE m_hThread;

Remarks

This variable is initialized as NULL. The CAMThread::Create method sets this variable to the thread handle. To determine whether the thread exists, call the CAMThread::ThreadExists method.

See Also

  • CAMThread Class


CAMThread::CAMThread

Constructor method.

Syntax

CAMThread(void);

Remarks

The constructor method does not create the thread. To create the thread, call the CAMThread::Create method.

See Also

  • CAMThread Class


CAMThread::~CAMThread

Destructor method.

Syntax

virtual ~CAMThread(void);

Remarks

The destructor calls the CAMThread::Close method, which waits for the thread to exit.

See Also

  • CAMThread Class


CAMThread::CallWorker

The CallWorker method signals the thread with a request.

Syntax

DWORD CallWorker(
    DWORD dwParam
);

Parameters

dwParam

Request parameter. The derived class defines the meaning of the parameter.

Return Value

Returns a value that is defined by the derived class.

Remarks

The CAMThread::GetRequest and CAMThread::CheckRequest methods retrieve the value of the dwParam parameter. The GetRequest method blocks until CallWorker is called.

This method blocks until the CAMThread::Reply method is called. The return value is the parameter given to Reply.

This method holds the CAMThread::m_AccessLock lock to serialize requests. Therefore, do call this method from the thread itself or from any member function that executes in the context of the thread.

See Also

  • CAMThread Class


CAMThread::CheckRequest

The CheckRequest method checks if there is a request, without blocking.

Syntax

BOOL CheckRequest(
    DWORD *pParam
);

Parameters

pParam

Pointer to a variable that receives the value passed in the last call to the CAMThread::CallWorker method.

Return Value

Returns TRUE if there is a pending request, or FALSE otherwise.

Remarks

This method is a non-blocking version of the CAMThread::GetRequest method.

If another thread is waiting on a call to CallWorker, this method retrieves the request parameter and returns TRUE. Otherwise, it returns FALSE. If the method returns TRUE, call the CAMThread::Reply method to release the requesting thread.

See Also

  • CAMThread Class


CAMThread::Close

The Close method waits for the thread to exit, then releases its resources.

Syntax

void Close(void);

Return Value

No return value.

Remarks

Before calling this method, you must provide a way for the thread to exit. For example, in your CAMThread::ThreadProc method, define a request that signals the thread to exit. Then call the CAMThread::CallWorker method with that value.

The ~CAMThread destructor method calls this method.

See Also

  • CAMThread Class


CAMThread::Create

The Create method creates the thread.

Syntax

BOOL Create(void);

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method creates the thread, using the CAMThread::InitialThreadProc method for the thread procedure and this for the thread argument.

The method fails if the thread already exists.

See Also

  • CAMThread Class


CAMThread::CoInitializeHelper

The CoInitializeHelper method calls the CoInitializeEx function at the start of the thread.

Syntax

static HRESULT CoInitializeHelper(void);

Return Value

Returns an HRESULT value. The following are possible values.

Value | Description
S_FALSE | The CoInitializeEx function is not available.
S_OK | Success.
E_FAIL | Failure.

Remarks

The CAMThread::InitialThreadProc method calls this helper method, which calls the CoInitializeEx function. It uses the COINIT_DISABLE_OLE1DDE flag, to disable Dynamic Data Exchange (DDE). For more information, see the Platform SDK.

See Also

  • CAMThread Class


CAMThread::GetRequest

The GetRequest method waits for the next request.

Syntax

DWORD GetRequest(void);

Return Value

Returns a value that is defined by the derived class.

Remarks

This method blocks until another thread calls the CAMThread::CallWorker method. Then it returns the parameter that was passed to CallWorker. Call the CAMThread::Reply method to release the requesting thread.

See Also

  • CAMThread Class


CAMThread::GetRequestHandle

The GetRequestHandle method retrieves a handle to the event that is signaled by the CAMThread::CallWorker method.

Syntax

HANDLE GetRequestHandle(void) const;

Return Value

Returns an event handle.

Remarks

The CAMEvent class keeps a private manual-reset event, which is set by CallWorker and reset by the CAMThread::Reply method.

If you call a function such as WaitForMultipleObjects, use GetRequestHandle to retrieve the event handle.

See Also

  • CAMThread Class


CAMThread::GetRequestParam

The GetRequestParam method retrieves the latest request.

Syntax

DWORD GetRequestParam(void) const;

Return Value

Returns the value of the parameter that was passed most recently to the CAMThread::CallWorker method.

See Also

  • CAMThread Class


CAMThread::InitialThreadProc

The InitialThreadProc method calls the main thread procedure.

Syntax

DWORD InitialThreadProc(
    LPVOID pv
);

Parameters

pv

this pointer.

Return Value

Returns the DWORD returned by CAMThread::ThreadProc. The derived class defines this value.

Remarks

The CAMThread::Create method uses this method for the thread procedure when it creates the thread. It uses the this pointer as the thread argument.

This method calls the CAMThread::CoInitializeHelper method and then ThreadProc.

See Also

  • CAMThread Class


CAMThread::Reply

The Reply method replies to a request.

Syntax

void Reply(
    DWORD dw
);

Parameters

dw

Value to return in the CAMThread::CallWorker method.

Remarks

The CallWorker method blocks until this method is called. The dw parameter supplies the return value for CallWorker. Call this method in your thread procedure after you retrieve a request, to release the requesting thread.

See Also

  • CAMThread Class


CAMThread::ThreadExists

The ThreadExists method queries whether the thread exists.

Syntax

BOOL ThreadExists(void);

Return Value

Returns TRUE if the thread exists, or FALSE if the thread does not exist.

See Also

  • CAMThread Class


CAMThread::ThreadProc

The ThreadProc method is the thread procedure.

Syntax

virtual DWORD ThreadProc(void) = 0;

Return Value

Returns a DWORD value whose meaning is defined by the derived class.

Remarks

This is a pure virtual method. Implement this method in your derived class to supply a thread procedure. When the CAMThread::Create method creates a thread, it gives the address of the CAMThread::InitialThreadProc method, which in turn calls your ThreadProc method.

Typically, your ThreadProc method will enter a loop that retrieves requests (by calling the CAMThread::GetRequest or CAMThread::CheckRequest methods) and processes data.

When this method returns, the thread exits.

See Also

  • CAMThread Class


CAutoLock Class

The CAutoLock class holds a critical section for the scope of a code block.

This class works in conjunction with the CCritSec class, which is a wrapper for critical section objects. The CAutoLock constructor locks the critical section, and the destructor unlocks it. By using a CAutoLock object as a local variable, you can lock a critical section with the guarantee that all code paths will unlock the critical section.

The following code example shows how to use this class:

CCritSec csMyLock;  // Critical section is not locked yet.
{
    CAutoLock cObjectLock(&csMyLock);  // Lock the critical section.

    // Protected section of code.

} // Lock goes out of scope here.

The methods in this class are not designed to be overridden.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pLock | Critical section for this lock.
Public Methods |
CAutoLock | Constructor method. Locks the specified critical section object.
~CAutoLock | Destructor method. Unlocks the critical section object.


CAutoLock::m_pLock

Critical section for this lock.

Syntax

CCritSec *m_pLock;

See Also

  • CAutoLock Class


CAutoLock::CAutoLock

Constructor method. The constructor locks the specified critical section object.

Syntax

CAutoLock(
    CCritSec *plock
);

Parameters

plock

Pointer to a CCritSec object, which contains a critical section object.

See Also

  • CAutoLock Class


CAutoLock::~CAutoLock

Destructor method. The destructor unlocks the critical section object.

Syntax

CAutoLock(void);

See Also

  • CAutoLock Class


CAutoUsingOutputPin Class

The CAutoUsingOutputPin class obtains and releases access to a CDynamicOutputPin object.

When certain methods are called on CDynamicOutputPin, the caller must obtain access to the pin and then release that access. To obtain access, the caller uses the CDynamicOutputPin::StartUsingOutputPin method. To release access, it calls the CDynamicOutputPin::StopUsingOutputPin method. The CAutoUsingOutputPin class is a helper class that handles these tasks in its constructor and destructor methods. The following code example shows how to use this class:

CDynamicOutputPin *pPin;
HRESULT hr = S_OK;  // Important! Initialize to S_OK.

// Obtain a pointer to the pin (not shown).
{
    CAutoUsingOutputPin UsingPin(pPin, &hr)
    if (SUCCEEDED(hr)) {
        // Safe to use the pin.
        pPin->Deliver(pSample);
    }
} // Object goes out of scope here.

// No longer safe to use the pin.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CAutoUsingOutputPin | Constructor method. Obtains access to the specified pin.
~CAutoUsingOutputPin | Destructor method. Releases access to the pin.


CAutoUsingOutputPin::CAutoUsingOutputPin

Constructor method. The constructor obtains access to the specified pin.

Syntax

CAutoUsingOutputPin(
    CDynamicOutputPin *pOutputPin,
    HRESULT *phr
);

Parameters

pOutputPin

Pointer to a CDynamicOutputPin object.

phr

Pointer to a variable that contains an HRESULT value. The value must be S_OK.

Remarks

When the method returns, the value of *phr indicates the success or failure of the method.

See Also

  • CAutoUsingOutputPin Class


CAutoUsingOutputPin::~CAutoUsingOutputPin

Destructor method. The destructor releases access to the pin.

Syntax

~CAutoUsingOutputPin(void);


CBaseAllocator Class

CBaseAllocator Class Hierarchy

The CBaseAllocator class is an abstract base class that implements an allocator. Allocators expose the IMemAllocator interface.

An allocator is an object that allocates memory buffers. The allocator maintains a list of available buffers. When a client (generally a filter) requests a buffer, the allocator retrieves one from the list. The client fills the buffer with data, and might pass the buffer to another object. Eventually the buffer is released and the allocator returns it to the list of available buffers.

Each buffer is encapsulated by an object called a media sample. Media samples are a way to package pointers to memory blocks within the Component Object Model (COM) framework. Media samples expose the IMediaSample interface, and are implemented using the CMediaSample class. A media sample contains a pointer to the associated buffer, which can be accessed by calling the IMediaSample::GetPointer method. For more information, see Samples and Allocators.

To use this class, perform the following steps:

  1. Call the CBaseAllocator::SetProperties method to specify the buffer requirements, including the number of buffers and the size of each buffer.
  2. Call the CBaseAllocator::Commit method to allocate the buffers.
  3. Call the CBaseAllocator::GetBuffer method to retrieve media samples. This method blocks until the next sample becomes available.
  4. When you are done with each sample, call the IUnknown::Release method on the sample. The sample is not deleted when its reference count reaches zero. Instead, the sample returns to the allocator's free list.
  5. When you are done using the allocator, call the CBaseAllocator::Decommit method to free the memory for the buffers.

The Commit method calls the virtual method CBaseAllocator::Alloc, which allocates the memory for the buffers. The Decommit method calls the pure virtual method CBaseAllocator::Free, which frees the memory. Derived classes must override these two methods.

The CMemAllocator base class derives from CBaseAllocator. The filter base classes use the CMemAllocator class.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_lFree | Pointer to a list of available (free) media samples.
m_hSem | Semaphore that is signaled when a sample becomes available.
m_lWaiting | Count of threads waiting for samples.
m_lCount | Number of buffers to provide.
m_lAllocated | Number of buffers currently allocated.
m_lSize | Size of each buffer.
m_lAlignment | Alignment of each buffer.
m_lPrefix | Prefix of each buffer.
m_bChanged | Flag indicating whether the buffer requirements have changed.
m_bCommitted | Flag indicating whether the allocator has been committed.
m_bDecommitInProgress | Flag indicating whether a decommit operation is in progress.
m_pNotify | Pointer to a callback interface, which is called when samples are released.
m_fEnableReleaseCallback | Flag indicating whether the release callback is enabled.
Protected Methods |
Alloc | Allocates memory for the buffers. Virtual.
Public Methods |
CBaseAllocator | Constructor method.
~CBaseAllocator | Destructor method.
SetNotify | Obsolete.
GetFreeCount | Retrieves the number of media samples that are not in use.
NotifySample | Releases any threads that are waiting for samples.
SetWaiting | Increments the count of waiting threads.
Pure Virtual Methods |
Free | Releases all of the buffer memory.
IMemAllocator Methods |
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.
GetProperties | Retrieves the number of buffers that the allocator will create, and the buffer properties.
Commit | Allocates the memory for the buffers.
Decommit | Decommits the buffers.
GetBuffer | Retrieves a media sample that contains a buffer.
ReleaseBuffer | Returns a media sample to the list of free media samples.


CBaseAllocator::m_lFree

Pointer to a list of available (free) media samples.

Syntax

CSampleList m_lFree;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_hSem

Semaphore that is signaled when a sample becomes available.

Syntax

HANDLE m_hSem;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lWaiting

Count of threads waiting for samples.

Syntax

long m_lWaiting

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lCount

Number of buffers to provide. The CBaseAllocator::SetProperties method sets this value. The buffers are not allocated until the CBaseAllocator::Commit method is called. The current number of allocated buffers is specified by the CBaseAllocator::m_lAllocated member variable.

Syntax

long m_lCount;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lAllocated

Number of buffers currently allocated.

Syntax

long m_lAllocated;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lSize

Size of each buffer.

Syntax

long m_lSize;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lAlignment

Alignment of each buffer. The address of each buffer must be an even multiple of this value. The prefix must be calculated into the alignment; see CBaseAllocator::m_lPrefix.

Syntax

long m_lAlignment;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_lPrefix

Prefix of each buffer, in bytes. If the value is non-zero, each buffer pointer returned by the CBaseAllocator::GetBuffer method is preceded by a block of bytes of size m_lPrefix. This memory block is called the prefix. The CBaseAllocator::m_lSize member variable does not include the prefix value.

Syntax

long m_lPrefix;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_bChanged

Flag indicating whether the buffer requirements have changed. The CBaseAllocator::SetProperties method sets the value to TRUE. In a derived class, the pure virtual method CBaseAllocator::Alloc should set the value back to FALSE. Once buffers have been allocated, there is no need to re-allocate them while m_bChanged is FALSE.

Syntax

BOOL m_bChanged;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_bCommitted

Flag indicating whether the allocator has been committed.

Syntax

BOOL m_bCommitted;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_bDecommitInProgress

Flag indicating whether a decommit operation is in progress. The value is TRUE after the CBaseAllocator::Decommit method is called, but before all the buffers have been released. If the value is TRUE, the CBaseAllocator::GetBuffer method fails. Also, the allocator should not deleted itself while the value is TRUE.

Syntax

BOOL m_bDecommitInProgress;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_pNotify

Pointer to a callback interface, which is called when samples are released.

Syntax

IMemAllocatorNotifyCallbackTemp *m_pNotify;

See Also

  • CBaseAllocator Class


CBaseAllocator::m_fEnableReleaseCallback

Flag indicating whether the release callback is enabled. This flag is set in the constructor method. If the value is FALSE, calling the CBaseAllocator::SetNotify method causes an assertion to fire (in debug builds).

Syntax

BOOL m_fEnableReleaseCallback;

See Also

  • CBaseAllocator Class


CBaseAllocator::Alloc

The Alloc method allocates memory for the buffers.

Syntax

virtual HRESULT Alloc(void);

Return Value

Returns one of the following HRESULT values.

Value | Description
S_FALSE | Buffer requirements have not changed.
S_OK | Buffer requirements have changed.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

This method is called by the CBaseAllocator::Commit method.

In the base class, this method does not allocate any memory. It returns an error if the buffer requirements were not set, S_FALSE if the requirements have not changed, and S_OK if the requirements have changed.

A derived class should override this method to perform the actual memory allocation. Typically, the derived class will perform the following steps:

  1. Call the base class implementation, to determine whether the memory truly needs allocating.
  2. Allocate memory.
  3. Create CMediaSample objects that contain chunks of memory from step 2.
  4. Add each CMediaSample object to the list of free samples (CBaseAllocator::m_lFree).

For an example, see CMemAllocator::Alloc.

See Also

  • CBaseAllocator Class


CBaseAllocator::CBaseAllocator

Constructor method.

Syntax

CBaseAllocator(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    BOOL bEvent = TRUE,
    BOOL fEnableReleaseCallback  = FALSE
);

Parameters

pName

Pointer to a string containing the debug name of the allocator. For more information, see CBaseObject.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Set the value to S_OK before creating the object. If the constructor fails, the value is set to an error code.

bEvent

Boolean value indicating whether to create a semaphore. If TRUE, the allocator creates a semaphore (CBaseAllocator::m_hSem), which is signaled whenever a sample becomes available. Set the value to FALSE if you are implementing a derived class that does not require a semaphore.

fEnableReleaseCallback

Boolean value indicating whether the release callback mechanism is enabled. Set the value to TRUE if you want to supply a callback interface, which is called when buffers are released. Specify the callback by calling the CBaseAllocator::SetNotify method.

See Also

  • CBaseAllocator Class


CBaseAllocator::~CBaseAllocator

Destructor method.

Syntax

~CBaseAllocator(void);

Remarks

Always call the CBaseAllocator::Decommit method before destroying the object. The base-class destructor cannot call Decommit, because that method calls the pure virtual method CBaseAllocator::Free. Derived classes should override this destructor and call Decommit.

See Also

  • CBaseAllocator Class


CBaseAllocator::Commit

The Commit method allocates the memory for the buffers. This method implements the IMemAllocator::Commit method.

Syntax

HRESULT Commit(void);

Return Value

Returns an HRESULT value. Possible values include those in the following list.

Value | Description
S_OK | Success.
VFW_E_SIZENOTSET | Buffer requirements were not specified.

Remarks

Before calling this method, call the CBaseAllocator::SetProperties method to specify the buffer requirements.

This method calls the virtual method CBaseAllocator::Alloc to allocate the memory for the buffers. Derived classes can override Alloc. If a decommit operation is pending, it is cancelled.

You must call this method before calling the CBaseAllocator::GetBuffer method.

See Also

  • CBaseAllocator Class


CBaseAllocator::Decommit

The Decommit method decommits the allocator. This method implements the IMemAllocator::Decommit method.

Syntax

HRESULT Decommit(void);

Return Value

Returns S_OK.

Remarks

After this method is called, calls to the CBaseAllocator::GetBuffer method will fail. As samples are released, they get returned to the free list. When the last sample is returned, the allocator calls the CBaseAllocator::Free method, which releases the allocated memory. (In the base class, Free is a pure virtual method.)

In addition, this method releases any threads that are blocked on GetBuffer calls. The calls to GetBuffer fail.

See Also

  • CBaseAllocator Class


CBaseAllocator::Free

The Free method releases all of the buffer memory. This method is called when the owning filter decommits the allocator, after the last media sample is released.

Syntax

virtual void Free(void) PURE;

Remarks

After the Decommit method is called, the allocator calls this method when it releases the last media sample. The derived class must implement this method.

See Also

  • CBaseAllocator Class


CBaseAllocator::GetBuffer

The GetBuffer method retrieves a media sample that contains a buffer. This method implements the IMemAllocator::GetBuffer method.

Syntax

HRESULT GetBuffer(
    IMediaSample **ppBuffer,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags
);

Parameters

ppBuffer

Address of a variable that receives a pointer to the buffer's IMediaSample interface.

pStartTime

Pointer to the start time of the sample.

pEndTime

Pointer to the end time of the sample.

dwFlags

Bitwise combination of zero or more flags. The base class supports the following flag:
AM_GBF_NOWAIT: Do not wait for a buffer to become available.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
VFW_E_NOT_COMMITTED | Allocator was not committed.
VFW_E_TIMEOUT | Timed out.

Remarks

Unless the caller specifies the AM_GBF_NOWAIT flag in dwFlags, this method blocks until the next sample is available.

The retrieved media sample has a valid pointer to the allocated buffer. The caller is responsible for setting any other properties on the sample, such as the time stamps, the media times, or the sync-point property. For more information, see IMediaSample.

In the base class, the pStartTime and pEndTime parameters are ignored. Derived classes can use these values. For example, the allocator for the Video Renderer filter uses these values to synchronize switching between Microsoft® DirectDraw® surfaces.

If the method needs to wait on a sample, it increments the count of waiting objects (CBaseAllocator::m_lCount) and the calls WaitForSingleObject function on the semaphore (CBaseAllocator::m_hSem). When a sample becomes available, it calls the CBaseAllocator::ReleaseBuffer method on the allocator, which increases the semaphore count by m_lCount (thereby releasing the waiting threads) and sets m_lCount back to zero.

See Also

  • CBaseAllocator Class


CBaseAllocator::GetFreeCount

The GetFreeCount method retrieves the number of media samples that are not in use.

Syntax

HRESULT GetFreeCount(
    LONG *plBuffersFree
);

Parameters

plBuffersFree

Address of a variable that receives the number of samples that are not in use.

Return Value

Returns S_OK.

Remarks

This method implements the IMemAllocatorCallbackTemp::GetFreeCount method. The allocator does not expose the IMemAllocatorCallbackTemp interface unless the fEnableReleaseCallback flag is set to TRUE in the CBaseAllocator constructor.

See Also

  • CBaseAllocator Class


CBaseAllocator::GetProperties

The GetProperties method retrieves the number of buffers that the allocator will create, and the buffer properties. This method implements the IMemAllocator::GetProperties method.

Syntax

HRESULT GetProperties(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

Pointer to an ALLOCATOR_PROPERTIES structure that receives the allocator properties.

Return Value

Returns S_OK.

See Also

  • CBaseAllocator Class


CBaseAllocator::NotifySample

The NotifySample method releases any threads that are waiting for samples.

Syntax

void NotifySample(void);

Remarks

When there are threads waiting for samples, the value of CBaseAllocator::m_lWaiting is greater than zero. If m_lWaiting is greater than zero, this method calls the ReleaseSemaphore function on the CBaseAllocator::m_hSem semaphore, activating any waiting threads. It also resets m_lWaiting to zero.

This method is called from within the CBaseAllocator::ReleaseBuffer method, when a sample is returned to the free list; and from the CBaseAllocator::Decommit method, when the allocator is decommitted.

See Also

  • CBaseAllocator Class


CBaseAllocator::ReleaseBuffer

The ReleaseBuffer method returns a media sample to the list of free media samples. This method implements the IMemAllocator::ReleaseBuffer method.

Syntax

HRESULT ReleaseBuffer(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface of the media sample object.

Return Value

Returns S_OK.

Remarks

When a media sample's reference count reaches zero, the sample calls ReleaseBuffer with itself as the parameter. This method performs the following actions.

  • Returns the media sample to the free list (CBaseAllocator::m_lFree).
  • Calls the CBaseAllocator::NotifySample method, which releases any threads that are blocked on calls to the CBaseAllocator::GetBuffer method.
  • If the CBaseAllocator::SetNotify method was called previously, calls the IMemAllocatorNotifyCallbackTemp::NotifyRelease method.
  • When the last sample is released, if there is a pending CBaseAllocator::Decommit call, calls the CBaseAllocator::Free method to release the buffer memory. (In the base class, Free is a pure virtual method.)

See Also

  • CBaseAllocator Class


CBaseAllocator::SetNotify

The SetNotify method sets or removes a callback on the allocator. The allocator calls the callback method whenever the allocator's IMemAllocator::ReleaseBuffer method is called.

Syntax

HRESULT SetNotify(
    IMemAllocatorNotifyCallbackTemp *pNotify
);

Parameters

pNotify

Pointer to the IMemAllocatorNotifyCallbackTemp interface that will be used for the callback. The caller must implement the interface. Use the value NULL to remove the callback.

Return Value

Returns S_OK.

Remarks

This method implements the IMemAllocatorCallbackTemp::SetNotify method. The allocator does not expose the IMemAllocatorCallbackTemp interface unless the fEnableReleaseCallback flag is set to TRUE in the CBaseAllocator constructor.

The IMemAllocatorNotifyCallbackTemp interface is deprecated, but this method remains in the CBaseAllocator class for backward compatibility. However, it is not recommended that you use it.

This method sets the CBaseAllocator::m_pNotify member variable equal to pNotify and increments the reference count on the interface. If m_pNotify is non-NULL, the allocator's ReleaseBuffer method calls IMemAllocatorNotifyCallbackTemp::NotifyRelease. See the Remarks section in that method for information about implementing the callback.

See Also

  • CBaseAllocator Class


CBaseAllocator::SetProperties

The SetProperties method specifies the number of buffers to allocate and the size of each buffer. This method implements the IMemAllocator::SetProperties method.

Syntax

HRESULT SetProperties(
    ALLOCATOR_PROPERTIES *pRequest,
    ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.

pActual

Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method specifies the buffer requirements, but does not allocate any buffers. Call the CBaseAllocator::Commit method to allocate buffers.

The caller allocates two ALLOCATOR_PROPERTIES structures. The pRequest parameter contains the caller's buffer requirements, including the number of buffers and the size of each buffer. When the method returns, the pActual parameter contains the actual buffer properties, as set by the allocator. In the base class, assuming that the method succeeds, the actual properties always match the requested properties. Derived classes might override this behavior.

The allocator must not be committed, and must not have outstanding buffers. In the base class, the alignment must equal 1. The CMemAllocator class overrides this requirement.

See Also

  • CBaseAllocator Class


CBaseAllocator::SetWaiting

The SetWaiting method increments the count of waiting threads.

Syntax

void SetWaiting(void);

Remarks

This method increments the CBaseAllocator::m_lWaiting member variable. If a thread is blocked in the CBaseAllocator::GetBuffer method, the allocator calls SetWaiting and then waits for the CBaseAllocator::m_hSem semaphore to be signalled. The CBaseAllocator::ReleaseBuffer method signals the semaphore and sets m_lWaiting back to zero.

See Also

  • CBaseAllocator Class


CBaseBasicVideo Class

CBaseBasicVideo Class Hierarchy

The CBaseBasicVideo class implements the IDispatch methods of the IBasicVideo interface. The remaining IBasicVideo methods are left as pure virtual methods, and must be implemented by a derived class.

The IDispatch methods in this class are standard implementations, and are not described in detail here.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • CBaseControlVideo Class
  • CBaseDispatch Class


CBaseControlVideo Class

CBaseControlVideo Class Hierarchy

The CBaseControlVideo class implements the IBasicVideo dual interface and controls the video properties of a generic video window. Generally, a CBaseControlVideo object is a video renderer that draws video into a window on the display.

The CBaseControlVideo class supports both properties and methods. Properties are more easily accessible from many Automation controllers (such as the Microsoft® Visual Basic® programming system). However, some operations require applications to be able to change several properties simultaneously; for this reason, methods are provided that enable a number of related properties to be changed.

Many CBaseControlVideo member functions require only that the video renderer be connected to a filter graph. If it is not connected, member functions will return VFW_E_NOT_CONNECTED. Properties set on a video renderer persist between successive connections and disconnections. All applications should ensure that they reset the renderer properties before starting a presentation.

When working with video, the application can select a portion of the video to use. This portion is the source rectangle that the CBaseControlVideo object controls. CBaseControlVideo enables your application to set and retrieve the source rectangle. All the rectangles that CBaseControlVideo uses employ top, left, width, and height rather than top, left, right, and bottom, which is favored in Microsoft Win32® programming. When no source rectangle has been set, the properties of the source rectangle return the full, native video size.

Protected Data Members

m_pFilter | Pointer to an owning media filter.
m_pInterfaceLock | Externally defined critical section.
m_pPin | Control of the media types for connection.

Member Functions

CBaseControlVideo | Constructs a CBaseControlVideo object.
CopyImage | Creates a memory copy of a video image.
GetImageSize | Retrieves video image size information.
SetControlVideoPin | Sets the pin with which this object should synchronize.

Overridable Member Functions

CheckSourceRect | Determines if a source rectangle is valid.
CheckTargetRect | Determines if a target rectangle is valid.
GetSourceRect | Retrieves the current source video rectangle (pure virtual).
GetStaticImage | Returns the current image in a memory buffer (pure virtual).
GetTargetRect | Retrieves the current target video rectangle (pure virtual).
GetVideoFormat | Retrieves the VIDEOINFOHEADER structure containing the video format.
IsDefaultSourceRect | Determines if the renderer is using the default source rectangle (pure virtual).
IsDefaultTargetRect | Determines if the renderer is using the default target rectangle (pure virtual).
OnUpdateRectangles | Called when the source or target rectangle changes.
OnVideoSizeChange | Passes EC_VIDEO_SIZE_CHANGED to the application.
SetDefaultSourceRect | Sets the default source video rectangle (pure virtual).
SetDefaultTargetRect | Sets the default target video rectangle (pure virtual).
SetSourceRect | Sets the current source video rectangle (pure virtual).
SetTargetRect | Sets the current target rectangle (pure virtual).

Implemented IBasicVideo Methods

get_AvgTimePerFrame | Retrieves an approximate average time per frame.
get_BitErrorRate | Retrieves an approximate bit error rate.
get_BitRate | Retrieves an approximate bit rate for the video.
GetCurrentImage | Retrieves a memory rendering of the current image.
get_DestinationHeight | Retrieves the current destination rectangle's height.
get_DestinationLeft | Retrieves the current destination rectangle's left coordinate.
GetDestinationPosition | Retrieves the current destination position.
get_DestinationTop | Retrieves the current destination rectangle's top coordinate.
get_DestinationWidth | Retrieves the current destination rectangle's width.
get_SourceHeight | Retrieves the current source rectangle's height.
get_SourceLeft | Retrieves the current source rectangle's left coordinate.
GetSourcePosition | Retrieves the current source position.
get_SourceTop | Retrieves the current source rectangle's top coordinate.
get_SourceWidth | Retrieves the current source rectangle's width.
get_VideoHeight | Retrieves the native video height.
GetVideoPaletteEntries | Retrieves a range of palette entries for the video.
GetVideoSize | Retrieves the width and height of the native video.
get_VideoWidth | Retrieves the native video width.
IsUsingDefaultDestination | Determines if the renderer is using the default destination window.
IsUsingDefaultSource | Determines if the renderer is using the default source window.
put_DestinationHeight | Sets the destination rectangle's height.
put_DestinationLeft | Sets the destination rectangle's left coordinate.
put_DestinationTop | Sets the destination rectangle's top coordinate.
put_DestinationWidth | Sets the destination rectangle's width.
put_SourceHeight | Sets the source rectangle's height.
put_SourceLeft | Sets the source rectangle's left coordinate.
put_SourceTop | Sets the source rectangle's top coordinate.
put_SourceWidth | Sets the source rectangle's width.
SetDefaultDestinationPosition | Sets the default destination position again.
SetDefaultSourcePosition | Sets the default source position again.
SetDestinationPosition | Sets the destination rectangle position.
SetSourcePosition | Sets the source rectangle position.


CBaseControlVideo::CBaseControlVideo

Constructor method.

Syntax

CBaseControlVideo(
    CBaseFilter *pFilter,
    CCritSec *pInterfaceLock,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
    );

Parameters

pFilter

Pointer to the owning media filter object.

pInterfaceLock

Pointer to the critical section to use for locking.

pName

Pointer to the object description.

pUnk

Pointer to the controlling IUnknown interface, if the object is part of an aggregate; otherwise, must be NULL.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the constructor method.

Return Value

No return value.

Remarks

The object implements the IBasicVideo control interface.

All the interface methods from IBasicVideo that this class implements require that the filter be connected correctly. For this reason, the class is passed a pin with which it should synchronize with. Whenever an interface method is called, the object determines that the pin is still connected.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::CheckSourceRect

Determines if a source rectangle is valid.

Syntax

virtual HRESULT CheckSourceRect(
    RECT *pSourceRect
);

Parameters

pSourceRect

Pointer to the source rectangle to check.

Return Value

Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

Remarks

This member function checks that the source rectangle requested does not exceed the available source video. The left and top coordinates cannot be negative, and the width and height cannot exceed the right and bottom of the video.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::CheckTargetRect

The CheckTargetRect method determines if a target rectangle is valid.

Syntax

virtual HRESULT CheckTargetRect(
    RECT *pTargetRect
);

Parameters

pTargetRect

Pointer to the target rectangle to check.

Return Value

Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

Remarks

This member function determines if the target rectangle requested is valid. Because the destination rectangle specifies a position in the logical client of the window, the coordinates can be negative, although the overall width and height cannot be zero or a negative value.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::CopyImage

Creates a memory copy of an image.

Syntax

HRESULT CopyImage(
    IMediaSample *pMediaSample,
    VIDEOINFOHEADER *pVideoInfo,
    LONG *pBufferSize,
    BYTE *pVideoImage,
    RECT *pSourceRect
);

Parameters

pMediaSample

Pointer to the sample containing the video image.

pVideoInfo

Pointer to the format representing the video image.

pBufferSize

Pointer to the size of the output buffer.

pVideoImage

Pointer to the output buffer.

pSourceRect

Pointer to the source video rectangle.

Return Value

If the pVideoImage parameter is NULL, the pBufferSize parameter is filled in with the number of bytes the output buffer requires to store the image. If the buffer passed in is too small or the member function fails to allocate sufficient memory, the member function returns E_OUTOFMEMORY.

Remarks

The member function retrieves the image from the sample and copies it into the output buffer. The section of video copied into the output buffer reflects the source rectangle that is set through the IBasicVideo interface (although it does not reflect the destination rectangle).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_AvgTimePerFrame

The get_AvgTimePerFrame method retrieves the average time per frame.

Syntax

HRESULT get_AvgTimePerFrame(
    REFTIME *pAvgTimePerFrame
);

Parameters

pAvgTimePerFrame

Pointer to the average time per frame.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_AvgTimePerFrame method. It calls the pure virtual CBaseControlVideo::GetVideoFormat member function to retrieve the VIDEOINFOHEADER structure from the derived class.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_BitErrorRate

The get_BitErrorRate method retrieves an approximate bit error rate for the video.

Syntax

HRESULT get_BitErrorRate(
    long *pBitErrorRate
);

Parameters

pBitErrorRate

Pointer to the bit error rate (one error for approximately this many bits).

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_BitErrorRate method. It calls the pure virtual CBaseControlVideo::GetVideoFormat method to retrieve the VIDEOINFOHEADER structure from the derived class.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_BitRate

The get_BitRate method retrieves an approximate bit rate for the video.

Syntax

HRESULT get_BitRate(
    long *pBitRate
);

Parameters

pBitRate

Pointer to the bit rate, in bits per second.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if not enough memory is available.

Remarks

This member function implements the IBasicVideo::get_BitRate method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetCurrentImage

The GetCurrentImage method retrieves a copy of the current image at the renderer.

Syntax

HRESULT GetCurrentImage(
    long *pBufferSize,
    long *pVideoImage
);

Parameters

pBufferSize

Pointer to the size of the output buffer.

pVideoImage

Pointer to the output buffer for the image.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Out of memory. Returned when the pVideoInfo parameter is NULL.
NOERROR | Success.
VFW_E_NOT_PAUSED | The operation could not be performed because the filter is not paused.

Remarks

This member function retrieves the image from the sample and copies it into the output buffer. The section of video copied into the output buffer reflects the source rectangle set through the IBasicVideo interface. It does not reflect the destination rectangle.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_DestinationHeight

The get_DestinationHeight method retrieves the current destination rectangle height.

Syntax

HRESULT get_DestinationHeight(
    long *pDestinationHeight
);

Parameters

pDestinationHeight

Pointer to the destination height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationHeight method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where it will be played. The destination rectangle is relative to the client area of the window that it is playing in. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_DestinationLeft

The get_DestinationLeft method retrieves the left coordinate of the current destination rectangle.

Syntax

HRESULT get_DestinationLeft(
    long *pDestinationLeft
);

Parameters

pDestinationLeft

Pointer to the left coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationLeft method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetDestinationPosition

The GetDestinationPosition method retrieves the destination rectangle in one atomic operation.

Syntax

HRESULT GetDestinationPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

Pointer to the left coordinate of the destination rectangle.

pTop

Pointer to the top coordinate of the destination rectangle.

pWidth

Pointer to the width of the destination rectangle.

pHeight

Pointer to the height of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function can be used in place of separate calls to the CBaseControlVideo::get_DestinationLeft, CBaseControlVideo::get_DestinationTop, CBaseControlVideo::get_DestinationWidth, and CBaseControlVideo::get_DestinationHeight member functions. An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_DestinationTop

The get_DestinationTop method retrieves the top coordinate of the current destination rectangle.

Syntax

HRESULT get_DestinationTop(
    long *pDestinationTop
);

Parameters

pDestinationTop

Pointer to the top coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationTop method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_DestinationWidth

The get_DestinationWidth method retrieves the width of the current destination rectangle.

Syntax

HRESULT get_DestinationWidth(
    long *pDestinationWidth
);

Parameters

pDestinationWidth

Pointer to the destination width.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationWidth method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetImageSize

The GetImageSize method retrieves video image size information.

Syntax

HRESULT GetImageSize(
    VIDEOINFOHEADER *pVideoInfo,
    long *pBufferSize,
    RECT *pSourceRect
);

Parameters

pVideoInfo

Pointer to a VIDEOINFOHEADER structure to be filled in.

pBufferSize

Pointer to the size of the video buffer.

pSourceRect

Pointer to the rectangle dimensions of the source video.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument. The data format is not compatible.
E_UNEXPECTED | Unexpected error occurred. One or more arguments are NULL.
NOERROR | Success.

Remarks

This member function is a helper function used for creating memory image renderings of DIB images. It is called from the base class implementation of CBaseControlVideo::GetCurrentImage when a null pVideoImage parameter is passed to that member function. As a result, this member function constructs and returns a VIDEOINFOHEADER structure, using the information in pBufferSize and pSourceRect.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_SourceHeight

The get_SourceHeight method retrieves the height of the current source rectangle.

Syntax

HRESULT get_SourceHeight(
    long *pSourceHeight
);

Parameters

pSourceHeight

Pointer to the height of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceHeight method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_SourceLeft

The get_SourceLeft method retrieves the left coordinate of the current source rectangle.

Syntax

HRESULT get_SourceLeft(
    long *pSourceLeft
);

Parameters

pSourceLeft

Pointer to the left coordinate of the current source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetSourcePosition

The GetSourcePosition method retrieves the position and dimensions of the source rectangle in one atomic operation.

Syntax

HRESULT GetSourcePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

Pointer to the left coordinate of the source rectangle.

pTop

Pointer to the top coordinate of the source rectangle.

pWidth

Pointer to the width of the source rectangle.

pHeight

Pointer to the height of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetSourceRect

The GetSourceRect method retrieves the source rectangle. This is an internal method.

Syntax

virtual HRESULT GetSourceRect(
    RECT *pSourceRect
) PURE;

Parameters

pSourceRect

Pointer to the retrieved source rectangle.

Return Value

Returns an HRESULT value.

Remarks

This member function must be overridden in the derived class to return the source rectangle held by the video renderer. It is called from the following CBaseControlVideo member functions.

  • CBaseControlVideo::GetSourcePosition
  • CBaseControlVideo::put_SourceLeft
  • CBaseControlVideo::get_SourceLeft
  • CBaseControlVideo::put_SourceWidth
  • CBaseControlVideo::get_SourceWidth
  • CBaseControlVideo::put_SourceTop
  • CBaseControlVideo::get_SourceTop
  • CBaseControlVideo::put_SourceHeight
  • CBaseControlVideo::get_SourceHeight

The following example demonstrates an implementation of this function in a derived class.

// Return the current source rectangle
HRESULT CVideoText::GetSourceRect(RECT *pSourceRect)
{
    ASSERT(pSourceRect);
    m_pRenderer->m_DrawImage.GetSourceRect(pSourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_SourceTop

The get_SourceTop method retrieves the top coordinate of the current source rectangle.

Syntax

HRESULT get_SourceTop(
    long *pSourceTop
);

Parameters

pSourceTop

Pointer to the top coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceTop method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_SourceWidth

The get_SourceWidth method retrieves the width of the current source rectangle.

Syntax

HRESULT get_SourceWidth(
    long *pSourceWidth
);

Parameters

pSourceWidth

Pointer to the width of the current source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceWidth method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetStaticImage

Pure virtual method that derived classes override.

Syntax

virtual HRESULT GetStaticImage(
    long *pBufferSize,
    long *pDIBImage
) PURE;

Parameters

pBufferSize

Pointer to the size of the output buffer.

pDIBImage

Pointer to the output buffer.

Return Value

Returns an HRESULT value.

Remarks

Through the IBasicVideo interface, an application can request that it be given a copy of the current image in a memory buffer (some renderers can return E_NOTIMPL to this if they do not support it). The derived class determines how to retrieve the image. When the application calls CBaseControlVideo::GetStaticImage, it calls this pure virtual method that the derived class should override to implement it. This is also called by the CBaseControlVideo::GetCurrentImage member function.

The class provides a helper member function, CBaseControlVideo::CopyImage, that can be given a sample that contains an image, and the member function will copy the relevant section of it (based on the current source rectangle) into the output buffer supplied by the application.

The following example demonstrates an implementation of this member function in a derived class. In this example, m_pRenderer holds an object of a class derived from CBaseVideoRenderer.

// Return a copy of the current image in the video renderer
HRESULT CVideoText::GetStaticImage(long *pBufferSize,long *pDIBImage)
{
    // Get any sample the renderer may be holding.

    IMediaSample *pMediaSample = m_pRenderer->GetCurrentSample();
    if (pMediaSample == NULL) {
        return E_UNEXPECTED;
    }

    // Call the base class helper method to do the work.

    HRESULT hr = CopyImage(pMediaSample,       // Buffer containing image
                      &m_pRenderer->m_mtIn,    // Type representing bitmap
                      pBufferSize,             // Size of buffer for DIB
                     (BYTE*) pDIBImage);       // Data buffer for output

    pMediaSample->Release();
    return hr;
}

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetTargetRect

The GetTargetRect method retrieves the destination rectangle. This is an internal helper member function.

Syntax

virtual HRESULT GetTargetRect(
    RECT *pTargetRect
) PURE;

Parameters

pTargetRect

Pointer to the destination rectangle.

Return Value

Returns an HRESULT value.

Remarks

This member function must be overridden in the derived class to return the target rectangle held by the video renderer. It is called from the following CBaseControlVideo member functions.

  • CBaseControlVideo::GetDestinationPosition
  • CBaseControlVideo::put_DestinationLeft
  • CBaseControlVideo::get_DestinationLeft
  • CBaseControlVideo::put_DestinationWidth
  • CBaseControlVideo::get_DestinationWidth
  • CBaseControlVideo::put_DestinationTop
  • CBaseControlVideo::get_DestinationTop
  • CBaseControlVideo::put_DestinationHeight
  • CBaseControlVideo::get_DestinationHeight

The following example demonstrates an implementation of this function in a derived class.

// Return the current destination rectangle.
HRESULT CVideoText::GetTargetRect(RECT *pTargetRect)
{
    ASSERT(pTargetRect);
    m_pRenderer->m_DrawImage.GetTargetRect(pTargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetVideoFormat

The GetVideoFormat method retrieves a video sample that represents the current video format.

Syntax

virtual VIDEOINFOHEADER * GetVideoFormat(void) PURE;

Return Value

Returns a pointer to a VIDEOINFOHEADER structure that contains the current video format.

Remarks

To return and check certain information through IBasicVideo, the object must know the current video format. It gets this information by calling this pure virtual method that derived classes must override. This member function is called by the following CBaseControlVideo member functions.

  • CBaseControlVideo::OnVideoSizeChange
  • CBaseControlVideo::get_AvgTimePerFrame
  • CBaseControlVideo::get_BitRate
  • CBaseControlVideo::get_BitErrorRate
  • CBaseControlVideo::get_VideoWidth
  • CBaseControlVideo::get_VideoHeight
  • CBaseControlVideo::GetVideoPaletteEntries
  • CBaseControlVideo::GetVideoSize

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_VideoHeight

The get_VideoHeight method retrieves the height of the native video.

Syntax

HRESULT get_VideoHeight(
    long *pVideoHeight
);

Parameters

pVideoHeight

Pointer to the height of the native video, in pixels.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_VideoHeight method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetVideoPaletteEntries

The GetVideoPaletteEntries method retrieves a range of palette entries for the video.

Syntax

HRESULT GetVideoPaletteEntries(
    long StartIndex,
    long Entries,
    long *pRetrieved,
    long *pPalette
);

Parameters

StartIndex

Zero-based start palette entry.

Entries

Number of entries required.

pRetrieved

Pointer to the number of colors obtained.

pPalette

Pointer to output buffer for colors.

Return Value

Returns NOERROR if successful, VFW_E_NO_PALETTE_AVAILABLE if the video samples has no color palette, E_OUTOFMEMORY if there is not enough memory available, E_INVALIDARG if StartIndex is invalid, or S_FALSE if there are no colors in the palette.

Remarks

This member function returns the current palette of the video as an array allocated by the user. To remain consistent, use the members in the Win32 PALETTEENTRY structure to return the colors, rather than the members in the RGBQUAD structure (although the parameter is a LONG). The memory is allocated by the caller, so simply copy each in turn. Determine that the number of entries requested and the start position offset are both valid. If the number of entries evaluates to zero, return an S_FALSE code.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::GetVideoSize

The GetVideoSize method retrieves the native video's width and height.

Syntax

HRESULT GetVideoSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth

Pointer to the video width.

pHeight

Pointer to the video height.

Return Value

Returns an HRESULT value.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::get_VideoWidth

The get_VideoWidth method retrieves the width of the native video.

Syntax

HRESULT get_VideoWidth(
    long *pVideoWidth
);

Parameters

pVideoWidth

Pointer to the width of the native video, in pixels.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_VideoWidth method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::IsDefaultSourceRect

The IsDefaultSourceRect method determines if the renderer is using the default source rectangle (pure virtual).

Syntax

virtual HRESULT IsDefaultSourceRect(void) PURE;

Return Value

Returns S_OK if the renderer is using the default source; otherwise, returns S_FALSE.

Remarks

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultSource member function.

The following example demonstrates an implementation of this function in a derived class.

// Return S_OK if using the default source; otherwise, S_FALSE.
HRESULT CVideoText::IsDefaultSourceRect()
{
    RECT SourceRect;

    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    m_pRenderer->m_DrawImage.GetSourceRect(&SourceRect);

    // Check the coordinates that match the video dimensions.

    if (SourceRect.left != 0 || SourceRect.top != 0 ||
            SourceRect.right != pHeader->biWidth ||
                SourceRect.bottom != pHeader->biHeight) {
                    return S_FALSE;
    }
    return S_OK;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with the media type of the input pin.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::IsDefaultTargetRect

The IsDefaultTargetRect method determines if the renderer is using the default target rectangle (pure virtual).

Syntax

virtual HRESULT IsDefaultTargetRect(void) PURE;

Return Value

Returns S_OK if the renderer is using the default target; otherwise, returns S_FALSE.

Remarks

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultDestination member function.

The following example demonstrates an implementation of this function in a derived class.

// Return S_OK if using the default target; otherwise, S_FALSE.
HRESULT CVideoText::IsDefaultTargetRect()
{
    RECT TargetRect;

    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    m_pRenderer->m_DrawImage.GetTargetRect(&TargetRect);

    // Check the destination that matches the initial client area.

    if (TargetRect.left != 0 || TargetRect.top != 0 ||
            TargetRect.right != m_Size.cx ||
                TargetRect.bottom != m_Size.cy) {
                    return S_FALSE;
    }
    return S_OK;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with media type of the input pin.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::IsUsingDefaultSource

The IsUsingDefaultSource method determines if the renderer is using the default source window.

Syntax

virtual HRESULT IsUsingDefaultSource(void);

Return Value

Returns S_OK if the renderer is using the default source; otherwise, returns S_FALSE.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::IsUsingDefaultDestination

The IsUsingDefaultDestination method determines if the renderer is using the default destination window.

Syntax

virtual HRESULT IsUsingDefaultDestination(void);

Return Value

Returns S_OK if using the default destination; otherwise, returns S_FALSE.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::OnUpdateRectangles

The OnUpdateRectangles method is called when either the source or destination rectangle changes.

Syntax

virtual HRESULT OnUpdateRectangles(void);

Return Value

Returns NOERROR.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::OnVideoSizeChange

Passes an EC_VIDEO_SIZE_CHANGED message to the filter graph manager.

Syntax

virtual HRESULT OnVideoSizeChange(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_OUTOFMEMORY | Out of memory.

Remarks

A video renderer should call this member function each time the video size is changed; this will typically be called once after initial connection. If the renderer can support dynamic format changes (from 320 x 240 to 160 x 120), it should also call it after each change.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_DestinationHeight

The put_DestinationHeight method sets the destination rectangle height.

Syntax

HRESULT put_DestinationHeight(
    long DestinationHeight
);

Parameters

DestinationHeight

New destination height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_DestinationLeft

The put_DestinationLeft method sets the left coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationLeft(
    long DestinationLeft
);

Parameters

DestinationLeft

New left coordinate of destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_DestinationTop

The put_DestinationTop method sets the top coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationTop(
    long DestinationTop
);

Parameters

DestinationTop

New top coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_DestinationWidth

The put_DestinationWidth method sets the width of the destination rectangle.

Syntax

HRESULT put_DestinationWidth(
    long DestinationWidth
);

Parameters

DestinationWidth

New destination width.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_SourceHeight

The put_SourceHeight method sets the source rectangle height.

Syntax

HRESULT put_SourceHeight(
    long SourceHeight
);

Parameters

SourceHeight

Source height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_SourceLeft

The put_SourceLeft method sets the source rectangle left coordinate.

Syntax

HRESULT put_SourceLeft(
    long SourceLeft
);

Parameters

SourceLeft

New left coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_SourceTop

The put_SourceTop method sets the top coordinate of the source rectangle.

Syntax

HRESULT put_SourceTop(
    long SourceTop
);

Parameters

SourceTop

New top coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::put_SourceWidth

The put_SourceWidth method sets the width of the source rectangle.

Syntax

HRESULT put_SourceWidth(
    long SourceWidth
);

Parameters

SourceWidth

New width of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetControlVideoPin

The SetControlVideoPin method sets the pin used by the filter.

Syntax

void SetControlVideoPin(
    CBasePin *pPin
);

Parameters

pPin

Pointer to the pin with which the interface is synchronized.

Return Value

No return value.

Remarks

The interface can be called only when the filter has been connected successfully. The object is passed through this method to the pin with which it is synchronized; in most cases it will determine if the pin is connected when it has an interface method called and will return VFW_E_NOT_CONNECTED if it fails.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetDefaultDestinationPosition

The SetDefaultDestinationPosition method sets the renderer back to using the default destination position (typically the entire window client area).

Syntax

HRESULT SetDefaultDestinationPosition(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetDefaultSourcePosition

The SetDefaultSourcePosition method sets the renderer back to using the default source position (typically all the native video).

Syntax

HRESULT SetDefaultSourcePosition(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetDefaultSourceRect

The SetDefaultSourceRect method sets the default source video rectangle (pure virtual). This in an internal member function that gets called when the source rectangle is reset.

Syntax

virtual HRESULT SetDefaultSourceRect(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to reset the source rectangle. It is called from CBaseControlVideo::SetDefaultSourcePosition.

The following example demonstrates an implementation of this function in a derived class.

// This is called when you reset the default source rectangle.
HRESULT CVideoText::SetDefaultSourceRect()
{
    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    RECT SourceRect = {0,0,pHeader->biWidth,pHeader->biHeight};
    m_pRenderer->m_DrawImage.SetSourceRect(&SourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with media type of the input pin.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetDefaultTargetRect

The SetDefaultTargetRect method sets the default target video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle is reset.

Syntax

virtual HRESULT SetDefaultTargetRect(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to reset the destination video rectangle. It is called from the CBaseControlVideo::SetDefaultDestinationPosition member function.

The following example demonstrates an implementation of this function in a derived class.

// This is called when you reset the default target rectangle.
HRESULT CVideoText::SetDefaultTargetRect()
{
    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    RECT TargetRect = {0,0,m_Size.cx,m_Size.cy};
    m_pRenderer->m_DrawImage.SetTargetRect(&TargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with the media type of the input pin.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetDestinationPosition

The SetDestinationPosition method sets the destination rectangle for the video.

Syntax

HRESULT SetDestinationPosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left

New left coordinate.

Top

New top coordinate.

Width

New width.

Height

New height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetSourcePosition

The SetSourcePosition method sets a new source position for the video.

Syntax

HRESULT SetSourcePosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left

New left coordinate.

Top

New top coordinate.

Width

New width.

Height

New height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetSourceRect

The SetSourceRect method sets the current source video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle changes.

Syntax

virtual HRESULT SetSourceRect(
    RECT *pSourceRect
) PURE;

Parameters

pSourceRect

Pointer to the source rectangle.

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this member function to know when the source rectangle changes. It is called from the following member functions.

  • CBaseControlVideo::SetSourcePosition
  • CBaseControlVideo::put_SourceLeft
  • CBaseControlVideo::put_SourceWidth
  • CBaseControlVideo::put_SourceTop
  • CBaseControlVideo::put_SourceHeight

The following example demonstrates an implementation of this function in a derived class.

HRESULT CVideoText::SetSourceRect(RECT *pSourceRect)
{
    m_pRenderer->m_DrawImage.SetSourceRect(pSourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

See Also

  • CBaseControlVideo Class


CBaseControlVideo::SetTargetRect

The SetTargetRect method sets the current target rectangle (pure virtual). This is an internal member function that gets called when the destination rectangle changes.

Syntax

virtual HRESULT SetTargetRect(
    RECT *pTargetRect
) PURE;

Parameters

pTargetRect

Pointer to the destination rectangle.

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to know when the destination rectangle changes. It is called from the following member functions.

  • CBaseControlVideo::SetDestinationPosition
  • CBaseControlVideo::put_DestinationLeft
  • CBaseControlVideo::put_DestinationWidth
  • CBaseControlVideo::put_DestinationTop
  • CBaseControlVideo::put_DestinationHeight

The following example demonstrates an implementation of this function in a derived class.

HRESULT CVideoText::SetTargetRect(RECT *pTargetRect)
{
    m_pRenderer->m_DrawImage.SetTargetRect(pTargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

See Also

  • CBaseControlVideo Class


CBaseControlWindow Class

CBaseControlWindow Class Hierarchy

The CBaseControlWindow class implements the IVideoWindow interface and controls external access to its associated filter. You must synchronize the CBaseControlWindow object with the filter by passing it a pointer to a critical section synchronization object. For more information about critical section synchronization objects, see the Platform SDK. The CBaseControlWindow class provides a number of methods that return property settings without dealing with this critical section. For example, calling CBaseControlWindow::get_AutoShow to retrieve the value of the m_bAutoShow data member locks the critical section. The filter might already have a locked internal critical section, however, which could violate the filter's lock hierarchy. Instead, calling the CBaseControlWindow::IsAutoShowEnabled member function returns the required value without affecting the critical section.

All CBaseControlWindow implemented IVideoWindow methods require that the filter be connected correctly with its upstream filter. For this reason, class objects require a synchronization pin, which you set by calling the CBaseControlWindow::SetControlWindowPin method. Whenever you call an IVideoWindow method, the CBaseControlWindow object checks that the pin is still connected.

Protected Data Members

m_bAutoShow | Result when the state changes.
m_bCursorHidden | Determination of whether the cursor is displayed or hidden.
m_BorderColour | Color of the current window border.
m_hwndDrain | Window handle to which messages received are posted.
m_hwndOwner | Owning window.
m_pFilter | Pointer to the owning media filter.
m_pInterfaceLock | Externally defined critical section.
m_pPin | Control of the media types for connection.

Member Functions

CBaseControlWindow | Constructs a CBaseControlWindow object.
DoGetWindowStyle | Retrieves either the typical or extended window styles.
DoSetWindowStyle | Sets the typical or extended window styles.
GetBorderColour | Retrieves the current border color. This is a helper member function.
GetOwnerWindow | Retrieves the owning window. This is a helper member function.
IsAutoShowEnabled | Retrieves information about whether the video window automatically appears when the rendering filter pauses or runs.
IsCursorHidden | Retrieves the current state of the m_bCursorHidden data member without locking the critical section. This is a helper member function.
PossiblyEatMessage | Distributes messages to the parent window.
SetControlWindowPin | Notifies the object of the pin to which it applies.

Implemented IVideoWindow Methods

get_AutoShow | Retrieves the current AutoShow flag setting.
get_BackgroundPalette | Retrieves the realized palette in the background flag.
get_BorderColor | Retrieves the current border color.
get_Caption | Retrieves the current window caption.
get_FullScreenMode | Retrieves the current full-screen mode.
get_Height | Retrieves the current window height.
get_Left | Retrieves the current left window coordinate.
GetMaxIdealImageSize | Retrieves the maximum size of the ideal image.
get_MessageDrain | Retrieves the current message drain.
GetMinIdealImageSize | Retrieves the minimum size of the ideal image.
get_Owner | Retrieves the Microsoft® Win32® parent window handle.
GetRestorePosition | Retrieves the position to which the window will be restored when maximized or minimized.
get_Top | Retrieves the y-coordinate for the top of the window.
get_Visible | Retrieves the current visibility setting of the window.
get_Width | Retrieves the width of the window.
GetWindowPosition | Retrieves the current window coordinates.
get_WindowState | Retrieves the current state of the window.
get_WindowStyle | Retrieves the standard window styles.
get_WindowStyleEx | Retrieves the extended window styles.
HideCursor | Hides or displays the cursor.
IsCursorHidden | Retrieves the current state of the m_bCursorHidden data member.
NotifyOwnerMessage | Passes on messages that are sent to owning windows.
put_AutoShow | Sets the AutoShow property.
put_BackgroundPalette | Sets a flag to realize the palette in the background.
put_BorderColor | Sets the current border color.
put_Caption | Sets the current window caption.
put_FullScreenMode | Sets the full-screen mode.
put_Height | Sets the current window height.
put_Left | Sets the left coordinate for the window.
put_MessageDrain | Sets the message drain window.
put_Owner | Sets the Microsoft Win32 parent window handle.
put_Top | Sets the position for the top of the window.
put_Visible | Hides or shows the window.
put_Width | Sets the width of the window.
put_WindowState | Sets the state of the window.
put_WindowStyle | Sets the standard window styles.
put_WindowStyleEx | Sets the extended window styles.
SetWindowForeground | Sets the window in the foreground.
SetWindowPosition | Sets the window position.


CBaseControlWindow::CBaseControlWindow

Constructor method.

Syntax

CBaseControlWindow(
    CBaseMediaFilter *pFilter,
    CCritSec *pInterfaceLock,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pFilter

Pointer to the owning media filter object.

pInterfaceLock

Pointer to the critical section to use for locking.

pName

Pointer to the object description.

pUnk

Pointer to the controlling IUnknown interface, if the object is part of an aggregate; otherwise, must be NULL.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the constructor method.

Return Value

No return value.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::DoGetWindowStyle

The DoGetWindowStyle method retrieves the current normal or extended window styles.

Syntax

HRESULT DoGetWindowStyle(
    long *pStyle,
    long WindowLong
);

Parameters

pStyle

Pointer to a variable that receives the style information.

WindowLong

Value specifying which styles to retrieve. Must be one of the following:

GWL_STYLE | Retrieve the window styles.
GWL_EXSTYLE | Retrieve the extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function calls the Win32 GetWindowLong function to retrieve the window style. It is called by the CBaseControlWindow::get_WindowStyle and CBaseControlWindow::get_WindowStyleEx member functions.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::DoSetWindowStyle

The DoSetWindowStyle method changes the typical or extended window styles.

Syntax

HRESULT DoSetWindowStyle(
    long Style,
    long WindowLong
);

Parameters

Style

Appropriate window styles.

WindowLong

Value specifying which styles to set. Must be one of the following:

GWL_STYLE | Retrieve the window styles.
GWL_EXSTYLE | Retrieve the extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function calls the Win32 SetWindowLong function to set the window style, and then redisplays the window in the current position. This member function is called by the CBaseControlWindow::put_WindowStyle and CBaseControlWindow::put_WindowStyleEx member functions.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_AutoShow

The get_AutoShow method retrieves the current AutoShow state flag.

Syntax

HRESULT get_AutoShow(
    long *AutoShow
);

Parameters

AutoShow

Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IVideoWindow::get_AutoShow method. This property simplifies window display access for applications. If this is set to –1 (on), the window, which is typically hidden after connection of the filter, will be displayed automatically when the filter pauses or runs. The window should not be hidden when the filter stops, however. If this parameter is set to 0 (off), the window is made visible only when the application calls CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState with the appropriate parameters.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::IsAutoShowEnabled member function to retrieve this property if you are not calling from an external object.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_BackgroundPalette

The get_BackgroundPalette method retrieves the realized palette in the background flag.

Syntax

HRESULT get_BackgroundPalette(
    long *pBackgroundPalette
);

Parameters

pBackgroundPalette

Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IVideoWindow::get_BackgroundPalette method. If a video will be played within another application or document, the application might want to use its own palette. It can ask that the video use the current foreground palette rather than its own by setting this flag to –1. If this is set to 0, the window will install and realize its own preferred palette. Note that asking the window to use a different palette will cause severe performance penalties.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_BorderColor

The get_BorderColor method retrieves the current border color.

Syntax

HRESULT get_BorderColor(
    long *Color
);

Parameters

Color

Pointer to the current border color.

Return Value

Returns an HRESULT value.

Remarks

An application can set a destination rectangle in which the video should be displayed. This rectangle is relative to the client area for the window. If this is done (the default is to always paint the entire window), there is a border surrounding the video. This property affects the color used by the border. Although the parameter is specified as a LONG type, it is actually a COLORREF value.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::GetBorderColour member function to retrieve this property if not calling from an external object.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetBorderColour

The GetBorderColour method retrieves the current window border color, m_BorderColour.

Syntax

COLORREF GetBorderColour(void);

Return Value

Returns the color of the border.

Remarks

An application can set a destination rectangle to display the video. This rectangle should be relative to the client area for the window. If this is done (the default is to always paint the entire window), there is an area that surrounds the video; that is, the border. The border color can be set through the CBaseControlWindow::put_BorderColor member function. This property affects the color of the border. Use this member function instead of CBaseControlWindow::get_BorderColor, unless you are calling this externally through the IVideoWindow::get_BorderColor method.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Caption

The get_Caption method retrieves the current window caption.

Syntax

HRESULT get_Caption(
    BSTR *pstrCaption
);

Parameters

pstrCaption

Pointer to the current window caption.

Return Value

Returns an HRESULT value.

Remarks

Most top-level windows on a Windows-based desktop have a title (caption) associated with them. This property can be queried and set through the IVideoWindow interface. Any caption set will be visible only if the window has the WS_CAPTION style applied. If it does not, the caption can still be set (and retrieved), although it will not be visible to the user.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_FullScreenMode

The get_FullScreenMode method retrieves the current full-screen mode.

Syntax

HRESULT get_FullScreenMode(
    long *FullScreenMode
);

Parameters

FullScreenMode

Pointer to the current full-screen mode.

Return Value

Returns an HRESULT value.

Remarks

This member function returns E_NOTIMPL by default. This informs the IVideoWindow plug-in distributor that this renderer does not implement a full-screen renderer.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Height

The get_Height method retrieves the current window height.

Syntax

HRESULT get_Height(
    long *pHeight
);

Parameters

pHeight

Pointer to the current window height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in Microsoft® DirectShow®. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Left

The get_Left method retrieves the current left window coordinate.

Syntax

HRESULT get_Left(
    long *pLeft
);

Parameters

pLeft

Pointer to the left coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This position is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left and up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height have no effect on the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetMaxIdealImageSize

The GetMaxIdealImageSize method retrieves the maximum ideal image size.

Syntax

HRESULT GetMaxIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth

Pointer to the maximum ideal width, in pixels.

pHeight

Pointer to the maximum ideal height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Various renderers have performance restrictions on the size of images they can display. Although they should still function properly when requested to display images larger than the specified maximum, renderers can nominate the minimum and maximum ideal sizes through the IVideoWindow interface. This interface can be called only when the filter graph is paused or running, because it is not until then that resources are allocated and the renderer can recognize its restrictions. If no restrictions exist, the renderer fills in the pWidth and pHeight parameters with the native video dimensions and returns S_FALSE. If restrictions do exist, the restricted width and height are entered, and the member function returns S_OK.

The dimensions apply to the size of the destination video and not to the overall window size. So, when calculating the size of the window to set, account for the current window styles (for example, WS_CAPTION and WS_BORDER).

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_MessageDrain

The get_MessageDrain method retrieves the current message drain.

Syntax

HRESULT get_MessageDrain(
    OAHWND *Drain
);

Parameters

Drain

Pointer to the current window receiving window messages.

Return Value

Returns an HRESULT value.

Remarks

Messages sent to the video renderer filter can be posted to another window. The window registered to receive these messages (using the CBaseControlWindow::get_MessageDrain member function) is the current message drain.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetMinIdealImageSize

The GetMinIdealImageSize method retrieves the minimum ideal image size.

Syntax

HRESULT GetMinIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth

Pointer to the minimum ideal width, in pixels.

pHeight

Pointer to the minimum ideal height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Various renderers have performance restrictions on the size of images they can display. Although they should still function properly when requested to display images larger than the specified maximum, renderers can nominate the minimum and maximum ideal sizes through the IVideoWindow interface. This interface can be called only when the filter graph is paused or running, because it is not until then that resources are allocated and the renderer can recognize its restrictions. If no restrictions exist, the renderer fills in the pWidth and pHeight parameters with the native video dimensions and returns S_FALSE. If restrictions do exist, the restricted width and height are entered, and the member function returns S_OK.

The dimensions apply to the size of the destination video and not to the overall window size. So, when calculating the size of the window to set, account for the current window styles (for example, WS_CAPTION and WS_BORDER).

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Owner

The get_Owner method retrieves the current window owner.

Syntax

HRESULT get_Owner(
    OAHWND *Owner
);

Parameters

Owner

Pointer to the window owner.

Return Value

Returns an HRESULT value.

Remarks

The video window can play back within a document environment. To do this, the window must be made a child of another window (so that it is clipped and moved appropriately). This property allows the owner of the window to be set and retrieved. When the window is owned by another window, it simply calls the Microsoft Win32 SetParent function. An application calling this function will change the window styles to set the WS_CHILD bit on.

When the window is owned by another window, it will automatically forward certain sets of messages (in particular, mouse and keyboard messages). This allows an application to do simple hot-spot editing and other interactions.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::GetOwnerWindow member function to retrieve this property if not calling from an external object.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetOwnerWindow

The GetOwnerWindow method retrieves the owning window handle, m_hwndOwner.

Syntax

HWND GetOwnerWindow(void);

Return Value

Returns an internal method to return the owner window.

Remarks

Retrieves the owning window without calling the interface method. Use this member function instead of CBaseControlWindow::get_Owner, unless you are calling this externally through the IVideoWindow::get_Owner method.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetRestorePosition

The GetRestorePosition method retrieves the position to which the window will be restored when it is not maximized or minimized.

Syntax

HRESULT GetRestorePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

Pointer to the value for leftmost coordinate.

pTop

Pointer to the value for top of the window.

pWidth

Pointer to the value for width of the window.

pHeight

Pointer to the value for height of window.

Return Value

Returns an HRESULT value.

Remarks

This is the same as the values returned by the CBaseControlWindow::GetWindowPosition function when the window is neither maximized nor minimized.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Top

The get_Top method retrieves the top window coordinate.

Syntax

HRESULT get_Top(
    long *pTop
);

Parameters

pTop

Pointer to the top coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Visible

The get_Visible method retrieves the current window visibility.

Syntax

HRESULT get_Visible(
    long *pVisible
);

Parameters

pVisible

Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function returns –1 if the window has the WS_VISIBLE style; 0 otherwise.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_Width

The get_Width method retrieves the current window width.

Syntax

HRESULT get_Width(
    long *pWidth
);

Parameters

pWidth

Pointer to the window width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::GetWindowPosition

The GetWindowPosition method retrieves the current coordinates for the window.

Syntax

HRESULT GetWindowPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft

Pointer to the left coordinate, in screen coordinates.

pTop

Pointer to the top coordinate, in screen coordinates.

pWidth

Pointer to the window width, in screen coordinates.

pHeight

Pointer to the window height, in screen coordinates.

Return Value

Returns an HRESULT value.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_WindowState

The get_WindowState method retrieves the current window state.

Syntax

HRESULT get_WindowState(
    long *pWindowState
);

Parameters

pWindowState

Pointer to the window state.

Return Value

Returns an HRESULT value.

Remarks

This member function returns a subset of the parameters of the Microsoft Win32 ShowWindow function. In particular, it returns SW_SHOW and SW_HIDE, depending on the current visibility of the window. It also returns SW_MINIMIZE and SW_MAXIMIZE, depending on whether the window is an icon or is expanded.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_WindowStyle

The get_WindowStyle method retrieves the standard window styles.

Syntax

HRESULT get_WindowStyle(
    long *pWindowStyle
);

Parameters

pWindowStyle

Pointer to window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function returns the standard window styles, such as WS_CHILD and WS_VISIBLE. It calls the CBaseControlWindow::DoGetWindowStyle member function.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::get_WindowStyleEx

The get_WindowStyleEx method retrieves the extended window styles.

Syntax

HRESULT get_WindowStyleEx(
    long *pWindowStyleEx
);

Parameters

pWindowStyleEx

Pointer to extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function retrieves the extended window styles. It calls the CBaseControlWindow::DoGetWindowStyle member function.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::HideCursor

The HideCursor method hides or displays the cursor.

Syntax

HRESULT HideCursor(
    long HideCursor
);

Parameters

HideCursor

Value specifying whether to show the cursor. Set to OATRUE to hide the cursor, or OAFALSE to display the cursor.

Return Value

Returns an HRESULT value.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::IsCursorHidden

The IsCursorHidden method retrieves the current state of the m_bCursorHidden data member.

Syntax

HRESULT IsCursorHidden(
    long *CursorHidden
);

Parameters

CursorHidden

Pointer to the value of m_bCursorHidden.

Return Value

When called without a parameter, returns OATRUE if the cursor is hidden, or OAFALSE if the cursor is visible.

When called with a parameter, returns an HRESULT value.

Remarks

Internal objects should call this member function without the CursorHidden parameter to avoid locking the critical section. External objects access this member function with the CursorHidden parameter through the IVideoWindow::IsCursorHidden method.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::IsAutoShowEnabled

The IsAutoShowEnabled method retrieves information about whether the video window automatically appears when the rendering filter pauses or runs.

Syntax

BOOL IsAutoShowEnabled(void);

Return Value

Returns TRUE if the m_bAutoShow member is set to –1 or FALSE if it is set to 0.

Remarks

If the m_bAutoShow member is set to –1 on a video window that is hidden, the window becomes visible when the filter pauses or runs. If this member is set to 0, the window will appear only if you use the CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState member function with the appropriate parameters.

This member function retrieves the m_bAutoShow member setting and has the same result as using the IVideoWindow::get_AutoShow method.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::NotifyOwnerMessage

The NotifyOwnerMessage method passes along specific messages to the video window.

Syntax

HRESULT NotifyOwnerMessage(
    long hwnd,
    long uMsg,
    long wParam,
    long lParam
);

Parameters

hwnd

Handle to the video window.

uMsg

Message details.

wParam

First message parameter.

lParam

Second message parameter.

Return Value

Returns NO_ERROR.

Remarks

When the video window is a child of another window, it does not receive certain top-level window messages. These messages can be valuable to a renderer, because they could affect its behavior. NotifyOwnerMessage passes any of the following messages to the video window.

  • WM_ACTIVATEAPP
  • WM_DEVMODECHANGE
  • WM_DISPLAYCHANGE
  • WM_PALETTECHANGED
  • WM_PALETTEISCHANGING
  • WM_QUERYNEWPALETTE
  • WM_SYSCOLORCHANGE

You can request that the IVideoWindow plug-in distributor (PID) make a window become a child of another window. When this occurs, the PID will look for certain messages that might be sent to the owning window. The PID will then forward those messages to the owned window. The default processing for the messages is to send them to the owned window procedure synchronously by calling the Win32 SendMessage function.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::PossiblyEatMessage

The PossiblyEatMessage method forwards keyboard and mouse messages to the message-drain window.

Syntax

BOOL WINAPI PossiblyEatMessage(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
)

Parameters

uMsg

Window message.

wParam

First message parameter.

lParam

Second message parameter.

Return Value

Returns TRUE if the message was forwarded to the window, or FALSE otherwise.

Remarks

The message-drain window is a window designated to receive certain mouse and keyboard messages. Initially the window is NULL; it can be set by calling CBaseControlWindow::put_MessageDrain.

If the message-drain window is non-NULL, PossiblyEatMessage posts the following messages to that window:

  • WM_CHAR
  • WM_DEADCHAR
  • WM_KEYDOWN
  • WM_KEYUP
  • WM_LBUTTONDBLCLK
  • WM_LBUTTONDOWN
  • WM_LBUTTONUP
  • WM_MBUTTONDBLCLK
  • WM_MBUTTONDOWN
  • WM_MBUTTONUP
  • WM_MOUSEACTIVATE
  • WM_MOUSEMOVE
  • WM_NCLBUTTONDBLCLK
  • WM_NCLBUTTONDOWN
  • WM_NCLBUTTONUP
  • WM_NCMBUTTONDBLCLK
  • WM_NCMBUTTONDOWN
  • WM_NCMBUTTONUP
  • WM_NCMOUSEMOVE
  • WM_NCRBUTTONDBLCLK
  • WM_NCRBUTTONDOWN
  • WM_NCRBUTTONUP
  • WM_RBUTTONDBLCLK
  • WM_RBUTTONDOWN
  • WM_RBUTTONUP
  • WM_SYSCHAR
  • WM_SYSDEADCHAR
  • WM_SYSKEYDOWN
  • WM_SYSKEYUP

It ignores other messages. If the message-drain window is NULL, the method ignores all window messages. The method returns TRUE if it posts the message, or FALSE otherwise. The CBaseWindow class calls this method when it receives a window message.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_AutoShow

The put_AutoShow method sets the AutoShow state flag.

Syntax

HRESULT put_AutoShow(
    long AutoShow
);

Parameters

AutoShow

Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This property simplifies window display access for applications. If this is set to –1 (on), the window, which is typically hidden after the filter is connected, will be displayed automatically when the filter pauses or runs. The window should not be hidden when the filter stops, however. If this is set to 0 (off), the window is made visible only when the application calls CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState with the appropriate parameters.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_BackgroundPalette

The put_BackgroundPalette method sets a flag to realize the palette in the background.

Syntax

HRESULT put_BackgroundPalette(
    long BackgroundPalette
);

Parameters

BackgroundPalette

Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

To play a video within another application or document, the application might want to use its own palette. It can ask that the video use the current foreground palette rather than its own as the background palette by setting this flag to –1. If this is set to 0, the window will install and realize its own preferred palette. Asking the window to use a different palette will cause severe performance penalties.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_BorderColor

The put_BorderColor method changes the border color.

Syntax

HRESULT put_BorderColor(
    long Color
);

Parameters

Color

New border color.

Return Value

Returns an HRESULT value.

Remarks

An application can establish a destination rectangle in which the video should be displayed. This rectangle is relative to the client area for the window. If this is done (the default is to always paint the entire window), there is a border surrounding the video. This property affects the color used by the border. Although the parameter is specified as a LONG type, it is actually a COLORREF value.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Caption

The put_Caption method sets the window title or caption.

Syntax

HRESULT put_Caption(
    BSTR strCaption
);

Parameters

strCaption

New window caption.

Return Value

Returns an HRESULT value.

Remarks

Most top-level windows on a Windows-based desktop have a title (caption) associated with them. This property can be queried and set through the IVideoWindow interface. Any caption set will be visible only if the window has the WS_CAPTION style applied. If it does not, the caption can still be set (and retrieved), although it will not be visible to the user.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_FullScreenMode

The put_FullScreenMode method sets the full-screen mode of the renderer.

Syntax

HRESULT put_FullScreenMode(
    long FullScreenMode
);

Parameters

FullScreenMode

Full-screen mode to apply.

Return Value

Returns an HRESULT value. The current implementation returns E_NOTIMPL.

Remarks

A video renderer that implements a full-screen mode should override this member function and implement whatever modes it supports.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Height

The put_Height method sets the window height.

Syntax

HRESULT put_Height(
    long Height
);

Parameters

Height

New window height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Left

The put_Left method sets the left coordinate for the window.

Syntax

HRESULT put_Left(
    long Left
);

Parameters

Left

New left coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_MessageDrain

The put_MessageDrain method sets the window to receive window messages sent to the video renderer.

Syntax

HRESULT put_MessageDrain(
    OAHWND Drain
);

Parameters

Drain

Window to post messages to.

Return Value

Returns an HRESULT value.

Remarks

Messages sent to the video renderer filter can be posted to another window. This member function registers the window to receive these messages. Unlike the CBaseControlWindow::put_Owner member function, this member function does not make the video window a child of another window. It is particularly useful for full-screen video renderers, which cannot be child windows.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Owner

The put_Owner method sets the video window's parent window; the parent window then forwards certain messages to the video window.

Syntax

HRESULT put_Owner(
    OAHWND Owner
);

Parameters

Owner

Handle to the parent window.

Return Value

Returns NOERROR.

Remarks

Internally, this method calls the Microsoft Win32 SetParent function to set the new owner and sets the parent window's style to WS_CHILD. The parent window will then forward certain sets of messages (in particular, mouse and keyboard messages) to the video window.

After you set the video window's owner, you must set the owner to NULL and the owner's window style to WS_OVERLAPPED and WS_CLIPCHILDREN before releasing the filter graph. When you set the owner to NULL, this method turns off the parent window's WS_CHILD bit. If you don't set the owner to NULL, the parent window will continue to pass messages to the video window and errors will likely occur when the application closes.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Top

The put_Top method sets the top window coordinate.

Syntax

HRESULT put_Top(
    long Top
);

Parameters

Top

New top coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Visible

The put_Visible method makes shows or hides the window.

Syntax

HRESULT put_Visible(
    long Visible
);

Parameters

Visible

Automation Boolean flag (0 means window is hidden, –1 means window is shown).

Return Value

Returns an HRESULT value.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_Width

The put_Width method sets the window width.

Syntax

HRESULT put_Width(
    long Width
);

Parameters

Width

New window width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_WindowState

The put_WindowState method sets the window state.

Syntax

HRESULT put_WindowState(
    long WindowState
);

Parameters

WindowState

New window state.

Return Value

Returns an HRESULT value.

Remarks

This member function takes the same parameters as the Microsoft Win32 ShowWindow function (for example, WS_SHOWNORMAL, WS_SHOWMINNOACTIVATE, and WS_SHOWMAXIMIZED).

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_WindowStyle

The put_WindowStyle method sets the standard window styles.

Syntax

HRESULT put_WindowStyle(
    long WindowStyle
);

Parameters

WindowStyle

New window styles.

Return Value

Returns an HRESULT value.

Remarks

Take care when changing the window styles. In most cases, an application should retrieve the current style and then add or remove the inappropriate bits. This procedure allows various internal window styles used by Windows® to remain intact.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::put_WindowStyleEx

The put_WindowStyleEx method sets the extended window styles.

Syntax

HRESULT put_WindowStyleEx(
    long WindowStyleEx
);

Parameters

WindowStyleEx

[in] Value that specifies the style of the control window.

Return Value

Returns NOERROR.

Remarks

This method uses extended window styles. For a complete list of extended window styles, see the Microsoft Win32 CreateWindowEx function. To change the window style, retrieve the current window style, and then add or remove the necessary bit fields.

Do not use the following window styles because they are not validated.

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

With some exceptions (noted here), the acceptable flags are the same as those allowed by the Win32 CreateWindow function.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::SetControlWindowPin

The SetControlWindowPin method sets the pin with which to synchronize.

Syntax

void SetControlWindowPin(
    CBasePin *pPin
);

Parameters

pPin

Pointer to the pin with which the interface is synchronized.

Return Value

No return value.

Remarks

This member function sets the m_pPin member variable equal to the pPin parameter. As described in the constructor, the interface can be called only when the filter has been connected successfully. The object is passed in through this member function to the pin with which it should synchronize; in most cases, it will determine if the pin is connected whenever it has an interface method called and will return VFW_E_NOT_CONNECTED if it fails.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::SetWindowForeground

The SetWindowForeground method moves the video window to the foreground and optionally gives it focus.

Syntax

HRESULT SetWindowForeground(
    long Focus
);

Parameters

Focus

Value that specifies whether the video window will get focus. A value of –1 gives the window focus and 0 does not.

Return Value

Returns one of the following values.

Value | Description
NOERROR | The method succeeded.
E_INVALIDARG | Focus doesn't equal –1 or 0.
VFW_E_NOT_CONNECTED | The current filter isn't connected to a complete filter graph.

See Also

  • CBaseControlWindow Class


CBaseControlWindow::SetWindowPosition

The SetWindowPosition method sets the window position on the desktop.

Syntax

HRESULT SetWindowPosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left

New left coordinate.

Top

New top coordinate.

Width

Width of the window.

Height

Height of the window.

Return Value

Returns an HRESULT value.

See Also

  • CBaseControlWindow Class


CBaseDispatch Class

CBaseDispatch Class Hierarchy

The CBaseDispatch class is a base class for implementing the IDispatch interface.

This class is limited to supporting the Automation-compatible interfaces exported by the DirectShow type library, QuartzTypeLib. For example, the CMediaControl and CMediaPosition classes use CBaseDispatch to implement IMediaControl and IMediaPosition, respectively. Because of this limitation, there is probably no reason to use CBaseDispatch directly in your own filters.

To use this class, do the following:

  • Declare a new class that supports IDispatch.
  • Give your new class a private member variable of type CBaseDispatch.
  • Implement the IDispatch methods. In your IDispatch methods, call the CBaseDispatch methods.

For more details, refer to the source code for any of the sample classes declared in Ctlutil.h.

For more information about the IDispatch methods, see the COM documentation included with the Microsoft® Platform SDK.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CBaseDispatch | Constructor method.
~CBaseDispatch | Destructor method.
GetIDsOfNames | Maps a set of names to a corresponding set of DISPIDs.
GetTypeInfo | Retrieves the type information for the object, which can then be used to get the type information for an interface.
GetTypeInfoCount | Retrieves the number of type information interfaces the object provides.


CBaseDispatch::CBaseDispatch

Constructor method.

Syntax

CBaseDispatch(void);

See Also

  • CBaseDispatch Class


CBaseDispatch::~CBaseDispatch

Destructor method.

Syntax

~CBaseDispatch(void);

See Also

  • CBaseDispatch Class


CBaseDispatch::GetIDsOfNames

The GetIDsOfNames method maps a set of names to a corresponding set of DISPIDs.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid

Reference to an interface identifier (IID) that specifies the interface.

rgszNames

Address of an array of wide-character strings that contain the names to be mapped.

cNames

Size of the array given by the rgszNames parameter.

lcid

Locale context in which to interpret the names. Can be NULL.

rgdispid

Pointer to an array that receives the DISPIDs. Each element of receives an identifier that corresponds to one of the names passed in the rgszNames parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
DISP_E_UNKNOWNNAME | One or more of the names were not known.

Remarks

This method behaves like the IDispatch::GetIDsOfNames method, but the riid parameter specifies the interface on which to retrieve DISPIDs. (In the IDispatch version, the riid parameter is reserved.)

If the method returns DISP_E_UNKNOWNNAME, the returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.

See Also

  • CBaseDispatch Class


CBaseDispatch::GetTypeInfo

The GetTypeInfo method retrieves the type information for the object, which can then be used to get the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    REFIID riid,
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

riid

Reference to an interface identifier (IID) that specifies the interface.

itinfo

Type information to return. Must be zero.

lcid

Locale identifier.

pptinfo

Address of a variable that receives an ITypeInfo pointer.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
TYPE_E_ELEMENTNOTFOUND | The itinfo parameter is not zero.

Remarks

This method behaves like the IDispatch::GetTypeInfo method. However, it includes an additional parameter, riid, which specifies the interface for which to retrieve type information.

See Also

  • CBaseDispatch Class


CBaseDispatch::GetTypeInfoCount

The GetTypeInfoCount method retrieves the number of type information interfaces the object provides.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo

Pointer to a variable that receives the number of type-information interfaces provided by the object. When the method returns, the value is 1.

Return Value

Returns one of the following values.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.

See Also

  • CBaseDispatch Class


CBaseFilter Class

CBaseFilter Class Hierarchy

The CBaseFilter class is an abstract class for implementing filters. To implement a filter using this class, you must perform at least the following steps:

  • Derive a new class from CBaseFilter.
  • Include member variables that define the pins on the filter. The pins must inherit from the CBasePin class.
  • Override the pure virtual method CBaseFilter::GetPin, which retrieves pins on the filter.
  • Override the pure virtual method CBaseFilter::GetPinCount, which retrieves the number of pins.
  • Provide methods for generating, processing, or rendering media samples.

Several base classes derive from CBaseFilter, including CSource, CBaseRenderer, and CTransformFilter. It is usually easier to implement a filter with one of these specialized classes, rather than use CBaseFilter directly.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_State | Current state of the filter.
m_pClock | Pointer to the filter's reference clock.
m_tStart | Reference time that corresponds to stream time 0.
m_clsid | Class identifier (CLSID) of the filter.
m_pLock | Pointer to a critical section that is used to serialize state changes.
m_pName | Filter name.
m_pGraph | Pointer to the filter graph manager.
m_pSink | Pointer to the IMediaEventSink interface on the filter graph manager.
m_PinVersion | Current version of the set of pins on this filter.
Public Methods |
CBaseFilter | Constructor method.
~CBaseFilter | Destructor method.
StreamTime | Retrieves the current stream time. Virtual.
IsActive | Determines whether the filter is currently active (running or paused).
IsStopped | Determines whether the filter is currently stopped.
NotifyEvent | Sends an event notification to the filter graph manager.
GetFilterGraph | Retrieves a pointer to the filter graph manager.
ReconnectPin | Breaks an existing pin connection and reconnects it to the same pin, using a specified media type.
GetPinVersion | Retrieves a version number for the set of pins on this filter. Virtual.
IncrementPinVersion | Increments the version number on the set of pins.
GetSetupData | Retrieves the registration data for the filter. Virtual.
Pure Virtual Methods |
GetPinCount | Retrieves the number of pins.
GetPin | Retrieves a pin.
IPersist Methods |
GetClassID | Retrieves the class identifier.
IMediaFilter Methods |
GetState | Retrieves the filter's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the filter.
GetSyncSource | Retrieves the reference clock that the filter is using.
Stop | Stops the filter.
Pause | Pauses the filter.
Run | Runs the filter.
IBaseFilter Methods |
EnumPins | Enumerates the pins on this filter.
FindPin | Retrieves the pin with the specified identifier.
QueryFilterInfo | Retrieves information about the filter.
JoinFilterGraph | Notifies the filter that it has joined or left a filter graph.
QueryVendorInfo | Retrieves a string containing vendor information.
IAMovieSetup Merthods |
Register | Adds the filter to the registry.
Unregister | Removes the filter from the registry.


CBaseFilter::m_State

Indicates the current state of the filter.

Syntax

FILTER_STATE m_State;

See Also

  • CBaseFilter Class


CBaseFilter::m_pClock

Pointer to the filter's reference clock.

Syntax

IReferenceClock *m_pClock;

See Also

  • CBaseFilter Class


CBaseFilter::m_tStart

Reference time that corresponds to stream time 0.

Syntax

CRefTime m_tStart;

See Also

  • CBaseFilter Class


CBaseFilter::m_clsid

Class identifier (CLSID) of the filter.

Syntax

CLSID m_clsid;

See Also

  • CBaseFilter Class


CBaseFilter::m_pLock

Pointer to a critical section that is used to serialize state changes.

Syntax

CCritSec *m_pLock;

Remarks

This variable is initialized in the class constructor; see CBaseFilter::CBaseFilter.

Hold this critical section during state transitions, or when a method accesses the state over several operations. The base class holds the critical section in the following methods:

  • CBaseFilter::FindPin
  • CBaseFilter::GetSyncSource
  • CBaseFilter::JoinFilterGraph
  • CBaseFilter::IsActive
  • CBaseFilter::SetSyncSource
  • CBaseFilter::Pause
  • CBaseFilter::Run
  • CBaseFilter::Stop

Do not hold this critical section during streaming operations (that is, when delivering samples to a downstream filter). Serialize streaming operations using a different critical section. Otherwise, it can cause deadlock.

See Also

  • CBaseFilter Class
  • Threads and Critical Sections


CBaseFilter::m_pName

Filter name.

Syntax

WCHAR *m_pName;

See Also

  • CBaseFilter Class


CBaseFilter::m_pGraph

Pointer to the filter graph manager.

Syntax

IFilterGraph *m_pGraph;

See Also

  • CBaseFilter Class


CBaseFilter::m_pSink

Pointer to the IMediaEventSink interface on the filter graph manager.

Syntax

IMediaEventSink *m_pSink;

See Also

  • CBaseFilter Class


CBaseFilter::m_PinVersion

Current version of the set of pins on this filter.

Syntax

long m_PinVersion;

See Also

  • CBaseFilter Class
  • CBaseFilter::GetPinVersion


CBaseFilter::CBaseFilter

Constructor method.

Syntax

CBaseFilter(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    CCritSec *pLock,
    REFCLSID clsid
);

Parameters

pName

Pointer to a string containing the name of the filter, for debugging purposes.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

pLock

Pointer to a CCritSec lock, used to serialize state changes.

clsid

Class identifier of the object.

Remarks

For the critical section object, you would typically do one of the following:

  • Derive a class that inherits both CBaseFilter and CCritSec. For pLock, pass the this pointer.
  • Derive a class that inherits CBaseFilter and contains a CCritSec member variable. For pLock, pass the address of that variable.

See Also

  • CBaseFilter Class


CBaseFilter::~CBaseFilter

Destructor method.

Syntax

CBaseFilter(void);

Remarks

Always stop the filter before destroying it.

See Also

  • CBaseFilter Class


CBaseFilter::EnumPins

The EnumPins method enumerates the pins on this filter. This method implements the IBaseFilter::EnumPins method.

Syntax

HRESULT EnumPins(
    IEnumPins **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumPins interface.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This method creates an instance of the CEnumPins base class, and returns a pointer to that object, of type IEnumPins. The CEnumPins class calls the filter's CBaseFilter::GetPin method to enumerate the pins on the filter.

If this method succeeds, the IEnumPins interface has an outstanding reference count. The caller must release the interface.

See Also

  • CBaseFilter Class


CBaseFilter::FindPin

The FindPin method retrieves the pin with the specified identifier. This method implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id

Pointer to a constant, null-terminated Unicode™ string that identifies the pin.

ppPin

Address of a variable that receives a pointer to the pin's IPin interface.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a matching pin.

Remarks

This method calls the CBasePin::Name method to compare each pin's name against the string specified by the Id parameter.

If the method succeeds, the IPin interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • CBaseFilter Class


CBaseFilter::GetClassID

The GetClassID method retrieves the class identifier of the filter. This method implements the IPersist::GetClassID method.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID

Pointer to a variable that receives the class identifier.

Return Value

Returns S_OK or E_POINTER.

See Also

  • CBaseFilter Class


CBaseFilter::GetFilterGraph

The GetFilterGraph method retrieves a pointer to the filter graph manager.

Syntax

IFilterGraph *GetFilterGraph(void);

Return Value

Returns the value of CBaseFilter::m_pGraph.

See Also

  • CBaseFilter Class


CBaseFilter::GetPin

The GetPin method retrieves a pin. The CEnumPins class calls this method to enumerate pins on the filter.

Syntax

virtual CBasePin *GetPin(
    int n
) PURE;

Parameters

n

Number of the specified pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin.

Remarks

You must implement this pure virtual method in your derived class. Return a pointer to the nth pin on this filter, indexed from zero. You can choose an arbitrary indexing order, as long as the ordering is fixed. If the filter adds or deletes pins, or the ordering changes for some other reason at run time, call the CBaseFilter::IncrementPinVersion method.

See Also

  • CBaseFilter Class


CBaseFilter::GetPinCount

The GetPinCount method retrieves the number of pins.

Syntax

virtual int GetPinCount(void) PURE;

Return Value

Returns the number of pins.

Remarks

The derived class must implement this pure virtual method. Return the number of pins that are currently available on this filter. Filters can dynamically create or destroy pins.

See Also

  • CBaseFilter Class


CBaseFilter::GetPinVersion

The GetPinVersion method retrieves a version number for the set of pins on this filter.

Syntax

virtual long GetPinVersion(void);

Return Value

Returns the CBaseFilter::m_PinVersion member variable.

Remarks

The CBaseFilter constructor initializes the pin version to 1. In the base class, this number never changes. If the filter dynamically creates or destroys pins, it should increment the pin version whenever the pins change. To increment the version number, call the CBaseFilter::IncrementPinVersion method.

The pin enumerator object, which is implemented by the CEnumPins class, uses the pin version to keep itself synchronized with the filter.

See Also

  • CBaseFilter Class


CBaseFilter::GetSetupData

The GetSetupData method retrieves the registration data for the filter.

Note This method is obsolete. It is called by the CBaseFilter::Register and CBaseFilter::Unregister methods.

Syntax

virtual LPAMOVIESETUP_FILTER GetSetupData(void);

Return Value

Returns a pointer to an AMOVIESETUP_FILTER structure containing registration information for the filter.

Remarks

The base class returns NULL.

See Also

  • CBaseFilter Class


CBaseFilter::GetState

The GetState method retrieves the filters's state (running, stopped, or paused). This method implements the IMediaFilter::GetState method.

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout

Time-out interval, in milliseconds.

State

Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns S_OK or E_POINTER.

Remarks

In the base class, all state transitions are synchronous and the dwMilliSecsTimeout parameter is ignored. If a derived class performs asynchronous state transitions, it should override this method to wait during state transitions, with a time-out of dwMilliSecsTimeout milliseconds.

See Also

  • CBaseFilter Class


CBaseFilter::GetSyncSource

The GetSyncSource method retrieves the reference clock that the filter is using. This method implements the IMediaFilter::GetSyncSource method.

Syntax

HRESULT GetSyncSource(
    IReferenceClock **pClock
);

Parameters

pClock

Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns S_OK or E_POINTER.

Remarks

If the filter is not using a reference clock, *pClock is set to NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • CBaseFilter Class


CBaseFilter::IncrementPinVersion

The IncremementPinVersion method increments the version number on the set of pins.

Syntax

void IncrementPinVersion(void);

Remarks

This method increments the CBaseFilter::m_PinVersion member variable. If the filter dynamically creates or destroys pins, call this method whenever the pins change.

See Also

  • CBaseFilter Class
  • CBaseFilter::GetPinVersion


CBaseFilter::IsActive

The IsActive method determines whether the filter is currently active (running or paused).

Syntax

BOOL IsActive(void);

Return Value

Returns TRUE if the filter is paused or running, or FALSE if it is stopped.

See Also

  • CBaseFilter Class


CBaseFilter::IsStopped

The IsStopped method determines whether the filter is currently stopped.

Syntax

BOOL IsStopped(void);

Return Value

Returns TRUE if the filter is stopped, or FALSE otherwise.

See Also

  • CBaseFilter Class


CBaseFilter::JoinFilterGraph

The JoinFilterGraph method notifies the filter that it has joined or left a filter graph. This method implements the IBaseFilter::JoinFilterGraph method.

Syntax

HRESULT JoinFilterGraph(
    IFilterGraph *pGraph,
    LPCWSTR pName
);

Parameters

pGraph

Pointer to the filter graph manager's IFilterGraph interface, or NULL if the filter is leaving the graph.

pName

[in, string] Pointer to a Unicode string containing a name for the filter.

Return Value

Returns S_OK.

Remarks

This method sets the CBaseFilter::m_pGraph member variable equal to the pGraph parameter. It also queries for an IMediaEventSink interface pointer and stores it in the CBaseFilter::m_pSink member variable. However, the filter does not keep a reference count on either of these interfaces. Doing so would create a circular reference count, because the filter graph manager keeps a reference count on the filter.

The method copies the string specified by pName into the CBaseFilter::m_pName member variable.

See Also

  • CBaseFilter Class


CBaseFilter::NotifyEvent

The NotifyEvent method sends an event notification to the filter graph manager.

Syntax

HRESULT NotifyEvent(
    long EventCode,
    LONG_PTR EventParam1,
    LONG_PTR EventParam2
);

Parameters

EventCode

Event notification code.

EventParam1

First parameter of the event.

EventParam2

Second parameter of the event.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_FALSE | The filter graph manager is not accepting event notifications.
S_OK | Success.
E_NOTIMPL | Filter does not have a pointer to the IMediaEventSink interface.

Remarks

For a list of notification codes and parameter values, see Event Notification Codes.

In the base class, if the event code is EC_COMPLETE, the method sets the EventParam2 parameter to a pointer to the filter's IBaseFilter interface.

See Also

  • CBaseFilter Class


CBaseFilter::Pause

The Pause method pauses the filter. This method implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method calls the CBasePin::Active method on each of the filter's connected pins.

See Also

  • CBaseFilter Class


CBaseFilter::QueryFilterInfo

The QueryFilterInfo method retrieves information about the filter. This method implements the IBaseFilter::QueryFilterInfo method.

Syntax

HRESULT QueryFilterInfo(
    FILTER_INFO *pInfo
);

Parameters

pInfo

Pointer to a FILTER_INFO structure.

Return Value

Returns S_OK or E_POINTER.

Remarks

This method copies the filter's name from the CBaseFilter::m_pName member variable into the achName member of the FILTER_INFO structure. If m_pName is NULL, the method sets achName to L'\0'.

The method sets the pGraph member of the FILTER_INFO structure equal to the CBaseFilter::m_pGraph member variable, and increments the reference count. The caller must release the interface.

See Also

  • CBaseFilter Class


CBaseFilter::QueryVendorInfo

The QueryVendorInfo method retrieves a string containing vendor information. This method implements the IBaseFilter::QueryVendorInfo method.

Syntax

HRESULT QueryVendorInfo(
    LPWSTR *pVendorInfo
);

Parameters

pVendorInfo

Address of a variable that receives a pointer to a wide-character string containing the vendor information.

Return Value

Returns E_NOTIMPL.

Remarks

To provide vendor information for a filter, override this method. If you implement this method, use the CoTaskMemAlloc function to allocate memory for the string. The caller is responsible for calling the CoTaskMemFree function.

See Also

  • CBaseFilter Class


CBaseFilter::ReconnectPin

The ReconnectPin method breaks an existing pin connection and reconnects it to the same pin, using a specified media type.

Syntax

HRESULT ReconnectPin(
    IPin *pPin,
    AM_MEDIA_TYPE const *pmt
);

Parameters

pPin

Pointer to the pin's IPin interface.

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type, or NULL.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
E_NOINTERFACE | m_pGraph member variable is NULL.

Remarks

This method calls the IFilterGraph2::ReconnectEx method on the filter graph manager. If the IFilterGraph2 interface is not available, the method calls IFilterGraph::Reconnect.

See Also

  • CBaseFilter Class


CBaseFilter::Register

The Register method adds the filter to the registry.

Note This method is obsolete. New filters should be registered using the AMovieDllRegisterServer2 function. For more information, see How to Register DirectShow Filters.

Syntax

HRESULT Register(void);

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success.
S_FALSE | No registration information is available.

See Also

  • CBaseFilter Class


CBaseFilter::Run

The Run method runs the filter. This method implements the IMediaFilter::Run method.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart

Reference time corresponding to stream time 0.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

If the filter is stopped, this method pauses the filter by calling the CBaseFilter::Pause method. It then calls the CBasePin::Run method on each of the filter's connected pins. Finally, it sets the CBaseFilter::m_State member variable to State_Running.

Stream time is calculated as the current reference time minus tStart. A media sample with a time stamp of zero should be rendered at time tStart.

See Also

  • CBaseFilter Class


CBaseFilter::SetSyncSource

The SetSyncSource method sets a reference clock for the filter. This method implements the IMediaFilter::SetSyncSource method.

Syntax

HRESULT SetSyncSource(
    IReferenceClock *pClock
);

Parameters

pClock

Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK.

See Also

  • CBaseFilter Class


CBaseFilter::Stop

The Stop method stops the filter. This method implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method calls the CBasePin::Inactive method on each of the filter's connected pins. It also sets the filter's state to State_Stopped.

When the filter stops, it should reject samples from upstream, stop delivering samples downstream, shut down worker threads, and free any resources that it used for streaming.

See Also

  • CBaseFilter Class


CBaseFilter::StreamTime

The StreamTime method retrieves the current stream time.

Syntax

virtual HRESULT StreamTime(
    CRefTime& rtStream
);

Parameters

rtStream

Reference to a CRefTime object that receives the current stream time.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_CLOCK | No reference clock is available.

Remarks

Stream time is defined as the current reference time (as given by the reference clock) minus the start time (specified by CBaseFilter::m_tStart). A media sample's time stamp specifies the stream time when it should be rendered. If a sample with a time stamp less than the current stream time has not yet been rendered, it is late.

See Also

  • CBaseFilter Class


CBaseFilter::Unregister

The Unregister method removes the filter from the registry.

Note This method is obsolete. New filters should be unregistered using the AMovieDllRegisterServer2 function. For more information, see How to Register DirectShow Filters.

Syntax

HRESULT Unregister(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

See Also

  • CBaseFilter Class


CBaseInputPin Class

CBaseInputPin Class Hierarchy

The CBaseInputPin class is an abstract base class for implementing input pins. This class adds support for the IMemInputPin interface, in addition to the IPin interface support provided by CBasePin.

To use this class, derive a new class and override at least the following methods:

  • CBaseInputPin::BeginFlush
  • CBaseInputPin::EndFlush
  • CBaseInputPin::Receive
  • CBasePin::CheckMediaType
  • CBasePin::GetMediaType

Depending on the function of the pin, you might need to override additional methods in CBaseInputPin or CBasePin.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pAllocator | Pointer to the memory allocator.
m_bReadOnly | Flag that indicates whether the allocator produces read-only media samples.
m_bFlushing | Flag that indicates whether the pin is currently flushing.
m_SampleProps | Properties of the most recent sample.
Public Methods |
CBaseInputPin | Constructor method.
~CBaseInputPin | Destructor method.
BreakConnect | Releases the pin from a connection.
IsReadOnly | Queries whether the allocator uses read-only media samples.
IsFlushing | Queries whether the filter is currently flushing.
CheckStreaming | Determines whether the pin can accept samples. Virtual.
PassNotify | Passes a quality-control message to the appropriate object.
Inactive | Notifies the pin that the filter is no longer active. Virtual.
SampleProps | Retrieves the properties of the most recent sample.
IPin Methods |
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
IMemInputPin Methods |
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves the allocator properties requested by the input pin.
Receive | Receives the next media sample in the stream.
ReceiveMultiple | Receives multiple samples in the stream.
ReceiveCanBlock | Determines whether calls to the CBaseInputPin::Receive method might block.
IQualityControl Methods |
Notify | Receives a quality-control message.


CBaseInputPin::m_pAllocator

Pointer to the memory allocator.

Syntax

IMemAllocator *m_pAllocator;

See Also

  • CBaseInputPin Class


CBaseInputPin::m_bReadOnly

Flag that indicates whether the allocator produces read-only media samples. If TRUE, the allocator produces read-only samples.

Syntax

BYTE m_bReadOnly;

See Also

  • CBaseInputPin Class


CBaseInputPin::m_bFlushing

Flag that indicates whether the pin is currently flushing. If TRUE, the pin is flushing.

Syntax

BYTE m_bFlushing;

See Also

  • CBaseInputPin Class


CBaseInputPin::m_SampleProps

Properties of the most recent sample.

Syntax

AM_SAMPLE2_PROPERTIES m_SampleProps;

See Also

  • CBaseInputPin Class


CBaseInputPin::BeginFlush

The CBaseInputPin method begins a flush operation. This method implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns S_OK.

Remarks

This method sets the CBaseInputPin::m_bFlushing flag to TRUE, which causes the CBaseInputPin::Receive method to reject any more samples.

The derived class must override this method and perform the following steps:

  1. Call the IPin::BeginFlush method on downstream input pins. If the pin has not yet delivered any media samples downstream, you can skip this step. If your output pins derive from the CBaseOutputPin class, you can call the CBaseOutputPin::DeliverBeginFlush method.
  2. Call the base class method.
  3. Begin discarding queued data.
  4. Return from any blocked calls to the Receive method.

See Also

  • CBaseInputPin Class


CBaseInputPin::BreakConnect

The BreakConnect method releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::BreakConnect method. It decommits the allocator and releases the IMemAllocator interface.

If you override this method, call the base-class method from your overriding method. Otherwise, you might cause memory leaks.

See Also

  • CBaseInputPin Class


CBaseInputPin::CBaseInputPin

Constructor method.

Syntax

CBaseInputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pPinName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin.

pLock

Pointer to a CCritSec lock, used to serialize state changes. This can be the same critical section as the filter lock, CBaseFilter::m_pLock.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

pPinName

Wide-character string containing the pin name (also used as the pin identifier).

Remarks

All of the parameters are passed directly to the CBasePin constructor.

See Also

  • CBaseInputPin Class


CBaseInputPin::~CBaseInputPin

Destructor method.

Syntax

~CBaseInputPin(void);

See Also

  • CBaseInputPin Class


CBaseInputPin::CheckStreaming

Determines whether the pin can accept samples.

Syntax

virtual HRESULT CheckStreaming(void);

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

The derived class can override this method to perform further checks. In the overriding method, also call the base class implementation.

The CBaseInputPin::Receive method calls this method. You should override the CBasePin::EndOfStream method to call this method as well.

See Also

  • CBaseInputPin Class


CBaseInputPin::EndFlush

The EndFlush method ends a flush operation. Implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK.

Remarks

This method sets the CBaseInputPin::m_bFlushing flag to TRUE, which enables the CBaseInputPin::Receive method to accept samples.

The derived class must override this method and perform the following steps:

  1. Free any buffered data and wait for all queued samples to be discarded.
  2. Clear any pending EC_COMPLETE notifications.
  3. Call the base class method.
  4. Call IPin::EndFlush on downstream input pins. If the pin has not yet delivered any media samples downstream, you can skip this step. If your output pins derive from the CBaseOutputPin class, you can call the CBaseOutputPin::DeliverEndFlush method.

See Also

  • CBaseInputPin Class


CBaseInputPin::GetAllocator

The GetAllocator method retrieves the memory allocator proposed by this pin. This method implements the IMemInputPin::GetAllocator method.

Syntax

HRESULT GetAllocator(
    IMemAllocator **ppAllocator
);

Parameters

ppAllocator

Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an error code from the CoCreateInstance function.

Remarks

This method creates a CMemAllocator object. Override this method if your filter uses an allocator from a downstream pin, or a custom allocator.

If the method succeeds, the IMemAllocator interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • CBaseInputPin Class


CBaseInputPin::GetAllocatorRequirements

The GetAllocatorRequirements method retrieves the allocator properties requested by the input pin.

Syntax

HRESULT GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

Pointer to an ALLOCATOR_PROPERTIES structure, which is filled in with the requirements.

Return Value

Returns E_NOTIMPL.

Remarks

When an output pin initializes a memory allocator, it can call this method to determine whether the input pin has any buffer requirements. For more information, see CBaseOutputPin::DecideAllocator.

Implementing this method is optional. If the filter has specific alignment or prefix requirements, override this method.

See Also

  • CBaseInputPin Class


CBaseInputPin::Inactive

The Inactive method notifies the pin that the filter is no longer active.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ALLOCATOR | No memory allocator is available.

Remarks

This method overrides the CBasePin::Inactive method. It calls the IMemAllocator::Decommit method to decommit the memory allocator.

If you override this method, call the base-class method from your overriding method.

See Also

  • CBaseInputPin Class


CBaseInputPin::IsFlushing

The IsFlushing method queries whether the filter is currently flushing.

Syntax

BOOL IsFlushing(void);

Return Value

Returns the CBaseInputPin::m_bFlushing member variable.

See Also

  • CBaseInputPin Class


CBaseInputPin::IsReadOnly

Queries whether the allocator uses read-only media samples.

Syntax

BOOL IsReadOnly(void);

Return Value

Returns the value of the CBaseInputPin::m_bReadOnly member variable.

See Also

  • CBaseInputPin Class


CBaseInputPin::Notify

The Notify method notifies the pin that a quality change is requested. This method implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf

Pointer to the filter that is sending the quality-control message.

q

Quality structure that contains the quality-control message.

Return Value

Returns S_OK.

Remarks

Filters usually pass quality-control messages to an upstream output pin, not to an input pin. Therefore, this method returns S_OK without doing anything.

See Also

  • CBaseInputPin Class
  • Quality-Control Management


CBaseInputPin::NotifyAllocator

The NotifyAllocator method specifies an allocator for the connection. This method implements the IMemInputPin::NotifyAllocator method.

Syntax

HRESULT NotifyAllocator(
    IMemAllocator *pAllocator,
    BOOL bReadOnly
);

Parameters

pAllocator

Pointer to the allocator's IMemAllocator interface.

bReadOnly

Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns S_OK.

Remarks

During the pin connection, the output pin chooses an allocator and calls this method to notify the input pin. The output pin can use the allocator that the input pin proposed in the IMemInputPin::GetAllocator method, or it can provide its own allocator.

See Also

  • CBaseInputPin Class


CBaseInputPin::PassNotify

The PassNotify method passes a quality-control message to the appropriate object.

Syntax

HRESULT PassNotify(
    Quality q
);

Parameters

q

Quality structure that contains the quality-control message.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_FOUND | Could not find an object to accept the message.

Remarks

Call this method if the filter does not handle quality-control messages. This method passes the message to one of the following objects, in order of preference:

  • An external quality-control manager, if the IQualityControl::SetSink method was called.
  • The upstream output pin.

See Also

  • CBaseInputPin Class
  • Quality-Control Management


CBaseInputPin::Receive

The Receive method receives the next media sample in the stream. This method implements the IMemInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

The upstream output pin calls this method to deliver a sample to the input pin. The input pin must do one of the following:

  • Process the sample before returning.
  • Return, and process the sample in a worker thread.
  • Reject the sample.

If the pin uses a worker thread to process the sample, add a reference count to the sample inside this method. After the method returns, the upstream pin releases the sample. When the sample's reference count reaches zero, the sample returns to the allocator for re-use.

This method is synchronous and can block. If the method might block, the pin's CBaseInputPin::ReceiveCanBlock method should return S_OK.

In the base class, this method performs the following steps:

  1. Calls the CBaseInputPin::CheckStreaming method to verify that the pin can process samples now. If it cannot—for example, if the pin is stopped—the method fails.
  2. Retrieves the sample properties and checks whether the format has changed (see below).
  3. If the format has changed, the method calls the CBasePin::CheckMediaType method to determine whether the new format is acceptable.
  4. If the new format is not acceptable, the method calls the CBasePin::EndOfStream method, posts an EC_ERRORABORT event, and returns an error code.
  5. Assuming there were no errors, the method returns S_OK.

Test for a format change as follows:

  • If the sample supports the IMediaSample2 interface, check the dwSampleFlags member of the AM_SAMPLE2_PROPERTIES structure. If the AM_SAMPLE_TYPECHANGED flag is present, the format has changed.
  • Otherwise, if the sample does not support IMediaSample2, call the IMediaSample::GetMediaType method. If the method returns a non-NULL value, the format has changed.

In the base class, this method does not process the sample. The derived class must override this method to perform the processing. (What this entails depends entirely on the filter.) The derived class should call the base-class method, to check for the errors described previously.

See Also

  • CBaseInputPin Class


CBaseInputPin::ReceiveCanBlock

The ReceiveCanBlock method determines whether calls to the IMemInputPin::Receive method might block. This method implements the IMemInputPin::ReceiveCanBlock method.

Syntax

HRESULT ReceiveCanBlock(void);

Return Value

Returns an HRESULT value. Possible value include those listed in the following table.

Value | Description
S_FALSE | The pin will not block on a call to Receive.
S_OK | The pin might block on a call to Receive.

Remarks

Return S_FALSE if calls to the Receive method are guaranteed not to block. Otherwise, return S_OK or an error code. If the Receive method calls Receive on a downstream pin, the downstream pin might block; ReceiveCanBlock must take that factor into account.

An upstream filter can use this method to determine its threading strategy. If the Receive method might block, the upstream filter might decide to use a worker thread that buffers data. See the COutputQueue class for an implementation of this strategy.

In the base class, this method returns S_OK when any of the following are true:

  • The filter has no output pins.
  • An input pin connected to this filter signals that it might block.
  • An input pin connected to this filter does not support the IMemInputPin interface.

See Also

  • CBaseInputPin Class


CBaseInputPin::ReceiveMultiple

The ReceiveMultiple method receives an array of samples. This method implements the IMemInputPin::ReceiveMultiple method.

Syntax

HRESULT ReceiveMultiple(
    IMediaSample **pSamples,
    long nSamples,
    long *nSamplesProcessed
);

Parameters

pSamples

Address of an array of IMediaSample pointers, of size nSamples.

nSamples

Number of samples to process.

nSamplesProcessed

Pointer to a variable that receives the number of samples that were processed.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method behaves like the CBaseInputPin::Receive method, but receives an array of samples. In the base class, the method loops through the array and calls Receive with each sample. Override this function if your filter can process batches of samples more efficiently than processing them one at a time.

See Also

  • CBaseInputPin Class


CBaseInputPin::SampleProps

The SampleProps method retrieves the properties of the most recent sample, in an AM_SAMPLE2_PROPERTIES structure.

Syntax

AM_SAMPLE2_PROPERTIES *SampleProps(void);

Return Value

Returns the address of the CBaseInputPin::m_SampleProps member variable.

See Also

  • CBaseInputPin Class


CBaseList Class

CBaseList Class Hierarchy

The CBaseList method implements an abtract list. The CGenericList class template, which derives from CBaseList, provides type checking and a simpler API than the CBaseList class.

The CBaseList class is modeled after the CObList class in the Microsoft® Foundation Classes (MFC) library. Positions within the list are represented by a POSITION structure. The caller should not access the internal members of the POSITION structure; treat it as a pointer to a list node. The position of an object in the list remains valid until the object is deleted.

The list does not require any support by the objects it contains. It performs no storage management or copying on the objects. Objects can be in multiple lists.

Roughly half of the methods in this class act on single objects. These methods have the suffix -I in the method name. The other methods act on entire lists. For example, the CBaseList::AddAfter method appends a list to another list. Single-object operations return POSITION values, or NULL on failure. List operations return TRUE if successful or FALSE otherwise.

Requirements

Header: Declared in Wxlist.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_Count | Number of items in the list.
m_pFirst | Pointer to the first node in the list.
m_pLast | Pointer to the last node in the list.
Protected Methods |
GetNextI | Retrieves the item at the specified position, and advances the position.
GetI | Retrieves the item at the specified position.
FindI | Retrieves the first position that holds the specified item.
RemoveHeadI | Removes the first item in the list.
RemoveTailI | Removes the last item in the list.
RemoveI | Removes the item at the specified position.
AddTailI | Adds an item to the end of the list.
AddHeadI | Adds an item to the front of the list.
AddAfterI | Inserts an item after the specified position.
AddBeforeI | Inserts an item before the specified position.
Public Methods |
CBaseList | Constructor method.
~CBaseList | Destructor method.
RemoveAll | Removes all nodes from the list.
GetHeadPositionI | Retrieves the position of the first item in the list.
GetTailPositionI | Retrieves the position of the last item of the list.
GetCountI | Retrieves the number of items in the list.
Next | Retrieves the next position in the list.
Prev | Retrieves the previous position in the list.
AddHead | Inserts another list at the front of this list.
AddTail | Appends another list to the end of this list.
AddAfter | Inserts a list after the specified position.
AddBefore | Inserts a list before the specified position.
MoveToTail | Splits the list and appends the head portion to the tail of another list.
MoveToHead | Splits the list and inserts the tail portion at the head of another list.
Reverse | Reverses the order of the list.


CBaseList::m_Count

Number of items in the list.

Syntax

long m_Count;

See Also

  • CBaseList Class


CBaseList::m_pFirst

Pointer to the first node in the list.

Syntax

CNode *m_pFirst;

See Also

  • CBaseList Class


CBaseList::m_pLast

Pointer to the last node in the list.

Syntax

CNode *m_pLast;

See Also

  • CBaseList Class


CBaseList::AddAfter

The AddAfter method inserts a list after the specified position.

Syntax

BOOL AddAfter(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos

Position after which to insert the list.

pList

Pointer to the list to insert.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Return Remarks

Existing position indicators, including the one specified in the pos parameter, remain valid. If the method fails, some of the items might have been added.

See Also

  • CBaseList Class


CBaseList::AddAfterI

The AddAfterI method inserts an item after the specified position.

Syntax

POSITION AddAfterI(
    POSITION pos,
    void *pObj
);

Parameters

pos

Position after which to add the item.

pObj

Pointer to the item to add.

Return Value

Returns the position indicator of the inserted item.

Remarks

If pos is NULL, this method adds the item to the head of the list (equivalent to calling the CBaseList::AddHeadI method.)

See Also

  • CBaseList Class


CBaseList::AddBefore

The AddBefore method inserts a list before the specified position.

Syntax

BOOL AddBefore(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos

Position before which to insert the list.

pList

Pointer to the list to insert.

Return Value

Returns TRUE if successful. Otherwise, returns FALSE.

Remarks

Existing position indicators, including the one specified in the pos parameter, remain valid. If the method fails, some of the items might have been added.

See Also

  • CBaseList Class


CBaseList::AddBeforeI

The AddBeforeI method inserts an item before the specified position.

Syntax

POSITION AddBeforeI(
    POSITION pos,
    void *pObj
);

Parameters

pos

Position before which to add the item.

pObj

Pointer to the item.

Return Value

Returns the position indicator for the inserted item.

Remarks

If pos is NULL, this method adds the item to the tail of the list (equivalent to calling the CBaseList::AddTailI method).

See Also

  • CBaseList Class


CBaseList::AddHead

The AddHead method inserts another list at the front of this list.

Syntax

BOOL AddHead(
    CBaseList *pList
);

Parameters

pList

Pointer to the list of items to add.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

If the method fails, some items might have been added to the list.

See Also

  • CBaseList Class


CBaseList::AddHeadI

The AddHeadI method adds an item to the front of the list.

Syntax

POSITION AddHeadI(
    void *pObj
);

Parameters

pObj

Pointer to the item.

Return Value

Returns a POSITION value indicating the new head position.

Remarks

If the method fails, the return value is NULL.

See Also

  • CBaseList Class


CBaseList::AddTail

The AddTail method appends another list to the end of this list.

Syntax

BOOL AddTail(
    CBaseList *pList
);

Parameters

pList

Pointer to the list to append.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

If the method fails, some items may have been added to the list.

See Also

  • CBaseList Class


CBaseList::AddTailI

The AddTailI method adds an item to the end of the list.

Syntax

POSITION AddTailI(
    void *pObj
);

Parameters

pObj

Pointer to the item.

Return Value

Returns a POSITION value for the new tail position.

Remarks

If the method fails, it returns NULL.

See Also

  • CBaseList Class


CBaseList::CBaseList

Constructor method.

Syntax

CBaseList(
    TCHAR *pName,
    INT iItems
);

CBaseList(
    TCHAR *pName
);

Parameters

pName

Pointer to the name of the list.

iItems

Size of the node cache.

Remarks

For efficiency, the CBaseList class maintains a cache of list nodes. If you know approximately how many items the list will hold, use the first version of the constructor. The second version uses a default cache size.

See Also

  • CBaseList Class


CBaseList::~CBaseList

Destructor method.

Syntax

~CBaseList(void);

See Also

  • CBaseList Class


CBaseList::FindI

The FindI method retrieves the first position that holds the specified item.

Syntax

POSITION FindI(
    void *pObj
);

Parameters

pObj

Pointer to the item.

Return Value

Returns a POSITION value, or NULL if the item is not in the list.

See Also

  • CBaseList Class


CBaseList::GetCountI

The GetCountI method retrieves the number of items in the list.

Syntax

int GetCountI(void);

Return Value

Returns the number of items in the list.

See Also

  • CBaseList Class


CBaseList::GetHeadPositionI

The GetHeadPositionI method retrieves the position of the first item in the list.

Syntax

POSITION GetHeadPositionI(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

See Also

  • CBaseList Class


CBaseList::GetI

The GetI method retrieves the item at the specified position.

Syntax

void *GetI(
    POSITION pos
);

Parameters

pos

Position indicator for the item to retrieve.

Return Value

Returns a pointer to the item.

Remarks

If pos is NULL, the method returns NULL.

See Also

  • CBaseList Class


CBaseList::GetNextI

The GetNextI method retrieves the item at the specified position, and advances the position.

Syntax

void *GetNextI(
    POSITION& rp
);

Parameters

rp

Reference to a POSITION value.

Return Value

Returns a pointer to the item.

Remarks

This method advances the position indicator to the next position. If the position indicator moves past the end of the list, the method sets it to NULL.

If rp is NULL, the method returns NULL.

See Also

  • CBaseList Class


CBaseList::GetTailPositionI

The GetTailPositionI method retrieves the position of the last item of the list.

Syntax

POSITION GetTailPositionI(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

See Also

  • CBaseList Class


CBaseList::MoveToHead

The MoveToHead method splits the list and inserts the tail portion at the head of another list.

Syntax

BOOL MoveToHead(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos

Position indicator that marks the split in the list.

pList

Pointer to another list.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method splits the list before the position specified by the pos parameter. The head portion remains in the list. The tail portion is inserted at the head of the other list.

See Also

  • CBaseList Class


CBaseList::MoveToTail

The MoveToTail method splits the list and appends the head portion to the tail of another list.

Syntax

BOOL MoveToTail(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos

Position indicator that marks the split in the list.

pList

Pointer to another list.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method splits the list after the position specified by the pos parameter. The tail portion remains in the list. The head portion is appended to the tail of the other list.

See Also

  • CBaseList Class


CBaseList::Next

The Next method retrieves the next position in the list.

Syntax

POSITION Next(
    POSITION pos
);

Parameters

pos

POSITION value.

Return Value

Returns the position indicator that follows the position specified by pos.

Remarks

If pos is the last position in the list, the method returns NULL. If pos is NULL, the method returns the first position in the list.

See Also

  • CBaseList Class


CBaseList::Prev

The Prev method retrieves the previous position in the list.

Syntax

POSITION Prev(
    POSITION pos
);

Parameters

pos

POSITION value.

Return Value

Returns the position indicator that is previous to the position specified in pos.

Remarks

If pos is the first position in the list, the method returns NULL. If pos is NULL, the method returns the last position in the list.

See Also

  • CBaseList Class


CBaseList::RemoveAll

The RemoveAll method removes all the nodes from the list.

Syntax

void RemoveAll(void);

Remarks

It is the caller's responsibility to delete the items contained in all the nodes.

See Also

  • CBaseList Class


CBaseList::RemoveHeadI

The RemoveHeadI method removes the first item in the list.

Syntax

void *RemoveHeadI(void);

Return Value

Returns a pointer to the item, or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that the node contains.

See Also

  • CBaseList Class


CBaseList::RemoveI

The RemoveI method removes the item at the specified position.

Syntax

void *RemoveI(
    POSITION pos
);

Parameters

pos

POSITION value indicating the item to remove.

Return Value

Returns a pointer to the item.

Remarks

This method deletes the node from the list, but does not delete the item contained in that node.

If pos is NULL, the method returns NULL.

See Also

  • CBaseList Class


CBaseList::RemoveTailI

The RemoveTailI method removes the last item in the list.

Syntax

void *RemoveTailI(void);

Return Value

Returns a pointer to the item, or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that is contained in the node.

See Also

  • CBaseList Class


CBaseList::Reverse

The Reverse method reverses the order of the list.

Syntax

void Reverse(void);

See Also

  • CBaseList Class


CBaseMediaFilter Class

The CBaseMediaFilter class implements the IMediaFilter interface. Use this class for plug-in distributors or other objects that need to support IMediaFilter without supporting the IBaseFilter interface. Do not use this class for filters. Instead, use the CBaseFilter class, or a base class derived from CBaseFilter.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_State | Current state of the object.
m_pClock | Pointer to the object's reference clock.
m_tStart | Reference time that corresponds to stream time 0.
m_clsid | Class identifier (CLSID) of the object.
m_pLock | Pointer to a critical section.
Public Methods |
CBaseMediaFilter | Constructor method.
~CBaseMediaFilter | Destructor method. Virtual.
StreamTime | Retrieves the current stream time. Virtual.
IsActive | Determines whether the object is active (running or paused).
IPersist Methods |
GetClassID | Retrieves the class identifier.
IMediaFilter Methods |
GetState | Retrieves the object's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the object.
GetSyncSource | Retrieves the reference clock that the object is using.
Stop | Stops the object.
Pause | Pauses the object.
Run | Runs the object.


CBaseMediaFilter::m_State

Indicates the current state of the object.

Syntax

FILTER_STATE m_State;

See Also

  • CBaseMediaFilter Class
  • CBaseMediaFilter::GetState


CBaseMediaFilter::m_pClock

Pointer to the object's reference clock.

Syntax

IReferenceClock *m_pClock;

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::m_tStart

Reference time that corresponds to stream time 0.

Syntax

CRefTime m_tStart;

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::m_clsid

Class identifier (CLSID) of the object.

Syntax

CLSID m_clsid;

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::m_pLock

Pointer to a critical section.

Syntax

CCritSec *m_pLock;

Remarks

The critical section is held during state transitions (CBaseMediaFilter::Run, CBaseMediaFilter::Pause, CBaseMediaFilter::Stop), when accessing the reference clock (CBaseMediaFilter::SetSyncSource, CBaseMediaFilter::GetSyncSource), and in the CBaseMediaFilter::IsActive method.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::CBaseMediaFilter

Constructor method.

Syntax

CBaseMediaFilter(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    CCritSec *pLock,
    REFCLSID clsid
);

Parameters

pName

Pointer to a string containing the name of the object.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

pLock

Pointer to a CCritSec lock, used to serialize state changes.

clsid

Class identifier of the object.

Remarks

If another object contains or aggregates the CBaseMediaFilter object, the CCritSec lock might be external to the CBaseMediaFilter object. In that case, pass a pointer to the lock in pLock.

Otherwise, you can:

  • Derive a class that inherits both CBaseMediaFilter and CCritSec. For pLock, pass the this pointer.
  • Derive a class that inherits CBaseMediaFilter and contains a CCritSec member variable. For pLock, pass the address of that variable.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::~CBaseMediaFilter

Destructor method.

Syntax

CBaseMediaFilter(void);

Remarks

Always stop the object before destroying it.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::GetClassID

The GetClassID method retrieves the class identifier. This method implements the IPersist::GetClassID method.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID

Pointer to a variable that receives the class identifier.

Return Value

Returns S_OK or E_POINTER.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::GetState

The GetState method retrieves the object's state (running, stopped, or paused). This method implements the IMediaFilter::GetState method.

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout

Time-out interval, in milliseconds.

State

Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the object's state.

Return Value

Returns S_OK or E_POINTER.

Remarks

In the base class, all state transitions are synchronous and the dwMilliSecsTimeout parameter is ignored. If a derived class performs asynchronous state transitions, it should override this method to wait during state transitions, with a time-out of dwMilliSecsTimeout milliseconds.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::GetSyncSource

The GetSyncSource method retrieves the reference clock that the object is using. This method implements the IMediaFilter::GetSyncSource method.

Syntax

HRESULT GetSyncSource(
    IReferenceClock **pClock
);

Parameters

pClock

Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns S_OK or E_POINTER.

Remarks

If the object is not using a reference clock, *pClock is set to NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::IsActive

The IsActive method determines whether the object is active (running or paused).

Syntax

BOOL IsActive(void);

Return Value

Returns TRUE if the object is paused or running, or FALSE if it is stopped.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::Pause

Pauses the object. Implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK.

Remarks

In the base class, this method sets the CBaseMediaFilter::m_State member variable to State_Paused but does nothing else.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::Run

The Run method runs the object. This method implements the IMediaFilter::Run method.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart

Reference time corresponding to stream time 0.

Return Value

Returns S_OK.

Remarks

If the object is stopped, this method pauses the object by calling the CBaseMediaFilter::Pause method. It then sets the CBaseMediaFilter::m_State member variable to State_Running.

Stream time is calculated as the current reference time minus tStart. A media sample with a time stamp of zero should be rendered at time tStart.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::SetSyncSource

The SetSyncSource method sets a reference clock for the object. This method implements the IMediaFilter::SetSyncSource method.

Syntax

HRESULT SetSyncSource(
    IReferenceClock *pClock
);

Parameters

pClock

Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::Stop

The Stop method stops the object. This method implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK.

Remarks

In the base class, this method sets the CBaseMediaFilter::m_State member variable to State_Stopped but does nothing else.

See Also

  • CBaseMediaFilter Class


CBaseMediaFilter::StreamTime

The StreamTime method retrieves the current stream time.

Syntax

virtual HRESULT StreamTime(
    CRefTime& rtStream
);

Parameters

rtStream

Reference to a CRefTime object that receives the current stream time.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_CLOCK | No reference clock is available.

Remarks

Stream time is defined as the current reference time (as given by the reference clock) minus the start time (specified by CBaseMediaFilter::m_tStart). A media sample's time stamp specifies the stream time when it should be rendered. If a sample with a time stamp less than the current stream time has not yet been rendered, it is late.

See Also

  • CBaseMediaFilter Class


CBaseObject Class

The CBaseObject class is an abstract class for implementing Microsoft® DirectShow® objects. To implement Component Object Model (COM) objects, use the CUnknown class, which derives from CBaseObject.

Most of the DirectShow classes derive from CBaseObject. This class provides debugging assistance by keeping a count of all the DirectShow objects active during run time. The object count is stored in a class-static member variable:

class CBaseObject
{
private:
    static LONG m_cObjects;  // Total number of objects active.
/* ... */
};

In debug builds, the DLL will assert if it is unloaded while the object count is greater than zero. This makes it easier to track down leaks caused by reference-counting problems.

The CObject constructor takes one argument, a debugging name for the object. This name is stored in a global table in the DLL. The DbgDumpObjectRegister function formats a list of the objects active in the DLL, and sends it to the debug output.

Requirements

Header: Declared in Combase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Class Methods |
CBaseObject | Constructor method.
~CBaseObject | Destructor method.
ObjectsActive | Retrieves the count of active objects.


CBaseObject::CBaseObject

Constructor method.

Syntax

CBaseObject(
    const TCHAR *pName
);

Parameters

pName

String that contains the name of the object, for debugging purposes.

Remarks

This method increments the active-object count. (See CBaseObject::ObjectsActive.)

Allocate the pName parameter in static memory:

// Correct.
CBaseObject *pObject = new CBaseObject(NAME("My Object"));

// Incorrect.
TCHAR ObjectName[] = TEXT("My Object");
CBaseObject *pObject = new CObject(ObjectName);

The NAME macro compiles to NULL in retail builds, so that static strings appear only in debug builds. For more information, see DbgDumpObjectRegister.

See Also

  • CBaseObject Class


CBaseObject::~CBaseObject

Destructor method.

Syntax

~CBaseObject(void);

Remarks

This method decrements the active-object count. (See CBaseObject::ObjectsActive.)

See Also

  • CBaseObject Class


CBaseObject::ObjectsActive

The ObjectsActive method retrieves a process-wide count of active objects.

Syntax

static LONG ObjectsActive(void);

Return Value

Returns the number of active objects.

See Also

  • CBaseObject Class


CBaseOutputPin Class

CBaseOutputPin Class Hierarchy

The CBaseOutputPin class is an abstract base class that implements an output pin.

This class derives from CBasePin. It differs from CBasePin in the following respects:

  • It connects only to input pins that support the IMemInputPin interface.
  • It supports local memory transport through the IMemAllocator interface.
  • It rejects end-of-stream, flush, and new-segment notifications. (These should not be sent to an output pin.)
  • It provides methods for delivering samples downstream.

When the pin connects, it requests a memory allocator from the input pin. Failing that, it creates a new allocator object. The output pin is responsible for setting the allocator properties. It does this through the pure virtual method CBaseOutputPin::DecideBufferSize. Override this method in your derived class. If the input pin has any buffer requirements, they are passed to the DecideBufferSize method.

Call the CBaseOutputPin::GetDeliveryBuffer method to obtain an empty media sample. Call the CBaseOutputPin::Deliver method to deliver samples downstream.

Your derived class must override the pure virtual CBasePin::CheckMediaType method to validate the media type during pin connections.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pAllocator | Pointer to the memory allocator.
m_pInputPin | Pointer to the input pin connected to this pin.
Public Methods |
CBaseOutputPin | Constructor method.
DecideAllocator | Selects a memory allocator. Virtual.
GetDeliveryBuffer | Retrieves a media sample that contains an empty buffer. Virtual.
Deliver | Delivers a media sample to the connected input pin. Virtual.
InitAllocator | Creates a memory allocator. Virtual.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
Active | Notifies the pin that the filter is now active.
Inactive | Notifies the pin that the filter is no longer active.
DeliverEndOfStream | Delivers an end-of-stream notification to the connected input pin. Virtual.
DeliverBeginFlush | Requests the connected input pin to begin a flush operation. Virtual.
DeliverEndFlush | Requests the connected input pin to end a flush operation. Virtual.
DeliverNewSegment | Delivers a new-segment notification to the connected input pin. Virtual.
Pure Virtual Methods |
DecideBufferSize | Sets the buffer requirements.
IPin Methods |
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
EndOfStream | Notifies the pin that no additional data is expected.


CBaseOutputPin::m_pAllocator

Pointer to the memory allocator.

Syntax

IMemAllocator *m_pAllocator;

See Also

  • CBaseOutputPin Class


CBaseOutputPin::m_pInputPin

Pointer to the input pin connected to this pin.

Syntax

IMemInputPin *m_pInputPin;

See Also

  • CBaseOutputPin Class


CBaseOutputPin::Active

The Active method notifies the pin that the filter is now active.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ALLOCATOR | No allocator is available.

Remarks

This method overrides the CBasePin::Active method. It calls the IMemAllocator::Commit method on the allocator, to allocate memory for buffers.

If you override this method, call the base-class method from your overriding method.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::BeginFlush

The BeginFlush method begins a flush operation. Implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::BreakConnect

The BreakConnect method releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::BreakConnect method. It decommits the allocator and releases the IMemAllocator and IPin interfaces.

If you override this method, call the base-class method from your overriding method. Otherwise, you might cause memory leaks.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::CBaseOutputPin

Constructor method.

Syntax

CBaseOutputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin.

pLock

Pointer to a CCritSec lock, used to serialize state changes. This can be the same critical section as the filter lock, CBaseFilter::m_pLock.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

pName

Wide-character string containing the pin name (also used as the pin identifier).

Remarks

All of the parameters are passed directly to the CBasePin constructor.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::CheckConnect

The CheckConnect method determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin

Pointer to the input pin's IPin interface.

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
E_NOINTERFACE | Input pin does not support IMemInputPin.
VFW_E_INVALID_DIRECTION | Pin directions are not compatible.

Remarks

This method calls the base-class CBasePin::CheckConnect method, and then queries the input pin for its IMemInputPin interface.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::CompleteConnect

The CompleteConnect method completes a connection to an input pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the input pin.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::CompleteConnect method. It calls the DecideAllocator method, which selects the memory allocator to use for this connection.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DecideAllocator

The DecideAllocator method selects a memory allocator.

Syntax

virtual HRESULT DecideAllocator(
    IMemInputPin *pPin,
    IMemAllocator **pAlloc
);

Parameters

pPin

Pointer to the input pin's IMemInputPin interface.

pAlloc

Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method is called at the end of the pin connection process. It performs the following steps:

  1. Calls the IMemInputPin::GetAllocatorRequirements method to retrieve the input pin's buffer requirements, if any.
  2. Calls the IMemInputPin::GetAllocator method to request an allocator from the input pin. If the input pin does not provide an allocator, the output pin creates one by calling the CBaseOutputPin::InitAllocator class method.
  3. Calls the CBaseOutputPin::DecideBufferSize class method, which sets the allocator properties. This is a pure virtual method; the derived class must implement it.
  4. Calls the IMemInputPin::NotifyAllocator method, which notifies the input pin of the allocator being used.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DecideBufferSize

The DecideBufferSize method sets the buffer requirements.

Syntax

virtual HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
) PURE;

Parameters

pAlloc

Pointer to the allocator's IMemAllocator interface.

ppropInputRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains the input pin's buffer requirements. If the input pin does not have any requirements, the caller should zero out the members of this structure before calling the method.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Override this method in your derived class. Call the IMemAllocator::SetProperties method to specify your buffer requirements. Typically, the derived class will honor the input pin's buffer requirements, but it is not required to.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::Deliver

The Deliver method delivers a media sample to the connected input pin.

Syntax

virtual HRESULT Deliver(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IMemInputPin::Receive method on the input pin. Receive can block if the IMemInputPin::ReceiveCanBlock method returns S_OK.

Release the sample after calling this method. The input pin might hold a reference count on the sample, so do not reuse the sample. Always call the CBaseOutputPin::GetDeliveryBuffer method to obtain a new sample.

Hold the filter's critical section before calling this method. Otherwise, the pin might get disconnected during the method call. If the filter uses a worker thread to deliver samples, hold the critical section when the filter is ready to deliver a sample. Otherwise, you can hold the critical section in the filter's IMemInputPin::Receive method, where the filter processes samples.

Worker threads can create a potential deadlock. When the thread holds the critical section, it might wait on a state change in the filter. At the same time, the state change might be waiting for the thread to complete. To prevent this, the state-change code should signal an event that terminates the thread, and then wait for the thread to signal completion.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DeliverBeginFlush

The DeliverBeginFlush method requests the connected input pin to begin a flush operation.

Syntax

virtual HRESULT DeliverBeginFlush(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::BeginFlush method on the input pin.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DeliverEndFlush

The DeliverEndFlush method requests the connected input pin to end a flush operation.

Syntax

virtual HRESULT DeliverEndFlush(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::EndFlush method on the input pin.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DeliverEndOfStream

The DeliverEndOfStream method delivers an end-of-stream notification to the connected input pin.

Syntax

virtual HRESULT DeliverEndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::EndOfStream method on the input pin.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::DeliverNewSegment

The DeliverNewSegment method delivers a new-segment notification to the connected input pin.

Syntax

virtual HRESULT DeliverNewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart

Starting media position of the segment, in 100-nanosecond units.

tStop

End media position of the segment, in 100-nanosecond units.

dRate

Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::NewSegment method on the input pin.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::EndFlush

The EndFlush method ends a flush operation. This method implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected. This method implements the IPin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::GetDeliveryBuffer

The GetDeliveryBuffer method retrieves a media sample that contains an empty buffer.

Syntax

virtual HRESULT GetDeliveryBuffer(
    IMediaSample **ppSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags
);

Parameters

ppSample

Address of a variable that receives a pointer to the buffer's IMediaSample interface.

pStartTime

Pointer to the start time of the sample, or NULL.

pEndTime

Pointer to the ending time of the sample, or NULL.

dwFlags

Bitwise combination of flags supported by the IMemAllocator::GetBuffer interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
E_NOINTERFACE | No allocator available.

Remarks

This method calls the IMemAllocator::GetBuffer method on the allocator, and passes the parameters to that method.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::Inactive

The Inactive method notifies the pin that the filter is no longer active.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ALLOCATOR | No memory allocator is available.

Remarks

This method overrides the CBasePin::Inactive method. It calls the IMemAllocator::Decommit method to decommit the memory allocator.

If you override this method, call the base-class method from your overriding method.

See Also

  • CBaseOutputPin Class


CBaseOutputPin::InitAllocator

The InitAllocator method creates a memory allocator.

Syntax

virtual HRESULT InitAllocator(
    IMemAllocator **ppAlloc
);

Parameters

ppAlloc

Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an error code from the CoCreateInstance function.

Remarks

If the input pin does not provide a memory allocator, the CBaseOutputPin::DecideAllocator method calls this method to create an allocator.

See Also

  • CBaseOutputPin Class


CBasePin Class

CBasePin Class Hierarchy

The CBasePin class is an abstract class that implements a generic pin.

The following topics describe how to use this class:

  • CBasePin Connection Process
  • Notifying CBasePin of Filter State Changes
  • Deriving from CBasePin

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pName | Pin name.
m_Connected | Pointer to the pin that is connected to this pin.
m_dir | Direction of the pin.
m_pLock | Pointer to a critical section object.
m_bRunTimeError | Flag that indicates whether a run-time error has occurred.
m_bCanReconnectWhenActive | Flag that indicates whether the pin supports dynamic reconnection.
m_bTryMyTypesFirst | Flag that indicates whether the pin tries its own preferred media types before those of the receiving pin.
m_pFilter | Pointer to the filter that created the pin.
m_pQSink | Pointer to the object that handles quality messages.
m_TypeVersion | Current version of the set of preferred media types.
m_mt | Media type for the current pin connection.
m_tStart | Segment start time.
m_tStop | Segment stop time.
m_dRate | Segment rate.
Protected Methods |
DisplayPinInfo | Traces a pin connection during debugging.
DisplayTypeInfo | Displays media type information during debugging.
AttemptConnection | Connects to another pin using a specified media type.
TryMediaTypes | Given a list of media types, tries to complete a connection using one of those types.
AgreeMediaType | Searches for a media type to make a pin connection.
DisconnectInternal | Breaks the current pin connection.
Public Methods |
CBasePin | Constructor method.
~CBasePin | Destructor method. Virtual.
IsConnected | Determines whether the pin is connected to another pin.
GetConnected | Retrieves the pin that is connected to this pin.
IsStopped | Determines whether the filter containing this pin is stopped.
GetMediaTypeVersion | Retrieves a version number for the set of preferred media types. Virtual.
IncrementTypeVersion | Increments the version number on the set of preferred media types.
Active | Notifies the pin that the filter is now active. Virtual.
Inactive | Notifies the pin that the filter is no longer active. Virtual.
Run | Notifies the pin that the filter is now running. Virtual.
SetMediaType | Sets the media type for the connection. Virtual.
CheckConnect | Determines whether a pin connection is suitable. Virtual.
BreakConnect | Releases the pin from a connection. Virtual.
CompleteConnect | Completes a connection to another pin. Virtual.
GetMediaType | Retrieves a preferred media type, by index value. Virtual.
CurrentStopTime | Retrieves the segment stop time.
CurrentStartTime | Retrieves the segment start time.
CurrentRate | Retrieves the segment rate.
Name | Retrieves the pin identifier.
SetReconnectWhenActive | Specifies whether the pin supports dynamic reconnections.
CanReconnectWhenActive | Queries whether the pin supports dynamic reconnections.
Pure Virtual Methods |
CheckMediaType | Determines if the pin accepts a specific media type.
IPin Methods |
Connect | Connects the pin to another pin.
ReceiveConnection | Accepts a connection from another pin.
Disconnect | Breaks the current pin connection.
ConnectedTo | Retrieves the pin connected to this pin.
ConnectionMediaType | Retrieves the media type for the current pin connection, if any.
QueryPinInfo | Retrieves information about the pin.
QueryDirection | Retrieves the direction of the pin (input or output).
QueryId | Retrieves the pin identifier.
QueryAccept | Determines whether the pin accepts a specified media type.
EnumMediaTypes | Enumerates the pin's preferred media types.
QueryInternalConnections | Retrieves the pins that are connected internally to this pin (within the filter).
EndOfStream | Notifies the pin that no additional data is expected.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
IQualityControl Methods |
Notify | Notifies the pin that a quality change is requested.
SetSink | Sets an external quality manager.


CBasePin Connection Process

This section describes how the CBasePin class implements the pin connection process.

The Filter Graph Manager initiates all pin connections. It calls the output pin's IPin::Connect method, specifying the input pin. The output pin completes the connection by calling the input pin's IPin::ReceiveConnection method. The input pin can accept or reject the connection.

The Filter Graph Manager can also specify a media type for the connection. If so, the pins try to connect with that type. If not, the pins must negotiate the type. The Filter Graph Manager may also specify a partial media type, which has the value GUID_NULL for either the major type, subtype, or format type. In that case, the pins try to match whichever portions of the media type were specified; the value GUID_NULL acts as a wildcard.

The CBasePin::Connect method starts by verifying that the pin can accept a connection. For example, it checks that the pin is not already connected. It delegates the rest of the connection process to the CBasePin::AgreeMediaType method. Everything that follows is performed by AgreeMediaType.

If the media type is fully specified, the pin calls the CBasePin::AttemptConnection method to attempt the connection. Otherwise, it tries media types in the following order:

  1. The input pin's preferred types.
  2. The output pin's preferred types.

You can reverse this order by setting the CBasePin::m_bTryMyTypesFirst flag to TRUE.

In each case, the pin calls IPin::EnumMediaTypes to enumerate the media types. This method retrieves an enumerator object, which is passed to the CBasePin::TryMediaTypes method. The TryMediaTypes method loops through each media type and calls AttemptConnection for each type.

Within the AttemptConnection method, the output pin calls the following methods:

  • It calls CBasePin::CheckConnect on itself, to check whether the input pin is suitable.
  • It calls CBasePin::CheckMediaType on itself, to validate the media type.
  • It calls IPin::ReceiveConnection on the input pin. The input pin uses this method to determine whether it should accept the connection.
  • It calls CBasePin::CompleteConnect on itself to completes the connection.

Note the following:

  • CheckConnect is a virtual method. In the base class, this method checks whether the pin directions are compatible. Output pins must connect to input pins, and vice versa. The derived pin class will typically override this method to perform other checks. For example, it might query the other pin for an interface that is required for the connection. If the derived class overrides CheckConnect, it should also call the CBasePin method.
  • CheckMediaType is a pure virtual method, which the derived class must implement.
  • CompleteConnect is a virtual method that does nothing in the base class. Derived classes can override this method to perform any additional work needed to complete the connection, such as deciding a memory allocator.

If any of these steps fails, the output pin calls the CBasePin::BreakConnect method to undo whatever steps were taken by CheckConnect.

The input pin's ReceiveConnection method calls the input pin's CheckConnect, CheckMediaType, and CompleteConnect methods. If any of these fail, the connection attempt also fails.

The following diagram shows the connection process in CBasePin:

CBasePin Connection Process


Notifying CBasePin of Filter State Changes

The CBasePin class is notified whenever the state of the owning filter changes. For each state transition, the filter calls a corresponding method on the pin, as shown in the following table.

New Filter State | CBasePin Method
Stopped | CBasePin::Inactive
Paused | CBasePin::Active
Running | CBasePin::Run

The derived class should override these methods to respond to the state change. Depending on the filter, the pin might start a worker thread that delivers samples, commit or decommit its memory allocator, and so forth.


Deriving from CBasePin

To implement a pin using CBasePin, you must derive a new class from the base class and override several of its methods. You must override the following methods:

  • CBasePin::CheckMediaType
  • CBasePin::GetMediaType

You will probably need to override these additional methods:

  • CBasePin::Active
  • CBasePin::BreakConnect
  • CBasePin::CheckConnect
  • CBasePin::CompleteConnect
  • CBasePin::EndOfStream
  • CBasePin::Inactive
  • CBasePin::Notify
  • CBasePin::Run

Finally, you must must implement the IPin::BeginFlush and IPin::EndFlush methods.

Some of these methods are implemented in base classes that derive from CBasePin, such as CBaseInputPin and CBaseOutputPin.


CBasePin::m_pName

Pin name.

Syntax

WCHAR *m_pName;

Remarks

The CBasePin::QueryPinInfo method returns this string as the pin name, and the CBasePin::QueryId method returns it as the pin identifier. In general, however, the pin name and the pin identifier are not required to be the same. The pin identifier is used for graph persistence. For more information, see IBaseFilter::FindPin.

See Also

  • CBasePin Class


CBasePin::m_Connected

Pointer to the pin that is connected to this pin.

Syntax

IPin *m_Connected;

See Also

  • CBasePin Class


CBasePin::m_dir

Direction of the pin.

Syntax

PIN_DIRECTION m_dir;

See Also

  • CBasePin Class


CBasePin::m_pLock

Pointer to a critical section object that protects the filter state.

Syntax

CCritSec *m_pLock;

See Also

  • CBasePin Class
  • Threads and Critical Sections


CBasePin::m_bRunTimeError

Flag that indicates whether a run-time error has occurred.

Syntax

bool m_bRunTimeError;

Remarks

This flag defaults to FALSE. Set the flag to TRUE if a run-time error occurs during streaming. The CBasePin::Inactive method resets the flag to FALSE.

See Also

  • CBasePin Class


CBasePin::m_bCanReconnectWhenActive

Flag that indicates whether the pin supports dynamic reconnection.

Syntax

bool m_bCanReconnectWhenActive;

Remarks

This flag defaults to FALSE.

See Also

  • CBasePin Class


CBasePin::m_bTryMyTypesFirst

Flag that indicates whether the pin tries its own preferred media types before those of the receiving pin.

Syntax

bool m_bTryMyTypesFirst;

Remarks

This flag defaults to FALSE. If the flag is TRUE, the CBasePin::AgreeMediaType method reverses the order in which it tries media types.

See Also

  • CBasePin Class


CBasePin::m_pFilter

Pointer to the filter that created the pin.

Syntax

CBaseFilter *m_pFilter;

See Also

  • CBasePin Class


CBasePin::m_pQSink

Pointer to the object that handles quality messages.

Syntax

IQualityControl *m_pQSink;

See Also

  • CBasePin Class


CBasePin::m_TypeVersion

Current version of the set of preferred media types.

Syntax

LONG m_TypeVersion;

See Also

  • CBasePin Class


CBasePin::m_mt

Media type for the current pin connection.

Syntax

CMediaType m_mt;

See Also

  • CBasePin Class


CBasePin::m_tStart

Segment start time.

Syntax

CRefTime m_tStart;

See Also

  • CBasePin Class


CBasePin::m_tStop

Segment stop time.

Syntax

CRefTime m_tStop;

See Also

  • CBasePin Class


CBasePin::m_dRate

Segment rate.

Syntax

double m_dRate;

See Also

  • CBasePin Class


CBasePin::Active

The Active method notifies the pin that the filter is now active.

Syntax

virtual HRESULT Active(void);

Return Value

Returns S_OK.

Remarks

When the filter goes from stopped to paused, the CBaseFilter class calls this method on all of the filter's connected pins.

This method does nothing in the base class. Derived classes can override this method; for example, a pin might commit allocators or obtain hardware resources.

The filter graph manager's internal state is not updated until after this member function returns, so do not test the state from this method.

See Also

  • CBasePin Class


CBasePin::AgreeMediaType

The AgreeMediaType method searches for a media type to make a pin connection.

Syntax

virtual HRESULT AgreeMediaType(
    IPin *pReceivePin,
    const CMediaType *pmt
);

Parameters

pReceivePin

Pointer to the receiving pin's IPin interface.

pmt

Pointer to a CMediaType object that specifies a media type, or NULL.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ACCEPTABLE_TYPES | No acceptable media type was found.

Remarks

If the pmt parameter is non-NULL and fully specifies a media type, this method attempts a connection using that media type. If the attempt fails, the method returns an error.

If the pmt parameter is NULL or specifies a partial media type, this method tries media types in the following order:

  1. The receiving pin's preferred media types.
  2. This pin's preferred media types.

Preferred media types are enumerated with the CBasePin::EnumMediaTypes method, and the resulting enumerator is passed to the CBasePin::TryMediaTypes method.

See Also

  • CBasePin Class


CBasePin::AttemptConnection

The AttemptConnection method connects to another pin using a specified media type.

Syntax

virtual HRESULT AttemptConnection(
    IPin *pReceivePin,
    const CMediaType *pmt
);

Parameters

pReceivePin

Pointer to the receiving pin's IPin interface.

pmt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
VFW_E_TYPE_NOT_ACCEPTED | The media type is not acceptable.

Remarks

This method attempts to connect the two pins with a specific media type. If the type is not acceptable, the method fails without trying other media types.

If the media type is acceptable, this method calls the receiving pin's IPin::ReceiveConnection method. Then it calls the CBasePin::CompleteConnect method to complete the connection.

See Also

  • CBasePin Class


CBasePin::BreakConnect

The BreakConnect method releases the pin from a connection.

Syntax

virtual HRESULT BreakConnect(void);

Return Value

Returns S_OK.

Remarks

This method is called during pin disconnection by the CBasePin::Disconnect method. It is also called during a connection attempt if the CBasePin::CheckConnect method fails.

This method must free any resources that were obtained by the CheckConnect method. For example, if CheckConnect allocates memory, BreakConnect should free the memory. If CheckConnect queries the connecting pin for an interface, BreakConnect should free the interface.

See Also

  • CBasePin Class


CBasePin::CanReconnectWhenActive

The CanReconnectWhenActive method queries whether the pin supports dynamic reconnections.

Syntax

bool CanReconnectWhenActive(void);

Return Value

Returns a Boolean value that specifies whether the pin can dynamically reconnect. If TRUE, the pin can dynamically reconnect.

Remarks

By default, you must stop a filter before reconnecting any of its pins. If a pin supports dynamic reconnection, however, it can reconnect while the filter is active. For more information, see Dynamic Graph Building.

See Also

  • CBasePin Class


CBasePin::CBasePin

Constructor method.

Syntax

CBasePin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName,
    PIN_DIRECTION dir
);

Parameters

pObjectName

String containing the debug name for the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin.

pLock

Pointer to a CCritSec lock, used to serialize state changes. Can be the same critical section as the filter lock, CBaseFilter::m_pLock.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Wide-character string containing the name of the pin. For more information, see CBasePin::QueryPinInfo.

dir

Member of the PIN_DIRECTION enumeration specifying the direction of the pin.

Remarks

The critical section specified by pLock serializes the pin's state, including its connection status, choice of allocator, media type, and the status of flush operations. Do not use this critical section to serialize streaming operations. For more information, see Data Flow in the Filter Graph.

A filter might create pins in its constructor method, so at this point the pFilter pointer might not refer to a valid object. Store the pointer, but do not dereference it while inside the pin's constructor.

See Also

  • CBasePin Class


CBasePin::~CBasePin

Destructor method.

Syntax

CBasePin(void);

See Also

  • CBasePin Class


CBasePin::CheckConnect

The CheckConnect method determines whether a pin connection is suitable.

Syntax

virtual HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin

Pointer to the other pin's IPin interface.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_E_INVALID_DIRECTION | Pin directions are not compatible.

Remarks

This method is called on both pins at the start of the connection process. The connecting pin calls it from within the CBasePin::Connect method, and the receiving pin calls it from within the CBasePin::ReceiveConnection method.

Use this method to determine whether the pin specified by the pPin parameter is suitable for a connection. The base class returns an error if both pins have the same direction (both input, or both output). Derived classes can override this method to verify other features in the pin. For example, the CBaseOutputPin class queries the input pin for its IMemInputPin interface.

If this method fails, the connection fails and the pin calls the CBasePin::BreakConnect method. Use BreakConnect to free any resources obtained in CheckConnect. For example, if CheckConnect calls the QueryInterface method, BreakConnect must release the interface.

See Also

  • CBasePin Class


CBasePin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type.

Syntax

virtual HRESULT CheckMediaType(
    const CMediaType *pmt
) PURE;

Parameters

pmt

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

The derived class must override this pure virtual method.

See Also

  • CBasePin Class


CBasePin::CompleteConnect

The CompleteConnect method completes a connection to another pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the other pin's IPin interface.

Return Value

Returns S_OK.

Remarks

This method is called on both pins at the end of the connection process. The connecting pin calls it from within the CBasePin::Connect method, and the receiving pin calls it from within the CBasePin::ReceiveConnection method.

In the base class, this method simply returns S_OK. If a derived class has any requirements for completing a connection, it should override this method. For example, the CBaseOutputPin class uses this method to decide the memory allocator.

If this method fails, the overall connection attempt also fails, and the pin disconnects from the receiving pin.

See Also

  • CBasePin Class


CBasePin::Connect

The Connect method connects the pin to another pin. This method implements the IPin::Connect method.

Syntax

HRESULT Connect(
    IPin *pReceivePin,
    const AM_MEDIA_TYPE *pmt
);

Parameters

pReceivePin

Pointer to the receiving pin's IPin interface.

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NO_ACCEPTABLE_TYPES | Could not find an acceptable media type.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pmt parameter can be NULL. It can also specify a partial media type, with a value of GUID_NULL for the major type, subtype, or format.

In the base class, this method tests whether the pin is already connected and whether the filter is stopped. It delegates the rest of the connection process to the CBasePin::AgreeMediaType method.

See Also

  • CBasePin Class


CBasePin::ConnectedTo

The ConnectedTo method retrieves a pointer to the connected pin, if any. This method implements the IPin::ConnectedTo method.

Syntax

HRESULT ConnectedTo(
    IPin **ppPin
);

Parameters

ppPin

Address of a variable that receives a pointer to the IPin interface of the other pin.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release it when you are done.

See Also

  • CBasePin Class


CBasePin::ConnectionMediaType

The ConnectionMediaType method retrieves the media type for the current pin connection, if any. This method implements the IPin::ConnectionMediaType method.

Syntax

HRESULT ConnectionMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the pin is connected, this method copies the media type into the AM_MEDIA_TYPE structure specified by pmt. The caller must free the media type's format block. You can use the Microsoft® Win32® CoTaskMemFree function, or the FreeMediaType helper function.

If the pin is not connected, this method zeroes the memory block specified by pmt and returns an error code.

See Also

  • CBasePin Class


CBasePin::CurrentRate

The CurrentRate method retrieves the segment rate, set by the CBasePin::NewSegment method.

Syntax

double CurrentRate(void);

Return Value

Returns the value of CBasePin::m_dRate.

See Also

  • CBasePin Class


CBasePin::CurrentStartTime

The CurrentStartTime method retrieves the segment start time, set by the CBasePin::NewSegment method.

Syntax

REFERENCE_TIME CurrentStartTime(void);

Return Value

Returns the value of CBasePin::m_tStart.

See Also

  • CBasePin Class


CBasePin::CurrentStopTime

The CurrentStopTime method retrieves the segment stop time, set by the CBasePin::NewSegment method.

Syntax

REFERENCE_TIME CurrentStopTime(void);

Return Value

Returns the value of CBasePin::m_tStop.

See Also

  • CBasePin Class


CBasePin::Disconnect

The Disconnect method breaks the current pin connection. This method implements the IPin::Disconnect method.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.

Remarks

The base class delegates most of the work to the CBasePin::DisconnectInternal method.

See Also

  • CBasePin Class


CBasePin::DisconnectInternal

The DisconnectInternal method breaks the current pin connection.

Syntax

HRESULT DisconnectInternal(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.

Remarks

The CBasePin::Disconnect method delegates the disconnect process to this method. This method calls the CBasePin::BreakConnect method. It also releases the reference count on the other pin, which is held by the CBasePin::m_Connected member variable.

See Also

  • CBasePin Class


CBasePin::DisplayPinInfo

The DisplayPinInfo method traces a pin connection during debugging.

Syntax

void DisplayPinInfo(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the receiving pin.

Remarks

In debug builds, this method calls the DbgLog function to trace a connection attempt. In retail builds, this method does nothing.

See Also

  • CBasePin Class


CBasePin::DisplayTypeInfo

The DisplayTypeInfo method displays media type information during debugging.

Syntax

void DisplayTypeInfo(
    IPin *pPin,
    const CMediaType *pmt
);

Parameters

pPin

Ignored.

pmt

Pointer to a CMediaType object that specifies the media type.

Remarks

In debug builds, this method calls the DbgLog function to display the specified media type. In retail builds, this method does nothing.

See Also

  • CBasePin Class


CBasePin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected. This method implements the IPin::EndOfStream method. Call this method only on input pins.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns S_OK.

Remarks

The filter should pass end-of-stream notifications downstream, to the input pins of connected filters. If the filter is a renderer, it should post an EC_COMPLETE event notification to the filter graph manager. For more information, see Data Flow in the Filter Graph.

In the base class, this method does nothing. Derived classes should override this method.

See Also

  • CBasePin Class


CBasePin::EnumMediaTypes

The EnumMediaTypes method enumerates the pin's preferred media types. This method implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Input pins are not required to enumerate any preferred types. Output pins must enumerate at least one preferred type. Otherwise, both pins could lack a preferred type, making a connection impossible.

The IEnumMediaTypes interface works like a standard COM enumerator. For more information, see Enumerating Objects in a Filter Graph. If the method succeeds, the IEnumMediaTypes interface has an outstanding reference count. Be sure to release it when you are done.

The CEnumMediaTypes base class implements IEnumMediaTypes. It calls the pin's CBasePin::GetMediaType method to enumerate the media types.

See Also

  • CBasePin Class


CBasePin::GetConnected

The GetConnected method retrieves the pin connected to this pin.

Syntax

IPin *GetConnected(void);

Return Value

Returns a pointer to the other pin's IPin interface.

Remarks

If the pin is not connected, this method returns NULL. Call the CBasePin::IsConnected method to determine whether the pin is connected.

The method does not call AddRef on the IPin interface, so the caller should not release the interface.

Example Code

Because the reference count is not incremented on the returned pointer, you can chain method calls together:

if (m_MyPin->IsConnected())
{
    m_MyPin->GetConnected()->EndOfStream();
}

This coding pattern is very convenient; but as the example shows, you must be careful not to dereference a NULL pointer when the pin is unconnected.

See Also

  • CBasePin Class


CBasePin::GetMediaType

The GetMediaType method retrieves a preferred media type, by index value.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition

Zero-based index value.

pMediaType

Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.
E_UNEXPECTED | Unexpected error.

Remarks

From the pin's list of preferred media types, this method returns the type with an index value of iPosition. The CEnumMediaTypes class calls this method to enumerate preferred media types.

The base class returns E_UNEXPECTED. Override this method in your derived class.

See Also

  • CBasePin Class


CBasePin::GetMediaTypeVersion

The GetMediaTypeVersion method retrieves a version number for the set of preferred media types.

Syntax

virtual LONG GetMediaTypeVersion(void);

Return Value

Returns the CBasePin::m_TypeVersion member variable.

Remarks

The CBasePin constructor initializes the version number to 1. In the base class, this number never changes. If the pin dynamically changes its list of preferred media types, it should increment the version number whenever the list changes. To increment the version number, call the CBasePin::IncrementTypeVersion method.

The media type enumerator, which is implemented by the CEnumMediaTypes class, uses the version number to keep itself synchronized with the pin.

See Also

  • CBasePin Class


CBasePin::Inactive

The Inactive method notifies the pin that the filter is no longer active.

Syntax

virtual HRESULT Inactive(void);

Return Value

Returns S_OK.

Remarks

When the filter stops, the CBaseFilter class calls this method on all of the filter's connected pins.

This method does nothing in the base class. Derived classes should override this method to free any resources obtained by the CBasePin::Active method; for example, to decommit the pin's allocators.

The filter graph manager's internal state is not updated until after this method returns, so do not test the state from this method.

See Also

  • CBasePin Class


CBasePin::IncrementTypeVersion

The IncrementTypeVersion method increments the version number on the set of preferred media types.

Syntax

void IncrementTypeVersion(void);

Remarks

This method increments the CBasePin::m_TypeVersion member variable. If the pin dynamically changes the list of preferred media types, call this method whenever the list changes. For more information, see CBasePin::GetMediaTypeVersion.

See Also

  • CBasePin Class


CBasePin::IsConnected

The IsConnected method determines whether the pin is connected to another pin.

Syntax

BOOL IsConnected(void);

Return Value

Returns TRUE if the pin is connected. Otherwise, returns FALSE.

See Also

  • CBasePin Class


CBasePin::IsStopped

The IsStopped method determines whether the filter containing this pin is stopped.

Syntax

BOOL IsStopped(void);

Return Value

Returns TRUE if the filter is stopped. Otherwise, returns FALSE.

Remarks

Do not call this method from within in the CBasePin constructor method, because the filter might not be initialized yet.

See Also

  • CBasePin Class


CBasePin::Name

The Name method retrieves the pin identifier.

Syntax

LPWSTR Name(void);

Return Value

Returns the value of the CBasePin::m_pName member variable.

See Also

  • CBasePin Class


CBasePin::NewSegment

The NewSegment method notifies the pin that media samples received after this call are grouped as a segment. Implements the IPin::NewSegment method.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart

Starting media position of the segment, in 100-nanosecond units.

tStop

End media position of the segment, in 100-nanosecond units.

dRate

Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns S_OK.

Remarks

This method sets the CBasePin::m_tStart, CBasePin::m_tStop, and CBasePin::m_dRate member variables. In your derived class, override this method to pass the notification downstream.

See Also

  • CBasePin Class


CBasePin::Notify

The Notify method notifies the pin that a quality change is requested. This method implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf

Pointer to the IBaseFilter interface of the filter that delivered the quality-control message.

q

Specifies a Quality structure that contains the quality-control message.

Return Value

The base class returns E_NOTIMPL.

Remarks

Output pins should override this method to accept quality-control messages.

If an external quality manager was installed (see CBasePin::SetSink), pass the message to that quality manager. Otherwise, the filter should handle the message itself, or pass the message upstream. For more information, see Quality-Control Management.

See Also

  • CBasePin Class


CBasePin::QueryAccept

The QueryAccept method determines whether the pin accepts a specified media type. This method implements the IPin::QueryAccept method.

Syntax

HRESULT QueryAccept(
    const AM_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns S_OK if the media type is acceptable. Otherwise, returns S_FALSE.

Remarks

In the base class, this method delegates to the CBasePin::CheckMediaType method. If CheckMediaType fails, QueryAccept returns S_FALSE.

This method does not hold the pin's critical section (CBasePin::m_pLock). If your derived class dynamically modifies the set of acceptable media types, you should override this method to hold the critical section.

See Also

  • CBasePin Class


CBasePin::QueryDirection

The QueryDirection method retrieves the direction of the pin (input or output). This method implements the IPin::QueryDirection method.

Syntax

HRESULT QueryDirection(
    PIN_DIRECTION *pPinDir
);

Parameters

pPinDir

Pointer to a variable that receives a member of the PIN_DIRECTION enumerated type.

Return Value

Returns S_OK or E_POINTER.

See Also

  • CBasePin Class


CBasePin::QueryId

The QueryId method retrieves the pin identifier. This method implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id

Pointer to the pin identifier.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.

Remarks

This method returns a copy of the CBasePin::m_pName member variable.

See Also

  • CBasePin Class


CBasePin::QueryInternalConnections

The QueryInternalConnections method retrieves the pins that are connected internally to this pin (within the filter). This method implements the IPin::QueryInternalConnections method.

Syntax

HRESULT QueryInternalConnections(
    IPin *apPin,
    ULONG *nPin
);

Parameters

apPin

Address of an array of IPin pointers.

nPin

On input, specifies the size of the array. When the method returns, the value is set to the number of pointers returned in the array.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Insufficient array size.
S_OK | Success.
E_FAIL | Failure.
E_NOTIMPL | Not implemented.

The base class returns E_NOTIMPL.

Remarks

On some filters, input pins correspond to particular output pins. For each pin, this method fills an array with pointers to the corresponding pins. If every input pin provides data for every output pin, return E_NOTIMPL.

See Also

  • CBasePin Class


CBasePin::QueryPinInfo

The QueryPinInfo method retrieves information about the pin. This method implements the IPin::QueryPinInfo method.

Syntax

HRESULT QueryPinInfo(
    PIN_INFO *pInfo
);

Parameters

pInfo

Pointer to a PIN_INFO structure that receives the pin information.

Return Value

Returns S_OK or E_POINTER.

Remarks

This method uses the CBasePin::m_pName member variable for the achName member of the PIN_INFO structure.

When the method returns, if the pFilter member of the PIN_INFO structure is non-NULL, it has an outstanding reference count. Be sure to release the interface when you are done.

See Also

  • CBasePin Class


CBasePin::ReceiveConnection

The ReceiveConnection method accepts a connection from another pin. This method implements the IPin::ReceiveConnection method.

Syntax

HRESULT ReceiveConnection(
    IPin *pConnector,
    AM_MEDIA_TYPE *pmt
);

Parameters

pConnector

Pointer to the connecting pin's IPin interface.

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The output pin calls this method on the input pin. If the input pin returns an error code, the connection fails.

In the base class, this method performs the following steps:

  • Checks whether the pin is already connected.
  • Checks whether the filter is stopped.
  • Calls the CBasePin::CheckConnect method to test whether the connecting pin is suitable.
  • Calls the CBasePin::CheckMediaType method to test whether the media type is acceptable.

If all of these steps succeed, the method calls the CBasePin::CompleteConnect and SetMediaType methods to complete the connection. These methods store the media type and a pointer to the output pin.

If CheckConnect or CheckMediaType fail, the base class calls the CBasePin::BreakConnect method to break the connection and then returns an error code from ReceiveConnection.

See Also

  • CBasePin Class


CBasePin::Run

The Run method notifies the pin that the filter is now running.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart

Start time as passed to the filter's IMediaFilter::Run method.

Return Value

Returns S_OK.

Remarks

When the filter goes from paused to running, the CBaseFilter class calls this method on all of the filter's pins.

This method does nothing in the base class. Derived classes can override this method. For example, a pin might start a worker thread that delivers samples.

The filter graph manager's internal state is not updated until after this member function returns, so do not test the state from this method.

See Also

  • CBasePin Class


CBasePin::SetMediaType

The SetMediaType method sets the media type for the connection.

Syntax

virtual HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method establishes the format for a pin connection. Before calling this method, the pin calls the CBasePin::CheckMediaType method to determine whether the media type is acceptable. Therefore, the pmt parameter is assumed to be an acceptable media type.

In the base class, this method sets the CBasePin::m_mt member variable and returns S_OK. A derived class can override this method if it requires notification when the media type is set.

See Also

  • CBasePin Class


CBasePin::SetReconnectWhenActive

The SetReconnectWhenActive method specifies whether the pin supports dynamic reconnections.

Syntax

void SetReconnectWhenActive(
    bool bCanReconnect
);

Parameters

bCanReconnect

Boolean value that specifies whether the pin can dynamically reconnect. If TRUE, the pin can dynamically reconnect.

Remarks

By default, you must stop a filter before reconnecting any of its pins. If the pin can reconnect while the filter is active, call this method with a value of TRUE. For more information, see Dynamic Graph Building.

See Also

  • CBasePin Class


CBasePin::SetSink

The SetSink method sets an external quality manager. This method implements the IQualityControl::SetSink method.

Syntax

HRESULT SetSink(
    IQualityControl *piqc
);

Parameters

piqc

Pointer to the IQualityControl interface of the quality manager.

Return Value

Returns S_OK.

Remarks

Call this method to redirect quality-control messages to an external quality manager. For more information, see Quality-Control Management.

See Also

  • CBasePin Class


CBasePin::TryMediaTypes

Given a list of media types, the TryMediaTypes method tries to complete a connection using one of those types.

Syntax

virtual HRESULT TryMediaTypes(
    IPin *pReceivePin,
    const CMediaType *pmt,
    IEnumMediaTypes *pEnum
);

Parameters

pReceivePin

Pointer to the receiving pin's IPin interface.

pmt

Pointer to a CMediaType object that limits the possible media types, or NULL.

pEnum

Pointer to an IEnumMediaTypes interface, used to enumerate the list of media types.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ACCEPTABLE_TYPES | Did not find an acceptable media type.

Remarks

For each media type returned by the IEnumMediaTypes interface, this method attempts a connection by calling the CBasePin::AttemptConnection method.

If the pmt parameter is non-NULL, the pin skips media types that do not match this type. The pmt parameter can specify a partial media type. A partial media type has a value of GUID_NULL for either the major type, the subtype, or the format. The GUID_NULL value matches any type, similar to a "wildcard" value.

See Also

  • CBasePin Class


CBasePropertyPage Class

CBasePropertyPage Class Hierarchy

The CBasePropertyPage class is an abstract class for implementing a property page. Use this class if you are writing a filter (or other object) that supports property pages.

A property page is a COM object, so you must generate a GUID for the class identifier (CLSID) and provide an entry in the CFactoryTemplate array. For more information, see DirectShow and COM. The following example shows a typical class factory entry:

CFactoryTemplate g_Templates[] =
{
    {
        L"My Property Page",
        &CLSID_MyPropPage,
        CMyProp::CreateInstance,
        NULL,
        NULL
    },
    /* Also include the template for your filter (not shown). */
};

Your filter must expose the ISpecifyPropertyPages interface. This interface contains a single method, GetPages, which returns the CLSID of the property page. The following example shows how to implement this method:

STDMETHODIMP CMyFilter::GetPages(CAUUID *pPages)
{
    if (!pPages) return E_POINTER;

    pPages->cElems = 1;
    pPages->pElems = reinterpret_cast<GUID*>(CoTaskMemAlloc(sizeof(GUID)));
    if (pPages->pElems == NULL)
    {
        return E_OUTOFMEMORY;
    }
    *(pPages->pElems) = CLSID_MyPropPage;
    return S_OK;
}

Remember to override the filter's NonDelegatingQueryInterface method as well. For more information, see DirectShow and COM and INonDelegatingUnknown.

Next, create the dialog as a resource in your project, and create a string resource that holds the dialog title. Both of these resource IDs are parameters to the CBasePropertyPage constructor. Keeping the title string in a resource makes it easier to localize your property page.

The CBasePropertyPage class provides a framework for the IPropertyPage interface. This framework calls a number of virtual methods, including CBasePropertyPage::OnActivate, CBasePropertyPage::OnApplyChanges, and so on. In the base class, these methods simply return S_OK. Your derived class will need to override some or all of these virtual methods. For details, see the remarks for the individual methods.

Requirements

Header: Declared in Cprop.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_bDirty | Indicates whether any of the properties have changed.
m_DialogId | Resource identifier for the dialog.
m_Dlg | Handle to the dialog window.
m_hwnd | Handle to the dialog window.
m_pPageSite | Pointer to the IPropertyPageSite interface of the property page site.
m_TitleId | Resource identifier for a string that contains the dialog title.
Public Methods |
CBasePropertyPage | Constructor method.
~CBasePropertyPage | Destructor method. Virtual.
OnActivate | Called when the property page is activated. Virtual.
OnApplyChanges | Called when the user applies changes to the property page. Virtual.
OnConnect | Provides an IUnknown pointer to the object associated with the property page. Virtual.
OnDeactivate | Called when the dialog box window is destroyed. Virtual.
OnDisconnect | Called when the property page should release the associated object. Virtual.
OnReceiveMessage | Called when the dialog box receives a message. Virtual.
IPropertyPage Methods |
Activate | Creates the dialog box window.
Apply | Applies the current property page values to the object associated with the property page
Deactivate | Destroys the dialog window.
GetPageInfo | Retrieves information about the property page.
Help | Invokes the property page help.
IsPageDirty | Indicates whether the property page has changed since it was activated or since the most recent call to IPropertyPage::Apply.
Move | Positions and resizes the dialog box.
SetObjects | Provides IUnknown pointers for the objects associated with the property page.
SetPageSite | Initializes the property page.
Show | Shows or hides the dialog box.
TranslateAccelerator | Instructs the property page to process a keystroke.


CBasePropertyPage::m_bDirty

The m_bDirty flag indicates whether any of the properties have changed. Set this flag to TRUE if the user changes any properties through the dialog controls.

Syntax

BOOL m_bDirty;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::m_DialogId

The m_DialogId member variable specifies the resource identifier for the dialog. This variable is initialized in the constructor method.

Syntax

int m_DialogId;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::m_Dlg

The m_Dlg member variable contains a handle to the dialog window. This member variable is initialized when the dialog window processes the WM_INITDIALOG message.

Syntax

HWND m_Dlg;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::m_hwnd

The m_hwnd member variable contains a handle to the dialog window. This member variable is initialized after the object creates the dialog window, when the CreateDialogParam function returns.

Syntax

HWND m_Dlg;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::m_pPageSite

The m_pPageSite member variable contains a pointer to the IPropertyPageSite interface of the property page site.

Syntax

IPropertyPageSite* m_pPageSite;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::m_TitleId

The m_pPageSite member variable specifies a resource identifier for a string that contains the dialog title. This variable is initialized in the constructor method.

Syntax

int m_TitleId;

See Also

  • CBasePropertyPage Class


CBasePropertyPage::Activate

The Activate method creates the dialog box window. This method implements the IPropertyPage::Activate method.

Syntax

HRESULT Activate(
    HWND hwndParent,
    LPCRECT prect,
    BOOL fModal
);

Parameters

hwndParent

Handle to the parent window of the dialog box.

prect

Pointer to a RECT structure that contains positioning information for the dialog box.

fModal

Boolean value indicating whether the dialog box frame is modal (TRUE) or modeless (FALSE).

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected failure.

See Also

  • CBasePropertyPage Class
  • CBasePropertyPage::OnActivate


CBasePropertyPage::Apply

The Apply method applies the current property page values to the object associated with the property page. This method implements the IPropertyPage::Apply method.

Syntax

HRESULT Apply(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | Unexpected failure.

Remarks

If the CBasePropertyPage::m_bDirty flag is TRUE, this method calls the CBasePropertyPage::OnApplyChanges method. Override OnApplyChanges to apply the changes to the object.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::CBasePropertyPage

Constructor method.

Syntax

CBasePropertyPage(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    int DialogId,
    int TitleId
);

Parameters

pName

String that contains the name of the object, for debugging purposes. For more information, see CBaseObject::CBaseObject.

pUnk

Pointer to the aggregating IUnknown interface.

DialogId

Resource ID for the dialog box.

TitleId

Resource ID for the string that contains the dialog box title.

Example Code

CMyProp::CMyProp(IUnknown *pUnk) :
    CBasePropertyPage(NAME("MyPropPage"), pUnk, IDD_PROPPAGE, IDS_TITLE),

See Also

  • CBasePropertyPage Class


CBasePropertyPage::~CBasePropertyPage

Destructor method.

Syntax

~CBasePropertyPage(void);

See Also

  • CBasePropertyPage Class


CBasePropertyPage::Deactivate

The Deactivate method destroys the dialog window. This method implements the IPropertyPage::Deactivate method.

Syntax

HRESULT Deactivate(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | Unexpected failure.

See Also

  • CBasePropertyPage Class
  • CBasePropertyPage::OnDeactivate


CBasePropertyPage::GetPageInfo

The GetPageInfo method retrieves information about the property page. This method implements the IPropertyPage::GetPageInfo method.

Syntax

HRESULT GetPageInfo(
    LPPROPPAGEINFO pPageInfo
);

Parameters

pPageInfo

Pointer to a caller-allocated PROPPAGEINFO structure.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::Help

The Help method invokes the property page help. This method implements the IPropertyPage::Help method.

Syntax

HRESULT Help(
    LPCWSTR lpszHelpDir
);

Parameters

lpszHelpDir

Pointer to the string under the HelpDir key in the property page's CLSID information in the registry.

Return Value

Returns E_NOTIMPL.

Remarks

In the base class, the method always returns E_NOTIMPL. When the method fails, the frame calls IPropertyPage::GetPageInfo to get the name of the help file and context identifier. By default, these are NULL. To provide help, therefore, the derived class can override either the Help method or the CBasePropertyPage::GetPageInfo method.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::IsPageDirty

The IsPageDirty method indicates whether the property page has changed since it was activated or since the most recent call to IPropertyPage::Apply. This method implements the IPropertyPage::IsPageDirty method.

Syntax

HRESULT IsPageDirty(void);

Return Value

Returns S_OK if CBasePropertyPage::m_bDirty is TRUE, or S_FALSE otherwise.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::Move

The Move method positions and resizes the dialog box. This method implements the IPropertyPage::Move method.

Syntax

HRESULT Move(
    LPCRECT prect
);

Parameters

prect

Pointer to a RECT structure containing the positioning information.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected failure.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnActivate

The OnActivate method is called when the property page is activated.

Syntax

virtual HRESULT OnActivate(void);

Return Value

The base-class implementation returns S_OK.

Remarks

The CBasePropertyPage::Activate method calls the OnActivate method. In your derived class, override OnActivate to initialize the dialog box.

Example Code

The following example initializes a trackbar control. This example assumes that m_pOwningFilter is a pointer to a custom interface on the filter associated with the property page. (Use the CBasePropertyPage::OnConnect method to initialize such pointers.)

HRESULT CMyProp::OnActivate(void)
{
    ASSERT(m_pOwningFilter != NULL);
    m_pOwningFilter->GetSomeProperty(&m_lOldVal);

    SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETRANGE, 0, MAKELONG(0, 100));
    SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETTICFREQ, 10, 0);
    SendDlgItemMessage(m_Dlg, IDC_SLIDER1, TBM_SETPOS, 1, m_lOldVal);
    return S_OK;
}

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnApplyChanges

The OnApplyChanges method is called when the user applies changes to the property page.

Syntax

virtual HRESULT OnApplyChanges(void);

Return Value

The base-class implementation returns S_OK.

Remarks

The CBasePropertyPage::Apply method calls OnApplyChanges if the CBasePropertyPage::m_bDirty flag is TRUE. Override OnApplyChanges to process the changes and reset m_bDirty to FALSE.

Example Code

HRESULT CMyProp::OnApplyChanges(void)
{
    ASSERT(m_pOwningFilter != NULL);
    return m_pOwningFilter->SetSomeProperty(&m_lNewVal);
}

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnConnect

The OnConnect method provides an IUnknown pointer to the object associated with the property page.

Syntax

virtual HRESULT OnConnect(
    IUnknown *pUnknown
);

Parameters

pUnknown

Pointer to the IUnknown interface of the object.

Return Value

The base-class implementation returns S_OK.

Remarks

The CBasePropertyPage::SetObjects method calls the OnConnect method. Override this method to store a pointer to the object specified by pUnknown. You can either store the pUnknown pointer itself, or query that pointer for other interfaces. If you store the pUnknown pointer, call AddRef before OnConnect returns.

In the CBasePropertyPage::OnActivate method, use the stored pointer (or pointers) to retrieve initial values for the dialog properties. In the CBasePropertyPage::OnApplyChanges method, apply any changes back to the object. Release all pointers in the CBasePropertyPage::OnDisconnect method.

Example Code

HRESULT CMyProp::OnConnect(IUnknown *pUnk)
{
    ASSERT(m_pOwningFilter == NULL);
    HRESULT hr;
    // Query pUnk for the filter's custom interface.
    hr = pUnk->QueryInterface(IID_ISomeCustomInterface,
             reinterpret_cast<void**>(&m_pOwningFilter));
    return hr;
}

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnDeactivate

The OnDeactivate method is called when the dialog box window is destroyed.

Syntax

virtual HRESULT OnDeactivate(void);

Return Value

The base-class implementation returns S_OK.

Remarks

The CBasePropertyPage::Deactivate method calls the OnDeactivate method. Override OnDeactivate to release any resources that the derived class obtained in the CBasePropertyPage::OnActivate method, or to perform other tasks as needed.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnDisconnect

The OnDisconnect method is called when the property page should release the associated object.

Syntax

virtual HRESULT OnDisconnect(void);

Return Value

The base-class implementation returns S_OK.

Remarks

The CBasePropertyPage::SetObjects method calls the OnDisconnect method. Override OnDisconnect to release any pointers that were obtained in the CBasePropertyPage::OnConnect method.

Example Code

HRESULT CMyProp::OnDisconnect(void)
{
    if (m_pOwningFilter)
    {
        m_pOwningFilter->Release();
        m_pOwningFilter = NULL;
    }
    return S_OK;
}

See Also

  • CBasePropertyPage Class


CBasePropertyPage::OnReceiveMessage

The OnReceiveMessage method is called when the dialog box receives a message.

Syntax

virtual BOOL OnReceiveMessage(
    HWND hwnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hwnd

Handle to the window.

uMsg

Message.

wParam

First message parameter.

lParam

Second message parameter.

Return Value

Returns a Boolean value. The dialog procedure returns this value; for more information, see the Platform SDK documentation.

Remarks

The base-class implementation calls DefWindowProc. Override this method to handle messages that relate to the dialog controls. If the overriding method does not handle a particular message, it should call the base-class method.

If the user changes any properties via the dialog controls, set the CBasePropertyPage::m_bDirty flag to TRUE. Then call the IPropertyPageSite::OnStatusChange method on the CBasePropertyPage::m_pPageSite pointer to inform the frame.

Example Code

The following example responds to a button click by updating a member variable, which is assumed to be defined in the derived class. This example also shows a helper function for setting the property page's dirty status.

BOOL CMyProp::OnReceiveMessage(HWND hwnd,
  UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        if (LOWORD(wParam) == IDC_BUTTON1)
        {
            m_lNewVal = GetDlgItemInt(m_Dlg, IDC_EDIT1, 0, TRUE);
            SetDirty();
            return TRUE;
        }
        break;
    } // switch

    // Did not handle the message.
    return CBasePropertyPage::OnReceiveMessage(hwnd, uMsg, wParam, lParam);
}

// Helper function to update the dirty status.
void CMyProp::SetDirty()
{
    m_bDirty = TRUE;
    if (m_pPageSite)
    {
        m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
    }
}

See Also

  • CBasePropertyPage Class


CBasePropertyPage::SetObjects

The SetObjects method provides IUnknown pointers for the objects associated with the property page. This method implements the IPropertyPage::SetObjects method.

Syntax

HRESULT SetObjects(
    ULONG cObjects,
    LPUNKNOWN *ppUnk
);

Parameters

cObjects

Specifies the number of IUnknown pointers in the array specified by ppUnk.

ppUnk

Specifies an array of IUnknown pointers.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected failure.

Remarks

Although ppUnk specifies an array of IUnknown pointers, the CBasePropertyPage class is designed only to support one associated object. If cObjects is greater than 1, the method returns E_UNEXPECTED.

If cObjects equals 1, this method calls the CBasePropertyPage::OnConnect method. If cObjects equals 0, this method calls the CBasePropertyPage::OnDisconnect method. The derived class should override both of those methods; for details, see the remarks for those methods.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::SetPageSite

The SetPageSite method initializes the property page and provides a pointer to the property frame's IPropertyPageSite interface. This method implements the IPropertyPage::SetPageSite method.

Syntax

HRESULT SetPageSite(
    IPropertyPageSite *pPageSite
);

Parameters

pPageSite

Pointer to the IPropertyPageSite interface.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | Unexpected failure.

Remarks

The method stores the pPageSite pointer in the CBasePropertyPage::m_pPageSite member variable.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::Show

The Show method shows or hides the dialog box. This method implements the IPropertyPage::Show method.

Syntax

HRESULT Show(
    UINT nCmdShow
);

Parameters

nCmdShow

Value that specifies whether to show or hide the window. For more information, see the Platform SDK documentaton.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | Unexpected failure.

See Also

  • CBasePropertyPage Class


CBasePropertyPage::TranslateAccelerator

The TranslateAccelerator method instructs the property page to process a keystroke. This method implements the IPropertyPage::TranslateAccelerator method.

Syntax

HRESULT TranslateAccelerator(
    LPMSG lpMsg
);

Parameters

lpMsg

Pointer to a MSG structure describing the keystroke to process.

Return Value

Returns E_NOTIMPL.

Remarks

Override this method if you want to provide keyboard accelerators for the property page.

See Also

  • CBasePropertyPage Class


CBaseReferenceClock Class

CBaseReferenceClock Class Hierarchy

The CBaseReferenceClock class implements a reference clock.

This class implements a reference clock that supports the IReferenceClock interface. If a filter can provide a reference clock for the filter graph—for example, by accessing a hardware device—it can use this class to implement the clock.

The CBaseReferenceClock object maintains two distinct time values:

  • Internally, the CBaseReferenceClock::GetPrivateTime method returns the actual time kept by the clock.
  • Externally, the CBaseReferenceClock::GetTime method returns the reference time for the filter graph.

It is valid for the internal clock to run backward over brief periods. For example, if the clock drifts forward, the filter can adjust it backwards. (See CBaseReferenceClock::SetTimeDelta.) The GetTime method uses the time values reported by GetPrivateTime. However, the reference time is monotonically increasing; in other words, it never runs backward. Therefore, if the internal clock runs backward, GetTime continues to report the old time until the internal clock catches up.

For example, the two methods might return the following sequences:

GetPrivateTime: 105, 106, 103, 104, 105, 106, 107, 108
GetTime:        105, 106, 106, 106, 106, 106, 107, 108

On the third clock tick, the internal clock jumps backward to 103. The GetTime method continues to report 106 until the internal clock catches up.

By default, GetPrivateTime returns the system time, through a call to the timeGetTime function. A filter that is providing a reference clock from an external device can do one of the following:

  • Override GetPrivateTime to return the time from the device.
  • Monitor the discrepancy between the device time and the system time, and call SetTimeDelta to make corrections.

This class uses a CAMSchedule object to handle scheduling of advise requests. For details, see the documentation for the CAMSchedule class.

Requirements

Header: Declared in Refclock.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pSchedule | CAMSchedule object that handles scheduling tasks for the clock.
Protected Methods |
~CBaseReferenceClock | Destructor method.
Public Methods |
CBaseReferenceClock | Constructor method.
GetPrivateTime | Retrieves the real time from the clock.
SetTimeDelta | Adjusts the internal clock time.
GetSchedule | Retrieves a pointer to the clock's scheduling object.
TriggerThread | Wakes up the worker thread that handles scheduling.
IReferenceClock Methods |
GetTime | Retrieves the current reference time.
AdviseTime | Creates a one-shot advise request.
AdvisePeriodic | Creates a periodic advise request.
Unadvise | Removes a pending advise request.
Helper Functions |
ConvertToMilliseconds | Converts a reference time to milliseconds.


CBaseReferenceClock::m_pSchedule

Pointer to a CAMSchedule object that handles scheduling tasks for the clock.

Syntax

CAMSchedule * const m_pSchedule;

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::AdvisePeriodic

The AdvisePeriodic method creates a periodic advise request. This method implements the IReferenceClock::AdvisePeriodic method.

Syntax

HRESULT AdvisePeriodic(
    REFERENCE_TIME StartTime,
    REFERENCE_TIME PeriodTime,
    HSEMAPHORE hSemaphore,
    DWORD *pdwAdviseToken
);

Parameters

StartTime

Time of the first notification, in 100-nanosecond units. Must be greater than zero and less than MAX_TIME.

PeriodTime

Time between notifications, in 100-nanosecond units. Must be greater than zero.

hSemaphore

Handle to a semaphore, created by the caller.

pdwAdviseToken

Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_INVALIDARG | Invalid time values
E_OUTOFMEMORY | Failure
E_POINTER | NULL pointer argument

Remarks

At each notification time, the clock releases the semaphore specified in the hSemaphore parameter. When no further notifications are required, call the CBaseReferenceClock::Unadvise method and pass the pdwAdviseToken value returned from this call.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::AdviseTime

The AdviseTime method creates a one-shot advise request. This method implements the IReferenceClock::AdviseTime method.

Syntax

HRESULT AdviseTime(
    REFERENCE_TIME baseTime,
    REFERENCE_TIME streamTime,
    HEVENT hEvent,
    DWORD *pdwAdviseToken
);

Parameters

baseTime

Base reference time, in 100-nanosecond units.

streamTime

Stream offset time, in 100-nanosecond units.

hEvent

Handle to an event, created by the caller.

pdwAdviseToken

Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_INVALIDARG | Invalid time values
E_OUTOFMEMORY | Failure
E_POINTER | NULL pointer argument

Remarks

This method creates a one-shot advise request for the reference time baseTime + streamTime. The sum must be greater than zero and less than MAX_TIME, or the method returns E_INVALIDARG. At the requested time, the clock signals the event specified in the hEvent parameter.

To cancel the notification before the time is reached, call the CBaseReferenceClock::Unadvise method and pass the pdwAdviseToken value returned from this call. After the notification has occurred, the clock automatically clears it, so it is not necessary to call Unadvise. However, it is not an error to do so.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::CBaseReferenceClock

Constructor method.

Syntax

CBaseReferenceClock(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    CAMSchedule *pSched = NULL
);

Parameters

pName

Pointer to a string containing the name of the object. For more information, see CBaseObject.

pUnk

Pointer to the IUnknown interface of the delegating object.

phr

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

pSched

Pointer to a CAMSchedule object. If NULL, this method creates a new CAMSchedule object.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::~CBaseReferenceClock

Destructor method.

Syntax

CBaseReferenceClock(void);

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::GetPrivateTime

The GetPrivateTime method retrieves the real time from the clock.

Syntax

virtual REFERENCE_TIME GetPrivateTime(void);

Return Value

Returns the current clock time, in 100-nanosecond units.

Remarks

This method returns the real time reported by the clock. External callers use the CBaseReferenceClock::GetTime method, which calls this method. Unlike the GetTime method, the internal clock is allowed to go backward. If that happens, the GetTime method continues to return the last time that it reported, until the GetPrivateTime method catches up.

This method returns the system time. Override this method if your clock gets the time from another source.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::GetSchedule

The GetSchedule method retrieves a pointer to the clock's scheduling object.

Syntax

CAMSchedule* GetSchedule(void);

Return Value

Returns the CBaseReferenceClock::m_pSchedule member variable.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::GetTime

The GetTime method retrieves the current reference time. This method implements the IReferenceClock::GetTime method.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTime
);

Parameters

pTime

Pointer to a variable that receives the current time, in 100-nanosecond units.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
E_POINTER | NULL pointer argument.
S_FALSE | Returned time is the same as the previous value.
S_OK | Success.

Remarks

This method calls the CBaseReferenceClock::GetPrivateTime method to determine the real clock time. If the clock time is strictly greater than the previous value, GetTime uses the clock time and returns S_OK. Otherwise, GetTime uses the previous value and returns S_FALSE. Therefore, the internal clock can run backward for a short period, without causing the reference time to run backward. Instead, the reference time will "stall" at the same value until the internal clock catches up.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::SetTimeDelta

The SetTimeDelta method adjusts the internal clock time.

Syntax

HRESULT SetTimeDelta(
    const REFERENCE_TIME& TimeDelta
);

Parameters

TimeDelta

Amount to adjust the clock time, in 100-nanosecond units. A positive value moves the clock forward, and a negative value moves the clock backward.

Return Value

Returns S_OK.

Remarks

The derived class can use this method to adjust the internal clock, if it drifts from the device that is providing timing information.

The CBaseReferenceClock::GetTime method never returns decreasing values. If you adjust the clock backwards, GetTime returns the previous value until the clock reaches that value again.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::TriggerThread

The TriggerThread method wakes up the worker thread that handles scheduling.

Syntax

void TriggerThread(void);

Return Value

No return value.

Remarks

The clock uses a worker thread that calls the CAMSchedule::Advise method at appropriate times. The derived class can call TriggerThread to wake up the thread.

See Also

  • CBaseReferenceClock Class


CBaseReferenceClock::Unadvise

The Unadvise method removes a pending advise request. This method implements the IReferenceClock::Unadvise method.

Syntax

HRESULT Unadvise(
    DWORD dwAdviseToken
);

Parameters

dwAdviseToken

Identifier of the request to remove. Use the value returned by the CBaseReferenceClock::AdviseTime or CBaseReferenceClock::AdvisePeriodic methods in the pdwAdviseToken parameter.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Not found.
S_OK | Success.

See Also

  • CBaseReferenceClock Class


ConvertToMilliseconds Function

The ConvertToMilliseconds function converts a reference time to milliseconds.

Syntax

LONGLONG ConvertToMilliseconds(
    const REFERENCE_TIME& RT
);

Parameters

RT

Reference time, in 100-nanosecond units.

Return Value

Returns the reference time converted to milliseconds.

See Also

  • CBaseReferenceClock Class


CBaseRenderer Class

CBaseRenderer Class Hierarchy

The CBaseRenderer class is a base class for implementing renderer filters. It supports one input pin, implemented by the CRendererInputPin class. To use this class, declare a derived class that inherits CBaseRenderer. At a minimum, the derived class must implement the following methods, which are declared as pure virtual in the base class:

  • CBaseRenderer::CheckMediaType: Accepts or rejects proposed media types. The filter calls this method during the pin connection process.
  • CBaseRenderer::DoRenderSample: Renders a sample. The filter calls this method for every sample that it receives while running.

The base class handles state changes and synchronization issues. It also schedules samples for rendering, although it does not implement any quality-control measures. The base class also declares several "handler" methods. These are methods that the filter calls at specific points in the streaming process. They do nothing in the base class, but the derived class can override them. In the table that follows, they are listed under the heading Public Methods: Handlers.

The CBaseRenderer::OnReceiveFirstSample handler deserves special mention. The filter calls this method if it receives a sample while the filter is paused. That can occur if the graph switches from stopped to paused, or if the graph is seeked while paused. Video renderers typically use the sample to display a still frame. When the filter switches from paused to running, it sends the same sample to the CBaseRenderer::DoRenderSample method, as the first sample in the stream.

The CBaseRenderer class exposes the IMediaSeeking and IMediaPosition interfaces through the CRendererPosPassThru object. It passes all seek requests to the next filter upstream.

Scheduling

When the upstream filter calls the input pin's IMemInputPin::Receive method to deliver a sample, the pin passes this call to the filter's CBaseRenderer::Receive method. The filter either drops the sample, renders it immediately, or schedules it for rendering.

If the sample has no time stamps, or if no reference clock is available, the filter renders the sample immediately. Otherwise, the filter calls the CBaseRenderer::ShouldDrawSampleNow method to determine what to do. By default, the sample is scheduled based on its time stamps. The derived class can override ShouldDrawSampleNow to support quality control.

To schedule a sample, the filter calls the IReferenceClock::AdviseTime method, which creates an advise request. The Receive method then blocks until the scheduled time, or until the filter changes state. Blocking prevents the upstream filter from delivering more samples until the current sample is rendered.

When the upstream filter calls the IPin::EndOfStream method to signal the end of the stream, the filter sends an EC_COMPLETE event to the filter graph manager. The filter waits for the current sample's stop time before sending the event.

Requirements

Header: Declared in Renbase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_bAbort | Flag that indicates whether to stop rendering and reject further samples.
m_bEOS | Flag that indicates whether end-of-stream was reached.
m_bEOSDelivered | Flag that indicates whether the filter has posted the EC_COMPLETE event.
m_bInReceive | Flag that indicates whether the filter is processing a Receive call.
m_bRepaintStatus | Flag that enables or disables repaint events.
m_bStreaming | Flag that indicates whether the filter is streaming data.
m_dwAdvise | Identifier of the timer event that schedules rendering.
m_EndOfStreamTimer | Timer-event identifier, for scheduling EC_COMPLETE notifications.
m_evComplete | Event that is signaled when a state transition is complete.
m_InterfaceLock | Filter-state lock.
m_ObjectCreationLock | Lock to protect the creation of objects inside the filter.
m_pInputPin | Pointer to the filter's input pin.
m_pMediaSample | Pointer to the current media sample.
m_pPosition | Helper object to pass seek commands upstream.
m_pQSink | Pointer to the object that receives quality-control messages.
m_RendererLock | Streaming lock.
m_RenderEvent | Event used to schedule rendering.
m_SignalTime | Stop time on the current sample.
m_ThreadSignal | Event used to release the streaming thread.
Public Methods |
CancelNotification | Cancels the timer event that schedules rendering. Virtual.
CBaseRenderer | Constructor method.
~CBaseRenderer | Destructor method.
GetMediaPositionInterface | Retrieves the filter's IMediaPosition and IMediaSeeking interface pointers. Virtual.
GetPin | Retrieves a pin. Virtual.
GetPinCount | Retrieves the number of pins. Virtual.
GetSampleTimes | Retrieves the time stamps from a sample. Virtual.
OnDisplayChange | Posts an EC_DISPLAY_CHANGED event to the filter graph manager.
PrepareReceive | Prepares to render a sample. Virtual.
Receive | Receives the next media sample in the stream. Virtual.
Render | Renders a sample. Virtual.
ScheduleSample | Schedules a sample for rendering. Virtual.
SendNotifyWindow | Notifies the upstream filter of the video window handle.
SendRepaint | Sends a repaint event to the filter graph manager.
SetMediaType | Called when the pin's media type is set. Virtual.
SignalTimerFired | Clears the timer identifier used to schedule rendering.
SourceThreadCanWait | Holds or releases the streaming thread. Virtual.
WaitForReceiveToComplete | Waits for the CBaseRenderer::Receive method to complete.
WaitForRenderTime | Waits for the current sample's presentation time. Virtual.
Public Methods: Accessor Methods |
ClearPendingSample | Releases the current sample. Virtual.
GetCurrentSample | Retrieves the current sample. Virtual.
GetRealState | Retrieves the filter state.
GetRenderEvent | Retrieves the event that schedules rendering.
HaveCurrentSample | Determines whether the filter has a sample. Virtual.
IsEndOfStream | Queries whether the end-of-stream notification was received.
IsEndOfStreamDelivered | Queries whether the EC_COMPLETE event has been delivered to the filter graph manager.
IsStreaming | Queries whether the filter is streaming data.
SetAbortSignal | Sets a flag which indicates whether to stop rendering and reject further samples.
SetRepaintStatus | Enables or disables repaint events.
Public Methods: State-Change Methods |

Active | Called when the state is switched to paused or running. Virtual.
BeginFlush | Begins a flush operation. Virtual.
BreakConnect | Releases the input pin from a connection. Virtual.
CheckReady | Queries whether a state transition is complete.
CompleteConnect | Completes the input pin's connection to another pin. Virtual.
CompleteStateChange | Determines whether a transition to the paused state is complete. Virtual.
EndFlush | Ends a flush operation. Virtual.
Inactive | Called when the state is switched to stopped. Virtual.
NotReady | Signals that a state transition is not yet complete.
Ready | Signals that a state transition is complete.
StartStreaming | Initiates streaming when the filter switches to a running state. Virtual.
StopStreaming | Halts streaming when the filter switches out of the running state. Virtual.
Public Methods: End-of-Stream Methods |
EndOfStream | Notifies the filter that the input pin received an end-of-stream notification. Virtual.
NotifyEndOfStream | Posts an EC_COMPLETE event to the filter graph manager.
ResetEndOfStream | Resets the end-of-stream flags.
ResetEndOfStreamTimer | Cancels the timer that schedules EC_COMPLETE notifications. Virtual.
SendEndOfStream | If end-of-stream was reached, schedules an EC_COMPLETE event for the filter graph manager. Virtual.
TimerCallback | Callback method for the end-of-stream timer event.
Public Methods: Handlers |
OnReceiveFirstSample | Called when the filter receives a sample while paused. Virtual.
OnRenderEnd | Called after a sample is rendered. Virtual.
OnRenderStart | Called when rendering is about to start. Virtual.
OnStartStreaming | Called when the filter begins streaming. Virtual.
OnStopStreaming | Called when the filter stops streaming. Virtual.
OnWaitEnd | Called when the filter starts waiting for a sample's presentation time. Virtual.
OnWaitStart | Called when the filter is done waiting for a sample's presentation time. Virtual.
PrepareRender | Called before the filter renders a sample. Virtual.
ShouldDrawSampleNow | Determines how a sample is scheduled for rendering. Virtual.
Pure Virtual Methods |
CheckMediaType | Determines if the filter accepts a specific media type.
DoRenderSample | Renders a sample.
IMediaFilter Methods |
GetState | Retrieves the filter's state (running, stopped, or paused).
Pause | Pauses the filter.
Run | Runs the filter.
Stop | Stops the filter.
IBaseFilter Methods |
FindPin | Retrieves the pin with the specified identifier.


CBaseRenderer::m_bAbort

Flag that indicates whether to stop rendering and reject further samples.

Syntax

BOOL m_bAbort;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_bEOS

Flag that indicates whether end-of-stream was reached.

Syntax

BOOL m_bEOS;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_bEOSDelivered

Flag that indicates whether the filter has posted the EC_COMPLETE event.

Syntax

BOOL m_bEOSDelivered;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_bInReceive

Flag that indicates whether the filter is processing a Receive call.

Syntax

BOOL m_bInReceive;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_bRepaintStatus

Flag that enables or disables repaint events.

Syntax

BOOL m_bRepaintStatus;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_bStreaming

Flag that indicates whether the filter is streaming data.

Syntax

BOOL m_bStreaming;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_dwAdvise

Identifier of the timer event that schedules rendering.

Syntax

DWORD_PTR m_dwAdvise;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_EndOfStreamTimer

Timer-event identifier, for scheduling EC_COMPLETE notifications.

Syntax

UINT m_EndOfStreamTimer;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_evComplete

Event that is signaled when a state transition is complete.

Syntax

CAMEvent m_evComplete;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_InterfaceLock

Filter-state lock.

Syntax

CCritSec m_InterfaceLock;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_ObjectCreationLock

Lock to protect the creation of objects inside the filter. The filter holds this lock when it creates the input pin (CBaseRenderer::m_pInputPin) or the CRendererPosPassThru object (CBaseRenderer::m_pPosition). This lock prevents multiple threads from attempting to create one of these objects at the same time.

Syntax

CCritSec m_ObjectCreationLock;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_pInputPin

Pointer to the filter's input pin.

Syntax

CRendererInputPin *m_pInputPin;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_pMediaSample

Pointer to the current media sample.

Syntax

IMediaSample *m_pMediaSample;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_pPosition

Helper object to pass seek commands upstream.

Syntax

CRendererPosPassThru *m_pPosition;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_pQSink

Pointer to the object that receives quality-control messages.

Syntax

IQualityControl *m_pQSink;

Remarks

The base class does not implement quality control. This member variable defaults to NULL.

See Also

  • CBaseRenderer Class


CBaseRenderer::m_RendererLock

Streaming lock.

Syntax

CCritSec m_RendererLock;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_RenderEvent

Event used to schedule rendering.

Syntax

CAMEvent m_RenderEvent;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_SignalTime

Stop time on the current sample.

Syntax

REFERENCE_TIME m_SignalTime;

See Also

  • CBaseRenderer Class


CBaseRenderer::m_ThreadSignal

Event used to release the streaming thread.

Syntax

CAMEvent m_ThreadSignal;

See Also

  • CBaseRenderer Class


CBaseRenderer::Active

The Active method is called when the state is switched to paused or running.

Syntax

virtual HRESULT Active(void);

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::Active method. This method does nothing in the base class.

See Also

  • CBaseRenderer Class


CBaseRenderer::BeginFlush

The BeginFlush method begins a flush operation.

Syntax

virtual HRESULT BeginFlush(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives a call to the IPin::BeginFlush method. The filter releases the streaming thread, and releases any sample that it was holding for rendering.

See Also

  • CBaseRenderer Class


CBaseRenderer::BreakConnect

The BreakConnect method releases the input pin from a connection.

Syntax

virtual HRESULT BreakConnect(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is still active.

Remarks

The filter's input pin calls this method from inside its own BreakConnect method. (For more information, see CBasePin::BreakConnect.) The filter performs some internal bookkeeping, such as resetting the end-of-stream flag.

See Also

  • CBaseRenderer Class


CBaseRenderer::CancelNotification

The CancelNotification method cancels the timer event that schedules rendering.

Syntax

virtual HRESULT CancelNotification(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | There was no pending timer event.
S_OK | Success.

Remarks

The filter calls this method when streaming stops. The method cancels any scheduled rendering.

See Also

  • CBaseRenderer Class


CBaseRenderer::CBaseRenderer

Constructor method.

Syntax

CBaseRenderer(
    REFCLSID RenderClass,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

RenderClass

Class identifier of the renderer.

pName

Pointer to a string containing the name of the filter, for debugging purposes.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT variable. (Ignored.)

See Also

  • CBaseRenderer Class


CBaseRenderer::~CBaseRenderer

Destructor method.

Syntax

~CBaseRenderer(void);

See Also

  • CBaseRenderer Class


CBaseRenderer::CheckMediaType

The CheckMediaType method determines if the filter accepts a specific media type.

Syntax

virtual HRESULT CheckMediaType(
    const CMediaType *pmt
) PURE;

Parameters

pmt

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

The input pin calls this method from its own CBasePin::CheckMediaType method. The derived class must implement this method.

See Also

  • CBaseRenderer Class


CBaseRenderer::CheckReady

The CheckReady method queries whether a state transition is complete.

Syntax

BOOL CheckReady(void);

Return Value

Returns TRUE if the state transition is complete, or FALSE if the filter is still transitioning to a new state.

See Also

  • CBaseRenderer Class
  • CBaseRenderer::NotReady
  • CBaseRenderer::Ready


CBaseRenderer::ClearPendingSample

The ClearPendingSample method releases the current sample.

Syntax

virtual HRESULT ClearPendingSample(void);

Return Value

Returns S_OK.

See Also

  • CBaseRenderer Class


CBaseRenderer::CompleteConnect

The CompleteConnect method completes the input pin's connection to another pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the output pin's IPin interface.

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method from inside its own CompleteConnect method, which is called in order to complete a pin connection. (For more information, see CBasePin::CompleteConnect.) The filter calls the CBaseRenderer::SetRepaintStatus method to enable EC_REPAINT events.

See Also

  • CBaseRenderer Class


CBaseRenderer::CompleteStateChange

The CompleteStateChange method determines whether a transition to the paused state is complete.

Syntax

virtual HRESULT CompleteStateChange(
    FILTER_STATE OldState
);

Parameters

OldState

State prior to the transition.

Return Value

Returns S_OK if the transition is complete. Otherwise, returns S_FALSE.

Remarks

The CBaseRenderer::Pause method calls this method to update the state-transition status. In general, the transition to paused does not finish until the filter receives a sample. However, in some situations the transition completes immediately: for example, if the filter is unconnected, or if the end of the stream was reached. This method checks the various criteria and then calls the CBaseRenderer::Ready method or the CBaseRenderer::NotReady method to update the transition status.

See Also

  • CBaseRenderer Class


CBaseRenderer::DoRenderSample

The DoRenderSample method renders a sample.

Syntax

virtual HRESULT DoRenderSample(
    IMediaSample *pMediaSample
) PURE;

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value.

Remarks

The derived class must implement this method. The behavior depends entirely on the type of filter being implemented. A video renderer, for example, would draw the video image contained in the sample.

See Also

  • CBaseRenderer Class


CBaseRenderer::EndFlush

The EndFlush method ends a flush operation.

Syntax

virtual HRESULT EndFlush(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives a call to the IPin::EndFlush method.

See Also

  • CBaseRenderer Class


CBaseRenderer::EndOfStream

The EndOfStream method notifies the filter that the input pin received an end-of-stream notification.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives an end-of-stream notification.

This method sets the CBaseRenderer::m_bEOS flag to TRUE and calls the CBaseRenderer::SendEndOfStream method to schedule an EC_COMPLETE event. If the filter is paused and waiting for a sample, this method completes the state transition.

See Also

  • CBaseRenderer Class


CBaseRenderer::FindPin

The FindPin method retrieves the pin with the specified identifier.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id

Pointer to a constant, null-terminated wide-character string that identifies the pin. Must be L"In".

ppPin

Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Not found.

Remarks

This method overrides the CBaseFilter::FindPin method. The filter's only pin (the input pin) is named In.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetCurrentSample

The GetCurrentSample method retrieves the current sample.

Syntax

virtual IMediaSample *GetCurrentSample(void);

Return Value

Returns a pointer to the sample's IMediaSample interface, or NULL if no sample is available.

Remarks

If the return value is non-NULL, the IMediaSample pointer has an outstanding reference count. Be sure to release it.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetMediaPositionInterface

The GetMediaPositionInterface method retrieves the filter's IMediaPosition and IMediaSeeking interface pointers.

Syntax

virtual HRESULT GetMediaPositionInterface(
    REFIID riid,
    void **ppv
);

Parameters

riid

Reference identifier of the interface.

ppv

Address of a variable that receives the interface pointer.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_NOINTERFACE | Interface not supported.

Remarks

The filter delegates all seeking commands to a CRendererPosPassThru object, which passes them upstream. This method creates the CRendererPosPassThru object, if it does not yet exist, and queries it for the requested interface.

The CBaseRenderer::m_pPosition member variable stores a pointer to the CRendererPosPassThru object.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetPin

The GetPin method retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n

Number of the specified pin. Must be zero.

Return Value

Returns the CBaseRenderer::m_pInputPin pointer.

Remarks

This method implements the CBaseFilter::GetPin method, which is pure virtual in the CBaseFilter class. The filter supports exactly one pin (the input pin). The first time this method is called, it creates the pin as a new CRendererInputPin object.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetPinCount

The GetPinCount method retrieves the number of pins.

Syntax

virtual int GetPinCount(void);

Return Value

Returns 1.

Remarks

This method implements the CBaseFilter::GetPinCount method, which is pure virtual in the CBaseFilter class.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetRealState

The GetRealState method retrieves the filter state.

Syntax

FILTER_STATE GetRealState(void);

Return Value

Returns the value of CBaseFilter::m_State. The value is a member of the FILTER_STATE enumerated type.

Remarks

This method provides a simpler alternative to the CBaseRenderer::GetState method, for internal use.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetRenderEvent

The GetRenderEvent method retrieves the event that schedules rendering.

Syntax

CAMEvent *GetRenderEvent(void);

Return Value

Returns a pointer to the CBaseRenderer::m_RenderEvent event.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetSampleTimes

The GetSampleTimes method retrieves the time stamps from a sample.

Syntax

virtual HRESULT GetSampleTimes(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

pStartTime

Pointer to a variable that receives the start time.

pEndTime

Pointer to a variable that receives the end time.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | The sample should be rendered immediately.
S_FALSE | The sample should be scheduled for rendering, based on the time stamps.
E_FAIL | Do not render this sample.
VFW_E_START_TIME_AFTER_END | Bad time stamp: The end time is earlier than the start time.

Remarks

The filter calls this method to determine how it should handle a sample. If the return value is S_OK, the filter renders the sample immediately. If the return value is S_FALSE, the filter schedules the sample for rendering, based on the time stamps. If the return value is an error code, the filter rejects the sample.

This method returns S_OK if the sample has no time stamps, or if the filter does not have a reference clock. Otherwise, it returns the value of the CBaseRenderer::ShouldDrawSampleNow method. In the base class, ShouldDrawSampleNow always returns S_FALSE. The derived class can override this behavior. For example, if the derived class implements quality control management, it might return E_FAIL to drop a sample.

See Also

  • CBaseRenderer Class


CBaseRenderer::GetState

The GetState method retrieves the filters's state (running, stopped, or paused).

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout

Time-out interval, in milliseconds.

State

Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_S_STATE_INTERMEDIATE | The filter is transitioning to the indicated state.
E_POINTER | NULL pointer argument.

Remarks

This method overrides the CBaseFilter::GetState method. When the renderer is paused, it does not complete the state transition until it receives a sample to render. If the time-out expires before the state transition is complete, the method returns VFW_S_STATE_INTERMEDIATE.

See Also

  • CBaseRenderer Class


CBaseRenderer::HaveCurrentSample

The HaveCurrentSample method determines whether the filter has a sample.

Syntax

virtual BOOL HaveCurrentSample(void);

Return Value

Returns TRUE if the filter has a sample, or FALSE otherwise.

See Also

  • CBaseRenderer Class


CBaseRenderer::Inactive

The Inactive method is called when the state is switched to stopped.

Syntax

virtual HRESULT Inactive(void);

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::Inactive method. The filter calls the CBaseRenderer::ClearPendingSample method to release the most recent sample.

See Also

  • CBaseRenderer Class


CBaseRenderer::IsEndOfStream

The IsEndOfStream method queries whether the end-of-stream notification was received.

Syntax

BOOL IsEndOfStream(void);

Return Value

Returns the CBaseRenderer::m_bEOS flag.

See Also

  • CBaseRenderer Class


CBaseRenderer::IsEndOfStreamDelivered

The IsEndOfStreamDelivered method queries whether the EC_COMPLETE event has been delivered to the filter graph manager.

Syntax

BOOL IsEndOfStreamDelivered(void);

Return Value

Returns the CBaseRenderer::m_bEOSDelivered flag.

See Also

  • CBaseRenderer Class


CBaseRenderer::IsStreaming

The IsStreaming method queries whether the filter is streaming data.

Syntax

BOOL IsStreaming(void);

Return Value

Returns the CBaseRenderer::m_bStreaming flag.

See Also

  • CBaseRenderer Class


CBaseRenderer::NotReady

The NotReady method signals that a state transition is not yet complete.

Syntax

void NotReady(void);

Remarks

This method causes the CBaseRenderer::GetState method to return VFW_S_STATE_INTERMEDIATE, which indicates that the filter is still transitioning to its current state. The filter calls this method whenever a state transition is pending. (This occurs when the filter pauses, until it receives a sample.)

See Also

  • CBaseRenderer Class
  • CheckReady
  • Ready


CBaseRenderer::NotifyEndOfStream

The NotifyEndOfStream method posts an EC_COMPLETE event to the filter graph manager.

Syntax

void NotifyEndOfStream(void);

See Also

  • CBaseRenderer Class
  • CBaseRenderer::EndOfStream
  • CBaseRenderer::SendEndOfStream


CBaseRenderer::OnDisplayChange

The OnDisplayChange method posts an EC_DISPLAY_CHANGED event to the filter graph manager.

Syntax

BOOL CBaseRenderer::OnDisplayChange(void);

Return Value

Returns TRUE if the event was posted, or FALSE otherwise.

Remarks

Video renderers should call this method in response to WM_DISPLAYCHANGE messages. If the input pin is connected, the method sends an EC_DISPLAY_CHANGED event to the filter graph manager.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnReceiveFirstSample

The OnReceiveFirstSample method is called when the filter receives a sample while paused.

Syntax

virtual void OnReceiveFirstSample(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Remarks

The CBaseRenderer::Receive method calls this method. It does nothing in the base class, but the derived class can override it. This method is intended primarily for video renderers. When a video renderer is paused, it typically displays the first sample as a still image.

Seeking the graph while paused also causes this method to be called.

See Also

  • 16CBaseRenderer Class


CBaseRenderer::OnRenderEnd

The OnRenderEnd method is called after a sample is rendered.

Syntax

virtual void OnRenderEnd(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Remarks

The CBaseRenderer::Render method calls this method. It does nothing in the base class, but the derived class can override it; for example, to collect quality-control data.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnRenderStart

The OnRenderStart method is called when rendering is about to start.

Syntax

virtual void OnRenderStart(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Remarks

The CBaseRenderer::Render method calls this method. It does nothing in the base class, but the derived class can override it; for example, to collect quality-control data.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnStartStreaming

The OnStartStreaming method is called when the filter begins streaming.

Syntax

virtual HRESULT OnStartStreaming(void);

Return Value

Returns S_OK.

Remarks

The CBaseRenderer::StartStreaming method calls this method. It does nothing in the base class, but the derived class can override it.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnStopStreaming

The OnStopStreaming method is called when the filter stops streaming.

Syntax

virtual HRESULT OnStopStreaming(void);

Return Value

Returns S_OK.

Remarks

The CBaseRenderer::StopStreaming method calls this method. It does nothing in the base class, but the derived class can override it.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnWaitEnd

The OnWaitEnd method is called when the filter is done waiting for a sample's presentation time.

Syntax

virtual void OnWaitEnd(void);

Remarks

The CBaseRenderer::WaitForRenderTime method calls this method when it has finished waiting for a sample's presentation time. This method does not do anything in the base class, but the derived class can override it.

If you are implementing quality control, you might override this method along with the CBaseRenderer::OnWaitStart method. You can use these methods to track the filter's performance.

See Also

  • CBaseRenderer Class


CBaseRenderer::OnWaitStart

The OnWaitStart method is called when the filter starts waiting for a sample's presentation time.

Syntax

virtual void OnWaitStart(void);

Remarks

The CBaseRenderer::WaitForRenderTime method calls this method when it begins waiting for a sample's presentation time. This method does not do anything in the base class, but the derived class can override it.

If you are implementing quality control, you might override this method along with the CBaseRenderer::OnWaitEnd method. You can use these methods to track the filter's performance.

See Also

  • CBaseRenderer Class


CBaseRenderer::Pause

The Pause method pauses the filter.

Syntax

HRESULT Pause(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | The transition is complete.
S_FALSE | Transition is not complete.

Remarks

This method overrides the CBaseFilter::Pause method. It performs the following steps:

  • Calls the CBaseFilter::Pause method.
  • Commits the allocator. (See IMemAllocator::Commit.)
  • If the previous state was stopped, the filter releases any sample it is holding. (The sample is no longer valid.)
  • Calls the CBaseRenderer::CompleteStateChange method and returns the value.

See Also

  • CBaseRenderer Class


CBaseRenderer::PrepareReceive

The PrepareReceive method prepares the filter to render a sample.

Syntax

virtual HRESULT PrepareReceive(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failed.
E_UNEXPECTED | Unexpected error.
VFW_E_SAMPLE_REJECTED | Filter is dropping this sample.

Remarks

The filter calls this method from inside the CBaseRenderer::Receive method, before it renders a sample. If the filter is running, this method schedules the sample for rendering.

If the filter already has a pending sample, or if the end-of-stream was already reached, the method returns E_UNEXPECTED. Possibly the upstream filter is not serializing its streaming calls correctly.

If the scheduling algorithm determines that the sample should be dropped (see CBaseRenderer::ScheduleSample), the method returns VFW_E_SAMPLE_REJECTED. However, the input pin's IMemInputPin::Receive method does not pass this error code to the upstream filter, because dropping a sample is not an error.

See Also

  • CBaseRenderer Class


CBaseRenderer::PrepareRender

The PrepareRender method is called before the filter renders a sample.

Syntax

virtual void PrepareRender(void);

Remarks

The filter calls this method before it calls the CBaseRenderer::OnReceiveFirstSample method or the CBaseRenderer::Render method. PrepareRender does not do anything in the base class. The derived class can override it to perform any actions required before rendering. For example, a video renderer can override this method to realize its palette.

See Also

  • CBaseRenderer Class


CBaseRenderer::Ready

The Ready method signals that a state transition is complete.

Syntax

void Ready(void);

Remarks

This method causes the CBaseRenderer::GetState method to return S_OK, which indicates that the filter has completed the transition to its current state. The filter calls this method whenever it completes a state transition.

See Also

  • CBaseRenderer Class
  • CBaseRenderer::CheckReady
  • CBaseRenderer::NotReady


CBaseRenderer::Receive

The Receive method receives the next media sample in the stream.

Syntax

virtual HRESULT Receive(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

The input pin calls this method when it receives a sample from the upstream filter.

If the filter is running, this method performs the following steps:

  1. Schedules the sample for rendering (CBaseRenderer::PrepareReceive).
  2. Waits for the scheduled time (CBaseRenderer::WaitForRenderTime).
  3. Renders the sample (CBaseRenderer::Render).
  4. Releases the sample (CBaseRenderer::ClearPendingSample).

If the filter is paused, the method performs the following steps:

  1. Notifies the derived class that a sample is available (CBaseRenderer::OnReceiveFirstSample).
  2. Waits for the scheduled time.
  3. Renders the sample.
  4. Releases the sample.

While paused, the method waits in step 2 until the filter switches to a running state. At that point, the filter schedules the sample.

In the base class, the OnReceiveFirstSample method does nothing. The derived class can override it. For example, when a video renderer is paused, it displays the first sample as a still image.

See Also

  • CBaseRenderer Class


CBaseRenderer::Render

The Render method renders a sample.

Syntax

virtual HRESULT Render(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_FALSE | The filter is stopped, or pMediaSample is NULL.
S_OK | Success.

Remarks

This method calls the pure virtual method CBaseRenderer::DoRenderSample, which does the real work. The derived class must implement DoRenderSample.

Immediately before calling DoRenderSample, this method calls the CBaseRenderer::OnRenderStart method. Immediately after, it calls the CBaseRenderer::OnRenderEnd method. The derived class can override those two methods as needed.

See Also

  • CBaseRenderer Class


CBaseRenderer::ResetEndOfStream

The ResetEndOfStream method resets the end-of-stream flags.

Syntax

virtual HRESULT ResetEndOfStream(void);

Return Value

Returns S_OK.

Remarks

This method clears the previous end-of-stream condition. At that point, the filter can receive new data. The CBaseRenderer::Stop and CBaseRenderer::BeginFlush methods call this method.

See Also

  • CBaseRenderer Class


CBaseRenderer::ResetEndOfStreamTimer

The ResetEndOfStreamTimer method cancels the timer that schedules EC_COMPLETE notifications.

Syntax

void ResetEndOfStreamTimer(void);

See Also

  • CBaseRenderer Class
  • CBaseRenderer::SendEndOfStream
  • CBaseRenderer::TimerCallback.


CBaseRenderer::Run

The Run method runs the filter.

Syntax

HRESULT Run(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBaseFilter::Run method. It performs the following actions:

  • Calls the CBaseFilter::Run method.
  • Commits the allocator. (See IMemAllocator::Commit.)
  • If the previous state was stopped, the filter releases any sample it is holding. (The sample is no longer valid.)
  • Calls the CBaseRenderer::StartStreaming method and returns the result. If a sample is pending, the StartStreaming method schedules it for rendering.

If the filter is not connected, it posts an EC_COMPLETE event immediately.

See Also

  • CBaseRenderer Class


CBaseRenderer::ScheduleSample

The ScheduleSample method schedules a sample for rendering.

Syntax

virtual BOOL ScheduleSample(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns TRUE if the sample was scheduled, or FALSE if the sample was dropped.

Remarks

This method first determines whether the sample should be rendered immediately, rendered in the future, or dropped. (To do so, it calls the CBaseRenderer::GetSampleTimes method.) If the sample should be rendered immediately, the method signals the CBaseRenderer::m_RenderEvent event. If the sample should be rendered in the future, the method calls the IReferenceClock::AdviseTime method for scheduling.

See Also

  • CBaseRenderer Class


CBaseRenderer::SendEndOfStream

If end-of-stream was reached, the SendEndOfStream method schedules an EC_COMPLETE event for the filter graph manager.

Syntax

virtual HRESULT SendEndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_FALSE | The filter graph manager is not accepting event notifications.
S_OK | Success.

Remarks

The filter might receive an end-of-stream notification before the current sample's stop time. If so, the filter should wait before posting an EC_COMPLETE notification to the filter graph manager.

Therefore:

  • If the filter has received an early end-of-stream (EOS) notification, this method schedules a timer event. When the timer event is activated, the filter posts the EC_COMPLETE event.
  • If the filter has received an EOS notification that was not early, this method posts the EC_COMPLETE event immediately.
  • If the filter does not have any pending EOS notification, the method returns without doing anything.

The timer callback method is CBaseRenderer::TimerCallback. To deliver the EC_COMPLETE event, the filter calls the CBaseRenderer::NotifyEndOfStream method.

See Also

  • CBaseRenderer Class


CBaseRenderer::SendNotifyWindow

The SendNotifyWindow method notifies the upstream filter of the video window handle.

Syntax

void SendNotifyWindow(
    IPin *pPin,
    HWND hwnd
);

Parameters

pPin

Pointer to the IPin interface of the upstream filter's output pin.

hwnd

Handle to the video window, or NULL.

Return Value

No return value.

Remarks

If the output pin of the upstream filter supports the IMediaEventSink interface, this method sends it the EC_NOTIFY_WINDOW event code along with the window handle.

Video renderers can override their CBaseRenderer::CompleteConnect methods to call this method. It provides a mechanism for informing the upstream filter of the window handle. If you do this, override the CBaseRenderer::BreakConnect method as well, and call SendNotifyWindow with a NULL handle.

See Also

  • CBaseRenderer Class


CBaseRenderer::SendRepaint

The SendRepaint method sends a repaint event to the filter graph manager.

Syntax

void SendRepaint(void);

Remarks

This method sends an EC_REPAINT event to the filter graph manager if the following conditions are true:

  • The input pin is connected.
  • The filter is not flushing data.
  • The end-of-stream was not reached.
  • The CBaseRenderer::m_bAbort flag is FALSE.
  • The CBaseRenderer::m_bRepaintStatus flag is TRUE.

Depending on the state of the graph, the EC_REPAINT event can cause the upstream filter to re-send a sample; the filter graph to seek to its current location; or the filter graph manager to pause momentarily. (See EC_REPAINT.) This event is potentially inefficient, so it should be used sparingly. However, video renderers sometimes need to refresh the display.

See Also

  • CBaseRenderer Class


CBaseRenderer::SetAbortSignal

The SetAbortSignal method sets a flag which indicates whether to stop rendering and reject further samples.

Syntax

void SetAbortSignal(
    BOOL bAbort
);

Parameters

bAbort

Boolean value indicating whether to stop rendering. If TRUE, the filter will not render any more samples.

Remarks

This method sets the CBaseRenderer::m_bAbort flag.

See Also

  • CBaseRenderer Class


CBaseRenderer::SetMediaType

The SetMediaType method is called when the pin's media type is set.

Syntax

virtual HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::SetMediaType method. This method does nothing in the base class.

See Also

  • CBaseRenderer Class


CBaseRenderer::SetRepaintStatus

The SetRepaintStatus method enables or disables repaint events.

Syntax

void SetRepaintStatus(
    BOOL bRepaint
);

Parameters

bRepaint

Boolean value indicating whether repaint events are enabled. If TRUE, the filter will sent EC_REPAINT events to the filter graph manager. Otherwise, it will not send EC_REPAINT events.

Remarks

This method ensures that the filter graph manager is not flooded with redundant EC_REPAINT events. After the filter sends an EC_REPAINT event, it calls this method with the value TRUE. The filter does not send more EC_REPAINT events until it receives more data.

See Also

  • CBaseRenderer Class


CBaseRenderer::ShouldDrawSampleNow

The ShouldDrawSampleNow method determines how a sample is scheduled for rendering.

Syntax

virtual HRESULT ShouldDrawSampleNow(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

pStartTime

Pointer to a variable that contains the sample's start time.

pEndTime

Pointer to a variable that contains the sample's end time.

Return Value

Returns S_FALSE. If the derived class overrides this method, return one of the values shown in the following table.

Value | Description
S_OK | The sample should be rendered immediately.
S_FALSE | The sample should be scheduled for rendering, based on the time stamps.
Error code | Do not render this sample.

Remarks

The CBaseRenderer::GetSampleTimes method calls this method. By default, samples are always scheduled for rendering based on their time stamps. The derived class can override this method; for example, to implement quality control.

See Also

  • CBaseRenderer Class


CBaseRenderer::SignalTimerFired

The SignalTimerFired method clears the timer identifier used to schedule rendering.

Syntax

virtual void SignalTimerFired(void);

Remarks

The filter calls this method when the rendering timer activates (see CBaseRenderer::WaitForRenderTime) or when the timer is canceled (see CBaseRenderer::CancelNotification). The method resets the CBaseRenderer::m_dwAdvise member variable to zero.

See Also

  • CBaseRenderer Class


CBaseRenderer::SourceThreadCanWait

The SourceThreadCanWait method holds or releases the streaming thread.

Syntax

virtual HRESULT SourceThreadCanWait(
    BOOL bCanWait
);

Parameters

bCanWait

Boolean value indicating whether to hold the streaming thread. If TRUE, the streaming thread is blocked while the filter waits to render the next samples. If FALSE, the streaming thread is released.

Return Value

Returns S_OK.

Remarks

Calling the SourceThreadCanWait method with the value FALSE forces the filter to return from a blocked IMemInputPin::Receive call. When the filter is running, it blocks Receive calls until the current sample's presentation time. When the filter is paused, it blocks Receive calls indefinitely. This behavior regulates the flow of data in the stream. When the filter is stopped or flushing, however, it should not block.

The blocking is controlled by the CBaseRenderer::WaitForRenderTime method, which waits on two events: CBaseRenderer::m_RenderEvent and CBaseRenderer::m_ThreadSignal. The m_RenderEvent event is signaled when the presentation time arrives. The m_ThreadSignal event is signaled when SourceThreadCanWait is called with the value FALSE. Calling SourceThreadCanWait with the value TRUE resets the event.

The CBaseRenderer::Stop and CBaseRenderer::BeginFlush methods call SourceThreadCanWait with the value FALSE (releasing the streaming thread). The CBaseRenderer::Pause, CBaseRenderer::Run, and CBaseRenderer::EndFlush methods call SourceThreadCanWait with the value TRUE.

See Also

  • CBaseRenderer Class


CBaseRenderer::StartStreaming

The StartStreaming method initiates streaming when the filter switches to a running state.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

If the filter has a sample, it schedules the sample for rendering. Otherwise, if there is a pending end-of-stream notification, the filter sends an EC_COMPLETE event to the filter graph manager.

This method calls the CBaseRenderer::OnStartStreaming method. That method does nothing in the base class, but the derived class can override it.

See Also

  • CBaseRenderer Class


CBaseRenderer::Stop

The Stop method stops the filter.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK.

Remarks

This method overrides the CBaseFilter::Stop method. It performs the following actions:

  • Calls CBaseFilter::Stop.
  • Decommits the allocator. (See IMemAllocator::Decommit.)
  • Cancels any scheduled rendering and releases the streaming thread.
  • Waits for any pending Receive call to complete.

See Also

  • CBaseRenderer Class


CBaseRenderer::StopStreaming

The StopStreaming method halts streaming when the filter switches out of the running state.

Syntax

virtual HRESULT StopStreaming(void);

Return Value

Returns S_OK.

Remarks

This method calls the CBaseRenderer::OnStopStreaming method. That method does nothing in the base class, but the derived class can override it.

See Also

  • CBaseRenderer Class


CBaseRenderer::TimerCallback

The TimerCallback method is a callback method for the end-of-stream timer event.

Syntax

void TimerCallback(void);

Remarks

The CBaseRenderer::SendEndOfStream method uses a timer event to schedule EC_COMPLETE notifications. The CBaseRenderer::TimerCallback method is the callback function for the timer event. The TimerCallback method calls SendEndOfStream again, and SendEndOfStream determines whether to send the EC_COMPLETE notification or set another timer.

The CBaseRenderer::ResetEndOfStreamTimer method cancels the timer event.

See Also

  • CBaseRenderer Class


CBaseRenderer::WaitForReceiveToComplete

The WaitForReceiveToComplete method waits for the CBaseRenderer::Receive method to complete.

Syntax

void WaitForReceiveToComplete(void);

Remarks

The CBaseRenderer::Stop and CBaseRenderer::BeginFlush methods call this method to synchronize the state change with the Receive method.

Specifically, this method dispatches messages while it waits for the CBaseRenderer::m_bInReceive flag to become FALSE. The flag becomes TRUE in the CBaseRenderer::PrepareReceive method and switches back to FALSE after the Receive method calls the CBaseRenderer::PrepareRender method. The derived class can use PrepareRender to set the palette. Waiting for PrepareRender to complete ensures that palette-change messages are dispatched before the state change occurs. This avoids a potential deadlock.

See Also

  • CBaseRenderer Class


CBaseRenderer::WaitForRenderTime

The WaitForRenderTime method waits for the current sample's presentation time.

Syntax

virtual HRESULT WaitForRenderTime(void);

Return Value

Returns one of the following HRESULT values.

Value | Description
S_OK | Success.
VFW_E_STATE_CHANGED | The filter state changed before the presentation time arrived.

Remarks

This method waits until one of the following occurs:

  • The sample's presentation time arrives, at which point the sample can be rendered.
  • The filter stops or begins flushing data.

If the presentation time arrives, the CBaseRenderer::m_RenderEvent event is signaled. If the state changes, the CBaseRenderer::m_ThreadSignal event is signaled. This method waits on both events. The derived class can override this method to wait on additional events, if necessary.

This method calls the CBaseRenderer::OnWaitStart method when the wait begins, and the CBaseRenderer::OnWaitEnd method when the wait is done. Neither method does anything in the base class, but the derived class can override them.

See Also

  • CBaseRenderer Class


CBaseStreamControl Class

CBaseStreamControl Class Hierarchy

This class implements the IAMStreamControl interface for input and output pins. It provides control over starting and stopping an individual pin on the filter. A pin that supports IAMStreamControl should inherit from this base class. The following is a typical declaration for an input pin:

class CMyInputPin : public CBaseInputPin, public CBaseStreamControl

Be sure to override NonDelegatingQueryInteface to expose IAMStreamControl. For more information, see How to Implement IUnknown.

This class requires the pin and the owning filter to notify the class when various events occur, such as the filter joining the graph or receiving a new reference clock. You should call the following class methods:

  • In the filter's IMediaFilter::SetSyncSource method, call the CBaseStreamControl::SetSyncSource method. This method notifies the class of the current reference clock.
  • In the filter's CBaseFilter::JoinFilterGraph method, call the CBaseStreamControl::SetFilterGraph method. This method gives the class a pointer to the Filter Graph Manager, so that the class can send the right stream-control events.
  • Whenever the filter changes state (to running, paused, or stopped), call the CBaseStreamControl::NotifyFilterState method.
  • In the pin's IPin::BeginFlush and IPin::EndFlush methods, call the CBaseStreamControl::Flushing method.

The CBaseStreamControl class uses the filter graph's reference clock to determine which samples the filter should be deliver, and which it should discard. In your pin's IMemInputPin::Receive method, call the CBaseStreamControl::CheckStreamState method with a pointer to the incoming media sample. If the method returns the value STREAM_FLOWING, deliver the sample downstream. Otherwise, discard it.

Requirements

Header: Declared in Strmctl.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods

Methods | Description
CBaseStreamControl | Constructor method.
~CBaseStreamControl | Destructor method.
CheckStreamState | Determines whether a media sample should be delivered or discarded.
Flushing | Notifies the base class that the pin has started or stopped flushing.
NotifyFilterState | Notifies the pin when the filter's state changes.
SetFilterGraph | Specifies the event sink for stream control events.
SetSyncSource | Notifies the base class of the current reference clock.

IAMStreamControl Methods

Method | Description
GetInfo | Retrieves information about the current stream-control settings, including the start and stop times.
StartAt | Informs the pin when to start delivering data.
StopAt | Informs the pin when to stop delivering data.


CBaseStreamControl::CBaseStreamControl

Constructor method.

Syntax

CBaseStreamControl(void);

Parameters

This method takes no parameters.

See Also

  • CBaseStreamControl Class


CBaseStreamControl::~CBaseStreamControl

Destructor method.

Syntax

~CBaseStreamControl(void);

Parameters

This method takes no parameters.

See Also

  • CBaseStreamControl Class


CBaseStreamControl::CheckStreamState

The CheckStreamState method determines whether a media sample should be delivered or discarded.

Syntax

enum StreamControlState CheckStreamState(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Values

Returns one of the following values.

Return code | Description
STREAM_DISCARDING | Discard this sample.
STREAM_FLOWING | Deliver this sample.

Remarks

Call this method when your pin receives a sample. Deliver the sample only if the return value is STREAM_FLOWING. If the return value is STREAM_DISCARDING, discard the sample.

If the pin discards any samples, it should mark the next sample that it delivers as a discontinuity, by calling the IMediaSample::SetDiscontinuity method.

If your filter implements the IAMDroppedFrames interface to count how many frames it drops, do not count a discarded frame as a dropped frame.

When the return value is STREAM_DISCARDING, the method blocks until the reference time reaches the sample's start time. This prevents your pin from discarding samples too quickly. If the filter is paused, the wait time is infinite, until the filter runs, stops, or flushes data. (Filter state changes and streaming happen on separate threads, so this does not cause any deadlock.)

The CBaseStreamControl::StreamControlState enumeration is defined as follows:

enum StreamControlState{
    STREAM_FLOWING = 0x1000,
    STREAM_DISCARDING
};

Example Code

The following example assumes that the pin uses a member variable named m_fLastSampleDiscarded to keep track of discontinuities.

CMyPin::Receive(IMediaSample *pSample)
{
    if (!pSample) return E_POINTER;

    int iStreamState = CheckStreamState(pSample);
    if (iStreamState == STREAM_FLOWING)
    {
        if (m_fLastSampleDiscarded)
            pSample->SetDiscontinuity(TRUE);
        m_fLastSampleDiscarded = FALSE;
        /* Deliver the sample. */
    }
    else
    {
        m_fLastSampleDiscarded = TRUE;
       // Discard this sample. Do not deliver it.
    }
}

See Also

  • CBaseStreamControl Class


CBaseStreamControl::Flushing

The Flushing method notifies the base class that the pin has started or stopped flushing.

Syntax

void Flushing(
    BOOL bInProgress
);

Parameters

bInProgress

Specifies a Boolean value that indicates whether the pin is flushing. Use the value TRUE when the pin begins a flush operation, and FALSE when the pin ends a flush operation.

Return Values

This method does not return a value.

Remarks

The pin must call this method from within its IPin::BeginFlush and IPin::EndFlush methods. Specify TRUE in BeginFlush and FALSE in EndFlush.

This method causes the CBaseStreamControl::CheckStreamState method to stop waiting. While the pin is flushing, CheckStreamState always returns STREAM_DISCARDING.

See Also

  • CBaseStreamControl Class


CBaseStreamControl::GetInfo

The GetInfo method retrieves information about the current stream-control settings, including the start and stop times. This method implements the IAMStreamControl::GetInfo method.

Syntax

HRESULT GetInfo(
    AM_STREAM_INFO *pInfo
);

Parameters

pInfo

Pointer to an AM_STREAM_INFO structure, allocated by the caller, that receives the current stream-control settings.

Return Values

Returns S_OK or E_POINTER.

See Also

  • CBaseStreamControl Class


CBaseStreamControl::NotifyFilterState

The NotifyFilterState method notifies the pin when the filter's state changes.

Syntax

void NotifyFilterState(
    FILTER_STATE new_state,
    REFERENCE_TIME tStart = 0
);

Parameters

new_state

Specifies the new state, as a member of the FILTER_STATE enumeration.

tStart

Specifies the start time. If the new filter state is State_Running, pass in the value from the IMediaFilter::Run method. Otherwise, use the default value.

Return Values

This method does not return a value.

Remarks

This method causes the CBaseStreamControl::CheckStreamState method to stop waiting. Call this method whenever the owning filter changes state.

Example Code

STDMETHODIMP CMyFilter::Run(REFERENCE_TIME tStart)
{
   /* Do other things needed by the filter ... */
   m_pMyPin->NotifyFilterState(State_Running, tStart);
   return CBaseFilter::Run(tStart); // Call the filter base class.
}

STDMETHODIMP CMyFilter::Pause()
{
   /* Do other things needed by the filter ... */
   m_pMyPin->NotifyFilterState(State_Paused);
   return CBaseFilter::Pause();
}

STDMETHODIMP CMyFilter::Stop()
{
   /* Do other things needed by the filter ... */
   m_pMyPin->NotifyFilterState(State_Stopped);
   return CBaseFilter::Stop();
}

See Also

  • CBaseStreamControl Class


CBaseStreamControl::SetFilterGraph

The SetFilterGraph method specifies the event sink for stream control events.

Syntax

void SetFilterGraph(
    IMediaEventSink *pSink
);

Parameters

pSink

Pointer to the Filter Graph Manager's IMediaEventSink interface, or NULL when the filter leaves the filter graph.

Return Values

This method does not return a value.

Remarks

Call this method from inside the filter's IBaseFilter::JoinFilterGraph method. The CBaseStreamControl class uses the IMediaEventSink interface to send EC_STREAM_CONTROL_STARTED and EC_STREAM_CONTROL_STOPPED events.

If your filter derives from CBaseFilter, first call the CBaseFilter::JoinFilterGraph method, which sets the CBaseFilter::m_pSink member variable. Then pass m_pSink to the SetFilterGraph method. Note that m_pSink is NULL when the filter leaves the graph, which is correct.

Example Code

STDMETHODIMP CMyFilter::JoinFilterGraph(IFilterGraph * pGraph, LPCWSTR pName)
{
    // Note: It's OK if pGraph is NULL.

    HRESULT hr = CBaseFilter::JoinFilterGraph(pGraph, pName);
    if (SUCCEEDED(hr))
    {
        m_pMyPin->SetFilterGraph(m_pSink);
    }
    return hr;
}

See Also

  • CBaseStreamControl Class


CBaseStreamControl::SetSyncSource

The SetSyncSource method notifies the base class of the current reference clock.

Syntax

void SetSyncSource(
    IReferenceClock *pRefClock
);

Parameters

pRefClock

Pointer to the IReferenceClock interface of the reference clock.

Return Values

This method does not return a value.

Remarks

Call this method from inside the filter's IMediaFilter::SetSyncSource method. The CBaseStreamControl class uses the IReferenceClock interface to ensure that it does not discard samples too quickly.

Example Code

STDMETHODIMP CMyFilter::SetSyncSource(IReferenceClock *pClock)
{
    // Note: It's OK if pClock is NULL.

    m_pMyPin->SetSyncSource(pClock);
    return CBaseFilter::SetSyncSource(pClock);
}

See Also

  • CBaseStreamControl Class


CBaseStreamControl::StartAt

The StartAt method informs the pin when to start delivering data. This method implements the IAMStreamControl::StartAt method.

Syntax

HRESULT StartAt(
    const REFERENCE_TIME *ptStart = NULL,
    DWORD dwCookie = 0
);

Parameters

ptStart

Pointer to a REFERENCE_TIME value that specifies when the pin should start delivering data.

dwCookie

Specifies a value to send along with the start notification.

Return Values

Returns S_OK.

See Also

  • CBaseStreamControl Class


CBaseStreamControl::StopAt

The StopAt method informs the pin when to stop delivering data. This method implements the IAMStreamControl::StopAt method.

Syntax

HRESULT StopAt(
    const REFERENCE_TIME *ptStop = NULL,
    BOOL bSendExtra = FALSE,
    DWORD dwCookie = 0
);

Parameters

ptStop

Pointer to a REFERENCE_TIME value that specifies when the pin should stop delivering data.

bSendExtra

Specifies a Boolean value that indicates whether to send an extra sample after the scheduled stop time. If TRUE, the pin sends one extra sample.

dwCookie

Specifies a value to send along with the start notification.

Return Values

Returns S_OK.

See Also

  • CBaseStreamControl Class


CBaseVideoRenderer Class

CBaseVideoRenderer Class Hierarchy

The CBaseVideoRenderer base class is used for building video renderer filters.

Protected Data Members

m_bDrawLateFrames | Flag to signal that no frames are to be dropped. Debug only. This destroys synchronization.
m_bSupplierHandlingQuality | TRUE indicates quality control messages are being handled. This lets the renderer know to wait until as late as possible to drop frames itself, and to display the next frame very early after the supplier has dropped a frame.
m_cFramesDrawn | Total number of frames that have been drawn since streaming started.
m_cFramesDropped | Cumulative frames that have been dropped in the renderer since streaming started. Frames can also be dropped upstream without the renderer recognizing them.
m_idDecision | MSR_id for the decision code of ShouldDrawSampleNow.
m_idDuration | MSR_id for the duration of a frame.
m_idFrameAccuracy | Performance log identifier for the time in milliseconds that the frame was late.
m_idFrameAvg | Performance log identifier for the average frame time that is used for synchronization and quality control.
m_idQualityRate | MSR_id for the quality rate requested.
m_idQualityTime | MSR_id for the quality time requested.
m_idRenderAvg | Performance log identifier for the average renderer time recorded.
m_idSchLateTime | MSR_id for how late the frame was when scheduled.
m_idSendQuality | MSR_id for timing the notifications (unused).
m_idTimeStamp | MSR_id for a frame time stamp.
m_idWait | Performance log identifier for the recorded wait time (unused).
m_idWaitReal | Performance log identifier for the true wait time.
m_iSumFrameTime | Sum of the interframe times; needed for the property page.
m_iSumSqAcc | Sum of the squares of the accuracies (in milliseconds) needed for the property page.
m_iSumSqFrameTime | Sum of the squares of interframe times; needed for the property page.
m_iTotAcc | Sum of the accuracies (in milliseconds) needed for the property page.
m_nNormal | Number of consecutive frames drawn at their scheduled time. A negative number indicates that a frame has just been dropped by the renderer.
m_trDuration | Duration of the last frame (difference between the start and end times).
m_trEarliness | How early a frame is allowed to be played when a frame has just been dropped.
m_trFrame | Most recently recorded time between frames. Used in statistical measurements.
m_trFrameAvg | Average interframe time in reference time units.
m_trLastDraw | Time of previous frame. Used for interframe time references.
m_trLate | Amount of time that the current frame was late. Used in statistical measurements.
m_trRenderAvg | Time that frames are taking to perform the bit-block transfer.
m_trRenderLast | Time for the last frame bit-block transfer.
m_trRenderStart | Time the bit-block transfer started. Used to get m_trRenderLast.
m_trThrottle | Period to insert after rendering each frame, typically used when audio quality has been increased and video performance must be decreased to allow this.
m_trWaitAvg | Average wait time in reference time units.
m_tStreamingStart | Used for property page statistics. Represents the start time of the current streaming process or the previous streaming process if not currently streaming.

Member Functions

CBaseVideoRenderer | Constructs a CBaseVideoRenderer object.
GetStdDev | Estimates the standard deviation in milliseconds between when each frame is due and when it is actually rendered, for per-frame statistics.
PreparePerformanceData | Sets the m_trLate and m_trFrame values of the current frame.
ThrottleWait | Inserts a wait period after each frame.

Overridable Member Functions

JoinFilterGraph | Sends an EC_WINDOW_DESTROYED event when filter is removed from the filter graph.
OnDirectRender | Collects timing information that controls synchronization and quality control.
OnRenderEnd | Records information for quality control and synchronization.
OnRenderStart | Records information for quality control and synchronization.
OnStartStreaming | Resets all times that control streaming.
OnStopStreaming | Called at the end of streaming to fix times for the property page report.
OnWaitEnd | Called when a wait time ends. Performance logging only.
OnWaitStart | Updates times spent waiting and not waiting. Performance logging only.
RecordFrameLateness | Records how timely the rendering occurred and gathers statistics for the property page.
ResetStreamingTimes | Resets all times that control the streaming.
ScheduleSample | Sets up an advise link with the clock.
SendQuality | Sends a quality message to indicate what the supplier should do about quality.
ShouldDrawSampleNow | Determines if the video should be drawn when it is due, without setting a timer advise link with the clock.

Implemented IQualProp Methods

get_AvgFrameRate | Retrieves the average frame rate since streaming started in frames per 100 seconds.
get_AvgSyncOffset | Retrieves the average of the time in milliseconds between when each frame was due and when it was actually rendered. This applies to all frames since streaming started.
get_DevSyncOffset | Retrieves the standard deviation of the time in milliseconds between when each frame was due and when it was actually rendered for all frames since streaming started.
get_FramesDrawn | Retrieves the number of frames drawn since streaming started.
get_FramesDroppedInRenderer | Retrieves the number of frames dropped by the renderer. Frames can also be dropped upstream.
get_Jitter | Retrieves the standard deviation of the time in milliseconds between each frame and the next. This applies to all frames since streaming started.

Implemented IQualityControl Methods

Notify | Notifies the recipient that a quality change is requested.
SetSink | Sets the IQualityControl object that will receive quality messages.


CBaseVideoRenderer::CBaseVideoRenderer

Constructor method.

Syntax

CBaseVideoRenderer(
    REFCLSID RenderClass,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

RenderClass

Class identifier for this renderer.

pName

Pointer to a description used for debugging purposes.

pUnk

Pointer to the aggregated owner object.

phr

Pointer to an HRESULT value.

Return Value

No return value.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_AvgFrameRate

The get_AvgFrameRate method calculates and retrieves the average frame rate achieved.

Syntax

HRESULT get_AvgFrameRate(
    int *piAvgFrameRate
);

Parameters

piAvgFrameRate

Pointer to the number of frames per second since streaming began.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_AvgFrameRate method.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_AvgSyncOffset

The get_AvgSyncOffset method retrieves the average of the time in milliseconds between when each frame was due and when it was actually rendered for all frames since streaming started.

Syntax

HRESULT get_AvgSyncOffset(
    int *piAvg
);

Parameters

piAvg

Pointer to the average of the time as previously described.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_AvgSyncOffset method.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_DevSyncOffset

The get_DevSyncOffset method retrieves the standard deviation of the time in milliseconds between when each frame was due and when it was actually rendered, for all frames since streaming started.

Syntax

HRESULT get_DevSyncOffset(
    int *piDev
);

Parameters

piDev

Pointer to the standard deviation of the time as previously described.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_DevSyncOffset method.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_FramesDrawn

The get_FramesDrawn method retrieves the m_cFramesDrawn member variable, giving the number of frames drawn since streaming started.

Syntax

HRESULT get_FramesDrawn(
    int *pcFramesDrawn
);

Parameters

pcFramesDrawn

Pointer to the number of frames drawn.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_FramesDrawn method.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_FramesDroppedInRenderer

The get_FramesDroppedInRenderer method retrieves the number of frames dropped by the renderer.

Syntax

HRESULT get_FramesDroppedInRenderer(
    int *pcFramesDropped
);

Parameters

pcFramesDropped

Pointer to the number of frames dropped.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_FramesDroppedInRenderer method. This is how the property page retrieves the data from the scheduler. Frames can also be dropped upstream without the renderer even seeing them.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::get_Jitter

The get_Jitter method retrieves the standard deviation of time in milliseconds between each frame and the next for all frames since streaming started.

Syntax

HRESULT get_Jitter(
    int *piJitter
);

Parameters

piJitter

Pointer to the standard deviation of the interframe time, in milliseconds.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_Jitter method.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::GetStdDev

The GetStdDev method estimates the standard deviation in milliseconds between when each frame is due and when it is actually rendered, for per-frame statistics.

Syntax

HRESULT GetStdDev(
    int nSamples,
    int *piResult,
    LONGLONG llSumSq,
    LONGLONG iTot
);

Parameters

nSamples

Integer value that contains the number of video samples received by the video renderer.

piResult

Pointer to an integer value that will contain the standard deviation.

llSumSq

Value that represents the standard deviation, in milliseconds, of all rendered video samples. The lower the value, the more consistent the rendering.

iTot

Value that represents the mean value, in milliseconds, between the stamped time and rendered time for all rendered video samples.

Return Value

Returns NOERROR.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::JoinFilterGraph

The JoinFilterGraph method sends EC_WINDOW_DESTROYED event notification when a filter is removed from the filter graph.

Syntax

HRESULT JoinFilterGraph(
    IBaseFilterGraph *pGraph,
    LPCWSTR pName
);

Parameters

pGraph

Pointer to the filter graph to join.

pName

[in, string] Pointer to the name of the filter being added.

Return Value

No return value.

Remarks

This member function overrides the CBaseFilter::JoinFilterGraph member function. If the filter is leaving the filter graph (pGraph is null), it sends an EC_WINDOW_DESTROYED event notification so that the resource manager does not hold on to the renderer as a focus object.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::Notify

The Notify method receives a notification that a quality change is requested.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf

[in] Pointer to the filter that is sending the quality notification.

q

[in] Quality notification structure.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualityControl::Notify method on the video renderer. This is called, typically by the filter graph manager, when the quality must be cut back. This might occur when the quality of audio playback has been increased to the point that the video playback quality must be decreased.

Notify sets the m_trThrottle data member to a delay value to be inserted between frames by ThrottleWait.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnDirectRender

The OnDirectRender method collects timing information that controls synchronization and quality control.

Syntax

virtual void OnDirectRender(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the media sample.

Return Value

Returns an HRESULT value.

Remarks

Call this member function instead of OnRenderStart and OnRenderEnd. This is used by the Microsoft® DirectDraw® video renderer.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnRenderEnd

The OnRenderEnd method performs smoothing for cases where the rendering time varies due to interruptions.

Syntax

void OnRenderEnd(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the media sample.

Return Value

No return value.

Remarks

This member function should be called just after drawing an image.

This member function overrides CBaseRenderer::OnRenderEnd.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnRenderStart

The OnRenderStart method sets information for rendering.

Syntax

void OnRenderStart(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the media sample.

Return Value

No return value.

Remarks

This member function retrieves the current clock time from the system and stores it in a member variable to be used when the drawing is complete. The function also performs performance logging. This member function should be called just before drawing starts.

This member function overrides CBaseRenderer::OnRenderStart.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnStartStreaming

The OnStartStreaming method resets all times that control streaming.

Syntax

HRESULT OnStartStreaming(void);

Return Value

Returns an HRESULT value.

Remarks

This member function overrides CBaseRenderer::OnStartStreaming.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnStopStreaming

The OnStopStreaming method is called at the end of streaming to fix times for the property page report.

Syntax

HRESULT OnStopStreaming(void);

Return Value

Returns an HRESULT value.

Remarks

This member function is called twice, once when pausing and again when the stream is actually stopped.

This member function overrides CBaseRenderer::OnStopStreaming.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnWaitEnd

The OnWaitEnd method is called when a wait time ends.

Syntax

void OnWaitEnd(void);

Return Value

No return value.

Remarks

This member function does only performance logging. It is called when the thread is awoken from waiting in the window, or when the next sample is due to be rendered. It could eventually be used to gather information that controls synchronization.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::OnWaitStart

The OnWaitStart method updates times spent waiting and not waiting.

Syntax

void OnWaitStart(void);

Return Value

No return value.

Remarks

This member function is called when starting to wait for a rendering event. It is used only for performance measurements.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::PreparePerformanceData

The PreparePerformanceData method sets the m_trLate and m_trFrame values of the current frame.

Syntax

void PreparePerformanceData(
    int trLate,
    int trFrame
);

Parameters

trLate

Value indicating how late the sample was beyond its due time, in reference time units.

trFrame

Interframe time, in reference time units.

Return Value

No return value.

Remarks

This member function sets m_trLate to the value of trLate and m_trFrame to the value of trFrame.

When the CBaseVideoRenderer::RecordFrameLateness member function is called from either CBaseVideoRenderer::OnRenderStart or CBaseVideoRenderer::OnDirectRender, it passes the values of m_trLate and m_trFrame for it to update the statistics. PreparePerformanceData is called from CBaseVideoRenderer::OnWaitEnd to set these data member values.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::RecordFrameLateness

The RecordFrameLateness method records how timely the rendering occurred and gathers statistics for the property page.

Syntax

virtual void RecordFrameLateness(
    int trLate,
    int trFrame
);

Parameters

trLate

Value indicating how late the sample was beyond its due time, in reference time units.

trFrame

Interframe time, in reference time units.

Return Value

No return value.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::ResetStreamingTimes

The ResetStreamingTimes method resets all times that control the streaming.

Syntax

virtual HRESULT ResetStreamingTimes(void);

Return Value

Returns an HRESULT value.

Remarks

The times are set so that frames will not be initially dropped and so that the first frame will be drawn.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::ScheduleSample

The ScheduleSample method overrides the base class that does the main work to keep a count of samples drawn and dropped (which are used by the IQualProp implementation).

Syntax

BOOL ScheduleSample(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the media sample.

Return Value

Returns TRUE if the sample is scheduled; otherwise, returns FALSE.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::SendQuality

The SendQuality method sends a quality message to indicate what the supplier should do about quality.

Syntax

virtual HRESULT SendQuality(
    REFERENCE_TIME trLate,
    REFERENCE_TIME trRealStream
);

Parameters

trLate

Amount of time by which the frame is late.

trRealStream

Current stream time.

Return Value

Returns an HRESULT value.

Remarks

This member function sends a quality control message upstream to control quality management. The nature of the quality message (that is, whether to reduce or increase the number of samples) is determined in the quality management implementation in this derived class (see CBaseVideoRenderer::ShouldDrawSampleNow).

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::SetSink

The SetSink method sets the IQualityControl object that will receive quality messages.

Syntax

HRESULT SetSink(
    IQualityControl *piqc
);

Parameters

piqc

Pointer to the IQualityControl object to which the notifications should be sent.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualityControl::SetSink method on the video renderer.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::ShouldDrawSampleNow

The ShouldDrawSampleNow method determines if the video should be drawn without setting a timer advise link with the clock.

Syntax

virtual HRESULT ShouldDrawSampleNow(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *ptrStart,
    REFERENCE_TIME *ptrEnd
);

Parameters

pMediaSample

Pointer to the IMediaSample interface for the sample.

ptrStart

Pointer to the time to begin rendering.

ptrEnd

Pointer to the time to stop rendering.

Return Value

Returns an HRESULT value. Returns S_OK to mean draw at once without waiting, S_FALSE to mean draw at time ptrStart, or an error to mean do not draw the sample; that is, skip it to save time.

Remarks

This member function overrides CBaseRenderer::ShouldDrawSampleNow.

See Also

  • CBaseVideoRenderer Class


CBaseVideoRenderer::ThrottleWait

The ThrottleWait method inserts a wait period after each frame.

Syntax

void ThrottleWait(void);

Return Value

No return value.

Remarks

This member function waits for a time period obtained from the m_trThrottle data member.

See Also

  • CBaseVideoRenderer Class


CBaseVideoWindow Class

CBaseVideoWindow Class Hierarchy

The CBaseVideoWindow class implements the IDispatch methods of the IVideoWindow interface. The remaining IVideoWindow methods are left as pure virtual methods, and must be implemented by a derived class.

The IDispatch methods in this class are standard implementations, and are not described in detail here.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • CBaseControlWindow Class
  • CBaseDispatch Class


CBaseWindow Class

The CBaseWindow class is a base class for managing windows. Video renderers can use this class to create video windows. To use this class, create a derived class that inherits from CBaseWindow. In the derived class:

  • Implement the pure virtual method CBaseWindow::GetClassWindowStyles, which defines the window styles.
  • Override the CBaseWindow::OnReceiveMessage method, which handles window messages.
  • Implement a destructor that calls the CBaseWindow::DoneWithWindow method.

Before using an instance of the derived class, call the CBaseWindow::PrepareWindow method.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_hInstance | Handle to the module instance.
m_hwnd | Handle to the object's window.
m_hdc | Handle to the window's device context.
m_Width | Width of the client area, in pixels.
m_Height | Height of the client area, in pixels.
m_bActivated | Flag that specifies whether the window has been activated.
m_pClassName | Static string that contains the name of the window class.
m_ClassStyles | Class styles for the window.
m_WindowStyles | Window styles for the window.
m_WindowStylesEx | Extended window styles for the window.
m_ShowStageMessage | Private message that brings the window to the foreground.
m_ShowStageTop | Private message that sets the window style to WS_EX_TOPMOST.
m_RealizePalette | Private message that realizes the palette.
m_MemoryDC | Handle to the memory device context.
m_hPalette | Handle to the window's palette.
m_bNoRealize | Flag that specifies whether the window should realize its palette.
m_bBackground | Flag that specifies whether the palette should be a background palette.
m_bRealizing | Flag that specifies whether a new palette is being realized.
m_WindowLock | Critical section, to serialize access to the object.
m_bDoGetDC | Flag that specifies whether to retrieve the device context.
m_bDoPostToDestroy | Flag that specifies whether the window posts or sends its destruction message.
Protected Methods |
OnPaletteChange | Handles palette-change messages. Virtual.
Public Methods |
CBaseWindow | Constructor method.
DoneWithWindow | Destroys the window. Virtual.
PrepareWindow | Creates the window. Virtual.
InactivateWindow | Inactivates the window. Virtual.
ActivateWindow | Sizes the window according to the requirements of the derived class. Virtual.
OnSize | Handles WM_SIZE messages. Virtual.
OnClose | Handles WM_CLOSE messages. Virtual.
GetDefaultRect | Retrieves the default size of the client area. Virtual.
UninitialiseWindow | Releases the window's resources. Virtual.
InitialiseWindow | Initializes the window. Virtual.
CompleteConnect | Notifies the window that the renderer's input pin has been connected.
DoCreateWindow | Creates the window.
PerformanceAlignWindow | Aligns the window to a DWORD boundary, for maximum performance.
DoShowWindow | Sets the window's show state.
PaintWindow | Causes the window to be repainted.
DoSetWindowForeground | Brings the window to the foreground.
SetPalette | Installs a palette for the window. Virtual.
SetRealize | Specifies whether the window realizes palettes.
DoRealisePalette | Realizes the window's current palette. Virtual.
PossiblyEatMessage | Enables a derived class to forward messages to another window. Virtual.
GetWindowWidth | Retrieves the current width of the window.
GetWindowHeight | Retrieves the current height of the window.
GetWindowHWND | Retrieves a handle to the window.
GetMemoryHDC | Retrieves a handle to the memory device context.
GetWindowHDC | Retrieves a handle to the window's device context.
OnReceiveMessage | Handles window messages. Virtual.
UnsetPalette | Deletes the window's current palette and restores the default system palette.
Pure Virtual Methods |
GetClassWindowStyles | Retrieves the window's class styles and window styles.

See Also

  • CDrawImage Class
  • CBaseControlWindow Class


CBaseWindow::m_hInstance

Handle to the module instance.

Syntax

HINSTANCE m_hInstance;

Remarks

The DLL entry point function sets a global variable with a handle to the module instance. The CBaseWindow class stores this handle in its constructor method.

See Also

  • CBaseWindow Class


CBaseWindow::m_hwnd

Handle to the object's window.

Syntax

HWND m_hwnd;

See Also

  • CBaseWindow Class


CBaseWindow::m_hdc

Handle to the window's device context.

Syntax

HDC m_hdc;

See Also

  • CBaseWindow Class


CBaseWindow::m_Width

Width of the client area, in pixels.

Syntax

LONG m_Width;

See Also

  • CBaseWindow Class


CBaseWindow::m_Height

Height of the client area, in pixels.

Syntax

LONG m_Height;

See Also

  • CBaseWindow Class


CBaseWindow::m_bActivated

Flag that specifies whether the window has been activated. If TRUE, the window has been activated.

Syntax

BOOL m_bActivated;

See Also

  • CBaseWindow Class


CBaseWindow::m_pClassName

Static string that contains the name of the window class.

Syntax

LPTSTR m_pClassName;

See Also

  • CBaseWindow Class


CBaseWindow::m_ClassStyles

Class styles for the window.

Syntax

DWORD m_ClassStyles;

See Also

  • CBaseWindow Class


CBaseWindow::m_WindowStyles

Window styles for the window.

Syntax

DWORD m_WindowStyles;

See Also

  • CBaseWindow Class


CBaseWindow::m_WindowStylesEx

Extended window styles for the window.

Syntax

DWORD m_WindowStylesEx;

See Also

  • CBaseWindow Class


CBaseWindow::m_ShowStageMessage

Private message that brings the window to the foreground.

Syntax

UINT m_ShowStageMessage;

Remarks

The CBaseWindow::DoSetWindowForeground method sends this message.

See Also

  • CBaseWindow Class


CBaseWindow::m_ShowStageTop

Private message that sets the window style to WS_EX_TOPMOST.

Syntax

UINT m_ShowStageTop;

Remarks

Video renderers should send this message to the window if they switch to full-screen mode.

See Also

  • CBaseWindow Class


CBaseWindow::m_RealizePalette

Private message that realizes the palette.

Syntax

UINT m_RealizePalette;

Remarks

The CBaseWindow::SetPalette method sends this message.

See Also

  • CBaseWindow Class


CBaseWindow::m_MemoryDC

Handle to the memory device context.

Syntax

HDC m_MemoryDC;

See Also

  • CBaseWindow Class


CBaseWindow::m_hPalette

Handle to the window's palette.

Syntax

HPALETTE m_hPalette;

See Also

  • CBaseWindow Class


CBaseWindow::m_bNoRealize

Flag that specifies whether the window should realize its palette. If TRUE, the window does not realize its palette. The default value is FALSE.

Syntax

BYTE m_bNoRealize;

See Also

  • CBaseWindow Class


CBaseWindow::m_bBackground

Flag that specifies whether the palette should be a background palette. If TRUE, the palette is selected as a background palette.

Syntax

m_bBackground;

See Also

  • CBaseWindow Class


CBaseWindow::m_bRealizing

Flag that specifies whether a new palette is being realized. In debug builds, the value is TRUE while the palette is changing and FALSE otherwise. This variable is not used in retail builds.

Syntax

BYTE m_bRealizing;

See Also

  • CBaseWindow Class


CBaseWindow::m_WindowLock

Critical section, to serialize access to the object.

Syntax

CCritSec m_WindowLock;

See Also

  • CBaseWindow Class


CBaseWindow::m_bDoGetDC

Flag that specifies whether to retrieve the device context (DC). If TRUE, the object retrieves a handle to the window's DC and creates a compatible memory DC.

Syntax

BOOL m_bDoGetDC;

See Also

  • CBaseWindow Class


CBaseWindow::m_bDoPostToDestroy

Flag that specifies whether the window posts or sends its destruction message. If TRUE, the CBaseWindow::DoneWithWindow method uses the PostMessage function to send itself a private destruction message. If FALSE, DoneWithWindow uses the SendMessage function to send the message. By default, the value is FALSE.

Syntax

BOOL m_bDoPostToDestroy;

See Also

  • CBaseWindow Class


CBaseWindow::ActivateWindow

The ActivateWindow method sizes the window according to the requirements of the derived class.

Syntax

virtual HRESULT ActivateWindow(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Window was already activated.
S_OK | Success.

Remarks

This methods calls the CBaseWindow::GetDefaultRect method to determine the window size. The derived class should override GetDefaultRect to return the size of the images that will be displayed.

If the window is already active, calling ActivateWindow moves the window to the top of the Z order, but does not resize the window. The same is true if the window has a parent.

See Also

  • CBaseWindow Class


CBaseWindow::CBaseWindow

Constructor method.

Syntax

CBaseWindow(
    BOOL bDoGetDC = TRUE
    BOOL bPostToDestroy = FALSE
);

Parameters

bDoGetDC

Boolean value that specifies whether to retrieve the device context.

bPostToDestroy

Boolean value that specifies the CBaseWindow::m_bDoPostToDestroy member variable.

Remarks

After you create the object, call the CBaseWindow::PrepareWindow method to create the window. PrepareWindow is a virtual method. It calls CBaseWindow::InitialiseWindow, also a virtual method. These methods are separated from the constructor so that derived classes can override them, if necessary.

If the value of the bDoGetDC parameter is TRUE, the CBaseWindow object retrieves a handle to the window's device context (DC) and stores it in the CBaseWindow::m_hdc member variable. The object also creates a compatible memory DC, which it stores in the CBaseWindow::m_MemoryDC member variable. These actions occur in the InitialiseWindow method.

See Also

  • CBaseWindow Class


CBaseWindow::CompleteConnect

The CompleteConnect method notifies the window that the renderer's input pin has been connected.

Syntax

HRESULT CompleteConnect(void);

Return Value

Returns S_OK.

Remarks

This method resets the window activation flag (CBaseWindow::m_bActivated) to FALSE. When a video renderer completes a pin connection, it might call the CBaseWindow::ActivateWindow method to set the window's size and position. To force ActivateWindow to recalculate these attributes, first call the CompleteConnect method.

See Also

  • CBaseWindow Class


CBaseWindow::DoCreateWindow

The DoCreateWindow method creates the window.

Syntax

HRESULT DoCreateWindow(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

The CBaseWindow::PrepareWindow method calls this method.

See Also

  • CBaseWindow Class


CBaseWindow::DoneWithWindow

The DoneWithWindow method destroys the window.

Syntax

virtual HRESULT DoneWithWindow(void);

Return Value

Returns S_OK.

Remarks

Call this method from the derived object's destructor method.

If this method is called from the same thread that created the window, the method performs the following actions:

  • Calls the CBaseWindow::InactivateWindow method, which deactivates the window.
  • Calls the CBaseWindow::UninitialiseWindow method, which releases resources used by the window.
  • Destroys the window.

If the thread calling DoneWithWindow is not the thread that created the window, the method sends a private "destroy" message to the window. When the window receives this message, it calls DoneWithWindow on itself. (If CBaseWindow::m_bDoPostToDestroy is TRUE, the window posts the message.)

See Also

  • CBaseWindow Class


CBaseWindow::DoRealisePalette

The DoRealisePalette method realizes the window's current palette.

Syntax

virtual HRESULT DoRealisePalette(
    BOOL bForceBackground
);

Parameters

bForceBackground

Boolean value that specifies whether the palette is forced to be a background palette. For more information, see SelectPalette in the Platform SDK.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | An internal call to GdiFlush returned an error.
S_OK | Success.

Remarks

The CBaseWindow::OnPaletteChange method calls this method. To set a new palette, call the CBaseWindow::SetPalette method.

See Also

  • CBaseWindow Class


CBaseWindow::DoSetWindowForeground

The DoSetWindowForeground method brings the window to the foreground.

Syntax

void DoSetWindowForeground(
    BOOL bFocus
);

Parameters

bFocus

Boolean value that specifies whether to give the window focus. If the value is TRUE, the window gains focus.

See Also

  • CBaseWindow Class


CBaseWindow::DoShowWindow

The DoShowWindow method sets the window's show state.

Syntax

HRESULT DoShowWindow(
    LONG ShowCmd
);

Parameters

ShowCmd

Flag that specifies how the window is to be shown. The value can be any constant defined for the nCmdShow parameter of the Microsoft® Windows® ShowWindow function. For more information, see the Platform SDK.

Return Value

Returns S_OK.

See Also

  • CBaseWindow Class


CBaseWindow::GetClassWindowStyles

The GetClassWindowStyles method retrieves the window's class styles and window styles.

Syntax

virtual LPTSTR GetClassWindowStyles(
    DWORD *pClassStyles,
    DWORD *pWindowStyles,
    DWORD *pWindowStylesEx
) PURE;

Parameters

pClassStyles

Pointer to a variable that receives the class styles.

pWindowStyles

Pointer to a variable that receives the window styles.

pWindowStylesEx

Pointer to a variable that receives the extended window styles.

Return Value

Returns a static text string that contains the class name.

Remarks

The CBaseWindow::PrepareWindow method calls this method to retrieve the window's class styles and window styles.

This method is pure virtual; the derived class must implement it. The following example shows a possible implementation:

LPTSTR CMyWindowClass::GetClassWindowStyles(DWORD *pClassStyles,
                                            DWORD *pWindowStyles,
                                            DWORD *pWindowStylesEx)
{
    *pClassStyles = CS_HREDRAW | CS_VREDRAW;
    *pWindowStyles = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
    *pWindowStylesEx = WS_EX_WINDOWEDGE;
    return TEXT("MyWindowClass");
}

The object uses the class style for the lpszClassName member of a WNDCLASS structure, which it passes to the RegisterClass function. The object uses the window styles for the dwExStyle and dwStyle parameters of the CreateWindowEx function. For more information, see the Platform SDK.

See Also

  • CBaseWindow Class


CBaseWindow::GetDefaultRect

The GetDefaultRect method retrieves the default size of the client area.

Syntax

virtual RECT GetDefaultRect(void);

Return Value

Returns the default rectangle.

Remarks

When the window is activated, the object calls this method to determine how large it should make the window's client area. In the base class, this method returns a rectangle whose height and width are the defined constants DEFHEIGHT and DEFWIDTH. A derived class should override this method. For a video renderer, the derived class will typically return the size of the native video image.

See Also

  • CBaseWindow Class


CBaseWindow::GetMemoryHDC

The GetMemoryHDC method retrieves a handle to the memory device context (DC).

Syntax

virtual HDC GetMemoryHDC(void);

Return Value

Returns a handle to the memory DC.

See Also

  • CBaseWindow Class


CBaseWindow::GetWindowHDC

The GetWindowHDC method retrieves a handle to the window's device context (DC).

Syntax

HDC GetWindowHDC(void);

Return Value

Returns a handle to the DC.

See Also

  • CBaseWindow Class


CBaseWindow::GetWindowHeight

The GetWindowHeight method retrieves the current height of the window.

Syntax

LONG GetWindowHeight(void);

Return Value

Returns the height of the window, in pixels.

See Also

  • CBaseWindow Class


CBaseWindow::GetWindowHWND

The GetWindowHWND method retrieves a handle to the window.

Syntax

HWND GetWindowHWND(void);

Return Value

Returns a handle to the window.

See Also

  • CBaseWindow Class


CBaseWindow::GetWindowWidth

The GetWindowWidth method retrieves the current width of the window.

Syntax

LONG GetWindowWidth(void);

Return Value

Returns the width of the window, in pixels.

See Also

  • CBaseWindow Class


CBaseWindow::InactivateWindow

The InactivateWindow method inactivates the window. In the base class, this method hides the window.

Syntax

virtual HRESULT InactivateWindow(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
S_FALSE | Window is already inactive.

See Also

  • CBaseWindow Class


CBaseWindow::InitialiseWindow

The InitialiseWindow method initializes the window.

Syntax

virtual InitialiseWindow(
    HWND hwnd
);

Parameters

hwnd

Handle to the window.

Return Value

Returns S_OK.

Remarks

By default, this method retrieves a handle to the window's device context (DC) and creates a compatible memory DC. If the value of the CBaseWindow::m_bDoGetDC flag is FALSE, however, this method does not retrieve the device contexts. The memory DC is useful for selecting bitmaps before blitting them to the window.

The CBaseWindow::DoCreateWindow method calls this method.

See Also

  • CBaseWindow Class


CBaseWindow::OnClose

The OnClose method handles WM_CLOSE messages.

Syntax

virtual BOOL OnClose(void);

Return Value

Returns TRUE.

Remarks

In the base class, this method simply hides the window. Typically, a derived class will override this method so that it sends an EC_USERABORT event as well. Do not override the method to destroy the window. Instead, call the CBaseWindow::DoneWithWindow method when the owning filter is destroyed.

See Also

  • CBaseWindow Class


CBaseWindow::OnPaletteChange

The OnPaletteChange method handles palette-change messages.

Syntax

virtual LRESULT OnPaletteChange(
    HWND hwnd,
    UINT Message
);

Parameters

hwnd

Handle to the window.

Message

Message identifier.

Return Value

Returns 0 if the message was processed, or 1 if the message was not processed.

Remarks

This method handles WM_PALETTECHANGED and WM_QUERYNEWPALETTE messages. It calls the CBaseWindow::DoRealisePalette method to realize the new palette.

See Also

  • CBaseWindow Class


CBaseWindow::OnReceiveMessage

The OnReceiveMessage method handles window messages.

Syntax

virtual LRESULT OnReceiveMessage(
    HWND hwnd,
    INT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hwnd

Handle to the window.

uMsg

Message identifier.

wParam

First message parameter.

lParam

Second message parameter.

Return Value

Returns 0 if the message was processed, or 1 if the message was not processed.

Remarks

The base class handles the following messages:

  • WM_CLOSE
  • WM_MOVE
  • WM_PALETTECHANGED
  • WM_QUERYNEWPALETTE
  • WM_SIZE
  • WM_SYSCOLORCHANGE

A derived class can override this method to handle other messages. The derived class should call the base class method to handle any messages that the derived class ignores.

See Also

  • CBaseWindow Class


CBaseWindow::OnSize

The OnSize method handles WM_SIZE messages.

Syntax

virtual BOOL OnSize(
    LONG Width,
    LONG Height
);

Parameters

Width

Width of the client area, in pixels.

Height

Height of the client area, in pixels.

Return Value

Returns TRUE.

Remarks

This method stores the new width and height. To retrieve these values, call the CBaseWindow::GetWindowHeight and CBaseWindow::GetWindowWidth methods.

See Also

  • CBaseWindow Class


CBaseWindow::PaintWindow

The PaintWindow method causes the window to be repainted.

Syntax

void PaintWindow(
    BOOL bErase
);

Parameters

bErase

Boolean value that specifies whether the background is erased. If the value is TRUE, the background is erased.

Remarks

This method generates a WM_PAINT message by invalidating the window's entire client area.

See Also

  • CBaseWindow Class


CBaseWindow::PerformanceAlignWindow

The PerformanceAlignWindow method aligns the window position to DWORD boundaries, for maximum performance.

Syntax

HRESULT PerformanceAlignWindow(void);

Return Value

Returns S_OK.

Remarks

This method aligns the left and top edges of the window to DWORD boundaries, which can improve performance. If the window has a parent, the method returns S_OK but does perform the alignment.

See Also

  • CBaseWindow Class


CBaseWindow::PossiblyEatMessage

The PossiblyEatMessage method enables a derived class to forward messages to another window.

Syntax

virtual BOOL PossiblyEatMessage(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

uMsg

Message identifier.

wParam

First message parameter.

lParam

Second message parameter.

Return Value

Returns TRUE if the message was forwarded, or FALSE otherwise. The base class returns FALSE.

Remarks

Before the CBaseWindow::OnReceiveMessage method handles a message, it calls PossiblyEatMessage. If PossiblyEatMessage returns TRUE, OnReceiveMessage ignores the message. A derived class can override PossiblyEatMessage so that it forwards some messages to an owner window. For example, the CBaseControlWindow class, which derives from CBaseWindow, forwards keyboard and mouse messages.

See Also

  • CBaseWindow Class


CBaseWindow::PrepareWindow

The PrepareWindow method creates the window.

Syntax

virtual HRESULT PrepareWindow(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure.

Remarks

Call this method after creating the object. This method performs some initial bookkeeping and then calls the CBaseWindow::DoCreateWindow method to create the window.

See Also

  • CBaseWindow Class


CBaseWindow::SetPalette

The SetPalette method installs a palette for the window.

Syntax

virtual HRESULT SetPalette(
    HPALETTE hPalette
);

HRESULT SetPalette(void);

Parameters

hPalette

Handle to the new palette. Cannot be NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | An internal call to GdiFlush returned an error.
S_OK | Success.

Remarks

The hPalette parameter specifies a new palette. If the method is called with no parameters, the palette given by the CBaseWindow::m_hPalette member variable is selected. The caller must ensure the validity of m_hPalette.

If the value of the CBaseWindow::m_bNoRealize member variable is FALSE (the default), this method selects the palette and realizes it. Otherwise, it selects the palette but does not realize it. The object does not delete any previous palette that it was using. The caller is responsible for deleting palettes.

Any thread can safely call this method, not just the thread that owns the window. The window sends a private message to itself, which triggers a call to the CBaseWindow::OnPaletteChange method.

See Also

  • CBaseWindow Class


CBaseWindow::SetRealize

The SetRealize method specifies whether the window realizes palettes.

Syntax

void SetRealize(
    BOOL bRealize
);

Parameters

bRealize

Boolean value that specifies whether to realize palettes. If TRUE, the CBaseWindow::SetPalette method realizes palettes.

Remarks

By default, the SetPalette method realizes the specified palette. Call this method to change the default behavior, so that palettes are selected but not realized. This method sets the CBaseWindow::m_bNoRealize member variable.

See Also

  • CBaseWindow Class


CBaseWindow::UninitialiseWindow

The UninitialiseWindow method releases the window's resources.

Syntax

virtual HRESULT UninitialiseWindow(void);

Return Value

Returns S_OK.

Remarks

This method frees resources that were acquired by the CBaseWindow::InitialiseWindow method. The CBaseWindow::DoneWithWindow method calls this method.

See Also

  • CBaseWindow Class


CBaseWindow::UnsetPalette

The UnsetPalette method deletes the window's current palette and restores the default system palette.

Syntax

void UnsetPalette(void);

Return Value

No return value.

See Also

  • CBaseWindow Class


CBasicAudio Class

CBasicAudio Class Hierarchy

The CBasicAudio class implements the IDispatch methods of the IBasicAudio interface. The remaining IBasicAudio methods are left as pure virtual methods, and must be implemented by a derived class.

The IDispatch methods in this class are standard implementations, and are not described in detail here.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • CBaseDispatch Class


CCmdQueue Class

The CCmdQueue class is a base class that provides a queue of CDeferredCommand objects and member functions to add, remove, check status, and invoke the queued commands. A CCmdQueue object is a part of an object that implements IQueueCommand methods. The filter graph manager implements IQueueCommand methods so that applications can queue commands to the filter graph. Filters that implement the IQueueCommand interface directly use this class. If you want to use CDeferredCommand objects, your queue must be derived from this class.

There are two modes of synchronization: coarse and accurate. In coarse mode, the application waits until a specified time arrives and then executes the command. In accurate mode, the application waits until processing begins on the sample that appears at the time, and then executes the command. The filter determines which one it will implement. The filter graph manager always implements coarse mode for commands that are queued at the filter graph manager.

If you want coarse synchronization, you probably want to wait until there is a command due, and then execute it. You can do this by calling CCmdQueue::GetDueCommand. If you have several things to wait for, get the event handle from CCmdQueue::GetDueHandle and then call CCmdQueue::GetDueCommand when this is signaled. stream time will advance only between calls to the CCmdQueue::Run and CCmdQueue::EndRun member functions. There is no guarantee that if the handle is set, there will be a command ready. Each time the event is signaled, call the GetDueCommand member function (probably with a time-out of zero); this can return E_ABORT if no command is ready.

If you want accurate synchronization, call the CCmdQueue::GetCommandDueFor member function and pass the samples you are about to process as a parameter. This returns the following:

  • A stream-time command due at or before that stream time.
  • A presentation-time command due at or before the presentation of the stream time. Do this only between the CCmdQueue::Run and CCmdQueue::EndRun member functions, because outside of this, the mapping from stream time to presentation time is not known.
  • Any presentation-time command due now.

If you want accurate synchronization for samples that might be processed during paused mode, you must use stream-time commands.

In all cases, commands remain queued until called or canceled. The setting and resetting of the event handle is managed entirely by this queue object.

Protected Data Members

m_bRunning | Flag for running state; set TRUE when running.
m_dwAdvise | Advise identifier from the reference clock (zero if no outstanding advise).
m_evDue | Sets the time when any commands are due.
m_listPresentation | Stores commands queued in presentation time.
m_listStream | Stores commands queued in stream time.
m_Lock | Protects access to lists.
m_pClock | Current reference clock.
m_StreamTimeOffset | Contains the stream time offset when m_bRunning is true.
m_StreamTimeOffset | Contains the stream time offset when m_bRunning is true.

Member Functions

CCmdQueue | Constructs a CCmdQueue object.
CheckTime | Determines if a given time is due.
GetDueHandle | Retrieves the event handle that will be signaled.

Overridable Member Functions

EndRun | Switches to stopped or paused mode.
GetCommandDueFor | Retrieves a deferred command that is scheduled at a specified time.
GetDueCommand | Retrieves a pointer to the next command that is due.
Insert | Adds the CDeferredCommand object to the queue.
New | Initializes a command to be run and returns a new CDeferredCommand object.
Remove | Removes the CDeferredCommand object from the queue.
Run | Switches to running mode.
SetSyncSource | Sets the clock used for timing.
SetTimeAdvise | Sets up a timer event with the reference clock.


CCmdQueue::CCmdQueue

Constructor method.

Syntax

CCmdQueue(void);

See Also

  • CCmdQueue Class


CCmdQueue::CheckTime

The CheckTime method determines if a specified time is due.

Syntax

BOOL CheckTime(
    CRefTime time,
    BOOL bStream
);

Parameters

time

Time to check.

bStream

TRUE if the time parameter is a stream-time value; FALSE if time is a presentation-time value.

Return Value

Returns TRUE if the specified time has not yet passed.

See Also

  • CCmdQueue Class


CCmdQueue::EndRun

The EndRun method switches to the stopped or paused mode.

Syntax

virtual HRESULT EndRun(void);

Return Value

Returns an HRESULT value that depends on the implementation.

Remarks

Time mapping between stream time and presentation time is not known after this member function has been called. Call the CCmdQueue::Run member function to carry out this mapping.

See Also

  • CCmdQueue Class


CCmdQueue::GetCommandDueFor

The GetCommandDueFor method retrieves a deferred command that is scheduled at a specified time.

Syntax

virtual HRESULT GetCommandDueFor(
    REFERENCE_TIME tStream,
    CDeferredCommand **ppCmd
);

Parameters

tStream

Time for which the command is scheduled.

ppCmd

Address of a pointer to the deferred command to be carried out at the time specified in the tStream parameter.

Return Value

Returns VFW_E_NOT_FOUND if no commands are due; otherwise, returns S_OK.

Remarks

This member function takes a stream time and returns the deferred command scheduled at that time. The actual stream-time offset is calculated when the command queue is run. Commands remain queued until run or canceled. This member function will not block.

See Also

  • CCmdQueue Class


CCmdQueue::GetDueCommand

The GetDueCommand method retrieves a pointer to the next command that is due.

Syntax

virtual HRESULT GetDueCommand(
    CDeferredCommand **ppCmd,
    long msTimeout
);

Parameters

ppCmd

Address of a pointer to the deferred command.

msTimeout

Amount of time to wait before carrying out the time-out.

Return Value

Returns E_ABORT if a time-out occurs. Returns S_OK if successful; otherwise, returns an error. Returns an object that has been incremented using IUnknown::AddRef.

Remarks

This member function blocks until a pending command is due. The member function blocks for the amount of time, in milliseconds, specified in the msTimeout parameter. Stream-time commands become due only between the CCmdQueue::Run and CCmdQueue::EndRun member functions. The command remains queued until run or canceled.

See Also

  • CCmdQueue Class


CCmdQueue::GetDueHandle

The GetDueHandle method retrieves the event handle to be signaled.

Syntax

HANDLE GetDueHandle(void);

Return Value

Returns the event handle.

Remarks

Return the event handle whenever there are deferred commands that are due for execution (when CCmdQueue::GetDueCommand will not block).

See Also

  • CCmdQueue Class


CCmdQueue::Insert

The Insert method adds the CDeferredCommand object to the queue.

Syntax

virtual HRESULT Insert(
    CDeferredCommand *pCmd
);

Parameters

pCmd

Pointer to the CDeferredCommand object to add to the queue.

Return Value

Returns S_OK in the default implementation.

See Also

  • CCmdQueue Class


CCmdQueue::New

The New method initializes a command to be run and returns a new CDeferredCommand object.

Syntax

virtual HRESULT New(
    CDeferredCommand **ppCmd,
    LPUNKNOWN pUnk,
    REFTIME time,
    GUID *iid,
    long dispidMethod,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr,
    BOOL bStream
);

Parameters

ppCmd

Address of a pointer to a CDeferredCommand object by which an application can cancel the command, set a new presentation time for it, or retrieve estimate information.

pUnk

Pointer to the object that will run the command.

time

Time at which to run the queued command or commands.

iid

Pointer to the globally unique identifier (GUID) of the interface to call.

dispidMethod

Method on the interface to be called.

wFlags

Flags describing the context of the call. This parameter supports the same flags as the IDispatch::Invoke method.

cArgs

Number of arguments passed.

pDispParams

Pointer to the list of variant types associated with the dispatch parameters.

pvarResult

Pointer to the list where results, if any, are to be returned.

puArgErr

Pointer to the index within the pDispParams parameter list where the last error occurred.

bStream

Value indicating whether the time parameter is a stream-time value (TRUE) or a presentation-time value (FALSE).

Return Value

Returns S_OK if successful. Returns E_OUTOFMEMORY if ppCmd returns from creating the new CDeferredCommand object with a value of NULL. Otherwise, returns an HRESULT that indicates an error from attempting to create a new CDeferredCommand object. If there is an error, no object has been queued.

Remarks

The new CDeferredCommand object will be initialized with the parameters and will be added to the queue during construction. This method is similar to the IDispatch::Invoke method.

Values for the wFlags parameter include the following:

Value | Description
DISPATCH_METHOD | The member is being run as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag can be set.
DISPATCH_PROPERTYGET | The member is being retrieved as a property or data member.
DISPATCH_PROPERTYPUT | The member is being changed as a property or data member.
DISPATCH_PROPERTYPUTREF | The member is being changed via a reference assignment, rather than a value assignment. This value is valid only when the property accepts a reference to an object.

See Also

  • CCmdQueue Class


CCmdQueue::Remove

The Remove method removes the CDeferredCommand object from the queue.

Syntax

virtual HRESULT Remove(
    CDeferredCommand *pCmd
);

Parameters

pCmd

Pointer to the CDeferredCommand object to remove from the queue.

Return Value

Returns VFW_E_NOT_FOUND if the object is not found in the queue. Otherwise, returns S_OK.

See Also

  • CCmdQueue Class


CCmdQueue::Run

The Run method switches to running mode so that commands that are deferred by the stream time can be run.

Syntax

virtual HRESULT Run(
    REFERENCE_TIME tStreamTimeOffset
);

Parameters

tStreamTimeOffset

Offset time.

Return Value

Returns S_OK.

Remarks

During running mode, stream-time-to-presentation-time mapping is known.

See Also

  • CCmdQueue Class


CCmdQueue::SetSyncSource

The SetSyncSource method sets the clock used for timing.

Syntax

virtual HRESULT SetSyncSource(
    IReferenceClock *pIrc
);

Parameters

pIrc

Pointer to the IReferenceClock interface.

Return Value

Returns S_OK.

See Also

  • CCmdQueue Class


CCmdQueue::SetTimeAdvise

The SetTimeAdvise method sets up a timer event with the reference clock.

Syntax

void SetTimeAdvise(void);

Return Value

No return value.

Remarks

This member function calls the IReferenceClock::AdviseTime method to set up a notification for the earliest time required in the queue. Presentation-time commands that are deferred are always checked. If the filter graph is in running mode, deferred commands using stream time are also checked.

See Also

  • CCmdQueue Class


CCritSec Class

The CCritSec class provides a thread lock.

This class is a wrapper for a critical section. You can lock and unlock the thread by calling the CCritSec::Lock and CCritSec::Unlock methods. However, it is safer to use this class in conjunction with the CAutoLock class. When the CAutoLock class goes out of scope, it automatically unlocks the CCritSec object. Moreover, it compiles to efficient inline code.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Member Variables |
m_currentOwner | Thread identifier of the owning thread.
m_lockCount | Number of outstanding locks on this object.
m_fTrace | Boolean value that specifies whether to trace this lock.
Public Methods |
CCritSec | Constructor method.
~CCritSec | Destructor method.
Lock | Locks the critical section object.
Unlock | Unlocks the critical section object.


CCritSec::m_currentOwner

Thread identifier of the owning thread.

Syntax

DWORD m_currentOwner;

Remarks

This member variable is defined only in the debug version of the base class. The Critical Section Debugging Functions use this member.

See Also

  • CCritSec Class


CCritSec::m_lockCount

Number of outstanding locks on this object.

Syntax

DWORD m_lockCount;

Remarks

This member variable is defined only in the debug version of the base class. The Critical Section Debugging Functions functions use this member.

See Also

  • CCritSec Class


CCritSec::m_fTrace

Boolean value that specifies whether to trace this lock.

Syntax

BOOL m_fTrace;

Remarks

This member variable is defined only in the debug version of the base class. If the value is TRUE, a trace of the lock state is written to the debug log. (Debug logging for critical sections must be active.) For more information, see DbgLockTrace.

See Also

  • CCritSec Class


CCritSec::CCritSec

Constructor method.

Syntax

CCritSec(void);

Remarks

This method calls the Microsoft® Win32® InitializeCriticalSection function to initialize the critical section.

See Also

  • CCritSec Class


CCritSec::~CCritSec

Destructor method.

Syntax

~CCritSec(void);

Remarks

This method calls the Microsoft® Win32® DeleteCriticalSection function to delete the critical section.

See Also

  • 6CCritSec Class


CCritSec::Lock

The Lock method locks the critical section object.

Syntax

void Lock(void);

Remarks

This method calls the Microsoft® Win32® EnterCriticalSection method.

Call the CCritSec::Unlock member function to unlock the critical section. You can make multiple calls to the Lock method on the same thread; be sure to call Unlock a corresponding number of times.

If the object is already locked by another thread, the CCritSec::Lock method blocks until the object is released, or until a possible-deadlock exception occurs.

See Also

  • CCritSec Class


CCritSec::Unlock

The Unlock method unlocks the critical section object.

Syntax

void Unlock(void);

Remarks

This method calls the Microsoft® Win32® LeaveCriticalSection method. Call this method once for each call to the CCritSec::Lock method.

See Also

  • CCritSec Class


CDeferredCommand Class

CDeferredCommand Class Hierarchy

Deferred commands are queued by calls to methods on the IQueueCommand interface and are exposed by the filter graph manager and by some filters. A successful call to one of these methods returns an IDeferredCommand interface representing the queued command.

A CDeferredCommand object represents a single deferred command and exposes the IDeferredCommand interface as well as other methods that permit time checks and actual execution. A CDeferredCommand object contains a reference to the CCmdQueue object on which it is queued.

Reference counts control the lifetime of the CDeferredCommand class. When calling the CDeferredCommand::Invoke member function, the calling application gets an interface pointer that is reference-counted, and the CCmdQueue object also holds a reference count on the deferred command. Calling the IDeferredCommand::Cancel member function takes the deferred command off the command queue and thus reduces the reference count by one. Once taken off the queue, the command cannot be put back on the queue.

Protected Data Members

m_bStream | Flag for stream time or presentation time. to be passed to the invoked method.
m_Dispatch | Accesses the ITypeInfo interface.
m_dispidMethod | Method on the interface to run.
m_DispParams | CDispParams object containing the DISPPARAMS parameter list
m_hrResult | Stores the returned HRESULT value.
m_iid | Globally unique identifier (GUID) of the interface.
m_pQueue | Pointer to the CCmdQueue object that exposes the IQueueCommand interface.
m_pUnk | IUnknown pointer to the interface on which the command will be run.
m_pvarResult | Resulting information, if any, from the invoked method.
m_time | Time at which the command will be run.
m_wFlags | Flags specifying the context of the invocation.

Member Functions

CDeferredCommand | Constructs a CDeferredCommand object.
GetFlags | Retrieves the context flags associated with the deferred command.
GetIID | Retrieves the interface identifier (IID) of the interface on which the method will be run.
GetMethod | Retrieves the dispatch identifier of the method to be run.
GetParams | Retrieves the DISPPARAMS argument list to the method.
GetResult | Retrieves the resulting argument list, if one exists.
GetTime | Retrieves the time when the method will be run.
Invoke | Provides access to methods and properties exposed by an object.
IsStreamTime | Specifies whether the command is to be run at stream time or presentation time.

Implemented IDeferredCommand Methods

Cancel | Cancels a previously queued CDeferredCommand::Invoke request.
Confidence | Not currently implemented.
Postpone | Specifies a new presentation time for a previously queued command.
GetHResult | Retrieves the HRESULT value of the invoked method.


CDeferredCommand::Cancel

The Cancel method cancels a previously queued CDeferredCommand::Invoke request.

Syntax

HRESULT Cancel(void);

Return Value

Returns VFW_E_ALREADY_CANCELLED if m_pQueue is NULL. Returns an HRESULT from CCmdQueue::Remove if the call generates an error. Returns S_OK if successful.

Remarks

This member function implements the IDeferredCommand::Cancel method.

See Also

  • CDeferredCommand Class


CDeferredCommand::CDeferredCommand

Constructor method.

Syntax

CDeferredCommand(
    CCmdQueue *pQ,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    LPUNKNOWN pUnkExecutor,
    REFTIME time,
    GUID *iid,
    long dispidMethod,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr,
    BOOL bStream
);

Parameters

pQ

Pointer to an object that exposes the IQueueCommand interface.

pUnk

Pointer to the outer IUnknown interface for aggregation.

phr

Pointer to a returned HRESULT value.

pUnkExecutor

Pointer to the object that will carry out this command.

time

Time at which the command will be run.

iid

Pointer to the globally unique identifier (GUID) of the interface that contains the method.

dispidMethod

Method on the interface to call.

wFlags

Context of the invocation.

cArgs

Number of arguments passed.

pDispParams

Pointer to a list of argument variant types.

pvarResult

Pointer to a returned variant type list, if any.

puArgErr

Pointer to the last argument in the pDispParams parameter list with an error.

bStream

Value indicating whether the deferred command time is in stream time (TRUE) or presentation time (FALSE).

Return Value

No return value.

See Also

  • CDeferredCommand Class


CDeferredCommand::Confidence

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Confidence(
    LONG *pConfidence
);

Parameters

pConfidence

Pointer to the confidence level.

Return Value

Returns E_NOTIMPL.

Remarks

For information about implementing this method, see IDeferredCommand::Confidence.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetFlags

The GetFlags method retrieves the context flags associated with the deferred command.

Syntax

short GetFlags(void);

Return Value

Returns one of the following:

Value | Description
DISPATCH_METHOD | Run the member as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag can be set.
DISPATCH_PROPERTYGET | The member is being retrieved as a property or data member.
DISPATCH_PROPERTYPUT | The member is being changed as a property or data member.
DISPATCH_PROPERTYPUTREF | The member is being changed via a reference assignment, rather than a value assignment. This flag is valid only when the property accepts a reference to an object.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetHResult

The GetHResult method retrieves the HRESULT value from the invoked command.

Syntax

HRESULT GetHResult(
    HRESULT *phrResult
);

Parameters

phrResult

Pointer to the HRESULT value.

Return Value

Returns E_ABORT if m_pQueue is NULL. Otherwise, returns S_OK.

Remarks

This member function implements the IDeferredCommand::GetHResult method.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetIID

The GetIID method retrieves the interface identifier (IID) of the interface on which the method will be run.

Syntax

REFIID GetIID(void);

Return Value

Returns the IID of the interface on which the method will be run.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetMethod

The GetMethod method retrieves the dispatch identifier (DISPID) of the method to be run.

Syntax

long GetMethod(void);

Return Value

Returns the DISPID of the method to run.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetParams

The GetParams method retrieves the DISPPARAMS argument list to the method.

Syntax

DISPPARAMS* GetParams(void);

Return Value

Returns a DISPPARAMS argument list.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetResult

The GetResult method retrieves the resulting argument list, if one exists.

Syntax

VARIANT* GetResult(void);

Return Value

Returns a VARIANT containing the method's argument list, if it exists.

See Also

  • CDeferredCommand Class


CDeferredCommand::GetTime

The GetTime method retrieves the time at which the method will be run.

Syntax

CRefTime GetTime(void);

Return Value

Returns a CRefTime object containing a reference time.

See Also

  • CDeferredCommand Class


CDeferredCommand::Invoke

The Invoke method provides access to methods and properties exposed by an object.

Syntax

HRESULT Invoke(void);

Return Value

Returns VFW_E_ALREADY_CANCELLED if m_pQueue is NULL. Otherwise, returns the HRESULT resulting from a call to IDispatch::GetTypeInfo or IUnknown::QueryInterface.

See Also

  • CDeferredCommand Class


CDeferredCommand::IsStreamTime

The IsStreamTime method specifies whether the command is to be run at stream time or presentation time.

Syntax

BOOL IsStreamTime(void);

Return Value

Returns TRUE if set to stream time; otherwise, returns FALSE.

See Also

  • CDeferredCommand Class


CDeferredCommand::Postpone

The Postpone method specifies a new presentation time for a previously queued command.

Syntax

HRESULT Postpone(
    REFTIME newtime
);

Parameters

newtime

New presentation time.

Return Value

Returns VFW_E_TIME_ALREADY_PASSED if newtime is already passed. Otherwise, returns an HRESULT resulting from a call to CCmdQueue::Remove (when extracting from the list) or CCmdQueue::Insert (when reinserting with the changed time).

Remarks

This member function implements the IDeferredCommand::Postpone method.

See Also

  • CDeferredCommand Class


CDispParams Class

CDispParams Class Hierarchy

The CDispParams class implements the DISPPARAMS structure used in Automation as a C++ base class. The IDispatch::Invoke method uses the OLE DISPPARAMS structure to contain the arguments passed to any method or property.

The DISPPARAMS structure is defined as follows:

typedef struct FARSTRUCT tagDISPPARAMS{
VARIANTARG FAR* rgvarg;               // Array of arguments
   DISPID FAR* rgdispidNamedArgs;     // Dispatch IDs of named arguments
   unsigned int cArgs;                // Number of arguments
   unsigned int cNamedArgs;           // Number of named arguments
} DISPPARAMS;

Member Functions

CDispParams Constructs a CDispParams object.


CDispParams::CDispParams

Constructor method.

Syntax

CDispParams(
  UINT nArgs,
  VARIANT *pArgs
);

Parameters

nArgs

Number of arguments passed to the method or property.

pArgs

Pointer to the list of arguments. In the list, each argument is stored with its variant type.

Return Value

No return value.

See Also

  • CDispParams Class


CDrawImage Class

The CDrawImage class is a helper class that manages drawing for a video renderer filter. All drawing operations are performed using GDI. This class does not provide any support for rendering with DirectDraw. The CDrawImage class requires that the owning filter also use the CBaseWindow class, which manages the video window. The CDrawImage constructor takes a pointer to the CBaseWindow object.

The following diagram shows the preferred way to use this class in a custom video renderer filter.

Custom Video Renderer Using CDrawImage

To use this class, do the following:

  • When the pins connect, call the CDrawImage::NotifyMediaType and CDrawImage::NotifyAllocator methods.
  • Whenever the media type changes, call NotifyMediaType again.
  • Before any rendering occurs, call CDrawImage::SetDrawContext.
  • Call CDrawImage::SetSourceRect if the source rectangle changes, and CDrawImage::SetTargetRect if the target rectangle changes.
  • Manage the palette for palettized images, as described in the section on palettes that follows.

Allocators

The filter shown in the previous diagram uses a custom allocator class, CImageAllocator. This allocator creates DIBs in shared memory, using the GDI CreateDIBSection function. The samples created by the allocator are CImageSample objects.

If the filter owns the allocator for the connection, then the media samples are guaranteed to be CImageSample objects. In that case, the CDrawImage object can optimize drawing by using BitBlt or StretchBlt. Otherwise, it must use the slower SetDIBitsToDevice or StretchDIBits functions. The faster option is implemented by the CDrawImage::FastRender method, the slower option by the CDrawImage::SlowRender method. (Despite the name, you probably won't see a large performance hit in SlowRender, especially on newer hardware.)

Palettes

If the FastRender method is used for drawing and the image is palettized, then the filter needs to manage the palette, as follows:

  • The CImageSample class contains a palette version number, stored in the DIBDATA structure. The value is initialized when the allocator creates the sample.
  • The CDrawImage class also contains a palette version number, which is initialized on creation.
  • Whenever the media type changes to a new palettized format, call CDrawImage::IncrementPaletteVersion. This method increments the CDrawImage object's palette version number. If the filter uses the CImagePalette class to manage the palette information, you can simply call CImagePalette::PreparePalette whenever the media type changes. The PreparePalette method increments the palette version only when necessary.
  • The FastRender method compares the CDrawImage palette version against the sample's palette version. If the sample's version number lags behind the CDrawImage version number, the FastRender method calls CDrawImage::UpdateColourTable. The UpdateColourTable method sets the color table in the device context, using the GDI SetDIBColorTable function. Also, the palette version on the sample is updated to the current version number.
  • If the pin reconnects, the filter should call CDrawImage::ResetPaletteVersion to reset the palette version. On pin reconnection, the allocator re-allocates all samples.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_bStretch | Indicates whether the video image must be stretched to fit the destination window.
m_bUsingImageAllocator | Indicates whether the allocator for the pin connection is a CImageAllocator object.
m_EndSample | Specifies the stop time of the most recent sample.
m_hdc | Handle to the device context of the owning window.
m_MemoryDC | Handle to the memory device context of the owning window.
m_PaletteVersion | Used to track when the palette changes.
m_pBaseWindow | Pointer to the owning CBaseWindow object.
m_pMediaType | Pointer to the current media type.
m_SourceRect | Specifies the source rectangle for drawing.
m_StartSample | Specifies the start time of the most recent sample.
m_TargetRect | Specifies the target rectangle for drawing.
Protected Methods |
DisplaySampleTimes | Draws the time stamps of a media sample on top of the video image.
FastRender | Draws the video image using the BitBlt or StretchBlt functions.
SetStretchMode | Calculates whether the video image must be stretched.
SlowRender | Draws the video image using the SetDIBitsToDevice or StretchDIBits functions.
UpdateColourTable | Updates the color table with a new palette.
Public Methods |
CDrawImage | Constructor method.
DrawImage | Draws a video frame on the video window.
DrawVideoImageHere | Draws an image from a media sample to a specified device context.
GetPaletteVersion | Retrieves the palette version.
GetSourceRect | Retrieves the current source rectangle.
GetTargetRect | Retrieves the current destination rectangle.
IncrementPaletteVersion | Increments the palette version.
NotifyAllocator | Informs the CDrawImage object whether the allocator for the connection is a CImageAllocator object.
NotifyEndDraw | Not supported.
NotifyMediaType | Notifies the object of the current media type.
NotifyStartDraw | Not supported.
ResetPaletteVersion | Resets the palette version.
ScaleSourceRect | Scales a specified source rectangle, if there is a difference between the native video size and the media type format. Virtual.
SetDrawContext | Sets the device contexts used for drawing.
SetSourceRect | Sets the source rectangle.
SetTargetRect | Sets the target rectangle.
UsingImageAllocator | Indicates whether the current allocator is a CImageAllocator object.


CDrawImage::m_bStretch

The m_bStretch member variable indicates whether the video image must be stretched to fit the destination window. The value is FALSE if the source rectangle is the same size as the destination rectangle, or TRUE otherwise.

Syntax

BOOL m_bStretch;

See Also

  • CDrawImage Class


CDrawImage::m_bUsingImageAllocator

The m_bUsingImageAllocator member variable indicates whether the allocator for the pin connection is a CImageAllocator object. If the value is TRUE, the allocator is a CImageAllocator object (or is derived from that class).

Syntax

BOOL m_bUsingImageAllocator;

Remarks

When the value is TRUE, the CDrawImage object can use the GDI BitBlt and StretchBlt functions to render the image, rather than the slower SetDIBitsToDevice and StretchDIBits functions.

See Also

  • CDrawImage Class
  • CDrawImage::NotifyAllocator
  • CDrawImage::UsingImageAllocator


CDrawImage::m_EndSample

The m_EndSample member variable specifies the stop time of the most recent sample.

Syntax

CRefTime m_EndSample;

Remarks

The value is only valid inside the CDrawImage::DisplaySampleTimes method.

See Also

  • CDrawImage Class


CDrawImage::m_hdc

The m_hdc member variable is a handle to the device context of the owning window.

Syntax

HDC m_hdc;

See Also

  • CDrawImage Class
  • CDrawImage::SetDrawContext


CDrawImage::m_MemoryDC

The m_MemoryDC member variable is a handle to the memory device context of the owning window.

Syntax

HDC m_MemoryDC;

See Also

  • CDrawImage Class
  • CDrawImage::SetDrawContext


CDrawImage::m_PaletteVersion

The m_PaletteVersion member variable is used to track when the palette changes.

Syntax

LONG m_PaletteVersion;

See Also

  • CDrawImage Class
  • CDrawImage::GetPaletteVersion


CDrawImage::m_pBaseWindow

The m_pBaseWindow member variable is a pointer to the owning CBaseWindow object.

Syntax

CBaseWindow *m_pBaseWindow;

See Also

  • CDrawImage Class


CDrawImage::m_pMediaType

The m_pMediaType member variable is a pointer to the current media type.

Syntax

CMediaType *m_pMediaType

See Also

  • CDrawImage Class
  • CDrawImage::NotifyMediaType


CDrawImage::m_SourceRect

The m_SourceRect member variable specifies the source rectangle for drawing. The initial value is an empty rectangle, indicating the entire image should be drawn.

Syntax

RECT m_SourceRect;

See Also

  • CDrawImage Class
  • CDrawImage::SetSourceRect


CDrawImage::m_StartSample

The m_StartSample member variable specifies the start time of the most recent sample.

Syntax

CRefTime m_StartSample;

Remarks

The value is only valid inside the CDrawImage::DisplaySampleTimes method.

See Also

  • CDrawImage Class


CDrawImage::m_TargetRect

The m_TargetRect member variable specifies the target rectangle for drawing. The initial value is an empty rectangle, indicating the image should be drawn to the entire destination window.

Syntax

RECT m_TargetRect;

See Also

  • CDrawImage Class
  • CDrawImage::SetTargetRect


CDrawImage::CDrawImage

The CDrawImage method is a constructor method.

Syntax

CDrawImage(
    CBaseWindow *pBaseWindow
);

Parameters

pBaseWindow

Pointer to the owning CBaseWindow object.

See Also

  • CDrawImage Class


CDrawImage::DisplaySampleTimes

The DisplaySampleTimes method draws the time stamps of a media sample on top of the video image.

Syntax

void DisplaySampleTimes(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface of the sample.

Return Value

No return value.

Remarks

This method is called only in debug builds.

See Also

  • CDrawImage Class


CDrawImage::DrawImage

The DrawImage method draws a video frame on the video window.

Syntax

BOOL DrawImage(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the IMediaSample interface of the sample that contains the image.

Return Value

No return value.

Remarks

This method delegates to CDrawImage::FastRender or CDrawImage::SlowRender, depending on whether the filter owns the allocator that provided the sample. If the filter does own the allocator, the sample is guaranteed to be a CImageSample object. In that case, the sample uses shared memory allocated by GDI, and the image can be drawn using either BitBlt or StretchBlt. Otherwise, the images must be drawn using the slower SetDIBitsToDevice or StretchDIBits functions.

In debug builds, this method calls DisplaySampleTimes to draw the sample's time stamps over the video image.

See Also

  • CDrawImage Class
  • CDrawImage::UsingImageAllocator


CDrawImage::DrawVideoImageHere

The DrawVideoImageHere method draws an image from a media sample to a specified device context.

Syntax

BOOL CDrawImage::DrawVideoImageHere(
    HDC hdc,
    IMediaSample *pMediaSample,
    RECT *lprcSrc,
    RECT *lprcDst
);

Parameters

hdc

Handle to a device context, where the drawing will occur.

pMediaSample

Pointer to the IMediaSample interface of the sample that contains the image.

lprcSrc

Pointer to a source rectangle to use for drawing. If NULL, the rectangle in CDrawImage::m_SourceRect is used.

lprcDst

Pointer to a target rectangle to use for drawing. If NULL, the rectangle in CDrawImage::m_TargetRect is used.

Return Value

Returns TRUE if successful.

See Also

  • CDrawImage Class


CDrawImage::FastRender

The FastRender method draws the video image using the BitBlt or StretchBlt functions.

Syntax

void FastRender(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the IMediaSample interface of the sample that contains the image.

Return Value

No return value.

Remarks

The CDrawImage::DrawImage method calls this method, but only if the allocator for the connection is a CImageAllocator object. In that case, the media sample is guaranteed to be a CImageSample object. The CImageSample object uses the CreateDIBSection function to allocate shared memory for the bitmap, which makes it possible to draw the image using either BitBlt or StretchBlt.

This method calls BitBlt if the source and targer rectangles exactly match, or StretchBlt otherwise.

If the filter does not own the allocator, the DrawImage method uses CDrawImage::SlowRender to draw the image.

See Also

  • CDrawImage Class


CDrawImage::GetPaletteVersion

The GetPaletteVersion method retrieves the current palette version.

Syntax

LONG GetPaletteVersion(void);

Return Value

Returns the value of the m_PaletteVersion member variable.

Remarks

The value returned by this method applies only when the allocator is a CImageAllocator object.

See Also

  • CDrawImage Class
  • CDrawImage::IncrementPaletteVersion
  • CDrawImage::ResetPaletteVersion


CDrawImage::GetSourceRect

The GetSourceRect method retrieves the current source rectangle.

Syntax

void GetSourceRect(
    RECT *pSourceRect
);

Parameters

pSourceRect

Pointer to a RECT structure that receives the source rectangle.

Return Value

No return value.

See Also

  • CDrawImage Class


CDrawImage::GetTargetRect

The GetTargetRect method retrieves the current destination rectangle.

Syntax

void GetTargetRect(
    RECT *pTargetRect
);

Parameters

pTargetRect

Pointer to a RECT structure that receives the target rectangle.

Return Value

No return value.

See Also

  • CDrawImage Class


CDrawImage::IncrementPaletteVersion

The IncrementPaletteVersion method increments the palette version. Call this method if the media type changes to a new palettized format.

Syntax

void IncrementPaletteVersion(void);

Return Value

No return value.

Remarks

This method increments the value of the m_PaletteVersion member variable.

See Also

  • CDrawImage Class
  • CDrawImage::GetPaletteVersion
  • CDrawImage::ResetPaletteVersion


CDrawImage::NotifyAllocator

The NotifyAllocator method informs the CDrawImage object whether the allocator for the connection is a CImageAllocator object.

Syntax

void NotifyAllocator(
    BOOL bUsingImageAllocator
);

Parameters

bUsingImageAllocator

Boolean value that indicates what kind of allocator is being used.

Return Value

No return value.

Remarks

The owning filter should call this method after the pins agree to an allocator. If the filter knows the allocator is a CImageAllocator object, it should call this method with the value TRUE. (Typically, the filter will know this only if it owns the allocator in question.) Otherwise, it should call this method with the value FALSE.

See Also

  • CDrawImage Class
  • CDrawImage::DrawImage


CDrawImage::NotifyEndDraw

The NotifyEndDraw method is not supported.

Syntax

void NotifyEndDraw(void);

Return Value

No return value.

Return Value

In earlier versions of the base-class library, this method supported performance measurements by the CDrawImage object.

See Also

  • CDrawImage Class


CDrawImage::NotifyMediaType

The NotifyMediaType method notifies the CDrawImage object of the current media type.

Syntax

void NotifyMediaType(
    CMediaType *pMediaType
);

Parameters

pMediaType

Pointer to a CMediaType object, or NULL to clear the media type.

Return Value

No return value.

Remarks

The owning filter should call this method whenever the media type changes. Typically this occurs when the pin first connects, and after a dynamic format change.

The CDrawImage object stores the pMediaType pointer in the m_pMediaType member variable. Therefore, if the caller needs to release the CMediaType object, it should update the CDrawImage object by calling this method again, either with a new pointer or with a NULL value. Otherwise, an error can occur when the CDrawImage object attempts to reference the old pointer.

See Also

  • CDrawImage Class


CDrawImage::NotifyStartDraw

The NotifyStartDraw method is not supported.

Syntax

void NotifyStartDraw(void);

Return Value

No return value.

Return Value

In earlier versions of the base-class library, this method supported performance measurements by the CDrawImage object.

See Also

  • CDrawImage Class


CDrawImage::ResetPaletteVersion

The ResetPaletteVersion method resets the palette version. Call this method if the owning filter's pin reconnects.

Syntax

void ResetPaletteVersion(void);

Return Value

No return value.

Remarks

This method sets the value of m_PaletteVersion to a predefined constant, PALETTE_VERSION.

See Also

  • CDrawImage Class
  • CDrawImage::GetPaletteVersion
  • CDrawImage::IncrementPaletteVersion


CDrawImage::ScaleSourceRect

The ScaleSourceRect method scales a rectangle, if there is a difference between the native video size and the media type format.

Syntax

virtual RECT ScaleSourceRect(
    const RECT *pSource
);

Parameters

pSource

Pointer to an unscaled rectangle.

Return Value

Returns the scaled rectangle.

Remarks

In the CDrawImage class, this method returns pSource without any change. You can override this method if the filter stretches the incoming video image. For example, the native video size might be 320 × 240, but the media type on the input pin might be 640 × 480. In that case the filter would need to scale the source rectangle by a factor of 2.

See Also

  • CDrawImage Class


CDrawImage::SetDrawContext

The SetDrawContext method sets the device contexts used for drawing.

Syntax

void SetDrawContext(void);

Return Value

No return value.

Remarks

This method retrieves the window and memory device contexts from the owning CBaseWindow object. Call this method after the window is initialized, but before you begin drawing.

See Also

  • CDrawImage Class


CDrawImage::SetSourceRect

The SetSourceRect method sets the source rectangle.

Syntax

void SetSourceRect(
    RECT *pSourceRect
);

Parameters

pSourceRect

Pointer to a RECT structure that defines the new source rectangle.

Return Value

No return value.

Remarks

The owning filter should call this method if the source rectangle changes; for example, in response to an IBasicVideo::SetSourcePosition call.

Validate the rectangle given in pSourceRect before calling this method, to make sure it does not extend beyond the native video size.

See Also

  • CDrawImage Class


CDrawImage::SetStretchMode

The SetStretchMode method calculates whether the video image must be stretched.

Syntax

void SetStretchMode(void);

Return Value

No return value.

Remarks

The CDrawImage class automatically calls this method whenever the source or target rectangle changes.

See Also

  • CDrawImage Class


CDrawImage::SetTargetRect

The SetTargetRect method sets the target rectangle.

Syntax

void SetTargetRect(
    RECT *pTargetRect
);

Parameters

pTargetRect

Pointer to a RECT structure that defines the new target rectangle.

Return Value

No return value.

Remarks

The owning filter should call this method if the source rectangle changes; for example, in response to an IBasicVideo::SetDestinationPosition call.

Before calling this method, validate the rectangle given in pTargetRect, relative to the video window.

See Also

  • CDrawImage Class


CDrawImage::SlowRender

The SlowRender method draws the video image using the SetDIBitsToDevice or StretchDIBits functions.

Syntax

void SlowRender(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the IMediaSample interface of the sample that contains the image.

Return Value

No return value.

Remarks

If CDrawImage::UsingImageAllocator returns FALSE, the CDrawImage::DrawImage method uses SlowRender to draw the video image. Otherwise, DrawImage uses the FastRender method.

See Also

  • CDrawImage Class
  • CDrawImage::FastRender


CDrawImage::UpdateColourTable

The UpdateColourTable method updates the color table with a new palette.

Syntax

void UpdateColourTable(
    HDC hdc,
    BITMAPINFOHEADER *pbmi
);

Parameters

hdc

Device context containing the image.

pbmi

Pointer to a BITMAPINFOHEADER structure containing the new palette.

Return Value

No return value.

See Also

  • CDrawImage Class


CDrawImage::UsingImageAllocator

The UsingImageAllocator method indicates whether the current allocator is a CImageAllocator object.

Syntax

BOOL UsingImageAllocator(void);

Return Value

Returns TRUE if the current allocator is a CImageAllocator object, or FALSE otherwise.

See Also

  • CDrawImage Class
  • CDrawImage::NotifyAllocator


CDynamicOutputPin Class

The CDynamicOutputPin class implements an output pin that supports dynamic reconnections and format changes.

This class derives from the CBaseOutputPin class and implements the IPinFlowControl interface. It supports several operations that are important for dynamic graph building:

  • Dynamic reconnection: The pin can disconnect and reconnect while the filter is still active (paused or running).
  • Dynamic format change: The pin can negotiate a new media type while the filter is still active, without reconnecting.
  • Flow control: The owning filter (or an application) can block data flow from the pin without stopping the filter.

For more information, see Dynamic Graph Building.

The pin has three possible states: blocked, unblocked, and pending. In the pending state, the pin is waiting for some operation to complete on another thread, before the pin switches to the blocked state. While the pin is blocked, the filter cannot deliver data through the pin, or change the pin's connection.

To coordinate among multiple threads, the owning filter must follow certain rules. (For more information about threads in the filter graph, see Threads and Critical Sections.) First, the streaming thread must always call the CDynamicOutputPin::StartUsingOutputPin method before it calls any of the following methods:

  • CDynamicOutputPin::ChangeOutputFormat
  • CDynamicOutputPin::ChangeMediaType
  • CDynamicOutputPin::DynamicReconnect
  • CBaseOutputPin::Deliver
  • CBaseOutputPin::DeliverEndOfStream
  • CBaseOutputPin::DeliverNewSegment
  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment

Afterward, it must call the CDynamicOutputPin::StopUsingOutputPin method.

Second, the application thread must not call any of the methods in the previous list. Third, the streaming thread must not call the class methods that block or unblock the pin. These methods are: CDynamicOutputPin::Block, CDynamicOutputPin::SynchronousBlockOutputPin, CDynamicOutputPin::AsynchronousBlockOutputPin, and CDynamicOutputPin::UnblockOutputPin.

These rules ensure that the application thread cannot block the pin while the streaming thread is using it, and vice versa. After the streaming thread has called StartUsingOutputPin, the pin will not block until the streaming thread calls StopUsingOutputPin. Conversely, if the pin is blocked, StartUsingOutputPin waits until the pin is unblocked.

To avoid forgetting to call StopUsingOutputPin, you can use the CAutoUsingOutputPin class. It calls StopUsingOutputPin automatically when it goes out of scope.

When the owning filter joins or leaveds the filter graph (in its IBaseFilter::JoinFilterGraph method), it must call the pin's CDynamicOutputPin::SetConfigInfo method.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_BlockStateLock | Critical section that protects the blocking state.
m_hUnblockOutputPinEvent | Event that is signaled when the pin is not blocked.
m_hNotifyCallerPinBlockedEvent | Event that is signaled when the pin successfully blocks, or the user cancels a pending block.
m_BlockState | Blocking state.
m_dwBlockCallerThreadID | The identifier of the thread that last called the IPinFlowControl::Block method on this pin.
m_dwNumOutstandingOutputPinUsers | Number of streaming threads using this pin.
m_hStopEvent | Event that is signaled when the filter stops or the pin flushes data.
m_pGraphConfig | Pointer to the IGraphConfig interface for performing dynamic reconnections.
m_bPinUsesReadOnlyAllocator | Flag that specifies whether samples from the pin's allocator are read-only.
Protected Methods |
SynchronousBlockOutputPin | Blocks the pin; does not return until the pin is blocked.
AsynchronousBlockOutputPin | Blocks the pin; might return before the pin is blocked.
UnblockOutputPin | Unblocks the pin.
BlockOutputPin | Blocks the pin.
WaitEvent | Waits until the specified event is signaled.
Public Methods |
CDynamicOutputPin | Constructor method.
~CDynamicOutputPin | Destructor method.
SetConfigInfo | Specifies the IGraphConfig pointer and the stop event.
DeliverBeginFlush | Requests the connected input pin to begin a flush operation.
DeliverEndFlush | Requests the connected input pin to end a flush operation.
Inactive | Notifies the pin that the filter has stopped.
Active | Notifies the pin that the filter is now active.
CompleteConnect | Completes a connection to an input pin. Virtual.
StartUsingOutputPin | Obtains access to the pin for a streaming operation. Virtual.
StopUsingOutputPin | Releases access to the pin after a streaming operation. Virtual.
StreamingThreadUsingOutputPin | Determines whether any thread is performing a streaming operation on the pin. Virtual.
ChangeOutputFormat | Dynamically changes the media type for the connection, and delivers new segment information.
ChangeMediaType | Dynamically changes the media type for the connection.
DynamicReconnect | Performs a dynamic reconnection with a new media type.
IPin Methods |
Disconnect | Breaks the current pin connection.
IPinFlowControl Methods |
Block | Blocks or unblocks the flow of data from the pin.


CDynamicOutputPin::m_BlockStateLock

Critical section that protects the blocking state.

Syntax

CCritSec m_BlockStateLock;

Remarks

Hold this critical section before using any of the following member variables:

  • CDynamicOutputPin::m_BlockState
  • CDynamicOutputPin::m_dwBlockCallerThreadID
  • CDynamicOutputPin::m_dwNumOutstandingOutputPinUsers
  • CDynamicOutputPin::m_hNotifyCallerPinBlockedEvent

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_hUnblockOutputPinEvent

Event that is signaled when the pin is not blocked.

Syntax

HANDLE m_hUnblockOutputPinEvent;

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_hNotifyCallerPinBlockedEvent

Event that is signaled when the pin successfully blocks, or the user cancels a pending block.

Syntax

HANDLE m_hNotifyCallerPinBlockedEvent;

Remarks

Before accessing this variable, hold the CDynamicOutputPin::m_BlockStateLock critical section.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_BlockState

Blocking state.

Syntax

BLOCK_STATE m_BlockState;

Remarks

The following states are defined:

  • NOT_BLOCKED
  • PENDING
  • BLOCKED

Before accessing this variable, hold the CDynamicOutputPin::m_BlockStateLock critical section.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_dwBlockCallerThreadID

The identifier of the thread that last called the IPinFlowControl::Block method on this pin. This member variable is only valid while the pin is blocked.

Syntax

DWORD m_dwBlockCallerThreadID;

Remarks

Before accessing this variable, hold the CDynamicOutputPin::m_BlockStateLock critical section.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_dwNumOutstandingOutputPinUsers

Number of streaming threads using this pin.

Syntax

DWORD m_dwNumOutstandingOutputPinUsers;

Remarks

The CDynamicOutputPin::StartUsingOutputPin method increments this variable, and the CDynamicOutputPin::StopUsingOutputPin method decrements it. When the value is greater than zero, some thread is using this pin to stream data or to change the connection type. The pin cannot be blocked while this is the case.

Before accessing this variable, hold the CDynamicOutputPin::m_BlockStateLock critical section.

See Also

  • CDynamicOutputPin Class
  • CDynamicOutputPin::StreamingThreadUsingOutputPin


CDynamicOutputPin::m_hStopEvent

Event that is signaled when the filter stops or the pin flushes data.

Syntax

HANDLE m_hStopEvent;

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_pGraphConfig

Pointer to the IGraphConfig interface for performing dynamic reconnections.

Syntax

IGraphConfig* m_pGraphConfig;

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::m_bPinUsesReadOnlyAllocator

Flag that specifies whether samples from the pin's allocator are read-only. If the value is TRUE, the sample are read-only. The default value is FALSE.

Syntax

BOOL m_bPinUsesReadOnlyAllocator;

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::Active

The Active method notifies the pin that the filter is now active.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure. CDynamicOutputPin::SetConfigInfo was not called.

Remarks

This method overrides the CBaseOutputPin::Active method. It resets the CDynamicOutputPin::m_hStopEvent event. If the owning filter has not called SetConfigInfo, this method returns E_FAIL.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::AsynchronousBlockOutputPin

The AsynchronousBlockOutputPin method blocks the pin. The method might return before the pin is blocked.

Syntax

HRESULT AsynchronousBlockOutputPin(
    HANDLE hNotifyCallerPinBlockedEvent
);

Parameters

hNotifyCallerPinBlockedEvent

Handle to an event. The event is signaled when the output pin is blocked, or if the caller cancels the block operation.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

Do not call this method from the streaming thread.

If no streaming thread is using the pin, this method immediately blocks the pin. Otherwise, it sets the pin status to "pending" and returns. When the streaming operation completes, the streaming thread calls the CDynamicOutputPin::StopUsingOutputPin method, which blocks the pin and signals the hNotifyCallerPinBlockedEvent event. To cancel a pending block, call the CDynamicOutputPin::UnblockOutputPin method.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::Block

The Block method blocks or unblocks the flow of data from the pin. This method implements the IPinFlowControl::Block method.

Syntax

HRESULT Block(
    DWORD dwBlockFlags,
    HANDLE hEvent
);

Parameters

dwBlockFlags

Flag that indicates whether to block or unblock the pin. Must be one of the following values:

Zero: Unblock data flow from the pin.

AM_PIN_FLOW_CONTROL_BLOCK: Block data flow from the pin.

hEvent

Handle to an event object, or NULL.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Pin is already unblocked.
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

For more information about this method, see IPinFlowControl::Block. Internally, this method calls one of the following protected methods:

  • Block (asynchronous): CDynamicOutputPin::AsynchronousBlockOutputPin
  • Block (synchronous): CDynamicOutputPin::SynchronousBlockOutputPin
  • Unblock: CDynamicOutputPin::UnblockOutputPin

Unblocking is always performed synchronously.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::BlockOutputPin

The BlockOutputPin method blocks the pin. While the pin is blocked, the CDynamicOutputPin::StartUsingOutputPin method waits for the pin to become unblocked. The blocked state prevents the output pin from delivering samples, changing its output format, or reconnecting itself.

Syntax

void BlockOutputPin(void);

Remarks

Before calling this method, hold the CDynamicOutputPin::m_BlockStateLock critical section. Do not call this method if a streaming thread is using the pin, either to deliver data or to change the connection. To check whether a streaming thread is using the pin, call the CDynamicOutputPin::StreamingThreadUsingOutputPin method.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::CDynamicOutputPin

Constructor method.

Syntax

CDynamicOutputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

Pointer to a string containing the name of the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin.

pLock

Pointer to a CCritSec lock, used to serialize state changes. Use the same critical section as the filter lock, CBaseFilter::m_pLock

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Pointer to a wide-character string containing the pin identifier. For more information, see IPin::QueryId.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::~CDynamicOutputPin

Destructor method.

Syntax

~CDynamicOutputPin(void);

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::ChangeMediaType

The ChangeMediaType method dynamically changes the media type for the connection. The change can occur while the filter graph is running. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Syntax

HRESULT ChangeMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call CDynamicOutputPin::SetConfigInfo.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Call the CDynamicOutputPin::StartUsingOutputPin method before calling this method.

This method first checks whether the downstream input pin can accept the new format without reconnecting. It queries the input pin for the IPinConnection interface. If the input pin supports IPinConnection, the method calls the IPinConnection::DynamicQueryAccept method with the proposed media type. If the input pin accepts the new media type, the method calls the IPin::ReceiveConnection method and renegotiates the allocator requirements.

On the other hand, if the downstream pin does not support IPinConnection, or if it rejects the new media type, the method calls the CDynamicOutputPin::DynamicReconnect method to perform a dynamic reconnection.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::ChangeOutputFormat

The ChangeOutputFormat method dynamically changes the media type for the connection, and delivers new segment information. The change can occur while the filter graph is running. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Syntax

HRESULT ChangeOutputFormat(
    const AM_MEDIA_TYPE *pmt,
    REFERENCE_TIME tSegmentStart,
    REFERENCE_TIME tSegmentStop,
    double dSegmentRate
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

tSegmentStart

Start time of the segment.

tSegmentStop

Stop time of the segment.

dSegmentRate

Segment rate.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call CDynamicOutputPin::SetConfigInfo.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

This method changes the format type while the filter is running. If the downstream pin accepts the new format, no reconnection is necessary. Otherwise, the method attempts to reconnect the pin. If the method successfully changes the format, it delivers the new segment information. This method calls the CDynamicOutputPin::ChangeMediaType method to perform the format change.

You must call the CDynamicOutputPin::StartUsingOutputPin method before calling this method.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::CompleteConnect

The CompleteConnect method completes a connection to an input pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the input pin's IPin interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::CompleteConnect method. To support dynamic reconnections, this method commits the allocator if the filter is active. In the base class, connections can occur only when the filter is stopped, so the allocator is always committed in the CBaseOutputPin::Active method.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::DeliverBeginFlush

The DeliverBeginFlush method requests the connected input pin to begin a flush operation.

Syntax

HRESULT DeliverBeginFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::DeliverBeginFlush method. It sets the CDynamicOutputPin::m_hStopEvent event.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::DeliverEndFlush

The DeliverEndFlush method requests the connected input pin to end a flush operation.

Syntax

HRESULT DeliverEndFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::DeliverEndFlush method. It resets the CDynamicOutputPin::m_hStopEvent event.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::Disconnect

The Disconnect method breaks the current pin connection. This method implements the IPin::Disconnect method.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | The pin was not connected.
S_OK | Success.

Remarks

This method overrides the CBasePin::Disconnect method to enable disconnecting while the filter is active.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::DynamicReconnect

The DynamicReconnect method performs a dynamic reconnection with a new media type. The reconnection can occur while the filter graph is running.

Syntax

HRESULT DynamicReconnect(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call the CDynamicOutputPin::SetConfigInfo method.

Remarks

This method must be called from the same thread that delivers data to the pin. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Call CDynamicOutputPin::StartUsingOutputPin before calling this method.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::Inactive

The Inactive method notifies the pin that the filter has stopped.

Syntax

HRESULT Inactive(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::Inactive method. It sets the CDynamicOutputPin::m_hStopEvent event.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::SetConfigInfo

The SetConfigInfo method specifies the IGraphConfig pointer and the stop event.

Syntax

void SetConfigInfo(
    IGraphConfig *pGraphConfig,
    HANDLE hStopEvent
);

Parameters

pGraphConfig

Pointer to the IGraphConfig interface, or NULL.

hStopEvent

Handle to an event that is signaled when the filter stops, or NULL.

Remarks

The filter must call this method when it joins the filter graph. The filter graph manager supports IGraphConfig. For the hStopEvent parameter, create a manual-reset event. When the filter leaves the filter graph, call this method again with NULL for both parameters.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::StartUsingOutputPin

The StartUsingOutputPin method obtains access to the pin for a streaming operation.

Syntax

virtual HRESULT StartUsingOutputPin(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_UNEXPECTED | Unexpected error.
VFW_E_STATE_CHANGED | The filter was stopped, or the pin has begun flushing.

Remarks

Call this method before calling any methods that deliver data to the connected input pin or that change the connection's media type. For example, this rule applies to the following methods:

  • CDynamicOutputPin::ChangeOutputFormat
  • CDynamicOutputPin::ChangeMediaType
  • CDynamicOutputPin::DynamicReconnect
  • CBaseOutputPin::Deliver
  • CBaseOutputPin::DeliverEndOfStream
  • CBaseOutputPin::DeliverNewSegment
  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment

Afterward, call the CDynamicOutputPin::StopUsingOutputPin method to release the access to the pin.

If the pin is blocked, StartUsingOutputPin waits for the pin to become unblocked. If the filter stops while the method is waiting, the method immediately returns VFW_E_STATE_CHANGED. The pin maintains a count of how many times StartUsingOutputPin has been called without a corresponding call to StopUsingOutputPin. If another thread tries to block the pin while this count is non-zero, the pin sets its blocking status to "pending." The pin becomes blocked once all of the streaming operations have completed, in the final call to StopUsingOutputPin.

Do not hold the CDynamicOutputPin::m_BlockStateLock critical section when you call this method. Otherwise, if the pin is blocked, it can never become unblocked, causing a deadlock.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::StopUsingOutputPin

The StopUsingOutputPin method releases access to the pin after a streaming operation.

Syntax

virtual void StopUsingOutputPin(void);

See Also

  • StartUsingOutputPin

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::StreamingThreadUsingOutputPin

The StreamingThreadUsingOutputPin method determines whether any thread is performing a streaming operation on the pin.

Syntax

virtual bool StreamingThreadUsingOutputPin(void);

Return Value

Returns TRUE if a thread is performing a streaming operation on the pin. Otherwise, returns FALSE.

Remarks

If any threads have successfully returned from the CDynamicOutputPin::StartUsingOutputPin method and have not made a corresponding call to the CDynamicOutputPin::StopUsingOutputPin method, this method returns TRUE.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::SynchronousBlockOutputPin

The SynchronousBlockOutputPin method blocks the pin; does not return until the pin is blocked.

Syntax

HRESULT SynchronousBlockOutputPin(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

Do not call this method from the streaming thread.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::UnblockOutputPin

The UnblockOutputPin method unblocks the pin. When the pin is unblocked, it can deliver samples, change its output format, and reconnect itself.

Syntax

HRESULT UnblockOutputPin(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Pin was already unblocked.
S_OK | Success.

See Also

  • CDynamicOutputPin Class


CDynamicOutputPin::WaitEvent

The WaitEvent method waits until the specified event is signaled.

Syntax

static HRESULT WaitEvent(
    HANDLE hEvent
);

Parameters

hEvent

Handle to an event.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_UNEXPECTED | Unexpected error.

See Also

  • CDynamicOutputPin Class


CEnumMediaTypes Class

CEnumMediaTypes Class Hierarchy

The CEnumMediaTypes class implements an enumerator for preferred media types.

This class implements the IEnumMediaTypes interface. It calls the following CBasePin methods:

  • CBasePin::GetMediaType:Retrieves a media type, referenced by a zero-based index.
  • CBasePin::GetMediaTypeVersion: Determines whether the set of preferred types has changed.

Whenever a pin alters its list of preferred media types, the pin increments the media-type version number. When this happens, the enumerator object is no longer synchronized with the pin, and the class methods return VFW_E_ENUM_OUT_OF_SYNC. Call the CEnumMediaTypes::Reset method to resynchronize the enumerator.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CEnumMediaTypes | Constructor method.
~CEnumMediaTypes | Destructor method. Virtual.
IEnumMediaTypes Methods |
Clone | Makes a copy of the enumerator with the same enumeration state.
Next | Retrieves a specified number of media types.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of media types.


CEnumMediaTypes::CEnumMediaTypes

Constructor method.

Syntax

CEnumMediaTypes(
    CBasePin *pPin,
    CEnumMediaTypes *pEnumMediaTypes
);

Parameters

pPin

Pointer to the pin on which the enumeration is to be performed.

pEnumMediaTypes

Pointer to the IEnumMediaTypes interface of an enumerator to clone, or NULL.

Remarks

If pEnumMediaTypes is NULL, this method initializes the enumerator to the beginning of the enumeration sequence. Otherwise, it duplicates the internal state of the enumerator specified by pEnumMediaTypes.

See Also

  • CEnumMediaTypes Class


CEnumMediaTypes::~CEnumMediaTypes

Destructor method.

Syntax

virtual ~CEnumMediaTypes(void);

See Also

  • CEnumMediaTypes Class


CEnumMediaTypes::Clone

The Clone method makes a copy of the enumerator with the same enumeration state. This method implements the IEnumMediaTypes::Clone method.

Syntax

HRESULT Clone(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumMediaTypes interface of the new enumerator.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

See Also

  • CEnumMediaTypes Class


CEnumMediaTypes::Next

The Next method retrieves a specified number of media types. This method implements the IEnumMediaTypes::Next method.

Syntax

HRESULT Next(
    ULONG cMediaTypes,
    AM_MEDIA_TYPE **ppMediaTypes,
    ULONG *pcFetched
);

Parameters

cMediaTypes

Number of media types to retrieve.

ppMediaTypes

Array of pointers to AM_MEDIA_TYPE structures, of size cPins.

pcFetched

Pointer to a variable that receives the number of media types the method returned. Can be NULL if cMediaTypes is 1.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Did not retrieve as many media types as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the method succeeds, the array specified by ppMediaTypes contains pointers to AM_MEDIA_TYPE structures. The number of structures is equal to *pcFetched. Free each media type by calling the DeleteMediaType function.

This method calls the pin's CBasePin::GetMediaType method to retrieve the media types.

See Also

  • CEnumMediaTypes Class


CEnumMediaTypes::Reset

The Reset method resets the enumeration sequence to the beginning. This method implements the IEnumMediaTypes::Reset method.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

See Also

  • CEnumMediaTypes Class


CEnumMediaTypes::Skip

The Skip method skips over a specified number of media types. This method implements the IEnumMediaTypes::Skip method.

Syntax

HRESULT Skip(
    ULONG cMediaTypes
);

Parameters

cMediaTypes

Number of media types to skip.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

See Also

  • CEnumMediaTypes Class


CEnumPins Class

CEnumPins Class Hierarchy

The CEnumPins class implements an enumerator for pins.

This class implements the IEnumPins interface. It calls the following CBaseFilter methods:

  • CBaseFilter::GetPin: Retrieves a pin on the filter, referenced by a zero-based index.
  • CBaseFilter::GetPinCount: Retrieves the total number of pins on the filter.
  • CBaseFilter::GetPinVersion: Determines whether the pins have changed.

If the filter dynamically creates or destroys pins, it increments the pin version whenever the pins change. If the version number changes, the enumerator object is no longer synchronized with the filter. Once the enumerator is out of sync, the methods in CEnumPins return VFW_E_ENUM_OUT_OF_SYNC. Call the CEnumPins::Reset method to resynchronize the enumerator.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CEnumPins | Constructor method.
~CEnumPins | Destructor method. Virtual.
IEnumPins Methods |
Clone | Makes a copy of the enumerator with the same enumeration state.
Next | Retrieves a specified number of pins.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of pins.


CEnumPins::CEnumPins

Constructor method.

Syntax

CEnumPins(
    CBaseFilter *pFilter,
    CEnumPins *pEnumPins
);

Parameters

pFilter

Pointer to the filter on which to enumerate the pins.

pEnumPins

Pointer to the IEnumPins interface of an enumerator to clone, or NULL.

Remarks

If pEnumPins is NULL, this method initializes the enumerator to the beginning of the enumeration sequence. Otherwise, it duplicates the internal state of the enumerator specified by pEnumPins.

See Also

  • CEnumPins Class


CEnumPins::~CEnumPins

Destructor method.

Syntax

virtual ~CEnumPins(void);

See Also

  • CEnumPins Class


CEnumPins::Clone

The Clone method makes a copy of the enumerator with the same enumeration state. This method implements the IEnumPins::Clone method.

Syntax

HRESULT Clone(
    IEnumPins **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumPins interface of the new enumerator.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

See Also

  • CEnumPins Class


CEnumPins::Next

The Next method retrieves a specified number of pins in the enumeration sequence. This method implements the IEnumPins::Next method.

Syntax

HRESULT Next(
    ULONG cPins,
    IPin **ppPins,
    ULONG *pcFetched
);

Parameters

cPins

Number of pins to retrieve.

ppPins

Array of size cPins that is filled with IPin pointers.

pcFetched

Pointer to a variable that receives the number of pins retrieved. Can be NULL if cPins is 1.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Did not retrieve as many pins as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

This method retrieves pointers to the specified number of pins, starting at the current position in the enumeration, and places them in the specified array.

This method calls the filter's CBaseFilter::GetPin method to retrieve the pins.

If the method succeeds, the IPin pointers all have outstanding reference counts. Be sure to release them when you are done.

See Also

  • CEnumPins Class


CEnumPins::Reset

The Reset method resets the enumeration sequence to the beginning. This method implements the IEnumPins::Reset method.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

See Also

  • CEnumPins Class


CEnumPins::Skip

The Skip method skips over a specified number of pins in the enumeration sequence. This method implements the IEnumPins::Skip method.

Syntax

HRESULT Skip(
    ULONG cPins
);

Parameters

cPins

Number of pins to skip.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

See Also

  • CEnumPins Class


CFactoryTemplate Class

Provides a template for creating class factories.

In Microsoft® DirectShow®, class factories are specialized using the CFactoryTemplate class, also called the factory template. Each class factory holds a pointer to a factory template. The factory template contains information about a COM object, including the object's class identifier (CLSID) and a pointer to a function that creates the object.

In your DLL, declare a global array of factory templates named g_Templates. Include one factory template for each object in the DLL. When the DllGetClassObject function makes a new class factory, it searches the array for a template with a matching CLSID. Assuming it finds one, it creates a class factory that holds a pointer to the matching template. When the client calls IClassFactory::CreateInstance, the class factory calls the instantiation function defined in the template.

For more information, see How to Create a DLL.

Requirements

Header: Declared in Combase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Member Variables |
m_Name | Name of the filter.
m_ClsID | Pointer to the CLSID of the object.
m_lpfnNew | Pointer to a function that creates an instance of the object.
m_lpfnInit | Pointer to a function that gets called from the DLL entry point.
m_pAMovieSetup_Filter | Pointer to an AMOVIESETUP_FILTER structure.
Public Methods |
IsClassID | Determines whether a CLSID matches this class template.
CreateInstance | Calls the object-creation function for the class.


CFactoryTemplate::m_Name

Wide-character string containing the name of the filter.

Syntax

const WCHAR *m_Name;

See Also

  • CFactoryTemplate Class


CFactoryTemplate::m_ClsID

Pointer to the CLSID of the object.

Syntax

const CLSID *m_ClsID;

See Also

  • CFactoryTemplate Class


CFactoryTemplate::m_lpfnNew

Pointer to a function that creates an instance of the object.

Syntax

typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(LPUNKNOWN pUnkOuter, HRESULT *phr);

LPFNNewCOMObject m_lpfnNew;

Remarks

In your DLL, declare a static function that returns a pointer to a new instance of the object. In the factory template, set the m_lpfnNew member variable to the address of this static function.

The following example shows a typical function for m_lpfnNew:

CUnknown * WINAPI CMyComponent::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CMyComponent *pNewObject = new CMyComponent(NAME("My Component"), pUnk, pHr );
    if (pNewObject == NULL)
{
        *phr = E_OUTOFMEMORY;
    }
    return pNewObject;
}

See Also

  • CFactoryTemplate Class


CFactoryTemplate::m_lpfnInit

Pointer to a function that gets called from the DLL entry point. Can be NULL.

Syntax

typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid);

LPFNInitRoutine m_lpfnInit;

Remarks

If you provide this function in your DLL, the DLL entry-point function calls it with following parameters:

  • bLoading: TRUE when the DLL is loaded, FALSE when the DLL is unloaded.
  • rclsid: Pointer to the object's CLISD, specified in the CFactoryTemplate::m_ClsID member variable.

See Also

  • CFactoryTemplate Class


CFactoryTemplate::m_pAMovieSetup_Filter

Pointer to an AMOVIESETUP_FILTER structure.

Syntax

const AMOVIESETUP_FILTER *m_pAMovieSetup_Filter;

Remarks

Use this structure to make a filter self-registering. If your component is not a filter, this member variable can be NULL. For more information, see How to Register DirectShow Filters.

See Also

  • CFactoryTemplate Class


CFactoryTemplate::CreateInstance

The CreateInstance method calls the object-creation function for the class.

Syntax

CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk

Pointer to the aggregating IUnknown interface.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

Return Value

Returns an instance of the class object.

Remarks

The IClassFactory::CreateInstance method calls this class method. This method calls the function pointed to by the CFactoryTemplate::m_lpfnNew member variable.

See Also

  • CFactoryTemplate Class


CFactoryTemplate::IsClassID

The IsClassID method determines whether a CLSID matches this class template.

Syntax

BOOL IsClassID(
    REFCLSID rclsid
);

Parameters

rclsid

Reference to a CLSID.

Return Value

Returns TRUE if the rclsid parameter is the same CLSID as the CFactoryTemplate::m_ClsID member variable, or else returns FALSE.

See Also

  • CFactoryTemplate Class


CGenericList Class

CGenericList Class Hierarchy

The CGenericList class template that implements a type-specific list. For more information, see CBaseList.

To use this template, declare a variable of type CGenericList with a template argument that defines the type of object in the list. For example, the following statement declares a list of CBaseFilter objects:

CGenericList<CBaseFilter> myFilterList("Filters");

For convenience, the following list types are defined:

typedef CGenericList<CBaseObject> CBaseObjectList;
typedef CGenericList<IUnknown> CBaseInterfaceList;

Requirements

Header: Declared in Wxlist.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CGenericList | Constructor method.
~CGenericList | Destructor method.
GetHeadPosition | Retrieves the position of the first item in the list.
GetTailPosition | Retrieves the position of the last item of the list.
GetCount | Retrieves the number of items in the list.
GetNext | Retrieves the item at the specified position, and advances the position.
Get | Retrieves the item at the specified position.
GetHead | Retrieves the item at the head of the list.
RemoveHead | Removes the first item in the list.
RemoveTail | Removes the last item in the list.
Remove | Removes the item at the specified position.
AddBefore | Inserts an item or list before the specified position.
AddAfter | Inserts an item or list after the specified position.
AddHead | Adds an item or list to the front of the list.
AddTail | Appends an item or list to the end of the list.
Find | Retrieves the first position that holds the specified item.


CGenericList::AddAfter

The AddAfter method inserts an item or list after the specified position.

Syntax

POSITION AddAfter(
    POSITION p,
    OBJECT *pObj
);

Parameters

p

Position after which to add the item. If p is NULL, the method adds the item to the head of the list.

pObj

Pointer to an object of type OBJECT (the template type).

Return Value

Returns the position indicator of the inserted item.

Syntax

BOOL AddAfter(
    POSITION pos,
    CGenericList<OBJECT> *pList
);

Parameters

pos

Position after which to insert the list.

pList

Pointer to the list to insert.

Return Value

Returns TRUE if successful, or FALSE otherwise.

See Also

  • CGenericList Class


CGenericList::AddBefore

The AddBefore method inserts an item or list before the specified position.

Syntax

POSITION AddBefore(
    POSITION p,
    OBJECT *pObj
);

Parameters

p

Position before which to insert the list. If p is NULL, this method adds the item to the tail of the list.

pObj

Pointer to an object of type OBJECT (the template type).

Return Value

Returns the position indicator for the inserted item.

Syntax

BOOL AddBefore(
    POSITION pos,
    CGenericList<OBJECT> *pList
);

Parameters

pos

Position before which to insert the list.

pList

Pointer to the list to insert.

Return Value

Returns TRUE if successful. Otherwise, returns FALSE.

See Also

  • CGenericList Class


CGenericList::AddHead

The AddHead method adds an item or list to the front of the list.

Syntax

POSITION AddHead(
    OBJECT *pObj
);

Parameters

pObj

Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value indicating the new head position. If the method fails, the return value is NULL.

Syntax

BOOL AddHead(
    CGenericList<OBJECT> *pList
);

Parameters

pList

Pointer to the list of items to add.

Return Value

Returns TRUE if successful, or FALSE otherwise.

See Also

  • CGenericList Class


CGenericList::AddTail

The AddTail method appends an item or list to the end of the list.

Syntax

POSITION AddTail(
    OBJECT *pObj
);

Parameters

pObj

Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value for the new tail position. If the method fails, it returns NULL.

Syntax

BOOL AddTail(
    CGenericList<OBJECT> *pList
);

Parameters

pList

Pointer to the list to append.

Return Value

Returns TRUE if successful, or FALSE otherwise.

See Also

  • CGenericList Class


CGenericList::CGenericList

Constructor method.

Syntax

CGenericList(
    TCHAR *pName,
    INT iItems,
    BOOL bLock,
    BOOL bAlert
);

CGenericList(
    TCHAR *pName
);

Parameters

pName

Pointer to the name of the list.

iItems

Size of the node cache.

bLock

Not used.

bAlert

Not used.

Remarks

For efficiency, the CGenericList class maintains a cache of list nodes. If you know approximately how many items the list will hold, use the first version of the constructor. The second version uses a default cache size.

See Also

  • CGenericList Class


CGenericList::~CGenericList

Destructor method.

Syntax

CGenericList(void);

See Also

  • CGenericList Class


CGenericList::Find

The Find method retrieves the first position that holds the specified item.

Syntax

POSITION Find(
    OBJECT *pObj
);

Parameters

pObj

Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value, or NULL if the item is not in the list.

See Also

  • CGenericList Class


CGenericList::Get

The Get method retrieves the item at the specified position.

Syntax

OBJECT *Get(
    POSITION pos
);

Parameters

pos

Position indicator for the item to retrieve.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

If pos is NULL, the method returns NULL.

See Also

  • CGenericList Class


CGenericList::GetCount

The GetCount method retrieves the number of items in the list.

Syntax

int GetCount(void);

Return Value

Returns the number of items in the list.

See Also

  • CGenericList Class


CGenericList::GetHead

The GetHead method retrieves the item at the head of the list.

Syntax

OBJECT GetHead(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type).

See Also

  • CGenericList Class


CGenericList::GetHeadPosition

The GetHeadPosition method retrieves the position of the first item in the list.

Syntax

POSITION GetHeadPosition(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

See Also

  • CGenericList Class


CGenericList::GetNext

The GetNext method retrieves the item at the specified position, and advances the position.

Syntax

OBJECT *GetNext(
    POSITION& rp
);

Parameters

rp

Reference to a POSITION value.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

This method advances the position indicator to the next position. If the position indicator moves past the end of the list, the method sets it to NULL.

If rp is NULL, the method returns NULL.

See Also

  • CGenericList Class


CGenericList::GetTailPosition

The GetTailPosition method retrieves the position of the last item of the list.

Syntax

POSITION GetTailPosition(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

See Also

  • CGenericList Class


CGenericList::Remove

The Remove method removes the item at the specified position.

Syntax

OBJECT *Remove(
    POSITION pos
);

Parameters

pos

POSITION value indicating the item to remove.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

This method deletes the node from the list, but does not delete the item contained in that node.

If pos is NULL, the method returns NULL.

See Also

  • CGenericList Class


CGenericList::RemoveHead

The RemoveHead method removes the first item in the list.

Syntax

OBJECT *RemoveHead(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type), or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that the node contains.

See Also

  • CGenericList Class


CGenericList::RemoveTail

The RemoveTail method removes the last item in the list.

Syntax

OBJECT *RemoveTail(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type), or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that is contained in the node.

See Also

  • CGenericList Class


CImageAllocator Class

CImageAllocator Class Hierarchy

The CImageAllocator class implements an allocator that manages GDI device-independent bitmaps (DIBs). This class derives from the CBaseAllocator class. It creates media samples that are implemented using the CImageSample class.

An allocator is shared by two connected pins, but is always owned by one of the filters in the connection. A filter that uses CImageAllocator must keep track of whether the allocator was provided by itself or by the other filter. If the allocator was provided by itself, the owning filter can rely on the fact that all media samples from the allocator are CImageSample objects. It can therefore use the CImageSample object to obtain information about the DIB, which is stored in a DIBDATA structure.

The owning filter should call NotifyMediaType whenever the media type changes.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_pFilter | Pointer to the owning filter.
m_pMediaType | Pointer to the current media type.
Protected Methods |
Alloc | Allocates memory for the buffers.
CheckSizes | Checks allocator properties against the current media type.
CreateDIB | Creates a DIB.
CreateImageSample | Creates a media sample. Virtual.
Free | Releases all of the buffer memory.
Public Methods |
CImageAllocator | Constructor method.
NotifyMediaType | Informs the object of the current media type.
IMemAllocator Methods |
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.

See Also

  • CDrawImage Class


CImageAllocator::m_pFilter

The m_pFilter member variable is a pointer to the owning filter.

Syntax

CBaseFilter *m_pFilter;

See Also

  • CImageAllocator Class


CImageAllocator::m_pMediaType

The m_pMediaType member variable is a pointer to the current media type.

Syntax

CMediaType *m_pMediaType;

See Also

  • CImageAllocator Class
  • CImageAllocator::NotifyMediaType


CImageAllocator::Alloc

The Alloc method allocates memory for the buffers. This method overrides the CBaseAllocator::Alloc method.

Syntax

HRESULT Alloc(void);

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

This method is called by the CBaseAllocator::Commit method, when the filter commits the allocator.

This method creates a list of media samples, which are implemented as CImageSample objects. Each sample contains a GDI device-independent bitmap, using the GDI CreateDIBSection function.

Internally this method calls CImageAllocator::CreateDIB to create each DIB, and CImageAllocator::CreateImageSample to create each sample.

See Also

  • CImageAllocator Class


CImageAllocator::CheckSizes

The CheckSizes method checks allocator properties against the current media type.

Syntax

HRESULT CheckSizes(
  ALLOCATOR_PROPERTIES *pRequest
);

Parameters

pRequest

Pointer to an ALLOCATOR_PROPERTIES structure that describes the requested allocator properties.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | The requested properties are compatible with the media type.
E_INVALIDARG | The requested properties are not compatible with the media type.
VFW_E_NOT_CONNECTED | The owning pin is not connected.

Remarks

When the method returns, if the return value is S_OK, the cbBuffer member of pRequest contains the actual buffer size. This might be larger than the requested size, but will never be smaller.

See Also

  • CImageAllocator Class


CImageAllocator::CImageAllocator

Constructor method.

Syntax

CImageAllocator(
  CBaseFilter *pFilter,
  TCHAR *pName,
  HRESULT *phr
);

Parameters

pFilter

Pointer to the owning filter.

pName

Pointer to a string containing the debug name of the allocator. For more information, see CBaseObject.

phr

Pointer to an HRESULT value. Set the value to S_OK before creating the object. If the constructor fails, the value is set to an error code.

See Also

  • CImageAllocator Class


CImageAllocator::CreateDIB

The CreateDIB method creates a GDI device-independent bitmap (DIB). The DIB is allocated in a shared mempory block, which eliminates a copy operation when the owning filter blits the image.

Syntax

HRESULT CreateDIB(
  LONG InSize,
  DIBDATA &DibData
);

Parameters

InSize

Size of the bitmap.

DibData

Reference to a DIBDATA structure. The method fills in this structure with information about the DIB.

Return Value

Returns S_OK if successful, or an error code otherwise.

See Also

  • CImageAllocator Class
  • CImageAllocator::Alloc


CImageAllocator::CreateImageSample

The CreateImageSample method creates a media sample.

Syntax

virtual CImageSample *CreateImageSample(
  LPBYTE pData,
  LONG Length
);

Parameters

pData

Pointer to a buffer of size Length, allocated by the caller.

Length

Length of the buffer.

Return Value

Returns a CImageSample object.

Remarks

This method creates a new media sample, implemented as a CImageSample object. The sample's IMediaSample::GetPointer method returns a pointer to the buffer specified in the pData parameter.

If you derive a new allocator class from CImageAllocator and a new media sample class from CImageSample, you should override this method to create an instance of your media sample class.

See Also

  • CImageAllocator Class
  • CImageAllocator::Alloc


CImageAllocator::Free

The Free method releases all of the buffer memory. This method implements the pure virtual CBaseAllocator::Free method.

Syntax

void Free(void);

Return Value

No return value.

See Also

  • CImageAllocator Class


CImageAllocator::NotifyMediaType

The NotifyMediaType method informs the object of the current media type.

Syntax

void NotifyMediaType(
  CMediaType *pMediaType
);

Parameters

pMediaType

Pointer to a CMediaType object, or NULL to clear the media type.

Return Value

No return value.

Remarks

The owning filter should call this method whenever the media type changes. Typically this occurs when the pin first connects, and after a dynamic format change. The allocator uses the media type to validate proposed allocator properties, and also when it creates media samples.

The CImageAllocator object stores the pMediaType pointer in the m_pMediaType member variable. Therefore, if the caller needs to release the CMediaType object, it should update the allocator by calling this method again, either with a new pointer or with a NULL value. Otherwise, an error can occur when the allocator attempts to reference the old pointer.

See Also

  • CImageAllocator Class


CImageAllocator::SetProperties

The SetProperties method specifies the number of buffers to allocate and the size of each buffer. This method overrides the CBaseAllocator::SetProperties method.

Syntax

HRESULT SetProperties(
  ALLOCATOR_PROPERTIES *pRequest,
  ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.

pActual

Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns an HRESULT value.

Remarks

This method calls CImageAllocator::CheckSizes to validate the requested buffer size. It also calls the base-class version of SetProperties.

See Also

  • CImageAllocator Class


CImageDisplay Class

The CImageDisplay class is a helper class for GDI video renderers to manage the display format. The object stores a VIDEOINFO structure that describes the current display mode, which is initialized in the object's constructor method. The object's CheckMediaType method checks whether a proposed media type can be rendered efficiently using GDI.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_Display | VIDEOINFO structure that describes the current display format.
Protected Methods |
CheckBitFields | Validates the color masks in a VIDEOINFO structure.
CountPrefixBits | Calculates the number of zero bits at the start of a specified bit field.
CountSetBits | Returns the number of bits set to 1 in a specified bit field.
Public Methods |
CheckHeaderValidity | Validates a BITMAPINFOHEADER structure.
CheckMediaType | Determines whether a proposed media type is compatible with the display format.
CheckPaletteHeader | Validates the palette entries in a VIDEOINFO structure.
CheckVideoType | Checks whether a specified VIDEOINFO format is compatible with the display format.
CImageDisplay | Constructor method.
GetBitMasks | Retrieves the color masks for a specified VIDEOINFO format.
GetColourMask | Retrieves the color masks for the current display format.
GetDisplayDepth | Retrieves the bit depth of the current display mode.
GetDisplayFormat | Retrieves a video format that describes the current display mode.
IsPalettised | Retermines whether the current display format is palettized.
RefreshDisplayType | Updates the object's video format to match the specified display

See Also

CDrawImage Class


CImageDisplay::m_Display

The m_Display member is a VIDEOINFO structure that describes the current display format.

Syntax

VIDEOINFO m_Display;

See Also

  • CImageDisplay Class


CImageDisplay::CheckBitFields

The CheckBitFields method validates the color masks in a VIDEOINFO structure.

Syntax

BOOL CheckBitFields(
    const VIDEOINFO *pInput
);

Parameters

pInput

Pointer to a VIDEOINFO structure.

Return Value

Returns TRUE if the color masks are valid, or FALSE otherwise.

Remarks

This method verifies that the color mask for each color component is between one and eight bits long, and that each color mask is a contiguous sequence of bits. Call this method only when the biCompression member is set to BI_BITFIELDS.

See Also

  • CImageDisplay Class


CImageDisplay::CheckHeaderValidity

The CheckHeaderValidity method validates a BITMAPINFOHEADER structure. This method is useful only for uncompressed RGB types, not for compressed types or YUV types.

Syntax

BOOL CheckHeaderValidity(
    const VIDEOINFO *pInput
);

Parameters

pInput

Pointer to a VIDEOINFO structure containing the BITMAPINFOHEADER structure.

Return Value

Returns TRUE if the BITMAPINFOHEADER is valid, or FALSE otherwise.

Remarks

This method checks that the image dimensions are non-negative; the compression type is BI_RGB or BI_BITFIELDS; the color depth and color masks are valid; the biPlanes member equals one; and the biSize and biSizeImage members are correct. It also checks for common errors in the palette entries, if any.

See Also

  • CImageDisplay Class


CImageDisplay::CheckMediaType

The CheckMediaType method determines whether a proposed media type is compatible with the display format.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmtIn
);

Parameters

pmtIn

Pointer to a CMediaType object that contains the media type.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Invalid media type.
E_INVALIDARG | Invalid media type.
S_OK | The media type is compatible.

See Also

  • CImageDisplay Class


CImageDisplay::CheckPaletteHeader

The CheckPaletteHeader method validates the palette entries in a VIDEOINFO structure.

Syntax

BOOL CheckPaletteHeader(
    const VIDEOINFO *pInput
);

Parameters

pInput

Pointer to a VIDEOINFO structure.

Return Value

Returns TRUE if the palette entries are valid, or FALSE otherwise.

Remarks

If the image format is not palettized, the method verifies that biClrUsed equals zero. Otherwise, the method verifies that the biCompression flag is BI_RGB; biClrImportant is not greater than biClrUsed; and the number of palette entries does not exceed the maximum, given the color depth.

See Also

  • CImageDisplay Class


CImageDisplay::CheckVideoType

The CheckVideoType method checks whether a specified VIDEOINFO format is compatible with the display format.

Syntax

HRESULT CheckVideoType(
    const VIDEOINFO *pInput
);

Parameters

pInput

Pointer to a VIDEOINFO structure.

Return Value

Returns S_OK if the format is compatible, or E_INVALIDARG otherwise.

Remarks

This method returns S_OK if the proposed type can be displayed easily under the current display settings.

See Also

  • CImageDisplay Class


CImageDisplay::CImageDisplay

Constructor method.

Syntax

CImageDisplay(void);

Return Value

No return value.

Remarks

The constructor initializes the format type, using the display settings for the main display device.

See Also

  • CImageDisplay Class
  • CImageDisplay::RefreshDisplayType


CImageDisplay::CountPrefixBits

The CountPrefixBits method calculates the number of zero bits at the start of a specified bit field.

Syntax

DWORD CountPrefixBits(
    const DWORD Field
);

Parameters

Field

Specifies a bit field as a DWORD value.

Return Value

Returns the number of zero bits that occur before the first 1 bit, or 0x80000000 if all bits are zero.

Remarks

This method is useful for working with color masks in VIDEOINFO structures.

See Also

  • CImageDisplay Class


CImageDisplay::CountSetBits

The CountSetBits method returns the number of bits set to 1 in a specified bit field.

Syntax

DWORD CountSetBits(
    const DWORD Field
);

Parameters

Field

Specifies a bit field as a DWORD value.

Return Value

Returns the number of bits that are set to 1.

See Also

  • CImageDisplay Class


CImageDisplay::GetBitMasks

The GetBitMasks method retrieves the color masks for a specified VIDEOINFO format.

Syntax

const DWORD *GetBitMasks(
    const VIDEOINFO *pVideoInfo
);

Parameters

pVideoInfo

Pointer to the VIDEOINFO structure.

Return Value

Returns an array of three DWORD values.

Remarks

If the biCompression member is BI_BITFIELDS, the method returns a pointer to the color masks that are supplied in the dwBitMasks member. If the biCompression member is BI_RGB, the method returns the color masks that correspond to the bit depth. If the method fails (for example, the bit depth is less than 16), the method returns the array {0,0,0}.

See Also

  • CImageDisplay Class


CImageDisplay::GetColourMask

The GetColourMask method retrieves the color masks for the current display format.

Syntax

BOOL GetColourMask(
    DWORD *pMaskRed,
    DWORD *pMaskGreen,
    DWORD *pMaskBlue
);

Parameters

pMaskRed

Pointer to a variable that receives the red-component mask.

pMaskGreen

Pointer to a variable that receives the green-component mask.

pMaskBlue

Pointer to a variable that receives the blue-component mask.

Return Value

Returns TRUE if successful, or FALSE otherwise.

See Also

  • CImageDisplay Class


CImageDisplay::GetDisplayDepth

The GetDisplayDepth method retrieves the bit depth of the current display mode.

Syntax

WORD GetDisplayDepth(void);

Return Value

Returns the number of bits per pixel.

See Also

  • CImageDisplay Class


CImageDisplay::GetDisplayFormat

The GetDisplayFormat method retrieves a video format that describes the current display mode.

Syntax

const VIDEOINFO *GetDisplayFormat(void);

Return Value

Returns a pointer to a VIDEOINFO structure.

See Also

  • CImageDisplay Class


CImageDisplay::IsPalettised

The IsPalettised method determines whether the current display format is palettized.

Syntax

BOOL IsPalettised(void);

Return Value

Returns TRUE if the format is palettized, or FALSE otherwise.

See Also

  • CImageDisplay Class


CImageDisplay::RefreshDisplayType

The RefreshDisplayType method updates the object's video format to match the specified display.

Syntax

HRESULT RefreshDisplayType(
    LPSTR szDeviceName
);

Parameters

szDeviceName

Pointer to a string that contains the name of the display device, as returned by the GDI EnumDisplayDevices function. To use the main display device, set this parameter to NULL.

Return Value

Returns S_OK if successful, or E_FAIL if unsuccessful.

Remarks

This method initializes the m_Display member to a video type that corresponds to the display mode on the specified device.

Call this method whenever a WM_DISPLAYCHANGED message is received, or to specify a secondary display device.

See Also

  • CImageDisplay Class


CImageDisplay::UpdateFormat

The UpdateFormat method fills in some optional members of the VIDEOINFO structure.

Syntax

HRESULT UpdateFormat(
    VIDEOINFO *pVideoInfo
);

Parameters

pVideoInfo

Pointer to a VIDEOINFO structure.

Return Value

Returns S_OK.

Remarks

This method sets the biClrUsed, biClrImportant, and biSizeImage members to the correct values, and clears the source and target rectangles.

See Also

  • CImageDisplay Class


CImagePalette Class

The CImagePalette class manages palettes for video renderers. It can be used to create a logical palette from a video format. This class is intended to be used with the CBaseWindow and CDrawImage classes, so it is somewhat specialized.

Protected Member Variables | Description
m_hPalette | Handle to the logical palette that this object manages.
m_pBaseWindow | Pointer to the CBaseWindow object that manages the window.
m_pDrawImage | Pointer to the CDrawImage object that draws the video image.
m_pFilter | Pointer to the owning filter.
Public Methods |
CImagePalette | Constructor method.
CopyPalette | Copies the palette from any VIDEOINFO structure to any palettized VIDEOINFO structure.
MakeIdentityPalette | Attempts to make a palette that maps directly to the palette selected in the display device.
MakePalette | Creates a logical palette from the color table in a video format.
PreparePalette | Sets up a palette, based on a media type from the owning filter.
RemovePalette | Deletes the existing logical palette.


CImagePalette::m_hPalette

The m_hPalette member variable is a handle to the logical palette that this object manages.

Syntax

HPALETTE m_hPalette;

See Also

  • CImagePalette Class


CImagePalette::m_pBaseWindow

The m_pBaseWindow member variable is a pointer to the CBaseWindow object that manages the window.

Syntax

CBaseWindow *m_pBaseWindow;

See Also

  • CImagePalette Class


CImagePalette::m_pDrawImage

The m_pDrawImage member variable is a pointer to the CDrawImage object that draws the video image.

Syntax

CDrawImage *m_pDrawImage;

See Also

  • CImagePalette Class


CImagePalette::m_pFilter

The m_pFilter member variable is a pointer to the owning filter.

Syntax

CBaseFilter *m_pFilter;

See Also

  • CImagePalette Class


CImagePalette::CImagePalette

Constructor method.

Syntax

CImagePalette(
    CBaseFilter *pBaseFilter,
    CBaseWindow *pBaseWindow,
    CDrawImage *pDrawImage
);

Parameters

pBaseFilter

Pointer to owning filter.

pBaseWindow

Pointer to a CBaseWindow object, which manages the window where the palette is realized. This parameter can be NULL.

pDrawImage

Pointer to a CDrawImage object, which draws the video image. This parameter can be NULL.

See Also

  • CImagePalette Class


CImagePalette::CopyPalette

The CopyPalette method copies the palette from any VIDEOINFO structure to any palettized VIDEOINFO structure.

Syntax

HRESULT CopyPalette(
    const CMediaType *pSrc,
    const CMediaType *pDest
);

Parameters

pSrc

Pointer to the source media type.

pDest

Pointer to the destination media type.

Return Value

Returns S_OK if the palette was copied. Returns S_FALSE if either the source or destination media type does not have a palette.

Remarks

The pDest media type must be a palettized format with a color depth of 8 bits or less. The pSrc media type can be any VIDEOINFOHEADER type with a palette, including YUV and true-color formats with palette entries. The method copies the palette entries from pSrc into a new palette, and attaches the new palette to pDest.

See Also

  • CImagePalette Class


CImagePalette::MakeIdentityPalette

The MakeIdentityPalette method attempts to make an "identity palette," defined as one that maps directly to the palette selected in the display device.

Syntax

HRESULT MakeIdentityPalette(
    PALETTEENTRY *pEntry,
    INT iColours,
    LPSTR szDevice
);

Parameters

pEntry

Pointer to an array of palette entries.

iColours

Number of palette entries in pEntry.

szDevice

Pointer to a string that contains the name of the display device, as returned by the GDI EnumDisplayDevices function. To use the main display device, set this parameter to NULL.

Return Value

Returns S_OK if successful or S_FALSE if unsuccessful.

Remarks

This method compares the reserved entries in the system palette against the corresponding entries in the pEntry array. If they match exactly, the method sets the PC_NOCOLLAPSE flag in the remaining (non-reserved) palette entries in pEntry. This flag prevents GDI from trying map logical palette entries to system palette entries.

The CImagePalette::MakePalette method calls this method.

See Also

  • CImagePalette Class


CImagePalette::MakePalette

The MakePalette method creates a logical palette from the color table in a video format.

Syntax

HPALETTE MakePalette(
    const VIDEOINFOHEADER *pVideoInfo,
    LPSTR szDevice
);

Parameters

pVideoInfo

Pointer to a VIDEOINFOHEADER structure that contains the color table.

szDevice

Pointer to a string that contains the name of the display device, as returned by the GDI EnumDisplayDevices function. To use the main display device, set this parameter to NULL.

Return Value

If successful, returns a handle to the palette. Otherwise, returns NULL.

See Also

  • CImagePalette Class


CImagePalette::PreparePalette

The PreparePalette method sets up a palette, based on a media type from the owning filter.

Syntax

HRESULT PreparePalette(
    const CMediaType *pmtNew,
    const CMediaType *pmtOld,
    LPSTR szDevice
);

Parameters

pmtNew

Pointer to the new media type. The format block must be a VIDEOINFOHEADER structure.

pmtOld

Pointer to the old media type. If the media type is being set for the first time, this parameter can be an empty type with no format block. Otherwise, the format block must be a VIDEOINFOHEADER structure.

szDevice

Pointer to a string that contains the name of the display device, as returned by the GDI EnumDisplayDevices function. To use the main display device, set this parameter to NULL.

Return Value

Returns S_OK if the palette was updated, or S_FALSE if the palette did not change.

Remarks

If the palette needs to be updated, this method performs the following actions:

  • Calls CImagePalette::MakePalette to create a new logical palette.
  • Sends an EC_PALETTE_CHANGED event to the Filter Graph Manager.
  • Calls CBaseWindow::SetPalette on the CBaseWindow object.
  • Calls CDrawImage::IncrementPaletteVersion on the CDrawImage object.

See Also

  • CImagePalette Class


CImagePalette::RemovePalette

The RemovePalette method deletes the existing logical palette and calls CBaseWindow::UnsetPalette on the CBaseWindow object.

Syntax

HRESULT RemovePalette(void);

Return Value

Returns S_OK.

See Also

  • CImagePalette Class


CImagePalette::ShouldUpdate

The ShouldUpdate method determines whether it is necessary to create a new palette.

Syntax

BOOL ShouldUpdate(
    const VIDEOINFOHEADER *pNewInfo,
    const VIDEOINFOHEADER *pOldInfo
);

Parameters

pNewInfo

Pointer to a VIDEOINFOHEADER structure containing the new color table.

pOldInfo

Pointer to a VIDEOINFOHEADER structure containing the old color table. This parameter can be NULL.

Return Value

Returns TRUE if the palette needs to be updated, or FALSE otherwise.

Remarks

  • If neither VIDEOINFOHEADER structure contains a color table, the method returns FALSE.
  • If only one structure contans a color table, or if pOldInfo is NULL, the method returns TRUE.
  • If both structures contain color tables, and the color entries match, the method returns FALSE.
  • If both structures contain color tables, but the color entries do not match, the method returns TRUE.

See Also

  • CImagePalette Class


CImageSample Class

CImageSample Class Hierarchy

The CImageSample class implements a media sample that manages a GDI device-independent bitmap (DIB). This class derives from the CMediaSample class. It is intended to be used with the CImageAllocator class. The CImageAllocator class provides an allocator that creates CImageSample objects.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_DibData | Contains information about the DIB that this object is managing.
m_bInit | Indicates whether the object has been initialized.
Public Methods |
CImageSample | Constructor method.
GetDIBData | Retrieves information about the DIB that this object is managing.
SetDIBData | Sets information about the DIB that this object is managing.


CImageSample::m_DibData

The m_DibData member variable is a DIBDATA structure that contains information about a GDI device-independent bitmap (DIB).

Syntax

DIBDATA m_DibData;

See Also

  • CImageSample Class


CImageSample::m_bInit

The m_bInit member variable indicates whether the CImageSample object has been initialized. If so, the value if TRUE. Otherwise, it is FALSE.

Syntax

BOOL m_bInit;

See Also

  • CImageSample Class
  • CImageSample::GetDIBData
  • CImageSample::SetDIBData


CImageSample::CImageSample

Constructor method.

Syntax

CImageSample(
  CBaseAllocator *pAllocator,
  TCHAR *pName,
  HRESULT *phr,
  LPBYTE pBuffer,
  LONG length
);

Parameters

pAllocator

Pointer to the allocator that created this sample.

pName

Ignored.

phr

Ignored.

pBuffer

Pointer to a memory buffer allocated by the caller, of size length. The buffer should contain a GDI device-independent bitmap (DIB).

length

Length of the buffer.

Remarks

The CImageAllocator class creates a DIB using a file-mapping object that is backed by the operating-system paging file. The handle to the file-mapping object is stored in the hMapping member of the m_DibData structure.

See Also

  • CImageSample Class


CImageSample::GetDIBData

The GetDIBData method retrieves information about the GDI device-independent bitmap (DIB) that this object is managing.

Syntax

DIBDATA *GetDIBData(void);

Return Value

Returns a pointer to a DIBDATA structure.

Remarks

The caller must initialize the DIBDATA structure before calling this method; check the value of CImageSample::m_bInit. To initialize the structure, call the CImageSample::SetDIBData method.

See Also

  • CImageSample Class


CImageSample::SetDIBData

The SetDIBData method specifies information about the GDI device-independent bitmap (DIB) that this object is managing. Call this method to initialize the CImageSample object.

Syntax

void SetDIBData(
  DIBDATA *pDibData
);

Parameters

pDibData

Pointer to a DIBDATA structure.

Return Value

No return value.

See Also

  • CImageSample Class


CLoadDirectDraw Class

The CLoadDirectDraw class is deprecated, although it is still provided with the DirectShow base-class library for backward compatibility.


CMediaControl Class

CMediaControl Class Hierarchy

The CMediaControl class provides base class handling of the IDispatch methods of the dual-interface IMediaControl. It leaves as pure virtual the properties and methods of the IMediaControl interface.

Typically, the filter graph manager is the only object that implements the IMediaControl interface. (filters implement the IMediaFilter interface, inherited by IBaseFilter, to receive control commands from the filter graph manager.) Therefore, this class library is of limited use to filter developers.

The CMediaControl::GetIDsOfNames, CMediaControl::GetTypeInfo, CMediaControl::GetTypeInfoCount, and CMediaControl::Invoke member functions are standard implementations of the IDispatch methods using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual methods of the IMediaControl interface.

The IMediaControl methods, defined in control.odl, are left as pure virtual.

Member Functions

CMediaControl Constructs a CMediaControl object.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers (DISPIDs), which can be used during subsequent calls to the CMediaControl::Invoke method.
GetTypeInfo | Retrieves a type-information object, which can retrieve the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.


CMediaControl::CMediaControl

Constructor method.

Syntax

CMediaControl(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

Parameters

pName

Pointer to the name of the object for debugging purposes.

pUnk

Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

See Also

  • CMediaControl Class


CMediaControl::GetIDsOfNames

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers (DISPIDs), which can be used upon subsequent calls to the CMediaControl::Invoke member function.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Address of a pointer to a passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

Locale context in which to interpret the names.

rgdispid

Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.

Value | Description
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

See Also

  • CMediaControl Class


CMediaControl::GetTypeInfo

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

itinfo

Type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.

pptinfo

Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type.

See Also

  • CMediaControl Class


CMediaControl::GetTypeInfoCount

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo

Pointer to the number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

See Also

  • CMediaControl Class


CMediaControl::Invoke

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
);

Parameters

dispidMember

Identifier of the member. Use CMediaControl::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.

riid

Reserved for future use. Must be IID_NULL.

lcid

Locale context in which to interpret arguments.

wFlags

Flags describing the context of the CMediaControl::Invoke call.

pdispparams

Pointer to a structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for number of elements in the arrays.

pvarResult

Pointer to where the result is to be stored, or NULL if the caller expects no result.

pexcepinfo

Pointer to a structure containing exception information.

puArgErr

Pointer to the index of the first argument, within the DISPPARAMS structure's rgvarg array, that has an error. For more information on DISPPARAMS, see the Platform SDK.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CMediaControl::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

See Also

  • CMediaControl Class


CMediaEvent Class

CMediaEvent Class Hierarchy

The CMediaEvent class provides base class implementation of the IDispatch methods of the dual-interface IMediaEvent. It leaves as pure virtual the properties and methods of the IMediaEvent interface.

The CMediaEvent class also provides base class implementation of the IMediaEventEx interface which derives from IMediaEvent.

The CMediaEvent::GetIDsOfNames, CMediaEvent::GetTypeInfo, CMediaEvent::GetTypeInfoCount, and CMediaEvent::Invoke member functions are standard implementations of the IDispatch interface using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual methods of the IMediaEvent interface.

Member Functions

CMediaEvent Constructs a CMediaEvent object.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used during subsequent calls to the IDispatch::Invoke method.
GetTypeInfo | Retrieves a type-information object, which retrieves the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.


CMediaEvent::CMediaEvent

Constructor method.

Syntax

CMediaEvent(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

Parameters

pName

Pointer to the name of the object for debugging purposes.

pUnk

Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

See Also

  • CMediaEvent Class


CMediaEvent::GetIDsOfNames

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used upon subsequent calls to the CMediaEvent::Invoke member function.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid

Reference identifier. Reserved for future use. Must be NULL.

rgszNames

Address of a pointer to a passed-in array of names to be mapped.

cNames

Count of the names to be mapped.

lcid

Locale context in which to interpret the names.

rgdispid

Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.

Value | Description
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

See Also

  • CMediaEvent Class


CMediaEvent::GetTypeInfo

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

itinfo

Type information to return. Pass zero to retrieve type information for the IDispatch implementation.

lcid

Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.

pptinfo

Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type.

See Also

  • CMediaEvent Class


CMediaEvent::GetTypeInfoCount

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo

Pointer to number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

See Also

  • CMediaEvent Class


CMediaEvent::Invoke

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
);

Parameters

dispidMember

Identifier of the member. Use CMediaEvent::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.

riid

Reserved for future use. Must be IID_NULL.

lcid

Locale context in which to interpret arguments.

wFlags

Flags describing the context of the CMediaEvent::Invoke call.

pdispparams

Pointer to a structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for the number of elements in the arrays.

pvarResult

Pointer to where the result is to be stored, or NULL if the caller expects no result.

pexcepinfo

Pointer to a structure containing exception information.

puArgErr

Pointer to the index of the first argument, within the DISPPARAMS structure's rgvarg array, that has an error. For more information on DISPPARAMS, see the Platform SDK.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CMediaEvent::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

See Also

  • CMediaEvent Class


CMediaPosition Class

CMediaPosition Class Hierarchy

The CMediaPosition class handles the IDispatch methods of the IMediaPosition dual interface.

This class inherits the IMediaPosition interface but does not implement it. It implements IDispatch through the CBaseDispatch class and the Microsoft® DirectShow® type library. Do not use this class directly. Instead, use one of the following classes:

  • Source filters: Use the CSourceSeeking base class to implement seeking.
  • Transform filters: Use the CPosPassThru class to pass seeking commands upstream.
  • Renderers: Use the CRendererPosPassThru class to pass seeking commands upstream.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CMediaPosition | Constructor method.
IDispatch Methods |
GetIDsOfNames | Maps a set of names to a corresponding set of DISPIDs.
GetTypeInfo | Retrieves the type information for the object, which can then be used to get the type information for an interface.
GetTypeInfoCount | Retrieves the number of type information interfaces the object provides.
Invoke | Provides access to properties and methods exposed by the object.


CMediaPosition::CMediaPosition

Constructor method.

Syntax

CMediaPosition(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

CMediaPosition(
    const TCHAR *pName,
    LPUNKNOWN pUnk
    HRESULT *phr
);

Parameters

pName

Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.

pUnk

Pointer to the owner of this object, or NULL if the object is not aggregated.

phr

Ignored.

See Also

  • CMediaPosition Class


CMediaPosition::GetIDsOfNames

The GetIDsOfNames method maps a set of names to a corresponding set of DISPIDs.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid

Reserved. Use IID_NULL.

rgszNames

Address of an array of wide-character strings that contain the names to be mapped.

cNames

Size of the array given by the rgszNames parameter.

lcid

Locale context in which to interpret the names. Can be NULL.

rgdispid

Pointer to an array that receives the DISPIDs. Each element of receives an identifier that corresponds to one of the names passed in the rgszNames parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
DISP_E_UNKNOWNNAME | One or more of the names were not known.

See Also

  • CMediaPosition Class


CMediaPosition::GetTypeInfo

The GetTypeInfo method retrieves the type information for the object, which can then be used to get the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

itinfo

Type information to return. Must be zero.

lcid

Locale identifier.

pptinfo

Address of a variable that receives an ITypeInfo pointer.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.
TYPE_E_ELEMENTNOTFOUND | The itinfo parameter is not zero.

See Also

  • CMediaPosition Class


CMediaPosition::GetTypeInfoCount

The GetTypeInfoCount method retrieves the number of type information interfaces the object provides.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo

Pointer to a variable that receives the number of type-information interfaces provided by the object. When the method returns, the value is 1.

Return Value

Returns one of the following values.

Value | Description
S_OK | Success.
E_POINTER | Null pointer argument.

See Also

  • CMediaPosition Class


CMediaPosition::Invoke

The Invoke method provides access to properties and methods exposed by the object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
);

Parameters

dispidMember

Identifier of the member. Use CMediaPosition::GetIDsOfNames to obtain the dispatch identifier.

riid

Reserved for future use. Must be IID_NULL.

lcid

Locale context in which to interpret arguments.

wFlags

Flags describing the context of the call.

pdispparams

Pointer to a DIPPARAMS structure that contains the arguments.

pvarResult

Pointer to a VARIANT that receives the result, or NULL if the caller expects no result.

pexcepinfo

Pointer to a structure that receives exception information.

puArgErr

Pointer to a variable that receives the index of the first argument that causes an error.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_UNKNOWNINTERFACE | The riid parameter is not IID_NULL

See Also

  • CMediaPosition Class


CMediaSample Class

CMediaSample Class Hierarchy

The CMediaSample class defines a media sample that supports the IMediaSample2 interface. The media sample contains a pointer to a memory buffer, and various properties stored as protected member variables.

Media samples are created by allocators, which are derived from the CBaseAllocator class. The CMediaSample constructor receives a pointer to an allocated buffer, along with the size of the buffer. Other properties are typically set and retrieved through IMediaSample interface methods.

The life cycle of a media sample differs from that of most COM objects:

  • The allocator holds a list of free samples. When a filter needs a new sample, it calls the allocator's IMemAllocator::GetBuffer method. The allocator retrieves a sample from its free list, increments the sample's reference count, and returns a pointer to the sample.
  • After the filter is done with the sample, it calls the IUnknown::Release method on the sample. Unlike most objects, the sample does not delete itself when its reference count reaches zero. Instead, it calls the IMemAllocator::ReleaseBuffer method on the allocator, and the allocator returns the sample to its free list.
  • The allocator does not destroy samples until the IMemAllocator::Decommit method is called.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_dwFlags | Sample property flags.
m_dwTypeSpecificFlags | Type-specific flags.
m_pBuffer | Pointer to the memory buffer that contains the media data.
m_lActual | Length of the valid data in the buffer, in bytes.
m_cbBuffer | Size of the buffer, in bytes.
m_pAllocator | Pointer to the allocator that created this sample.
m_pNext | Pointer to the next sample in the allocator's list of samples.
m_Start | Sample start time.
m_End | Sample end time.
m_MediaStart | Media start time.
m_MediaEnd | Media stop time.
m_pMediaType | Pointer to the media type, if the type has changed from the previous sample in the data stream.
m_dwStreamId | Stream identifier.
Public Member Variables |
m_cRef | Reference count.
Public Methods |
CMediaSample | Constructor method.
~CMediaSample | Destructor method. Virtual.
SetPointer | Sets the pointer to the memory buffer.
IMediaSample Methods |
GetPointer | Retrieves a read/write pointer to the buffer.
GetSize | Retrieves the size of the buffer.
GetTime | Retrieves the stream times at which this sample should begin and finish.
SetTime | Sets the stream times at which this sample should start and finish.
IsSyncPoint | Determines if the beginning of the sample is a synchronization point.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
IsPreroll | Determines if this sample is a preroll sample.
SetPreroll | Specifies whether this sample is a preroll sample.
GetActualDataLength | Retrieves the length of the valid data in the buffer.
SetActualDataLength | Sets the length of the valid data in the buffer.
GetMediaType | Retrieves the media type, if the media type differs from the previous sample.
SetMediaType | Sets the media type for the sample.
IsDiscontinuity | Determines if this sample represents a break in the data stream.
SetDiscontinuity | Specifies whether this sample represents a break in the data stream.
GetMediaTime | Retrieves the media times for this sample.
SetMediaTime | Sets the media times for this sample.
IMediaSample2 Methods |
GetProperties | Retrieves the properties of the sample.
SetProperties | Sets the properties of the sample.


CMediaSample::m_dwFlags

Sample property flags. Bitwise combination of flags from the AM_SAMPLE_PROPERTY_FLAGS enumerated type.

Syntax

DWORD m_dwFlags;

See Also

  • CMediaSample Class


CMediaSample::m_dwTypeSpecificFlags

Type-specific flags. The meaning of this member variable depends on the media type of the sample.

Syntax

DWORD m_dwTypeSpecificFlags;

See Also

  • CMediaSample Class


CMediaSample::m_pBuffer

Pointer to the memory buffer that contains the media data.

Syntax

LPBYTE m_pBuffer;

See Also

  • CMediaSample Class


CMediaSample::m_lActual

Length of the valid data in the buffer, in bytes. The value must be equal to or less than the size of the buffer, specified by the CMediaSample::m_cbBuffer member variable.

Syntax

LONG m_lActual;

See Also

  • CMediaSample Class


CMediaSample::m_cbBuffer

Size of the buffer, in bytes.

Syntax

LONG m_cbBuffer;

See Also

  • CMediaSample Class


CMediaSample::m_pAllocator

Pointer to the allocator that created this sample.

Syntax

CBaseAllocator *m_pAllocator;

Remarks

Although the sample keeps a pointer to the allocator, it does not hold a reference count. Instead, the allocator increments its own reference count in the IMemAllocator::GetBuffer method, and releases itself in the IMemAllocator::ReleaseBuffer method. This guarantees that the allocator will be available as long as another object is using the sample.

See Also

  • CMediaSample Class


CMediaSample::m_pNext

Pointer to the next sample in the allocator's list of samples.

Syntax

CMediaSample *m_pNext;

See Also

  • CMediaSample Class


CMediaSample::m_Start

Sample start time. This value is valid only if the CMediaSample::m_dwFlags member variable contains the AM_SAMPLE_TIMEVALID flag.

Syntax

REFERENCE_TIME m_Start;

See Also

  • CMediaSample Class


CMediaSample::m_End

Sample end time. This value is valid only if the CMediaSample::m_dwFlags member variable contains the AM_SAMPLE_STOPVALID flag.

Syntax

REFERENCE_TIME m_End;

See Also

  • CMediaSample Class


CMediaSample::m_MediaStart

Media start time.

Syntax

LONGLONG m_MediaStart;

See Also

  • CMediaSample Class


CMediaSample::m_MediaEnd

Media stop time. This value is calculated as an offset from the media start time, specified by the CMediaSample::m_MediaStart member variable.

Syntax

LONG m_MediaEnd;

See Also

  • CMediaSample Class


CMediaSample::m_pMediaType

Pointer to the media type, if the type has changed from the previous sample in the data stream. Otherwise, this member variable is NULL.

Syntax

AM_MEDIA_TYPE *m_pMediaType;

See Also

  • CMediaSample Class


CMediaSample::m_dwStreamId

Stream identifier. For more information, see AM_SAMPLE2_PROPERTIES.

Syntax

DWORD m_dwStreamId;

See Also

  • CMediaSample Class


CMediaSample::m_cRef

Reference count.

Syntax

LONG m_cRef;

See Also

  • CMediaSample Class


CMediaSample::CMediaSample

Constructor method.

Syntax

CMediaSample(
    TCHAR *pName,
    CBaseAllocator *pAllocator,
    HRESULT *phr,
    LPBYTE pBuffer = NULL,
    LONG length = 0
);

Parameters

pName

Ignored.

pAllocator

Pointer to the CBaseAllocator object that created this sample.

phr

Ignored.

pBuffer

Pointer to a memory buffer allocated by the caller, of size length.

length

Length of the memory buffer.

Remarks

The base class does not modify the HRESULT value passed in the phr parameter.

See Also

  • CMediaSample Class


CMediaSample::~CMediaSample

Destructor method.

Syntax

~CMediaSample(void);

See Also

  • CMediaSample Class


CMediaSample::GetActualDataLength

The GetActualDataLength method retrieves the length of the valid data in the buffer. This method implements the IMediaSample::GetActualDataLength method.

Syntax

LONG GetActualDataLength(void);

Return Value

Returns the length of the valid data, in bytes.

Remarks

The CMediaSample::m_lActual member variable specifies this property.

See Also

  • CMediaSample Class


CMediaSample::GetMediaTime

The GetMediaTime method retrieves the media times for this sample. This method implements the IMediaSample::GetMediaTime method.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pStart,
    LONGLONG *pEnd
);

Parameters

pStart

Pointer to a variable that receives the media start time.

pEnd

Pointer to a variable that receives the media stop time.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | No media times were set for this sample.

Remarks

The CMediaSample::m_MediaEnd member variable specifies an offset from CMediaSample::m_MediaStart, but the value received by the pEnd parameter is an absolute media time, calculated as m_MediaStart + m_MediaEnd.

For information about media times, see Time and Clocks in DirectShow.

See Also

  • CMediaSample Class


CMediaSample::GetMediaType

The GetMediaType method retrieves the media type, if the media type differs from the previous sample. This method implements the IMediaSample::GetMediaType method.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType

Address of a variable that receives a pointer to an AM_MEDIA_TYPE structure. If the media type has not changed from the previous sample, *ppMediaType is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_FALSE | The media type has not changed from the previous sample.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

Remarks

When you are done with the media type, free the memory block by calling the DeleteMediaType utility function.

The CMediaSample::m_pMediaType member variable specifies the media type. The CMediaSample::m_dwFlags member variable specifies whether the media type has changed.

See Also

  • CMediaSample Class


CMediaSample::GetPointer

The GetPointer method retrieves a read/write pointer to the buffer. This method implements the IMediaSample::GetPointer method.

Syntax

HRESULT GetPointer(
    BYTE **ppBuffer
);

Parameters

ppBuffer

Address of a variable that receives a pointer to the buffer.

Return Value

Returns S_OK.

See Also

  • CMediaSample Class


CMediaSample::GetProperties

The GetProperties method retrieves the properties of the sample. This method implements the IMediaSample2::GetProperties method.

Syntax

HRESULT GetProperties(
    DWORD cbProperties,
    BYTE *pbProperties
);

Parameters

cbProperties

Length of property data to retrieve, in bytes.

pbProperties

Pointer to a buffer of size cbProperties.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • CMediaSample Class


CMediaSample::GetSize

The GetSize method retrieves the size of the buffer. This method implements the IMediaSample::GetSize method.

Syntax

LONG GetSize(void);

Return Value

Returns the size of the buffer, in bytes.

See Also

  • CMediaSample Class


CMediaSample::GetTime

The GetTime method retrieves the stream times at which this sample should begin and finish. This method implements the IMediaSample::GetTime method.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

Pointer to a variable that receives the beginning stream time, in 100-nanosecond units.

pTimeEnd

Pointer to a variable that receives the ending stream time, in 100-nanosecond units. If the sample has no stop time, the value is set to the start time plus one.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_S_NO_STOP_TIME | Sample has a valid start time, but no stop time.
VFW_E_SAMPLE_TIME_NOT_SET | Sample does not have valid time stamps.

Remarks

The CMediaSample::m_Start and CMediaSample::m_End member variables specify the time stamps. The CMediaSample::m_dwFlags member variable specifies whether the time stamps are valid.

For information about time stamps, see Time and Clocks in DirectShow.

See Also

  • CMediaSample Class


CMediaSample::IsDiscontinuity

The IsDiscontinuity method determines if this sample represents a break in the data stream. This method implements the IMediaSample::IsDiscontinuity method.

Syntax

HRESULT IsDiscontinuity(void);

Return Value

Returns S_OK if the sample is a break in the data stream, and S_FALSE otherwise.

Remarks

The CMediaSample::m_dwFlags member variable specifies this property.

See Also

  • CMediaSample Class


CMediaSample::IsPreroll

The IsPreroll method determines if this sample is a preroll sample. A preroll sample should not be displayed. This method implements the IMediaSample::IsPreroll method.

Syntax

HRESULT IsPreroll(void);

Return Value

Returns S_OK if the sample is a preroll sample, and S_FALSE otherwise.

Remarks

The CMediaSample::m_dwFlags member variable specifies this property.

See Also

  • CMediaSample Class


CMediaSample::IsSyncPoint

The IsSyncPoint method determines if the beginning of the sample is a synchronization point. This method implements the IMediaSample::IsSyncPoint method.

Syntax

HRESULT IsSyncPoint(void);

Return Value

Returns S_OK if the sample is a synchronization point, or S_FALSE otherwise.

Remarks

The CMediaSample::m_dwFlags member variable specifies this property.

See Also

  • CMediaSample Class


CMediaSample::SetActualDataLength

The SetActualDataLength method sets the length of the valid data in the buffer. This method implements the IMediaSample::SetActualDataLength method.

Syntax

HRESULT SetActualDataLength(
    long lLen
);

Parameters

lLen

Length of the valid data, in bytes.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_E_BUFFER_OVERFLOW | lLen is larger than the allocated buffer size.

Remarks

This method sets the CMediaSample::m_lActual member variable.

See Also

  • CMediaSample Class


CMediaSample::SetDiscontinuity

The SetDiscontinuity method specifies whether this sample represents a break in the data stream. This method implements the IMediaSample::SetDiscontinuity method.

Syntax

HRESULT SetDiscontinuity(
    BOOL bDiscont
);

Parameters

bDiscont

Boolean value that specifies whether this sample is a discontinuity. If TRUE, the media sample is discontinuous with the previous sample.

Return Value

Returns S_OK.

Remarks

This method updates the CMediaSample::m_dwFlags member variable, which specifies the discontinuity property.

See Also

  • CMediaSample Class


CMediaSample::SetMediaTime

The SetMediaTime method sets the media times for this sample. This method implements the IMediaSample::SetMediaTime method.

Syntax

HRESULT SetMediaTime(
    LONGLONG *pStart,
    LONGLONG *pEnd
);

Parameters

pStart

Pointer to the media start time, or NULL.

pEnd

Pointer to the media stop time, or NULL.

Return Value

Returns S_OK.

Remarks

The media stop time must be greater than the media start time. Use NULL to invalidate the media times.

The pEnd parameter specifies an absolute media time, but the CMediaSample::m_MediaEnd member variable is calculated as an offset from pStart. In other words, m_MediaEnd = *pTimeEnd – *pTimeStart.

For information about media times, see Time and Clocks in DirectShow.

See Also

  • CMediaSample Class


CMediaSample::SetMediaType

The SetMediaType method sets the media type for the sample. This method implements the IMediaSample::SetMediaType method.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType

Pointer to an AM_MEDIA_TYPE structure.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

This method sets the CMediaSample::m_pMediaType member variable, which specifies the media type, and the CMediaSample::m_dwFlags member variable, which specifies whether the media type has changed.

This method makes a copy of the AM_MEDIA_TYPE structure.

See Also

  • CMediaSample Class


CMediaSample::SetPointer

The SetPointer method sets the pointer to the memory buffer.

Syntax

HRESULT SetPointer(
    BYTE *ptr,
    LONG cBytes
);

Parameters

ptr

Pointer to a memory buffer allocated by the caller, of size cBytes.

cBytes

Length of the buffer, in bytes.

Return Value

Returns S_OK.

Remarks

This method enables the allocator to set a new pointer for the sample.

This method is not available through the IMediaSample interface. The object that creates the sample can access this method (through CMediaSample), but other objects cannot.

See Also

  • CMediaSample Class


CMediaSample::SetPreroll

The SetPreroll method specifies whether this sample is a preroll sample. A preroll sample should not be displayed. This method implements the IMediaSample::SetPreroll method.

Syntax

HRESULT SetPreroll(
    BOOL bIsPreroll
);

Parameters

bIsPreroll

Boolean value that specifies whether this is a preroll sample. If TRUE, this is a preroll sample.

Return Value

Returns S_OK.

Remarks

This method updates the CMediaSample::m_dwFlags member variable, which specifies the preroll property.

See Also

  • CMediaSample Class


CMediaSample::SetProperties

The SetProperties method sets the properties of the sample. This method implements the IMediaSample2::SetProperties method.

Syntax

HRESULT SetProperties(
    DWORD cbProperties,
    const BYTE *pbProperties
);

Parameters

cbProperties

Length of property data to set, in bytes.

pbProperties

Pointer to a buffer of size cbProperties.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_INVALIDARG | Invalid argument
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

See Also

  • CMediaSample Class


CMediaSample::SetSyncPoint

The SetSyncPoint method specifies whether the beginning of this sample is a synchronization point. This method implements the IMediaSample::SetSyncPoint method.

Syntax

HRESULT SetSyncPoint(
    BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint

Boolean value that specifies whether this is a synchronization point. If TRUE, this is a synchronization point.

Return Value

Returns S_OK.

Remarks

This method updates the CMediaSample::m_dwFlags member variable, which specifies the synchronization-point property.

See Also

  • CMediaSample Class


CMediaSample::SetTime

The SetTime method sets the stream times when this sample should begin and finish. This method implements the IMediaSample::SetTime method.

Syntax

HRESULT SetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

Pointer to the stream time at which the sample begins, in 100-nanosecond units, or NULL.

pTimeEnd

Pointer to the stream time at which the sample ends, in 100-nanosecond units, or NULL.

Return Value

Returns S_OK.

Remarks

This method sets the CMediaSample::m_Start and CMediaSample::m_End member variables, which specify the time stamps. It also updates the CMediaSample::m_dwFlags member variable, which specifies whether the time stamps are valid.

For information about time stamps, see Time and Clocks in DirectShow.

See Also

  • CMediaSample Class


CMediaType Class

CMediaType Class Hierarchy

The CMediaType class manages media types. This class inherits the AM_MEDIA_TYPE structure. It can be cast to a variable of type AM_MEDIA_TYPE.

Requirements

Header: Declared in Mtype.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CMediaType | Constructor method.
~CMediaType | Destructor method.
Set | Sets the media type from another media type.
IsValid | Determines whether a major type has been assigned to this object.
Type | Retrieves the major type.
SetType | Specifies the major type.
Subtype | Retrieves the subtype.
SetSubtype | Specifies the subtype.
IsFixedSize | Determines if the samples have a fixed size or a variable size.
IsTemporalCompressed | Determines if the stream uses temporal compression.
GetSampleSize | Retrieves the sample size.
SetSampleSize | Specifies a fixed sample size, or specifies that samples have a variable size.
SetVariableSize | Specifies that samples do not have a fixed size.
SetTemporalCompression | Specifies whether samples are compressed using temporal compression.
Format | Retrieves a pointer to the format block.
FormatLength | Retrieves the length of the format block.
SetFormatType | Specifies the format type.
FormatType | Retrieves the format type.
SetFormat | Specifies the format block.
ResetFormatBuffer | Deletes the format block.
AllocFormatBuffer | Allocates memory for the format block.
ReallocFormatBuffer | Reallocates the format block to a new size.
InitMediaType | Initializes the media type.
MatchesPartial | Determines if this media type matches a partially specified media type.
IsPartiallySpecified | Determines if the media type is partially defined.
Operators |
operator = | Overloads the assignment operator to copy a media type.
operator == | Tests for equality between CMediaType objects.
operator != | Tests for inequality between CMediaType objects.


CMediaType::AllocFormatBuffer

The AllocFormatBuffer method allocates memory for the format block.

Syntax

BYTE* AllocFormatBuffer(
    ULONG length
);

Parameters

length

Size required for the format block, in bytes.

Return Value

Returns a pointer to the new block if successful. Otherwise, returns NULL.

Remarks

If the method successfully allocates a new format block, it frees the existing format block. If the allocation fails, the method leaves the existing format block.

See Also

  • CMediaType Class


CMediaType::CMediaType

Constructor method.

Syntax

CMediaType(void);

CMediaType(
    const GUID *majortype
);

CMediaType(
    const AM_MEDIA_TYPE& mtype,
    HRESULT *phr = NULL
);

CMediaType(
    const CMediaType& cmtype,
    HRESULT *phr = NULL
);

Parameters

majortype

Pointer to a major type GUID. The constructor initializes the major type GUID to this value.

mtype

Reference to an AM_MEDIA_TYPE structure. The constructor copies the media type to the new object, including the format block, if any.

cmtype

Reference to a CMediaType object. The constructor copies the media type to the new object, including the format block, if any.

phr

Pointer to a variable that receives an HRESULT value. This parameter can be a NULL pointer. Otherwise, the caller must set the value to S_OK before calling the constructor. If the constructor fails, it sets the value to a failure code.

Remarks

The constructor calls the CMediaType::InitMediaType method to initialize the media type.

See Also

  • CMediaType Class


CMediaType::~CMediaType

Destructor method.

Syntax

~CMediaType(void);

Remarks

The destructor calls the FreeMediaType function on itself.

See Also

  • CMediaType Class


CMediaType::Format

The Format method retrieves a pointer to the format block.

Syntax

BYTE* Format(void) const;

Return Value

Returns the pbFormat member.

See Also

  • CMediaType Class


CMediaType::FormatLength

The FormatLength method retrieves the length of the format block.

Syntax

ULONG FormatLength(void) const;

Return Value

Returns the cbFormat member.

See Also

  • CMediaType Class


CMediaType::FormatType

The FormatType method retrieves the format type.

Syntax

const GUID *FormatType(void) const;

Return Value

Returns a pointer to the formattype member.

See Also

  • CMediaType Class


CMediaType::GetSampleSize

The GetSampleSize method retrieves the sample size.

Syntax

ULONG GetSampleSize(void) const;

Return Value

If the sample size is fixed, returns the sample size in bytes. Otherwise, returns zero.

See Also

  • CMediaType Class


CMediaType::InitMediaType

The InitMediaType method initializes the media type.

Syntax

void InitMediaType(void);

Remarks

This method zeroes the object's memory, sets the fixed-sample-size property to TRUE, and sets the sample size to 1.

See Also

  • CMediaType Class


CMediaType::IsFixedSize

The IsFixedSize method determines if the samples have a fixed size or a variable size.

Syntax

BOOL IsFixedSize(void) const;

Return Value

Returns the value of the bFixedSizeSamples member.

See Also

  • CMediaType Class


CMediaType::IsPartiallySpecified

The IsPartiallySpecified method determines if the media type is partially defined. A media type is partial if the major type, subtype, or format type is GUID_NULL.

Syntax

BOOL IsPartiallySpecified(void) const;

Return Value

Returns TRUE if the media type is partially specified. Otherwise, returns FALSE.

Remarks

The IPin::Connect method can accept partial media types.

The implementation does not actually test the subtype. If there is a specified format type, the media type is not considered partial, even if the subtype is GUID_NULL.

See Also

  • CMediaType Class


CMediaType::IsTemporalCompressed

The IsTemporalCompressed method determines if the stream uses temporal compression.

Syntax

BOOL IsTemporalCompressed(void) const;

Return Value

Returns the value of the bTemporalCompression member.

See Also

  • CMediaType Class


CMediaType::IsValid

The IsValid method determines whether a major type has been assigned to this object.

Syntax

BOOL IsValid(void) const;

Return Value

Returns TRUE if a major type has been assigned to this object. Otherwise, returns FALSE.

Remarks

By default, CMediaType objects are initialized with a major type of GUID_NULL. Call this method to determine whether the object has been correctly initialized.

See Also

  • CMediaType Class


CMediaType::MatchesPartial

The MatchesPartial method determines if this media type matches a partially specified media type.

Syntax

BOOL MatchesPartial(
    const CMediaType *ppartial
) const;

Parameters

ppartial

Pointer to the media type to match.

Return Value

Returns TRUE if the media types match. Otherwise, returns FALSE.

Remarks

The media type specified by ppartial can have a value of GUID_NULL for the major type, subtype, or format type. Any members with GUID_NULL values are not tested. (In effect, GUID_NULL acts as a wildcard.) Members with values other than GUID_NULL must match for the media type to match.

See Also

  • CMediaType Class


CMediaType::ReallocFormatBuffer

The ReallocFormatBuffer method reallocates the format block to a new size.

Syntax

BYTE* ReallocFormatBuffer(
    ULONG length
);

Parameters

length

New size required for the format block, in bytes. Must be greater than zero.

Return Value

Returns a pointer to the new block if successful. Otherwise, returns either a pointer to the old format block, or NULL.

Remarks

This method allocates a new format block. It copies as much of the existing format block as possible into the new format block. If the new block is smaller than the existing block, the existing format block is truncated. If the new block is larger, the contents of the additional space are undefined. They are not explicitly set to zero.

See Also

  • CMediaType Class


CMediaType::ResetFormatBuffer

The ResetFormatBuffer method deletes the format block.

Syntax

void ResetFormatBuffer(void);

See Also

  • CMediaType Class


CMediaType::Set

The Set method sets the media type from another media type.

Syntax

HRESULT Set(
    const CMediaType& cmtype
);

HRESULT Set(
    const AM_MEDIA_TYPE& mtype
};

Parameters

cmtype

Reference to a CMediaType object.

length

Reference to an AM_MEDIA_TYPE structure.

Return Value

Returns S_OK or E_OUTOFMEMORY.

Remarks

This method copies the entire media type from cmtype or mtype.

See Also

  • CMediaType Class


CMediaType::SetFormat

The SetFormat method initializes the format block.

Syntax

BOOL SetFormat(
    BYTE *pFormat,
    ULONG length
);

Parameters

pFormat

Pointer to a block of memory that contains the format block.

length

Length of the format block, in bytes.

Return Value

Returns TRUE if successful, or FALSE if an error occurred.

Remarks

This method allocates memory for the format block and copies the buffer specified by pFormat into the new format block. If the media type already contains a format block, the old one is released.

To set the format type, call the CMediaType::SetFormatType method.

See Also

  • CMediaType Class


CMediaType::SetFormatType

The SetFormatType method specifies the format type.

Syntax

void SetFormatType(
    const GUID *pformattype
);

Parameters

pformattype

Pointer to a GUID that specifies the format type.

Remarks

This method sets the formattype member. The format type defines the layout of the format block. For example, if the format type is FORMAT_VideoInfo, the format block should contain a VIDEOINFOHEADER structure. To set the format block, call the CMediaType::SetFormat method. The caller is responsible for making sure that the format block matches the format type.

See Also

  • CMediaType Class


CMediaType::SetSampleSize

The SetSampleSize method specifies a fixed sample size, or specifies that samples have a variable size.

Syntax

void SetSampleSize(
    ULONG sz
);

Parameters

sz

Sample size, in bytes, or zero.

Remarks

If value of sz is zero, the media type uses variable sample sizes. Otherwise, the sample size is fixed at sz bytes.

See Also

  • CMediaType Class


CMediaType::SetSubtype

The SetSubtype method specifies the subtype.

Syntax

void SetSubtype(
    const GUID *psubtype
);

Parameters

psubtype

Pointer to a GUID that specifies the subtype.

See Also

  • CMediaType Class


CMediaType::SetTemporalCompression

The SetTemporalCompression method specifies whether samples are compressed using temporal (interframe) compression.

Syntax

void SetTemporalCompression(
    BOOL bCompressed
);

Parameters

bCompressed

Boolean value that specifies whether the stream uses temporal compression. If the stream uses temporal compression, set the value to TRUE.

Remarks

This method sets the bTemporalCompression member.

See Also

  • CMediaType Class


CMediaType::SetType

The SetType method specifies the major type.

Syntax

void SetType(
    const GUID *ptype
);

Parameters

ptype

Pointer to a GUID that specifies the major type.

See Also

  • CMediaType Class


CMediaType::SetVariableSize

The SetVariableSize method specifies that samples do not have a fixed size.

Syntax

void SetVariableSize(void);

Remarks

This method sets the bFixedSizeSamples member to FALSE. Subsequent calls to the CMediaType::GetSampleSize method return zero.

See Also

  • CMediaType Class


CMediaType::Subtype

The Subtype method retrieves the subtype.

Syntax

const GUID *Type(void) const;

Return Value

Returns a pointer to the subtype member.

See Also

  • CMediaType Class


CMediaType::Type

The Type method retrieves the major type.

Syntax

const GUID *Type(void) const;

Return Value

Returns a pointer to the majortype member.

See Also

  • CMediaType Class


CMediaType::operator =

This operator overloads the assignment operator to copy a media type.

Syntax

CMediaType& operator=(
    const CMediaType& cmtype
);

CMediaType& operator=(
    const AM_MEDIA_TYPE& mtype
);

Parameters

cmtype

Reference to a CMediaType object.

mtype

Reference to an AM_MEDIA_TYPE structure.

Return Value

Returns a reference to the object.

See Also

  • CMediaType Class


CMediaType::operator ==

This operator tests for equality between CMediaType objects.

Syntax

inline BOOL operator==(
    const CMediaType& rt
) const;

Parameters

rt

Reference to the CMediaType object to compare.

Return Value

Returns TRUE if rt is equal to this object. Otherwise, returns FALSE.

See Also

  • CMediaType Class


CMediaType::operator !=

This operator tests for inequality between CMediaType objects.

Syntax

BOOL operator!=(
    const CMediaType& rt
) const;

Parameters

rt

Reference to the CMediaType object to compare.

Return Value

Returns TRUE if rt is not equal to this object. Otherwise, returns FALSE.

See Also

  • CMediaType Class


CMemAllocator Class

CMemAllocator Class Hierarchy

Implements an allocator that supports the IMemAllocator interface.

This class derives from CBaseAllocator. For more information about allocators, refer to the documentation for CBaseAllocator.

Requirements

Header: Declared in Amfilter.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pBuffer | Pointer to the memory block that contains the buffers.
Protected Methods |
Free | Placeholder method; called during a decommit operation.
ReallyFree | Releases the memory for the buffers.
Alloc | Allocates memory for the buffers.
Public Methods |
CMemAllocator | Constructor method.
~CMemAllocator | Destructor method.
CreateInstance | Creates a new instance of the CMemAllocator class.
IMemAllocator Methods |
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.


CMemAllocator::m_pBuffer

Pointer to the memory block that contains the buffers.

Syntax

LPBYTE m_pBuffer;

Remarks

Sample buffers are calculated as offsets from this pointer.

See Also

  • CMemAllocator Class


CMemAllocator::Alloc

The Alloc method allocates memory for the buffers.

Syntax

HRESULT Alloc(void);

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

This method is called by the CBaseAllocator::Commit method. It allocates a contiguous block of memory sufficient for the buffer requirements given in the CMemAllocator::SetProperties method.

See Also

  • CMemAllocator Class


CMemAllocator::CMemAllocator

Constructor method.

Syntax

CMemAllocator(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
);

Parameters

pName

Pointer to a string containing the name of the allocator.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

See Also

  • CMemAllocator Class


CMemAllocator::~CMemAllocator

Destructor method.

Syntax

~CMemAllocator(void);

Remarks

This method overrides the base-class destructor to call CBaseAllocator::Decommit and CMemAllocator::ReallyFree.

See Also

  • CMemAllocator Class


CMemAllocator::CreateInstance

The CreateInstance method creates a new instance of the CMemAllocator class.

Syntax

static CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

Return Value

Returns a pointer to a new CMemAllocator object, typed as a CUnknown object.

See Also

  • CMemAllocator Class


CMemAllocator::Free

The Free method is called during a decommit operation. This method implements the pure virtual CBaseAllocator::Free method, but does nothing. The buffer memory is not actually released until the CMemAllocator object is destroyed. The destructor method calls CMemAllocator::ReallyFree to release the memory.

Syntax

void Free(void);

See Also

  • CMemAllocator Class


CMemAllocator::ReallyFree

The ReallyFree method releases the memory for the buffers.

Syntax

void ReallyFree (void);

Remarks

The CMemAllocator class holds memory until the object is deleted.

See Also

  • CMemAllocator Class


CMemAllocator::SetProperties

The SetProperties method specifies the number of buffers to allocate and the size of each buffer.

Syntax

HRESULT SetProperties(
    ALLOCATOR_PROPERTIES *pRequest,
    ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.

pActual

Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method overrides the CBaseAllocator::SetProperties method.

The buffer alignment, specified by the cbAlign member of the ALLOCATOR_PROPERTIES structure, must be an even power of two.

See Also

  • CMemAllocator Class


CMsg Class

The CMsgThread class provides support for a worker thread to which requests can be posted asynchronously instead of sent directly. The CAMThread class provides a worker thread to which single requests can be sent. Only one client can make a request at a time, and the client blocks until the worker thread has completed the request. By contrast, the CMsgThread class provides a worker thread to which any number of requests can be posted. The requests (in the form of a CMsg object) are queued and executed in order, asynchronously. No reply or return value is received.

Data Members

dwFlags | Flag parameter to the request code.
lpParam | Data required by the worker thread as parameter or return values. This data should not be stack-based, as it will be referenced some time after completing the queuing operation.
pEvent | Event object that a worker thread can signal to indicate the completion of the operation.
uMsg | Request code that is defined by the client of the thread class and understood by the overridden worker thread function.

Member Functions

CMsg Constructs a CMsg object.


CMsg::CMsg

CMsg Class

Constructs a CMsg object.

Syntax

CMsg(
  UINT u,
  DWORD dw,
  LPVOID lp,
  CAMEvent *pEvent
);

Parameters

u

Request code, defined by the client of the thread class and understood by the overridden worker thread function.

dw

Flag parameter to the request code.

lp

Pointer to data required by the worker thread as parameter or return values. This data should not be stack-based, as it will be referenced some time after completing the queuing operation.

pEvent

Pointer to the event object that a worker thread can signal to indicate the completion of the operation.

Return Value

No return value.

Remarks

This member function contains a request for a CMsgThread worker thread to act on. All the parameters are passed to the worker thread function as parameters when this message gets processed. The meanings of the parameters are defined by the client function that calls the worker thread and the derived class that supplies the worker thread's execution function.


CMsgThread Class

The CMsgThread class is a worker-thread class that queues requests to the queuing thread for completion asynchronously. To use this class, derive your class from it and override the CMsgThread::ThreadMessageProc member function. The ThreadMessageProc member function carries out each request. Your client functions and the ThreadMessageProc member function must share a common definition of the parameters in the CMsg object.

A negotiated mechanism tells the worker thread to exit. Typically, this will be one value of the CMsg class's uMsg message code.

It is a good idea to send this message from the destructor of your derived class, and call the CMsgThread::WaitForThreadExit member function before completing the destruction of the derived class.

Protected Data Members

m_hSem | Indicates a handle used for signaling.
m_Lock | Protects access to lists.
m_lWaiting | Indicates waiting for a free thread.
m_ThreadQueue | Overrides the CMsgThread::GetThreadMsg member function and blocks on things other than this queue.

Member Functions

CMsgThread | Constructs a CMsgThread object.
CreateThread | Creates a thread.
GetThreadHandle | Retrieves the thread handle.
GetThreadID | Retrieves the identifier of the thread.
GetThreadPriority | Retrieves the current thread priority.
PutThreadMsg | Queues a request for execution by the worker thread.
ResumeThread | Continues the operation of the worker thread.
SetThreadPriority | Sets the priority of the thread to a new value.
SuspendThread | Suspends the operation of a running thread.
WaitForThreadExit | Blocks until the thread has exited after a call to the CMsgThread::SuspendThread member function.

Overridable Member Functions

GetThreadMsg | Retrieves a queued CMsg object containing a request.
OnThreadInit | Provides initialization on a thread.
ThreadMessageProc | Processes requests. This is a pure virtual member function.


CMsgThread::CMsgThread

Constructor method.

Syntax

CMsgThread(void);

Return Value

No return value.

Remarks

Constructing a message thread object does not automatically create the thread. You must call the CMsgThread::CreateThread member function to create the thread.

See Also

  • CMsgThread Class


CMsgThread::CreateThread

Creates a thread.

Syntax

BOOL CreateThread(void);

Return Value

Returns one of the following values.

Value | Description
TRUE | Thread was successfully created.
FALSE | Thread was not successfully created.

Remarks

The thread will loop, blocking until a request is queued (through the CMsgThread::PutThreadMsg member function) and then calling the CMsgThread::ThreadMessageProc member function with each message.

See Also

  • CMsgThread Class


CMsgThread::GetThreadHandle

Retrieves the handle to the thread in the CMsgThread object.

Syntax

HANDLE GetThreadHandle(void);

Return Value

Returns the thread handle.

Remarks

The thread handle can be passed to Microsoft® Win32® application programming interface (API) functions, such as WaitForMultipleObjects. The thread handle is signaled when the thread has exited.

See Also

  • CMsgThread Class


CMsgThread::GetThreadID

Retrieves the thread's identifier.

Syntax

DWORD GetThreadID(void);

Return Value

Returns the m_ThreadId private data member.

Remarks

This function returns the Microsoft Win32 identifier for the worker thread. You can call this member function on either the worker thread or a client thread.

See Also

  • CMsgThread Class


CMsgThread::GetThreadMsg

Retrieves a queued CMsg object containing a request.

Syntax

void virtual GetThreadMsg(
    CMsg *msg
);

Parameters

msg

Pointer to an allocated CMsg object.

Remarks

This member function is called from the worker thread's private ThreadProc function to retrieve the next member function. The msg parameter should point to an allocated CMsg object that will be filled with the parameters to the next request in the queue. If there are no queued requests, this member function blocks until the next request is queued (by a call to the CMsgThread::PutThreadMsg member function).

See Also

  • CMsgThread Class


CMsgThread::GetThreadPriority

Uses the Microsoft Win32 GetThreadPriority function to retrieve the priority of the current worker thread.

Syntax

int GetThreadPriority(void);

Return Value

Returns the thread priority as an integer.

See Also

  • CMsgThread Class


CMsgThread::OnThreadInit

Provides initialization on a thread.

Syntax

virtual void OnThreadInit(void);

Return Value

No return value.

Remarks

Override this function if you want to do your own specific initialization on thread startup.

See Also

  • CMsgThread Class


CMsgThread::PutThreadMsg

Queues a request for execution by the worker thread.

Syntax

void PutThreadMsg(
    UINT uMsg,
    DWORD dwMsgFlags,
    LPVOID lpMsgParam,
    CAMEvent *pEvent = NULL
);

Parameters

uMsg

Request code.

dwMsgFlags

Optional flags parameter.

lpMsgParam

Optional pointer to a data block containing additional parameters or return values. Must be statically or heap-allocated and not automatic.

pEvent

Optional pointer to an event object to be signaled upon completion.

Return Value

No return value.

Remarks

This member function queues a request for execution by the worker thread. The parameters of this member function will be queued (in a CMsg object) and passed to the CMsgThread::ThreadMessageProc member function of the worker thread. This member function returns immediately after queuing the request and does not wait for the thread to fulfill the request. The CMsgThread::ThreadMessageProc member function of the derived class defines the four parameters.

This member function uses a multithread safe list, so multiple calls to this member function from different threads can be made safely.

See Also

  • CMsgThread Class


CMsgThread::ResumeThread

Uses the Microsoft Win32 ResumeThread function to continue the operation of the worker thread after a previous call to the CMsgThread::SuspendThread member function.

Syntax

DWORD ResumeThread(void);

Return Value

If the member function succeeds, the return value is the previous suspend count of the thread. If the member function fails, the return value is 0xFFFFFFFF. To obtain extended error information, call the Microsoft Win32 GetLastError function.

See Also

  • CMsgThread Class


CMsgThread::SetThreadPriority

Uses the Microsoft Win32 SetThreadPriority function to set the priority of the thread to a new value.

Syntax

BOOL SetThreadPriority(
    int nPriority
);

Parameters

nPriority

Priority of the thread.

Return Value

Returns one of the following values.

Value | Description
TRUE | Priority was successfully set.
FALSE | Priority was not set.

Remarks

The client and the worker thread can call this member function.

See Also

  • CMsgThread Class


CMsgThread::SuspendThread

Uses the Microsoft Win32 SuspendThread function to suspend the operation of a running thread.

Syntax

DWORD SuspendThread(void);

Return Value

If the member function succeeds, the return value is the previous suspend count of the thread. If the member function fails, the return value is 0xFFFFFFFF. To obtain extended error information, call the Microsoft Win32 GetLastError function.

Remarks

The client thread calls this member function to suspend the operation of the worker thread. The worker thread remains suspended and will not execute until an additional call to the CMsgThread::ResumeThread member function is made.

See Also

  • CMsgThread Class


CMsgThread::ThreadMessageProc

Processes requests. This is a pure virtual member function.

Syntax

virtual LRESULT ThreadMessageProc(
    UINT uMsg,
    DWORD dwFlags,
    LPVOID lpParam,
    CAMEvent *pEvent
);

Parameters

uMsg

Request code.

dwFlags

Optional flag parameter to request.

lpParam

Optional pointer to extra data or a return data block.

pEvent

Optional pointer to an event object.

Return Value

Any nonzero return causes the thread to exit. Returns zero unless an exit request has been processed recently.

Remarks

This pure virtual function must be overridden in your derived class. It will be called once for each request queued by a call to the CMsgThread::PutThreadMsg member function.

The member function defines the four parameters. Typically, use the uMsg parameter to indicate the request, and the other three parameters will be optional additional parameters. The calling application can supply a pointer to a CAMEvent object in the pEvent parameter if your application requires it. You must set this event after processing the event by using an expression such as:

pEvent->SetEvent

One request code must be set aside to tell the worker thread to exit. Upon receiving this request, return 1 from this member function. Return 0 if you do not want the worker thread to exit.

See Also

  • CMsgThread Class


CMsgThread::WaitForThreadExit

Blocks until the thread exits.

Syntax

BOOL WaitForThreadExit(
    LPDWORD lpdwExitCode
);

Parameters

lpdwExitCode

Pointer to the exit code returned by the thread.

Return Value

Returns either TRUE or FALSE, the meaning of which is determined by the class supplying the overridden CMsgThread::ThreadMessageProc member function and the calling member function.

Remarks

Ensure that the worker thread has exited completely before completing the destruction of your derived class; otherwise, the thread might still execute after your dynamic-link library (DLL) has been unloaded from the address space of the process. Even if the only instruction left to exit is a single-return instruction, this would cause an exception. The only reliable way to ensure that the thread has exited is to signal the thread to exit (using a privately negotiated CMsg object sent to the CMsgThread::PutThreadMsg member function) and then call this member function. You should do this in the destructor for your derived class.

See Also

  • CMsgThread Class


COARefTime Class

COARefTime Class Hierarchy

The COARefTime class converts reference times between seconds and 100-nanosecond units.

This class converts between reference times that are compatible with Automation and reference times that are compatible with C/C++. Automation-compatible interfaces use double values to represent time in seconds. Other interfaces use 64-bit LONGLONG values to represent time in 100-nanosecond units. The following types are defined for these values:

typedef LONGLONG  REFERENCE_TIME;
typedef double    REFTIME;

Filters can use the COARefTime class to convert between the two formats. This class is derived from the CRefTime class.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
COARefTime | Constructor method.
Operators |
double | Converts the reference time to a double value.
REFERENCE_TIME | Retrieves the reference time as a REFERENCE_TIME value.
Operator = | Assigns a new reference time.
Operator == | Tests for equality between two reference times.
Operator != | Tests for inequality between two reference times.
Operator < | Tests if one reference time is less than another.
Operator > | Tests if one reference time is greater than another.
Operator <= | Tests if one reference time is less than or equal to another.
Operator >= | Tests if one reference time is greater than or equal to another.
Operator + | Adds two reference times.
Operator – | Subtracts one reference time from another.
Operator += | Adds two reference times, and sets this object to the result.
Operator –= | Subtracts one reference time from another, and sets this object to the result.
Operator * | Multiplies a reference time.
Operator / | Divides a reference time.


COARefTime::COARefTime

Constructor method.

Syntax

COARefTime(void);

COARefTime(
    CRefTime crt
);

COARefTime(
    REFERENCE_TIME t
);

COARefTime(
    double d
);

Parameters

crt

CRefTime object that specifies the reference time.

t

REFERENCE_TIME value that specifies the reference time in 100-nanosecond units.

d

double value that specifies the reference time in seconds.

Remarks

The reference time defaults to zero.

See Also

  • COARefTime Class


COARefTime::double

This operator converts the reference time to a double value.

Syntax

operator double();

Return Value

Returns the reference time in seconds.

See Also

  • COARefTime Class


COARefTime::REFERENCE_TIME

This operator retrieves the reference time as a REFERENCE_TIME value.

Syntax

operator REFERENCE_TIME();

Return Value

Returns the reference time in 100-nanosecond units.

See Also

  • COARefTime Class


COARefTime::Operator =

This operator assigns a new reference time.

Syntax

COARefTime& operator=(
    const double& rd
);

COARefTime& operator=(
    const REFERENCE_TIME& rt
);

Parameters

rd

Reference to a double value that specifies the new reference time in seconds.

rt

Reference to a REFERENCE_TIME value that specifies the new reference time in 100-nanosecond units.

Return Value

Returns a reference to the object.

See Also

  • COARefTime Class


COARefTime::Operator ==

This operator tests for equality between two reference times.

Syntax

BOOL operator==(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if the two objects are equal. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator !=

This operator tests for inequality between two reference times.

Syntax

BOOL operator!=(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if the two objects are not equal. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator <

This operator tests if one reference time is less than another.

Syntax

BOOL operator<(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is strictly less than rt. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator >

This operator tests if one reference time is greater than another.

Syntax

BOOL operator>(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is strictly greater than rt. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator >=

This operator tests if one reference time is less than or equal to another.

Syntax

BOOL operator>=(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is less than or equal to rt. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator <=

This operator tests if one reference time is greater than or equal to another.

Syntax

BOOL operator<=(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is greater than or equal to rt. Otherwise, returns FALSE.

See Also

  • COARefTime Class


COARefTime::Operator +

This operator adds two reference times.

Syntax

COARefTime operator+(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to add.

Return Value

Returns a new COARefTime object equal to the sum of the reference times.

See Also

  • COARefTime Class


COARefTime::Operator -

Microsoft DirectX 9.0

COARefTime::Operator –

This operator subtracts one reference time from another.

Syntax

COARefTime operator-(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to subtract.

Return Value

Returns a new COARefTime object equal to the difference of the reference times.

See Also

  • COARefTime Class


COARefTime::Operator +=

This operator adds two reference times, and sets this object to the result.

Syntax

COARefTime& operator+=(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to add.

Return Value

Returns a reference to the object.

See Also

  • COARefTime Class


COARefTime::Operator -=

Microsoft DirectX 9.0

COARefTime::Operator –=

This operator subtracts one reference time from another, and sets this object to the result.

Syntax

COARefTime& operator-=(
    const COARefTime& rt
);

Parameters

rt

Reference to the COARefTime object to subtract.

Return Value

Returns a reference to the object.

See Also

  • COARefTime Class


COARefTime::Operator *

This operator multiplies a reference time by a value.

Syntax

COARefTime operator*(
    LONG l
);

Parameters

l

Multiplier.

Return Value

Returns a new COARefTime object equal to the product of this object and l.

See Also

  • COARefTime Class


COARefTime::Operator /

This operator divides a reference time by a value.

Syntax

COARefTime operator/(
    LONG l
);

Parameters

l

Divisor.

Return Value

Returns a new COARefTime object equal to the quotient of this object and l.

See Also

  • COARefTime Class


COutputQueue Class

The COutputQueue class implements a queue to deliver media samples.

This class enables an output pin to deliver samples asynchronously. Samples are placed on a queue, and a worker thread delivers them to the input pin. The queue can also hold control messages that indicate a new segment, an end-of-stream notification, or a flush operation.

To use this class, create a COutputQueue object for every output pin on the filter. In the constructor method, specify the input pin connected to that output pin. Using this class, the output pin does not call methods directly on the input pin. Instead, it calls corresponding methods in COutputQueue, as shown in the following table.

Pin Method | COutputQueue Method
IPin::BeginFlush | BeginFlush
IPin::EndFlush | EndFlush
IPin::EndOfStream | EOS
IPin::NewSegment | NewSegment
IMemInputPin::Receive | Receive
IMemInputPin::ReceiveMultiple | ReceiveMultiple

Optionally, you can configure the COutputQueue object to deliver samples synchronously, without a worker thread. The object can also decide at run time whether to use a worker thread, based on the characteristics of the input pin. For more information, see COutputQueue::COutputQueue.

Requirements

Header: Declared in Outputq.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pPin | Pointer to the input pin's IPin interface.
m_pInputPin | Pointer to the input pin's IMemInputPin interface.
m_bBatchExact | Flag that specifies whether the object delivers samples in exact batches.
m_lBatchSize | Batch size.
m_List | Media sample queue.
m_hSem | Handle to a semaphore, used by the thread to wait for samples.
m_evFlushComplete | Event that signals when a flush operation has finished.
m_hThread | Handle to the worker thread.
m_ppSamples | Array of samples of size COutputQueue::m_lBatchSize.
m_nBatched | Number of samples currently batched and awaiting processing.
m_lWaiting | Flag that has a nonzero value when the thread is waiting for a sample.
m_bFlushing | Flag that specifies whether the object is performing a flush operation.
m_bTerminate | Flag that specifies whether the thread should terminate.
m_bSendAnyway | Flag to override batch processing.
m_hr | HRESULT value that indicates whether the object will accept samples.
m_hEventPop | Event that is signalled whenever the object removes a sample from the queue.
Protected Methods |
InitialThreadProc | Calls the COutputQueue::ThreadProc method when the thread is created.
ThreadProc | Retrieves samples from the queue and delivers them to the input pin.
IsQueued | Determines whether the object is using a worker thread to deliver samples.
QueueSample | Queues a media sample or control message.
IsSpecialSample | Determines whether queued data is a control message.
FreeSamples | Frees all pending samples.
NotifyThread | Notifies the thread that the queue contains data.
Public Methods |
COutputQueue | Constructor method.
~COutputQueue | Destructor method.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
EOS | Delivers an end-of-stream call to the input pin.
SendAnyway | Delivers any pending samples.
NewSegment | Delivers a new segment to the input pin.
Receive | Delivers a media sample to the input pin.
ReceiveMultiple | Delivers a batch of media samples to the input pin.
Reset | Resets the object so that it can receive more data.
IsIdle | Determines whether the object is waiting for data.
SetPopEvent | Specifies an event that is signalled whenever the object removes a sample from the queue.


COutputQueue::m_pPin

Pointer to the input pin's IPin interface.

Syntax

IPin * const m_pPin;

See Also

  • COutputQueue Class


COutputQueue::m_pInputPin

Pointer to the input pin's IMemInputPin interface.

Syntax

IMemInputPin *m_pInputPin;

See Also

  • COutputQueue Class


COutputQueue::m_bBatchExact

Flag that specifies whether the object delivers samples in exact batches.

Syntax

BOOL const m_bBatchExact;

Remarks

If the value is TRUE, the object waits until it has a complete batch of media samples before delivering any. Otherwise, it delivers samples as they arrive. The COutputQueue::m_lBatchSize member variable defines the batch size.

See Also

  • COutputQueue Class


COutputQueue::m_lBatchSize

Batch size.

Syntax

LONG const m_lBatchSize;

See Also

  • COutputQueue Class


COutputQueue::m_List

Media sample queue.

Syntax

typedef CGenericList<IMediaSample> CSampleList;
CSampleList *m_List;

Remarks

Pointer to a CGenericList class template, specialized to hold IMediaSample pointers.

See Also

  • COutputQueue Class


COutputQueue::m_hSem

Handle to a semaphore, used by the thread to wait for samples.

Syntax

HANDLE m_hSem;

See Also

  • COutputQueue Class


COutputQueue::m_evFlushComplete

Event that signals when a flush operation has finished.

Syntax

CAMEvent m_evFlushComplete;

See Also

  • COutputQueue Class


COutputQueue::m_hThread

Handle to the worker thread.

Syntax

HANDLE m_hThread;

See Also

  • COutputQueue Class


COutputQueue::m_ppSamples

Array of samples of size COutputQueue::m_lBatchSize.

Syntax

IMediaSample  **m_ppSamples;

Remarks

The worker thread pulls samples from the queue and places them in this array. It passes the array to the IMemInputPin::ReceiveMultiple method. If the object is not using a worker thread, the object places samples directly into this array. The COutputQueue::m_List member variable holds the queue.

See Also

  • COutputQueue Class


COutputQueue::m_nBatched

Number of samples currently batched and awaiting processing.

Syntax

LONG m_nBatched;

See Also

  • COutputQueue Class


COutputQueue::m_lWaiting

Flag that has a nonzero value when the thread is waiting for a sample.

Syntax

LONG m_lWaiting;

See Also

  • COutputQueue Class


COutputQueue::m_bFlushing

Flag that specifies whether the object is performing a flush operation. If TRUE, the object has started flushing.

Syntax

BOOL m_bFlushing;

See Also

  • COutputQueue Class


COutputQueue::m_bTerminate

Flag that specifies whether the thread should terminate. If TRUE, the thread terminates.

Syntax

BOOL m_bTerminate;

See Also

  • COutputQueue Class


COutputQueue::m_bSendAnyway

Flag to override batch processing. Setting this flag to TRUE overrides the COutputQueue::m_bBatchExact flag and delivers all pending samples.

Syntax

BOOL m_bSendAnyway;

See Also

  • COutputQueue Class


COutputQueue::m_hr

HRESULT value that indicates whether the object will accept samples. If the value is S_OK, the object will accept samples. Otherwise, it rejects samples.

Syntax

BOOL volatile m_hr;

Remarks

This member variable is used to coordinate activities across threads. If the downstream input pin rejects a sample, or if the object begins flushing, the value is set to S_FALSE or an error code. The object will not deliver any more samples until flushing is complete, or until the COutputQueue::Reset method is called.

See Also

  • COutputQueue Class


COutputQueue::m_hEventPop

Optional event that is signaled whenever the object removes a sample from the queue. The value is initially NULL. Call the COutputQueue::SetPopEvent method to specify an event handle.

Syntax

HANDLE m_hEventPop;

See Also

  • COutputQueue Class


COutputQueue::BeginFlush

The BeginFlush method begins a flush operation.

Syntax

void BeginFlush(void);

Remarks

This method sets the COutputQueue::m_bFlushing member variable to TRUE. If the object is using a thread, the thread calls the COutputQueue::FreeSamples method to free any pending samples. Otherwise, the object calls FreeSamples during the COutputQueue::EndFlush method. This method also sets the COutputQueue::m_hr member variable to S_FALSE, which causes the object to discard all new samples.

The object passes the flush notification downstream by calling the IPin::BeginFlush method on the input pin.

See Also

  • COutputQueue Class


COutputQueue::COutputQueue

Constructor method.

Syntax

COutputQueue(
    IPin *pInputPin,
    HRESULT *phr,
    BOOL bAuto = TRUE,
    BOOL bQueue = TRUE,
    LONG lBatchSize = 1,
    BOOL bBatchExact = FALSE,
    LONG lListSize = DEFAULTCACHE,
    DWORD dwPriority = THREAD_PRIORITY_NORMAL
);

Parameters

pInputPin

Pointer to the IPin interface of the input pin. The object will deliver samples to this pin.

phr

Pointer to an HRESULT return code. Set the value to S_OK before calling this method. On return, phr receives a value that indicates the success or failure of the method.

bAuto

Flag that specifies whether the object decides when to create a queue. If TRUE, the object creates a queue only if the input pin might block. If FALSE, the bQueue parameter specifies whether to create a queue.

bQueue

If bAuto is TRUE, this parameter is ignored. If bAuto is FALSE, this flag specifies whether to create a queue.

lBatchSize

Maximum number of samples to deliver in one batch.

bBatchExact

Flag that specifies whether to use exact batch sizes. If TRUE, the object waits for lBatchSize samples before delivering them to the input pin. If FALSE, the object delivers samples as it receives them.

lListSize

Cache size for the queue. The default value, DEFAULTCACHE, is a constant defined for the CBaseList class.

dwPriority

Priority of the thread that delivers samples.

Remarks

If bAuto is TRUE, the object calls the IMemInputPin::ReceiveCanBlock method on the downstream pin. If ReceiveCanBlock returns S_OK (meaning the pin might block on IMemInputPin::Receive calls), the object creates a thread for delivering samples. Otherwise, it does not create a thread.

If bAuto is FALSE, the value of bQueue determines whether to create a thread.

If the object creates a thread, it assigns the thread handle to the COutputQueue::m_hThread member variable. The thread procedure is COutputQueue::InitialThreadProc, and the thread parameter is a pointer to this. The object also creates a queue for holding samples, which is given by the COutputQueue::m_List member variable.

See Also

  • COutputQueue Class


COutputQueue::~COutputQueue

Destructor method.

Syntax

~COutputQueue(void);

See Also

  • COutputQueue Class


COutputQueue::EndFlush

The EndFlush method ends a flush operation.

Syntax

void EndFlush(void);

Remarks

If the object is using a thread, this method waits for the COutputQueue::m_evFlushComplete event. The thread signals this event after it frees any pending samples. If the object is not using a thread, this method calls the COutputQueue::FreeSamples method. Then the EndFlush method calls the IPin::EndFlush method on the input pin.

See Also

  • COutputQueue Class


COutputQueue::EOS

The EOS method delivers an end-of-stream call to the input pin.

Syntax

void EOS(void);

Remarks

If the object is using a thread, it queues an EOS_PACKET control message. The thread delivers any pending samples and calls the IPin::EndOfStream method on the input pin.

If the object is not using a thread, it calls the COutputQueue::SendAnyway method to deliver any pending samples. Then it calls IPin::EndOfStream on the input pin.

See Also

  • COutputQueue Class


COutputQueue::FreeSamples

The FreeSamples method frees all pending samples.

Syntax

void FreeSamples(void);

Remarks

This method removes any pending samples from the queue and from the sample array.

See Also

  • COutputQueue Class


COutputQueue::InitialThreadProc

The InitialThreadProc method calls the COutputQueue::ThreadProc method when the thread is created.

Syntax

static DWORD WINAPI InitialThreadProc(
    LPVOID pv
);

Parameters

pv

this pointer.

Return Value

Returns the value returned by the COutputQueue::ThreadProc method.

Remarks

This method is the thread procedure for the object's worker thread. The object's this pointer is the thread parameter. The method dereferences this to call ThreadProc.

See Also

  • COutputQueue Class


COutputQueue::IsIdle

The IsIdle method determines whether the object is waiting for data.

Syntax

BOOL IsIdle(void);

Return Value

Returns TRUE if the thread is waiting and the sample array is empty. Otherwise, returns FALSE.

See Also

  • COutputQueue Class


COutputQueue::IsQueued

The IsQueued method determines whether the object is using a worker thread to deliver samples.

Syntax

BOOL IsQueued(void);

Return Value

Returns TRUE if the object is using a worker thread, or FALSE otherwise.

See Also

  • COutputQueue Class


COutputQueue::IsSpecialSample

The IsSpecialSample method determines whether queued data is a control message.

Syntax

BOOL IsSpecialSample(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to an item in the queue.

Return Value

Returns TRUE if pSample is a control message, or FALSE otherwise.

Remarks

The COutputQueue::QueueSample method can receive control messages in addition to media samples. A control message is a defined constant (cast to a LONG_PTR type) that instructs the thread to perform an action. Control messages do not contain media data. For more information, see COutputQueue::QueueSample.

See Also

  • COutputQueue Class


COutputQueue::NewSegment

The NewSegment method delivers a new segment to the input pin.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart

Starting media position of the segment, in 100-nanosecond units.

tStop

End media position of the segment, in 100-nanosecond units.

dRate

Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns an HRESULT value.

Remarks

If the object is using a thread, it queues the following items, in order:

  • A NEW_SEGMENT control message.
  • The segment data.

The NEW_SEGMENT message notifies the thread that the next item on the queue will contain segment data. The segment data is bundled in a structure, declared as follows:

struct NewSegmentPacket {
    REFERENCE_TIME tStart;
    REFERENCE_TIME tStop;
    double dRate;
};

The thread calls the IPin::NewSegment method on the input pin, using the data given in the structure.

If the object is not using a thread, it calls the COutputQueue::SendAnyway method to deliver any pending samples. Then it calls IPin::NewSegment on the input pin.

See Also

  • COutputQueue Class


COutputQueue::NotifyThread

The NotifyThread method notifies the thread that the queue contains data.

Syntax

void NotifyThread(void);

Remarks

Hold the critical section before calling this method.

See Also

  • COutputQueue Class


COutputQueue::QueueSample

The QueueSample method queues a sample.

Syntax

void QueueSample(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Remarks

This method adds a sample to the tail of the queue. Hold the critical section before calling this method, and call it only when the object is using a thread to deliver samples. To determine if the object is using a thread, call the COutputQueue::IsQueued method.

This method can also be used to put control messages onto the queue. A control message is a defined constant (cast to a LONG_PTR type) that instructs the thread to perform some action. The COutputQueue class defines the control messages shown in the following table.

Message | Action
EOS_PACKET | Deliver an end-of-stream notification.
NEW_SEGMENT | Deliver a new segment.
RESET_PACKET | Reset the state of the queue.
SEND_PACKET | Send a partial batch of samples.

This is a protected method, which the COutputQueue class uses internally.

See Also

  • COutputQueue Class


COutputQueue::Receive

The Receive method delivers a media sample to the input pin.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | End-of-stream notification received before processing this sample.
S_OK | Success.

Remarks

This method calls the COutputQueue::ReceiveMultiple method.

See Also

  • COutputQueue Class


COutputQueue::ReceiveMultiple

The ReceiveMultiple method delivers a batch of media samples to the input pin.

Syntax

HRESULT ReceiveMultiple (
    IMediaSample **ppSamples,
    long nSamples,
    long *nSamplesProcessed
);

Parameters

ppSamples

Address of a pointer to an array of samples.

nSamples

Number of samples in the array.

nSamplesProcessed

Pointer to a variable that receives the number of samples delivered successfully.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | End-of-stream notification received before processing this sample.
S_OK | Success.

Remarks

If the object is using a thread, this method queues all of the samples passed in the array. Otherwise, the method calls the IMemInputPin::ReceiveMultiple method on the input pin.

See Also

  • COutputQueue Class


COutputQueue::Reset

The Reset method resets the object so that it can receive more data.

Syntax

void Reset(void);

Return Value

No return value.

Remarks

This method resets the COutputQueue::m_hr member variable to S_OK. The object can receive media samples again; for example, after a flush operation.

See Also

  • COutputQueue Class


COutputQueue::SendAnyway

The SendAnyway method delivers any pending samples.

Syntax

void SendAnyway(void);

Remarks

If the COutputQueue::m_bBatchExact member variable is TRUE, the object fills the COutputQueue::m_ppSamples array before it delivers a batch of samples. Call this method to deliver a partial batch. For example, the COutputQueue::EOS method calls SendAnyway to serialize end-of-stream messages.

See Also

  • COutputQueue Class


COutputQueue::SetPopEvent

The SetPopEvent method specifies an event that is signalled whenever the object removes a sample from the queue.

Syntax

void COutputQueue::SetPopEvent(
    HANDLE hEvent
);

Parameters

hEvent

Handle to an event created by the caller.

See Also

  • COutputQueue Class


COutputQueue::ThreadProc

The ThreadProc method retrieves samples from the queue and delivers them to the input pin.

Syntax

DWORD ThreadProc(void);

Return Value

Returns zero.

Remarks

The COutputQueue::InitialThreadProc method calls this method, which implements the main thread loop. Within the loop, the method performs the following steps:

  1. Retrieves a sample for the queue.
  2. If the sample is a control message, the thread executes the control action. Otherwise, it places the sample into the COutputQueue::m_ppSamples array.
  3. When the array is full (or if COutputQueue::m_bBatchExact is FALSE), the thread calls the IMemInputPin::ReceiveMultiple method to deliver the samples.
  4. If no samples are queued, the thread waits on the COutputQueue::m_hSem semaphore.

The thread terminates when the COutputQueue::m_bTerminate member variable becomes TRUE.

See Also

  • COutputQueue Class


CPersistStream Class

CPersistStream Class Hierarchy

CPersistStream is the base class for persistent properties of filters (that is, filter properties in saved graphs).

The simplest way to use CPersistStream is to:

  1. Arrange for your filter to inherit this class.
  2. Implement WriteToStream and ReadFromStream in your class. These will override the functions here, which do nothing but act as placeholders.
  3. Change your NonDelegatingQueryInterface to handle IPersistStream.
  4. Implement SizeMax to return an upper bound on the number of bytes of data you save.

    If you save Unicode™ data, remember that a WCHAR is 2 bytes.

  5. When your data changes, call SetDirty.

Version Numbers

At some point you might decide to alter or extend the format of your data. You will then wish you had a version number in all the old saved streams so you can tell, when you read them, whether they represent the old or new form. To assist you, this class writes and reads a version number. When it writes, it calls GetSoftwareVersion to inquire as to the version of the software being used at the moment. (In effect, this is a version number of the data layout in the file.) It writes this as the first thing in the data. If you want to change the version, implement (override) GetSoftwareVersion. It reads the version number from the file into mPS_dwFileVersion before calling ReadFromStream, so in ReadFromStream you can check mPS_dwFileVersion to see if you are reading an old version file. Usually you should accept files whose version is no newer than the software version that is reading them.

Protected Data Members

mPS_dwFileVersion | Version number of the file.
mPS_fDirty | Data for this stream must be saved.

Member Functions

CPersistStream | Constructs a CPersistStream object.
SetDirty | Indicates that the object must be saved to the stream.

Overridable Member Functions

GetClassID | Retrieves the class identifier of this stream.
GetSoftwareVersion | Retrieves the version number for this file format.
ReadFromStream | Reads the filter's data from the stream.
SizeMax | Retrieves the number of bytes needed for data (not including version number).
WriteToStream | Writes the filter's data to the stream.

CPersistStream implements IPersistStream. For more implementation information, see the COM Reference in the Microsoft Platform SDK.

Implemented IPersistStream Methods

GetSizeMax | Retrieves the number of bytes needed for data (including version number).
IsDirty | Checks if the object must be saved.
Load | Loads the data from the stream into memory.
Save | Saves the data from memory to the stream.


CPersistStream::CPersistStream

Constructor method.

Syntax

CPersistStream(
    IUnknown *pUnk,
    HRESULT *phr
);

Parameters

pUnk

Pointer to the IUnknown interface of the delegating object.

phr

Pointer to the general COM return value. This value is changed only if this function fails.

Return Value

No return value.

See Also

  • CPersistStream Class


CPersistStream::GetClassID

Retrieves the class identifier for this filter.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID

Pointer to a CLSID structure. Copy your class ID to here.

Return Value

Returns an HRESULT value.

See Also

  • CPersistStream Class


CPersistStream::GetSizeMax

Retrieves the maximum byte size needed for the current stream, including the version number.

Syntax

HRESULT GetSizeMax(
    ULARGE_INTEGER *pcbSize
);

Parameters

pcbSize

Pointer to the size in bytes needed to save this stream, including the version number.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::GetSizeMax method.

See Also

  • CPersistStream Class


CPersistStream::GetSoftwareVersion

Retrieves the software version for this stream.

Syntax

virtual DWORD GetSoftwareVersion(void);

Return Value

Returns a DWORD containing the version number. Each time the format of the stream is changed, this function should be altered to return a larger number than before.

See Also

  • CPersistStream Class


CPersistStream::IsDirty

Indicates whether the object has changed since it was last saved to its current stream.

Syntax

HRESULT IsDirty(void);

Return Value

Returns S_OK if the filter needs saving and S_FALSE if it does not need saving.

Remarks

This member function implements the IPersistStream::IsDirty method.

See Also

  • CPersistStream Class


CPersistStream::Load

Loads the filter's data from a given stream.

Syntax

HRESULT Load(
    LPSTREAM pStm
);

Parameters

pStm

Pointer to the stream from which to be loaded.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::Load method.

See Also

  • CPersistStream Class


CPersistStream::ReadFromStream

Reads the filter's data from the given stream.

Syntax

virtual HRESULT ReadFromStream(
    IStream *pStream
);

Parameters

pStream

Pointer to an IStream interface from which data is to be read.

Return Value

Returns S_OK. The derived class should return a valid HRESULT value.

Remarks

The default version reads nothing; it can be overridden to read data specific to your class.

See Also

  • CPersistStream Class


CPersistStream::Save

Saves the filter's data to the given stream.

Syntax

HRESULT Save(
    LPSTREAM pStm,
    BOOL fClearDirty
);

Parameters

pStm

Pointer to the stream to which data is to be saved.

fClearDirty

Flag that indicates whether to reset the current stream's dirty flag; TRUE means to reset it. (When the method is called as part of a Save operation, the value is typically TRUE; when called as part of a Save As operation, the value is typically FALSE.)

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::Save method. It calls WriteInt with the software version, calls CPersistStream::WriteToStream with the stream in pStm, and resets mPS_fDirty.

See Also

  • CPersistStream Class


CPersistStream::SetDirty

Changes the dirty flag for the current stream.

Syntax

HRESULT SetDirty(
    BOOL fDirty
);

Parameters

fDirty

New dirty flag for this stream. TRUE means that the data has not been saved.

Return Value

Returns an HRESULT value.

See Also

  • CPersistStream Class


CPersistStream::SizeMax

Retrieves the maximum byte size needed for the current stream, not including the version number.

Syntax

virtual int SizeMax(void);

Return Value

Returns the number of bytes needed for data, not including the version number.

Remarks

The default version returns zero; it should be overridden to provide some other appropriate value.

See Also

  • CPersistStream Class


CPersistStream::WriteToStream

Writes the filter's data to the given stream.

Syntax

virtual HRESULT WriteToStream(
    IStream *pStream
);

Parameters

pStream

Pointer to an IStream interface that specifies the filter data's destination stream.

Return Value

Returns S_OK. The derived class should return a valid HRESULT value.

Remarks

The default version writes nothing; it can be overridden to write data specific to your class.

See Also

  • CPersistStream Class


CPosPassThru Class

CPosPassThru Base Class Hierarchy

The CPosPassThru class handles seek commands for transform filters, by passing them upstream to the next filter.

When an application seeks the filter graph, the Filter Graph Manager gives the seek command to the renderer filters. The command is passed upstream, through each filter's output pin, until it reaches a filter that can execute the command (if any). For details, see Seeking. The CPosPassThru class passes all seek commands to the output pin on the upstream filter, as shown in the following diagram.

The CPosPassThru class sends seek commands upstream.

Although this class is provided in the base class library, DirectShow also provides the same class in Quartz.dll. Using the Quartz.dll version can reduce the code size in your filter somewhat, because the class is loaded at run-time from the DLL. To use that version, call the CreatePosPassThru function.

In your output pin's NonDelegatingQueryInterface method, delegate to the CPosPassThru object whenever the requested interface is IMediaSeeking or IMediaPosition, as shown in the following code:

// The following member variables are assumed:
IPin *m_pInput;    // Pointer to the input pin on your filter.
IUnknown *m_pPos;  // Pointer to the CPosPassThru object.

STDMETHODIMP CMyPin::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
    HRESULT hr
    if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking)
    {
        if (m_pPos == NULL)
        {
            // We have not created the CPosPassThru object yet. Do so now.
            hr = CreatePosPassThru(GetOwner(), FALSE, m_pInput, &m_pPos);
            if (FAILED(hr)) return hr;
        }
        return m_pPos->QueryInterface(riid, ppv);
    }
    else
    {
         // Other interfaces (not shown).
    }
}

~CMyPin::CMyPin()
{
    // Release the CPosPassThruObject.
    if (m_pPos != NULL) m_pPos->Release();
}

Except where noted, all IMediaPosition and IMediaSeeking methods in this class call the corresponding method on the connected pin and return the result.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CPosPassThru | Constructor method.
ForceRefresh | Obsolete.
GetMediaTime | Retrieves the time stamps on the current sample. Virtual.
IMediaPosition Methods |
get_Duration | Retrieves the duration of the stream.
put_CurrentPosition | Sets the current position, relative to the total duration of the stream.
get_StopTime | Retrieves the time at which the playback will stop, relative to the duration of the stream.
put_StopTime | Sets the time at which the playback will stop, relative to the duration of the stream.
get_PrerollTime | Retrieves the amount of data that will be queued before the start position.
put_PrerollTime | Sets the amount of data that will be queued before the start position.
get_Rate | Retrieves the playback rate.
put_Rate | Sets the playback rate.
get_CurrentPosition | Retrieves the current position, relative to the total duration of the stream.
CanSeekForward | Determines whether the stream can be seeked backward.
CanSeekBackward | Determines whether the stream can be seeked forward.
IMediaSeeking Methods |
CheckCapabilities | Queries whether a stream has specified seeking capabilities.
ConvertTimeFormat | Converts from one time format to another.
GetAvailable | Retrieves the range of times in which seeking is efficient.
GetCapabilities | Retrieves all the seeking capabilities of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
GetDuration | Retrieves the duration of the stream.
GetPositions | Retrieves the current position and the stop position, relative to the total duration of the stream.
GetPreroll | Retrieves the amount of data that will be queued before the start position.
GetRate | Retrieves the playback rate.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetTimeFormat | Retrieves the current time format.
IsFormatSupported | Determines whether a specified time format is supported.
IsUsingTimeFormat | Determines whether a specified time format is the format currently in use.
QueryPreferredFormat | Retrieves the preferred time format for the stream.
SetPositions | Sets the current position and the stop position.
SetRate | Sets the playback rate.
SetTimeFormat | Sets the time format.
Helper Functions |
CreatePosPassThru | Creates a CPosPassThru or CRendererPosPassThru object.


CPosPassThru::CanSeekBackward

The CanSeekBackward method determines whether the stream can be seeked backward. This method implements the IMediaPosition::CanSeekBackward method.

Syntax

HRESULT CanSeekBackward(
    LONG *pCanSeekBackward
);

Parameters

pCanSeekBackward

Pointer to a variable that receives the value OATRUE if the filter can seek backward, or OAFALSE otherwise.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::CanSeekForward

The CanSeekForward method determines whether the stream can be seeked forward. This method implements the IMediaPosition::CanSeekForward method.

Syntax

HRESULT CanSeekForward(
    LONG *pCanSeekForward
);

Parameters

pCanSeekForward

Pointer to a variable that receives the value OATRUE if the filter can seek forward, or OAFALSE otherwise.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::CheckCapabilities

The CheckCapabilities method queries whether a stream has specified seeking capabilities. This method implements the IMediaSeeking::CheckCapabilities method.

Syntax

HRESULT CheckCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities

Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes. When the method returns, the value indicates which of those attributes are available.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::ConvertTimeFormat

The ConvertTimeFormat method converts from one time format to another. This method implements the IMediaSeeking::ConvertTimeFormat method.

Syntax

HRESULT ConvertTimeFormat(
    LONGLONG *pTarget,
    const GUID *pTargetFormat,
    LONGLONG Source,
    const GUID *pSourceFormat
);

Parameters

pTarget

Pointer to a variable that receives the converted time.

pTargetFormat

Pointer to the time format GUID of the target format. If NULL, the current format is used.

Source

Time value to be converted.

pSourceFormat

Pointer to the time format GUID of the format to convert. If NULL, the current format is used.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CPosPassThru::CPosPassThru

Constructor method.

Syntax

CPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    IPin *pPin
);

Parameters

pName

Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Ignored.

pPin

Pointer to the IPin interface of the filter's input pin.


CPosPassThru::ForceRefresh

The ForceRefresh method is obsolete.

Syntax

HRESULT ForceRefresh(void);

Return Value

Returns S_OK.

Remarks

Originally this class was designed to cache pointers to the connected pin's IMediaPosition and IMediaSeeking interfaces. The ForceRefresh method released those interfaces.

As currently implemented, this class does not cache those interfaces. For compatibility, the ForceRefresh method is still included, but it returns S_OK without doing anything.

See Also

  • CPosPassThru Class


CPosPassThru::GetAvailable

The GetAvailable method retrieves the range of times in which seeking is efficient. This method implements the IMediaSeeking::GetAvailable method.

Syntax

HRESULT GetAvailable(
    LONGLONG *pEarliest,
    LONGLONG *pLatest
);

Parameters

pEarliest

Pointer to a variable that receives the earliest time for efficient seeking.

pLatest

Pointer to a variable that receives the latest time for efficient seeking.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetCapabilities

The GetCapabilities method retrieves all the seeking capabilities of the stream. This method implements the IMediaSeeking::GetCapabilities method.

Syntax

HRESULT GetCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities

Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetCurrentPosition

The GetCurrentPosition method retrieves the current position, relative to the total duration of the stream. This method implements the IMediaSeeking::GetCurrentPosition method.

Syntax

HRESULT GetCurrentPosition(
    LONGLONG *pCurrent
);

Parameters

pCurrent

Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method calls the CPosPassThru::GetMediaTime method to retrieve the most recent position. If GetMediaTime fails, the method calls IMediaSeeking::GetCurrentPosition on the connected pin.

The GetMediaTime method fails by default in the base class. If your filter caches the current position, override GetMediaTime to return the cached value.

See Also

  • CPosPassThru Class


CPosPassThru::get_CurrentPosition

The get_CurrentPosition method retrieves the current position, relative to the total duration of the stream. This method implements the IMediaPosition::get_CurrentPosition method.

Syntax

HRESULT get_CurrentPosition(
    REFTIME *pllTime
);

Parameters

pllTime

Pointer to a variable that receives the current position, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetDuration

The GetDuration method retrieves the duration of the stream. This method implements the IMediaSeeking::GetDuration method.

Syntax

HRESULT GetDuration(
    LONGLONG *pDuration
);

Parameters

pDuration

Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::get_Duration

The get_Duration method retrieves the duration of the stream. This method implements the IMediaPosition::get_Duration method.

Syntax

HRESULT get_Duration(
    REFTIME *plength
);

Parameters

plength

Pointer to a variable that receives the total stream length, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetMediaTime

The GetMediaTime method retrieves the time stamps on the current sample.

Syntax

virtual HRESULT GetMediaTime(
    LONGLONG *pStartTime,
    LONGLONG *pEndTime
);

Parameters

pStartTime

Pointer to a variable that receives the start time, in units of the current time format.

pEndTime

Pointer to a variable that receives the end time, in units of the current time format.

Return Value

Returns E_FAIL.

Remarks

Override this method if your filter caches the time stamps on the samples it receives.

See Also

  • CPosPassThru Class


CPosPassThru::GetPositions

The GetPositions method retrieves the current position and the stop position, relative to the total duration of the stream. This method implements the IMediaSeeking::GetPositions method.

Syntax

HRESULT GetPositions(
    LONGLONG *pCurrent,
    LONGLONG *pStop
);

Parameters

pCurrent

Pointer to a variable that receives the current position, in units of the current time format.

pStop

Pointer to a variable that receives the stop position, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetPreroll

The GetPreroll method retrieves the amount of data that will be queued before the start position. This method implements the IMediaSeeking::GetPreroll method.

Syntax

HRESULT GetPreroll(
    LONGLONG *pllPreroll
);

Parameters

pllPreroll

Pointer to a variable that receives the preroll time, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::get_PrerollTime

The get_PrerollTime method retrieves the amount of data that will be queued before the start position. This method implements the IMediaPosition::get_PrerollTime method.

Syntax

HRESULT get_PrerollTime(
    REFTIME *pllTime
);

Parameters

pllTime

Pointer to a variable that receives the preroll time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetRate

The GetRate method retrieves the playback rate. This method implements the IMediaSeeking::GetRate method.

Syntax

HRESULT GetRate(
    double *pdRate
);

Parameters

pdRate

Pointer to a variable that receives the playback rate.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::get_Rate

The get_Rate method retrieves the playback rate. This method implements the IMediaPosition::get_Rate method.

Syntax

HRESULT get_Rate(
    double *pdRate
);

Parameters

pdRate

Pointer to a variable that receives the playback rate.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetStopPosition

The GetStopPosition method retrieves the time at which the playback will stop, relative to the duration of the stream. This method implements the IMediaSeeking::GetStopPosition method.

Syntax

HRESULT GetStopPosition(
    LONGLONG *pStop
);

Parameters

pStop

Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::get_StopTime

The get_StopTime method retrieves the time at which the playback will stop, relative to the duration of the stream. This method implements the IMediaPosition::get_StopTime method.

Syntax

HRESULT get_StopTime(
    REFTIME *pllTime
);

Parameters

pllTime

Pointer to a variable that receives the stop time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::GetTimeFormat

The GetTimeFormat method retrieves the current time format. This method implements the IMediaSeeking::GetTimeFormat method.

Syntax

HRESULT GetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a variable that receives a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CPosPassThru::IsFormatSupported

The IsFormatSupported method determines whether a specified time format is supported. This method implements the IMediaSeeking::IsFormatSupported method.

Syntax

HRESULT IsFormatSupported(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CPosPassThru::IsUsingTimeFormat

The IsUsingTimeFormat method determines whether a specified time format is the format currently in use. This method implements the IMediaSeeking::IsUsingTimeFormat method.

Syntax

HRESULT IsUsingTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CPosPassThru::put_CurrentPosition

The put_CurrentPosition method sets the current position, relative to the total duration of the stream. This method implements the IMediaPosition::put_CurrentPosition method.

Syntax

HRESULT put_CurrentPosition(
    REFTIME llTime
);

Parameters

llTime

New position, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::put_PrerollTime

The put_PrerollTime method sets the amount of data that will be queued before the start position. This method implements the IMediaPosition::put_PrerollTime method.

Syntax

HRESULT put_PrerollTime(
    REFTIME llTime
);

Parameters

llTime

Preroll time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::put_Rate

The put_Rate method sets the playback rate. This method implements the IMediaPosition::put_Rate method.

Syntax

HRESULT put_Rate(
    double dRate
);

Parameters

dRate

Playback rate. Must not be zero.

Return Value

Returns E_INVALIDARG if dRate is zero. Otherwise, returns the HRESULT value from the connected pin.

Remarks

Negative rates indicate reverse play. Not all media will support reverse play.

See Also

  • CPosPassThru Class


CPosPassThru::put_StopTime

The put_StopTime method sets the time at which the playback will stop, relative to the duration of the stream. This method implements the IMediaPosition::put_StopTime method.

Syntax

HRESULT put_StopTime(
    REFTIME llTime
);

Parameters

llTime

Stop time as a double value, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::QueryPreferredFormat

The QueryPreferredFormat method retrieves the preferred time format for the stream. This method implements the IMediaSeeking::QueryPreferredFormat method.

Syntax

HRESULT QueryPreferredFormat(
    GUID *pFormat
);

Parameters

pFormat

Pointer to a variable that receives a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CPosPassThru::SetPositions

The SetPositions method sets the current position and the stop position. This method implements the IMediaSeeking::SetPositions method.

Syntax

HRESULT SetPositions(
    LONGLONG *pCurrent,
    DWORD dwCurrentFlags,
    LONGLONG *pStop,
    DWORD dwStopFlags
);

Parameters

pCurrent

Pointer to a variable that specifies the current position, in units of the current time format.

dwCurrentFlags

Bitwise combination of flags. See IMediaSeeking::SetPositions for more information.

pStop

Pointer to a variable that specifies the stop time, in units of the current time format.

dwStopFlags

Bitwise combination of flags. See IMediaSeeking::SetPositions for more information.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::SetRate

The SetRate method sets the playback rate. This method implements the IMediaSeeking::SetRate method.

Syntax

HRESULT SetRate(
    double dRate
);

Parameters

dRate

Playback rate. Must not be zero.

Return Value

Returns E_INVALIDARG if dRate is zero. Otherwise, returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class


CPosPassThru::SetTimeFormat

The SetTimeFormat method sets the time format. This method implements the IMediaSeeking::SetTimeFormat method.

Syntax

HRESULT SetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

See Also

  • CPosPassThru Class
  • Time Format GUIDs


CreatePosPassThru Function

The CreatePosPassThru function creates a CPosPassThru object or CRendererPosPassThru object.

Syntax

STDAPI CreatePosPassThru(
    LPUNKNOWN pAgg,
    BOOL bRenderer,
    IPin *pPin,
    IUnknown **ppPassThru
);

Parameters

pAgg

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

bRenderer

Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise. If the value is TRUE, this method creates an instance of the CRendererPosPassThru class. If the value is false, the method creates an instance of the CPosPassThru class.

pPin

Pointer to the IPin interface on the filter's input pin.

ppPassThru

Address of a variable that receives a pointer to the object's IUnknown interface.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method uses the ISeekingPassThru interface to create the object. The object is loaded dynamically from Quartz.dll.

If the function succeeds, the returned IUnknown interface has an outstanding reference count. The caller must release the interface.

See Also

  • CPosPassThru Class


CPullPin Class

CPullPin Class Hierarchy

The CPullPin class provides support for input pins that pull data through the IAsyncReader interface. Use this class if you are implementing a filter that uses the pull model to request data from the upstream filter. For more information, see Data Flow in the Filter Graph and Pull Model.

This class does not derive from CBasePin or implement the IPin interface, and some of the method names clash with IPin, so it is best used as a helper object inside your pin. To use this class, do the following:

  1. Derive a helper class from CPullPin, and derive an input pin class from CBasePin. Declare an instance of the CPullPin object as a member variable of the pin class.
  2. Override the CBasePin::CheckConnect method to call CPullPin::Connect. This method queries the other pin for IAsyncReader.
  3. Override the CBasePin::BreakConnect method to call CPullPin::Disconnect.
  4. Override the CBasePin::Active method to call CPullPin::Active. This method starts up a worker thread that pulls samples from the upstream filter. When the pins connect, you can specify whether you want the worker thread to make asynchronous or synchronous read requests.
  5. Override the CBasePin::Inactive method to call CPullPin::Inactive. This method shuts down the worker thread.
  6. Implement the pure virtual CPullPin::Receive method to process incoming samples and deliver them downstream.
  7. To set the stop and start positions, or to seek the stream, call the CPullPin::Seek method. This method pauses the worker thread and flushes the filter graph.
  8. Implement the pure virtual CPullPin::EndOfStream, CPullPin::BeginFlush, and CPullPin::EndFlush methods, as described in the remarks for those methods.
  9. Implement the pure virtual CPullPin::OnError method to handle streaming errors.

Requirements

Header: Include Pullpin.h and Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Member Variables | Description
m_pAlloc | Pointer to the IMemAllocator interface of the memory allocator.
Public Methods |
Active | Creates a worker thread that pulls data from the output pin.
AlignDown | Truncates a value to a specified alignment boundary.
AlignUp | Rounds a value up to a specified alignment boundary.
Connect | Completes a connection to the output pin.
CPullPin | Constructor method.
~CPullPin | Destructor method. Virtual.
DecideAllocator | Negotiates an allocator with the output pin. Virtual.
Disconnect | Beaks the connection with the output pin.
Duration | Retrieves the duration of the stream.
GetReader | Returns a pointer to the output pin's IAsyncReader interface.
Inactive | Shuts down the worker thread that pulls data from the output pin.
Seek | Sets the start and stop positions of the stream.
Pure Virtual Methods |
BeginFlush | Informs the owning filter to flush the downstream filters.
EndFlush | Informs the owning filter to end a flush operation.
EndOfStream | Called after the object delivers the last sample.
OnError | Called if an error occurs during streaming.
Receive | Called when the object receives a media sample from the output pin.


CPullPin::m_pAlloc

The m_pAlloc member variable is a pointer to the IMemAllocator interface of the memory allocator.

Syntax

IMemAllocator *m_pAlloc

Remarks

The CPullPin::DecideAllocator method sets this member variable.

See Also

  • CPullPin Class


CPullPin::Active

The Active method creates a worker thread that pulls data from the output pin. This method also commits the allocator.

Syntax

HRESULT Active(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_UNEXPECTED | The pin connection was not established correctly.
E_FAIL | Could not create the thread, or the thread already exists.

Remarks

Call this method when the owning filter becomes active. (If your input pin derives from CBasePin, override the CBasePin::Active method.)

Before calling this method, call the CPullPin::Connect method to establish the connection with the output pin.

See Also

  • CPullPin Class


CPullPin::AlignDown

The AlignDown method truncates a value to a specified alignment boundary.

Syntax

LONGLONG AlignDown(
    LONGLONG ll,
    LONG lAlign
);

Parameters

ll

Specifies the number to align.

lAlign

Specifies the alignment boundary.

Return Value

Returns the aligned result.

See Also

  • CPullPin Class


CPullPin::AlignUp

The AlignUp method rounds a value up to a specified alignment boundary.

Syntax

LONGLONG AlignUp(
    LONGLONG ll,
    LONG lAlign
);

Parameters

ll

Specifies the number to align.

lAlign

Specifies the alignment boundary.

Return Values

Returns the aligned result.

See Also

  • CPullPin Class


CPullPin::BeginFlush

The BeginFlush method informs the owning filter to flush the downstream filters. The derived class must implement this method.

Syntax

virtual HRESULT BeginFlush(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

The CPullPin::Seek method calls this method. Implement this method to call the IPin::BeginFlush method on each downstream input pin that receives data from this object. If your filter's output pin(s) derive from CBaseOutputPin, call the CBaseOutputPin::DeliverBeginFlush method.

This design enables the filter to seek the stream simply by calling Seek on the CPullPin object.

See Also

  • CPullPin Class


CPullPin::Connect

The Connect method completes a connection to the output pin.

Syntax

HRESULT Connect(
    IUnknown *pUnk,
    IMemAllocator *pAlloc,
    BOOL bSync
);

Parameters

pUnk

Pointer to the IUnknown interface of the output pin.

pAlloc

Pointer to the IMemAllocator interface of the input pin's preferred allocator, or NULL.

bSync

Boolean value that specifies whether to use synchronous reads. If TRUE, the pin performs synchronous read operations on the output pin. If FALSE, the pin makes asynchronous read requests.

Return Values

Returns an HRESULT. Possible values include the following.

Return code | Description
S_OK | Success.
VFW_E_ALREADY_CONNECTED | The input pin is already connected.
E_NOINTERFACE | The output pin does not expose IAsyncReader.

Remarks

Call this method during the input pin's connection process. If the method fails, the pin should fail the connection.

This method queries the output pin for the IAsyncReader interface. If successful, it calls CPullPin::DecideAllocator to negotiate the allocator for the connection. If your input pin has a preferred allocator, specify it in the pAlloc parameter; the DecideAllocator method passes this pointer to the output pin's IAsyncReader::RequestAllocator method. Otherwise, set pAlloc to NULL.

If the value of bSync is TRUE, the CPullPin object makes synchronous read requests, by calling the output pin's IAsyncReader::SyncReadAligned. Otherwise, it calls the IAsyncReader::Request method to make overlapping read requests.

See Also

  • CPullPin Class


CPullPin::CPullPin

Constructor method.

Syntax

CPullPin(void);

Parameters

This method takes no parameters.

See Also

  • CPullPin Class


CPullPin::~CPullPin

Destructor method.

Syntax

virtual ~CPullPin(void);

Parameters

This method takes no parameters.

See Also

  • CPullPin Class


CPullPin::DecideAllocator

The DecideAllocator method negotiates an allocator with the output pin.

Syntax

virtual HRESULT DecideAllocator(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pAlloc

Pointer to the IMemAllocator interface of the input pin's preferred allocator, or NULL.

pProps

Pointer to an optional ALLOCATOR_PROPERTIES structure that contains the input pin's buffer requirements.

Return Values

Returns S_OK if successful, or an error code otherwise.

Remarks

This method calls the IAsyncReader::RequestAllocator method to negotiate an allocator. It passes the pAlloc parameter directly to the RequestAllocator method. It passes the pProps parameter to RequestAllocator if pProps is non-NULL; otherwise, it creates an ALLOCATOR_PROPERTIES structure with a default request of three 64K buffers.

See Also

  • CPullPin Class
  • CPullPin::Connect


CPullPin::Disconnect

The Disconnect method breaks the connection with the output pin.

Syntax

HRESULT Disconnect(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK.

Remarks

This method breaks any connection made in the CPullPin::Connect method. Call this method inside your IPin::Disconnect method. (If your pin derives from CBasePin, override CBasePin::BreakConnect to call this method.)

See Also

  • CPullPin Class


CPullPin::Duration

The Duration method retrieves the duration of the stream.

Syntax

HRESULT Duration(
    REFERENCE_TIME *ptDuration
);

Parameters

ptDuration

Pointer to a variable that receives the duration, in bytes multiplied by 10,000,000.

Return Values

Returns S_OK.

Remarks

The duration is indeterminate until the CPullPin::Connect method is called.

See Also

  • CPullPin Class


CPullPin::EndFlush

The EndFlush method informs the owning filter to end a flush operation. The derived class must implement this method.

Syntax

virtual HRESULT EndFlush(void) PURE;

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

The CPullPin::Seek method calls this method. Implement this method to call the IPin::EndFlush method on each downstream input pin that receives data from this object. If your filter's output pin(s) derive from CBaseOutputPin, call the CBaseOutputPin::DeliverEndFlush method.

This design enables the filter to seek the stream simply by calling Seek on the CPullPin object.

See Also

  • CPullPin Class


CPullPin::EndOfStream

The EndOfStream method is called after the object delivers the last sample. The derived class must implement this method.

Syntax

virtual HRESULT EndOfStream(void) PURE;

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Remarks

Use this method to call IPin::EndOfStream on each downstream input pin that receives data from this object. If your filter's output pin(s) derive from CBaseOutputPin, call the CBaseOutputPin::DeliverEndOfStream method.

See Also

  • CPullPin Class


CPullPin::GetReader

The GetReader method returns a pointer to the output pin's IAsyncReader interface.

Syntax

IAsyncReader* GetReader(void);

Parameters

This method takes no parameters.

Return Values

Returns a pointer to the IAsyncReader interface.

Remarks

The returned interface has an outstanding reference count. The caller must release the interface.

The method does not check the value of the interface pointer before calling AddRef, so do not call this until you have successfully called the CPullPin::Connect method. Otherwise, the interface pointer might be NULL and calling AddRef will throw an exception.

See Also

  • CPullPin Class


CPullPin::Inactive

The Inactive method shuts down the worker thread that pulls data from the output pin. This method also decommits the allocator.

Syntax

HRESULT Inactive(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK.

Remarks

Call this method when the owning filter becomes inactive. (If your input pin derives from CBasePin, override the CBasePin::Inactive method.)

See Also

  • CPullPin Class


CPullPin::OnError

The OnError method is called if an error occurs during streaming. The derived class must implement this method.

Syntax

virtual void OnError(
    HRESULT hr
) PURE;

Parameters

hr

Specifies the HRESULT value returned by the method that failed.

Return Values

This method does not return a value.

Remarks

The object calls this method whenever an error occurs that halts the data-pulling thread. The filter can use this method to recover from streaming errors gracefully. In most cases, the error is returned from the upstream filter, so the upstream filter is responsible for reporting it to the Filter Graph Manager. If the error occurs inside the CPullPin::Receive method, your filter should send an EC_ERRORABORT event. (See IMediaEventSink::Notify.)

See Also

  • CPullPin Class


CPullPin::Receive

The Receive method is called when the object receives a media sample from the output pin. The derived class must implement this method.

Syntax

virtual HRESULT Receive(
    IMediaSample *pSample
) PURE;

Parameters

pSample

Pointer to the IMediaSample interface of the media sample.

Return Values

Returns an HRESULT value. Returning a value other than S_OK will stop the data-pulling thread.

Remarks

This method is called whenever a new sample arrives from the output pin. Write this method in the same manner as the IMemInputPin::Receive method.

The time stamps on the sample specify the byte offsets, relative to the original start position that was specified in CPullPin::Seek method.

The start position is rounded down to the nearest alignment boundary, and the stop position is rounded up to the nearest alignment boundary. Also, if the stop position exceeds the total duration, the duration is used instead.

All time stamps are given as a byte offset multiplied by 10,000,000, defined as the constant UNITS. Thus, notionally one second is one byte. To find the actual byte offsets, call IMediaSample::GetTime and divide the results by UNITS.

See Also

  • CPullPin Class


CPullPin::Seek

The Seek method sets the start and stop positions of the stream.

Syntax

HRESULT Seek(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop
);

Parameters

tStart

Specifies the start position, in bytes multiplied by 10,000,000.

tStop

Specifies the stop position, in bytes multiplied by 10,000,000.

Return Values

Returns S_OK if the method succeeds, or an error code otherwise.

Remarks

If the worker thread is running, the method pauses the thread, flushes the filter graph, and resumes the thread. The thread begins pulling data from the new start position. Otherwise, the new position values become effective whenever the thread is started.

Positions are relative to the start of the original source. Multiply the desired byte offsets by the constant UNITS, which is defined in the base class library as 10,000,000.

When the pin first connects, the stop and start positions default to the beginning and end of the stream.

See Also

  • CPullPin Class


CQueue Class

The CQueue class template implements a simple, statically sized queue.

The class constructor specifies the size of the queue. Use the CQueue::PutQueueObject to put an item on the queue, and the CQueue::GetQueueObject method to dequeues an item. If the queue is full, the PutQueueObject method blocks until an item is dequeued. If the queue is empty, the GetQueueObject blocks until an item is queued. The template parameter specifies the type of item. For example:

CQueue<int> number_queue;
number_queue.PutQueueObject(7);

The class uses two semaphores to control queuing operations, a "get" semaphore and a "put" semaphore. The GetQueueObject method waits on the "get" semaphore (using the WaitForSingleObject function) and releases the "put" semaphore (using the ReleaseSemaphore function). The PutQueueObject method waits on the "put" semaphore and releases the "get" semaphore. The class uses a critical section to serialize queuing operations among multiple threads.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CQueue | Constructor method.
~CQueue | Destructor method.
GetQueueObject | Retrieves the next item from the queue.
PutQueueObject | Puts an item onto the queue.


CQueue::CQueue

Constructor method.

Syntax

CQueue(
    int n
);

CQueue(void);

Parameters

n

Size of the queue to create.

Remarks

If created with no parameters, the size of the queue is set to DEFAULT_QUEUESIZE.

See Also

  • CQueue Class


CQueue::~CQueue

Destructor method.

Syntax

~CQueue(void);

See Also

  • CQueue Class


CQueue::GetQueueObject

Retrieves the next item from the queue.

Syntax

T GetQueueObject(void);

Return Value

Returns an object of type T (the template type).

Remarks

This method blocks until an item is available on the queue.

See Also

  • CQueue Class


CQueue::PutQueueObject

Puts an item onto the queue.

Syntax

void PutQueueObject(
    T object
);

Parameters

object

Object of type T (the template type).

Remarks

This method blocks until there is space in the queue for the item.

See Also

  • CQueue Class


CRefTime Class

CRefTime Class Hierarchy

The CRefTime class is a helper class for managing reference times.

A reference time is a unit of time represented in 100-nanosecond units. This class shares the same data layout as the REFERENCE_TIME data type, but adds some methods and operators that provide comparison, conversion, and arithmetic functions. For more information about reference times, see Time and Clocks in DirectShow.

There is a potential pitfall with using this class. If you apply the += operator with a CRefTime object as the left operand and a variable of type LONG as the right operand, the compiler will implicitly coerce the right operand into a CRefTime object. This coercion uses the CRefTime constructor that converts milliseconds into REFERENCE_TIME units; as a result, the right operand is multiplied by 10,000:

CRefTime rt;   // rt.m_time is 0.
LONG val = 20;
rt += val;    // Coerce val to CRefTime, rt.m_time is now 200,000.

However, the same thing does not happen using the + operator:

CRefTime rt;   // rt.m_time is 0.
LONG val = 20;
rt = rt + val; // CRefTime, rt.m_time is 20.

Requirements

Header: Declared in Reftime.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Member Variables |
m_time | Specifies the REFERENCE_TIME value.
Public Methods |
CRefTime | Constructor method.
GetUnits | Retrieves the reference time in 100-nanosecond units.
Millisecs | Converts the reference time to milliseconds.
Operators |
operator REFERENCE_TIME() | Casts the object to a REFERENCE_TIME data type.
operator = | Assigns a new reference time.
operator += | Adds two reference times.
operator –= | Subtracts one reference time from another.


CRefTime::m_time

Specifies the REFERENCE_TIME value.

Syntax

REFERENCE_TIME m_time;

See Also

CRefTime Class


CRefTime::CRefTime

Constructor method.

Syntax

CRefTime(void);

CRefTime(
    LONG msecs
);

CRefTime(
    REFERENCE_TIME rt
);

Parameters

msecs

Time in milliseconds.

rt

Time in 100-nanosecond units.

Remarks

The reference time defaults to zero.

See Also

CRefTime Class


CRefTime::GetUnits

The GetUnits method retrieves the reference time in 100-nanosecond units.

Syntax

LONGLONG GetUnits(void);

Return Value

Returns the value of CRefTime::m_time.

See Also

CRefTime Class


CRefTime::Millisecs

The Millisecs method converts the reference time to milliseconds.

Syntax

LONG Millisecs(void);

Return Value

Returns the reference time in milliseconds.

See Also

CRefTime Class


CRefTime::operator REFERENCE_TIME()

The REFERENCE_TIME() operator casts the object to a REFERENCE_TIME data type.

Syntax

operator REFERENCE_TIME() const;

Return Value

Returns the value of CRefTime::m_time.

Remarks

The following example shows how to use this cast operator:

CRefTime cRT(1000);
REFERENCE_TIME rt = (REFERENCE_TIME)cRT;

See Also

CRefTime Class


CRefTime::operator =

The = operator assigns a new reference time.

Syntax

CRefTime& operator=(
    const CRefTime& rt
);

CRefTime& operator=(
    const LONGLONG ll
);

Parameters

rt

Reference to a CRefTime object that specifies the new reference time.

ll

New reference time, in 100-nanosecond units.

Return Value

Returns a reference to the object.

See Also

CRefTime Class


CRefTime::operator +=

The += operator adds two reference times.

Syntax

CRefTime& operator+=(
    const CRefTime& rt
);

Parameters

rt

Reference to a CRefTime object.

Return Value

Returns a reference to the object.

See Also

CRefTime Class


CRefTime::operator -=

Microsoft DirectX 9.0

CRefTime::operator –=

The -= operator subtracts one reference time from another.

Syntax

CRefTime& operator-=(
    const CRefTime& rt
);

Parameters

rt

Reference to a CRefTime object.

Return Value

Returns a reference to the object.

See Also

CRefTime Class


CRenderedInputPin Class

CRenderedInputPin Class Hierarchy

The CRenderedInputPin class is a base class for implementing an input pin on a renderer. This class is designed for renderer filters that do not derive from the CBaseRenderer class. (Filters that derive from CBaseRenderer should use the CRendererInputPin class for the input pin.)

To use this class, you must do at least the following:

  • Declare a new pin class that inherits CRenderedInputPin.
  • In your pin class, declare a critical section object to hold the streaming lock. You can use the CCritSec class for this purpose. For more information, see Threads and Critical Sections.
  • Override CRenderedInputPin::EndOfStream to hold the streaming lock.
  • Implement the IMemInputPin::Receive, CBasePin::CheckMediaType, and CBasePin::GetMediaType methods.
  • In your filter, implement CBaseFilter::GetPin to return an instance of your pin class.

You can use this class in a renderer that has more than one input pin. This class inherits the CBaseInputPin class.

Requirements

Header: Declared in Amextra.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables | Description
m_bAtEndOfStream | Indicates whether the end of the stream was reached.
m_bCompleteNotified | Indicates whether the pin has sent an EC_COMPLETE event to the Filter Graph Manager.
Public Methods |
Active | Notifies the pin that the filter is now active.
CRenderedInputPin | Constructor method.
Run | Notifies the pin that the filter is now running.
IPin Methods |
EndFlush | Ends a flush operation.
EndOfStream | Notifies the pin that no additional data is expected until the filter receives a new run command.


CRenderedInputPin::m_bAtEndOfStream

The m_bAtEndOfStream member variable is a Boolean flag indicating whether the end of the stream was reached.

Syntax

BOOL m_bAtEndOfStream;

See Also

  • CRenderedInputPin Class


CRenderedInputPin::m_bCompleteNotified

The m_bCompleteNotified member variable is a Boolean flag indicating whether the pin has sent an EC_COMPLETE event to the Filter Graph Manager.

Syntax

BOOL m_bCompleteNotified;

See Also

  • CRenderedInputPin Class


CRenderedInputPin::Active

The Active method notifies the pin that the filter is now active. This method overrides the CBasePin::Active method.

Syntax

HRESULT Active(void);

Return Value

Returns S_OK if successful, or an error code otherwise.

See Also

  • CRenderedInputPin Class


CRenderedInputPin::CRenderedInputPin

Constructor method.

Syntax

CRenderedInputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject Class.

pFilter

Pointer to the filter that created this pin.

pLock

Pointer to a CCritSec lock, used to serialize state changes. This can be the same critical section as the filter lock, CBaseFilter::m_pLock.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

pName

Wide-character string containing the pin name (also used as the pin identifier).

See Also

  • CRenderedInputPin Class


CRenderedInputPin::EndFlush

The EndFlush method ends a flush operation. This method implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK if successful, or an error code otherwise.

Remarks

This method clears any pending EC_COMPLETE events.

See Also

  • CRenderedInputPin Class


CRenderedInputPin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected, until a new run command is issued to the filter. This method implements the IPin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns S_OK if successful, or an error code otherwise.

Remarks

If the filter is running, this method sends an EC_COMPLETE event to the Filter Graph Manager. Otherwise, is sets a flag so that the EC_COMPLETE event is sent when the filter next runs. Flushing the filter clears the flag.

You should override this method to hold the pin's streaming lock:

class CMyInputPin : public CRenderedInputPin
{
private:
    CCritSec * const m_pReceiveLock; // Streaming lock.
public:
    STDMETHODIMP EndOfStream(void);

    /* (Remainder of the class declaration not shown.) */
};

STDMETHODIMP CMyInputPin::EndOfStream(void)
{
    CAutoLock lock(m_pReceiveLock);
    return CRenderedInputPin::EndOfStream();
}

Also, if the filter processes Receive calls asynchronously, the pin should wait to send the EC_COMPLETE event until the filter has processed all pending samples.

See Also

  • CRenderedInputPin Class


CRenderedInputPin::Run

The Run method notifies the pin that the filter is now running. This method overrides the CBasePin::Run method.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart

The start time that was passed to the filter's IMediaFilter::Run method.

Return Value

Returns S_OK.

See Also

  • CRenderedInputPin Class


CRendererInputPin Class

CRendererInput Pin Class Hierarchy

The CBaseRendererInputPin class implements an input pin for the CBaseRenderer class. Except where noted, the methods in this class delegate to corresponding methods on the CBaseRenderer class.

Requirements

Header: Declared in Renbase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pRenderer | Pointer to the filter.
Public Methods |
CRendererInputPin | Constructor method.
BreakConnect | Adds customized code upon breaking a connection.
CompleteConnect | Completes the connection.
CheckMediaType | Determines if the pin can support a specific media type.
Active | Switches the pin to the active (paused or running) mode.
Inactive | Switches the pin to an inactive state and releases the memory of the allocator.
SetMediaType | Sets the media type of the pin.
Allocator | Retrieves a pointer to the default memory allocator.
IPin Methods |
QueryId | Retrieves an identifier for the pin.
EndOfStream | Informs the pin that no additional data is expected until a new run command is issued.
BeginFlush | Informs the pin to begin a flush operation.
EndFlush | Informs the pin to end a flush operation.
IMemInputPin Methods |
Receive | Retrieves the next block of data from the stream.


CRendererInputPin::m_pRenderer

The m_pRenderer member variable is a pointer to the filter.

Syntax

CBaseRenderer *m_pRenderer;

See Also

  • CRendererInputPin Class


CRendererInputPin::Active

The Active method notifies the pin that the filter is now active. This method overrides the CBasePin::Active method.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::Allocator

The Allocator method retrieves a pointer to the memory allocator.

Syntax

IMemAllocator* Allocator(void) const;

Return Value

Returns a pointer to the allocator's IMemAllocator interface, or NULL.

Remarks

This method returns the CBaseInputPin::m_pAllocator member variable. The method does not increment the reference count on the interface. This method is strictly an accessor method.

See Also

  • CRendererInputPin Class


CRendererInputPin::BeginFlush

The BeginFlush method begins a flush operation. This method overrides the CBaseInputPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::BreakConnect

The BreakConnect method releases the pin from a connection. This method overrides the CBaseInputPin::BreakConnect method.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type. This method overrides the CBasePin::CheckMediaType method.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a media type object that contains the proposed media type.

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::CompleteConnect

The CompleteConnect method completes a connection to an output pin. This method overrides the CBasePin::CompleteConnect method.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the output pin's IPin interface

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::CRendererInputPin

The CRendererInputPin method is a constructor method.

Syntax

CRendererInputPin(
    CBaseRenderer *pRenderer,
    HRESULT *phr,
    LPCWSTR Name
);

Parameters

pRenderer

Pointer to the CBaseRenderer object that implements the filter.

phr

Pointer to a variable that receives an HRESULT value.

Name

Pointer to a wide-character string containing the pin identifier.

See Also

  • CRendererInputPin Class


CRendererInputPin::EndFlush

The EndFlush method ends a flush operation. This method overrides the CBaseInputPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected. This method overrides the CBasePin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::Inactive

The Inactive method notifies the pin that the filter is no longer active. This method overrides the CBaseInputPin::Inactive method.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::QueryId

The QueryId method retrieves the pin identifier. This method overrides the CBasePin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id

Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This method allocates the wide-character string "In" and assigns it to the Id parameter. The caller must free the allocated memory, using the CoTaskMemFree function.

See Also

  • CRendererInputPin Class


CRendererInputPin::Receive

The Receive method receives the next media sample in the stream. This method overrides the CBaseInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererInputPin::SetMediaType

The SetMediaType method sets the media type for the connection. This method overrides the CBasePin::SetMediaType method.

Syntax

HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value.

See Also

  • CRendererInputPin Class


CRendererPosPassThru Class

CRendererPosPassThru Class Hierarchy

The CRendererPosPassThru class handles seek commands for renderer filters, by passing them upstream to the next filter.

This class derives from the CPosPassThru class. It adds support for caching the time stamps from samples as they arrive. Use this class in the same way as the CPosPassThru class. Refer to the CPosPassThru documentation for details.

The renderer filter must update the CRendererPosPassThru object's cached time stamps, as follows:

  • For each sample the filter receives, call the CRendererPosPassThru::RegisterMediaTime method.
  • When the filter is stopped or receives an EndFlush call, call the CRendererPosPassThru::ResetMediaTime method.
  • When the filter receives an end-of-stream notification, call the CRendererPosPassThru::EOS method.

For an example of how to use this class, refer to the CBaseRenderer source code.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CRendererPosPassThru | Constructor method.
GetMediaTime | Retrieves the time stamps on the current sample.
RegisterMediaTime | Caches the time stamps from the current sample.
ResetMediaTime | Resets the cached time stamps to zero.
EOS | Updates the cached time stamps after an end-of-stream notification.


CRendererPosPassThru::CRendererPosPassThru

Constructor method.

Syntax

CRendererPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    IPin *pPin
);

Parameters

pName

Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Ignored.

pPin

Pointer to the IPin interface of the filter's input pin.

See Also

CRendererPosPassThru Class


CRendererPosPassThru::EOS

The EOS method updates the cached time stamps after an end-of-stream notification.

Syntax

HRESULT EOS(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
E_FAIL | Failure. Possibly the filter is not streaming.

Remarks

The filter should call this method when it receives an end-of-stream notification (IPin::EndOfStream). The method sets both cached time stamps equal to the stop position, ensuring that the IMediaSeeking::GetCurrentPosition method returns the correct values at the end of the stream.

See Also

CRendererPosPassThru Class


CRendererPosPassThru::GetMediaTime

The GetMediaTime method retrieves the time stamps on the current sample.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pStartTime,
    LONGLONG *pEndTime
);

Parameters

pStartTime

Pointer to a variable that receives the start time, in units of the current time format.

pEndTime

Pointer to a variable that receives the end time, in units of the current time format. Can be NULL.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
E_INVALIDARG | Conversion to this format is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method overrides the CPosPassThru::GetMediaTime method. The time-stamp values are converted to the current time format by calling the CPosPassThru::ConvertTimeFormat method.

See Also

CRendererPosPassThru Class


CRendererPosPassThru::RegisterMediaTime

The RegisterMediaTime method caches the time stamps from the current sample.

Syntax

HRESULT RegisterMediaTime(
    IMediaSample *pMediaSample
);

HRESULT RegisterMediaTime(
    LONGLONG StartTime,
    LONGLONG EndTime
);

Parameters

pMediaSample

Pointer to the IMediaSample interface of the sample.

StartTime

Sample start time, in 100-nanosecond units.

EndTime

Sample end time, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | The sample is not time-stamped.

Remarks

This method stores the time stamps from the current sample. The CRendererPosPassThru::GetMediaTime method retrieves the same values.

The filter should call this method for each sample that it receives. The method is overloaded to accept either a pointer to the sample, or the time stamp values themselves.

See Also

CRendererPosPassThru Class


CRendererPosPassThru::ResetMediaTime

The ResetMediaTime method resets the cached time stamps to zero.

Syntax

HRESULT ResetMediaTime(void);

Return Value

Returns S_OK.

Remarks

The filter should call this method whenever the time stamps cached by the CRendererPosPassThru::RegisterMediaTime method become invalid. Specifically, it should call this method in response to the IPin::EndFlush and IMediaFilter::Stop methods.

After this method is called, the CRendererPosPassThru::GetMediaTime method returns zero for the start and end times.

See Also

CRendererPosPassThru Class


CSeekingPassThru Class

The CSeekingPassThru class is a helper object that creates CPosPassThru and CRendererPosPassThru objects.

The CPosPassThru and CRendererPosPassThru classes are helper objects that pass seeking commands upstream, so the CSeekingPassThru class is a helper object for creating helper objects.

It is not necessary to use this class directly. Instead, use the CreatePosPassThru function, which handles all of the details of using this class. It has the further advantage of loading the object from Quartz.dll, which reduces the code size of your filter somewhat. For more information, see CPosPassThru.

The CSeekingPassThru class exposes the ISeekingPassThru interface. The ISeekingPassThru::Init method initializes the object. After the object is initialized, the filter can query it for the IMediaSeeking and IMediaPosition interfaces.

Requirements

Header: Declared in Seekpt.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Public Methods |
CSeekingPassThru | Constructor method.
~CSeekingPassThru | Destructor method.
CreateInstance | Creates an instance of the object.
ISeekingPassThru Methods |
Init | Initializes the object.


CSeekingPassThru::CSeekingPassThru

Constructor method.

Syntax

CPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
);

Parameters

pName

String containing the name of the object. See CBaseObject for more information.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Ignored.

See Also

  • CSeekingPassThru Class


CSeekingPassThru::~CSeekingPassThru

Destructor method.

Syntax

~CPosPassThru(void);

See Also

  • CSeekingPassThru Class


CSeekingPassThru::CreateInstance

The CreateInstance method creates an instance of the object. This method supports creation of the object through a class factory. For more information, see CFactoryTemplate.

Syntax

static CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Ignored.

Return Value

Returns a pointer to a new CSeekingPassThru object.

See Also

  • CSeekingPassThru Class


CSeekingPassThru::Init

The Init method initializes the object.

Syntax

HRESULT Init(
    BOOL bSupportRendering,
    IPin *pPin
);

Parameters

bSupportRendering

[in] Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise.

pPin

Pointer to the IPin interface on the filter's input pin.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_FAIL | Object was already initialized.
E_OUTOFMEMORY | Not enough memory to create the object.

Remarks

If the value of bSupportRendering is TRUE, this method creates an instance of the CRendererPosPassThru class. Otherwise, it creates an instance of the CPosPassThru class.

See Also

  • CSeekingPassThru Class


CSource Class

CSource Class Hierarchy

The CSource class is a base class for implementing source filters. A filter derived from CSource contains one or more output pins derived from the CSourceStream class. Each output pin creates a worker thread that pushes media samples downstream.

To implement an output pin, do the following:

  • Derive a class from CSourceStream.
  • Override the CSourceStream::GetMediaType method and possibly the CSourceStream::CheckMediaType method, which validate media types for the pin.
  • Implement the CBaseOutputPin::DecideBufferSize method, which returns the pin's buffer requirements.
  • Implement the CSourceStream::FillBuffer method, which fills a media sample buffer with data.

To implement the filter, do the following:

  • Derive a class from CSource.
  • In the constructor, create one or more output pins derived from CSourceStream. The pins automatically add themselves to the filter in their constructor methods, and remove themselves in their destructor methods.

To synchronize the filter state among multiple threads, call the CSource::pStateLock method. This method returns a pointer to the filter-state critical section. Use the CAutoLock class to hold the critical section. From a pin, you can access pStateLock from the pin's CBasePin::m_pFilter member variable, as follows:

CAutoLock lock(m_pFilter->pStateLock());

Note The CSource class is designed to support the push model for data flow. This class is not recommended for creating file-reader filters. File readers should support the pull model, through the IAsyncReader interface. For more information, see Data Flow for Filter Developers.

Requirements

Header: Declared in Source.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_iPins | Number of pins on the filter.
m_paStreams | Array of pins.
m_cStateLock | Critical section object that protects the filter state.
Public Methods |
CSource | Constructor method.
~CSource | Destructor method.
GetPinCount | Retrieves the number of pins on the filter.
GetPin | Retrieves a pin.
pStateLock | Retrieves a pointer to the filter's critical section object.
AddPin | Adds a new output pin to the filter.
RemovePin | Removes a specified pin from the filter.
FindPinNumber | Retrieves the number of a specified pin on the filter.
IBaseFilter Methods |
FindPin | Retrieves the pin with the specified identifier.


CSource::m_iPins

Number of pins on the filter.

Syntax

int m_iPins;

See Also

  • CSource Class


CSource::m_paStreams

Array of pins belonging to this filter.

Syntax

CSourceStream **m_paStreams;

See Also

  • CSource Class


CSource::m_cStateLock

Critical section object that protects the filter state. The CSource::pStateLock helper method returns a pointer to this member variable.

Syntax

CCritSec m_cStateLock;

See Also

  • CSource Class


CSource::AddPin

The AddPin method adds a new output pin to the filter.

Syntax

HRESULT AddPin(
    CSourceStream *pStream
);

Parameters

pStream

Pointer to the CSourceStream object that implements the pin.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

The constructor method calls this method, to add the output pin to the filter.

See Also

  • CSource Class


CSource::CSource

Constructor method.

Syntax

CSource(
    TCHAR *pName,
    LPUNKNOWN lpunk,
    CLSID clsid
);

Parameters

pName

Pointer to a string containing the name of the object. For more information, see CBaseObject.

lpunk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

clsid

Class identifier of the filter.

See Also

  • CSource Class


CSource::~CSource

Destructor method.

Syntax

~CSource(void);

See Also

  • CSource Class


CSource::FindPin

The FindPin method retrieves the pin with the specified identifier. This method implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id

Pointer to a null-terminated string that identifies the pin.

ppPin

Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

The first pin is always named "1"; the second pin is named "2"; and so forth. For more information, see CSourceStream::QueryId.

See Also

  • CSource Class


CSource::FindPinNumber

The FindPinNumber method retrieves the number of a specified pin on the filter.

Syntax

int FindPinNumber(
    IPin *iPin
);

Parameters

iPin

Pointer to the pin's IPin interface.

Return Value

Returns the pin number, or –1 if the pin is not found on this filter. The first pin is numbered zero.

See Also

  • CSource Class


CSource::GetPin

The GetPin method retrieves a pin. This method implements the pure virtual CBaseFilter::GetPin method.

Syntax

CBasePin *GetPin(
    int n
);

Parameters

n

Number of the specified pin.

Return Value

Returns the pointer to the CBasePin object that implements the pin, or NULL if the index is out of range.

See Also

  • CSource Class


CSource::GetPinCount

The GetPinCount method retrieves the number of pins on the filter. This method implements the pure virtual CBaseFilter::GetPinCount method.

Syntax

int GetPinCount(void);

Return Value

Returns the number of pins on this filter.

See Also

  • CSource Class


CSource::pStateLock

The pStateLock method retrieves a pointer to the filter's critical section object.

Syntax

CCritSec* pStateLock(void);

Return Value

Returns a pointer to the CSource::m_cStateLock member variable.

See Also

  • CSource Class


CSource::RemovePin

The RemovePin method removes a specified pin from the filter. The method does not delete the pin.

Syntax

HRESULT RemovePin(
    CSourceStream *pStream
);

Parameters

pStream

Pointer to the CSourceStream object that implements the pin.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
S_FALSE | The filter does not contain this pin.

Remarks

The destructor method calls this method, to remove the output pin from the filter.

See Also

  • CSource Class


CSourcePosition Class

CSourcePosition is an abstract class for implementing the IMediaPosition interface on a source filter.

This class is obsolete. If your source filter is seekable, it should expose the IMediaSeeking interface instead of IMediaPosition. You can use the CSourceSeeking base class for this purpose.


CSourceSeeking Class

CSourceSeeking Class Hierarchy

The CSourceSeeking class is an abstract class for implementing seeking in source filters with one output pin.

This class supports the IMediaSeeking interface. It provides default implementations for all of the IMediaSeeking methods. Protected member variables store the start time, stop time, and current rate. By default, the only time format supported by the class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units). See Remarks for more information.

Requirements

Header: Declared in Ctlutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_rtDuration | Duration of the stream.
m_rtStart | Start time.
m_rtStop | Stop time.
m_dRateSeeking | Playback rate.
m_dwSeekingCaps | Seeking capabilities.
m_pLock | Pointer to a critical section object for locking.
Protected Methods |
CSourceSeeking | Constructor method.
Pure Virtual Methods |
ChangeRate | Called when the playback rate changes.
ChangeStart | Called when the start position changes.
ChangeStop | Called when the stop position changes.
IMediaSeeking Methods |
IsFormatSupported | Determines whether a specified time format is supported.
QueryPreferredFormat | Retrieves the object's preferred time format.
SetTimeFormat | Sets the time format.
IsUsingTimeFormat | Determines whether a specified time format is the format currently in use.
GetTimeFormat | Retrieves the current time format.
GetDuration | Retrieves the duration of the stream.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
GetCapabilities | Retrieves all the seeking capabilities of the stream.
CheckCapabilities | Queries whether the stream has specified seeking capabilities.
ConvertTimeFormat | Converts from one time format to another.
SetPositions | Sets the current position and the stop position.
GetPositions | Retrieves the current position and the stop position.
GetAvailable | Retrieves the range of times in which seeking is efficient.
SetRate | Sets the playback rate.
GetRate | Retrieves the playback rate.
GetPreroll | Retrieves the preroll time.

Remarks

Whenever the start position, stop position, or playback rate changes, the CSourceSeeking object calls a corresponding pure virtual method:

  • Start position: CSourceSeeking::ChangeStart
  • Stop position: CSourceSeeking::ChangeStop
  • Playback rate: CSourceSeeking::ChangeRate

The derived class must implement these methods. After any seek operation, a filter must do the following:

  1. Call the IPin::BeginFlush method on the downstream input pin.
  2. Halt the worker thread that is delivering data.
  3. Call the IPin::EndFlush method on the input pin.
  4. Restart the worker thread.
  5. Call the IPin::NewSegment method on the input pin.
  6. Set the discontinuity property on the first sample. Call the IMediaSample::SetDiscontinuity method.

The call to BeginFlush frees the worker thread, if the thread is blocked waiting to deliver a sample.

In step 2, make sure that the thread has stopped sending data. Depending on the implementation, you might need to wait for the thread to exit, or for the thread to signal a response of some kind. If your filter uses the CSourceStream class, the CSourceStream::Stop method blocks until the worker thread replies.

Ideally, the new segment (step 5) should be delivered from the worker thread. It can also be done by the CSourceSeeking object, as long as the filter serializes it with the samples.

The following example shows a possible implementation. It assumes that the source filter's output pin is derived from CSourceSeeking and CSourceStream. This example defines a helper method, UpdateFromSeek, that performs steps 1–4. The CSourceStream::OnThreadStartPlay method is overridden to send the new segment, and to set a flag indicating the discontinuity. The worker thread picks up this flag and calls the IMediaSample::SetDiscontinuity method:

void CMyStream::UpdateFromSeek()
{
    if (ThreadExists())
    {
        DeliverBeginFlush();
        Stop();
        DeliverEndFlush();
        Run();
    }
}

HRESULT CMyStream::OnThreadStartPlay()
{
    m_bDiscontinuity = TRUE;
    return DeliverNewSegment(m_rtStart, m_rtStop, m_dRateSeeking);
}

Supporting Additional Time Formats

By default, this class supports seeking only in units of reference time (TIME_FORMAT_MEDIA_TIME). To support additional time formats, override the IMediaSeeking methods that deal with time formats:

  • IMediaSeeking::GetTimeFormat
  • IMediaSeeking::IsFormatSupported
  • IMediaSeeking::IsUsingTimeFormat
  • IMediaSeeking::QueryPreferredFormat
  • IMediaSeeking::SetTimeFormat

In addition, override the remaining IMediaSeeking methods to perform the necessary conversions between time formats. After the SetTimeFormat method is called, all IMediaSeeking methods must treat incoming and outgoing time parameters as being in the new time format. For example, if the m_rtDuration variable represents the duration in units of reference time, but the current time format is frames, then the GetDuration method must return the value m_rtDuration converted to frames. For example:

STDMETHODIMP GetDuration(LONGLONG *pDuration)
{
    HRESULT hr = CSourceSeeking::GetDuration(pDuration);
    if (SUCCEEDED(hr))
    {
        if (m_TimeFormat == TIME_FORMAT_FRAME)
        {
            // Convert from reference time to frames.
            *pDuration = TimeToFrame(*pDuration);  // Private method.
        }
    }
    return hr
}

Also, make sure to check for the AM_SEEKING_ReturnTime flag in the IMediaSeeking::SetPositions method. If this flag is present, convert the position values into reference times when you return them to the caller.


CSourceSeeking::m_rtDuration

Duration of the stream. By default, the value is set to the value of the CSourceSeeking::m_rtStop member variable.

Syntax

CRefTime m_rtDuration;

Remarks

Hold the m_pLock critical section before accessing this variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::m_rtStart

Start time. By default, the value is set to zero.

Syntax

CRefTime m_rtStart;

Remarks

Hold the m_pLock critical section before accessing this variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::m_rtStop

Stop time. By default, the value is set to a very large number. The derived class can reset the value in its constructor, or when the filter is initialized.

Syntax

CRefTime m_rtStop;

Remarks

Hold the m_pLock critical section before accessing this variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::m_dRateSeeking

Playback rate. By default, the value is set to 1.0.

Syntax

double m_dRateSeeking;

Remarks

Hold the m_pLock critical section before accessing this variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::m_dwSeekingCaps

Seeking capabilities.

Syntax

DWORD m_dwSeekingCaps;

Remarks

By default, the value is set to the bitwise combination of the following flags:

  • AM_SEEKING_CanSeekForwards
  • AM_SEEKING_CanSeekBackwards
  • AM_SEEKING_CanSeekAbsolute
  • AM_SEEKING_CanGetStopPos
  • AM_SEEKING_CanGetDuration

If the filter supports a different set of capabilities, override this value.

See Also

  • CSourceSeeking Class


CSourceSeeking::m_pLock

Pointer to a critical section object. The CSourceSeeking class uses this critical section to synchronize access to the start and stop times, duration, and rate variables. This variable is initialized in the constructor method; see CSourceSeeking::CSourceSeeking.

Syntax

CCritSec *m_pLock;

See Also

  • CSourceSeeking Class


CSourceSeeking::ChangeRate

The ChangeRate method is called when the playback rate changes.

Syntax

virtual HRESULT ChangeRate(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The CSourceSeeking::SetRate method calls this method, which the derived class must implement. The SetRate method updates the CSourceSeeking::m_dRateSeeking member variable, but does not validate the new value. A rate of zero should always be rejected. Rates less than zero indicate negative playback. Most filters do not support negative rates.

The following example shows a possible implementation:

HRESULT CMyStream::ChangeRate( )
{
    {   // Scope for critical section lock.
        CAutoLock cAutoLockSeeking(CSourceSeeking::m_pLock);
        if( m_dRateSeeking <= 0 ) {
            m_dRateSeeking = 1.0;  // Reset to a reasonable value.
            return E_FAIL;
        }
    }
    UpdateFromSeek();
    return S_OK;
}

See Also

  • CSourceSeeking Class


CSourceSeeking::ChangeStart

The ChangeStart method is called when the start position changes.

Syntax

virtual HRESULT ChangeStart(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The CSourceSeeking::SetPositions method calls this method if the start position changes. This method is pure virtual; the derived class must implement it. After a seek operation, time stamps should restart from zero. Media times should reflect the new start time. The following example shows a possible implementation:

HRESULT CMyStream::ChangeStart( )
{
    m_rtSampleTime = 0;          // Reset the time stamps.
    m_rtMediaTime = m_rtStart;   // Reset the media times.
    UpdateFromSeek();
    return S_OK;
}

See Also

  • CSourceSeeking Class


CSourceSeeking::ChangeStop

The ChangeStop method is called when the stop position changes.

Syntax

virtual HRESULT ChangeStop(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The CSourceSeeking::SetPositions method calls this method if the stop position changes. This method is pure virtual; the derived class must implement it. The following example shows a possible implementation:

HRESULT CMyStream::ChangeStop( )
{
    UpdateFromSeek();
    return S_OK;
}

See Also

  • CSourceSeeking Class


CSourceSeeking::CheckCapabilities

The CheckCapabilities method queries whether the stream has specified seeking capabilities. This method implements the IMediaSeeking::CheckCapabilities method.

Syntax

HRESULT CheckCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities

Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_FALSE | Not all of the capabilities in pCapabilities are present.
S_OK | All capabilities in pCapabilities are present.
E_POINTER | NULL pointer argument.

Remarks

As implemented, this method checks the value of *pCapabilities against the CSourceSeeking::m_dwSeekingCaps member variable. However, it does not set *pCapabilities equal to m_dwSeekingCaps, as described for the IMediaSeeking::CheckCapabilities method. Also, in the case where none of the specified capabilities are available, the method does not return E_FAIL. A more complete implementation would be as follows:

STDMETHODIMP CheckCapabilities(DWORD *pCapabilities)
{
    CheckPointer(pCapabilities, E_POINTER);
    DWORD dwCaps;
    HRESULT hr = GetCapabilities(&dwCaps);
    if (SUCCEEDED(hr))
    {
        dwCaps &= *pCapabilities;
        if (dwCaps)
        {
            hr =  (dwCaps == *pCapabilities ? S_OK : S_FALSE );
        }
        else
        {
            dwCaps = E_FAIL;
        }
        *pCapabilities = dwCaps;
    }
    else *pCapabilities = 0;
    return hr;
}

See Also

  • CSourceSeeking Class


CSourceSeeking::ConvertTimeFormat

The ConvertTimeFormat method converts from one time format to another. This method implements the IMediaSeeking::ConvertTimeFormat method.

Syntax

HRESULT ConvertTimeFormat(
    LONGLONG *pTarget,
    const GUID *pTargetFormat,
    LONGLONG Source,
    const GUID *pSourceFormat
);

Parameters

pTarget

Pointer to a variable that receives the converted time.

pTargetFormat

Pointer to the GUID of the target format. If NULL, the current format is used. See Time Format GUIDs.

Source

Time value to be converted.

pSourceFormat

Pointer to the time format GUID of the format to convert. If NULL, the current format is used.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_INVALIDARG | Invalid argument
E_POINTER | NULL pointer argument

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units). This method returns E_INVALIDARG, except in the trivial case where pTargetFormat and pSourceFormat both specify TIME_FORMAT_MEDIA_TIME.

See Also

  • CSourceSeeking Class


CSourceSeeking::CSourceSeeking

Constructor method.

Syntax

CSourceSeeking(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    CCritSec *pLock
);

Parameters

pName

Pointer to a string containing the name of the object. For more information, see CBaseObject.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

phr

Pointer to an HRESULT value. Ignored.

pLock

Pointer to a CCritSec object. In your derived class, declare a CCritSec member variable and use the address of it for this parameter. The CSourceSeeking class uses this critical section to synchronize access to the start and stop times, duration, and playback rate. Whenever you access those variables in your derived class, hold this lock.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetAvailable

The GetAvailable method retrieves the range of times in which seeking is efficient. This method implements the IMediaSeeking::GetAvailable method.

Syntax

HRESULT GetAvailable(
    LONGLONG *pEarliest,
    LONGLONG *pLatest
);

Parameters

pEarliest

Pointer to a variable that receives the earliest time for efficient seeking. The variable is set to zero.

pLatest

Pointer to a variable that receives the latest time for efficient seeking. The variable is set to the value of the CSourceSeeking::m_rtDuration member variable.

Return Value

Returns S_OK.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetCapabilities

The GetCapabilities method retrieves all the seeking capabilities of the stream. This method implements the IMediaSeeking::GetCapabilities method.

Syntax

HRESULT GetCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities

Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The seeking capabilities are specified by the CSourceSeeking::m_dwSeekingCaps member variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetCurrentPosition

The GetCurrentPosition method retrieves the current position, relative to the total duration of the stream. Not implemented.

Syntax

HRESULT GetCurrentPosition(
  LONGLONG *pCurrent
);

Parameters

pCurrent

Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns E_NOTIMPL.

Remarks

Source filters typically do not support this method. Instead, renderer filters report the current position through the CRendererPosPassThru class.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetDuration

The GetDuration method retrieves the duration of the stream. This method implements the IMediaSeeking::GetDuration method.

Syntax

HRESULT GetDuration(
    LONGLONG *pDuration
);

Parameters

pDuration

Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The duration is specified by the CSourceSeeking::m_rtDuration member variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetPositions

The GetPositions method retrieves the current position and the stop position. This method implements the IMediaSeeking::GetPositions method.

Syntax

HRESULT GetPositions(
    LONGLONG *pCurrent,
    LONGLONG *pStop
);

Parameters

pCurrent

Pointer to a variable that receives the start position.

pStop

Pointer to a variable that receives the stop position.

Return Value

Returns S_OK.

Remarks

For the pCurrent parameter, this method returns the value of the CSourceSeeking::m_rtStart member variable, which represents the latest seek time, not the current streaming position. However, when an application calls IMediaSeeking::GetPositions through the filter graph manager, the values typically come from a renderer filter, not a source filter.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetPreroll

The GetPreroll method retrieves the preroll time. This method implements the IMediaSeeking::GetPreroll method.

Syntax

HRESULT GetPreroll(
    LONGLONG *pPreroll
);

Parameters

pPreroll

Pointer to a variable that receives the preroll time. The value is set to zero.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

See Also

  • CSourceSeeking Class


CSourceSeeking::GetRate

The GetRate method retrieves the playback rate. This method implements the IMediaSeeking::GetRate method.

Syntax

HRESULT GetRate(
    double *pdRate
);

Parameters

pdRate

Pointer to a variable that receives the playback rate.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The playback rate is specified by the CSourceSeeking::m_dRateSeeking member variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetStopPosition

The GetStopPosition method retrieves the time when playback will stop, relative to the duration of the stream. This method implements the IMediaSeeking::GetStopPosition method.

Syntax

HRESULT GetStopPosition(
    LONGLONG *pStop
);

Parameters

pStop

Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The stop time is specified by the CSourceSeeking::m_rtStop member variable.

See Also

  • CSourceSeeking Class


CSourceSeeking::GetTimeFormat

The GetTimeFormat method retrieves the current time format. This method implements the IMediaSeeking::GetTimeFormat method.

Syntax

HRESULT GetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a variable that receives a time format GUID. See Time Format GUIDs.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

See Also

  • CSourceSeeking Class


CSourceSeeking::IsFormatSupported

The IsFormatSupported method determines whether a specified time format is supported. This method implements the IMediaSeeking::IsFormatSupported method.

Syntax

HRESULT IsFormatSupported(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID. See Time Format GUIDs.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_FALSE | The format is not supported.
S_OK | The format is supported.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

See Also

  • CSourceSeeking Class


CSourceSeeking::IsUsingTimeFormat

The IsUsingTimeFormat method determines whether a specified time format is the format currently in use.

Syntax

HRESULT IsUsingTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID. See Time Format GUIDs.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_FALSE | The specified format is not the current format.
S_OK | The specified format is the current format.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

See Also

  • CSourceSeeking Class


CSourceSeeking::QueryPreferredFormat

The QueryPreferredFormat method retrieves the object's preferred time format. This method implements the IMediaSeeking::QueryPreferredFormat method.

Syntax

HRESULT QueryPreferredFormat(
    GUID *pFormat
);

Parameters

pFormat

Pointer to a variable that receives a time format GUID. See Time Format GUIDs.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success
E_POINTER | NULL pointer value

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

See Also

  • CSourceSeeking Class


CSourceSeeking::SetPositions

The SetPositions method sets the current position and the stop position. This method implements the IMediaSeeking::SetPositions method.

Syntax

HRESULT SetPositions(
    LONGLONG *pCurrent,
    DWORD CurrentFlags,
    LONGLONG *pStop,
    DWORD StopFlags
);

Parameters

pCurrent

Pointer to a variable that specifies the current position.

CurrentFlags

Bitwise combination of flags. See Remarks.

pStop

Pointer to a variable that specifies the stop time, in units of the current time format.

StopFlags

Bitwise combination of flags. See Remarks.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_OK | Success
E_INVALIDARG | Invalid flags
E_POINTER | NULL pointer argument

Remarks

The following flags are supported:

  • AM_SEEKING_NoPositioning
  • AM_SEEKING_AbsolutePositioning
  • AM_SEEKING_RelativePositioning
  • AM_SEEKING_IncrementalPositioning (pStop only)

For more information, see IMediaSeeking::SetPositions.

This method updates the values of the CSourceSeeking::m_rtStart and CSourceSeeking::m_rtStop member variables, and then calls the pure virtual methods CSourceSeeking::ChangeStart and CSourceSeeking::ChangeStop.

See Also

  • CSourceSeeking Class


CSourceSeeking::SetRate

The SetRate method sets the playback rate. This method implements the IMediaSeeking::SetRate method.

Syntax

HRESULT SetRate(
    double dRate
);

Parameters

dRate

Playback rate.

Return Value

Returns an HRESULT value.

Remarks

This method updates the value of the CSourceSeeking::m_dRateSeeking member variable, and then calls the pure virtual method CSourceSeeking::ChangeRate. The method does not validate the dRate parameter.

See Also

  • CSourceSeeking Class


CSourceSeeking::SetTimeFormat

The SetTimeFormat method sets the time format. This method implements the IMediaSeeking::SetTimeFormat method.

Syntax

HRESULT SetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat

Pointer to a time format GUID. See Time Format GUIDs.

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success.
E_INVALIDARG | Specified format is not supported.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

See Also

  • CSourceSeeking Class


CSourceStream Class

CSourceStream Class Hierarchy

The CSourceStream class provides an output pin for the CSource filter class.

For information on using this class, see CSource. This class inherits the CAMThread class, which provides a worker thread for streaming data from the pin. The CSourceStream class implements the following helper methods to send requests to the thread:

  • CSourceStream::Exit
  • CSourceStream::Init
  • CSourceStream::Pause
  • CSourceStream::Run
  • CSourceStream::Stop

The first request to the thread must be Init. The Exit request terminates the thread. In practice, it is not necessary to call any of these methods directly, because the pin's CSourceStream::Active and CSourceStream::Inactive methods call them as needed.

The class also provides several "handler" methods:

  • CSourceStream::OnThreadCreate
  • CSourceStream::OnThreadDestroy
  • CSourceStream::OnThreadStartPlay

These do nothing in the base class, but the derived class can override them.

Requirements

Header: Declared in Source.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pFilter | Pointer to the filter that contains this pin.
Protected Methods |
OnThreadCreate | Called when the streaming thread is initialized. Virtual.
OnThreadDestroy | Called when the streaming thread is about to exit. Virtual.
OnThreadStartPlay | Called at the start of the CSourceStream::DoBufferProcessingLoop method. Virtual.
Active | Notifies the pin that the filter is now active.
Inactive | Notifies the pin that the filter is no longer active.
GetRequest | Waits for the next thread request.
CheckRequest | Checks if there is a thread request, without blocking.
ThreadProc | Thread procedure. Virtual.
DoBufferProcessingLoop | Generates media data and delivers it to the downstream input pin. Virtual.
CheckMediaType | Determines if the pin accepts a specific media type. Virtual.
GetMediaType | Retrieves a preferred media type. Virtual.
Public Methods |
CSourceStream | Constructor method.
~CSourceStream | Destructor method. Virtual.
Init | Initializes the streaming thread.
Exit | Signals the streaming thread to exit.
Run | Signals the streaming thread to run.
Pause | Signals the streaming thread to become active.
Stop | Signals the streaming thread to stop.
Pure Virtual Methods |
FillBuffer | Fills a media sample with data.
IPin Methods |
QueryId | Retrieves an identifier for the pin.


CSourceStream::m_pFilter

Pointer to the filter that contains this pin.

Syntax

CSource *m_pFilter;

See Also

  • CSourceStream Class


CSourceStream::Active

The Active method notifies the pin that the filter is now active. This method overrides the CBasePin::Active method. If the pin is connected, this method starts the streaming thread.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

Value | Description
S_FALSE | The pin is already active.
S_OK | Success.
E_FAIL | Could not start the thread.

See Also

  • CSourceStream Class


CSourceStream::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type. This method implements the pure virtual CBasePin::CheckMediaType method.

Syntax

virtual HRESULT CheckMediaType(
    const CMediaType *pMediaType
);

Parameters

pMediaType

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | This pin supports this media type.
E_FAIL | The pin does not support this media type.

Remarks

By default, the pin supports a single media type. This method retrieves the supported type by calling the single-parameter version of the CSourceStream::GetMediaType method, and compares it to the proposed type. If your pin supports more than one media type, override this method.

See Also

  • CSourceStream Class


CSourceStream::CheckRequest

The CheckRequest method checks if there is a thread request, without blocking.

Syntax

BOOL CheckRequest(
    Command *pCom
);

Parameters

pCom

Pointer to a variable that receives the value passed in the last call to the CAMThread::CallWorker method.

Return Value

Returns TRUE if there is a pending request, or FALSE otherwise.

Remarks

This method overrides the CAMThread::CheckRequest method to perform type-checking. The CSourceStream class defines the following enumerated type for the pCom parameter:

enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT};

See Also

  • CSourceStream Class


CSourceStream::CSourceStream

Constructor method.

Syntax

CSourceStream(
    TCHAR *pObjectName,
    HRESULT *phr,
    CSource *pms,
    LPCWSTR pName
);

Parameters

pObjectName

Pointer to a string containing the debug name of the pin.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pms

Pointer to the CSource filter that created this pin.

pName

Pointer to a string that contains the name of the pin.

Remarks

The string given in the pObjectName parameter is used only for debugging purposes. For more information, see CBaseObject.

The string given in the pName parameter is the name returned by the IPin::QueryPinInfo method. The CSourceStream class does not use this name for the pin identifier returned by the CSourceStream::QueryId method. Instead, QueryId calculates a pin identifier based on the pin number. (Pin identifiers support graph persistence. For more information, see IPin::QueryId.)

The constructor automatically adds the pin to the owning filter, by calling CSource::AddPin.

See Also

  • CSourceStream Class


CSourceStream::~CSourceStream

Destructor method.

Syntax

~CSourceStream(void);

Remarks

The destructor automatically removes the pin from the owning filter, by calling CSource::RemovePin.

See Also

  • CSourceStream Class


CSourceStream::DoBufferProcessingLoop

The DoBufferProcessingLoop method generates media data and delivers it to the downstream input pin.

Syntax

virtual HRESULT DoBufferProcessingLoop(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Thread received a stop request.
S_OK | Stream ended, or downstream filter is not accepting samples.

Remarks

This method implements the main loop that processes data and delivers it downstream. Each time through the loop, the method retrieves an empty media sample from the allocator. It passes the sample to the CSourceStream::FillBuffer method. The FillBuffer method, which the derived class must implement, generates media data and places it in the sample buffer.

The loop ends when any of the following occurs:

  • The input pin's IMemInputPin::Receive method rejects a sample.
  • The FillBuffer method returns S_FALSE, indicating the end of the stream, or returns an error code.
  • The thread receives a CSourceStream::Stop request.

The DoBufferProcessingLoop method handles the end-of-stream notification. If an error occurs, it sends an EC_ERRORABORT event to the filter graph manager.

See Also

  • CSourceStream Class


CSourceStream::Exit

The Exit method signals the streaming thread to exit.

Syntax

HRESULT Exit(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The CSourceStream::Inactive method calls this method.

See Also

  • CSourceStream Class


CSourceStream::FillBuffer

The FillBuffer method fills a media sample with data.

Syntax

virtual HRESULT FillBuffer(
    IMediaSample *pSample
) PURE;

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | End of stream
S_OK | Success

Remarks

The derived class must implement this method.

The media sample given to this method has no time stamps. The derived class should call the IMediaSample::SetTime method to set the time stamps. If appropriate for the media type, the derived class should also set the media times, by calling the IMediaSample::SetMediaTime method. For more information, see Time and Clocks in DirectShow.

Return S_FALSE at the end of the stream. This causes the CSourceStream class to send the end-of-stream notification and halt the buffer processing loop. See CSourceStream::DoBufferProcessingLoop for more information.

See Also

  • CSourceStream Class


CSourceStream::GetMediaType

The GetMediaType method retrieves a preferred media type.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

virtual HRESULT GetMediaType(
    CMediaType *pMediaType
);

Parameters

iPosition

Zero-based index value.

pMediaType

Pointer to a CMediaType object that receives the media type.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.
E_UNEXPECTED | Unexpected error.

Remarks

There are two versions of this method. One version overrides the CBasePin::GetMediaType method and takes an index value as a parameter. The other version is designed to retrieve a single media type, so it lacks the index parameter.

The single-parameter method returns E_UNEXPECTED. The two-parameter method verifies that the iPosition parameter is zero and then calls the single-parameter version. Depending on the number of media types the pin supports, you must override one of these methods:

  • If the pin supports exactly one media type, override the single-parameter version. Fill in the media type that the pin supports.
  • If the pin supports more than one media type, override the two-parameter version. Also override the CSourceStream::CheckMediaType method.

See Also

  • CSourceStream Class


CSourceStream::GetRequest

The GetRequest method waits for the next thread request.

Syntax

Command GetRequest(void);

Return Value

Returns the next thread request.

Remarks

This method overrides the CAMThread::GetRequest method. The return value is cast to the following enumerated type:

enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT};

See Also

  • CSourceStream Class


CSourceStream::Inactive

The Inactive method notifies the pin that the filter is no longer active. This method overrides the CBasePin::Inactive method. If the streaming thread is active, this method stops it and waits for the thread to exit.

Syntax

HRESULT Inactive(void);

Return Value

Returns S_OK or another HRESULT value.

See Also

  • CSourceStream Class


CSourceStream::Init

The Init method initializes the streaming thread.

Syntax

HRESULT Init(void);

Return Value

Returns S_OK, or another HRESULT value.

Remarks

This method must be the first thread request sent to the CSourceStream::ThreadProc method. The CSourceStream::Active method calls this method.

See Also

  • CSourceStream Class


CSourceStream::OnThreadCreate

The OnThreadCreate method is called when the streaming thread is initialized.

Syntax

virtual HRESULT OnThreadCreate(void);

Return Value

Returns S_OK.

Remarks

The thread procedure, CSourceStream::ThreadProc, calls this method when it first receives a CSourceStream::Init request. The method does nothing in the base class. The derived class can override this method to perform thread initializations. If the derived class returns an error code, the thread exits with an error.

See Also

  • CSourceStream Class


CSourceStream::OnThreadDestroy

The OnThreadDestroy method is called when the streaming thread is about to exit.

Syntax

virtual HRESULT OnThreadDestroy(void);

Return Value

Returns S_OK.

Remarks

The thread procedure, CSourceStream::ThreadProc, calls this method before it exits. The method does nothing in the base class; it is available for the derived class to override. If the derived class returns an error code, the thread exits with an error.

See Also

  • CSourceStream Class


CSourceStream::OnThreadStartPlay

The OnThreadStartPlay method is called at the start of the CSourceStream::DoBufferProcessingLoop method.

Syntax

virtual HRESULT OnThreadStartPlay(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class; it is available for the derived class to override.

See Also

  • CSourceStream Class


CSourceStream::Pause

The Pause method signals the streaming thread to become active.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The CSourceStream::Active method calls this method. When the CSourceStream::ThreadProc method receives this request, it calls the CSourceStream::DoBufferProcessingLoop method.

See Also

  • CSourceStream Class


CSourceStream::QueryId

The QueryId method retrieves an identifier for the pin.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id

Pointer to a variable that receives a string containing the pin identifier.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Pin was not found on the filter.

Remarks

This method implements the IPin::QueryId method. To construct an identifier string, the pin calls the CSource::FindPinNumber method with itself as the parameter. The FindPinNumber method returns the pin number, indexed from zero. QueryId increments the return value by one and converts the result to a string. For example, the first pin becomes "1"; the second pin becomes "2"; and so forth.

If this method returns VFW_E_NOT_FOUND, it indicates that the filter's array of pins is invalid, presumably caused by a bug in the filter.

See Also

  • CSourceStream Class


CSourceStream::Run

The Run method signals the streaming thread to run.

Syntax

HRESULT Run(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

In the base class, this method has the same effect as the CSourceStream::Pause request, and is not used.

See Also

  • CSourceStream Class


CSourceStream::Stop

The Stop method signals the streaming thread to stop.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The CSourceStream::Inactive method calls this method.

See Also

  • CSourceStream Class


CSourceStream::ThreadProc

The ThreadProc method is the thread procedure for the worker thread. This method implements the pure virtual CAMThread::ThreadProc method.

Syntax

virtual DWORD ThreadProc(void);

Return Value

Returns 0 if the thread completed successfully or 1 otherwise. If the return value is 1, the thread's resources might still be allocated.

Remarks

This method waits indefinitely for thread requests, by calling the CAMThread::GetRequest method. If it receives a CSourceStream::Run or CSourceStream::Pause request, it calls the CSourceStream::DoBufferProcessingLoop method. The DoBufferProcessingLoop method pushes data until it receives a CSourceStream::Stop request. The thread procedure exits when it receives a CSourceStream::Exit request.

See Also

  • CSourceStream Class


CSystemClock Class

CSystemClock Class Hierarchy

The CSystemClock class implements a clock that returns the system time.

This class derives from the CBaseReferenceClock class, and adds support for the IPersist and IAMClockAdjust interfaces.

Public Methods |
CreateInstance | Creates a new instance of this object.
CSystemClock | Constructor method.
IAMClockAdjust Methods |
SetClockDelta | Adjusts the clock time.
IPersist Methods |
GetClassID | Returns the class identifier (CLSID) of the object.


CSystemClock::CreateInstance

The CreateInstance method creates a new instance of this object.

Syntax

static CUnknown * WINAPI CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk

Pointer to the aggregating IUnknown interface.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

Return Value

Returns a pointer to a new instance of this object.

Remarks

The class factory calls this method to create the object.

See Also

CSystemClock Class

CFactoryTemplate::CreateInstance

How to Create a DLL


CSystemClock::CSystemClock

Constructor method.

Syntax

CSystemClock(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pName

String containing the debug name of the object. For more information, see CBaseObject.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL..

phr

Pointer to the HRESULT value. If an error occurs, the method returns an error code in this parameter.

See Also

CSystemClock Class


CSystemClock::GetClassID

The GetClassID method retrieves the class identifier (CLSID) of the object. This method implements the IPersist::GetClassID method.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID

Pointer to a variable that receives the value CLSID_SystemClock.

Return Value

Returns S_OK or E_POINTER.

See Also

CSystemClock Class


CSystemClock::SetClockDelta

The SetClockDelta method adjusts the clock time. This method implements the IAMClockAdjust::SetClockDelta method.

Syntax

HRESULT SetClockDelta(
    REFERENCE_TIME rtDelta
);

Parameters

rtDelta

Specifies the amount by which to adjust the clock, as a REFERENCE_TIME value. A positive value moves the clock forward, and a negative value moves the clock backward.

Return Value

Returns S_OK or an HRESULT error code.

Remarks

This method simply calls CBaseReferenceClock::SetTimeDelta.

The time values returned by IReferenceClock::GetTime are monotonically increasing. If you set the clock back, GetTime continues to report the old time until the internal clock catches up.

See Also

CSystemClock Class


CTransformFilter Class

CTransformFilter Class Hierarchy

The CTransformFilter class is a base class for implementing transform filters. This class is designed for implementing a transform filter with one input pin and one output pin. It uses separate allocators for the input pin and the output pin. To create a filter that processes data in place, use the CTransInPlaceFilter class.

This filter uses the CTransformInputPin class for its input pin, and the CTransformOutputPin class for its output pin. Typically, you do not need to override these pin classes. Most of the pin methods call corresponding methods on the CTransformFilter class, so you can override the filter methods if necessary. The filter creates both pins in the CTransformFilter::GetPin method. If you do override the pin classes, you must override GetPin to create your custom pins.

To use this class, derive a new class from CTransformFilter and implement the following methods:

  • CTransformFilter::CheckInputType
  • CTransformFilter::CheckTransform
  • CTransformFilter::DecideBufferSize
  • CTransformFilter::GetMediaType
  • CTransformFilter::Transform

You might need to override other methods as well, depending on the requirements of your filter.

Media Types

This filter's input pin does not propose any media types; it relies on the upstream filter to propose the media types for the connection. The reason for this design is that in most cases, the upstream filter can provide more information about the format. For example, with video formats, the upstream filter knows the video dimensions and the frame rate, whereas the transform filter has no way to determine this information. If you want to change this behavior, override the input pin's GetMediaType method. When the upstream filter proposes a media type, the input pin calls the filter's CheckInputType method (pure virtual).

Until the input pin is connected, the output pin refuses all connections, and does not return any preferred media types. After the input pin is connected, the output pin returns a list of preferred types by calling the filter's GetMediaType method. It checks output types for the connection through the filter's CheckTransform method. (Both methods are pure virtual.) Typically, the input type will partly determine the acceptible output types.

Depending on the filter, you might want to register some of the filter's supported media types, so that the Filter Mapper object can locate your filter. For more information, see How to Register DirectShow Filters.

Streaming

This class does not queue the output data. Each output sample is delivered inside the IMemInputPin::Receive method. The Receive method calls the filter's Transform method (also pure virtual) to process the data.

Requirements

Header: Declared in Transfrm.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_bEOSDelivered | Flag that indicates whether the filter has sent an end-of-stream notification.
m_bSampleSkipped | Flag that indicates whether the most recent sample was dropped.
m_bQualityChanged | Flag that indicates whether the quality has changed.
m_csFilter | Critical section that protects the filter state.
m_csReceive | Critical section that protects the streaming state.
m_pInput | Pointer to the input pin.
m_pOutput | Pointer to the output pin.
Public Methods |
CTransformFilter | Constructor method.
~CTransformFilter | Destructor method.
GetPinCount | Retrieves the number of pins on the filter. Virtual.
GetPin | Retrieves a pin. Virtual.
Transform | Transforms an input sample to produce an output sample. Virtual.
StartStreaming | Called when the filter switches to the paused state. Virtual.
StopStreaming | Called when the filter switches to the stopped state. Virtual.
AlterQuality | Notifies the filter that a quality change is requested. Virtual.
SetMediaType | Called when the media type is set on one of the filter's pins. Virtual.
CheckConnect | Determines whether a pin connection is suitable. Virtual.
BreakConnect | Releases a pin from a connection. Virtual.
CompleteConnect | Completes a pin connection. Virtual.
Receive | Receives a media sample, processes it, and delivers an output sample to the downstream filter. Virtual.
InitializeOutputSample | Retrieves a new output sample and initializes it.
EndOfStream | Notifies the filter that no additional data is expected from the input pin. Virtual.
BeginFlush | Begins a flush operation. Virtual.
EndFlush | Ends a flush operation. Virtual.
NewSegment | Notifies the filter that media samples received after this call are grouped as a segment. Virtual.
Pure Virtual Methods |
CheckInputType | Checks whether a specified media type is acceptable for input.
CheckTransform | Checks whether an input media type is compatible with an output media type.
DecideBufferSize | Sets the output pin's buffer requirements.
GetMediaType | Retrieves a preferred media type for the output pin.
IMediaFilter Methods |
Stop | Stops the filter.
Pause | Pauses the filter.
IBaseFilter Methods |
FindPin | Retrieves the pin with the specified identifier.


CTransformFilter::m_bEOSDelivered

Flag that indicates whether the filter has sent an end-of-stream notification.

Syntax

BOOL m_bEOSDelivered;

Remarks

If the filter pauses when it does not have an input connection, it sends an end-of-stream notification downstream and sets this flag to TRUE. The end-of-stream notification ensures that the downstream filter does not wait for samples. Note that the filter's EndOfStream method does not set this flag.

See Also

CTransformFilter Class


CTransformFilter::m_bSampleSkipped

Flag that indicates whether the most recent sample was dropped. If the Receive method drops a sample, it sets the value to TRUE.

Syntax

BOOL m_bSampleSkipped;

See Also

CTransformFilter Class


CTransformFilter::m_bQualityChanged

Flag that indicates whether the quality has changed. The first time that the filter drops a sample, it sends an EC_QUALITY_CHANGE event to the filter graph manager and sets this flag to TRUE. It does not send this event again until the filter stops and restarts, even if it continues to drop samples in the meantime.

Syntax

BOOL m_bQualityChanged;

See Also

CTransformFilter Class


CTransformFilter::m_csFilter

Critical section that protects the filter state. For more information, see Data Flow for Filter Developers.

Syntax

CCritSec m_csFilter;

See Also

CTransformFilter Class


CTransformFilter::m_csReceive

Critical section that protects the streaming state. For more information, see Data Flow for Filter Developers.

Syntax

CCritSec m_csReceive;

See Also

CTransformFilter Class


CTransformFilter::m_pInput

Pointer to the input pin.

Syntax

CTransformInputPin *m_pInput;

See Also

CTransformFilter Class


CTransformFilter::m_pOutput

Pointer to the output pin.

Syntax

CTransformOutputPin *m_pOutput;

See Also

CTransformFilter Class


CTransformFilter::AlterQuality

The AlterQuality method notifies the filter that a quality change is requested.

Syntax

virtual HRESULT AlterQuality(
    Quality q
);

Parameters

q

Quality structure that contains the quality control message.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Did not handle the quality message. The message should be passed upstream.
S_OK | Handled the quality message. No further action is necessary.

The base class returns S_FALSE.

Remarks

Override this method if the filter can perform quality control. For more information, see Quality-Control Management.

See Also

CTransformFilter Class


CTransformFilter::BeginFlush

The BeginFlush method begins a flush operation.

Syntax

virtual HRESULT BeginFlush(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

At the start of a flush operation, the input pin's CTransformInputPin::BeginFlush method calls this method. This method passes the BeginFlush call downstream.

If the derived class uses a worker thread to deliver samples, it should discard any queued data during a flush operation. That can be done either in the BeginFlush method, or in the EndFlush method. However, note that calls to BeginFlush are not synchronized with the streaming thread. If the BeginFlush method discards the queued data, the filter must be careful not to process any more data between the BeginFlush and EndFlush calls. For more information, see Data Flow for Filter Developers.

See Also

CTransformFilter Class


CTransformFilter::BreakConnect

The BreakConnect method releases a pin from a connection.

Syntax

virtual HRESULT BreakConnect(
    PIN_DIRECTION dir
);

Parameters

dir

Member of the PIN_DIRECTION enumerated type, specifying which pin connection was broken (input or output).

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::BreakConnect and CTransformOutputPin::BreakConnect methods call this method when a pin connection is broken. This method does nothing in the base class. If you override the CheckConnect method, override this method to release any resources obtained in the CheckConnect method, including interface pointers.

See Also

CTransformFilter Class


CTransformFilter::CheckConnect

The CheckConnect method determines whether a pin connection is suitable.

Syntax

virtual HRESULT CheckConnect(
    PIN_DIRECTION dir,
    IPin *pPin
);

Parameters

dir

Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.

pPin

Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::CheckConnect and CTransformOutputPin::CheckConnect methods call this method during the pin connection process. This method does nothing in the base class. The derived class can override it. For example, the derived class might query the other pin for a particular interface.

See Also

CTransformFilter Class


CTransformFilter::CheckInputType

The CheckInputType method checks whether a specified media type is acceptable for input.

Syntax

virtual HRESULT CheckInputType(
    const CMediaType *mtIn
) PURE;

Parameters

mtIn

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Media type is acceptable.
VFW_E_TYPE_NOT_ACCEPTED | Media type is not acceptable.

Remarks

The derived class must implement this method. Return S_OK if the proposed input format is acceptable, or an error code otherwise.

This method does not need to verify that the input format is compatible with the output format (if any). The input pin verifies that by calling the CheckTransform method.

See Also

CTransformFilter Class


CTransformFilter::CheckTransform

The CheckTransform method checks whether an input media type is compatible with an output media type.

Syntax

virtual HRESULT CheckTransform(
    const CMediaType *mtIn,
    const CMediaType *mtOut
) PURE;

Parameters

mtIn

Pointer to a CMediaType object that specifies the input type.

mtOut

Pointer to a CMediaType object that specifies the output type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | The media types are compatible.
VFW_E_TYPE_NOT_ACCEPTED | The media types are not compatible.

Remarks

The derived class must implement this method. Return S_OK if the filter can accept both of the specified media types, or an error code otherwise.

See Also

CTransformFilter Class


CTransformFilter::CompleteConnect

The CompleteConnect method completes a pin connection.

Syntax

virtual HRESULT CompleteConnect(
    PIN_DIRECTION direction,
    IPin *pReceivePin
);

Parameters

direction

Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.

pReceivePin

Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::CompleteConnect and CTransformOutputPin::CompleteConnect methods call this method during the pin connection process. This method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::CTransformFilter

Constructor method.

Syntax

CTransformFilter(
    TCHAR *pObjectName,
    LPUNKNOWN lpUnk,
    CLSID clsid
);

Parameters

pObjectName

String containing the debug name of the filter. For more information, see CBaseObject.

lpUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

clsid

Class identifier of the filter.

Remarks

The constructor does not create the filter's pins. That happens during the first call to the GetPin method. The constructor initializes the m_pInput and m_pOutput member variables to NULL.

See Also

CTransformFilter Class


CTransformFilter::~CTransformFilter

Destructor method.

Syntax

~CTransformFilter(void);

See Also

CTransformFilter Class


CTransformFilter::DecideBufferSize

The DecideBufferSize method sets the output pin's buffer requirements.

Syntax

virtual HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
) PURE;

Parameters

pAlloc

Pointer to the IMemAllocator interface on the output pin's allocator.

ppropInputRequest

Pointer to an ALLOCATOR_PROPERTIES structure that contains buffer requirements from the downstream input pin.

Return Value

Returns S_OK or another HRESULT value.

Remarks

The output pin's CTransformOutputPin::DecideBufferSize method calls this method. The derived class must implement this method. For more information, see CBaseOutputPin::DecideBufferSize.

See Also

CTransformFilter Class


CTransformFilter::EndFlush

The EndFlush method ends a flush operation.

Syntax

virtual HRESULT EndFlush(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

At the end of a flush operation, the input pin's CTransformInputPin::EndFlush method calls this method. This method passes the EndFlush call downstream.

If the derived class uses a worker thread to deliver samples, it must discard any queued data before sending the EndFlush call downstream. For more information, see Data Flow for Filter Developers.

See Also

CTransformFilter Class


CTransformFilter::EndOfStream

The EndOfStream method notifies the filter that no additional data is expected from the input pin.

Syntax

virtual HRESULT EndOfStream(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

The input pin's CTransformInputPin::EndOfStream method calls this method. This method delivers the end-of-stream notification downstream. If the derived class uses a worker thread to deliver media samples, it should override this method and queue the end-of-stream notification.

See Also

CTransformFilter Class


CTransformFilter::FindPin

The FindPin method retrieves the pin with the specified identifier. This method implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id

Wide-character string that contains the pin identifier.

ppPin

Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

The identifier for the input pin is In, and the identifier for the output pin is Out.

See Also

CTransformFilter Class


CTransformFilter::GetMediaType

The GetMediaType method retrieves a preferred media type for the output pin.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
) PURE;

Parameters

iPosition

Zero-based index value.

pMediaType

Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.

Remarks

The output pin's CTransformOutputPin::GetMediaType method calls this method. The derived class must implement this method. For more information, see CBasePin::GetMediaType.

See Also

CTransformFilter Class


CTransformFilter::GetPin

The GetPin method retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n

Number of the specified pin, indexed from zero. On this filter, pin 0 is the input pin, and pin 1 is the output pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin, or NULL if the method fails.

Remarks

This method implements the pure virtual CBaseFilter::GetPin method. The first time the method is called, it creates both pins.

This method does not increment the reference count on the returned pin, so the returned pin does not have an outstanding reference count. If the caller needs to keep a reference on the pin, it should call the IUnknown::AddRef method on the pin.

If the filter uses the default CTransformInputPin and CTransformOutputPin pins, you probably do not need to override this method. If the filter uses pins that extend those classes, however, you must override this method to create pins of that type.

See Also

CTransformFilter Class


CTransformFilter::GetPinCount

The GetPinCount method retrieves the number of pins on the filter.

Syntax

virtual int GetPinCount(void);

Return Value

Returns 2.

Remarks

This method overrides the CBaseFilter::GetPinCount method. The CTransformFilter class supports exactly one input pin and one output pin.

See Also

CTransformFilter Class


CTransformFilter::InitializeOutputSample

The InitializeOutputSample method retrieves a new output sample and initializes it.

Syntax

HRESULT InitializeOutputSample(
    IMediaSample *pSample,
    IMediaSample **ppOutSample
);

Parameters

pSample

Pointer to the input sample's IMediaSample interface.

ppOutSample

Address of a variable that receives a pointer to the output sample's IMediaSample interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method retrieves a new sample from the output pin's allocator. Then it copies the sample properties from the input sample to the output sample.

See Also

CTransformFilter Class


CTransformFilter::NewSegment

The NewSegment method notifies the filter that media samples received after this call are grouped as a segment.

Syntax

virtual HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart

Start time of the segment, relative to the original source.

tStop

Stop time of the segment, relative to the original source.

dRate

Rate at which the segment should be processed.

Return Value

Returns S_OK.

Remarks

The input pin's CTransformInputPin::NewSegment method calls this method. This method delivers the NewSegment call to the downstream input pin.

See Also

CTransformFilter Class


CTransformFilter::Pause

The Pause method pauses the filter. This method implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method calls the StartStreaming method. The StartStreaming method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::Receive

The Receive method receives a media sample, processes it, and delivers an output sample to the downstream filter.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface on the input sample.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | The upstream filter should stop sending samples.
S_OK | Success.

Remarks

The filter's input pin calls this method when it receives a sample. This method calls the CTransformFilter::InitializeOutputSample method, which prepares a new output sample. Then it calls the CTransformFilter::Transform method, which the derived class must implement. The Transform method processes the input data and produces output data.

If the Transform method returns S_FALSE, the Receive method drops this sample. On the first dropped sample, the filter sends an EC_QUALITY_CHANGE event to the filter graph manager. Otherwise, if the Transform method returns S_OK, the filter delivers the output sample. To do so, it calls the IMemInputPin::Receive method on the downstream input pin.

See Also

CTransformFilter Class


CTransformFilter::SetMediaType

The SetMediaType method is called when the media type is set on one of the filter's pins.

Syntax

virtual HRESULT SetMediaType(
    PIN_DIRECTION direction,
    const CMediaType *pmt
);

Parameters

direction

Member of the PIN_DIRECTION enumerated type, specifying a pin on the filter (input or output).

pmt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::SetMediaType and CTransformOutputPin::SetMediaType methods call this method when a pin's media type is set. This method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::StartStreaming

The StartStreaming method is called when the filter switches to the paused state.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::Stop

Stops the filter. This method implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

After this method decommits both allocators, it calls the StopStreaming method. The StopStreaming method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::StopStreaming

The StopStreaming method is called when the filter switches to the stopped state.

Syntax

virtual HRESULT StopStreaming(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class, but the derived class can override it.

See Also

CTransformFilter Class


CTransformFilter::Transform

The Transform method transforms an input sample to produce an output sample.

Syntax

virtual HRESULT Transform(
    IMediaSample *pIn,
    IMediaSample *pOut
);

Parameters

pIn

Pointer to the input sample's IMediaSample interface.

pOut

Pointer to the output sample's IMediaSample interface.

Return Value

The base class returns E_UNEXPECTED.

The derived class should return an HRESULT value, indicating success or failure. Possible values include those shown in the following table.

Value | Description
S_FALSE | Do not deliver this sample.
S_OK | Success.

Remarks

Override this method to produce output data. Read the input data from the sample specified by the pIn parameter, and write the new data into the sample specified by the pOut parameter.

Before the filter calls this method, it copies the properties from the input sample to the output sample. The Transform method should set any properties that differ between the two samples, using IMediaSample methods or the IMediaSample2 interface (if available).

If the filter should not deliver this sample (for example, to support quality control), the method should return S_FALSE.

See Also

CTransformFilter Class


CTransformInputPin Class

CTransformInputPin Class Hierarchy

The CTransformInputPin class implements an input pin that is used by the CTransformFilter class.

Typically, you do not need to derive from this class. Most of the methods in this class call corresponding methods on the CTransformFilter class, which you can override. If you derive from this class, you must override the filter's CTransformFilter::GetPin method to create instances of your derived class.

Requirements

Header: Declared in Transfrm.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pTransformFilter | Pointer to the owning filter.
Public Methods |
CTransformInputPin | Constructor method.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
CompleteConnect | Completes a connection to another pin.
CheckMediaType | Determines if the pin accepts a specific media type.
SetMediaType | Sets the media type for the connection.
CheckStreaming | Determines whether the pin can accept samples. Virtual.
CurrentMediaType | Retrieves the media type for the current pin connection.
IPin Methods |
QueryId | Retrieves an identifier for the pin.
EndOfStream | Notifies the pin that no additional data is expected.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
IMemInputPin Methods |
Receive | Receives the next media sample in the stream.


CTransformInputPin::m_pTransformFilter

Pointer to the owning filter.

Syntax

CTransformFilter *m_pTransformFilter;

See Also

CTransformInputPin Class


CTransformInputPin::BeginFlush

The BeginFlush method begins a flush operation. This method implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Output pin is not connected.

Remarks

This method calls the pin's CBaseInputPin::BeginFlush method. Then it calls the filter's CTransformFilter::BeginFlush method to deliver the call downstream.

See Also

CTransformInputPin Class


CTransformInputPin::BreakConnect

The BreakConnect method releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseInputPin::BreakConnect method. It calls the filter's CTransformFilter::BreakConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::BreakConnect method.

See Also

CTransformInputPin Class


CTransformInputPin::CheckConnect

The CheckConnect method determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin

Pointer to the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
VFW_E_INVALID_DIRECTION | Wrong pin direction

Remarks

This method overrides the CBasePin::CheckConnect method. It calls the filter's CTransformFilter::CheckConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CheckConnect method to perform additional checks.

See Also

CTransformInputPin Class


CTransformInputPin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *mtIn
);

Parameters

mtIn

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method implements the pure virtual CBasePin::CheckMediaType method. It calls the filter's CTransformFilter::CheckInputType method, which is also pure virtual. The filter's derived class must implement CheckInputType to determine whether a given input type is acceptable.

If the filter's output pin is connected, this method also calls the filter's CTransformFilter::CheckTransform method to determine whether the input type is compatible with the output type. The CheckTransform method is pure virtual as well.

See Also

CTransformInputPin Class


CTransformInputPin::CheckStreaming

The CheckStreaming method determines whether the pin can accept samples.

Syntax

HRESULT CheckStreaming(void);

Return Value

Returns one of the HRESULT values listed in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_NOT_CONNECTED | The output pin is not connected.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method overrides the CBaseInputPin::CheckStreaming method.

See Also

CTransformInputPin Class


CTransformInputPin::CompleteConnect

The CompleteConnect method completes a connection to another pin.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the other pin's IPin interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBasePin::CompleteConnect method. It calls the filter's CTransformFilter::CompleteConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CompleteConnect method to perform additional checks.

See Also

CTransformInputPin Class


CTransformInputPin::CTransformInputPin

Constructor method.

Syntax

CTransformInputPin(
    TCHAR *pObjectName,
    CTransformFilter *pTransformFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pTransformFilter

Pointer to the filter that created this pin, which must be a CTransformFilter object.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Wide-character string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always In. For more information, see QueryId.

See Also

CTransformInputPin Class


CTransformInputPin::CurrentMediaType

The CurrentMediaType method retrieves the media type for the current pin connection.

Syntax

CMediaType& CurrentMediaType(void);

Return Value

Returns a reference to the CBasePin::m_mt member variable.

See Also

CTransformInputPin Class


CTransformInputPin::EndFlush

The EndFlush method ends a flush operation. This method implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_CONNECTED | Output pin is not connected.

Remarks

This method calls the filter's CTransformFilter::EndFlush method to deliver the call downstream. Then it calls the pin's CBaseInputPin::EndFlush method.

See Also

CTransformInputPin Class


CTransformInputPin::EndOfStream

The EndOfStream method notifies the pin that no additional data is expected. This method implements the IPin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_NOT_CONNECTED | The output pin is not connected.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method calls the filter's CTransformFilter::EndOfStream method to deliver the end-of-stream notification downstream.

See Also

CTransformInputPin Class


CTransformInputPin::NewSegment

The NewSegment method notifies the pin that media samples received after this call are grouped as a segment. This method implements the IPin::NewSegment method.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart

Start time of the segment.

tStop

Stop time of the segment.

dRate

Rate of the segment.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBasePin::NewSegment method. It calls the filter's CTransformFilter::NewSegment method to deliver the call downstream.

See Also

CTransformInputPin Class


CTransformInputPin::QueryId

The QueryId method retrieves an identifier for the pin. This method implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id

Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

The pin identifier is used for graph persistence. The pin identifier for this class is In. This class overrides the behavior of the CBasePin class. In the CBasePin class, the pin identifier is the same as the pin name, specified in the class constructor. In the CTransformInputPin class, the pin identifier and the pin name are not the same.

See Also

CTransformInputPin Class


CTransformInputPin::Receive

The Receive method receives the next media sample in the stream. This method implements the IMemInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Pin is currently flushing; sample was rejected.
S_OK | Success.

Remarks

This method calls the pin's CBaseInputPin::Receive method, which checks the pin's streaming state and checks for format changes in the media type. Then it calls the filter's CTransformFilter::Receive method, which processes the sample and delivers it downstream.

If the filter needs to access the sample after this method returns, it should hold a reference count by calling the IUnknown::AddRef method on the sample. For example, some decoder filters need the current sample in order to decode the next sample.

See Also

CTransformInputPin Class


CTransformInputPin::SetMediaType

The SetMediaType method sets the media type for the connection.

Syntax

HRESULT SetMediaType(
    const CMediaType *mt
);

Parameters

mt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method overrides the CBasePin::SetMediaType method. It calls the filter's CTransformFilter::SetMediaType method to inform the filter.

The pin must verify that the media type is acceptable before calling this method.

See Also

CTransformInputPin Class


CTransformOutputPin Class

CTransformOutputPin Class Hierarchy

The CTransformOutputPin class implements an output pin that is used by the CTransformFilter class.

Typically, you do not need to derive from this class. Most of the methods in this class call corresponding methods on the CTransformFilter class, which you can override. If you derive from this class, you must override the filter's CTransformFilter::GetPin method to create instances of your derived class.

This class exposes the IMediaSeeking and IMediaPosition interfaces through the CPosPassThru object. It passes all seek requests to the next filter upstream.

Requirements

Header: Declared in Transfrm.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pTransformFilter | Pointer to the owning filter.
Public Member Variables |
m_pPosition | Helper object to pass seek commands upstream.
Public Methods |
CTransformOutputPin | Constructor method.
~CTransformOutputPin | Destructor method.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
CompleteConnect | Completes a connection to another pin.
CheckMediaType | Determines if the pin accepts a specific media type.
SetMediaType | Sets the media type for the connection.
DecideBufferSize | Sets the buffer requirements.
GetMediaType | Retrieves a preferred media type, by index value.
CurrentMediaType | Retrieves the media type for the current pin connection.
IPin Methods |
QueryId | Retrieves an identifier for the pin.
IQualityControl Methods |
Notify | Notifies the pin that a quality change is requested.


CTransformOutputPin::m_pTransformFilter

Pointer to the owning filter.

Syntax

CTransformOutputPin *m_pTransformFilter;

See Also

CTransformOutputPin Class


CTransformOutputPin::m_pPosition

Helper object to pass seek commands upstream.

Syntax

IUnknown *m_pPosition;

Remarks

When the pin is first queried for the IMediaPosition or IMediaSeeking interface, it creates and aggregates a CPosPassThru helper object.

See Also

CTransformOutputPin Class


CTransformOutputPin::BreakConnect

The BreakConnect method releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseOutputPin::BreakConnect method. It calls the filter's CTransformFilter::BreakConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::BreakConnect method.

See Also

CTransformOutputPin Class


CTransformOutputPin::CheckConnect

The CheckConnect method determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin

Pointer to the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_UNEXPECTED | The filter's input pin is not connected.

Remarks

This method overrides the CBaseOutputPin::CheckConnect method. It calls the filter's CTransformFilter::CheckConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CheckConnect method to perform additional checks.

See Also

CTransformOutputPin Class


CTransformOutputPin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *mtIn
);

Parameters

mtIn

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_INVALIDARG | The filter's input pin is not connected.

Remarks

This method implements the pure virtual CBasePin::CheckMediaType method. The method fails if the filter's input pin is not connected. Otherwise, it calls the filter's CTransformFilter::CheckTransform method, which is also pure virtual. The filter's derived class must implement CheckTransform, which determines if the proposed output media type is compatible with the input media type.

See Also

CTransformOutputPin Class


CTransformOutputPin::CompleteConnect

The CompleteConnect method completes a connection to another pin.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin

Pointer to the other pin's IPin interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseOutputPin::CompleteConnect method. It calls the filter's CTransformFilter::CompleteConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CompleteConnect method to perform additional checks.

See Also

CTransformOutputPin Class


CTransformOutputPin::CTransformOutputPin

Constructor method.

Syntax

CTransformOutputPin(
    TCHAR *pObjectName,
    CTransformFilter *pTransformFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pTransformFilter

Pointer to the filter that created this pin, which must be a CTransformFilter object.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Wide-character string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always Out. For more information, see QueryId.

See Also

CTransformOutputPin Class


CTransformOutputPin::~CTransformOutputPin

Destructor method.

Syntax

~CTransformOutputPin(void);

See Also

CTransformOutputPin Class


CTransformOutputPin::CurrentMediaType

The CurrentMediaType method retrieves the media type for the current pin connection.

Syntax

CMediaType& CurrentMediaType(void);

Return Value

Returns a reference to the CBasePin::m_mt member variable.

See Also

CTransformOutputPin Class


CTransformOutputPin::DecideBufferSize

The DecideBufferSize method sets the buffer requirements.

Syntax

HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
);

Parameters

pAlloc

Pointer to the allocator's IMemAllocator interface.

ppropInputRequest

Pointer an ALLOCATOR_PROPERTIES structure that contains the input pin's buffer requirements.

Return Value

Returns an HRESULT value.

Remarks

This method overrides the CBaseOutputPin::DecideBufferSize method. It calls the filter's pure virtual CTransformFilter::DecideBufferSize method, which the filter's derived class must implement.

See Also

CTransformOutputPin Class


CTransformOutputPin::GetMediaType

The GetMediaType method retrieves a preferred media type, by index value.

Syntax

HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition

Zero-based index value.

pMediaType

Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
VFW_S_NO_MORE_ITEMS | Index out of range

Remarks

This method overrides the CBasePin::GetMediaType method. If the filter's input pin is not connected, the method returns VFW_S_NO_MORE_ITEMS. Otherwise, it calls the filter's CTransformFilter::GetMediaType method to retrieve the media type. The CTransformFilter::GetMediaType method is pure virtual; the filter's derived class must override it.

See Also

CTransformOutputPin Class


CTransformOutputPin::Notify

The Notify method notifies the pin that a quality change is requested. This method implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf

Pointer to the IBaseFilter interface of the filter that delivered the quality control message.

q

Quality structure that contains the quality control message.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_FOUND | Could not find an object to accept the message.

Remarks

This method calls the filter's CTransformFilter::AlterQuality method. If the filter does not handle the quality message, this method calls the CBaseInputPin::PassNotify method on the filter's input pin. The PassNotify method passes the quality message upstream (or to a custom quality manager, if one was installed).

See Also

CTransformOutputPin Class


CTransformOutputPin::QueryId

The QueryId method retrieves an identifier for the pin. This method implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id

Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

The pin identifier is used for graph persistence. The pin identifier for this class is Out. This class overrides the behavior of the CBasePin class. In the CBasePin class, the pin identifier is the same as the pin name, specified in the class constructor. In the CTransformInputPin class, the pin identifier and the pin name are not the same.

See Also

CTransformOutputPin Class


CTransformOutputPin::SetMediaType

The SetMediaType method sets the media type for the connection.

Syntax

HRESULT SetMediaType(
    const CMediaType *mt
);

Parameters

mt

Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method overrides the CBasePin::SetMediaType method. It calls the filter's CTransformFilter::SetMediaType method to inform the filter.

The pin must verify that the media type is acceptable before calling this method.

See Also

CTransformOutputPin Class


CTransInPlaceFilter Class

CTransInPlaceFilter Class Hierarchy

The CTransInPlaceFilter class is designed for in-place transform filters, which are filters that modify the input data rather than copying the data across buffers.To use this class, derive a new class from CTransInPlaceFilter and implement the following methods:

  • CTransformFilter::CheckInputType
  • CTransInPlaceFilter::Transform

This class uses the CTransInPlaceInputPin class for its input pin, and the CTransInPlaceOutputPin class for its output pin. Typically, you do not need to override these pin classes. The filter creates both pins in the CTransInPlaceFilter::GetPin method. If you do override the pin classes, you must override GetPin to create your custom pins.

This class is designed so the input type always matches the output type. Whenever possible, the filter uses a single allocator for both pin connections.

Preferred Media Types

If the output pin is already connected, the input pin offers the downstream filter's preferred types. (In fact it simply returns the downstream filter's enumerator object.) Otherwise, it has no preferred types. The output pin has the same behavior, but in reverse: If the input pin is already connected, the output pin offers the upstream filter's preferred types. Otherwise, it has no preferred types.

Pin Connections

When one pin connects, the filter generally reconnects the other pin, to make sure that both pins use the same media type and the same allocator. (The mechanism for reconnecting pins is described in Reconnecting Pins.) Two scenarios are possible: Either the input pin connects first, or the ouput pin connects first.

Suppose the input pin connects first. The following steps occur:

  1. The input pin calls the filter's CheckInputType method to check the media type.
  2. The upstream filter selects an allocator. At this point, the input pin has no allocator requirements, and it accepts any allocator for the connection. If the upstream filter requests an allocator, the pin creates a new one. For reasons described shortly, this allocator will not be used in the final connection. It is provided only to help finish this stage of the connection process.

Later, when the output pin connects:

  1. The output pin calls the filter's CheckInputType method to check the media type. It also calls IPin::QueryAccept on the upstream filter. This ensures that the input pin can change its media type to match.
  2. The output pin selects an allocator, . It asks the downstream filter for an allocator, but uses the allocator properties from the upstream connection.
  3. The filter reconnects the input pin, using the media type from the output pin.
  4. This time, the input pin's GetAllocator method returns the downstream allocator, and GetAllocatorRequirements returns the downstream filter's allocator requirements. The input pin accepts whatever allocator the upstream filter chooses.
  5. The filter uses the same allocator for the downstream connection.

Now consider the opposite scenario, where the output pin is the first pin to connect.

  1. The output pin calls the filter's CheckInputType method to check the media type.
  2. It selects an allocator, preferring to use the downstream filter's allocator.

Then, when the input pin connects:

  1. The input pin checks the media type by calling CheckInputType on the filter, and by calling QueryAccept on the downstream filter.
  2. If the input type does not match the output type, the filter reconnects the output pin.
  3. The upstream filter selects an allocator. The input pin's GetAllocator method returns the downstream allocator, and the input pin accepts whatever allocator the upstream filter selects.
  4. The filter uses the same allocator for the downstream connection, possibly overriding the original downstream allocator.

This sequence of events changes slightly if any of the allocators involved are read-only, because the downstream allocator must be writable. In that case, the filter might use two separate allocators.

Requirements

Header: Declared in Transip.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Methods |
Copy | Copies a media sample.
InputPin | Retrieves a pointer to the filter's input pin.
OutputPin | Retrieves a pointer to the filter's output pin.
TypesMatch | Determines whether the input media type matches the output media type.
UsingDifferentAllocators | Determines whether the input and output pins are using different allocators.
Public Methods |
CTransInPlaceFilter | Constructor method.
GetPin | Retrieves a pin.
GetMediaType | Retrieves a preferred media type for the output pin.
DecideBufferSize | Sets the output pin's buffer requirements.
CheckTransform | Checks whether an input media type is compatible with an output media type.
CompleteConnect | Completes a pin connection.
Receive | Receives a media sample, processes it, and delivers it to the downstream filter.
Pure Virtual Methods |
Transform | Transforms a sample in place.


CTransInPlaceFilter::CheckTransform

The CheckTransform method checks whether an input media type is compatible with an output media type. This method overrides the CTransformFilter::CheckTransform method.

Syntax

HRESULT CheckTransform(
    const CMediaType *mtIn,
    const CMediaType *mtOut
);

Parameters

mtIn

Pointer to a CMediaType object that specifies the input type.

mtOut

Pointer to a CMediaType object that specifies the output type.

Return Value

Returns S_OK.

Remarks

The CTransInPlace filter never calls CheckTransform. Instead, all pin connection use CTransformFilter::CheckInputType to check the media type, with the assumption that the input and output types always match.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::CompleteConnect

The CompleteConnect method completes a pin connection.

Syntax

HRESULT CompleteConnect(
    PIN_DIRECTION direction,
    IPin *pReceivePin
);

Parameters

direction

Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.

pReceivePin

Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns an HRESULT. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in a filter graph.

Remarks

This method overrides the CTransformFilter::CompleteConnect method.

The behavior of the filter depends on the order of the pin connections:

  • If the input pin is connected first, the connection uses a temporary allocator. When the output pin is connected, the filter reconnects the input pin. Reconnecting the input pin causes the upstream filter to renegotiate the allocator. At that point, the input pin proposes an allocator from the downstream filter. For more information, see CTransInPlaceInputPin::GetAllocator.
  • If the output pin is connected first, the output pin does not select an allocator. When the input pin is connected, it negotiates an allocator for both connections. If the input and output media types are not the same, the filter reconnects the output pin using the input type.

The filter performs all pin reconnections by calling the CBaseFilter::ReconnectPin method. The ReconnectPin method, in turn, calls the IFilterGraph2::ReconnectEx method on the filter graph manager.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::Copy

The Copy method copies a media sample.

Syntax

IMediaSample *CTransInPlaceFilter::Copy(
    IMediaSample *pSource
);

Parameters

pSource

Pointer to the IMediaSample interface of the sample.

Return Value

Returns a pointer to the IMediaSample interface on the new sample.

Remarks

This method retrieves an empty buffer from the downstream allocator. It copies all of the sample properties from pSource into the new sample, along with the actual data in the sample. If the filter is using two allocators, it calls this method to copy data across buffers.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::CTransInPlaceFilter

Constructor method.

Syntax

CTransInPlaceFilter(
    TCHAR *pObjectName,
    LPUNKNOWN lpUnk,
    REFCLSID clsid,
    HRESULT *phr,
    bool bModifiesData = true
);

Parameters

pObjectName

String containing the debug name of the filter. For more information, see CBaseObject.

lpUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

clsid

Class identifier of the filter.

phr

Ignored.

bModifiesData

Boolean value that specifies whether the filter modifies the input data. If TRUE, the filter modifies the data. Otherwise, the filter passes the data downstream unchanged.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::DecideBufferSize

The DecideBufferSize method sets the output pin's buffer requirements.

Syntax

HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *pProperties
);

Parameters

pAlloc

Pointer to the IMemAllocator object used by the output pin.

pProperties

Pointer to the requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_FAIL | Failure

Remarks

This method is called when the CTransInPlaceFilter class needs to provide a buffer size to the downstream filter. If the CTransInPlaceFilter filter is already connected upstream, it uses the allocator properties on the upstream pin connection. Otherwise, it sets the buffer size to 1 byte as a temporary place-holder value. When the upstream filter connects, the CTransInPlaceFilter class renegotiates the downstream allocator. For more information about the pin connection process in this class, see CTransInPlaceFilter Class.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::GetMediaType

The GetMediaType method retrieves a preferred media type for the output pin.

Syntax

HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition

Zero-based index value.

pMediaType

Pointer to a CMediaType object that receives the media type.

Return Value

Returns E_UNEXPECTED.

Remarks

This method overrides the CTransformFilter::GetMediaType method. In the CTransInPlaceFilter class, each pin calls the opposite connected pin to enumerate preferred media types. The input pin calls the downstream filter's input pin, and the output pin calls the upstream filter's output pin. Therefore, the filter's GetMediaType method is never called.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::GetPin

The GetPin method retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n

Number of the specified pin, indexed from zero. On this filter, pin 0 is the input pin, and pin 1 is the output pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin, or NULL if the method fails.

Remarks

This method overrides the CTransformFilter::GetPin method. The first time the method is called, it creates both pins.

This method does not increment the reference count on the returned pin, so the returned pin does not have an outstanding reference count. If the caller needs to keep a reference on the pin, it should call the IUnknown::AddRef method on the pin.

If the filter uses the default CTransInPlaceInputPin and CTransInPlaceOutputPin pins, you probably do not need to override this method. If the filter uses pins that extend those classes, however, you must override this method to create pins of that type.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::InputPin

The InputPin method retrieves a pointer to the filter's input pin.

Syntax

CTransInPlaceInputPin *InputPin(void);

Return Value

Returns the CTransformFilter::m_pInput member variable.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::OutputPin

The OutputPin method retrieves a pointer to the filter's output pin.

Syntax

CTransInPlaceOutputPin *OutputPin(void);

Return Value

Returns the CTransformFilter::m_pOutput member variable.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::Receive

The Receive method receives a media sample, processes it, and delivers it to the downstream filter.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface on the sample.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_UNEXPECTED | Unexpected error

Remarks

The filter's input pin calls this method when it receives a sample. The filter calls the Transform method, which the derived class must implement. The Transform method processes the data. If the filter is using only one allocator, it passes pSample directly to the Tranform method. Otherwise, it copies pSample and passes the copy.

If the Transform method returns S_FALSE, the Receive method drops the sample. On the first dropped sample, the filter sends an EC_QUALITY_CHANGE event to the filter graph manager. Otherwise, if the Transform method returns S_OK, the filter delivers the output sample. To do so, it calls the IMemInputPin::Receive method on the downstream input pin.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::Transform

The Transform method transforms a sample in place.

Syntax

virtual HRESULT Transform(
    IMediaSample *pSample
) PURE;

Parameters

pSample

Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_FALSE | Do not deliver this sample.
S_OK | Success.

Remarks

The derived class must implement this method. Transform the sample data in place. If the filter is using two allocators, it copies the data from the input sample to a new sample, and passes the copy to this method.

If the filter should not deliver this sample (for example, to support quality control), the method should return S_FALSE.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::TypesMatch

The TypesMatch method determines whether the input media type matches the output media type.

Syntax

BOOL TypesMatch(void);

Return Value

Returns TRUE if the input and output media types are the same, or FALSE otherwise.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceFilter::UsingDifferentAllocators

The UsingDifferentAllocators method determines whether the input and output pins are using different allocators.

Syntax

BOOL UsingDifferentAllocators(void) const;

Return Value

Returns TRUE if the input and output pins are using different allocators, or FALSE otherwise.

See Also

  • CTransInPlaceFilter Class


CTransInPlaceInputPin Class

CTransInPlaceInputPin Class Hierarchy

The CTransInPlaceInputPin class implements an input pin that is used by the CTransInPlaceFilter class.

Typically, you do not need to derive from this class. If you do, you must override the filter's CTransInPlaceFilter::GetPin method to create instances of your derived class.

Requirements

Header: Declared in Transip.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_bReadOnly | Flag that specifies whether the input stream is read-only.
m_pTIPFilter | Pointer to the filter that created this pin.
Public Methods |
CTransInPlaceInputPin | Constructor method.
CheckMediaType | Determines if the pin accepts a specific media type.
PeekAllocator | Retrieves a pointer to the pin's allocator.
ReadOnly | Indicates whether the input stream is read-only.
IPin Methods |
EnumMediaTypes | Enumerates the pin's preferred media types.
IMemInputPin Methods |
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves the allocator properties requested by the pin.


CTransInPlaceInputPin::m_bReadOnly

Flag that specifies whether the input stream is read-only. The upstream filter specifies this information when it calls the NotifyAllocator method. By default, the value is FALSE.

Syntax

BOOL m_bReadOnly;

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::m_pTIPFilter

Pointer to the filter that created this pin.

Syntax

CTransInPlaceFilter * const m_pTIPFilter;

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

This method overrides the CTransformInputPin::CheckMediaType method. It calls the filter's CTransformFilter::CheckInputType method to check the input type. If the output pin is connected, this method also calls the IPin::QueryAccept method on the downstream input pin.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::CTransInPlaceInputPin

Constructor method.

Syntax

CTransInPlaceInputPin(
    TCHAR *pObjectName,
    CTransInPlaceFilter *pFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin, which must be a CTransInPlaceFilter object.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Wide-character string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, this string is not used for the pin identifier. The pin identifier for this class is always In. For more information, see CTransformInputPin::QueryId.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::EnumMediaTypes

The EnumMediaTypes method enumerates the pin's preferred media types. This method implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer.
VFW_E_NOT_CONNECTED | The output pin is not connected.

Remarks

This method returns the IEnumMediaTypes interface from downstream input pin.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::GetAllocator

The GetAllocator method retrieves the memory allocator proposed by this pin. This method implements the IMemInputPin::GetAllocator method.

Syntax

HRESULT GetAllocator(
    IMemAllocator **ppAllocator
);

Parameters

ppAllocator

Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_NO_ALLOCATOR | No allocator is available.

Remarks

If the filter's output pin is connected, this method requests an allocator from the downstream filter's input pin.

If the filter's output pin is not connected, this method creates a temporary allocator. Later, when the output pin is connected, the filter will reconnect the input pin and renegotiate the allocator.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::GetAllocatorRequirements

The GetAllocatorRequirements method retrieves the allocator properties requested by the pin. This method implements the IMemInputPin::GetAllocatorRequirements method.

Syntax

HRESULT GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

Pointer to an ALLOCATOR_PROPERTIES structure, which is filled in with the requirements.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_NOTIMPL | The output pin is not connected, or the downstream input pin does not support the method.
E_POINTER | Null pointer argument.

Remarks

If the output pin is connected, this method passes the call to the downstream input pin. Otherwise, it returns E_NOTIMPL.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::NotifyAllocator

The NotifyAllocator method specifies an allocator for the connection. This method implements the IMemInputPin::NotifyAllocator method.

Syntax

HRESULT NotifyAllocator(
    IMemAllocator *pAllocator,
    BOOL bReadOnly
);

Parameters

pAllocator

Pointer to the allocator's IMemAllocator interface.

bReadOnly

Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success
E_FAIL | Failure
E_POINTER | NULL pointer argument

Remarks

The filter attempts to use the same allocator for both pin connections.

  • If the output pin is not connected, the input pin automatically accepts the allocator. When the output pin is connected, the filter will reconnect the input pin. At that point, the filter will try again to use a single allocator.
  • If the output pin is connected, the input pin accepts the allocator. The output pin also uses the same allocator. It calls NotifyAllocator on the downstream input pin.

The previous case has the following exception:

  • If the proposed allocator is read-only (that is, the bReadOnly parameter is TRUE) and the filter needs to modify the samples, then the filter must use two different allocators. In this case, if the upstream filter is proposing to use the downstream filter's allocator, the method returns E_FAIL.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::PeekAllocator

The PeekAllocator method retrieves a pointer to the pin's allocator. The method does not increment the reference count on the interface.

Syntax

IMemAllocator *PeekAllocator(void)

Return Value

Returns the CBaseInputPin::m_pAllocator member variable.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceInputPin::ReadOnly

The ReadOnly method indicates whether the input stream is read-only.

Syntax

const BOOL ReadOnly(void);

Return Value

Returns the value of the m_bReadOnly member variable.

See Also

  • CTransInPlaceInputPin Class


CTransInPlaceOutputPin Class

CTransInPlaceOutputPin Class Hierarchy

The CTransInPlaceOutputPin class implements an output pin that is used by the CTransInPlaceFilter class.

Typically, you do not need to derive from this class. If you do, you must override the filter's CTransInPlaceFilter::GetPin method to create instances of your derived class.

Requirements

Header: Declared in Transip.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Protected Member Variables |
m_pTIPFilter | Pointer to the filter that created this pin.
Public Methods |
CTransInPlaceOutputPin | Constructor method.
CheckMediaType | Determines if the pin accepts a specific media type.
SetAllocator | Specifies an allocator for the connection.
ConnectedIMemInputPin | Retrieves a pointer to the downstream input pin.
PeekAllocator | Retrieves a pointer to the pin's allocator.
IPin Methods |
EnumMediaTypes | Enumerates the pin's preferred media types.


CTransInPlaceOutputPin::m_pTIPFilter

Pointer to the filter that created this pin.

Syntax

CTransInPlaceFilter * const m_pTIPFilter;

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::CheckMediaType

The CheckMediaType method determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt

Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
VFW_E_TYPE_NOT_ACCEPTED | Media type not accepted.

Remarks

This method overrides the CTransformOutputPin::CheckMediaType method.

If the filter is already streaming and is using two allocators, this method rejects any format changes. Otherwise, this method calls the filter's CTransformFilter::CheckInputType method to check the media type. If the input pin is connected, it also calls the IPin::QueryAccept method on the upstream output pin.

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::ConnectedIMemInputPin

The ConnectedIMemInputPin method retrieves a pointer to the downstream input pin. This method returns the CBaseOutputPin::m_pInputPin member variable.

Syntax

IMemInputPin *ConnectedIMemInputPin(void);

Return Value

Returns a pointer to the IMemInputPin interface on the downstream input pin.

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::CTransInPlaceOutputPin

Constructor method.

Syntax

CTransInPlaceOutputPin(
    TCHAR *pObjectName,
    CTransInPlaceFilter *pFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName

String containing the debug name of the object. For more information, see CBaseObject.

pFilter

Pointer to the filter that created this pin, which must be a CTransInPlaceFilter object.

phr

Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.

pName

Wide-character string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always Out. For more information, see QueryId.

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::EnumMediaTypes

The EnumMediaTypes method enumerates the pin's preferred media types. This method implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum

Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer.
VFW_E_NOT_CONNECTED | The filter's input pin is not connected.

Remarks

This method returns the IEnumMediaTypes interface from the upstream output pin.

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::PeekAllocator

The PeekAllocator method retrieves a pointer to the pin's allocator. The method does not increment the reference count on the interface.

Syntax

IMemAllocator *PeekAllocator(void)

Return Value

Returns the CBaseOutputPin::m_pAllocator member variable.

See Also

  • CTransInPlaceOutputPin Class


CTransInPlaceOutputPin::SetAllocator

The SetAllocator method specifies an allocator for the connection.

Syntax

void SetAllocator(
    IMemAllocator *pAllocator
);

Parameters

pAllocator

Pointer to the allocator's IMemAllocator interface.

Remarks

The output pin for this filter never provides an allocator. This method specifies the allocator for the output pin. It sets the value of the CBaseOutputPin::m_pAllocator member variable.

See Also

  • CTransInPlaceOutputPin Class


CUnknown Class

CUnknown Class Hierarchy

The CUnknown object implements the IUnknown interface. Most Component Object Model (COM) objects in Microsoft® DirectShow® derive from CUnknown.

If you implement a COM object, you might want to derive it from CUnknown. Deriving from CUknown provides a thread-safe implementation, and saves you the trouble of implementing IUnknown.

For a detailed discussion of how to use this base class, see How to Implement IUnknown. What follows is a brief summary:

  • Include the DECLARE_IUNKNOWN macro in the public section of your class definition. This macro declares the three methods of the IUnknown interface.
  • Override the NonDelegatingQueryInterface method to support interfaces other than IUnknown. Within this method, call the GetInterface function to retrieve interface pointers.
  • In your class constructor, invoke the CUnknown constructor method.

Requirements

Header: Declared in Combase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

  • Protected Member Variables
    m_cRef | Reference count.
    Public Methods
    CUnknown | Constructor method.
    ~CUnknown | Destructor method. Virtual.
    GetOwner | Retrieves a pointer to the controlling IUnknown.
    INonDelegatingUnknown Methods
    NonDelegatingAddRef | Increments the reference count.
    NonDelegatingQueryInterface | Retrieves an interface pointer and increments the reference count.
    NonDelegatingRelease | Decrements the reference count.


CUnknown::m_cRef

Reference count.

Syntax

volatile LONG m_cRef;

Remarks

Use this member variable if you override the NonDelegatingAddRef or NonDelegatingRelease method.

See Also

CUnknown Class


CUnknown::CUnknown

Constructor method.

Syntax

CUnknown(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

Parameters

pName

String containing the name of the object; used in the CBaseObject constructor for debugging.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

Remarks

The object is initialized with a reference count of zero.

See Also

CUnknown Class


CUnknown::~CUnknown

Destructor method.

Syntax

virtual ~CUnknown(void);

See Also

CUnknown Class


CUnknown::GetOwner

The GetOwner method retrieves a pointer to the IUnknown interface of the owning component. For an aggregated component, the owner is the outer component. Otherwise, the component owns itself.

Syntax

LPUNKNOWN GetOwner(void);

Return Value

Returns a pointer to the controlling IUnknown interface.

See Also

CUnknown Class


CUnknown::NonDelegatingAddRef

The NonDelegatingAddRef method increments the reference count on the object. This method implements the INonDelegatingUnknown::NonDelegatingAddRef method.

Syntax

ULONG NonDelegatingAddRef(void);

Return Value

Returns the reference count.

See Also

CUnknown Class


CUnknown::NonDelegatingQueryInterface

Retrieves an interface pointer and increments the reference count. This method implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
);

Parameters

riid

Identifier of the interface.

ppv

Address of a pointer to receive the interface.

Return Value

Returns one of the HRESULT values shown in the following table.

Value | Description
S_OK | Success.
E_NOINTERFACE | Object does not support this interface.
E_POINTER | NULL pointer argument.

Remarks

The CUnknown class exposes only the IUknown interface. Override this method to expose additional interfaces. For information on how to override this method, see How to Implement IUnknown.

See Also

CUnknown Class


CUnknown::NonDelegatingRelease

Decrements the reference count on the object. This method implements the INonDelegatingUnknown::NonDelegatingRelease method.

Syntax

ULONG NonDelegatingRelease(void);

Return Value

Returns the reference count.

Remarks

When the reference count reaches zero, the object deletes itself.

See Also

CUnknown Class


CVideoTransformFilter Class

CVideoTransformFilter Class Hierarchy

The CVideoTransformFilter class is designed primarily as a base class for AVI decompressor filters. This class adds support for quality control to the CTransformFilter class. The filter's Receive method can decide to drop frames, based on quality messages from the renderer and performance measurements that the filter collects while it is streaming.

If the filter drops a frame, it continues to drop frames until it reaches the next key frame. For MPEG streams, the filter does not distinguish between B frames and P frames.

Protected Member Variables | Description
m_bQualityChanged | Indicates whether the filter has dropped frames.
m_bSkipping | Indicates whether the filter is currently dropping frames.
m_itrAvgDecode | Average length of time it has taken to decode a frame.
m_itrLate | Indicates how late the samples are arriving at the renderer.
m_nFramesSinceKeyFrame | The number of frames that the filter has received since the last key frame.
m_nKeyFramePeriod | The largest observed interval between key frames.
m_nWaitForKey | The current maximum number of delta frames to drop.
m_tDecodeStart | Length of time that it took to decode the most recent sample.
Protected Methods |
AbortPlayback | Used to signal a streaming error.
AlterQuality | Notifies the filter that a quality change is requested.
Receive | Receives a media sample, processes it, and delivers an output sample to the downstream filter.
ShouldSkipFrame | Determines whether the filter should drop a specified sample.
StartStreaming | Called when the filter switches to the paused state.
Public Methods |
CVideoTransformFilter | Constructor method.
EndFlush | Ends a flush operation.


CVideoTransformFilter::m_bQualityChanged

Boolean value that indicates whether the filter has dropped frames. This member variable controls when the filter sends EC_QUALITY_CHANGE events.

Syntax

BOOL m_bQualityChanged;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_bSkipping

Boolean value that indicates whether the filter is currently dropping frames. If this value is TRUE, the filter continues to drop frames until it reaches the next key frame, or until it receives 30 delta frames in a row without a key frame.

Syntax

BOOL m_bSkipping;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_itrAvgDecode

Average length of time it has taken to decode a frame, over the past 16 samples.

Syntax

int m_itrAvgDecode;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_itrLate

Indicates how late the samples are arriving at the renderer, in reference time units. Syntax

int m_itrLate;

Remarks

When the filter receives a quality message from downstream, it stores the lateness value in this variable. As the filter drops frames, it updates this value by subtracting the duration of each frame.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_nFramesSinceKeyFrame

The number of frames that the filter has received since the last key frame.

Syntax

int m_nFramesSinceKeyFrame;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_nKeyFramePeriod

The largest observed interval between key frames.

Syntax

int m_nKeyFramePeriod;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_nWaitForKey

The current maximum number of delta frames to drop. While this variable is greater than zero, the filter will drop frames until it reaches a key frame. For each frame that is dropped, the filter decrements this variable by one, which prevents the filter from dropping an excessive number of frames. After 30 delta frames in a row with no key frames, the filter will start delivering frames again.

Syntax

int m_nWaitForKey;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::m_tDecodeStart

Length of time that it took to decode the most recent sample, in milliseconds.

Syntax

int m_tDecodeStart;

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::AbortPlayback

The AbortPlayback method is used to signal a streaming error. It sends an EC_ERRORABORT event to the Filter Graph Manager, and sends an end-of-stream notification downstream.

Syntax

HRESULT AbortPlayback(
    HRESULT hr
);

Parameters

hr

HRESULT value of the operation that failed. This value is used as the first event parameter for the EC_ERRORABORT event.

Return Value

Returns the value of the hr parameter.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::AlterQuality

The AlterQuality method notifies the filter that a quality change is requested. This method overrides the CTransformFilter::AlterQuality method.

Syntax

virtual HRESULT AlterQuality(
    Quality q
);

Parameters

q

Quality structure that contains the quality control message.

Return Value

Returns E_FAIL.

Remarks

This method is called when the output pin receives a quality message (through the IQualityControl::Notify method).

The lateness value from q is stored in the m_itrLate member variable. The return value of E_FAIL indicates that the renderer should catch up by dropping frames, although the CVideoTransformFilter class will also drop frames under the right conditions.

See Also

  • CVideoTransformFilter Class
  • CVideoTransformFilter::ShouldSkipFrame


CVideoTransformFilter::CVideoTransformFilter

Constructor method.

Syntax

CVideoTransformFilter(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    REFCLSID clsid
);

Parameters

pName

String containing the debug name of the filter. For more information, see CBaseObject::CBaseObject.

pUnk

Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

clsid

Class identifier of the filter.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::EndFlush

The EndFlush method ends a flush operation. This method overrides the CTransformFilter::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK if successful, or an error code.

Remarks

This method resets all of the filter's internal performance measurements.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::Receive

The Receive method receives a media sample, processes it, and delivers an output sample to the downstream filter. This method overrides the CTransformFilter::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample

Pointer to the IMediaSample interface on the input sample.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | The upstream filter should stop sending samples.
S_OK | Success.

Remarks

This method calls CVideoTransformFilter::ShouldSkipFrame to determine whether it should deliver this sample or simply discard it. If ShouldSkipFrame returns FALSE (indicating the sample should be delivered), the method does the following:

  1. Calls CTransformFilter::InitializeOutputSample to prepare the output sample
  2. Calls CTransformFilter::Transform to process the input sample. This method is pure virtual, and must be implemented in the derived class.
  3. Calls CBaseOutputPin::Deliver to deliver the output sample.

Also, this method checks for format changes on the input or output sample, by calling IMediaSample::GetMediaType. If there is a format change, the method sets the connection type on the corresponding pin. Before it sets the new type, it calls StopStreaming. After it sets the new type, it calls StartStreaming. The derived class can use these methods to update its internal state. The derived class might also need to check for the new format in its Transform method.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::ShouldSkipFrame

The ShouldSkipFrame method determines whether the filter should drop a specified sample.

Syntax

BOOL ShouldSkipFrame(
    IMediaSample *pIn
);

Parameters

pIn

Pointer to the IMediaSample interface of the sample.

Return Value

Returns TRUE if the filter should drop this sample, or TRUE if the filter should process this sample.

Remarks

This method returns TRUE if the following conditions are met:

  • The sample has time stamps.
  • The average decoding time is at least 25% of the frame duration.
  • The renderer is currently at least one frame late, as reported through quality messages.
  • Skipping to the next key frame would not cause the frame to arrive more than one frame early.

For purposes of this calculation, the filter records the following information as it processes data:

  • The average decoding time over the past 20 frames (m_itrAvgDecode)
  • The number of frames since the last key frame (m_nFramesSinceKeyFrame)
  • An estimate of how many frames there are between key frames (m_nKeyFramePeriod)

Once the filter drops a frame, it continues to drop frames until it reaches the next key frame. If this method returns TRUE, it also sends an EC_QUALITY_CHANGE event to the Filter Graph Manager.

See Also

  • CVideoTransformFilter Class


CVideoTransformFilter::StartStreaming

The StartStreaming method is called when the filter switches to the paused state. This method overrides the CTransformFilter::StartStreaming method.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns S_OK.

Remarks

This method resets all of the performance statistics.

See Also

  • CVideoTransformFilter Class


DIBDATA Structure

The DIBDATA structure contains information about a GDI device-independent bitmap (DIB).

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Syntax

typedef struct tagDIBDATA {
    LONG        PaletteVersion;
    DIBSECTION  DibSection;
    HBITMAP     hBitmap;
    HANDLE      hMapping;
    BYTE        *pBase;
} DIBDATA;

Members

PaletteVersion

This member should be incremented whenever the palette changes.

DibSection

DIBSECTION structure that contains information about the DIB. See the GDI documentation for details.

hBitmap

Handle to the bitmap.

hMapping

Handle to a file-mapping object that is used to share memory between GDI and a CImageSample object.

pBase

Address of the bitmap.


FOURCCMap Class

FOURCCMap Class Hierarchy

The FOURCCMap class provides conversion between GUID media subtypes and old-style FOURCC 32-bit media tags. In the original Microsoft® Windows® multimedia APIs, media types were tagged with 32-bit values created from four 8-bit characters and were known as FOURCCs. Microsoft DirectShow® media types have GUIDs for the subtype, partly because these are simpler to create (creation of a new FOURCC requires its registration with Microsoft). Because FOURCCs are unique, a one-to-one mapping has been made possible by allocating a range of 4,000 million GUIDs representing FOURCCs. This range is all GUIDs of the form:

XXXXXXXX-0000-0010-8000-00AA00389B71

This class simplifies conversion between GUIDs and FOURCCs. This is for compatibility only. It is recommended that all new media subtypes be represented by GUIDs created by Guidgen.exe or a similar tool, and not by mapping FOURCCs.

The object is derived from a GUID, with no extra data members, and can be cast to a GUID. The object can be passed a FOURCC at construction time. The default constructor will initialize the FOURCC to zero.

The GetFOURCC and SetFOURCC methods do not check that the fixed portions of the GUID correspond to the FOURCC range. Thus, if you cast a pointer to a GUID into a pointer to a FOURCC and then set or get the FOURCC field, you also need to check separately that the GUID is within the FOURCC range.

Member Functions

FOURCCMap | Constructor method.
GetFOURCC | Retrieves the FOURCC from a FOURCCMap object.
SetFOURCC | Sets the FOURCC portion of the FOURCCMap object.


FOURCCMap::FOURCCMap

Constructor method. The constuctor provides the mapping between old-style multimedia format DWORD types and new-style GUID types.

Syntax

FOURCCMap( );

FOURCCMap(
  DWORD Fourcc
);

FOURCCMap(
  const GUID *pguid
);

Parameters

Fourcc

DWORD that specifies the FOURCC.

pguid

Pointer to the globally unique identifier (GUID).

Return Value

No return value.

Remarks

If this object is constructed with the FOURCC code, a GUID is created to match it. If this object is created with an existing GUID, the FOURCC value of the object is set to zero. Thereafter, the FOURCC value can be set or retrieved using the SetFOURCC and GetFOURCC member functions, respectively.

See Also

  • FOURCCMap Class


FOURCCMap::GetFOURCC

Retrieves the FOURCC DWORD from the FOURCCMap object.

Syntax

DWORD GetFOURCC(void);

Return Value

Returns the FOURCC DWORD value. Note that if you construct a GUID that was not originally derived from FOURCC, the return value will be essentially random.

See Also

  • FOURCCMap Class


FOURCCMap::SetFOURCC

Sets the FOURCC portion of the FOURCCMap object.

Syntax

void SetFOURCC(
  const GUID *pguid
);

Parameters

pguid

Pointer to the returned globally unique identifier (GUID) part of the FOURCCMap object.

Return Value

No return value.

See Also

  • FOURCCMap Class


Utility Functions

This section contains reference entries for the Microsoft® DirectShow® utility functions and macros. To use these functions, you must build the DirectShow base-class library.

  • COM Helper Functions
  • DLL Setup Functions
  • Media Type Functions
  • Miscellaneous Helper Functions
  • Property Page Helper Functions
  • Video and Image Functions

See Also

  • Using the DirectShow Base Classes


COM Helper Functions

These functions provide support for implementing the IUnknown interface.

Requirements

Header: Declared in Combase.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
DECLARE_IUNKNOWN | Declares the three methods of the base interface for a new interface.
GetInterface | Retrieves an interface pointer to the requested client.
INonDelegatingUnknown | Nondelegating version of the IUnknown interface.
LoadOLEAut32 | Loads the Automation DLL (OleAut32.dll).


DECLARE_IUNKNOWN

The DECLARE_IUNKNOWN macro declares the three methods of the base interface for a new interface.

Syntax

#define DECLARE_IUNKNOWN                                        \
    STDMETHODIMP QueryInterface(REFIID riid, void **ppv) {      \
        return GetOwner()->QueryInterface(riid,ppv);            \
    };                                                          \
    STDMETHODIMP_(ULONG) AddRef() {                             \
        return GetOwner()->AddRef();                            \
    };                                                          \
    STDMETHODIMP_(ULONG) Release() {                            \
        return GetOwner()->Release();                           \
    };

Remarks

When you create a new interface, it must derive from IUnknown, which has three methods: QueryInterface, AddRef, and Release. This macro simplifies the declaration process by declaring each of these methods for the new interface.

See Also

  • COM Helper Functions
  • CUnknown::GetOwner


GetInterface

The GetInterface function retrieves an interface pointer.

Syntax

HRESULT GetInterface(
    LPUNKNOWN pUnk,
    void **ppv
);

Parameters

pUnk

Pointer to the IUnknown interface.

ppv

Address of a pointer to the retrieved interface.

Return Value

Returns an HRESULT value.

Remarks

This member function performs a thread-safe increment of the reference count. To retrieve the interface and add a reference, call this function from your overriding implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method.

See Also

  • COM Helper Functions
  • INonDelegatingUnknown


INonDelegatingUnknown

The INonDelegatingUnknown interace is a version of IUnknown that is renamed to enable support for both nondelegating and delegating IUnknown interfaces in the same COM object.

Syntax

interface INonDelegatingUnknown
{
    virtual HRESULT NonDelegatingQueryInterface) (REFIID riid, LPVOID *ppv) PURE;
    virtual ULONG NonDelegatingAddRef)(void) PURE;
    virtual ULONG NonDelegatingRelease)(void) PURE;
};

Remarks

To use INonDelegatingUnknown for multiple inheritance, perform the following steps.

  1. Derive your class from an interface, for example, IMyInterface.
  2. Include DECLARE_IUNKNOWN in your class definition to declare implementations of QueryInterface, AddRef, and Release that call the outer unknown.
  3. Override NonDelegatingQueryInterface to expose IMyInterface with code such as the following:
         if (riid == IID_IMyInterface) {
         return GetInterface((IMyInterface *) this, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }
  4. Declare and implement the member functions of IMyInterface.

To use INonDelegatingUnknown for nested interfaces, perform the following steps:

  1. Declare a class derived from CUnknown.
  2. Include DECLARE_IUNKNOWN in your class definition.
  3. Override NonDelegatingQueryInterface to expose IMyInterface with the code such as the following:
         if (riid == IID_IMyInterface) {
         return GetInterface((IMyInterface *) this, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }
  4. Implement the member functions of IMyInterface. Use CUnknown::GetOwner to access the COM object class.
  5. In your COM object class, make the nested class a friend of the COM object class, and declare an instance of the nested class as a member of the COM object class.

Because you must always pass the outer unknown and an HRESULT to the CUnknown constructor, you can't use a default constructor. You have to make the member variable a pointer to the class and make a new call in your constructor to actually create it.

Override the NonDelegatingQueryInterface with code such as the following:

     if (riid == IID_IMyInterface) {
         return m_pImplFilter->
            NonDelegatingQueryInterface(IID_IMyInterface, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }

You can have mixed classes that support some interfaces through multiple inheritance and some interfaces through nested classes.

See Also

  • COM Helper Functions


LoadOLEAut32

The LoadOLEAut32 function loads the Automation dynamic-link library (OleAut32.dll).

Syntax

HINSTANCE LoadOLEAut32(void);

Return Value

Returns a handle to an Automation DLL instance.

Remarks

When the CBaseObject destructor destroys the object that loaded OleAut32.dll, it will unload the library if it is still loaded.

See Also

  • COM Helper Functions


DLL Setup Functions

These functions register a filter.

Requirements

Header: Declared in Dllsetup.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
AMovieDllRegisterServer | Obsolete.
AMovieDllRegisterServer2 | Registers and unregisters filters.
AMovieDllUnregisterServer | Obsolete.
AMovieSetupRegisterFilter | Obsolete.
AMovieSetupRegisterFilter2 | Registers a filter's merit, pins, and media types.


AMovieDllRegisterServer

Obsolete. Use AMovieDllRegisterServer2 instead.

Syntax

HRESULT AMovieDllRegisterServer(void);

See Also

  • DLL Setup Functions


AMovieDllRegisterServer2

The AMovieDllRegisterServer2 function registers and unregisters filters.

Syntax

HRESULT AMovieDllRegisterServer2(
    BOOL bRegister
);

Parameters

bRegister

TRUE indicates register the filter, FALSE indicates unregister it.

Return Value

Returns S_OK if the method succeeds, or an HRESULT error code.

Remarks

Use this function to set up your filters. For more information, see How to Register DirectShow Filters.

See Also

  • DLL Setup Functions


AMovieDllUnregisterServer

Obsolete. Use AMovieDllRegisterServer2 instead.

Syntax

HRESULT AMovieDllUnregisterServer(void);

See Also

  • DLL Setup Functions


AMovieSetupRegisterFilter

Obsolete. Use AMovieSetupRegisterFilter2 instead.

Syntax

HRESULT AMovieSetupRegisterFilter(
    const AMOVIESETUP_FILTER const *psetupdata,
    IFilterMapper *pIFM,
    BOOL bRegister
);

See Also

  • DLL Setup Functions


AMovieSetupRegisterFilter2

The AMovieSetupRegisterFilter2 function registers a filter's merit, pins, and media types in the registry using the IFilterMapper2 interface.

Syntax

HRESULT AMovieSetupRegisterFilter2(
    const AMOVIESETUP_FILTER const *psetupdata,
    IFilterMapper2 *pIFM2,
    BOOL bRegister
);

Parameters

psetupdata

Pointer to the AMOVIESETUP_FILTER data.

pIFM

Pointer to IFilterMapper2 interface.

bRegister

Value indicating whether to register the filter; TRUE indicates register the filter, FALSE indicates unregister it.

Return Value

Returns S_OK if the method succeeds, or an HRESULT error code.

Remarks

AMovieDllRegisterServer2 uses this helper function to register a filter after the COM server has been registered.

Typically, a filter will use AMovieDllRegisterServer2 and will not call this function directly.

See Also

  • DLL Setup Functions


Media Type Functions

The DirectShow base classes provides helper functions for handling the AM_MEDIA_TYPE structure.

The AM_MEDIA_TYPE structure contains a pointer (the pbFormat member) to another block of memory, which is called the format block. When you work with this structure, therefore, you must be careful about memory allocation in order to avoid memory leaks.

The following functions allocate memory:

  • CreateMediaType allocates a new AM_MEDIA_TYPE structure and the format block.
  • CopyMediaType copies to an existing AM_MEDIA_TYPE structure, but allocates the format block.
  • CreateAudioMediaType initializes an existing AM_MEDIA_TYPE structure, and optionally allocates the format block.

The following functions free memory:

  • FreeMediaType releases the format block.
  • DeleteMediaType frees an AM_MEDIA_TYPE structure, including the format block.

Requirements

Header: Declared in Mtype.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
CopyMediaType | Copies a task-allocated AM_MEDIA_TYPE structure.
CreateAudioMediaType | Initializes a media type structure given a wave format structure.
CreateMediaType | Allocates and initializes an AM_MEDIA_TYPE structure, from an existing AM_MEDIA_TYPE structure.
DeleteMediaType | Deletes a task-allocated AM_MEDIA_TYPE structure.
FreeMediaType | Frees a task-allocated AM_MEDIA_TYPE structure from memory.


CopyMediaType

The CopyMediaType function copies an AM_MEDIA_TYPE structure into another structure, including the format block

Syntax

HRESULT WINAPI CopyMediaType(
    AM_MEDIA_TYPE *pmtTarget,
    const AM_MEDIA_TYPE *pmtSource
);

Parameters

pmtTarget

Pointer to an AM_MEDIA_TYPE structure. The method copies the media type into this structure.

pmtSource

Pointer to a source AM_MEDIA_TYPE structure to copy.

Return Value

Returns S_OK or E_OUTOFMEMORY.

Remarks

This function allocates the memory for the format block. If the pmtTarget parameter already contains an allocated format block, a memory leak will occur. To avoid a memory leak, call FreeMediaType before calling this function.

After the method returns, call FreeMediaType on pmtTarget to free the format block.

See Also

  • Media Type Functions


CreateAudioMediaType

The CreateAudioMediaType function initializes a media type from a WAVEFORMATEX structure.

Syntax

STDAPI CreateAudioMediaType(
    const WAVEFORMATEX *pwfx,
    AM_MEDIA_TYPE *pmt,
    BOOL bSetFormat
);

Parameters

pwfx

Pointer to the supplied WAVEFORMATEX structure.

pmt

Pointer to the AM_MEDIA_TYPE structure to initialize.

bSetFormat

Flag indicating whether to initialize the format block. Specify TRUE to initialize it, or FALSE otherwise.

Return Value

Returns E_OUTOFMEMORY if memory could not be allocated for the format data; S_OK otherwise.

Remarks

If the bSetFormat parameter is TRUE, the method allocates the memory for the format block. If the pmt parameter already contains an allocated format block, a memory leak will occur. To avoid a memory leak, call FreeMediaType before calling this function. After the method returns, call FreeMediaType again to free the format block.

See Also

  • Media Type Functions


CreateMediaType

The CreateMediaType function allocates a new AM_MEDIA_TYPE structure, including the format block.

Syntax

AM_MEDIA_TYPE * WINAPI CreateMediaType(
    AM_MEDIA_TYPE const *pSrc
);

Parameters

pSrc

Pointer to an AM_MEDIA_TYPE structure. The method copies this structure into the new structure.

Return Value

Returns a new AM_MEDIA_TYPE structure, or NULL if there is an error.

Remarks

To free the memory allocated by this function, call DeleteMediaType.

See Also

  • Media Type Functions


DeleteMediaType

The DeleteMediaType function deletes an allocated AM_MEDIA_TYPE structure, including the format block.

Syntax

void WINAPI DeleteMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to an AM_MEDIA_TYPE structure.

Return Value

No return value.

Remarks

Use this function to release any media type structure that was allocated using either CoTaskMemAlloc or CreateMediaType.

If you prefer not to link to the base class library, you can use the following code directly:

void MyDeleteMediaType(AM_MEDIA_TYPE *pmt)
{
    if (pmt != NULL)
    {
        MyFreeMediaType(*pmt); // See FreeMediaType for the implementation.
        CoTaskMemFree(pmt);
    }
}

See Also

  • FreeMediaType
  • Media Type Functions


FreeMediaType

The FreeMediaType function frees the format block in an AM_MEDIA_TYPE structure.

Syntax

void WINAPI FreeMediaType(
    AM_MEDIA_TYPE& mt
);

Parameters

mt

Reference to an AM_MEDIA_TYPE structure.

Return Value

No return value.

Remarks

Use this function to free just the format block. To delete an allocated AM_MEDIA_TYPE structure, call DeleteMediaType.

If you prefer not to link to the base class library, you can use the following code directly:

void MyFreeMediaType(AM_MEDIA_TYPE& mt)
{
    if (mt.cbFormat != 0)
    {
        CoTaskMemFree((PVOID)mt.pbFormat);
        mt.cbFormat = 0;
        mt.pbFormat = NULL;
    }
    if (mt.pUnk != NULL)
    {
        // Unecessary because pUnk should not be used, but safest.
        mt.pUnk->Release();
        mt.pUnk = NULL;
    }
}

See Also

  • Media Type Functions


Miscellaneous Helper Functions

The following are some miscellaneous helper functions.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
EqualPins | Checks if two pins are on the same object.
Int64x32Div32 | Implements the formula ((a*b)+rnd)/c where a is a 64-bit value and b, c, and rnd are 32-bit values.
IsEqualObject | Checks if two interfaces are on the same object.
llMulDiv | Implements the formula ((a*b)+rnd)/c where each term is a 64-bit value.
WaitDispatchingMessages | Waits for an object to be signaled, while dispatching window messages.


EqualPins

The EqualPins function checks if two pins are on the same object.

Syntax

BOOL EqualPins(
    IUnknown *pPin1,
    IUnknown *pPin2
);

Parameters

pPin1

Pointer to one pin.

pPin2

Pointer to the other pin.

Return Value

Returns TRUE if both pins are on the same object, or FALSE otherwise.

See Also

  • Miscellaneous Helper Functions


Int64x32Div32

The Int64x32Div32 function implements the formula ((a*b)+rnd)/c where a is a 64-bit value and b, c, and rnd are 32-bit values.

Time stamps and seek times are 64-bit values, so this function is useful for performing conversions on 32-bit systems. For example, in MPEG-1 the system clock reference is 90-kHz, or 90,000 ticks per second. The formula to convert this to reference time (100-nanosecond units) is

(timestamp * 1000) / 9

which can be calculated as Int64x32Div32(timestamp, 1000, 9, 0). Use the rnd parameter as a rounding factor.

Syntax

LONGLONG WINAPI Int64x32Div32(
  LONGLONG a,
  LONG b,
  LONG c,
  LONG rnd
);

Return Value

Returns either the (a * b + rnd)/c calculation or one of the following values.

0x7FFFFFFFFFFFFFFF | Overflow occurred because the result is too large (positive).
0x8000000000000000 | Overflow occurred because the result is too large (negative).

Remarks

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.

See Also

  • Miscellaneous Helper Functions
  • llMulDiv


IsEqualObject

Checks if two interfaces are on the same object.

Syntax

BOOL WINAPI IsEqualObject(
    IUnknown *pFirst,
    IUnknown *pSecond
);

Parameters

pFirst

Pointer to one interface.

pSecond

Pointer to the other interface.

Return Value

Returns TRUE if the interfaces are both on the same object, or FALSE otherwise.

See Also

  • Miscellaneous Helper Functions


llMulDiv

The llMulDiv function implements the formula ((a*b)+rnd)/c where each term is a 64-bit value.

Time stamps and seek times are 64-bit values, so this function is useful for performing conversions on 32-bit systems. For example, the formula for bytes-per-second is

(Number of Bytes * Reference Time) / 10,000,000

which can be calculated as llMulDiv(nBytes, rtTime, 10000000, 0). Use the rnd parameter as a rounding factor.

Syntax

LONGLONG WINAPI llMulDiv(
  LONGLONG a,
  LONGLONG b,
  LONGLONG c,
  LONGLONG rnd
);

Return Value

Returns either the (a * b + rnd)/c calculation or one of the following values.

0x7FFFFFFFFFFFFFFF | Overflow occurred because the result is too large (positive).
0x8000000000000000 | Overflow occurred because the result is too large (negative).

Remarks

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.

See Also

  • Miscellaneous Helper Functions
  • Int64x32Div32


WaitDispatchingMessages

The WaitDispatchingMessages function waits for an object to be signaled, while dispatching window messages.

Syntax

DWORD WINAPI WaitDispatchingMessages(
    HANDLE hObject,
    DWORD dwWait,
    HWND hwnd = NULL,
    UINT uMsg = 0
    HANDLE hEvent = NULL
);

Parameters

hObject

Handle of the object to wait for.

dwWait

Time-out interval, in milliseconds.

hwnd

Optional handle to a window.

uMsg

Optional window message, specifying a message to dispatch.

hEvent

Optional handle to an event to wait for.

Return Value

Returns the value from the WaitForMultipleObjects function.

Remarks

If an object owns a window, it should dispatch window messages while waiting. This function enables the object to wait for an event, semaphore, or other mutual exclusion object while dispatching messages.

See Also

  • Miscellaneous Helper Functions


Property Page Helper Functions

The Videoctl.h header file in the Microsoft® DirectShow® base classes provides functions to help with property page implementations.

Function | Description
GetDialogSize | Retrieves the size of a resource dialog box in screen pixels.
StringFromResource | Loads a string from a resource file with the given resource identifier.
WideStringFromResource | Loads a wide-character string from a resource file with the given resource identifier.


GetDialogSize

The GetDialogSize function retrieves the size of a resource dialog box.

Syntax

BOOL WINAPI GetDialogSize(
    int iResourceID,
    DLGPROC pDlgProc,
    LPARAM lParam,
    SIZE *pResult
);

Parameters

iResourceID

Dialog box resource identifier.

pDlgProc

Pointer to the dialog box procedure.

lParam

Value passed in the WM_INITDIALOG message sent to the temporary dialog box just after it is created.

pResult

Pointer to a SIZE structure that receives the dimensions of the dialog box, in screen pixels.

Return Value

Returns TRUE if the dialog box resource was found, or FALSE otherwise.

Remarks

Property pages can use this function to return the actual display size they require. Most property pages are dialog boxes and, as such, have dialog box templates stored in resource files. Templates use dialog box units that do not map directly onto screen pixels. However, a property page's GetPageInfo function must return the actual display size in pixels. The property page can call GetDialogSize to calculate the display size.

This function creates a temporary instance of the dialog box. To avoid having the dialog box appear on the screen, the dialog box template in the resource file should not have a WS_VISIBLE property.

See Also

  • Property Page Helper Functions


StringFromResource

The StringFromResource function loads a string from a resource file with the given resource identifier.

Syntax

TCHAR * WINAPI StringFromResource(
    TCHAR *pBuffer,
    int iResourceID
);

Parameters

pBuffer

Pointer to the string corresponding to iResourceID.

iResourceID

Resource identifier of the string to retrieve.

Return Value

Returns the same string as pBuffer. If the function is not successful, returns a null string.

Remarks

The pBuffer buffer must be at least STR_MAX_LENGTH bytes.

See Also

  • Property Page Helper Functions


WideStringFromResource

The WideStringFromResource function loads a wide-character string from a resource file with the given resource identifier.

Syntax

WCHAR * WINAPI WideStringFromResource(
    WCHAR *pBuffer,
    int iResourceID
);

Parameters

pBuffer

Pointer to the string corresponding to iResourceID.

iResourceID

Resource identifier of the string to retrieve.

Return Value

Returns the same string as pBuffer. If the function is not successful, returns a null string.

Remarks

Property pages are typically called through their COM interfaces, which use wide-character strings regardless of how the binary is built. This function allows you to convert a resource string to a wide-character string. The function converts the resource to a wide-character string (if it is not already one) after loading it.

See Also

  • Property Page Helper Functions


Video and Image Functions

These functions and macros manipulate the DirectShow video format structures.

Function | Description
BIT_MASKS_MATCH | Compares the color masks for two VIDEOINFO structures.
BITMASKS | Retrieves the color masks from a VIDEOINFO structure
COLORS | Retrieves the palette entries from a VIDEOINFO structure
ContainsPalette | Determines whether a specified VIDEOINFOHEADER structure contains a palette.
ConvertVideoInfoToVideoInfo2 | Converts a media type that uses VIDEOINFOHEADER to one that uses VIDEOINFOHEADER2
DIBSIZE | Calculates the number of bytes required by a device-independent bitmap (DIB).
GetBitCount | Returns the number of bits per pixel used by a specified video subtype.
GetBitmapFormatSize | Calculates the size needed for a VIDEOINFO structure that can hold a specified BITMAPINFOHEADER structure.
GetBitmapPalette | Returns the first palette entry in a VIDEOINFOHEADER structure.
GetBitmapSize | Calculates the number of bytes required by a device-independent bitmap (DIB).
GetBitmapSubtype | Returns the media subtype GUID for the specified bitmap.
GetSubtypeName | Retrieves the human-readable name of a video subtype.
GetTrueColorType | Returns the media subtype GUID for a 16-bit uncompressed RGB bitmap.
HEADER | Returns the address of the BITMAPINFOHEADER within a VIDEOINFOHEADER.
MPEG1_SEQUENCE_INFO | Returns the address of the sequence header inside an MPEG1VIDEOINFO structure.
PALETTISED | Checks whether a bitmap has a color depth of 8 bits or less.
PALETTE_ENTRIES | Retrieves the maximum number of colors in the palette of a specified bitmap.
RESET_MASKS | Fills the color mask fields in a VIDEOINFO structure with zeroes.
RESET_HEADER | Fills a VIDEOINFOHEADER with zeroes.
RESET_PALETTE | Fills the palette entries in a VIDEOINFO structure with zeroes.
SIZE_EGA_PALETTE | Calculates the size needed for the palette entries in a 4-bit RGB bitmap.
SIZE_MASKS | Calculates the size of the color masks in a VIDEOINFO structure.
SIZE_MPEG1VIDEOINFO | Calculates the size of an MPEG1VIDEOINFO structure, including the sequence header.
SIZE_PALETTE | calculates the size of the palette entries in a VIDEOINFO structure.
SIZE_PREHEADER | Calculates the byte offset of the bmiHeader field within a VIDEOINFOHEADER structure.
SIZE_VIDEOHEADER | Calculates the size of the VIDEOINFOHEADER structure.
TRUECOLOR | Returns the TRUECOLORINFO structure from a VIDEOINFO structure.

Remarks

Most of the macros and functions described in the section are designed for manipulating VIDEOINFOHEADER and VIDEOINFO structures for RGB bitmaps. Use these macros with care: Most of them assume that the specified structure has been initialized properly. Many of them also assume that the BITMAPINFOHEADER structure is the standard size; that is, biSize == sizeof(BITMAPINFOHEADER).

The DirectShow base class library also provide the following global constants, which define the standard color masks for true-color bitmaps.

Global Data | Description
bits555 | Array of color masks for a 16-bit RGB bitmap in 5-5-5 format.
bits565 | Array of color masks for a 16-bit RGB bitmap in 5-6-5 format.
bits888 | Array of color masks for a 24-bit RGB bitmap.

Each of these constants in an array of three DWORDs, containing the red, green, and blue masks, in that order.


BIT_MASKS_MATCH

The BIT_MASKS_MATCH macro compares the color masks for two VIDEOINFO structures.

Syntax

BIT_MASKS_MATCH(pbmi1, pbmi2)

Parameters

pbmi1

Pointer to the first VIDEOINFO structure.

pbmi2

Pointer to the second VIDEOINFO structure.

Return Value

Returns TRUE if the color masks are identical, or FALSE otherwise.

Example Code

VIDEOINFO *pVi, *pVi2;
/* Initialize pVi and pVi2 (not shown). */
if (BIT_MASKS_MATCH(pVi, pVi2)
{
    // ....
}

See Also

  • Video and Image Functions


BITMASKS

The BITMASKS macro retrieves the color masks from a VIDEOINFO structure.

Syntax

BITMASKS(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFO structure.

Return Value

Returns a DWORD pointer value that is the address of the dwBitMasks member of the VIDEOINFO structure.

Remarks

This macro calculates the address as an offset from the start of the BITMAPINFOHEADER structure, using the value of bmiHeader.biSize. Make sure to initialize the VIDEOINFO structure before calling this macro.

Example Code

VIDEOINFO *pVi;
/* Initialize pVi (not shown). */
DWORD dwRed   = BITMASKS(pVi)[iRED],
      dwGreen = BITMASKS(pVi)[iGREEN],
      dwBlue  = BITMASKS(pVi)[iBLUE];

See Also

  • Video and Image Functions


COLORS

The COLORS macro retrieves the palette entries from a VIDEOINFO structure.

Syntax

COLORS(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFO structure.

Return Value

Returns a pointer to an array of RGBQUAD structures.

Remarks

This macro calculates the address as an offset from the start of the BITMAPINFOHEADER structure, using the value of bmiHeader.biSize. Make sure to initialize the VIDEOINFO structure before calling this macro.

See Also

  • Video and Image Functions


ContainsPalette

The ContainsPalette function determines whether a specified VIDEOINFOHEADER structure contains a palette.

Syntax

BOOL ContainsPalette(
  const VIDEOINFOHEADER *pVideoInfo
);

Parameters

pVideoInfo

Pointer to a VIDEOINFOHEADER structure.

Return Value

Returns TRUE if the bitdepth is 8 or less (bmiHeader.biBitCount), or the number of color indexes is more than zero (bmiHeader.biClrUsed). Returns FALSE otherwise.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


ConvertVideoInfoToVideoInfo2

The ConvertVideoInfoToVideoInfo2 function converts a media type that uses VIDEOINFOHEADER to one that uses VIDEOINFOHEADER2.

Syntax

STDAPI ConvertVideoInfoToVideoInfo2(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to the AM_MEDIA_TYPE structure to convert. The structure must have format type FORMAT_VideoInfo.

Return Value

Returns S_OK or E_OUTOFMEMORY.

Remarks

This function allocates a new VIDEOINFOHEADER2 structure, copies the members of the VIDEOINFOHEADER structure into it, and replaces the old structure with the new structure in the format block of the media type.

Requirements

Header: Declared in Winutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


DIBSIZE

The DIBSIZE macro calculates the number of bytes required by a device-independent bitmap (DIB).

Syntax

DIBSIZE(bi)

Parameters

bi

Specifies a BITMAPINFOHEADER structure.

Return Value

Returns the size in bytes.

Remarks

The size of a DIB is calculated as stride * height, where stride is width * bits per pixel/8, rounded up to the nearest DWORD alignment; and height is the absolute value of biHeight.

See Also

  • Video and Image Functions


GetBitCount

The GetBitCount function returns the number of bits per pixel used by a specified video subtype. This function is valid for uncompressed RGB subtypes only.

Syntax

WORD GetBitCount(
  const GUID *pSubtype
);

Parameters

pSubtype

Pointer to a video subtype GUID.

Return Value

Returns the number of bits per pixel for this subtype, or the value USHRT_MAX if the subtype is not recognized.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


GetBitmapFormatSize

The GetBitmapFormatSize function calculates the size needed for a VIDEOINFO structure that can hold a specified BITMAPINFOHEADER structure.

Syntax

LONG GetBitmapFormatSize(
  const BITMAPINFOHEADER *pHeader
);

Parameters

pHeader

Pointer to a BITMAPINFOHEADER structure.

Return Value

Returns the size, in bytes.

Remarks

A BITMAPINFOHEADER structure might be followed by color masks or palette entries, so it can be difficult to determine the number of bytes required to construct a VIDEOINFO structure from an existing BITMAPINFOHEADER structure.

To copy a BITMAPINFOHEADER structure into a VIDEOINFO structure, use the HEADER macro, which calculates the correct offset.

Example Code

LONG size = GetBitmapFormatSize(&bmi);
VIDEOINFO *pVi = static_cast<VIDEOINFO*>(CoTaskMemAlloc(size));
if (pVi != NULL)
{
    CopyMemory(HEADER(pVi), &bmi, sizeof(BITMAPINFOHEADER));
}

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


GetBitmapPalette

The GetBitmapPalette function returns the first palette entry in a VIDEOINFOHEADER structure.

Syntax

const RGBQUAD * GetBitmapPalette(
  const VIDEOINFOHEADER *pVideoInfo
);

Parameters

pVideoInfo

Pointer to a VIDEOINFOHEADER structure.

Return Value

Returns a pointer to the first palette entry.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).


GetBitmapSize

The GebBitmapSize function calculates the number of bytes required by a device-independent bitmap (DIB). This function simply calls the DIBSIZE macro.

Syntax

DWORD GetBitmapSize(
  const BITMAPINFOHEADER *pHeader
);

Parameters

pHeader

Pointer to a BITMAPINFOHEADER structure.

Return Value

Returns the size in bytes.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


GetBitmapSubtype

The GetBitmapSubtype function returns the media subtype GUID for the specified bitmap.

Syntax

const GUID GetBitmapSubtype(
    const BITMAPINFOHEADER *pHeader
);

Parameters

pHeader

Pointer to a BITMAPINFOHEADER structure.

Return Value

Returns the media subtype GUID.

Remarks

For uncompressed RGB types, this function maps the biBitCount field to the subtype. For compressed video types, this function uses the FOURCCMap class to map the biCompression field to the subtype.

If the function cannot match the format to a subtype, the return value is GUID_NULL.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


GetSubtypeName

The GetSubtypeName function retrieves the human-readable name of a video subtype.

Syntax

TCHAR * GetSubtypeName(
    const GUID *pSubtype
);

Parameters

pSubtype

Pointer to a video subtype GUID.

Return Value

Returns a string containing the name.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


GetTrueColorType

The GetTrueColorType function returns the media subtype GUID for a 16-bit uncompressed RGB bitmap.

Syntax

const GUID GetTrueColorType(
  const BITMAPINFOHEADER *pHeader
);

Parameters

pHeader

Pointer to a BITMAPINFOHEADER structure that defines the bitmap.

Return Value

Returns MEDIASUBTYPE_RGB555 or MEDIASUBTYPE_RGB565.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

See Also

  • Video and Image Functions


HEADER

The HEADER macro returns the address of the BITMAPINFOHEADER within a VIDEOINFOHEADER.

Syntax

HEADER(pVideoInfo)

Parameters

pVideoInfo

Pointer to a VIDEOINFOHEADER structure or VIDEOINFO structure.

Return Value

Returns the address of the VIDEOINFOHEADER structure's bmiHeader member.

Example Code

LONG size = GetBitmapFormatSize(&bmi);
VIDEOINFO *pVi = static_cast<VIDEOINFO*>(CoTaskMemAlloc(size));
if (pVi != NULL)
{
    CopyMemory(HEADER(pVi), &bmi, sizeof(BITMAPINFOHEADER));
}

See Also

  • Video and Image Functions


MPEG1_SEQUENCE_INFO

The MPEG1_SEQUENCE_INFO macro returns the address of the sequence header inside an MPEG1VIDEOINFO structure.

Syntax

MPEG1_SEQUENCE_INFO(pv)

Parameters

pv

Pointer to an MPEG1VIDEOINFO structure.

Return Value

Returns the address of the bSequenceHeader member of the MPEG1VIDEOINFO structure.

See Also

  • Video and Image Functions


PALETTISED

The PALETTISED macro checks whether a bitmap has a color depth of 8 bits or less.

Syntax

PALETTISED(pbmi);

Parameters

pbmi

Pointer to a VIDEOINFOHEADER structure or VIDEOINFO structure.

Return Value

Returns TRUE if the color depth (bmiHeader.biBitCount) is 8 bits or less, or FALSE otherwise.

See Also

  • Video and Image Functions
  • ContainsPalette
  • PALETTE_ENTRIES


PALETTE_ENTRIES

The PALETTE_ENTRIES macro retrieves the maximum number of colors in the palette of a specified bitmap.

Syntax

PALETTE_ENTRIES(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFOHEADER structure or VIDEOINFO structure.

Return Value

Returns 2 raised to the power of the color depth; that is, 1 << bmiHeader.biBitCount.

See Also

  • Video and Image Functions


RESET_MASKS

The RESET_MASKS macro fills the color mask fields in a VIDEOINFO structure with zeroes.

Syntax

RESET_MASKS(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFO structure.

Return Value

No return value.

Remarks

As defined in the header file Amvideo.h, this macro is not correct and will cause a compile error. Replace it with the following:

#undef RESET_MASKS
#define RESET_MASKS(x) (ZeroMemory((PVOID)(x)->dwBitMasks, SIZE_MASKS))

See Also

  • Video and Image Functions


RESET_HEADER

The RESET_HEADER macro fills a VIDEOINFOHEADER with zeroes. You can also use this macro to clear just the VIDEOINFOHEADER portion of a VIDEOINFO structure.

This macro is equivalent to calling ZeroMemory with sizeof(VIDEOINFOHEADER).

Syntax

RESET_HEADER(
  pbmi
)

Parameters

pbmi

Pointer to a VIDEOINFOHEADER structure.

Return Value

No return value.

See Also

  • Video and Image Functions


RESET_PALETTE

The RESET_PALETTE macro fills the palette entries in a VIDEOINFO structure with zeroes.

Syntax

RESET_PALETTE(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFO structure.

Return Value

No return value.

See Also

  • Video and Image Functions


SIZE_EGA_PALETTE

The SIZE_EGA_PALETTE macro calculates the size needed for the palette entries in a 4-bit RGB bitmap.

Syntax

SIZE_EGA_PALETTE

Return Value

Returns 16 * sizeof(RGBQUAD).

See Also

  • Video and Image Functions


SIZE_MASKS

The SIZE_MASKS macro calculates the size of the color masks in a VIDEOINFO structure.

Syntax

SIZE_MASKS

Return Value

Returns 3 * sizeof(DWORD).

See Also

  • Video and Image Functions


SIZE_MPEG1VIDEOINFO

The SIZE_MPEG1VIDEOINFO macro calculates the size of an MPEG1VIDEOINFO structure, including the sequence header (bSequenceHeader).

Syntax

SIZE_MPEG1VIDEOINFO(pv)

Parameters

pv

Pointer to an MPEG1VIDEOINFO structure.

Return Value

Returns the byte size of the specified MPEG1VIDEOINFO structure.

See Also

  • Video and Image Functions


SIZE_PALETTE

The SIZE_PALLETEE macro calculates the size of the palette entries in a VIDEOINFO structure. The VIDEOINFO structure assumes a 256-color palette.

Syntax

SIZE_PALETTE

Return Value

Returns 256 * sizeof(RGBQUAD).

See Also

  • Video and Image Functions


SIZE_PREHEADER

The SIZE_PREHEADER macro calculates the byte offset of the bmiHeader field within a VIDEOINFOHEADER structure.

Syntax

SIZE_PREHEADER

Return Value

Returns the byte offset.

See Also

  • Video and Image Functions


SIZE_VIDEOHEADER

The SIZE_VIDEOHEADER macro calculates the size of the VIDEOINFOHEADER structure. This macro is equivalent to sizeof(VIDEOINFOHEADER).

Syntax

SIZE_VIDEOHEADER

Return Value

Returns the size VIDEOINFOHEADER structure, in bytes.

See Also

  • Video and Image Functions


TRUECOLOR

The TRUECOLOR macro returns the TRUECOLORINFO structure from a VIDEOINFO structure. The TRUECOLORINFO structure contains color bitmasks followed by palette information, and is used for true-color images (16 bit or higher) that contain palettes.

Syntax

TRUECOLORINFO(pbmi)

Parameters

pbmi

Pointer to a VIDEOINFO structure.

Return Value

Returns a pointer to a TRUECOLORINFO structure.

Remarks

This macro calculates the address as an offset from the start of the BITMAPINFOHEADER structure, using the value of bmiHeader.biSize. Make sure to initialize the VIDEOINFO structure before calling this macro.

See Also

  • Video and Image Functions


Debugging Utilities

This section contains reference entries for the macros and functions that Microsoft® DirectShow® supplies to assist debugging. To use these functions, you must build the DirectShow base-class library.

  • Assert and Breakpoint Macros
  • Critical Section Debugging Functions
  • Debug Output Functions
  • Pointer Validation Macros
  • Wait Debugging Functions

See Also

  • Debugging in DirectShow
  • Using the DirectShow Base Classes


Assert and Breakpoint Macros

The Microsoft® DirectShow® base classes provide several macros that perform asserts or cause breakpoints.

Requirements

Header: Declared in Wxdebug.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Macro | Description
ASSERT | Evaluates an expression, and displays a diagnostic message if the expression is FALSE.
DbgAssertAligned | Tests whether a pointer is aligned to a specified boundary.
DbgBreak | Displays a message box with the specified string, the name of the source file, and the line number.
EXECUTE_ASSERT | Evaluates an expression in debug and retail builds. In debug builds, displays a diagnostic message if the expression is FALSE.
KASSERT | Evaluates an expression, and causes a breakpoint exception if the expression is FALSE.
KDbgBreak | Causes a breakpoint exception, and logs the specified string.


ASSERT

Evaluates an expression, and displays a diagnostic message if the expression is FALSE. Ignored in retail builds.

Syntax

ASSERT(
    cond
);

Parameters

cond

Expression to evaluate.

Remarks

In debug builds, if the expression is FALSE, this macro displays a message box with the text of the expression, the name of the source file, and the line number. The user can ignore the assertion, enter the debugger, or quit the application.

Example

ASSERT(rtStartTime <= rtEndTime);

See Also

  • Assert and Breakpoint Macros


DbgAssertAligned

Tests whether a pointer is aligned to a specified boundary. If not, this macro invokes the ASSERT macro. Ignored in retail builds.

Syntax

DbgAssertAligned(
    ptr,
    alignment
);

Parameters

ptr

Pointer variable.

alignment

Required alignment.

See Also

  • Assert and Breakpoint Macros


DbgBreak

Displays a message box with the specified string, the name of the source file, and the line number. The user can ignore the message, enter the debugger, or quit the application. Ignored in retail builds.

Syntax

DbgBreak(
    strLiteral
);

Parameters

strLiteral

Text string.

Example

DbgBreak("Unrecoverable error occurred.");

See Also

  • Assert and Breakpoint Macros


EXECUTE_ASSERT

Evaluates an expression in debug and retail builds. In debug builds, displays a diagnostic message if the expression is FALSE.

Syntax

EXECUTE_ASSERT(
    cond
);

Parameters

cond

Expression to evaluate.

Remarks

Unlike the ASSERT macro, this macro evaluates the expression in retail builds. In debug builds, if the expression is FALSE, the macro displays a message box with the text of the expression, the name of the source file, and the line number. The user can ignore the assertion, enter the debugger, or quit the application.

See Also

  • Assert and Breakpoint Macros


KASSERT

Evaluates an expression, and causes a breakpoint exception if the expression is FALSE. The text of the expression, the name of the source file, and the line number are logged using the DbgLog macro. Ignored in retail builds.

Syntax

KASSERT(
    cond
);

Parameters

cond

Expression to evaluate.

Remarks

Unlike the ASSERT and EXECUTE_ASSERT macros, this macro does not display a message box prompting the user. In debug builds, if the expression is FALSE, the macro automatically causes a breakpoint exception to occur.

See Also

  • Assert and Breakpoint Macros


KDbgBreak

Causes a breakpoint exception, and logs the specified string using the DbgLog macro. Ignored in retail builds.

Syntax

KDbgBreak(
    strLiteral
);

Parameters

strLiteral

Text string.

Remarks

Unlike the DbgBreak macro, this macro does not display a message box prompting the user. In debug builds, it automatically causes a breakpoint exception to occur.

See Also

  • Assert and Breakpoint Macros


Critical Section Debugging Functions

These functions help to debug critical sections in your code, which can make it easier to find the cause of a deadlock. These functions use the CCritSec helper class.

Requirements

Header: Declared in Wxutil.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
CritCheckIn | Returns TRUE if the current thread owns the specified critical section.
CritCheckOut | Returns FALSE if the current thread owns the specified critical section.
DbgLockTrace | Enables or disables debug logging for a given critical section.


CritCheckIn

Returns TRUE if the current thread is the owner of the specified critical section.

Syntax

BOOL WINAPI CritCheckIn(
    CCritSec *pcCrit
);

Parameters

pcCrit

Pointer to a CCritSec critical section.

Return Value

In debug builds, returns TRUE if the current thread is the owner of this critical section, or FALSE otherwise. In retail builds, always returns TRUE.

Remarks

This function is especially useful within the ASSERT macro, to test whether a thread owns a given lock.

Example Code

The following code example shows how to use this function:

{
    CCritSec MyLock;  // Critical section is not locked yet.

    ASSERT(CritCheckIn(&MyLock)); // This assert will fire.

    // Lock the critical section.
    CAutoLock cObjectLock(&MyLock);

    ASSERT(CritCheckIn(&MyLock)); // This assert will not fire.

} // Lock goes out of scope here.

See Also

  • Critical Section Debugging Functions


CritCheckOut

Returns FALSE if the current thread is the owner of the specified critical section.

Syntax

BOOL WINAPI CritCheckOut(
    CCritSec *pcCrit
);

Parameters

pcCrit

Pointer to a CCritSec critical section.

Return Value

In debug builds, returns FALSE if the current thread is the owner of this critical section, or TRUE otherwise. In retail builds, always returns TRUE.

Remarks

This function is the inverse of the CritCheckIn function. If CritCheckIn returns TRUE, CritCheckOut returns FALSE, and vice versa.

See Also

  • Critical Section Debugging Functions


DbgLockTrace

Enables or disables debug logging of a given critical section.

Syntax

void WINAPI DbgLockTrace(
    CCritSec *pcCrit,
    BOOL fTrace
);

Parameters

pcCrit

Pointer to a CCritSec critical section.

fTrace

Value specifying whether logging is enabled. Use TRUE to enable logging or FALSE to disable it.

Remarks

Use this function to trace a specific critical section. By default, debug logging of critical sections is disabled, because of the large number of critical sections.

To trace a critical section, perform the following steps:

  1. Define DEBUG or _DEBUG before you include the DirectShow headers.
  2. Enable debug logging for critical sections, by calling DbgSetModuleLevel with the LOG_LOCKING flag.
  3. Call DbgLockTrace on the critical section you want to trace.

In retail builds, the DbgLockTrace function has no effect.

Example Code

The following code example shows how to trace a critical section:

DbgInitialise(g_hInst);
DbgSetModuleLevel(LOG_LOCKING, 3);

{
    CCritSec MyLock;
    DbgLockTrace(&MyLock, TRUE);

    CAutoLock cObjectLock(&MyLock);

    // Protected section of code.
    DbgOutString("This code is inside a critical section.\n");

} // Lock goes out of scope here.

DbgTerminate();

The debug output will look similar to the following:

Example.exe(tid 360)     2012 : Thread 864 now owns lock 12fc2c
This code is inside a critical section.
Example.exe(tid 360)     4887 : Thread 864 releasing lock 12fc2c

See Also

  • Critical Section Debugging Functions


Debug Output Functions

The Microsoft® DirectShow® base classes provide several macros for displaying debugging information.

Requirements

Header: Declared in Wxdebug.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
DbgCheckModuleLevel | Checks whether logging is enabled for the given message types and level.
DbgDumpObjectRegister | Displays information about active objects.
DbgInitialise | Initializes the debug library.
DbgLog | Sends a string to the debug output location, if logging is enabled for the specified type and level.
DbgOutString | Sends a string to the debug output location.
DbgSetModuleLevel | Sets the logging level for one or more message types.
DbgTerminate | Cleans up the debug library.
DisplayType | Sends information about a media type to the debug output location.
DumpGraph | Sends information about a filter graph to the debug output location.
GuidNames | Global array that contains strings representing the GUIDs defined in Uuids.h.
NAME | Generates a debug-only string.
NOTE | Sends a string to the debug output location.
REMIND | Generates a reminder at compile time.

Remarks

The debugging facilities in DirectShow can be fine-tuned to display specific types of debug information, while ignoring others. With this feature, you can pinpoint problems in particular areas of your code. DirectShow defines several message types, shown in the following table.

Value | Description
LOG_ERROR | Error notification.
LOG_LOCKING | Locking and unlocking of critical sections.
LOG_MEMORY | Memory allocation, and object creation and destruction.
LOG_TIMING | Timing and performance measurements.
LOG_TRACE | General call tracing.
CUSTOM1 through CUSTOM5 | Available for custom debug messages

Each of the DirectShow debug logging functions specifies a message type and a log level. The debug message is displayed only when the current debugging level for that message type is equal to or greater than the level specified in the logging function. Otherwise, the message is ignored.

For example, the following code outputs the string "This is a debug message" if the LOG_TRACE level is 3 or higher:

DbgLog((LOG_TRACE, 3, TEXT("This is a debug message")));

Every module can set its own debugging level for each message type. (A module is a DLL or executable that can be loaded using the Microsoft® Win32® LoadLibrary function.) A module's debugging levels appear in the registry under the following key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\<Message Type>

where <Message Type> is the message type minus the initial "LOG_"; for example, LOCKING for LOG_LOCKING messages. When a module is loaded, the debug library finds the module's logging levels in the registry. If the registry keys do not exist, the debug library creates them.

A module can also set its own levels at run time, using the DbgSetModuleLevel function. To send a message to the debug output, call the DbgLog macro. The following example creates a level 3 message of type LOG_TRACE:

You can also specify global logging levels, with the following registry key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\GLOBAL\<Message Type>

The debug library uses whichever level is greater, the global level or the module level.

Debug Output Location

The debug output location is determined by another registry key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\LogToFile

If the value of this key is Console, the output goes to the console window. If the value is Deb, Debug, Debugger, or an empty string, the output goes to the debugger window. Otherwise, the output is written to a file specified by the registry key.

Before an executable uses the DirectShow debug library, it must call the DbgInitialise function. Afterward, it must call the DbgTerminate function. DLLs do not need to call these functions, because the DLL entry point (defined in the base class library) calls them automatically.


DbgCheckModuleLevel

The DbgCheckModuleLevel function checks whether logging is enabled for the given message types and level. Ignored in retail builds.

Syntax

BOOL DbgCheckModuleLevel(
    DWORD Types,
    DWORD Level
);

Parameters

Types

Bitwise combination of one or more message types.

Level

Logging level

Return Value

Returns TRUE if logging for any of the specified message types is set to the specified level or higher. Otherwise, returns FALSE.

See Also

  • Debug Output Functions


DbgDumpObjectRegister

The DbgDumpObjectRegister function displays information about active objects. Ignored in retail builds.

Syntax

void DbgDumpObjectRegister(void);

Remarks

In debug builds, the debug library maintains a list of active objects. The list includes any objects that derive from CBaseObject, were created by the current module, and have not been destroyed. The CBaseObject constructor and destructor methods update the list.

This function generates several LOG_MEMORY messages. At logging level 1, the function displays only the total number of objects. At logging level 2 or higher, it displays a list of the objects.

See Also

  • Debug Output Functions


DbgInitialise

The DbgInitialise function initializes the debug library. Ignored in retail builds.

Syntax

void DbgInitialise(
    HINSTANCE hInst
);

Parameters

hInst

Handle to the module instance.

Remarks

In an executable, call this method before using the DirectShow debug facilities. Before the executable quits, call the DbgTerminate function to clean up the debug library.

In a DLL that links to the base-class library (Strmbase.lib), it is not necessary to call this function. The function is called automatically when the DLL is loaded.

See Also

  • Debug Output Functions


DbgLog

The DbgLog macro sends a string to the debug output location, if logging is enabled for the specified type and level. This macro is ignored in retail builds.

Syntax

void DbgLog((
    DWORD Types,
    DWORD Level,
    const TCHAR *pFormat,
    ...
));

Parameters

Types

Bitwise combination of one or more message types.

Level

Logging level for this message.

pFormat

A printf-style format string.

...

Additional arguments for the format string.

Remarks

If debug logging for any of the message types is set to the specified level or higher, this macro sends the formatted string to the debug output location.

The macro automatically adds a newline character to the output string.

Example

DbgLog((LOG_TRACE, 3, TEXT("Connected input pin %d"), nPinNumber));

Note the additional set of parentheses that must enclose the macro parameters.

See Also

  • Debug Output Functions


DbgOutString

The DbgOutString macro sends a string to the debug output location. Ignored in retail builds.

Syntax

void DbgOutString(
    LPCTSTR psz
);

Parameters

psz

String to output.

Remarks

In debug builds, this function always outputs the string, regardless of the current debug output levels. For finer control over the output, use the DbgLog macro.

Example

DbgOutString("Creating the filter graph...\n");

See Also

  • Debug Output Functions


DbgSetModuleLevel

The DbgSetModuleLevel function sets the logging level for one or more message types. Ignored in retail builds.

Syntax

void DbgSetModuleLevel(
    DWORD Types,
    DWORD Level
);

Parameters

Types

Bitwise combination of one or more message types.

Level

Logging level for the specified message types.

See Also

  • Debug Output Functions


DbgTerminate

The DbgTerminate function cleans up the debug library. Ignored in retail builds.

Syntax

void DbgTerminate(void);

Remarks

Call this function if you call the DbgInitialise function.

See Also

  • Debug Output Functions


DisplayType

The DisplayType function sends information about a media type to the debug output location. Ignored in retail builds.

Syntax

void DisplayType(
    LPTSTR label,
    const AM_MEDIA_TYPE *pmtIn
);

Parameters

label

String that contains a message to display with the media type information.

pmtIn

Pointer to the AM_MEDIA_TYPE structure that contains the media type.

Remarks

This function generates several LOG_TRACE messages. At logging level 2 or higher, the function displays the major type, subtype, and format type, and data from the format block. At logging level 5 or higher, the function displays additional information, such as the source and target rectangles for video types.

See Also

  • Debug Output Functions


DumpGraph

The DumpGraph function sends information about a filter graph to the debug output location. Ignored in retail builds.

Syntax

void DumpGraph(
    IFilterGraph *pGraph,
    DWORD dwLevel
);

Parameters

pGraph

Pointer to the IFilterGraph interface on the filter graph manager.

dwLevel

Logging level. The function generates a LOG_TRACE message with the specified logging level.

See Also

  • Debug Output Functions


GuidNames

GuidNames is a global array in the DirectShow base class library that contains strings representing the GUIDs defined in Uuids.h. This array is useful for generating debug output.

Syntax

char* GuidNames[guid]

Parameters

guid

Specifies any GUID value defined in the header file Uuids.h.

Remarks

Use this global array to output GUID constants as strings. For example, the following code prints the string "MEDIATYPE_Video" to the console:

puts(GuidNames[MEDIATYPE_Video]);

If the GUID is not matched, the string "Unknown GUID Name" is returned. Not all DirectShow GUIDs are defined in uuids.h.

See Also

  • Debug Output Functions


NAME

The NAME macro generates a debug-only string.

Syntax

NAME(
    strLiteral
);

Parameters

strLiteral

Text string.

Remarks

In debug builds, this macro is equivalent to the TEXT macro. In retail builds, it resolves to (TCHAR*) NULL. This macro is useful when declaring the name of an object that derives from the CBaseObject class.

Example

pObject = new CBaseObject(NAME("My Object"));

See Also

  • Debug Output Functions


NOTE

The NOTE macro sends a string to the debug output location. Ignored in retail builds.

Syntax

NOTE(
    pFormat
);

NOTEn(
    pFormat,
    arg1 ... arg5
);

Parameters

pFormat

A printf-style format string.

arg1 – arg5

Additional arguments for the format string. The number of arguments must match the macro name. For example, NOTE1 takes one argument, and NOTE5 takes five arguments.

Remarks

These macros are variants of the DbgLog macro. They generate level 5 LOG_TRACE messages.

Example

NOTE("Warning, failed to created graph.");
NOTE2("Width: %d, Height: %d", width, height);

See Also

  • Debug Output Functions


REMIND

The REMIND macro generates a reminder at compile time. This macro generates a string that includes the parameter string, the name of the source file, and the line number.

Syntax

REMIND(
    strLiteral
);

Parameters

strLiteral

Text string.

Example

This macro is useful for generating compile-time warnings:

#pragma message (REMIND("TO DO: Add support for IDispatch."))

See Also

  • Debug Output Functions


Pointer Validation Macros

Microsoft® DirectShow® provides several macros for validating pointers.

Requirements

Header: Declared in Wxdebug.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Macro | Description
CheckPointer | Checks whether a pointer is NULL.
ValidateReadPtr | Verifies that the calling process has read access to a memory block.
ValidateReadWritePtr | Verifies that the calling process has read/write access to a memory block.
ValidateStringPtr | Verifies that the calling process has read access to a string.
ValidateStringPtrA | Verifies that the calling process has read access to an ANSI string.
ValidateStringPtrW | Verifies that the calling process has read access to a wide-character string.
ValidateWritePtr | Verifies that the calling process has write access to a memory block.


CheckPointer

Checks whether a pointer is NULL. If the pointer is NULL, the function or method in which the macro appears returns the specified value.

Syntax

CheckPointer(
    p,
    ret
);

Parameters

p

Pointer to check.

ret

Value that the function or method returns if p is NULL.

Example

HRESULT MyFunction(VOID *pSomeParameter)
{
    CheckPointer(pSomeParameter, E_INVALIDARG)

    // Rest of the function (not shown).
}

See Also

  • Pointer Validation Macros


ValidateReadPtr

Verifies that the calling process has read access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateReadPtr(
    const void *p,
    UINT cb
);

Parameters

p

Pointer to a memory block.

cb

Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

See Also

  • Pointer Validation Macros


ValidateReadWritePtr

Verifies that the calling process has read/write access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateReadWritePtr(
    const void *p,
    UINT cb
);

Parameters

p

Pointer to a memory block.

cb

Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

See Also

  • Pointer Validation Macros


ValidateStringPtr

Verifies that the calling process has read access to a string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtr(
    LPCTSTR p
);

Parameters

p

Pointer to a NULL-terminated TCHAR string.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

See Also

  • Pointer Validation Macros


ValidateStringPtrA

Verifies that the calling process has read access to an ANSI string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtrA(
    LPCSTR p
);

Parameters

p

Pointer to a NULL-terminated ANSI string.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included.

See Also

  • Pointer Validation Macros


ValidateStringPtrW

Verifies that the calling process has read access to a wide-character string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtrW(
    LPCWSTR p
);

Parameters

p

Pointer to a NULL-terminated wide-character string.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

See Also

  • Pointer Validation Macros


ValidateWritePtr

Verifies that the calling process has write access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateWritePtr(
    const void *p,
    UINT cb
);

Parameters

p

Pointer to a memory block.

cb

Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG, _DEBUG, or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

See Also

  • Pointer Validation Macros


Wait Debugging Functions

Microsoft® DirectShow® provides several functions for debugging infinite waits.

In retail builds, the DbgWaitForMultipleObjects and DbgWaitForSingleObject functions work like their Microsoft® Win32® counterparts, WaitForMultipleObjects and WaitForSingleObject, with infinite time-out intervals.

In debug builds, these functions use a global time-out value. If the time-out expires, the function triggers an assert. The following registry key specifies the time-out value, in milliseconds:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\TIMEOUT

If the key does not exist, the time-out value defaults to INFINITE. You can use the DbgSetWaitTimeout function to override the registry entry.

Requirements

Header: Declared in Wxdebug.h; include Streams.h.

Library: Use Strmbase.lib (retail builds) or Strmbasd.lib (debug builds).

Function | Description
DbgSetWaitTimeout | Sets the debugging time-out value.
DbgWaitForMultipleObjects | Waits for any (or all) of the specified objects to be signaled.
DbgWaitForSingleObject | Waits for an object to become signaled.


DbgSetWaitTimeout

Sets the debugging time-out value. Ignored in retail builds.

Syntax

void DbgSetWaitTimeout(
    DWORD dwTimeout
);

Parameters

dwTimeout

Time-out value in milliseconds, or INFINITE to wait indefinitely.

Remarks

In debug builds, the DbgWaitForMultipleObjects and DbgWaitForSingleObject functions use this value as the time-out interval.

See Also

  • Wait Debugging Functions


DbgWaitForMultipleObjects

Waits for any (or all) of the specified objects to be signaled.

In a debug build, this function triggers an assert if the time-out interval expires before the objects are signaled. To set the time-out interval, call the DbgSetWaitTimeout function.

In a retail build, this function is equivalent to the WaitForMultipleObjects function with a time-out interval of INFINITE.

Syntax

DWORD DbgWaitForMultipleObjects(
    DWORD nCount,
    CONST HANDLE *lpHandles,
    BOOL bWaitAll
);

Parameters

nCount

Number of objects.

lpHandles

Array of handles to objects, of size nCount.

bWaitAll

Boolean value that specifies whether to wait for all of the objects. If TRUE, the function waits for all of the objects to be signaled. Otherwise, it waits for at least one object to be signaled.

See Also

  • Wait Debugging Functions


DbgWaitForSingleObject

Waits for an object to become signaled.

In a debug build, this function triggers an assert if the time-out interval expires before the object is signaled. To set the time-out interval, call the DbgSetWaitTimeout function.

In a retail build, this function is equivalent to the WaitForSingleObject function with a time-out interval of INFINITE.

Syntax

DWORD DbgWaitForSingleObject(
    HANDLE h
);

Parameters

h

Handle to the object.

See Also

  • Wait Debugging Functions


Microsoft TV Technologies C++ Reference

This section contains the reference documentation for the C++ objects, interfaces, structures, constants and events defined for Microsoft® TV Technologies, grouped by the following functional areas:

  • TV Ratings Reference
  • Video Control C++ Reference
  • Microsoft Unified Tuning Model C++ Reference
  • Transport Information Interfaces
  • BDA Filter Interfaces

See Also

  • Microsoft TV Technologies


TV Ratings Reference

This topic applies to Windows XP Service Pack 1 only.

The following sections describe the objects, structures, and enumerations used by the Microsoft TV Ratings system:

  • TV Ratings Objects
  • TV Ratings Filters
  • TV Ratings Interfaces
  • TV Ratings Enumerations
  • TV Ratings Broadcast Events

See Also

  • TV Ratings Components


TV Ratings Objects

This topic applies to Windows XP Service Pack 1 only.

The following table lists the TV Ratings objects.

Object | Description
EvalRat | Evaluates program ratings. This object is created by third parties.
XDSToRat | Parses rating information from line 21 data and converts it into program ratings. This object is created by third parties.


EvalRat Object

This topic applies to Windows XP Service Pack 1 only.

The EvalRat object evaluates program ratings and determines whether a program should be blocked under the current set of permissions. The permissions are set by the application. The rating itself is parsed from the broadcast stream using the XDSToRat object.

This object is created by third parties. It must support the IEvalRat interface. This object is used by the Encrypter/Tagger filter and the Decrypter/Detagger filter. Applications do not use this object directly.

CLSID | CLSID_EvalRat
Interfaces | IEvalRat

See Also

  • TV Ratings Reference


XDSToRat Object

This topic applies to Windows XP Service Pack 1 only.

The XDSToRat object parses rating information from line 21 data and converts it into program ratings.

This object is created by third parties. It must support the IXDSToRat interface. This object is used by the XDS Codec filter. Applications do not use this object directly.

CLSID | CLSID_XDSToRat
Interfaces | IXDSToRat

See Also

  • TV Ratings Reference


TV Ratings Filters

This topic applies to Windows XP Service Pack 1 only.

The following table lists the TV Ratings filters.

Filter | Description
Decrypter/Detagger | Decrypts samples.
Encrypter/Tagger | Encrypts samples and tags them with ratings information.
XDS Codec | Supports third-party software that decodes TV ratings information.


Decrypter/Detagger Filter

This topic applies to Windows XP Service Pack 1 only.

The Decrypter/Detagger filter conditionally decrypts samples that are encrypted by the Encrypter/Tagger filter.

This filter reads ratings information from the encrypted samples and passes them to the EvalRat object. The EvalRat object determines whether the content is allowed. If so, the Decrypter/Detagger filter decrypts the samples and passes them downstream for rendering.

Filter interfaces | IBaseFilter, IDTFilter, IDTFilterConfig, IBroadcastEvent
Input pin media types | MEDIASUBTYPE_ETDTFilter_Tagged
Input pin interfaces | IKsPropertySet, IMemInputPin, IPin, IQualityControl
Output pin media types | See Remarks
Output pin interfaces | IPin, IQualityControl
Filter CLSID | CLSID_DTFilter
Merit | MERIT_DO_NOT_USE
Filter category | CLSID_CPCAFiltersCategory

Remarks

The output type matches the original input type received by the Encrypter/Tagger filter.

See Also

  • Overview of the TV Ratings System


Encrypter/Tagger Filter

This topic applies to Windows XP Service Pack 1 only.

The Encrypter/Tagger filter encrypts media samples and tags them with ratings information from the XDS Codec filter.

Filter interfaces | IBaseFilter, IBroadcastEvent, IETFilter, IETFilterConfig
Input pin media types | Any
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | MEDIASUBTYPE_ETDTFilter_Tagged
Output pin interfaces | IPin, IQualityControl
Filter CLSID | CLSID_ETFilter
Merit | MERIT_DO_NOT_USE
Filter category | CLSID_CPCAFiltersCategory

Remarks

The output type matches the input type, except the subtype is changed to MEDIASUBTYPE_ETDTFilter_Tagged.

See Also

  • Overview of the TV Ratings System


XDS Codec Filter

This topic applies to Windows XP Service Pack 1 only.

The XDS Codec filter supports third-party software that decodes TV ratings information from the extended data services (XDS) channel of line 21.

This filter receives XDS data from the CC Decoder filter or some other source. It passes this data to the XDSToRat object, which is responsible for parsing the data into content ratings. The XDSToRat object returns the decoded ratings to the XDS Codec filter.

Filter interfaces | IBaseFilter, IBroadcastEvent, IXDSCodec
Input pin media types | Major type: MEDIATYPE_AUXLine21Data Subtype: MEDIASUBTYPE_Line21_BytePair
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | Not applicable
Output pin interfaces | Not applicable
Filter CLSID | CLSID_XDSCodec
Merit | MERIT_DO_NOT_USE
Filter category | CLSID_CPCAFiltersCategory

See Also

  • Overview of the TV Ratings System


TV Ratings Interfaces

This topic applies to Windows XP Service Pack 1 only.

The following table lists the interfaces that are defined for the TV Ratings objects.

Interface | Description
IDTFilter | Exposed by the Decrypter/Detagger filter.
IDTFilterConfig | Configures the Decrypter/Detagger filter.
IETFilter | Exposed by the Encrypter/Tagger filter.
IETFilterConfig | Configures the Encrypter/Tagger filter.
IEvalRat | Evaluates content ratings carried by a broadcast stream.
IXDSCodec | Exposed by the XDS Codec filter.
IXDSToRat | Parses rating information from extended data services (XDS) information in line 21.


IDTFilter Interface

This topic applies to Windows XP Service Pack 1 only.

The IDTFilter interface is exposed by the Decrypter/Detagger filter. Applications can use this interface to set the ratings permissions.

IID: IID_IDTFilter

In addition to the methods inherited from IUnknown, the IDTFilter interface exposes the following methods.

Method | Description
get_BlockedRatingAttributes | Determines whether content is blocked for a given rating system and rating level.
get_BlockUnRated | Indicates whether a program without rating information is blocked.
get_BlockUnRatedDelay | Retrieves that length of time the filter waits before it blocks unrated content.
get_EvalRatObjOK | Queries whether the EvalRat object was created successfully.
GetCurrRating | Retrieves the current rating.
put_BlockedRatingAttributes | Specifies whether to block content that has a specified rating.
put_BlockUnRated | Specifies whether to block a program for which rating information has not been obtained.
put_BlockUnRatedDelay | Sets the length of time the filter waits before it blocks unrated content.


IDTFilter::get_BlockedRatingAttributes

This topic applies to Windows XP Service Pack 1 only.

The get_BlockedRatingAttributes method determines whether content is blocked for a given rating system and rating level.

Syntax

HRESULT get_BlockedRatingAttributesmethod(
    EnTvRat_System  EnSystem
    EnTvRat_GenericLevel  EnRating
    LONG  plbfEnAttr
);

Parameters

EnSystem

[in] Specifies the rating system as an EnTvRat_System enumeration type.

EnRating

[in] Specifies the rating level as an EnTvRat_GenericLevel enumeration type.

plbfEnAttr

[out, retval] Pointer to a variable that receives a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_NOINTERFACE | The EvalRat object was not successfully created.
S_OK | Success.

Remarks

The filter passes this call through to the EvalRat object. For more information, see IEvalRat::get_BlockedRatingAttributes.

See Also

  • IDTFilter Interface
  • Setting Allowable Viewing Levels


IDTFilter::get_BlockUnRated

This topic applies to Windows XP Service Pack 1 only.

The get_BlockUnRated method indicates whether a program without rating information is blocked.

Syntax

HRESULT get_BlockUnRated(
    BOOL *pfBlockUnRatedShows
);

Parameters

pfBlockUnRatedShows

[out, retval] Pointer to a variable that receives a Boolean value. If the value is TRUE, unrated shows are blocked. Otherwise, they are not blocked.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_NOINTERFACE | The EvalRat object was not successfully created.
S_OK | Success.

Remarks

The filter passes this call through to the EvalRat object. For more information, see IEvalRat::get_BlockUnRated.

See Also

  • IDTFilter Interface
  • Setting Allowable Viewing Levels


IDTFilter::get_BlockUnRatedDelay

This topic applies to Windows XP Service Pack 1 only.

The get_BlockUnRatedDelay method retrieves that length of time the filter waits before it blocks unrated content.

Syntax

HRESULT get_BlockUnRatedDelay(
    LONG  *pmsecsDelayBeforeBlock
);

Parameters

pmsecsDelayBeforeBlock

[out, retval] Pointer to a variable that receives the delay, in milliseconds.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

Regardless of the value of this property, the filter does not block unrated content unless the BlockUnRated property is TRUE.

See Also

  • IDTFilter Interface
  • IDTFilter::get_BlockUnRated


IDTFilter::get_EvalRatObjOK

This topic applies to Windows XP Service Pack 1 only.

The get_EvalRatObjOK method queries whether the EvalRat object was created successfully.

Syntax

HRESULT get_EvalRatObjOK(
    HRESULT  *pHrCoCreateRetVal
);

Parameters

pHrCoCreateRetVal

[out, retval] Pointer to a variable that receives an HRESULT value. The HRESULT is the value that was returned when the filter called CoCreateInstance to create the EvalRat object. If it equals S_OK, the EvalRat object was created successfully.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IDTFilter Interface


IDTFilter::GetCurrRating

This topic applies to Windows XP Service Pack 1 only.

The GetCurrRating method retrieves the current rating, based on the most recent media sample.

Syntax

HRESULT GetCurrRating(
    EnTvRat_System  *pEnSystem
    EnTvRat_GenericLevel  *pEnRating
    LONG  *plbfEnAttr
);

Parameters

pEnSystem

[out] Pointer to a variable that receives the rating system, as an EnTvRat_System enumeration type.

pEnRating

[out] Pointer to a variable that receives the rating level, as an EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

plbfEnAttr

[out] Pointer to a variable that receives a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration. The flags specify content attributes, such as violence or adult language. Content attributes do not apply to all rating systems.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • IDTFilter Interface


IDTFilter::put_BlockedRatingAttributes

This topic applies to Windows XP Service Pack 1 only.

The put_BlockedRatingAttributes method specifies whether to block content that has a specified rating.

Syntax

HRESULT put_BlockedRatingAttributesmethod(
    EnTvRat_System  EnSystem
    EnTvRat_GenericLevel  EnRating
    LONG  lbfEnAttr
);

Parameters

EnSystem

[in] Specifies the rating system, as an EnTvRat_System enumeration type.

EnRating

[in] Specifies the rating level, as an EnTvRat_GenericLevel enumeration type.

lbfEnAttr

[in] Bitwise combination of zero or more flags from the BfEnTvRat_GenericAttributes enumeration.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_NOINTERFACE | The EvalRat object was not successfully created.
S_OK | Success.

Remarks

The filter passes this call through to the EvalRat object. For more information, see IEvalRat::put_BlockedRatingAttributes.

See Also

  • IDTFilter Interface


IDTFilter::put_BlockUnRated

This topic applies to Windows XP Service Pack 1 only.

The put_BlockUnRated method specifies whether to block a program for which rating information has not been obtained.

Syntax

HRESULT put_BlockUnRated(
    BOOL fBlockUnRatedShows
);

Parameters

fBlockUnRatedShows

[in] Boolean value. Specify TRUE to block unrated programs, or specify FALSE not to block unrated programs.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_NOINTERFACE | The EvalRat object was not successfully created.
S_OK | Success.

Remarks

The filter passes this call through to the EvalRat object. For more information, see IEvalRat::put_BlockUnRated.

See Also

  • IDTFilter Interface


IDTFilter::put_BlockUnRatedDelay

This topic applies to Windows XP Service Pack 1 only.

The put_BlockUnRatedDelay method sets the length of time the filter waits before it blocks unrated content.

Syntax

HRESULT put_BlockUnRatedDelay(
    LONG  msecsDelayBeforeBlock
);

Parameters

msecsDelayBeforeBlock

[in] Specifies the delay, in milliseconds. The value must be from 0 to 60000 (60 seconds).

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

Regardless of the value of this property, the filter does not block unrated content unless the BlockUnRated property is TRUE.

See Also

  • IDTFilter Interface
  • IDTFilter::put_BlockUnRated


IDTFilterConfig Interface

This topic applies to Windows XP Service Pack 1 only.

The IDTFilterConfig interface configures the Decrypter/Detagger filter. Most applications will not have to use this interface.

IID: IID_IDTFilterConfig

In addition to the methods inherited from IUnknown, the IDTFilterConfig interface exposes the following method.

Method | Description
GetSecureChannelObject | Retrieves the secure channel object used to decrypt the stream.


IDTFilterConfig::GetSecureChannelObject

This topic applies to Windows XP Service Pack 1 only.

The GetSecureChannelObject method retrieves the secure channel object used to decrypt the stream.

Syntax

HRESULT GetSecureChannelObject(
    IUnknown **ppUnkSecureChannel
);

Parameters

ppUnkDRMSecureChannel

[out] Address of a variable that receives a pointer to the secure channel object's IUnknown interface.

Return Values

Returns an HRESULT.

Remarks

If the method succeeds, the caller must release the IUnknown interface.

See Also

  • IDTFilterConfig Interface


IETFilter Interface

This topic applies to Windows XP Service Pack 1 only.

The IETFilter interface is exposed by the Encrypter/Tagger filter. Most applications will not have to use this interface.

IID: IID_IETFilter

In addition to the methods inherited from IUnknown, the IETFilter interface exposes the following method.

Method | Description
get_EvalRatObjOK | Queries whether the EvalRat object was created successfully.
GetCurrRating | Retrieves the current rating.


IETFilter::get_EvalRatObjOK

This topic applies to Windows XP Service Pack 1 only.

The get_EvalRatObjOK method queries whether the EvalRat object was created successfully.

Syntax

HRESULT get_EvalRatObjOK(
    HRESULT  *pHrCoCreateRetVal
);

Parameters

pHrCoCreateRetVal

[out, retval] Pointer to a variable that receives an HRESULT value. The HRESULT is the value that was returned when the filter called CoCreateInstance to create the EvalRat object. If it equals S_OK, the EvalRat object was created successfully.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IETFilter Interface


IETFilter::GetCurrRating

This topic applies to Windows XP Service Pack 1 only.

The GetCurrRating method retrieves the current rating, based on the most recent media sample.

Syntax

HRESULT GetCurrRating(
    EnTvRat_System  *pEnSystem
    EnTvRat_GenericLevel  *pEnRating
    LONG  *plbfEnAttr
);

Parameters

pEnSystem

[out] Pointer to a variable that receives the rating system, as an EnTvRat_System enumeration type.

pEnRating

[out] Pointer to a variable that receives the rating level, as an EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

plbfEnAttr

[out] Pointer to a variable that receives a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration. The flags specify content attributes, such as violence or adult language. Content attributes do not apply to all rating systems.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • IETFilter Interface


IETFilterConfig Interface

This topic applies to Windows XP Service Pack 1 only.

The IETFilterConfig interface configures the Encrypter/Tagger filter. Most applications will not have to use this interface.

IID: IID_IETFilterConfig

In addition to the methods inherited from IUnknown, the IETFilterConfig interface exposes the following methods.

Method | Description
GetSecureChannelObject | Retrieves the secure channel object used to encrypt the stream.
InitLicense | Initializes an encryption license.


IETFilterConfig::GetSecureChannelObject

This topic applies to Windows XP Service Pack 1 only.

The GetSecureChannelObject method retrieves the secure channel object used to encrypt the stream.

Syntax

HRESULT GetSecureChannelObject(
    IUnknown **ppUnkSecureChannel
);

Parameters

ppUnkDRMSecureChannel

[out] Address of a variable that receives a pointer to the secure channel object's IUnknown interface.

Return Values

Returns an HRESULT.

Remarks

If the method succeeds, the caller must release the IUnknown interface.

See Also

  • IETFilterConfig Interface


IETFilterConfig::InitLicense

This topic applies to Windows XP Service Pack 1 only.

The InitLicense method initializes an encryption license.

Syntax

HRESULT InitLicense(
    int  LicenseId
);

Parameters

LicenseId

[in] Identifies the license.

Return Values

Returns an HRESULT.

See Also

  • IETFilterConfig Interface


IEvalRat Interface

This topic applies to Windows XP Service Pack 1 only.

The IEvalRat interface is used to evaluate content ratings carried by a broadcast stream. This interface is exposed by the EvalRat (ratings evaluator) object. The EvalRat object is implemented by third parties.

The Encrypter/Tagger filter and the Decrypter/Detagger filter use this interface. Applications use the interfaces exposed by those filters, but typically do not use the IEvalRat interface.

IID: IID_IEvalRat

In addition to the methods inherited from IDispatch, the IEvalRat interface exposes the following methods.

Method | Description
get_BlockedRatingAttributes | Determines whether content is blocked for a given rating system and rating level.
get_BlockUnRated | Indicates whether a program without rating information is blocked.
MostRestrictiveRating | Compares two ratings and returns the more restrictive of the two.
put_BlockedRatingAttributes | Specifies whether to block content that has a specified rating.
put_BlockUnRated | Specifies whether to block a program for which rating information has not been obtained.
TestRating | Determines whether a program with the specified rating should be blocked.


IEvalRat::get_BlockedRatingAttributes

This topic applies to Windows XP Service Pack 1 only.

The get_BlockedRatingAttributes method determines whether content is blocked for a given rating system and rating level.

Syntax

HRESULT get_BlockedRatingAttributes(
  EnTvRat_System  enSystem,
  EnTvRat_GenericLevel  enLevel,
  LONG*  plbfAttrs
);

Parameters

enSystem

[in] Specifies the rating system, as an EnTvRat_System enumeration type.

enLevel

[in] Specifies the rating level, as an EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

plbfAttrs

[out, retval] Pointer to a variable that receives a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration. The flags indicate whether the overall rating is blocked, or specific attributes within the rating are blocked.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

If the BfIsBlocked flag is set, all content with the specified rating level will be blocked. If one of the BfIsAttr_X flags is set, any content with that rating level and attribute will be blocked.

See Also

  • IEvalRat Interface
  • IEvalRat::put_BlockedRatingAttributes
  • Setting Allowable Viewing Levels


IEvalRat::get_BlockUnRated

This topic applies to Windows XP Service Pack 1 only.

The get_BlockUnRated method indicates whether a program without rating information is blocked.

Syntax

HRESULT get_BlockUnRated(
  BOOL*  pfBlockUnRatedShows
);

Parameters

pfBlockUnRatedShows

[out, retval] Pointer to a variable that receives a Boolean value. If the value is TRUE, unrated shows are blocked. Otherwise, they are not blocked.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

For more information, see Setting Allowable Viewing Levels.

Implementation Note: By default, unrated programs should be allowed. Return FALSE in pfBlockUnRatedShows unless the put_BlockUnRated method was previously called with the value TRUE.

See Also

  • IEvalRat Interface
  • IEvalRat::put_BlockUnRated


IEvalRat::MostRestrictiveRating

This topic applies to Windows XP Service Pack 1 only.

The MostRestrictiveRating method compares two ratings and returns the more restrictive of the two.

Syntax

HRESULT MostRestrictiveRating(
  EnTvRat_System  enSystem1,
  EnTvRat_GenericLevel  enEnLevel1,
  LONG  lbfEnAttr1,
  EnTvRat_System  enSystem2,
  EnTvRat_GenericLevel  enEnLevel2,
  LONG  lbfEnAttr2,
  EnTvRat_System*  penSystem,
  EnTvRat_GenericLevel*  penEnLevel,
  LONG*  plbfEnAttr
);

Parameters

enSystem1

[in] The rating system of the first rating to compare, specified as a member of the EnTvRat_System enumeration.

enEnLevel1

[in] The rating level of the first rating, specified as a member of the EnTvRat_GenericLevel enumeration.

lbfEnAttr1

[in] Specifies the content attributes of the first rating, as a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration.

enSystem2

[in] The rating system of the second rating to compare, specified as a member of the EnTvRat_System enumeration.

enEnLevel2

[in] The rating level of the second rating, specified as a member of the EnTvRat_GenericLevel enumeration.

lbfEnAttr2

[in] Specifies the content attributes of the second rating, as a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration.

penSystem

[out] Pointer to a variable that receives the rating system of the more restrictive rating.

penEnLevel

[out] Pointer to a variable that receives the rating level of the more restrictive rating.

plbfEnAttr

[out] Pointer to a variable that receives a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_POINTER | NULL pointer argument.
S_FALSE | The ratings are from two different rating systems.
S_OK | The method succeeded.

Remarks

This method enables the client to determine which of two ratings is more restrictive. For example, in the MPAA system, PG is more restrictive than R. The more restrictive rating is returned in the penSystem, penEnLevel, and plbfEnAttr parameters.

When the method compares ratings from two different ratings systems, it returns a rating expressed in the first system, unless the first system is unknown (TvRat_SystemDontKnow). In that case, it returns a rating using the second system.

The method returns S_FALSE if the ratings systems are not the same. There may not be an exact mapping between the two systems.

See Also

  • IEvalRat Interface


IEvalRat::put_BlockedRatingAttributes

This topic applies to Windows XP Service Pack 1 only.

The put_BlockedRatingAttributes method specifies whether to block content that has a specified rating.

Syntax

HRESULT put_BlockedRatingAttributes(
  EnTvRat_System  enSystem,
  EnTvRat_GenericLevel  enLevel,
  LONG  lbfAttrs
);

Parameters

enSystem

[in] Specifies the rating system, as an EnTvRat_System enumeration type.

enLevel

[in] Specifies the rating level, as an EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

lbfAttrs

[in] Bitwise combination of zero or more flags from the BfEnTvRat_GenericAttributes enumeration. The flags specify whether the overall rating is blocked, or specific attributes within the rating are blocked.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

This method should be called once for each level in a rating system, to specify viewing permissions for that level. The lbfAttrs parameter indicates the permissions for the specified rating level:

  • If no flags are set, this rating level is unrestricted. Any program with this rating level can be viewed.
  • If the BflsBlocked flag is set, this rating level is restricted. No program with this rating level can be viewed.
  • Flags in the range BfIsAttr_1 to BfIsAttr_7 specify content attributes, such as violence or adult language. If one of these flags is set, it means that a program with that content attribute and the specified rating level will be blocked.

For more information, see Setting Allowable Viewing Levels.

See Also

  • IEvalRat Interface


IEvalRat::put_BlockUnRated

This topic applies to Windows XP Service Pack 1 only.

The put_BlockUnRated method specifies whether to block a program for which rating information has not been obtained.

Syntax

HRESULT put_BlockUnRated(
  BOOL  fBlockUnRatedShows
);

Parameters

fBlockUnRatedShows

[in] Boolean value. Specify TRUE to block unrated programs, or specify FALSE not to block unrated programs.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

For more information, see Setting Allowable Viewing Levels.

See Also

  • IEvalRat Interface


IEvalRat::TestRating

This topic applies to Windows XP Service Pack 1 only.

The TestRating method determines whether a program with the specified rating should be blocked.

Syntax

HRESULT TestRating(
  EnTvRat_System  enShowSystem,
  EnTvRat_GenericLevel  enShowLevel,
  LONG  lbfEnShowAttributes
);

Parameters

enShowSystem

[in] Specifies the rating system, as an EnTvRat_System enumeration type.

enShowLevel

[in] Specifies the rating level, as an EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

lbfEnShowAttributes

[in] Bitwise combination of zero or more flags from the BfEnTvRat_GenericAttributes enumeration. The flags specify content attributes, such as violence or adult language. Content attributes do not apply to all rating systems.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid argument.
S_FALSE | This program is restricted and should be blocked.
S_OK | This program is allowed and should not be blocked.

Remarks

The application sets viewing permissions through the IEvalRat::put_BlockedRatingAttributes method. Whenever the Decrypter/Detagger filter receives a new rating in a program, it calls TestRating to determine whether to block the program. If TestRating returns S_OK, the rating is restricted under the current set of viewing permissions, and the Decrypter/Tagger filter blocks the program.

Implementation Note:

For each supported rating system, store a table that contains bitmasks for each level within that system. On object creation, initialize each bitmask to zero. Update the bitmasks in the put_BlockedRatingAttributes method.

In the TestRating method, use the enShowSystem and enShowLevel parameters to perform a table lookup and get the corresponding bitmask. If the BfIsBlocked flag is set in the bitmask, return S_OK. Otherwise, return S_OK if any of the attribute flags in lbfEnShowAttributes are also in the bitmask. Use a bitwise AND to test the bitmask.

The following code shows a possible implementation of this test. It assumes that the object stores the bitmasks in a two-dimensional array named Mask:

if ((0 != Mask[system][level] & BfIsBlocked) ||
    (0 != Mask[system][level] & attributes))
{
    return S_OK; // Blocked.
}
else
{
    return S_FALSE; // Not blocked.
}

See Also

  • IEvalRat Interface
  • Setting Allowable Viewing Levels


IXDSCodec Interface

This topic applies to Windows XP Service Pack 1 only.

The IXDSCodec interface is exposed by the XDS Codec filter. Most applications will not have to use this interface.

In addition to the methods inherited from IUnknown, the IXDSCodec interface exposes the following methods.

Method | Description
get_CCSubstreamService | Queries which line 21 data channels the XDS Codec filter sends to the XDSToRat object.
get_XDSToRatObjOK | Queries whether the XDSToRat object was created successfully.
GetContentAdvisoryRating | Retrieves the most recent ratings information parsed by the XDSToRat object.
GetXDSPacket | Retrieves the most recent XDS packet.
put_CCSubstreamService | Specifies which line 21 data channels the XDS Codec filter sends to the XDSToRat object.


IXDSCodec::get_CCSubstreamService

This topic applies to Windows XP Service Pack 1 only.

The get_CCSubstreamService method queries which line 21 data channels the XDS Codec filter sends to the XDSToRat object. By default, it sends just the Extended Data Services (XDS) channel.

Syntax

HRESULT get_CCSubstreamService(
    long  *pSubstreamMask
);

Parameters

pSubstreamMask

[out, retval] Pointer to a variable that receives a bitwise combination of zero or more KS_CC_SUBSTREAM flags.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IXDSCodec Interface


IXDSCodec::get_XDSToRatObjOK

This topic applies to Windows XP Service Pack 1 only.

The get_XDSToRatObjOK method queries whether the XDSToRat object was created successfully.

Syntax

HRESULT get_XDSToRatObjOK(
    HRESULT  *pHrCoCreateRetVal
);

Parameters

pHrCoCreateRetVal

[out, retval] Pointer to a variable that receives an HRESULT value. The HRESULT is the value that was returned when the filter called CoCreateInstance to create the XDSToRat object. If it equals S_OK, the EvalRat object was created successfully.

Return Values

Returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IXDSCodec Interface


IXDSCodec::GetContentAdvisoryRating

This topic applies to Windows XP Service Pack 1 only.

The GetContentAdvisoryRating method retrieves the most recent ratings information parsed by the XDSToRat object.

Syntax

HRESULT GetContentAdvisoryRating(
    PackedTvRating  *pRat
    long  *pPktSeqID
    long  *pCallSeqID
    REFERENCE_TIME  *pTimeStart
    REFERENCE_TIME  *pTimeEnd
);

Parameters

pRat

[out] Pointer to a variable that receives the most recent rating. The rating is packed into a format that is used internally by the XDS Codec filter, Encrypter/Tagger filter, and Decrypter/Detagger filter. It is not intended for use by other objects.

pPktSeqID

[out] Pointer to a variable that receives the number of ratings packets that have been decoded. This information can be used for diagnostic purposes.

pCallSeqID

[out] Pointer to a variable that receives the number of times this method has been called for the current ratings packet. This information can be used for diagnostic purposes.

pTimeStart

[out] Pointer to a variable that receives the start time of the sample that completed the ratings packet.

pTimeEnd

[out] Pointer to a variable that receives the stop time of the sample that completed the ratings packet.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IXDSCodec Interface


IXDSCodec::GetXDSPacket

This topic applies to Windows XP Service Pack 1 only.

The GetXDSPacket method retrieves the most recent XDS packet.

Syntax

HRESULT GetXDSPacket(
    long  *pXDSClassPkt
    long  *pXDSTypePkt
    BSTR  *pBstrXDSPkt
    long  *pPktSeqID
    long  *pCallSeqID
    REFERENCE_TIME  *pTimeStart
    REFERENCE_TIME  *pTimeEnd
);

Parameters

pXDSClassPkt

[out] Pointer to a variable that receives the packet class.

pXDSTypePkt

[out] Pointer to a variable that receives the class-specific packet type.

pBstrXDSPkt

[out] Pointer to a variable that receives the packet as a BSTR value.

pPktSeqID

[out] Pointer to a variable that receives the number of ratings packets that have been decoded. This information can be used for diagnostic purposes.

pCallSeqID

[out] Pointer to a variable that receives the number of times this method has been called for the current ratings packet. This information can be used for diagnostic purposes.

pTimeStart

[out] Pointer to a variable that receives the start time of the sample containing the packet.

pTimeEnd

[out] Pointer to a variable that receives the stop time of the sample containing the packet.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The returned BSTR contains binary data which might include embedded NULL characters. The caller must free the returned BSTR by calling SysFreeString.

See Also

  • IXDSCodec Interface


IXDSCodec::put_CCSubstreamService

This topic applies to Windows XP Service Pack 1 only.

The put_CCSubstreamService method specifies which line 21 data channels the XDS Codec filter sends to the XDSToRat object. By default, only the Extended Data Services (XDS) channel is supported.

Syntax

HRESULT put_CCSubstreamService(
    long  SubstreamMask
);

Parameters

SubstreamMask

[in] Bitwise combination of zero or more KS_CC_SUBSTREAM flags, specifying the line 21 services.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument
S_OK | Success

See Also

  • IXDSCodec Interface


IXDSToRat Interface

This topic applies to Windows XP Service Pack 1 only.

The IXDSToRat interface parses rating information from extended data services (XDS) information in line 21. This interface is exposed by the XDSToRat (ratings decoder) object. The XDSToRat object is implemented by third parties.

The XDS Codec filter uses this interface. Applications do not use this interface.

IID: IID_IXDSToRat

In addition to the methods inherited from IDispatch, the IXDSToRat interface exposes the following methods.

Method | Description
Init | Sets the XDSToRat object to its initial state.
ParseXDSBytePair | Parses a single byte pair from an XDS stream.


IXDSToRat::Init

This topic applies to Windows XP Service Pack 1 only.

The Init method sets the XDSToRat object to its initial state.

Syntax

HRESULT Init(void);

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The XDS Codec filter calls this method on startup or after a discontinuity, such as a channel change. The XDSToRat object should clear any internal buffers and reset its parsing state. This method prevents decoding errors caused by channel changes or other interruptions.

See Also

  • IXDSToRat Interface


IXDSToRat::ParseXDSBytePair

This topic applies to Windows XP Service Pack 1 only.

The ParseXDSBytePair method parses a single byte pair from an XDS stream. If the byte pair is the last pair in a completed ratings packet, the method returns the rating information.

Syntax

HRESULT ParseXDSBytePair(
  BYTE  byte1,
  BYTE  byte2,
  EnTvRat_System*  pEnSystem,
  EnTvRat_GenericLevel*  pEnLevel,
  LONG*  plBfEnAttributes
);

Parameters

byte1

[in] The first byte of the byte pair.

byte2

[in] The second byte of the byte pair.

pEnSystem

[out] Pointer to a variable that receives the rating system, as a member of the EnTvRat_System enumeration type.

pEnLevel

[out] Pointer to a variable that receives the rating level, as a member of the EnTvRat_GenericLevel enumeration type. The meaning of this value depends on the rating system.

plBfEnAttributes

[out] Pointer to a variable that receives a bitwise combination of zero or more flags from the BfEnTvRat_GenericAttributes enumeration. These flags specify additional content attributes, such as violence or adult language. They do not apply to every rating system.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
S_FALSE | The rating has not changed, or no rating has been detected in the stream yet.

Remarks

The XDS Codec filter calls this method to pass XDS data to the XDSToRat object, one pair of bytes at a time. The XDSToRat object must store enough information between calls to be able to parse a complete ratings packet.

This method returns S_FALSE until the XDSToRat object decodes a complete ratings packet. At that point, the method returns S_OK and returns the rating information in the pEnSystem, pEnLevel, and plBfEnAttributes parameters. Subsequent calls return S_FALSE again until the next packet is decoded.

Ratings values may be delivered by either the XDS Content Advisory packet, or the Composite Packet-1 packet. For details, see sections 9.5.1.5 and 9.5.1.10, respectively, of the EIA/CEA-608B specification.

This method should also detect the Current Class Program Identificaton Number and Program Name packets indicating the end of show and return an S_OK value along with the values in the following table.

Return the following values for non-ratings packets.

Parameter | Value
pEnSystem | TvRat-SystemDontKnow
pEnLevel | TvRat_LevelDontKnow
plBfEnAttributes | BfAttrNone

For details, see section 9.5.1.5.4 (General Content Advisory Requirements) of the EIA/CEA-608-B specification.

See Also

  • IXDSToRat Interface


TV Ratings Enumerations

This topic applies to Windows XP Service Pack 1 only.

The following enumerations are used by the TV Ratings objects.

Enumeration | Description
BfEnTvRat_Attributes_CAE_TV | Specifies content rating attributes in the English-Canadian television system.
BfEnTvRat_Attributes_CAF_TV | Specifies content rating attributes in the French-Canadian television system.
BfEnTvRat_Attributes_MPAA | Specifies content rating attributes in the MPAA rating system.
BfEnTvRat_Attributes_US_TV | Specifies content rating attributes in the US television system.
BfEnTvRat_GenericAttributes | Specifies content rating attributes that can be used for any rating system.
EnTvRat_CAE_TV | Specifies rating levels for English-Canadian television.
EnTvRat_CAF_TV | Specifies rating levels for French-Canadian television.
EnTvRat_GenericLevel | Specifies a generic range of rating levels.
EnTvRat_MPAA | Specifies rating levels in the MPAA rating system.
EnTvRat_System | Specifies a rating system.
EnTvRat_US_TV | Specifies rating levels for US television.

See Also

  • TV Ratings Reference


BfEnTvRat_Attributes_CAE_TV

This topic applies to Windows XP Service Pack 1 only.

The BfEnTvRat_Attributes_CAE_TV enumeration type specifies content rating attributes in the English-Canadian television system.

Syntax

typedef enum {
  CAE_IsBlocked  = BfIsBlocked,
  CAE_ValidAttrSubmask  = 1
} BfEnTvRat_Attributes_CAE_TV;

Elements

CAE_IsBlocked

Block playback.

CAE_ValidAttrSubmask

A bitmask of all valid attribute bits for the English-Canadian language rating system.

Remarks

This enumeration type maps BfEnTvRat_GenericAttributes flags to the English-Canadian television system. The only valid flag is CAE_IsBlocked.

See Also

  • Setting Allowable Viewing Levels


BfEnTvRat_Attributes_CAF_TV

This topic applies to Windows XP Service Pack 1 only.

The BfEnTvRat_Attributes_CAF_TV enumeration type specifies content rating attributes in the French-Canadian television system.

Syntax

typedef enum {
  CAF_IsBlocked         = BfIsBlocked,
  CAF_ValidAttrSubmask  = 1
} BfEnTvRat_Attributes_CAF_TV;

Members

CAF_IsBlocked

Block playback.

CAF_ValidAttrSubmask

A bitmask of all valid attribute bits for the French-Canadian rating system.

Remarks

This enumeration type maps BfEnTvRat_GenericAttributes flags to the French-Canadian television system. The only valid flag is CAF_IsBlocked.

See Also

  • Setting Allowable Viewing Levels


BfEnTvRat_Attributes_MPAA

This topic applies to Windows XP Service Pack 1 only.

The BfEnTvRat_Attributes_MPAA enumeration type specifies content rating attributes in the Motion Picture Association of America (MPAA) rating system.

Syntax

typedef enum {
  MPAA_IsBlocked         = BfIsBlocked,
  MPAA_ValidAttrSubmask  = 1
} BfEnTvRat_Attributes_MPAA;

Members

MPAA_IsBlocked

Block playback.

MPAA_ValidAttrSubmask

A bitmask of all valid attribute bits for the MPAA rating system.

Remarks

This enumeration type maps BfEnTvRat_GenericAttributes flags to the MPAA rating system. The only valid flag is MPAA_IsBlocked.

See Also

  • Setting Allowable Viewing Levels


BfEnTvRat_Attributes_US_TV

This topic applies to Windows XP Service Pack 1 only.

The BfEnTvRat_Attributes_US_TV enumeration type specifies content rating attributes in the US television system.

Syntax

typedef enum {
  US_TV_IsBlocked                   = BfIsBlocked,
  US_TV_IsViolent                   = BfIsAttr_1,
  US_TV_IsSexualSituation           = BfIsAttr_2,
  US_TV_IsAdultLanguage             = BfIsAttr_3,
  US_TV_IsSexuallySuggestiveDialog  = BfIsAttr_4,
  US_TV_ValidAttrSubmask            = 31
} BfEnTvRat_Attributes_US_TV;

Members

US_TV_IsBlocked

Block playback.

US_TV_IsViolent

Content contains violence.

US_TV_IsSexualSituation

Content contains sexual situations.

US_TV_IsAdultLanguage

Content contains adult language.

US_TV_IsSexuallySuggestiveDialog

Content contains sexually suggestive dialogue.

US_TV_ValidAttrSubmask

A bitmask of all valid attribute bits for the US TV ratings system.

Remarks

This enumeration type maps BfEnTvRat_GenericAttributes flags to the MPAA rating system.

See Also

  • EnTvRat_GenericLevel
  • Setting Allowable Viewing Levels


BfEnTvRat_GenericAttributes

This topic applies to Windows XP Service Pack 1 only.

The BfEnTvRat_GenericAttributes enumeration type specifies additional content-rating attributes that can be used for any rating system, including custom rating systems.

Syntax

typedef enum {
  BfAttrNone   =   0,
  BfIsBlocked  =   1
  BfIsAttr_1   =   2,
  BfIsAttr_2   =   4,
  BfIsAttr_3   =   8,
  BfIsAttr_4   =  16,
  BfIsAttr_5   =  32,
  BfIsAttr_6   =  64,
  BfIsAttr_7   = 128,
  BfValidAttrSubmask  = 255
} BfEnTvRat_GenericAttributes;

Members

BfAttrNone

No restrictions are in place.

BfIsBlocked

Block all content, regardless of other flags.

BfIsAttr_1

Generic attribute 1.

BfIsAttr_2

Generic attribute 2.

BfIsAttr_3

Generic attribute 3.

BfIsAttr_4

Generic attribute 4.

BfIsAttr_5

Generic attribute 5.

BfIsAttr_6

Generic attribute 6.

BfIsAttr_7

Generic attribute 7.

BfValidAttrSubmask

A bitmask of all valid attribute bits.

Remarks

The BfIsBlocked flag specifies that a program should be blocked regardless of the type of content. Flags in the range BfIsAttr_1 to BfIsAttr_7 represent generic content attributes, such as violence or adult language. Content attributes do not apply to every ratings system. For an example of how these generic attributes map to a particular system, see BfEnTvRat_Attributes_US_TV.

See Also

  • Setting Allowable Viewing Levels


EnTvRat_CAE_TV

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_CAE_TV enumeration type specifies rating levels for English-Canadian television.

Syntax

typedef enum {
  CAE_TV_Exempt    = TvRat_0,
  CAE_TV_C         = TvRat_1,
  CAE_TV_C8        = TvRat_2,
  CAE_TV_G         = TvRat_3,
  CAE_TV_PG        = TvRat_4,
  CAE_TV_14        = TvRat_5,
  CAE_TV_18        = TvRat_6,
  CAE_TV_Reserved  = TvRat_7
} EnTvRat_CAE_TV;

Members

CAE_TV_Exempt

E rating: Exempt.

CAE_TV_C

C rating: Children.

CAE_TV_C8

C8 rating: Children over 8 years.

CAE_TV_G

G rating: General.

CAE_TV_PG

PG rating: Parental Guidance.

CAE_TV_14

14+ rating: Over 14 years.

CAE_TV_18

18+ rating: Adults.

CAE_TV_Reserved

Not currently used.

Remarks

The values are based on the EnTvRat_GenericLevel enumeration values.

See Also

  • EnTvRat_CAF_TV
  • Setting Allowable Viewing Levels


EnTvRat_CAF_TV

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_CAF_TV enumeration type specifies a rating level for French-Canadian television.

Syntax

typedef enum {
  CAF_TV_Exempt     = TvRat_0,
  CAF_TV_G          = TvRat_1,
  CAF_TV_8          = TvRat_2,
  CAF_TV_13         = TvRat_3,
  CAF_TV_16         = TvRat_4,
  CAF_TV_18         = TvRat_5,
  CAF_TV_Reserved6  = TvRat_6,
  CAF_TV_Reserved   = TvRat_7
} EnTvRat_CAF_TV;

Members

CAF_TV_Exempt

E — Exemptées.

CAF_TV_G

G — Général.

CAF_TV_8

8 ans+ — Général-Déconseillé aux jeunes enfants.

CAF_TV_13

13 ans+ — Cette émission peut ne pas convenir aux enfants de moins de 13 ans.

CAF_TV_16

16 ans+ — Cette émission ne convient pas aux moins de 16 ans.

CAF_TV_18

18 ans+ — Cette émission est réservée aux adultes.

CAF_TV_Reserved6

Not currently used.

CAF_TV_Reserved

Not currently used.

Remarks

The values are based on the EnTvRat_GenericLevel enumeration values.

See Also

  • EnTvRat_CAE_TV
  • Setting Allowable Viewing Levels


EnTvRat_GenericLevel

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_GenericLevel enumeration type specifies a generic range of levels that correspond to levels currently in use, or can be used for a custom rating system.

Syntax

typedef enum {
  TvRat_0 = 0,
  TvRat_1 = 1,
  TvRat_2 = 2,
  TvRat_3 = 3,
  TvRat_4 = 4,
  TvRat_5 = 5,
  TvRat_6 = 6,
  TvRat_7 = 7,
  TvRat_kLevels = 8,
  TvRat_LevelDontKnow = 255
} EnTvRat_GenericLevel;

Members

TvRat_0

Generic level 0.

TvRat_1

Generic level 1.

TvRat_2

Generic level 2.

TvRat_3

Generic level 3.

TvRat_4

Generic level 4.

TvRat_5

Generic level 5.

TvRat_6

Generic level 6.

TvRat_7

Generic level 7.

TvRat_kLevels

Specifies the number of rating levels that are defined.

TvRat_LevelDontKnow

Rating level is currently unknown. This value is returned until a rating level is obtained from the XDS stream.

See Also

  • Setting Allowable Viewing Levels


EnTvRat_MPAA

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_MPAA enumeration type specifies a rating level in the Motion Picture Association of America (MPAA) rating system.

Syntax

typedef enum {
  MPAA_NotApplicable  = TvRat_0,
  MPAA_G              = TvRat_1,
  MPAA_PG             = TvRat_2,
  MPAA_PG13           = TvRat_3,
  MPAA_R              = TvRat_4,
  MPAA_NC17           = TvRat_5,
  MPAA_X              = TvRat_6,
  MPAA_NotRated       = TvRat_7
} EnTvRat_MPAA;

Members

MPAA_NotApplicable

MPAA rating is not applicable (for example, sports or news broadcasts).

MPAA_G

G rating.

MPAA_PG

PG rating.

MPAA_PG13

PG-13 rating.

MPAA_R

R rating.

MPAA_NC17

NC-17 rating.

MPAA_X

X rating.

MPAA_NotRated

The program is not rated by the MPAA.

Remarks

The values are based on the EnTvRat_GenericLevel enumeration values.

See Also

  • EnTvRat_GenericLevel
  • Setting Allowable Viewing Levels


EnTvRat_System

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_System enumeration type specifies the rating system in use.

Syntax

typedef enum {
  MPAA              = 0,
  US_TV             = 1,
  Canadian_English  = 2,
  Canadian_French   = 3,
  Reserved4         = 4,
  System5           = 5,
  System6           = 6,
  Reserved7         = 7,
  TvRat_kSystems    = 8,
  TvRat_SystemDontKnow  = 255
} EnTvRat_System;

Members

MPAA

MPAA rating system.

US_TV

US rating system.

Canadian_English

English-Canadian rating system.

Canadian_French

French-Canadian rating system.

Reserved4

Not used.

System5

System 5 in XDS rating table 19 (reserved for non–North American systems).

System6

System 6 in XDS rating table 19 (reserved for non–North American systems).

Reserved7

Not used.

TvRat_kSystems

Specifies the number of rating systems that can be defined.

TvRat_SystemDontKnow

System currently unknown. This value is used after channel changes or other stream discontinuities, until a valid rating is obtained from the stream.

Remarks

This enumeration is used by the IEvalRat and IXDSToRat interfaces to define the rating systems being used. When the EvalRat object is initialized, or when the stream changes (such as with a channel change) the default type is TvRat_SystemDontKnow.


EnTvRat_US_TV

This topic applies to Windows XP Service Pack 1 only.

The EnTvRat_US_TV enumeration type specifies rating levels in the US television rating system.

Syntax

typedef enum {
  US_TV_None  = TvRat_0,
  US_TV_Y     = TvRat_1,
  US_TV_Y7    = TvRat_2,
  US_TV_G     = TvRat_3,
  US_TV_PG    = TvRat_4,
  US_TV_14    = TvRat_5,
  US_TV_MA    = TvRat_6,
  US_TV_None7 = TvRat_7
} EnTvRat_US_TV;

Members

US_TV_None

No rating level used.

US_TV_Y

TVY — All children.

US_TV_Y7

TVY7 — Directed to older children.

US_TV_G

TVG — General audience.

US_TV_PG

TVPG — Parental guidance suggested.

US_TV_14

TV14 — Parents strongly cautioned.

US_TV_MA

TVMA — Mature audience only.

US_TV_None7

Not currently used.

See Also

  • EnTvRat_GenericLevel
  • Setting Allowable Viewing Levels


TV Ratings Broadcast Events

This topic applies to Windows XP Service Pack 1 only.

The TV Ratings components fire the following broadcast events.

TV rating event | Description
EVENTID_DTFilterDataFormatFailure | Sent by the Decrypter/Detagger filter if the data format is unreadable.
EVENTID_DTFilterDataFormatOK | Sent by the Decrypter/Detagger filter if the data format becomes readable after a previous failure.
EVENTID_DTFilterRatingChange | The current rating has changed. (Sent by the Decrypter/Detagger filter.)
EVENTID_DTFilterRatingsBlock | The Decrypter/Detagger filter has blocked the stream, because the rating is not allowed under the current permissions.
EVENTID_DTFilterRatingsUnblock | The Decrypter/Detagger filter has unblocked the stream.
EVENTID_DTFilterXDSPacket | Sent by the Decrypter/Detagger filter when it receives a new XDS packet.
EVENTID_ETDTFilterLicenseFailure | The Encrypter/Tagger filter or the Decrypter/Detagger filter failed to get an encryption/decryption license.
EVENTID_ETDTFilterLicenseOK | The Encrypter/Tagger filter or the Decrypter/Detagger filter succeeded in getting an encryption/decryption license. This event is fired only if a failure occurred earlier.
EVENTID_XDSCodecNewXDSPacket | Sent by the XDS Codec filter when it receives a non-ratings XDS packet.
EVENTID_XDSCodecDuplicateXDSRating | Sent by the XDS Codec filter when it receives a duplicate rating. (The event is not sent if the rating is unknown, or TvRat_SystemDontKnow)
EVENTID_XDSCodecNewXDSRating | Sent by the XDS Codec filter when it receives a new rating.

See Also

  • IBroadcastEvent Interface


Video Control C++ Reference

This topic applies to Windows XP only.

This section contains the reference documentation for the Microsoft® TV Technologies Video Control application programming interfaces (APIs). For more information on using these APIs, see Using the Video Control.

  • Video Control Objects (C++)
  • Video Control Interfaces
  • Video Control Event Interfaces
  • Video Control Enumerations


Video Control Objects (C++)

This topic applies to Windows XP only.

The following tables list the Video Control objects, grouped by functionality.

Video Control

The Video Control (MSVidCtl) is the primary object that a television application uses to display television, tune to channels, and so forth.

Object | Description
MSVidCtl | Represents the Video Control.

Devices

Devices represent components that the Video Control uses to display television. Devices include input devices, such as tuners, and output devices, such as audio renderers and video renderers.

Object | Description
MSVidAnalogTunerDevice | Represents a non-BDA analog TV tuner.
MSVidAudioRenderer | Represents the audio renderer.
MSVidBDATunerDevice | Represents a BDA-compatible TV tuner.
MSVidFilePlaybackDevice | Represents a file-playback filter.
MSVidStreamBufferSink | Represents a stream buffer output device.
MSVidStreamBufferSource | Represents a stream buffer source device.
MSVidVideoRenderer | Represents the video renderer.

Features

Features represent additional functionality that an application can activate, such as closed captioning and IP data services.

Object | Description
MSVidClosedCaptioning | Represents the closed captioning feature.
MSVidDataServices | Represents the data services feature.
MSVidEncoder | Represents the encoder feature.

Collections

Collection objects manage collections of other objects.

Object | Description
MSVidAudioRendererDevices | Represents a collection of audio renderers.
MSVidFeatures | Represents a collection of features.
MSVidInputDevices | Represents a collection of input devices.
MSVidOutputDevices | Represents a collection of output devices.
MSVidVideoRendererDevices | Represents a collection of video renderers.

Helper Objects

The following helper objects are used by other Video Control objects.

Object | Description
Broadcast Event Service | Handles broadcast events for the Filter Graph Manager.
MSVidRect | Represents a rectangle with an associated window.

Abstract Classes

The following objects represent abstract classes. They are never directly instantiated, and exist only to support polymorphism.

Object | Description
MSVidInputDevice | Represents an input device.
MSVidOutputDevice | Represents an output device.
MSVidVideoInputDevice | Represents a video input device.
MSVidFeature | Represents a feature supported by the Video Control.


Broadcast Event Service

The Broadcast Event Service object handles broadcast events for the Filter Graph Manager. For more information, see IBroadcastEvent.

Interfaces | IBroadcastEvent, IConnectionPoint
Outgoing Event Interfaces | None

See Also

  • Video Control Objects (C++)


MSVidAnalogTunerDevice

This topic applies to Windows XP only.

The MSVidAnalogTunerDevice object represents a non-BDA analog TV tuner.

Interfaces | IMSVidAnalogTuner
Outgoing Event Interfaces | IMSVidAnalogTunerEvent

Remarks

If the current input device is a non-BDA analog tuner, you can obtain this object by calling the IMSVidCtl::get_InputActive method on the Video Control. Also, if the user's system contains a non-BDA analog tuner, you can obtain this object by calling the IMSVidCtl::get__InputsAvailable method.

See Also

  • Video Control Objects (C++)


MSVidAudioRenderer

This topic applies to Windows XP only.

The MSVidAudioRenderer object represents the audio renderer.

Interfaces | IMSVidAudioRenderer
Outgoing Event Interfaces | IMSVidAudioRendererEvent

Remarks

To obtain this object, either call the IMSVidCtl::get_AudioRendererActive method, or call the IMSVidCtl::get_AudioRenderersAvailable method and enumerate the returned collection.

See Also

  • Video Control Objects (C++)


MSVidAudioRendererDevices

This topic applies to Windows XP only.

The MSVidAudioRendererDevices object represents a collection of audio renderers.

Interfaces | IMSVidAudioRendererDevices
Outgoing Event Interfaces | None.

Remarks

You can obtain this object by calling the IMSVidCtl::get_AudioRenderersAvailable method.

See Also

  • Video Control Objects (C++)


MSVidBDATunerDevice

This topic applies to Windows XP only.

The MSVidBDATunerDevice object represents a BDA-compatible digital TV tuner.

Interfaces | IMSVidTuner
Outgoing Event Interfaces | IMSVidTunerEvent

Remarks

If the current input device is a BDA-compatible digital tuner, you can obtain this object by calling the IMSVidCtl::get_InputActive method on the Video Control. Also, if the user's system contains a BDA-compatible digital tuner, you can obtain this object by calling the IMSVidCtl::get__InputsAvailable method.

See Also

  • Video Control Objects (C++)


MSVidClosedCaptioning

This topic applies to Windows XP only.

The MSVidClosedCaptioning object represents the closed captioning feature.

Interfaces | IMSVidClosedCaptioning, IMSVidClosedCaptioning2
Outgoing Event Interfaces | None.

Remarks

To obtain this object, call the IMSVidCtl::get_FeaturesActive method or the IMSVidCtl::get_FeaturesAvailable method and enumerate the returned collection.

See Also

  • Displaying Closed Captioning in C++
  • Video Control Objects (C++)


MSVidCtl

This topic applies to Windows XP only.

The MSVidCtl object, also called the Video Control, is the primary object that television applications use to display digital or analog television. It can also be used to control DVD playback.

Interfaces | IMSVidCtl
Outgoing Event Interfaces | _IMSVidCtlEvents

See Also

  • TV Applications in C++ (Video Control)


MSVidDataServices

This topic applies to Windows XP only.

The MSVidDataServices object represents the data services feature.

Interfaces | IMSVidDataServices
Outgoing Event Interfaces | None

Remarks

The IMSVidDataServices interface inherits from IMSVidDevice, but adds no new methods or properties.

To obtain this object, call the IMSVidCtl::get_FeaturesActive or IMSVidCtl::get_FeaturesAvailable method and enumerate the returned collection.

See Also

  • Video Control Objects (C++)


MSVidEncoder

This topic applies to Windows XP Service Pack 1 only.

The MSVidEncoder object represents the encoder feature, which is required for using the Stream Buffer Engine with the Video Control.

Interfaces | IMSVidEncoder
Outgoing Event Interfaces | None

Remarks

To obtain this object, call the IMSVidCtl::get_FeaturesAvailable method and enumerate the returned collection.

See Also

  • Using the Stream Buffer Engine with the Video Control
  • Video Control Objects (C++)


MSVidFeature

This topic applies to Windows XP only.

The MSVidFeature object represents any of the features supported by the Video Control.

Interfaces | IMSVidFeature
Outgoing Event Interfaces | None.

Remarks

This object represents an abstract class. It is never directly instantiated, and exists only to support polymorphism.

See Also

  • MSVidClosedCaptioning
  • MSVidDataServices
  • MSVidEncoder
  • Video Control Objects (C++)


MSVidFeatures

This topic applies to Windows XP only.

The MSVidFeatures object represents a collection of features.

Interfaces | IMSVidFeatures
Outgoing Event Interfaces | None.

Remarks

To obtain the collection of features that are currently active, call the IMSVidCtl::get_FeaturesActive method. To obtain the collection of all the features that are available, call the IMSVidCtl::get_FeaturesAvailable method.

To set the active features, create an empty MSVidFeatures object using CoCreateInstance. Enumerate the available features collection, and add the features that you want to activate into the new MSVidFeatures object. Then call the IMSVidCtl::put_FeaturesActive method with a pointer to your MSVidFeatures object.

See Also

  • Video Control Objects (C++)


MSVidFilePlaybackDevice

This topic applies to Windows XP Service Pack 1 only.

The MSVidFilePlaybackDevice object represents a file-playback filter.

Interfaces | IMSVidFilePlayback
Outgoing Event Interfaces | IMSVidFilePlaybackEvent

See Also

  • Video Control Objects (C++)


MSVidInputDevice

This topic applies to Windows XP only.

The MSVidInputDevice object represents an input device, such as a tuner.

Interfaces | IMSVidInputDevice
Outgoing Event Interfaces | None.

Remarks

This object represents an abstract class. It is never directly instantiated, and exists only to support polymorphism.

See Also

  • MSVidAnalogTunerDevice
  • MSVidBDATunerDevice
  • Video Control Objects (C++)


MSVidInputDevices

This topic applies to Windows XP only.

The MSVidInputDevices object represents a collection of input devices.

Interfaces | IMSVidInputDevices
Outgoing Event Interfaces | None.

Remarks

To obtain this collection , call the IMSVidCtl::get_InputsAvailable method.

See Also

  • Video Control Objects (C++)


MSVidOutputDevice

This topic applies to Windows XP only.

The MSVidOutputDevice object represents an output device.

Interfaces | IMSVidOutputDevice
Outgoing Event Interfaces | None.

Remarks

This object represents an abstract class. It is never directly instantiated, and exists only to support polymorphism.

See Also

  • MSVidAudioRenderer
  • MSVidVideoRenderer
  • Video Control Objects (C++)


MSVidOutputDevices

This topic applies to Windows XP only.

The MSVidOutputDevices object represents a collection of output devices.

Interfaces | IMSVidOutputDevices
Outgoing Event Interfaces | None.

See Also

  • Video Control Objects (C++)


MSVidRect

This topic applies to Windows XP only.

The MSVidRect object represents a rectangle.

Interfaces | IMSVidRect
Outgoing Event Interfaces | None.

See Also

  • Video Control Objects (C++)


MSVidStreamBufferSink

This topic applies to Windows XP Service Pack 1 only.

The MSVidStreamBufferSink object represents a stream buffer output device.

Interfaces | IMSVidStreamBufferSink
Outgoing Event Interfaces | IMSVidStreamBufferSinkEvent

See Also

  • Using the Stream Buffer Engine with the Video Control
  • Video Control Objects (C++)


MSVidStreamBufferSource

This topic applies to Windows XP Service Pack 1 only.

The MSVidStreamBufferSource object represents a stream buffer source device.

Interfaces | IMSVidStreamBufferSource
Outgoing Event Interfaces | IMSVidStreamBufferSourceEvent

See Also

  • Using the Stream Buffer Engine with the Video Control
  • Video Control Objects (C++)


MSVidVideoInputDevice

This topic applies to Windows XP only.

The MSVidVideoInputDevice object represents a video input device.

Interfaces | IMSVidVideoInputDevice
Outgoing Event Interfaces | None.

Remarks

This object represents an abstract class. It is never directly instantiated, and exists only to support polymorphism.

See Also

  • MSVidAnalogTunerDevice
  • MSVidBDATunerDevice
  • Video Control Objects (C++)


MSVidVideoRenderer

This topic applies to Windows XP only.

The MSVidVideoRenderer object represents a video renderer.

Interfaces | IMSVidVideoRenderer, IMSVidVideoRenderer2
Outgoing Event Interfaces | IMSVidVideoRendererEvent

See Also

  • Video Control Objects (C++)


MSVidVideoRendererDevices

This topic applies to Windows XP only.

The MSVidVideoRendererDevices object represents a collection of video renderers.

Interfaces | IMSVidVideoRendererDevices
Outgoing Event Interfaces | None.

Remarks

To obtain this collection, call the IMSVidCtl::get_VideoRenderersAvailable method. In practice, this collection will only contain a single object, representing the Video Mixing Renderer filter.

See Also

  • Video Control Objects (C++)


Video Control Interfaces

This topic applies to Windows XP only.

The following table lists the interfaces implemented by the Video Control and its related objects.

Interface | Description
IBroadcastEvent | Enables an object to receive events from another object without setting up a direct connection point.
IMSVidAnalogTuner | Represents an analog-only tuner card that does not support the Broadcast Driver Architecture (BDA).
IMSVidAudioRenderer | Represents an audio renderer device.
IMSVidAudioRendererDevices | Represents a collection of audio renderers.
IMSVidClosedCaptioning | Enables or disables closed captioning.
IMSVidClosedCaptioning2 | Sets the closed captioning service.
IMSVidCtl | The primary interface for the Video Control.
IMSVidDataServices | Represents the data services feature.
IMSVidDevice | Base interface for all the devices and features that the Video Control supports.
IMSVidEncoder | Represents the MSVidEncoder feature.
IMSVidFeature | Represents a feature that is available through the Video Control, such as data services or closed captioning.
IMSVidFeatures | Represents a collection of Video Control features.
IMSVidFilePlayback | Enables the client to specify a local file for playback.
IMSVidGraphSegmentContainer | Obtains a pointer the Filter Graph Manager.
IMSVidInputDevice | Represents any input device that is recognized by the Video Control, such as a television tuner card.
IMSVidInputDevices | Represents a collection of input devices.
IMSVidOutputDevice | Represents an output device.
IMSVidOutputDevices | Represents a collection of output devices.
IMSVidPlayback | Controls a playback device.
IMSVidRect | Represent a rectangle with an associated window handle.
IMSVidStreamBufferRecordingControl | Enables an application to manage a stream buffer recording object through the Video Control.
IMSVidStreamBufferSink | Represents a stream buffer output device.
IMSVidStreamBufferSource | Represents a stream buffer source object.
IMSVidTuner | Manages tuning devices.
IMSVidVideoInputDevice | Represents a video input device.
IMSVidVideoRenderer | Represents a video renderer device.
IMSVidVideoRenderer2 | Represents a video renderer device.
IMSVidVideoRendererDevices | Represents a collection of video renderers.


IBroadcastEvent Interface

This topic applies to Windows XP only.

The IBroadcastEvent interface enables an object to receive events from another object without setting up a direct connection point. Applications typically do not need to use this interface.

In addition to the methods inherited from IUnknown, the IBroadcastEvent interface exposes the following method.

Method | Description
Fire | Fires an event.

Remarks

Broadcast events enable communication among DirectShow filters, Video Control features, and Video Control device objects. To send a broadcast event, an object calls IBroadcastEvent::Fire on the Broadcast Event Service object. Other objects can listen for events by setting up a connection point with the Broadcast Event Service object. The listener implements IBroadcastEvent and the Broadcast Event Service object calls the listener's Fire method whenever there is a new broadcast event.

Broadcast events are useful for several reasons:

  • The DirectShow event mechanism, IMediaEventSink, does not support multiple listeners. DirectShow events go onto a queue, and retrieving an event removes it from the queue.
  • COM connection points require the sink object to locate the source object. With broadcast events, the Broadcast Event Service acts as a relay between the source object and the sink object.
  • In a connection point, the source must fire events on the same thread that the sink used to establish the connection, or else marshal the event interface pointer. Filter graphs are multithreaded, so the Broadcast Event Service object implements the necessary marshaling. It uses a background thread to distribute events to all the registered listeners.

The IBroadcastEvent interface is a service, which can be obtained through the Filter Graph Manager's IServiceProvider interface. To do so, call IServiceProvider::QueryService and specify the following values:

  • Service identifier: SID_SBroadcastEventService.
  • Interface identifier: IID_IBroadcastEvent

A failure code from QueryService indicates that no object has yet registered the Broadcast Event Service object with the Filter Graph Manager. In that case, do the following:

  1. Create a new Broadcast Event Service object, using CoCreateInstance.
  2. Query the Filter Graph Manager for IRegisterServiceProvider.
  3. Call IRegisterServiceProvider::RegisterService with the service identifier.

Once you have a pointer to the IBroadcastEvent interface, you can use it either to send events or to sink events. To send events, call the Fire method. To sink events, implement IBroadcastEvent on the sink object, query the Broadcast Event Service for IConnectionPoint, and call IConnectionPoint::Advise to establish the connection. For a list of defined broadcast events, see IBroadcastEvent::Fire.

Example Code

The following example implements a class that can source or sink broadcast events:

class TunerEvent : public IBroadcastEvent
{

private:
    long m_nRefCount; // Holds the reference count.
public:
    // IUnknown methods
    STDMETHODIMP_(ULONG) AddRef()
    {
        return InterlockedIncrement(&m_nRefCount);
    }
    STDMETHODIMP_(ULONG) Release()
    {
        _ASSERT(m_nRefCount >= 0);
        ULONG uCount = InterlockedDecrement(&m_nRefCount);
        if (uCount == 0)
        {
            delete this;
        }
        // Return the temporary variable, not the member
        // variable, for thread safety.
        return uCount;
    }
    STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject)
    {
        if (NULL == ppvObject)
            return E_POINTER;
        if (riid == __uuidof(IUnknown))
            *ppvObject = static_cast<IUnknown*>(this);
        else if (riid == __uuidof(IBroadcastEvent))
            *ppvObject = static_cast<IBroadcastEvent*>(this);
        else
            return E_NOINTERFACE;
        AddRef();
        return S_OK;
    }

    // The one IBroadcastEvent method
    STDMETHOD(Fire)(GUID eventID)
    {
        // The one defined event
        if (eventID == EVENTID_TuningChanged)
        {
            // The tuner changed stations or channels.
        }

        return S_OK;
    }

    TunerEvent() : m_dwBroadcastEventCookie(0), m_nRefCount(1) {};

private:
    HRESULT HookupGraphEventService(IFilterGraph *pGraph);
    HRESULT RegisterForTunerEvents();
    HRESULT UnRegisterForTunerEvents();
    HRESULT Fire_Event(GUID eventID);

    CComPtr<IBroadcastEvent>   m_spBroadcastEvent;
    DWORD m_dwBroadcastEventCookie;
};

// Query the Filter Graph Manager for the broadcast event service.
// If not found, create it and register it.
HRESULT TunerEvent::HookupGraphEventService(IFilterGraph *pGraph)
{
    HRESULT hr = S_OK;
    if (!m_spBroadcastEvent)
    {
        CComQIPtr<IServiceProvider> spServiceProvider(pGraph);
        if (!spServiceProvider)
        {
            return E_NOINTERFACE;
        }
        hr = spServiceProvider->QueryService(SID_SBroadcastEventService,
            IID_IBroadcastEvent,
            reinterpret_cast<void**>(&m_spBroadcastEvent));
        if (FAILED(hr))
        {
            // Create the Broadcast Event Service object.
            hr = m_spBroadcastEvent.CoCreateInstance(
                CLSID_BroadcastEventService,
                NULL, CLSCTX_INPROC_SERVER);
            if (FAILED(hr))
            {
                return hr;
            }

            CComQIPtr<IRegisterServiceProvider> spRegService(pGraph);
            if (!spRegService)
            {
                return E_NOINTERFACE;
            }

            // Register the Broadcast Event Service object as a service.
            hr = spRegService->RegisterService(
                SID_SBroadcastEventService,
                m_spBroadcastEvent);
        }
    }
    return hr;
}

// Establish the connection point to receive events.
HRESULT TunerEvent::RegisterForTunerEvents()
{
    if (!m_spBroadcastEvent)
    {
        return E_FAIL;  // Forgot to call HookupGraphEventService.
    }
    if(m_dwBroadcastEventCookie)
    {
        return S_FALSE;  // There is already a connection; nothing to do.
    }
    CComQIPtr<IConnectionPoint> spConnectionPoint(m_spBroadcastEvent);
    if(!spConnectionPoint)
    {
        return E_NOINTERFACE;
    }
    return spConnectionPoint->Advise(static_cast<IBroadcastEvent*>(this),
        &m_dwBroadcastEventCookie);
}

// Un-register for events.
HRESULT TunerEvent::UnRegisterForTunerEvents()
{
    HRESULT hr = S_OK;
    if(!m_dwBroadcastEventCookie)
    {
        return S_OK; // Not registered for events; nothing to do.
    }
    CComQIPtr<IConnectionPoint> spConnectionPoint(m_spBroadcastEvent);
    if(!spConnectionPoint)
    {
        return E_NOINTERFACE;
    }

    // Release the connection point.
    hr = spConnectionPoint->Unadvise(m_dwBroadcastEventCookie);
    if (FAILED(hr))
    {
        // Error: Unable to unadvise the connection point.
        return hr;
    }
    m_dwBroadcastEventCookie = 0;
    m_spBroadcastEvent.Release();
    return S_OK;
}

// Send an event (for source objects).
HRESULT TunerEvent::Fire_Event(GUID eventID)
{
    if (!m_spBroadcastEvent)
    {
        return E_FAIL; // Forgot to call HookupGraphEventService.
    }
    return m_spBroadcastEvent->Fire(eventID);
}


IBroadcastEvent::Fire

The Fire method fires a broadcast event.

Syntax

HRESULT Fire(
  GUID  EventID
);

Parameters

EventID

GUID that specifies the event.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

For television tuning, the following event is defined.

Tuner Event | Description
EVENTID_TuningChanged | Fired when the tuner changes stations or channels.

See Also

  • IBroadcastEvent Interface
  • TV Ratings Broadcast Events


IMSVidAnalogTuner Interface

This topic applies to Windows XP only.

The IMSVidAnalogTuner interface represents an analog-only tuner card that does not support the Broadcast Driver Architecture (BDA). This interface provides Automation access to the IAMTVTuner and IAMTVAudio interfaces.

In addition to the methods inherited from IMSVidTuner, the IMSVidAnalogTuner interface exposes the following methods.

Method | Description
ChannelAvailable | Queries whether a specified channel is available for viewing.
get_AudioFrequency | Retrieves the tuner's audio frequency.
get_Channel | Retrieves the tuner's channel setting.
get_CountryCode | Retrieves the tuner's country/region code.
get_SAP | Retrieves the tuner's SAP setting to enable secondary audio components.
get_VideoFrequency | Retrieves the tuner's video frequency.
put_Channel | Specifies the tuner's channel setting.
put_CountryCode | Specifies the tuner's country/region code.
put_SAP | Specifies the tuner's SAP setting to enable secondary audio components.


IMSVidAnalogTuner::ChannelAvailable

This topic applies to Windows XP only.

The ChannelAvailable method queries whether a specified channel is available for viewing.

This method is currently not supported.

Syntax

HRESULT ChannelAvailable(
  long  nChannel,
  long*  pSignalStrength,
  VARIANT_BOOL*  pfSignalPresent
);

Parameters

nChannel

[in] Integer containing the channel.

pSignalStrength

[in, out] Specifies the signal strength.

pfSignalPresent

[out] Flag indicating whether a signal is present.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IAMTuner::SignalPresent
  • IMSVidAnalogTuner Interface


IMSVidAnalogTuner::get_AudioFrequency

This topic applies to Windows XP only.

The get_AudioFrequency method retrieves the tuner's audio frequency.

Syntax

HRESULT get_AudioFrequency(
  long* plcc
);

Parameters

plcc

[out] Pointer to a variable that receives the audio frequency, in hertz (Hz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is intended for diagnostic and testing purposes.

See Also

  • IAMTVTuner::get_AudioFrequency
  • IMSVidAnalogTuner Interface


IMSVidAnalogTuner::get_Channel

This topic applies to Windows XP only.

The get_Channel method retrieves the tuner's current channel.

Syntax

HRESULT get_Channel(
  long* pChannel
);

Parameters

pChannel

[out] Pointer to a variable that receives the channel.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IAMTuner::get_Channel
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::put_Channel


IMSVidAnalogTuner::get_CountryCode

This topic applies to Windows XP only.

The get_CountryCode method retrieves the tuner's country/region code.

Syntax

HRESULT get_CountryCode(
  long* plcc
);

Parameters

plcc

[out] Pointer to a variable that receives the country/region code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Do not confuse the international country/region code with the LCID. The country/region code establishes the mapping between channel numbers and frequencies.

See Also

  • IAMTuner::get_CountryCode
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::put_CountryCode
  • International Analog TV Tuning


IMSVidAnalogTuner::get_SAP

This topic applies to Windows XP only.

The get_SAP method retrieves the tuner's SAP setting to enable secondary audio components.

This method is currently not supported.

Syntax

HRESULT get_SAP(
  VARIANT_BOOL*  pfSapOn
);

Parameters

pfSapOn

[out] Pointer to a flag indicating whether SAP is on.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IAMTVAudio Interface
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::put_SAP


IMSVidAnalogTuner::get_VideoFrequency

This topic applies to Windows XP only.

The get_VideoFrequency method retrieves the tuner's video frequency for testing purposes.

Syntax

HRESULT get_VideoFrequency(
  long* plcc
);

Parameters

plcc

[out] Pointer to a variable that receives the video frequency, in hertz (Hz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is intended for diagnostic and testing purposes.

See Also

  • IAMTVTuner::get_VideoFrequency
  • IMSVidAnalogTuner Interface


IMSVidAnalogTuner::put_Channel

This topic applies to Windows XP only.

The put_Channel method specifies the tuner's channel.

Syntax

HRESULT put_Channel(
  long  Channel
);

Parameters

Channel

[in] Specifies the channel.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IAMTuner::put_Channel
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::get_Channel


IMSVidAnalogTuner::put_CountryCode

This topic applies to Windows XP only.

The put_CountryCode method specifies the tuner's country/region code.

Syntax

HRESULT put_CountryCode(
  long  lcc
);

Parameters

lcc

[in] Specifies the international country/region code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Do not confuse the international country/region code with the LCID. The country/region code establishes the mapping between channel numbers and frequencies.

See Also

  • IAMTuner::put_CountryCode
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::get_CountryCode
  • International Analog TV Tuning


IMSVidAnalogTuner::put_SAP

This topic applies to Windows XP only.

The put_SAP method specifies the tuner's SAP setting to enable secondary audio components.

This method is currently not supported.

Syntax

HRESULT put_SAP(
  VARIANT_BOOL  fSapOn
);

Parameters

fSapOn

[in] Flag indicating whether to enable or disable SAP.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IAMTVAudio Interface
  • IMSVidAnalogTuner Interface
  • IMSVidAnalogTuner::get_SAP


IMSVidAudioRenderer Interface

This topic applies to Windows XP only.

The IMSVidAudioRenderer interface represents an audio renderer device. It enables applications to control the volume and balance. To retrieve the audio renderer device that is currently active, call the IMSVidCtl::get_AudioRendererActive method.

In addition to the methods inherited from IMSVidOutputDevice, the IMSVidAudioRenderer interface exposes the following methods.

Method | Description
get_Balance | Retrieves the balance level.
get_Volume | Retrieves the volume level.
put_Balance | Specifies the balance level.
put_Volume | Specifies the volume level.


IMSVidAudioRenderer::get_Balance

This topic applies to Windows XP only.

The get_Balance method retrieves the audio renderer's balance level.

Syntax

HRESULT get_Balance(
  long* plBal
);

Parameters

plBal

[out] Pointer to a variable that receives the balance level.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The balance level is a value between –10,000 and 10,000, measured in hundredths of a decibel (dB). If the value is -10,000, the left channel is at full volume and the right channel is attenuated by 100 dB. If the value is 10,000, the right channel is at full volume and the left channel is attenuated by 100 dB. If the value is zero, both channels are at full volume.

See Also

  • IBasicAudio::get_Balance
  • IMSVidAudioRenderer Interface
  • IMSVidAudioRenderer::put_Balance


IMSVidAudioRenderer::get_Volume

This topic applies to Windows XP only.

The get_Volume method retrieves the audio renderer's volume level.

Syntax

HRESULT get_Volume(
  long* plVol
);

Parameters

plVol

[out] Pointer to a variable that receives the volume level, in units of .01 decibel (dB).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Full volume is 0 and silence is –10,000. Divide by 100 to get the equivalent decibel value; for example, –10,000 is –100 dB.

See Also

  • IBasicAudio::get_Volume
  • IMSVidAudioRenderer Interface
  • IMSVidAudioRenderer::put_Volume


IMSVidAudioRenderer::put_Balance

This topic applies to Windows XP only.

The put_Balance method specifies the audio renderer's balance level.

Syntax

HRESULT put_Balance(
  long lBal
);

Parameters

lBal

[in] Specifies the balance level.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The balance level is a value between –10,000 and 10,000, measured in hundredths of a decibel (dB). If the value is -10,000, the left channel is at full volume and the right channel is attenuated by 100 dB. If the value is 10,000, the right channel is at full volume and the left channel is attenuated by 100 dB. If the value is zero, both channels are at full volume.

See Also

  • IBasicAudio::put_Balance
  • IMSVidAudioRenderer Interface
  • IMSVidAudioRenderer::get_Balance


IMSVidAudioRenderer::put_Volume

This topic applies to Windows XP only.

The put_Volume method specifies the audio renderer's volume level.

Syntax

HRESULT put_Volume(
  long lVol
);

Parameters

lVol

[in] Specifies the volume level, in units of .01 decibel (dB).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Full volume is 0 and silence is –10,000. Multiply the desired decibel level by 100; for example, –100 dB is -10,000.

See Also

  • IBasicAudio::put_Volume
  • IMSVidAudioRenderer Interface
  • IMSVidAudioRenderer::get_Volume


IMSVidAudioRendererDevices Interface

This topic applies to Windows XP only.

The IMSVidAudioRendererDevices interface represents a collection of audio renderers. Applications can use this interface to enumerate the collection. The MSVidAudioRendererDevices object exposes this method.

In addition to the methods inherited from IDispatch, the IMSVidAudioRendererDevices interface exposes the following methods.

Method | Description
Add | Adds an audio renderer to the collection.
get_Count | Retrieves the number of items in the collection.
get_Item | Retrieves the specified item from the collection
get__NewEnum | Retrieves an enumerator for the collection.
Remove | Removes an item from the collection.


IMSVidAudioRendererDevices::Add

This topic applies to Windows XP only.

The Add method adds an audio renderer to the collection.

Syntax

HRESULT Add(
  IMSVidAudioRenderer* pDB
);

Parameters

pDB

[in] Specifies a pointer to the audio renderer's IMSVidAudioRenderer interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ACCESSDENIED | The collection is read-only; cannot add any items.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidAudioRendererDevices Interface


IMSVidAudioRendererDevices::get_Count

This topic applies to Windows XP only.

The get_Count method retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
  long*  plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the number of items.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidAudioRendererDevices Interface


IMSVidAudioRendererDevices::get_Item

This topic applies to Windows XP only.

The get_Item method retrieves the specified item from the collection.

Syntax

HRESULT get_Item(
  VARIANT  v,
  IMSVidAudioRenderer**  ppDB
);

Parameters

v

[in] VARIANT that specifies the index of the item to retrieve.

ppDB

[out] Address of a variable that receives an IMSVidAudioRenderer interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidAudioRendererDevices::get_Count - 1.

If the method succeeds, the IMSVidAudioRenderer interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidAudioRendererDevices Interface


IMSVidAudioRendererDevices::get__NewEnum

This topic applies to Windows XP only.

The get__NewEnum method retrieves an enumerator for the collection.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT **ppD
);

Parameters

ppD

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method is provided so that Automation clients can iterate through the collection using a For...Each loop.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread. (C++ applications should generally use the IMSVidAudioRendererDevices::get_Item method instead.)

If the method succeeds, the IEnumVARIANT interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidAudioRendererDevices Interface


IMSVidAudioRendererDevices::Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

HRESULT Remove(
  VARIANT  v
);

Parameters

v

[in] VARIANT that specifies the index of the item to remove.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_ACCESSDENIED | The collection is read-only; cannot remove any items.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidAudioRendererDevices::get_Count - 1.

See Also

  • IMSVidAudioRendererDevices::Add
  • IMSVidAudioRendererDevices Interface


IMSVidClosedCaptioning Interface

This topic applies to Windows XP only.

The IMSVidClosedCaptioning interface enables or disables closed captions. The MSVidClosedCaptioning feature exposes this interface.

To obtain this interface, enumerate the collection of available features on the Video Control. To use closed captioning, activate the closed captioning feature before you build the graph. Once the feature is active, you can enable or disable the closed captioning display by calling the IMSVidClosedCaptioning::put_Enable method.

In addition to the methods inherited from IMSVidFeature, the IMSVidClosedCaptioning interface exposes the following methods.

Method | Description
get_Enable | Queries whether closed captioning is enabled.
put_Enable | Enables or disables closed captioning.

See Also

  • Displaying Closed Captioning in C++


IMSVidClosedCaptioning::get_Enable

This topic applies to Windows XP only.

The get_Enable method queries whether closed captioning is enabled.

Syntax

HRESULT get_Enable(
  VARIANT_BOOL* pOn
);

Parameters

pOn

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_TRUE | Closed captioning is enabled.
VARIANT_FALSE | Closed captioning is disabled.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidClosedCaptioning Interface
  • IMSVidClosedCaptioning::put_Enable


IMSVidClosedCaptioning::put_Enable

This topic applies to Windows XP only.

The put_Enable method enables or disables closed captioning.

Syntax

HRESULT put_Enable(
  VARIANT_BOOL  On
);

Parameters

On

[in] Specifies whether to enable or disable the closed captioning feature. Use one of the following values.

Value | Description
VARIANT_TRUE | Enable closed captioning.
VARIANT_FALSE | Disable closed captioning.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidClosedCaptioning Interface
  • IMSVidClosedCaptioning::get_Enable


IMSVidClosedCaptioning2 Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidClosedCaptioning2 interface sets the closed captioning service, such as CC1 or CC2. The MSVidClosedCaptioning feature exposes this interface.

In addition to the methods inherited from IMSVidClosedCaptioning, the IMSVidClosedCaptioning2 interface exposes the following methods.

Method | Description
get_Service | Retrieves the current closed captioning service.
put_Service | Sets the closed captioning service.


IMSVidClosedCaptioning2::get_Service

This topic applies to Windows XP Service Pack 1 only.

The get_Service method retrieves the current closed captioning service.

Syntax

HRESULT get_Service(
  MSVidCCService *pService
);

Parameters

pService

[out] Pointer to a variable that receives a member of the MSVidCCService enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • IMSVidClosedCaptioning2 Interface


IMSVidClosedCaptioning2::put_Service

This topic applies to Windows XP Service Pack 1 only.

The get_Service method sets the closed captioning service.

Syntax

HRESULT put_Service(
  MSVidCCService Service
);

Parameters

Service

[in] Specifies the closed captioning service, as a member of the MSVidCCService enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

See Also

  • IMSVidClosedCaptioning2 Interface


IMSVidCtl Interface

This topic applies to Windows XP only.

The IMSVidCtl interface is the main interface for the Video Control. It contains methods to enumerate available devices and features, and to select which features and devices will be active. It also contains methods to build, stop, start, and pause the filter graph.

In addition to the methods inherited from IDispatch, the IMSVidCtl interface exposes the following methods.

Method | Description
Build | Builds the underlying filter graph and connects all the filters.
Decompose | Disassembles the filter graph.
DisableAudio | Disables the audio output device.
DisableVideo | Disables the video output device.
get__InputsAvailable | Retrieves a collection of inputs available on the local system.
get__OutputsAvailable | Retrieves a collection of outputs for a specified category that are available on the local system.
get_AudioRendererActive | Retrieves the currently active audio renderer.
get_AudioRenderersAvailable | Retrieves a collection containing the available audio renderers.
get_AutoSize | Retrieves a value that determines whether the Video Control is automatically resized to display its entire contents.
get_BackColor | Retrieves the background color of the Video Control.
get_ColorKey | Retrieves the color key.
get_DisplaySize | Retrieves the display size.
get_Enabled | Retrieves a value that determines whether the Video Control can respond to user-generated events.
get_FeaturesActive | Retrieves a collection of the features currently active.
get_FeaturesAvailable | Retrieves a collection of features available on the local system.
get_InputActive | Retrieves the currently active input device.
get_InputsAvailable | Retrieves a collection of inputs available on the local system.
get_MaintainAspectRatio | Retrieves a value indicating whether the Video Control should maintain the aspect ratio of the source video when resizing its own rectangle.
get_OutputsActive | Retrieves the currently active output device collection.
get_OutputsAvailable | Retrieves a collection of outputs for a specified category that are available on the local system.
get_State | Retrieves the state of the Video Control.
get_TabStop | Retrieves a value indicating whether a user can use the TAB key to give the focus to the Video Control.
get_VideoRendererActive | Retrieves the currently active video renderer.
get_VideoRenderersAvailable | Retrieves a collection of video renderers available on the local system.
get_Window | Retrieves the window handle associated with the Video Control.
Pause | Pauses the filter graph.
put_AudioRendererActive | Sets the currently active audio renderer.
put_AutoSize | Sets a value that determines whether the Video Control is automatically resized to display its entire contents.
put_BackColor | Sets the background color of the Video Control.
put_ColorKey | Sets the color key.
put_DisplaySize | Sets the display size.
put_Enabled | Sets a value that determines whether the Video Control can respond to user-generated events.
put_FeaturesActive | Sets a collection of the features currently active.
put_InputActive | Sets the currently active input device.
put_MaintainAspectRatio | Sets a value indicating whether the Video Control should maintain the aspect ratio of the source video when resizing its own rectangle.
put_OutputsActive | Sets the currently active output device collection.
put_TabStop | Sets a value indicating whether a user can use the TAB key to give the focus to the Video Control.
put_VideoRendererActive | Sets the currently active video renderer.
Refresh | Refreshes the graph configuration and the video display rectangle.
Run | Runs the filter graph.
Stop | Stops the filter graph.
View | Selects an input device that is capable of handling a specified tune request.
ViewNext | Finds another input device for viewing the specified item.

See Also

  • Using the Video Control


IMSVidCtl::Build

This topic applies to Windows XP only.

The Build method builds the filter graph and connects all the filters.

Syntax

HRESULT Build();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method builds a filter graph using the current input device. To select an input device, call the IMSVidCtl::View method or the IMSVidCtl::put_InputActive method. If no input device has been selected, the method fails.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::Decompose


IMSVidCtl::Decompose

This topic applies to Windows XP only.

The Decompose method tears down the filter graph.

Syntax

HRESULT Decompose();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is the inverse of the IMSVidCtl::Build method. Call this method before you change the Active Features collection, specify a new renderer, or specify a new input device. The method does not modify the Active Features collection.

See Also

  • IMSVidCtl Interface


IMSVidCtl::DisableAudio

This topic applies to Windows XP only.

The DisableAudio method disables the audio output device.

Syntax

HRESULT DisableAudio();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method sets the active audio output device to NULL.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_AudioRendererActive


IMSVidCtl::DisableVideo

This topic applies to Windows XP only.

The DisableVideo method disables the video renderer.

Syntax

HRESULT DisableVideo();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method sets the active video renderer device to NULL.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_VideoRendererActive


IMSVidCtl::get__InputsAvailable

This topic applies to Windows XP only.

The get__InputsAvailable method retrieves the input devices that are available in a specified category.

Syntax

HRESULT get__InputsAvailable(
  const GUID*  CategoryGuid,
  IMSVidInputDevices**  ppVal
);

Parameters

CategoryGuid

[in] Pointer to a GUID that specifies the category to enumerate. Supported categories include the following:

Value | Description
KSCATEGORY_BDA_NETWORK_PROVIDER | BDA-compatible tuner devices.
KSCATEGORY_TVTUNER | Non-BDA analog tuner devices.
GUID_NULL | Miscellaneous devices (file source, DVD).

ppVal

[out] Address of a variable that receives an IMSVidInputDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method returns a read-only collection of input devices. Use the returned IMSVidInputDevices pointer to enumerate the collection.

If the method succeeds, the IMSVidInputDevices interface has an outstanding reference count. The caller must release the interface.

Example Code

The following example enumerates the available BDA-compatible tuners and retrieves their friendly names.

CComPtr<IMSVidInputDevices> pInputs;
hr = pVidControl->get__InputsAvailable(&KSCATEGORY_BDA_NETWORK_PROVIDER, &pInputs);
if (SUCCEEDED(hr))
{
    long lCount;
    hr = pInputs->get_Count(&lCount);
    for (long ix = 0; ix < lCount; ix++)
    {
        CComBSTR bstrName;
        CComVariant var(ix);
        CComPtr<IMSVidInputDevice> pInput;
        hr = pInputs->get_Item(var, &pInput);
        hr = pInput->get_Name(&bstrName);
        // Display the name.
    }
}

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_InputActive


IMSVidCtl::get__OutputsAvailable

This topic applies to Windows XP only.

The get__OutputsAvailable method retrieves the output devices that are available in a specified category.

This method is currently not supported.

Syntax

HRESULT get__OutputsAvailable(
  LPCGUID  CategoryGuid,
  IMSVidOutputDevices**  ppVal
);

Parameters

CategoryGuid

[in] Pointer to a GUID that specifies the category to enumerate.

ppVal

[out] Address of a variable that receives an IMSVidOutputDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

To obtain the available renderers, use the get_AudioRenderersAvailable and get_VideoRenderersAvailable methods.

See Also

  • IMSVidCtl Interface


IMSVidCtl::get_AudioRendererActive

This topic applies to Windows XP only.

The get_AudioRendererActive method retrieves the audio renderer that is currently active.

Syntax

HRESULT get_AudioRendererActive(
  IMSVidAudioRenderer**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidAudioRenderer interface pointer. If no audio renderer is active, this parameter receives the value NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The returned IMSVidAudioRenderer interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_AudioRendererActive


IMSVidCtl::get_AudioRenderersAvailable

This topic applies to Windows XP only.

The get_AudioRenderersAvailable method retrieves the available audio renderers.

Syntax

HRESULT get_AudioRenderersAvailable(
  IMSVidAudioRendererDevices**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidAudioRendererDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method returns a read-only collection of input devices. Use the returned IMSVidAudioRendererDevices pointer to enumerate the collection.

The returned IMSVidAudioRendererDevices interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_AudioRendererActive


IMSVidCtl::get_AutoSize

This topic applies to Windows XP only.

The get_AutoSize method retrieves a value that determines whether the Video Control is automatically resized to display its entire contents.

Syntax

HRESULT get_AutoSize(
  VARIANT_BOOL*  pbool
);

Parameters

pbool

[out] Pointer to a variable of type VARIANT_BOOL that receives the current value of the property.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_AutoSize


IMSVidCtl::get_BackColor

This topic applies to Windows XP only.

The get_BackColor method retrieves the background color of the Video Control.

Syntax

HRESULT get_BackColor(
  OLE_COLOR*  pbackcolor
);

Parameters

pbackcolor

[out] Pointer to a variable that receives an OLE_COLOR value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Example Code

OLE_COLOR ocBack;
COLORREF clrBack;
pVideoControl->get_BackColor(&ocBack);
OleTranslateColor(ocBack, 0, &clrBack);

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_BackColor


IMSVidCtl::get_ColorKey

This topic applies to Windows XP only.

The get_ColorKey method retrieves the color key that the video renderer is using.

Syntax

HRESULT get_ColorKey(
  OLE_COLOR*  pCurrentValue
);

Parameters

pCurrentValue

[out] Pointer to a variable that receives an OLE_COLOR value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The color key is used when the video renderer draws to an overlay surface.

Example Code

OLE_COLOR ocKey;
COLORREF clrKey;
pVideoControl->get_ColorKey(&ocKey);
OleTranslateColor(ocKey, 0, &clrKey);

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_ColorKey
  • IVMRWindowlessControl::GetColorKey


IMSVidCtl::get_DisplaySize

This topic applies to Windows XP only.

The get_DisplaySize method retrieves the display size.

Syntax

HRESULT get_DisplaySize(
  DisplaySizeList*  pCurrentValue
);

Parameters

pCurrentValue

[out] Pointer to a variable that receives a member of the DisplaySizeList enumeration.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The display size has no effect if the AutoSize property is false.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_AutoSize
  • IMSVidCtl::put_DisplaySize


IMSVidCtl::get_Enabled

This topic applies to Windows XP only.

The get_Enabled method retrieves a value that determines whether the Video Control can respond to user-generated events.

Syntax

HRESULT get_Enabled(
  VARIANT_BOOL*  pbool
);

Parameters

pbool

[out] Variable of type VARIANT_BOOL that receives the current value of the property.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_Enabled


IMSVidCtl::get_FeaturesActive

This topic applies to Windows XP only.

The get_FeaturesActive method retrieves the features that are currently active.

Syntax

HRESULT get_FeaturesActive(
  IMSVidFeatures**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidFeatures interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If no features are active, the method might return NULL in the pVal parameter. Otherwise, it returns a collection of feature objects. Use the returned IMSVidFeatures pointer to enumerate the collection.

The returned IMSVidFeatures interface has an outstanding reference count. The caller must release the interface.

Example Code

CComPtr<IMSVidFeatures> pFeatures;
hr = m_pVideoControl->get_FeaturesActive(&pFeatures);
if (SUCCEEDED(hr) && pFeatures)
{
    long c;
    pFs->get_Count(&c);
    /* Enumerate the features */
}

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_FeaturesActive
  • Displaying Closed Captioning in C++


IMSVidCtl::get_FeaturesAvailable

This topic applies to Windows XP only.

The get_FeaturesAvailable method retrieves the features that are available on the local system.

Syntax

HRESULT get_FeaturesAvailable(
  IMSVidFeatures**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidFeatures interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method returns a collection of feature objects. Use the returned IMSVidFeatures pointer to enumerate the collection. To activate a feature, add it to the active features collection. To search for a specific feature, call the IMSVidDevice::get__ClassID method on each feature and compare the result against the CLSID of the feature you are looking for.

The returned IMSVidFeatures interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface


IMSVidCtl::get_InputActive

This topic applies to Windows XP only.

The get_InputActive method retrieves the input device that is currently active.

Syntax

HRESULT get_InputActive(
  IMSVidInputDevice**  pVal
);

Parameters

pVal

[out] Address of a variable that receives an IMSVidInputDevice interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the method succeeds, the returned IMSVidInputDevice interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_InputActive


IMSVidCtl::get_InputsAvailable

This topic applies to Windows XP only.

The get_InputsAvailable method retrieves the input devices that are available within a specified category.

Syntax

HRESULT get_InputsAvailable(
  BSTR  CategoryGuid,
  IMSVidInputDevices**  ppVal
);

Parameters

CategoryGuid

[in] BSTR that specifies the GUID of the category to enumerate.

ppVal

[out] Address of a variable that receives an IMSVidInputDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Use the returned IMSVidInputDevices pointer to enumerate the devices.

This method is provided for Automation clients. C++ applications can use the IMSVidCtl::get__InputsAvailable method, which takes a GUID rather than a BSTR value.

If the method succeeds, the IMSVidInputDevices interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface


IMSVidCtl::get_MaintainAspectRatio

This topic applies to Windows XP only.

The get_MaintainAspectRatio method queries whether the Video Control maintains the aspect ratio of the source video.

Syntax

HRESULT get_MaintainAspectRatio(
  VARIANT_BOOL*  pCurrentValue
);

Parameters

pCurrentValue

[out] Pointer to a variable of type VARIANT_BOOL that receives one of the following values.

Value | Description
VARIANT_TRUE | The Video Control will maintain the aspect ratio of the source video.
VARIANT_FALSE | The Video Control will stretch the video to fill the window.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_MaintainAspectRatio


IMSVidCtl::get_OutputsActive

This topic applies to Windows XP only.

The get_OutputsActive method retrieves the output devices that are currently active.

Syntax

HRESULT get_OutputsActive(
  IMSVidOutputDevices**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidOutputDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_AudioRendererActive
  • IMSVidCtl::get_VideoRendererActive


IMSVidCtl::get_OutputsAvailable

This topic applies to Windows XP only.

The get_OutputsAvailable method retrieves the output devices that are available in a specified category.

Syntax

HRESULT get_OutputsAvailable(
  BSTR  CategoryGuid,
  IMSVidOutputDevices**  ppVal
);

Parameters

CategoryGuid

[in] BSTR that specifies the GUID of the category to enumerate

ppVal

[out] Address of a variable that receives an IMSVidOutputDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_AudioRenderersAvailable
  • IMSVidCtl::get_VideoRenderersAvailable


IMSVidCtl::get_State

This topic applies to Windows XP only.

The get_State method retrieves the state of the filter graph.

Syntax

HRESULT get_State(
  MSVidCtlStateList*  plState
);

Parameters

plState

[out] Pointer to a variable that receives a member of the MSVidCtlStateList enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidCtl Interface


IMSVidCtl::get_TabStop

This topic applies to Windows XP only.

The get_TabStop method queries whether a user can use the TAB key to give the focus to the Video Control.

Syntax

HRESULT get_TabStop(
  VARIANT_BOOL*  pbool
);

Parameters

pbool

[out] Variable of type VARIANT_BOOL that receives one of the following values.

Value | Description
VARIANT_TRUE | The Video Control is in the tabbing order.
VARIANT_FALSE | The Video Control is not in the tabbing order.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_TabStop


IMSVidCtl::get_VideoRendererActive

This topic applies to Windows XP only.

The get_VideoRendererActive method retrieves the currently active video renderer.

Syntax

HRESULT get_VideoRendererActive(
  IMSVidVideoRenderer**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidVideoRenderer interface pointer. If no video renderer is active, this parameter receives the value NULL.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned IMSVidVideoRenderer interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::put_VideoRendererActive


IMSVidCtl::get_VideoRenderersAvailable

This topic applies to Windows XP only.

The get_VideoRenderersAvailable method retrieves a collection of video renderers available on the local system.

Syntax

HRESULT get_VideoRenderersAvailable(
  IMSVidVideoRendererDevices**  ppVal
);

Parameters

ppVal

[out] Address of a variable that receives an IMSVidVideoRendererDevices interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method returns a collection of video renderer devices. Use the returned IMSVidVideoRendererDevices pointer to enumerate the collection.

Note   In the current implementation, the collection always contains exactly one item: an MSVidVideoRenderer object that represents the Video Mixing Renderer filter.

The returned IMSVidVideoRendererDevices interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_VideoRendererActive


IMSVidCtl::get_Window

This topic applies to Windows XP only.

The get_Window method retrieves the window associated with the Video Control.

Syntax

HRESULT get_Window(
  HWND*  phwnd
);

Parameters

phwnd

[out] Pointer to a variable of that receives a handle to the window.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidCtl Interface


IMSVidCtl::Pause

This topic applies to Windows XP only.

The Pause method pauses the filter graph.

Syntax

HRESULT Pause();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface


IMSVidCtl::put_AudioRendererActive

This topic applies to Windows XP only.

The put_AudioRendererActive method specifies the active audio renderer.

Syntax

HRESULT put_AudioRendererActive(
  IMSVidAudioRenderer*  pVal
);

Parameters

pVal

[in] Pointer to an IMSVidAudioRenderer interface that specifies the audio renderer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_AudioRendererActive


IMSVidCtl::put_AutoSize

This topic applies to Windows XP only.

The put_AutoSize method specifies whether the Video Control automatically resizes to display its entire contents.

Syntax

HRESULT put_AutoSize(
  VARIANT_BOOL  vbool
);

Parameters

vbool

[in] Specifies whether the Video Control automatically resizes. Use one of the following values.

Value | Description
VARIANT_TRUE | The Video Control automatically resizes.
VARIANT_FALSE | The Video Control does not automatically resize.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl::get_AutoSize
  • IMSVidCtl Interface


IMSVidCtl::put_BackColor

This topic applies to Windows XP only.

The put_BackColor method specifies the background color of the Video Control.

Syntax

HRESULT put_BackColor(
  OLE_COLOR  backcolor
);

Parameters

backcolor

[in] Specifies the background color as an OLE_COLOR value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The Video Control uses the background color when the filter graph is stopped or unbuilt. It also uses this color in letterbox mode to paint unused areas of the video rectangle. The background color is sometimes called the "border" color.

Example Code

COLORREF orange = RGB(0xFF, 0x80, 0x00);
hr = pVideoControl->put_BackColor(static_cast<OLE_COLOR>(orange));

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_BackColor
  • IVMRWindowlessControl::SetBorderColor


IMSVidCtl::put_ColorKey

This topic applies to Windows XP only.

The put_ColorKey method specifies the color key.

Syntax

HRESULT put_ColorKey(
  OLE_COLOR  NewValue
);

Parameters

NewValue

[in] Specifies the color key as an OLE_COLOR value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The color key is used when the video renderer draws to an overlay surface.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_ColorKey


IMSVidCtl::put_DisplaySize

This topic applies to Windows XP only.

The put_DisplaySize method specifies the display size.

Syntax

HRESULT put_DisplaySize(
  DisplaySizeList  NewValue
);

Parameters

NewValue

[in] Specifies the display size as a member of the DisplaySizeList enumeration.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Setting this property has no effect if the AutoSize property is false.

See Also

  • IMSVidCtl::get_DisplaySize
  • IMSVidCtl::put_AutoSize
  • IMSVidCtl Interface


IMSVidCtl::put_Enabled

This topic applies to Windows XP only.

The put_Enabled method specifies a value that determines whether the Video Control can respond to user-generated events.

Syntax

HRESULT put_Enabled(
  VARIANT_BOOL  vbool
);

Parameters

vbool

[in] Specifies the new value of the property.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl::get_Enabled
  • IMSVidCtl Interface


IMSVidCtl::put_FeaturesActive

This topic applies to Windows XP only.

The put_FeaturesActive method specifies a collection of features to activate.

Syntax

HRESULT put_FeaturesActive(
  IMSVidFeatures*  pVal
);

Parameters

pVal

[in] Specifies a pointer to the IMSVidFeatures interface on a collection of features.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Features represent additional capabilities beyond basic tuning and rendering, such as closed captioning or IP data services. When the Video Control builds the filter graph, it uses the active features collection to configure the graph.

For a default graph, it is not necessary to specify the active features. To activate a feature, create a new MSVidFeatures collection object. Then use the IMSVidCtl::get_FeaturesAvailable method to enumerate the available features, and call IMSVidDevice::get__ClassID on each feature. If the CLSID matches the feature you wish to activate, add that feature to your MSVidFeatures collection. Then call put_FeaturesActive with a pointer to the MSVidFeatures collection.

If the Video Control's state is not STATE_UNBUILT, call the IMSVidCtl::Decompose to tear down the filter graph before calling this method.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_FeaturesActive
  • IMSVidCtl::get_State


IMSVidCtl::put_InputActive

This topic applies to Windows XP only.

The put_InputActive method specifies the input device to use in the filter graph.

Syntax

HRESULT put_InputActive(
  IMSVidInputDevice*  pVal
);

Parameters

pVal

[in] Specifies a pointer to the input device's IMSVidInputDevice interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the Video Control's state is not STATE_UNBUILT, call the IMSVidCtl::Decompose to tear down the filter graph before calling this method.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_InputActive
  • IMSVidCtl::get_State


IMSVidCtl::put_MaintainAspectRatio

This topic applies to Windows XP only.

The put_MaintainAspectRatio method specifies whether the Video Control maintains the aspect ratio of the source video.

Syntax

HRESULT put_MaintainAspectRatio(
  VARIANT_BOOL  NewValue
);

Parameters

NewValue

[in] Specifies one of the following values.

Value | Description
VARIANT_TRUE | The Video Control will maintain the aspect ratio of the source video.
VARIANT_FALSE | The Video Control will stretch the video to fill the window. Default

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl::get_MaintainAspectRatio
  • IMSVidCtl Interface


IMSVidCtl::put_OutputsActive

This topic applies to Windows XP only.

The put_OutputsActive method specifies the active output devices.

Syntax

HRESULT put_OutputsActive(
  IMSVidOutputDevices*  pVal
);

Parameters

pVal

[in] Specifies the new collection of output devices.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl::get_OutputsActive
  • IMSVidCtl Interface


IMSVidCtl::put_TabStop

This topic applies to Windows XP only.

The put_TabStop method specifies whether a user can use the TAB key to give the focus to the Video Control.

Syntax

HRESULT put_TabStop(
  VARIANT_BOOL  vbool
);

Parameters

vbool

[in] Specifies one of the following values.

Value | Description
VARIANT_TRUE | Include the Video Control in the tabbing order.
VARIANT_FALSE | Do not include the Video Control in the tabbing order.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidCtl::get_TabStop
  • IMSVidCtl Interface


IMSVidCtl::put_VideoRendererActive

This topic applies to Windows XP only.

The put_VideoRendererActive method specifies the active video renderer.

Syntax

HRESULT put_VideoRendererActive(
  IMSVidVideoRenderer*  pVal
);

Parameters

pVal

[in] Specifies a pointer to the IMSVidVideoRenderer interface of the video renderer device.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Currently the only supported video renderer is the Video Mixing Renderer (VMR) filter. The VMR is used by default, so it is not necessary to call this method.

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_VideoRendererActive


IMSVidCtl::Refresh

This topic applies to Windows XP only.

The Refresh method immediately updates the Video Control's appearance.

Syntax

HRESULT Refresh();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is a stock ActiveX® Control method. It forces the Video Control window to repaint itself. Before repainting, the Video Control ensures that the video rectangle is up to date and that all Video Mixing Renderer settings are correct.

See Also

  • IMSVidCtl Interface


IMSVidCtl::Run

This topic applies to Windows XP only.

The Run method runs the filter graph.

Syntax

HRESULT Run();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method builds the filter graph if the state is unbuilt, and puts the graph into the running state. For more information on the behavior of Build, View and Run, see IMSVidCtl::View.

See Also

  • IMSVidCtl Interface


IMSVidCtl::Stop

This topic applies to Windows XP only.

The Stop method stops the filter graph.

Syntax

HRESULT Stop();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method leaves the filter graph intact and ready to pause or run. To tear down the filter graph, use the IMSVidCtl::Decompose method.

See Also

  • IMSVidCtl Interface


IMSVidCtl::View

This topic applies to Windows XP only.

The View method configures the Video Control to view an input source, which can be a tune request, a DVD, or a media file.

Syntax

HRESULT View(
  VARIANT*  pv
);

Parameters

pv

[in] Specifies the input source as a VARIANT type. This parameter must be one of the following:

  • A pointer to a valid tune request object that supports the ITuneRequest interface. The tune request must be initialized with all the tuning information required for the particular network type.
  • The string "DVD:" for DVD playback.
  • The name of a media file.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the Video Control already has an active input device, this method configures the device for the specified input. Otherwise, this method locates an input device that can handle the input and activates it.

An input device typically corresponds to a source filter. If the pv parameter is a tune request object, the Video Control determines which filter to use by examining the network type on the tune request. For digital television, the input device will be a BDA Network Provider filter. For analog television, it will be a WDM TV Tuner filter. The specific name and implementation of the filter are device-dependent.

After calling View, use the following methods to build and run the filter graph:

  • The IMSVidCtl::Build method builds the rest of the filter graph, based on the selected input and the active features collection. The Build method leaves the graph in a stopped state.
  • The IMSVidCtl::Run method calls Build if the graph is not built, and puts the graph into a running state. When the filter graph runs, the video control starts playing the specified tune request.

If the filter graph is already built and running, an application can call View to specify a new tune request, either on the same network type or on a different network type.

If the View method succeeds, you can obtain the input device by calling the IMSVidCtl::get_InputActive method.

You can specify a particular input device by calling the IMSVidCtl::put_InputActive method and then calling IMSVidInputDevice::View on the device, instead of calling View on the Video Control. This might be useful if the local system has multiple devices of the same type. The View method is preferred, however, because it automatically locates the correct device type.

Example Code

The following example shows how to submit a tune request to the Video Control:

ITuneRequest *pTuneReq;
/* Obtain the tune request (not shown). */
CComVariant varTuneRequest = pTuneReq;
hr = pVidControl->View(&varTuneRequest);

The next example shows how to play a local file:

CComVariant varFileName(OLESTR("C:Example.avi"));
hr = pVidControl->View(&varFileName);

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::get_InputsAvailable
  • DVD Applications in Visual Basic (Video Control)


IMSVidCtl::ViewNext

This topic applies to Windows XP only.

The ViewNext method finds another input device to view the specified tune request.

This method is supported only for analog tuner devices. It does not work with digital tuners.

Syntax

HRESULT ViewNext(
  VARIANT*  pv
);

Parameters

pv

[in] Specifies the tune request as a VARIANT type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method works like the IMSVidCtl::View method, with the following difference: If the system has more than one tuner that supports the specified network type, the ViewNext method skips the current input device and uses the next one. (The ordering of devices is arbitrary.)

See Also

  • IMSVidCtl Interface
  • IMSVidCtl::View


IMSVidDataServices Interface

The IMSVidDataServices interface represents the data services feature. The MSVidDataServices feature object exposes this interface.

This interface inherits from the IMSVidFeature interface, but adds no methods to it.


IMSVidDevice Interface

This topic applies to Windows XP only.

The IMSVidDevice interface is the base interface for all the devices and features that the Video Control supports.

In addition to the methods inherited from IDispatch, the IMSVidDevice interface exposes the following methods.

Method | Description
get__Category | Retrieves the category of the device as a GUID.
get__ClassID | Retrieves the class identifier (CLSID) of the device as a GUID.
get_Category | Retrieves the category of the device as a BSTR.
get_ClassID | Retrieves the CLSID of the device as a BSTR.
get_Name | Retrieves the friendly name of the device.
get_Power | Retrieves the power status of the device.
get_Status | Retrieves status information about the device.
IsEqualDevice | Queries whether this device and another device represent the same underlying hardware
put_Power | Turns the device on or off.


IMSVidDevice::get__Category

This topic applies to Windows XP only.

The get__Category method retrieves the category of the device as a GUID.

Syntax

HRESULT get__Category(
  GUID*  pGuid
);

Parameters

pGuid

[out] Pointer to a variable of type GUID that receives the device category.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidDevice Interface


IMSVidDevice::get__ClassID

This topic applies to Windows XP only.

The get__ClassID method retrieves the device's class identifier (CLSID) as a GUID.

Syntax

HRESULT get__ClassID(
  GUID*  pClsid
);

Parameters

pClsid

[out] Pointer to a variable of type GUID that receives the CLSID.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidDevice Interface


IMSVidDevice::get_Category

This topic applies to Windows XP only.

The get_Category method retrieves the category of the device as a BSTR.

Syntax

HRESULT get_Category(
  BSTR*  pGuid
);

Parameters

pGuid

[out] BSTR that receives the device category.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The device category is identified by a GUID. This method returns a string representation of the GUID.

This method is provided for Automation clients. C++ applications can use the IMSVidDevice::get__Category method, which returns a GUID rather than a BSTR.

The caller must free the returned string, using the SysFreeString function.

See Also

  • IMSVidDevice Interface


IMSVidDevice::get_ClassID

This topic applies to Windows XP only.

The get_ClassID method retrieves the device's class identifier (CLSID) as a BSTR.

Syntax

HRESULT get_ClassID(
  BSTR*  pClsid
);

Parameters

pClsid

[out] Pointer to a variable that receives a string representation of the CLSID.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

This method is provided for Automation clients. C++ applications can use the IMSVidDevice::get__ClassID method, which returns a GUID rather than a BSTR.

The caller must free the returned string, using the SysFreeString function.

See Also

  • IMSVidDevice Interface


IMSVidDevice::get_Name

This topic applies to Windows XP only.

The get_Name method retrieves the friendly name of the device.

Syntax

HRESULT get_Name(
  BSTR*  pName
);

Parameters

pName

[out] Pointer to a variable that receives the friendly name.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The caller must free the returned string, using the SysFreeString function.

See Also

  • IMSVidDevice Interface


IMSVidDevice::get_Power

This topic applies to Windows XP only.

The get_Power method queries whether the device is off or on.

Syntax

HRESULT get_Power(
  VARIANT_BOOL*  pPower
);

Parameters

pPower

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_TRUE | The device is on.
VARIANT_FALSE | The device is off.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

Not all device types implement this method.

See Also

  • IMSVidDevice Interface
  • IMSVidDevice::put_Power


IMSVidDevice::get_Status

This topic applies to Windows XP only.

The get_Status method retrieves status information about the device.

Syntax

HRESULT get_Status(
  long*  pStatus
);

Parameters

pStatus

[out] Pointer to a variable of that receives the current status.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

Not all device types implement this method.

See Also

  • IMSVidDevice Interface


IMSVidDevice::IsEqualDevice

This topic applies to Windows XP only.

The IsEqualDevice method queries whether this device and another device represent the same underlying hardware.

Syntax

HRESULT IsEqualDevice(
  IMSVidDevice*  pDevice,
  VARIANT_BOOL*  pIsEqual
);

Parameters

pDevice

[in] Pointer to the other device's IMSVidDevice interface.

pIsEqual

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_TRUE | The two devices represent the same underlying hardware.
VARIANT_FALSE | The two devices do not represent the same hardware.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success; returned VARIANT_TRUE.
S_FALSE | Success; returned VARIANT_FALSE.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error occurred.

See Also

  • IMSVidDevice Interface


IMSVidDevice::put_Power

This topic applies to Windows XP only.

The put_Power method turns the device on or off.

Syntax

HRESULT put_Power(
  VARIANT_BOOL  Power
);

Parameters

Power

[in] Specifies whether to turn the power on or off. Use one of the following values.

Value | Description
VARIANT_TRUE | Turn the device on.
VARIANT_FALSE | Turn the device off.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

Not all device types implement this method.

See Also

  • IMSVidDevice::get_Power
  • IMSVidDevice Interface


IMSVidEncoder Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidEncoder interface represents the MSVidEncoder feature object, which is required for stream buffer applications using the Video Control. For more information, see Using the Stream Buffer Engine with the Video Control.

In addition to the methods inherited from IMSVidFeature, the IMSVidEncoder interface exposes the following methods.

Method | Description
get_AudioEncoderInterface | Retrieves a pointer to the audio encoder interface.
get_VideoEncoderInterface | Retrieves a pointer to the video encoder interface.


IMSVidEncoder::get_AudioEncoderInterface

This topic applies to Windows XP Service Pack 1 only.

The get_AudioEncoderInterface method retrieves a pointer to the audio encoder interface.

Syntax

HRESULT get_AudioEncoderInterface(
  IUnknown **ppEncInt
);

Parameters

ppEncInt

[out] Pointer to a variable that receives an IUnknown interface pointer. The caller can query this interface for the IEncoderAPI interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the method succeeds, the caller must release the IUnknown interface.

See Also

  • IMSVidEncoder Interface


IMSVidEncoder::get_VideoEncoderInterface

This topic applies to Windows XP Service Pack 1 only.

The get_VideoEncoderInterface method retrieves a pointer to the video encoder interface.

Syntax

HRESULT get_VideoEncoderInterface(
  IUnknown **ppEncInt
);

Parameters

ppEncInt

[out] Pointer to a variable that receives an IUnknown interface pointer. The caller can query this interface for the IEncoderAPI interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the method succeeds, the caller must release the IUnknown interface.

See Also

  • IMSVidEncoder Interface


IMSVidFeature Interface

This topic applies to Windows XP only.

The IMSVidFeature interface represents a feature that is available through the Video Control, such as data services or closed captioning.

The IMSVidFeature interface inherits from IMSVidDevice and adds no methods to it.

Remarks

To obtain a collection of the features that are available, call the IMSVidCtl::get_FeaturesAvailable method on the Video Control. To activate a feature, create a new MSVidFeatures collection object and assign it to the Video Control by calling the IMSVidCtl::put_FeaturesActive method.

Feature objects do not implement the IMSVidDevice::get_Power or IMSVidDevice::get_Status method.


IMSVidFeatures Interface

This topic applies to Windows XP only.

The IMSVidFeatures interface represents a collection of Video Control features. The MSVidFeatures collection object exposes this interface.

This interface is used for two purposes: to retrieve a read-only collection of the features available on the current system (the available features collection), and to create a read/write list of activated features (the active features collection).

In addition to the methods inherited from IDispatch, the IMSVidFeatures interface exposes the following methods.

Method | Description
Add | Adds a feature to the collection.
get_Count | Retrieves the number of items in the collection.
get_Item | Retrieves the specified item from the collection.
get__NewEnum | Retrieves an enumerator for the collection.
Remove | Removes an item from the collection.


IMSVidFeatures::Add

This topic applies to Windows XP only.

The Add method adds a feature to the collection.

Syntax

HRESULT Add(
  IMSVidFeature*  pDB
);

Parameters

pDB

[in] Specifies a pointer to the feature's IMSVidFeature interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ACCESSDENIED | The collection is read-only; cannot add any items.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidFeatures Interface
  • IMSVidFeatures::Remove


IMSVidFeatures::get_Count

This topic applies to Windows XP only.

The get_Count method retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
  long*  plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the number of items.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidFeatures Interface


IMSVidFeatures::get_Item

This topic applies to Windows XP only.

The get_Item method retrieves the specified item from the collection.

Syntax

HRESULT get_Item(
  VARIANT  v,
  IMSVidFeature**  ppDB
);

Parameters

v

[in] VARIANT that specifies the index of the item to retrieve.

ppDB

[out] Address of a variable that receives an IMSVidFeature interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidFeatures::get_Count - 1.

If the method succeeds, the IMSVidFeature interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidFeatures Interface


IMSVidFeatures::get__NewEnum

This topic applies to Windows XP only.

The get__NewEnum method retrieves an enumerator for the collection.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppD
);

Parameters

ppD

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method is provided so that Automation clients can iterate through the collection using a For...Each loop.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread. (C++ applications should generally use the IMSVidFeatures::get_Item method instead.)

If the method succeeds, the IEnumVARIANT interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidFeatures Interface


IMSVidFeatures::Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

HRESULT Remove(
  VARIANT  v
);

Parameters

v

[in] VARIANT that specifies the index of the item to remove.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_ACCESSDENIED | The collection is read-only; cannot remove any items.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidFeatures::get_Count - 1.

See Also

  • IMSVidFeatures::Add
  • IMSVidFeatures Interface


IMSVidFilePlayback Interface

This topic applies to Windows XP only.

The IMSVidFilePlayback interface enables the client to specify a local file for playback. It is implemented by the MSVidFilePlaybackDevice object.

In addition to the methods inherited from IMSVidPlayback, the IMSVidFilePlayback interface exposes the following methods.

Method | Description
get_FileName | Sets the name of the file to play.
put_FileName | Retrieves the name of the file to play.

Remarks

To play a media file using the Video Control, call the IMSVidCtl::View method with the name of the file. The View method automatically loads the MSVidFilePlayback object.


IMSVidFilePlayback::get_FileName

This topic applies to Windows XP only.

The get_FileName method retrieves the name of the file to play.

Syntax

HRESULT get_FileName(
  BSTR*  FileName
);

Parameters

FileName

[out] Pointer to a variable that receives the file name.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the returned string, using the CoTaskMemFree function.

See Also

  • IMSVidFilePlayback Interface


IMSVidFilePlayback::put_FileName

This topic applies to Windows XP only.

The put_FileName method sets the name of the file to play.

Syntax

HRESULT put_FileName(
  BSTR  FileName
);

Parameters

FileName

[in] Specifies the file name.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidFilePlayback Interface


IMSVidGraphSegmentContainer Interface

This topic applies to Windows XP only.

The IMSVidGraphSegmentContainer interface is exposed by the Video Control and contains one supported method, get_Graph, which obtains a pointer to the Filter Graph Manager. This interface has additional methods besides the one shown here, but they are not supported.

Method | Description
get_Graph | Returns a pointer to the Filter Graph Manager.


IMSVidGraphSegmentContainer::get_Graph

This topic applies to Windows XP only.

The get_Graph method returns a pointer to the Filter Graph Manager.

Syntax

HRESULT get_Graph(
  IGraphBuilder  **ppGraph
);

Parameters

ppGraph

[in] Address of a variable that receives an IGraphBuilder interface pointer.

Return Values

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

Objects can use this method to find a specific DirectShow filter in the filter graph. It is not recommended that applications use this method. Applications should always control the filter graph using the Video Control.

The returned IGraphBuilder interface has an outstanding reference count. The caller must release the interface.

Example Code

CComQIPtr<IMSVidGraphSegmentContainer> pSeg(m_pVideoControl);
if (pSeg)
{
    CComPtr<IGraphBuilder> pGraph;
    hr = pSeg->get_Graph(&pGraph);
    if (SUCCEEDED(hr))
    {
        // Use IGraphBuilder::EnumFilters to enumerate the filters.
    }
}

See Also

  • IMSVidGraphSegmentContainer Interface


IMSVidInputDevice Interface

This topic applies to Windows XP only.

The IMSVidInputDevice interface represents any input device that is recognized by the Video Control, such as a television tuner card. This is a generic interface that serves as an abstract base class for input devices. Several interfaces inherit IMSVidInputDevice, including the following:

  • IMSVidTuner
  • IMSVidAnalogTuner

When a method returns an IMSVidInputDevice pointer, the object that is returned typically supports one of the derived interfaces.

In addition to the methods inherited from IMSVidDevice, the IMSVidInputDevice interface exposes the following methods.

Method | Description
IsViewable | Determines whether this device can view the specified tune request.
View | Configures the input device to view the specified tune request.


IMSVidInputDevice::IsViewable

This topic applies to Windows XP only.

The IsViewable method determines whether this device can view the specified tune request.

Currently this method is not implemented by any of the supported input devices.

Syntax

HRESULT IsViewable(
  VARIANT*  pv,
  VARIANT_BOOL*  pfViewable
);

Parameters

pv

[in] Specifies the tune request as a VARIANT type.

pfViewable

[out] Pointer to variable that receives one of the following values.

Value | Description
VARIANT_TRUE | The device can view this tune request.
VARIANT_FALSE | The device cannot view this tune request.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidInputDevice Interface


IMSVidInputDevice::View

This topic applies to Windows XP only.

The View method configures this input device to view the specified tune request.

Syntax

HRESULT View(
  VARIANT*  pv
);

Parameters

pv

[in] Specifies the tune request as a VARIANT type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Before calling this method, set the device as the active input by calling the IMSVidCtl::put_InputActive method. Unless the application needs to choose a specific input device, however, the IMSVidCtl::View method is recommended instead of the IMSVidInputDevice::View method.

See Also

  • IMSVidInputDevice Interface


IMSVidInputDevices Interface

This topic applies to Windows XP only.

The IMSVidInputDevices interface represents a collection of input devices. The MSVidInputDevices object exposes this object.

In addition to the methods inherited from IDispatch, the IMSVidInputDevices interface exposes the following methods.

Method | Description
Add | Adds an input device to the collection.
get_Count | Retrieves the number of items in the collection.
get_Item | Retrieves the specified item from the collection.
get__NewEnum | Retrieves an enumerator for the collection.
Remove | Removes an item from the collection.


IMSVidInputDevices::Add

This topic applies to Windows XP only.

The Add method adds an input device to the collection.

Syntax

HRESULT Add(
  IMSVidInputDevice*  pDB
);

Parameters

pDB

[in] Pointer to the device's IMSVidInputDevice interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ACCESSDENIED | This collection is read-only; cannot add any items.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidInputDevices Interface
  • IMSVidInputDevices::Remove


IMSVidInputDevices::get_Count

This topic applies to Windows XP only.

The get_Count method retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
  long*  plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the number of items.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidInputDevices Interface


IMSVidInputDevices::get_Item

This topic applies to Windows XP only.

The get_Item method retrieves the specified item from the collection.

Syntax

HRESULT get_Item(
  VARIANT  v,
  IMSVidInputDevice**  ppDB
);

Parameters

v

[in] VARIANT that specifies the index of the item to retrieve.

ppDB

[out] Address of a variable that receives an IMSVidInputDevice interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidInputDevices::get_Count() - 1.

If the method succeeds, the IMSVidInputDevice interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidInputDevices Interface


IMSVidInputDevices::get__NewEnum

This topic applies to Windows XP only.

The get__NewEnum method retrieves an enumerator for the collection.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppD
);

Parameters

ppD

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method is provided so that Automation clients can iterate through the collection using a For...Each loop.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread. (C++ applications should generally use the IMSVidInputDevices::get_Item method instead.)

If the method succeeds, the IEnumVARIANT interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidInputDevices Interface


IMSVidInputDevices::Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

HRESULT Remove(
  VARIANT  v
);

Parameters

v

[in] VARIANT that specifies the index of the item to remove.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | Index out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_ACCESSDENIED | This collection is read-only; no items can be removed from it
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidInputDevices::get_Count() - 1.

See Also

  • IMSVidInputDevices Interface
  • IMSVidInputDevices::Add


IMSVidOutputDevice Interface

This topic applies to Windows XP only.

The IMSVidOutputDevice interface represents an output device. This interface derives from the IMSVidDevice interface but adds no methods to it. It exists to support polymorphism.

Output devices include audio and video renderers, and the Stream Buffer Sink object. Video renderers expose the IMSVidVideoRenderer interface, and audio renderers exposes the IMSVidAudioRenderer interface, both of which derive from IMSVidOutputDevice.


IMSVidOutputDevices Interface

This topic applies to Windows XP only.

The IMSVidOutputDevices interface represents a collection of output devices.

Output devices include video and audio renderers, and the Stream Buffer Sink object. To obtain the audio and video renders, you can use the following methods:

  • IMSVidCtl::get_AudioRendererActive
  • IMSVidCtl::get_AudioRenderersAvailable
  • IMSVidCtl::get_VideoRendererActive
  • IMSVidCtl::get_VideoRenderersAvailable

In addition to the methods inherited from IDispatch, the IMSVidOutputDevices interface exposes the following methods.

Method | Description
Add | Adds an output device to the collection.
get_Count | Retrieves the number of items in the collection.
get_Item | Retrieves the specified item from the collection.
get__NewEnum | Retrieves an enumerator for the collection.
Remove | Removes an item from the collection.


IMSVidOutputDevices::Add

This topic applies to Windows XP only.

The Add method adds an output device to the collection.

Syntax

HRESULT Add(
  IMSVidOutputDevice*  pDB
);

Parameters

pDB

[in] Specifies a pointer to the device's IMSVidOutputDevice interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ACCESSDENIED | The collection is read-only; cannot add any items.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidOutputDevices Interface
  • IMSVidOutputDevices::Remove


IMSVidOutputDevices::get_Count

This topic applies to Windows XP only.

The get_Count method retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
  long*  plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the number of items.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidOutputDevices Interface


IMSVidOutputDevices::get_Item

This topic applies to Windows XP only.

The get_Item method retrieves the specified item from the collection.

Syntax

HRESULT get_Item(
  VARIANT  v,
  IMSVidOutputDevice**  ppDB
);

Parameters

v

[in] VARIANT that specifies the index of the item to retrieve.

ppDB

[out] Address of a variable that receives an IMSVidOutputDevice interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidOutputDevices::get_Count - 1.

If the method succeeds, the IMSVidInputDevice interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidOutputDevices Interface


IMSVidOutputDevices::get__NewEnum

This topic applies to Windows XP only.

The get__NewEnum method retrieves an enumerator for the collection.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppD
);

Parameters

ppD

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method is provided so that Automation clients can iterate through the collection using a For...Each loop.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread. (C++ applications should generally use the IMSVidOutputDevices::get_Item method instead.)

If the method succeeds, the IEnumVARIANT interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidOutputDevices Interface


IMSVidOutputDevices::Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

HRESULT Remove(
  VARIANT  v
);

Parameters

v

[in] VARIANT that specifies the index of the item to remove.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_ACCESSDENIED | The collection is read-only; cannot remove any items.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidOutputDevices::get_Count - 1.

See Also

  • IMSVidOutputDevices Interface
  • IMSVidOutputDevices::Add


IMSVidPlayback Interface

This topic applies to Windows XP only.

The IMSVidPlayback interface controls a Video Control playback device.

In addition to the methods inherited from IMSVidInputDevice, the IMSVidPlayback interface exposes the following methods.

Method | Description
get_CanStep | Queries whether the input source can step frame by frame.
get_CurrentPosition | Returns the current playback position of the source.
get_EnableResetOnStop | Indicates how playback will resume if the graph is rebuilt.
get_Length | Retrieves the length of the playback source.
get_PositionMode | Indicates how position values are interpreted by this interface.
get_Rate | Retrieves the playback rate.
Pause | Pauses the playback device.
put_CurrentPosition | Seeks to a specified position in the source.
put_EnableResetOnStop | Specifies how playback will resume if the graph is rebuilt.
put_PositionMode | Specifies how position values will be interpreted by this interface.
put_Rate | Sets the playback rate.
Run | Runs the playback device.
Step | Steps through the video stream by a specified number of frames.
Stop | Stops the playback device.


IMSVidPlayback::get_CanStep

This topic applies to Windows XP only.

The get_CanStep method queries whether the input source can step frame by frame.

Syntax

HRESULT get_CanStep(
  VARIANT_BOOL  fBackwards,
  VARIANT_BOOL *pfCan
);

Parameters

fBackwards

[in] Use one of the following values.

Value | Description
VARIANT_FALSE | Query whether the input can step forward
VARIANT_TRUE | Query whether the input can step backward.

pfCan

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_FALSE | The source cannot step in the specified direction.
VARIANT_TRUE | The source can step in the specified direction.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

Example Code

VARIANT_BOOL fCan = VARIANT_FALSE;
hr = m_pPlayback->get_CanStep(VARIANT_FALSE, &fCan);

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::get_CurrentPosition

This topic applies to Windows XP only.

The get_CurrentPosition method returns the current playback position of the source.

Syntax

HRESULT get_CurrentPosition(
  long*  lPosition
);

Parameters

lPosition

[out] Pointer to a variable that receives the playback position. The units for the returned value are determined by the current position mode:

Position Mode | Returned Value
FrameMode | Frame number
TenthsSecondsMode | Hundredths of seconds

To set the position mode, call IMSVidPlayback::put_PositionMode.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::get_EnableResetOnStop

This topic applies to Windows XP only.

The get_EnableResetOnStop method indicates how playback will resume if the graph is rebuilt.

Syntax

HRESULT get_EnableResetOnStop(
  VARIANT_BOOL*  pVal
);

Parameters

pVal

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_FALSE | The Video Control will not seek to start of the media.
VARIANT_TRUE | The Video Control will seek to start of the media.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

For more information, see IMSVidPlayback::put_EnableResetOnStop.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::get_Length

This topic applies to Windows XP only.

The get_Length method retrieves the length of the playback source.

Syntax

HRESULT get_Length(
  long*  lLength
);

Parameters

lLength

[out] Pointer to a variable that receives the length. The units for the returned value are determined by the current position mode:

Position Mode | Returned Value
FrameMode | Frame number
TenthsSecondsMode | Hundredths of seconds

To set the position mode, call IMSVidPlayback::put_PositionMode.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_NOINTERFACE | The source does not support getting the length.
E_POINTER | NULL pointer argument.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::get_PositionMode

This topic applies to Windows XP only.

The get_PositionMode method indicates how position values are interpreted by this interface.

Syntax

HRESULT get_PositionMode(
  PositionModeList*  lPositionMode
);

Parameters

lPositionMode

[out] Pointer to a variable that receives one of the following values.

Value | Description
FrameMode | Position values are specified as frame numbers.
TenthsSecondsMode | Position values are specified as hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

The value returned by this method determines how the parameters are interpreted for the following methods:

  • IMSVidPlayback::get_Length
  • IMSVidPlayback::get_CurrentPosition
  • IMSVidPlayback::put_CurrentPosition

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::get_Rate

This topic applies to Windows XP only.

The get_Rate method retrieves the playback rate.

Syntax

HRESULT get_Rate(
  double*  plRate
);

Parameters

plRate

[out] Pointer to a variable that receives the playback rate, as a ratio to the authored rate. For example, 0.5 means half the normal speed, 1.0 means normal speed, and 2.0 means twice the normal speed.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::Pause

This topic applies to Windows XP only.

The Pause method pauses the playback device.

Applications should call the IMSVidCtl::Pause method, rather than this method.

Syntax

HRESULT Pause();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_NOTIMPL | Not implemented.
S_OK | The method succeeded.

Remarks

This method allows for direct control of the source. However, if the underlying source filter is controlled using the standard DirectShow IMediaControl interface, this method returns E_NOTIMPL.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::put_CurrentPosition

This topic applies to Windows XP only.

The put_CurrentPosition method seeks to a specified position in the source.

Syntax

HRESULT put_CurrentPosition(
  long  lPosition
);

Parameters

lPosition

[in] Specifies the new position. The units for this parameter are determined by the current position mode:

Position Mode | Returned Value
FrameMode | Frame number
TenthsSecondsMode | Hundredths of seconds

To set the position mode, call IMSVidPlayback::put_PositionMode.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
E_INVALIDARG | Invalid argument.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

If the new position is earlier than the current position and the source cannot seek backward, the method returns E_INVALIDARG.

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::put_EnableResetOnStop

This topic applies to Windows XP only.

The put_EnableResetOnStop method indicates how playback will resume if the graph is rebuilt..

Syntax

HRESULT put_EnableResetOnStop(
  VARIANT_BOOL  newVal
);

Parameters

newVal

[in] Specifies one of the following values.

Value | Description
VARIANT_FALSE | The Video Control attempts to start from position where playback was interrupted. (Default)
VARIANT_TRUE | The Video Control seeks back to the start before resuming playback.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

In some situaitions, the filter graph may be torn down and rebuilt during play. For example, this can happen if the monitor resolution is changed or the screen saver starts. The EnableResetOnStop property specifies whether the Video Control should resume playback where it was interrupted, or should restart at the beginning of the source.

By default, it resumes from the point where playback was interruptes. If newVal is VARIANT_TRUE, however, the Video Control will issue a seek command back to time zero. Note that setting this parameter to VARIANT_TRUE does not guarantee that the stream can be seeked. The seek command might fail, depending on the source.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::put_PositionMode

This topic applies to Windows XP only.

The put_PositionMode method specifies how position values will be interpreted by this interface.

Syntax

HRESULT put_PositionMode(
  PositionModeList  lPositionMode
);

Parameters

lPositionMode

[in] Specifies one of the following values.

Value | Description
FrameMode | Position values are specified as frame numbers.
TenthsSecondsMode | Position values are specified as hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
E_FAIL | Failed. Possibly the source does not support this mode.
E_INVALIDARG | Invalid argument.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

The position mode determines how the parameters are interpreted for the following methods:

  • IMSVidPlayback::get_Length
  • IMSVidPlayback::get_CurrentPosition
  • IMSVidPlayback::put_CurrentPosition

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

Example Code

hr = m_pPlayback->put_PositionMode(TenthsSecondsMode);

See Also

  • get_PositionMode
  • IMSVidPlayback Interface


IMSVidPlayback::put_Rate

This topic applies to Windows XP only.

The put_Rate method sets the playback rate.

Syntax

HRESULT put_Rate(
  double  plRate
);

Parameters

plRate

[in] Specifies the playback rate, as a ratio to the authored rate. For example, 0.5 means half the normal speed, 1.0 means normal speed, and 2.0 means twice the normal speed.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | The source filter does not support the specified rate.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::Run

This topic applies to Windows XP only.

The Run method runs the playback device.

Applications should call the IMSVidCtl::Run method, rather than this method.

Syntax

HRESULT Run();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_NOTIMPL | Not implemented.
S_OK | The method succeeded.

Remarks

This method allows for direct control of the source. However, if the underlying source filter is controlled using the standard DirectShow IMediaControl interface, this method returns E_NOTIMPL.

See Also

  • IMSVidPlayback Interface


IMSVidPlayback::Step

This topic applies to Windows XP only.

The Step method steps through the video stream by a specified number of frames.

Syntax

HRESULT Step(
  long  lStep
);

Parameters

lStep

[in] Specifies how many frames to step. If lStep is 1, the Video Control steps forward one frame. If lStep is a number N greater than 1, the Video Control skips N - 1 frames and shows the Nth frame.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_NOTIMPL | Not implemented.
ERROR_INVALID_STATE | The graph is not built. Call the Build or View method on the Video Control.
S_OK | The method succeeded.

Note The value ERROR_INVALID_STATE is converted to an HRESULT with the HRESULT_FROM_WIN32 macro.

Remarks

Although a negative value for lStep is defined as stepping backwards, that functionality is currently not implemented, and the method returns E_NOTIMPL.

Call the IMSVidCtl::Build or IMSVidCtl::View method before calling this method.

See Also

  • IMSVidPlayback Interface
  • IMSVidPlayback::get_CanStep


IMSVidPlayback::Stop

This topic applies to Windows XP only.

The Stop method stops the playback device.

Applications should call the IMSVidCtl::Stop method, rather than this method.

Syntax

HRESULT Stop();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_NOTIMPL | Not implemented.
S_OK | The method succeeded.

Remarks

This method allows for direct control of the source. However, if the underlying source filter is controlled using the standard DirectShow IMediaControl interface, this method returns E_NOTIMPL.

See Also

  • IMSVidPlayback Interface


IMSVidRect Interface

This topic applies to Windows XP only.

The IMSVidRect interface represents a rectangle with an associated window handle. It contains methods to set and retrieve the top and left coordinates, the width, and the height. All values are in pixels. The top and left coordinates are relative to the associated window.

In addition to the methods inherited from IDispatch, the IMSVidRect interface exposes the following methods.

Method | Description
get_Height | Retrieves the height of the rectangle.
get_HWnd | Retrieves the window associated with the rectangle.
get_Left | Retrieves the left x-coordinate of the rectangle.
get_Top | Retrieves the top y-coordinate of the rectangle.
get_Width | Retrieves the width of the rectangle.
put_Height | Specifies the height of the rectangle
put_HWnd | Specifies the window associated with the rectangle.
put_Left | Specifies the left x-coordinate of the rectangle.
put_Rect | Copies the values of another rectangle to this rectangle.
put_Top | Specifies the top y-coordinate of the rectangle.
put_Width | Specifies the width of the rectangle.


IMSVidRect::get_Height

This topic applies to Windows XP only.

The get_Height method retrieves the height of the rectangle.

Syntax

HRESULT get_Height(
  LONG*  pHeightVal
);

Parameters

pHeightVal

[out] Pointer to a variable that receives the height, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Calling the IMSVidRect::put_Top method changes the height of the rectangle. For example, if the y-coordinate is zero and the height is 100, setting the y-coordinate to 10 changes the height to 90.

See Also

  • IMSVidRect Interface
  • IMSVidRect::put_Height


IMSVidRect::get_HWnd

This topic applies to Windows XP only.

The get_HWnd method retrieves the window associated with the rectangle.

Syntax

HRESULT get_HWnd(
  HWND*  pHWndVal
);

Parameters

pHWndVal

[out] Pointer to a variable that receives a handle to the window.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::put_HWnd


IMSVidRect::get_Left

This topic applies to Windows XP only.

The get_Left method retrieves the left x-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

HRESULT get_Left(
  LONG*  pLeftVal
);

Parameters

pLeftVal

[out] Pointer to a variable that receives the left x-coordinate, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_HWnd
  • IMSVidRect::put_Left


IMSVidRect::get_Top

This topic applies to Windows XP only.

The get_Top method retrieves the top y-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

HRESULT get_Top(
  LONG*  pTopVal
);

Parameters

pTopVal

[out] Pointer to a variable that receives the top y-coordinate, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_HWnd
  • IMSVidRect::put_Top


IMSVidRect::get_Width

This topic applies to Windows XP only.

The get_Width method retrieves the width of the rectangle.

Syntax

HRESULT get_Width(
  LONG*  pWidthVal
);

Parameters

pWidthVal

[out] Pointer to a variable that receives the width, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Calling the IMSVidRect::put_Left method changes the width of the rectangle. For example, if the x-coordinate is zero and the width is 100, setting the x-coordinate to 10 changes the width to 90.

See Also

  • IMSVidRect Interface
  • IMSVidRect::put_Width


IMSVidRect::put_Height

This topic applies to Windows XP only.

The put_Height method specifies the height of the rectangle.

Syntax

HRESULT put_Height(
  LONG  HeightVal
);

Parameters

HeightVal

[in] Specifies the height, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_Height


IMSVidRect::put_HWnd

This topic applies to Windows XP only.

The put_HWnd method specifies the window associated with the rectangle.

Syntax

HRESULT put_HWnd(
  HWND  HWndVal
);

Parameters

HWndVal

[in] Specifies the handle to the window.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_HWnd


IMSVidRect::put_Left

This topic applies to Windows XP only.

The put_Left method specifies the left x-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

HRESULT put_Left(
  LONG  LeftVal
);

Parameters

LeftVal

[in] Specifies the left x-coordinate, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Setting the left x-coordinate also changes the width of the rectangle. For example, if the x-coordinate is zero and the width is 100, setting the x-coordinate to 10 changes the width to 90.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_HWnd
  • IMSVidRect::get_Left


IMSVidRect::put_Rect

This topic applies to Windows XP only.

The put_Rect method copies the values of another rectangle to this rectangle.

Syntax

HRESULT put_Rect(
  IMSVidRect*  pRectVal
);

Parameters

pRectVal

[in] Specifies a pointer to the IMSVidRect interface of the rectangle to copy.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface


IMSVidRect::put_Top

This topic applies to Windows XP only.

The put_Top method specifies the top y-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

HRESULT put_Top(
  LONG  TopVal
);

Parameters

TopVal

[in] Specifies the top y-coordinate, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Setting the top y-coordinate also changes the height of the rectangle. For example, if the y-coordinate is zero and the height is 100, setting the y-coordinate to 10 changes the height to 90.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_HWnd
  • IMSVidRect::get_Top


IMSVidRect::put_Width

This topic applies to Windows XP only.

The put_Width method specifies the width of the rectangle.

Syntax

HRESULT put_Width(
  LONG  WidthVal
);

Parameters

WidthVal

[in] Specifies the width, in pixels.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidRect Interface
  • IMSVidRect::get_Width


IMSVidStreamBufferRecordingControl Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidStreamBufferRecordingControl interface enables an application to manage a stream buffer recording object through the Video Control. To obtain this interface, call one of the following methods:

  • IMSVidStreamBufferSink::get_ContentRecorder
  • IMSVidStreamBufferSink::get_ReferenceRecorder

In addition to the methods inherited from IDispatch, the IMSVidStreamBufferRecordingControl interface exposes the following methods.

Method | Description
get_RecordingAttribute | Retrieves the recording object that is controlled by this interface.
get_RecordingStarted | Queries whether the recording has started.
get_RecordingStopped | Queries whether the recording has stopped.
get_RecordingType | Retrieves the type of recording, either content recording or reference recording.
get_StartTime | Retrieves the start time of the recording.
get_StopTime | Retrieves the stop time of the recording.
put_StartTime | Sets the start time for the recording.
put_StopTime | Sets the stop time for the recording.


IMSVidStreamBufferRecordingControl::get_RecordingAttribute

This topic applies to Windows XP Service Pack 1 only.

The get_RecordingAttribute method retrieves the stream buffer Recording object that is controlled by this interface.

Syntax

HRESULT get_RecordingAttribute(
  IUnknown**  pRecordingAttribute
);

Parameters

pRecordingAttribute

[out] Address of a variable that receives a pointer to the Recording object's IUnknown interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the returned IUnknown pointer.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::get_RecordingStarted

This topic applies to Windows XP Service Pack 1 only.

The get_RecordingStarted method queries whether the recording has started.

Syntax

HRESULT get_RecordingStarted(
  VARIANT_BOOL*  phResult
);

Parameters

phResult

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_FALSE | The recording has not started.
VARIANT_TRUE | The recording has started.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::get_RecordingStopped

This topic applies to Windows XP Service Pack 1 only.

The get_RecordingStopped method queries whether the recording has stopped.

Syntax

HRESULT get_RecordingStopped(
  VARIANT_BOOL*  phResult
);

Parameters

phResult

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_FALSE | The recording has not stopped.
VARIANT_TRUE | The recording has stopped.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::get_RecordingType

This topic applies to Windows XP Service Pack 1 only.

The get_RecordingType method retrieves the type of recording, either content recording or reference recording.

Syntax

HRESULT get_RecordingType(
  RecordingType*  dwType
);

Parameters

dwType

[out] Pointer to a variable that receives one of the following values.

Value | Description
CONTENT | Content recording
REFERENCE | Reference recording

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • Creating Stream Buffer Recordings
  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::get_StartTime

This topic applies to Windows XP Service Pack 1 only.

The get_StartTime method retrieves the start time of the recording.

Syntax

HRESULT get_StartTime(
  long*  pStart
);

Parameters

pStart

[out] Pointer to a variable that receives the start time, in hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::get_StopTime

This topic applies to Windows XP Service Pack 1 only.

The get_StopTime method retrieves the stop time of the recording.

Syntax

HRESULT get_StopTime(
  long*  pStop
);

Parameters

pStop

[out] Pointer to a variable that receives the stop time, in hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::put_StartTime

This topic applies to Windows XP Service Pack 1 only.

The put_StartTime method sets the start time for the recording.

Syntax

HRESULT put_StartTime(
  long  Start
);

Parameters

Start

[in] Specifies the start time, in hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferRecordingControl::put_StopTime

This topic applies to Windows XP Service Pack 1 only.

The put_StopTime method sets the stop time for the recording.

Syntax

HRESULT put_StopTime(
  long  Stop
);

Parameters

Stop

[in] Specifies the stop time, in hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferRecordingControl Interface


IMSVidStreamBufferSink Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidStreamBufferSink interface represents a stream buffer output device.

In addition to the methods inherited from IMSVidOutputDevice, the IMSVidStreamBufferSink interface exposes the following methods.

Method | Description
get_ContentRecorder | Creates a new content recording object.
get_ReferenceRecorder | Creates a new reference recording object.
get_SBESink | Retrieves a pointer to the Stream Buffer Sink filter.
get_SinkName | Retrieves the name of the stub file that points to the backing files.
NameSetLock | Locks the stream buffer profile.
put_SinkName | Sets the name of the stub file that points to the backing files.


IMSVidStreamBufferSink::get_ContentRecorder

This topic applies to Windows XP Service Pack 1 only.

The get_ContentRecorder method creates a new content recording object.

Syntax

HRESULT get_ContentRecorder(
  BSTR  pszFilename,
  IMSVidStreamBufferRecordingControl **pRecordingIUnknown
);

Parameters

pszFilename

[in] Specifies the name of the file to hold the recording.

pRecordingIUnknown

[out] Address of a variable that receives a pointer to the recording object's IMSVidStreamBufferRecordingControl interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the returned IMSVidStreamBufferRecordingControl interface.

See Also

  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSink::get_ReferenceRecorder

This topic applies to Windows XP Service Pack 1 only.

The get_ReferenceRecorder method creates a new reference recording object.

Syntax

HRESULT get_ReferenceRecorder(
  BSTR  pszFilename,
  IMSVidStreamBufferRecordingControl  **pRecordingIUnknown
);

Parameters

pszFilename

[in] Specifies the name of the file to hold the recording.

pRecordingIUnknown

[out] Address of a variable that receives a pointer to the recording object's IMSVidStreamBufferRecordingControl interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the IMSVidStreamBufferRecordingControl interface.

See Also

  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSink::get_SBESink

This topic applies to Windows XP Service Pack 1 only.

The get_SBESink method retrieves a pointer to the Stream Buffer Sink filter.

Syntax

HRESULT get_SBESink(
  IUnknown **ppUnk
);

Parameters

ppUnk

[out] Address of a variable that receives a pointer to the filter's IUnknown interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the IUnknown interface.

See Also

  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSink::get_SinkName

This topic applies to Windows XP Service Pack 1 only.

The get_SinkName method retrieves the name of the stub file that points to the backing files.

Syntax

HRESULT get_SinkName(
  BSTR *pName
);

Parameters

pName

[out] Pointer to a variable that receives the file name.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

The caller must release the returned string, using the SysFreeString function.

See Also

  • Buffering in the Stream Buffer Engine
  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSink::NameSetLock

This topic applies to Windows XP Service Pack 1 only.

The NameSetLock method locks the stream buffer profile.

Syntax

HRESULT NameSetLock();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • Buffering in the Stream Buffer Engine
  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSink::put_SinkName

This topic applies to Windows XP Service Pack 1 only.

The put_SinkName method sets the name of the stub file that points to the backing files.

Syntax

HRESULT put_SinkName(
  BSTR  Name
);

Parameters

Name

[in] Specifies the file name.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
S_OK | The method succeeded.

Parameters

Call this method before calling NameSetLock, while the graph is stopped. Otherwise, the method fails and returns E_FAIL.

See Also

  • Buffering in the Stream Buffer Engine
  • IMSVidStreamBufferSink Interface


IMSVidStreamBufferSource Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidStreamBufferSource interface represents a stream buffer source object.

In addition to the methods inherited from IMSVidFilePlayback, the IMSVidStreamBufferSource interface exposes the following methods.

Method | Description
CurrentRatings | Retrieves the current ratings information from the data source.
get_RecordingAttribute | Retrieves the Stream Buffer Source filter that this object manages.
get_SBESource | Retrieves a pointer to the Stream Buffer Source filter.
get_Start | Retrieves the start time.
MaxRatingsLevel | Specifies the maximum ratings level the object is permitted to play.
put_BlockUnrated | Specifies whether to block unrated content.
put_UnratedDelay | Specifies the amount of time to play unrated content before blocking it.


IMSVidStreamBufferSource::CurrentRatings

This topic applies to Windows XP Service Pack 1 only.

The CurrentRatings method retrieves the current ratings information from the data source.

Syntax

HRESULT CurrentRatings(
  EnTvRat_System*  pEnSystem,
  EnTvRat_GenericLevel*  pEnRating,
  long*  pBfEnAttr
);

Parameters

pEnSystem

[out] Pointer to a variable that receives the rating system, as an EnTvRat_System enumeration value.

pEnRating

[out] Pointer to a variable that receives the rating level, as an EnTvRat_GenericLevel enumeration value.

pBfEnAttr

[out] Pointer to a variable that receives the ratings attributes, as a bitwise combination of zero or more flags from the BfEnTvRat_GenericAttributes enumeration.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferSource Interface
  • TV Ratings Components


IMSVidStreamBufferSource::get_RecordingAttribute

This topic applies to Windows XP Service Pack 1 only.

The get_RecordingAttribute method retrieves the Stream Buffer Source filter that this object manages.

Syntax

HRESULT get_RecordingAttribute(
  IUnknown**  pRecordingAttribute
);

Parameters

pRecordingAttribute

[out] Pointer to a variable that receives a pointer to the filter's IUnknown interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the returned IUnknown interface.

See Also

  • IMSVidStreamBufferSource Interface


IMSVidStreamBufferSource::get_SBESource

This topic applies to Windows XP Service Pack 1 only.

The get_SBESource method retrieves a pointer to the Stream Buffer Source filter.

Syntax

HRESULT get_SBESource(
  IUnknown **sbeFilter
);

Parameters

sbeFilter

[out] Address of a variable that receives a pointer to the filter's IUnknown interface.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must release the IUnknown interface.

See Also

  • IMSVidStreamBufferSource Interface


IMSVidStreamBufferSource::get_Start

This topic applies to Windows XP Service Pack 1 only.

The get_Start method retrieves the start time.

Syntax

HRESULT get_Start(
  long*  lStart
);

Parameters

lStart

[out] Pointer to a variable that receives the start time, in hundredths of seconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferSource Interface


IMSVidStreamBufferSource::MaxRatingsLevel

This topic applies to Windows XP Service Pack 1 only.

The MaxRatingsLevel method specifies the maximum ratings level the object is permitted to play.

Syntax

HRESULT MaxRatingsLevel(
  EnTvRat_System  pEnSystem,
  EnTvRat_GenericLevel  pEnRating,
  long  pBfEnAttr
);

Parameters

pEnSystem

[in] Specifies the rating system, as an EnTvRat_System enumeration value.

pEnRating

[in] Specifies the maximum rating level, as an EnTvRat_GenericLevel enumeration value.

pBfEnAttr

[in] Specifies zero or more ratings attributes, as a bitwise combination of flags from the BfEnTvRat_GenericAttributes enumeration.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferSource Interface
  • TV Ratings Components


IMSVidStreamBufferSource::put_BlockUnrated

This topic applies to Windows XP Service Pack 1 only.

The put_BlockUnrated method specifies whether to block unrated content.

Syntax

HRESULT put_BlockUnrated(
  VARIANT_BOOL  bBlock
);

Parameters

bBlock

[in] Specifies one of the following values.

Value | Description
VARIANT_FALSE | Do not block unrated content.
VARIANT_TRUE | Block unrated content.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferSource Interface
  • IMSVidStreamBufferSource::put_UnratedDelay


IMSVidStreamBufferSource::put_UnratedDelay

This topic applies to Windows XP Service Pack 1 only.

The put_UnratedDelay method specifies how long the Video Control will play unrated content before blocking it. The value is ignored until the put_BlockUnrated method is called with the value VARIANT_TRUE.

Syntax

HRESULT put_UnratedDelay(
  long  dwDelay
);

Parameters

dwDelay

[in] Specifies the delay before blocking unrated content, in milliseconds.

Return Values

The method returns an HRESULT. Possible values include the following.

Value | Description
S_OK | The method succeeded.

See Also

  • IMSVidStreamBufferSource Interface
  • IMSVidStreamBufferSource::put_BlockUnrated


IMSVidTuner Interface

This topic applies to Windows XP only.

The IMSVidTuner interface manages tuning devices. It is exposed by the MSVidBDATunerDevice object, which represents Broadcast Driver Architecture (BDA)-compliant tuning devices. Non-BDA analog tuners expose the IMSVidAnalogTuner interface, which inherits from this interface.

In addition to the methods inherited from IMSVidVideoInputDevice, the IMSVidTuner interface exposes the following methods.

Method | Description
get_Tune | Retrieves the current tune request.
get_TuningSpace | Retrieves the current tuning space.
put_Tune | Specifies the tune request.
put_TuningSpace | Specifies the tuning space.


IMSVidTuner::get_Tune

This topic applies to Windows XP only.

The get_Tune method retrieves the current tune request.

Syntax

HRESULT get_Tune(
  ITuneRequest**  ppTR
);

Parameters

ppTR

[out] Pointer to a variable that receives an ITuneRequest interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned ITuneRequest interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidTuner Interface
  • IMSVidTuner::put_Tune
  • The Microsoft Unified Tuning Model


IMSVidTuner::get_TuningSpace

This topic applies to Windows XP only.

The get_TuningSpace method retrieves the current tuning space.

Syntax

HRESULT get_TuningSpace(
  ITuningSpace**  pplTS
);

Parameters

pplTS

[out] Pointer to a variable that receives an ITuningSpace interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned ITuningSpace interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidTuner Interface
  • IMSVidTuner::put_TuningSpace
  • The Microsoft Unified Tuning Model


IMSVidTuner::put_Tune

This topic applies to Windows XP only.

The put_Tune method specifies the tune request.

Syntax

HRESULT put_Tune(
  ITuneRequest*  pTR
);

Parameters

pTR

[in] Specifies a pointer to the tune request's ITuneRequest interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidTuner Interface
  • IMSVidTuner::get_Tune
  • The Microsoft Unified Tuning Model


IMSVidTuner::put_TuningSpace

This topic applies to Windows XP only.

The put_TuningSpace method specifies the tuning space.

Syntax

HRESULT put_TuningSpace(
  ITuningSpace*  plTS
);

Parameters

plTS

[in] Specifies a pointer to the tuning space's ITuningSpace interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidTuner Interface
  • IMSVidTuner::get_TuningSpace
  • The Microsoft Unified Tuning Model


IMSVidVideoInputDevice Interface

This topic applies to Windows XP only.

The IMSVidVideoInputDevice interface represents a video input device. This interface inherits from the IMSVidInputDevice interface but adds no methods to it. It exists to support polymorphism.

The IMSVidTuner interface, which represents video tuning devices, inherits from this interface.


IMSVidVideoRenderer Interface

This topic applies to Windows XP only.

The IMSVidVideoRenderer interface represents a video renderer device. The MSVidVideoRenderer object exposes this interface.

This interface provides access to the Video Mixing Renderer (VMR) filter.

In addition to the methods inherited from IMSVidOutputDevice, the IMSVidVideoRenderer interface exposes the following methods.

Method | Description
Capture | Captures the video frame that is currently being rendered by the VMR.
get__CustomCompositor | Retrieves the VMR's current image compositor.
get__CustomCompositorClass | Retrieves the class identifier (CLSID) of the VMR's current image compositor, as a GUID
get__MixerBitmap | Retrieves the VMR's IVMRMixerBitmap interface, which controls how the VMR mixes a static bitmap
get_AvailableSourceRect | Retrieves the size of the native video.
get_ClippedSourceRect | Retrieves the clipping rectangle on the video source.
get_CustomCompositorClass | Retrieves the CLSID of the VMR's current image compositor, as a BSTR.
get_DecimateInput | Indicates whether the VMR will decimate the video (that is, reduce the native video size) before processing it.
get_FramesPerSecond | Retrieves the current frame rate.
get_MaxVidRect | Retrieves the maximum ideal size of the video rectangle.
get_MinVidRect | Retrieves the minimum ideal size of the video rectangle.
get_MixerBitmap | Retrieves the static bitmap image, as an IPictureDisp type.
get_MixerBitmapOpacity | Retrieves the opacity of the static bitmap image.
get_MixerBitmapPositionRect | Retrieves the position of the static bitmap image, relative to the video window.
get_OverScan | Retrieves the amount of clipping to perform on all sides of the video frame, in order to cut off random video noise.
get_SourceSize | Retrieves the type of clipping to apply to the video rectangle, if any.
get_UsingOverlay | Queries whether the VMR is using the hardware overlay.
put__CustomCompositor | Specifies a custom image compositor for the VMR to use.
put__CustomCompositorClass | Specifies the CLSID of a custom image compositor, as a GUID.
put__MixerBitmap | Specifies the static bitmap image.
put_ClippedSourceRect | Specifies the clipping rectangle on the video source.
put_CustomCompositorClass | Specifies the CLSID of a custom image compositor, as a BSTR.
put_DecimateInput | Specifies whether the VMR will decimate the video (that is, reduce the native video size) before processing it.
put_MixerBitmap | Specifies the static bitmap image, as an IPictureDisp type.
put_MixerBitmapOpacity | Specifies the opacity of the static bitmap image.
put_MixerBitmapPositionRect | Specifies the position of the static bitmap image, relative to the video window.
put_OverScan | Specifies the amount of clipping to perform on all sides of the video frame, in order to cut off random video noise.
put_SourceSize | Specifies the type of clipping to apply to the video rectangle, if any.
put_UsingOverlay | Specifies whether the VMR will use the hardware overlay.
SetupMixerBitmap | Configures the VMR to display an alpha-blended bitmap on top of the video.


IMSVidVideoRenderer::Capture

This topic applies to Windows XP only.

The Capture method captures the video frame that is currently being rendered by the Video Mixing Renderer (VMR).

Syntax

HRESULT Capture(
  IPictureDisp**  ppcurrentImage
);

Parameters

ppcurrentImage

[out] Address of a variable that receives an IPictureDisp interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned IPictureDisp interface has an outstanding reference count. The caller must release the interface.

For information about the IPictureDisp interface, see the Microsoft Platform SDK documentation.

Example Code

CComPtr<IMSVidCtl> m_pVideoControl; // Pointer to the Video Control.

/* Build and run the filter graph (not shown). */

// Find the video renderer
CComPtr<IMSVidVideoRenderer> pVideo;
hr = m_pVideoControl->get_VideoRendererActive(&pVideo);
if (SUCCEEDED(hr))
{
    // Capture the image.
    CComPtr<IPictureDisp> pPic;
    hr = pVideo->Capture(&pPic);
}

See Also

  • IMSVidVideoRenderer Interface
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::get__CustomCompositor

This topic applies to Windows XP only.

The get__CustomCompositor method retrieves the Video Mixing Renderer's current image compositor.

Syntax

HRESULT get__CustomCompositor(
  IVMRImageCompositor**  ppCompositor
);

Parameters

ppCompositor

[out] Address of an variable that receives an IVMRImageCompositor interface pointer .

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Applications can provide their own compositors to perform custom image compositing. For more information, see Using the Video Mixing Renderer.

The returned IVMRImageCompositor interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get__CustomCompositorClass
  • IMSVidVideoRenderer::put__CustomCompositor


IMSVidVideoRenderer::get__CustomCompositorClass

This topic applies to Windows XP only.

The get__CustomCompositorClass method retrieves the class identifier (CLSID) of the Video Mixing Renderer's current image compositor, as a GUID.

Syntax

HRESULT get__CustomCompositorClass(
  GUID*  pCompositorCLSID
);

Parameters

pCompositorCLSID

[out] Pointer to a variable that receives the CLSID.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Applications can provide their own compositors to perform custom image compositing. For more information, see Using the Video Mixing Renderer.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get__CustomCompositor
  • IMSVidVideoRenderer::put__CustomCompositorClass


IMSVidVideoRenderer::get__MixerBitmap

This topic applies to Windows XP only.

The get__MixerBitmap method retrieves the Video Mixing Renderer's IVMRMixerBitmap interface, which controls how the VMR mixes a static bitmap.

Syntax

HRESULT get__MixerBitmap(
  IVMRMixerBitmap**  ppMixerPicture
);

Parameters

ppMixerPicture

[out] Address of a variable that receives an IVMRMixerBitmap interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned IVMRMixerBitmap interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmap
  • IMSVidVideoRenderer::put__MixerBitmap
  • Mixing an Image Onto the Video Window in C++


IMSVidVideoRenderer::get_AvailableSourceRect

This topic applies to Windows XP only.

The get_AvailableSourceRect method retrieves the size of the native video.

Syntax

HRESULT get_AvailableSourceRect(
  IMSVidRect**  ppRect
);

Parameters

ppRect

[out] Address of a variable that receives an IMSVidRect interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The returned IMSVidRect interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface


IMSVidVideoRenderer::get_ClippedSourceRect

This topic applies to Windows XP only.

The get_ClippedSourceRect method retrieves the clipping rectangle on the video source.

Syntax

HRESULT get_ClippedSourceRect(
  IMSVidRect**  ppRect
);

Parameters

ppRect

[out] Address of a variable that receives an IMSVidRect interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the current clipping mode is sslClipByClipRect, the VMR clips the video image to the video source rectangle, and stretches the clipped image to fill the Video Control's video window. For more information, see IMSVidVideoRenderer::put_SourceSize.

The returned IMSVidRect interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_ClippedSourceRect


IMSVidVideoRenderer::get_CustomCompositorClass

This topic applies to Windows XP only.

The get_CustomCompositorClass method retrieves the class identifier (CLSID) of the Video Mixing Renderer's current image compositor, as a BSTR.

Syntax

HRESULT get_CustomCompositorClass(
  BSTR*  pCompositorCLSID
);

Parameters

pCompositorCLSID

[out] Pointer to a variable that receives a string representation of the CLSID.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is provided for Automation clients. C++ applications can use the IMSVidVideoRenderer::get__CustomCompositorClass method, which returns a GUID rather than a BSTR.

The caller must free the returned string, using the SysFreeString function.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_CustomCompositorClass
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::get_DecimateInput

This topic applies to Windows XP only.

The get_DecimateInput method queries whether the Video Mixing Renderer (VMR) is currently configured to decimate the video (that is, reduce the native video size) before processing it.

This method is currently not supported.

Syntax

HRESULT get_DecimateInput(
    VARIANT_BOOL* pDeci
  );

Parameters

pDeci

[out] Pointer to a variable that receives one of the following values.

Value | Description
VARIANT_TRUE | The VMR is configured to decimate the video.
VARIANT_FALSE | The VMR is not configured to decimate the video.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This property should be set to true when the native video stream is HDTV but the system monitor is set to a lower resolution. This prevents the VMR from doing unnecessary work by processing the video at high resolution and then shrinking it.

See Also

  • IMSVidVideoRenderer Interface
  • IVMRMixerControl::GetMixingPrefs
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::get_FramesPerSecond

This topic applies to Windows XP only.

The get_FramesPerSecond method retrieves the current frame rate.

Syntax

HRESULT get_FramesPerSecond(
    long* pVal
  );

Parameters

pVal

[out] Pointer to a variable that receives the frame rate, in frames per second.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::get_MaxVidRect

This topic applies to Windows XP only.

The get_MaxVidRect method retrieves the maximum ideal size of the video rectangle.

Syntax

HRESULT get_MaxVidRect(
  IMSVidRect**  ppVidRect
);

Parameters

ppVidRect

[out] Address of a variable that receives an IMSVidRect interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The maximum ideal image size is the maximum video size that can be displayed without significantly degrading performance or image quality.

The returned IMSVidRect interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MinVidRect


IMSVidVideoRenderer::get_MinVidRect

This topic applies to Windows XP only.

The get_MinVidRect method retrieves the minimum ideal size of the video rectangle.

Syntax

HRESULT get_MinVidRect(
  IMSVidRect**  ppVidRect
);

Parameters

ppVidRect

[out] Address of a variable that receives an IMSVidRect interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The minimum ideal image size is the minimum video size that can be displayed without significantly degrading performance or image quality.

The returned IMSVidRect interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MaxVidRect


IMSVidVideoRenderer::get_MixerBitmap

This topic applies to Windows XP only.

The get_MixerBitmap method retrieves the static bitmap image, as an IPictureDisp type.

Syntax

HRESULT get_MixerBitmap(
  IPictureDisp**  ppMixerPictureDisp
);

Parameters

ppMixerPictureDisp

[out] Address of a variable that receives an IPictureDisp interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
CO_E_NOTINITIALIZED | No bitmap was set.

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image. For information about the IPictureDisp interface, see the Platform SDK documentation.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmapOpacity
  • IMSVidVideoRenderer::get_MixerBitmapPositionRect
  • IMSVidVideoRenderer::put_MixerBitmap
  • Mixing an Image Onto the Video Window in C++


IMSVidVideoRenderer::get_MixerBitmapOpacity

This topic applies to Windows XP only.

The get_MixerBitmapOpacity method retrieves the opacity of the static bitmap image.

Syntax

HRESULT get_MixerBitmapOpacity(
  int*  pOpacity
);

Parameters

pOpacity

[out] Pointer to a variable that receives the opacity, expressed as an integer from 0 (transparent) to 100 (opaque).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image, using the opacity given in pOpacity.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmap
  • IMSVidVideoRenderer::put_MixerBitmapOpacity


IMSVidVideoRenderer::get_MixerBitmapPositionRect

This topic applies to Windows XP only.

The get_MixerBitmapPositionRect method retrieves the position of the static bitmap image, relative to the video window.

Syntax

HRESULT get_MixerBitmapPositionRect(
  IMSVidRect**  pprDest
);

Parameters

pprDest

[out] Address of a variable that receives an IMSVidRect interface pointer.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image, using the position rectangle given in pprDest.

The returned IMSVidRect interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmap
  • IMSVidVideoRenderer::put_MixerBitmapPositionRect


IMSVidVideoRenderer::get_OverScan

This topic applies to Windows XP only.

The get_OverScan method retrieves the amount of clipping to perform on all sides of the video frame, in order to cut off random video noise.

Syntax

HRESULT get_OverScan(
  long*  plPercent
);

Parameters

plPercent

[out] Pointer to a variable that receives the amount to clip, in hundredths of a percent.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the current clipping mode is sslClipByOverScan, the VMR clips the video image by the amount given in the plPercent parameter. For more information, see IMSVidVideoRenderer::put_SourceSize.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_OverScan


IMSVidVideoRenderer::get_SourceSize

This topic applies to Windows XP only.

The get_SourceSize method retrieves the type of clipping to apply to the video rectangle, if any.

Syntax

HRESULT get_SourceSize(
  SourceSizeList*  pCurrentSize
);

Parameters

pCurrentSize

Pointer to a variable that receives a member of the SourceSizeList enumeration.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_SourceSize


IMSVidVideoRenderer::get_UsingOverlay

This topic applies to Windows XP only.

The get_UsingOverlay method queries whether the Video Mixing Renderer (VMR) is using the hardware overlay.

Syntax

HRESULT get_UsingOverlay(
  VARIANT_BOOL*  pUseOverlayVal
);

Parameters

pUseOverlayVal

[out] Pointer to a variable the receives one of the following values.

Value | Description
VARIANT_TRUE | The VMR is using the hardware overlay.
VARIANT_FALSE | The VMR is not using the hardware overlay.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_UsingOverlay


IMSVidVideoRenderer::put__CustomCompositor

This topic applies to Windows XP only.

The put__CustomCompositor method specifies a custom image compositor for the Video Mixing Renderer (VMR) to use.

Syntax

HRESULT put__CustomCompositor(
  IVMRImageCompositor*  pCompositor
);

Parameters

pCompositor

[in] Pointer to the IVMRImageCompositor interface of the image compositor.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Applications can provide their own compositors to perform custom image compositing. For more information, see Using the Video Mixing Renderer.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get__CustomCompositor
  • IMSVidVideoRenderer::put__CustomCompositorClass


IMSVidVideoRenderer::put__CustomCompositorClass

This topic applies to Windows XP only.

The put__CustomCompositorClass method specifies the class identifier (CLSID) of a custom image compositor, as a GUID.

Syntax

HRESULT put__CustomCompositorClass(
  REFCLSID  CompositorCLSID
);

Parameters

CompositorCLSID

[in] Specifies the CLSID of the custom compositor.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Applications can provide their own compositors to perform custom image compositing. For more information, see Using the Video Mixing Renderer.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get__CustomCompositorClass
  • IMSVidVideoRenderer::put__CustomCompositor


IMSVidVideoRenderer::put__MixerBitmap

This topic applies to Windows XP only.

The put__MixerBitmap method specifies the static bitmap image.

Syntax

HRESULT put__MixerBitmap(
  VMRALPHABITMAP*  pMixerPicture
);

Parameters

pMixerPicture

[in] Specifies the address of a VMRALPHABITMAP structure that contains information about the bitmap.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

No special remarks.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get__MixerBitmap
  • IMSVidVideoRenderer::put_MixerBitmap
  • Mixing an Image Onto the Video Window in C++


IMSVidVideoRenderer::put_ClippedSourceRect

This topic applies to Windows XP only.

The put_ClippedSourceRect method specifies the clipping rectangle on the video source.

Syntax

HRESULT put_ClippedSourceRect(
  IMSVidRect*  pRect
);

Parameters

pRect

[in] Pointer to an IMSVidRect interface that specifies the rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the current clipping mode is sslClipByClipRect, the VMR clips the video image to the video source rectangle and stretches this to fill the Video Control's video window. For more information, see IMSVidVideoRenderer::put_SourceSize.

Example Code

The following example clips the video image to the upper left corner of the source rectangle.

CComPtr<IMSVidVideoRenderer> pVideo;
HRESULT hr = pVideoControl->get_VideoRendererActive(&pVideo);
if (SUCCEEDED(hr))
{
    long lWidth, lHeight;
    CComPtr<IMSVidRect> pRect;

    hr = pVideo->get_AvailableSourceRect(&pRect);
    pRect->get_Height(&lHeight);
    pRect->get_Width(&lWidth);
    pRect->put_Height(lHeight / 2);
    pRect->put_Width(lWidth / 2);
    pVideo->put_SourceSize(sslClipByClipRect);
    hr = pVideo->put_ClippedSourceRect(pRect);
}

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_ClippedSourceRect


IMSVidVideoRenderer::put_CustomCompositorClass

This topic applies to Windows XP only.

The put_CustomCompositorClass method specifies the class identifier (CLSID) of a custom image compositor, as a BSTR.

Syntax

HRESULT put_CustomCompositorClass(
  BSTR  CompositorCLSID
);

Parameters

CompositorCLSID

[in] Specifies the CLSID as a string.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is provided for Automation clients. C++ applications can use the IMSVidVideoRenderer::put__CustomCompositorClass method, which specifies a GUID rather than a BSTR.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_CustomCompositorClass
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::put_DecimateInput

This topic applies to Windows XP only.

The put_DecimateInput method specifies whether the Video Mixing Renderer (VMR) will decimate the video (that is, reduce the native video size) before processing it.

This method is currently not supported.

Syntax

HRESULT put_DecimateInput(
    VARIANT_BOOL bDecimate
  );

Parameters

bDecimate

Specifies whether to enable or disable video decimation. Use one of the following values.

Value | Description
VARIANT_TRUE | Enable video decimation.
VARIANT_FALSE | Disable video decimation.

Return Value

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This property should be set to true when the native video stream is HDTV but the system monitor is set to a lower resolution. This prevents the VMR from doing unnecessary work by processing the video at high resolution and then shrinking it.

See Also

  • IMSVidVideoRenderer Interface
  • IVMRMixerControl::SetMixingPrefs
  • Using the Video Mixing Renderer


IMSVidVideoRenderer::put_MixerBitmap

This topic applies to Windows XP only.

The put_MixerBitmap method specifies the static bitmap image, as an IPictureDisp type.

Syntax

HRESULT put_MixerBitmap(
  IPictureDisp*  pMixerPictureDisp
);

Parameters

pMixerPictureDisp

[in] Specifies a pointer to the IPictureDisp interface.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The VMR alpha-blends the static bitmap image onto the video image. For information about the IPictureDisp interface, see the Platform SDK documentation.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmap
  • IMSVidVideoRenderer::put_MixerBitmapOpacity
  • IMSVidVideoRenderer::put_MixerBitmapPositionRect
  • IMSVidVideoRenderer::SetupMixerBitmap
  • Mixing an Image Onto the Video Window in C++


IMSVidVideoRenderer::put_MixerBitmapOpacity

This topic applies to Windows XP only.

The put_MixerBitmapOpacity method specifies the opacity of the static bitmap image.

Syntax

HRESULT put_MixerBitmapOpacity(
  int  opacity
);

Parameters

opacity

[in] Specifies the opacity as an integer from 0 (transparent) to 100 (opaque).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the static bitmap image is set, the VMR alpha blends the bitmap onto the video image, using the specified opacity.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmapOpacity
  • IMSVidVideoRenderer::put_MixerBitmap
  • IMSVidVideoRenderer::SetupMixerBitmap


IMSVidVideoRenderer::put_MixerBitmapPositionRect

This topic applies to Windows XP only.

The put_MixerBitmapPositionRect method specifies the position of the static bitmap image, relative to the video window.

Syntax

HRESULT put_MixerBitmapPositionRect(
  IMSVidRect*  prDest
);

Parameters

prDest

[in] Pointer to an IMSVidRect interface, specifying the rectangle.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the static bitmap image is set, the VMR alpha blends the bitmap onto the video image, using the specified position rectangle.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_MixerBitmapPositionRect
  • IMSVidVideoRenderer::put_MixerBitmap
  • IMSVidVideoRenderer::SetupMixerBitmap


IMSVidVideoRenderer::put_OverScan

This topic applies to Windows XP only.

The put_OverScan method specifies the amount of clipping to perform on all sides of the video frame to cut off random video noise.

Syntax

HRESULT put_OverScan(
  long  lPercent
);

Parameters

lPercent

[in] Specifies the amount to clip, in hundredths of a percent. For example, 175 indicates 1.75%.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the current clipping mode is sslClipByOverScan, the VMR clips the video image by the specified amount. For more information, see IMSVidVideoRenderer::put_SourceSize.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_OverScan


IMSVidVideoRenderer::put_SourceSize

This topic applies to Windows XP only.

The put_SourceSize method specifies the type of clipping to apply to the video rectangle, if any.

Syntax

HRESULT put_SourceSize(
  SourceSizeList  NewSize
);

Parameters

NewSize

[in] Specifies a member of the SourceSizeList enumeration.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_SourceSize
  • IMSVidVideoRenderer::put_ClippedSourceRect
  • IMSVidVideoRenderer::put_OverScan


IMSVidVideoRenderer::put_UsingOverlay

This topic applies to Windows XP only.

The put_UsingOverlay method specifies whether the Video Mixing Renderer will use the hardware overlay.

Syntax

HRESULT put_UsingOverlay(
  VARIANT_BOOL  UseOverlayVal
);

Parameters

UseOverlayVal

[in] Flag that specifies whether to use the hardware overlay. Use one of the following values.

Value | Description
VARIANT_TRUE | Use the hardware overlay.
VARIANT_FALSE | Do not use the hardware overlay.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::get_UsingOverlay


IMSVidVideoRenderer::SetupMixerBitmap

This topic applies to Windows XP only.

The SetupMixerBitmap method configures the Video Mixing Renderer (VMR) to display an alpha-blended bitmap on top of the video.

Syntax

HRESULT SetupMixerBitmap(
  IPictureDisp*  pMixerPictureDisp,
  long  Opacity,
  IMSVidRect*  prDest
);

Parameters

pMixerPictureDisp

[in] Pointer to an IPictureDisp interface that specifies the bitmap.

Opacity

[in] Specifies the opacity of the bitmap, as an integer from 0 (transparent) to 100 (opaque).

prDest

[in] Pointer to an IMSVidRect interface that specifies the position of the bitmap, relative to the video window.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • IMSVidVideoRenderer Interface
  • IMSVidVideoRenderer::put_MixerBitmap
  • IMSVidVideoRenderer::put_MixerBitmapOpacity
  • IMSVidVideoRenderer::put_MixerBitmapPositionRect


IMSVidVideoRenderer2 Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidVideoRenderer2 interface represents a video renderer device. The MSVidVideoRenderer object exposes this interface.

This interface provides access to the Video Mixing Renderer (VMR) filter. It inherits the IMSVidVideoRenderer and adds support for custom allocator-presenters.

In addition to the methods inherited from IMSVidVideoRenderer, the IMSVidVideoRenderer2 interface exposes the following methods.

Method | Description
get__Allocator | Retrieves the allocator-presenter from the VMR
get_Allocator | Retrieves the allocator-presenter from the VMR as an IUnknown pointer.
get_Allocator_ID | Retrieves an identifier for the VMR filter's allocator-presenter
get_SuppressEffects | Retrieves settings that control power management and visual effects.
put_SuppressEffects | Sets preferences for power management and visual effects.
_SetAllocator | Specifies an allocator-presenter for the VMR.
SetAllocator | Specifies an allocator-presenter for the VMR as an IUnknown pointer.

See Also

  • Using the Video Mixing Renderer


IMSVidVideoRenderer2::get__Allocator

This topic applies to Windows XP Service Pack 1 only.

The get__Allocator method retrieves the allocator-presenter from the VMR.

Syntax

HRESULT get__Allocator(
    IVMRSurfaceAllocator **ppAllocPresent
);

Parameters

ppAllocPresent

[out] Address of a variable that receives an IVMRSurfaceAllocator interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The caller must release the IVMRSurfaceAllocator interface.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRenderer2::get_Allocator

This topic applies to Windows XP Service Pack 1 only.

The get__Allocator method retrieves the allocator-presenter from the VMR as an IUnknown pointer.

This method is provided for Automation clients. C++ applications can also use the get__Allocator method, which returns an IVMRSurfaceAllocator pointer.

Syntax

HRESULT get_Allocator(
    IUnknown **ppAllocPresent
);

Parameters

ppAllocPresent

[out] Address of a variable that receives a pointer to the allocator-presenter's IUnknown interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

Remarks

The caller must release the returned IUnknown interface.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRenderer2::get_Allocator_ID

This topic applies to Windows XP Service Pack 1 only.

The get_Allocator_ID method retrieves an identifier for the VMR filter's allocator-presenter.

Syntax

HRESULT get_Allocator_ID(
    long *pID
);

Parameters

pID

[out] Pointer to a variable that receives the identifier. If the returned value is -1, the MSVidVideoRenderer object will assign a default identifier when it builds the filter graph.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

Remarks

The identifier is for application use; it is not used by the VMR.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRenderer2::get_SuppressEffects

This topic applies to Windows XP Service Pack 1 only.

The get_SuppressEffects method retrieves settings that control power management and visual effects.

Syntax

HRESULT get_SuppressEffects(
    VARIANT_BOOL *pbSuppress
);

Parameters

pbSuppress

[out] Pointer to a variable that receives the value VARIANT_TRUE or VARIANT_FALSE. For more information, see IMSVidVideoRenderer2::put_SuppressEffects.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRenderer2::put_SuppressEffects

This topic applies to Windows XP Service Pack 1 only.

The put_SuppressEffects method sets preferences for power management and visual effects.

Syntax

HRESULT put_SuppressEffects(
    VARIANT_BOOL bSuppress
);

Parameters

bSuppress

[in] Specifies a Boolean value. See Remarks for more information.

Remarks

If bSuppress equals VARIANT_TRUE, the Video Control does the following

  • Disables font smoothing and the system-wide drop shadow effect. (Only when the Video Control is using hardware overlay.) This is useful if the application draws onto the overlay.
  • Disables the screen saver, and turns off power management for the display. This is useful to prevent the operating system from interrupting playback while the user is watching a program.

The Video Control restores the original system settings after it stops.

If bSuppress equals VARIANT_FALSE, the Video Control uses the existing system settings.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

See Also

  • IMSVidVideoRenderer2 Interface
  • IMSVidVideoRenderer::put_UsingOverlay


IMSVidVideoRenderer2::_SetAllocator

This topic applies to Windows XP Service Pack 1 only.

The _SetAllocator method specifies an allocator-presenter for the VMR. Applications can use this method to provide their own custom allocator-presenter objects.

Syntax

HRESULT _SetAllocator(
    IVMRSurfaceAllocator *pAllocPresent,
    long ID = -1
);

Parameters

pAllocPresent

[in] Pointer to the IVMRSurfaceAllocator interface of the allocator-presenter object.

ID

[in] Optionally, specifies an identifier (ID) for the allocator-presenter object. The default value of -1 indicates that the MSVidVideoRenderer object will create an ID when it builds the filter graph. In that case, the MSVidVideoRenderer object uses the lower 32 bits of the allocator-presenter's IUnknown interface pointer as the ID. Note that the ID is for application use; the VMR does not use it.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRenderer2::SetAllocator

This topic applies to Windows XP Service Pack 1 only.

The SetAllocator method specifies an allocator-presenter for the VMR as an IUnknown pointer.

This method is provided for Automation clients. C++ applications can also use the _SetAllocator method, which takes an IVMRSurfaceAllocator pointer.

Syntax

HRESULT SetAllocator(
    IUnknown *pAllocPresent,
    long ID = -1
);

Parameters

pAllocPresent

[in] Pointer to the IUnknown interface of the allocator-presenter object.

ID

[in] Optionally, specifies an identifier (ID) for the allocator-presenter object. The default value of -1 indicates that the MSVidVideoRenderer object will create an ID when it builds the filter graph. In that case, the MSVidVideoRenderer object uses the lower 32 bits of the allocator-presenter's IUnknown interface pointer as the ID. Note that the ID is for application use; the VMR does not use it.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.

See Also

  • IMSVidVideoRenderer2 Interface


IMSVidVideoRendererDevices Interface

This topic applies to Windows XP only.

The IMSVidVideoRendererDevices interface represents a collection of video renderers. The MSVidVideoRendererDevices object exposes this method. Applications can use this interface to enumerate the collection.

In addition to the methods inherited from IDispatch, the IMSVidVideoRendererDevices interface exposes the following methods.

Method | Description
Add | Adds a video renderer to the collection.
get_Count | Retrieves the number of items in the collection.
get_Item | Retrieves the specified item from the collection.
get__NewEnum | Retrieves an enumerator for the collection.
Remove | Removes an item from the collection.


IMSVidVideoRendererDevices::Add

This topic applies to Windows XP only.

The Add method adds a video renderer to the collection.

Syntax

HRESULT Add(
  IMSVidVideoRenderer* pDB
);

Parameters

pDB

[in] Specifies a pointer to the video renderers IMSVidVideoRenderer interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_ACCESSDENIED | The collection is read-only; cannot add any items.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidVideoRendererDevices Interface


IMSVidVideoRendererDevices::get_Count

This topic applies to Windows XP only.

The get_Count method retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
  long*  plCount
);

Parameters

plCount

[out] Pointer to a variable that receives the number of items.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_POINTER | NULL pointer argument.

See Also

  • IMSVidVideoRendererDevices Interface


IMSVidVideoRendererDevices::get_Item

This topic applies to Windows XP only.

The get_Item method retrieves the specified item from the collection.

Syntax

HRESULT get_Item(
  VARIANT  v,
  IMSVidVideoRenderer**  ppDB
);

Parameters

v

[in] VARIANT that specifies the index of the item to retrieve.

ppDB

[out] Address of a variable that receives an IMSVidVideoRenderer interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidVideoRendererDevices::get_Count - 1.

If the method succeeds, the IMSVidVideoDevice interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRendererDevices Interface


IMSVidVideoRendererDevices::get__NewEnum

This topic applies to Windows XP only.

The get__NewEnum method retrieves an enumerator for the collection.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppD
);

Parameters

ppD

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method is provided so that Automation clients can iterate through the collection using a For...Each loop.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread. (C++ applications should generally use the IMSVidVideoRendererDevices::get_Item method instead.)

If the method succeeds, the IEnumVARIANT interface has an outstanding reference count. The caller must release the interface.

See Also

  • IMSVidVideoRendererDevices Interface


IMSVidVideoRendererDevices::Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

HRESULT Remove(
  VARIANT  v
);

Parameters

v

[in] VARIANT that specifies the index of the item to remove.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
DISP_E_BADINDEX | The index is out of range.
DISP_E_TYPEMISMATCH | Wrong VARIANT type.
E_ACCESSDENIED | The collection is read-only; cannot remove any items.
E_UNEXPECTED | Unexpected error.

Remarks

The v parameter must be a VARIANT that contains an integer type (VT_I4). The valid range is from 0 to IMSVidVideoRendererDevices::get_Count - 1.

See Also

  • IMSVidVideoRendererDevices Interface


Video Control Event Interfaces

This topic applies to Windows XP only.

The following table lists the outgoing event interfaces that an application must implement in order to receive events from various objects associated with the Video Control.

Interface | Description
_IMSVidCtlEvents | Implement this interface to receive events from the Video Control.
IMSVidAnalogTunerEvent | Implement this interface to receive events from an analog tuner device.
IMSVidAudioRendererEvent | Implement this interface to receive events from an audio renderer.
IMSVidDeviceEvent | Base interface for device events.
IMSVidFilePlaybackEvent | Implement this interface to receive events from the file playback object.
IMSVidInputDeviceEvent | Base interface for input device events.
IMSVidOutputDeviceEvent | Base interface for output device events.
IMSVidPlaybackEvent | Implement this interface to receive events from a playback device.
IMSVidStreamBufferSinkEvent | Implement this interface to receive events from the MSVidStreamBufferSink object.
IMSVidStreamBufferSourceEvent | Implement this interface to receive events from the MSVidStreamBufferSource object.
IMSVidTunerEvent | Implement this interface to receive events from a tuner device.
IMSVidVideoRendererEvent | Implement this interface to receive events from a video renderer.

See Also

  • Receiving Video Control Events in C++
  • Receiving Video Control Events in ATL


_IMSVidCtlEvents Interface

This topic applies to Windows XP only.

The _IMSVidCtlEvents interface is used to receive events from the Video Control.

This interface is an outgoing connection-point interface. To receive events from the Video Control, implement this interface in your application. Then call the IConnectionPoint::Advise method on the Video Control to establish a connection.

_IMSVidCtlEvents is a dispinterface, invoked through IDispatch. The dispatch identifier is DIID__IMSVidCtlEvents. The interface supports supports the following methods.

Method | Description
Click | Called when a user clicks anywhere on the Video Control's rectangle.
DblClick | Called when a user double-clicks on the Video Control's rectangle.
Error | Called when an error occurs in the control or the underlying filter graph. Currently no errors are defined for this event.
KeyDown | Called when the user presses a key.
KeyPress | Called when the user presses and releases a key.
KeyUp | Called when the user releases a key.
MouseDown | Called when the user presses the left mouse key down while the mouse pointer is over the Video Control.
MouseMove | Called when the user moves the mouse pointer over the Video Control.
MouseUp | Called when the user releases the left mouse button while the mouse pointer is over the Video Control.
StateChange | Called when the state of the Video Control changes.


_IMSVidCtlEvents::Click

This topic applies to Windows XP only.

The Click method is called when a user clicks anywhere on the Video Control's rectangle.

Syntax

void Click();

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

The dispatch identifier (dispid) of this method is DISPID_CLICK.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::DblClick

This topic applies to Windows XP only.

The DblClick method is called when a user double-clicks on the Video Control's rectangle.

Syntax

void DblClick();

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

The dispatch identifier (dispid) of this method is DISPID_DBLCLICK.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::Error

This topic applies to Windows XP only.

The Error method is called when an error occurs in the control or the underlying filter graph. Currently no errors are defined for this event.

Syntax

void Error(
  short  Number,
  BSTR*  pDescription,
  long  Scode,
  BSTR  Source,
  BSTR  HelpFile,
  long  HelpContext,
  boolean*  pCancelDisplay
);

Parameters

Number

Specifies the error number.

pDescription

Contains a "friendly" description of the error.

Scode

Specifies the S code for this error.

Source

Specifies the source of the error.

HelpFile

Specifies the Help file associated with the error.

HelpContext

Specifies Help context associated with the error.

pCancelDisplay

Specifies whether the display should be cancelled.

Return Values

This method does not return a value.

Remarks

The dispatch identifier (dispid) of this method is DISPID_ERROREVENT.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::KeyDown

This topic applies to Windows XP only.

The KeyDown method is called when the user presses a key.

Syntax

void KeyDown(
  short*  pKeyCode,
  short  Shift
);

Parameters

pKeyCode

Specifies the key code.

Shift

Specifies the shift state. See Remarks.

Return Values

This method does not return a value.

Remarks

The Shift, Ctrl and ALT keys have the following values:

Value | Meaning
1 | The Shift key was pressed.
2 | The Ctrl key was pressed.
4 | The ALT key was pressed.

The value of the Shift parameter may also be any bitwise OR combination of these values.

The dispatch identifier (dispid) of this method is DISPID_KEYDOWN.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::KeyPress

This topic applies to Windows XP only.

The KeyPress method is called when the user presses and releases a key.

Syntax

void KeyPress(
  short*  pKeyAscii
);

Parameters

pKeyAscii

Specifies the ASCII value of the key.

Return Values

This method does not return a value.

Remarks

The dispatch identifier (dispid) of this method is DISPID_KEYPRESS.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::KeyUp

This topic applies to Windows XP only.

The KeyUp method is called when the user releases a key.

Syntax

void KeyUp(
  short*  pKeyCode,
  short  Shift
);

Parameters

pKeyCode

Specifies the key code.

Shift

Specifies the shift state. See Remarks.

Return Values

This method does not return a value.

Remarks

The Shift, Ctrl and ALT keys have the following values:

Value | Meaning
1 | The Shift key was pressed.
2 | The Ctrl key was pressed.
4 | The ALT key was pressed.

The value of the Shift parameter may also be any bitwise OR combination of these values.

The dispatch identifier (dispid) of this method is DISPID_KEYUP.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::MouseDown

This topic applies to Windows XP only.

The MouseDown method is called when the user presses a mouse key down while the mouse pointer is over the Video Control.

Syntax

void MouseDown(
  short  Button,
  short  Shift,
  OLE_XPOS_PIXELS  x,
  OLE_YPOS_PIXELS  y
);

Parameters

Button

Specifies the mouse button. See Remarks.

Shift

Specifies the shift state. For possible values, see _IMSVidCtlEvents::KeyUp.

x

Specifies the x position.

y

Specifies the y position.

Return Values

This method does not return a value.

Remarks

The Button parameter may have one of the following values:

Value | Meaning
0x1 | The left button is pressed.
0x2 | The right button is pressed.
0x4 | The middle button is pressed.
0x8 | The X button 1 was pressed.
0x10 | The X button 2 was pressed.

The dispatch identifier (dispid) of this method is DISPID_MOUSEDOWN.

See Also

  • _IMSVidCtlEvents Interface
  • _IMSVidCtlEvents::MouseMove


_IMSVidCtlEvents::MouseMove

This topic applies to Windows XP only.

The MouseMove method is called when the user moves the mouse pointer over the Video Control.

Syntax

void MouseMove(
  short  Button,
  short  Shift,
  OLE_XPOS_PIXELS  x,
  OLE_YPOS_PIXELS  y
);

Parameters

Button

Specifies the mouse button. See Remarks.

Shift

Specifies the shift state. For possible values, see the Remarks for the KeyUp event.

x

Specifies the x position.

y

Specifies the y position.

Return Values

This method does not return a value.

Remarks

The Button parameter may have one of the following values:

Value | Meaning
0x1 | The left button is pressed.
0x2 | The right button is pressed.
0x4 | The middle button is pressed.

The dispatch identifier (dispid) of this method is DISPID_MOUSEMOVE.

See Also

  • _IMSVidCtlEvents Interface
  • _IMSVidCtlEvents::MouseDown


_IMSVidCtlEvents::MouseUp

This topic applies to Windows XP only.

The MouseUp method is called when the user releases the left mouse button while the mouse pointer is over the Video Control.

Syntax

void MouseUp(
  short  Button,
  short  Shift,
  OLE_XPOS_PIXELS  x,
  OLE_YPOS_PIXELS  y
);

Parameters

Button

Specifies the mouse button. See Remarks.

Shift

Specifies the shift state. For possible values, see the Remarks for the KeyUp event.

x

Specifies the x position.

y

Specifies the y position.

Return Values

This method does not return a value.

Remarks

The Button parameter may have one of the following values:

Value | Meaning
0x1 | The left button is pressed.
0x2 | The right button is pressed.
0x4 | The middle button is pressed.

The dispatch identifier (dispid) of this method is DISPID_MOUSEUP.

See Also

  • _IMSVidCtlEvents Interface


_IMSVidCtlEvents::StateChange

This topic applies to Windows XP only.

The StateChange method is called by when the state of the Video Control changes.

Syntax

void StateChange(
  MSVidCtlStateList  PrevState,
  MSVidCtlStateList  CurrState
);

Parameters

PrevState

Specifies the previous state, as a member of the MSVidCtlStateList enumeration.

CurrState

Specifies the current state, as as a member of the MSVidCtlStateList enumeration.

Return Values

This method does not return a value.

Remarks

The state of the Video Control does not necessarily correspond to the state of all the devices in the filter graph.

The dispatch identifier (dispid) of this method is dispidStateChange.

See Also

  • _IMSVidCtlEvents Interface


IMSVidAnalogTunerEvent Interface

This topic applies to Windows XP only.

The IMSVidAnalogTunerEvent interface is used to receive events from non-BDA analong tuners.

This interface is an outgoing connection-point interface. To receive events related to analong tuning, implement this interface in your application. Then call the IConnectionPoint::Advise method on the MSVidAnalogTunerDevice object to establish a connection.

IMSVidAnalogTunerEvent inherits the IMSVidTunerEvent interface, but adds no other methods to it.


IMSVidAudioRendererEvent Interface

This topic applies to Windows XP only.

The IMSVidAudioRendererEvent interface is used to receive events from the audio renderer.

This interface is an outgoing connection-point interface. To receive events related to audio rendering, implement this interface in your application. Then call the IConnectionPoint::Advise method on the MSVidAudioRenderer object to establish a connection.

IMSVidAudioRendererEvent inherits the IMSVidOutputDeviceEvent interface, but adds no other methods to it.


IMSVidDeviceEvent Interface

This topic applies to Windows XP only.

The IMSVidDeviceEvent interface is the base interface for device events. Do not implement this interface directly. Other event interfaces derive from this interface.

In addition to the methods inherited from IDispatch, the IMSVidDeviceEvent interface exposes the following method.

Method | Description
StateChange | Signals that the state of the device has changed.


IMSVidDeviceEvent::StateChange

This topic applies to Windows XP only.

The StateChange method signals that the state of the device has changed.

Syntax

HRESULT StateChange(
  IMSVidDevice*  plpd,
  long  oldState,
  long  newState
);

Parameters

plpd

[in] Pointer to the device object that signalled the change.

oldState

[in] Specifies the old state as an MSVidCtlStateList value.

newState

[in] Specifies the new state as an MSVidCtlStateList value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The dispatch identifier (dispid) of this method is eventidStateChange.

See Also

  • IMSVidDeviceEvent Interface


IMSVidFilePlaybackEvent Interface

This topic applies to Windows XP only.

The IMSVidFilePlaybackEvent interface is used to receive events from the file playback object.

This interface is an outgoing connection-point interface. To receive events related to file playback, implement this interface in your application. Then call the IConnectionPoint::Advise method on the MSVidFilePlaybackDevice object to establish a connection.

IMSVidFilePlaybackEvent inherits the IMSVidPlaybackEvent interface, but adds no other methods to it.


IMSVidInputDeviceEvent Interface

This topic applies to Windows XP only.

The IMSVidInputDeviceEvent interface is the base interface for input device events. Do not implement this interface directly. Other event interfaces derive from this interface.

IMSVidInputDeviceEvent inherits the IDispatch interface.


IMSVidOutputDeviceEvent Interface

This topic applies to Windows XP only.

The IMSVidOutputDeviceEvent interface is the base interface for output device events. It inherits the IMSVidDeviceEvent interface, but adds no other methods to it.


IMSVidPlaybackEvent Interface

This topic applies to Windows XP only.

The IMSVidPlaybackEvent interface is used to receive events from playback devices, such as the file playback object and the stream buffer source object.

This interface is an outgoing connection-point interface. To receive events from a playback device, implement this interface and then call the IConnectionPoint::Advise method to establish a connection.

In addition to the methods inherited from IMSVidInputDeviceEvent, the IMSVidPlaybackEvent interface exposes the following method.

Method | Description
EndOfMedia | Called when playback has reached the end of the source media.

See Also

  • IMSVidFilePlaybackEvent Interface


IMSVidPlaybackEvent::EndOfMedia

This topic applies to Windows XP only.

The EndOfMedia method is called when playback reaches the end of the source media.

Syntax

HRESULT EndOfMedia(
  IMSVidPlayback*  lpd
);

Parameters

lpd

[in] Specifies a pointer to the IMSVidPlayback interface of the playback device.

Return Values

Return S_OK or an error code.

Remarks

The dispatch identifier (dispid) of this method is eventidEndOfMedia.

See Also

  • IMSVidPlaybackEvent Interface


IMSVidStreamBufferSinkEvent Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidStreamBufferSinkEvent interface is used to receive events from the MSVidStreamBufferSink object.

This interface is an outgoing connection-point interface. To receive events from a playback device, implement this interface and then call the IConnectionPoint::Advise method to establish a connection.

In addition to the methods inherited from IMSVidOutputDeviceEvent, the IMSVidStreamBufferSinkEvent interface exposes the following methods.

Method | Description
CertificateFailure | The object failed to get an encryption/decription license.
CertificateSuccess | The object succeeded in getting an encryption/decription license.


IMSVidStreamBufferSinkEvent::CertificateFailure

This topic applies to Windows XP Service Pack 1 only.

The CertificateFailure method is called when the object fails to get an encryption/decription license.

Syntax

HRESULT CertificateFailure(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

See Also

  • IMSVidStreamBufferSinkEvent Interface


IMSVidStreamBufferSinkEvent::CertificateSuccess

This topic applies to Windows XP Service Pack 1 only.

The CertificateSuccess method is called when the object succeeds in getting an encryption/decription license. The method is called only if an earlier failure occurred.

Syntax

HRESULT CertificateSuccess(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

See Also

  • IMSVidStreamBufferSinkEvent Interface


IMSVidStreamBufferSourceEvent Interface

This topic applies to Windows XP Service Pack 1 only.

The IMSVidStreamBufferSourceEvent interface is used to receive events from the MSVidStreamBufferSource object.

This interface is an outgoing connection-point interface. To receive events from a playback device, implement this interface and then call the IConnectionPoint::Advise method to establish a connection.

In addition to the methods inherited from IMSVidFilePlaybackEvent, the IMSVidStreamBufferSourceEvent interface exposes the following methods.

Method | Description
CertificateFailure | The object failed to get an encryption/decription license.
CertificateSuccess | The object succeeded in getting an encryption/decription license.
ContentBecomingStale | Called when the stream buffer source lags behind the stream buffer sink.
RatingsBlocked | The object has blocked the stream, because the rating is not allowed under the current permissions.
RatingsChanged | The current rating has changed.
RatingsUnblocked | The object has unblocked the stream.
StaleDataRead | Called when the MSVidStreamBufferSource object reads from a temporary recording file that has been marked for deletion.
StaleFileDeleted | Called when a temporary recording file is deleted.
TimeHole | Called when playback reaches a gap in the recorded content.


IMSVidStreamBufferSourceEvent::CertificateFailure

This topic applies to Windows XP Service Pack 1 only.

The CertificateFailure method is called when the object fails to get an encryption/decription license.

Syntax

HRESULT CertificateFailure(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the EVENTID_ETDTFilterLicenseFailure event in the TV Ratings system. See TV Ratings Broadcast Events.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::CertificateSuccess

This topic applies to Windows XP Service Pack 1 only.

The CertificateSuccess method is called when the object succeeds in getting an encryption/decription license. The method is called only if an earlier failure occurred.

Syntax

HRESULT CertificateSuccess(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the EVENTID_ETDTFilterLicenseOK event in the TV Ratings system. See TV Ratings Broadcast Events.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::ContentBecomingStale

This topic applies to Windows XP Service Pack 1 only.

The CertificateSuccess method is called when the stream buffer source lags behind the stream buffer sink by more than a preset number of files.

Syntax

HRESULT ContentBecomingStale(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the STREAMBUFFER_EC_CONTENT_BECOMING_STALE event in the Stream Buffer Engine. See Stream Buffer Engine Event Codes.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::RatingsBlocked

This topic applies to Windows XP Service Pack 1 only.

The RatingsBlocked method is called when the object blocks the stream, which occurs if the rating is not allowed under the current permissions.

Syntax

HRESULT RatingsBlocked(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the EVENTID_DTFilterRatingsBlock event in the TV Ratings system. See TV Ratings Broadcast Events.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::RatingsChanged

This topic applies to Windows XP Service Pack 1 only.

The RatingsChanged method is called when the rating changes.

Syntax

HRESULT RatingsChanged(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the EVENTID_DTFilterRatingChange event in the TV Ratings system. See TV Ratings Broadcast Events.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::RatingsUnblocked

This topic applies to Windows XP Service Pack 1 only.

The RatingsUnblocked method is called when the object unblocks the stream. This event occurs only if the stream was previously blocked and is then unblocked.

Syntax

HRESULT RatingsUnblocked(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the EVENTID_DTFilterRatingsUnblock event in the TV Ratings system. See TV Ratings Broadcast Events.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::StaleDataRead

This topic applies to Windows XP Service Pack 1 only.

The TimeHole method is called when the MSVidStreamBufferSource object reads from a temporary recording file that has been marked for deletion.

Syntax

HRESULT StaleDataRead(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the STREAMBUFFER_EC_STALE_DATA_READ event in the Stream Buffer Engine. See Stream Buffer Engine Event Codes.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::StaleFileDeleted

This topic applies to Windows XP Service Pack 1 only.

The StaleFileDeleted method is called when a temporary recording file is deleted.

Syntax

HRESULT StaleFileDeleted(void);

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the STREAMBUFFER_EC_STALE_FILE_DELETED event in the Stream Buffer Engine. See Stream Buffer Engine Event Codes.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidStreamBufferSourceEvent::TimeHole

This topic applies to Windows XP Service Pack 1 only.

The TimeHole method is called when playback reaches a gap in the recorded content.

Syntax

HRESULT TimeHole(
    long StreamOffsetMS,
    long SizeMS
);

Parameters

StreamOffsetMS

[in] Specifies the start of the gap, in milliseconds, relative to the content start.

SizeMS

[in] Specifies the length of the gap, in milliseconds.

Return Values

Return S_OK or an error code.

Remarks

This event corresponds to the STREAMBUFFER_EC_TIMEHOLE event in the Stream Buffer Engine. See Stream Buffer Engine Event Codes.

See Also

  • IMSVidStreamBufferSourceEvent Interface


IMSVidTunerEvent Interface

This topic applies to Windows XP only.

The IMSVidTunerEvent interface is used to receive events from BDA-compliant digital TV tuners.

This interface is an outgoing connection-point interface. To receive events from a BDA digital tuner, implement this interface in your application. Then call the IConnectionPoint::Advise method on the MSVidBDATunerDevice object to establish a connection.

In addition to the methods inherited from IMSVidInputDeviceEvent, the IMSVidTunerEvent interface exposes the following method.

Method | Description
TuneChanged | Signals that the tuner has tuned to a new frequency.


IMSVidTunerEvent::TuneChanged

This topic applies to Windows XP only.

The TuneChanged method signals that the tuner has tuned to a new frequency.

Syntax

HRESULT TuneChanged(
  IMSVidTuner*  plpd
);

Parameters

plpd

[in] Pointer to the MSVidTuner object that fired the event.

Return Values

Return S_OK or an error code.

Remarks

The dispatch identifier (dispid) of this method is eventidOnTuneChanged.

See Also

  • IMSVidTunerEvent Interface


IMSVidVideoRendererEvent Interface

This topic applies to Windows XP only.

The IMSVidVideoRendererEvent interface is used to receive events from the video renderer.

This interface is an outgoing connection-point interface. To receive events from a playback device, implement this interface in your application. Then call the IConnectionPoint::Advise method on the MSVidVideoRenderer object to establish a connection.

In addition to the methods inherited from IMSVidDeviceEvent, the IMSVidVideoRendererEvent interface exposes the following method.

Method | Description
OverlayUnavailable | Signals that the overlay surface on the graphics card is not available.


IMSVidVideoRendererEvent::OverlayUnavailable

This topic applies to Windows XP only.

The OverlayUnavailable method signals that the overlay surface on the graphics card is not available.

Syntax

HRESULT OverlayUnavailable();

Parameters

This method takes no parameters.

Return Values

Return S_OK or an error code.

Remarks

The dispatch identifier (dispid) of this method is eventidOverlayUnavailable.

See Also

  • IMSVidVideoRendererEvent Interface


Video Control Enumerations

This topic applies to Windows XP only.

The following table lists all the enumerations used by the Video Control interface methods.

Enumeration | Description
DisplaySizeList | Defines the sizes at which the video rectangle may be rendered.
DVDSPExt | Indicates the default DVD subpicture language extension.
DVDTextStringType | Indicates the type of information contained in a DVD text string.
DVDMenuIDConstants | Describes menu types.
MSVidCtlStateList | Defines the possible states of the video control and the underlying filter graph.
SourceSizeList | Defines the ways in which the source video rectangle may be clipped.
MSVidCCService | Indicates closed captioning services.


DisplaySizeList Enumeration

This topic applies to Windows XP only.

The DisplaySizeList enumeration defines the possible sizes at which the video rectangle may be rendered.

Syntax

typedef enum DisplaySizeList{
    dslDefaultSize,
    dslSourceSize = 0,
    dslHalfSourceSize,
    dslDoubleSourceSize,
    dslFullScreen,
    dslHalfScreen,
    dslQuarterScreen,
    dslSixteenthScreen
};

Elements

dslDefaultSize

Display the video rectangle at the native size.

dslSourceSize

Same as dslDefaultSize.

dslHalfSourceSize

Display the video rectangle by shrinking the width and height by half.

dslDoubleSourceSize

Display the video rectangle by stretching the width and height to twice their native size.

dslFullScreen

Display the video rectangle by stretching the width and height to fill the entire screen as much as possible while maintaining the original aspect ratio.

dslHalfScreen

Display the video rectangle by stretching the width and height as much as possible to fill half (50%) of the screen while maintaining the original aspect ratio.

dslQuarterScreen

Display the video rectangle by stretching the width and height as much as possible to fill one quarter (25%) of the screen while maintaining the original aspect ratio.

dslSixteenthScreen

Display the video rectangle by stretching the width and height as much as possible to fill one sixteenth (6.25%) of the screen while maintaining the original aspect ratio.

See Also

  • IMSVidCtl::get_DisplaySize
  • IMSVidCtl::put_DisplaySize


DVDSPExt

The DVDSPExt enumeration type holds a value indicating the default DVD subpicture language extension.

Syntax

typedef enum DVDSPExt{
  dvdSPExt_NotSpecified  = 0,
  dvdSPExt_Caption_Normal  = 1,
  dvdSPExt_Caption_Big  = 2,
  dvdSPExt_Caption_Children  = 3,
  dvdSPExt_CC_Normal  = 5,
  dvdSPExt_CC_Big  = 6,
  dvdSPExt_CC_Children  = 7,
  dvdSPExt_Forced  = 9,
  dvdSPExt_DirectorComments_Normal  = 13,
  dvdSPExt_DirectorComments_Big  = 14,
  dvdSPExt_DirectorComments_Children  = 15
};

Members

dvdSPExt_NotSpecified

Extension not specified.

dvdSPExt_Caption_Normal

Normal caption size.

dvdSPExt_Caption_Big

Big captions.

dvdSPExt_Caption_Children

Children's captions.

dvdSPExt_CC_Normal

Normal-sized closed captions.

dvdSPExt_CC_Big

Big closed captions.

dvdSPExt_CC_Children

Children's closed captions.

dvdSPExt_Forced

Forced.

dvdSPExt_DirectorComments_Normal

Normal-sized director's comments.

dvdSPExt_DirectorComments_Big

Big director's comments.

dvdSPExt_DirectorComments_Children

Director's comments for children.

Remarks

For more information on when and how to retrieve this property, see the following links.

See Also

  • DefaultSubpictureLanguageExt
  • SelectDefaultSubpictureLanguage
  • Video Control Enumerations


DVDTextStringType

The DVDTextStringType enumeration type indicates the type of information contained in a DVD text string.

Syntax

typedef enum DVDTextStringType{
  // Disc structure identifiers (0x00..0x0f)
  // These are empty strings whose string type
  // is used to organize the content strings.
  dvdStruct_Volume  = 0x1,
  dvdStruct_Title  = 0x2,
  dvdStruct_ParentalID  = 0x3,
  dvdStruct_PartOfTitle  = 0x4,
  dvdStruct_Cell  = 0x5,
  dvdStream_Audio  = 0x10,
  dvdStream_Subpicture  = 0x11,
  dvdStream_Angle  = 0x12,
  // Channel in stream (0x20..0x2f)
  dvdChannel_Audio  = 0x20,
  // Application information
  // General (0x30..0x37)
  // This is used to identify the name
  // for the current node, that is, volume title,
  // movie title, song title, and so on.
  dvdGeneral_Name  = 0x30,
  dvdGeneral_Comments  = 0x31,

  // Title (0x38..0x3f)
  dvdTitle_Series  = 0x38,
  dvdTitle_Movie  = 0x39,
  dvdTitle_Video  = 0x3a,
  dvdTitle_Album  = 0x3b,
  dvdTitle_Song  = 0x3c,
  dvdTitle_Other  = 0x3f,

  // Title (sub) (0x40..0x47)
  dvdTitle_Sub_Series  = 0x40,
  dvdTitle_Sub_Movie  = 0x41,
  dvdTitle_Sub_Video  = 0x42,
  dvdTitle_Sub_Album  = 0x43,
  dvdTitle_Sub_Song  = 0x44,
  dvdTitle_Sub_Other  = 0x47,

  // Title (original) (0x48..0x4f)
  dvdTitle_Orig_Series  = 0x48,
  dvdTitle_Orig_Movie  = 0x49,
  dvdTitle_Orig_Video  = 0x4a,
  dvdTitle_Orig_Album  = 0x4b,
  dvdTitle_Orig_Song  = 0x4c,
  dvdTitle_Orig_Other  = 0x4f,

  // Other info (0x50..0x57)
  dvdOther_Scene  = 0x50,
  dvdOther_Cut  = 0x51,
  dvdOther_Take  = 0x52
};

Elements

dvdStruct_Volume

Indicates the top-level of the logical hierarchy. Refers to the entire contents of a one-sided disc or one side of a two-sided disc.

dvd_Struct_Title

Indicates that all content strings, until the next dvd_Struct_Title, belong to one title.

dvd_Struct_ParentalID

Indicates the parental ID of the following strings.

dvd_Struct_PartOfTitle

Indicates that all content strings, until the next dvd_Struct_PartOfTitle, belong to one chapter.

dvd_Struct_Cell

Indicates that all content strings, until the next dvd_Struct_Cell, belong to one cell, which can be a scene from a chapter.

dvd_Stream_Audio

Indicates that the following content strings refer to the audio stream.

dvd_Stream_Subpicture

Indicates that the following content strings refer to the subpicture stream.

dvd_Stream_Angle

Indicates that the following content strings refer to the angle.

dvd_Channel_Audio

Indicates that the following content strings refer to the audio channel.

dvd_General_Name

Indicates the most important content string. Strings of this type contain the name of the volume, title, chapter, and so on, and can follow any structure identifiers.

dvd_General_Comments

Identifies a content string with additional information about the title, chapter, and so on, described by the dvd_General_Name string. The exact nature or structure of these comments is not defined.

dvd_Title_Series

Identifies a content string containing the name of a series to which the title belongs.

dvd_Title_Movie

Identifies a content string with the main movie title.

dvd_Title_Video

Identifies a content string containing the name of the video title.

dvd_Title_Album

Identifies a content string containing the name of the album title.

dvd_Title_Song

Identifies a content string containing the name of the song title.

dvd_Title_Other

Identifies a content string containing the name of the title of some other genre.

dvd_Title_Sub_Series

Identifies a content string with the name of the series localized to a particular country/region.

dvd_Title_Sub_Movie

Identifies a content string with the movie title localized to a particular country/region.

dvd_Title_Sub_Video

Identifies a content string with the video title localized to a particular country/region.

dvd_Title_Sub_Album

Identifies a content string with the album title localized to a particular country/region.

dvd_Title_Sub_Song

Identifies a content string with the song title localized to a particular country/region.

dvd_Title_Sub_Other

Identifies a content string with the title of some other genre localized to a particular country/region.

dvd_Title_Orig_Series

Identifies a content string with the original name of the series.

dvd_Title_Orig_Movie

Identifies a content string with the original name of the movie.

dvd_Title_Orig_Video

Identifies a content string with the original name of the video.

dvd_Title_Orig_Album

Identifies a content string with the original name of the album.

dvd_Title_Orig_Song

Identifies a content string with the original name of the song.

dvd_Title_Orig_Other

Identifies a content string with the original name of the content.

dvd_Other_Scene

Identifies a content string pertaining to a particular scene in a movie or video.

dvd_Other_Cut

Identifies a content string pertaining to a particular cut in a movie or video.

dvd_Other_Take

Identifies a content string pertaining to a particular take in a movie or video.

Remarks

A DVD_TextStringType is returned in the DVDTextStringType method to identify how the disc authors have categorized the specified text string. See Working with DVD Text Strings for general information on text strings.

One important text string type not defined in this enumeration is 0xF0, the extension sorting text string type. You can use this type of string in many ways to enable players to sort the string data. It can be a unique number or a repetition of a previous string with the word order changed. For example, a string type of 0x30 that has the name "The Greatest Hits" might be followed by a string of type 0xF0 that says "Greatest Hits, The." As with content strings, the use of the sorting string is not strictly defined.

See Also

  • DVDTextStringType
  • Video Control Enumerations
  • Working with DVD Text Strings


DVDMenuIDConstants Enumeration

The DVDMenuIDConstants enumeration type defines menu type ID numbers used to display specific menus.

Syntax

typedef enum DVDMenuIDConstants {
    dvdMenu_Title       = 2,
    dvdMenu_Root        = dvdMenu_Title + 1,
    dvdMenu_Subpicture  = dvdMenu_Root + 1,
    dvdMenu_Audio       = dvdMenu_Subpicture + 1,
    dvdMenu_Angle       = dvdMenu_Audio + 1,
    dvdMenu_Chapter     = dvdMenu_Angle + 1
};

Members

dvdMenu_Title

Title menu, also called the Video Manager Menu.

dvdMenu_Root

Root menu, the menu for one video title set, which can contain one title or a group of titles.

dvdMenu_Subpicture

Subpicture menu.

dvdMenu_Audio

Audio menu.

dvdMenu_Angle

Angle menu.

dvdMenu_Chapter

Chapter menu.

Remarks

All the titles in a title set share the same Subpicture, Audio, Angle, and Chapter menus.

See Also

  • ShowMenu
  • Video Control Enumerations


MSVidCCService Enumeration

This topic applies to Windows XP Service Pack 1 only.

The MSVidCCService enumeration indicates closed captioning services.

Syntax

typedef enum {
    None,
    Caption1,
    Caption2,
    Text1,
    Text2,
    XDS
} MSVidCCService;

Members

None

No current service

Caption1

CC1 (caption channel)

Caption2

CC2 (caption channel)

Text1

T1 (text channel)

Text2

T2 (text channel)

XDS

Extended data services (XDS or EDS)

See Also

  • Video Control Enumerations


MSVidCtlStateList Enumeration

This topic applies to Windows XP only.

The MSVidCtlStateList enumeration defines the possible state values of the Video Control or the underlying filter graph.

Syntax

typedef enum MSVidCtlStateList{
    STATE_UNBUILT = -1,
    STATE_STOP,
    STATE_PAUSE,
    STATE_PLAY
};

Elements

STATE_UNBUILT

Indicates that there is no filter graph.

STATE_STOP

Indicates that the Video Control is stopped.

STATE_PAUSE

Indicates that the Video Control is paused.

STATE_PLAY

Indicates that the Video Control is playing.

See Also

  • _IMSVidCtlEvents::StateChange
  • IMSVidDeviceEvent::StateChange
  • Video Control Enumerations


SourceSizeList Enumeration

This topic applies to Windows XP only.

The SourceSizeList enumeration is used to indicate how the VMR will clip the source video rectangle.

Syntax

typedef enum SourceSizeList{
    sslFullSize,
    sslClipByOverScan,
    sslClipByClipRect
};

Elements

sslFullSize

Do not clip the source video rectangle.

sslClipByOverScan

Clip the source video rectangle by the value specified in the last call to IMSVidVideoRenderer::put_OverScan.

sslClipByClipRect

Clip the source video rectangle by the value specified in the last call to IMSVidVideoRenderer::put_ClippedSourceRect

See Also

  • IMSVidVideoRenderer::get_SourceSize
  • IMSVidVideoRenderer::put_SourceSize
  • Video Control Enumerations


Microsoft Unified Tuning Model C++ Reference

This section contains the reference documentation for the Microsoft® Unified Tuning Model application programming interfaces (APIs). The objects and interfaces documented here provide the tuning abstraction layer that enables applications to remain network-independent.

The process of obtaining, storing and submitting tuning information using the Tuning Model objects differs depending on whether the platform is Microsoft Windows® XP, or an earlier version of Windows.

For more information on using the APIs documented in the following sections, see The Microsoft Unified Tuning Model.

  • Microsoft Unified Tuning Model Objects
  • Microsoft Unified Tuning Model Interfaces
  • Microsoft Unified Tuning Model Enumerations


Microsoft Unified Tuning Model Objects

Tuning Space Objects

A tuning space represents a particular type of network, along with other information that identifies a particular network provider or broadcast source. Microsoft provides five default tuning spaces; third parties may add their own tuning space. Tuning spaces are stored in the system registry. Use the SystemTuningSpaces object to create new tuning spaces or access existing ones.

Object | Description
AnalogRadioTuningSpace | Represents a tuning space for analog radio networks.
AnalogTVTuningSpace | Represents a tuning space for analog TV networks.
ATSCTuningSpace | Represents a tuning space for ATSC networks.
AuxInTuningSpace | Represents a video auxiliary input, such as S-Video or composite video.
DVBSTuningSpace | Represents a tuning space for DVB-S networks.
DVBTuningSpace | Represents a tuning space for DVB networks.
SystemTuningSpaces | Represents the collection of tuning spaces installed on the host system.

Stream Component Objects

A "component" in the context of digital television refers to an elementary stream within an MPEG-2 program stream. For example, a program stream may have three audio components, one in English, one in Spanish, and one in French. The actual components being provided by a service in some cases can only be discovered after reception begins. The Transport Information Filter (TIF) works with the Network Provider to fill in the component data in the tune request after tuning has occurred. The application can then examine the tune request, for example to inform the user of additional audio streams that are available.

Object | Description
ATSCComponentType | Represents an ATSC component type.
Component | Represents a generic program component.
Components | Represents a collection of components.
ComponentType | Represents a generic component type.
ComponentTypes | Represents a collection of component types.
LanguageComponentType | Represents a component type that has a defined language code.
MPEG2Component | Represents an MPEG-2 stream component.
MPEG2ComponentType | Represents a component type associated with an MPEG-2 stream component.

Locator Objects

Locator objects contain low-level information that a tuner and Network Provider use to locate a program within a tuning space. This information includes the frequency and modulation type of the television signal, Quadrature Phase Shift Keying (QPSK) symbol rate, the type of forward error correction used, and other parameters specific to the network type. Each tune request contains a locator object, although it is not always necessary that all properties of the locator be set. A third party such as a cable or satellite provider may provide a default locator for their tuning space, which a Guide Store loader can use when creating tune requests. Locators are typically not used by applications, except perhaps for debugging purposes, or in the case where an application creates its own tune request.

Object | Description
ATSCLocator | Contains tuning information specific to ATSC networks.
DVBCLocator | Contains tuning information specific to DVB-C networks.
DVBSLocator | Contains tuning information specific to DVB-S networks.
DVBTLocator | Contains tuning information specific to DVB-T networks.
Locator | Base class for the other locators. Contains tuning information required for all network types.


AnalogRadioTuningSpace Object

Not supported in this release.

The AnalogRadioTuningSpace object represents a tuning space for analog radio.

Interfaces | IAnalogRadioTuningSpace
Outgoing Event Interfaces | None.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


AnalogTVTuningSpace Object

The AnalogTVTuningSpace object represents a tuning space for analog television.

Interfaces | IAnalogTVTuningSpace
Outgoing Event Interfaces | None.
CLSID | CLSID_AnalogTVTuningSpace

Remarks

The Microsoft Unified Tuning Model supports analog tuning spaces, but there are no analog TV devices based on the Broadcast Driver Architecture (BDA). When the Video Control receives an analog TV tune request, it gets the channel number and creates a WDM analog TV filter graph.

Applications should get this object from the SystemTuningSpaces collection; the CLSID is provided for clients that wish to create custom tuning spaces.

Tune request objects created by this tuning space support the ITuneRequest and IChannelTuneRequest interfaces.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


ATSCComponentType Object

The ATSCComponentType object represents an ATSC component type. The ATSC component type indicates whether an audio stream is in AC-3 format.

Interfaces | IATSCComponentType
Outgoing Event Interfaces | None.
CLSID | CLSID_ATSCComponentType

Remarks

The ATSCComponentType object is obtained through the IComponent::get_Type method of a component object for an ATSC tune request. It may also be used as a default preferred component type on the tuning space, or the preferred type on a tune request. In this case, it is obtained through the Components collection object.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


ATSCLocator Object

The ATSCLocator object contains tuning information for an ATSC tuning space.

Interfaces | IATSCLocator
Outgoing Event Interfaces | None.
CLSID | CLSID_ATSCLocator

Remarks

The default ATSC tuning space contains a default ATSC locator. For more information, see Default Tuning Spaces.

The most important information in this object is the physical channel, which can be obtained by calling the IATSCLocator::get_PhysicalChannel method.

See Also

  • Locators
  • Microsoft Unified Tuning Model Objects


ATSCTuningSpace Object

The ATSCTuningSpace object represents a tuning space for ATSC networks.

Interfaces | IATSCTuningSpace
Outgoing Event Interfaces | None.
CLSID | CLSID_ATSCTuningSpace

Remarks

Applications should get this object from the SystemTuningSpaces collection; the CLSID is provided for clients that wish to create custom tuning spaces.

Tune request objects created by this tuning space support following interfaces:

  • IATSCChannelTuneRequest
  • IChannelTuneRequest
  • ITuneRequest

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


AuxInTuningSpace Object

The AuxInTuningSpace object represents an auxiliary video input such as composite video or S-video.

Interfaces | IAuxInTuningSpace
Outgoing Event Interfaces | None.

Remarks

Applications should get this object from the SystemTuningSpaces collection. See Default Tuning Spaces.

Tune request objects created by this tuning space support the ITuneRequest and IChannelTuneRequest interfaces. The channel number indicates the input source:

Channel Number | Input
0 | S-video
1 | Composite video

When the Video Control receives an AuxIn tune request, it creates a WDM analog TV filter graph and uses the crossbar filter to select the input.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


Component Object

The Component object represents a generic program component.

Interfaces | IComponent
Outgoing Event Interfaces | None.
CLSID | CLSID_Component

Remarks

This object describes a component (such as audio or video) in a program. It contains a ComponentType object that has additional information about the component.

To get this object from an existing tune request, use the ITuneRequest::get_Components method to enumerate the components collection on the tune request. The CLSID is provided for guide store loaders that need to set the component information for a tune request.

For MPEG-2 streams, use the MPEG2Component object.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


Components Object

The Components object represents a collection of components.

Interfaces | IComponents
Outgoing Event Interfaces | None.
CLSID | Not applicable.

Remarks

Each tune request has a Components collection. The collection contains zero or more Component objects, each of which describes a stream in the program.

Component information may be filled in when the Guide Store Loader initially creates the tune request, or it may not be known until the program stream is being captured by the hardware and the Transport Information Filter (TIF) has examined the PSI tables. In either case, after a tune request has been submitted, the components collection is updated by the TIF. An application can examine the tune request after submitting it, to discover possible additional information about the program stream.

To get a Components object, call the ITuneRequest::get_Components method on a tune request. The Components object cannot be created with CoCreateInstance.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


ComponentType Object

The ComponentType object represents a generic component type.

Interfaces | IComponentType
Outgoing Event Interfaces | None.
CLSID | CLSID_ComponentType

Remarks

To get the component type from an existing component object, use the IComponent::get_Type method. The CLSID is provided for clients that need to set the type on a component, or set a default preferred type on a tuning space.

For MPEG-2 streams, use the MPEG2ComponentType object.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


ComponentTypes Object

The ComponentTypes object represents a collection of component types.

Interfaces | IComponentTypes
Outgoing Event Interfaces | None.
CLSID | CLSID_ComponentTypes

Remarks

Each Component object contains one ComponentType object. The ComponentTypes collection is used to create a list of default preferred component types for a tuning space, or a list of preferred component types on the tune request which override the default types.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


DVBCLocator Object

The DVBCLocator object contains tuning information for a cable DVB (DVB-C) network.

Interfaces | IDVBCLocator
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBCLocator

See Also

  • Locators
  • Microsoft Unified Tuning Model Objects


DVBSLocator Object

The DVBSLocator object is a locator for a satellite DVB (DVB-S) network.

Interfaces | IDVBSLocator
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBSLocator

See Also

  • Locators
  • Microsoft Unified Tuning Model Objects


DVBSTuningSpace Object

The DVBSTuningSpace object is a tuning space for satellite DVB (DVB-S) networks.

Interfaces | IDVBSTuningSpace
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBSTuningSpace

Remarks

Tune request objects created by this tuning space support the ITuneRequest and IDVBTuneRequest interfaces.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


DVBTLocator Object

The DVBTLocator object is used by the Network Provider to obtain information about tuning within a terrestrial DVB (DVB-T) tuning space.

Interfaces | IDVBTLocator
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBTLocator

See Also

  • Microsoft Unified Tuning Model Objects
  • Locators


DVBTuneRequest Object

The DVBTuneRequest object represents a tune request for any DVB tuning space.

Interfaces | IDVBTuneRequest
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBTuneRequest

See Also

  • Microsoft Unified Tuning Model Objects


DVBTuningSpace Object

The DVBTuningSpace object represents a tuning space for DVB-T and DVB-C network types.

Interfaces | IDVBTuningSpace, IDVBTuningSpace2
Outgoing Event Interfaces | None.
CLSID | CLSID_DVBTuningSpace

Remarks

Tune request objects created by this tuning space support the ITuneRequest and IDVBTuneRequest interfaces.

For DVB-S network types, use the DVBSTuningSpace object.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


LanguageComponentType Object

The LanguageComponentType object represents a component type that has a defined language code.

Interfaces | ILanguageComponentType
Outgoing Event Interfaces | None.
CLSID | CLSID_LanguageComponentType

Remarks

To get the component type from an existing component object, use the IComponent::get_Type method. The CLSID is provided for clients that need to set the type on a component, or set a default preferred type on a tuning space.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


Locator Object

The Locator object represents the base functionality for all network-specific locators. It is not used directly. Always use a network-specific locator.

Interfaces | ILocator
Outgoing Event Interfaces | None.

See Also

  • Locators
  • Microsoft Unified Tuning Model Objects


MPEG2Component Object

The MPEG2Component object represents a component in an MPEG-2 stream.

Interfaces | IMPEG2Component
Outgoing Event Interfaces | None.
CLSID | CLSID_MPEG2Component

Remarks

To get this object from an existing tune request, use the ITuneRequest::get_Components method to enumerate the components collection on the tune request. The CLSID is provided for guide store loaders that need to set the component information for a tune request.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


MPEG2ComponentType Object

The MPEG2ComponentType object represents a component type associated with an MPEG-2 stream component.

Interfaces | IMPEG2ComponentType
Outgoing Event Interfaces | None.
CLSID | CLSID_MPEG2ComponentType

Remarks

To get the component type from an existing component object, use the IComponent::get_Type method. The CLSID is provided for clients that need to set the type on a component, or set a default preferred type on a tuning space.

See Also

  • Components
  • Microsoft Unified Tuning Model Objects


SystemTuningSpaces Object

The SystemTuningSpaces object represents the collection of tuning spaces installed on the host system.

Interfaces | ITuningSpaceContainer
Outgoing Event Interfaces | None.
CLSID | CLSID_SystemTuningSpaces

Remarks

This object is used by installation applications or some other component to create new tuning spaces or enumerate or modify existing ones. A Guide Store Loader creates this object as the first step in the creation of tune requests. After creating the object, the loader uses the ITuningSpaceContainer interface to obtain an IEnumTuningSpaces collection of the tuning spaces installed on the host system. The loader then enumerates this collection to obtain the desired tuning space, then calls QueryInterface on that tuning space to obtain the required network-specific interface. It then uses this interface to create all tune requests for any program or service located in the tuning space.

See Also

  • Microsoft Unified Tuning Model Objects
  • Tuning Spaces


Microsoft Unified Tuning Model Interfaces

These interfaces are used primarily by guide store loaders, to create tune requests for an EPG database (guide store), and by applications that install custom tuning spaces on a system. Applications can also use these interfaces to:

  • Create or modify a tune request dynamically.
  • Test the validity of a tuning space.
  • Create a default preferred components list that indicates user preferences for options such as the audio stream language.
  • Examine the components (such as audio substreams) available on a specified service.

For more information, see The Microsoft Unified Tuning Model.

Tuning Space Interfaces

These interfaces manage tuning space objects. You will never use the base class ITuningSpace interface directly; you will always use a derived interface that is specific to a particular network type.

Interface | Description
IAnalogRadioTuningSpace | Represents a tuning space for analog radio networks. (Not implemented in this release.)
IAnalogTVTuningSpace | Represents a tuning space for analog TV networks.
IATSCTuningSpace | Represents a tuning space for ATSC networks.
IAuxInTuningSpace | Represents a tuning space for S-video or composite video inputs.
ICreatePropBagOnRegKey | Creates a property bag for saving a default tune request to the system registry.
IDVBSTuningSpace | Represents a tuning space for satellite DVB (DVB-S) networks.
IDVBTuningSpace | Represents a tuning space for DVB networks.
IDVBTuningSpace2 | Represents a tuning space for DVB networks; extends the IDVBTuningSpace interface.
IEnumTuningSpaces | Standard COM enumeration interface for tuning spaces.
IMPEG2TuneRequestFactory | Creates a minimal MPEG-2 tune request for a specified tuning space.
ITuningSpace | Base interface for all tuning spaces.
ITuningSpaceContainer | Provides access to all of the tuning spaces installed on the host system.
ITuningSpaces | Represents a collection of tuning spaces.

Tune Request Interfaces

Tune requests are not created directly. They are obtained through a call to CreateTuneRequest on a network-specific tuning space interface, such as IDVBTuningSpace.

Interface | Description
IATSCChannelTuneRequest | Provides tuning information specific to ATSC TV networks.
IChannelTuneRequest | Provides tuning information specific to analog TV networks.
IDVBTuneRequest | Provides tuning information specific to DVB TV networks.
IMPEG2TuneRequest | Represents a minimal MPEG-2 tune request.
ITuneRequest | Provides tuning information relevant for all network types.

Stream Component Interfaces

A "component" in this context refers to a substream within a broadcast. Applications create a default preferred components collection based on user input, in order to specify, for example, a preferred audio stream language. When an audio stream is specified in this way, the Network Provider will always attempt to use it for all tune request in the tuning space (See ITuningSpace::put_DefaultPreferredComponentTypes.) In some cases the actual components of a broadcast stream can only be discovered after reception begins, or the actual components may differ from what was advertised in the EPG information. At that time the BDA Network Provider will fill in the Component information in the tune request, and the application can then retrieve it and use it, for example, to change the audio stream or determine which audio streams are currently available.

Interface | Description
IATSCComponentType | Provides a method that indicates whether the audio substream is in AC-3 format.
IComponent | Base class for all derived component interfaces.
IComponents | Provides a standard COM enumeration of components.
IComponentType | Base class for all derived component type interfaces.
IComponentTypes | Provides a standard COM enumeration of component types.
IEnumComponents | Implemented on a standard COM collection object containing all the active or inactive components on the current broadcast stream.
ILanguageComponentType | Provides methods that describe the language of the substream.
IMPEG2ComponentType | Provides methods that describe a component type associated with an MPEG-2 stream type.

Locator Interfaces

Locators are used by the Network Provider and other filters in the graph to determine how to locate a specified program. These interfaces are not used by applications except possibly for debugging purposes. Third parties that install new tuning spaces should also provide a default locator for the tuning space. An individual tune request contains a locator, which can be different from the default locator. If present, the locator in the tune request takes precedence over the default locator

Interface | Description
IATSCLocator | Provides tuning information for an ATSC network.
IDVBCLocator | Provides tuning information for a DVB-C network.
IDVBSLocator | Provides tuning information for a DVB-S network.
IDVBTLocator | Provides tuning information for a DVB-T network.
ILocator | Base interface for all derived locator interfaces. Not used directly.


IAnalogRadioTuningSpace Interface

Not implemented in this release.

The IAnalogRadioTuningSpace interface provides methods for getting and setting parameters associated with tuning spaces for analog radio transmissions.

In addition to the methods inherited from ITuningSpace, IAnalogRadioTuningSpace exposes the following methods.

Method | Description
get_MaxFrequency | Retrieves the maximum frequency for this tuning space.
get_MinFrequency | Retrieves the minimum frequency for this tuning space.
get_Step | Retrieves the step increment for this tuning space.
put_MaxFrequency | Sets the maximum frequency for this tuning space.
put_MinFrequency | Sets the minimum frequency for this tuning space.
put_Step | Sets the step increment for this tuning space.


IAnalogRadioTuningSpace::get_MaxFrequency

Not implemented in this release.

The get_MaxFrequency method retrieves the maximum frequency for this tuning space.

Syntax

HRESULT get_MaxFrequency(
  long*  pMaxFrequencyVal
);

Parameters

pMaxFrequencyVal

[out] Pointer to a variable receives the maximum frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogRadioTuningSpace::get_MinFrequency

Not implemented in this release.

The get_MinFrequency method retrieves the minimum frequency for this tuning space.

Syntax

HRESULT get_MinFrequency(
  long*  pMinFrequencyVal
);

Parameters

pMinFrequencyVal

[out] Pointer to a variable that receives the minimum frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogRadioTuningSpace::get_Step

Not implemented in this release.

The get_Step method retrieves the step value to the next frequency.

Syntax

HRESULT get_Step(
  long*  pStepVal
);

Parameters

pStepVal

[out] Pointer to a variable receives the step value to the next frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogRadioTuningSpace::put_MaxFrequency

Not implemented in this release.

The put_MaxFrequency method sets the maximum frequency for this tuning space.

Syntax

HRESULT put_MaxFrequency(
  Long  NewMaxFrequencyVal
);

Parameters

NewMaxFrequencyVal

[in] Specifies the maximum frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogRadioTuningSpace::put_MinFrequency

Not implemented in this release.

The put_MinFrequency method sets the minimum frequency for this tuning space.

Syntax

HRESULT put_MinFrequency(
  Long  NewMinFrequencyVal
);

Parameters

NewMinFrequencyVal

[in] Specifies the minimum frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogRadioTuningSpace::put_Step

Not implemented in this release.

The put_Step method sets the step value to the next frequency.

Syntax

HRESULT put_Step(
  Long  NewStepVal
);

Parameters

NewStepVal

[in] Specifies the step value to the next frequency, in kilohertz (kHz).

Return Values

Returns E_NOTIMPL.

See Also

  • IAnalogRadioTuningSpace Interface


IAnalogTVTuningSpace Interface

The IAnalogTVTuningSpace interface provides methods for getting and setting parameters associated with analog TV tuning spaces. In Windows® XP, the Video Control uses these methods when building and controlling a WDM Analog TV filter graph.

In addition to the methods inherited from ITuningSpace, the IAnalogTVTuningSpace interface exposes the following methods.

Method | Description
get_CountryCode | Gets the country/region code of the tuning space (based on TAPI country/region codes).
get_InputType | Gets the input type (antenna or cable) intended for the tuning space.
get_MaxChannel | Gets the highest channel number for this tuning space.
get_MinChannel | Gets the lowest channel number for this tuning space.
put_CountryCode | Sets the country/region code of the tuning space (based on TAPI country/region codes).
put_InputType | Sets the input type (antenna or cable) intended for the tuning space.
put_MaxChannel | Sets the highest channel number for this tuning space.
put_MinChannel | Sets the lowest channel number for this tuning space.


IAnalogTVTuningSpace::get_CountryCode

The get_CountryCode method gets the country/region code of the tuning space (based on TAPI country/region codes).

Syntax

HRESULT get_CountryCode(
  long*  pCountryCodeVal
);

Parameters

pCountryCodeVal

[out] Pointer to a variable of type long that receives the value for the country/region code.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The tuner can use the country/region code to locate a likely channel for frequency mapping.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::get_InputType

The get_InputType method gets the input type (antenna or cable) intended for the tuning space.

Syntax

HRESULT get_InputType(
  TunerInputType*  pInputTypeVal
);

Parameters

pInputTypeVal

[out] Pointer to a variable of type TunerInputType that receives the input type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::get_MaxChannel

The get_MaxChannel method gets the highest channel number for this tuning space.

Syntax

HRESULT get_MaxChannel(
  long*  pMaxChannelVal
);

Parameters

pMaxChannelVal

[out] Pointer to a variable of type long that receives the value for the highest channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

For example, an NTSC tuning space connected to an antenna would return 69.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::get_MinChannel

The get_MinChannel method gets the lowest channel number for this tuning space.

Syntax

HRESULT get_MinChannel(
  long*  pMinChannelVal
);

Parameters

pMinChannelVal

[out] Pointer to a variable of type long that receives the value for the lowest channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

An NTSC tuning space connected to an antenna will return a value of 2.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::put_CountryCode

The put_CountryCode method sets the country/region code of the tuning space (based on TAPI country/region codes).

Syntax

HRESULT put_CountryCode(
  long  NewCountryCodeVal
);

Parameters

NewCountryCodeVal

[in] Variable of type long that specifies the country/region code.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The tuner can use the country/region code to locate a likely channel for frequency mapping.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::put_InputType

The put_InputType method sets the input type (antenna or cable) intended for the tuning space.

Syntax

HRESULT put_InputType(
  TunerInputType  NewInputTypeVal
);

Parameters

NewInputTypeVal

[in] Variable of type TunerInputType that specifies the input type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::put_MaxChannel

The put_MaxChannel method sets the highest channel number for this tuning space.

Syntax

HRESULT put_MaxChannel(
  long  NewMaxChannelVal
);

Parameters

NewMaxChannelVal

[in] Variable of type long that specifies the highest channel number.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IAnalogTVTuningSpace Interface


IAnalogTVTuningSpace::put_MinChannel

The put_MinChannel method sets the lowest channel number for this tuning space.

Syntax

HRESULT put_MinChannel(
  long  NewMinChannelVal
);

Parameters

NewMinChannelVal

[in] Variable of type long that specifies the lowest channel number.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IAnalogTVTuningSpace Interface


IATSCChannelTuneRequest Interface

The IATSCChannelTuneRequest interface is implemented on the ATSCChannelTuneRequest object and provides methods for getting and setting the minor channel for an ATSC transmission. The major channel is accessed using the get_Channel and put_Channel methods inherited from the IChannelTuneRequest interface, and the physical channel is accessed through the IATSCLocator interface.

In addition to the methods inherited from IChannelTuneRequest interface, the IATSCChannelTuneRequest interface exposes the following methods.

Method | Description
get_MinorChannel | Gets the current minor channel.
put_MinorChannel | Sets the minor channel to be tuned.


IATSCChannelTuneRequest::get_MinorChannel

The get_MinorChannel method gets the current minor channel.

Syntax

HRESULT get_MinorChannel(
  long*  pMinorChannel
);

Parameters

pMinorChannel

[out] Pointer to a variable of type long that receives the current minor channel. -1 means that the tuner should tune to the first valid minor channel it finds.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCChannelTuneRequest Interface


IATSCChannelTuneRequest::put_MinorChannel

The put_MinorChannel method sets the minor channel to be tuned.

Syntax

HRESULT put_MinorChannel(
  long  MinorChannel
);

Parameters

MinorChannel

[in] Variable of type long that specifies the minor channel. Specify -1 to instruct the tuner to tune to the first valid minor channel it finds.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCChannelTuneRequest Interface


IATSCComponentType Interface

The IATSCComponentType interface represents a component type for a component in an ATSC broadcast. The ATSCComponentType object exposes this interface. Use this interface to determine if an audio stream is in AC-3 format.

In addition to the methods inherited from IMPEG2ComponentType, the IATSCComponentType interface exposes the following methods.

Method | Description
get_Flags | Queries whether an audio component is in AC-3 format.
put_Flags | Specifies whether an audio component is in AC-3 format.


IATSCComponentType::get_Flags

The get_Flags method queries whether an audio component is in AC-3 format.

Syntax

HRESULT get_Flags(
  long*  pFlags
);

Parameters

pFlags

[out] Pointer to a variable that receives one of the following values.

Value | Description
Zero | The component does not contain AC-3 audio
ATSCCT_AC3 | The component contains AC-3 audio

See ATSCComponentTypeFlags Enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCComponentType Interface


IATSCComponentType::put_Flags

The put_Flags method specifies whether an audio component is in AC-3 format.

Syntax

HRESULT put_Flags(
  long  Flags
);

Parameters

Flags

[in] Specifies one of the following values:

Value | Description
Zero | The component does not contain AC-3 audio
ATSCCT_AC3 | The component contains AC-3 audio

See ATSCComponentTypeFlags Enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCComponentType Interface


IATSCLocator Interface

The IATSCLocator interface is implemented on the ATSCLocator object and contains methods that enable the network provider to determine the physical channel and transport stream ID of an ATSC transmission. Applications do not use Locator interfaces except possibly for debugging purposes. All Locator objects also support IPersistPropertyBag.

In addition to the methods inherited from ILocator, the IATSCLocator interface exposes the following methods.

Method | Description
get_PhysicalChannel | Retrieves the physical channel.
get_TSID | Retrieves the transport stream ID.
put_PhysicalChannel | Sets the physical channel.
put_TSID | Sets the transport stream ID.


IATSCLocator::get_PhysicalChannel

The get_PhysicalChannel method retrieves the physical channel.

Syntax

HRESULT get_PhysicalChannel(
  long*  pPhysicalChannel
);

Parameters

pPhysicalChannel

[out] Pointer to a variable of type long that receives the physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This is a required property. A tuner cannot locate an ATSC transmission source without it.

See Also

  • IATSCLocator Interface


IATSCLocator::get_TSID

The get_TSID method retrieves the transport stream ID.

Syntax

HRESULT get_TSID(
  long*  pTSID
);

Parameters

pTSID

[out] Pointer to a variable of type long that receives the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property is not required for tuning. It will be set by the BDA Transport Information Filter (TIF) when the signal is acquired. This property is not used by the application but may be used by one or more of the receiver filters. For example, a TIF may use this to determine whether the transport stream has changed from what was originally tuned and generate events that cause re-acquisition of the requested program.

See Also

  • IATSCLocator Interface


IATSCLocator::put_PhysicalChannel

The put_PhysicalChannel method sets the physical channel.

Syntax

HRESULT put_PhysicalChannel(
  long  PhysicalChannel
);

Parameters

PhysicalChannel

[in] Variable of type long that specifies the physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This is a required property. A tuner cannot locate an ATSC transmission source without it.

See Also

  • IATSCLocator Interface

pTSID

[out] Pointer to a variable of type long that receives the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property is not required for tuning. It will be set by the BDA Transport Information Filter (TIF) when the signal is acquired. This property is not used by the application but may be used by one or more of the receiver filters. For example, a TIF may use this to determine whether the transport stream has changed from what was originally tuned and generate events that cause re-acquisition of the requested program.

See Also

  • IATSCLocator Interface


IATSCLocator::put_TSID

The put_TSID method sets the transport stream ID.

Syntax

HRESULT put_TSID(
  long  TSID
);

Parameters

TSID

[in] Variable of type long that specifies the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property is optional.

See Also

  • IATSCLocator Interface


IATSCTuningSpace Interface

The IATSCTuningSpace interface is implemented on ATSCTuningSpace objects, which represent any tuning space with an ATSC network type. Microsoft provides a default ATSC tuning space with Windows XP, and also with DirectX 9.0. Third parties such as cable providers may install a custom tuning space using the ITuningSpaceContainer interface. An ATSCTuningSpace object creates tune requests that expose IATSCChannelTuneRequest.

When the minimum and maximum physical channel and minor channel for a tuning space are set using these methods, the tuner will automatically "wrap around" to the minimum value when the user tries to specify a channel that is greater than the maximum value.

In addition to the methods inherited from IAnalogTVTuningSpace, the IATSCTuningSpace interface exposes the following methods.

Method | Description
get_MaxMinorChannel | Gets the highest minor channel number for this tuning space.
get_MaxPhysicalChannel | Gets the highest physical channel number ever allowed for this tuning space.
get_MinMinorChannel | Gets the lowest minor channel number ever allowed for this tuning space.
get_MinPhysicalChannel | Gets the lowest physical channel number ever allowed for this tuning space.
put_MaxMinorChannel | Sets the highest minor channel number for this tuning space.
put_MaxPhysicalChannel | Sets the highest physical channel number ever allowed for this tuning space.
put_MinMinorChannel | Sets the lowest minor channel number ever allowed for this tuning space.
put_MinPhysicalChannel | Sets the lowest physical channel number ever allowed for this tuning space.


IATSCTuningSpace::get_MaxMinorChannel

The get_MaxMinorChannel method gets the highest minor channel number for this tuning space.

Syntax

HRESULT get_MaxMinorChannel(
  long*  pMaxMinorChannelVal
);

Parameters

pMaxMinorChannelVal

[out] Pointer to a variable of type long that receives the highest minor channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface


IATSCTuningSpace::get_MaxPhysicalChannel

The get_MaxPhysicalChannel method gets the highest physical channel number for this tuning space.

Syntax

HRESULT get_MaxPhysicalChannel(
  long*  pMaxPhysicalChannelVal
);

Parameters

pMaxPhysicalChannelVal

[out] Pointer to a variable of type long that receives the highest physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface
  • IChannelTuneRequest::put_Channel


IATSCTuningSpace::get_MinMinorChannel

The get_MinMinorChannel method gets the lowest minor channel number ever allowed for this tuning space.

Syntax

HRESULT get_MinMinorChannel(
  long*  pMinMinorChannelVal
);

Parameters

pMinMinorChannelVal

[out] Pointer to a variable of type long that receives the lowest minor channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface


IATSCTuningSpace::get_MinPhysicalChannel

The get_MinPhysicalChannel method sets the lowest physical channel number for this tuning space.

Syntax

HRESULT get_MinPhysicalChannel(
  long*  pMinPhysicalChannelVal
);

Parameters

pMinPhysicalChannelVal

[out] Pointer to a variable of type long that receives the lowest physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface
  • IChannelTuneRequest::put_Channel


IATSCTuningSpace::put_MaxMinorChannel

The put_MaxMinorChannel method gets the highest minor channel number for this tuning space.

Syntax

HRESULT put_MaxMinorChannel(
  long  NewMaxMinorChannelVal
);

Parameters

NewMaxMinorChannelVal

[in] Variable of type long that specifies the highest minor channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property must be set before calling put_MinMinorChannel to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

See Also

  • IATSCTuningSpace Interface


IATSCTuningSpace::put_MaxPhysicalChannel

The put_MaxPhysicalChannel method sets the highest physical channel number for this tuning space.

Syntax

HRESULT put_MaxPhysicalChannel(
  long  NewMaxPhysicalChannelVal
);

Parameters

NewMaxPhysicalChannelVal

[in] Variable of type long that specifies the highest physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface
  • IChannelTuneRequest::put_Channel


IATSCTuningSpace::put_MinMinorChannel

The put_MinMinorChannel method sets the lowest minor channel number ever allowed for this tuning space.

Syntax

HRESULT put_MinMinorChannel(
  long  NewMinMinorChannelVal
);

Parameters

NewMinMinorChannelVal

[in] Variable of type long that specifies the lowest minor channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property must be set after calling put_MaxMinorChannel to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

See Also

  • IATSCTuningSpace Interface


IATSCTuningSpace::put_MinPhysicalChannel

The put_MinPhysicalChannel method sets the lowest physical channel number for this tuning space.

Syntax

HRESULT put_MinPhysicalChannel(
  long  NewMinPhysicalChannelVal
);

Parameters

NewMinPhysicalChannelVal

[in] Variable of type long that specifies the lowest physical channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IATSCTuningSpace Interface
  • IChannelTuneRequest::put_Channel


IAuxInTuningSpace Interface

The IAuxInTuningSpace interface is implemented on AuxInTuningSpace objects, which represent auxiliary video inputs such as S-video or composite video on a hardware device connected to the PC. This interface inherits from ITuningSpace and adds no new methods.


IChannelTuneRequest Interface

The IChannelTuneRequest interface is implemented on tune request objects that support channel numbers, including analog TV and ATSC.

This interface enables a guide store loader running on Microsoft® Windows® XP to create tune requests for analog TV networks, which an application can then pass to the Video Control. The Video Control examines all tune requests it receives. If it is an analog tune request, the Video Control creates a filter graph that can play the specified channel. Applications running on earlier versions of Windows are responsible for creating their own analog graphs if the user selects a program on an analog channel. Downlevel applications should never pass an analog tune request to a BDA tuning device because the device will not be able to interpret it.

In addition to the methods inherited from ITuneRequest, the IChannelTuneRequest interface exposes the following methods.

Method | Description
get_Channel | Gets the channel to be tuned.
put_Channel | Sets the channel to be tuned.


IChannelTuneRequest::get_Channel

The get_Channel method gets the channel to be tuned.

Syntax

HRESULT get_Channel(
  long*  pChannel
);

Parameters

pChannel

[out] Pointer to a variable of type long that receives the current channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IChannelTuneRequest Interface


IChannelTuneRequest::put_Channel

The put_Channel method sets the channel to be tuned.

Syntax

HRESULT put_Channel(
  long  Channel
);

Parameters

Channel

[in] Variable of type long that specifies the channel.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

If the value specified for Channel is less than the minimum channel set for the tuning space, it will "wrap around" to the maximum channel value. Likewise, if the value specified for Channel is greater than the maximum channel set for the tuning space, it will "wrap around" to the minimum channel value.

See Also

  • IChannelTuneRequest Interface


IComponent Interface

The IComponent interface a base class for all derived interfaces such as IMPEG2Component and it describes the general characteristics of a component, which is an elementary stream within the program stream. The derived interfaces describe the properties of a component that are specific to a given network type. Component objects are created and attached to the tune request by the BDA Transport Information Filter (TIF) after reception has begun. All component objects also support IPersistPropertyBag.

In addition to the methods inherited from IDispatch, the IComponent interface exposes the following methods.

Method | Description
Clone | Creates a copy of the component.
get_DescLangID | Retrieves the language for presentation of the description.
get_Description | Retrieves the description of the component.
get_Status | Retrieves the requested or actual status of the component.
get_Type | Retrieves an IComponentType interface describing the general characteristics of the Component.
put_DescLangID | Sets the language for presentation of the description.
put_Description | Sets the description of the component.
put_Status | Sets the requested or actual status of the component.
put_Type | Sets an IComponentType object describing the general characteristics of the Component.


IComponent::Clone

The Clone method creates a copy of the component.

Syntax

HRESULT Clone(
  IComponent**  ppNewComponent
);

Parameters

ppNewComponent

[out] Address of a variable that receives an IComponent interface pointer. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponent Interface


IComponent::get_DescLangID

The get_DescLangID method retrieves the language identifier for the description property.

Syntax

HRESULT get_DescLangID(
  long*  pLangID
);

Parameters

pLangID

[out] Pointer to a variable receives the language identifier.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The returned language identifer identifies the language of the description property, which is obtained by calling the get_Description method.

To get the language of the stream content, call the ILanguageComponentType::get_LangID method (only if the component object exposes the ILanguageComponentType interface).

See Also

  • IComponent Interface
  • IComponent::get_Description


IComponent::get_Description

The get_Description method retrieves the description of the component.

Syntax

HRESULT get_Description(
  BSTR*  pDescription
);

Parameters

pDescription

[out] Pointer to a variable that receives the description.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • IComponent Interface


IComponent::get_Status

The get_Status method retrieves the requested or actual status of the component.

Syntax

HRESULT get_Status(
  ComponentStatus*  pStatus
);

Parameters

pStatus

[out] Pointer to a ComponentStatus enumeration that receives the status value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

When the TIF adds a component to the IComponents collection, it can indicate whether the component is active or not. An application can attempt to set this status, and resubmit a tune request. The tuner will update the status from the enumeration: Active, Inactive, Unavailable. The Unavailable status is only set by a tuner in response to a request to activate, when the component is not really available.

See Also

  • IComponent Interface


IComponent::get_Type

The get_Type method retrieves an IComponentType interface describing the general characteristics of the component.

Syntax

HRESULT get_Type(
  IComponentType**  ppCT
);

Parameters

ppCT

[out] Address of an IComponentType interface pointer that will be set to the retrieved component.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponent Interface


IComponent::put_DescLangID

The put_DescLangID method sets the language for presentation of the description.

Syntax

HRESULT put_DescLangID(
  long  LangID
);

Parameters

LangID

[in] Variable of type long that specifies the language ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This is the language of the descriptive info in the component object. It is not the same as the language ID in the language component type which defines the language of the stream content. An application can modify this value in order to activate a different language substream.

See Also

  • IComponent Interface


IComponent::put_Description

The put_Description method sets the description of the component.

Syntax

HRESULT put_Description(
  BSTR  Description
);

Parameters

Description

[in] Variable of type BSTR that contains the new description.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponent Interface


IComponent::put_Status

The put_Status method sets the requested or actual status of the component.

Syntax

HRESULT put_Status(
  ComponentStatus  Status
);

Parameters

Status

[in] A variable of type ComponentStatus that specifies the status value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Use this method to activate or inactivate a stream component.

See Also

  • IComponent Interface
  • IComponent::get_Status


IComponent::put_Type

The put_Type method sets an IComponentType object describing the general characteristics of the component.

Syntax

HRESULT put_Type(
  IComponentType*  pCT
);

Parameters

pCT

[in] Pointer to an IComponentType object that specifies the new values for the component.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Using the IComponent base class interface, it is possible to set the type to be NULL. If you try to do this with the derived IMPEG2Component class interface, this method will return E_POINTER. The IMPEG2Component object cannot have the base IComponentType class interface as the set type - this will return Type Mismatch (0x80020005).

See Also

  • IComponent Interface


IComponents Interface

The IComponents interface represents a collection of components. In digital television, the term component refers to a substream within the program stream. For example, a program stream may have three audio streams in different languages; in this case each audio stream is a component of the program stream. The IComponents interface is implemented on the Components object, which is a collection of components. The Components object enables applications to enumerate components within a program stream and perform operations related to individual components in the collection. The Components object also supports IPersistPropertyBag.

In addition to the methods inherited from IDispatch, the IComponents interface exposes the following methods.

Method | Description
Add | Adds a Component object to the collection.
Clone | Creates a new copy of the collection.
EnumComponents | Returns an IEnumComponents enumerator for all components in the collection.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
get_Count | Gets the number of Component objects in the collection.
get_Item | Enables the caller to access a component by index.
Remove | Removes a Component object from the collection.


IComponents::Add

The Add method adds a Component object to the collection.

Syntax

HRESULT Add(
  IComponent*  pComponent,
  VARIANT*  pNewIndex
);

Parameters

pComponent

[in] Pointer to the Component object to be added.

pNewIndex

[out] Pointer to a VARIANT that will receive the index of the Component object after it has been added.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponents Interface


IComponents::Clone

The Clone method creates a new copy of the collection.

Syntax

HRESULT Clone(
  IComponents**  ppNewList
);

Parameters

ppNewList

[out] Address of an IComponents interface pointer that will be set to the new Components object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponents Interface


IComponents::EnumComponents

The EnumComponents method returns an enumerator for the components in the collection.

Syntax

HRESULT EnumComponents(
  IEnumComponents**  ppNewEnum
);

Parameters

ppNewEnum

[out] Address of a variable that receives an IEnumComponents interface pointer.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

If the method succeeds, the IEnumComponents interface has an outstanding reference count. The caller must release the interface.

See Also

  • IComponents Interface


IComponents::get__NewEnum

The get__NewEnum enumeration method supports For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppNewEnum
);

Parameters

ppNewEnum

[out] Address of an IEnumVARIANT interface pointer that will receive the enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided so that scripting and Visual Basic applications can iterate through the collection in a For...Each loop. C++ applications should use the IComponents::EnumComponents method.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread.

See Also

  • IComponents Interface


IComponents::get_Count

The get_Count method gets the number of Component objects in the collection.

Syntax

HRESULT get_Count(
  long*  pCount
);

Parameters

pCount

[out] Pointer to a variable of type long that receives the number of components.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponents Interface


IComponents::get_Item

The get_Item method enables the caller to access a component by index.

Syntax

HRESULT get_Item(
  VARIANT  Index,
  IComponent**  ppComponent
);

Parameters

Index

[in] Variable of type VARIANT specifying the zero-based index in the collection.

ppComponent

[out] Address of an IComponent interface pointer that will receive the Component object at the specified index.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponents Interface


IComponents::Remove

The Remove method removes a Component object from the collection.

Syntax

HRESULT Remove(
  VARIANT  Index
);

Parameters

Index

[in] Variable of type VARIANT that specifies the index number of the Component object to be removed.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponents Interface


IComponentType Interface

The IComponentType interface is implemented on ComponentType objects, and contains methods for setting and retrieving various properties for a Component. Every Component object has an associated ComponentType object that is set or retrieved with the get_Type and put_Type methods.

In addition to the methods inherited from IDispatch, the IComponentType interface exposes the following methods.

Method | Description
Clone | Creates a new copy of this component type.
get__MediaFormatType | Retrieves the DirectShow media format type as a GUID.
get__MediaMajorType | Retrieves the DirectShow media major type as a GUID.
get__MediaSubType | Retrieves the DirectShow media subtype as a GUID.
get_Category | Retrieves the component category.
get_MediaFormatType | Retrieves the DirectShow media format type as a BSTR.
get_MediaMajorType | Retrieves the DirectShow media major type as a BSTR.
get_MediaSubType | Retrieves the DirectShow media subtype as a BSTR.
get_MediaType | Retrieves the DirectShow AM_MEDIA_TYPE media type structure for the component.
put__MediaFormatType | Sets the DirectShow media format type.
put__MediaMajorType | Sets the DirectShow AM_MEDIA_TYPE majortype member for the component.
put__MediaSubType | Sets the DirectShow AM_MEDIA_TYPE subtype member for the component.
put_Category | Sets the component category.
put_MediaFormatType | Sets the DirectShow media format type.
put_MediaMajorType | Sets the DirectShow AM_MEDIA_TYPE majortype member for the component.
put_MediaSubType | Sets the DirectShow AM_MEDIA_TYPE subtype member for the component.
put_MediaType | Sets the DirectShow AM_MEDIA_TYPE media type structure for the component.


IComponentType::Clone

The Clone method creates a new copy of this component type.

Syntax

HRESULT Clone(
  IComponentType**  ppNewCT
);

Parameters

ppNewCT

[out] Address of the IComponentType interface pointer that will be set to the returned interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentType Interface


IComponentType::get__MediaFormatType

The get__MediaFormatType method retrieves the DirectShow media format type as a GUID.

Syntax

HRESULT get__MediaFormatType(
  GUID*  pMediaFormatType
);

Parameters

pMediaFormatType

[out] Pointer to a GUID that will receive the format type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get__MediaMajorType

The get__MediaMajorType method retrieves the DirectShow media format type as a GUID.

Syntax

HRESULT get__MediaMajorType(
  GUID*  MediaMajorType
);

Parameters

MediaMajorType

[out] Pointer to a GUID that will receive the major type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get__MediaSubType

The get__MediaSubType method retrieves the DirectShow media subtype as a GUID.

Syntax

HRESULT get__MediaSubType(
  GUID*  pMediaSubType
);

Parameters

pMediaSubType

[out] Pointer to a GUID that will receive the major type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get_Category

The get_Category method retrieves the component category.

Syntax

HRESULT get_Category(
  ComponentCategory*  pCategory
);

Parameters

pCategory

[out] Pointer to a ComponentCategory data type that will receive the category.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentType Interface


IComponentType::get_MediaFormatType

The get_MediaFormatType method retrieves the DirectShow media format type as a BSTR.

Syntax

HRESULT get_MediaFormatType(
  BSTR*  pMediaFormatType
);

Parameters

pMediaFormatType

[out] Pointer to a BSTR that will receive the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get_MediaMajorType

The get_MediaMajorType method retrieves the DirectShow media major type as a BSTR.

Syntax

HRESULT get_MediaMajorType(
  BSTR*  pMediaMajorType
);

Parameters

pMediaMajorType

[out] Pointer to a BSTR that will receive the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get_MediaSubType

The get_MediaSubType method retrieves the DirectShow media subtype as a BSTR.

Syntax

HRESULT get_MediaSubType(
  BSTR*  pMediaSubType
);

Parameters

pMediaSubType

[out] Pointer to a BSTR that will receive the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::get_MediaType

The get_MediaType method retrieves the DirectShow AM_MEDIA_TYPE structure for the component.

Syntax

HRESULT get_MediaType(
  AM_MEDIA_TYPE*  pMediaType
);

Parameters

pMediaType

[out] Pointer to an AM_MEDIA_TYPE structure that will be filled in with the values associated with the current ComponentType.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put__MediaFormatType

The put__MediaFormatType method sets the DirectShow media format type.

Syntax

HRESULT put__MediaFormatType(
  REFCLSID  MediaFormatType
);

Parameters

MediaFormatType

[in] REFCLSID that specifies the media format type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put__MediaMajorType

The put__MediaMajorType method sets the DirectShow media major type.

Syntax

HRESULT put__MediaMajorType(
  REFCLSID MediaMajorType
);

Parameters

MediaMajorType

[in] REFCLSID that specifies the media major type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put__MediaSubType

The put__MediaSubType method sets the DirectShow media subtype.

Syntax

HRESULT put__MediaSubType(
  REFCLSID MediaSubType
);

Parameters

MediaSubType

[in] REFCLSID that specifies the media sub type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put_Category

The put_Category method sets the component category.

Syntax

HRESULT put_Category(
  ComponentCategory  Category
);

Parameters

Category

[in] A ComponentCategory value that specifies the new category for this component type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentType Interface


IComponentType::put_MediaFormatType

The put_MediaFormatType method sets the DirectShow media format type.

Syntax

HRESULT put_MediaFormatType(
  BSTR  MediaFormatType
);

Parameters

MediaFormatType

[in] BSTR that specifies the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put_MediaMajorType

The put_MediaMajorType method sets the DirectShow media major type.

Syntax

HRESULT put_MediaMajorType(
  BSTR MediaMajorType
);

Parameters

MediaMajorType

[in] BSTR that specifies the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentType::put_MediaSubType

The put_MediaSubType method sets the DirectShow media subtype.

Syntax

HRESULT put_MediaSubType(
  BSTR  MediaSubType
);

Parameters

MediaSubType

[in] BSTR that specifies the GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentType Interface


IComponentType::put_MediaType

The put_MediaType method sets the DirectShow AM_MEDIA_TYPE structure for the component.

Syntax

HRESULT put_MediaType(
  AM_MEDIA_TYPE  MediaType
);

Parameters

MediaType

[in] AM_MEDIA_TYPE structure that specifies the major type, subtype, format, and so on.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • AM_MEDIA_TYPE
  • IComponentType Interface


IComponentTypes Interface

The IComponentTypes interface is implemented on ComponentTypes objects and contains methods that enable applications to enumerate, add, remove and retrieve individual ComponentType objects. All ComponentTypes objects also support IPersistPropertyBag.

In addition to the methods inherited from IDispatch, the IComponentTypes interface exposes the following methods.

Method | Description
Add | Adds a new ComponentType object to the collection.
Clone | Creates a new copy of the collection.
EnumComponentTypes | Returns an IEnumComponentTypes enumerator for all component types in the collection.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
get_Count | Returns the number of Component Types in the collection.
get_Item | Retrieves the IComponentType interface pointer at the specified index number.
put_Item | Replaces the ComponentType object at the specified index with a new ComponentType object.
Remove | Removes the ComponentType object at the specified index number.


IComponentTypes::Add

The Add method adds a new ComponentType object to the collection.

Syntax

HRESULT Add(
  IComponentType*  pComponentType,
  VARIANT*  pNewIndex
);

Parameters

pComponentType

[in] Pointer to the IComponentType object that will be added to the collection.

pNewIndex

[out] The index number of the component type after it has been added to the collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::Clone

The Clone method creates a new copy of the collection.

Syntax

HRESULT Clone(
  IComponentTypes**  ppNewList
);

Parameters

ppNewList

[out] Address of an IComponentTypes interface pointer that will be set to the new ComponentTypes object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::EnumComponentTypes

The EnumComponentTypes method returns an IEnumComponentTypes enumerator for all component types in the collection.

Syntax

HRESULT EnumComponentTypes(
  IEnumComponentTypes**  ppNewEnum
);

Parameters

ppNewEnum

[out] Address of an IEnumComponentTypes interface pointer that will receive the new collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::get__NewEnum

The get__NewEnum enumeration method supports For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
  IEnumVARIANT**  ppNewEnum
);

Parameters

ppNewEnum

[out] Address of an interface pointer to an IEnumVARIANT object that will receive the new collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided to enable scripting and Visual Basic applications to iterate through the collection in a For...Each loop. C++ applications should use the IComponentTypes::EnumComponentTypes method.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread.

See Also

  • IComponentTypes Interface


IComponentTypes::get_Count

The get_Count method returns the number of component types in the collection.

Syntax

HRESULT get_Count(
  long*  pCount
);

Parameters

pCount

[out] Pointer to a variable of type long that will receive the number of items in the collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::get_Item

The get_Item method retrieves the IComponentType interface pointer at the specified index number.

Syntax

HRESULT get_Item(
  VARIANT  Index,
  IComponentType**  ppComponentType
);

Parameters

Index

[in] The index number of the object to retrieve.

ppComponentType

[out] Address of an IComponentType interface pointer that will be set to the object at the specified index.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::put_Item

The put_Item method replaces the ComponentType object at the specified index with a new ComponentType object.

Syntax

HRESULT put_Item(
  VARIANT  Index,
  IComponentType*  pComponentType
);

Parameters

Index

[in] Index number of the item to be replaced.

pComponentType

[in] Pointer to the IComponentType object that will be inserted into the collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


IComponentTypes::Remove

The Remove method removes the ComponentType object at the specified index number.

Syntax

HRESULT Remove(
  VARIANT  Index
);

Parameters

Index

[in] Index of the item to remove.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IComponentTypes Interface


ICreatePropBagOnRegKey Interface

The ICreatePropBagOnRegKey interface creates a property bag that can store information in the system registry.

Use this interface to store the default tune request in the registry. When Microsoft® Internet Explorer® loads a "tv:" object in a Web page, it automatically tunes to the default tune request.

In addition to the methods inherited from IUnknown, the ICreatePropBagOnRegKey interface exposes the following method.

Method | Description
Create | Creates a property bag that can store information in the system registry.


ICreatePropBagOnRegKey::Create

The Create method creates a property bag that can store information in the system registry.

Syntax

HRESULT Create(
  HKEY  hkey,
  LPCOLESTR  subkey,
  DWORD  ulOptions,
  DWORD  samDesired,
  REFIID  iid,
  LPVOID*  ppBag
);

Parameters

hkey

[in] Specifies a handle to the registry key.

subkey

[in] Specifies the subkey.

ulOptions

[in] Reserved; must be zero.

samDesired

[in] Specifies the desired access rights to the key. The value can be any combination of flags from the samDesired parameter in the Win32 RegOpenKeyEx function.

iid

Specifies the interface identifier (IID) of a property bag interface. Use the value IID_IPropertyBag or IID_IPropertyBag2.

ppBag

[out] Address of a variable that receives the interface specified by the iid parameter.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_NOTIMPL | The specified IID is not supported.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

This method creates a property bag and returns a pointer to the IPropertyBag or IPropertyBag2 interface, depending on the value of the iid parameter. The returned property bag can access the specified registry key, using the access rights given in the samDesired parameter. The various property bag methods require different access rights, as follows:

Method | Required Access Rights
IPropertyBag::Read | KEY_READ
IPropertyBag::Write | KEY_WRITE
IPropertyBag2::CountProperties | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS
IPropertyBag2::GetPropertyInfo | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS

If you write a value of VT_EMPTY or VT_NULL the property is removed from the bag and the corresponding registry values are deleted.

Example Code

To create a default tune request in the registry, first create a tune request object and query it for the IPersistPropertyBag interface. Then call IPersistPropertyBag::Save with a pointer to the property bag:

ICreatePropBagOnRegKey *pCreateRegBag;
IPropertyBag *pRegBag;
IPersistPropertyBag *pPersist;
ITuneRequest *pTuneReq;

// Create an instance of the CreatePropBagOnRegKey object
// and obtain a pointer to the interface.
HRESULT hr = CoCreateInstance(CLSID_CreatePropBagOnRegKey, NULL, CLSCTX_INPROC_SERVER,
    IID_ICreatePropBagOnRegKey, (void**)&pCreateRegBag);
if (SUCCEEDED(hr))
{
    //Create the property bag.
    hr = pCreateRegBag->Create(HKEY_CURRENT_USER,
        OLESTR("SOFTWARE\\Microsoft\\MSVidCtl\\DefaultTuneRequest"),
        0, KEY_READ | KEY_WRITE, IID_IPropertyBag, (void**)&pRegBag);
    if (SUCCEEDED(hr))
    {
        // Assume pTuneReq is a pointer to a valid tune request, which was
        // created as specified elsewhere in this documentation.
        pTuneReq->QueryInterface(IID_IPersistPropertyBag, (void**)&pPersist);
        // Save the property bag to the registry.
        pPersist->Save(pRegBag, FALSE, TRUE);

        pRegBag->Release();
        pPersist->Release();
    }
    pCreateRegBag->Release();
}

The following example loads the default tune request and returns an ITuneRequest interface pointer:

HRESULT LoadDefaultTuneReq(ITuneRequest **ppTuneReq)
{
    HRESULT hr;
    *ppTuneReq = NULL;
    CComPtr<ICreatePropBagOnRegKey> pCreateRegBag;
    hr = pCreateRegBag.CoCreateInstance(CLSID_CreatePropBagOnRegKey,
        NULL, CLSCTX_INPROC_SERVER);
    if (FAILED(hr)) return hr;

    //Create the property bag.
    CComPtr<IPropertyBag> pRegBag;
    hr = pCreateRegBag->Create(HKEY_CURRENT_USER,
        OLESTR("SOFTWARE\\Microsoft\\MSVidCtl"), 0, KEY_READ,
        IID_IPropertyBag, reinterpret_cast<void**>(&pRegBag));
    if (FAILED(hr)) return hr;

    // Read the default tune request from the property bag.
    CComVariant var;
    hr = pRegBag->Read(OLESTR("DefaultTuneRequest"), &var, NULL);
    if (FAILED(hr)) return hr;

    // Make sure we got a tune request object.
    CComQIPtr<ITuneRequest> pTune;
    switch (var.vt)
    {
    case VT_UNKNOWN:
        pTune = var.punkVal;
        break;
    case VT_DISPATCH:
        pTune = var.pdispVal;
        break;
    }
    if (pTune)
    {
        *ppTuneReq = pTune.Detach();
        return S_OK;
    }
    return E_FAIL;
}

See Also

  • ICreatePropBagOnRegKey Interface


IDVBCLocator Interface

The IDVBCLocator interface is implemented on DVBCLocator objects, which contain tuning information for DVB-C networks. This interface inherits the ILocator interface and adds no new methods.


IDVBSLocator Interface

The IDVBSLocator interface is implemented on the DVBSLocator object. It provides information to enable a tuner to acquire a satellite DVB (DVB-S) transmission. The methods for acquiring a transport stream once the signal is tuned are provided by IDVBTuneRequest. Locator data is meant for consumption by the BDA hardware drivers. Applications do not need to interpret any of this data except perhaps for some debugging purposes.

Locators can be created dynamically when the tune request is created, by a loader that has access to the necessary information about the tuning space, or a default locator can be installed when the tuning space is first installed, and the loader can use the default locator when creating tune requests. Applications do not need to use any of the Locator interfaces unless they are creating tune requests. All Locator objects also support IPersistPropertyBag.

In addition to the methods inherited from ILocator, the IDVBSLocator interface exposes the following methods.

Method | Description
get_Azimuth | Retrieves the azimuth setting used for positioning the satellite dish.
get_Elevation | Retrieves the elevation of the satellite in tenths of a degree.
get_OrbitalPosition | Retrieves the setting for the satellite's orbital position.
get_SignalPolarisation | Retrieves the signal polarisation.
get_WestPosition | Retrieves a value indicating whether the orbital position is given in east or west longitude.
put_Azimuth | Adjusts the azimuth setting used for positioning the satellite dish.
put_Elevation | Sets the elevation of the satellite in tenths of a degree.
put_OrbitalPosition | Sets the setting for the satellite's orbital position.
put_SignalPolarisation | Sets the signal polarisation.
put_WestPosition | Sets the longitudinal position as west longitude or east longitude.


IDVBSLocator::get_Azimuth

The get_Azimuth method retrieves the azimuth setting used for positioning the satellite dish.

Syntax

HRESULT get_Azimuth(
  long*  pAzimuth
);

Parameters

pAzimuth

[out] Pointer to a variable of type long that receives the azimuth in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::get_Elevation

The get_Elevation method retrieves the elevation of the satellite in tenths of a degree.

Syntax

HRESULT get_Elevation(
  long*  pElevation
);

Parameters

pElevation

[out] Pointer to a variable of type long that receives the elevation setting in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::get_OrbitalPosition

The get_OrbitalPosition method retrieves the setting for the satellite's orbital position.

Syntax

HRESULT get_OrbitalPosition(
  long*  plongitude
);

Parameters

plongitude

[out] Pointer to a variable of type long that receives the longitude setting in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::get_SignalPolarisation

The get_SignalPolarisation method retrieves the signal polarisation.

Syntax

HRESULT get_SignalPolarisation(
  Polarisation*  pPolarisationVal
);

Parameters

pPolarisationVal

[out] Pointer to a variable of type Polarisation that receives the polarisation value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method and the associated enumeration type use the British spelling for "polarisation" and so to maintain consistency the documentation also uses that spelling.

See Also

  • IDVBSLocator Interface


IDVBSLocator::get_WestPosition

The get_WestPosition method retrieves a value indicating whether the orbital position is given in east or west longitude.

Syntax

HRESULT get_WestPosition(
  VARIANT_BOOL*  pWestLongitude
);

Parameters

pWestLongitude

[out] Pointer to a variable of type VARIANT_BOOL; a value of true means "west longitude."

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::put_Azimuth

The put_Azimuth method adjusts the azimuth setting used for positioning the satellite dish.

Syntax

HRESULT put_Azimuth(
  long  Azimuth
);

Parameters

Azimuth

[in] Variable of type long that specifies the azimuth in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::put_Elevation

The put_Elevation method sets the elevation of the satellite in tenths of a degree.

Syntax

HRESULT put_Elevation(
  long Elevation
);

Parameters

Elevation

[in] Variable of type long that specifies for the locator the satellite's elevation in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::put_OrbitalPosition

The put_OrbitalPosition method sets the setting for the satellite's orbital position.

Syntax

HRESULT put_OrbitalPosition(
  long  longitude
);

Parameters

longitude

[in] Variable of type long that specifies the satellite's longitude in tenths of a degree.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSLocator::put_SignalPolarisation

The put_SignalPolarisation method sets the signal polarisation.

Syntax

HRESULT put_SignalPolarisation(
  Polarisation  PolarisationVal
);

Parameters

PolarisationVal

[in] Variable of type Polarisation that specifies the signal polarisation value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method and the associated enumeration type use the British spelling for "polarisation" and so to maintain consistency the documentation also uses that spelling.

See Also

  • IDVBSLocator Interface


IDVBSLocator::put_WestPosition

The put_WestPosition method sets the longitudinal position as west longitude or east longitude.

Syntax

HRESULT put_WestPosition(
  VARIANT_BOOL  WestLongitude
);

Parameters

WestLongitude

[in] Variable of type VARIANT_BOOL that specifies whether the following longitude values that follow will be west or east longitude. True means "west longitude."

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSLocator Interface


IDVBSTuningSpace Interface

The IDVBSTuningSpace interface is implemented on the DVBTuningSpace object and provides methods for working with tuning spaces with a DVBS network type.

In addition to the methods inherited from IDVBTuningSpace2, the IDVBSTuningSpace interface exposes the following methods.

Method | Description
get_HighOscillator | Retrieves the high oscillator frequency.
get_InputRange | Retrieves an integer indicating which option or switch contains the requested signal source.
get_LNBSwitch | Retrieves the LNB switch frequency.
get_LowOscillator | Retrieves the low oscillator frequency.
get_SpectralInversion | Retrieves an integer indicating the spectral inversion.
put_HighOscillator | Sets the high oscillator frequency.
put_InputRange | Sets an integer indicating which option or switch contains the requested signal source.
put_LNBSwitch | Sets the LNB switch frequency.
put_LowOscillator | Sets the low oscillator frequency.
put_SpectralInversion | Sets an integer indicating the spectral inversion.


IDVBSTuningSpace::get_HighOscillator

The get_HighOscillator method retrieves the high oscillator frequency.

Syntax

HRESULT get_HighOscillator(
  long*  pHighOscillator
);

Parameters

pHighOscillator

[out] Receive the high oscillator frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::get_InputRange

The get_InputRange method retrieves an integer indicating which option or switch contains the requested signal source.

Syntax

HRESULT get_InputRange(
  long*  pInputRange
);

Parameters

pInputRange

[out] Specifies the address of a long integer to receive the integer value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::get_LNBSwitch

The get_LNBSwitch method retrieves the LNB switch.

Syntax

HRESULT get_LNBSwitch(
  long*  pLNBSwitch
);

Parameters

pLNBSwitch

[out] Receives the LNB switch frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::get_LowOscillator

The get_LowOscillator method retrieves the low oscillator frequency.

Syntax

HRESULT get_LowOscillator(
  long*  pLowOscillator
);

Parameters

pLowOscillator

[out] Receives the low oscillator frequency. in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::get_SpectralInversion

The get_SpectralInversion method retrieves an integer indicating the spectral inversion.

Syntax

HRESULT get_SpectralInversion(
  long*  pSpectralInversion
);

Parameters

pSpectralInversion

[out] Specifies the address of a long integer to receive the integer value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::put_HighOscillator

The put_HighOscillator method sets the high oscillator frequency.

Syntax

HRESULT put_HighOscillator(
  long  HighOscillator
);

Parameters

HighOscillator

[in] Specifies the high oscillator frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::put_InputRange

The put_InputRange method sets a value indicating which option or switch contains the requested signal source.

Syntax

HRESULT put_InputRange(
  long  InputRange
);

Parameters

InputRange

[in] Specifies a value indicating which option or switch contains the requested signal source as a long integer.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::put_LNBSwitch

The put_LNBSwitch method sets the LNB switch frequency.

Syntax

HRESULT put_LNBSwitch(
  long  LNBSwitch
);

Parameters

LNBSwitch

[in] Specifies the LNB switch frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::put_LowOscillator

The put_LowOscillator method sets the low oscillator frequency.

Syntax

HRESULT put_LowOscillator(
  long  LowOscillator
);

Parameters

LowOscillator

[in] Specifies the low oscillator frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBSTuningSpace::put_SpectralInversion

The put_SpectralInversion method sets a value indicating the spectral inversion.

Syntax

HRESULT put_SpectralInversion(
  long  SpectralInversion
);

Parameters

SpectralInversion

[in] Specifies a value indicating the spectral inversion as a long integer.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBSTuningSpace Interface


IDVBTLocator Interface

The IDVBTLocator interface is implemented on the DVBTLocator object. It provides methods to enable a tuner to acquire a terrestrial DVB (DVB-T) transport stream. The data types are defined in Bdatypes.h. Locator data is meant for consumption by the BDA hardware drivers. Applications do not need to interpret any of this data except perhaps for some debugging purposes.

Locators can be created dynamically when the tune request is created, by a loader that has access to the necessary information about the tuning space, or a default locator can be installed when the tuning space is first installed, and the loader can use the default locator when creating tune requests. Applications do not need to use any of the Locator interfaces unless they are creating tune requests. All Locator objects also support IPersistPropertyBag.

In addition to the methods inherited from ILocator, the IDVBTLocator interface exposes the following methods.

Method | Description
get_Bandwidth | Retrieves the bandwidth of the frequency in megahertz, usually 7 or 8.
get_Guard | Retrieves the guard interval.
get_HAlpha | Retrieves the hierarchy alpha.
get_LPInnerFEC | Retrieves the inner FEC type of the low-priority stream.
get_LPInnerFECRate | Retrieves the inner FEC rate of the low-priority stream.
get_Mode | Receives the transmission mode.
get_OtherFrequencyInUse | Indicates whether the frequency is being used by another DVB-T broadcaster.
put_Bandwidth | Sets the bandwidth of the frequency in megahertz, usually 7 or 8.
put_Guard | Sets the guard interval.
put_HAlpha | Sets the hierarchy alpha.
put_LPInnerFEC | Sets the inner FEC type of the low-priority stream.
put_LPInnerFECRate | Sets the inner FEC rate of the low-priority stream.
put_Mode | Sets the transmission mode.
put_OtherFrequencyInUse | Specifies whether the frequency is being used by another DVB-T broadcaster.


IDVBTLocator::get_Bandwidth

The get_Bandwidth method retrieves the bandwidth of the frequency.

Syntax

HRESULT get_Bandwidth(
  long*  pBandWidthVal
);

Parameters

pBandWidthVal

[out] Pointer to a variable receives the bandwidth, in megahertz (MHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The bandwidth is determined by the bandwidth field in the DVB terrestrial delivery system descriptor, as defined in EN 300 468. Valid values are 7 or 8.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_Guard

The get_Guard method retrieves the guard interval.

Syntax

HRESULT get_Guard(
  GuardInterval*  pGI
);

Parameters

pGI

[out] Pointer to a variable that receives a member of the GuardInterval enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_HAlpha

The get_HAlpha method retrieves the hierarchy alpha.

Syntax

HRESULT get_HAlpha(
  HierarchyAlpha*  pAlpha
);

Parameters

pAlpha

[out] Pointer to a variable that receives a member of the HierarchyAlpha enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_LPInnerFEC

The get_LPInnerFEC method retrieves the inner FEC type of the low-priority stream.

Syntax

HRESULT get_LPInnerFEC(
  FECMethod*  pFEC
);

Parameters

pFEC

[out] Pointer to a variable that receives a member of the FECMethod enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_LPInnerFECRate

The get_LPInnerFECRate method retrieves the inner FEC rate of the low-priority stream.

Syntax

HRESULT get_LPInnerFECRate(
  BinaryConvolutionCodeRate*  pFEC
);

Parameters

pFEC

[out] Pointer to a variable that receives a member of the BinaryConvolutionCodeRate enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_Mode

The get_Mode method receives the transmission mode.

Syntax

HRESULT get_Mode(
  TransmissionMode*  pmode
);

Parameters

pmode

[out] Pointer to a variable that receives a member of the TransmissionMode enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::get_OtherFrequencyInUse

The get_OtherFrequencyInUse method indicates whether the frequency is being used by another DVB-T broadcaster.

Syntax

HRESULT get_OtherFrequencyInUse(
  VARIANT_BOOL*  pOtherFrequencyInUseVal
);

Parameters

pOtherFrequencyInUseVal

[out] Pointer to a variable that receives that value VARIANT_TRUE if the frequency is being used by another DVB-T broadcaster, or VARIANT_FALSE otherwise.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_Bandwidth

The put_BandWidth method sets the bandwidth of the frequency.

Syntax

HRESULT put_Bandwidth(
  long  BandwidthVal
);

Parameters

BandwidthVal

[in] Specifies the bandwidth, in megahertz (MHz). The value should be taken from the bandwidth field in the terrestrial delivery system descriptor.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_Guard

The put_Guard method sets the guard interval.

Syntax

HRESULT put_Guard(
  GuardInterval  GI
);

Parameters

GI

[in] Variable of type GuardInterval that specifies the guard interval.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_HAlpha

The put_HAlpha method sets the hierarchy alpha.

Syntax

HRESULT put_HAlpha(
  HierarchyAlpha  Alpha
);

Parameters

Alpha

[in] Variable of type HierarchyAlpha that specifies the hierarchy alpha.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_LPInnerFEC

The put_LPInnerFEC method sets the inner FEC type of the low-priority stream.

Syntax

HRESULT put_LPInnerFEC(
  FECMethod  FEC
);

Parameters

FEC

[in] Variable of type FECMethod that specifies the FEC type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_LPInnerFECRate

The put_LPInnerFECRate method sets the inner FEC rate of the low-priority stream.

Syntax

HRESULT put_LPInnerFECRate(
  BinaryConvolutionCodeRate  FEC
);

Parameters

FEC

[in] Variable of type BinaryConvolutionCodeRate that specifies the rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_Mode

The put_Mode method sets the transmission mode.

Syntax

HRESULT put_Mode(
  TransmissionMode  mode
);

Parameters

mode

[in] Specifies the transmission mode as a member of the TransmissionMode enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTLocator::put_OtherFrequencyInUse

The put_OtherFrequencyInUse method specifies whether the frequency is being used by another DVB-T broadcaster.

Syntax

HRESULT put_OtherFrequencyInUse(
  VARIANT_BOOL  OtherFrequencyInUseVal
);

Parameters

OtherFrequencyInUseVal

[in] Specify VARIANT_TRUE if the frequency is being used by another DVB-T broadcaster, or VARIANT_FALSE otherwise.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTLocator Interface


IDVBTuneRequest Interface

The IDVBTuneRequest interface is implemented on the DVBTuneRequest object. It provides methods for acquiring a transport stream, and a service on that stream, in tuning spaces with a DVB network type. This information is obtained by the Guide Store loader from the TIF, stored in the tune request, and ultimately used by the Network Provider to configure the MPEG-2 Demultiplexer so that the correct packets are decoded and passed on to the downstream filters.

In addition to the methods inherited from ITuneRequest, the IDVBTuneRequest interface exposes the following methods.

Method | Description
get_ONID | Retrieves the original network ID.
get_SID | Sets the service ID.
get_TSID | Retrieves the transport stream ID.
put_ONID | Sets the original network ID.
put_SID | Retrieves the service ID.
put_TSID | Sets the transport stream ID.


IDVBTuneRequest::get_ONID

The get_ONID method retrieves the original network ID.

Syntax

HRESULT get_ONID(
  long*  ONID
);

Parameters

ONID

[out] Pointer to a variable of type long that receives the original network ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuneRequest::get_SID

The get_SID method retrieves the service ID for the network.

Syntax

HRESULT get_SID(
  long*  pSID
);

Parameters

pSID

[out] Pointer to a variable of type long that receives the service ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuneRequest::get_TSID

The get_TSID method retrieves the transport stream ID.

Syntax

HRESULT get_TSID(
  long*  pTSID
);

Parameters

pTSID

[out] Pointer to a variable of type long that receives the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuneRequest::put_ONID

The put_ONID method sets the original network ID.

Syntax

HRESULT put_ONID(
  long  ONID
);

Parameters

ONID

[in] Variable of type long that specifies the original network ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuneRequest::put_SID

The put_SID method sets the service ID.

Syntax

HRESULT put_SID(
  long  SID
);

Parameters

SID

[in] Variable of type long that specifies the service ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuneRequest::put_TSID

The put_TSID method sets the transport stream ID.

Syntax

HRESULT put_TSID(
  long  TSID
);

Parameters

TSID

[in] Variable of type long that specifies the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuneRequest Interface


IDVBTuningSpace Interface

The IDVBTuningSpace interface is implemented on the DVBTuningSpace object.

Note New applications should use the IDVBTuningSpace2 interface, which inherits IDVBTuningSpace and adds additional methods.

In addition to the methods inherited from ITuningSpace, the IDVBTuningSpace interface exposes the following methods.

Method | Description
get_SystemType | Retrieves the DVB system type.
put_SystemType | Sets the DVB system type.


IDVBTuningSpace::get_SystemType

The get_SystemType method retrieves the system type.

Syntax

HRESULT get_SystemType(
  DVBSystemType*  pSysType
);

Parameters

pSysType

[out] Pointer to a variable of type DVBSystemType that receives the system type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuningSpace Interface


IDVBTuningSpace::put_SystemType

The put_SystemType method sets the system type.

Syntax

HRESULT put_SystemType(
  DVBSystemType  SysType
);

Parameters

SysType

[in] Variable of type DVBSystemType that specifies the system type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuningSpace Interface


IDVBTuningSpace2 Interface

The IDVBTuningSpace2 interface is implemented on the DVBTuningSpace object. It provides methods for working with tuning spaces with a network type of DVB.

In addition to the methods inherited from IDVBTuningSpace, the IDVBTuningSpace2 interface exposes the following methods.

Method | Description
get_NetworkID | Retrieves the NetworkID of the DVB system.
put_NetworkID | Sets the NetworkID of the DVB system


IDVBTuningSpace2::get_NetworkID

The get_NetworkID method retrieves the Network ID of the DVB system.

Syntax

HRESULT get_NetworkID(
  long*  pNetworkID
);

Parameters

pNetworkID

[out] Specifies the address of a long integer to receive the NetworkID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuningSpace2 Interface


IDVBTuningSpace2::put_NetworkID

The put_NetworkID method sets the Network ID of the DVB system.

Syntax

HRESULT get_NetworkID(
  long  NetworkID
);

Parameters

NetworkID

[in] Specifies the NetworkID as a long integer.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IDVBTuningSpace2 Interface


IEnumComponents Interface

The IEnumComponents interface provides a standard COM enumeration object for the components (substreams) in a given program stream. C++ applications should use this interface to enumerate components, rather than using the IComponents collection interface, which is intended for Automation clients.

In addition to the methods inherited from IUnknown, the IEnumComponents interface exposes the following methods.

Method | Description
Clone | Create a new copy of the entire collection.
Next | Retrieves the next n elements in the collection.
Reset | Reset the enumerator to the beginning of the collection.
Skip | Skip the specified element in the collection without retrieving it.


IEnumComponents::Clone

The Clone method creates a new copy of the entire collection.

Syntax

HRESULT Clone(
  IEnumComponents**  ppEnum
);

Parameters

ppEnum

[out] Address of an IEnumComponents interface pointer that will be set to the new collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The application must release this new collection when done with it.

See Also

  • IEnumComponents Interface


IEnumComponents::Next

The Next method retrieves the next n elements in the collection.

Syntax

HRESULT Next(
  ULONG  celt,
  IComponent**  pprgelt,
  ULONG*  pceltFetched
);

Parameters

celt

[in] Variable of type ULONG that specifies the number of elements to retrieve.

pprgelt

[out, size_is(celt), length_is(pceltFetched)] Address of an array of IComponent interface pointers that will receive the retrieved Component objects.

pceltFetched

[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponents Interface


IEnumComponents::Reset

The Reset method resets the enumerator to the beginning of the collection.

Syntax

HRESULT Reset();

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponents Interface


IEnumComponents::Skip

The Skip method skips the specified element in the collection without retrieving it.

Syntax

HRESULT Skip(
  ULONG  celt
);

Parameters

celt

[in] Variable of type ULONG specifying the element to skip.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponents Interface


IEnumComponentTypes Interface

The IEnumComponentTypes interface is implemented on a standard COM collection of ComponentType objects associated with a given broadcast stream, and returned through a call to IComponentTypes::EnumComponentTypes.

In addition to the methods inherited from IUnknown, the IEnumComponentTypes interface exposes the following methods.

Method | Description
Clone | Creates a new copy of the entire collection and all its sub-objects.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips the element at the specified index.


IEnumComponentTypes::Clone

The Clone method creates a new copy of the collection and all its sub-objects.

Syntax

HRESULT Clone(
    IEnumComponentTypes** ppEnum
    );

Parameters

ppEnum

[out] Address of an IEnumComponentTypes interface pointer that will be set to the returned collection object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponentTypes Interface


IEnumComponentTypes::Next

The Next method retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG celt,
    IComponentType** pprgelt,
    ULONG* pceltFetched
    );

Parameters

celt

[in] The number of elements to retrieve.

pprgelt

[out, size_is(celt), length_is(*pceltFetched)] Address of an array of IComponentType interface pointers that will receive the returned ComponentType objects.

pceltFetched

[out] Pointer to a variable of type ULONG that will receive the number of elements actually retrieved.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponentTypes Interface


IEnumComponentTypes::Reset

The Reset method moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponentTypes Interface


IEnumComponentTypes::Skip

The Skip method skips the element at the specified index.

Syntax

HRESULT Skip(
    ULONG celt
    );

Parameters

celt

[in] Index of the element to skip.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumComponentTypes Interface


IEnumTuningSpaces Interface

The IEnumTuningSpaces interface is implemented on a standard COM collection of tuning space objects and is obtained through various ITuningSpaceContainer.

In addition to the methods inherited from IUnknown, the IEnumTuningSpaces interface exposes the following methods.

Method | Description
Clone | Creates a new copy of the collection and all its sub-objects.
Next | Retrieves the next n element in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips the specified element in the collection.


IEnumTuningSpaces::Clone

The Clone method creates a new copy of the collection and all its sub-objects.

Syntax

HRESULT Clone(
    IEnumTuningSpaces** ppEnum
    );

Parameters

ppEnum

[out] Address of an IEnumTuningSpaces interface pointer that will receive the returned interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumTuningSpaces Interface


IEnumTuningSpaces::Next

The Next method retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG celt,
    ITuningSpace** pprgelt,
    ULONG* pceltFetched
    );

Parameters

celt

[in] The number of elements to retrieve.

pprgelt

[out, size_is(celt), length_is(*pceltFetched)] Address of an array of ITuningSpace interface pointers that will receive the retrieved Tuning Space objects.

pceltFetched

[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Values

Returns S_OK if successful. This method will succeed even if celt is zero. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumTuningSpaces Interface


IEnumTuningSpaces::Reset

The Reset method moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumTuningSpaces Interface


IEnumTuningSpaces::Skip

The Skip method skips the specified element in the collection.

Syntax

HRESULT Skip(
    ULONG celt
    );

Parameters

celt

[in] The index of the element to skip.

Return Values

Returns S_OK if successful. This method will succeed even if celt is zero. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IEnumTuningSpaces Interface


ILanguageComponentType Interface

The ILanguageComponentType interface is implemented on LanguageComponentType objects. It provides methods that define the language of the stream content. Not all streams have a language component.

In addition to the methods inherited from IComponentType, the ILanguageComponentType interface exposes the following methods.

Method | Description
get_LangID | Retrieves the language of the stream content.
put_LangID | Sets the language of the stream content.


ILanguageComponentType::get_LangID

The get_LangID method retrieves the LCID that identifies the language.

Syntax

HRESULT get_LangID(
    long* pLangID
);

Parameters

pLangID

[out] Pointer to a variable that receives the LCID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

pLangID is a pointer to a Win32 LCID. Use this method to determine the language of an audio stream. Use the IComponent::get_DescLangID to determine the language of the text description of the stream.

See Also

  • ILanguageComponentType Interface
  • ILanguageComponentType::put_LangID


ILanguageComponentType::put_LangID

The put_LangID method specifies the LCID that identifies the language

Syntax

HRESULT put_LangID(
    long LangID
);

Parameters

LangID

[in] Specifies the LCID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

LangID is a Win32 LCID. Use this method to set the language of an audio stream, for example when creating a new entry for the Guide Store database. Use the IComponent::put_DescLangID method to specify the language of the text description of the stream.

See Also

  • ILanguageComponentType Interface
  • ILanguageComponentType::get_LangID


ILocator Interface

The ILocator base class interface is implemented (through its derived interfaces such as IATSCLocator) on Locator objects that contain tuning information about the tuning space. The base interface is never used directly, but only through the derived interfaces that are specific for a given network type. Locator objects can be created dynamically by Guide Store Loaders that have the necessary information about the tuning space, or a default locator for a tuning space can be installed by the third party who installs the tuning space. In any case, applications never create or examine locators except in certain testing or debugging scenarios. All Locator objects also support IPersistPropertyBag.

In addition to the methods inherited from IUnknown, the ILocator interface exposes the following methods.

Method | Description
Clone | Creates a copy of the Locator.
get_CarrierFrequency | Retrieves the frequency of the RF signal.
get_InnerFEC | Retrieves the type of inner forward error correction that is used.
get_InnerFECRate | Retrieves the inner FEC rate.
get_Modulation | Retrieves the modulation type.
get_OuterFEC | Retrieves the type of outer forward error correction that is used.
get_OuterFECRate | Sets the outer FEC rate.
get_SymbolRate | Gets the QPSK symbol rate.
put_CarrierFrequency | Sets the frequency of the RF signal.
put_InnerFEC | Sets the type of inner forward error correction that is used.
put_InnerFECRate | Sets the inner FEC rate.
put_Modulation | Sets the modulation type.
put_OuterFEC | Sets the type of inner forward error correction that is used.
put_OuterFECRate | Sets the outer FEC rate.
put_SymbolRate | Sets the QPSK symbol rate.


ILocator::Clone

The Clone method creates a copy of the Locator.

Syntax

HRESULT Clone(
    ILocator** ppNewLocator
    );

Parameters

ppNewLocator

[out] Address of an ILocator interface pointer that will receive the returned interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_CarrierFrequency

The get_CarrierFrequency method retrieves the frequency of the RF signal.

Syntax

HRESULT get_CarrierFrequency(
    long* pFrequency
    );

Parameters

pFrequency

[out] Pointer to a variable that receives the frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_InnerFEC

The get_InnerFEC method retrieves the type of inner forward error correction that is used.

Syntax

HRESULT get_InnerFEC(
    FECMethod* pFEC
    );

Parameters

pFEC

[out] Pointer to a variable of type FECMethod that receives the inner forward FEC.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_InnerFECRate

The get_InnerFECRate method retrieves the inner FEC rate.

Syntax

HRESULT get_InnerFECRate(
    BinaryConvolutionCodeRate* pFEC
    );

Parameters

pFEC

[out] Pointer to a variable of type BinaryConvolutionCodeRate that receives the inner FEC rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_Modulation

The get_Modulation method retrieves the modulation type.

Syntax

HRESULT get_Modulation(
    ModulationType* pModulation
    );

Parameters

pModulation

[out] Pointer to a variable that receives the modulation type, as a member of the ModulationType enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

See put_Modulation for the definition of ModulationType.

See Also

  • ILocator Interface


ILocator::get_OuterFEC

The get_OuterFEC method retrieves the type of outer forward error correction that is used.

Syntax

HRESULT get_OuterFEC(
    FECMethod* pFEC
    );

Parameters

pFEC

[out] Pointer to a variable of type FECMethod that receives the outer forward FEC.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_OuterFECRate

The get_OuterFECRate method retrieves the outer FEC rate.

Syntax

HRESULT get_OuterFECRate(
    BinaryConvolutionCodeRate* pFEC
    );

Parameters

pFEC

[out] Pointer to a variable of type BinaryConvolutionCodeRate that receives the outer FEC rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::get_SymbolRate

The get_SymbolRate method retrieves the QPSK symbol rate.

Syntax

HRESULT get_SymbolRate(
    long* pRate
    );

Parameters

pRate

[out] Pointer to a variable of type long that receives the QPSK symbol rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • ILocator Interface


ILocator::put_CarrierFrequency

The put_CarrierFrequency method sets the frequency of the RF signal.

Syntax

HRESULT put_CarrierFrequency(
    long Frequency
    );

Parameters

Frequency

[in] Specifies the frequency, in kilohertz (kHz).

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_InnerFEC

The put_InnerFEC method sets the type of inner forward error correction that is used.

Syntax

HRESULT put_InnerFEC(
    FECMethod FEC
    );

Parameters

FEC

[in] Variable of type FECMethod that specifies the inner FEC.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_InnerFECRate

The put_InnerFECRate method sets the inner FEC rate.

Syntax

HRESULT put_InnerFECRate(
    BinaryConvolutionCodeRate FEC
    );

Parameters

FEC

[in] Variable of type BinaryConvolutionCodeRate that specifies the inner FEC rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_Modulation

The put_Modulation method sets the modulation type.

Syntax

HRESULT put_Modulation(
    ModulationType Modulation
    );

Parameters

Modulation

[in] Specifies the modulation type, as a member of the ModulationType enumeration.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_OuterFEC

The put_OuterFEC method sets the type of outer forward error correction that is used.

Syntax

HRESULT put_OuterFEC(
    FECMethod FEC
    );

Parameters

FEC

[in] Variable of type FECMethod that specifies the outer forward error correction.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_OuterFECRate

The put_OuterFECRate method sets the outer FEC rate.

Syntax

HRESULT put_OuterFECRate(
    BinaryConvolutionCodeRate FEC
    );

Parameters

FEC

[in] Variable of type BinaryConvolutionCodeRate that specifies the outer FEC rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ILocator Interface


ILocator::put_SymbolRate

The put_SymbolRate method sets the QPSK symbol rate.

Syntax

HRESULT put_SymbolRate(
    long Rate
    );

Parameters

Rate

[in] Variable of type long that specifies the QPSK symbol rate.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • ILocator Interface


IMPEG2Component Interface

The IMPEG2Component interface contains methods for getting and setting properties that describe an MPEG2 elementary stream. These properties are set by the TIF or Guide Store loader based on data in the transport stream tables. After the tune request is retrieved from the Guide Store and submitted either to the Video Control or directly to the Network Provider, these properties are used by the Network Provider and MPEG-2 Demultiplexer to acquire the specified substream and pass it to the downstream filters.

In addition to the methods inherited from IComponent, the IMPEG2Component interface exposes the following methods.

Method | Description
get_PCRPID | Returns the MPEG2 Packet ID (PID) for this substream's time stamps.
get_PID | Get the packet identifier for this substream.
get_ProgramNumber | Gets the program number, which provides a reverse lookup to PAT.
put_PCRPID | Sets the MPEG2 Packet ID for this substream's time stamps.
put_PID | Set the packet identifier for this substream.
put_ProgramNumber | Sets the program number, which provides a reverse lookup to PAT.


IMPEG2Component::get_PCRPID

The get_PCRPID method returns the packet identifier (PID) for the packets that contain the PCR for this substream.

Syntax

HRESULT get_PCRPID(
    long* pPCRPID
    );

Parameters

pPCRPID

[out] Pointer to a variable that receives the PCR PID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2Component::get_PID

The get_PID method returns the packet identifier (PID) for this substream.

Syntax

HRESULT get_PID(
    long* pPID
    );

Parameters

pPID

[out] Pointer to a variable that receives the PID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2Component::get_ProgramNumber

The get_ProgramNumber method returns the program number for this substream.

Syntax

HRESULT get_ProgramNumber(
    long* pProgramNumber
    );

Parameters

pProgramNumber

[out] Pointer to a variable that receives the program number.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2Component::put_PCRPID

The put_PCRPID method sets the packet identifier (PID) for the packets that contain the PCR for this substream.

Syntax

HRESULT put_PCRPID(
    long PCRPID
    );

Parameters

PCRPID

[in] Specifies the PCR PID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2Component::put_PID

The put_PID method sets the packet identifier (PID) for this substream.

Syntax

HRESULT put_PID(
    long PID
    );

Parameters

PID

[in] Specifies the PID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2Component::put_ProgramNumber

The put_ProgramNumber method sets the program number for this substream.

Syntax

HRESULT put_ProgramNumber(
    long ProgramNumber
    );

Parameters

ProgramNumber

[in] Specifies the program number.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2Component Interface


IMPEG2ComponentType Interface

The IMPEG2ComponentType interface is implemented on MPEG2ComponentType objects. It enables applications to set and retrieve information about MPEG2 stream types.

In addition to the methods inherited from ILanguageComponentType, the IMPEG2ComponentType interface exposes the following methods.

Method | Description
get_StreamType | Retrieves the stream type.
put_StreamType | Sets the stream type.


IMPEG2ComponentType::get_StreamType

The get_StreamType method retrieves the stream type.

Syntax

HRESULT get_StreamType(
    MPEG2StreamType* pMP2StreamType
    );

Parameters

pMP2StreamType

[out] Pointer to a variable of type MPEG2StreamType that receives the stream type value.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2ComponentType Interface


IMPEG2ComponentType::put_StreamType

The put_StreamType method sets the MPEG2 stream type.

Syntax

HRESULT put_StreamType(
    MPEG2StreamType MP2StreamType
    );

Parameters

MP2StreamType

[in] Variable of type MPEG2StreamType that specifies the stream type.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2ComponentType Interface


IMPEG2TuneRequest Interface

This topic applies to Windows XP Service Pack 1 only.

The IMPEG2TuneRequest interface represents a tune request for a basic MPEG-2 transport stream containing the minimal tables.

Use the IMPEG2TuneRequestFactory::CreateTuneRequest method to obtain this interface. It returns the minimal MPEG-2 tune request for a specified tuning space. To create a full tune request, use the CreateTuneRequest method provided by one of the tuning space objects.

In addition to the methods inherited from ITuneRequest, the IMPEG2TuneRequest interface exposes the following methods.

Method | Description
get_ProgNo | Retrieves the program number ID.
get_TSID | Retrieves the transport stream ID.
put_ProgNo | Sets the program number ID.
put_TSID | Sets the transport stream ID.


IMPEG2TuneRequest::get_ProgNo

This topic applies to Windows XP Service Pack 1 only.

The get_ProgNo method retrieves the program number ID.

Syntax

HRESULT get_ProgNo(
    long *ProgNo
);

Parameters

ProgNo

[out] Pointer to a variable that receives the program number ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2TuneRequest Interface


IMPEG2TuneRequest::get_TSID

This topic applies to Windows XP Service Pack 1 only.

The get_TSID method retrieves the transport stream ID.

Syntax

HRESULT get_TSID(
    long *TSID
);

Parameters

TSID

[out] Pointer to a variable that receives the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2TuneRequest Interface


IMPEG2TuneRequest::put_ProgNo

This topic applies to Windows XP Service Pack 1 only.

The put_ProgNo method sets the program number ID.

Syntax

HRESULT put_ProgNo(
    long ProgNo
);

Parameters

ProgNo

[in] Specifies the program number ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2TuneRequest Interface


IMPEG2TuneRequest::put_TSID

This topic applies to Windows XP Service Pack 1 only.

The put_TSID method sets the transport stream ID.

Syntax

HRESULT put_TSID(
    long TSID
);

Parameters

TSID

[in] Specifies the transport stream ID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2TuneRequest Interface


IMPEG2TuneRequestFactory Interface

This topic applies to Windows XP Service Pack 1 only.

The IMPEG2TuneRequestFactory interface creates a tune request for a basic MPEG-2 transport stream containing the minimal tables. To obtain this interface, call CoCreateInstance with the class identifier CLSID_MPEG2TuneRequestFactory.

In addition to the methods inherited from IDispatch, the IMPEG2TuneRequestFactory interface exposes the following method.

Method | Description
CreateTuneRequest | Creates the minimal MPEG-2 tune request for a specified tuning space

Remarks

To create a full tune request, use the CreateTuneRequest method provided by one of the tuning space objects.


IMPEG2TuneRequestFactory::CreateTuneRequest

This topic applies to Windows XP Service Pack 1 only.

The CreateTuneRequest method creates the minimal MPEG-2 tune request for a specified tuning space.

Syntax

HRESULT CreateTuneRequest(
    ITuningSpace *TuningSpace,
    IMPEG2TuneRequest **TuneRequest
);

Parameters

TuningSpace

[in] Pointer to the ITuningSpace interface of the tuning space.

TSID

[in] Address of a variable that receives a pointer to the IMPEG2TuneRequest interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • IMPEG2TuneRequestFactory Interface


ITuneRequest Interface

The ITuneRequest interface is the base interface for all tune requests. Each tune request object supports a network-specific interface that derives from ITuneRequest, such as IATSCChannelTuneRequest or IDVBTuneRequest.

This interface is used by any application that creates tune requests, such as a Guide Store loader. A tune request must be associated with a specific network type. When a tune request is submitted, the derived interfaces are used by the Network Provider to extract the tuning information required by the hardware. All tune request objects also support IPersistPropertyBag, which enables them to be persisted in some type of third-party storage mechanism.

In addition to the methods inherited from IDispatch, the ITuneRequest interface exposes the following methods.

Method | Description
Clone | Returns a new copy of this tune request.
get_Components | Retrieves the components contained in this tune request.
get_Locator | Called from the Network Provider to get the ILocator object associated with the requested broadcast.
get_TuningSpace | Retrieves the tuning space that was used to create this tune request.
put_Locator | Called from the Network Provider to set the ILocator object associated with the requested broadcast.


ITuneRequest::get_TuningSpace

The get_TuningSpace method retrieves the tuning space that was used to create this tune request.

Syntax

HRESULT get_TuningSpace(
    ITuningSpace** ppTuningSpace
    );

Parameters

ppTuningSpace

[out] Address of an ITuningSpace interface pointer that will be set to the returned object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

You must first access the tuning space in order to obtain the default locator and the default preferred component types.

See Also

  • ITuneRequest Interface


ITuneRequest::get_Components

The get_Components method retrieves the components contained in this tune request.

Syntax

HRESULT get_Components(
    IComponents** ppComponents
);

Parameters

ppComponents

[out] Address of a variable that receives an IComponents interface pointer.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

A tune request always contains a collection of components, but the collection can be empty. If the component information is present in the transport stream tables, a Guide Store loader can obtain the information from the TIF and include it in the tune request at the time it creates it.

If the method succeeds, the IComponents interface has an outstanding reference count. The caller must release the interface.

See Also

  • ITuneRequest Interface


ITuneRequest::Clone

The Clone method returns a new copy of this tune request.

Syntax

HRESULT Clone(
    ITuneRequest** ppNewTuneRequest
    );

Parameters

ppNewTuneRequest

[out] Address of an ITuneRequest interface pointer that will be set to the new object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method performs a "deep copy" of the object; in other words it copies all sub-objects as well, including Components, LanguageComponentType objects, and so on.

See Also

  • ITuneRequest Interface


ITuneRequest::get_Locator

The get_Locator method is called from the Network Provider to get the ILocator object associated with the requested broadcast.

Syntax

HRESULT get_Locator(
    ILocator** ppLocator
    );

Parameters

ppLocator

[out] Address of an ILocator interface pointer that will be set to the new object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuneRequest Interface


ITuneRequest::put_Locator

The put_Locator method is called from the Network Provider to set the ILocator object associated with the requested broadcast.

Syntax

HRESULT put_Locator(
    ILocator* pLocator
    );

Parameters

pLocator

[in] Pointer to an ILocator interface that specifies the new locator.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuneRequest Interface


ITuningSpace Interface

The ITuningSpace interface provides the common functionality for all network-specific tuning spaces. Applications can obtain tuning spaces from the SystemTuningSpaces collection. A tuning space generally exposes an interface that inherits ITuningSpace, such as IATSCTuningSpace.

In addition to the methods inherited from IDispatch, the ITuningSpace interface exposes the following methods.

Method | Description
Clone | Creates a new copy of the tuning space.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) tune request.
EnumCategoryGUIDs | (Currently not implemented.) Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | (Currently not implemented.) Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_DefaultLocator | Retrieves the default locator for a tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_FrequencyMapping | Retrieves the frequency mapping previously created by the network provider.
get_FriendlyName | Retrieves the localized, user-friendly name of the tuning space.
get_NetworkType | Retrieves the network type of the tuning space as a BSTR.
get_UniqueName | Retrieves a unique name for the tuning space. Can be either a short name, or a GUID.
put__NetworkType | Sets the network type for this tuning space as a CLSID.
put_DefaultLocator | Sets the default locator for a tuning space.
put_DefaultPreferredComponentTypes | Creates an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_FrequencyMapping | Creates a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.
put_FriendlyName | Sets the localized, user-friendly name of the tuning space.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
put_UniqueName | Sets a unique name for the tuning space. Can be either a short name, or a GUID.


ITuningSpace::Clone

The Clone method creates a new copy of the tuning space.

Syntax

HRESULT Clone(
    ITuningSpace** ppNewTS
    );

Parameters

ppNewTS

[out] Address of a variable that receives a pointer to the ITuningSpace interface of the new tuning space object. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) tune request.

Syntax

HRESULT CreateTuneRequest(
    ITuneRequest** ppTuneRequest
    );

Parameters

ppTuneRequest

[out] Address of a variable that receives a pointer to the ITuneRequest interface of the new tune request object. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

You can query the returned ITuneRequest pointer for derived interfaces. For more information, see the reference pages for the individual tuning space objects, which are listed in the topic Microsoft Unified Tuning Model Objects.

See Also

  • ITuningSpace Interface


ITuningSpace::EnumCategoryGUIDs

Currently not implemented.

The EnumCategoryGUIDs method creates an enumerator for the DirectShow category of filters that support the tuning space.

Syntax

HRESULT EnumCategoryGUIDs(
    IEnumGUID** ppEnum
    );

Parameters

ppEnum

[out] Address of an IEnumGUID interface pointer that receives the returned enumeration object.

Return Values

Returns E_NOTIMPL.

Remarks

This method is hidden from automation languages.

See Also

  • ITuningSpace Interface


ITuningSpace::EnumDeviceMonikers

Currently not implemented.

The EnumDeviceMonikers method creates an enumerator of device monikers representing the tuner filters that support this tuning space.

Syntax

HRESULT EnumDeviceMonikers(
    IEnumMoniker** ppEnum
    );

Parameters

ppEnum

[out] Address of an IEnumMoniker interface pointer that receives the returned enumeration object.

Return Values

Returns E_NOTIMPL.

Remarks

This method is hidden from automation languages.

See Also

  • ITuningSpace Interface


ITuningSpace::get__NetworkType

The get_NetworkType method retrieves the network type for this tuning space.

Syntax

HRESULT get__NetworkType(
    GUID* pNetworkTypeGuid
    );

Parameters

pNetworkTypeGuid

[out] Pointer to a variable that receives the network type GUID. This GUID corresponds to the CLSID of the Network Provider for the tuning space. For some tuning spaces, the network type is GUID_NULL, which means the tuning space does not use a Network Provider filter.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::get_CLSID

The get_CLSID method gets the CLSID of the tuning space as a BSTR.

Syntax

HRESULT get_CLSID(
    BSTR* pSpaceCLSID
    );

Parameters

pSpaceCLSID

[out] Pointer to a variable that receives a string representation of the tuning space CLSID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method provides script access to the IPersist::GetClassID method.

The returned CLSID represents the COM object that implements this tuning space. The CLSID is not guaranteed to be unique to this tuning space, however, because the same object may implement several tuning spaces.

See Also

  • ITuningSpace Interface


ITuningSpace::get_DefaultLocator

The get_DefaultLocator method retrieves the default locator for this tuning space.

Syntax

HRESULT get_DefaultLocator(
    ILocator** ppLocatorVal
    );

Parameters

ppLocatorVal

[out] Address of a variable that receives a pointer to ILocator interface. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The tuning space might not have a default locator. It is the application's responsibility to provide a default locator for the tuning space if needed.

If the tuning space does not have a default locator, this method succeeds but returns the value NULL in the ppLocatorVal parameter. Check for a NULL value before attempting to dereference the pointer.

See Also

  • ITuningSpace Interface
  • ITuningSpace::put_DefaultLocator


ITuningSpace::get_DefaultPreferredComponentTypes

The get_DefaultPreferredComponentTypes method returns an list of the default preferred component types for this tuning space.

Syntax

HRESULT get_DefaultPreferredComponentTypes(
    IComponentTypes** ppComponentTypes
    );

Parameters

ppComponentTypes

[out] Address of a variable that receives an IComponentTypes interface pointer. Use this interface to enumerate the component types. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

A component is a stream within the program. An example of a preferred component type would be an audio stream in English. When multiple components are available, the Tuner attempts to play the preferred ones first.

If the tuning space does not have any default preferred types, this method succeeds but returns the value NULL in the ppComponentTypes parameter. Check for a NULL value before attempting to dereference the pointer.

See Also

  • ITuningSpace Interface


ITuningSpace::get_FrequencyMapping

The get_FrequencyMapping method retrieves the frequency mapping previously created by the network provider by a call to put_FrequencyMapping.

Syntax

HRESULT get_FrequencyMapping(
    BSTR* pMapping
    );

Parameters

pMapping

[out] Pointer to a variable that receives the frequency mappings created by the Network Provider filter.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The returned BSTR is treated as a binary blob. It is expected to contain embedded NULL values, and it may be formatted internally by the BDA Network Provider.

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • ITuningSpace Interface


ITuningSpace::get_FriendlyName

The get_FriendlyName method retrieves the localized, user-friendly name of the tuning space.

Syntax

HRESULT get_FriendlyName(
    BSTR* pName
);

Parameters

pName

[out] Pointer to a variable receives the user-friendly name.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • ITuningSpace Interface


ITuningSpace::get_NetworkType

The get_NetworkType method retrieves the network type of the tuning space as a BSTR.

This method is intended for Automation clients, because it returns the CLSID as a BSTR. C++ applications can use the ITuningSpace::get__NetworkType method instead, which returns a GUID value

Syntax

HRESULT get_NetworkType(
    BSTR* pNetworkTypeGuid
    );

Parameters

pNetworkTypeGuid

[out] Pointer to a variable that receives a string containing the network type GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • ITuningSpace Interface


ITuningSpace::get_UniqueName

The get_UniqueName method retrieves the unique name of the tuning space.

Syntax

HRESULT get_UniqueName(
    BSTR* pName
);

Parameters

pName

[out] Pointer to a variable that receives the unique name.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The caller must release the returned BSTR by calling SysFreeString.

See Also

  • ITuningSpace Interface


ITuningSpace::put__NetworkType

The put_NetworkType method specifies the network type of the tuning space.

Syntax

HRESULT put__NetworkType(
    REFCLSID NetworkTypeGuid
    );

Parameters

NetworkTypeGuid

[in] Specifies the network type GUID. This GUID corresponds to the CLSID of the Network Provider for the tuning space. The value GUID_NULL means the tuning space does not use a Network Provider filter.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::put_DefaultLocator

The put_DefaultLocator method sets the default locator for this tuning space.

Syntax

HRESULT put_DefaultLocator(
    ILocator* pLocatorVal
    );

Parameters

pLocatorVal

[in] Pointer to the ILocator interface of the locator object.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

See ITuningSpace::get_DefaultLocator for more information about the default locator.

For DVB tuning spaces, the sytem type (cable, terrestrial, or satelite) of the tuning space must match the locator object. Otherwise, the method returns DISP_E_TYPEMISMATCH. For more information, see IDVBTuningSpace::put_SystemType.

See Also

  • ITuningSpace Interface


ITuningSpace::put_DefaultPreferredComponentTypes

The put_DefaultPreferredComponentTypes method specifies the default preferred component types for this tuning space.

Syntax

HRESULT put_DefaultPreferredComponentTypes(
    IComponentTypes* pNewComponentTypes
    );

Parameters

pNewComponentTypes

[in] Pointer to the IComponentTypes interface of the component types collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::put_FrequencyMapping

The put_FrequencyMapping method creates a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.

Syntax

HRESULT put_FrequencyMapping(
    BSTR Mapping
    );

Parameters

Mapping

[in] BSTR that contains the frequency mappings.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is used by the network provider to store a string that contains the frequency mappings.

See Also

  • ITuningSpace Interface


ITuningSpace::put_FriendlyName

The put_FriendlyName method sets the localized, user-friendly name of the tuning space.

Syntax

HRESULT put_FriendlyName(
    BSTR Name
);

Parameters

Name

[in] Specifies the user-friendly name.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::put_NetworkType

The put_NetworkType method specifies the network type of the tuning space as a BSTR.

This method is intended for Automation clients, because it specifies the CLSID as a BSTR. C++ applications can use the ITuningSpace::put__NetworkType method instead, which takes a GUID value.

Syntax

HRESULT put_NetworkType(
    BSTR NetworkTypeGuid
    );

Parameters

NetworkTypeGuid

[in] Contains the string representation of the network type GUID.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpace Interface


ITuningSpace::put_UniqueName

The put_UniqueName method sets a unique name for the tuning space.

Syntax

HRESULT put_UniqueName(
    BSTR Name
);

Parameters

Name

[in] Variable of type BSTR that specifies the unique name.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

If you attempt to add a new tuning space to the System Tuning Spaces collection, this property must be unique within the collection. For more information, see ITuningSpaceContainer::Add.

See Also

  • ITuningSpace Interface


ITuningSpaceContainer Interface

The ITuningSpaceContainer interface is implemented on the SystemTuningSpaces object. It provides access to all tuning spaces installed on the host system.

In addition to the methods inherited from IDispatch, the ITuningSpaceContainer interface exposes the following methods.

Method | Description
_TuningSpacesForCLSID | Retrieves a collection of tuning spaces that match the specified CLSID. (For use by C++ clients.)
Add | Adds a new persistent tuning space to the system.
FindID | Retrieves the ID of a specified tuning space within the collection.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
get_Count | Retrieves the number of tuning spaces currently available on the local system.
get_EnumTuningSpaces | Retrieves a collection of all tuning spaces available on the local system.
get_Item | Retrieves a tuning space with the specified ID.
get_MaxCount | Retrieves the maximum number of tuning spaces allowed on the system.
put_Item | Saves changes to an existing tuning space in the collection.
put_MaxCount | Sets the maximum number of tuning spaces allowed on the system.
Remove | Permanently removes a tuning space from the system.
TuningSpacesForCLSID | Retrieves a collection of tuning spaces that match the specified CLSID string. (For use by Automation clients.)
TuningSpacesForName | Retrieves a collection of tuning spaces that match the specified name.


ITuningSpaceContainer::_TuningSpacesForCLSID

The _TuningSpacesForCLSID method retrieves a collection of tuning spaces that match the specified CLSID.

Syntax

HRESULT _TuningSpacesForCLSID(
    REFCLSID SpaceCLSID,
    ITuningSpaces** ppTuningSpaces
);

Parameters

SpaceCLSID

[in] Specifies the CLSID of the tuning spaces to retrieve.

ppTuningSpaces

[out] Address of a variable that receives an ITuningSpaces interface pointer. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The CLSID represents the object that implements the tuning space. The same object may implement several related tuning spaces. For example, ATSC Digital Antenna and ATSC Digital Cable are both supported by the ATSCTuningSpace object (CLSID_ATSCTuningSpace).

This method matches against the CLSID returned by the ITuningSpace::get_CLSID method. The returned collection might be empty; call ITuningSpaces::get_Count to determine how many tuning spaces were returned.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::Add

The Add method adds a new persistent tuning space to the system.

Syntax

HRESULT Add(
    ITuningSpace* pTuningSpace,
    VARIANT* pNewIndex
    );

Parameters

pTuningSpace

[in] Pointer to the ITuningSpace interface of the new tuning space

pNewIndex

[out] Pointer to a variable of type VARIANT that receives the ID of the new tuning space within the current collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method adds a new tuning space to the collection. The collection object automatically persists the tuning space information.

The tuning space must have a unique name that does not clash with any of the tuning spaces already in the collection. To overwrite an existing tuning space, use the ITuningSpaceContainer::put_Item method.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::FindID

The FindID method retrieves the ID of a specified tuning space within the collection.

Syntax

HRESULT FindID(
    ITuningSpace* pTuningSpace,
    long* pID
);

Parameters

pTuningSpace

[in] Pointer to the ITuningSpace interface of the tuning space.

pID

[out] Pointer to a variable that receives the ID of the tuning space. The returned value is specific to this collection object (which represents the local system).

Return Values

Returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | The specified tuning space is not a member of this collection.
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::get__NewEnum

The get__NewEnum method supports For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT** ppNewEnum
    );

Parameters

ppNewEnum

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided to enable scripting and VB applications to iterate through the collection in a For...Each loop. C++ applications should use the ITuningSpaceContainer::get_EnumTuningSpaces method.

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::get_Count

The get_Count method retrieves the number of tuning spaces currently available on the local system.

Syntax

HRESULT get_Count(
    long* pCount
    );

Parameters

pCount

[out] Pointer to a variable receives the number of tuning spaces.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::get_EnumTuningSpaces

The get_EnumTuningSpaces method retrieves a collection of all tuning spaces available on the local system.

Syntax

HRESULT get_EnumTuningSpaces(
    IEnumTuningSpaces** ppEnum
);

Parameters

ppEnum

[out] Pointer to a variable that receives an IEnumTuningSpaces interface pointer. Use this interface to enumerate the collection. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

C++ applications use this method to get the initial list of tuning spaces defined on the local system.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::get_Item

The get_Item method retrieves a tuning space with the specified ID.

Syntax

HRESULT get_Item(
    VARIANT varIndex,
    ITuningSpace** ppTuningSpace
    );

Parameters

varIndex

[in] VARIANT that specifies the ID of the tuning space.

ppTuningSpace

[out] Address of an ITuningSpace interface pointer that will be set to the returned interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Tuning spaces are identified by ID number. The ID number is unique within the collection. The range of valid IDs is not guaranteed to be contiguous; there may be holes if tuning spaces are added and then removed.

Example Code

CComPtr <ITuningSpaceContainer>  pTuningSpaceContainer;
// Create the SystemTuningSpaces object (not shown).

long cCount = 0;
long ID = 1; // zero is not a valid ID.
hr = pTuningSpaceContainer->get_Count(&cCount);
if (SUCCEEDED(hr))
{
    while (cCount)
    {
        CComPtr<ITuningSpace> pTuningSpace;
        CComVariant varIndex(ID);
        hr = pITuningSpaceContainer->get_Item(varIndex, &pTuningSpace);
        if (SUCCEEDED(hr))
        {
             // pTuningSpace now points to the tuning space with this ID.
             --cCount;
        }
        ID++; // incremement for the next ID.
    }
}

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::get_MaxCount

The get_MaxCount method retrieves the maximum number of tuning spaces allowed on the system.

Syntax

HRESULT get_MaxCount(
    long* pMaxCount
    );

Parameters

pMaxCount

[out] Pointer to a variable that receives the maximum number of tuning spaces.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::put_Item

The put_Item method saves changes to an existing tuning space in the collection.

Syntax

HRESULT put_Item(
    VARIANT varIndex,
    ITuningSpace* pTuningSpace
    );

Parameters

varIndex

[in] VARIANT that specifies the index of the tuning space.

pTuningSpace

[in] Pointer to the ITuningSpace interface of the tuning space.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
S_OK | Success.

If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

An application can retrieve an existing tuning space from the collection, modify its properties by calling ITuningSpace methods, and then call put_Item to save the changes. The unique name property on the tuning space must match the tuning space at the specified index in the collection; otherwise, the method returns E_INVALIDARG.

To add a new tuning space, use the ITuningSpaceContainer::Add method.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::put_MaxCount

The put_MaxCount method sets the maximum number of tuning spaces allowed on the system.

Syntax

HRESULT put_MaxCount(
    long MaxCount
    );

Parameters

MaxCount

[in] Specifies the maximum number of tuning spaces.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::Remove

The Remove method permanently removes a tuning space from the system.

Syntax

HRESULT Remove(
    VARIANT Index
);

Parameters

Index

[in] Variable of type VARIANT that specifies the ID of the tuning space to remove.

Return Values

Returns S_OK if successful. If the specified tuning space was invalid or corrupted in the Registry, this method will delete whatever information is there and return S_FALSE.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::TuningSpacesForCLSID

The TuningSpacesForCLSID method retrieves a collection of tuning spaces that match the specified CLSID string.

This method is intended for Automation clients, because it returns the CLSID as a BSTR. C++ applications can use the ITuningSpaceContainer::_TuningSpacesForCLSID method instead, which returns a GUID value.

Syntax

HRESULT TuningSpacesForCLSID(
    BSTR SpaceCLSID,
    ITuningSpaces **ppTuningSpaces
);

Parameters

SpaceCLSID

[in] String representation of the CLSID of the tuning space.

ppTuningSpaces

[out] Pointer to a variable that receives an ITuningSpaces interface pointer. Use this interface to enumerate the collection. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaceContainer::TuningSpacesForName

The TuningSpacesForName method retrieves a collection of tuning spaces that match the specified name.

Syntax

HRESULT TuningSpacesForName(
    BSTR Name,
    ITuningSpaces** ppTuningSpaces
);

Parameters

Name

[in] String that contains a regular expression to match against either the friendly name or the unique name of the tuning space.

ppTuningSpaces

[out] Address of variable that receives an ITuningSpaces interface pointer. Use this interface to enumerate the collection. The caller must release the interface.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Example Code

CComPtr <ITuningSpaceContainer>  pTuningSpaceContainer;
// Create the SystemTuningSpaces object (not shown).

// Try to match any tuning spaces named "Local (something) Cable".
CComPtr<ITuningSpaces> pTunes;
CComBSTR bstrName("Local.*Cable");
hr = pITuningSpaceContainer->TuningSpacesForName(bstrName, &pTunes);
if (SUCCEEDED(hr))
{
    // Find the size of the returned collection.
    long cCount = 0;
    hr = pTunes->get_Count(&cCount);
    if (SUCCEEDED(hr) && (cCount > 0))
    {
        // Enumerate the collection.
        CComPtr<IEnumTuningSpaces> pTuneEnum;
        hr = pTunes->get_EnumTuningSpaces(&pTuneEnum);
        if (SUCCEEDED(hr))
        {
            // Use IEnumTuningSpaces to iterate through the collection.
        }
    }
}

Remarks

The returned collection might be empty, if no tuning spaces match the name.

See Also

  • ITuningSpaceContainer Interface


ITuningSpaces Interface

The ITuningSpaces interface represents a collection of tuning spaces.

Method | Description
get__NewEnum | Retrieves an enumerator for the collection. (For use by Automation clients.)
get_Count | Returns the number of tuning spaces in this collection.
get_EnumTuningSpaces | Retrieves an enumerator for the collection. (For use by C++ clients.)
get_Item | Returns a specified item in the collection.

Remarks

This interface is used to enumerate subsets of tuning spaces within the SystemTuningSpaces object. To enumerate all of the tuning spaces available on the system, use the ITuningSpaceContainer interface on the SystemTuningSpaces object.


ITuningSpaces::get__NewEnum

The get__NewEnum method returns an enumerator for the collection.

This method is provided to enable scripting and Visual Basic applications to iterate through the collection in a For...Each loop. C++ applications should use the ITuningSpaces::get_EnumTuningSpaces method.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT** ppNewEnum
    );

Parameters

ppNewEnum

[out] Pointer to a variable that receives an IEnumVARIANT interface pointer. The caller must release the interface.

Return Values

Returns S_OK if successful.

Remarks

The returned IEnumVARIANT interface is not thread safe, because it is intended primarily for use by Automation clients. Clients should not call methods on the interface from more than one thread.

See Also

  • ITuningSpaces Interface


ITuningSpaces::get_Count

The get_Count method returns the number of tuning spaces in the collection.

Syntax

HRESULT get_Count(
    long* pCount
    );

Parameters

pCount

[out] Pointer to a variable that receives the number of items in the collection.

Return Values

Returns S_OK if successful.

See Also

  • ITuningSpaces Interface


ITuningSpaces::get_EnumTuningSpaces

The get_EnumTuningSpaces method returns an enumerator for the collection.

Syntax

HRESULT get_EnumTuningSpaces(
    IEnumTuningSpaces** ppNewEnum
    );

Parameters

ppNewEnum

[out] Pointer to a variable that receives an IEnumTuningSpaces interface pointer. Use this interface to iterate through the collection. The caller must release the interface.

Return Values

Returns S_OK if successful.

See Also

  • ITuningSpaces Interface


ITuningSpaces::get_Item

The get_Item method returns the specified item in the collection.

Syntax

HRESULT get_Item(
    VARIANT varIndex,
    ITuningSpace** ppTuningSpace
    );

Parameters

varIndex

[in] VARIANT type that specifies the ID of the tuning space. The ID uniquely identifies the tuning space within the SystemTuningSpaces object.

ppTuningSpace

[out] Address of a variable that receives a pointer to the tuning space's ITuningSpace interface. The caller must release the interface.

Return Values

Returns S_OK if successful.

See Also

  • ITuningSpaces Interface


Microsoft Unified Tuning Model Enumerations

The following table lists all the Enumeration types used by the Microsoft Unified Tuning Model interface methods.

Enumeration Type | Description
ATSCComponentTypeFlags | Specifies an AC3 audio stream.
BinaryConvolutionCodeRate | Specifies the binary convolution code rate.
ComponentCategory | Specifies the component (substream) category.
ComponentStatus | Specifies the status of a component (substream).
DVBSystemType | Specifies the type of DVB system supported in a Tuning Space.
FECMethod | Specifies the type of forward error correction being used at the transmission source.
GuardInterval | Specifies the guard interval.
HierarchyAlpha | Specifies the hierarchy alpha.
KS_CC_SUBSTREAM | Specifies line 21 services.
ModulationType | Specifies the modulation type.
MPEG2StreamType | Specifies the MPEG2 stream type.
Polarisation | Specifies the polarisation type.
SpectralInversion | Specifies the spectral inversion.
TransmissionMode | Specifies the transmission mode.


ATSCComponentTypeFlags Enumeration

Specifies a flag that identifies an AC-3 audio stream in an ATSC broadcast stream.

Syntax

typedef enum ATSCComponentTypeFlags {
    ATSCCT_AC3 = 0x00000001,
} ATSCComponentTypeFlags;

Members

ATSCCT_AC3

Indicates that the component contains AC-3 audio.

Remarks

Component in this context means a sub-stream.

See Also

  • IATSCComponentType Interface
  • Microsoft Unified Tuning Model Enumerations


BDA_UNDEFINED_CHANNEL

Specifies an undefined channel in a channel tune request.

Syntax

enum {

    BDA_UNDEFINED_CHANNEL = -1

};

Members

BDA_UNDEFINED_CHANNEL

Indicates that the channel is undefined.

See Also

  • Microsoft Unified Tuning Model Enumerations


BinaryConvolutionCodeRate Enumeration

Specifies the binary convolution code rate used in the forward error correction scheme.

Syntax

enum BinaryConvolutionCodeRate {
    BDA_BCC_RATE_NOT_SET = -1,
    BDA_BCC_RATE_NOT_DEFINED = 0,
    BDA_BCC_RATE_1_2         = 1,
    BDA_BCC_RATE_2_3         = 2,
    BDA_BCC_RATE_3_4         = 3,
    BDA_BCC_RATE_3_5         = 4,
    BDA_BCC_RATE_4_5         = 5,
    BDA_BCC_RATE_5_6         = 6,
    BDA_BCC_RATE_5_11        = 7,
    BDA_BCC_RATE_7_8         = 8,
    BDA_BCC_RATE_MAX         = 9
} BinaryConvolutionCodeRate;

Members

BDA_BCC_RATE_NOT_SET

Indicates that no rate is specified.

BDA_BCC_RATE_NOT_DEFINED

Indicates that the rate is not defined.

BDA_BCC_RATE_1_2

Indicates that the rate is ½.

BDA_BCC_RATE_2_3

Indicates that the rate is 2/3.

BDA_BCC_RATE_3_4

Indicates that the rate is 3/4.

BDA_BCC_RATE_3_5

Indicates that the rate is 3/5.

BDA_BCC_RATE_4_5

Indicates that the rate is 4/5.

BDA_BCC_RATE_5_6

Indicates that the rate is 5/6.

BDA_BCC_RATE_5_11

Indicates that the rate is 5/11.

BDA_BCC_RATE_7_8

Indicates that the rate is 7/8.

BDA_BCC_RATE_MAX

Reserved; do not use.

See Also

  • ILocator::get_OuterFECRate
  • ILocator::get_InnerFECRate
  • Microsoft Unified Tuning Model Enumerations


ComponentCategory Enumeration

Specifies the type of content in an Advanced Television System Committee (ASTC) sub-stream (component).

Syntax

enum ComponentCategory
{
    CategoryNotSet = -1,
    CategoryOther  =  0,
    CategoryVideo  =  1,
    CategoryAudio  =  2,
    CategoryText   =  3,
    CategoryData   =  4
} ComponentCategory;

Members

CategoryNotSet

The category for the component is not set.

CategoryOther

The component contains none of the defined types.

CategoryVideo

The component contains a video stream.

CategoryAudio

The component contains an audio stream.

CategoryText

The component contains a text stream.

CategoryData

The component contains a data stream.

See Also

  • IComponentType::get_Category
  • Microsoft Unified Tuning Model Enumerations


ComponentStatus Enumeration

Specifies the status of a sub-stream (component).

Syntax

enum ComponentStatus
{
    StatusActive      = 0,
    StatusInactive    = 1,
    StatusUnavailable = 2
} ComponentStatus;

Members

StatusActive

The component is active.

StatusInactive

The component is inactive

StatusUnavailable

The component is not available.

See Also

  • IComponent::get_Status
  • Microsoft Unified Tuning Model Enumerations


DVBSystemType Enumeration

Specifies the type of Digital Video Broadcasting (DVB) system supported in a tuning space.

Syntax

enum DVBSystemType
{
    DVB_Cable       = 0,
    DVB_Terrestrial = 1,
    DVB_Satellite   = 2
} DVBSystemType;

Members

DVB_Cable

Indicates a cable DVB system (DVB-c).

DVB_Terrestrial

Indicates a terrestrial DVB system (DVB-T).

DVB_Satellite

Indicates a satellite DVB system (DVB-S).

See Also

  • IDVBTuningSpace::get_SystemType
  • Microsoft Unified Tuning Model Enumerations


FECMethod Enumeration

Specifies the type of forward error correction being used by the provider.

Syntax

enum FECMethod {
    BDA_FEC_METHOD_NOT_SET     = -1,
    BDA_FEC_METHOD_NOT_DEFINED =  0,
    BDA_FEC_VITERBI            =  1,
    BDA_FEC_RS_204_188         =  2,
    BDA_FEC_MAX                =  3
} FECMethod;

Members

BDA_FEC_METHOD_NOT_SET

The FEC method is not set.

BDA_FEC_METHOD_NOT_DEFINED

The FEC method is not defined.

BDA_FEC_VITERBI

The FEC is a Viterbi Binary Convolution.

BDA_FEC_RS_204_188

The FEC is Reed-Solomon 204/188 (outer FEC)

BDA_FEC_MAX

Reserved; do not use.

See Also

  • ILocator::get_OuterFEC
  • ILocator::get_InnerFEC
  • Microsoft Unified Tuning Model Enumerations


GuardInterval Enumeration

Specifies the guard interval on a Digital Video Broadcasting-Terrestrial (DVB-T) system.

Syntax

enum GuardInterval {
    BDA_GUARD_NOT_SET     = -1,
    BDA_GUARD_NOT_DEFINED =  0,
    BDA_GUARD_1_32        =  1,
    BDA_GUARD_1_16        =  2,
    BDA_GUARD_1_8         =  3,
    BDA_GUARD_1_4         = 4,
    BDA_GUARD_MAX         = 5
} GuardInterval;

Members

BDA_GUARD_NOT_SET

The guard interval is not set.

BDA_GUARD_NOT_DEFINED

The guard interval is not defined.

BDA_GUARD_1_32

The guard interval is 1/32.

BDA_GUARD_1_16

The guard interval is 1/16.

BDA_GUARD_1_8

The guard interval is 1/8.

BDA_GUARD_1_4

The guard interval is 1/4.

BDA_GUARD_MAX

Reserved; do not use.

See Also

  • IDVBTLocator::get_Guard
  • Microsoft Unified Tuning Model Enumerations


HierarchyAlpha Enumeration

Specifies the hierarchy alpha on a Digital Video Broadcasting-Terrestrial (DVB-T) system.

Syntax

enum HierarchyAlpha {
    BDA_HALPHA_NOT_SET     = -1,
    BDA_HALPHA_NOT_DEFINED =  0,
    BDA_HALPHA_1           =  1,
    BDA_HALPHA_2           =  2,
    BDA_HALPHA_4           =  3,
    BDA_HALPHA_MAX         =  4
} HierarchyAlpha;

Members

BDA_HALPHA_NOT_SET

The hierarchy alpha is not set.

BDA_HALPHA_NOT_DEFINED

The hierarchy alpha is not defined.

BDA_HALPHA_1

The hierarchy alpha is 1.

BDA_HALPHA_2

The hierarchy alpha is 2.

BDA_HALPHA_4

The hierarchy alpha is 4.

BDA_HALPHA_MAX

Reserved; do not use.

See Also

  • IDVBTLocator::get_HAlpha
  • Microsoft Unified Tuning Model Enumerations


KS_CC_SUBSTREAM Constants

The KS_CC_SUBSTREAM constants specify the various services that are available on line 21 of the vertical blanking interval (VBI).

Requirements

Requires Ks.h and Ksmedia.h. Include Ks.h before Ksmedia.h

Constant | Value | Description
KS_CC_SUBSTREAM_SERVICE_CC1 | 0x0001 | CC1 (caption channel)
KS_CC_SUBSTREAM_SERVICE_CC2 | 0x0002 | CC2 (caption channel)
KS_CC_SUBSTREAM_SERVICE_T1 | 0x0004 | T1 (text channel)
KS_CC_SUBSTREAM_SERVICE_T2 | 0x0008 | T2 (text channel)
KS_CC_SUBSTREAM_SERVICE_CC3 | 0x0100 | CC3 (caption channel)
KS_CC_SUBSTREAM_SERVICE_CC4 | 0x0200 | CC4 (caption channel)
KS_CC_SUBSTREAM_SERVICE_T3 | 0x0400 | T3 (text channel)
KS_CC_SUBSTREAM_SERVICE_T4 | 0x0800 | T4 (text channel)
KS_CC_SUBSTREAM_SERVICE_XDS | 0x1000 | Extended Data Services (XDS)
KS_CC_SUBSTREAM_FIELD1_MASK | 0x000F | Bitmask to filter field 1 substreams.
KS_CC_SUBSTREAM_FIELD2_MASK | 0x1F00 | Bitmask to filter field 2 substreams

  • Microsoft Unified Tuning Model Enumerations


ModulationType Enumeration

Specifies the modulation type.

Syntax

enum ModulationType {
    BDA_MOD_NOT_SET     = -1,
    BDA_MOD_NOT_DEFINED =  0,
    BDA_MOD_16QAM       =  1,
    BDA_MOD_32QAM       =  2,
    BDA_MOD_64QAM       =  3,
    BDA_MOD_80QAM       =  4,
    BDA_MOD_96QAM       =  5,
    BDA_MOD_112QAM      =  6,
    BDA_MOD_128QAM      =  7,
    BDA_MOD_160QAM      =  8,
    BDA_MOD_192QAM      =  9,
    BDA_MOD_224QAM      = 10,
    BDA_MOD_256QAM      = 11,
    BDA_MOD_320QAM      = 12,
    BDA_MOD_384QAM      = 13,
    BDA_MOD_448QAM      = 14,
    BDA_MOD_512QAM      = 15,
    BDA_MOD_640QAM      = 16,
    BDA_MOD_768QAM      = 17,
    BDA_MOD_896QAM      = 18,
    BDA_MOD_1024QAM     = 19,
    BDA_MOD_QPSK        = 20,
    BDA_MOD_BPSK        = 21,
    BDA_MOD_OQPSK       = 22,
    BDA_MOD_8VSB        =  23,
    BDA_MOD_16VSB       = 24,
    BDA_MOD_ANALOG_AMPLITUDE  = 25,
    BDA_MOD_ANALOG_FREQUENCY  = 26,
    BDA_MOD_MAX         = 27
} ModulationType;

Members

BDA_MOD_NOT_SET

Modulation not set.

BDA_MOD_NOT_DEFINED

Modulation not defined.

BDA_MOD_16QAM

16 symbol Quadrature Amplitude Modulation (QAM)

BDA_MOD_32QAM

32 symbol QAM.

BDA_MOD_64QAM

64 symbol QAM.

BDA_MOD_80QAM

80 symbol QAM.

BDA_MOD_96QAM

96 symbol QAM.

BDA_MOD_112QAM

112 symbol QAM.

BDA_MOD_128QAM

128 symbol QAM.

BDA_MOD_160QAM

160 symbol QAM.

BDA_MOD_192QAM

192 symbol QAM.

BDA_MOD_224QAM

224 symbol QAM.

BDA_MOD_256QAM

256 symbol QAM.

BDA_MOD_320QAM

320 symbol QAM.

BDA_MOD_384QAM

384 symbol QAM.

BDA_MOD_448QAM

448 symbol QAM.

BDA_MOD_512QAM

512 symbol QAM.

BDA_MOD_640QAM

640 symbol QAM.

BDA_MOD_768QAM

768 symbol QAM.

BDA_MOD_896QAM

896 symbol QAM.

BDA_MOD_1024QAM

1024 symbol QAM.

BDA_MOD_QPSK

Quadrature Phase-Shift Keying (QPSK) modulation.

BDA_MOD_BPSK

Binary Phase Shift Keying modulation.

BDA_MOD_OQPSK

Offset QPSK modulation.

BDA_MOD_8VSB

8 Vestigial Side-Band modulation.

BDA_MOD_16VSB

16 Vestigial Side-Band modulation.

BDA_MOD_ANALOG_AMPLITUDE

Analog amplitude modulation (AM).

BDA_MOD_ANALOG_FREQUENCY

Analog frequency modulation (FM).

BDA_MOD_MAX

Reserved; do not use.

See Also

  • ILocator::get_Modulation
  • Microsoft Unified Tuning Model Enumerations


MPEG2StreamType Enumeration

Specifies the MPEG2 stream type. The values in this enumeration correspond to the value of the stream_type field in the program map table (PMT). The list is not exhaustive; other values may be possible.

Syntax

enum MPEG2StreamType {
    BDA_UNITIALIZED_MPEG2STREAMTYPE = -1,
    Reserved1                       =  0,
    ISO_IEC_11172_2_VIDEO           =  1,
    ISO_IEC_13818_2_VIDEO           =  2,
    ISO_IEC_11172_3_AUDIO           =  3,
    ISO_IEC_13818_3_AUDIO           =  4,
    ISO_IEC_13818_1_PRIVATE_SECTION =  5,
    ISO_IEC_13818_1_PES             =  6,
    ISO_IEC_13522_MHEG              =  7,
    ANNEX_A_DSM_CC                  =  8,
    ITU_T_REC_H_222_1               =  9,
    ISO_IEC_13818_6_TYPE_A          = 10,
    ISO_IEC_13818_6_TYPE_B          = 11,
    ISO_IEC_13818_6_TYPE_C          = 12,
    ISO_IEC_13818_6_TYPE_D          = 13,
    ISO_IEC_13818_1_AUXILIARY       = 14,
    ISO_IEC_13818_1_RESERVED        = 15,
    USER_PRIVATE                    = 16
} MPEG2StreamType;

Members

BDA_UNITIALIZED_MPEG2STREAMTYPE

MPEG-2 un-initialized streams.

Reserved1

Reserved for future use.

ISO_IEC_11172_2_VIDEO

MPEG-1 video stream. (ISO/IEC 11172 video.)

ISO_IEC_13818_2_VIDEO

MPEG-2 video stream. (ISO/IEC 13818-2 video.)

ISO_IEC_11172_3_AUDIO

MPEG-1 audio stream. (ISO/IEC 11172 audio.)

ISO_IEC_13818_3_AUDIO

MPEG-2 audio stream. (ISO/IEC 13818-3 audio.)

ISO_IEC_13818_1_PRIVATE_SECTION

MPEG-2 private sections. (ISO/IEC 13818-1 private sections.)

ISO_IEC_13818_1_PES

MPEG-2 Packetized Elementary Stream (PES) packets containing private data. (ISO/IEC 13818-1 PES).

ISO_IEC_13522_MHEG

MHEG-5 Audio-Visual streams. (ISO/IEC 13522 MHEG.)

ANNEX_A_DSM_CC

Digital Storage Media Command and Control (DSM-CC) stream. (ISO/IEC 13818-1 Annex A.)

ITU_T_REC_H_222_1

ITU-T Satellite Audio-Visual streams. (ITU-T Rec. H.222.1.)

ISO_IEC_13818_6_TYPE_A

MPEG-2 Video Clip A streams. (ISO/IEC 13818-6 type A.)

ISO_IEC_13818_6_TYPE_B

MPEG-2 Video Clip B streams. (ISO/IEC 13818-6 type B.)

ISO_IEC_13818_6_TYPE_C

MPEG-2 Video Clip C streams. (ISO/IEC 13818-6 type C.)

ISO_IEC_13818_6_TYPE_D

MPEG-2 Video Clip D streams. (ISO/IEC 13818-6 type D.)

ISO_IEC_13818_1_AUXILIARY

MPEG-2 Auxiliary streams. (ISO/IEC 13818-1 auxiliary.)

ISO_IEC_13818_1_RESERVED

MPEG-2 Reserved streams.

USER_PRIVATE

User proprietary streams.

See Also

  • IMPEG2ComponentType::get_StreamType
  • Microsoft Unified Tuning Model Enumerations


Polarisation Enumeration

Specifies the polarization type.

Syntax

enum Polarisation {
    BDA_POLARISATION_NOT_SET     = -1,
    BDA_POLARISATION_NOT_DEFINED =  0,
    BDA_POLARISATION_LINEAR_H    = 1,
    BDA_POLARISATION_LINEAR_V    = 2,
    BDA_POLARISATION_CIRCULAR_L  = 3,
    BDA_POLARISATION_CIRCULAR_R  = 4,
    BDA_POLARISATION_MAX         = 5
} Polarisation;

Members

BDA_POLARISATION_NOT_SET

Polarization not set.

BDA_POLARISATION_NOT_DEFINED

Polarization not defined.

BDA_POLARISATION_LINEAR_H

Linear horizontal polarization.

BDA_POLARISATION_LINEAR_V

Linear vertical polarization.

BDA_POLARISATION_CIRCULAR_L

Circular left polarization.

BDA_POLARISATION_CIRCULAR_R

Circular right polarization.

BDA_POLARISATION_MAX

Reserved; do not use.

See Also

  • IDVBSLocator::get_SignalPolarisation
  • Microsoft Unified Tuning Model Enumerations


SpectralInversion Enumeration

Indicates the type of spectral inversion on Quadrature Phase Shift Keying (QPSK) in a Broadcast Driver Architecture (BDA) capture device.

Syntax

enum SpectralInversion
 {
    BDA_SPECTRAL_INVERSION_NOT_SET     = -1,
    BDA_SPECTRAL_INVERSION_NOT_DEFINED =  0,
    BDA_SPECTRAL_INVERSION_AUTOMATIC   =  1,
    BDA_SPECTRAL_INVERSION_NORMAL      =  2,
    BDA_SPECTRAL_INVERSION_INVERTED    =  3,
    BDA_SPECTRAL_INVERSION_MAX         = 4
} SpectralInversion;

Members

BDA_SPECTRAL_INVERSION_NOT_SET

Spectral Inversion is not set.

BDA_SPECTRAL_INVERSION_NOT_DEFINED

Spectral Inversion is not defined.

BDA_SPECTRAL_INVERSION_AUTOMATIC

Spectral Inversion is automatic.

BDA_SPECTRAL_INVERSION_NORMAL

Spectral Inversion is normal.

BDA_SPECTRAL_INVERSION_INVERTED

Spectral Inversion is inverted.

BDA_SPECTRAL_INVERSION_MAX

Reserved; do not use.

See Also

  • IDVBSTuningSpace::get_SpectralInversion
  • Microsoft Unified Tuning Model Enumerations


TransmissionMode Enumeration

Specifies the transmission mode.

Syntax

enum TransmissionMode {
    BDA_XMIT_MODE_NOT_SET     = -1,
    BDA_XMIT_MODE_NOT_DEFINED =  0,
    BDA_XMIT_MODE_2K          =  1,
    BDA_XMIT_MODE_8K          =  2,
    BDA_XMIT_MODE_MAX         =  3
} TransmissionMode;

Members

BDA_XMIT_MODE_NOT_SET

Transmission mode is not set.

BDA_XMIT_MODE_NOT_DEFINED

Transmission mode is not defined.

BDA_XMIT_MODE_2K

Transmission uses 1705 carriers (use a 2K FFT).

BDA_XMIT_MODE_8K

Transmission uses 6817 carriers (use an 8K FFT).

BDA_XMIT_MODE_MAX

Reserved; do not use.

See Also

  • IDVBTLocator::get_Mode
  • Microsoft Unified Tuning Model Enumerations


Transport Information Interfaces

The following interfaces are implemented on a BDA Network Provider filter, a BDA MPEG-2 Transport Information Filter (TIF), or a Guide Data Loader.

These interfaces are not used by applications. They are used solely to enable the Network Provider, TIF, and Loader to share information essential to tuning on MPEG-2 transport streams. These interfaces are documented so that independent software vendors (ISVs) can create guide data loaders and TV applications that support standard or non-standard network types. To use these interfaces, you should have a good understanding of MPEG-2 transport streams and the Microsoft Unified Tuning Model. (For more information, see The Microsoft Unified Tuning Model.)

The following transport information interfaces are supported.

Interface | Description
IBDA_TIF_REGISTRATION | Enables a Transport Information Filter (TIF) to register itself with the Network Provider.
IEnumGuideDataProperties | Represents a collection of guide data properties for programs, services, and schedule entries that have been generated by the TIF.
IEnumTuneRequests | Represents a collection of tune request objects.
IGuideData | Implemented on the Transport Information Filter (TIF) and used by a guide data loader to enumerate the primary elements that it will use to create the objects that it will persist in some way.
IGuideDataEvent | IConnectionPoint notification callback interface that is implemented on the Network Provider filter or any other object that needs to receive these events from the TIF.
IGuideDataProperty | Represents the name, value, and language of a property associated with a Service, Program or ScheduleEntry.
IMPEG2_TIF_CONTROL | Implemented by the Network Provider and used by the TIF to register itself and request table sections carried on specific PIDs within the transport stream.
ITuneRequestInfo | Implemented on the TIF and used by the Network Provider when, in order to resolve a tune request, it needs additional network-specific information about locating transport streams and acquiring services.


IBDA_TIF_REGISTRATION Interface

The IBDA_TIF_REGISTRATION interface is exposed by the BDA Network Provider. It enables a Transport Information Filter (TIF) to register itself with the Network Provider. This interface supercedes the IMPEG2_TIF_CONTROL interface.

Applications do not use this interface.

In addition to the methods inherited from IUnknown, the IBDA_TIF_REGISTRATION interface exposes the following methods.

Method | Description
RegisterTIFEx | Registers the TIF with the Network Provider.
UnregisterTIF | Unregisters the TIF with the Network Provider.


IBDA_TIF_REGISTRATION::RegisterTIFEx

The RegisterTIFEx method registers a Transport Information Filter (TIF) with the Network Provider.

Syntax

HRESULT RegisterTIFEx(
    IPin *pTIFInputPin,
    ULONG *ppvRegistrationContext,
    IUnknown **ppMpeg2DataControl
);

Parameters

pTIFInputPin

[in] Pointer to the IPin interface of the input pin on the TIF.

ppvRegistrationContext

[in, out] Pointer to a variable that receives a token identifying the connection. Pass this token in the UnregisterTIF method when the TIF unregisters itself.

ppMpeg2DataControl

[in, out] Address of a variable that receives a pointer to an IUnknown interface, which the TIF queries for the IMPEG2PIDMap interface. It uses the IMPEG2PIDMap to map and unmap PID values.

Return Values

The method returns an HRESULT value.

See Also

  • IBDA_TIF_REGISTRATION Interface


IBDA_TIF_REGISTRATION::UnregisterTIF

The UnregisterTIF method unregisters a Transport Information Filter (TIF) with the Network Provider.

Syntax

HRESULT nregisterTIF(
 LONG pvRegistrationContext
);

Parameters

pvRegistrationContext

[in] Specifies the token that the RegisterTIFEx method returned in the ppvRegistrationContext parameter.

Return Values

The method returns an HRESULT value.

See Also

  • IBDA_TIF_REGISTRATION Interface


IEnumGuideDataProperties Interface

The IEnumGuideDataProperties interface represents a collection of guide data properties that has been generated by the TIF. Separate collections are created for programs, services, and schedule entries. This interface is obtained from the TIF using the following methods.

  • IGuideData::GetProgramProperties.
  • IGuideData::GetScheduleEntryProperties
  • IGuideData::GetServiceProperties

In addition to the methods inherited from IUnknown, the IEnumGuideDataProperties interface exposes the following methods.

Method | Description
Clone | Creates a copy of the collection. (Currently not implemented.)
Next | Retrieves the next item or items in the collection.
Reset | Sets the enumerator to the first item in the collection.
Skip | Skips the specified number of items. (Currently not implemented.)

Requirements

Include Bdatif.h.


IEnumGuideDataProperties::Clone

Not implemented for this release.

The Clone method creates a copy of the collection.

Syntax

HRESULT Clone(
  IEnumGuideDataProperties**  ppenum
);

Parameters

ppenum

[out] Pointer to a variable that receives a pointer to the new collection's IEnumGuideDataProperties interface.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IEnumGuideDataProperties Interface


IEnumGuideDataProperties::Next

The Next method retrieves the specified number of items in the enumeration sequence.

Syntax

HRESULT Next(
  unsigned long celt,
  IGuideDataProperty **ppProp,
  unsigned long *pcelt
);

Parameters

celt

[in] Specifies the number of items to retrieve.

ppProp

[out] Address of an array of size celt, allocated by the caller. The array is filled with IGuideDataProperty interface pointers.

pcelt

[out] Pointer to a variable that receives the number of items received.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
S_FALSE | The collection is at the end of the enumeration sequence.
E_POINTER | NULL pointer argument.

See Also

  • Error and Success Codes
  • IEnumGuideDataProperties Interface


IEnumGuideDataProperties::Reset

The Reset method resets the enumerator to the first item in the collection.

Syntax

HRESULT Reset();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IEnumGuideDataProperties Interface


IEnumGuideDataProperties::Skip

Not implemented for this release.

The Skip method skips over a specified number of items in the collection.

Syntax

HRESULT Skip(
  unsigned long  celt
);

Parameters

celt

[in] Specifies the number of items to skip.

Return Values

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IEnumGuideDataProperties Interface


IEnumTuneRequests Interface

The IEnumTuneRequests interface provides access to a collection of tune requests returned from a call to IGuideData::GetServices. This collection of tune requests represents all the services available in the tuning space.

In addition to the methods inherited from IUnknown, the IEnumTuneRequests interface exposes the following methods.

Method | Description
Clone | Creates a copy of the collection.
Next | Retrieves the next item or items in the collection.
Reset | Sets the enumerator to the first item in the collection.
Skip | Skips the specified number of items.

Requirements

Include Bdatif.h.


IEnumTuneRequests::Clone

The Clone method creates a copy of the collection.

Syntax

HRESULT Clone(
  IEnumTuneRequests**  ppEnum
);

Parameters

ppEnum

[out] Pointer to a variable that receives the new collection.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IEnumTuneRequests Interface


IEnumTuneRequests::Next

The Next method retrieves the specified number of items in the collection.

Syntax

HRESULT Next(
  unsigned long celt,
  ITuneRequest **ppProp,
  unsigned long *pcelt
);

Parameters

celt

[in] Specifies the number of items to retrieve.

ppProp

[out] Array of size celt that is filled with ITuneRequest interface pointers.

pcelt

[out] Pointer to a variable that receives the number of items retrieved.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
S_FALSE | The collection is at the end of the enumeration sequence.

See Also

  • Error and Success Codes
  • IEnumTuneRequests Interface


IEnumTuneRequests::Reset

The Reset method sets the enumerator to the first item in the collection.

Syntax

HRESULT Reset();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IEnumTuneRequests Interface


IEnumTuneRequests::Skip

The Skip method skips over the specified number of items in the collection.

Syntax

HRESULT Skip(
  unsigned long  celt
);

Parameters

celt

[in] Specifies the number of items to skip.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IEnumTuneRequests Interface


IGuideData Interface

The IGuideData interface is exposed by the BDA MPEG-2 Transport Information Filter (TIF). It enables the client to get service information from the MPEG-2 transport stream. Use this interface if you are writing a guide store loader.

In addition to the methods inherited from IUnknown, the IGuideData interface exposes the following methods.

Method | Description
GetGuideProgramIDs | Returns a list of unique identifiers for all of the programs contained in all transport streams.
GetProgramProperties | Retrieves the properties for a specified program.
GetScheduleEntryIDs | Returns a list of unique identifiers for all of the schedule entries contained in all transport streams.
GetScheduleEntryProperties | Retrieves the properties for a specified schedule entry.
GetServiceProperties | Retrieves the properties for a specified service.
GetServices | Retrieves a collection of tune requests representing all of the services available in the tuning space.

Remarks

The TIF collects service informaton for services, programs, and schedule entries. A service is analogous to a channel; a program is a television show (also known as an "event"); and a schedule entry is an event that occurs at a specific time on a specific service.

For each program and schedule entry, the TIF creates a string that uniquely identifies that element within the multiplex. The GetGuideProgramIDs and GetScheduleEntryIDs methods return a list of these identifiers. You can then pass the identifier to the GetProgramProperties and GetScheduleEntryProperties methods to get additional properties for a particular element.

Requirements

Include Bdatif.h.


IGuideData::GetGuideProgramIDs

The GetGuideProgramIDs method returns a list of unique identifiers for all of the programs contained in all transport streams.

Syntax

HRESULT GetGuideProgramIDs(
  IEnumVARIANT**  ppEnumPrograms
);

Parameters

ppEnumPrograms

[out] Address of a variable that receives a pointer to the IEnumVARIANT interface. Use this interface to enumerate the collection. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

The method fails if the TIF has not received the program information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ProgramChanged event to be fired.

Each VARIANT type in the collection contains a BSTR that uniquely identifies one program within the multiplex. To get more information about the program, pass the VARIANT to the IGuideData::GetProgramProperties method.

The returned IEnumVARIANT interface is not thread safe. Clients should not call methods on the interface from more than one thread.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideData::GetProgramProperties

The GetProgramProperties method retrieves the properties for a specified program.

Syntax

HRESULT GetProgramProperties(
  VARIANT  varProgramDescriptionID,
  IEnumGuideDataProperties**  ppEnumProperties
);

Parameters

varProgramDescriptionID

[in] Specifies the unique identifier for the program. Call the IGuideData::GetGuideProgramIDs method to get a list of program identifiers.

ppEnumProperties

[out] Pointer to a variable that receives an IEnumGuideDataProperties interface pointer. Use this interface to enumerate the properties. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

The returned collection includes the following properties.

Property | Description
Description.ID | The unique identifier for the program.
Description.One Sentence | The description of the program.
Description.Title | The name of the program.

The method fails if the TIF has not received the program information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ProgramChanged event to be fired.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideData::GetScheduleEntryIDs

The GetScheduleEntryIDs method returns a list of unique identifiers for all of the schedule entries contained in all transport streams.

Syntax

HRESULT GetScheduleEntryIDs(
  IEnumVARIANT**  ppEnumScheduleEntries
);

Parameters

ppEnumScheduleEntries

[out] Address of a variable that receives a pointer to the IEnumVARIANT interface. Use this interface to enumerate the collection. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

The method fails if the TIF has not received the schedule information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ScheduleEntryChanged event to be fired.

Each VARIANT type in the collection contains a BSTR that uniquely identifies one schedule entry within the multiplex. To get more information about the schedule entry, pass the VARIANT to the IGuideData::GetScheduleEntryProperties method.

The returned IEnumVARIANT interface is not thread safe. Clients should not call methods on the interface from more than one thread.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideData::GetScheduleEntryProperties

The GetScheduleEntryProperties method retrieves the properties for a specified schedule entry.

Syntax

HRESULT GetScheduleEntryProperties(
  VARIANT  varScheduleEntryDescriptionID,
  IEnumGuideDataProperties**  ppEnumProperties
);

Parameters

varScheduleEntryDescriptionID

[in] Specifies the unique identifier for the schedule entry. Call the IGuideData::GetScheduleEntryIDs method to get a list of schedule entry identifiers.

ppEnumProperties

[out] Pointer to a variable that receives an IEnumGuideDataProperties interface pointer. Use this interface to enumerate the properties. The caller must release the interface

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

The returned collection includes the following properties.

Property | Description
Description.ID | The unique identifier for the schedule entry.
Time.Start | The starting time and date of this schedule entry. The value of this property is an unsigned long containing the time and date in GPS time.
Time.End | The ending time and date of this schedule entry. The value of this property is an unsigned long containing the time and date in GPS time.
ScheduleEntry.ProgramID | Identifies the program that will play at the time specified by this schedule entry. The value of this property corresponds to the Description.ID property of the program.
ScheduleEntry.ServiceID | Identifies the service that carries the program represented by this schedule entry. The value of this property corresponds to the Description.ID property of the service.

The method fails if the TIF has not received the schedule information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ScheduleEntryChanged event to be fired.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideData::GetServiceProperties

The GetServiceProperties method retrieves the properties for a specified service.

Syntax

HRESULT GetServiceProperties(
  ITuneRequest*  pTuneRequest,
  IEnumGuideDataProperties**  ppEnumProperties
);

Parameters

pTuneRequest

[in] Pointer to the ITuneRequest interface of a valid tune request. Call the IGuideData::GetServices method to get a list of tune requests.

ppEnumProperties

[out] Pointer to a variable that receives an IEnumGuideDataProperties interface pointer. Use this interface to enumerate the properties. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

The returned collection includes the following properties.

Property | Description
Description.ID | The unique identifier for the service.
Description.Name | Default name to use for this service in the channel lineup.
Provider.Name | Name of the service provider.
Provider.NetworkName | Name of the network on which the service is provided.

The method fails if the TIF has not received the service information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ServiceChanged event to be fired.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideData::GetServices

The GetServices method retrieves a collection of tune requests representing all the services available in the tuning space.

Syntax

HRESULT GetServices(
  IEnumTuneRequests**  ppEnumTuneRequests
);

Parameters

ppEnumTuneRequests

[out] Pointer to a variable that receives an IEnumTuneRequests interface pointer. Use this interface to enumerate the properties. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

This method is used to enumerate all services listed in the service descriptor table. Each tune request in the returned collection contains locator data for the service. To get more information about a service, pass the ITuneRequest pointer to the IGuideData::GetServiceProperties method.

The method fails if the TIF has not received the service information from the PSI tables in the transport stream. The client should implement the IGuideDataEvent interface and wait for the IGuideDataEvent::ServiceChanged event to be fired.

See Also

  • Error and Success Codes
  • IGuideData Interface


IGuideDataEvent Interface

The IGuideDataEvent interface is used to receive events from the BDA MPEG-2 Transport Information Filter (TIF).

This interface is an outgoing connection-point interface. To receive events from a playback device, implement this interface and then call the IConnectionPoint::Advise method to establish a connection. The event sink must not block the calling thread. If the client requires additional information about the event, it should make calls on a separate thread.

In addition to the methods inherited from IUnknown, the IGuideDataEvent interface exposes the following methods.

Method | Description
GuideDataAcquired | Called when a complete set of guide data has been acquired from the current transport stream. (Currently not supported.)
ProgramChanged | Called when information about one or more programs has changed.
ProgramDeleted | Called when a program has been deleted. (Currently not supported.)
ScheduleDeleted | Called when a schedule entry has been deleted. (Currently not supported.)
ScheduleEntryChanged | Called when information about one or more schedule entries has changed.
ServiceChanged | Called when a service has been changed.
ServiceDeleted | Called when a service has been deleted. (Currently not supported.)

Requirements

Include Bdatif.h.


IGuideDataEvent::GuideDataAcquired

The GuideDataAcquired method is called when a complete set of guide data has been acquired from the current transport stream.

Currently the BDA MPEG-2 Transport Information Filter (TIF) does not support this event, so this method is not called.

Syntax

HRESULT GuideDataAcquired();

Parameters

This method takes no parameters.

Return Values

Return S_OK if successful, or an error code.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ProgramChanged

The ProgramChanged method is called when information about one or more programs has changed.

Syntax

HRESULT ProgramChanged(
  VARIANT  varProgramDescriptionID
);

Parameters

varProgramDescriptionID

[in] Specifies the unique identifier of the program that has changed. Call IGuideData::GetProgramProperties to get information about the program. The value of this parameter may be an empty VARIANT type (VT_EMPTY); if so, examine all of the programs to determine which ones have changed.

Return Values

Return S_OK if successful, or an error code.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ProgramDeleted

The ProgramDeleted method is called when a program has been deleted.

Currently the BDA MPEG-2 Transport Information Filter (TIF) does not support this event, so this method is not called.

Syntax

HRESULT ProgramDeleted(
  VARIANT  varProgramDescriptionID
);

Parameters

varProgramDescriptionID

[in] Specifies the unique identifier of the program that was deleted.

Return Values

Return S_OK if successful, or an error code.

Remarks

The event sink is not required to support this event; it may return E_NOTIMPL.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ScheduleDeleted

The ScheduleDeleted method is called when a schedule entry has been deleted.

Currently the BDA MPEG-2 Transport Information Filter (TIF) does not support this event, so this method is not called.

Syntax

HRESULT ScheduleDeleted(
  VARIANT  varScheduleEntryDescriptionID
);

Parameters

varScheduleEntryDescriptionID

[in] Specifies the unique identifier of the schedule entry that was deleted.

Return Values

Return S_OK if successful, or an error code.

Remarks

The event sink is not required to support this event; it may return E_NOTIMPL.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ScheduleEntryChanged

The ScheduleEntryChanged method is called by the TIF when information about one or more schedule entries has changed.

Syntax

HRESULT ScheduleEntryChanged(
  VARIANT  varScheduleEntryDescriptionID
);

Parameters

varScheduleEntryDescriptionID

[in] Specifies the unique identifier of the program that has changed. Call IGuideData::GetScheduleEntryProperties to get information about the program. The value of this parameter may be an empty VARIANT type (VT_EMPTY); if so, examine all of the programs to determine which ones have changed.

Return Values

Return S_OK if successful, or an error code.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ServiceChanged

The ServiceChanged method is called when a service has been changed.

Syntax

HRESULT ServiceChanged(
  VARIANT  varServiceDescriptionID
);

Parameters

varServiceDescriptionID

[in] Specifies the unique identifier of the service that has changed.

Return Values

Return S_OK if successful, or an error code.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataEvent::ServiceDeleted

The ServiceDeleted method is called when a service has been deleted.

Currently the BDA MPEG-2 Transport Information Filter (TIF) does not support this event, so this method is not called.

Syntax

HRESULT ServiceDeleted(
  VARIANT  varServiceDescriptionID
);

Parameters

varServiceDescriptionID

[in] Specifies the unique identifier of the service that was deleted.

Return Values

Return S_OK if successful, or an error code.

Remarks

The event sink is not required to support this event; it may return E_NOTIMPL.

See Also

  • Error and Success Codes
  • IGuideDataEvent Interface


IGuideDataProperty Interface

The IGuideDataProperty interface represents the name, value, and language of a property associated with a Service, Program or ScheduleEntry object.

In addition to the methods inherited from IUnknown, the IGuideDataProperty interface exposes the following methods.

Method | Description
get_Language | Retrieves the language associated with the property.
get_Name | Retrieves the name of the property.
get_Value | Retrieves the value associated with the property.

Requirements

Include Bdatif.h.


IGuideDataProperty::get_Language

The get_Language method retrieves the language associated with the property.

Syntax

HRESULT get_Language(
  long* pidLang
);

Parameters

pidLang

[out] Pointer to a variable that receives the language identifier.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IGuideDataProperty Interface


IGuideDataProperty::get_Name

The get_Name method retrieves the name of the property.

Syntax

HRESULT get_Name(
  BSTR* pbstrName
);

Parameters

pbstrName

[out] Pointer to a variable that receives a string containing the property name, for example "Description.ID" or "Description.Title".

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • Error and Success Codes
  • IGuideDataProperty Interface


IGuideDataProperty::get_Value

The get_Value method retrieves the value associated with the property.

Syntax

HRESULT get_Value(
  VARIANT* pvar
);

Parameters

pvar

[out] Pointer to a variable that receives the value of the property as a VARIANT.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

If the name of the property is "Description.Name" then the value of the property is the actual name of the service or show.

See Also

  • Error and Success Codes
  • IGuideDataProperty Interface


IMPEG2_TIF_CONTROL Interface

The IMPEG2_TIF_CONTROL interface is implemented by the BDA Network Provider. A Transport Information Filter (TIF) can use this interface to register itself and request table sections carried on specific PIDs within the transport stream. The Network Provider Filter instructs the MPEG-2 Demultiplexer (Demux) to send or stop sending the specified packets to the TIF's input pin. All sections are delivered by the Demux to the TIF as complete MPEG-2 table sections.

This interface is now obsolete. Instead, use the IBDA_TIF_REGISTRATION interface to register the TIF with the Network Provider, and use the IMPEG2PIDMap interface to map or unmap PIDs.

In addition to the methods inherited from IUnknown, the IMPEG2_TIF_CONTROL interface exposes the following methods.

Method | Description
AddPIDs | Notifies the Network Provider which PIDs the TIF should receive.
DeletePIDs | Informs the Network Provider that the TIF no longer requires the specified PID.
GetPIDCount | Retrieves the number of MPEG2 Packet IDs being filtered by the Demux into the TIF's input data.
GetPIDs | Retrieves the list of MPEG2 Packet IDs being filtered into the TIF's input data.
RegisterTIF | Called by the Transport Information Filter to register itself with the Network Provider.
UnregisterTIF | Called by the Transport Information Filter to unregister itself with the Network Provider.

Requirements

Include Bdatif.h.

See Also

  • Microsoft TV Technologies
  • Transport Information Interfaces


IMPEG2_TIF_CONTROL::AddPIDs

The AddPIDs method tells the Network Provider which PIDs the TIF should receive.

Syntax

HRESULT AddPIDs(
  ULONG  ulcPIDs,
  ULONG*  pulPIDs
);

Parameters

ulcPIDs

[in] Specifies the number of PIDs to add. This value must be equal to the number of elements in the array specified by pulPIDs.

pulPIDs

[in] Specifies an array of PID values to add. The array must contain ulcPIDs elements.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

Only the TIF knows which table sections it requires. It uses this method to tell the Network Provider the PIDs for the packets that contain those tables. The Network Provider forwards the information to the Demux, which immediately begins routing packets with the specified PIDs to the TIF.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface
  • IMPEG2_TIF_CONTROL::GetPIDs


IMPEG2_TIF_CONTROL::DeletePIDs

The DeletePIDs method informs the Network Provider that the TIF no longer requires the specified PID.

Syntax

HRESULT DeletePIDs(
  ULONG  ulcPIDs,
  ULONG*  pulPIDs
);

Parameters

ulcPIDs

[in] Specifies the number of PIDs to delete. This value must equal the number of elements in the array specified by pulPIDs.

pulPIDs

[in] Specifies an array of PID values containing ulcPIDs elements.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

This method is called if a set of tables in the transport stream goes away, in order to remove the PSI/SI MPEG2 packet IDs from the TIF's data stream.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface


IMPEG2_TIF_CONTROL::GetPIDCount

The GetPIDCount method retrieves the number of MPEG2 Packet IDs being filtered by the MPEG-2 Demultiplexer into the TIF's input data.

Syntax

HRESULT GetPIDCount(
  ULONG*  pulcPIDs
);

Parameters

pulcPIDs

[out] Pointer to a variable that receives the number of PIDs currently being filtered to the Demux.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

A custom TIF extension might or might not need this method.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface
  • IMPEG2_TIF_CONTROL::GetPIDs


IMPEG2_TIF_CONTROL::GetPIDs

The GetPIDs method retrieves the list of MPEG2 Packet IDs being filtered into the TIF's input data.

Syntax

HRESULT GetPIDs(
  ULONG*  pulcPIDs,
  ULONG*  pulPIDs
);

Parameters

pulcPIDs

[out] Pointer to a variable that receives the number of PIDs that were retrieved.

pulPIDs

[out] Pointer to a variable that receives an array of returned ULONG values representing the PID values. The number of elements in the array is equal to the value of pulcPIDs.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

Remarks

A custom TIF extension might or might not have need for this method.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface
  • IMPEG2_TIF_CONTROL::AddPIDs
  • IMPEG2_TIF_CONTROL::GetPIDCount


IMPEG2_TIF_CONTROL::RegisterTIF

The RegisterTIF method is called by the Transport Information Filter (TIF) to register itself with the Network Provider.

Syntax

HRESULT RegisterTIF(
  IUnknown*  pUnkTIF,
  ULONG*  pvRegistrationContext
);

Parameters

pUnkTIF

[in] Pointer to the TIF's IUnknown interface.

pvRegistrationContext

[in, out] Pointer to a variable that receives an identifier. Use this value as the parameter to the IMPEG2_TIF_CONTROL::UnregisterTIF method.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Could not find a necessary interface on the TIF.
VFW_E_ALREADY_CONNECTED | A TIF is already registered with the Network Provider.

Remarks

Call this method immediately after the TIF's input pin is connected to the Demux.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface


IMPEG2_TIF_CONTROL::UnregisterTIF

The UnregisterTIF method unregisters the TIF with the Network Provider.

Syntax

HRESULT UnregisterTIF(
  ULONG  pvRegistrationContext
);

Parameters

pvRegistrationContext

[in] Identifier returned by the IMPEG2_TIF_CONTROL::RegisterTIF method.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_INVALIDARG | Invalid argument.

Remarks

Call this method after the TIF's intput pin has been disconnected from the Demux.

See Also

  • Error and Success Codes
  • IMPEG2_TIF_CONTROL Interface


ITuneRequestInfo Interface

The ITuneRequestInfo interface is implemented on the BDA MPEG2 Transport Information Filter (TIF) and is used by the Network Provider. When the Network Provider receives a tune request, it is not guaranteed that all the necessary locator information will be present in the locator object associated with the tune request. If information is missing, the Network Provider uses this interface to instruct the TIF to fill in the locator data. Similarly, a tune request might not contain a complete list of all the components (substreams) available on the service at a given time. After the Network Provider has tuned to a service, it can ask the TIF to fill in the component information associated with the tune request. An application can then re-examine the tune request after it has been submitted, and compare it to the list of default preferred component types to determine whether to tune to a particular audio stream, or inform the user of any substreams that were not mentioned in the EPG data. For more information, see ITuningSpace::get_DefaultPreferredComponentTypes.

If the TIF is not able to provide the locator data for the transport stream, it must provide the default locator for the tuning space associated with the tune request.

In addition to the methods inherited from IUnknown, the ITuneRequestInfo interface exposes the following methods.

Method | Description
CreateComponentList | Creates a new Components collection for the tune request, and fills it in with all network-specific data after the receiver has tuned to the service.
GetComponentData | Fills in all network-specific component data for the existing Components collection on the specified tune request.
GetLocatorData | Provides channel/program locator information for the specified tune request.
GetNextLocator | Creates a new tune request with locator information for the next transport stream on the network.
GetNextProgram | Creates a new tune request with channel/program locator information for the next service on the current transport stream.
GetPreviousLocator | Creates a new tune request with locator information for the previous transport stream on the network.
GetPreviousProgram | Creates a new tune request with locator information for the previous service on the current transport stream.

Requirements

Include Bdatif.h.


ITuneRequestInfo::CreateComponentList

The CreateComponentList method creates a new Components collection for the tune request, and fills it in with all network-specific data after the receiver has tuned to the service.

Syntax

HRESULT CreateComponentList(
  ITuneRequest*  pCurrentRequest
);

Parameters

pCurrentRequest

[in] Pointer to the ITuneRequest interface on the tune request.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded and new data was added.
S_FALSE | The method succeeded but no new data was added.
E_FAIL | No data could be acquired.

Remarks

After the Network Provider has acquired the correct transport stream, it asks the TIF to fill in the component data. If the tune request does not already have a components list, the Network Provider calls this method and asks the TIF to create one based on the relevant transport stream tables. Generally, the components will include one or more audio streams, video, data, and text. Each component has a component type, and on MPEG2 tuning spaces each component has an associated PID and pcrPID. Ideally, when the Guide Store Loader creates tune requests, it will include all the component information that is available.

The ITuneRequestInfo::GetComponentData method is used to enable the TIF to change an existing list of components. S_FALSE indicates nothing was changed.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetComponentData

The GetComponentData method fills in all network-specific component data for the existing Components collection on the specified tune request.

Syntax

HRESULT GetComponentData(
  ITuneRequest*  pCurrentRequest
);

Parameters

pCurrentRequest

[in] Pointer to the ITuneRequest interface on the tune request.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded and new data was added.
S_FALSE | The method succeeded but no new data was added.

Remarks

The Network Provider calls this method after the tuner has tuned to the specified service.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetLocatorData

The GetLocatorData method fills in channel or program locator information for the specified tune request.

Syntax

HRESULT GetLocatorData(
  ITuneRequest*  pRequest
);

Parameters

pRequest

[in] Pointer to the ITuneRequest interface on the tune request.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded and new locator data was acquired.
S_FALSE | The method succeeded but no new locator data was acquired.
E_POINTER | Request is not valid.

Remarks

After the TIF fills in the locator information, the Network Provider uses that information to configure the tuner and demodulator. It is expected that the TIF will always know everything about a locator. If it doesn't know how to locate a specific tune request, it can always fall back to the default locator for the tuning space. As soon as the TIF starts getting tables from the default stream, it signals the Network Provider, which then asks for the new locator data. When the TIF fills that in, it signals the Network Provider, which tunes again using the new information. When the TIF begins getting tables on the new stream, it signals the Network Provider again, and the process is repeated.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetNextLocator

The GetNextLocator method creates a new tune request with locator information for the next transport stream on the network.

Syntax

HRESULT GetNextLocator(
  ITuneRequest*  pCurrentRequest,
  ITuneRequest**  ppTuneRequest
);

Parameters

pCurrentRequest

[in] Specifies the ITuneRequest interface of the current tune request. NULL means to return information for the first stream.

ppTuneRequest

[out] Pointer to a variable that receives a tune request for the next transport stream.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_POINTER | CurrentRequest is not valid, or TuneRequest is NULL.

Remarks

This method is used internally by the Network Provider's IScanningTuner::SeekUp and IScanningTuner::SeekDown methods, and is also useful for any Guide Store Loader that scans a network for EPG information.

Currently this method is not implemented for DVB-C or DVB-S networks, and the method returns E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetNextProgram

The GetNextProgram method creates a new tune request with channel or program locator information for the next service.

Syntax

HRESULT GetNextProgram(
  ITuneRequest*  pCurrentRequest,
  ITuneRequest**  ppTuneRequest
);

Parameters

pCurrentRequest

[in] Specifies the ITuneRequest interface of the current request.

ppTuneRequest

[out] Pointer to a variable that will receive a tune request for the next service on the transport stream.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_POINTER | CurrentRequest is not valid, or TuneRequest is NULL.

Remarks

This method might be used by a custom Guide Store Loader to enumerate the available services on a transport stream.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetPreviousLocator

The GetPreviousLocator method creates a new tune request with locator information for the previous transport stream.

Syntax

HRESULT GetPreviousLocator(
  ITuneRequest*  pCurrentRequest,
  ITuneRequest**  ppTuneRequest
);

Parameters

pCurrentRequest

[in] Specifies current request.

ppTuneRequest

[out] Pointer to a variable that receives the tune request for the previous transport stream in the network.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_POINTER | CurrentRequest is not valid, or TuneRequest is NULL.

Remarks

Currently this method is not implemented for DVB-C or DVB-S networks, and the method returns E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


ITuneRequestInfo::GetPreviousProgram

The GetPreviousProgram method creates a new tune request with channel or program locator information for the previous service.

Syntax

HRESULT GetPreviousProgram(
  ITuneRequest*  pCurrentRequest,
  ITuneRequest**  ppTuneRequest
);

Parameters

pCurrentRequest

[in] Specifies the current request.

ppTuneRequest

[out] Pointer to a variable that receives a tune request for the previous service in the current transport stream.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_POINTER | CurrentRequest is not valid, or TuneRequest is NULL.

Remarks

This method might be used by a custom Guide Store Loader to enumerate the available services on a transport stream.

See Also

  • Error and Success Codes
  • ITuneRequestInfo Interface


BDA Filter Interfaces

The following section contains reference pages for low-level interfaces that are used in communication between the Broadcast Driver Architecture (BDA) Device filters, and other filters in the graph, specifically the BDA Network Provider and BDA IP Sink filter. This documentation is relevant for those who are developing a custom Network Provider filter or a BDA device driver. Applications based on DirectX 9.0 will need to use the IScanningTuner interface on the Network Provider in order to submit tune requests. No other interfaces are intended for use by applications. Specifically, applications should never attempt to perform tuning by controlling the BDA device filters directly, but should always use the tuning abstraction layer provided by the Microsoft Unified Tuning Model.

Network Provider Interfaces

Interface | Description
IBDA_NetworkProvider | Provides methods that BDA device filters call to register themselves after they are added to the graph.
IBDA_EthernetFilter | Provides methods that are called by the BDA IPSink filter in order to give the Network Provider a list of multicast Ethernet addresses being requested by an application.
IBDA_IPV4Filter | Provides methods that are called by the BDA IPSink filter in order to give the Network Provider a list of multicast IPv4 Ethernet addresses being requested by an application.
IBDA_IPV6Filter | Provides methods that are called by the BDA IPSink filter in order to give the Network Provider a list of multicast IPv6 Ethernet addresses being requested by an application.
IFrequencyMap | Sets the frequency table used by the BDA Network Provider filter.
IScanningTuner | Provides methods that permit direct control of a tuner that supports searching for valid programming.
ITuner | Provides methods for passing tune requests down to the hardware device and receiving current tuning settings.

BDA IP Sink Interfaces

Interface | Description
IBDA_IPSinkControl | Implemented on the BDA IP Sink filter, which manages the delivery of in-band IP data to the network stack.
IBDA_IPSinkInfo | This interface supersedes IBDA_IPSinkControl.

BDA Device Filter Interfaces

The following interfaces are automatically exposed on BDA device filters through the KsProxy wrapper filter which translates Ring 0 property sets and method sets on device drivers into Ring 3 COM interfaces. In other words, these interfaces are how the device drivers communicate with the Network Provider in the filter graph. (For more information, see How Hardware Devices Participate in the Filter Graph.)

Since these interfaces are simply translations of driver property and method sets, readers are referred to the Microsoft® Windows DDK for more information.

Interface | Description
IBDA_AutoDemodulate | If a BDA device filter, specifically a demodulator, exposes this interface, it indicates that the filter can automatically detect signal characteristics.
IBDA_DeviceControl | Implemented on all BDA device filters. The methods provided by this interface are called by a Network Provider to control a BDA device.
IBDA_DigitalDemodulator | Exposed on BDA demodulators that are not capable of automatically detecting the characteristics of a signal.
IBDA_FrequencyFilter | Implemented on a BDA tuner device, and is used by the Network Provider to tell the tuner how to set its frequencies.
IBDA_LNBInfo | Implemented on a BDA device filter, specifically an LNB device. The methods are called by the Network Provider to instruct the device on how to acquire the satellite signal.
IBDA_NullTransform | Implemented on all BDA device filters. The Network Provider filter calls these methods to instruct the filter to either pass data through without modifying it, or else to perform its particular transformation on the data.
IBDA_PinControl | Exposed on a BDA device filter's pins. A Network Provider calls these methods to determine the type and ID of each pin on the filter.
IBDA_SignalStatistics | Implemented on a BDA device filter and provides methods by which the filter can describe the condition of a signal that is being received.
IBDA_Topology | Provides methods that are used by a Network Provider to discover the capabilities of a device filter, and to control it.
IBDA_VoidTransform | Implemented on a BDA device filter. It is used by the Network Provider to inactivate a portion of a filter graph without stopping the graph.


IBDA_AutoDemodulate Interface

If a BDA device filter, specifically a demodulator, exposes this interface, it indicates that the filter can automatically detect signal characteristics. With this information, the Network Provider can be more efficient in managing the tuning process. For more information, see KSPROPSETID_BdaAutodemodulate in the Windows DDK.

In addition to the methods inherited from IUnknown, the IBDA_AutoDemodulate interface exposes the following methods.

Method | Description
put_AutoDemodulate | Instructs the BDA device filter to automatically detect signal characteristics.


IBDA_AutoDemodulate::put_AutoDemodulate

The put_AutoDemodulate method instructs the BDA device filter to automatically detect signal characteristics.

Syntax

HRESULT put_AutoDemodulate();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_AutoDemodulate Interface


IBDA_DeviceControl Interface

The IBDA_DeviceControl interface is implemented on all BDA device filters. The methods provided by this interface are called by a Network Provider to control a BDA device. Each instance of a device has one transaction list. A Network Provider first calls the StartChanges method. This deletes any previous uncommitted changes that were still pending. Then a Network Provider modifies whatever properties on the filter are required for the particular tuning operation. Then it calls the CheckChanges method to determine whether the modifications will be successful, without instructing the filter to actually make the changes. If this call succeeds, then a Network Provider calls CommitChanges to cause the filter to actually modify the specified properties. For more information, see "Changing BDA Filter Properties" in the Windows DDK.

In addition to the methods inherited from IUnknown, the IBDA_DeviceControl interface exposes the following methods.

Method | Description
CheckChanges | Queries the device filter as to whether the changes that are pending would succeed if they were committed.
CommitChanges | Instructs the device to perform the changes specified in the previous call to StartChanges.
GetChangeState | Returns a value indicating whether any uncommitted changes are currently pending in the filter.
StartChanges | Called by a Network Provider before it begins to modify a set of properties on a BDA device filter.


IBDA_DeviceControl::CheckChanges

The CheckChanges method queries the device filter as to whether the changes that are pending would succeed if they were committed.

Syntax

HRESULT CheckChanges();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method provides a means to determine whether a particular set of changes would be successful, without actually modifying any parameters on the device.

See Also

  • Error and Success Codes
  • IBDA_DeviceControl Interface


IBDA_DeviceControl::CommitChanges

The CommitChanges method instructs the device to perform the changes specified in the previous call to StartChanges.

Syntax

HRESULT CommitChanges();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DeviceControl Interface


IBDA_DeviceControl::GetChangeState

The GetChangeState method returns a value indicating whether any uncommitted changes are currently pending in the filter.

Syntax

HRESULT GetChangeState(
  ULONG*  pState
);

Parameters

pState

[out] Pointer to a variable that receives the current state of the filter. See BDA_CHANGE_STATE in the Windows DDK for possible values.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DeviceControl Interface


IBDA_DeviceControl::StartChanges

The StartChanges method is called by a Network Provider before it begins to modify a set of properties on a BDA device filter.

Syntax

HRESULT StartChanges();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The device filter validates and accumulates all changes requested after StartChanges. It makes the accumulated list of changes when CommitChanges is called.

See Also

  • Error and Success Codes
  • IBDA_DeviceControl Interface


IBDA_DigitalDemodulator Interface

The IBDA_DigitalDemodulator interface is exposed on BDA device filters, specifically demodulators, that are not capable of automatically detecting the characteristics of a signal. A Network Provider calls these methods on the filter to provide the demodulator with the information it needs to acquire a particular signal. The Network Provider obtains these values from the Locator object associated with the tune request or tuning space.

In addition to the methods inherited from IUnknown, the IBDA_DigitalDemodulator interface exposes the following methods.

Method | Description
get_InnerFECMethod | Retrieves the inner forward error correction method.
get_InnerFECRate | Retrieves the inner forward error correction rate being used on the signal.
get_ModulationType | Retrieves the modulation type for the signal.
get_OuterFECMethod | Retrieves the outer forward error correction method for the signal.
get_OuterFECRate | Retrieves the outer forward error correction rate for the signal.
get_SpectralInversion | Retrieves the spectral inversion value for the signal.
get_SymbolRate | Retrieves the symbol rate for the signal.
put_InnerFECMethod | Specifies the inner forward error correction method for the signal.
put_InnerFECRate | Specifies the inner forward error correction rate.
put_ModulationType | Specifies the modulation type for the signal.
put_OuterFECMethod | Specifies the outer forward error correction method for the signal.
put_OuterFECRate | Specifies the outer forward error correction rate for the signal.
put_SpectralInversion | Specifies the spectral inversion value for the signal.
put_SymbolRate | Specifies the symbol rate for the signal.


IBDA_DigitalDemodulator::get_InnerFECMethod

The get_InnerFECMethod method retrieves the inner forward error correction method.

Syntax

HRESULT get_InnerFECMethod(
  FECMethod*  pFECMethod
);

Parameters

pFECMethod

[out] Pointer that receives an FECMethod variable.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_OuterFECMethod
  • IBDA_DigitalDemodulator::put_InnerFECMethod


IBDA_DigitalDemodulator::get_InnerFECRate

The get_InnerFECRate method retrieves the inner forward error correction rate being used on the signal.

Syntax

HRESULT get_InnerFECRate(
  BinaryConvolutionCodeRate*  pFECRate
);

Parameters

pFECRate

[out] Pointer that receives a BinaryConvolutionCodeRate variable that indicates the rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_OuterFECRate
  • IBDA_DigitalDemodulator::put_InnerFECRate


IBDA_DigitalDemodulator::get_ModulationType

The get_ModulationType method retrieves the modulation type for the signal.

Syntax

HRESULT get_ModulationType(
  ModulationType*  pModulationType
);

Parameters

pModulationType

[out] Pointer that receives a ModulationType variable indicating the modulation type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::put_ModulationType


IBDA_DigitalDemodulator::get_OuterFECMethod

The get_OuterFECMethod method retrieves the outer forward error correction method for the signal .

Syntax

HRESULT get_OuterFECMethod(
  FECMethod*  pFECMethod
);

Parameters

pFECMethod

[out] Pointer that receives an FECMethod variable that indicates the FEC method.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_InnerFECMethod
  • IBDA_DigitalDemodulator::put_OuterFECMethod


IBDA_DigitalDemodulator::get_OuterFECRate

The get_OuterFECRate method retrieves the outer forward error correction rate for the signal.

Syntax

HRESULT get_OuterFECRate(
  BinaryConvolutionCodeRate*  pFECRate
);

Parameters

pFECRate

[out] Pointer that receives a BinaryConvolutionCodeRate variable that indicates the rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_InnerFECRate
  • IBDA_DigitalDemodulator::put_OuterFECRate


IBDA_DigitalDemodulator::get_SpectralInversion

The get_SpectralInversion method retrieves the spectral inversion value for the signal.

Syntax

HRESULT get_SpectralInversion(
  SpectralInversion*  pSpectralInversion
);

Parameters

pSpectralInversion

[out] Pointer that receives a SpectralInversion variable.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

For more information, see KSPROPERTY_BDA_SPECTRAL_INVERSION in the Windows DDK.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::put_SpectralInversion


IBDA_DigitalDemodulator::get_SymbolRate

The get_SymbolRate method retrieves the symbol rate for the signal.

Syntax

HRESULT get_SymbolRate(
  ULONG*  pSymbolRate
);

Parameters

pSymbolRate

[out] Pointer that receives the symbol rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::put_SymbolRate


IBDA_DigitalDemodulator::put_InnerFECMethod

The put_InnerFECMethod method specifies the inner forward error correction method for the signal.

Syntax

HRESULT put_InnerFECMethod(
  FECMethod*  pFECMethod
);

Parameters

pFECMethod

[in] Pointer to an FECMethod variable that specifies the inner forward error correction method.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_InnerFECMethod
  • IBDA_DigitalDemodulator::put_OuterFECMethod


IBDA_DigitalDemodulator::put_InnerFECRate

The put_InnerFECRate method specifies the inner forward error correction rate.

Syntax

HRESULT put_InnerFECRate(
  BinaryConvolutionCodeRate*  pFECRate
);

Parameters

pFECRate

[in] Pointer to a BinaryConvolutionCodeRate variable that specifies the inner FEC rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_InnerFECRate
  • IBDA_DigitalDemodulator::put_OuterFECRate


IBDA_DigitalDemodulator::put_ModulationType

The put_ModulationType method specifies the modulation type for the signal.

Syntax

HRESULT put_ModulationType(
  ModulationType*  pModulationType
);

Parameters

pModulationType

[in] Pointer to a ModulationType variable that specifies the modulation type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_ModulationType


IBDA_DigitalDemodulator::put_OuterFECMethod

The put_OuterFECMethod method specifies the outer forward error correction method for the signal.

Syntax

HRESULT put_OuterFECMethod(
  FECMethod*  pFECMethod
);

Parameters

pFECMethod

[in] Pointer to an FECMethod variable.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_OuterFECMethod
  • IBDA_DigitalDemodulator::put_InnerFECMethod


IBDA_DigitalDemodulator::put_OuterFECRate

The put_OuterFECRate method specifies the outer forward error correction rate for the signal.

Syntax

HRESULT put_OuterFECRate(
  BinaryConvolutionCodeRate*  pFECRate
);

Parameters

pFECRate

[in] Pointer to a BinaryConvolutionCodeRate variable that specifies the FEC rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_OuterFECRate
  • IBDA_DigitalDemodulator::put_InnerFECRate


IBDA_DigitalDemodulator::put_SpectralInversion

The put_SpectralInversion method specifies the spectral inversion value for the signal.

Syntax

HRESULT put_SpectralInversion(
  SpectralInversion*  pSpectralInversion
);

Parameters

pSpectralInversion

[in] Pointer to a SpectralInversion variable.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_SpectralInversion


IBDA_DigitalDemodulator::put_SymbolRate

The put_SymbolRate method specifies the symbol rate for the signal.

Syntax

HRESULT put_SymbolRate(
  ULONG*  pSymbolRate
);

Parameters

pSymbolRate

[in] Pointer to a ULONG that specifies the symbol rate.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_DigitalDemodulator Interface
  • IBDA_DigitalDemodulator::get_SymbolRate


IBDA_EthernetFilter Interface

The IBDA_EthernetFilter interface is implemented on a Network Provider. The methods are called by the BDA IPSink filter in order to give the Network Provider a list of multicast Ethernet addresses being requested by an application. The Network Provider then informs all registered transport information filters (TIFs) of the new addresses. The TIF(s) are responsible for mapping those addresses to PIDs and passing the PIDs back to the Network Provider, which then resets the PID list for the IP data output pin on the MPEG-2 Demultiplexer. This causes the IP data on the specified PIDs to be routed through the data services segment of the graph and on to Winsock where the listening application can receive it. The IBDA_IPV4Filter interface performs the same function for IPv4 multicast addresses.

In addition to the methods inherited from IUnknown, the IBDA_EthernetFilter interface exposes the following methods.

Method | Description
GetMulticastList | Retrieves the list of multicast addresses stored by the Network Provider.
GetMulticastListSize | Retrieves the number of addresses currently in the list.
GetMulticastMode | Retrieves the multicast mode.
PutMulticastList | Specifies the list of multicast addresses on the Network Provider.


IBDA_EthernetFilter::GetMulticastListSize

The GetMulticastListSize method retrieves the number of addresses currently in the list.

Syntax

HRESULT GetMulticastListSize(
  ULONG*  pulcbAddresses
);

Parameters

pulcbAddresses

[out] Pointer that receives the number of addresses currently in the Network Provider's list.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Addresses in the address list are byte aligned in Network order. UlcbAddresses will always be an integer multiple of the size of an Ethernet address.

See Also

  • Error and Success Codes
  • IBDA_EthernetFilter Interface


IBDA_EthernetFilter::GetMulticastList

The GetMulticastList method retrieves the list of multicast addresses on the Network Provider.

Syntax

HRESULT GetMulticastList(
  ULONG*  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in, out] On input, specifies the maximum number of addresses to retrieve, multiplied by the number of bytes per address. On output, receives the actual number of bytes retrieved.

pAddressList

[out, size_is(ulcbAddresses)] Pointer that receives an array of addresses whose size in bytes is equal to ulcbAddresses. See Remarks.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The declaration of pAddressList is not COM compliant. As a workaround, the client should allocate the pAddressList buffer. The buffer should be the same size as advertised in the pulcbAddresses parameter. The network provider will just fill in the buffer allocated by the caller.

See Also

  • Error and Success Codes
  • IBDA_EthernetFilter Interface


IBDA_EthernetFilter::GetMulticastMode

The GetMulticastMode method retrieves the multicast mode.

Syntax

HRESULT GetMulticastMode(
  ULONG*  pulModeMask
);

Parameters

pulModeMask

[out] Pointer that receives the multicast mode.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

See the Windows DDK for possible values.

See Also

  • Error and Success Codes
  • IBDA_EthernetFilter Interface


IBDA_EthernetFilter::PutMulticastList

The PutMulticastList method sets the list of multicast addresses on the Network Provider.

Syntax

HRESULT PutMulticastList(
  ULONG  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in] Specifies the number of addresses in the list, multiplied by the number of bytes per address.

pAddressList

[in, size_is(ulcbAddresses)] Pointer to an array of addresses whose size in bytes is equal to ulcbAddresses.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_EthernetFilter Interface


IBDA_FrequencyFilter Interface

The IBDA_FrequencyFilter interface is implemented on a BDA tuner device, and is used by the Network Provider to tell the tuner how to set its frequencies.

In addition to the methods inherited from IUnknown, the IBDA_FrequencyFilter interface exposes the following methods.

Method | Description
get_Autotune | Retrieves a channel frequency to scan for a precise signal.
get_Bandwidth | Retrieves the bandwidth parameters.
get_Frequency | Retrieves the frequency parameters.
get_FrequencyMultiplier | Retrieves the frequency multiplier parameters.
get_Polarity | Retrieves the polarity parameters.
get_Range | Retrieves the range parameters.
put_Autotune | Specifies a channel frequency to scans for a precise signal.
put_Bandwidth | Specifies the bandwidth parameters.
put_Frequency | Specifies the frequency parameters.
put_FrequencyMultiplier | Specifies the frequency multiplier parameters.
put_Polarity | Specifies the polarity parameters.
put_Range | Specifies the range parameters


IBDA_FrequencyFilter::get_Autotune

The get_Autotune method retrieves the autotune frequency.

Syntax

HRESULT get_Autotune(
  ULONG*  pulTransponder
);

Parameters

pulTransponder

[in, out] Specifies the transponder frequency.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::put_Autotune


IBDA_FrequencyFilter::get_Bandwidth

The get_Bandwidth method retrieves the bandwidth.

Syntax

HRESULT get_Bandwidth(
  ULONG*  pulBandwidth
);

Parameters

pulBandwidth

[out] Pointer that receives the bandwidth. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::put_Bandwidth


IBDA_FrequencyFilter::get_Frequency

The get_Frequency method retrieves the frequency.

Syntax

HRESULT get_Frequency(
  ULONG*  pulFrequency
);

Parameters

pulFrequency

[out] Pointer that receives the frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_FrequencyMultiplier
  • IBDA_FrequencyFilter::put_Frequency


IBDA_FrequencyFilter::get_FrequencyMultiplier

The get_FrequencyMultiplier method retrieves the frequency multiplier. The frequency multiplier determines the frequency units for the methods on this interface. The default value is 1000, meaning that frequencies are expressed in kilohertz (kHz).

Syntax

HRESULT get_FrequencyMultiplier(
  ULONG*  pulMultiplier
);

Parameters

pulMultiplier

[out] Pointer that receives the multiplier.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Frequency
  • IBDA_FrequencyFilter::put_FrequencyMultiplier


IBDA_FrequencyFilter::get_Polarity

The get_Polarity method retrieves the polarity.

Syntax

HRESULT get_Polarity(
  Polarisation*  pPolarity
);

Parameters

pPolarity

[out] Pointer that receives a Polarisation variable.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::put_Polarity


IBDA_FrequencyFilter::get_Range

The get_Range method retrieves the range.

Syntax

HRESULT get_Range(
  ULONG*  pulRange
);

Parameters

pulRange

[out] Pointer that receives the range.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::put_Range


IBDA_FrequencyFilter::put_Autotune

The put_Autotune method specifies whether to activate the device's autotune capabilities.

Syntax

HRESULT put_Autotune(
  ULONG  ulTransponder
);

Parameters

ulTransponder

[in] Specifies the transponder frequency.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Autotune


IBDA_FrequencyFilter::put_Bandwidth

The put_Bandwidth method specifies the bandwidth.

Syntax

HRESULT put_Bandwidth(
  ULONG  ulBandwidth
);

Parameters

ulBandwidth

[in] Specifies the bandwidth. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Bandwidth


IBDA_FrequencyFilter::put_Frequency

The put_Frequency method specifies the frequency.

Syntax

HRESULT put_Frequency(
  ULONG  ulFrequency
);

Parameters

ulFrequency

[in] Specifies the frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Frequency
  • IBDA_FrequencyFilter::put_FrequencyMultiplier


IBDA_FrequencyFilter::put_FrequencyMultiplier

The put_FrequencyMultiplier method specifies the frequency multiplier. The frequency multiplier determines the frequency units for the methods on this interface. The default value is 1000, meaning that frequencies are expressed in kilohertz (kHz).

Syntax

HRESULT put_FrequencyMultiplier(
  ULONG  ulMultiplier
);

Parameters

ulMultiplier

[in] Specifies the multiplier.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_FrequencyMultiplier
  • IBDA_FrequencyFilter::put_Frequency


IBDA_FrequencyFilter::put_Polarity

The put_Polarity method specifies the polarity of the signal.

Syntax

HRESULT put_Polarity(
  Polarisation  Polarity
);

Parameters

Polarity

[in] Specifies the polarity as a member of the Polarisation enumerated type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Polarity


IBDA_FrequencyFilter::put_Range

The put_Range method specifies the range.

Syntax

HRESULT put_Range(
  ULONG  ulRange
);

Parameters

ulRange

[in] Specifies the range.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_FrequencyFilter Interface
  • IBDA_FrequencyFilter::get_Range


IBDA_IPSinkControl Interface

The IBDA_IPSinkControl interface is implemented on the BDA IP Sink filter, which manages the delivery of in-band IP data to the network stack. This interface is superseded by IBDA_IPSinkInfo.

In addition to the methods inherited from IUnknown, the IBDA_IPSinkControl interface exposes the following methods.

Method | Description
GetAdapterIPAddress | Retrieves the IP address of the NIC.
GetMulticastList | Retrieves a list of the multicast addresses to which the IP Sink filter is listening.


IBDA_IPSinkControl::GetAdapterIPAddress

The GetAdapterIPAddress method retrieves the IP address of the NIC.

Syntax

HRESULT GetAdapterIPAddress(
  unsigned long  *pulcbSize,
  BYTE**  pbBuffer
);

Parameters

pulcbSize

[out] Pointer to a variable that receives the length of the buffer, in bytes.

pbBuffer

[out] Pointer to a byte array containing the address.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

IBDA_IPSinkControl is no longer being supported for Ring 3 clients. Use the BDA_IPSinkInfo interface instead.

See Also

  • Error and Success Codes
  • IBDA_IPSinkControl Interface


IBDA_IPSinkControl::GetMulticastList

The GetMulticastList method retrieves a list of the multicast addresses to which the IP Sink filter is listening.

Syntax

HRESULT GetMulticastList(
  unsigned long  *pulcbSize,
  BYTE**  pbBuffer
);

Parameters

pulcbSize

[out] Pointer to a variable that receives the length of the buffer, in bytes.

pbBuffer

[out] Pointer to a byte array containing the multicast list.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

IBDA_IPSinkControl is no longer being supported for Ring 3 clients. Use the BDA_IPSinkInfo interface instead.

See Also

  • Error and Success Codes
  • IBDA_IPSinkControl Interface


IBDA_IPSinkInfo Interface

The IBDA_IPSinkInfo interface is implemented on the BDA IP Sink filter, which manages the delivery of in-band IP data to the network stack. This interface supersedes IBDA_IPSinkControl.

In addition to the methods inherited from IUnknown, the IBDA_IPSinkInfo interface exposes the following methods.

Method | Description
get_AdapterDescription | Retrieves the description of the network adapter.
get_AdapterIPAddress | Retrieves the IP address of the data that the IP Sink filter receives.
get_MulticastList | Retrieves a list of the multicast addresses to which the IP Sink filter is listening.


IBDA_IPSinkInfo::get_AdapterDescription

The get_AdapterDescription method retrieves the description of the network adapter.

Syntax

HRESULT get_AdapterDescription(
  BSTR*  pbstrBuffer
);

Parameters

pbstrBuffer

[out] Pointer to a BSTR that receives the description.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The caller must free the returned string, using the SysFreeString method.

See Also

  • Error and Success Codes
  • IBDA_IPSinkInfo Interface


IBDA_IPSinkInfo::get_AdapterIPAddress

The get_AdapterIPAddress method retrieves the IP address of the data that the IP Sink filter receives. This address is assigned by the system; it is not guaranteed to be the same for any two instances of the IP Sink filter.

Syntax

HRESULT get_AdapterIPAddress(
  BSTR*  pbstrBuffer
);

Parameters

pbstrBuffer

[out] Pointer to a BSTR that receives the IP address. The returned string has the form N.N.N.N; for example, 3.0.0.0.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The caller must free the returned string, using the SysFreeString method.

See Also

  • Error and Success Codes
  • IBDA_IPSinkInfo Interface


IBDA_IPSinkInfo::get_MulticastList

The get_MulticastList method retrieves a list of the multicast addresses to which the IP Sink filter is listening. This method returns a list of IP addresses in 6-byte IEEE 802.3 format; the list is returned as an array of bytes.

Syntax

HRESULT get_MulticastList(
  ULONG*  pulcbAddresses,
  BYTE**  ppbAddressList
);

Parameters

pulcbAddresses

[out] Pointer to a variable that receives the number of bytes in the returned array.

ppbAddressList

[out, size_is(*pulcbAddresses)] Pointer to variable that receives an array of bytes, of size *pulcbAddresses. Each IP address is 6 consecutive bytes.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The method allocates the memory for the array. The caller must free the memory by calling CoTaskMemFree.

See Also

  • Error and Success Codes
  • IBDA_IPSinkInfo Interface


IBDA_IPV4Filter Interface

The IBDA_ IPV4Filter interface is implemented on a Network Provider. The methods are called by the BDA IPSink filter in order to give the Network Provider a list of multicast Ethernet addresses being requested by an application. The Network Provider then informs all registered transport information filters (TIFs) of the new addresses. The TIF(s) are responsible for mapping those addresses to PIDs and passing the PIDs back to the Network Provider, which then resets the PID list for the IP data output pin on the MPEG-2 Demultiplexer. This causes the IP data on the specified PIDs to be routed through the data services segment of the graph and on to Winsock where the listening application can receive it. The IBDA_EthernetFilter interface performs the same function for Ethernet multicast addresses.

In addition to the methods inherited from IUnknown, the IBDA_IPV4Filter interface exposes the following methods.

Method | Description
GetMulticastList | Retrieves the list of multicast addresses stored by the Network Provider.
GetMulticastListSize | Retrieves the number of addresses in the list.
GetMulticastMode | Retrieves the multicast mode.
PutMulticastList | Specifies the list of multicast addresses on the Network Provider.


IBDA_IPV4Filter::GetMulticastList

The GetMulticastList method retrieves the list of multicast addresses on the Network Provider.

Syntax

HRESULT GetMulticastList(
  ULONG*  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in, out] On input, specifies the maximum number of addresses to retrieve, multiplied by the number of bytes per address. On output, receives the actual number of bytes retrieved.

pAddressList

[out, size_is(ulcbAddresses)] Pointer that receives an array of addresses whose size in bytes is equal to ulcbAddresses.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The declaration of pAddressList is not COM compliant. As a workaround, the client should allocate the pAddressList buffer. The buffer should be the same size as advertised in the pulcbAddresses parameter. The network provider will just fill in the buffer allocated by the caller.

See Also

  • Error and Success Codes
  • IBDA_IPV4Filter Interface


IBDA_IPV4Filter::GetMulticastListSize

The GetMulticastListSize method retrieves the number of addresses in the list.

Syntax

HRESULT GetMulticastListSize(
  ULONG*  pulcbAddresses
);

Parameters

pulcbAddresses

[in, out] Pointer that receives the number of addresses multiplied by the size of an IPv4 address.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is used by an IPv4 Network Data Sink filter to request that a Network Provider make its best effort to tune to the stream(s) on which a list of IPv4 multicast addresses may be transmitted. Addresses in the address list are byte-aligned in Network order. UlcbAddresses will always be an integer multiple of the size of an IPv4 address.

See Also

  • Error and Success Codes
  • IBDA_IPV4Filter Interface


IBDA_IPV4Filter::GetMulticastMode

The GetMulticastMode method retrieves the multicast mode.

Syntax

HRESULT GetMulticastMode(
  ULONG*  pulModeMask
);

Parameters

pulModeMask

[out] Pointer that receives the mask. See the Windows DDK for possible values.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_IPV4Filter Interface


IBDA_IPV4Filter::PutMulticastList

The PutMulticastList method sets the list of multicast addresses on the Network Provider.

Syntax

HRESULT PutMulticastList(
  ULONG  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in] Specifies the number of addresses in the list, times the number of bytes per address.

pAddressList

[in, size_is(ulcbAddresses)] Pointer that receives an array of addresses whose size in bytes is equal to ulcbAddresses.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_IPV4Filter Interface


IBDA_IPV6Filter Interface

In addition to the methods inherited from IUnknown, the IBDA_IPV6Filter interface exposes the following methods.

Method | Description
GetMulticastList | Retrieves the list of multicast addresses stored by the Network Provider.
GetMulticastListSize | Retrieves the size in bytes of the list of multicast addresses.
GetMulticastMode | Retrieves the mode(s) of the multicast.
PutMulticastList | Specifies the parameters of the multicast list.


IBDA_IPV6Filter::GetMulticastList

The GetMulticastList method retrieves the list of multicast addresses on the Network Provider.

Syntax

HRESULT GetMulticastList(
  ULONG*  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in, out] On input, specifies the maximum number of addresses to retrieve, multiplied by the number of bytes per address. On output, receives the actual number of bytes retrieved.

pAddressList

[out, size_is(ulcbAddresses)] Pointer that receives an array of addresses whose size in bytes is equal to ulcbAddresses.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The declaration of pAddressList is not COM compliant. As a workaround, the client should allocate the pAddressList buffer. The buffer should be the same size as advertised in the pulcbAddresses parameter. The network provider will just fill in the buffer allocated by the caller.

See Also

  • Error and Success Codes
  • IBDA_IPV4Filter Interface


IBDA_IPV6Filter::GetMulticastListSize

The GetMulticastListSize method retrieves the size in bytes of the list of multicast addresses.

Syntax

HRESULT GetMulticastListSize(
  ULONG*  pulcbAddresses
);

Parameters

pulcbAddresses

[in, out] Pointer that receives the size in bytes.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

This method is used by the BDA IP Sink filter to request that a Network Provider make its best effort to tune to the stream(s) on which a list of IPv6 multicast addresses may be transmitted. Addresses in the address list are byte aligned in Network order. UlcbAddresses will always be an integer multiple of the size of an IPv6 address.

See Also

  • Error and Success Codes
  • IBDA_IPV6Filter Interface


IBDA_IPV6Filter::GetMulticastMode

The GetMulticastMode method retrieves the mode(s) of the multicast.

Syntax

HRESULT GetMulticastMode(
  ULONG*  pulModeMask
);

Parameters

pulModeMask

[out] Pointer that receives the mode mask.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_IPV6Filter Interface


IBDA_IPV6Filter::PutMulticastList

The PutMulticastList method specifies the parameters of the multicast list.

Syntax

HRESULT PutMulticastList(
  ULONG  ulcbAddresses,
  BYTE   pAddressList []
);

Parameters

ulcbAddresses

[in] Specifies the number of addresses in the list, multiplied by the number of bytes per address.

pAddressList

[in] Pointer to an array of addresses whose size in bytes is equal to ulcbAddresses.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_IPV6Filter Interface


IBDA_LNBInfo Interface

The IBDA_LNBInfo interface is implemented on a BDA device filter, specifically an LNB device. The methods are called by the Network Provider to instruct the device on how to acquire the satellite signal.

In addition to the methods inherited from IUnknown, the IBDA_LNBInfo interface exposes the following methods.

Method | Description
get_HighLowSwitchFrequency | Retrieves the frequency of the high-low switch.
get_LocalOscilatorFrequencyHighBand | Retrieves the high band of the local oscillator frequency.
get_LocalOscilatorFrequencyLowBand | Retrieves the low band of the local oscillator frequency.
put_HighLowSwitchFrequency | Specifies the frequency of the high-low switch.
put_LocalOscilatorFrequencyHighBand | Specifies the frequency of the local oscillator high band.
put_LocalOscilatorFrequencyLowBand | Specifies the frequency of the local oscillator's low band.


IBDA_LNBInfo::get_HighLowSwitchFrequency

The get_HighLowSwitchFrequency method retrieves the frequency of the high-low switch.

Syntax

HRESULT get_HighLowSwitchFrequency(
  ULONG*  pulSwitchFrequency
);

Parameters

pulSwitchFrequency

[in, out] Pointer that receives the frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::put_HighLowSwitchFrequency


IBDA_LNBInfo::get_LocalOscilatorFrequencyHighBand

The get_LocalOscilatorFrequencyHighBand method retrieves the high band of the local oscillator frequency.

Syntax

HRESULT get_LocalOscilatorFrequencyHighBand(
  ULONG*  pulLOFHigh
);

Parameters

pulLOFHigh

[out] Pointer that receives the high band value. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::put_LocalOscilatorFrequencyHighBand


IBDA_LNBInfo::get_LocalOscilatorFrequencyLowBand

The get_LocalOscilatorFrequencyLowBand method retrieves the low band of the local oscillator frequency.

Syntax

HRESULT get_LocalOscilatorFrequencyLowBand(
  ULONG*  pulLOFLow
);

Parameters

pulLOFLow

[out] Pointer that receives the low band of the frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::put_LocalOscilatorFrequencyLowBand


IBDA_LNBInfo::put_HighLowSwitchFrequency

The put_HighLowSwitchFrequency method specifies the frequency of the high-low switch.

Syntax

HRESULT put_HighLowSwitchFrequency(
  ULONG  ulSwitchFrequency
);

Parameters

ulSwitchFrequency

[in] Specifies the frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::get_HighLowSwitchFrequency


IBDA_LNBInfo::put_LocalOscilatorFrequencyHighBand

The put_LocalOscilatorFrequencyHighBand method specifies the frequency of the local oscillator's high band.

Syntax

HRESULT put_LocalOscilatorFrequencyHighBand(
  ULONG  ulLOFHigh
);

Parameters

ulLOFHigh

[in] Specifies the frequency's high band. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::get_LocalOscilatorFrequencyHighBand


IBDA_LNBInfo::put_LocalOscilatorFrequencyLowBand

The put_LocalOscilatorFrequencyLowBand method specifies the frequency of the local oscillator's low band.

Syntax

HRESULT put_LocalOscilatorFrequencyLowBand(
  ULONG  ulLOFLow
);

Parameters

ulLOFLow

[in] Specifies the low band frequency. The units are 1 Hz x the frequency multiplier, where the frequency multiplier is the value returned by the IBDA_FrequencyFilter::get_FrequencyMultiplier method. The default frequency multiplier is 1000, so the default units are kilohertz (kHz).

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_LNBInfo Interface
  • IBDA_LNBInfo::get_LocalOscilatorFrequencyLowBand


IBDA_NetworkProvider Interface

The IBDA_NetworkProvider interface is implemented on a Network Provider filter. It provides methods that BDA device filters call to register themselves after they are added to the graph.

In addition to the methods inherited from IUnknown, the IBDA_NetworkProvider interface exposes the following methods.

Method | Description
RegisterDeviceFilter | Called by a BDA device filter to register itself in the filter graph.
UnRegisterDeviceFilter | Called by BDA device filters when they are removed from the filter graph.


IBDA_NetworkProvider::RegisterDeviceFilter

The RegisterDeviceFilter method is called by a BDA device filter to register itself in the filter graph.

Syntax

HRESULT RegisterDeviceFilter(
  IUnknown*  pUnkFilterControl,
  ULONG*  pulRegisitrationContext
);

Parameters

pUnkFilterControl

[in] Pointer to the filter's IUnknown interface.

pulRegisitrationContext

[out] Pointer that receives the registration context. The filter should store this value and return it in the call to UnRegisterDeviceFilter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_NetworkProvider Interface


IBDA_NetworkProvider::UnRegisterDeviceFilter

The UnRegisterDeviceFilter method is called by BDA device filters when they are removed from the filter graph.

Syntax

HRESULT UnRegisterDeviceFilter(
  ULONG  ulRegistrationContext
);

Parameters

ulRegistrationContext

[in] The registration context that the filter received in the call to RegisterDeviceFilter.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_NetworkProvider Interface


IBDA_NullTransform Interface

The IBDA_NullTransform interface is implemented on all BDA device filters. The Network Provider filter calls these methods to instruct the filter to either pass data through without modifying it, or else to perform its particular transformation on the data.

In addition to the methods inherited from IUnknown, the IBDA_NullTransform interface exposes the following methods.

Method | Description
Start | Restarts the transforms on data flowing through the control node.
Stop | Stops the transforms on data flowing through the control node.


IBDA_NullTransform::Start

The Start method restarts the transforms on data flowing through the control node.

Syntax

HRESULT Start();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_NullTransform Interface


IBDA_NullTransform::Stop

The Stop method stops the transforms on data flowing through the control node.

Syntax

HRESULT Stop();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_NullTransform Interface


IBDA_PinControl Interface

The IBDA_PinControl interface is exposed on a BDA device filter's pins. A Network Provider calls these methods to determine the type and identifier of each pin on the filter. A Network Provider uses this information when building the graph.

In addition to the methods inherited from IUnknown, the IBDA_PinControl interface exposes the following methods.

Method | Description
GetPinID | Retrieves the identifier of the pin.
GetPinType | Retrieves the type of the pin.
RegistrationContext | Retrieves the registration context of a particular pin.


IBDA_PinControl::GetPinID

The GetPinID method retrieves the ID of the pin.

Syntax

HRESULT GetPinID(
  ULONG*  pulPinID
);

Parameters

pulPinID

[out] Pointer that receives the pin's identifier.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_PinControl Interface


IBDA_PinControl::GetPinType

The GetPinType method retrieves the type of the pin.

Syntax

HRESULT GetPinType(
  ULONG*  pulPinType
);

Parameters

pulPinType

[out] Pointer that receives the pin type.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_PinControl Interface


IBDA_PinControl::RegistrationContext

The RegistrationContext method retrieves the registration context of a particular pin.

Syntax

HRESULT RegistrationContext(
  ULONG*  pulRegistrationCtx
);

Parameters

pulRegistrationCtx

[out] Pointer that receives the registration context.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The registration context uniquely identifies an instance of a particular pin. A Network Provider does not modify this value; it simply retains it in order to keep track of the pins in the graph.

See Also

  • Error and Success Codes
  • IBDA_PinControl Interface


IBDA_SignalStatistics Interface

The IBDA_SignalStatistics interface is implemented on a BDA device filter and provides methods by which the filter can describe the condition of a signal that is being received. In addition to the methods inherited from IUnknown, the IBDA_SignalStatistics interface exposes the following methods.

Method | Description
get_SampleTime | Retrieves the sample time used to measure the signal.
get_SignalLocked | Retrieves a Boolean value indicating whether the signal is locked.
get_SignalPresent | Retrieves a Boolean value indicating whether a signal is present.
get_SignalQuality | Retrieves a value from 1 to 100 indicating the quality of the signal.
get_SignalStrength | Retrieves a value that indicates the strength of the signal in decibels.
put_SampleTime | Specifies the sample time used to measure the signal.
put_SignalLocked | Specifies whether the signal is locked.
put_SignalPresent | Specifies whether a signal is present.
put_SignalQuality | Specifies the quality of the signal.
put_SignalStrength | Specifies the strength of the signal in decibels.


IBDA_SignalStatistics::get_SampleTime

The get_SampleTime method retrieves the sample time used to measure the signal.

Syntax

HRESULT get_SampleTime(
  LONG*  plmsSampleTime
);

Parameters

plmsSampleTime

[out] Pointer that receives the sample time.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::put_SampleTime


IBDA_SignalStatistics::get_SignalLocked

The get_SignalLocked method retrieves a Boolean value indicating whether the signal is locked.

Syntax

HRESULT get_SignalLocked(
  BOOLEAN*  pfLocked
);

Parameters

pfLocked

[out] Pointer to a flag indicating whether the signal is locked.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::put_SignalLocked


IBDA_SignalStatistics::get_SignalPresent

The get_SignalPresent method retrieves a Boolean value indicating whether a signal is present.

Syntax

HRESULT get_SignalPresent(
  BOOLEAN*  pfPresent
);

Parameters

pfPresent

[out] Pointer to a flag indicating whether a signal is present.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::put_SignalPresent


IBDA_SignalStatistics::get_SignalQuality

The get_SignalQuality method retrieves a value from 1 to 100 indicating the quality of the signal.

Syntax

HRESULT get_SignalQuality(
  LONG*  plPercentQuality
);

Parameters

plPercentQuality

[out] Pointer that receives the value as a percentage. 100 indicates best quality and 0 indicates worst quality.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::put_SignalQuality


IBDA_SignalStatistics::get_SignalStrength

The get_SignalStrength method retrieves a value that indicates the strength of the signal in decibels.

Syntax

HRESULT get_SignalStrength(
  LONG*  plDbStrength
);

Parameters

plDbStrength

[out] Pointer that receives the signal strength value.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::put_SignalStrength


IBDA_SignalStatistics::put_SampleTime

The put_SampleTime method specifies the sample time of the signal.

Syntax

HRESULT put_SampleTime(
  LONG  lmsSampleTime
);

Parameters

lmsSampleTime

[in] Specifies the sample time.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::get_SampleTime


IBDA_SignalStatistics::put_SignalLocked

The put_SignalLocked method specifies whether the signal is locked.

Syntax

HRESULT put_SignalLocked(
  BOOLEAN  fLocked
);

Parameters

fLocked

[in] Flag that indicates whether to lock the signal.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::get_SignalLocked


IBDA_SignalStatistics::put_SignalPresent

The put_SignalPresent method specifies whether a signal is present.

Syntax

HRESULT put_SignalPresent(
  BOOLEAN  fPresent
);

Parameters

fPresent

[in] Flag indicating whether the signal is present. TRUE means a signal is present.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::get_SignalPresent


IBDA_SignalStatistics::put_SignalQuality

The put_SignalQuality method specifies the quality of the signal.

Syntax

HRESULT put_SignalQuality(
  LONG  lPercentQuality
);

Parameters

lPercentQuality

[in] Long integer that specifies the quality of the signal as a percentage. 100 indicates best quality and 0 indicates worst quality.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::get_SignalQuality


IBDA_SignalStatistics::put_SignalStrength

The put_SignalStrength method specifies the strength of the signal in decibels.

Syntax

HRESULT put_SignalStrength(
  LONG  lDbStrength
);

Parameters

lDbStrength

[in] Long integer that specifies the db strength.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_SignalStatistics Interface
  • IBDA_SignalStatistics::get_SignalStrength


IBDA_Topology Interface

The IBDA_Topology interface is implemented on BDA device filters. A single filter may represent multiple hardware devices (called control nodes) which may be connected in various ways within the filter itself. These connections generally represent hardware paths on the card. This interface provides methods that enable a Network Provider to configure or discover the types of nodes within the filter, and how these nodes are connected. The methods correspond closely to the Ring 0 property sets which are documented in the Windows DDK.

In addition to the methods inherited from IUnknown, the IBDA_Topology interface exposes the following methods.

Method | Description
CreatePin | Creates an instance of a specified pin type.
CreateTopology | Associates an instance of an input pin with an instance of an output pin.
DeletePin | Deletes a pin from the filter's topology.
GetControlNode | Retrieves an IUnknown interface pointer for a specified control node.
GetNodeInterfaces | Retrieves a list of the interfaces supported by a node type.
GetNodeTypes | Retrieves a list of all the node types in the template topology for this filter and network type.
GetPinTypes | Retrieves a list of all the pin types in the template topology for this filter and network type.
GetTemplateConnections | Retrieves a list of all template connections that appear in the template topology for this filter and network type.
SetMediaType | Configures the media types that can be accepted by a particular pin.
SetMedium | Configures the media types that can be accepted by a particular pin.


IBDA_Topology::CreatePin

The CreatePin method creates an instance of a specified pin type.

Syntax

HRESULT CreatePin(
  ULONG  ulPinType,
  ULONG*  pulPinId
);

Parameters

ulPinType

[in] Specifies the type of pin to create. To obtain the available values, call IBDA_Topology::GetPinTypes.

pulPinId

[out] Pointer that receives the identifier for the new pin.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::CreateTopology

The CreateTopology method associates an instance of an input pin with an instance of an output pin.

Syntax

HRESULT CreateTopology(
  ULONG  ulInputPinId,
  ULONG  ulOutputPinId
);

Parameters

ulInputPinId

[in] Specifies the identifier of the input pin for which a topology should be created.

ulOutputPinId

[in] Specifies the identifier of the output pin for which a topology should be created.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::DeletePin

The DeletePin method deletes a pin from the filter's topology.

Syntax

HRESULT DeletePin(
  ULONG  ulPinId
);

Parameters

ulPinId

[in] Specifies the identifier of the pin to be deleted.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::GetControlNode

The GetControlNode method retrieves an IUnknown interface pointer for a specified control node.

Syntax

HRESULT GetControlNode(
  ULONG  ulInputPinId,
  ULONG  ulOutputPinId,
  ULONG  ulNodeType,
  IUnknown**  ppControlNode
);

Parameters

ulInputPinId

[in] Specifies the identifier of the input pin for which a topology should be created.

ulOutputPinId

[in] Specifies the identifier of the output pin for which a topology should be created.

ulNodeType

[in] The type of node to be opened.

ppControlNode

[out] Pointer to a pointer to the control node's IUnknown interface

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::GetNodeInterfaces

The GetNodeInterfaces method retrieves a list of the interfaces supported by a node type.

Syntax

HRESULT GetNodeInterfaces(
  ULONG  ulNodeType,
  ULONG*  pulcInterfaces,
  ULONG  ulcInterfacesMax,
  GUID  rgguidInterfaces[]
);

Parameters

ulNodeType

[in] Specifies the node type for which the interface list is being requested.

pulcInterfaces

[out] Pointer that receives the number of interfaces in the list.

ulcInterfacesMax

[in] Specifies the maximum number of interfaces that rgguidInterfaces can hold.

rgguidInterfaces[]

[out] Pointer to a buffer that holds the list of interface GUIDs.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::GetNodeTypes

The GetNodeTypes method retrieves a list of all the node types in the template topology for this filter and network type.

Syntax

HRESULT GetNodeTypes(
  ULONG*  pulcNodeTypes,
  ULONG  ulcNodeTypesMax,
  ULONG  rgulNodeTypes[]
);

Parameters

pulcNodeTypes

[out] Pointer that receives the number of node types in the list.

ulcNodeTypesMax

[in] The maximum number of node types that can be held by the rgulNodeTypes buffer.

rgulNodeTypes[]

[out] Pointer to a buffer that receives the list of node types.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

The IBDA_Topology interface is implemented by a BDA Device Filter. It is used by a Network Provider to query a BDA Device Filter's possible topologies (template topology) and to configure the device with an appropriate topology for the current tuning request. It is also used to get an IUnknown to a control node which may be used to set specific tuning information.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::GetPinTypes

The GetPinTypes method retrieves a list of all the pin types in the template topology for this filter and network type.

Syntax

HRESULT GetPinTypes(
  ULONG*  pulcPinTypes,
  ULONG  ulcPinTypesMax,
  ULONG  rgulPinTypes[]
);

Parameters

pulcPinTypes

[out] Pointer to a value that receives the number of pin types in the list.

ulcPinTypesMax

[in] The maximum number of pin types that can be held by the rgulPinTypes[] buffer.

rgulPinTypes[]

[out] Pointer to a buffer to receive the list of pin types.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::GetTemplateConnections

The GetTemplateConnections method retrieves a list of all template connections that appear in the template topology for this filter and network type.

Syntax

HRESULT GetTemplateConnections(
  ULONG*  pulcConnections,
  ULONG  ulcConnectionsMax,
  BDA_TEMPLATE_CONNECTION  rgConnections[]
);

Parameters

pulcConnections

[out] Pointer to a value to receive the number of connections in the list.

ulcConnectionsMax

[in] The maximum number of connections that can be held by the rgConnections[] buffer.

rgConnections[]

[out] Pointer to a buffer that receives the list of connections.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::SetMediaType

The SetMediaType method configures the media types that can be accepted by a particular pin.

Syntax

HRESULT SetMediaType(
  ULONG  ulPinId,
  AM_MEDIA_TYPE*  pMediaType
);

Parameters

ulPinId

[in] The identifier of the pin on which to set the media type.

pMediaType

[in] Pointer to a buffer that holds the list of media types that the pin should support.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_Topology::SetMedium

The SetMedium method configures the medium on which a particular pin sends data.

Syntax

HRESULT SetMedium(
  ULONG  ulPinId,
  REGPINMEDIUM*  pMedium
);

Parameters

ulPinId

[in] Specifies the identifier of the pin on which to set the medium.

pMedium

[in] Pointer to the medium on which the pin will send data.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

A medium is a structure that identifies a hardware data path between two devices on the host system. They can be devices on the same card, such as a crossbar and a tuner on a TV card; devices on separate cards; or external devices. Kernel-mode filters based on the Windows Driver Model can use mediums instead of media types to determine pin connections.

See Also

  • Error and Success Codes
  • IBDA_Topology Interface


IBDA_VoidTransform Interface

The IBDA_VoidTransform interface is implemented on a BDA device filter. It is used by the Network Provider to inactivate a portion of a filter graph without stopping the graph.

In addition to the methods inherited from IUnknown, the IBDA_VoidTransform interface exposes the following methods.

Method | Description
Start | Restarts data flow through a control node.
Stop | Stops data flow through a control node.


IBDA_VoidTransform::Start

The Start method restarts data flow through a control node.

Syntax

HRESULT Start();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_VoidTransform Interface


IBDA_VoidTransform::Stop

The Stop method stops data flow through a control node.

Syntax

HRESULT Stop();

Parameters

This method takes no parameters.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IBDA_VoidTransform Interface


IFrequencyMap Interface

The IFrequencyMap interface sets the frequency table used by the BDA Network Provider filter.

A frequency table is a list of broadcast or cable frequencies for a given country/region. The Network Provider uses a frequency table to find the next frequency when IScanningTuner methods are called. On startup, the Network Provider loads a default frequency table. An application can use the IFrequencyMap interface to specify the user's country/region, which causes the Network Provider filter to load the corresponding frequency table. The application can also modify the current table, or provide a completely new table, using the put_FrequencyMapping method.

Frequencies used by this interface are measured in units of kilohertz (kHz), and refer to the center frequency of each band. For more information, see "Terrestrial delivery system descriptor" in EN 300 468.

Note Currently only the DVB-T Network Provider supports this interface.

In addition to the methods inherited from IUnknown, the IFrequencyMap interface exposes the following methods.

Method | Description
get_CountryCode | Returns the country/region code that the Network Provider is currently using.
get_CountryCodeList | Returns a list of all the country/region codes for which the Network Provider has a frequency table.
get_DefaultFrequencyMapping | Returns the default frequency table for a given country/region code.
get_FrequencyMapping | Returns the Network Provider filter's current frequency table.
put_CountryCode | Sets the country/region code.
put_FrequencyMapping | Sets the frequency table.


IFrequencyMap::get_CountryCode

The get_CountryCode method returns the country/region code the Network Provider is currently using. The country/region code determines which frequency table the Network Provider loads.

Syntax

HRESULT get_CountryCode(
    ULONG *pulCountryCode
);

Parameters

pulCountryCode

[out] Pointer to a variable that receives the country/region code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

For a list of country/region codes, see Country/Region Assignments.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IFrequencyMap::get_CountryCodeList

The get_CountryCodeList method returns a list of all the country/region codes for which the Network Provider has a frequency table.

Syntax

HRESULT get_CountryCodeList(
    ULONG *pulCount,
    ULONG **ppulList
);

Parameters

pulCount

[out] Pointer to a variable that receives the number of country/region codes.

ppulList

[out] Pointer to a variable that receives the address of an array of size pulCount, allocated by the method. The array contains a list of the country/region codes. The caller must free the array by calling CoTaskMemFree.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

For a list of country/region codes, see Country/Region Assignments.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IFrequencyMap::get_DefaultFrequencyMapping

The get_DefaultFrequencyMapping method returns the default frequency table for a given country/region code. This method returns the frequency table, but does not set the country/region code on Network Provider. The Network Provider continues to use the same frequency table it was using before the method was called.

Syntax

HRESULT get_DefaultFrequencyMapping(
    ULONG ulCountryCode,
    ULONG *pulCount,
    ULONG **ppulList
);

Parameters

ulCountryCode

[in] Specifies the country/region code.

pulCount

[out] Pointer to a variable that receives the size of the frequency table.

ppulList

[out] Pointer to a variable that receives the address of the frequency table. The frequency table is an array of size pulCount, allocated by the method. The caller must free the array by calling CoTaskMemFree.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Each entry in the frequency table is a tuning frequency, in kilohertz (kHz).

For a list of country/region codes, see Country/Region Assignments.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IFrequencyMap::get_FrequencyMapping

The get_FrequencyMapping method returns the Network Provider filter's current frequency table.

Syntax

HRESULT get_FrequencyMapping(
    ULONG *pulCount,
    ULONG **ppulList
);

Parameters

pulCount

[out] Pointer to a variable that receives the size of the frequency table.

ppulList

[out] Pointer to a variable that receives the address of the frequency table. The frequency table is an array of size pulCount, allocated by the method. The caller must free the array by calling CoTaskMemFree.

Return Values

Each entry in the frequency table is a tuning frequency, in kilohertz (kHz).

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IFrequencyMap::put_CountryCode

The put_CountryCode method sets the country/region code on the Network Provider filter.

Syntax

HRESULT put_CountryCode(
    ULONG ulCountryCode
);

Parameters

ulCountryCode

[in] Specifies the country/region code.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

If the method succeeds, the Network Provider loads the frequency table for the specified country/region code. It uses this table in all subsequent calls to IScanningTuner methods.

If the country/region code does not match an existing frequency table, the method fails and the Network Provider continues to use the previous table. However, it stores the new country/region code, and the application can create a new frequency table by calling the put_FrequencyMapping method. This behavior enables an application to define new country/region codes with new frequency tables.

For a list of existing country/region codes, see Country/Region Assignments.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IFrequencyMap::put_FrequencyMapping

The put_FrequencyMapping method sets the frequency table.

Syntax

HRESULT put_FrequencyMapping(
    ULONG ulCount,
    ULONG pList[]
);

Parameters

ulCount

[in] Specifies the size of the array given in pList.

pList

[in] Address of an array of size ulCount, allocated by the caller. The array should contain a list of all the frequencies (in kHz) that are valid in the current country/region.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Remarks

Applications can use this method to modify a frequency table or create new frequency tables. The changes are not stored by the Network Provider; the application must store the information itself and call put_FrequencyMapping each time the Network Provider is created.

See Also

  • Error and Success Codes
  • IFrequencyMap Interface


IScanningTuner Interface

The IScanningTuner interface is implemented on the BDA Network Provider filter. It inherits from ITuner and permits direct control of a tuner that supports searching for valid programming. The client must provide a valid tuning space (using ITuner::put_TuningSpace or ITuner::put_TuneRequest) before calling any of the methods in this interface. This interface is meant to be used in conjunction with the IBroadcastEvent outbound interface.

Note Only applications intended to run on Microsoft® Windows® 98 or Windows 2000 should use this interface. On Windows XP, the Video Control handles all tuning interactions with the Network Provider.

In addition to the methods inherited from ITuner, the IScanningTuner interface exposes the following methods.

Method | Description
AutoProgram | Scans for all channels with valid programming.
ScanDown | Changes the channel to the next lower channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.
ScanUp | Changes the channel to the next higher channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.
SeekDown | Changes the channel to the next lower channel with valid programming.
SeekUp | Changes the channel to the next higher channel with valid programming.

Remarks

Currently the DVB-C and DVB-S Network Provider filters do not implement this interface. The interface is implemented for DVB-T.


IScanningTuner::AutoProgram

The AutoProgram method scans for all channels with valid programming.

Syntax

HRESULT AutoProgram();

Parameters

This method takes no parameters.

Return Values

When the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

This method returns immediately, and the scan continues in the background. If the device allows it, the scan can be canceled by calling any other tuning operation. Otherwise, the scan will complete once all channels have been visited once. Internal devices will likely have a software implementation of this feature, and will collect fine-tuning information resulting from the scan. External devices will likely implement this feature, so this is just a means to trigger the process.

Currently the DVB-C and DVB-S Network Provider filters do not implement this method, and return E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • IScanningTuner Interface


IScanningTuner::ScanDown

The ScanDown method changes the channel to the next lower channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.

Syntax

HRESULT ScanDown(
  long MillisecondsPause
);

Parameters

MillisecondsPause

[in] Variable of type long that specifies the number of milliseconds to pause.

Return Values

When the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The call returns immediately, while the scan continues in the background. The scan can be canceled by calling any other tuning operation.

Currently the DVB-C and DVB-S Network Provider filters do not implement this method, and return E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • IScanningTuner Interface


IScanningTuner::ScanUp

The ScanUp method changes the channel to the next higher channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.

Syntax

HRESULT ScanUp(
  long MillisecondsPause
);

Parameters

MillisecondsPause

[in] Specifies the number of milliseconds to pause.

Return Values

When the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

The call returns immediately, while the scan continues in the background. The scan can be canceled by calling any other tuning operation.

Currently the DVB-C and DVB-S Network Provider filters do not implement this method, and return E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • IScanningTuner Interface


IScanningTuner::SeekDown

The SeekDown method changes the channel to the next lower channel with valid programming.

Syntax

HRESULT SeekDown();

Parameters

This method takes no parameters.

Return Values

When the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

This method returns immediately, and the seek continues in the background. The seek can be canceled by calling any other tuning operation.

Currently the DVB-C and DVB-S Network Provider filters do not implement this method, and return E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • IScanningTuner Interface


IScanningTuner::SeekUp

The SeekUp method changes the channel to the next higher channel with valid programming.

Syntax

HRESULT SeekUp();

Parameters

This method takes no parameters.

Return Values

When the method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

This method returns immediately, and the seek continues in the background. The seek can be canceled by calling any other tuning operation.

Currently the DVB-C and DVB-S Network Provider filters do not implement this method, and return E_NOTIMPL. The method is implemented for DVB-T.

See Also

  • Error and Success Codes
  • IScanningTuner Interface


ITuner Interface

The ITuner interface is implemented on the Microsoft BDA Network Provider filters. It provides methods for passing tune requests down to the hardware device and receiving current tuning settings. Generally, applications should use the derived interface IScanningTuner instead of ITuner.

Note Only applications that are intended to run on Microsoft® Windows® 9.x or Windows 2000 will use this interface. On Windows XP, the Video Control handles all tuning interactions with the Network Provider.

In addition to the methods inherited from IUnknown, the ITuner interface exposes the following methods.

Method | Description
EnumTuningSpaces | Creates a collection of the tuning spaces preferred by this implementation.
get_PreferredComponentTypes | Gets the collection of ComponentType objects used for default component selection.
get_SignalStrength | Retrieves the Network Provider-specific signal strength metric.
get_TuneRequest | Gets the tune request currently in effect for the Network Provider.
get_TuningSpace | Gets the tuning space currently in effect for the Network Provider.
put_PreferredComponentTypes | Sets the collection of ComponentType objects used for default component selection.
put_TuneRequest | Sets the tune request for the Network Provider.
put_TuningSpace | Sets the tuning space for the Network Provider.
Validate | Returns a value indicating that the tune request can be carried out.


ITuner::get_TuningSpace

The get_TuningSpace method gets the tuning space currently in effect for the Network Provider.

Syntax

HRESULT get_TuningSpace(
  ITuningSpace** ppTuningSpace
);

Parameters

ppTuningSpace

[out] Address of an ITuningSpace interface pointer that will be set to the current tuning space.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::put_TuningSpace

The put_TuningSpace method sets the tuning space for the Network Provider.

Syntax

HRESULT put_TuningSpace(
  ITuningSpace* pTuningSpace
);

Parameters

pTuningSpace

[in] Pointer to the tuning space that will be set in the Network Provider.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • ITuner Interface
  • ITuningSpace Interface


ITuner::EnumTuningSpaces

The EnumTuningSpaces method creates a collection of tuning spaces preferred by this implementation.

Syntax

HRESULT EnumTuningSpaces(
  IEnumTuningSpaces** ppEnum
);

Parameters

ppEnum

[out] Address of a IEnumTuningSpaces interface pointer that will be set to the returned collection.

Return Values

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This list is a subset of the compatible tuning spaces for this implementation.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::get_TuneRequest

The get_TuneRequest method gets the tune request currently in effect for the Network Provider.

Syntax

HRESULT get_TuneRequest(
  ITuneRequest** ppTuneRequest
);

Parameters

ppTuneRequest

[out] Address of an ITuneRequest interface pointer that will be set to the returned object.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

After a tune request is submitted to the Tuner, its Components collection will be filled in. By calling get_TuneRequest after tuning to the program, an application can determine which components are currently available for that program, and then use the IComponent::put_Status method on the Component objects in the collection to activate or inactivate them. This is how an application, for example, changes from an English audio stream to a Spanish audio stream.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::put_TuneRequest

The put_TuneRequest method sets the tune request currently in effect for the Network Provider.

Syntax

HRESULT put_TuneRequest(
  ITuneRequest* pTuneRequest
);

Parameters

pTuneRequest

[in] Pointer to an ITuneRequest object that will be used to set the Network Provider.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

Calling this method initiates a tuning operation based on the properties of the tune request. The tuning operation may be asynchronously attempted.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::Validate

The Validate method returns a value indicating that the tune request can be carried out.

Syntax

HRESULT Validate(
  ITuneRequest* pTuneRequest
);

Parameters

pTuneRequest

[in] Pointer to the tune request object.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

Takes an IUnknown* as input. The Network Provider will first query for its preferred tune request interface(s). If any are found, the Network Provider will validate that the tune request could be carried out. If none are available, it will then query for its preferred tuning space interface(s). If any are found, the Network Provider will validate that it could configure itself for the given tuning space.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::get_PreferredComponentTypes

The get_PreferredComponentTypes method gets the collection of ComponentType objects used for default component selection.

Syntax

HRESULT get_PreferredComponentTypes(
  IComponentTypes** ppComponentTypes
);

Parameters

ppComponentTypes

[out] Address of an IComponentTypes interface pointer that receives the collection of ComponentType objects.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

When a program ends, there may be a new set of stream components available, so at that time the tuner will automatically examine the list of preferred component types and select a component based on that list. If no list is available, the tuner will make a selection based on other factors. Applications call this method simply to examine the current list.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::put_PreferredComponentTypes

The put_PreferredComponentTypes method sets the collection of ComponentType objects used for default component selection.

Syntax

HRESULT put_PreferredComponentTypes(
  IComponentTypes* pComponentTypes
);

Parameters

pComponentTypes

[in] Pointer to an IComponentTypes interface that contains the collection of ComponentType objects.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

Applications create a list of preferred component types by instantiating an empty ComponentTypes collection, filling it, then submitting it to the Tuner using put_PreferredComponentTypes.

See Also

  • Error and Success Codes
  • ITuner Interface


ITuner::get_SignalStrength

The get_SignalStrength method retrieves the Network Provider-specific signal strength metric.

Syntax

HRESULT get_SignalStrength(
  long* pStrength
);

Parameters

pStrength

[out] Pointer to a variable that receives the signal strength.

Return Values

When the method is successful, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

The value -1 means can't determine, 0 means not tuned, highest value means best signal. For digital tuners, this also accounts for the FEC bit error rate (BER).

See Also

  • Error and Success Codes
  • ITuner Interface


MPEG-2 Sections and Tables Filter Reference

This section contains the following reference information for the MPEG-2 Sections and Tables filter:

  • MPEG-2 Section and Table Interfaces
  • MPEG-2 Section and Table Structures
  • MPEG-2 Section and Table Enumeration Types
  • MPEG-2 Section and Table Data Types

See Also

  • Getting MPEG-2 PSI Tables


MPEG-2 Section and Table Interfaces

This section contains reference pages for the interfaces used by the MPEG-2 Sections and Tables filter.

Interface | Description
IMpeg2Data | Retrieves unparsed sections or tables from an MPEG-2 transport stream.
IMpeg2Stream | Represents a stream of MPEG-2 data.
ISectionList | Represents a list of MPEG-2 table sections.


IMpeg2Data Interface

The IMpeg2Data interface is exposed by the MPEG-2 Sections and Tables filter. It enables the client to retrieve unparsed sections or tables from an MPEG-2 transport stream.

In addition to the methods inherited from IUnknown, the IMpeg2Data interface exposes the following methods.

Method | Description
GetSection | Retrieves an MPEG-2 table section.
GetStreamOfSections | Starts an ongoing request for specific MPEG-2 table sections.
GetTable | Retrieves a complete MPEG-2 PSI table.

See Also

  • Getting MPEG-2 PSI Tables


IMpeg2Data::GetSection

The GetSection method retrieves an MPEG-2 table section. This method blocks until the filter receives a matching table section, or until the specified time out elapses.

Syntax

HRESULT GetSection(
  PID  pid,
  TID  tid,
  PMPEG2_FILTER  pFilter,
  DWORD  dwTimeout,
  ISectionList**  ppSectionList
);

Parameters

pid

[in] Specifies the packet identifier (PID) of the transport stream packets to examine.

tid

[in] Specifies the table identifier (TID) of the section to retrieve.

pFilter

[in] Optional pointer to an MPEG2_FILTER structure. The caller can use this parameter to exclude packets based on additional MPEG-2 header fields. This parameter can be NULL.

dwTimeout

[in] Specifies a time-out value, in milliseconds. If the filter does not receive a matching section within the time-out period, the method fails.

ppSectionList

[out] Pointer to a variable that receives an ISectionList interface pointer. Use this interface to retrieve the section data. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_INVALIDARG | Invalid argument.
MPEG2_E_SECTION_NOT_FOUND | The filter did not receive a matching table section.

See Also

  • IMpeg2Data Interface


IMpeg2Data::GetStreamOfSections

The GetStreamOfSections method starts an ongoing request for specific MPEG-2 table sections.

Syntax

HRESULT GetStreamOfSections(
  PID  pid,
  TID  tid,
  PMPEG2_FILTER  pFilter,
  HANDLE  hDataReadyEvent,
  IMpeg2Stream**  ppMpegStream
);

Parameters

pid

[in] Specifies the packet identifier (PID) of the transport stream packets to examine.

tid

[in] Specifies the table identifier (TID) of the section to retrieve.

pFilter

[in] Optional pointer to an MPEG2_FILTER structure. The caller can use this parameter to exclude packets based on additional MPEG-2 header fields. This parameter can be NULL.

hDataReadyEvent

[in] Handle to an event created by the caller. The filter signals this event whenever it receives new data.

ppMpegStream

[out] Pointer to a variable that receives an IMpeg2Stream interface pointer. The caller must release the interface. Use this interface to retrieve the data when it arrives.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

See Also

  • IMpeg2Data Interface


IMpeg2Data::GetTable

The GetTable method retrieves a complete MPEG-2 PSI table. This method blocks until the filter receives all of the sections that make up the requested table, or until the specified time out elapses.

Syntax

HRESULT GetTable(
  PID  pid,
  TID  tid,
  PMPEG2_FILTER  pFilter,
  DWORD  dwTimeout,
  ISectionList**  ppSectionList
);

Parameters

pid

[in] Specifies the packet identifier (PID) of the transport stream packets to examine.

tid

[in] Specifies the table identifier (TID) of the section to retrieve.

pFilter

[in] Optional pointer to an MPEG2_FILTER structure. The caller can use this parameter to exclude packets based on additional MPEG-2 header fields. This parameter can be NULL.

dwTimeout

[in] Specifies a time-out value, in milliseconds. If the filter does not receive a matching section within the time-out period, the method fails.

ppSectionList

[out] Pointer to a variable that receives an ISectionList interface pointer. Use this interface to retrieve the section data. The caller must release the interface.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
MPEG2_E_SECTION_NOT_FOUND | The filter did not receive a matching table section.
S_OK | The method succeeded.

Remarks

You can use the pFilter parameter to specify the Table_ID_extension field or the version number field. Otherwise, the filter caches these values from the first section that matches the search criteria. It uses those values to match subsequent sections.

See Also

  • IMpeg2Data Interface


IMpeg2Stream Interface

The IMpeg2Stream interface represents a stream of MPEG-2 data. The IMpeg2Data::GetStreamOfSections method returns a pointer to this interface.

In addition to the methods inherited from IUnknown, the IMpeg2Stream interface exposes the following methods.

Method | Description
Initialize | Initializes the object.
SupplyDataBuffer | Provides a buffer for the object to write data.


IMpeg2Stream::Initialize

The Initialize method initializes the MPEG2Stream object. This method should be called once, immediately after creating the object. The IMpeg2Data::GetStreamOfSections method calls this method internally, so typically an application will not call it.

Syntax

HRESULT Initialize(
  MPEG_REQUEST_TYPE  requestType,
  IMpeg2Data*  pMpeg2Data,
  PMPEG_CONTEXT  pContext,
  PID  pid,
  TID  tid,
  PMPEG2_FILTER  pFilter,
  HANDLE  hDataReadyEvent
);

Parameters

requestType

[in] Specifies the request type, as an MPEG_REQUEST_TYPE value.

pMpeg2Data

[in] Pointer to the IMpeg2Data interface of the MPEG-2 Sections and Tables filter.

pContext

[in] Pointer to an MPEG_CONTEXT structure. This structure indicates the MPEG-2 source.

pid

[in] Specifies a packet identifier (PID), indicating which packets in the transport stream are requested.

tid

[in] Specifies a table identifier (TID), indicating which table sections to retrieve.

pFilter

[in] Optional pointer to an MPEG2_FILTER structure. The caller can use this parameter to exclude packets based on additional MPEG-2 header fields. This parameter can be NULL.

hDataReadyEvent

[in] Handle to an event. The filter signals this event whenever it receives new data.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | Invalid or NULL pointer argument.
E_OUTOFMEMORY | Insufficient memory.
MPEG2_E_ALREADY_INITIALIZED | The method has been called on this object already.
S_OK | The method succeeded.

See Also

  • IMpeg2Stream Interface


IMpeg2Stream::SupplyDataBuffer

The SupplyDataBuffer method provides a buffer for the Mpeg2Stream object to write data.

Syntax

HRESULT SupplyDataBuffer(
  PMPEG_STREAM_BUFFER  pStreamBuffer
);

Parameters

pStreamBuffer

[in] Pointer to an MPEG_STREAM_BUFFER structure allocated by the caller. This structure contains a pointer to the buffer, also allocated by the caller. The buffer must be at least 4096 bytes.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.
E_INVALIDARG | Invalid argument or NULL parameter.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | Failure.

Remarks

The first time this method is called, it starts a worker thread that streams data to the buffer. When the data arrives, the MPEG2Stream object signals the event that was passed to the IMpeg2Stream::Initialize method. (Typically an application specifies the event handle when it calls IMpeg2Data::GetStreamOfSections.)

When the event is signaled, examine the hr field of the MPEG_STREAM_BUFFER structure. If this value is a success code, the request was successful and the buffer contains valid data. To get more data, call the SupplyDataBuffer method again and wait for the event to be signaled.

The section headers are not converted from network byte order or otherwise processed.

If the object is still waiting for data, this method returns E_FAIL.

See Also

  • IMpeg2Stream Interface


ISectionList Interface

The ISectionList interface represents a list of MPEG-2 table sections.

In addition to the methods inherited from IUnknown, the ISectionList interface exposes the following methods.

Method | Description
CancelPendingRequest | Cancels any pending asynchronous request.
GetNumberOfSections | Returns the number of MPEG-2 sections that were received.
GetProgramIdentifier | Retrieves the program identifier (PID) of the packets that this object is receiving.
GetSectionData | Retrieves a section.
GetTableIdentifier | Returns the table identifier (TID) of the packets that this object is receiving.
Initialize | Initializes the object.
InitializeWithRawSections | Initializes the object with raw section data.


ISectionList::CancelPendingRequest

The CancelPendingRequest method cancels any pending asynchronous request.

Syntax

HRESULT CancelPendingRequest();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
S_OK | The method succeeded.

See Also

  • ISectionList Interface


ISectionList::GetNumberOfSections

The GetNumberOfSections method returns the number of MPEG-2 sections that were received.

Syntax

HRESULT GetNumberOfSections(
  WORD*  pCount
);

Parameters

pCount

[out] Pointer to a variable that receives the number of sections.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_ACCESSDENIED | The request has not completed yet.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

See Also

  • ISectionList Interface


ISectionList::GetProgramIdentifier

The GetProgramIdentifier method retrieves the program identifier (PID) of the packets that this object is receiving.

Syntax

HRESULT GetProgramIdentifier(
  PID*  pPid
);

Parameters

pPid

Pointer to a variable that receives the PID.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

The PID value is set when the object is first initialized.

See Also

  • ISectionList Interface


ISectionList::GetSectionData

The GetSectionData method retrieves a section.

Syntax

HRESULT GetSectionData(
  WORD  sectionNumber,
  DWORD*  pdwRawPacketLength,
  PSECTION*  ppSection
);

Parameters

sectionNumber

[in] Specifies the section number to retrieve, indexed from zero. Call the GetNumberOfSections method to get the number of sections.

pdwRawPacketLength

[out] Pointer to a variable that receives the size of the section data, in bytes.

ppSection

[out] Address of a variable that receives a pointer to a SECTION structure, containing the section data. Do not free the memory for the structure; the object frees the memory when the interface is released.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_ACCESSDENIED | The request has not completed yet.
E_POINTER | NULL pointer argument.
MPEG2_E_OUT_OF_BOUNDS | The section number is out of range.
S_OK | The method succeeded.

Remarks

The section header is converted from network byte order to native byte order. The number of header bytes that are converted depends on the header type. The header types are short header (SECTION structure), long header (LONG_SECTION structure), or DSM-CC header (DSMCC_SECTION structure). If the section has a short header, the first three bytes are converted; for a long header, the first eight bytes are converted; and for a DSM-CC header, the first 20 bytes are converted.

The body of the section data, after the header, is left unparsed and unconverted.

See Also

  • ISectionList Interface


ISectionList::GetTableIdentifier

The GetTableIdentifier method returns the table identifier (TID) of the packets that this object is receiving.

Syntax

HRESULT GetTableIdentifier(
  TID*  pTableId
);

Parameters

pTableId

Pointer to a variable that receives the TID.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

The TID value is set when the object is first initialized.

See Also

  • ISectionList Interface


ISectionList::Initialize

The Initialize method initializes the object. This method should be called once, immediately after creating the object. The IMpeg2Data::GetSection and IMpeg2Data::GetTable methods call this method internally, so typically an application will not call it.

Syntax

HRESULT Initialize(
  MPEG_REQUEST_TYPE  requestType,
  IMpeg2Data*  pMpeg2Data,
  PMPEG_CONTEXT  pContext,
  PID  pid,
  TID  tid,
  PMPEG2_FILTER  pFilter,
  DWORD  timeout,
  HANDLE  hDoneEvent
);

Parameters

requestType

[in] Specifies the request type, as an MPEG_REQUEST_TYPE value.

pMpeg2Data

[in] Pointer to the IMpeg2Data interface of the MPEG-2 Sections and Tables filter.

pContext

[in] Pointer to an MPEG_CONTEXT structure. This structure indicates the MPEG-2 source.

pid

[in] Specifies a packet identifier (PID), indicating which packets in the transport stream are requested.

tid

[in] Specifies a table identifier (TID), indicating which table sections to retrieve.

pFilter

[in] Optional pointer to an MPEG2_FILTER structure. The caller can use this parameter to exclude packets based on additional MPEG-2 header fields. This parameter can be NULL.

timeout

[in] Specifies the maximum length of time that a synchronous request should wait before it times out.

hDoneEvent

[in] Specifies a handle to an event. The object signals the event when the request completes. This parameter is optional; it should be specified for asynchronous requests.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
MPEG2_E_ALREADY_INITIALIZED | The object has already been initialized.
S_OK | The method succeeded.

Remarks

This method is either synchronous or asynchronous, depending on the request type defined in the requestType parameter. When the method is asynchronous, it returns immediately and signals the event specified in hDoneEvent. When the method is synchronous, it blocks until the request completes or until the time out specified in the timeout parameter expires.

See Also

  • ISectionList Interface


ISectionList::InitializeWithRawSections

The InitializeWithRawSections method initializes the object with raw section data. This method allows for custom processing of section data.

Syntax

HRESULT InitializeWithRawSections(
    PMPEG_PACKET_LIST  pmplSections
);

Parameters

pmplSections

[in] Pointer to an MPEG_PACKET_LIST structure that contains a list of MPEG-2 sections.

Return Values

The method returns an HRESULT. Possible values include those in the following table.

Return code | Description
E_INVALIDARG | Invalid argument.
MPEG2_E_ALREADY_INITIALIZED | The object has already been initialized.
S_OK | The method succeeded.

Remarks

Use this method as follows:

  1. Get the section data by calling the IMpeg2Data::GetStreamOfSections method.
  2. Create a new SectionList object and call InitializeWithRawSections with the section data.

See Also

  • ISectionList Interface


MPEG-2 Section and Table Structures

This section contains reference pages for the structures used by the MPEG-2 Sections and Tables filter.

Structure | Description
ATSC_FILTER_OPTIONS | Specifies additional criteria for matching ATSC section headers.
DSMCC_FILTER_OPTIONS | Specifies additional filtering criteria for the DSM-CC portions of the section header.
DSMCC_SECTION | Represents a DSM-CC section header.
LONG_SECTION | Represents a long MPEG-2 section header.
MPEG2_FILTER | Specifies criteria for matching MPEG-2 section headers.
MPEG_BCS_DEMUX | Identifies the filter graph that is providing the MPEG-2 data stream.
MPEG_CONTEXT | Identifies the source of an MPEG-2 data stream.
MPEG_HEADER_BITS | Contains the first 16 bits that follow the table_id in a generic MPEG-2 section header.
MPEG_HEADER_VERSION_BITS | Contains the first 8 bits following the TSID in an MPEG-2 PSI section.
MPEG_PACKET_LIST | Contains a list of MPEG-2 sections.
MPEG_RQST_PACKET | Defines a buffer to receive MPEG-2 section data.
MPEG_STREAM_BUFFER | Defines a buffer that receives MPEG-2 data.
MPEG_WINSOCK | Not supported.
SECTION | Represents a short header from an MPEG-2 section.


ATSC_FILTER_OPTIONS Structure

The ATSC_FILTER_OPTIONS structure specifies additional criteria for matching ATSC section headers.

Syntax

typedef struct {
    BOOL  fSpecifyEtmId;
    DWORD EtmId;
} ATSC_FILTER_OPTIONS;

Members

fSpecifyEtmId

If this flag is TRUE, the ETM_id field in the header must match the value of the EtmId structure member. Otherwise, the ETM_id field is ignored.

EtmId

Specifies a value for the ETM_id field.

See Also

  • MPEG-2 Section and Table Structures
  • MPEG2_FILTER Structure


DSMCC_FILTER_OPTIONS Structure

The DSMCC_FILTER_OPTIONS structure specifies additional filtering criteria for the DSM-CC portions of the section header.

Syntax

typedef struct {
    BOOL  fSpecifyProtocol;
    BYTE  Protocol;
    BOOL  fSpecifyType;
    BYTE  Type;
    BOOL  fSpecifyMessageId;
    WORD  MessageId;
    BOOL  fSpecifyTransactionId;
    BOOL  fUseTrxIdMessageIdMask;
    DWORD TransactionId;
    BOOL  fSpecifyModuleVersion;
    BYTE  ModuleVersion;
    BOOL  fSpecifyBlockNumber;
    WORD  BlockNumber;
    BOOL  fGetModuleCall;
    WORD  NumberOfBlocksInModule;
} DSMCC_FILTER_OPTIONS;

Members

fSpecifyProtocol

If this flag is TRUE, the protocolDiscriminator field in the header must match the value of the Protocol structure member. Otherwise, the protocolDiscriminator field is ignored.

Protocol

Specifies a value for the protocolDiscriminator field. For MPEG-2 DSM-CC messages, this field must equal 0x11.

fSpecifyType

If this field is TRUE, the dsmccType field in the header must match the value of the Type structure member. Otherwise, the dsmccType field is ignored.

Type

Specifies a value for the dsmccType field, which defines the DSM-CC message type.

fSpecifyMessageId

If this flag is TRUE, the messageId field in the header must match the value of the MessageId structure member. Otherwise, the messageId field is ignored.

MessageId

Specifies a value for the messageId field, which defines the DSM-CC message within the scope of the message type.

fSpecifyTransactionId

If this flag is TRUE, the transactionId (or downloadId) field in the header must match the value of the TransactionId structure member. Otherwise, the transactionId/downloadId field is ignored.

fUseTrxIdMessageIdMask

If this flag is TRUE, the transactionId bits are masked so that the following subfields are ignored:

  • Updated flag
  • Version

The following subfields are matched against the TransactionId structure member:

  • Identification
  • Originator

For more information about the subfields within the transactionId, see section 4.6.5 of TR 101 202, Digital Video Broadcasting (DVB); Implementation Guidelines for Data Broadcasting.

This flag is ignored if fSpecifyTransactionId is FALSE.

TransactionId

Specifies a value for the transactionId field.

fSpecifyModuleVersion

If this flag is TRUE, the moduleVersion field in the header must match the value of the ModuleVersion structure member. Otherwise, the moduleVersion field is ignored.

ModuleVersion

Specifies a value for the moduleVersion field.

fSpecifyBlockNumber

If this flag is TRUE, the blockNumber field in the header must match the value of the BlockNumber structure member. Otherwise, the moduleVersion field is ignored.

BlockNumber

Specifies a value for the blockNumber field.

fGetModuleCall

If this flag is TRUE, the NumberOfBlocksInModule structure member specifies the number of blocks in the module. Applies only to download data block (DDB) messages.

NumberOfBlocksInModule

Specifies the number of blocks in the module. Applies only to DDB messages.

See Also

  • MPEG-2 Section and Table Structures
  • MPEG2_FILTER Structure


DSMCC_SECTION Structure

The DSMCC_SECTION structure represents a DSM-CC section header. If a section contains a DSM-CC header, you can cast a SECTION pointer to a DSMCC_SECTION pointer. For more information, see the Remarks section in the SECTION reference.

Syntax

typedef struct {
    TID TableId;
    union
    {
        MPEG_HEADER_BITS_MIDL S;
        WORD                  W;
    } Header;
    WORD TableIdExtension;
    union
    {
        MPEG_HEADER_VERSION_BITS_MIDL S;
        BYTE                          B;
    } Version;
    BYTE  SectionNumber;
    BYTE  LastSectionNumber;
    BYTE  ProtocolDiscriminator;
    BYTE  DsmccType;
    WORD  MessageId;
    DWORD TransactionId;
    BYTE  Reserved;
    BYTE  AdaptationLength;
    WORD  MessageLength;
    BYTE  RemainingData[1];
} DSMCC_SECTION, *PDSMCC_SECTION;

Members

TableId

Specifies the table identifier (TID) of the section.

Header.S

Contains packed header bits, as an MPEG_HEADER_BITS_MIDL structure. Applications should use the Header.W field instead.

Header.W

Contains the header bits as a WORD type. To get the individual bitfields, coerce this member to an MPEG_HEADER_BITS structure.

TableIdExtension

Specifies the table_id_extension field.

Version.S

Contains the version number and current/next indicator bit as an MPEG_HEADER_VERSION_BITS_MIDL structure. Applications should use the Version.S field instead.

Version.B

Contains the version number and current/next indicator bit as a BYTE type. To get the individual bit fields, coerce this member to an MPEG_HEADER_VERSION_BITS structure.

SectionNumber

Specifies the section_number field, which gives the section number for this section.

LastSectionNumber

Specifies the last_section_number field, which gives the last (highest) section number for the table.

ProtocolDiscriminator

Indicates that the message is an MPEG-2 DSM-CC message. The value of this field is always 0x11.

DsmccType

Specifies the DSM-CC message type.

MessageId

Specifies the DSM-CC message identifier.

TransactionId

Specifies the transaction identifier.

Reserved

Reserved bytes.

AdaptationLength

Specifies the adaptation field length.

MessageLength

Specifies the message length.

RemainingData

Contains the remaining section data, as a byte array. The length of the array is Header.W.SectionLength - 17 bytes.

Remarks

This structure extends the LONG_SECTION structure.

See Also

  • MPEG-2 Section and Table Structures


LONG_SECTION Structure

The LONG_SECTION structure represents a long MPEG-2 section header. If a section contains a long header, you can cast a SECTION pointer to a LONG_SECTION pointer. For more information, see the Remarks section in the SECTION reference.

Syntax

typedef struct {
    TID TableId;
    union
    {
        MPEG_HEADER_BITS_MIDL S;
        WORD                  W;
    } Header;
    WORD TableIdExtension;
    union
    {
        MPEG_HEADER_VERSION_BITS_MIDL S;
        BYTE                          B;
    } Version;
    BYTE SectionNumber;
    BYTE LastSectionNumber;
    BYTE RemainingData[1];
} LONG_SECTION, *PLONG_SECTION;

Members

TableId

Specifies the table identifier (TID) of the section.

Header.S

Contains packed header bits, as an MPEG_HEADER_BITS_MIDL structure. Applications should use the Header.W field instead.

Header.W

Contains the header bits as a WORD type. To get the individual bitfields, coerce this member to an MPEG_HEADER_BITS structure.

TableIdExtension

Specifies the table_id_extension field.

Version.S

Contains the version number and current/next indicator bit as an MPEG_HEADER_VERSION_BITS_MIDL structure. Applications should use the Version.S field instead.

Version.B

Contains the version number and current/next indicator bit as a BYTE type. To get the individual bit fields, coerce this member to an MPEG_HEADER_VERSION_BITS structure.

SectionNumber

Specifies the section_number field, which gives the section number for this section.

LastSectionNumber

Specifies the last_section_number field, which gives the last (highest) section number for the table.

RemainingData

Contains the remaining section data, as a byte array. The length of the array is Header.W.SectionLength - 5 bytes.

Remarks

The following code shows how to access the bit fields within the Version member:

LONG_SECTION *pSection; // Points to the section data.

// Coerce the Version field to an MPEG_HEADER_VERSION_BITS type.
MPEG_HEADER_VERSION_BITS *pVersion;
pVersion = (MPEG_HEADER_VERSION_BITS*)&pSection->Version.B;

// Now use the pHeader pointer to access the bit fields.
BYTE VersionNumber = pSection->VersionNumber;

See Also

  • MPEG-2 Section and Table Structures


MPEG2_FILTER Structure

The MPEG2_FILTER structure specifies criteria for matching MPEG-2 section headers.

Syntax

typedef struct {
    BYTE  bVersionNumber;
    WORD  wFilterSize;
    BOOL  fUseRawFilteringBits;
    BYTE  Filter[16];
    BYTE  Mask[16];
    BOOL  fSpecifyTableIdExtension;
    WORD  TableIdExtension;
    BOOL  fSpecifyVersion;
    BYTE  Version;
    BOOL  fSpecifySectionNumber;
    BYTE  SectionNumber;
    BOOL  fSpecifyCurrentNext;
    BOOL  fNext;
    BOOL  fSpecifyDsmccOptions;
    DSMCC_FILTER_OPTIONS  Dsmcc;
    BOOL  fSpecifyAtscOptions;
    ATSC_FILTER_OPTIONS  Atsc;
} MPEG2_FILTER, *PMPEG2_FILTER;

Members

bVersionNumber

Specifies the version number of the structure. This value must be 1 or higher.

wFilterSize

Specifies the size of the structure data, excluding any padding bytes. Set this field equal to the constant MPEG2_FILTER_VERSION_1_SIZE.

fUseRawFilteringBits

If this flag is TRUE, the Filter and Mask members specify the filtering criteria as a pair of bit masks, and the remaining members of this structure are ignored. If this field is FALSE, the Filter and Mask members are ignored, and the other structure members contain the filtering criteria.

Filter

Specifies a 16-byte bit mask, which contains the bit values to match in the section header.

Mask

Specifies a 16-byte bit mask. Set any "don't care" bits equal to 1, and all other bits to 0. In other words, for each bit, if the value in Mask is 0, the corresponding bit in Filter will be matched against that bit in the section header. If the value in Mask is 1, that bit in the section header is ignored.

fSpecifyTableIdExtension

If this flag is TRUE, the table_ID_extension field in the header must match the value of the TableIdExtension structure member. Otherwise, the table_ID_extension field is ignored.

TableIdExtension

Specifies a value for the table_ID_extension field.

fSpecifyVersion

If this flag is TRUE, the version_number field in the header must match the value of the Version structure member. Otherwise, the version_number field is ignored.

Version

Specifies a value for the version_number field.

fSpecifySectionNumber

If this flag is TRUE, the section_number field in the header must match the value of the SectionNumber structure member. Otherwise, the section_number field is ignored.

SectionNumber

Specifies a value for the section_number field.

fSpecifyCurrentNext

If this flag is TRUE, the current_next_indicator bit in the header must match the value of the fNext structue member. Otherwise, the current_next_indicator field is ignored.

fNext

Specifies a value for the current_next_indicator bit. You can use the MPEG_CURRENT_NEXT_BIT enumeration type to specify this value.

fSpecifyDsmccOptions

If this field is TRUE, the Dsmcc member contains additional filtering criteria for the DSM-CC portions of the section header. Otherwise, the Dsmcc member is ignored.

Dsmcc

Specifies a DSMCC_FILTER_OPTIONS structure that contains additional filtering criteria for the DSM-CC portions of the section header.

fSpecifyAtscOptions

If this flag is TRUE, the Atsc member contains additional filtering criteria. Otherwise, the Atsc member is ignored.

Atsc

Specifies an ATSC_FILTER_OPTIONS structure that contains additional filtering criteria.

See Also

  • MPEG-2 Section and Table Structures


MPEG_BCS_DEMUX Structure

The MPEG_BCS_DEMUX structure identifies the filter graph that is providing the MPEG-2 data stream.

Syntax

typedef struct {
    DWORD AVMGraphId;
} MPEG_BCS_DEMUX;

Members

AVMGraphId

Specifies the filter graph instance.

See Also

  • MPEG_CONTEXT Structure
  • MPEG-2 Section and Table Structures


MPEG_CONTEXT Structure

The MPEG_CONTEXT structure identifies the source of an MPEG-2 data stream.

Syntax

typedef struct MPEG_CONTEXT {
    MPEG_CONTEXT_TYPE Type;
    union
    {
        MPEG_BCS_DEMUX Demux;
        MPEG_WINSOCK   Winsock;
    } U;
};

Members

Type

Specifies the source type, as an MPEG_CONTEXT_TYPE value. Currently, the value must be MPEG_CONTEXT_BCS_DEMUX.

U.Demux

Specifies an MPEG_BCS_DEMUX structure that identifies the filter graph instance.

U.Winsock

Currently not supported.

See Also

  • MPEG-2 Section and Table Structures


MPEG_HEADER_BITS Structure

The MPEG_HEADER_BITS structure contains the first 16 bits that follow the table_id in a generic MPEG-2 section header.

Syntax

typedef struct
{
    WORD SectionLength          : 12;
    WORD Reserved               :  2;
    WORD PrivateIndicator       :  1;
    WORD SectionSyntaxIndicator :  1;
} MPEG_HEADER_BITS, *PMPEG_HEADER_BITS;

typedef struct
{
    WORD Bits;
} MPEG_HEADER_BITS_MIDL;

Members

SectionLength

The length of the section, in bytes.

Reserved

Two reserved bits.

PrivateIndicator

The private_indicator bit.

SectionSyntaxIndicator

The section_syntax_indicator bit.

Remarks

The MPEG_HEADER_BITS_MIDL structure is defined for compatibility with the MIDL compiler. Applications should use the MPEG_HEADER_BITS structure, which defines the individual bit fields within the WORD value.

Requirements

Include Mpeg2bits.h.

See Also

  • MPEG-2 Section and Table Structures
  • SECTION Structure


MPEG_HEADER_VERSION_BITS Structure

The MPEG_HEADER_VERSION_BITS structure contains the first 8 bits following the TSID in an MPEG-2 PSI section. These bits contain the version number and the current/next indicator.

Syntax

typedef struct
{
    BYTE CurrentNextIndicator : 1;
    BYTE VersionNumber        : 5;
    BYTE Reserved             : 2;
} MPEG_HEADER_VERSION_BITS, *PMPEG_HEADER_VERSION_BITS;

typedef struct
{
    BYTE Bits;
} MPEG_HEADER_VERSION_BITS_MIDL;

Members

CurrentNextIndicator

The current_next_indicator field.

VersionNumber

The version_number field.

Reserved

Two reserved bits.

Remarks

The MPEG_HEADER_VERSION_BITS_MIDL structure is defined for compatibility with the MIDL compiler. Applications should use the MPEG_HEADER_VERSION_BITS structure, which defines the individual bit fields within the byte.

Requirements

Include Mpeg2bits.h.

See Also

  • MPEG-2 Section and Table Structures


MPEG_PACKET_LIST Structure

The MPEG_PACKET_LIST structure contains a list of MPEG-2 sections.

Syntax

typedef struct {
    WORD              wPacketCount;
    PMPEG_RQST_PACKET PacketList[1];
} MPEG_PACKET_LIST, *PMPEG_PACKET_LIST;

Members

wPacketCount

Specifies the size of the PacketList array.

PacketList

Specifies a pointer to an array of MPEG_RQST_PACKET structures, which themselves contain pointers to buffers that hold the sectioned data.

See Also

  • MPEG_STREAM_BUFFER Structure
  • MPEG-2 Section and Table Structures


MPEG_RQST_PACKET Structure

The MPEG_RQST_PACKET structure defines a buffer to receive MPEG-2 section data.

Syntax

typedef struct {
    DWORD     dwLength;
    PSECTION  pSection;
} MPEG_RQST_PACKET, *PMPEG_RQST_PACKET;

Members

dwLength

Specifies the length of the buffer that pSection points to. The minimum size for section data is 4096 bytes.

pSection

Pointer to a buffer that receives the section data. The pointer is typed as a SECTION structure. The first bytes in the section contain header fields that are defined in the SECTION structure. The SectionData member of the SECTION structure is an array of bytes, containing the body of the section after the header bytes.

See Also

  • MPEG_PACKET_LIST Structure
  • MPEG-2 Section and Table Structures


MPEG_STREAM_BUFFER Structure

The MPEG_STREAM_BUFFER structure defines a buffer that receives MPEG-2 data.

Syntax

typedef struct {
    HRESULT hr;
    DWORD   dwDataBufferSize;
    DWORD   dwSizeOfDataRead;
    BYTE*   pDataBuffer;
} MPEG_STREAM_BUFFER, *PMPEG_STREAM_BUFFER;

Members

hr

Specifies a status code. Use this value to check the status of the read request.

dwDataBufferSize

Specifies the size of the buffer, in bytes.

dwSizeOfDataRead

Specifies the amount of valid data in the buffer, in bytes

pDataBuffer

Pointer to a buffer that holds the MPEG-2 data.

Remarks

This structure is used with the IMpeg2Stream::SupplyDataBuffer method to get raw MPEG-2 data.

For PSI tables and sections, set pDataBuffer to point to a SECTION structure. If you also create an MPEG_PACKET_LIST structure to hold a list of buffers, you can pass that list to the ISectionList::InitializeWithRawSections method.

The following code shows how to initialize an MPEG_STREAM_BUFFER structure so that it points to a SECTION structure contained in an MPEG_PACKET_LIST section list:

// Allocate two buffers for section data.
const int cBufferSize = 4096;
BYTE pBuffer1[cBufferSize];
BYTE pBuffer2[cBufferSize];

// Create a packet list to hold both buffers.
MPEG_RQST_PACKET RqstPacket[2];
MPEG_PACKET_LIST Packets;

RqstPacket[0].dwLength = cBufferSize;
RqstPacket[0].pSection = (SECTION*)pBuffer1;
RqstPacket[1].dwLength = cBufferSize;
RqstPacket[1].pSection = (SECTION*)pBuffer2;

Packets.wPacketCount = 2;
Packets.PacketList[0] = &RqstPacket[0];
Packets.PacketList[1] = &RqstPacket[1];

// Set the stream buffer structure to point to the first packet in the list.
MPEG_STREAM_BUFFER StreamBuffer;
ZeroMemory(&StreamBuffer, sizeof(MPEG_STREAM_BUFFER));
StreamBuffer.dwDataBufferSize = Packets.PacketList[0]->dwLength;
StreamBuffer.pDataBuffer = (BYTE*) Packets.PacketList[0]->pSection;

See Also

  • MPEG-2 Section and Table Structures


MPEG_WINSOCK Structure

The MPEG_WINSOCK structure is not supported.

Syntax

typedef struct MPEG_WINSOCK{
    DWORD  AVMGraphId;
};

Members

AVMGraphId

Reserved.

See Also

  • MPEG-2 Section and Table Structures


SECTION Structure

The SECTION structure represents a short header from an MPEG-2 table section.

Syntax

typedef struct {
    TID TableId;
    union
    {
        MPEG_HEADER_BITS_MIDL S;
        WORD                  W;
    } Header;
    BYTE SectionData[1];
} SECTION, *PSECTION;

Members

TableId

Specifies the table identifier (TID) of the section.

Header.S

Contains header bits, as an MPEG_HEADER_BITS_MIDL structure. Applications should use the Header.W field instead.

Header.W

Contains the header bits as a WORD type. To get the individual bit fields, coerce this member to an MPEG_HEADER_BITS structure.

SectionData

Contains the section data, as a byte array. The length of the array is given by the Header.W.SectionLength field.

Remarks

This structure represents an MPEG-2 short header. The section might contain a long header or DSM-CC header, each of which extends the short header:

  • If the Header.W.SectionSyntaxIndicator bit is set, the section uses the long syntax. In that case, you can cast a SECTION pointer to a LONG_SECTION pointer.
  • If the TID indicates a DSM-CC user-to-network message (0x3B) or a download data message (0x3C), the section uses the DSM-CC header syntax. In that case, you can cast a SECTION pointer to a DSMCC_SECTION pointer.

The following code shows how to access the bit fields within the Header member:

SECTION *pSection; // Points to the section data.

// Coerce the Header field to an MPEG_HEADER_BITS type.
MPEG_HEADER_BITS *pHeader = (MPEG_HEADER_BITS*)&pSection->Header.W;

// Now use the pHeader pointer to access the bit fields.
WORD SectionLength = pHeader->SectionLength;

See Also

  • MPEG-2 Section and Table Structures


MPEG-2 Section and Table Enumeration Types

This section contains reference pages for the enumeration types used by the MPEG-2 Section and Table interfaces.

Enumeration type | Description
MPEG_CONTEXT_TYPE | Identifies the source of an MPEG-2 data stream.
MPEG_CURRENT_NEXT_BIT | Specifies the value of the current_next_indicator bit.
MPEG_REQUEST_TYPE | Specifies a request for MPEG-2 data.


MPEG_CONTEXT_TYPE

The MPEG_CONTEXT_TYPE enumeration type identifies the source of an MPEG-2 data stream.

Syntax

typedef enum {
    MPEG_CONTEXT_BCS_DEMUX,
    MPEG_CONTEXT_WINSOCK
} MPEG_CONTEXT_TYPE;

Members

MPEG_CONTEXT_BCS_DEMUX

Indicates that the source is a DirectShow filter graph using the MPEG-2 Demultiplexer filter.

MPEG_CONTEXT_WINSOCK

Reserved. Do not use.

See Also

  • MPEG_CONTEXT
  • MPEG-2 Section and Table Enumeration Types


MPEG_CURRENT_NEXT_BIT

The MPEG_CURRENT_NEXT_BIT enumeration type specifies the value of the current_next_indicator bit.

Syntax

typedef enum {
    MPEG_SECTION_IS_NEXT    = 0,
    MPEG_SECTION_IS_CURRENT = 1
} MPEG_CURRENT_NEXT_BIT;

Members

MPEG_SECTION_IS_NEXT

Indicates that the table is current applicable.

MPEG_SECTION_IS_CURRENT

Indicates that the table is not yet applicable, and will be the next valid table.

See Also

  • MPEG-2 Section and Table Enumeration Types


MPEG_REQUEST_TYPE

The MPEG_REQUEST_TYPE enumeration type specifies a request for MPEG-2 data.

Syntax

typedef enum {
    MPEG_RQST_UNKNOWN = 0,
    MPEG_RQST_GET_SECTION,
    MPEG_RQST_GET_SECTION_ASYNC,
    MPEG_RQST_GET_TABLE,
    MPEG_RQST_GET_TABLE_ASYNC,
    MPEG_RQST_GET_SECTIONS_STREAM,
    MPEG_RQST_GET_PES_STREAM,
    MPEG_RQST_GET_TS_STREAM,
    MPEG_RQST_START_MPE_STREAM
} MPEG_REQUEST_TYPE;

Members

MPEG_RQST_UNKNOWN

Unknown request type. Do not use this value.

MPEG_RQST_GET_SECTION

Get one table section. (Synchronous call.)

MPEG_RQST_GET_SECTION_ASYNC

Get one table section. (Asynchronous call.)

MPEG_RQST_GET_TABLE

Get a complete table. (Synchronous call.)

MPEG_RQST_GET_TABLE_ASYNC

Get a complete table. (Asynchronous call.)

MPEG_RQST_GET_SECTIONS_STREAM

Get a stream of sections.

MPEG_RQST_GET_PES_STREAM

Get a stream of packetized elementary stream (PES) packets.

MPEG_RQST_GET_TS_STREAM

Get a stream of transport stream (TS) packets.

MPEG_RQST_START_MPE_STREAM

Get a stream of multi-protocol encapsulation (MPE) packets.

See Also

  • ISectionList::Initialize
  • MPEG-2 Section and Table Enumeration Types


MPEG-2 Section and Table Data Types

The following data types are used with the MPEG-2 Sections and Tables interfaces.

Data type | Description
PID | Defines a packet identifier (PID).
TID | Defines a table identifier (TID).


PID

The PID type defines a packet identifier (PID).

Syntax

typedef WORD PID;

See Also

  • MPEG-2 Section and Table Data Types


TID

The TID type defines a table identifier (TID)

Syntax

typedef BYTE TID;

See Also

  • MPEG-2 Section and Table Data Types


Microsoft TV Technologies Visual Basic and Script Reference

This section contains the reference documentation for the Automation-compliant objects, constants and events defined for Microsoft® TV Technologies, grouped by the following functional areas:

  • Video Control Visual Basic Reference
  • Microsoft Unified Tuning Model Visual Basic Reference

See Also

  • Microsoft TV Technologies


Video Control Visual Basic Reference

This topic applies to Windows XP only.

This section contains the reference documentation for the Automation objects and events that are accessible from Microsoft® Visual Basic® and script applications. For more information on how to use these objects, see TV Applications in Script (Video Control). The information in that article is mostly applicable to Visual Basic as well. For more information on creating a DVD application using the Video Control, see DVD Applications Using Visual Basic (Video Control). Most of the information in this article is also relevant for client applications written in C++ or a scripting language.

This section contains the following topics.

  • Video Control Objects (Visual Basic)
  • Video Control Events
  • Video Control Constants


Video Control Objects (Visual Basic)

This topic applies to Windows XP only.

Object | Description
IMSVidDevice | Base class for all devices and features used by the video control
IMSVidFeature | Represents a feature.
IMSVidInputDevice | Base class for input devices.
IMSVidOutputDevice | Base class for output devices, including renderers.
IMSVidPlayback | Base class for file and DVD playback objects used by the Video Control.
IMSVidRect | Represents a rectangle and is used in various MSVidVideoRenderer methods.
MSEventBinder | In script contained in an HTML page, this object is used to bind application-defined event handlers (subroutines) to events fired by the various device objects.
MSVidAnalogTunerDevice | Represents a hardware analog video tuning device.
MSVidAudioRenderer | Represents a hardware audio rendering device.
MSVidAudioRendererDevices | Represents a read-only collection of audio rendering devices (such as sound cards).
MSVidBDATunerDevice | Represents a BDA-compatible tuner device.
MSVidClosedCaptioning | Represents the closed captioning feature.
MSVidCtl | Represents the control class for the MSVidCtl ActiveX control.
MSVidDataServices | Represents the data services feature.
MSVidFeatures | Represents a collection of features.
MSVidFilePlaybackDevice | Represents a file-playback input device.
MSVidInputDevices | Represents a collection of MSVidAnalogTunerDevice or MSVidBDATunerDevice objects.
MSVidOutputDevices | Represents a collection of MSVidVideoRenderer objects or MSVidAudioRenderer objects.
MSVidStreamBufferRecordingControl | Manages a stream buffer recording.
MSVidStreamBufferSink | Represents a stream buffer output device.
MSVidStreamBufferSource | Represents a stream buffer source object.
MSVidVideoRenderer | Provides access for script and Visual Basic® applications to the Video Mixing Renderer filter.
MSVidVideoRendererDevices | Represents a collection of MSVidVideoRenderer objects.
MSVidWebDVD | Controls DVD-Video navigation and playback.
MSVidWebDVDAdm | Sets and retrieves persistent settings for the MSVidWebDVD object


IMSVidDevice Object

This topic applies to Windows XP only.

IMSVidDevice is the base class for all devices and features used by the Video Control. All the derived classes (or "objects" in script) inherit the methods of IMSVidDevice.

This object exposes the following methods and properties.

Property | Description
Category | Retrieves
ClassID | Retrieves a string CLASSID that uniquely identifies this particular device.
Name | Retrieves the friendly name of the device.
Power | Specifies and retrieves a value indicating whether the device is currently on or off.
Status | Retrieves the current status of the device.

Method | Description
IsEqualDevice | Determines whether two devices represent the same underlying hardware.


IMSVidDevice.Category

This topic applies to Windows XP only.

The Category property retrieves the category of the device.

Syntax

objIMSVidDevice.Category As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a string representation of a GUID, which identifies the category.

Remarks

This property is read-only.

See Also

  • IMSVidDevice Object


IMSVidDevice.ClassID

This topic applies to Windows XP only.

The ClassID property retrieves the class identifier (CLSID) of the device.

Syntax

objIMSVidDevice.ClassID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a string representation of the CLSID.

Remarks

This property is read-only.

See Also

  • IMSVidDevice Object


IMSVidDevice.Name

This topic applies to Windows XP only.

The Name property retrieves the friendly name of the device.

Syntax

objIMSVidDevice.Name As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the friendly name.

Remarks

This property is read-only.

See Also

  • IMSVidDevice Object


IMSVidDevice.Power

This topic applies to Windows XP only.

The Power property indicates whether the device is currently on or off.

Syntax

objIMSVidDevice.Power As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the device is on, or False if the device is off.

Remarks

Not all device types support this property.

This property is read/write.

See Also

  • IMSVidDevice Object


IMSVidDevice.Status

This topic applies to Windows XP only.

The Status property retrieves status information about the device .

Syntax

objIMSVidDevice.Status As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the device status as a Long value.

Remarks

Not all device types support this property.

This property is read-only.

See Also

  • IMSVidDevice Object


IMSVidDevice.IsEqualDevice

This topic applies to Windows XP only.

The IsEqualDevice method indicates whether this device and another device represent the same underlying hardware.

Syntax

ObjIMSVidDevice.IsEqualDevice(
    Device As MSVidDevice
) As Boolean

Parameters

Device

Specifies an IMSVidDevice object or an object that derives from this type.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the two objects represent the same device, or False otherwise.

Remarks

If a system has two identical video cards installed, this method can be used to distinguish between them.

See Also

  • IMSVidDevice Object


IMSVidFeature Object

This topic applies to Windows XP only.

The IMSVidFeature object represents a feature that is exposed by the Video Control. Each feature object is identified by its own globally unique identifier (called a GUID). Applications first obtain a reference to an IMSVidFeature by enumerating through the MSVidCtl.FeaturesAvailable property and comparing the GUID of the desired object with the GUID of the current item in the collection. To enable the feature, the application then adds the object to the MSVidCtl.FeaturesActive collection as described in TV Applications in Script (Video Control).

This object inherits all of the methods and properties of the IMSVidDevice object.


IMSVidInputDevice Object

This topic applies to Windows XP only.

IMSVidInputDevice is the base class for all input devices.

This object inherits all the methods and properties of the IMSVidDevice object. In addition, it exposes the following methods.

Method | Description
IsViewable | Determines whether the device can view the specified item.
View | Sets the device to view the specified item.


IMSVidInputDevice.IsViewable

This topic applies to Windows XP only.

The IsViewable method determines whether this device can view the specified tune request.

Currently this method is not implemented by any of the supported input devices.

Syntax

ObjIMSVidInputDevice.IsViewable(
    v As Object
) As Boolean

Parameters

v

Specifies the tune request as an ITuneRequest object.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the device can view the specified tune request, or False otherwise.

See Also

  • IMSVidInputDevice Object


IMSVidInputDevice.View

This topic applies to Windows XP only.

The View method configures this input device to view the specified tune request.

Syntax

ObjIMSVidInputDevice.View(
    varContent As Object
)

Parameters

varContent

Specifies the tune request as an ITuneRequest object.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

Before calling this method, set the MSVidCtl.InputActive property equal to the device; doing so configures this device as the Video Control's active input device. Unless the application needs to choose a specific input device, however, the MSVidCtl.View method is recommended over the IMSVidInputDevice.View method.

See Also

  • IMSVidInputDevice Object


IMSVidOutputDevice Object

This topic applies to Windows XP only.

The IMSVidOutputDevice object is the base class for Video Control output devices. This object is defined to support polymorphism. It inherits all the methods and properties of the IMSVidDevice object, but adds no other methods or properties.

The MSVidCtl.OutputsAvailable property returns an MSVidOutputDevices collection, which contains IMSVidOutputDevice objects.

See Also

  • MSVidVideoRenderer Object
  • MSVidAudioRenderer Object


IMSVidPlayback Object

This topic applies to Windows XP Service Pack 1 only.

The IMSVidPlayback object is the base class for file and DVD playback objects used by the Video Control.

This object inherits all the properties and methods of the IMSVidDevice object. In addition, it exposes the following properties and methods.

Property | Description
CanStep | Indicates whether the input source can step frame by frame.
CurrentPosition | Indicates the current playback position.
EnableResetOnStop | Indicates how playback will resume if the graph is rebuilt.
Length | Returns the duration of the source.
PositionMode | Indicates how position values are interpreted by this object.
Rate | Sets or retrieves the playback rate.

Method | Description
Pause | Pauses the playback device.
Run | Runs the playback device.
Step | Steps through the video stream by a specified number of frames.
Stop | Stops the playback device.

See Also

  • MSVidFilePlaybackDevice Object
  • MSVidWebDVD Object


IMSVidPlayback.CanStep

This topic applies to Windows XP Service Pack 1 only.

The CanStep property indicates whether the input source can step frame by frame. Check this property before calling the Step method.

Syntax

objVidPlayback.CanStep(
    fBackwards As Boolean
) As Boolean

Parameters

fBackwards

If True, the returned value indicates whether the input source can step backward. If False, the value indicates whether the source can step forward.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the source can step in the specified direction, or False otherwise.

Remarks

This property is read-only.

Backward stepping is not currently supported in any commercially available decoders.

See Also

  • IMSVidPlayback Object
  • IMSVidPlayback.Step


IMSVidPlayback.CurrentPosition

This topic applies to Windows XP Service Pack 1 only.

The CurrentPosition property indicates the current playback position. Setting this property causes the object to seek to the specified position.

Syntax

objVidPlayback.CurrentPosition As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the position. The units are determined by the value of the PositionMode property.

Remarks

This property is read/write.

See Also

  • IMSVidPlayback Object
  • IMSVidPlayback.PositionMode


IMSVidPlayback.EnableResetOnStop

This topic applies to Windows XP Service Pack 1 only.

The EnableResetOnStop property indicates how playback will resume if the graph is rebuilt.

Syntax

objVidPlayback.EnableResetOnStop As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a Boolean value. If True, the Video Control seeks back to the start before resuming playback. If False, it attempts to start from position where playback was interrupted.

Remarks

In some situaitions, the filter graph may be torn down and rebuilt during play. For example, this can happen if the monitor resolution is changed or the screen saver starts. The EnableResetOnStop property specifies whether the Video Control should resume playback where it was interrupted, or should restart at the beginning of the source.

Generally this property should be set to False (the default value) to ensure continuous viewing. However, if the Video Control has difficulty returning to the last playback point, set the value to True.

This property is read/write.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Length

This topic applies to Windows XP Service Pack 1 only.

The Length property returns the duration of the source.

Syntax

objVidPlayback.Length As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the position. The units are determined by the value of the PositionMode property.

Remarks

This property is read-only.

See Also

  • IMSVidPlayback Object
  • IMSVidPlayback.PositionMode


IMSVidPlayback.PositionMode

This topic applies to Windows XP Service Pack 1 only.

The PositionMode property indicates how position values are interpreted by this object.

Syntax

objVidPlayback.PositionMode As PositionModeList

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a PositionModeList constant:

Constant | Value | Description
FrameMode | 0 | Values are specified as frame numbers.
TenthsSecondsMode | 1 | Values are specified as hundredths of seconds.

Remarks

The value of this property determines how the Length and CurrentPosition properties are interpreted.

This property is read/write.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Rate

This topic applies to Windows XP Service Pack 1 only.

The Rate property sets or retrieves the playback rate.

Syntax

objVidPlayback.Rate As Double

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Setting this property to a rate that is not supported by the input source will cause an error.

Return Values

Returns the playback rate, as a ratio to the authored rate. For example, 0.5 means half the normal speed, 1.0 means normal speed, and 2.0 means twice the normal speed.

Remarks

This property is read/write.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Pause

This topic applies to Windows XP Service Pack 1 only.

The Pause method pauses the playback device. Applications should call the MSVidCtl.Pause method instead.

Syntax

objVidPlayback.Pause()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Run

This topic applies to Windows XP Service Pack 1 only.

The Run method runs the playback device. Applications should call the MSVidCtl.Run method instead.

Syntax

objVidPlayback.Run()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Step

This topic applies to Windows XP Service Pack 1 only.

The Step method steps through the video stream by a specified number of frames.

Syntax

objVidPlayback.Step(
    lStep As Long
)

Parameters

lStep

Specifies how many frames to step. If lStep is 1, the Video Control steps forward one frame. If lStep is a number N greater than 1, the Video Control skips N - 1 frames and shows the Nth frame.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • IMSVidPlayback Object


IMSVidPlayback.Stop

This topic applies to Windows XP Service Pack 1 only.

The Stop method stops the playback device. Applications should use the MSVidCtl.Stop method.

Syntax

objVidPlayback.Stop()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • IMSVidPlayback Object


IMSVidRect Object

This topic applies to Windows XP only.

The IMSVidRect object represents a rectangle with an associated window handle. It contains properties that define the size and position of the rectangle.

The top and left coordinates are relative to the associated window. The height and width are relative to the top left corner of the rectangle. All values are in pixels.

This object exposes the following properties.

Property | Description
Height | Sets or retrieves the height of the rectangle.
HWnd | Not supported for Visual Basic.
Left | Sets or retrieves the left x-coordinate of the rectangle.
Top | Sets or retrieves the top y-coordinate of the rectangle.
Width | Sets or retrieves the width of the rectangle.
Rect | Copies the values of another rectangle to this rectangle.


IMSVidRect.Height

This topic applies to Windows XP only.

The Height property sets or retrieves the height of the rectangle.

Syntax

objIMSVidRect.Height As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the height, in pixels.

Remarks

Setting the IMSVidRect.Top property changes the value of this property. For example, if the Top property is zero and the Height property is 100, setting the Top property to 10 changes the Height property to 90.

This property is read/write.

See Also

  • IMSVidRect Object
  • IMSVidRect.Rect


IMSVidRect.HWnd

This topic applies to Windows XP only.

The HWnd property is not supported for Visual Basic.

Syntax

objIMSVidRect.HWnd As wireHWND


IMSVidRect.Left

This topic applies to Windows XP only.

The Left property sets or retrieves the left x-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

objIMSVidRect.Left As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the left x-coordinate, in pixels.

Remarks

Setting this property also changes the width of the rectangle. For example, if the Left property is zero and the IMSVidRect.Width property is 100, setting the Left property to 10 changes the Width property to 90.

This property is read/write.

See Also

  • IMSVidRect Object
  • IMSVidRect.Rect


IMSVidRect.Top

This topic applies to Windows XP only.

The Top property sets or retrieves the top y-coordinate of the rectangle. This coordinate is relative to the rectangle's associated window.

Syntax

objIMSVidRect.Top As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the top y-coordinate, in pixels.

Remarks

Setting this property also changes the height of the rectangle. For example, if the Top property is zero and the Height property is 100, setting the Top property to 10 changes the Height property to 90.

This property is read/write.

See Also

  • IMSVidRect Object
  • IMSVidRect.Rect


IMSVidRect.Width

This topic applies to Windows XP only.

The Width property sets or retrieves the width of the rectangle.

Syntax

objIMSVidRect.Width As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the width, in pixels.

Remarks

Setting the IMSVidRect.Left property changes the value of this property. For example, if the Left property is zero and the Width property is 100, setting the Left property to 10 changes the Width property to 90.

This property is read/write.

See Also

  • IMSVidRect Object
  • IMSVidRect.Rect


IMSVidRect.Rect

This topic applies to Windows XP only.

The Rect property copies the values of another rectangle to this rectangle.

Syntax

objIMSVidRect.Rect As MSVidRect

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

Remarks

This property is write-only.

See Also

  • IMSVidRect Object


MSEventBinder Object

This topic applies to Windows XP only.

In script contained in an HTML page, the MSEventBinder object is used to bind application-defined event handlers to events fired by the various device objects.

Visual Basic clients do not require this object; instead, use the WithEvents keyword to receive events from an object.

This object exposes the following methods.

Method | Description
Bind | Binds the event to the specified application-defined event handler.
Unbind | Unbinds the event and the event handler.

See Also

  • Binding Event Handlers to Events in Script Applications


MSEventBinder.Bind

This topic applies to Windows XP only.

The Bind method "binds" or associates an event with an application-defined event handler (subroutine). The event handler is called whenevere the event is fired.

Syntax

objMSEventBinder.Bind(
  Event As Object,
  EventName As String,
  EventHandler As String
) As Long

Parameters

Event

Specifies the object that fires the event.

EventName

String that specifies name of the event.

EventHandler

String that specifies the name of the event handler, as implemented by the application.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method returns a number that uniquely identifies the binding between the event and the event handler. Store this value and pass it to the MSEventBinder.Unbind method to unbind the event from the event handler.

See Also

  • MSEventBinder Object


MSEventBinder.Unbind

This topic applies to Windows XP only.

The Unbind method removes the binding between an event and its associated event handler.

Syntax

ObjEventBinder.Unbind(
    CancelCookie As <Unsupported variant type>
)

Parameters

CancelCookie

Specifies which event handler to unbind. Use the return value from the MSEventBinder.Bind method.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

See Also

  • MSEventBinder Object


MSVidAnalogTunerDevice Object

This topic applies to Windows XP only.

The MSVidAnalogTunerDevice object represents a hardware analog video tuning device on the local system. Internally, the Video Control uses the DirectShow IAMTuner and IAMTVTuner COM interfaces to control and configure an analog TV tuner. In some cases, the documentation for those interfaces contains further information relevant to the properties and methods of MSVidAnalogTunerDevice.

This object inherits all the method and properties of the IMSVidInputDevice object. In addition, it exposes the following methods and properties.

Property | Description
AudioFrequency | Retrieves the tuner's audio frequency for testing purposes.
Channel | Specifies and retrieves the tuner's channel setting.
CountryCode | Specifies and retrieves the tuner's country/region code.
SAP | Specifies and retrieves the tuner's SAP setting to enable secondary audio components.
Tune | Specifies and retrieves the Tune Request object currently associated with the tuner.
TuningSpace | Retrieves the tuning space associated with the currently active tune request.
VideoFrequency | Retrieves the tuner's video frequency for testing purposes.

Method | Description
ChannelAvailable | Retrieves a value indicating whether a specified channel is available for viewing.

Event | Description
TuneChanged | Called by the tuner when it cannot tune to the requested channel or frequency.


MSVidAnalogTunerDevice.AudioFrequency

This topic applies to Windows XP only.

The AudioFrequency property retrieves the tuner's audio frequency.

Syntax

objMSVidAnalogTunerDevice.AudioFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the audio frequency.

Remarks

This property is read-only.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.Channel

This topic applies to Windows XP only.

The Channel property sets or retrieves the tuner's current channel.

Syntax

objMSVidAnalogTunerDevice.Channel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the channel number.

Remarks

This property is read/write.

See Also

  • MSVidAnalogTunerDevice.ChannelAvailable
  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.CountryCode

This topic applies to Windows XP only.

The CountryCode property sets or retrieves the tuner's country/region code.

Syntax

objMSVidAnalogTunerDevice.CountryCode As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the country/region code.

Remarks

Do not confuse the international country/region code with the LCID. The country/region code establishes the mapping between channel numbers and frequencies

This property is read/write.

See Also

  • MSVidAnalogTunerDevice Object
  • International Analog TV Tuning


MSVidAnalogTunerDevice.SAP

This topic applies to Windows XP only.

The SAP property sets and retrieves the tuner's secondary audio program (SAP) setting to enable or disable the SAP channel.

This property is currently not implemented.

Syntax

objMSVidAnalogTunerDevice.SAP As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the SAP channel is enabled, or False otherwise.

Remarks

The SAP channel applies only to analog TV broadcasts; digital broadcasts use other means to enable multiple audio channels.

This property is read/write.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.VideoFrequency

This topic applies to Windows XP only.

The VideoFrequency property retrieves the tuner's video frequency.

Syntax

objMSVidAnalogTunerDevice.VideoFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the video frequency.

Remarks

This property is read-only.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.ChannelAvailable

This topic applies to Windows XP only.

The ChannelAvailable method queries whether a specified channel is available for viewing.

This method is currently not implemented.

Syntax

objMSVidAnalogTunerDevice.ChannelAvailable(
  nChannel As Long,
  SignalStrength As Long
) As Boolean

Parameters

nChannel

Specifying the channel.

SignalStrength

Variable that receives the signal strength.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the channel is available, or False otherwise.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.Tune

This topic applies to Windows XP only.

The Tune property sets or retrieves the current tune request.

Syntax

objMSVidAnalogTunerDevice.Tune As ITuneRequest

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an ITuneRequest object.

Remarks

Setting the property causes the device to tune to the channel or frequency specified in the tune request.

This property is read/write.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAnalogTunerDevice.TuningSpace

This topic applies to Windows XP only.

The TuningSpace property sets or retrieves the current tuning space.

Syntax

objMSVidAnalogTunerDevice.TuningSpace As ITuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an ITuningSpace object.

Remarks

This property is read/write.

See Also

  • MSVidAnalogTunerDevice Object


MSVidAudioRenderer Object

This topic applies to Windows XP only.

The MSVidAudioRenderer object represents a hardware audio rendering device on the local system, in other words a sound card and its associated driver.

This object inherits all the methods and properties of the IMSVidDevice object. In addition, it exposed the following properties.

Property | Description
Balance | Specifies and retrieves the balance between the left and right audio channels.
Volume | Specifies and retrieves the volume level.

Event | Description
StateChange | Called when the state of the device changes.


MSVidAudioRenderer.Balance

This topic applies to Windows XP only.

The Balance property sets or retrieves the audio renderer's balance level.

Syntax

objMSVidAudioRenderer.Balance As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a number from -10,000 to 10,000.

Remarks

The balance level is a value between –10,000 and 10,000, measured in hundredths of a decibel (dB). If the value is -10,000, the left channel is at full volume and the right channel is attenuated by 100 dB. If the value is 10,000, the right channel is at full volume and the left channel is attenuated by 100 dB. If the value is zero, both channels are at full volume.

This property is read/write.

See Also

  • MSVidAudioRenderer Object


MSVidAudioRenderer.Volume

This topic applies to Windows XP only.

The Volume property sets or retrieves the audio renderer's volume level.

Syntax

objMSVidAudioRenderer.Volume As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a number from -10,000 to 0, inclusive.

Remarks

Full volume is 0 and silence is –10,000. Divide by 100 to get the equivalent decibel value; for example, –10,000 is –100 dB.

This property is read/write.

See Also

  • MSVidAudioRenderer Object
  • IBasicAudio Interface
  • IAMTVAudio Interface


MSVidAudioRendererDevices Object

This topic applies to Windows XP only.

The MSVidAudioRendererDevices object represents a read-only collection of audio rendering devices (such as sound cards) on the local system. On most systems, there will be only one item in this collection.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the specified MSVidAudioRenderer object.

Method | Description
Add | Has no effect on this read-only collection.
Remove | Has no effect on this read-only collection.


MSVidAudioRendererDevices.Count

This topic applies to Windows XP only.

The Count property retrieves the number of items in the collection.

Syntax

objMSVidAudioRendererDevices.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the number of items in the collection.

Remarks

This property is read-only.

See Also

  • MSVidAudioRendererDevices Object


MSVidAudioRendererDevices.Item

This topic applies to Windows XP only.

The Item property retrieves a specified item in the collection.

Syntax

objMSVidAudioRendererDevices.Item(
    v As Object
) As MSVidAudioRenderer

Parameters

v

Specifies the index of the item to retrieve. The valid range is from 0 to MSVidAudioRendererDevices.Count - 1.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidAudioRenderer object.

Remarks

This property is the default member of the MSVidAudioRendererDevices object, so you do not need to specify the property name when you retrieve it. For example, the following are equivalent:

Set objAudioRenderer = colAudioRenderers.Item(1)
Set objAudioRenderer = colAudioRenderers(1)

This property is read-only.

See Also

  • MSVidAudioRendererDevices Object


MSVidAudioRendererDevices.Add

This topic applies to Windows XP only.

The Add method adds an item to the collection

Syntax

ObjMSVidAudioRendererDevices.Add(
    pDB As MSVidAudioRenderer
)

Parameters

Specifies the MSVidAudioRenderer object to add.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidAudioRendererDevices Object


MSVidAudioRendererDevices.Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

ObjMSVidAudioRendererDevices.Remove(
    v As Object
)

Parameters

v

Specifies the index of the item to remove. The valid range is from 0 to MSVidAudioRendererDevices.Count - 1.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remove

This method fails if the collection is read-only.

See Also

  • MSVidAudioRendererDevices Object


MSVidBDATunerDevice Object

This topic applies to Windows XP only.

The MSVidBDATunerDevice object represents a BDA-compatible tuner device.

This object inherits all the methods and properties of the IMSVidInputDevice object. In addition, it exposes the following properties.

Property | Description
Tune | Specifies and retrieves the Tune Request object currently associated with the tuner.
TuningSpace | Retrieves the tuning space associated with the currently active tune request.

Event | Description
TuneChanged | Called when the device cannot tune to the requested channel or frequency.


MSVidBDATunerDevice.Tune

This topic applies to Windows XP only.

The Tune property sets or retrieves the current tune request.

Syntax

objMSVidBDATunerDevice.Tune As ITuneRequest

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an ITuneRequest object.

Remarks

Setting the property causes the device to tune to the channel or frequency specified in the tune request.

This property is read/write.

See Also

  • MSVidBDATunerDevice Object


MSVidBDATunerDevice.TuningSpace

This topic applies to Windows XP only.

The TuningSpace property sets or retrieves the current tuning space.

Syntax

objMSVidBDATunerDevice.TuningSpace As ITuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an ITuningSpace object.

Remarks

This property is read/write.

See Also

  • MSVidBDATunerDevice Object
  • MSVidBDATunerDevice.Tune


MSVidClosedCaptioning Object

This topic applies to Windows XP only.

The MSVidClosedCaptioning object represents the closed-captioning feature in the features collection.

This object has the following CLSID:

{7F9CB14D-48E4-43B6-9346-1AEBC39C64D3}

To access this object, enumerate the features in the MSVidCtl.FeaturesAvailable collection. Compare the IMSVidDevice.ClassID property with the CLSID. To enable the feature, add the object to the MSVidCtl.FeaturesActive collection. Once the feature is active, you can enable or disable closed captioning by setting the Enable property.

This object inherits all the methods and properties of the IMSVidDevice object. In addition, it exposes the following property.

Property | Type
Enable | Enables or disables closed captioning.
Service | Sets the closed captioning service.

See Also

  • Displaying Closed Captioning in Visual Basic


MSVidClosedCaptioning.Enable

This topic applies to Windows XP only.

The Enable property enables or disables closed captioning.

Syntax

objMSVidClosedCaptioning.Enable As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if closed caption is enabled, or False otherwise.

Remarks

This property is read/write.

See Also

  • MSVidClosedCaptioning Object


MSVidClosedCaptioning.Service

This topic applies to Windows XP Service Pack 1 only.

The Service property sets the closed captioning service.

Syntax

objMSVidClosedCaptioning.Service As MSVidCCService

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidCCService constant.

Remarks

This property is read/write.

See Also

  • MSVidClosedCaptioning Object


MSVidCtl Object

This topic applies to Windows XP only.

The MSVidCtl object, also called the Video Control, is an ActiveX control that creates and manages filter graphs for analog and digital TV. In addition to the stock ActiveX properties, MSVidCtl provides methods for building the filter graph; submitting a tune request; and running, pausing, and stopping the graph. It also contains properties for retrieving devices and features.

Visual Basic applications can host this control directly in a Visual Basic form. Script applications can host this control using the OBJECT tag:

<OBJECT ID="MSVidCtl" CLASSID="CLSID:B0EDF163-910A-11D2-B632-00C04F79498E"></OBJECT>

This object exposes the following methods and properties.

Property | Description
AudioRendererActive | Sets or retrieves the currently active audio renderer.
AudioRenderersAvailable | Retrieves a collection of audio renderer devices available on the local system.
AutoSize | Returns or sets a value that determines whether the Video Control is automatically resized to display its entire contents.
BackColor | Retrieves or sets the background color of the Video Control.
ColorKey | Retrieves or sets the color key.
DisplaySize | Retrieves or sets the display size.
Enabled | Sets or retrieves a value that determines whether the Video Control can respond to user-generated events.
FeaturesActive | Sets or retrieves a collection of the features currently active.
FeaturesAvailable | Retrieves a collection of features available on the local system.
InputActive | Sets or retrieves the currently active input device.
InputsAvailable | Retrieves a collection of inputs available on the local system.
MaintainAspectRatio | Sets or retrieves a value indicating whether the Video Control should maintain the aspect ratio of the source video when resizing its own rectangle.
OutputsActive | Sets or retrieves the currently active output device.
OutputsAvailable | Retrieves a collection of outputs for a specified category that are available on the local system.
State | Retrieves the current state of the Video Control.
TabStop | Sets or retrieves a value indicating whether a user can use the TAB key to give the focus to the Video Control.
VideoRendererActive | Sets or retrieves the currently active video renderer.
VideoRenderersAvailable | Retrieves a collection of video renderers available on the local system.
Window | Retrieves the window handle associated with the Video Control.

Method | Type
Build | Builds the underlying filter graph and connects all the filters.
Decompose | Disassembles the filter graph.
DisableAudio | Sets the active audio renderer to Nothing.
DisableVideo | Sets the active video renderer to Nothing.
Pause | Pauses the filter graph.
Refresh | Immediately updates the Video Control's appearance.
Run | Runs (and, if necessary, builds) the filter graph.
Stop | Stops the filter graph.
View | Selects an input device that is capable of handling a specified channel or frequency, and builds a filter graph.
ViewNext | Finds another input device for viewing the specified item.

Event | Description
Click | Called when a user clicks anywhere on the MSVidCtl rectangle.
DblClick | Called when a user double-clicks on the MSVidCtl rectangle.
Error | Called when an error occurs in the Video Control or in the underlying filter graph. Currently, no errors are defined for this event.
KeyDown | Called when the user presses a key.
KeyPress | Called when the user presses and releases a key.
KeyUp | Called when the user releases a key.
MouseDown | Called when the user presses the left mouse key down while the mouse pointer is over the Video Control.
MouseMove | Called when the user moves the mouse pointer over the Video Control.
MouseUp | Called when the user releases the left mouse button while the mouse pointer is over the Video Control.
StateChange | Called when the state of the control changes.

See Also

  • TV Applications in Visual Basic (Video Control)
  • TV Applications in Script (Video Control)


MSVidCtl.AudioRendererActive

This topic applies to Windows XP only.

The Active property sets or retrieves the currently active audio renderer.

Syntax

objMSVidCtl.AudioRendererActive As MSVidAudioRenderer

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidAudioRenderer object, or Nothing.

Remarks

This property is read/write. It is set automatically when the Video Control builds the filter graph.

Example Code

Dim objAudioRenderer As MSVidAudioRenderer
Set objAudioRenderer = VideoControl1.AudioRendererActive
If (Not objAudioRenderer Is Nothing) Then
    VolumeLabel.Caption = Str(objAudioRenderer.Volume)
End If

See Also

  • MSVidCtl Object
  • MSVidCtl.VideoRendererActive


MSVidCtl.AudioRenderersAvailable

This topic applies to Windows XP only.

The AudioRenderersAvailable object retrieves the available audio renderers.

Syntax

objMSVidCtl.AudioRenderersAvailable As MSVidAudioRendererDevices

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a read-only MSVidAudioRendererDevices collection.

Remarks

This property is read-only.

Example Code

Dim objAudio As MSVidAudioRenderer
For Each objAudio In VideoControl1.AudioRenderersAvailable
    ' ...
Next

See Also

  • MSVidCtl Object
  • MSVidCtl.AudioRendererActive


MSVidCtl.AutoSize

This topic applies to Windows XP only.

The AutoSize property determines whether the Video Control is automatically resized to display its entire contents.

Syntax

objMSVidCtl.AutoSize As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the Video Control is automatically resized, or False otherwise.

Remarks

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

See Also

  • MSVidCtl Object


MSVidCtl.BackColor

This topic applies to Windows XP only.

The BackColor property sets or retrieves the background color of the Video Control.

Syntax

objMSVidCtl.BackColor As OLE_COLOR

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an OLE_COLOR value.

Remarks

The Video Control uses the background color when the filter graph is stopped or unbuilt. It also uses this color in letterbox mode to paint unused areas of the video rectangle. The background color is sometimes called the "border" color.

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

Example Code

Const Orange = &H80FF&
VideoControl1.BackColor = Orange

See Also

  • MSVidCtl Object


MSVidCtl.ColorKey

This topic applies to Windows XP only.

The ColorKey property sets or retrieves the color key that the video renderer is using. The color key is used when the video renderer draws to an overlay surface

Syntax

objMSVidCtl.ColorKey As OLE_COLOR

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an OLE_COLOR value.

Remarks

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

See Also

  • MSVidCtl Object


MSVidCtl.DisableAudio

This topic applies to Windows XP only.

The DisableAudio method disables the audio output device.

Syntax

ObjMSVidCtl.DisableAudio()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

This method sets the MSVidCtl.AudioRendererActive property to Nothing.

See Also

  • MSVidCtl Object


MSVidCtl.DisableVideo

This topic applies to Windows XP only.

The DisableVideo method disables the video renderer.

Syntax

ObjMSVidCtl.DisableVideo()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

This method sets the MSVidCtl.VideoRendererActive property to Nothing.

See Also

  • MSVidCtl Object


MSVidCtl.DisplaySize

This topic applies to Windows XP only.

The DisplaySize property sets or retrieves the current display size.

Syntax

objMSVidCtl.DisplaySize As DisplaySizeList

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a DisplaySizeList constant.

Remarks

This property has no effect if the MSVidCtl.AutoSize property is False. If AutoSize is True, this property determines the Video Control's dimensions when it resizes itself.

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

Example

' Set the display size to half-screen.
VideoControl1.AutoSize = True
VideoControl1.DisplaySize = dslHalfScreen

See Also

  • MSVidCtl Object


MSVidCtl.Enabled

This topic applies to Windows XP only.

The Enabled property determines whether the Video Control responds to user-generated events, such as mouse clicks.

Syntax

objMSVidCtl.Enabled As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the Video Control responds to user-generated events, or False otherwise.

Remarks

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

See Also

  • MSVidCtl Object


MSVidCtl.FeaturesActive

This topic applies to Windows XP only.

The FeaturesActive property sets or retrieves the features that are currently active.

Syntax

objMSVidCtl.FeaturesActive As MSVidFeatures

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidFeatures collection.

Remarks

Features represent additional capabilities beyond basic tuning and rendering, such as closed captioning or IP data services. When the Video Control builds the filter graph, it uses the active features collection to configure the graph.

If no features are active, the value of this property might be Nothing. Otherwise, it returns an MSVidFeatures collection; use this collection to enumerate the features.

For a default graph, it is not necessary to specify the active features. To activate a feature, create a new MSVidFeatures collection object. Enumerate the available features using the Video Control's MSVidCtl.FeaturesAvailable property. If the IMSVidDevice.ClassID property matches the class identifier (CLSID) of the feature you wish to activate, add that feature to your MSVidFeatures collection. Finally, set the MSVidCtl.FeaturesActive property equal to the new MSVidFeatures collection.

If the MSVidCtl.State property is not STATE_UNBUILT, call the MSVidCtl.Decompose to tear down the filter graph before setting this property.

This property is read/write.

See Also

  • MSVidCtl Object
  • Displaying Closed Captioning in Visual Basic


MSVidCtl.FeaturesAvailable

This topic applies to Windows XP only.

The FeaturesAvailable property retrieves the features that are available on the local system.

Syntax

objMSVidCtl.FeaturesAvailable As MSVidFeatures

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidFeatures collection.

Remarks

This property returns a collection of IMSVidFeature objects. To activate a feature, add it to the active features collection. To search for a specific feature, compare the IMSVidDevice.ClassID property of each against the class identifier (CLSID) of the feature you are looking for.

This property is read-only.

See Also

  • 52MSVidCtl Object
  • MSVidCtl.FeaturesActive


MSVidCtl.InputActive

This topic applies to Windows XP only.

The InputActive property sets or input device that is currently active.

Syntax

objMSVidCtl.InputActive As MSVidInputDevice

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns either an MSVidBDATunerDevice or an MSVidAnalogTunerDevice object.

Remarks

If the MSVidCtl.State property is not STATE_UNBUILT, call the MSVidCtl.Decompose to tear down the filter graph before setting this property.

This property is read/write.

See Also

  • MSVidCtl Object


MSVidCtl.InputsAvailable

This topic applies to Windows XP only.

The InputsAvailable property retrieves the input devices that are available within a specified category.

Syntax

objMSVidCtl.InputsAvailable(
    CategoryGuid As String
) As MSVidInputDevices

Parameters

strCategoryGuid

Specifies a GUID that identifies the device category to enumerate. Supported categories include the following:

Value | Description
{71985F4B-1CA1-11d3-9CC8-00C04F7971E0} | BDA-compatible tuner devices
{a799a800-a46d-11d0-a18c-00a02401dcd4} | Non-BDA analog tuner devices.
{00000000-0000-0000-0000-000000000000} | Miscellaneous input devices (file playback, DVD).

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a read-only MSVidInputDevices collection.

Remarks

This property is read-only.

Example Code

Const clsidAnalogTuners = "{a799a800-a46d-11d0-a18c-00a02401dcd4}"
Dim objTuner As MSVidAnalogTunerDevice
For Each objTuner in VideoControl.InputsAvailable(clsidAnalogTuners)
    List1.AddItem objTuner.Name
Next

See Also

  • MSVidCtl Object


MSVidCtl.MaintainAspectRatio

This topic applies to Windows XP only.

The MaintainAspectRatio property determines whether the Video Control maintains the aspect ratio of the source video.

Syntax

objMSVidCtl.MainAspectRatio As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the Video Control maintains the aspect ratio of the source video, or False otherwise.

Remarks

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

See Also

  • MSVidCtl Object


MSVidCtl.OutputsActive

This topic applies to Windows XP only.

The OutputsActive property sets or retrieves the output devices that are currently active.

This property is currently not supported. To obtain the active renderers, use the MSVidCtl.AudioRendererActive and MSVidCtl.VideoRendererActive properties.

Syntax

objMSVidCtl.OutputsActive As MSVidOutputDevices

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidOutputDevices collection.

Remarks

This property is read/write.

See Also

  • MSVidCtl Object


MSVidCtl.OutputsAvailable

This topic applies to Windows XP only.

The OutputsAvailable property retrieves the output devices that are available in a specified category.

This property is currently not supported.

Syntax

objMSVidCtl.OutputsAvailable(
    CategoryGuid As String
) As MSVidOutputDevices

Parameters

CategoryGuid

Specifies a GUID that identifies the device category to enumerate.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidOutputDevices collection.

Remarks

This property is read-only.

See Also

  • MSVidCtl Object


MSVidCtl.State

This topic applies to Windows XP only.

The State property retrieves the current state of the filter graph.

Syntax

objMSVidCtl.State As MSVidCtlStateList

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidCtlStateList constant.

Remarks

This property is read-only.

See Also

  • MSVidCtl Object


MSVidCtl.TabStop

This topic applies to Windows XP only.

The TabStop property indicates whether a user can use the TAB key to give the focus to the Video Control.

Syntax

objMSVidCtl.TabStop As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the Video Control is in the tabbing order, or False otherwise.

Remarks

This property is read/write. In Visual Basic, you can set this property at design time using the Properties dialog.

See Also

  • MSVidCtl Object


MSVidCtl.VideoRendererActive

This topic applies to Windows XP only.

The VideoRendererActive property sets or retrieves the currently active video renderer.

Syntax

objMSVidCtl.VideoRendererActive As MSVidVideoRenderer

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidVideoRenderer object.

Remarks

Currently the only supported video renderer is the Video Mixing Renderer Filter (VMR). The VMR is used by default, so it is not necessary to set the property. Applications can retrieve this property to set properties on the VMR, such as the clipping rectangle or the static bitmap.

This property is read/write.

See Also

  • MSVidCtl Object


MSVidCtl.VideoRenderersAvailable

This topic applies to Windows XP only.

The VideoRenderersAvailable property retrieves a collection of video renderers available on the local system.

Syntax

objMSVidCtl.VideoRenderersAvailable As MSVideoRendererDevice

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a read-only MSVidVideoRendererDevices collection.

Remarks

Currently, this property always returns a collection that contains exactly one item: an MSVidVideoRenderer object representing the Video Mixing Renderer Filter (VMR).

Once the filter graph is built, you can also obtain the VMR through the MSVidCtl.VideoRendererActive property.

This property is read-only.

See Also

  • MSVidCtl Object


MSVidCtl.Window

This topic applies to Windows XP only.

This property is not supported for Visual Basic.

Syntax

objMSVidCtl.Window As wireHWND

See Also

  • MSVidCtl Object


MSVidCtl.Build

This topic applies to Windows XP only.

The Build method builds the filter graph.

Syntax

objMSVidCtl.Build()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method builds a filter graph using the current input device. To select an input device, call the MSVidCtl.View method or set the MSVidCtl.InputActive property. If no input device has been selected, the method fails.

See Also

  • MSVidCtl Object


MSVidCtl.Decompose

This topic applies to Windows XP only.

The Decompose method tears down the filter graph.

Syntax

objMSVidCtl.Decompose()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method is the inverse of MSVidCtl.Build. Call this method before you change the active features collection, specify a new renderer, or specify a new input device. The method does not modify the active features collection.

See Also

  • MSVidCtl Object


MSVidCtl.Pause

This topic applies to Windows XP only.

The Pause method pauses the filter graph.

Syntax

objMSVidCtl.Pause()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

See Also

  • MSVidCtl Object


MSVidCtl.Refresh

This topic applies to Windows XP only.

The Refresh method immediately updates the Video Control's appearance.

Syntax

objMSVidCtl.Refresh()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Example

VidCtl.Refresh

Remarks

This method is a stock ActiveX® Control method. It forces the Video Control window to repaint itself. Before repainting, the Video Control ensures that the video rectangle is up to date and that all Video Mixing Renderer settings are correct.

See Also

  • MSVidCtl Object


MSVidCtl.Run

This topic applies to Windows XP only.

The Run method runs the filter graph.

Syntax

objMSVidCtl.Run()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Example

VidCtl.Run

Remarks

This method builds the filter graph if the state is unbuilt, and puts the graph into the running state. For more information on the behavior of Build, View and Run, see MSVidCtl.View

See Also

  • MSVidCtl Object


MSVidCtl.Stop

This topic applies to Windows XP only.

Stops the filter graph.

Syntax

objMSVidCtl.Stop()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method leaves the filter graph intact and ready to pause or run. To tear down the filter graph, use the MSVidCtl.Decompose method.

See Also

  • MSVidCtl Object


MSVidCtl.View

This topic applies to Windows XP only.

The View method configures an input device for a specified tune request.

Syntax

objMSVidCtl.View(
    v As Object
)

Parameters

v

Specifies the tune request as an ITuneRequest object.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

If the Video Control already has an active input device, this method configures the device for the specified tune request. Otherwise, this method locates an input device that can handle the tune request and activates it.

An input device typically corresponds to a source filter. The Video Control determines which filter to use by examining the network type on the tune request. For digital television, the input device will be a BDA Network Provider filter. For analog television, it will be a WDM TV Tuner filter. The specific name and implementation of the filter are device-dependent.

After calling View, build and run the filter graph, using the following methods:

  • The MSVidCtl.Build method builds the rest of the filter graph, based on the selected input and the active features collection. The Build method leaves the graph in a stopped state.
  • The MSVidCtl.Run method calls Build if the graph is not built, and puts the graph into a running state. When the filter graph runs, the video control starts playing the specified tune request.

If the filter graph is already built and running, an application can call View to specify a new tune request, either on the same network type or on a different network type.

You can specify a particular input device by setting the MSVidCtl.InputActive property and then calling IMSVidInputDevice.View on the device, instead of calling View on the Video Control. This might be useful if the local system has multiple devices of the same type. The MSVidCtl.View method is preferred, however, because it automatically locates the correct device type.

See Also

  • MSVidCtl Object
  • The Microsoft Unified Tuning Model
  • Hosting the Video Control in a Visual Basic Form


MSVidCtl.ViewNext

This topic applies to Windows XP only.

The ViewNext method finds another input device to view the specified tune request.

This method is supported only for analog tuner devices. It does not work with digital tuners.

Syntax

objMSVidCtl.View(
    v As Object
)

Parameters

v

Specifies the tune request as an ITuneRequest object.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

This method works like the MSVidCtl.View method, with the following difference: If the system has more than one tuner that supports the specified network type, the ViewNext method skips the current input device and uses the next one. (The ordering of devices is arbitrary.)

See Also

  • MSVidCtl Object
  • The Microsoft Unified Tuning Model


MSVidDataServices Object

This topic applies to Windows XP only.

The MSVidDataServices object represents the data services feature that is exposed by the Video Control.

This object has the following CLSID:

{334125C0-77E5-11d3-B653-00C04F79498E}

To access this object, enumerate the features in the MSVidCtl.FeaturesAvailable collection. Compare the IMSVidDevice.ClassID property with the CLSID. To enable the feature, add the object to the MSVidCtl.FeaturesActive collection.

This object inherits all the methods and properties of the IMSVidDevice object.


MSVidFeatures Object

This topic applies to Windows XP only.

The MSVidFeatures object is a collection of IMSVidFeature objects, each of which represents a feature supported by the Video Control. Applications work with two instances of this collection:

The MSVidCtl.FeaturesAvailable collection contains all of the features that are available on the current system

The MSVidCtl.FeaturesActive collection contains the features that are active for the current session.

This object exposes the following properties and methods.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the specified item from the collection.

Method | Description
Add | Adds a feature to the collection.
Remove | Removes a feature from the collection.


MSVidFeatures.Count

This topic applies to Windows XP only.

The Count property retrieves the number of items in the collection.

Syntax

objMSVidFeatures.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the number of items.

Remarks

This property is read-only.

See Also

  • MSVidFeatures Object


MSVidFeatures.Item

This topic applies to Windows XP only.

The Item property retrieves the specified item from the collection.

Syntax

objMSVidFeatures.Item(
    v As Object
) As MSVidFeature

Parameters

v

Specifies the index of the item to retrieve. The valid range is from 0 to MSVidFeatures.Count - 1.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an IMSVidFeature.

Remarks

This property is the default member of the MSVidFeatures object, so you do not need to specify the property name when you retrieve it. For example, the following are equivalent:

Set objFeature = colFeatures.Item(1)
Set objFeature = colFeatures(1)

This property is read-only.

See Also

  • MSVidFeatures Object


MSVidFeatures.Add

This topic applies to Windows XP only.

The Add method adds an item to the collection.

Syntax

objMSVidFeatures.Add(
    pDB As MSVidFeature
)

Parameters

pDB

Specifies the IMSVidFeature to add.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidFeatures Object


MSVidFeatures.Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

ObjMSVidFeatures.Remove(
    v As Object
)

Parameters

v

Specifies the index of the item to remove. The valid range is from 0 to MSVidFeatures.Count - 1.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidFeatures Object


MSVidFilePlaybackDevice Object

This topic applies to Windows XP Service Pack 1 only.

The MSVIdFilePlaybackDevice object represents a file-playback input device.

This object has the following CLSID:

{37B0353C-A4C8-11d2-B634-00C04F79498E}

To play back a local file with the Video Control, pass the file name to the MSVidCtl.View method. If the method succeeds, you can get the MSVidFilePlaybackDevice object from the MSVidCtl.InputActive property.

This object inherits all of the properties and methods of the IMSVidPlayback object. In addition, it supports the following properties and events.

Property | Description
FileName | Sets or retrieves the name of the file to play.

Event | Description
EndOfMedia | Called when playback reaches the end of the file.


MSVidFilePlaybackDevice.FileName

This topic applies to Windows XP Service Pack 1 only.

The FileName property indicates the name of the file to play.

Syntax

objMSVidFilePlayback.FileName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the file name.

Remarks

This property is read/write.

See Also

  • MSVidFilePlaybackDevice Object


MSVidInputDevices Object

This topic applies to Windows XP only.

The MSVidInputDevices object represents a collection input devices. Currently, this object always contains MSVidAnalogTunerDevice objects or MSVidBDATunerDevice objects.

The MSVidCtl.InputsAvailable property returns this object.

This object exposes the following methods and properties.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the specified item from the collection.

Method | Description
Add | Adds an item to the collection.
Remove | Removes an item from the collection.


MSVidInputDevices.Count

This topic applies to Windows XP only.

The Count property etrieves the number of items in the collection.

Syntax

objMSVidInputDevices.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the number of items.

Remarks

This property is read-only.

See Also

  • MSVidInputDevices Object


MSVidInputDevices.Item

This topic applies to Windows XP only.

The Item property retrieves the specified item from the collection.

Syntax

objMSVidInputDevices.Item(
    v As Object
) As MSVidInputDevice

Parameters

v

Specifies the index of the item to retrieve. The valid range is from 0 to MSVidInputDevices.Count - 1.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns either an MSVidAnalogTunerDevice object or an MSVidBDATunerDevice object.

Remarks

This property is the default member of the MSVidInputDevices object, so you do not need to specify the property name when you retrieve it. For example, the following are equivalent:

Set objInput = colInputs.Item(1)
Set objInput = colInputs(1)

This property is read-only.

See Also

  • MSVidInputDevices Object


MSVidInputDevices.Add

This topic applies to Windows XP only.

The Add method adds an item to the collection.

Syntax

objMSVidInputDevices.Add(
    pDB As MSVidInputDevice
)

Parameters

pDB

Specifies the object to add.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method has no return value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidInputDevices Object


MSVidInputDevices.Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

ObjMSVidInputDevices.Remove(
    v As Object
)

Parameters

v

Specifies the index of the item to remove. The valid range is from 0 to MSVidInputDevices.Count - 1.

Return Values

This method has no return value.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidInputDevices Object


MSVidOutputDevices Object

This topic applies to Windows XP only.

The MSVidOutputDevices object represents a collection output devices. In this version of Windows XP, however, there are no supported methods that return this object.

The only output devices currently supported are video and audio renderers. To obtain these, use the following properties:

  • MSVidCtl.AudioRendererActive
  • MSVidCtl.AudioRenderersAvailable
  • MSVidCtl.VideoRendererActive
  • MSVidCtl.VideoRenderersAvailable

This object exposes the following methods and properties.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the specified item from the collection.

Method | Description
Add | Adds an item to the collection.
Remove | Removes an item from the collection.


MSVidOutputDevices.Count

This topic applies to Windows XP only.

The Count property retrieves the number of items in the collection.

Syntax

objMSVidOutputDevices.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the number of items.

Remarks

This property is read-only.

See Also

  • MSVidOutputDevices Object


MSVidOutputDevices.Item

This topic applies to Windows XP only.

The Item property retrieves the specified item from the collection.

Syntax

objMSVidOutputDevices.Item(
    v
) As MSVidOutput

Parameters

v

Specifies the index of the item to retrieve. The valid range is from 0 to MSVidOutputDevices.Count - 1.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidOutputDevice object.

Remarks

This property is the default member of the MSVidOutputDevices object, so you do not need to specify the property name when you retrieve it. For example, the following are equivalent:

Set objOutput = colOutputs.Item(1)
Set objOutnput = colOutputs(1)

This property is read-only.

See Also

  • MSVidOutputDevices Object


MSVidOutputDevices.Add

This topic applies to Windows XP only.

The Add method adds an item to the collection.

Syntax

ObjMSVidOutputDevices.Add(
    pDB As MSVidOutput
)

Parameters

pDB

Specifies the object to add.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method has no return value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidOutputDevices Object


MSVidOutputDevices.Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

ObjMSVidOutputDevices.Remove(
    v As Object
)

Parameters

v

Specifies the index of the item to remove. The valid range is from 0 to MSVidOutputDevices.Count - 1.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidOutputDevices Object


MSVidStreamBufferRecordingControl Object

The MSVidStreamBufferRecordingControl object is used to manage a stream buffer recording. The MSVidStreamBufferSink.ContentRecorder and MSVidStreamBufferSink.ReferenceRecorder properties return this object.

The MSVidStreamBufferRecordingControl object exposes the following properties.

Property | Description
RecordingAttribute | Returns the underlying Recording object that is controlled by this object.
RecordingStarted | Indicates whether the recording has started.
RecordingStopped | Indicates whether the recording has stopped.
RecordingType | Retrieves the type of recording, either reference or content.
StartTime | Sets the start time for the recording.
StopTime | Sets the stop time for the recording.


MSVidStreamBufferRecordingControl.RecordingAttribute

This topic applies to Windows XP Service Pack 1 only.

The RecordingAttribute property returns the underlying Recording object that is controlled by this object.

Syntax

objSBERecording.RecordingAttribute As Unknown

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the Recording object as an Unknown object.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferRecordingControl.RecordingStarted

This topic applies to Windows XP Service Pack 1 only.

The RecordingStarted property indicates whether the recording has started.

Syntax

objSBERecording.RecordingStarted As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the recording has started, or False otherwise.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferRecordingControl.RecordingStopped

This topic applies to Windows XP Service Pack 1 only.

The RecordingStopped property indicates whether the recording has stopped.

Syntax

objSBERecording.RecordingStopped As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the recording has stopped, or False otherwise.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferRecordingControl.RecordingType

This topic applies to Windows XP Service Pack 1 only.

The RecordingType property retrieves the type of recording, either content recording or reference recording.

Syntax

objSBERecording.RecordingType As RecordingType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns one of the following constants.

Constant | Value | Description
CONTENT | 0 | Content recording.
REFERENCE | 1 | Reference recording.

Remarks

This property is read-only.

See Also

  • Creating Stream Buffer Recordings
  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferRecordingControl.StartTime

This topic applies to Windows XP Service Pack 1 only.

The StartTime property sets the start time for the recording.

Syntax

objSBERecording.StartTime As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the start time, in hundredths of seconds.

Remarks

This property is read/write.

See Also

  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferRecordingControl.StopTime

This topic applies to Windows XP Service Pack 1 only.

The StopTime property sets the stop time for the recording.

Syntax

objSBERecording.StopTime As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the stop time, in hundredths of seconds.

Remarks

This property is read/write.

See Also

  • MSVidStreamBufferRecordingControl Object


MSVidStreamBufferSink Object

This topic applies to Windows XP Service Pack 1 only.

The MSVidStreamBufferSink object represents a stream buffer output (sink) device.

This object has the following CLSID:

{9E77AAC4-35E5-42a1-BDC2-8F3FF399847C}

This object inherits all the methods and properties of the IMSVidDevice object. In addition, it exposes the following methods and properties.

Property | Description
ContentRecorder | Creates a new content recording object.
ReferenceRecorder | Creates a new reference recording object.
SBESink | Retrieves the Stream Buffer Sink filter.
SinkName | Sets and retrieves the name of the stub file that points to the backing files.

Method | Description
NameSetLock | Locks the stream buffer profile.

The IMSVidStreamBuffer object fires the following events.

Event | Description
CertificateFailure | Fired when the object fails to get an encryption/decription license.
CertificateSuccess | Fired when the object succeeds in getting an encryption/decription license.
StateChange | Called when the object changes state.


MSVidStreamBufferSink.ContentRecorder

This topic applies to Windows XP Service Pack 1 only.

The ContentRecorder property creates a new content recording object.

Syntax

objSBESink.ContentRecorder(
    szFilename As MSVidStreamBufferRecordingControl
) As Boolean

Parameters

szFilename

Specifies the name of the file to hold the recording.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a new MSVidStreamBufferRecordingControl object. Use this object to start and stop the recording.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSink Object


MSVidStreamBufferSink.ReferenceRecorder

This topic applies to Windows XP Service Pack 1 only.

The ReferenceRecorder property creates a new reference recording object.

Syntax

objSBESink.ReferenceRecorder(
    szFilename As MSVidStreamBufferRecordingControl
) As Boolean

Parameters

szFilename

Specifies the name of the file to hold the recording.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a new MSVidStreamBufferRecordingControl object. Use this object to start and stop the recording.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSink Object


MSVidStreamBufferSink.SBESink

This topic applies to Windows XP Service Pack 1 only.

The SBESink property retrieves the Stream Buffer Sink filter.

Syntax

objSBESink.SBESink As Unknown

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the Stream Buffer Sink filter as an Unknown object.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSink Object


MSVidStreamBufferSink.SinkName

This topic applies to Windows XP Service Pack 1 only.

The SinkName property sets and retrieves the name of the stub file that points to the backing files.

Syntax

objSBESink.SinkName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the file name.

Remarks

Set this property before calling NameSetLock and while the graph is stopped.

This property is read/write.

See Also

  • Buffering in the Stream Buffer Engine
  • MSVidStreamBufferSink Object
  • MSVidStreamBufferSink.NameSetLock


MSVidStreamBufferSink.NameSetLock

This topic applies to Windows XP Service Pack 1 only.

The NameSetLock method locks the stream buffer profile.

Syntax

objSBESink.NameSetLock()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • Buffering in the Stream Buffer Engine
  • MSVidStreamBufferSink Object
  • MSVidStreamBufferSink.SinkName


MSVidStreamBufferSource Object

This topic applies to Windows XP Service Pack 1 only.

The MSVidStreamBufferSource object represents a stream buffer source object.

This object has the following CLSID:

{AD8E510D-217F-409b-8076-29C5E73B98E8}

This object inherits all the methods and properties of the IMSVidPlayback object. In addition, it exposes the following methods and properties.

Property | Description
BlockUnrated | Specifies whether to block unrated content.
RecordingAttribute | Retrieves the Stream Buffer Source filter.
SBESource | Retrieves the Stream Buffer Source filter.
Start | Retrieves the start time.
UnratedDelay | Specifies how long the object will play unrated content before blocking it.

Method | Description
CurrentRatings | Retrieves the current ratings information from the data source.
MaxRatingsLevel | Specifies the maximum ratings level the object is permitted to play.

The MSVidStreamBufferSource object fires the following events.

Event | Description
CertificateFailure | Fired when the object fails to get an encryption/decription license.
CertificateSuccess | Fired when the object succeeds in getting an encryption/decription license.
ContentBecomingStale | Fired when the stream buffer source lags behind the stream buffer sink.
EndOfMedia | Fired when the object reaches the end of the source file.
RatingsBlocked | Fired when the object blocks playback.
RatingsChanged | Fired when the content rating changes.
RatingsUnblocked | Fired when the object unblocks placyback.
StaleDataRead | Fired when the object reads from a temporary recording file that has been marked for deletion.
StaleFileDeleted | Fired when a temporary recording file is deleted.
TimeHole | Fired when playback reaches a gap in the recorded content.


MSVidStreamBufferSource.BlockUnrated

This topic applies to Windows XP Service Pack 1 only.

The BlockUnrated property specifies whether to block unrated content. If True, the Video Control will block any stream buffer content without a rating.

Syntax

objSBESource.BlockUnrated As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

Remarks

This property is write-only.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.RecordingAttribute

This topic applies to Windows XP Service Pack 1 only.

The RecordingAttribute property retrieves the Stream Buffer Source filter that this object manages.

Syntax

objSBESource.RecordingAttribute As Unknown

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the Stream Buffer Source filter, as an Unknown object.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.SBESource

This topic applies to Windows XP Service Pack 1 only.

The SBESource property retrieves the Stream Buffer Source filter that this object manages.

Syntax

objSBESource.SBESource As Unknown

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the Stream Buffer Source filter, as an Unknown object.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.Start

This topic applies to Windows XP Service Pack 1 only.

The Start property retrieves the start time.

Syntax

objSBESource.Start As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the start time, in hundredths of seconds.

Remarks

This property is read-only.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.UnratedDelay

This topic applies to Windows XP Service Pack 1 only.

The UnratedDelay property specifies how long the Video Control will play unrated content before blocking it, in milliseconds. This property is ignored unless the BlockUnrated property is set to True.

Syntax

objSBESource.UnratedDelay As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

Remarks

This property is write-only.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.CurrentRatings

This topic applies to Windows XP Service Pack 1 only.

The CurrentRatings method retrieves the current ratings information from the data source.

Syntax

objSBESource.CurrentRatings(
    EnSystem As EnTvRat_System
    EnRating As EnTvRat_GenericLevel
    BfEnAttr As Long
)

Parameters

EnSystem

Variable that receives the rating system, as an EnTvRat_System constant.

EnRating

Variable that receives the rating level, as an EnTvRat_GenericLevel constant.

BfEnAttr

Variable that receives the ratings attributes, as a bitwise combination of zero or more BfEnTvRat_GenericAttributes constants.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • MSVidStreamBufferSource Object


MSVidStreamBufferSource.MaxRatingsLevel

This topic applies to Windows XP Service Pack 1 only.

The MaxRatingsLevel method specifies the maximum ratings level the object is permitted to play.

Syntax

objSBESource.MaxRatingsLevel(
    EnSystem As EnTvRat_System
    EnRating As EnTvRat_GenericLevel
    BfEnAttr As Long
)

Parameters

EnSystem

Specifies the rating system, as an EnTvRat_System constant.

EnRating

Specifies the rating level, as an EnTvRat_GenericLevel constant.

BfEnAttr

Specifies the ratings attributes, as a bitwise combination of zero or more BfEnTvRat_GenericAttributes constants.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

No return value.

See Also

  • MSVidStreamBufferSource Object


MSVidVideoRenderer Object

This topic applies to Windows XP only.

The MSVidVideoRenderer object enables Automation clients to set properties on the Video Mixing Renderer Filter (VMR). For more complete information on the VMR, see Using the Video Mixing Renderer.

This object inherits all the methods and properties of the IMSVidDevice object. In addition, it exposes the following methods and properties.

Property | Description
AvailableSourceRect | Retrieves the size of the native video.
ClippedSourceRect | Sets or retrieves the clipping rectangle on the video source.
CustomCompositorClass | Sets or retrieves the CLSID of the VMR's current image compositor.
DecimateInput | Indicates whether the VMR will decimate the video (that is, reduce the native video size) before processing it.
FramesPerSecond | Retrieves the frame rate.
MaxVidRect | Retrieves the maximum ideal size of the video rectangle.
MinVidRect | Retrieves the minimum ideal size of the video rectangle.
MixerBitmap | Sets or retrieves the static bitmap image.
MixerBitmapOpacity | Sets or retrieves the opacity of the static bitmap image.
MixerBitmapPositionRect | Sets or retrieves the position of the static bitmap image, relative to the video window.
OverScan | Sets or retrieves the amount of clipping to perform on all sides of the video frame, in order to cut off random video noise.
SourceSize | Indicates the type of clipping to apply to the video rectangle, if any.
SuppressEffects | Sets and retrieves preferences for power management and visual effects.
UsingOverlay | Indicates whether the VMR should use the hardware overlay.

Method | Description
Capture | Captures the video frame that is currently being rendered by the VMR.
SetupMixerBitmap | Configures the VMR to display an alpha-blended bitmap on top of the video.

Event | Description
OverlayUnavailable | Called when the hardware overlay surface is unavailable.
StateChange | Called when the state of the device changes.


MSVidVideoRenderer.AvailableSourceRect

This topic applies to Windows XP only.

The AvailableSourceRect property retrieves the size of the native video.

Syntax

objMSVidVideoRenderer.AvailableSourceRect As MSVidRect

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an IMSVidRect object.

Remarks

This property is read-only.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.Capture

This topic applies to Windows XP only.

The Capture method captures the video frame that is currently being rendered by the Video Mixing Renderer (VMR).

Syntax

objMSVidVideoRenderer.Capture() As IPictureDisp

Parameters

This method has no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an IPictureDisp object.

Remarks

For information about the IPictureDisp object, see the Microsoft Platform SDK documentation.

Example Code

Dim objVid As MSVidVideoRenderer
Set objVid = VideoControl1.VideoRendererActive
If (Not objVid Is Nothing) Then
    Picture1.Picture = objVid.Capture
End If

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.ClippedSourceRect

This topic applies to Windows XP only.

The ClippedSourceRect property sets or retrieves the clipping rectangle on the video source.

Syntax

objMSVidVideoRenderer.ClippedSourceRect As MSVidRect

Parameters

This property takes no parameters.

Return Values

Returns an IMSVidRect object.

Remarks

If the MSVidVideoRenderer.SourceSize property is sslClipByClipRect, the VMR clips the video image to the video source rectangle, and stretches the clipped image to fill the Video Control's video window. Otherwise, this property has no effect.

This property is read/write.

Example Code

The following example toggles between showing the entire video and showing the video zoomed in by a factor of two:

Private bClipped As Boolean

Private Sub ClipFrame_Click()
    Dim objVid As MSVidVideoRenderer
    Set objVid = VideoControl1.VideoRendererActive
    If (Not objVid Is Nothing) Then
        Dim objRect As IMSVidRect
        Set objRect = objVid.AvailableSourceRect

        If (Not bClipped) Then  ' Zoom in.
            Dim h As Long, w As Long
            h = objRect.height
            w = objRect.width
            objRect.Top = h / 4
            objRect.Left = w / 4
            objRect.height = h / 2
            objRect.width = w / 2
        End If

        ' Otherwise, show the entire video.
        objVid.ClippedSourceRect = objRect
        objVid.SourceSize = sslClipByClipRect
        ' Toggle the state.
        bClipped = Not bClipped
    End If
End Sub

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.CustomCompositorClass

This topic applies to Windows XP only.

The CustomCompositorClass property sets or retrieves the class identifier (CLSID) of the Video Mixing Renderer's current image compositor.

Syntax

objMSVidVideoRenderer.CustomCompositorClass As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a string that contains the CLSID.

Remarks

Applications can provide their own compositors to perform custom image compositing. For more information, see Using the Video Mixing Renderer.

This property is read/write.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.DecimateInput

This topic applies to Windows XP only.

The DecimateInput property indicates whether the Video Mixing Renderer (VMR) will decimate the video (that is, reduce the native video size) before processing it.

This property is currently not supported.

Syntax

objMSVidVideoRenderer.DecimateInput As Boolean

Parameters

This property has no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the VMR will decimate the video, or False otherwise.

Remarks

This property should be set to True when the native video stream is HDTV but the system monitor is set to a lower resolution. This prevents the VMR from doing unnecessary work by processing the video at high resolution and then shrinking it.

This property is read/write.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.FramesPerSecond

This topic applies to Windows XP only.

The FramesPerSecond property retrieves the current frame rate.

Syntax

objMSVidVideoRenderer.FramesPerSecond As Long

Parameters

This property has no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the frame rate, in frames per second.

Remarks

This property is read-only.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.MaxVidRect

This topic applies to Windows XP only.

The MaxVidRect property retrieves the maximum ideal size for the video rectangle.

Syntax

objMSVidVideoRenderer.MaxVidRect As MSVidRect

Parameters

This property has no parameters

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns an IMSVidRect object.

Remarks

The maximum ideal image size is the maximum video size that can be displayed without significantly degrading performance or image quality.

This property is read-only.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.MinVidRect

This topic applies to Windows XP only.

The MinVidRect property retrieves the minimum ideal size of the video rectangle.

Syntax

objMSVidVideoRenderer.MinVidRect As MSVidRect

Parameters

This property has no parameters

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns an IMSVidRect object.

Remarks

The minimum ideal image size is the minimum video size that can be displayed without significantly degrading performance or image quality.

This property is read-only.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.MixerBitmap

This topic applies to Windows XP only.

The MixerBitmap property sets or retrieves the static bitmap image.

Syntax

objMSVidVideoRenderer.MixerBitmap As IPictureDisp

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an IPictureDisp object.

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image. For information about the IPictureDisp interface, see the Platform SDK documentation.

This property is read/write.

See Also

  • MSVidVideoRenderer Object
  • MSVidVideoRenderer.MixerBitmapOpacity
  • MSVidVideoRenderer.MixerBitmapPositionRect
  • Mixing an Image Onto the Video Window in Visual Basic


MSVidVideoRenderer.MixerBitmapOpacity

This topic applies to Windows XP only.

The MixerBitmapOpacity property sets or retrieves the opacity of the static bitmap image.

Syntax

objMSVidVideoRenderer.MixerBitmapOpacity As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the opacity, expressed as an number from 0 (transparent) to 100 (opaque).

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image, using the opacity specified by this property.

This property is read/write.

See Also

  • MSVidVideoRenderer Object
  • MSVidVideoRenderer.MixerBitmap
  • MSVidVideoRenderer.MixerBitmapPositionRect
  • Mixing an Image Onto the Video Window in Visual Basic


MSVidVideoRenderer.MixerBitmapPositionRect

This topic applies to Windows XP only.

The MixerBitmapPositionRect property sets or retrieves the position of the static bitmap image, relative to the video window.

Syntax

objMSVidVideoRenderer.MixerBitmapPositionRect As MSVidRect

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an IMSVidRect object.

Remarks

If the static bitmap image is set, the VMR alpha-blends the bitmap onto the video image, using the position rectangle specified by this property.

This property is read/write.

See Also

  • MSVidVideoRenderer Object
  • MSVidVideoRenderer.MixerBitmap
  • MSVidVideoRenderer.MixerBitmapOpacity
  • Mixing an Image Onto the Video Window in Visual Basic


MSVidVideoRenderer.OverScan

This topic applies to Windows XP only.

The OverScan property sets or retrieves the amount of clipping to perform on all sides of the video frame, in order to cut off random video noise.

Syntax

objMSVidVideoRenderer.OverScan As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the amount to clip, in hundredths of a percent. For example, 175 indicates 1.75%.

Remarks

If the MSVidVideoRenderer.SourceSize property is sslClipByOverScan, the VMR clips the video image by the specified amount. Otherwise, this property has no effect.

This property is read/write.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.SourceSize

This topic applies to Windows XP only.

The SourceSize property indicates the type of clipping to apply to the video rectangle, if any.

Syntax

objMSVidVideoRenderer.SourceSize As SourceSizeList

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a SourceSizeList constant.

Remarks

This property is read/write.

See Also

  • MSVidVideoRenderer Object
  • MSVidVideoRenderer.ClippedSourceRect
  • MSVidVideoRenderer.OverScan


MSVidVideoRenderer.SuppressEffects

This topic applies to Windows XP Service Pack 1 only.

The SuppressEffects property sets and retrieves preferences for power management and visual effects..

Syntax

objMSVidVideoRenderer.SuppressEffects As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

If this property is True, the Video Control does the following

  • Disables font smoothing and the system-wide drop shadow effect. (Only when the Video Control is using hardware overlay.) This is useful if the application draws onto the overlay.
  • Disables the screen saver, and turns off power management for the display. This is useful to prevent the operating system from interrupting playback while the user is watching a program.

The Video Control restores the original system settings after it stops.

If this property is False, the Video Control uses the existing system settings.

Remarks

This property is read/write.

See Also

  • MSVidVideoRenderer Object
  • MSVidVideoRenderer.UsingOverlay


MSVidVideoRenderer.UsingOverlay

This topic applies to Windows XP only.

The UsingOverlay property indicates whether the Video Mixing Renderer (VMR) is using the hardware overlay.

Syntax

objMSVidVideoRenderer.UsingOverLay As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns True if the VMR is using the hardware overlay, or False otherwise.

Remarks

When the hardware overlay is not available, the VMR attempts to blit directly to video memory.

This property is read/write.

See Also

  • MSVidVideoRenderer Object


MSVidVideoRenderer.SetupMixerBitmap

This topic applies to Windows XP only.

The SetupMixerBitmap method configures the Video Mixing Renderer (VMR) to display an alpha-blended static bitmap on top of the video.

Syntax

ObjMSVidVideoRenderer.SetupMixerBitmap(
  MixerPictureDisp IpictureDisp,
  Opacity As Long,
  rDest As MSVidRect
)

Parameters

MixerPictureDisp

Specifies the bitmap as an IPictureDisp object.

Opacity

Specifies the opacity of the bitmap, as a number from 0 (transparent) to 100 (opaque).

Rectangle

Specifies the bitmap's rectangle as an IMSVidRect object relative to the video window.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

The VMR alpha-blends the static bitmap image onto the video image. For information about the IPictureDisp interface, see the Platform SDK documentation.

This method sets the MSVidVideoRenderer.MixerBitmap, MSVidVideoRenderer.MixerBitmapOpacity, and MSVidVideoRenderer.MixerBitmapPositionRect properties.

See Also

  • MSVidVideoRenderer Object
  • Mixing an Image Onto the Video Window in Visual Basic


MSVidVideoRendererDevices Object

This topic applies to Windows XP only.

The MSVidVideoRendererDevices object represents a collection of video renderers. Each item in the collection is an MSVidVideoRenderer object.

This object exposes the following methods and properties.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the specified item from the collection.

Method | Description
Add | Adds an item to the collection.
Remove | Removes an item from the collection.


MSVidVideoRendererDevices.Count

This topic applies to Windows XP only.

The Count property retrieves the number of items in the collection.

Syntax

objMSVidVideoRendererDevices.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns the number of items.

Remarks

This property is read-only.

See Also

  • MSVidVideoRendererDevices Object


MSVidVideoRendererDevices.Item

This topic applies to Windows XP only.

The Item property retrieves the specified item from the collection.

Syntax

objMSVidVideoRendererDevices.Item(
    v As Object
) As MSVidVideoRenderer

Parameters

v

Specifies the index of the item to retrieve. The valid range is from 0 to MSVidVideoRendererDevices.Count - 1.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns an MSVidVideoRenderer object.

Remarks

This property is the default member of the MSVidVideoRendererDevices object, so you do not need to specify the property name when you retrieve it. For example, the following are equivalent:

Set objVideoRenderer = colVideoRenderers.Item(1)
Set objVideoRenderer = colVideoRenderers(1)

This property is read-only.

See Also

  • MSVidVideoRendererDevices Object


MSVidVideoRendererDevices.Add

This topic applies to Windows XP only.

Adds the specified item to the collection.

Syntax

ObjMSVidVideoRendererDevices.Add(
    pDB As MSVidVideoRenderer
)

Parameters

pDB

Specifies the MSVidVideoRenderer device to add.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidVideoRendererDevices Object


MSVidVideoRendererDevices.Remove

This topic applies to Windows XP only.

The Remove method removes an item from the collection.

Syntax

ObjMSVidVideoRendererDevices.Remove(v)

Parameters

varDevice

Specifies the index of the item to remove. The valid range is from 0 to MSVidVideoRendererDevices.Count - 1.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

This method does not return a value.

Remarks

This method fails if the collection is read-only.

See Also

  • MSVidVideoRendererDevices Object


MSVidWebDVD Object

This topic applies to Windows XP Service Pack 1 only.

The methods, properties, and events of the MSVidWebDVD object enable an application to control all aspects of DVD-Video navigation and playback, and to retrieve information from the disc. The MSVidWebDVD object does not perform the actual graph building or running; that is handled by the MSVidCtl object, which uses the DVD Navigator filter to perform the actual DVD control. Use MSVidCtl to control larger actions, such as stop, run, and pause, but use the MSVidWebDVD object to control more specific details such as the play rate, displaying menus or activating buttons. When methods overlap, check the documentation, or try using the MSVidCtl method first.

Note Neither Windows XP nor the DirectX SDK offer an MPEG-2 decoder for writing DVD applications. Many DVD hardware providers offer hardware or software decoding options, and many DVDs come packaged with a DVD decoder.

The MSVidWebDVD methods and properties act on the current playback state. To save and retrieve persistent application-specific information in the registry, such as default language or default parental level, use the corresponding methods in the MSVidWebDVDAdm object.

The following tables list the MSVidWebDVD properties and methods, grouped by functionality. Certain methods are not implemented or should be called from the MSVidCtl, as indicated. In addition, the MSVidWebDVD object inherits all of the properties and methods of the IMSVidPlayback object.

Controlling Playback

Method or Property | Description
Eject | Ejects or inserts a disc from or into the drive.
PlayAtTimeInTitle | Starts playback at the specified time within the specified title.
PlayAtTime | Starts playback in the current title at the specified time.
PlayChapterInTitle | Plays the specified chapter in the specified title.
PlayChaptersAutoStop | Starts playback at the specified chapter in the specified title, for the number of chapters specified.
PlayChapter | Starts playback from the specified chapter in the current title.
PlayNextChapter | Starts playback from the next chapter in the current title.
PlayPeriodInTitleAutoStop | Starts playback at the specified time in the specified title until the specified stop time.
PlayPrevChapter | Starts playback from the previous chapter in the current title.
PlayTitle | Starts playback at the beginning of the specified title.
ReplayChapter | Starts playback at the beginning of the current chapter.
Resume | Resumes playback after a menu has been displayed.
StillOff | Resumes playback, canceling still mode.

Menus and Buttons

Method or Property | Description
ActivateAtPosition | Activates the menu button at the specified position.
ActivateButton | Activates the selected menu button.
ButtonsAvailable | Retrieves the total number of buttons on the current menu.
CurrentButton | Retrieves the number of the selected button.
DefaultMenuLanguage | Retrieves the default menu language from the disc.
ButtonAtPosition | Retrieves the number of the button at the specified coordinates without selecting or activating it.
ButtonRect | Not implemented.
ReturnFromSubmenu | Returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.
SelectAndActivateButton | Selects and activates the specified button.
SelectAtPosition | Selects the menu button at the specified position.
SelectLeftButton | Selects the left directional button from the displayed menu.
SelectLowerButton | Selects the lower directional button from the displayed menu.
SelectRightButton | Selects the right directional button from the displayed menu.
SelectUpperButton | Selects the upper directional button from the displayed menu.
ShowMenu | Displays the specified menu on the screen.

Audio Stream

Method or Property | Description
AudioLanguage | Retrieves a human-readable string indicating the language of the specified audio stream.
AudioStreamsAvailable | Retrieves the number of audio streams available in the current title.
CurrentAudioStream | Sets or retrieves the number of the enabled audio stream.
DefaultAudioLanguage | Retrieves a number representing the default audio language set in SelectDefaultAudioLanguage.
DefaultAudioLanguageExt | Retrieves a number representing the default audio language extension set in SelectDefaultAudioLanguage.
IsAudioStreamEnabled | Retrieves a value indicating whether the specified audio stream is enabled in the current title.
SelectDefaultAudioLanguage | Sets the current default audio language in the DVD Navigator filter.

Subpicture Stream

Method or Property | Description
CurrentSubpictureStream | Retrieves the selected subpicture stream.
DefaultSubpictureLanguage | Retrieves the default subpicture language as a human-readable string set in SelectDefaultSubpictureLanguage.
DefaultSubpictureLanguageExt | Retrieves the default subpicture language extension set in SelectDefaultSubpictureLanguage.
SubpictureLanguage | Retrieves the language for the specified subpicture stream as a human-readable string.
IsSubpictureStreamEnabled | Retrieves a value indicating whether the specified subpicture stream is enabled in the current title.
PreferredSubpictureStream | Sets or retrieves the user's preferred subpicture stream for the current viewing session.
SelectDefaultSubpictureLanguage | Sets the current default subpicture language.
SubpictureOn | Sets or retrieves the current subpicture state (on or off).
SubpictureStreamsAvailable | Retrieves the number of subpicture streams available in the current title.

Angle Blocks

Method or Property | Description
AnglesAvailable | Retrieves the number of angles available.
CurrentAngle | Sets or retrieves the current angle in an angle block.

Karaoke Audio

Method or Property | Description
KaraokeChannelAssignment | Retrieves a value that indicates how the karaoke channels are assigned to different speakers.
KaraokeChannelContent | Retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.
KaraokeAudioPresentationMode | Sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.

Text Strings

Method or Property | Description
DVDTextLanguageLCID | Retrieves the locale identifier (LCID) for the specified text language block.
DVDTextNumberOfLanguages | Retrieves the number of text languages available in the current DVD directory.
DVDTextNumberOfStrings | Retrieves the number of text strings available for the specified language.
DVDTextString | Retrieves the specified text string from the disc.
DVDTextStringType | Retrieves a value that indicates the type of information contained in the specified DVD text string.
LanguageFromLCID | Retrieves a human-readable string when given a primary language identifier (ID).

Parental Management

Method or Property | Description
AcceptParentalLevelChange | Instructs the DVD Navigator filter to accept or reject the new temporary parental management level.
PlayerParentalCountry | Retrieves the current country/region as set in the DVD Navigator filter.
PlayerParentalLevel | Retrieves the parental management level set in the DVD Navigator filter.
TitleParentalLevels | Retrieves the parental management level for the specified title.
NotifyParentalLevelChange | Enables or disables the event handling for temporary parental management level commands.
SelectParentalCountry | Sets the specified parental country/region for subsequent playback.
SelectParentalLevel | Sets the specified parental level for subsequent playback.

Disc and Playback Information

Method or Property | Description
CurrentChapter | Retrieves the number of the chapter currently playing.
CurrentDiscSide | Retrieves the current side of the DVD.
CurrentDomain | Retrieves the DVD domain that the DVD Navigator filter is in.
CurrentTime | Retrieves the current playback time.
CurrentTitle | Retrieves the number of the title currently playing.
CurrentVolume | Retrieves the volume number for the current root directory.
DVDDirectory | Retrieves or sets the root directory of the current DVD volume.
DVDTimeCode2bstr | Retrieves a string indicating the current time on the disc.
DVDUniqueID | Retrieves a system-generated ID that uniquely identifies the current DVD.
NumberOfChapters | Retrieves the number of chapters in the specified title.
TitlesAvailable | Retrieves the number of titles available on the DVD.
TotalTitleTime | Retrieves the total playback time for the current title.
UOPValid | Retrieves a value that indicates whether the specified user operation is currently valid.
VolumesAvailable | Retrieves a value specifying the number of volumes in the disc set.

Object Initialization and Control

Settings in the MSVidWebDVD typically only affect the current session. Persistent default settings are saved in the registry using the MSVidWebDVDAdm.

Method or Property | Description
DVDAdm | Provides access to the MSVidWebDVDAdm object containing methods and properties for saving application and user information.
RegionChange | Displays a system dialog box that enables the user to change the region associated with the DVD drive.
RestorePreferredSettings | Restores the registry's DVD default language and level settings.

Bookmarks

Bookmarks save the current position and setting information for later viewing. Only one bookmark may be saved at a time.

Method or Property | Description
DeleteBookmark | Deletes the current bookmark.
RestoreBookmark | Moves the DVD Navigator filter to the point on the DVD specified in the current bookmark, with all audio, video and subpicture settings restored.
SaveBookmark | Saves the current disc position and state of the DVD Navigator filter to disc so that the user can return to the same place later.

GPRMs and SPRMs

Method or Property | Description
GPRM | Retrieves or sets the specified general parameter register.
SPRM | Retrieves the specified system parameter register.

See Also

  • DVD Applications in Visual Basic (Video Control)


MSVidWebDVD.AnglesAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The AnglesAvailable property retrieves the number of angles currently available.

Syntax

VidWebDVD.AnglesAvailable as Long

Parameters

This property takes no parameters.

Return Values

Returns a long value from 1 through 9 representing the number of angles currently available. If the return value is 1, there is no angle block at the current location.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
VFW_E_DVD_OPERATION_INHIBITED | This user operation is not allowed by the DVD content at this time.
E_UNEXPECTED | Unspecified error.

Remarks

This property is read-only.

Example

' Returning the property.
lAngles = VidWebDVD.AnglesAvailable

See Also

  • Angle Blocks
  • MSVidWebDVD Object
  • TitlesAvailable


MSVidWebDVD.AudioLanguage Property

This topic applies to Windows XP Service Pack 1 only.

The AudioLanguage property retrieves a string indicating the language of the specified audio stream.

Syntax

VidWebDVD.AudioLanguage(
  lStream As Long,
  fFormat As Boolean
)as String

Parameters

lStream

Long indicating the stream, from 0 through 7.

fFormat

Flag, True indicating sound format details included in return value. Currently not implemented.

Return Values

Returns a human-readable string identifying the language of the audio stream in the current title.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_NO_IDVD2_PRESENT | Unspecified internal error.
E_NO_DVD_VOLUME | No DVD available.
E_REGION_CHANGE_FAIL | The DVD has the wrong region code for this machine.

Remarks

This property is read-only. This method is zero-based, unlike AudioStreamsAvailable, so be careful to subtract one from the return value of AudioStreamsAvailable when iterating through all streams.

Example

' Returning the property.
bstrAudioLang = VidWebDVD.AudioLanguage(lStream, fFormat)

See Also

  • Audio Streams: Controlling Spoken Language
  • MSVidWebDVD Object


MSVidWebDVD.AudioStreamsAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The AudioStreamsAvailable property retrieves the number of audio streams available in the current title.

Syntax

VidWebDVD.AudioStreamsAvailable as Long

Parameters

This property takes no parameters.

Return Values

Returns an integer value from 1 through 8 representing the number of audio streams available in the current title.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_NO_IDVD2_PRESENT | Unspecified internal error.
E_NO_DVD_VOLUME | No DVD available.
E_REGION_CHANGE_FAIL | The DVD has the wrong region code for this machine.

Remarks

This property is read-only with no default value. The primary use of multiple audio streams is to provide movie soundtracks in more than one language. Typically, not every title on a disc has all audio streams enabled. For example, the feature movie might have soundtracks in three different languages, but the trailers might have only an English soundtrack. Before a user can select a stream, the application must determine which streams are available within the current title. Note that particular streams are identified by an index from 0 through 7.

Discs generally present a menu showing the available soundtracks, which allows the user to select the audio stream to enable.

Example

' Returning the property
lStreamsAvail = VidWebDVD.AudioStreamsAvailable

See Also

  • Audio Streams: Controlling Spoken Language
  • MSVidWebDVD Object


MSVidWebDVD.ButtonAtPosition Property

This topic applies to Windows XP Service Pack 1 only.

The ButtonAtPosition property retrieves the number of the button at the specified coordinates without selecting or activating it.

Syntax

VidWebDVD.ButtonAtPosition(
  xPos As Long,
  yPos As Long
) as Long

Parameters

xPos

Specifies the x-coordinate of the mouse pointer as an Integer.

yPos

Specifies the y-coordinate of the mouse pointer as an Integer.

Return Values

Returns a Long value specifying the button, if any, at the specified position.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_NO_IDVD2_PRESENT | Unspecified internal error.
E_NO_DVD_VOLUME | No DVD available.
E_REGION_CHANGE_FAIL | The DVD has the wrong region code for this machine.

Remarks

This method returns 0 if no button is present at the given coordinates. The buttons checked by this method are the DVD's onscreen buttons, not the surrounding HTML page or form buttons.

Example

' Returning the property.
lButton = VidWebDVD.ButtonAtPosition(xPos, yPos)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object


MSVidWebDVD.ButtonRect Property

This topic applies to Windows XP Service Pack 1 only.

The ButtonRect property is not implemented.

See Also

  • MSVidWebDVD Object


MSVidWebDVD.ButtonsAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The ButtonsAvailable property retrieves the total number of buttons on the current menu.

Syntax

VidWebDVD.ButtonsAvailable As Long

Parameters

This property takes no parameters.

Return Values

When getting the value, this property returns a Long representing the number of buttons.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_NO_IDVD2_PRESENT | Unspecified internal error.
E_NO_DVD_VOLUME | No DVD available.
E_REGION_CHANGE_FAIL | The DVD has the wrong region code for this machine.

Remarks

This property is read-only. The buttons checked by this method are the DVD's onscreen buttons, not the surrounding HTML page or form buttons.

Example

' Returning the property.
Long = VidWebDVD.ButtonsAvailable

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object


MSVidWebDVD.CurrentAngle Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentAngle property sets or retrieves the current angle in an angle block.

Syntax

VidWebDVD.CurrentAngle As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the angle. Must be a value from 1 through 9.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
VFW_E_DVD_OPERATION_INHIBITED | This user operation is not allowed by the DVD content at this time.
E_UNEXPECTED | Unspecified error.

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Angle_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

Remarks

This property will be initialized to 1 before the First Play domain.

Example

' Setting the property.
VidWebDVD.CurrentAngle = lAngle
' Returning the property.
lAngle = VidWebDVD.CurrentAngle

See Also

  • Angle Blocks
  • CurrentTitle
  • MSVidWebDVD Object


MSVidWebDVD.CurrentAudioStream Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentAudioStream property sets and retrieves the number of the enabled audio stream.

Syntax

VidWebDVD.CurrentAudioStream As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value from 0 through 7 indicating the current audio stream.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
VFW_E_DVD_OPERATION_INHIBITED | This user operation is not allowed by the DVD content at this time.
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_STREAM_DISABLED | The specified stream is disabled.

Remarks

This property is read/write and defaults to 0 (zero). Before attempting to set a new audio stream, call IsAudioStreamEnabled to verify that the stream is available.

Example

' Setting the property.
VidWebDVD.CurrentAudioStream = Long
' Returning the property.
Long = VidWebDVD.CurrentAudioStream

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Audio_Stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • Audio Streams: Controlling Spoken Language
  • MSVidWebDVD Object


MSVidWebDVD.CurrentButton Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentButton property retrieves the number of the selected menu button.

Syntax

VidWebDVD.CurrentButton As Long

Parameters

This property takes no parameters.

Return Values

When getting the value, this property returns a Long.

Remarks

This property is read-only and defaults to 1 when buttons are available. The buttons checked by this method are the DVD's on-screen buttons, not the surrounding HTML page or form buttons.

Example

' Returning the property.
lButton = VidWebDVD.CurrentButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object


MSVidWebDVD.CurrentChapter Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentChapter property retrieves the number of the chapter currently playing.

Syntax

VidWebDVD.CurrentChapter As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the current chapter in the current title.

Remarks

This property is read-only. Checking this property outside a valid title will cause an error.

Example

' Returning the property.
lChapter = VidWebDVD.CurrentChapter

See Also

  • MSVidWebDVD Object


MSVidWebDVD.CurrentDiscSide Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentDiscSide property retrieves the current side of the disc.

Syntax

VidWebDVD.CurrentDiscSide As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the current side, where side A = 1 and side B = 2.

Remarks

This property is read-only with no default value.

Example

' Returning the property.
lCurrSide = VidWebDVD.CurrentDiscSide

See Also

  • MSVidWebDVD Object


MSVidWebDVD.CurrentDomain Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentDomain property retrieves the DVD domain of the MSVidWebDVD object.

Syntax

VidWebDVD.CurrentDomain As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value from 1 to 5 representing the current domain:

Value | Domain
1 | First play
2 | Video Manager Menu
3 | Video Title Set Menu
4 | Title
5 | Stop

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error

Remarks

This property is read-only. Call this method to ensure that you are in a valid domain for the method you are about to call. For example, before calling PlayTitle, check the CurrentDomain property to make sure that you are not in the Stop or First Play domain.

Example

' Returning the property.
lCurrDomain = VidWebDVD.CurrentDomain

See Also

  • MSVidWebDVD Object


MSVidWebDVD.CurrentSubpictureStream Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentSubpictureStream property sets or retrieves the current subpicture stream.

Syntax

VidWebDVD.CurrentSubpictureStream As Long

Parameters

This property takes no parameters.

Return Values

This property returns a Long indicating the current subpicture stream number. Possible values include the following.

Value | Description
0-31 | Subpicture stream
63 | Muted low-bitrate stream

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
CO_E_NOTINITIALIZED | The graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
VFW_E_DVD_OPERATION_INHIBITED | This user operation is prevented by UOP command.
E_INVALIDARG | Invalid stream number entered.

Remarks

This property is read/write and defaults to 0 (zero). Before setting a new subpicture stream, call IsSubpictureStreamEnabled to verify that the stream is available.

Setting this property causes the SubpictureOn property to toggle to True.

Example

' Setting the property.
VidWebDVD.CurrentSubpictureStream = lNewStream
' Returning the property.
lCurrStream = VidWebDVD.CurrentSubpictureStream

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Sub-picture_stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.CurrentTime Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentTime property retrieves the current playback time.

Syntax

VidWebDVD.CurrentTime As String

Parameters

This property takes no parameters.

Return Values

This property returns a String representing the current playback time in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only. The DVD player must be in a title for this property to be checked.

Example

' Returning the property.
strCurrTime = VidWebDVD.CurrentTime

See Also

  • CurrentTitle
  • MSVidWebDVD Object


MSVidWebDVD.CurrentTitle Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentTitle property retrieves the number of the title currently playing.

Syntax

VidWebDVD.CurrentTitle As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value from 1 through 99 indicating the number of the title currently playing.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only with no default value. Be sure you are in a valid domain before calling this method.

Example

' Returning the property.
lCurrTitle = VidWebDVD.CurrentTitle

See Also

  • CurrentAngle
  • CurrentTime
  • MSVidWebDVD Object


MSVidWebDVD.CurrentVolume Property

This topic applies to Windows XP Service Pack 1 only.

The CurrentVolume property retrieves the volume number for the current root directory.

Syntax

VidWebDVD.CurrentVolume As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the current DVD volume. If a disc is part of a multi-volume set, then the value should be greater than zero.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only with no default value.

Example

' Returning the property.
lCurrVolume = VidWebDVD.CurrentVolume

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DefaultAudioLanguage Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultAudioLanguage property retrieves the default audio language.

Syntax

VidWebDVD.DefaultAudioLanguage As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only. To set this property, use the VidWebDVDAdm object's DefaultAudioLCID property. The default value is -1.

Example

' Returning the property.
lLanguage = VidWebDVD.DefaultAudioLanguage

See Also

  • Audio Streams: Controlling Spoken Language
  • DefaultAudioLanguageExt
  • MSVidWebDVD Object


MSVidWebDVD.DefaultAudioLanguageExt Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultAudioLanguageExt property retrieves the default audio language extension.

Syntax

VidWebDVD.DefaultAudioLanguageExt As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value indicating the default audio language extension:

Value | Description
0 | Not specified
1 | Captions
2 | Visually impaired
3 | Director comments 1
4 | Director comments 2

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only. Currently, few discs specify this property, instead returning 0 (not specified).

Example

' Returning the property.
lLanguageExt = VidWebDVD.DefaultAudioLanguageExt

See Also

  • Audio Streams: Controlling Spoken Language
  • DefaultAudioLanguage
  • MSVidWebDVD Object


MSVidWebDVD.DefaultMenuLanguage Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultMenuLanguage property specifies and retrieves the default menu language.

Syntax

VidWebDVD.DefaultMenuLanguage As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long LCID value containing the primary language ID for the default menu language. The default value is -1. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

DefaultMenuLanguage is read/write with no default value. To set this property, use the MSVidWebDVDAdm object's DefaultMenuLCID property.

Example

' Setting the property.
VidWebDVD.DefaultMenuLanguage = lDefMenuLang
' Returning the property
lDefMenuLang = VidWebDVD.DefaultMenuLanguage

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DefaultSubpictureLanguage Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultSubpictureLanguage property retrieves the default subpicture language.

Syntax

VidWebDVD.DefaultSubpictureLanguage As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long LCID value containing the primary language ID for the default subpicture language. The default value is -1. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only with no default. To set this property, use the MSVidWebDVDAdm object's DefaultSubpictureLCID property.

Example

' Returning the property.
lDefSubLang = VidWebDVD.DefaultSubpictureLanguage

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • DefaultSubpictureLanguageExt
  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.DefaultSubpictureLanguageExt Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultSubpictureLanguageExt property retrieves the default DVD subpicture language extension.

Syntax

VidWebDVD.DefaultSubpictureLanguageExt As DVDSPExt

Parameters

This property takes no parameters.

Return Values

This property returns a DVDSPExt enumeration object indicating the default DVD subpicture language extension. For more on the return values and what they mean, see DVDSPExt Constants.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only, with no default value. Currently, few discs specify this property, instead returning 0 (not specified).

Example

' Returning the property.
dspDefLangExt = VidWebDVD.DefaultSubpictureLanguageExt

See Also

  • DefaultSubpictureLanguage
  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.DVDAdm Property

This topic applies to Windows XP Service Pack 1 only.

The DVDAdm property provides access to the MSVidWebDVDAdm object that contains methods and properties for saving application and user information.

Syntax

VidWebDVD.DVDAdm As IDispatch

Parameters

This property takes no parameters.

Return Values

This property allows the user to set and retrieve values of the MSVidWebDVDAdm object without creating a separate object. If one wishes to create a separate MSVidWebDVDAdm object, use the return value as shown:

Dim oVidWebAdm As MSVidWebDVDAdm
Set oVidWebAdm = oVidWebDVD.DVDAdm

Remarks

This property is read-only in the sense that one cannot set the base property. However, one can set or retrieve appropriate methods and properties accessed through this property.

Example

' Returning the property.
idAdm = VidWebDVD.DVDAdm
' Setting a property through this property.
VidWebDVD.DVDAdm.ChangePassword("","Secret","Supersecret")

See Also

  • MSVidWebDVD Object
  • MSVidWebDVDAdm Object


MSVidWebDVD.DVDDirectory Property

This topic applies to Windows XP Service Pack 1 only.

The DVDDirectory property sets and retrieves the current directory of the current DVD volume.

Syntax

VidWebDVD.DVDDirectory As String

Parameters

This property takes no parameters.

Return Values

Returns a String value indicating the path to the DVD root directory.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_INVALIDARG | The name of the directory is too long.

Remarks

This property is read/write with no default value. Use this method to set the root path when there is more than one DVD drive on a system. When there is only one drive on the system and its drive letter is higher than "C", the MSVidWebDVD object finds it automatically. For a standard DVD-Video disc, the root path should include the ts_video directory:

Example

MSVidWebDVD.DVDDirectory = "e:\\video_ts"

Some DVD volumes may have their video in a directory named something other than "video_ts." The general idea is that an additional "DVD volume" (the set of .IFO. VOB, and .BUP files that would normally be stored in the VIDEO_TS directory) can be placed in a subdirectory on the disc. By changing the root to point to this directory, MSVidWebDVD will operate on this separate DVD volume. A new set of menus, titles, and so on, will be available, independent of the titles in the VIDEO_TS root, which will no longer be accessible. Such directories are called "hidden directories." The following example shows how to set a hidden directory as the root, where "hidden" is a placeholder for whatever name the disc authors have given to the directory.

Example

MSVidWebDVD.DVDDirectory = "d:\\webdvd\\hidden"

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DVDTextLanguageLCID Property

This topic applies to Windows XP Service Pack 1 only.

The DVDTextLanguageLCID property retrieves the locale identifier (LCID) for the specified text language block.

Syntax

VidWebDVD.DVDTextLanguageLCID(
  lLangIndex As Long
) As Long

Parameters

lLangIndex

Long specifying the text language block on the disc.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_INVALIDARG | The index number passed in was invalid.

Return Values

Returns an LCID value that contains information specifying the language the strings are written in. See Working with LCIDs for information on extracting the primary language code from an LCID.

Remarks

Supplemental text strings are stored in contiguous blocks on the disc. Each language has one block of strings. An application specifies these blocks by an index, which must be less than the value returned by DVDTextNumberOfLanguages.

Example

' Returning the property.
Long = VidWebDVD.DVDTextLanguageLCID(lLangIndex)

See Also

  • LanguageFromLCID
  • MSVidWebDVD Object
  • Working with DVD Text Strings


MSVidWebDVD.DVDTextNumberOfLanguages Property

This topic applies to Windows XP Service Pack 1 only.

The DVDTextNumberOfLanguages property retrieves the number of text languages available on the list.

Syntax

VidWebDVD.DVDTextNumberOfLanguages As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Return Values

Returns a Long value indicating the number of text languages on the disc.

Remarks

This property is read-only.

Example

' Returning the property.
lNumLangs = VidWebDVD.DVDTextNumberOfLanguages

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DVDTextNumberOfStrings Property

This topic applies to Windows XP Service Pack 1 only.

The DVDTextNumberOfStrings property retrieves the number of text strings available for the specified language.

Syntax

VidWebDVD.DVDTextNumberOfStrings(
  lLangIndex As Long
) As Long

Parameters

lLangIndex

Long containing the language index. The value must range from zero through one less than the value returned by DVDTextNumberOfLanguages.

Return Values

When getting the value, this property returns a Long.

Value | Description
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

This property is read-only.

Example

' Returning the property.
lNumStrings = VidWebDVD.DVDTextNumberOfStrings(lLangIndex)

See Also

  • MSVidWebDVD Object
  • Text Strings


MSVidWebDVD.DVDTextString Property

This topic applies to Windows XP Service Pack 1 only.

The DVDTextString property retrieves a specified text string.

Syntax

VidWebDVD.DVDTextString(
  lLangIndex As Long,
  lStringIndex As Long
) As String

Parameters

lLangIndex

Long specifying the language index number.

lStringIndex

Long specifying the string index number.

Return Values

This property returns a String.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
VFW_E_DVD_OPERATION_INHIBITED | Operation prevented by UOP command.

Remarks

This property is read-only.

Example

' Returning the property.
String = VidWebDVD.DVDTextString(lLangIndex, lStringIndex)

See Also

  • DVDTextStringType
  • MSVidWebDVD Object
  • Text Strings
  • Working with DVD Text Strings


MSVidWebDVD.DVDTextStringType Property

This topic applies to Windows XP Service Pack 1 only.

The DVDTextStringType property retrieves a value that indicates the type of information contained in the specified DVD text string.

Syntax

VidWebDVD.DVDTextStringType(
  lLangIndex As Long,
  lStringIndex As Long
) As DVDTextStringType

Parameters

lLangIndex

Long specifying the language index.

lStringIndex

Long specifying the string index number.

Return Values

This property returns a DVDTextStringType that indicates the type of information contained in the specified DVD text string.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
VFW_E_DVD_OPERATION_INHIBITED | Operation prevented by UOP command.

Remarks

This property is read-only.

Example

' Returning the property.
dvdtsStringType = VidWebDVD.DVDTextStringType(lLangIndex, lStringIndex)

See Also

  • DVDTextString
  • MSVidWebDVD Object
  • Text Strings


MSVidWebDVD.DVDUniqueID Property

This topic applies to Windows XP Service Pack 1 only.

The DVDUniqueID property retrieves a system-generated ID that uniquely identifies the current disc.

Syntax

VidWebDVD.DVDUniqueID As String

Parameters

This property takes no parameters.

Return Values

This property returns a String that serves as a unique identifier for the current disc.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | MSVidWebDVD has not been initialized.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
VFW_E_DVD_OPERATION_INHIBITED | Operation prevented by UOP command.

Remarks

This property is read-only with no default value. The identifier (ID) number is not truly unique, but it is unique for all practical purposes. The ID applies to all replicated copies of a disc. In other words, all copies of a specific movie have the same ID. The ID is based on file sizes, dates, and other information, and not the BCA value.

Example

' Returning the property.
strID = VidWebDVD.DVDUniqueID

See Also

  • MSVidWebDVD Object


MSVidWebDVD.GPRM Property

This topic applies to Windows XP Service Pack 1 only.

The GPRM property specifies and retrieves the specified general parameter register.

Syntax

VidWebDVD.GPRM(
  lIndex As Long
) As Short

Parameters

lIndex

Long specifying the general parameter register. The value must range from 0 through 15.

Return Values

When getting the value, this property returns a Short.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Index is less than 0 or greater than 15.

Remarks

General parameter registers, or GPRMs, are 16-bit registers that each disc can use in unique ways for temporary data storage. A player application does not need to access these registers for any standard playback or navigation control using the MSVidWebDVD object. This method is provided for player applications implementing advanced functionality. Do not attempt to modify the GPRMs directly unless you have a thorough knowledge of the DVD specification and the ways in which the GPRMs are used on the particular disc to be played. Changing these values can result in unpredictable behavior.

Example

' Setting the property.
VidWebDVD.GPRM(lIndex) = sRegister
' Returning the property.
sRegister = VidWebDVD.GPRM(lIndex)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
none | All

See Also

  • MSVidWebDVD Object
  • SPRM


MSVidWebDVD.KaraokeAudioPresentationMode Property

This topic applies to Windows XP Service Pack 1 only.

The KaraokeAudioPresentationMode property sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.

Syntax

VidWebDVD.KaraokeAudioPresentationMode As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value containing a set of bit flags indicating how the auxiliary karaoke channels are mixed to the left and right speakers.

Remarks

This property is read/write with a default value of zero.

Audio channels are zero-based, so channels 0 and 1 generally represent the right and left speaker channels and channels 2 through 4 are the three auxiliary karaoke channels. When the MSVidWebDVD object enters karaoke mode, it automatically mutes channels 2 and higher. Use bitwise OR operations to set the appropriate bit in order to send an auxiliary channel to the left speaker, right speaker, both speakers (both bits on), or to no speakers (both bits off). These bits are all off by default when entering karaoke mode. The value of the bits and their corresponding action is given in the following table.

Hexadecimal Value | Description
0x0004 | Mix channel 2 to the left speaker.
0x0008 | Mix channel 3 to the left speaker.
0x0010 | Mix channel 4 to the left speaker.
0x0400 | Mix channel 2 to the right speaker.
0x0800 | Mix channel 3 to the right speaker.
0x1000 | Mix channel 4 to the right speaker.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
VFW_E_DVD_OPERATION_INHIBITED | Operation prevented by UOP command.

Example

The following code example shows how to send channel 2 to the left speaker and channels 3 and 4 to the right channel by using a bitwise OR operation:

Dim lMode As Long               ' lMode automatically initialized to 0.
lMode = &H4 Or &H800 Or &H1000  ' VB-style hex values.
VidWebDVD.KaraokeAudioPresentationMode = lMode

To retrieve the value of KaraokeAudioPresentationMode, use a bitwise AND operation against the possible values, as shown in the following code example:

If (VidWebDVD.KaraokeAudioPresentationMode And &H4) Then
  ' Channel 2 is being sent to the left speaker.
End If
If (VidWebDVD.KaraokeAudioPresentationMode And &H8) Then
   ' Channel 3 is being sent to the left speaker.
End If
  ' And so on for all possible values.

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Karaoke_Audio_Presentation_Mode_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • Playing Karaoke Audio Streams


MSVidWebDVD.KaraokeChannelAssignment Property

This topic applies to Windows XP Service Pack 1 only.

The KaraokeChannelAssignment property retrieves a value that indicates how the karaoke channels in a stream are assigned to the speakers.

Syntax

VidWebDVD.KaraokeChannelAssignment(
  lStream As Long
) As Long

Parameters

lStream

Long specifying the audio stream.

Return Values

This property returns a Long describing the speaker assignment for all the channels in a specified stream. Return values include the following.

Return Code | Description
2 | The channels are assigned to the left and right speakers.
3 | The channels are assigned to the left, right, and middle speakers.
4 | The channels are assigned to the left, right, and audio1 speakers.
5 | The channels are assigned to the left, right, middle, and audio1 speakers.
6 | The channels are assigned to the left, right, and audio2 speakers.
7 | The channels are assigned to the left, right, middle, and audio2 speakers.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
E_INVALIDARG | lStream is less than 0.

Remarks

This property is read-only.

Example

' Returning the property.
lKarChnAsn = VidWebDVD.KaraokeChannelAssignment(lStream)

See Also

  • MSVidWebDVD Object
  • Playing Karaoke Discs


MSVidWebDVD.KaraokeChannelContent Property

This topic applies to Windows XP Service Pack 1 only.

The KaraokeChannelContent property retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.

Syntax

VidWebDVD.KaraokeChannelContent(
  lStream As Long,
  lChan As Long
) As Long

Parameters

lStream

Long specifying the stream to check.

lChan

Long specifying the channel to check.

Return Values

Returns an integer value whose individual bits specify the contents of the karaoke channel. Returned values include the following.

Hexadecimal Value | Description
0x0001 | Guide vocal 1
0x0002 | Guide vocal 2
0x0004 | Guide melody 1
0x0008 | Guide melody 2
0x0010 | Guide melody A
0x0020 | Guide melody B
0x0040 | Sound effect A
0x0080 | Sound effect B

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_REGION_CHANGE_FAIL | The DVD has a different region than the player.
E_INVALIDARG | lStream is less than 0 or lChan is greater than 7.

Remarks

This property is read-only. DVD audio channel numbering is zero-based, so channels 2, 3, and 4 are the auxiliary karaoke channels. After the method returns, perform a bitwise AND operation on the return value to determine the contents of each channel. Because a single channel might have more than one type of content recorded on it, you should test for all the possible values even after a match is found.

The following code example demonstrates how to test the content of a stream's channel against each possible value:

iContent = VidWebDVD.KaraokeChannelContent(lStream, lChan)
' VB-style hex values.
If(iContent And &H1) Then
     ' Set a check box or another UI control to
     '  indicate this channel has the Guide Vocal 1.
End If
If(iContent And &H2) Then
     ' Set a check box or another UI control to
    '  indicate this channel has the Guide Vocal 2.
 End If
If(iContent And &H4) Then
    ' Set a check box or another UI control to
    '  indicate this channel has the Guide Melody 1.
 End If
 ' Repeat for each possible value for each channel.

After the user knows the contents of each channel, he or she must be able to adjust the volume or turn the individual channels on or off as needed. Implement this functionality in your application by using the KaraokeAudioPresentationMode property.

Note To play karaoke discs, the audio decoder on the user's system must be compatible with the DirectShow® 8 karaoke implementation.

See Also

  • MSVidWebDVD Object
  • Playing Karaoke Audio Streams


MSVidWebDVD.LanguageFromLCID Property

This topic applies to Windows XP Service Pack 1 only.

The LanguageFromLCID property retrieves a human-readable string when given a primary language ID.

Syntax

VidWebDVD.LanguageFromLCID(
  lcid As Long
) As String

Parameters

lcid

Specifies the primary language ID as a Long. See Working with LCIDs for a table of some possible values.

Return Values

Returns a String representation of the language that can be displayed in the application's user interface.

Remarks

This property is read-only. Although this method is named LanguageFromLCID, the parameter that is passed in is actually the primary language ID, not the language ID.

Example

' Returning the property.
strLang = VidWebDVD.LanguageFromLCID(lcid)

See Also

  • AudioLanguage
  • DVDTextLanguageLCID
  • MSVidWebDVD Object
  • Text Strings
  • Working with LCIDs


MSVidWebDVD.NumberOfChapters Property

This topic applies to Windows XP Service Pack 1 only.

The NumberOfChapters property retrieves the number of chapters in the specified title.

Syntax

VidWebDVD.NumberOfChapters(
  lTitle As Long
) As Long

Parameters

lTitle

Long specifying the title.

Return Values

Returns an integer value from 1 through 999 indicating the number of chapters.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.
E_NO_DVD_VOLUME | No DVD in the machine.
E_INVALIDARG | lTitle is not a valid title number.
VFW_E_DVD_OPERATION_INHIBITED | Operation prevented by UOP command.

Remarks

This property is read-only.

Example

' Returning the property.
lChapters = VidWebDVD.NumberOfChapters(lTitle)

See Also

  • MSVidWebDVD Object


MSVidWebDVD.PlayerParentalCountry Property

This topic applies to Windows XP Service Pack 1 only.

The PlayerParentalCountry property retrieves the current country/region as set in the MSVidWebDVD object.

Syntax

VidWebDVD.PlayerParentalCountry As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value specifying the country/region code.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only. Default value is -1.

Example

' Returning the property.
lParentCountry = VidWebDVD.PlayerParentalCountry

See Also

  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • Parental Management
  • PlayerParentalLevel
  • SelectParentalCountry
  • SelectParentalLevel
  • TitleParentalLevels


MSVidWebDVD.PlayerParentalLevel Property

This topic applies to Windows XP Service Pack 1 only.

The PlayerParentalLevel property retrieves the parental management level set in the MSVidWebDVD object.

Syntax

VidWebDVD.PlayerParentalLevel As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value specifying the current parental level, or -1 if parental management is disabled.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only. A player application is responsible for enforcing parental controls. DVD designers are not required to include a parental level that corresponds to the Motion Picture Association of America (MPAA) rating, or even to include a parental level at all, and DVD parental levels are not systematically applied.

Example

' Returning the property.
lParentLevl = VidWebDVD.PlayerParentalLevel

See Also

  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • Parental Management
  • PlayerParentalCountry
  • SelectParentalCountry
  • SelectParentalLevel
  • TitleParentalLevels


MSVidWebDVD.PreferredSubpictureStream Property

This topic applies to Windows XP Service Pack 1 only.

The PreferredSubpictureStream property retrieves the preferred subpicture stream for the current viewing session.

Syntax

VidWebDVD.PreferredSubpictureStream As Long

Parameters

This property takes no parameters.

Return Values

When getting the value, this property returns a Long representing the current preferred subpicture stream in the system registry.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph not built.

Remarks

This property is read-only; to set the preferred subpicture stream, use the MSVidWebDVDAdm object's DefaultSubpictureLCID method. The value defaults to 0.

Example

' Returning the property.
lSubpictStream = VidWebDVD.PreferredSubpictureStream
' Setting the property through the DVDAdm object.
vidWebDVD.DVDAdm.DefaultSubpictureLCID = lSubpictStream

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.SPRM Property

This topic applies to Windows XP Service Pack 1 only.

The SPRM property retrieves the specified system parameter register.

Syntax

VidWebDVD.SPRM(
  lIndex As Long
) As Short

Parameters

lIndex

Specifies the register to retrieve as a Long. The register number ranges from 0 through 23, inclusive.

Return Values

Returns a Short value representing the contents of the specified register. For a listing of possible return values, see the table under the Remarks section.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph not built.
E_INVALIDARG | lIndex less than 0 or greater than 23.

Remarks

This property is read-only. The disc controls system parameter registers (SPRMs). A player application doesn't need to access these registers for any standard navigation functionality. SPRMs represent the status of the player. Each one has a meaning, set by user preferences, disc commands, and other occurrences that an application has no direct control over. An application can read these registers but cannot write to them. To use these registers effectively, you will probably need a more detailed knowledge of the DVD navigation commands than is provided in this documentation. The following table shows the contents of each register. For more detailed information on the register contents, see IDvdInfo2::GetAllSPRMs in the C++ reference section.

Register | Contents
0 | Language code
1 | Audio stream number
2 | Subpicture stream number
3 | Current angle number
4 | Title number
5 | Current title number
6 | PGC number
7 | Current chapter number
8 | Highlighted button number
9 | Navigation timer
10 | PGC jump for navigation timer
11 | Karaoke audio presentation mode
12 | PML country/region code
13 | PML
14 | Video setting
15 | Audio capability
16 | Audio language
17 | Audio language extension
18 | Subpicture language
19 | Subpicture language extension
20 | Player region code
21 | Reserved
22 | Reserved
23 | Reserved

Example

' Returning the property.
sSPRM = VidWebDVD.SPRM(lIndex)

See Also

  • GPRM
  • MSVidWebDVD Object


MSVidWebDVD.SubpictureLanguage Property

This topic applies to Windows XP Service Pack 1 only.

The SubpictureLanguage property retrieves the language for the specified subpicture stream.

Syntax

VidWebDVD.SubpictureLanguage(
  lStream As Long
) As Strong

Parameters

lStream

Long value specifying the stream of interest.

Return Values

Returns a human-readable string identifying the language of the subpicture stream in the current title.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph not built.
E_INVALIDARG | lStream is not 63 or 0 through 31.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not initialized or not in a valid domain.

Remarks

This property is read-only.

Example

' Returning the property.
strSubLang = VidWebDVD.SubpictureLanguage(lStream)

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.SubpictureOn Property

This topic applies to Windows XP Service Pack 1 only.

The SubpictureOn property sets and retrieves current subpicture state (either on or off).

Syntax

VidWebDVD.SubpictureOn As Boolean

Parameters

This property takes no parameters.

Return Values

Returns a Boolean value indicating whether the subpicture is displayed.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property does not affect display of closed captions. Closed captions are embedded within the video stream. DVD subpictures are transported on a separate stream.

This property is read/write with a default value of False.

If the subpicture stream has been changed with CurrentSubpictureStream, this value will automatically toggle to True.

Example

' Setting the property.
VidWebDVD.SubpictureOn = True
' Returning the property.
bSubOn = VidWebDVD.SubpictureOn

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Sub-picture_stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.SubpictureStreamsAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The SubpictureStreamsAvailable property retrieves the number of subpicture streams available in the current title.

Syntax

VidWebDVD.SubpictureStreamsAvailable As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long indicating the number of subpicture streams available.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | You attempted to take the value in a domain that does not support this property.

Remarks

This property is read-only with no default value.

Use this method to discover upper boundaries when querying each stream for its language attribute. When using this value, remember that stream numbering is zero-based.

Example

' Returning the property.
lSubStreamsMax = VidWebDVD.SubpictureStreamsAvailable

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Sub-picture_Stream_Change | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.TitleParentalLevels Property

This topic applies to Windows XP Service Pack 1 only.

The TitleParentalLevels property retrieves the parental management levels for the specified title.

Syntax

VidWebDVD.TitleParentalLevels(
  lTitle As Long
) As Long

Parameters

lTitle

Long value specifying a title.

Return Values

Returns a Long value whose individual bits indicate which parental management levels (PML) are set in the specified title.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.
E_INVALIDARG | Invalid argument.

Remarks

This property is read-only. A title may have chapters or even short segments that have a PML different from the overall PML for the title. Use this method to determine all the PMLs that will be encountered when playing a specified title. The returned integer is a set of bit flags that are defined as shown in the table below. Perform a bitwise AND operation on iLevels and each possible value. If the operation returns True, it means that PML will be encountered at some point in this title.

Value | Description
0x100 | DVD parental level 1
0x200 | DVD parental level 2
0x400 | DVD parental level 3
0x800 | DVD parental level 4
0x1000 | DVD parental level 5
0x2000 | DVD parental level 6
0x4000 | DVD parental level 7
0x8000 | DVD parental level 8

Example

The following code snippet shows how to test for PMLs on Title 1. One use for this information is to compare the highest PML defined for the title to the PML assigned to the current user and determine whether to play the specified title or not.

' Hexadecimal values shown in VB style.
lLevels = oVidWebDVD.TitleParentalLevels(lTitle)
If(lLevels And &H100) Then
   'PML 1 is defined for this title
End If
If(lLevels And &H200) Then
   ' PML 2 is defined for this title
End If
If(lLevels And &H400) Then
  ' PML 3 is defined for this title
End If
' And so on for all eight levels...

See Also

  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • Parental Management
  • MSVidWebDVD.SelectParentalCountry
  • MSVidWebDVD.PlayerParentalLevel
  • MSVidWebDVD.PlayerParentalCountry
  • MSVidWebDVD.SelectParentalLevel


MSVidWebDVD.TitlesAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The TitlesAvailable property retrieves the number of titles available on the disc.

Syntax

VidWebDVD.TitlesAvailable As Long

Parameters

This property takes no parameters.

Return Values

Returns the number of available titles as a Long value from 1 through 99.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.

Remarks

This property is read-only with no default value.

Example

' Returning the property.
lTitlesAvail = VidWebDVD.TitlesAvailable

See Also

  • MSVidWebDVD.AnglesAvailable
  • MSVidWebDVD Object


MSVidWebDVD.TotalTitleTime Property

This topic applies to Windows XP Service Pack 1 only.

The TotalTitleTime property retrieves the total playback time for the current title.

Syntax

VidWebDVD.TotalTitleTime As String

Parameters

This property takes no parameters.

Return Values

Returns the total playing time of the current title as a String in the format "hh:mm:ss:ff".

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the title domain.
VFW_S_DVD_NON_ONE_SEQUENTIAL | The title is not a one sequential video title.

Remarks

This property is read-only. The returned string is 11 characters long in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

Example

' Returning the property.
strTitleTime = VidWebDVD.TotalTitleTime

See Also

  • IMSVidPlayback.Length
  • MSVidWebDVD Object
  • MSVidWebDVD.PlayAtTime
  • MSVidWebDVD.PlayAtTimeInTitle


MSVidWebDVD.VolumesAvailable Property

This topic applies to Windows XP Service Pack 1 only.

The VolumesAvailable property retrieves the number of volumes in a multivolume set.

Syntax

VidWebDVD.VolumesAvailable As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long indicating the number of volumes in the set.

Remarks

This property is read-only with no default value. Some DVD titles are released as a multidisc set or series. Use this method to determine the volume number for the current disc.

Example

' Returning the property.
lVolsAvail = VidWebDVD.VolumesAvailable

See Also

  • MSVidWebDVD Object


MSVidWebDVD.AcceptParentalLevelChange Method

This topic applies to Windows XP Service Pack 1 only.

The AcceptParentalLevelChange method accepts or rejects a newly posted temporary parental management level.

Syntax

VidWebDVD.AcceptParentalLevelChange(
  bAccept As Boolean,
  strUserName As String,
  strPassword As String
)

Parameters

bAccept

Boolean value indicating whether or not to accept newly posted level.

strUserName

Specifies a user name. This parameter is currently ignored, so use an empty string ("").

strPassword

Specifies the user's password.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error; possibly the graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the title domain.
E_ACCESSDENIED | Incorrect password.

Remarks

If the NotifyParentalLevelChange property has been set to True, the player will send an EC_DVD_PARENTAL_LEVEL_CHANGE message when it encounters a new parental management level more restrictive than the preceding one, and wait for AcceptParentalLevelChange to be called, to accept or reject continued playback or branch to another, possibly less restrictive, level. If NotifyParentalLevelChange has been set to False, the message will still be sent, but playback will not be stopped.

Example

oVidWebDVD.AcceptParentalLevelChange(True, "", strPassword)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

  • DVD Event Notification Codes
  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • NotifyParentalLevelChange
  • Parental Management
  • PlayerParentalCountry
  • PlayerParentalLevel
  • SelectParentalCountry
  • SelectParentalLevel
  • TitleParentalLevels


MSVidWebDVD.ActivateAtPosition Method

This topic applies to Windows XP Service Pack 1 only.

The ActivateAtPosition method activates the menu button at the specified position.

Syntax

VidWebDVD.ActivateAtPosition(
  xPos As Long,
  yPos As Long
)

Parameters

xPos

Specifies an x coordinate.

yPos

Specifies a y coordinate.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error. Two possible reasons include: The graph has not been built. --or-- The button is present but is not working.
E_INVALIDARG | The point lies outside the valid video region.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a menu domain.
VFW_E_DVD_NO_BUTTON | There is no menu button under the mouse pointer position.
VFW_E_DVD_OPERATION_INHIBITED | The operation is inhibited by user operation (UOP) control.

Remarks

The buttons checked by this method are the MSVidWebDVD screen buttons, not the surrounding HTML page or form buttons.

Example

oVidWebDVD.ActivateAtPosition(xPos, yPos)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu

See Also

  • MSVidWebDVD Object


MSVidWebDVD.ActivateButton Method

This topic applies to Windows XP Service Pack 1 only.

The ActivateButton method activates the selected menu button.

Syntax

VidWebDVD.ActivateButton

Parameters

This method takes no parameters.

Return Values

Use this method to activate a button that has been selected through the SelectLeftButton, SelectLowerButton, SelectUpperButton, or SelectRightButton method.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error. Possible reason is that the graph has not been built.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a menu domain.
VFW_E_DVD_NO_BUTTON | No button is currently selected.
VFW_E_DVD_OPERATION_INHIBITED | The operation is inhibited by user operation (UOP) control.

Remarks

The buttons checked by this method are the MSVidWebDVD screen buttons, not the surrounding HTML page or form buttons.

Example

oVidWebDVD.ActivateButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Activate | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DeleteBookmark Method

This topic applies to Windows XP Service Pack 1 only.

The DeleteBookmark method deletes the saved bookmark.

Syntax

VidWebDVD.DeleteBookmark

Parameters

This property takes no parameters.

Return Values

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_FAIL | Unspecified error.

Remarks

There can only be one bookmark at a time, so the bookmark need not be specified.

Example

oVidWebDVD.DeleteBookmark

See Also

  • MSVidWebDVD Object


MSVidWebDVD.DVDTimeCode2bstr Method

This topic applies to Windows XP Service Pack 1 only.

The DVDTimeCode2bstr method retrieves a string indicating the current time on the disc.

Syntax

VidWebDVD.DVDTimeCode2bstr(
  timeCode As Long
) As String

Parameters

timeCode

Specifies the current time on the disc relative to the start of the title as a Long obtained through the EC_DVD_CURRENT_HMSF_TIME event.

Return Values

This method returns an 11-character String in the format "hh:mm:ss:ff" representing the hours, minutes, seconds and frames that define the current time.

Remarks

This method is read-only.

Example

strDiscTime = VidWebDVD.DVDTimeCode2bstr(timeCode)

See Also

  • Handling DVD Event Notifications
  • MSVidWebDVD Object


MSVidWebDVD.Eject Method

This topic applies to Windows XP Service Pack 1 only.

The Eject method ejects a disc from, or inserts a disc into, the DVD drive.

Syntax

VidWebDVD.Eject

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_FAIL | Unspecified error.
E_UNEXPECTED | Unspecified error.

Remarks

On some DVD drives this method acts as a toggle, inserting and ejecting on alternate calls. This behavior is device-dependent.

Example

oVidWebDVD.Eject

See Also

  • MSVidWebDVD Object


MSVidWebDVD.IsAudioStreamEnabled Method

This topic applies to Windows XP Service Pack 1 only.

The IsAudioStreamEnabled method returns a value indicating whether the specified audio stream is enabled in the current title.

Syntax

VidWebDVD.IsAudioStreamEnabled(
  lStream As Long
) As Boolean

Parameters

lStream

Specifies the audio stream as a Long value.

Return Values

This method returns a Boolean value indicating whether the specified audio stream is available for the current title. True means it is available.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lStream is less than 0 or greater than (number of streams - 1).

Remarks

Although a disc can contain up to eight independent audio streams, each stream is not necessarily available for each title. For example, a main movie title might have three audio streams for English, Spanish, and Japanese, but the "Coming Attractions" title might have only one audio stream in English. Always verify that a stream is available for a title before setting the CurrentAudioStream property

Example

bAudioEnabled = VidWebDVD.IsAudioStreamEnabled(lStream)

See Also

  • Audio Streams: Controlling Spoken Language
  • MSVidWebDVD Object


MSVidWebDVD.IsSubpictureStreamEnabled Method

This topic applies to Windows XP Service Pack 1 only.

The IsSubpictureStreamEnabled method returns a value indicating whether the specified subpicture stream is enabled in the current title.

Syntax

VidWebDVD.IsSubpictureStreamEnabled(
  lStream As Long
) As Boolean

Parameters

lStream

Specifies the subpicture stream as a Long. Values include the following.

Value | Description
0 to 31 | Subpicture stream
63 | Muted low bit-rate stream

Return Values

Returns a Boolean value indicating whether the specified subpicture stream is available in the current title. True means it is available.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lStream is outside the allowed values.

Remarks

Although a disc can contain up to 32 subpicture streams, each stream is not necessarily available for each title. Always verify that a stream is available for a title before setting the CurrentSubpictureStream property.

Example

Boolean = VidWebDVD.IsSubpictureStreamEnabled(lStream)

See Also

  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.NotifyParentalLevelChange Method

This topic applies to Windows XP Service Pack 1 only.

The NotifyParentalLevelChange method enables or disables playback stop for temporary parental management level commands.

Syntax

VidWebDVD.NotifyParentalLevelChange(
  bNotify As Boolean
)

Parameters

bNotify

Specifies a Boolean value indicating whether or not the application should be notified when the reader encounters video segments with a rating more restrictive than the overall rating for the disc.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error

Remarks

The EC_DVD_PLAYBACK_RATE_CHANGE notification is sent regardless of whether or not this method has been set to True or False. However, this value determines the behavior of the DVD Navigator filter when it encounters different temporary parental levels.

If NotifyParentalLevelChange is set to True and the player encounters a temporary management level more restrictive than the player's current value, the DVD Navigator filter will pause playback and wait for the AcceptParentalLevelChange method to either allow or prevent playback of the restricted content. It is up to the application to create a message box or otherwise reject or accept the new level. If the level change is rejected, playback will either branch to a permissible path specified by the disc, or halt playback if no path is specified.

If NotifyParentalLevelChange is set to False, the application will automatically branch to a permissable path specified by the disc, or stop if no permissable path is specified.

Call this method during initialization of your application if you need to handle temporary parental management level commands from the disc. To disable parental management after it is enabled, call this method with an argument of False. For more details on parental management, see AcceptParentalLevelChange.

NotifyParentalLevelChange is set to False by default.

Example

oVidWebDVD.NotifyParentalLevelChange(bNotify)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

  • AcceptParentalLevelChange
  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • Parental Management
  • PlayerParentalCountry
  • PlayerParentalLevel
  • SelectParentalCountry
  • SelectParentalLevel
  • TitleParentalLevels


MSVidWebDVD.PlayAtTime Method

This topic applies to Windows XP Service Pack 1 only.

The PlayAtTime method starts playback in the current title at the specified time.

Syntax

VidWebDVD.PlayAtTime(
  strTime As String
)

Parameters

strTime

Specifies the time at which to start playing as a String. The string must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).

Return Values

This method has no return values.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid time.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.

Example

oVidWebDVD.PlayAtTime(strTime)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Time_Search | DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object
  • PlayAtTimeInTitle


MSVidWebDVD.PlayAtTimeInTitle Method

This topic applies to Windows XP Service Pack 1 only.

The PlayAtTimeInTitle method starts playback at the specified time in the specified in the specified title.

Syntax

VidWebDVD.PlayAtTimeInTitle(
  lTitle As Long,
  strTime As String
)

Parameters

lTitle

Specifies the index of the title as a Long.

strTime

Specifies the time at which to start playback as a string. The string must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid time or title.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.

Example

oVidWebDVD.PlayAtTimeInTitle(lTitle, strTime)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J command name | Valid domains
Time_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • PlayAtTime


MSVidWebDVD.PlayChapter Method

This topic applies to Windows XP Service Pack 1 only.

The PlayChapter method starts playback at the specified chapter in the current title.

Syntax

VidWebDVD.PlayChapter(
  lChapter As Long
)

Parameters

lChapter

Long specifying the chapter.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid chapter.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.

Remarks

When the end of the specified chapter is reached, this method continues playing subsequent chapters, if any exist. If you want to play only a specified chapter, use PlayChaptersAutoStop.

Example

oVidWebDVD.PlayChapter(lChapter)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
PTT_Search | DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object
  • PlayChapterInTitle
  • PlayChaptersAutoStop
  • PlayNextChapter
  • PlayPrevChapter


MSVidWebDVD.PlayChapterInTitle Method

This topic applies to Windows XP Service Pack 1 only.

The PlayChapterInTitle method plays the specified chapter in the specified title.

Syntax

VidWebDVD.PlayChapterInTitle(
  lTitle As Long,
  lChapter As Long
)

Parameters

lTitle

Long specifying the title.

lChapter

Long specifying the chapter.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid chapter or title number.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.

Remarks

This method starts playback at the specified chapter and then continues playing indefinitely. If you want to play only a particular chapter, use PlayChaptersAutoStop.

Example

oVidWebDVD.PlayChapterInTitle(lTitle, lChapter)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
PTT_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • PlayChapter


MSVidWebDVD.PlayChaptersAutoStop Method

This topic applies to Windows XP Service Pack 1 only.

The PlayChaptersAutoStop method starts playback at the specified chapter in the specified title, and continues for a specified number of chapters.

Syntax

VidWebDVD.PlayChaptersAutoStop(
  lTitle As Long,
  lChapter As Long,
  lChapterCount As Long
)

Parameters

lTitle

Long specifying the title.

lChapter

Long specifying the chapter.

lChapterCount

Long specifying the number of chapters to play.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_INVALIDARG | Invalid chapter or title number or chapter count.
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_GRAPHNOTREADY | The graph is not in a running state.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

When the last chapter has played, this method causes an EC_DVD_CHAPTER_AUTOSTOP event notification to be sent to the application

Example

oVidWebDVD.PlayChaptersAutoStop(lTitle, lChapter, lChapterCount)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None. | All

See Also

  • MSVidWebDVD Object
  • PlayChapter


MSVidWebDVD.PlayNextChapter Method

This topic applies to Windows XP Service Pack 1 only.

The PlayNextChapter method starts playback at the next chapter.

Syntax

VidWebDVD.PlayNextChapter

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.PlayNextChapter

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
NextPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object
  • PlayChapter
  • PlayPrevChapter


MSVidWebDVD.PlayPeriodInTitleAutoStop Method

This topic applies to Windows XP Service Pack 1 only.

The PlayPeriodInTitleAutoStop method plays the DVD from a specified start time to a specified stop time within a specified title.

Syntax

VidWebDVD.PlayPeriodInTitleAutoStop(
  lTitle As Long,
  strStartTime As String,
  strEndTime As String
)

Parameters

lTitle

Long specifying the title.

strStartTime

String specifying start time in the format "hh:mm:ss:ff" (representing hours, minutes, seconds, and frames).

strEndTime

String specifying stop time in the format "hh:mm:ss:ff" (representing hours, minutes, seconds, and frames).

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_INVALIDARG | Invalid title, start or end time.
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_GRAPHNOTREADY | The graph is not in a running state.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.PlayPeriodInTitleAutoStop(lTitle, strStartTime, strEndTime)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • PlayAtTimeInTitle
  • PlayAtTime
  • PlayChaptersAutoStop


MSVidWebDVD.PlayPrevChapter Method

This topic applies to Windows XP Service Pack 1 only.

The PlayPrevChapter method starts playback from the previous chapter in the current title.

Syntax

VidWebDVD.PlayPrevChapter

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.PlayPrevChapter

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
PrevPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object
  • PlayChapter
  • PlayNextChapter


MSVidWebDVD.PlayTitle Method

This topic applies to Windows XP Service Pack 1 only.

The PlayTitle method starts playback at the beginning of the specified title.

Syntax

VidWebDVD.PlayTitle(
  lTitle As Long
)

Parameters

lTitle

Long specifying the title.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lTitle less than 0 or greater than (number of titles - 1).
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.

Example

oVidWebDVD.PlayTitle(lTitle)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Title_Play | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object
  • PlayPeriodInTitleAutoStop


MSVidWebDVD.RegionChange Method

This topic applies to Windows XP Service Pack 1 only.

The RegionChange method displays a system dialog box that enables the user to change the region associated with the DVD drive.

Syntax

VidWebDVD.RegionChange

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_REGION_CHANGE_FAIL | Operation failed.

Remarks

The region for a DVD drive can only be changed five times.

Example

oVidWebDVD.RegionChange

See Also

  • MSVidWebDVD Object


MSVidWebDVD.ReplayChapter Method

This topic applies to Windows XP Service Pack 1 only.

The ReplayChapter method starts playback at the beginning of the current chapter.

Syntax

VidWebDVD.ReplayChapter

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.ReplayChapter

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
TopPG_Search | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object
  • PlayChapter
  • PlayChaptersAutoStop


MSVidWebDVD.RestoreBookmark Method

This topic applies to Windows XP Service Pack 1 only.

The RestoreBookmark method moves the player to the point on the disc specified in the current bookmark, with all audio, video, and subpicture settings restored.

Syntax

VidWebDVD.RestoreBookmark

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error
E_FAIL | Unspecified failure

Remarks

Bookmarks are useful for allowing a user to stop playback, then restart play where it was stopped, avoiding any mandatory playback such as the FBI warning at the beginning of a disc. It is possible that this technique could fail, however, since a few codecs are not fast enough to negotiate key permissions in the time required before playback.

Example

oVidWebDVD.RestoreBookmark

See Also

  • MSVidWebDVD Object
  • SaveBookmark
  • Saving and Restoring Bookmarks


MSVidWebDVD.RestorePreferredSettings Method

This topic applies to Windows XP Service Pack 1 only.

The RestorePreferredSettings method restores the registry's DVD default language and level settings.

Syntax

VidWebDVD.RestorePreferredSettings

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | Must be in Stop domain for this operation.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

Properties such as parental level or default audio language that are set using the MSVidWebDVD object are generally applied to the current session only. A user wishing to save these settings as default values in the registry should use the corresponding methods on the MSVidWebDVDAdm object.

Sometimes a user may wish to temporarily change settings, then revert to the saved settings during a viewing session. For example, a parent watching a film may temporarily raise the parental level of the viewer to allow mature content, but wish to restore lower settings after playing a disc. RestorePreferredSettings allows the user to restore the saved DVD language and level settings saved using SaveParentalLevel on the MSVidWebDVDAdm object. The reader must be stopped when executing this method.

Example

oVidWebDVD.RestorePreferredSettings

Valid Domains

The following table shows the domains in which this method is valid.

Annex J Command Name | Valid Domains
 | DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object


MSVidWebDVD.Resume Method

This topic applies to Windows XP Service Pack 1 only.

The Resume method resumes playback after a menu has been displayed.

Syntax

VidWebDVD.Resume

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_NO_RESUME_INFORMATION | Resume was called from the Video Manager Menu.
VFW_E_DVD_INVALIDDOMAIN | Must be in Stop domain for this operation.

Example

oVidWebDVD.Resume

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Resume | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Stop

See Also

  • MSVidWebDVD Object


MSVidWebDVD.ReturnFromSubmenu Method

This topic applies to Windows XP Service Pack 1 only.

The ReturnFromSubmenu method returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.

Syntax

VidWebDVD.ReturnFromSubmenu

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.ReturnFromSubmenu

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
GoUP | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • MSVidWebDVD Object


MSVidWebDVD.SaveBookmark Method

This topic applies to Windows XP Service Pack 1 only.

The SaveBookmark method saves the current disc position and state of the MSVidWebDVD object so the user can return to the same place later.

Syntax

VidWebDVD.SaveBookmark

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error
E_FAIL | Unspecified failure

Remarks

A bookmark is a snapshot of the player's current state. This includes information such as where it is playing on the disc, and which audio and subpictures streams are selected. The most common use for bookmarks is to allow the user to stop playback, and even shut down the computer, and come back later to continue viewing the disc right where he or she left off, with all settings just as they were before, avoiding any mandatory playback screens such as the FBI warning. Without using a bookmark, these screens would have to be replayed each time the graph is restarted.

Only one bookmark can be saved at any given time. When you call SaveBookmark, the old bookmark is overwritten.

Example

oVidWebDVD.SaveBookmark

See Also

  • MSVidWebDVD Object
  • RestoreBookmark
  • Saving and Restoring Bookmarks


MSVidWebDVD.SelectAndActivateButton Method

This topic applies to Windows XP Service Pack 1 only.

The SelectAndActivateButton method selects and activates the specified button.

Syntax

VidWebDVD.SelectAndActivateButton(
  lButton As Long
)

Parameters

lButton

Long specifying the button.

Return Values

This method does not return a value.

Remarks

This method highlights the specified button and activates it automatically. The buttons checked by this method are the DVD's onscreen buttons, not the surrounding HTML page or form buttons.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lButton is less than 0 or greater than the highest button index.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Example

oVidWebDVD.SelectAndActivateButton(lButton)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Button_Select_And_Activate | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • ActivateButton
  • ButtonAtPosition
  • ButtonsAvailable
  • CurrentButton
  • MSVidWebDVD Object
  • SelectAtPosition


MSVidWebDVD.SelectAtPosition Method

This topic applies to Windows XP Service Pack 1 only.

The SelectAtPosition method selects the menu button at the specified mouse pointer coordinates.

Syntax

VidWebDVD.SelectAtPosition(
  xPos As Long,
  yPos As Long
)

Parameters

xPos

Specifies the x-coordinate as a Long.

yPos

Specifies the y-coordinate as a Long.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_NO_BUTTON | No button is present at the specified position.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is in the Stop domain.

Remarks

Selecting merely highlights the button. To send the command associated with a button that has been selected, call ActivateButton. To simulate clicking a button, call SelectAndActivateButton. The buttons described are the menu buttons on the Video Control, not the buttons in the surrounding form or HTML.

Example

oVidWebDVD.SelectAtPosition(xPos, yPos)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title DVD_DOMAIN_FirstPlay

See Also

  • ButtonAtPosition
  • ButtonsAvailable
  • CurrentButton
  • MSVidWebDVD Object
  • SelectAndActivateButton


MSVidWebDVD.SelectDefaultAudioLanguage Method

This topic applies to Windows XP Service Pack 1 only.

The SelectDefaultAudioLanguage method sets the current default audio language in the MSVidWebDVD object.

Syntax

VidWebDVD.SelectDefaultAudioLanguage(
  lang As Long,
  ext As Long
)

Parameters

lang

Specifies the language as a Long LCID value. See the table under Working with LCIDs for possible values.

ext

Specifies the DVD audio language extension as a Long value. The following table shows possible values.

Value | Description
0 | Not specified
1 | Captions
2 | Visually impaired
3 | Director comments 1
4 | Director comments 2

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lang or ext are invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the Stop domain.

Example

oVidWebDVD.SelectDefaultAudioLanguage(lang, ext)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • Audio Streams: Controlling Spoken Language
  • MSVidWebDVD Object


MSVidWebDVD.SelectDefaultSubpictureLanguage Method

This topic applies to Windows XP Service Pack 1 only.

The SelectDefaultSubpictureLanguage method sets the current default subpicture language.

Syntax

VidWebDVD.SelectDefaultSubpictureLanguage(
  lang As Long,
  ext As DVDSPExt
)

Parameters

lang

Specifies the language as a Long value.

ext

Specifies the subpicture language extension as a Long value. See DVDSPExt Constants enumeration for possible values.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | lang or ext are invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the Stop domain.

Remarks

The subpicture language extension provides further information about the subpicture.

Example

oVidWebDVD.SelectDefaultSubpictureLanguage(lang, ext)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

See Also

  • DVD_SUBPICTURE_LANG_EXT
  • MSVidWebDVD Object
  • Subpicture Streams: Controlling Subtitles


MSVidWebDVD.SelectLeftButton Method

This topic applies to Windows XP Service Pack 1 only.

The SelectLeftButton method selects the left directional button from the displayed menu.

Syntax

VidWebDVD.SelectLeftButton

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.

Example

oVidWebDVD.SelectLeftButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Left_Button_Select | DVD_DOMAIN_Stop

See Also

  • ActivateButton
  • MSVidWebDVD Object
  • SelectLowerButton
  • SelectRightButton
  • SelectUpperButton


MSVidWebDVD.SelectLowerButton Method

This topic applies to Windows XP Service Pack 1 only.

The SelectLowerButton method selects the lower directional button from the displayed menu.

Syntax

VidWebDVD.SelectLowerButton

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.

Example

oVidWebDVD.SelectLowerButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Lower_Button_Select | DVD_DOMAIN_Stop

See Also

  • ActivateButton
  • MSVidWebDVD Object
  • SelectLeftButton
  • SelectRightButton
  • SelectUpperButton


MSVidWebDVD.SelectParentalCountry Method

This topic applies to Windows XP Service Pack 1 only.

The SelectParentalCountry method sets the specified parental country/region for subsequent playback.

Syntax

VidWebDVD.SelectParentalCountry(
  lCountry As Long,
  strUserName As String,
  strPassword As String
)

Parameters

lCountry

Long specifying the country/region.

strUserName

String specifying the current user. This parameter is currently ignored, so use an empty string ("").

strPassword

String specifying the application password.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Country/region value is invalid.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.
E_ACCESSDENIED | Incorrect password.

Remarks

The parental country/region determines how the parental levels are interpreted.

Example

oVidWebDVD.SelectParentalCountry(lCountry, "", strPassword)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Country_Select | DVD_DOMAIN_Stop

See Also

  • AcceptParentalLevelChange
  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • NotifyParentalLevelChange
  • Parental Management
  • PlayerParentalCountry
  • PlayerParentalLevel
  • SelectParentalLevel
  • TitleParentalLevels


MSVidWebDVD.SelectParentalLevel Method

This topic applies to Windows XP Service Pack 1 only.

The SelectParentalLevel method sets the parental level for subsequent playback.

Syntax

VidWebDVD.SelectParentalLevel(
  lParentalLevel As Long,
  strUserName As String,
  strPassword As String
)

Parameters

lParentalLevel

Specifies the parental management level as a Long. To enable parental management, lParentalLevel must range from 1 through 8. To disable parental management, set lParentalLevel to -1.

strUserName

Specifies the current user as a String. This method is currently ignored, so use an empty string ("")

strPassword

Specifies the password currently stored in the registry as a String.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Country/region value is invalid.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.
E_ACCESSDENIED | Incorrect password.

Remarks

This method sets the access level in the MSVidWebDVD object, which determines what content the user can play back. Higher levels can play lower-level content but lower levels can't play higher-level content. The exact meaning of the eight DVD parental management levels varies depending on the country/region. In the United States and Canada, the levels are mapped to the Motion Picture Association of America (MPAA) rating categories. Parental management is disabled by default.

Note Player parental levels can only be set in the Stop domain.

Example

oVidWebDVD.SelectParentalLevel(lParentalLevel, "", strPassword)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Level_Select | DVD_DOMAIN_Stop

See Also

  • AcceptParentalLevelChange
  • Enforcing Parental Management Levels
  • MSVidWebDVD Object
  • NotifyParentalLevelChange
  • Parental Management
  • PlayerParentalCountry
  • PlayerParentalLevel
  • SelectParentalCountry
  • TitleParentalLevels


MSVidWebDVD.SelectRightButton Method

This topic applies to Windows XP Service Pack 1 only.

The SelectRightButton method selects the right directional button from the displayed menu.

Syntax

VidWebDVD.SelectRightButton

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.

Example

oVidWebDVD.SelectRightButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Right_Button_Select | DVD_DOMAIN_Stop

See Also

  • ActivateButton
  • MSVidWebDVD Object
  • SelectLeftButton
  • SelectLowerButton
  • SelectUpperButton


MSVidWebDVD.SelectUpperButton Method

This topic applies to Windows XP Service Pack 1 only.

The SelectUpperButton method selects the upper directional button from the displayed menu.

Syntax

VidWebDVD.SelectUpperButton

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.

Example

oVidWebDVD.SelectUpperButton

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Upper_Button_Select | DVD_DOMAIN_Stop

See Also

  • ActivateButton
  • MSVidWebDVD Object
  • SelectLeftButton
  • SelectLowerButton
  • SelectRightButton


MSVidWebDVD.ShowMenu Method

This topic applies to Windows XP Service Pack 1 only.

The ShowMenu method displays the specified menu on the screen.

Syntax

VidWebDVD.ShowMenu(
  MenuID As DVDMenuIDConstants
)

Parameters

MenuID

Specifies which menu has been enabled or disabled. For a list of possible values, see DVDMenuID Constants.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid menu ID number.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

DVD menu names can be somewhat confusing. The Title menu is another name for the Video Manager Menu, the main menu for the entire disc; it generally lists all the video title sets available on the disc. The root menu is the menu for one video title set, which can contain one title or a group of titles. All the titles in a title set share the same Subpicture, Audio, and Angle menus.

Example

oVidWebDVD.ShowMenu(MenuID)

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Menu_Call | All

See Also

  • MSVidWebDVD Object


MSVidWebDVD.StillOff Method

This topic applies to Windows XP Service Pack 1 only.

The StillOff method cancels the still mode and resumes playback.

Syntax

VidWebDVD.StillOff

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain for this method.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The player goes into still mode when it encounters a still frame authored on the disc. Still frames include the FBI warning and the title screen. The player notifies your application of a still frame by sending an EC_DVD_STILL_ON event. Still mode is different from the player being in a paused state because of a user operation. Calling StillOff resumes playback from still mode but does not restart the DVD Navigator filter when it is in a paused state.

Example

oVidWebDVD.StillOff

Valid Domains

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Still_Off | DVD_DOMAIN_VideoManagerMenu DVD_DOMAIN_VideoTitleSetMenu DVD_DOMAIN_Title

See Also

  • EC_DVD_STILL_ON
  • MSVidWebDVD Object


MSVidWebDVD.UOPValid Method

This topic applies to Windows XP Service Pack 1 only.

The UOPValid method retrieves a value that indicates whether the specified user operation (UOP) is currently valid.

Syntax

VidWebDVD.UOPValid(
  lUOP As Long
) As Boolean

Parameters

lUOP

Specifies the user operation (UOP) as a Long. Values can include the following.

Value | Description
0 | PlayTitle, PlayAtTime, and PlayAtTimeInTitle
1 | PlayChapter
2 | PlayTitle
3 | Stop (not enforced on the MSVidCtl object)
4 | ReturnFromSubmenu
5 | PlayChapter
6 | PlayPrevChapter, ReplayChapter
7 | PlayNextChapter
8 | Forward play allowed.
9 | Backward play allowed.
10 | ShowMenu with a parameter value of 2 (DVD_MENU_Title).
11 | ShowMenu with a parameter value of 3 (DVD_MENU_Root).
12 | ShowMenu with a parameter value of 4 (DVD_MENU_Subpicture).
13 | ShowMenu with a parameter value of 5 (DVD_MENU_Audio).
14 | ShowMenu with a parameter value of 6 (DVD_MENU_Angle).
15 | ShowMenu with a parameter value of 7 (DVD_MENU_Chapter).
16 | Resume
17 | SelectLeftButton, SelectRightButton, SelectUpperButton, and SelectLowerButton
18 | StillOff
19 | Pause (not enforced on the MSVidCtl object)
20 | CurrentAudioStream
21 | CurrentSubpictureStream
22 | CurrentAngle, SelectParentalLevel
23 | KaraokeAudioPresentationMode
24 | Select video mode preference.

Return Values

Returns a Boolean indicating whether the specified operation is permitted.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | UOP number less than 0 or greater than 24 entered.

Remarks

DVD authors can encode the disc to enable or disable certain commands by the user. These user operations (UOP) generally handle disc navigation. Attempting to access a property or method that is not currently allowed or valid will cause your application to raise an error. UOPValid allows you to determine if you can access a method or property to avoid such errors.

In addition to avoiding run-time errors, UOPValid allows you to visibly disable controls for prohibited actions on the user interface.

Certain methods—Stop, Pause, and Run—apply to both the MSVidWebDVD object and the MSVidCtl object. These methods should be run from the MSVidCtl object, or your application will raise an error. Disc permissions cannot prevent the MSVidCtl object from implementing these methods even when the UOPValid method returns false. However, an application designer may choose to disable user controls for these methods when the UOP value is false.

Example

' Check if forward or reverse play is allowed before changing playback rate.
dRate = txtRate.Text
If oVidWebDVD.UOPValid(&H80) And dRate > 0 Then  ' Handle forward.
   oVidWebDVD.Rate = dRate
ElseIf oVidWebDVD.UOPValid(&H100) And dRate < 0 Then   ' Handle reverse.
   oVidWebDVD.Rate = dRate
End If

See Also

  • MSVidWebDVD Object


MSVidWebDVDAdm Object

This topic applies to Windows XP Service Pack 1 only.

The MSVidWebDVDAdm object gets and sets saved settings for the MSVidWebDVD object.

Settings are saved in the Microsoft® Windows® registry. The registry is a database that Windows applications use to store information about themselves for use at initialization or run time.

Most of these methods and properties do not set or retrieve the current values in the DVD Navigator filter itself. This means, for example, that when you call GetParentalLevel the returned value is not the current parental level stored in the object. Rather, it is the default parental level stored in the registry. To get the current parental level in the player, call the MSVidWebDVD method PlayerParentalLevel. Calling MSVidWebDVDAdm.SaveParentalLevel simply writes a new default parental access level to the registry; you still need to call the MSVidWebDVD method SelectParentalLevel to make the change take effect immediately in the player. The default locale identifier (LCID) methods work in a similar way.

You can either create the MSVidWebDVDAdm as a separate object, or else access the object's properties and methods through the DVDAdm property of MSVidWebDVD. The following code is an example of calling the GetParentalLevel method by accessing the MSVidWebDVDAdm through the MSVidWebDVD (assuming the MSVidWebDVD object is named oDVD):

lDefParentalLevel = oDVD.DVDAdm.GetParentalLevel

The following code would create an independent MSVidWebDVD object and call the GetParentalLevel method on it:

Option Explicit
Dim WithEvents oVidWebDVD As MSVidWebDVD
Dim oVidWebAdm As MSVidWebDVDAdm

' Call this subroutine to create all objects first.
Sub cmdPlay_Click()
   oVideoControl.View ("DVD:")
   oVideoControl.Build
   Set oVidWebDVD = oVideoControl.InputActive
   Set oVidWebAdm = oVidWebDVD.DVDAdm
   oVideoControl.Run
End Sub

' Call this function to get the default parental level in the registry.
Function GetDefParentalLevel()
   ChangePassword = oVidWebAdm.GetParentalLevel
End Function

The MSVidWebDVDAdm object exposes the following properties and methods.

Properties

Property | Description
BookmarkOnStop | Sets or retrieves a value that tells the MSVidWebDVDAdm object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.
DefaultAudioLCID | Sets or retrieves the registry setting for the user-specified default LCID for the audio stream.
DefaultMenuLCID | Sets or retrieves the registry setting for the user-specified default LCID for menus.
DefaultSubpictureLCID | Sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.

Methods

Method | Description
ChangePassword | Saves a new application password in the registry.
ConfirmPassword | Tests whether the specified password matches the previously saved password.
GetParentalCountry | Retrieves the parental country/region that was last saved to the registry.
GetParentalLevel | Retrieves the parental level that was last saved to the registry.
SaveParentalCountry | Saves the application's new parental country/region to the registry.
SaveParentalLevel | Saves a new default parental level to the registry.

See Also

  • DVD Applications in Visual Basic (Video Control)


MSVidWebDVDAdm.BookmarkOnStop Property

This topic applies to Windows XP Service Pack 1 only.

The BookmarkOnStop property sets or retrieves a value that tells the MSVidWebDVD object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.

Syntax

VidWebDVDAdm.BookmarkOnStop As Boolean

Parameters

This property takes no parameters.

Return Values

Returns a Boolean value indicating whether the MSVidWebDVDAdm object will save a bookmark of all DVD settings, including position on disc, parental level, and parental country/region.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error

Remarks

This property is read/write with a default value of False.

Bookmarks are valid only for a particular machine. A user cannot save a bookmark and then send it to someone else to read on a different machine.

Example

' Setting the property.
oVidWebDVDAdm.BookmarkOnStop = bSaveBookmark
' Returning the property.
bSaveBookmark = oVidWebDVDAdm.BookmarkOnStop

See Also

  • MSVidWebDVDAdm Object
  • Saving and Restoring Bookmarks


MSVidWebDVDAdm.DefaultAudioLCID Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultAudioLCID property sets or retrieves the registry setting for the user-specified default LCID for the audio stream.

Syntax

VidWebDVDAdm.DefaultAudioLCID As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the user-specified default audio LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default audio stream as authored on the DVD. For the range of valid LCIDs, see the Microsoft® Win32® documentation in the Platform SDK.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid LCID entered.

Remarks

This property is read/write with no default value. If no default audio LCID is specified, the MSVidWebDVDAdm object will play the audio stream that is marked as the default stream on the disc

Example

' Setting the property.
oVidWebDVDAdm.DefaultAudioLCID = lDefAudioLCID
' Returning the property.
lDefAudioLCID = oVidWebDVDAdm.DefaultAudioLCID

See Also

  • MSVidWebDVDAdm Object


MSVidWebDVDAdm.DefaultMenuLCID Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultMenuLCID property sets or retrieves the registry setting for the user-specified default LCID for menus.

Syntax

VidWebDVDAdm.DefaultMenuLCID As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default menu language as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid LCID entered.

Remarks

This property is read/write with no default value. If no default menu LCID is specified, the MSVidWebDVDAdm object will use the language that is marked as the default menu language on the disc.

Example

' Setting the property.
oVidWebDVDAdm.DefaultMenuLCID = lDefMenu
' Returning the property.
lDefMenu = oVidWebDVDAdm.DefaultMenuLCID

See Also

  • MSVidWebDVDAdm Object


MSVidWebDVDAdm.DefaultSubpictureLCID Property

This topic applies to Windows XP Service Pack 1 only.

The DefaultSubpictureLCID property sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.

Syntax

VidWebDVDAdm.DefaultSubpictureLCID As Long

Parameters

This property takes no parameters.

Return Values

Returns a Long value representing the user-specified default subpicture LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default subpicture stream as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid LCID entered.

Remarks

This property is read/write with no default value. If no default subpicture LCID is specified, the MSVidWebDVDAdm object will play the subpicture stream that is marked as the default stream on the disc.

Example

' Setting the property.
oVidWebDVDAdm.DefaultSubpictureLCID = lDefSubpicture
' Returning the property.
lDefSubpicture = oVidWebDVDAdm.DefaultSubpictureLCID

See Also

  • MSVidWebDVDAdm Object


MSVidWebDVDAdm.ChangePassword Method

This topic applies to Windows XP Service Pack 1 only.

The ChangePassword method saves a new application password in the registry.

Syntax

VidWebDVDAdm.ChangePassword(
  strUserName As String,
  strOld As String,
  strNew As String
)

Parameters

strUserName

Specifies the current user's logon name as a String. This parameter is not currently implemented, so use an empty string (""). See Remarks.

strOld

Specifies the user's old password as a String.

strNew

Specifies the user's new password as a String. Cannot be an empty string.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid new password entered; probably too long.
E_ACCESSDENIED | Permission to change password could not be verified.
E_OUTOFMEMORY | Not enough memory to complete the task.

Remarks

Currently, the strUserName parameter is ignored on this and all related methods. This means that whoever knows the password can set the parental level. There is only one password and one parental level for the application. There is no support for individual user logon names or multiple password management. To enforce parental management levels, parents should set the password and then set the parental level appropriate for younger members of the family. When parents want to view a disc with adult-rated content, they can change the level, and then change it back when they are done viewing. As long as the children do not know the password, they can only watch content at or below the level set for them.

Example

oVidWebDVDAdm.ChangePassword("", strOld, strNew)

See Also

  • ConfirmPassword
  • MSVidWebDVDAdm Object


MSVidWebDVDAdm.ConfirmPassword Method

This topic applies to Windows XP Service Pack 1 only.

The ConfirmPassword method tests whether the specified password matches the saved password.

Syntax

VidWebDVDAdm.ConfirmPassword(
  strUserName As String,
  strPassword As String
) As Boolean

Parameters

strUserName

Specifies the user name as a String. This parameter is currently ignored, so use an empty string ("").

strPassword

Specifies a password as a String.

Return Values

This method returns a Boolean indicating if the passwords match.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid password entered; probably too long.

Remarks

Currently, the user name is ignored on this and all related methods

Example

bAllowed = oVidWebDVDAdm.ConfirmPassword("", strPassword)

See Also

  • MSVidWebDVDAdm Object


MSVidWebDVDAdm.GetParentalCountry Method

This topic applies to Windows XP Service Pack 1 only.

The GetParentalCountry method retrieves the parental country/region that was last saved to the registry.

Syntax

VidWebDVDAdm.GetParentalCountry As Long

Parameters

This method takes no parameters.

Return Values

This method returns a Long value indicating the default parental country/region in the registry.

Remarks

The parental country/region this method retrieves is not necessarily the same country/region currently stored in the MSVidWebDVD object.

Example

lDefaultCountry = oVidWebDVDAdm.GetParentalCountry

See Also

  • GetParentalLevel
  • MSVidWebDVDAdm Object
  • SaveParentalCountry
  • SaveParentalLevel


MSVidWebDVDAdm.GetParentalLevel Method

This topic applies to Windows XP Service Pack 1 only.

The GetParentalLevel method retrieves the parental level that was last saved to the registry.

Syntax

VidWebDVDAdm.GetParentalLevel As Long

Parameters

This method takes no parameters.

Return Values

This method returns a Long value from 1 through 8, indicating the default parental level saved in the registry.

Remarks

The parental level this method retrieves is not necessarily the same level currently stored in the MSVidWebDVD control; to get the level currently stored in the control, call the MSVidWebDVD.PlayerParentalLevel method. A value of -1 indicates that parental management is disabled. See PlayerParentalLevel for more information on parental levels.

Example

lDefParentalLevel = oVidWebDVDAdm.GetParentalLevel

See Also

  • Enforcing Parental Management Levels
  • GetParentalCountry
  • MSVidWebDVDAdm Object
  • SaveParentalCountry
  • SaveParentalLevel


MSVidWebDVDAdm.SaveParentalCountry Method

This topic applies to Windows XP Service Pack 1 only.

The SaveParentalCountry method saves a new parental country/region to the registry.

Syntax

VidWebDVDAdm.SaveParentalCountry(
  lCountry As Long,
  strUserName As String,
  strPassword As String
)

Parameters

lCountry

Specifies the country/region.

strUserName

Specifies the user name. This parameter is not currently used, so use an empty string ("").

strPassword

Specifies a password.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Invalid country/region code entered.
E_ACCESSDENIED | Invalid password or permissions to change the country/region.

Remarks

This method enables a user who knows the current password to save a new parental country/region setting to the registry. As with all the methods of MSVidWebDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSVidWebDVD object is created, it will open with the new country/region. To change the player's current parental country/region, call MSVidWebDVD.SelectParentalCountry, which does not change the registry setting.

Example

oVidWebDVDAdm.SaveParentalCountry(lCountry, "", strPassword)

See Also

  • GetParentalCountry
  • GetParentalLevel
  • MSVidWebDVDAdm Object
  • SaveParentalLevel


MSVidWebDVDAdm.SaveParentalLevel Method

This topic applies to Windows XP Service Pack 1 only.

The SaveParentalLevel method saves a new default parental level to the registry.

Syntax

VidWebDVDAdm.SaveParentalLevel(
  lLevel As Long,
  strUserName As String,
  strPassword As String
)

Parameters

lLevel

Indicates the new default parental level, from 1 through 8.

strUserName

Specifies the user name. This parameter is not currently used, so use an empty string ("").

strPassword

Specifies a password.

Return Values

This method does not return a value.

Error Codes

If the property fails, Err.Number may be set to one of the following values.

Value | Description
E_UNEXPECTED | Unspecified error.
E_INVALIDARG | Level less than 1 or greater than 8 entered.
E_ACCESSDENIED | Invalid password or permissions to change the country/region.

Remarks

This method enables a user who knows the current password to save a new parental level setting to the registry. As with all the methods of MSVidWebDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSVidWebDVD object is started, it will open with the new level. Specify -1 to disable parental management. To change the parental level in the player, call MSVidWebDVD.SelectParentalLevel, which does not change the registry setting. See PlayerParentalLevel for more information on parental levels.

Example

oVidWebDVDAdm.SaveParentalLevel(lLevel, "", strPassword)

See Also

  • Enforcing Parental Management Levels
  • GetParentalCountry
  • GetParentalLevel
  • MSVidWebDVDAdm Object
  • SaveParentalCountry


Video Control Events

This topic applies to Windows XP only.

This section lists the methods (also known as event handlers) that applications must implement to handle events from the video control and its associated objects. When an event occurs, the object calls the event handler in your application, if the handler is implemented. No event handler is required to be implemented, although some provide the only way to achieve desired functionality.

Event | Description
CertificateFailure | Called when the object fails to get an encryption/decription license.
CertificateSuccess | Called when the object succeeds in getting an encryption/decription license.
Click | Called by the MSVidCtl object when a user clicks anywhere on the video rectangle.
ContentBecomingStale | Called when the stream buffer source lags behind the stream buffer sink.
DblClick | Called by the MSVidCtl object when a user double-clicks on the video rectangle.
EndOfMedia | Called by a file playback device when it reaches the end of the source file.
Error | Called by the MSVidCtl object when an error occurs in the Video Control or in the underlying filter graph. Currently, no errors are defined for this event.
KeyDown | Called by the MSVidCtl object when the user presses a key.
KeyPress | Called by the MSVidCtl object when the user presses and releases a key.
KeyUp | Called by the MSVidCtl object when the user releases a key.
MouseDown | Called by the MSVidCtl object when the user presses the left mouse key down while the mouse pointer is over the Video Control.
MouseMove | Called by the MSVidCtl object when the user moves the mouse pointer over the Video Control.
MouseUp | Called by the MSVidCtl object when the user releases the left mouse button while the mouse pointer is over the Video Control.
OverlayUnavailable | Called when the hardware overlay surface is unavailable.
RatingsBlocked | Called when the object blocks playback.
RatingsChanged | Called when the content rating changes.
RatingsUnblocked | Called when the object unblocks playback.
StaleDataRead | Called when the source object reads from a temporary recording file that has been marked for deletion.
StaleFileDeleted | Called when a temporary recording file is deleted.
StateChange (MSVidCtl) | Called by the Video Control when the state of the control changes.
StateChange (IMSVidDevice) | Called by a device object when the state of the device changes.
TimeHole | Called when playback reaches a gap in the recorded content.
TuneChanged | Called by the currently active tuner device when it cannot tune to the requested channel or frequency.

See Also

  • MSVidWebDVD Events


CertificateFailure Event

This topic applies to Windows XP Service Pack 1 only.

The CertificateFailure event is fired when the object fails to get an encryption/decription license.

Syntax

object_CertificateFailure()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


CertificateSuccess Event

This topic applies to Windows XP Service Pack 1 only.

The CertificateSuccess event is fired when the object succeeds in getting an encryption/decription license. The event is firest only if an earlier failure occurred.

Syntax

object_CertificateSuccess()

Parameters

This event takes no parameters.

Return Values

No return value.

See Also

  • Video Control Events


Click Event

This topic applies to Windows XP only.

The Click event is called by the MSVidCtl object when a user clicks anywhere in the MSVidCtl rectangle.

Syntax

object_Click()

Parameters

This method takes no parameters.

See Also

  • Video Control Events


ContentBecomingStale Event

This topic applies to Windows XP Service Pack 1 only.

The ContentBecomingStale event is fired when the stream buffer source lags behind the stream buffer sink by more than a preset number of files.

Syntax

object_ContentBecomingStale()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


DblClick Event

This topic applies to Windows XP only.

The DblClick event is called by the MSVidCtl object when a user double-clicks on the MSVidCtl rectangle.

Syntax

object_DblClick()

Parameters

This method takes no parameters.

See Also

  • Video Control Events


EndOfMedia Event

This topic applies to Windows XP Service Pack 1 only.

The EndOfMedia event is called by a file playback device when it reaches the end of the source file.

Syntax

object_EndOfMedia(
    lpd As MSVidVideoPlaybackDevice
)

Parameters

lpd

Specifies the file playback device that sent this event.

See Also

  • MSVidFilePlaybackDevice Object
  • Video Control Events


Error Event

This topic applies to Windows XP only.

The Error event is called by the MSVidCtl object when an error occurs in the Video Control or in the underlying filter graph. Currently no errors are defined for this event.

Syntax

object_Error(
  Number As Integer,
  Description As String,
  SCode As Long,
  Source As String,
  HelpFile As String,
  HelpContext As String,
  CancelDisplay As <Unsupported variant type>)

Parameters

Number

Specifies the error number.

Description

Contains a description of the error.

SCode

Specifies the S code for this error.

Source

Specifies the source of the error.

HelpFile

Specifies the Help file associated with the error.

HelpContext

Specifies Help context associated with the error.

CancelDisplay

Specifies whether the display should be cancelled.

See Also

  • Video Control Events


KeyDown Event

This topic applies to Windows XP only.

The KeyDown event is called by the MSVidCtl object when the user presses a key.

Syntax

object_KeyDown(
    KeyCode As Integer,
    Shift As Integer)

Parameters

KeyCode

Specifies the key that was pressed.

Shift

Specifies whether the shift, control or ALT keys were pressed at the time the event was sent. See Remarks.

Remarks

The Shift parameter may have the following values:

Value | Meaning
1 | The Shift key was pressed.
2 | The Ctrl key was pressed.
4 | The ALT key was pressed.

See Also

  • Video Control Events


KeyPress Event

This topic applies to Windows XP only.

The KeyPress event is called by the MSVidCtl object when the user presses and releases a key.

Syntax

object_KeyPress(
    KeyAscii As Integer)

Parameters

KeyAscii

Specifies the ASCII code of the key that was pressed as an integer subtype.

See Also

  • Video Control Events


KeyUp Event

This topic applies to Windows XP only.

The KeyUp event is called by the MSVidCtl object when the user releases a key.

Syntax

object_KeyUp(
    KeyCode As Integer,
    Shift As Integer)

Parameters

KeyCode

Specifies the key code.

Shift

Specifies whether the Shift, Ctrl or ALT keys were pressed.

Remarks

The Shift parameter may have the following values:

Value | Meaning
1 | The Shift key was pressed.
2 | The Ctrl key was pressed.
4 | The ALT key was pressed.

See Also

  • Video Control Events


MouseDown Event

This topic applies to Windows XP only.

The MouseDown event is called by the MSVidCtl object when the user presses the left mouse key down while the mouse pointer is over the Video Control.

Syntax

object_MouseDown(
    Button As Integer,
    Shift As Integer,
    x As Single,
    y As Single)

Parameters

Button

Specifies the mouse button that was pressed.

Shift

Specifies whether the shift key was pressed.

x

Specifies the x-position in pixels within the Video Control rectangle at the time the mouse button was pressed.

y

Specifies the y-position in pixels within the Video Control rectangle at the time the mouse button was pressed.

Remarks

See the KeyDown event for possible values for Shift. The following table lists the possible values for Button:

Value | Meaning
1 | The left button was pressed.
2 | The right button was pressed.
4 | The middle button was pressed.
8 | The X button 1 was pressed.
10 | The X button 2 was pressed.

See Also

  • MouseMove
  • Video Control Events


MouseMove Event

This topic applies to Windows XP only.

The MouseMove event is called by the MSVidCtl object when the user moves the mouse pointer over the Video Control.

Syntax

object_MouseMove(
    Button As Integer,
    Shift As Integer,
    x As Single,
    y As Single)

Parameters

Button

Specifies the mouse button, if any, that was pressed when the mouse move occurred.

Shift

Specifies whether the shift key was pressed.

x

Specifies the x-position in pixels at the time the event was fired.

y

Specifies the y-position in pixels at the time the event was fired.

Remarks

See the KeyDown event for possible values for Shift. See the MouseDown event for the possible values of Button.

See Also

  • MouseDown
  • Video Control Events


MouseUp Event

This topic applies to Windows XP only.

The MouseUp event is called by the MSVidCtl object when the user releases the left mouse button while the mouse pointer is over the Video Control.

Syntax

object_MouseUp(
    Button As Integer,
    Shift As Integer,
    x As Single,
    y As Single)

Parameters

Button

Specifies the mouse button that was released.

Shift

Specifies whether the shift key was pressed when the button was released.

x

Specifies the x-position in pixels at the time the event was fired.

y

Specifies the y-position in pixels at the time the event was fired.

Remarks

See the KeyDown event for possible values for Shift. See the MouseDown event for the possible values of Button.

See Also

  • Video Control Events


OverlayUnavailable Event

This topic applies to Windows XP only.

The OverlayUnavailable event is called when the hardware overlay surface is unavailable.

Syntax

object_OverlayUnavailable()

Parameters

This method has no parameters.

Remarks

This event can indicate either that the hardware overlay surface is in use by another application, or that it is not present.

See Also

  • Video Control Events


RatingsBlocked Event

This topic applies to Windows XP Service Pack 1 only.

The RatingsBlocked event is fired when the object blocks playback, which occurs if the rating is not allowed under the current permissions.

Syntax

object_RatingsBlocked()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


RatingsChanged Event

This topic applies to Windows XP Service Pack 1 only.

The RatingsChanged event is fired when the content rating changes.

Syntax

object_RatingsChanged()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


RatingsUnblocked Event

This topic applies to Windows XP Service Pack 1 only.

The RatingsUnblocked event is fired when the object unblocks playback. This event occurs only if the stream was previously blocked and then is unblocked.

Syntax

object_.RatingsUnblocked()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


StaleDataRead Event

This topic applies to Windows XP Service Pack 1 only.

The StaleDataRead event is fired when the source object reads from a temporary recording file that has been marked for deletion.

Syntax

object_StaleDataRead()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


StaleFileDeleted Event

This topic applies to Windows XP Service Pack 1 only.

The StaleFileDeleted event is fired when a temporary recording file is deleted.

Syntax

object_StaleFileDeleted()

Parameters

This event takes no parameters.

See Also

  • Video Control Events


StateChange Event (IMSVidDevice)

This topic applies to Windows XP only.

The StateChange for a device object event is called by any input device or rendering device object when the state of the device changes.

Syntax

object_StateChange(
    lpd As MSVidDevice,
    OldState As Long,
    NewState As Long)

Parameters

lpd

Specifies the IMSVidDevice object that sent the event.

OldState

Identifies the previous state of the device.

NewState

Identifies the new state.

Remarks

This event is analogous to the DirectShow EC_COMPLETE event. You will need to implement a separate event handler in your application for each device type. OldState and NewState can have one of the values shown in the following table.

Value | Description
1 | The device is not part of a filter graph.
2 | The device is stopped.
3 | The device is paused.
4 | The device is playing.

See Also

  • Video Control Events


StateChange Event (MSVidCtl)

This topic applies to Windows XP only.

The StateChange event is called by the MSVidCtl object when the state of the Video Control changes.

Syntax

object_StateChange(
    PrevState As Long,
    NewState As Long)

Parameters

PrevState

Identifies the previous state of the Video Control.

NewState

Identifies the new state of the Video Control.

Remarks

Possible values for PrevState and NewState are shown in the following table.

Value | Description
1 | The Video Control has not created a filter graph.
2 | The Video Control is stopped.
3 | The Video Control is paused.
4 | The Video Control is playing.

This event is analogous to the DirectShow EC_COMPLETE event. You will need to implement a separate event handler in your application for each device type.

See Also

  • Video Control Events


TimeHole Event

This topic applies to Windows XP Service Pack 1 only.

The TimeHole event is fired when playback reaches a gap in the recorded content.

Syntax

object_TimeHole(
    StreamOffsetMS As Long
    SizeMS As Long
)

Parameters

StreamOffsetMS

Specifies the start of the gap, in milliseconds, relative to the content start.

SizeMS

Specifies the length of the gap, in milliseconds.

See Also

  • Video Control Events


TuneChanged Event

This topic applies to Windows XP only.

The TuneChanged event is called by the tuner device when it cannot tune to the requested channel or frequency.

Syntax

object_TuneChanged(
    lpd As MSVidBDATunerDevice
)

Parameters

lpd

Specifies the tuner device as an MSVidBDATunerDevice object.

See Also

  • Video Control Events


MSVidWebDVD Events

This topic applies to Windows XP Service Pack 1 only.

The MSVidWebDVD object has various events associated with it. These events come in two types: those sent when a disc capability is disabled or enabled (Author-programmed events), and those sent by the filter graph manager, such as a domain change (Filter Graph events). Filter graph events are passed through the DVDNotify event.

All events are channeled through the MSVidCtl object and must be captured by subroutines in the code associated with the form hosting the Video Control.

Note The MSVidWebDVD object must be declared using the WithEvents keyword if you wish to capture these events. This alerts Visual Basic that the MSVidWebDVD is exposing custom events.

Author-programmed events

Author-programmed events are events that the DVD author has programmed into the disc, usually enabling or disabling navigation features, such as pause, play chapter, or play title. These events can be used to enable or disable form controls appropriately. These events can be handled without further parsing as a subroutine declared in the following style:

Private Sub MSVidWebDVDobjectname_Eventname([ByVal parameters])

The following code demonstrates disabling a form pause button when the DVD author has disabled pause capability:

' Note: You must declare MSVidWebDVD using WithEvents to
'      capture all sent events.
Dim WithEvents oDVDPlayer as MSVidWebDVD
Private Sub oDVDPlayer_PauseOn(ByVal bEnabled As Boolean)
   ' Enable or disable Pause button.
   cmdPause.Enabled = bEnabled
End Sub

Note The MSVidWebDVD object must be declared using the WithEvents keyword if you wish to capture these events. This alerts Visual Basic that the MSVidWebDVD is exposing custom events.

Event parameters are sent by value, and must be written in exactly the same way as declared in the event definition, although the parameter names may be changed. An easy way to create event-capturing subroutines in the Microsoft® Visual Basic® development environment is to select the local name of the MSVidWebDVD object in the Object drop-down menu on the left, then choose the event name in the Procedure drop-down menu on the right. If the event does not already have a handling subroutine, one will be created for you with the proper name and parameters.

Filter graph events

Filter graph events typically concern playback or domain changes, such as angle changes, disc ejection, or playback stop, and are sent to the DVDNotify event. These can be used as notifications to refresh chapter or title lists, among other uses. The disc or DVD Navigator filter may send events at counterintuitive times, during setup, for example, so be sure to know when a disc sends particular messages before relying on them in your application.

These events are sent as integer values to the DVDNotify event, and require the message to be parsed before handling. The message is typically handled with If...Then or Case statements, similar to the way Windows messages are handled. A DVDNotify event code is accompanied by two parameters that may contain additional information about the event. The following code shows how some DVDNotify events might be handled:

Private Sub oVidWebDVD_DVDNotify(ByVal lEventCode As Long, _
            ByVal lParam1 As Variant, ByVal lParam2 As Variant)
Select Case lEventCode
    ' If in the FBI warning domain, disable inappropriate buttons.
    Case EC_DVD_DOMAIN_CHANGE
        If lParam1 = DVD_DOMAIN_FirstPlay Then
           cmdPause.Enabled = False
           cmdFastForward.Enabled = False
        End If
    Case EC_DVD_PARENTAL_LEVEL_CHANGE
        If lParam1 < oVidWebDVD.PlayerParentalLevel Then
           'Handle forbidden player level...
        End If
    'Handle other cases...
End Select

Note Event code constants must be assigned manually. See Handling DVD Event Notifications for a list of event code values.

Event | Description
ChangeCurrentAngle | Sent when the disc enables or disables changing the angle.
ChangeCurrentAudioStream | Sent when the disc enables or disables changing the audio stream.
ChangeCurrentSubpictureStream | Sent when the disc enables or disables changing the subpicture stream.
ChangeKaraokePresMode | Sent when the disc enables or disables changing the karaoke presentation mode.
ChangeVideoPresMode | Sent when the disc enables or disables changing the video presentation mode.
DVDNotify | Notifies an application of many different DVD events and disc instructions.
PauseOn | Sent when the Pause command has been enabled or disabled. Ignored by MSVidCtl.
PlayAtTime | Sent when the PlayAtTime command has been enabled or disabled.
PlayAtTimeInTitle | Sent when the PlayAtTimeInTitle command has been enabled or disabled.
PlayBackwards | Sent when the disc enables or disables play in a backward direction.
PlayChapter | Sent when the PlayChapter command has been enabled or disabled.
PlayChapterInTitle | Sent when the PlayChapterInTitle command has been enabled or disabled.
PlayForwards | Sent when the disc enables or disables play in a forward direction.
PlayNextChapter | Sent when the PlayNextChapter command has been enabled or disabled.
PlayPrevChapter | Sent when the PlayPrevChapter command has been enabled or disabled.
PlayTitle | Sent when the PlayTitle command has been enabled or disabled.
ReplayChapter | Sent when the ReplayChapter command has been enabled or disabled.
Resume | Sent when the Resume command has been enabled or disabled.
ReturnFromSubmenu | Sent when the ReturnFromSubmenu command has been enabled or disabled.
SelectOrActivateButton | Sent when the disc enables or disables the selection or activation of a menu button.
ShowMenu | Sent when the disc enables or disables the showing of a menu.
StillOff | Sent when the StillOff command has been enabled or disabled.
Stop | Sent when the Stop command has been enabled or disabled. Ignored by MSVidCtl.

See Also

  • DVD Event Notification Codes
  • Handling DVD Event Notifications
  • MSVidWebDVD Object
  • MSVidWebDVDAdm Object
  • UOPValid method


MSVidWebDVDEvent.ChangeCurrentAngle Event

This topic applies to Windows XP Service Pack 1 only.

The ChangeCurrentAngle event is sent when the disc enables or disables changing the angle.

Syntax

VidWebDVD_ChangeCurrentAngle(
  byVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating whether the user can (True) or can't (False) change the current angle.

Remarks

The command to allow or prevent angle changes is encoded into the disc by its producers.

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.ChangeCurrentAudioStream Event

This topic applies to Windows XP Service Pack 1 only.

The ChangeCurrentAudioStream event is sent when the disc enables or disables changing the current audio stream.

Syntax

VidWebDVD_ChangeCurrentAudioStream(
  byVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the user can (True) or can't (False) change the current audio stream.

Remarks

The command to enable or disable audio stream changes is encoded in the disc by its producers.

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.ChangeCurrentSubpictureStream Event

This topic applies to Windows XP Service Pack 1 only.

The ChangeCurrentSubpictureStream event is sent when the disc enables or disables changing the subpicture stream.

Syntax

VidWebDVD_ChangeCurrentSubpictureStream(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the user can (True) or can't (False) change the current subpicture stream.

Remarks

The command to enable or disable audio stream changes is encoded in the disc by its producers.

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.ChangeKaraokePresMode Event

This topic applies to Windows XP Service Pack 1 only.

The ChangeKaraokePresMode method is sent when the disc enables or disables the ability to change karaoke audio presentation mode.

Syntax

VidWebDVD_ChangeKaraokePresMode(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the user can (True) or can't (False) change the current karaoke presentation mode.

Return Values

This method does not return a value.

Example

Private Sub oVidWebDVD_ChangeKaraokePresMode(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • KaraokeAudioPresentationMode
  • MSVidWebDVD Events


MSVidWebDVDEvent.ChangeVideoPresMode Event

This topic applies to Windows XP Service Pack 1 only.

The ChangeVideoPresMode method is sent when the disc enables or disables the ability to change video presentation mode.

Syntax

VidWebDVD_ChangeVideoPresMode(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the user can (True) or can't (False) change the current video presentation mode.

Return Values

This method does not return a value.

Example

Private Sub oVidWebDVD_ChangeVideoPresMode(bEnabled)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.DVDNotify Event

This topic applies to Windows XP Service Pack 1 only.

The DVDNotify event notifies an application of many different DVD events and disc instructions.

Syntax

VidWebDVD_DVDNotify(
  ByVal lEventCode As Long,
  ByVal lParam1 As Variant,
  ByVal lParam2 As Variant
)

Parameters

lEventCode

Long containing the event code.

lParam1

Long that can contain additional information for this event.

lParam2

Long that can contain additional information for this event.

Return Values

This method does not return a value.

Remarks

The DVD Navigator filter and other filters in the filter graph send a variety of notification codes about the state of the disc and the file that can be captured with this event. These codes are often accompanied by parameters that hold additional information. See DVD Event Notification Codes for more information about the event codes and their parameters.

A good use of this feature is to capture domain changes to disable unavailable features for the new domain. If using this method, be aware that the DVD does not send a domain change method on startup.

Example

Private Sub oVidWebDVD_DVDNotify(ByVal lEventCode As Long, ByVal lParam1 As Variant, ByVal lParam2 As Variant)
Select Case lEventCode
    Case 280   ' EC_DVD_DISC_EJECTED.
        MsgBox "Disc ejected!"
    Case 257   ' EC_DVD_DOMAIN_CHANGE.
        Select Case lParam1
            Case 1
                ' First play domain.
            Case 2
                ' Video manager set domain.
            Case 3
                ' Video title set domain.
            Case 4
                ' Title domain.
            Case 5
                ' Stop domain.
        End Select
    ' Handle other messages...
End Select
End Sub

See Also

  • DVD Event Notification Codes
  • Handling DVD Event Notifications
  • MSVidWebDVD Events


MSVidWebDVDEvent.PauseOn Event

This topic applies to Windows XP Service Pack 1 only.

The PauseOn event is sent when the Pause method is enabled or disabled.

Syntax

VidWebDVD_PauseOn(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) pause playback.

Remarks

The Pause command should only be sent to the MSVidCtl object, not the MSVidWebDVD object. The MSVidCtl can pause playback regardless of the disc commands.

Example

Private Sub oVidWebDVD_PauseOn(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.PlayAtTime Event

This topic applies to Windows XP Service Pack 1 only.

The PlayAtTime event is sent when the PlayAtTime method is enabled or disabled.

Syntax

VidWebDVD_PlayAtTime(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayAtTime method.

Example

Private Sub oVidWebDVD_PlayAtTime(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • PlayAtTime


MSVidWebDVDEvent.PlayAtTimeInTitle Event

This topic applies to Windows XP Service Pack 1 only.

The PlayAtTimeInTitle event is sent when the PlayAtTimeInTitle method is enabled or disabled.

Syntax

VidWebDVD_PlayAtTimeInTitle(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayAtTimeInTitle method.

Example

Private Sub oVidWebDVD_PlayAtTimeInTitle(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • PlayAtTime


MSVidWebDVDEvent.PlayBackwards Event

This topic applies to Windows XP Service Pack 1 only.

The PlayBackwards event is sent when the disc enables or disables play in a backward direction.

Syntax

VidWebDVD_PlayBackwards(
  ByVal bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) play in a backward direction.

Example

Private Sub oVidWebDVD_PlayBackwards(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.PlayChapter Event

This topic applies to Windows XP Service Pack 1 only.

The PlayChapter event is sent when the PlayChapter method is enabled or disabled.

Syntax

VidWebDVD_PlayChapter(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayChapter method.

Example

Private Sub oVidWebDVD_PlayChapter(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • PlayChapterInTitle
  • PlayNextChapter
  • PlayPrevChapter


MSVidWebDVDEvent.PlayChapterInTitle Event

This topic applies to Windows XP Service Pack 1 only.

The PlayChapterInTitle event is sent when the PlayChapterInTitle method is enabled or disabled.

Syntax

VidWebDVD_PlayChapterInTitle(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayChapterInTitle method.

Example

Private Sub oVidWebDVD_PlayChapterInTitle(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.PlayForwards Event

This topic applies to Windows XP Service Pack 1 only.

The PlayForwards event is sent when the disc enables or disables play in a forward direction.

Syntax

VidWebDVD_PlayForwards(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayForwards method.

Example

Private Sub oVidWebDVD_PlayForwards(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.PlayNextChapter Event

This topic applies to Windows XP Service Pack 1 only.

The PlayNextChapter event is sent when the PlayNextChapter event is enabled or disabled.

Syntax

VidWebDVD_PlayNextChapter(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayNextChapter method.

Example

Private Sub oVidWebDVD_PlayNextChapter(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • PlayChapter
  • PlayPrevChapter


MSVidWebDVDEvent.PlayPrevChapter Event

This topic applies to Windows XP Service Pack 1 only.

The PlayPrevChapter event is sent when the PlayPrevChapter event is enabled or disabled.

Syntax

VidWebDVD_PlayPrevChapter(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayPrevChapter method.

Example

Private Sub oVidWebDVD_PlayPrevChapter(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • PlayChapter
  • PlayNextChapter


MSVidWebDVDEvent.PlayTitle Event

This topic applies to Windows XP Service Pack 1 only.

The PlayTitle event is sent when the PlayTitle method is enabled or disabled.

Syntax

VidWebDVD_PlayTitle(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the PlayTitle method.

Example

Private Sub oVidWebDVD_PlayTitle(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.ReplayChapter Event

This topic applies to Windows XP Service Pack 1 only.

The ReplayChapter event is sent when the ReplayChapter event is enabled or disabled.

Syntax

VidWebDVD_ReplayChapter(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the ReplayChapter method.

Example

Private Sub oVidWebDVD_ReplayChapter(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.Resume Event

This topic applies to Windows XP Service Pack 1 only.

The Resume event is sent when the Resume method is enabled or disabled.

Syntax

VidWebDVD_Resume(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the Resume method.

Example

Private Sub oVidWebDVD_Resume(ByVal bEnabled As Boolean)

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.ReturnFromSubmenu Event

This topic applies to Windows XP Service Pack 1 only.

The ReturnFromSubmenu event is sent whenever the ReturnFromSubmenu method is enabled or disabled.

Syntax

VidWebDVD_ReturnFromSubmenu(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the ReturnFromSubmenu method.

Example

Private Sub oVidWebDVD_ReturnFromSubmenu(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.SelectOrActivateButton Event

This topic applies to Windows XP Service Pack 1 only.

The SelectOrActivateButton event is sent whenever the disc deactivates the selection or activation of menu buttons.

Syntax

VidWebDVD_SelectOrActivateButton(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) select or activate buttons.

Example

Private Sub oVidWebDVD_SelectOrActivateButton(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • ActivateButton
  • MSVidWebDVD Events
  • SelectAndActivateButton
  • SelectAtPosition


MSVidWebDVDEvent.ShowMenu Event

This topic applies to Windows XP Service Pack 1 only.

The ShowMenu event is sent whenever the disc enables or disables the showing of a menu.

Syntax

VidWebDVD_ShowMenu(
  lMenu As DVDMenuIDConstant
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) show the selected menu.

lMenu

Long, represented by a constant, indicating the type of menu disabled or enabled. Menu types are represented in the following table.

Constant | Value | Menu
dvdMenu_Title | 2 | Title
dvdMenu_Root | 3 | Root
dvdMenu_Subpicture | 4 | Subpicture
dvdMenu_Audio | 5 | Audio
dvdMenu_Angle | 6 | Angle
dvdMenu_Chapter | 7 | Chapter

Example

Private Sub oVidWebDVD_ShowMenu(ByVal lMenu As Long, DVDByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


MSVidWebDVDEvent.StillOff Event

This topic applies to Windows XP Service Pack 1 only.

The StillOff event is sent when the StillOff method is enabled or disabled.

Syntax

VidWebDVD_StillOff(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the StillOff method.

Example

Private Sub oVidWebDVD_StillOff(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events
  • StillOff


MSVidWebDVDEvent.Stop Event

This topic applies to Windows XP Service Pack 1 only.

The Stop event is sent when the Stop method is enabled or disabled.

Syntax

VidWebDVD_Stop(
  bEnabled As Boolean
)

Parameters

bEnabled

Boolean value indicating that the application can (True) or can't (False) use the Stop method.

Remarks

The Stop method should only be called on the MSVidCtl object, not on the MSVidWebDVD object. The MSVidCtl can stop playback regardless of the disc commands.

Example

Private Sub oVidWebDVD_Stop(ByVal bEnabled As Boolean)
'...
End Sub

See Also

  • MSVidWebDVD Events


Video Control Constants

This topic applies to Windows XP only.

This section lists the constant values used by the Video Control

Constant | Description
DisplaySizeList | These constants define the size of the video rectangle.
DVDSPExt | These constants indicate the default DVD subpicture language extension.
DVDTextStringType | These constants indicate the type of information contained in a DVD text string.
DVDMenuID | These constants define menu type ID numbers used to display specific menus.
MSVidCCService | These constants define closed captioning services.
MSVidCtlStateList | These constants define the possible filter graph states.
SourceSizeList | These constants define how the Video Mixing Renderer (VMR) clips the source video rectangle.


DisplaySizeList Constants

This topic applies to Windows XP only.

These constants define the size of the video rectangle, relative either to the native video or to the display.

Constant | Value | Description
dslDefaultSize | 0 | Display the video rectangle at the native size.
dslSourceSize | 0 | Same as dslDefaultSize.
dslHalfSourceSize | 1 | Shrink the width and height of the native video by half.
dslDoubleSourceSize | 2 | Stretch the width and height of the native video by a factor of two
dslFullScreen | 3 | Stretch the video to fill the screen while maintaining the original aspect ratio.
dslHalfScreen | 4 | Stretch the video to fill 50% of the screen while maintaining the original aspect ratio.
dslQuarterScreen | 5 | Stretch the video to fill 25% of the screen while maintaining the original aspect ratio.
dslSixteenthScreen | 6 | Stretch the video to fill 6.25% of the screen while maintaining the original aspect ratio.

See Also

  • MSVidCtl.DisplaySize
  • Video Control Constants


DVDSPExt Constants

This topic applies to Windows XP Service Pack 1 only.

The DVDSPExt constants indicate the default DVD subpicture language extension.

Constant | Value | Description
dvdSPExt_NotSpecified | 0 | Extension not specified.
dvdSPExt_Caption_Normal | 1 | Normal caption size.
dvdSPExt_Caption_Big | 2 | Big captions.
dvdSPExt_Caption_Children | 3 | Children's captions.
dvdSPExt_CC_Normal | 5 | Normal-sized closed captions.
dvdSPExt_CC_Big | 6 | Big closed captions.
dvdSPExt_CC_Children | 7 | Children's closed captions.
dvdSPExt_Forced | 9 | Forced.
dvdSPExt_DirectorComments_Normal | 13 | Normal-sized director's comments.
dvdSPExt_DirectorComments_Big | 14 | Big director's comments.
dvdSPExt_DirectorComments_Big | 15 | Director's comments for children.

Remarks

For more information on when and how to retrieve this property, see the following links.

See Also

  • DefaultSubpictureLanguageExt (to retrieve the value)
  • SelectDefaultSubpictureLanguage (to set the value)
  • Video Control Constants


DVDTextStringType Constants

This topic applies to Windows XP Service Pack 1 only.

The DVDTextStringType constants indicate the type of information contained in a DVD text string.

Constant | Value | Description
dvdStruct_Volume | 1 | Indicates the top-level of the logical hierarchy. Refers to the entire contents of a one-sided disc or one side of a two-sided disc.
dvdStruct_Title | 2 | Indicates that all content strings, until the next dvd_Struct_Title, belong to one title.
dvdStruct_ParentalID | 3 | Indicates the parental ID of the following strings.
dvdStruct_PartOfTitle | 4 | Indicates that all content strings, until the next dvd_Struct_PartOfTitle, belong to one chapter.
dvdStruct_Cell | 5 | Indicates that all content strings, until the next dvd_Struct_Cell, belong to one cell, which can be a scene from a chapter.
dvdStream_Audio | 16 | Indicates that the following content strings refer to the audio stream.
dvdStream_Subpicture | 17 | Indicates that the following content strings refer to the subpicture stream.
dvdStream_Angle | 18 | Indicates that the following content strings refer to the angle.
dvdChannel_Audio | 32 | Indicates that the following content strings refer to the audio channel.
dvdGeneral_Name | 48 | Indicates the most important content string. Strings of this type contain the name of the volume, title, chapter, and so on, and can follow any structure identifiers.
dvdGeneral_Comments | 49 | Identifies a content string with additional information about the title, chapter, and so on, described by the dvd_General_Name string. The exact nature or structure of these comments is not defined.
dvdTitle_Series | 56 | Identifies a content string containing the name of a series to which the title belongs.
dvdTitle_Movie | 57 | Identifies a content string with the main movie title.
dvdTitle_Video | 58 | Identifies a content string containing the name of the video title.
dvdTitle_Album | 59 | Identifies a content string containing the name of the album title.
dvdTitle_Song | 60 | Identifies a content string containing the name of the song title.
dvdTitle_Other | 63 | Identifies a content string containing the name of the title of some other genre.
dvdTitle_Sub_Series | 64 | Identifies a content string with the name of the series localized to a particular country/region.
dvdTitle_Sub_Movie | 65 | Identifies a content string with the movie title localized to a particular country/region.
dvdTitle_Sub_Video | 66 | Identifies a content string with the video title localized to a particular country/region.
dvdTitle_Sub_Album | 67 | Identifies a content string with the album title localized to a particular country/region.
dvdTitle_Sub_Song | 68 | Identifies a content string with the song title localized to a particular country/region.
dvdTitle_Sub_Other | 71 | Identifies a content string with the title of some other genre localized to a particular country/region.
dvdTitle_Orig_Series | 72 | Identifies a content string with the original name of the series.
dvdTitle_Orig_Movie | 73 | Identifies a content string with the original name of the movie.
dvdTitle_Orig_Video | 74 | Identifies a content string with the original name of the video.
dvdTitle_Orig_Album | 75 | Identifies a content string with the original name of the album.
dvdTitle_Orig_Song | 76 | Identifies a content string with the original name of the song.
dvdTitle_Orig_Other | 79 | Identifies a content string with the original name of the content.
dvdOther_Scene | 80 | Identifies a content string pertaining to a particular scene in a movie or video.
dvdOther_Cut | 81 | Identifies a content string pertaining to a particular cut in a movie or video.
dvdOther_Take | 82 | Identifies a content string pertaining to a particular take in a movie or video.

Remarks

A DVD_TextStringType is returned in the DVDTextStringType method to identify how the disc authors have categorized the specified text string. See Working with DVD Text Strings for general information on text strings.

One important text string type not defined in this enumeration is 0xF0, the extension sorting text string type. You can use this type of string in many ways to enable players to sort the string data. It can be a unique number or a repetition of a previous string with the word order changed. For example, a string type of 0x30 that has the name "The Greatest Hits" might be followed by a string of type 0xF0 that says "Greatest Hits, The." As with content strings, the use of the sorting string is not strictly defined.

See Also

  • DVDTextStringType
  • Video Control Constants
  • Working with DVD Text Strings


DVDMenuID Constants

This topic applies to Windows XP Service Pack 1 only.

The DVDMenuID constants define menu type ID numbers used to display specific menus.

Constant | Value | Description
dvdMenu_Title | 2 | Title menu, also called the Video Manager Menu.
dvdMenu_Root | 3 | Root menu, the menu for one video title set, which can contain one title or a group of titles.
dvdMenu_Subpicture | 4 | Subpicture menu.
dvdMenu_Audio | 5 | Audio menu.
dvdMenu_Angle | 6 | Angle menu.
dvdMenu_Chapter | 7 | Chapter menu.

Remarks

All the titles in a title set share the same Subpicture, Audio, Angle, and Chapter menus.

See Also

  • ShowMenu
  • Video Control Constants


MSVidCCService Constants

This topic applies to Windows XP Service Pack 1 only.

These constants define closed captioning services.

Constant | Value | Description
None | 0 | No current service
Caption1 | 1 | CC1 (caption channel)
Caption2 | 2 | CC2 (caption channel)
Text1 | 3 | T1 (text channel)
Text2 | 4 | T2 (text channel)
XDS | 5 | Extended data services (XDS or EDS)

See Also

  • Video Control Constants


MSVidCtlStateList Constants

This topic applies to Windows XP only.

These constants define the possible filter graph states.

Constant | Value | Description
STATE_UNBUILT | -1 | The filter graph is not yet built.
STATE_STOP | 0 | The filter graph is stopped.
STATE_PAUSE | 1 | The filter graph is paused.
STATE_PLAY | 2 | The filter graph is running.

See Also

  • MSVidCtl.State
  • Video Control Constants


SourceSizeList Constants

This topic applies to Windows XP only.

These constants define how the Video Mixing Renderer (VMR) clips the source video rectangle.

Constant | Value | Description
sslFullSize | 0 | Do not clip the source video rectangle.
sslClipByOverScan | 1 | Clip the source video rectangle as specified by the MSVidVideoRenderer.OverScan property.
sslClipByClipRect | 2 | Clip the source video rectangle as specified by the MSVidVideoRenderer.ClippedSourceRect property.

See Also

  • MSVidVideoRenderer.SourceSize
  • Video Control Constants


Microsoft Unified Tuning Model Visual Basic Reference

This section documents the Microsoft® Unified Tuning Model Automation objects. These objects are primarily used when applications are creating their own tune requests. No events are defined for the tuning model objects. Constants are not yet documented for the Automation objects in this release. See the corresponding C++ documentation for information on enumerations and constants.

  • Microsoft Unified Tuning Model Objects (Visual Basic)
  • Microsoft Unified Tuning Model Constants (Visual Basic)

SeeAlso

  • The Microsoft Unified Tuning Model


Microsoft Unified Tuning Model Objects (Visual Basic)

These objects are used primarily by a guide store loader to create tune requests for storage in an EPG database (guide store), and by applications that install custom tuning spaces on a system. You can use Visual Basic to write a loader that obtains EPG information from a source such as a Web page or network server, but loaders that obtain in-band EPG information from the BDA MPEG-2 Transport Information Filter must be written in C++. Visual Basic applications use these objects in the following scenarios to:

  • Create or modify a tune request dynamically.
  • Test the validity of a tuning space.
  • Create a default preferred components list that indicates user preferences for options such as the audio stream language.
  • Examine the components (such as audio substreams) available on a specified service.

For more information, see The Microsoft Unified Tuning Model.

Tuning Space Objects

Object | Description
AnalogRadioTuningSpace | Tuning space specific to terrestrial Radio networks. (Currently not implemented.)
AnalogTVTuningSpace | Represents a tuning space specific to analog TV networks.
ATSCTuningSpace | Represents a tuning space specific to ATSC networks.
AuxInTuningSpace | Represents a video auxiliary input, such as S-Video or composite video.
DVBSTuningSpace | Represents a tuning space for satellite DVB (DVBS) networks.
DVBTuningSpace | Represents a tuning space specific to DVB networks.
SystemTuningSpaces | Provides access to all tuning spaces installed on the host system.

Tune Request Objects

Tune requests are created through a call to CreateTuneRequest. Applications generally will not create their own tune requests, but will obtain them from the database. Applications in some circumstances will use the tune request to obtain access to the Locator or tuning space objects.

Object | Description
IChannelTuneRequest | Implemented on tune request objects specific to analog TV networks.
IATSCChannelTuneRequest | Implemented on tune request objects specific to ATSC TV networks.
IDVBTuneRequest | Implemented on tune request objects specific to DVB TV networks.

Stream Component Objects

A "component" in this context refers to a sub-stream within a broadcast. Applications use these objects to examine the available components in a program stream once reception has begun, and to activate or inactivate each component. For example, an application may switch from an English audio stream to a German audio stream.

Object | Description
IComponent | Base class for specific component objects.
ComponentType | Base class for specific component type objects.
ComponentTypes | Provides a standard COM enumeration of component types.
IComponents | Provides a standard COM enumeration of components.
LanguageComponentType | Component type associated with the language of the sub-stream.
MPEG2ComponentType | Implemented on a component type associated with an MPEG-2 stream type.
ATSCComponentType | Implemented on a component type that indicates whether the audio sub-stream is in AC-3 format.

Locator Objects

Locator objects are used in some cases by the Network Provider and other filters in the graph to locate a service and all its available components (substreams) within a specified network. Each tuning space should have a default locator that was installed with the tuning space. The Guide Store loader can also specify a locator when it creates a tune request. Applications generally should have no need to use these objects.

Object | Description
ILocator | Base class for all derived locators. Not used directly by applications.
ATSCLocator | Contains locator information about tuning in an ATSC network.
DVBTLocator | Contains locator information about tuning in a DVB-T network.
DVBSLocator | Contains locator information about tuning in a DVB-S network.


AnalogRadioTuningSpace Object

Not implemented in this release.

The AnalogRadioTuningSpace object represents an AM or FM analog radio tuning space.

Method or Property | Description
Clone | Creates a new copy of the object.
CLSID | The CLSID property retrieves the CLSID of the tuning space.
CreateTuneRequest | Creates an empty (uninitialized) IChannelTuneRequest object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default locator for this tuning space. (Not used for analog tuning spaces.)
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing the default preferred component types specified by the user or application. (Not used for analog tuning spaces.)
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
MaxFrequency | Sets or retrieves the highest frequency for this tuning space.
MinFrequency | Sets or retrieves the lowest frequency for this tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
Step | Sets or retrieves the step value to the next frequency.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


AnalogRadioTuningSpace.Clone

Not implemented in this release.

The Clone method creates a new copy of this AnalogRadioTuningSpace object.

Syntax

ObjAnalogRadioTuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new AnalogRadioTuningSpace object whose values are identical to the current AnalogRadioTuningSpace object.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.CLSID

Not implemented in this release.

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objAnalogRadioTuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only. The CLSID for this tuning space is "{8A674B4C-1F63-11d3-B64C-00C04F79498E}".

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.CreateTuneRequest

Not implemented in this release.

The CreateTuneRequest method creates an empty (uninitialized) Tune Request object specific to this tuning space.

Syntax

objAnalogRadioTuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns an ITuneRequest object as an Object.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.DefaultLocator

Not implemented in this release.

The DefaultLocator property sets or retrieves the initial default locator for this tuning space. (Not used for analog tuning spaces.)

Syntax

objAnalogRadioTuningSpace.DefaultLocator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Locator object as an Object.

Remarks

This property is read-write. See ATSCTuningSpace.DefaultLocator for more information about the default locator.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.DefaultPreferredComponentTypes

Not implemented in this release.

The DefaultPreferredComponentTypes property retrieves or creates a ComponentTypes collection object containing the default preferred component types specified by the user or application. (Not used for analog tuning spaces.)

Syntax

objAnalogRadioTuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the IComponents collection as an Object.

Remarks

This property is not used for analog tuning spaces.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.FriendlyName

Not implemented in this release.

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objAnalogRadioTuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • AnalogRadioTuningSpace Object


AnalogRadioTuningSpace.MaxFrequency

Not implemented in this release.

The MaxFrequency property sets or retrieves the highest frequency for this tuning space.

Syntax

objAnalogRadioTuningSpace.MaxFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum frequency, in kilohertz (kHz).

Remarks

This property is read-write.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.MinFrequency

Not implemented in this release.

The MinFrequency property sets or retrieves the lowest frequency of this tuning space.

Syntax

objAnalogRadioTuningSpace.MinFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the minimum frequency, in kilohertz (kHz).

Remarks

This property is read-write.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.NetworkType

Not implemented in this release.

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objAnalogRadioTuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.Step

Not implemented in this release.

The Step property sets or retrieves the step value to the next freequency.

Syntax

objAnalogRadioTuningSpace.Step As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the step value to the next frequency, in kilohertz (kHz).

Remarks

This property is read-write.

See Also

  • AnalogRadioTuningSpace


AnalogRadioTuningSpace.UniqueName

Not implemented in this release.

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objAnologRadioTuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • AnalogRadioTuningSpace


AnalogTVTuningSpace Object

The AnalogTVTuningSpace object represents an analog TV tuning space. See Default Tuning Spaces for the properties of the default analog TV tuning space.

Method or Property | Description
Clone | Creates a new copy of the object.
CLSID | Retrieves the CLSID of the tuning space.
CountryCode | Sets or retrieves the country/region code of the tuning space (based on TAPI country/region codes).
CreateTuneRequest | Creates an empty (uninitialized) Tune Request object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default locator on the local system for this tuning space. (Not used for analog tuning spaces.)
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing the default preferred component types specified by the user or application. (Not used for analog tuning spaces.)
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
InputType | Sets or retrieves the input type, such as antenna or cable, for the tuning space.
MaxChannel | Sets or retrieves the highest channel number for the tuning space.
MinChannel | Sets or retrieves the lowest channel number for the tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


AnalogTVTuningSpace.Clone

The Clone method creates a new copy of this AnalogTVTuningSpace object.

Syntax

objAnalogTVTuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new AnalogTVTuningSpace object whose values are identical to the current AnalogTVTuningSpace object.

See Also

AnalogTVTuningSpace


AnalogTVTuningSpace.CLSID

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objAnalogTVTuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only. The CLSID for this tuning space is "{8A674B4D-1F63-11D3-B64C-00C04F79498E}".

See Also

  • AnalogTVTuningSpace
  • Default Tuning Spaces


AnalogTVTuningSpace.CountryCode

The CountryCode property sets or retrieves the country/region code of the tuning space (based on TAPI country/region codes).

Syntax

objAnalogTVTuningSpace.CountryCode As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the country/region code as a Long integer.

Remarks

Uses TAPI country/region codes.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) ITuneRequest object specific to this tuning space.

Syntax

objAnalogTVTuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a Tune Request object as an Object.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.DefaultLocator

The DefaultLocator property sets or retrieves the initial default locator object on the local system, which the tuner may use after installation. (Not used for analog tuning spaces.)

Syntax

objAnalogTVTuningSpace.DefaultLocator As Object

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the locator object as an Object.

Remarks

This property is not used in analog tuning spaces.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.DefaultPreferredComponentTypes

This property is not used in the AnalogTVTuningSpace object, because analog broadcasts do not have components.

Syntax

objAnalogTVTuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the IComponents collection as an Object.

See Also

  • AnalogTVTuningSpace Object


AnalogTVTuningSpace.FriendlyName

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objAnalogTVTuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.InputType

The InputType property sets or retrieves the input type, such as antenna or cable, for the tuning space.

Syntax

objAnalogTVTuningSpace.InputType As TunerInputType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the input type as a TunerInputType Integer.

Remarks

This property is read-write.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.MaxChannel

The MaxChannel property sets or retrieves the highest channel number for the tuning space.

Syntax

objAnalogTVTuningSpace.MaxChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum channel number as an Integer.

Remarks

This property is read-write.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.MinChannel

The MinChannel property sets or retrieves the lowest channel number for the tuning space.

Syntax

objAnalogTVTuningSpace.MinChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the minimum channel number as an Integer.

Remarks

This property is read-write.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.NetworkType

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objAnalogTVTuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • AnalogTVTuningSpace


AnalogTVTuningSpace.UniqueName

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objAnalogTVTuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • AnalogTVTuningSpace


IATSCChannelTuneRequest Object

The IATSCChannelTuneRequest object represents a tune request valid for ATSC network types. Applications create IATSCChannelTuneRequest object using the ATSCTuningSpace.CreateTuneRequest method. See Default Tuning Spaces for the properties of the default ATSC TV tuning space.

Method or Property | Description
Channel | Retrieves or sets the channel to be viewed.
Clone | Creates a new copy of this IATSCChannelTuneRequest object.
Components | Retrieves the IComponents object collection for this IATSCChannelTuneRequest object.
Locator | Sets or retrieves the locator object associated with the requested broadcast.
MinorChannel | Sets or retrieves the minor channel number to be viewed.
TuningSpace | Retrieves the tuning space object


IATSCChannelTuneRequest.Channel

The Channel property retrieves or sets the channel to be viewed.

Syntax

objIATSCChannelTuneRequest.Channel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the channel number to be viewed as an Integer.

Remarks

If the value specified to assign the channel number is less than the minimum channel number set for the tuning space, the channel number to be viewed will be set to the maximum channel number for the tuning space. Likewise, if the channel number is greater than the maximum channel number set for the tuning space, the channel to be viewed will be set to the minimum channel number for the tuning space.

See Also

  • IATSCChannelTuneRequest Object


IATSCChannelTuneRequest.Clone

The Clone method creates a new copy of this IATSCChannelTuneRequest object.

Syntax

objIATSCChannelTuneRequest.Clone() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the cloned copy as an Object.

Return Value

Returns an IATSCChannelTuneRequest object that is a copy of the current object.

See Also

  • IATSCChannelTuneRequest Object


IATSCChannelTuneRequest.Components

The Components property retrieves the IComponents object collection for this IATSCChannelTuneRequest object.

Syntax

objIATSCChannelTuneRequest.Components As Components

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the IComponents collection as an Object

Remarks

This property is read-only. An empty collection is valid.

See Also

  • IATSCChannelTuneRequest Object


IATSCChannelTuneRequest.Locator

The Locator property sets or retrieves the locator object associated with the requested broadcast.

Syntax

objIATSCChannelTuneRequest.Locator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an ATSCLocator object as an Object.

See Also

  • IATSCChannelTuneRequest Object


IATSCChannelTuneRequest.MinorChannel

The MinorChannel property sets or retrieves the minor channel number to be viewed.

Syntax

objIATSCChannelTuneRequest.MinorChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the minor channel as an Integer.

Remarks

A channel, such as channel 10, may have minor channels, such as 10.1 and 10.2. The minor channel in this example is 1 or 2.

See Also

  • IATSCChannelTuneRequest Object


IATSCChannelTuneRequest.TuningSpace

The TuningSpace property retrieves the tuning space object for this IATSCChannelTuneRequest object.

Syntax

objIATSCChannelTuneRequest.TuningSpace As TuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ATSCTuningSpace object associated with the tune request as an Object.

Remarks

This property is read only.

See Also

  • IATSCChannelTuneRequest Object


ATSCComponentType Object

Represents an ATSC component type object.

Method or Property | Description
Category | Sets or retrieves the component category.
Clone | Create a copy of this component type.
Flags | Sets or retrieves a flag indicating whether or not the audio is in AC-3 format.
LangID | Language identifier for Substream Content Language.
MediaFormatType | Sets or retrieves the DirectShow media format type as a String.
MediaMajorType | Sets or retrieves the DirectShow media major type as a String.
MediaSubType | Sets or retrieves the DirectShow media subtype as a String.
StreamType | MPEG2 Stream Type.


ATSCComponentType.Category

The Category property sets or retrieves the category of the IComponent object that is associated with this ATSCComponentType object.

Syntax

objATSCComponentType.Category As ComponentCategory

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the category as a ComponentCategory Integer.

Remarks

This property is read-write.

See Also

  • ATSCComponentType Object


ATSCComponentType.Clone

The Clone method creates a new copy of this ATSCComponentType object.

Syntax

objATSCComponentType.Clone() As ComponentType

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new ATSCComponentType object whose values are identical to the current object.

See Also

  • ATSCComponentType Object


ATSCComponentType.Flags

The Flags property sets or retrieves miscellaneous ATSC component type properties.

Syntax

objATSCComponentType.Flags As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns 1 if the componet is an AC-3 audio stream, or zero otherwise.

Return Value

This property is read/write.

See Also

  • ATSCComponentType Object


ATSCComponentType.LangID

The LangID property sets or retrieves the language identifier for the stream content.

Syntax

objATSCComponentType.LangID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the language identifier as a Long integer.

See Also

  • ATSCComponentType Object


ATSCComponentType.MediaFormatType

The MediaFormatType property sets or retrieves the DirectShow AM_MEDIA_TYPE formattype member.

Syntax

objATSCComponentType.MediaFormatType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the formattype member as a String formatted as a GUID.

See Also

  • ATSCComponentType Object


ATSCComponentType.MediaMajorType

The MediaMajorType property sets or retrieves the DirectShow AM_MEDIA_TYPE majortype.

Syntax

objATSCComponentType.MediaMajorType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the majortype member as a String formatted as a GUID.

See Also

  • ATSCComponentType Object


ATSCComponentType.MediaSubType

The MediaSubType property sets or retrieves the DirectShow AM_MEDIA_TYPE subtype as a GUID.

Syntax

objATSCComponentType.MediaSubType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the subtype member as a String formatted as a GUID.

See Also

  • ATSCComponentType Object


ATSCComponentType.StreamType

The StreamType property sets or retrieves the stream type value.

Syntax

objATSCComponentType.StreamType As MPEG2StreamType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the stream type as an MPEG2StreamType constant.

Remarks

This property is read-write.

See Also

  • ATSCComponentType Object


ATSCLocator Object

An ATSCLocator object is a locator object for an ATSC network type.

Method or Property | Description
CarrierFrequency | Sets or retrieves the carrier frequency of the RF signal.
Clone | Creates a new copy of this ATSCLocator object.
InnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used.
InnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate.
Modulation | Sets or retrieves the modulation type.
OuterFEC | Sets or retrieves the type of outer forward error correction (FEC) that is used.
OuterFECRate | Sets or retrieves the outer forward error correction (FEC) rate.
PhysicalChannel | Sets or retrieves the physical channel.
SymbolRate | Sets or retrieves the QPSK symbol rate.
TSID | Sets or retrieves the transport stream ID.


ATSCLocator.CarrierFrequency

The CarrierFrequency property sets or retrieves the carrier frequency of the RF signal.

Syntax

objATSCLocator.CarrierFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the carrier frequency, in kilohertz (kHz).

See Also

  • ATSCLocator Object


ATSCLocator.Clone

The Clone method creates a new copy of this ATSCLocator object.

Syntax

objATSCLocator.Clone() As Locator

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns an ATSCLocator object that is a copy of the current object.

See Also

  • ATSCLocator Object


ATSCLocator.InnerFEC

The InnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used.

Syntax

objATSCLocator.InnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod Integer.

Remarks

This property is read-write.

See Also

  • ATSCLocator Object


ATSCLocator.InnerFECRate

The InnerFECRate property sets or retrieves the inner forward error correction (FEC) rate.

Syntax

objATSCLocator.InnerFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate Integer.

Remarks

This property is read only.

See Also

  • ATSCLocator Object


ATSCLocator.Modulation

The Modulation property sets or retrieves the modulation type.

Syntax

objATSCLocator.Modulation As ModulationType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the modulation rate as a ModulationType Integer.

Remarks

This property is read-write.

See Also

  • ATSCLocator Object


ATSCLocator.OuterFEC

The OuterFec property sets or retrieves the type of outer forward error correction (FEC) that is used.

Syntax

objATSCLocator.OuterFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the outer forward error correction as an FECMethod Integer.

Remarks

This property is read-write.

See Also

  • ATSCLocator Object


ATSCLocator.OuterFECRate

The OuterFECRate property sets or retrieves the outer forward error correction (FEC) rate.

Syntax

objATSCLocator.OuterFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate Integer.

Remarks

This property is read only.

See Also

  • ATSCLocator Object


ATSCLocator.PhysicalChannel

The PhysicalChannel property sets or retrieves the physical channel.

Syntax

objATSCLocator.PhysicalChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the physical channel as a Long integer.

Remarks

This property is read-write.

See Also

  • ATSCLocator Object


ATSCLocator.SymbolRate

The SymbolRate property sets or retrieves the QPSK symbol rate.

Syntax

objATSCLocator.SymbolRate As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the QPSK symbol rate as a Long integer.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • ATSCLocator Object


ATSCLocator.TSID

The TSID property sets or retrieves the transport stream ID.

Syntax

objATSCLocator.TSID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the transport stream ID as a Long integer.

Remarks

This property is read-write.

See Also

  • ATSCLocator Object


ATSCTuningSpace Object

An ATSCTuningSpace object represents a tuning space with an ATSC network type. Microsoft provides a default ATSC tuning space with Windows XP, and also with DirectX 9.0. (See Default Tuning Spaces.) Third parties such as cable providers may install a custom tuning space using the SystemTuningSpaces object.

When the minimum and maximum physical channel and minor channel for a tuning space are set using these methods, the tuner will automatically wrap around to the minimum value when the user tries to specify a channel that is greater than the maximum value.

Method or Property | Description
Clone | Creates a new copy of the object.
CLSID | Retrieves the CLSID of the tuning space.
CountryCode | Sets or retrieves the country/region code of the tuning space (based on TAPI country/region codes).
CreateTuneRequest | Creates an empty (uninitialized) Tune Request object specific to this tuning space.
DefaultLocator | Sets or retrieves the efault locator for this tuning space.
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing the default preferred component types specified by the user or application.
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
InputType | Sets or retrieves the input type, either antenna or cable, for the tuning space.
MaxChannel | Sets or retrieves the highest channel number for the tuning space.
MaxMinorChannel | Sets or retrieves the highest minor channel number ever provided by this tuning space.
MaxPhysicalChannel | Sets or retrieves the highest physical channel number for the tuning space.
MinChannel | Sets or retrieves the lowest channel number for the tuning space.
MinMinorChannel | Sets or retrieves the highest minor channel number ever provided by this tuning space.
MinPhysicalChannel | Sets or retrieves the lowest physical channel number for the tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


ATSCTuningSpace.Clone

The Clone method creates a new copy of this ATSCTuningSpace object.

Syntax

objATSCTuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new ATSCTuningSpace object whose values are identical to the current ATSCTuningSpace object.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.CLSID

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objATSCTuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only. The CLSID for this tuning space is "{A2E30750-6C3D-11D3-B653-00C04F79498E}".

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.CountryCode

The CountryCode property sets or retrieves the country/region code of the tuning space (based on TAPI country/region codes).

Syntax

objATSCTuningSpace.CountryCode As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the country/region code as a Long integer.

Remarks

Uses TAPI country/region codes.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) Tune Request object specific to this tuning space.

Syntax

objATSCTuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Values

Returns a Tune Request object as an Object.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.DefaultLocator

The DefaultLocator property sets or retrieves the default locator for this tuning space.

Syntax

objATSCTuningSpace.DefaultLocator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an ATSCLocator object as an Object.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.DefaultPreferredComponentTypes

The DefaultPreferredComponentTypes property retrieves or creates a ComponentTypes collection of ATSCComponentType objects containing the default preferred component types specified by the user or application.

Syntax

objATSCTuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ComponentTypes collection as an Object.

Remarks

A component in this context means a substream within the program. An example of a preferred component would be an audio stream in English. When multiple streams or components are available, the MSVidBDATunerDevice object will always attempt to play the preferred ones first.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.FriendlyName

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objATSCTuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.InputType

The InputType property sets or retrieves the input type, either antenna or cable, for the tuning space.

Syntax

objATSCTuningSpace.InputType As TunerInputType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the input type as a TunerInputType Integer.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MaxChannel

The MaxChannel property sets or retrieves the highest channel number for the tuning space.

Syntax

objATSCTuningSpace.MaxChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum channel number as an Integer.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MaxMinorChannel

The MaxMinorChannel property sets or retrieves the highest minor channel number ever provided by this tuning space.

Syntax

objATSCTuningSpace.MaxMinorChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum minor channel as a Long integer.

Remarks

This property is read-write. This property must be set before setting the MinMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MaxPhysicalChannel

The MaxPhysicalChannel property sets or retrieves the highest physical channel number for the tuning space.

Syntax

objATSCTuningSpace.MaxPhysicalChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum physical channel number as an Integer.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MinChannel

The MinChannel property sets or retrieves the lowest channel number for the tuning space.

Syntax

objATSCTuningSpace.MinChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the minimum channel number as an Integer.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MinMinorChannel

The MinMinorChannel property sets or retrieves the lowest minor channel number ever provided by this tuning space.

Syntax

objATSCTuningSpace.MinMinorChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum minor channel as a Long integer.

Remarks

This property is read-write. This property must be set after setting the MaxMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.MinPhysicalChannel

The MinPhysicalChannel property sets or retrieves the lowest physical channel number for the tuning space.

Syntax

objATSCTuningSpace.MinPhysicalChannel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum physical channel number as an Integer.

Remarks

This property is read-write.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.NetworkType

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objATSCTuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • ATSCTuningSpace Object


ATSCTuningSpace.UniqueName

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objATSCTuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • ATSCTuningSpace Object


AuxInTuningSpace Object

An AuxInTuningSpace object represents an S-Video or composite video input. This object's methods are exactly the same as those of the ITuningSpace object.


IChannelTuneRequest Object

A IChannelTuneRequest object represents a tune request valid for an analog TV network type. Applications cannot create an IChannelTuneRequest object.

Method or Property | Description
Channel | Sets or retrieves the channel to be tuned.
Clone | Creates a new copy of this IChannelTuneRequest object.
Components | Retrieves the IComponents collection object associated with this IChannelTuneRequest.
Locator | Retrieves the locator associated with this IChannelTuneRequest object.
TuningSpace | Retrieves the AnalogTVTuningSpace associated with this object.


IChannelTuneRequest.Channel

The Channel property sets or retrieves the channel to be tuned.

Syntax

objIChannelTuneRequest.Channel As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the channel to be tuned as a Long integer.

Remarks

This property is read-write. If the value specified for Channel is less than the minimum channel set for the tuning space, it will wrap around to the maximum channel value. Likewise, if the value specified for Channel is greater than the maximum channel set for the tuning space, it will wrap around to the minimum channel value.

See Also

  • IChannelTuneRequest Object


IChannelTuneRequest.Clone

The Clone method creates a new copy of this IChannelTuneRequest object.

Syntax

objIChannelTuneRequest.Clone() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns a IChannelTuneRequest object that is a copy of the current object as an Object.

See Also

  • IChannelTuneRequest Object


IChannelTuneRequest.Components

The Components property retrieves the IComponents object collection for this IChannelTuneRequest object.

Syntax

objIChannelTuneRequest.Components As Components

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an IComponents object as an Object.

Remarks

This property is read-only. This property is not used for analog tune requests.

See Also

  • IChannelTuneRequest Object


IChannelTuneRequest.Locator

The Locator property retrieves the Locator object for this IChannelTuneRequest object. (Not used for analog tune requests.)

Syntax

objIChannelTuneRequest.Locator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a Locator object as an Object.

Remarks

This property is read-write. This property is not used for analog tune requests.

See Also

  • IChannelTuneRequest Object


IChannelTuneRequest.TuningSpace

The TuningSpace property retrieves the AnalogTVTuningSpace object associated with this IChannelTuneRequest object.

Syntax

objIChannelTuneRequest.TuningSpace As TuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an AnalogTVTuningSpace object as an Object.

Remarks

This property is read-only.

See Also

  • IChannelTuneRequest Object


IComponent Object

The IComponent object represents the general characteristics of a component, which is typically an elementary stream within the program stream. Applications cannot create an IComponent object directly.

Method or Property | Description
Clone | Creates a new copy of this IComponent object.
DescLangID | Sets or retrieves the Language Identifier for IComponent.Description.
Description | Sets or retrieves the description of this IComponent object.
Status | Sets or retrieves the requested or actual status of this IComponent object.
Type | Sets or retrieves a ComponentType object that describes the general characteristics of this IComponent object.

See Also

  • IMPEG2Component Object


IComponent.Clone

The Clone method creates a new copy of this IComponent object.

Syntax

objIComponent.Clone() As Component

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns a copy of the current IComponent formatted as an Object.

See Also

  • IComponent Object


IComponent.DescLangID

The DescLangID property sets or retrieves the Language Identifier for IComponent.Description.

Syntax

objIComponent.DescLangID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Language Identifier as a Long integer.

Remarks

This property is read-write.

See Also

  • IComponent Object


IComponent.Description

The Description property sets or retrieves the description of this IComponent object.

Syntax

objIComponent.Description As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns this IComponent object description as a String.

Remarks

This property is read-write.

See Also

  • IComponent Object


IComponent.Status

The Status property sets or retrieves the requested or actual status of this IComponent object.

Syntax

objIComponent.Status As ComponentStatus

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the status as a ComponentStatus Integer.

Remarks

Use this property to activate or inactivate a stream component (substream).

See Also

  • IComponent Object


IComponent.Type

The Type property sets or retrieves a ComponentType object that describes the general characteristics of this IComponent object.

Syntax

objIComponent.Type As ComponentType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ComponentType object as an Object.

Remarks

A ComponentType object is not required.

See Also

  • IComponent Object


IComponents Object

An IComponents object contains a collection of IComponent objects. Applications cannot create an IComponents object.

Method or Property | Description
Add | Adds a component to the collection.
Clone | Creates a new collection object that contains a copy of every component in this collection.
Count | Retrieves the number of items in the collection.
Item | Retrieves a specified item from the collection.
Remove | Removes an item from the collection.


IComponents.Add

The Add method add a component to the collection.

Syntax

objIComponents.Add(Component As Component) As VARIANT

Parameters

Component

Specifies the IComponent object to be added to the collection.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns the index value of the component within this collection.

See Also

  • IComponents Object


IComponents.Clone

The Clone method creates a new collection object that contains a copy of every component in this collection.

Syntax

objIComponents.Clone() As Components

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns the new IComponents object as an Object.

See Also

  • IComponents Object


IComponents.Count

The Count property retrieves the number of items in the collection.

Syntax

objIComponents.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the number of items in the collection.

Remarks

This property is read only.

See Also

  • IComponents Object


IComponents.Item

The Item property retrieves a Component object from the collection at the specified index.

Syntax

objIComponents.Item(index) As Component

Parameters

Index

Specifies the index of the object to retrieve as a Long integer.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a Component object as an Object.

See Also

  • IComponents Object


IComponents.Remove

The Remove method removes a Component object from the collection at the specified index.

Syntax

objIComponents.Remove(Index)

Parameters

Index

Specifies the index of the object to remove as a Long integer.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the Component object that was removed from the collection.

See Also

  • IComponents Object


ComponentType Object

In DVB program streams, an IComponent object refers to an elementary stream, such as an audio stream. Every IComponent object has an associated ComponentType object that describes the properties of the component.

Method or Property | Description
Category | Sets or retrieves the Component category.
Clone | Creates a new copy of this component type.
MediaFormatType | Sets or retrieves the DirectShow media format type as a String.
MediaMajorType | Sets or retrieves the DirectShow media major type as a String.
MediaSubType | Sets or retrieves the DirectShow media subtype as a String.


ComponentType.Category

The Category property sets or retrieves the category of the IComponent object that associates this ComponentType object.

Syntax

objComponentType.Category As ComponentCategory

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the category as a ComponentCategory object.

Remarks

This property is read-write.

See Also

  • ComponentType Object


ComponentType.Clone

The Clone method creates a new copy of this ComponentType object.

Syntax

objComponentType.Clone As ComponentType

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new ComponentType object whose values are identical to the current ComponentType object.

See Also

  • ComponentType Object


ComponentType.MediaFormatType

The MediaFormatType property sets or retrieves the DirectShow Media Type Format.

Syntax

objComponentType.MediaFormatType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Format as a String formatted as a GUID.

See Also

  • ComponentType Object


ComponentType.MediaMajorType

The MediaMajorType property sets or retrieves the DirectShow Media Type Major Type.

Syntax

objComponentType.MediaMajorType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Major Type as a String formatted as a GUID.

See Also

  • ComponentType Object


ComponentType.MediaSubType

The MediaSubType property sets or retrieves the DirectShow Media Type Subtype GUID.

Syntax

objComponentType.MediaSubType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Subtype as a String formatted as a GUID.

See Also

  • ComponentType Object


ComponentTypes Object

A ComponentTypes object manages a collection of ComponentType objects.

Method or Property | Description
Add | Creates a new ComponentType object and adds it to the collection of this ComponentTypes object.
Clone | Creates a new copy of this ComponentTypes object including a new copy of the collection of ComponentType objects.
Count | Retrieves the number of ComponentType objects in the collection of this ComponentTypes object.
Item | Sets or retrieves a ComponentType object at a specified index.
Remove | Removes a ComponentType object from the collection at the specified index.


ComponentTypes.Add

The Add method creates a new ComponentType object and adds it to the collection of this ComponentTypes object.

Syntax

objComponentTypes.Add(ComponentType As ComponentType)

Parameters

ComponentType

Specifies the ComponentType object to be added to the collection.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the index value for the newly added object as a VARIANT.

See Also

  • ComponentTypes Object


ComponentTypes.Clone

The Clone method creates a new copy of this ComponentTypes object including a new copy of the collection of ComponentType objects.

Syntax

ComponentTypes.Clone() As ComponentTypes

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the new ComponentTypes object as an Object.

See Also

  • ComponentTypes Object


ComponentTypes.Count

The Count property retrieves the number of ComponentType objects in the collection of this ComponentTypes object.

Syntax

objComponentTypes.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the number of objects as a Long integer.

Remarks

This property is read-only.

See Also

  • ComponentTypes Object


ComponentTypes.Item

The Item property sets or retrieves a ComponentType object at a specified index.

Syntax

objComponentTypes.Item(Index) As ComponentType

Parameters

Index

Specifies the index of the object to retrieve as a Long integer.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a ComponentType object as an Object.

See Also

  • ComponentTypes Object


ComponentTypes.Remove

The Remove method removes a ComponentType object from the collection at the specified index.

Syntax

objComponentTypes.Remove(Index)

Parameters

Index

Specifies the index of the object to remove as a Long integer.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns nothing.

See Also

  • ComponentTypes Object


DVBCLocator Object

A DVBCLocator is a Locator object for a DVB-C network type.

Method or Property | Description
CarrierFrequency | Sets or retrieves the carrier frequency of the RF signal.
Clone | Creates a new copy of this DVBCLocator object.
InnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used.
InnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate.
Modulation | Sets or retrieves the modulation type.
OuterFEC | Sets or retrieves the type of outer forward error correction (FEC) that is used.
OuterFECRate | Sets or retrieves the outer forward error correction (FEC) rate.
SymbolRate | Sets or retrieves the QPSK symbol rate.


DVBCLocator.CarrierFrequency

The CarrierFrequency property sets or retrieves the carrier frequency of the RF signal.

Syntax

objDVBCLocator.CarrierFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the carrier frequency, in kilohertz.

See Also

  • DVBCLocator Object


DVBCLocator.Clone

The Clone method creates a new copy of this DVBCLocator object.

Syntax

objDVBCLocator.Clone() As Locator

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a DVBCLocator object that is a copy of the current object.

See Also

  • DVBCLocator Object


DVBCLocator.InnerFEC

The InnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used.

Syntax

objDVBCLocator.InnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod Integer.

Remarks

This property is read-write.

See Also

  • DVBCLocator Object


DVBCLocator.InnerFECRate

The InnerFECRate property sets or retrieves the inner forward error correction (FEC) rate.

Syntax

objDVBCLocator.InnerFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate Integer.

Remarks

This property is read only.

See Also

  • DVBCLocator Object


DVBCLocator.Modulation

The Modulation property sets or retrieves the modulation type.

Syntax

objDVBCLocator.Modulation As ModulationType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the modulation rate as a ModulationType Integer.

Remarks

This property is read-write.

See Also

  • DVBCLocator Object


DVBCLocator.OuterFEC

The OuterFEC property sets or retrieves the type of outer forward error correction (FEC) that is used.

Syntax

objDVBCLocator.OuterFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the outer forward error correction as an FECMethod Integer.

Remarks

This property is read-write.

See Also

  • DVBCLocator Object


DVBCLocator.OuterFECRate

The OuterFECRate property sets or retrieves the outer forward error correction (FEC) rate.

Syntax

objDVBCLocator.OuterFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate Integer.

Remarks

This property is read only.

See Also

  • DVBCLocator Object


DVBCLocator.SymbolRate

The SymbolRate property sets or retrieves the QPSK symbol rate.

Syntax

objDVBCLocator.SymbolRate As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the QPSK symbol rate as a Long integer.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • DVBCLocator Object


DVBSLocator Object

A DVBSLocator is a Locator object for a DVB-S network type.

Method or Property | Description
Azimuth | Sets or retrieves the azimuth setting used for positioning the satellite dish.
CarrierFrequency | Sets or retrieves the carrier frequency of the RF signal.
Clone | Creates a new copy of this DVBSLocator object.
Elevation | Sets or retrieves the elevation of the satellite.
InnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used.
InnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate.
Modulation | Sets or retrieves the modulation type.
OrbitalPosition | Sets or retrieves the elevation of the satellite.
OuterFEC | Sets or retrieves the type of outer forward error correction (FEC) that is used.
OuterFECRate | Sets or retrieves the outer forward error correction (FEC) rate.
SignalPolarisation | Sets or retrieves the signal polarization.
SymbolRate | Sets or retrieves the QPSK symbol rate.
WestPosition | Sets or retrieves a flag indicating whether or not longitude values are "west longitude".


DVBSLocator.Azimuth

The Azimuth property sets or retrieves the azimuth setting used for positioning the satellite dish.

Syntax

objDVBCLocator.Azimuth As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the azimuth as a Long integer.

Remarks

The value of the azimuth is expressed in tenths of a degree.

See Also

  • DVBSLocator Object


DVBSLocator.CarrierFrequency

The CarrierFrequency property sets or retrieves the carrier frequency of the RF signal.

Syntax

objDVBCLocator.CarrierFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the carrier frequency, in kilohertz (kHz).

See Also

  • DVBSLocator Object


DVBSLocator.Clone

The Clone method creates a new copy of this DVBSLocator object.

Syntax

objDVBCLocator.Clone() As Locator

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a DVBSLocator object that is a copy of the current object.

See Also

  • DVBSLocator Object


DVBSLocator.Elevation

The Elevation property sets or retrieves the elevation of the satellite.

Syntax

objDVBCLocator.Elevation As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the elevation as a Long integer.

Remarks

The elevation is expressed in tenths of a degree.

See Also

  • DVBSLocator Object


DVBSLocator.InnerFEC

The InnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used.

Syntax

objDVBCLocator.InnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod type.

Remarks

This property is read-write.

See Also

  • DVBSLocator Object


DVBSLocator.InnerFECRate

The InnerFECRate property sets or retrieves the inner forward error correction (FEC) rate.

Syntax

objDVBCLocator.InnerFecRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • DVBSLocator Object


DVBSLocator.Modulation

The Modulation property sets or retrieves the modulation type.

Syntax

objDVBCLocator.Modulation As ModulationType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the modulation rate as a ModulationType type.

Remarks

This property is read-write.

See Also

  • DVBSLocator Object


DVBSLocator.OrbitalPosition

The OrbitalPosition property sets or retrieves the elevation of the satellite.

Syntax

objDVBCLocator.OrbitalPosition As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the elevation as a Long integer.

Remarks

The orbital position is expressed as longitude in tenths of a degree.

See Also

  • DVBSLocator Object


DVBSLocator.OuterFEC

The OuterFEC property sets or retrieves the type of outer forward error correction (FEC) that is used.

Syntax

objDVBCLocator.OuterFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the outer forward error correction as an FECMethod type.

Remarks

This property is read-write.

See Also

  • DVBSLocator Object


DVBSLocator.OuterFECRate

The OuterFECRate property sets or retrieves the outer forward error correction (FEC) rate.

Syntax

objDVBCLocator.OuterFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • DVBSLocator Object


DVBSLocator.SignalPolarisation

The SignalPolarisation property sets or retrieves the signal polarization.

Syntax

objDVBCLocator.SignalPolarisation As Polarisation

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the polarization as a Polarisation type.

Remarks

This property is read-write.

See Also

  • DVBSLocator Object


DVBSLocator.SymbolRate

The SymbolRate property sets or retrieves the QPSK symbol rate.

Syntax

objDVBCLocator.SymbolRate As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the QPSK symbol rate as a Long integer.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • DVBSLocator Object


DVBSLocator.WestPosition

The WestPosition property sets or retrieves a flag indicating whether or not longitude values are "west longitude".

Syntax

objDVBCLocator.WestPosition As Boolean

Parameters

This property takes no parameters

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns VARIANT_TRUE when longitude values are "west longitude" and VARIANT_FALSE otherwise.

Remarks

When assigning this property, the value specified will apply to all longitude values that follow.

See Also

  • DVBSLocator Object


DVBSTuningSpace Object

A DVBSTuningSpace object represents a tuning space with a DVB-S network type.

Method or Property Name | Description
Clone | Creates a new copy of the object.
CLSID | Retrieves the CLSID of the tuning space.
CreateTuneRequest | Creates an empty (uninitialized) Tune Request object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default DVBSLocator object on the local system, which the Tuner may use after installation.
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing MPEG2ComponentType objects specified by the user or application.
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
HighOscillator | Sets or retrieves the high oscillator frequency.
InputRange | Sets or retrieves an integer indicating which option or switch contains the requested signal source.
LNBSwitch | Sets or retrieves the LNB switch frequency.
LowOscillator | Sets or retrieves the low oscillator frequency.
NetworkID | Sets or retrieves the network ID of the tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
SpectralInversion | Sets or retrieves an integer indicating the spectral inversion.
SystemType | Sets or retrieves the DVB system type as cable, terrestrial, or satellite.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


DVBSTuningSpace.Clone

The Clone method creates a new copy of this DVBSTuningSpace object.

Syntax

objDVBSTuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new DVBSTuningSpace object whose values are identical to the current DVBSTuningSpace object.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.CLSID

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objDVBSTuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only. The CLSID for this tuning space is "{B64016F3-C9A2-4066-96F0-BD9563314726}".

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) Tune Request object specific to this tuning space.

Syntax

objDVBSTuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a IDVBTuneRequest object as an Object.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.DefaultLocator

The DefaultLocator property sets or retrieves the initial default DVBSLocator object on the local system, which the Tuner may use after installation.

Syntax

objDVBSTuningSpace.DefaultLocator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Locator object as an Object.

Remarks

This property is read-write.

See ATSCTuningSpace.DefaultLocator for more information about the default locator.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.DefaultPreferredComponentTypes

The DefaultPreferredComponentTypes property retrieves or creates a ComponentTypes collection object containing MPEG2ComponentType objects specified by the user or application.

Syntax

objDVBSTuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ComponentTypes collection as an Object.

Remarks

A component in this context means a stream within the program. An example of a preferred component would be an audio stream in English. When multiple streams or components are available, the MSVidBDATunerDevice object will always attempt to play the preferred ones first.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.FriendlyName

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objDVBSTuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.HighOscillator

The HighOscillator property sets or retrieves the high oscillator frequency.

Syntax

objDVBSTuningSpace.HighOscillator As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the high oscillator frequency, in kilohertz (kHz).

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.InputRange

The InputRange property sets or retrieves an integer indicating which option or switch contains the requested signal source.

Syntax

objDVBSTuningSpace.InputRange As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the LNB switch frequency as a long integer.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.LNBSwitch

The LNBSwitch property sets or retrieves the LNB switch frequency.

Syntax

objDVBSTuningSpace.LNBSwitch As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the LNB switch frequency, in kilohertz (kHz).

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.LowOscillator

The LowOscillator property sets or retrieves the low oscillator frequency.

Syntax

objDVBSTuningSpace.LowOscillator As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the low oscillator frequency, in kilohertz (kHz).

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.NetworkID

The NetworkID property sets or retrieves the network id of the tuning space.

Syntax

objDVBSTuningSpace.NetworkID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network id as a long integer.

Remarks

A Network ID is specific to DVB. It is a unique ID that specifies a particular broadcast provider (not a network type). Two broadcasters will have different network IDs even if they both provide DVB satellite broadcasts. Network IDs are allocated by the Joint Technical Committee (JTC) of the European Broadcasting Union (EBU) and the European Telecommunications Standards Institute (ETSI). Applications that obtain tune requests from a database do not generally need to be concerned about this property. Guide Store loaders will probably need to use it. Applications that are specific to a broadcaster and don't use a database to access preconfigured tune requests may use this ID to locate the tuning space for the particular broadcaster they are interested in.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.NetworkType

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objDVBSTuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.SpectralInversion

The SpectralInversion property sets or retrieves an integer indicating the spectral inversion.

Syntax

objDVBSTuningSpace.SpectralInversion As SpectralInversion

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the spectral inversion as a SpectralInversion integer.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.SystemType

The SystemType property sets or retrieves the DVB system type as cable, terrestrial, or satellite.

Syntax

objDVBSTuningSpace.SystemType As DVBSystemType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the system type as a DVBSystemType Integer.

Remarks

This property is read-write.

See Also

  • DVBSTuningSpace Object


DVBSTuningSpace.UniqueName

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objDVBSTuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • DVBSTuningSpace Object


DVBTLocator Object

A DVBTLocator object is the locator object for a DVB-T network type.

Method or Property | Description
Bandwidth | Sets or retrieves the bandwidth of the carrier frequency.
CarrierFrequency | Sets or retrieves the carrier frequency of the RF signal.
Clone | Creates a new copy of this object.
Guard | Sets or retrieves the guard interval.
HAlpha | Sets or retrieves the hierarchy alpha.
InnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used.
InnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate.
LPInnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used for the low-priority stream.
LPInnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate of the low-priority stream.
Mode | Sets or retrieves the transmission mode.
Modulation | Sets or retrieves the modulation type.
OtherFrequencyInUse | Sets or retrieves a flag indicating whether another DVB-T broadcaster is using the frequency.
OuterFEC | Sets or retrieves the type of outer forward error correction (FEC) that is used.
OuterFECRate | Sets or retrieves the outer forward error correction (FEC) rate.
SymbolRate | Sets or retrieves the QPSK symbol rate.


DVBTLocator.Bandwidth

The Bandwidth property sets or retrieves the bandwidth of the carrier frequency.

Syntax

objDVBTLocator.Bandwidth As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the bandwidth as a Long integer.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.CarrierFrequency

The CarrierFrequency property sets or retrieves the carrier frequency of the RF signal.

Syntax

objDVBTLocator.CarrierFrequency As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the frequency, in kilohertz (kHz).

See Also

  • DVBTLocator Object


DVBTLocator.Clone

The Clone method creates a new copy of this object.

Syntax

objDVBTLocator.Clone() As Locator

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a DVBTLocator object that is a copy of the current object.

See Also

  • DVBTLocator Object


DVBTLocator.Guard

The Guard property sets or retrieves the guard interval.

Syntax

objDVBTLocator.Guard As GuardInterval

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the guard interval as a GuardInterval type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.HAlpha

The HAlpha property sets or retrieves the hierarchy alpha.

Syntax

objDVBTLocator.HAlpha As HierarchyAlpha

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the hierarchy alpha as a HierarchyAlpha type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.InnerFEC

The InnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used.

Syntax

objDVBTLocator.InnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.InnerFECRate

The InnerFECRate property sets or retrieves the inner forward error correction (FEC) rate.

Syntax

objDVBTLocator.InnerFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • DVBTLocator Object


DVBTLocator.LPInnerFEC

The LPInnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used for the low-priority stream.

Syntax

objDVBTLocator.LPInnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.LPInnerFECRate

The LPInnerFECRate property sets or retrieves the inner forward error correction (FEC) rate of the low-priority stream.

Syntax

objDVBTLocator.LPInnerFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • DVBTLocator Object


DVBTLocator.Mode

The Mode property sets or retrieves the transmission mode.

Syntax

objDVBTLocator.Mode As TransmissionMode

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the transmission mode as a TransmissionMode type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.Modulation

The Modulation property sets or retrieves the modulation type.

Syntax

objDVBTLocator.Modulation As ModulationType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the modulation rate as a ModulationType type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.OtherFrequencyInUse

The OtherFrequencyInUse property sets or retrieves a flag indicating whether another DVB-T broadcaster is using the frequency.

Syntax

objDVBTLocator.OtherFrequencyInUse As Boolean

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the VARIANT_TRUE indicating whether another DVB-T broadcaster is using the frequency and VARIANT_FALSE otherwise.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.OuterFEC

The OuterFEC property sets or retrieves the type of outer forward error correction (FEC) that is used.

Syntax

objDVBTLocator.OuterFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the outer forward error correction as an FECMethod type.

Remarks

This property is read-write.

See Also

  • DVBTLocator Object


DVBTLocator.OuterFECRate

The OuterFECRate property sets or retrieves the outer forward error correction (FEC) rate.

Syntax

objDVBTLocator.OuterFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • DVBTLocator Object


DVBTLocator.SymbolRate

The SymbolRate property sets or retrieves the QPSK symbol rate.

Syntax

objDVBTLocator.SymbolRate As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the QPSK symbol rate as a Long integer.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • DVBTLocator Object


IDVBTuneRequest Object

A IDVBTuneRequest object represents a tune request valid for a DVB network type. Applications cannot create an IDVBTuneRequest object.

Method or Property Name | Description
Clone | Creates a new copy of this IDVBTuneRequest object.
Components | Retrieves the IComponents object with its collection of IComponent objects.
Locator | Retrieves the ILocator object associated with this IDVBTuneRequest object.
ONID | Sets or retrieves the original network ID.
SID | Sets or retrieves the service ID for the network.
TSID | Sets or retrieves the transport stream ID.
TuningSpace | Retrieves the tuning space for this IDVBTuneRequest object.


IDVBTuneRequest.Clone

The Clone method creates a new copy of this IDVBTuneRequest object.

Syntax

objIDVBTuneRequest.Clone() As TuneRequest

Parameters

This property takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a IDVBTuneRequest object that is a copy of the current object.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.Components

The Components property retrieves the IComponents object with its collection of Component objects.

Syntax

objIDVBTuneRequest.Components As Components

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an IComponents object as an Object.

Remarks

This property is read only.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.Locator

The Locator property retrieves the Locator object associated with this IDVBTuneRequest object.

Syntax

objIDVBTuneRequest.Locator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Locator object as an Object.

Remarks

This property is read-write.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.ONID

The ONID property sets or retrieves the original network ID.

Syntax

objIDVBTuneRequest.ONID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the original network ID as a Long integer.

Remarks

This property is read-write.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.SID

The SID property sets or retrieves the service ID for the network.

Syntax

objIDVBTuneRequest.SID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the service ID as a Long integer.

Remarks

This property is read-write.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.TSID

The TSID property sets or retrieves the transport stream ID.

Syntax

objIDVBTuneRequest.TSID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the transport stream ID as a Long integer.

Remarks

This property is read-write.

See Also

  • IDVBTuneRequest Object


IDVBTuneRequest.TuningSpace

The TuningSpace property retrieves the TuningSpace object for this IDVBTuneRequest object.

Syntax

objIDVBTuneRequest.TuningSpace As TuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the TuningSpace object as an Object.

Remarks

This property is read-only.

See Also

  • IDVBTuneRequest Object


DVBTuningSpace Object

A DVBTuningSpace object represents a tuning space with a DVB network type.

Method or Property Name | Description
Clone | Creates a new copy of the object.
CLSID | Retrieves the CLSID of the tuning space.
CreateTuneRequest | Creates an empty (uninitialized) IDVBTuneRequest object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default ILocator object on the local system for this tuning space.
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing MPEG2ComponentType objects specified by the user or application.
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
NetworkID | Sets or retrieves the network ID of the tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
SystemType | Sets or retrieves the DVB system type as cable, terrestrial, or satellite.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


DVBTuningSpace.Clone

The Clone method creates a new copy of this DVBTuningSpace object.

Syntax

objDVBTuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new DVBTuningSpace object whose values are identical to the current DVBTuningSpace object.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.CLSID

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objDVBTuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only. The CLSID for this tuning space is "{C6B14B32-76AA-4A86-A7AC-5C79AAF58DA7}".

See Also

  • DVBTuningSpace Object


DVBTuningSpace.CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) IDVBTuneRequest object specific to this tuning space.

Syntax

objDVBTuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a IDVBTuneRequest object as an Object.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.DefaultLocator

The DefaultLocator property sets or retrieves the default locator for this tuning space.

Syntax

objDVBTuningSpace.DefaultLocator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a DVBCLocator object.

Remarks

This property is read-write.

The default locator provides the information that enables the tuner to locate the default transport stream on the network. On DVB networks, the vendor who creates the tuning space should also provide the default locator for that tuning space. See ATSCTuningSpace.DefaultLocator for more information about the default locator.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.DefaultPreferredComponentTypes

Retrieves or creates a ComponentTypes collection object containing MPEG2ComponentType objects specified by the user or application.

Syntax

objDVBTuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ComponentTypes collection as an Object.

Remarks

A component in this context means a stream within the program. An example of a preferred component would be an audio stream in English. When multiple streams or components are available, the Tuner object will always attempt to play the preferred ones first.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.FriendlyName

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objDVBTuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.NetworkID

The NetworkID property sets or retrieves the network id of the tuning space.

Syntax

objDVBTuningSpace.NetworkID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network id as a long integer.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.NetworkType

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objDVBTuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.SystemType

The SystemType property sets or retrieves the DVB system type as cable, terrestrial, or satellite.

Syntax

objDVBTuningSpace.SystemType As DVBSystemType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the system type as a DVBSystemType type.

Remarks

This property is read-write.

See Also

  • DVBTuningSpace Object


DVBTuningSpace.UniqueName

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objDVBTuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • DVBTuningSpace Object


ILocator Object

An ILocator object represents the base class for all derived locator objects. Applications cannot create an ILocator object directly.

Method or Property | Description
CarrierFrequency | Sets or retrieves the carrier frequency of the RF signal.
Clone | Creates a new copy of this ILocator object.
InnerFEC | Sets or retrieves the type of inner forward error correction (FEC) that is used.
InnerFECRate | Sets or retrieves the inner forward error correction (FEC) rate.
Modulation | Sets or retrieves the modulation type.
OuterFEC | Sets or retrieves the type of outer forward error correction (FEC) that is used.
OuterFECRate | Sets or retrieves the outer forward error correction (FEC) rate.
SymbolRate | Sets or retrieves the QPSK symbol rate.


ILocator.CarrierFrequency

The CarrierFrequency property sets or retrieves the carrier frequency of the RF signal.

Syntax

objILocator.CarrierFrequency As

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the carrier frequency, in kilohertz (kHz).

See Also

  • ILocator Object


ILocator.Clone

The Clone method creates a new copy of this ILocator object.

Syntax

objILocator.Clone() As Locator

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns an ILocator object that is a copy of the current object.

See Also

  • ILocator Object


ILocator.InnerFEC

The InnerFEC property sets or retrieves the type of inner forward error correction (FEC) that is used.

Syntax

objILocator.InnerFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the FEC as an FECMethod type.

Remarks

This property is read-write.

See Also

  • ILocator Object


ILocator.InnerFECRate

The InnerFECRate property sets or retrieves the inner forward error correction (FEC) rate.

Syntax

objILocator.InnerFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • ILocator Object


ILocator.Modulation

The Modulation property sets or retrieves the modulation type.

Syntax

objILocator.Modulation As ModulationType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the modulation rate as a ModulationType type.

Remarks

This property is read-write.

See Also

  • ILocator Object


ILocator.OuterFEC

The OuterFec property sets or retrieves the type of outer forward error correction (FEC) that is used.

Syntax

objILocator.OuterFEC As FECMethod

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the outer forward error correction as an FECMethod type.

Remarks

This property is read-write.

See Also

  • ILocator Object


ILocator.OuterFECRate

The OuterFECRate property sets or retrieves the outer forward error correction (FEC) rate.

Syntax

objILocator.OuterFECRate As BinaryConvolutionCodeRate

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the inner FEC rate as a BinaryConvolutionCodeRate type.

Remarks

This property is read only.

See Also

  • ILocator Object


ILocator.SymbolRate

The SymbolRate property sets or retrieves the QPSK symbol rate.

Syntax

objILocator.SymbolRate As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the QPSK symbol rate as a Long integer.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

  • ILocator Object


ITuneRequest Object

A ITuneRequest object represents a tune request valid for an analog TV network type. Applications cannot create an ITuneRequest object.

Method or Property | Description
Clone | Creates a new copy of this ITuneRequest object.
Components | Retrieves the IComponents collection for this ITuneRequest object.
Locator | Retrieves the ILocator object for this ITuneRequest object.
TuningSpace | Retrieves the tuning space for this ITuneRequest object.


ITuneRequest.Clone

The Clone method creates a new copy of this ITuneRequest object.

Syntax

objITuneRequest.Clone() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns a ITuneRequest object that is a copy of the current object as an Object.

See Also

  • ITuneRequest Object


ITuneRequest.Components

The Components property retrieves the IComponents object collection for this ITuneRequest object.

Syntax

objITuneRequest.Components As Components

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns an IComponents object as an Object. This IComponents object has a collection of Component objects for this ITuneRequest object.

Remarks

This property is read-only.

See Also

  • ITuneRequest Object


ITuneRequest.Locator

The Locator property retrieves the ILocator object for this ITuneRequest object.

Syntax

objITuneRequest.Locator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a ILocator object as an Object.

Remarks

This property is read-write.

See Also

  • ITuneRequest Object


ITuneRequest.TuningSpace

The TuningSpace property retrieves the ITuningSpace object for this ITuneRequest object.

Syntax

ObjITuneRequest.TuningSpace As TuningSpace

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns a ITuningSpace object as an Object.

Remarks

This property is read-only.

See Also

  • ITuneRequest Object


ITuningSpace Object

The ITuningSpace object is the base class for all derived tuning space objects. It is not used directly by applications. Applications always used the derived objects:

  • AnalogTVTuningSpace
  • ATSCTuningSpace
  • DVBSTuningSpace
  • DVBTuningSpace
Method or Property | Description
Clone | Creates a new copy of the object.
CLSID | The CLSID property retrieves the CLSID of the tuning space.
CreateTuneRequest | Creates an empty (uninitialized) Tune Request object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default ILocator object that the Tuner may use after installation.
DefaultPreferredComponentTypes | Retrieves or creates a ComponentTypes collection object containing ComponentType objects specified by the user or application.
FriendlyName | Sets or retrieves a user-friendly name of the tuning space.
NetworkType | Sets or retrieves the network type of the tuning space.
UniqueName | Sets or retrieves the globally unique name of the tuning space.


ITuningSpace.Clone

The Clone method creates a new copy of this ITuningSpace object.

Syntax

objITuningSpace.Clone() As TuningSpace

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new ITuningSpace object whose values are identical to the current ITuningSpace object.

See Also

  • ITuningSpace Object


ITuningSpace.CLSID

The CLSID property retrieves the CLSID of the tuning space.

Syntax

objITuningSpace.CLSID As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the CLSID as a String.

Remarks

This property is read only.

See Also

  • ITuningSpace Object


ITuningSpace.CreateTuneRequest

The CreateTuneRequest method creates an empty (uninitialized) Tune Request object specific to this tuning space.

Syntax

objITuningSpace.CreateTuneRequest() As TuneRequest

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a Tune Request object as an Object.

See Also

  • ITuningSpace Object


ITuningSpace.DefaultLocator

The DefaultLocator property sets or retrieves the initial default Locator object on the local system for this tuning space.

Syntax

objITuningSpace.DefaultLocator As Locator

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Locator object as an Object.

Remarks

This property is read-write. The default locator provides the information that enables the tuner to locate the default transport stream on the network. On DVB networks, the vendor who creates the tuning space should also provide the default locator for that tuning space. See ATSCTuningSpace.DefaultLocator for more information about the default locator.

See Also

  • ITuningSpace Object


ITuningSpace.DefaultPreferredComponentTypes

The DefaultPreferredComponentTypes property retrieves or creates a ComponentTypes collection object containing ComponentType objects specified by the user or application.

Syntax

objITuningSpace.DefaultPreferredComponentTypes As ComponentTypes

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the ComponentTypes collection as an Object.

Remarks

A component in this context means a stream within the program. An example of a preferred component would be an audio stream in English. When multiple streams or components are available, the Tuner object will always attempt to play the preferred ones first.

See Also

  • ITuningSpace Object


ITuningSpace.FriendlyName

The FriendlyName property sets or retrieves a user-friendly name of the tuning space.

Syntax

objITuningSpace.FriendlyName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the user-friendly name as a String.

Remarks

This property is read-write.

See Also

  • ITuningSpace Object


ITuningSpace.NetworkType

The NetworkType property sets or retrieves the network type of the tuning space.

Syntax

objITuningSpace.NetworkType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the network type as a String.

Remarks

The network type is formatted as a CLSID.

See Also

  • ITuningSpace Object


ITuningSpace.UniqueName

The UniqueName property sets or retrieves the globally unique name of the tuning space.

Syntax

objITuningSpace.UniqueName As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

The property returns the globally unique name as a String.

Remarks

The globally unique name is formatted as a CLSID.

See Also

  • ITuningSpace Object


ITuningSpaces Object

The ITuningSpaces object contains a collection of any specific type of tuning space, such as DVBTuningSpace2, ATSCTuningSpace, and so on. This collection is obtained from a call to the SystemTuningSpaces.TuningSpacesForName or TuningSpacesForCLSID method. Applications cannot create an ITuningSpaces object. The ITuningSpaces object exposes the following methods.

Property | Description
Count | Retrieves the number of items in the collection.
Item | Retrieves the item at the specified index.


ITuningSpaces.Count

The Count property retrieves the number of items in the collection.

Syntax

objITuningSpaces.Count As Long

Parameters

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the count as a long integer.

Remarks

This property is read-only.

See Also

SystemTuningSpaces.TuningSpacesForCLSID

SystemTuningSpaces.TuningSpacesForName


ITuningSpaces.Item

The Item property retrieves the item at the specified index.

Syntax

objITuningSpaces.Item(varIndex) As TuningSpace

Parameters

varIndex

Specifies the index of the item to retrieve. Must be no greater than the number returned from the ITuningSpaces.Count property.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the item as an object. See Remarks

Remarks

The specific object type depends on the CLSID or name that was specified when the collection was obtained from the SystemTuningSpaces.TuningSpacesForCLSID or SystemTuningSpaces.TuningSpacesForName method. The possible types are:

  • AnalogTVTuningSpace
  • ATSCTuningSpace
  • DVBSTuningSpace
  • DVBTuningSpace


LanguageComponentType Object

Represents the language component type for a single component (substream) in a broadcast stream.

Method or Property | Description
Category | Sets or retrieves the Component category.
Clone | Create a copy of this component type.
LangID | Language Identifier for Substream Content Language.
MediaFormatType | Sets or retrieves the DirectShow media formattype as a String.
MediaMajorType | Sets or retrieves the DirectShow media majortype as a String.
MediaSubType | Sets or retrieves the DirectShow media subtype as a String.


LanguageComponentType.Category

The Category property sets or retrieves the category of the Component object that associates this LanguageComponentType object.

Syntax

objLanguageComponentType.Category As ComponentCategory

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the category as a ComponentCategory Integer.

Remarks

This property is read-write.

See Also

  • ComponentType Object
  • LanguageComponentType Object


LanguageComponentType.Clone

The Clone method creates a new copy of this LanguageComponentType object.

Syntax

objLanguageComponentType.Clone() As ComponentType

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new LanguageComponentType object whose values are identical to the current object.

See Also

  • ComponentType Object
  • LanguageComponentType Object


LanguageComponentType.LangID

The LangID property sets or retrieves the language identifier for the stream content.

Syntax

objLanguageComponentType.LangID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the language identifier as a Long integer.

See Also

  • ComponentType Object
  • LanguageComponentType Object


LanguageComponentType.MediaFormatType

The MediaFormatType property sets or retrieves the DirectShow media type format.

Syntax

objLanguageComponentType.MediaFormatType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow media type format as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object


LanguageComponentType.MediaMajorType

The MediaMajorType property sets or retrieves the DirectShow Media Type Major Type.

Syntax

objLanguageComponentType.MediaMajorType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow AM_MEDIA_TYPE majortype member as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object


LanguageComponentType.MediaSubType

The MediaSubType property sets or retrieves the DirectShow Media Type Subtype GUID.

Syntax

objLanguageComponentType.MediaSubType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Subtype as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object


IMPEG2Component Object

An IMPEG2Component object represents a single component (substream) in an MPEG-2 broadcast stream. Applications cannot create an IMPEG2Component object.

Method or Property | Description
Clone | Creates a new copy of this IMPEG2Component object.
DescLangID | Sets or retrieves the Language Identifier for the IMPEG2Component.Description.
Description | Component Description.
PCRPID | Sets or retrieves the MPEG2 Packet ID for this substream's time stamps.
PID | Sets or retrieves the MPEG2 Packet ID for this Substream.
ProgramNumber | Sets or retrieves the MPEG2 Program Number, which provides a reverse lookup to PAT.
Status | Sets or retrieves the requested or actual status of this IMPEG2Component object.
Type | Sets or retrieves an MPEG2ComponentType object that describes the general characteristics of this IMPEG2Component object.


IMPEG2Component.Clone

The Clone method creates a new copy of this IMPEG2Component object.

Syntax

objIMPEG2Component.Clone() As Component

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns a copy of the current IMPEG2Component formatted as an Object.

See Also

  • IMPEG2Component Object


IMPEG2Component.DescLangID

The DescLangID property sets or retrieves the Language Identifier for the IMPEG2Component.Description.

Syntax

objIMPEG2Component.DescLangID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the Language Identifier as a Long integer.

Remarks

This property is read/write.

See Also

  • IMPEG2Component Object


IMPEG2Component.Description

The Description property sets or retrieves the description of this IMPEG2Component object.

Syntax

objIMPEG2Component.Description As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns this IMPEG2Component object description as a String.

Remarks

This property is read/write.

See Also

  • IMPEG2Component Object


IMPEG2Component.PCRPID

The PCRPID property sets or retrieves the MPEG2 Packet ID for this substream's time stamps.

Syntax

objIMPEG2Component.PCRPID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the MPEG2 Packet ID as a Long integer.

Remarks

This property is read/write.

See Also

  • IMPEG2Component Object


IMPEG2Component.PID

The PID property sets or retrieves the MPEG2 Packet ID for this substream.

Syntax

objIMPEG2Component.PID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the MPEG2 Packet ID for this substream as a Long integer.

Remarks

Do not confuse this property with the PCRPID property. The PCRPID property deals with the MPEG2 Packet ID for this substream's time stamps.

See Also

  • IMPEG2Component Object


IMPEG2Component.ProgramNumber

The ProgramNumber property sets or retrieves the MPEG2 program number, which provides a reverse lookup to PAT.

Syntax

objIMPEG2Component.ProgramNumber As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the program number as a Long integer.

Remarks

This property is read/write.

See Also

  • IMPEG2Component Object


IMPEG2Component.Status

The Status property sets or retrieves the requested or actual status of this IMPEG2Component object.

Syntax

objIMPEG2Component.Status As ComponentStatus

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the status as a ComponentStatus Integer.

Remarks

Use this property to activate or inactivate a stream component (substream).

See Also

  • IMPEG2Component Object


IMPEG2Component.Type

The Type property sets or retrieves an MPEG2ComponentType object that describes the general characteristics of this IMPEG2Component object.

Syntax

objIMPEG2Component.Type as ComponentType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the MPEG2ComponentType object as an Object.

Remarks

An MPEG2ComponentType object is required for all IMPEG2Component objects.

See Also

  • IMPEG2Component Object


MPEG2ComponentType Object

Represents the stream type for a single component in an MPEG-2 stream.

Method or Property | Description
Category | Sets or retrieves the Component category.
Clone | Create a copy of this component type.
LangID | Language Identifier for Substream Content Language.
MediaFormatType | Sets or retrieves the DirectShow media format type as a String.
MediaMajorType | Sets or retrieves the DirectShow media major type as a String.
MediaSubType | Sets or retrieves the DirectShow media subtype as a String.
StreamType | Sets or retrieves the MPEG2 Stream Type.


MPEG2ComponentType.Category

The Category property sets or retrieves the category of the Component object that is associated with this MPEG2ComponentType object.

Syntax

objMPEG2ComponentType.Category As ComponentCategory

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the category as a ComponentCategory Integer.

Remarks

This property is read/write.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.Clone

The Clone method creates a new copy of this MPEG2ComponentType object.

Syntax

objMPEG2ComponentType.Clone() As ComponentType

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns a new MPEG2ComponentType object whose values are identical to the current MPEG2ComponentType object.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.LangID

The LangID property sets or retrieves the language identifier for the stream content.

Syntax

objMPEG2ComponentType.LangID As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the language identifier as a Long integer.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.MediaFormatType

The MediaFormatType property sets or retrieves the DirectShow Media Type Format.

Syntax

objMPEG2ComponentType.MediaFormatType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Format as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.MediaMajorType

The MediaMajorType property sets or retrieves the DirectShow Media Type Major Type.

Syntax

objMPEG2ComponentType.MediaMajorType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Major Type as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.MediaSubType

The MediaSubType property sets or retrieves the DirectShow Media Type Subtype GUID.

Syntax

objMPEG2ComponentType.MediaSubType As String

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the DirectShow Media Type Subtype as a String formatted as a GUID.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


MPEG2ComponentType.StreamType

The StreamType property sets or retrieves the MPEG2 Stream Type.

Syntax

objMPEG2ComponentType.StreamType As MPEG2StreamType

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the stream type as an MPEG2StreamType Integer.

Remarks

This property is read-write.

See Also

  • ComponentType Object
  • LanguageComponentType Object
  • MPEG2ComponentType Object


SystemTuningSpaces Object

The SystemTuningSpaces object contains a collection of all tuning spaces currently available on the local system, and provides methods for adding new tuning spaces or removing existing ones.

Method or Property | Description
Add | Adds a new tuning space to the collection. This tuning space will be persisted unless removed.
Count | Number of items in the collection.
FindID | Finds Local ID Number of the specified tuning space.
Item | Finds the tuning space with the specified index or updates an existing tuning space in the collection.
MaxCount | Retrieves the maximum number of items allowed in the collection.
Remove | Removes a tuning space from the collection. This tuning space will be deleted from the registry.
TuningSpacesForCLSID | Returns a collection of tuning spaces that match the specified CLSID.
TuningSpacesForName | Returns a collection of tuning spaces that match the specified name.


SystemTuningSpaces.Add

The Add method adds a new, persistent, tuning space to the system.

Syntax

objSystemTuningSpaces.Add(TuningSpace As TuningSpace)

Parameters

TuningSpace

Specifies the tuning space to add to the system.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the index of the newly added object as a VARIANT.

Remarks

Any tuning space object may be added to the collection, such as ATSCTuningSpace or DVBTuningSpace objects.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.Count

The Count property retrieves the number of tuning space objects in the system.

Syntax

objSystemTuningSpaces.Count As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the number of tuning space objects as a Long integer.

Remarks

This property is read only.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.FindID

The FindID function retrieves the local unique ID Number of the specified tuning space.

Syntax

objSystemTuningSpaces.FindID(TuningSpace As TuningSpace) As Long

Parameters

TuningSpace

The tuning space object whose ID is to be retrieved.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns the ID of the specified tuning space object as a Long integer.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.Item

The Item property sets or retrieves a tuning space in the collection using a specified index.

Syntax

objSystemTuningSpaces.Item(varIndex) As TuningSpace

Parameters

varIndex

Specifies the index of the tuning space to retrieve or assign as a VARIANT.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

Returns the tuning space.

Remarks

This property is read/write. Assigning the tuning space object will save the changes to disk.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.MaxCount

The MaxCount property retrieves the maximum number of tuning spaces allowed in the collection.

Syntax

objSystemTuningSpaces.MaxCount As Long

Parameters

This property takes no parameters.

Error Codes

If the property fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This property returns the maximum number of tuning spaces allowed in the collection as a Long integer.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.Remove

The Remove method removes a tuning space object from the collection.

Syntax

ObjSystemTuningSpaces.Remove(Index)

Parameters

Index

Specifies the index of the tuning space object to be removed from the collection.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns nothing.

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.TuningSpacesForCLSID

The TuningSpacesForCLSID function returns a collection of tuning spaces that match the specified CLSID.

Syntax

objSystemTuningSpaces.TuningSpacesForCLSID(SpaceCLSID As String) As
ITuningSpaces

Parameters

SpaceCLSID

Specifies the CLSID as a String.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns an ITuningSpaces collection as an Object.

Remarks

This method matches against the ITuningSpace.CLSID property of each tuning space.

Code Example

Public Const AnalogRadioCLSID As String = "{8A674B4C-1F63-11d3-B64C-00C04F79498E}"
Public Const AnalogTVCLSID As String = "{8A674B4D-1F63-11D3-B64C-00C04F79498E}"
Public Const AtscCLSID As String = "{A2E30750-6C3D-11D3-B653-00C04F79498E}"
Public Const DvbcLSID As String = "{C6B14B32-76AA-4A86-A7AC-5C79AAF58DA7}"
Public Const DVBSCLSID As String = "{B64016F3-C9A2-4066-96F0-BD9563314726}"
Dim mTuningSpaces As New SystemTuningSpaces
Dim objTuningSpaces As ITuningSpaces
objTuningSpaces = mTuningSpaces.TuningSpacesForCLSID(AtscCLSID)

See Also

  • SystemTuningSpaces Object


SystemTuningSpaces.TuningSpacesForName

The TuningSpacesForName function returns the collection of tuning space objects where each tuning space object contains the specified string in the FriendlyName.

Syntax

objSystemTuningSpaces.TuningSpacesForName(Name As String) As ITuningSpaces

Parameters

strName

Specifies the search string as a String.

Error Codes

If the method fails, an error is raised and Err.Number is set to a value other than zero.

Return Value

This method returns an ITuningSpaces collection as an Object.

Remarks

The FriendlyName of each of the tuning space objects contains strName.

See Also

  • SystemTuningSpaces Object


Microsoft Unified Tuning Model Constants (Visual Basic)

Constant | Description
BinaryConvolutionCodeRate | Specifies the binary convolution code rate used in the forward error correction scheme.
ComponentCategory | Specifies the type of content in an Advanced Television System Committee (ASTC) sub-stream (component).
ComponentStatus | Specifies the status of a sub-stream (component).
DVBSystemType | Specifies the type of Digital Video Broadcasting (DVB) system supported in a Tuning Space.
FECMethod | Specifies the type of forward error correction being used by the provider.
GuardInterval | Specifies the guard interval on a Digital Video Broadcasting-Terrestrial (DVB-T) system.
HierarchyAlpha | Specifies the hierarchy alpha on a Digital Video Broadcasting-Terrestrial (DVB-T) system.
ModulationType | Specifies the modulation type.
MPEG2StreamType | Specifies the MPEG stream type.
Polarisation | Specifies the polarization type.
SpectralInversion | Indicates the type of spectral inversion on Quadrature Phase Shift Keying in a Broadcast Driver Architecture capture device.
TransmissionMode | Specifies the transmission mode.
TunerInputType | Specifies the frequency of a TV tuner (cable or antenna).


BinaryConvolutionCodeRate Constants

Specifies the binary convolution code rate used in the forward error correction scheme.

Constant | Value | Description
BDA_BCC_RATE_NOT_SET | -1 | Indicates that no rate is specified.
BDA_BCC_RATE_NOT_DEFINED | 0 | Indicates that the rate is not defined.
BDA_BCC_RATE_1_2 | 1 | Indicates that the rate is 1/2.
BDA_BCC_RATE_2_3 | 2 | Indicates that the rate is 2/3.
BDA_BCC_RATE_3_4 | 3 | Indicates that the rate is 3/4.
BDA_BCC_RATE_3_5 | 4 | Indicates that the rate is 3/5.
BDA_BCC_RATE_4_5 | 5 | Indicates that the rate is 4/5.
BDA_BCC_RATE_5_6 | 6 | Indicates that the rate is 5/6.
BDA_BCC_RATE_5_11 | 7 | Indicates that the rate is 5/11.
BDA_BCC_RATE_7_8 | 8 | Indicates that the rate is 7/8.
BDA_BCC_RATE_MAX | 9 | Indicates the maximum rate.


ComponentCategory Constants

Specifies the type of content in an Advanced Television System Committee (ASTC) sub-stream (component).

Constant | Value | Description
CategoryNotSet | -1 | Category is not set.
CategoryOther | 0 | Content other than Video, Audio, Text or Data.
CategoryVideo | 1 | Content is Video.
CategoryAudio | 2 | Content is Audio
CategoryText | 3 | Content is Text.
CategoryData | 4 | Content is Data.


ComponentStatus Constants

Specifies the status of a sub-stream (component).

Constant | Value | Description
StatusActive | -1 | Active status.
StatusInactive | 0 | Inactive status.
StatusUnavailable | 1 | Unavailable status.


DVBSystemType Constants

Specifies the type of Digital Video Broadcasting (DVB) system supported in a Tuning Space.

Constant | Value | Description
DVB_Cable | -1 | Indicates a cable DVB system.
DVB_Terrestrial | 0 | Indicates a terrestrial DVB system (broadcast antenna).
DVB_Satellite | 1 | Indicates a satellite DVB system


FECMethod Constants

Specifies the type of forward error correction being used by the provider.

Constant | Value | Description
BDA_FEC_METHOD_NOT_SET | -1 | The FEC method is not set.
BDA_FEC_METHOD_NOT_DEFINED | 0 | The FEC method is not defined.
BDA_FEC_VITERBI | 1 | The FEC is a Viterbi Binary Convolution.
BDA_FEC_RS_204_188 | 2 | The FEC is Reed-Solomon 204/188 (outer FEC).
BDA_FEC_MAX | 3 | The FEC is the maximum.


GuardInterval Constants

Specifies the guard interval on a Digital Video Broadcasting-Terrestrial (DVB-T) system.

Constant | Value | Description
BDA_GUARD_NOT_SET | -1 | The guard interval is not set.
BDA_GUARD_NOT_DEFINED | 0 | The guard interval is not defined.
BDA_GUARD_1_32 | 1 | The guard interval is 1/32.
BDA_GUARD_1_16 | 2 | The guard interval is 1/16.
BDA_GUARD_1_8 | 3 | The guard interval is 1/8.
BDA_GUARD_1_4 | 4 | The guard interval is 1/4.
BDA_GUARD_MAX | 5 | The guard interval is the maximum.


HierarchyAlpha Constants

Specifies the hierarchy alpha on a Digital Video Broadcasting-Terrestrial (DVB-T) system.

Constants | Value | Description
BDA_HALPHA_NOT_SET | -1 | The hierarchy alpha is not set.
BDA_HALPHA_NOT_DEFINED | 0 | The hierarchy alpha is not defined.
BDA_HALPHA_1 | 1 | The hierarchy alpha is 1.
BDA_HALPHA_2 | 2 | The hierarchy alpha is 2.
BDA_HALPHA_4 | 3 | The hierarchy alpha is 4.
BDA_HALPHA_MAX | 4 | The hierarchy alpha is the maximum.


ModulationType Constants

Specifies the modulation type.

Constant | Value | Description
BDA_MOD_NOT_SET | -1 | Modulation not set.
BDA_MOD_NOT_DEFINED | 0 | Modulation not defined.
BDA_MOD_16QAM | 1 | 16 symbol Quadrature Amplitude Modulation.
BDA_MOD_32QAM | 2 | 32 symbol Quadrature Amplitude Modulation.
BDA_MOD_64QAM | 3 | 64 symbol Quadrature Amplitude Modulation.
BDA_MOD_80QAM | 4 | 80 symbol Quadrature Amplitude Modulation.
BDA_MOD_96QAM | 5 | 96 symbol Quadrature Amplitude Modulation.
BDA_MOD_112QAM | 6 | 112 symbol Quadrature Amplitude Modulation.
BDA_MOD_128QAM | 7 | 128 symbol Quadrature Amplitude Modulation.
BDA_MOD_160QAM | 8 | 160 symbol Quadrature Amplitude Modulation.
BDA_MOD_192QAM | 9 | 192 symbol Quadrature Amplitude Modulation
BDA_MOD_224QAM | 10 | 224 symbol Quadrature Amplitude Modulation.
BDA_MOD_256QAM | 11 | 256 symbol Quadrature Amplitude Modulation.
BDA_MOD_320QAM | 12 | 320 symbol Quadrature Amplitude Modulation.
BDA_MOD_384QAM | 13 | 384 symbol Quadrature Amplitude Modulation.
BDA_MOD_448QAM | 14 | 448 symbol Quadrature Amplitude Modulation.
BDA_MOD_512QAM | 15 | 512 symbol Quadrature Amplitude Modulation.
BDA_MOD_640QAM | 16 | 640 symbol Quadrature Amplitude Modulation.
BDA_MOD_768QAM | 17 | 768 symbol Quadrature Amplitude Modulation.
BDA_MOD_896QAM | 18 | 896 symbol Quadrature Amplitude Modulation.
BDA_MOD_1024QAM | 19 | 1024 symbol Quadrature Amplitude Modulation.
BDA_MOD_QPSK | 20 | Quadrature Phase-Shift Keying modulation.
BDA_MOD_BPSK | 21 | Binary Phase Shift Keying modulation.
BDA_MOD_OQPSK | 22 | Offset Quadrature Phase-Shift Keying modulation.
BDA_MOD_8VSB | 23 | 8 Vestigial Side-Band modulation.
BDA_MOD_16VSB | 24 | 16 Vestigial Side-Band modulation.
BDA_MOD_ANALOG_AMPLITUDE | 25 | Analog Amplitude modulation.
BDA_MOD_ANALOG_FREQUENCY | 26 | Analog Frequency modulation.
BDA_MOD_MAX | 27 | Maximum Modulation.


MPEG2StreamType Constants

Specifies the MPEG stream type.

Constant | Value | Description
BDA_UNITIALIZED_MPEG2STREAMTYPE | -1 | MPEG-2 un-initialized streams.
Reserved1 | 0 | Reserved for future use.
ISO_IEC_11172_2_VIDEO | 1 | MPEG-1 video streams.
ISO_IEC_13818_2_VIDEO | 2 | MPEG-2 video streams.
ISO_IEC_11172_3_AUDIO | 3 | MPEG-1 audio streams.
ISO_IEC_13818_3_AUDIO | 4 | MPEG-2 audio streams.
ISO_IEC_13818_1_PRIVATE_SECTION | 5 | MPEG-2 IPR protection.
ISO_IEC_13818_1_PES | 6 | MPEG-2 Packetized Elementary Streams.
ISO_IEC_13522_MHEG | 7 | MHEG-5 Audio-Visual streams.
ANNEX_A_DSM_CC | 8 | Digital Storage Media Command and Control streams.
ITU_T_REC_H_222_1 | 9 | ITU-T Satellite Audio-Visual streams.
ISO_IEC_13818_6_TYPE_A | 10 | MPEG-2 Video Clip A streams.
ISO_IEC_13818_6_TYPE_B | 11 | MPEG-2 Video Clip B streams.
ISO_IEC_13818_6_TYPE_C | 12 | MPEG-2 Video Clip C streams.
ISO_IEC_13818_6_TYPE_D | 13 | MPEG-2 Video Clip D streams.
ISO_IEC_13818_1_AUXILIARY | 14 | MPEG-2 Auxiliary streams.
ISO_IEC_13818_1_RESERVED | 15 | MPEG-2 Reserved streams.
USER_PRIVATE | 16 | User proprietary streams.


Polarisation Constants

Specifies the polarization type.

Constant | Value | Description
BDA_POLARISATION_NOT_SET | -1 | Polarization not set.
BDA_POLARISATION_NOT_DEFINED | 0 | Polarization not defined.
BDA_POLARISATION_LINEAR_H | 1 | Linear horizontal polarization.
BDA_POLARISATION_LINEAR_V | 2 | Linear vertical polarization.
BDA_POLARISATION_CIRCULAR_L | 3 | Circular right polarization.
BDA_POLARISATION_CIRCULAR_R | 4 | Circular left polarization.
BDA_POLARISATION_MAX | 5 | Maximum polarization.


SpectralInversion Constants

Indicates the type of spectral inversion on Quadrature Phase Shift Keying in a Broadcast Driver Architecture capture device.

Constant | Value | Description
BDA_SPECTRAL_INVERSION_NOT_SET | -1 | Spectral Inversion is not set.
BDA_SPECTRAL_INVERSION_NOT_DEFINED | 0 | Spectral Inversion is not defined.
BDA_SPECTRAL_INVERSION_AUTOMATIC | 1 | Spectral Inversion is automatic.
BDA_SPECTRAL_INVERSION_NORMAL | 2 | Spectral Inversion is normal.
BDA_SPECTRAL_INVERSION_INVERTED | 3 | Spectral Inversion is inverted.
BDA_SPECTRAL_INVERSION_MAX | 4 | Spectral Inversion is at maximum.


TransmissionMode Constants

Specifies the transmission mode.

Constant | Value | Description
BDA_XMIT_MODE_NOT_SET | -1 | Transmission mode is not set.
BDA_XMIT_MODE_NOT_DEFINED | 0 | Transmission mode is not defined.
BDA_XMIT_MODE_2K | 1 | Transmission uses 1705 carriers (use a 2K FFT).
BDA_XMIT_MODE_8K | 2 | Transmission uses 6817 carriers (use an 8K FFT).
BDA_XMIT_MODE_MAX | 3 | Transmission mode at maximum.


TunerInputType Constants

Specifies the frequency of a TV tuner (cable or antenna).

Constant | Value | Description
TunerInputCable | -1 | Indicates cable frequency.
TunerInputAntenna | 0 | Indicates broadcast antenna frequency.


DirectShow Editing Services C++ Reference

This section contains all the Microsoft® DirectShow® Editing Services reference information. This material is presented in the following articles:

  • Interfaces
  • Structures
  • Enumerated Types
  • Constants
  • Transitions and Effects
  • DirectShow Editing Services Objects
  • XTL Reference
  • Rendering Errors

See Also

  • DirectShow Editing Services


Interfaces

This section contains reference entries for all the Microsoft DirectShow Editing Services (DES) COM interfaces and their methods.

Interface | Description
IAMErrorLog | Provides a callback method for error logging.
IAMSetErrorLog | Sets or retrieves an error log.
IAMTimeline | Provides methods for manipulating the timeline.
IAMTimelineComp | Inserts or retrieves virtual tracks on a composition.
IAMTimelineEffect | Provides methods for manipulating.
IAMTimelineEffectable | Provides methods for adding effects to a timeline object.
IAMTimelineGroup | Sets and retrieves properties on groups.
IAMTimelineObj | Provides methods for manipulating timeline objects.
IAMTimelineSplittable | Splits a timeline object.
IAMTimelineSrc | Provides methods for manipulating and setting properties on source objects.
IAMTimelineTrack | Provides methods for manipulating track objects.
IAMTimelineTrans | Provides methods for manipulating transition objects.
IAMTimelineTransable | Adds transitions to an object.
IAMTimelineVirtualTrack | Provides methods for working with virtual tracks.
IDxtAlphaSetter | Sets properties on the Alpha Setter effect.
IDxtCompositor | Sets properties on the Compositor transition.
IDxtJpeg | Sets properties on the SMPTE Wipe transition.
IDxtKey | Sets properties on the Key transition.
IFindCompressorCB | Not supported.
IGrfCache | Not supported.
IMediaDet | Retrieves information about a media file, such as the number of streams and the type, duration, and frame rate of each stream.
IMediaLocator | Provides methods for validating file names.
IPropertySetter | Sets properties on an effect or transition.
IRenderEngine | Renders a DES project by constructing a filter graph from a timeline.
IRenderEngine2 | Enables the application to replace the default video resizing filter used by DES.
IResize | Must be supported by any custom video resizer filter.
ISmartRenderEngine | Provides methods that support smart recompression.
IXml2Dex | Saves and loads DES project files in Extensible Markup Language (XML).


IAMErrorLog Interface

The IAMErrorLog interface provides a callback method for error logging in DirectShow Editing Services (DES).

DES does not implement this interface. To perform error logging, implement this interface in your application and call IAMSetErrorLog::put_ErrorLog on the timeline. If an error occurs when you render the project, DES will call the IAMErrorLog::LogError method implemented by your application.

DES logs errors only when you render a project using the IRenderEngine interface. For example, if you save a project as a DirectShow filter graph (.grf format) and play the graph file, there is no error logging. For more information on using this interface, see Logging Errors.

In addition to the methods inherited from IUnknown, the IAMErrorLog interface exposes the following methods.

Method | Description
LogError | Logs an error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMErrorLog::LogError

The LogError method logs an error. Applications do not need to call this method. It is called internally in response to rendering errors.

Syntax

HRESULT LogError(
    LONG Severity,
    BSTR ErrorString,
    LONG ErrorCode,
    HRESULT hresult,
    VARIANT *pExtraInfo
);

Parameters

Severity

Reserved. Do not use.

ErrorString

String value containing the text of the error.

ErrorCode

Error code.

hresult

The HRESULT value that was returned by the method call that caused the error.

pExtraInfo

[in] Pointer to a VARIANT that contains any additional information about the error.

Return Value

Returns an HRESULT value. Return the value of the hresult parameter.

Remarks

Within this method, do not free the VARIANT pointed to by pExtraInfo. Also, the VARIANT becomes invalid after the method returns, so do not try to reference it later.

Implement this method to return as quickly as possible. Do not make function calls from inside this method that might block program execution. For example, do not call Microsoft® Win32® functions that send window messages, block on events, or otherwise might block execution. Doing so could cause the computer to stop responding, or "hang."

For a list of errors defined by DES, along with the meaning and data type of the VARIANT pointed to by pExtraInfo, see Rendering Errors.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMErrorLog Interface
  • Error and Success Codes


IAMSetErrorLog Interface

The IAMSetErrorLog interface sets or retrieves an error log in DirectShow Editing Services (DES). The timeline object implements this interface. Applications can use this interface to log rendering errors at run time. Implement the IAMErrorLog interface in your application, and then call the IAMSetErrorLog::put_ErrorLog method on the timeline.

For more information on using this interface, see Logging Errors.

In addition to the methods inherited from IUnknown, the IAMSetErrorLog interface exposes the following methods.

Method | Description
get_ErrorLog | Retrieves the current error log for this object.
put_ErrorLog | Specifies an error log for the object.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMSetErrorLog::get_ErrorLog

The get_ErrorLog method retrieves the current error log for this object.

Syntax

HRESULT get_ErrorLog(
    IAMErrorLog **pVal
);

Parameters

pVal

[out, retval] Address of a pointer that receives the error log's IAMErrorLog interface. If the timeline does not have an error log, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in pVal is not NULL, the IAMErrorLog interface has an outstanding reference count. Be sure to release the interface when you are done using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMSetErrorLog Interface
  • Error and Success Codes


IAMSetErrorLog::put_ErrorLog

The put_ErrorLog method specifies an error log for the object.

Syntax

HRESULT put_ErrorLog(
    IAMErrorLog *newVal
);

Parameters

newVal

[in] Pointer to the error log's IAMErrorLog interface.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMSetErrorLog Interface
  • Error and Success Codes


IAMTimeline Interface

The IAMTimeline interface provides methods for manipulating the timeline, the central object in Microsoft DirectShow Editing Services (DES). A timeline is a collection of time-ordered elements, such as video clips, audio clips, effects, and transitions between clips. The render engine uses the timeline to create a filter graph, from which the application can generate the rendered output.

IAMTimeline performs three basic services. It

  • Creates the objects in the timeline.
  • Acts as a container for those objects.
  • Sets and retrieves general parameters of the timeline.

To create the timeline object, call CoCreateInstance with the class identifier CLSID_AMTimeline.

In addition to the methods inherited from IUnknown, the IAMTimeline interface exposes the following methods.

Method | Description
AddGroup | Adds a group to the timeline.
ClearAllGroups | Removes all groups from the timeline, along with all objects contained in those groups.
CreateEmptyNode | Creates a new timeline object.
EffectsEnabled | Determines whether effects are enabled.
EnableEffects | Enables or disables all effects in the timeline.
EnableTransitions | Enables or disables all transitions in the timeline.
GetCountOfType | Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.
GetDefaultEffect | Retrieves the default effect.
GetDefaultEffectB | Retrieves the default effect as a BSTR value.
GetDefaultFPS | Retrieves the default output frame rate, in frames per second.
GetDefaultTransition | Retrieves the default transition.
GetDefaultTransitionB | Retrieves the default transition as a BSTR value.
GetDirtyRange | Not supported.
GetDuration | Retrieves the timeline duration.
GetDuration2 | Retrieves the timeline duration as a double.
GetGroup | Retrieves a specified group.
GetGroupCount | Retrieves the number of groups that are contained in the timeline.
GetInsertMode | Not supported.
IsDirty | Not supported.
RemGroupFromList | Not supported.
SetDefaultEffect | Sets the default effect.
SetDefaultEffectB | Sets the default effect as a BSTR value.
SetDefaultFPS | Sets the default output frame rate, in frames per second.
SetDefaultTransition | Sets the default transition.
SetDefaultTransitionB | Sets the default transition as a BSTR value.
SetInsertMode | Not implemented.
SetInterestRange | Not implemented.
TransitionsEnabled | Determines whether transitions are enabled.
ValidateSourceNames | Validates source names in the timeline.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimeline::AddGroup

The AddGroup method adds a group to the timeline.

Syntax

HRESULT AddGroup(
    IAMTimelineObj *pGroup
);

Parameters

pGroup

Pointer to the IAMTimelineObj interface of the group.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | Maximum number of groups exceeded.
E_NOINTERFACE | The object is not a group.

Remarks

Currently, timelines support a maximum of 32 groups.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::ClearAllGroups

The ClearAllGroups method removes all groups from the timeline, along with all objects contained in those groups.

Syntax

HRESULT ClearAllGroups( void );

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::CreateEmptyNode

The CreateEmptyNode method creates a new timeline object.

Use this method to create timeline objects, rather than the CoCreateInstance function, because this method performs important initialization routines. Every object created by this method supports at least the IAMTimelineObj interface, along with other interfaces specific to that type of object.

Syntax

HRESULT CreateEmptyNode(
    IAMTimelineObj **ppObj,
    TIMELINE_MAJOR_TYPE Type
);

Parameters

ppObj

[out] Address of a pointer that receives the new object's IAMTimelineObj interface.

Type

Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to create.

Return Value

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Object type is not valid.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Do not add the new object to another timeline instance. Every object in a timeline must be created by that timeline.

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::EffectsEnabled

The EffectsEnabled method determines whether effects are enabled. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

HRESULT EffectsEnabled(
    BOOL *pfEnabled
);

Parameters

pfEnabled

Pointer to a variable that receives a Boolean value indicating whether effects are enabled. If TRUE, effects are enabled. If FALSE, effects are disabled.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::EnableEffects

The EnableEffects method enables or disables all effects in the timeline. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

HRESULT EnableEffects(
    BOOL fEnabled
);

Parameters

fEnabled

Boolean value that specifies whether to enable or disable effects. If TRUE, effects are enabled. If FALSE, effects are disabled.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::EnableTransitions

The EnableTransitions method enables or disables all transitions in the timeline. If transitions are disabled, the render engines treats them as cuts; that is, the rendered output jumps instantly from one track to the next. The default cut point is halfway through the duration of the transition. You can change the cut point by calling the IAMTimelineTrans::SetCutPoint method on the transition. Disabled transitions are not removed from the timeline.

Syntax

HRESULT EnableTransitions(
    BOOL fEnabled
);

Parameters

fEnabled

Boolean value that specifies whether to enable or disable transitions. If TRUE, transitions are enabled. If FALSE, transitions are disabled.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetCountOfType

The GetCountOfType method retrieves the number of objects of the specified type that are contained in a specified group and all of its children.

Syntax

HRESULT GetCountOfType(
    long Group,
    long *pVal,
    long *pValWithComps,
    TIMELINE_MAJOR_TYPE MajorType
);

Parameters

Group

Index number of the group for which to retrieve the count.

pVal

Pointer to a variable that receives the number of objects of the specified type contained in the group and all of its virtual tracks, recursively.

pValWithComps

Pointer to a variable that receives the count returned in pVal plus the number of compositions searched, including this one.

MajorType

Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Return Value

Returns one of the following HRESULT values.

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid group number.
E_POINTER | NULL pointer argument.

Remarks

Calling this method is equivalent to calling IAMTimelineComp::GetCountOfType on the specified group. See the Remarks section of that method for more information.

Typically, an application will not call this method. It is called internally by the render engine.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDefaultEffect

The GetDefaultEffect method retrieves the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

HRESULT GetDefaultEffect(
    GUID *pGuid
);

Parameters

pGuid

Pointer to a variable that receives the globally unique identifier (GUID) of the default effect.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDefaultEffectB

The GetDefaultEffectB method retrieves the default effect. This method is equivalent to IAMTimeline::GetDefaultEffect, but receives a BSTR value rather than a GUID.

Syntax

HRESULT GetDefaultEffectB(
    BSTR *pGuid
);

Parameters

pGuid

[out, retval] Pointer to a variable that receives a BSTR value representing the GUID of the default effect.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDefaultFPS

The GetDefaultFPS method retrieves the default output frame rate, in frames per second (FPS). Groups use this value as their default frame rate. To set a group's frame rate, call the IAMTimelineGroup::SetOutputFPS method on the group.

Syntax

HRESULT GetDefaultFPS(
    double *pFPS
);

Parameters

pFPS

Pointer to a variable that receives the default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDefaultTransition

The GetDefaultTransition method retrieves the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

HRESULT GetDefaultTransition(
    GUID *pGuid
);

Parameters

pGuid

Pointer to a variable that receives the GUID of the default transition.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDefaultTransitionB

The GetDefaultTransitionB method retrieves the default transition. This method is equivalent to IAMTimeline::GetDefaultTransition, but receives a BSTR value, rather than a GUID.

Syntax

HRESULT GetDefaultTransitionB(
    BSTR *pGuid
);

Parameters

pGuid

[out, retval] Pointer to a variable that receives a BSTR value representing the GUID of the default transition.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDirtyRange

Not supported.

Syntax

HRESULT GetDirtyRange(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

See Also

  • IAMTimeline Interface


IAMTimeline::GetDuration

The GetDuration method retrieves the duration of the timeline.

Syntax

HRESULT GetDuration(
    REFERENCE_TIME *pDuration
);

Parameters

pDuration

Pointer to a variable that receives the duration of the timeline, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetDuration2

The GetDuration2 method retrieves the duration of the timeline. This method is equivalent to IAMTimeline::GetDuration, but takes a parameter of type double.

Syntax

HRESULT GetDuration2(
    double *pDuration
);

Parameters

pDuration

Pointer to a variable that receives the duration of the timeline, in fractional seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetGroup

The GetGroup method retrieves a specified group.

Syntax

HRESULT GetGroup(
    IAMTimelineObj **ppGroup,
    long WhichGroup
);

Parameters

ppGroup

[out] Address of a pointer that receives the group's IAMTimelineObj interface.

WhichGroup

Index of the group to retrieve, based on the order in which the groups were added to the timeline. The first group added to the timeline has an index of 0.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetGroupCount

The GetGroupCount method retrieves the number of groups that are contained in the timeline.

Syntax

HRESULT GetGroupCount(
    long *pCount
);

Parameters

pCount

Pointer to a variable that receives the number of groups in the timeline.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::GetInsertMode

Not supported.

Syntax

HRESULT GetInsertMode(
    long *pMode
);

See Also

  • IAMTimeline Interface


IAMTimeline::IsDirty

Not supported.

Syntax

HRESULT IsDirty(
    BOOL *pDirty
);

See Also

  • IAMTimeline Interface


IAMTimeline::RemGroupFromList

Not supported.

Syntax

HRESULT RemGroupFromList(
    IAMTimelineObj *pGroup
);

See Also

  • IAMTimeline Interface


IAMTimeline::SetDefaultEffect

The SetDefaultEffect method sets the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

HRESULT SetDefaultEffect(
    GUID *pGuid
);

Parameters

pGuid

Pointer to a variable that contains the GUID of the default effect.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If you do not set a default effect, or if the effect that you specify as a default causes an error, DES uses its own default effect.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::SetDefaultEffectB

The SetDefaultEffectB method sets the default effect. This method is equivalent to IAMTimeline::SetDefaultEffect, but takes a BSTR value, rather than a pointer to a GUID.

Syntax

HRESULT SetDefaultEffectB(
    BSTR pGuid
);

Parameters

pGuid

BSTR value representing the GUID of the default effect.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::SetDefaultFPS

The SetDefaultFPS method sets the default output frame rate, in frames per second. Groups use this value as their default frame rate. To set a group's frame rate, call the IAMTimelineGroup::SetOutputFPS method on the group.

Syntax

HRESULT SetDefaultFPS(
    double FPS
);

Parameters

FPS

Default frame rate, in frames per second.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::SetDefaultTransition

The SetDefaultTransition method sets the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

HRESULT SetDefaultTransition(
    GUID *pGuid
);

Parameters

pGuid

Pointer to a variable that contains the GUID of the default transition.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If you do not set a default transition, or if the transition that you specify as a default causes an error, DES uses its own default transition.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::SetDefaultTransitionB

The SetDefaultTransitionB method sets the default transition. This method is equivalent to IAMTimeline::SetDefaultTransition, but takes a BSTR value, rather than a pointer to a GUID.

Syntax

HRESULT SetDefaultTransitionB(
    BSTR pGuid
);

Parameters

pGuid

BSTR value representing the GUID of the default transition.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimeline::SetInsertMode

Not implemented.

Syntax

HRESULT SetInsertMode(
    long Mode
);

See Also

  • IAMTimeline Interface


IAMTimeline::SetInterestRange

Not implemented.

Syntax

HRESULT SetInterestRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

See Also

  • IAMTimeline Interface


IAMTimeline::TransitionsEnabled

The TransitionsEnabled method determines whether transitions are enabled.

Syntax

HRESULT TransitionsEnabled(
    BOOL *pfEnabled
);

Parameters

pfEnabled

Pointer to a variable that receives a Boolean value. If TRUE, transitions are enabled. Otherwise, transitions are disabled.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • IAMTimeline::EnableTransitions
  • Error and Success Codes


IAMTimeline::ValidateSourceNames

The ValidateSourceNames method validates source names in the timeline, using the media locator. Optionally, this method also updates any source object for which it locates a file.

Syntax

HRESULT ValidateSourceNames(
    long ValidateFlags,
    IMediaLocator *pOverride,
    long NotifyEventHandle
);

Parameters

ValidateFlags

Bitwise combination of File Name Validation Flags specifying the behavior of the media locator. The SFN_VALIDATEF_REPLACE and SFN_VALIDATEF_CHECK flags must be present, or the method returns E_INVALIDARG.

pOverride

Optional pointer to the IMediaLocator interface of a media locator to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.

NotifyEventHandle

Handle to an event. The method signals the event after it has completed the validation.

Return Value

Returns S_OK if successful. Otherwise, returns E_INVALIDARG or another error code.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the IMediaLocator interface. For example, the default media locator will not notify your application about the files that it finds (or cannot find). To get around this limitation, you could implement a custom media locator, making it a wrapper for the default version. In your custom version, pass IMediaLocator::FindMediaFile calls directly to the default version, and examine the return value.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimeline Interface
  • Error and Success Codes


IAMTimelineComp Interface

The IAMTimelineComp interface inserts or retrieves virtual tracks on a composition in DirectShow Editing Services (DES).

A composition is a collection of layers that acts as a single, composited track. For example, a composition that contains two tracks with a transition between them acts as a single track with the transition precomposited. A composition should contain media of only one type (such as audio or video), but this limitation is not enforced. A virtual track is any object that can reside in a composition, including tracks and other compositions.

The topmost nodes in the timeline are groups. Groups implement both the IAMTimelineComp interface and the IAMTimelineGroup interface.

To create a composition object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_COMPOSITE. You can query the returned IAMTimelineObj pointer for the IAMTimelineComp interface. For more information, see The Timeline Model and Constructing a Timeline.

In addition to the methods inherited from IUnknown, the IAMTimelineComp interface exposes the following methods.

Method | Description
GetCountOfType | Retrieves the number of objects of a given type contained in this composition and all of its virtual tracks, recursively.
GetNextVTrack | Retrieves the next virtual track after a specified virtual track.
GetRecursiveLayerOfType | Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.
GetRecursiveLayerOfTypeI | Not supported.
GetVTrack | Retrieves the virtual track at the specified priority.
VTrackGetCount | Retrieves the number of virtual tracks contained in the composition.
VTrackInsBefore | Inserts a virtual track into the composition at the specified priority.
VTrackSwapPriorities | Switches the priority levels of two tracks.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineComp::GetCountOfType

The GetCountOfType method retrieves the number of objects of a given type contained in this composition and all its virtual tracks, recursively.

Syntax

HRESULT GetCountOfType(
    long *pVal,
    long *pValWithComps,
    TIMELINE_MAJOR_TYPE MajorType
);

Parameters

pVal

Pointer to a variable that receives the number of objects of the specified type contained in this composition and all its virtual tracks, recursively.

pValWithComps

Pointer to a variable that receives the count returned in pVal plus the number of compositions searched, including this one.

MajorType

Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Typically, an application will not call this method. It is called by the render engine.

If you count compositions, the value returned in pVal is zero and the value returned in pValWithComps is the number of compositions. The value of *pValWithComps includes the composition on which you call the method. For example, if you call this method on an empty composition, *pValWithComps equals 1.

Groups cannot reside inside compositions, so you cannot use this method to count groups. (The returned count will always be zero.) To count groups, call the IAMTimeline::GetGroupCount method.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::GetNextVTrack

The GetNextVTrack method retrieves the next virtual track after a specified virtual track.

Syntax

HRESULT GetNextVTrack(
    IAMTimelineObj *pVirtualTrack,
    IAMTimelineObj **ppNextVirtualTrack
);

Parameters

pVirtualTrack

Pointer to the previous virtual track, or NULL to retrieve the first virtual track in the composition.

ppNextVirtualTrack

[out] Address of a pointer that receives the IAMTimelineObj interface of the next virtual track, in order of priority.

Return Value

Returns S_OK if the method retrieves a virtual track, or S_FALSE otherwise.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::GetRecursiveLayerOfType

The GetRecursiveLayerOfType method performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.

Syntax

HRESULT GetRecursiveLayerOfType(
    IAMTimelineObj **ppVirtualTrack,
    long WhichLayer,
    TIMELINE_MAJOR_TYPE Type
);

Parameters

ppVirtualTrack

[out] Address of a pointer that receives the virtual track's IAMTimelineObj interface.

WhichLayer

Value that specifies which virtual track to retrieve, indexed from zero.

Type

Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies whether to include tracks in the search.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | No object of the specified type.
E_POINTER | NULL pointer argument.

Remarks

Typically, an application will not need to call this method.

If the Type parameter is TIMELINE_MAJOR_TYPE_TRACK, the depth-first ordering includes tracks. If not, it includes only compositions and groups. The object itself is included in the ordering.

For example, in the following arrangement, starting from Composition A, the ordering would be B, C, F, D, E, A.

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::GetRecursiveLayerOfTypeI

Not supported. Call the IAMTimelineComp::GetRecursiveLayerOfType method instead.

Syntax

HRESULT GetRecursiveLayerOfTypeI(
    IAMTimelineObj **ppVirtualTrack,
    long *pWhichLayer,
    TIMELINE_MAJOR_TYPE Type
);

See Also

  • IAMTimelineComp Interface


IAMTimelineComp::GetVTrack

The GetVTrack method retrieves the virtual track at the specified priority.

Syntax

HRESULT GetVTrack(
    IAMTimelineObj **ppVirtualTrack,
    long Which
);

Parameters

ppVirtualTrack

[out] Address of a pointer that receives the virtual track's IAMTimelineObj interface.

Which

Priority of the virtual track to retrieve.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | No virtual track with the specified priority.
E_POINTER | NULL pointer argument.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::VTrackGetCount

The VTrackGetCount method retrieves the number of virtual tracks contained in the composition.

Syntax

HRESULT VTrackGetCount(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the number of virtual tracks.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::VTrackInsBefore

The VTrackInsBefore method inserts a virtual track into the composition at the specified priority.

Syntax

HRESULT VTrackInsBefore(
    IAMTimelineObj *pVirtualTrack,
    long Priority
);

Parameters

pVirtualTrack

Pointer to the IAMTimelineObj interface of the virtual track.

Priority

Priority at which to insert the virtual track, or –1 to insert the virtual track at the end of the priority list. The priority list determines which clips are visible. See Remarks for more information.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object is not a virtual track.

Remarks

Each virtual track in composition has a unique priority level. Priority levels range from 0 to n - 1, where n is the number of virtual tracks in the composition. For video groups, a virtual track hides any virtual tracks with a lower priority level, except in places where the track is empty or contains a transition. You can think of virtual tracks as being layers in the final composition. Track 1 is layered on top of track 0, track 2 is layered on top of track 1, and so forth.

If you specify -1 for the Priority parameter, the virtual track is inserted at the end of the list, with a higher priority value than the existing tracks. If you specify a priority value that already exists in the composition, every track with an equal or greater priority moves up one priority level.

Example: Track A has priority 0, and track B has priority 1. If track C is inserted at priority 0, track A moves to priority 1, and track B moves to priority 2.

If the specified priority is greater than the current number of tracks in the composition, the method fails.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineComp::VTrackSwapPriorities

The VTrackSwapPriorities method switches the priority levels of two tracks.

Given two priority levels, this method switches the virtual tracks at those priorities. When the method returns, the track that was at the first priority level is now at the second priority level, and vice versa.

Syntax

HRESULT VTrackSwapPriorities(
    long VirtualTrackA,
    long VirtualTrackB
);

Parameters

VirtualTrackA

First priority level at which to swap virtual tracks.

VirtualTrackB

Second priority level at which to swap virtual tracks.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineComp Interface
  • Error and Success Codes


IAMTimelineEffect Interface

The IAMTimelineEffect interface provides methods for manipulating audio and video effects in DirectShow Editing Services (DES). An effect can be added to any timeline object that exposes the IAMTimelineEffectable interface. To set properties on an effect, use the IPropertySetter interface.

The DES effect object is actually a wrapper for one of two other objects:

  • For audio effects, any DirectShow audio effect filter.
  • For video effects, and 1-input DirectX Transform object.

Microsoft no longer supports the development of third-party DirectX Transform objects.

To specify the filter or DirectX Transform object for an effect, call the IAMTimelineObj::SetSubObjectGUID method.

To create an effect object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_EFFECT. You can query the returned IAMTimelineObj pointer for the IAMTimelineEffect interface.

In addition to the methods inherited from IUnknown, the IAMTimelineEffect interface exposes the following method.

Method | Description
EffectGetPriority | Retrieves the effect's priority level.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Working with Effects and Transitions


IAMTimelineEffect::EffectGetPriority

The EffectGetPriority method retrieves the effect's priority level. For a given object, the render engine applies effects in order of priority, starting with priority level zero.

Syntax

HRESULT EffectGetPriority(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the priority level.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineEffect Interface
  • Error and Success Codes


IAMTimelineEffectable Interface

The IAMTimelineEffectable interface provides methods for adding effects to a timeline object in DirectShow Editing Services (DES), and for manipulating the effects on an object. All objects that can have effects applied to them implement this interface; this includes sources, tracks, and compositions.

An object that implements this interface can have any number of effects. For each object, the render engine applies its effects in order of priority, starting with priority level 0.

In addition to the methods inherited from IUnknown, the IAMTimelienEffectable interface exposes the following methods.

Method | Description
EffectGetCount | Retrieves the number of effects on this object.
EffectInsBefore | Inserts an effect into the object at the specified priority level.
EffectSwapPriorities | Switches the priority levels of two effects.
GetEffect | Retrieves the effect at the specified priority level.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineEffectable::EffectGetCount

The EffectGetCount method retrieves the number of effects on this object.

Syntax

HRESULT EffectGetCount(
    long *pCount
);

Parameters

pCount

Pointer to a variable that receives the number of effects.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineEffectable Interface
  • Error and Success Codes


IAMTimelineEffectable::EffectInsBefore

The EffectInsBefore method inserts an effect into the object at the specified priority level.

Syntax

HRESULT EffectInsBefore(
    IAMTimelineObj *pFX,
    long Priority
);

Parameters

pFX

Pointer to the IAMTimelineObj interface of the effect.

Priority

Priority level at which to insert the effect. Use the value –1 to insert the effect at the end of the priority list.

Return Value

Returns S_OK if successful or E_NOTIMPL if the object is not an effect. Otherwise, returns another HRESULT value indicating the cause of the error.

Remarks

The start and stop times of the effect are clipped within the bounds of the object's time range, if necessary. If there is already an effect at the specified priority level, all the effects from that point on move down the priority list to make room for the new effect.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineEffectable Interface
  • Error and Success Codes


IAMTimelineEffectable::EffectSwapPriorities

The EffectSwapPriorities method switches the priority levels of two effects.

Given two priority values, this method swaps the effects at those priorities. When the method returns, the effect that was at the first priority level is at the second priority level, and vice versa.

Syntax

HRESULT EffectSwapPriorities(
    long PriorityA,
    long PriorityB
);

Parameters

PriorityA

First priority level at which to swap effects.

PriorityB

Second priority level at which to swap effects.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineEffectable Interface
  • Error and Success Codes


IAMTimelineEffectable::GetEffect

The GetEffect method retrieves the effect at the specified priority level.

Syntax

HRESULT GetEffect(
    IAMTimelineObj **ppFx,
    long Which
);

Parameters

ppFX

[out] Address of a pointer that receives the effect's IAMTimelineObj interface.

Which

Priority level of the effect to retrieve.

Return Value

Returns an HRESULT value. Possible values include the following:

Return code | Description
S_FALSE | No effect at the specified priority,
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineEffectable Interface
  • Error and Success Codes


IAMTimelineGroup Interface

The IAMTimelineGroup interface sets and retrieves properties on groups in DirectShow Editing Services (DES).

A group contains one or more tracks, and possibly one or more compositions, which in turn contain source clips of a uniform type, such as video or audio. Groups are the topmost compositions in a timeline, and also expose the IAMTimelineComp interface. A timeline can contain multiple groups.

Each group has the following attributes.

  • An associated media type.
  • The frame rate at which the group renders, in frames per second (FPS). All edits occur at a time rounded to the nearest frame boundary, as defined by the group's FPS setting.
  • A priority level, for writing files with multiple streams of the same media type (for example, a two-video-stream AVI file).

To create a group object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_GROUP. You can query the returned IAMTimelineObj pointer for the IAMTimelineGroup interface.

In addition to the methods inherited from IUnknown, the IAMTimelineGroup interface exposes the following methods.

Method | Description
ClearRecompressFormatDirty | Not supported.
GetGroupName | Retrieves the application-defined name of the group.
GetMediaType | Retrieves the uncompressed media type for the group.
GetOutputBuffering | Retrieves the number of frames rendered in advance during preview.
GetOutputFPS | Retrieves the output frame rate of this group.
GetPreviewMode | Retrieves the preview mode for the group.
GetPriority | Retrieves the group's priority.
GetSmartRecompressFormat | Retrieves the current compression format for smart recompression.
GetTimeline | Retrieves the timeline to which this group belongs.
IsRecompressFormatDirty | Not supported.
IsSmartRecompressFormatSet | Determines whether a smart compression format was set for the group.
SetGroupName | Sets the application-defined name of the group.
SetMediaType | Sets the uncompressed media type for the group.
SetMediaTypeForVB | Specifies the group media type, for Automation clients.
SetOutputBuffering | Specifies the number of frames rendered in advance during preview.
SetOutputFPS | Sets the uncompressed output frame rate for this group.
SetPreviewMode | Sets the preview mode for the group.
SetSmartRecompressFormat | Specifies a compression format to use for smart recompression.
SetRecompFormatFromSource | Sets the video recompression format using the compression format from a source file.
SetTimeline | Not supported.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineGroup::ClearRecompressFormatDirty

Not supported.

Syntax

HRESULT ClearRecompressFormatDirty(void);

See Also

  • IAMTimelineGroup Interface


IAMTimelineGroup::GetGroupName

The GetGroupName method retrieves the application-defined name of the group.

Syntax

HRESULT GetGroupName(
    BSTR *pGroupName
);

Parameters

pGroupName

[out, retval] Pointer to a variable of type BSTR that receives the name of the group.

Return Value

Returns S_OK if successful. Otherwise, returns E_POINTER or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetMediaType

The GetMediaType method retrieves the uncompressed media type for the group.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[out] Pointer to an AM_MEDIA_TYPE structure that is filled with the media type.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

The caller must free the returned media type's format block, given in the pbFormat member of the returned AM_MEDIA_TYPE structure. You can use the helper function FreeMediaType from the base class library.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetOutputBuffering

The GetOutputBuffering method retrieves the number of frames rendered in advance during preview.

Syntax

HRESULT GetOutputBuffering(
    int *pnBuffer
);

Parameters

pnBuffer

[out] Pointer to a variable that receives the number of buffered frames.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetOutputFPS

The GetOutputFPS method retrieves the output frame rate of this group.

Syntax

HRESULT GetOutputFPS(
    double *pFPS
);

Parameters

pFPS

Pointer to a variable that receives the output frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetPreviewMode

The GetPreviewMode method retrieves the preview mode for the group.

Syntax

HRESULT GetPreviewMode(
    BOOL *pfPreview
);

Parameters

pfPreview

Pointer to a variable that receives a Boolean value indicating the preview mode. If TRUE, the group is in preview mode. If FALSE, the group is in authoring mode.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might become out of sync with the audio.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetPriority

The GetPriority method retrieves the group's priority.

Syntax

HRESULT GetPriority(
    long *pPriority
);

Parameters

pPriority

Pointer to a variable that receives the group's priority.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetSmartRecompressFormat

The GetSmartRecompressFormat method retrieves the current compression format for smart recompression.

Syntax

HRESULT GetSmartRecompressFormat(
   long **ppFormat
);

Parameters

ppFormat

Address of a variable that receives a pointer to an SCompFmt0 structure, cast as a pointer to a long. If the method fails, the value is set to NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

Return code | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

If the application has not set a smart compression format (by calling IAMTimelineGroup::SetSmartRecompressFormat), the format returned by this method will be invalid. Call the IAMTimelineGroup::IsSmartRecompressFormatSet method to determine whether a compression format was set.

If the method succeeds, the caller must free the returned media type and delete the SCompFmt0 structure:

if (pFormat) {
    FreeMediaType(pFormat->MediaType);
    delete pFormat;
}

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::GetTimeline

The GetTimeline method retrieves the timeline to which this group belongs.

Syntax

HRESULT GetTimeline(
    IAMTimeline **ppTimeline
);

Parameters

ppTimeline

[out] Address of a pointer that receives the timeline's IAMTimeline interface. If the group is not part of a timeline, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in ppTimeline is not NULL, the IAMTimeline interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::IsRecompressFormatDirty

Not supported.

Syntax

HRESULT IsRecompressFormatDirty(
    BOOL *pVal
);

See Also

  • IAMTimelineGroup Interface


IAMTimelineGroup::IsSmartRecompressFormatSet

The IsSmartRecompressFormatSet method determines whether a smart recompression format was set for the group.

Syntax

HRESULT IsSmartRecompressFormatSet(
    BOOL *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value indicating whether a compression format was set. If TRUE, a compression format was set.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetGroupName

The SetGroupName method sets the application-defined name of the group.

Syntax

HRESULT SetGroupName(
    BSTR pGroupName
);

Parameters

pGroupName

BSTR that specifies the name of the group. The maximum length of the name is 256 characters, incuding the null terminator.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetMediaType

The SetMediaType method sets the uncompressed media type for the group.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[in] Pointer to an AM_MEDIA_TYPE structure describing the format.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | The specified media type is invalid.

Remarks

Currently, the following media types are supported:

  • Uncompressed RGB video
  • 16 bits per pixel, 555 format (MEDIASUBTYPE_RGB555)
  • 24 bits per pixel (MEDIASUBTYPE_RGB24)
  • 32 bits per pixel, with alpha (MEDIASUBTYPE_ARGB32, not MEDIASUBTYPE_RGB32)
  • 16-bit stereo PCM audio (MEDIASUBTYPE_PCM)

Video types must use FORMAT_VideoInfo for the format type and VIDEOINFOHEADER for the format block. The VIDEOINFOHEADER2 format is not supported. Also, top-down video formats (biHeight < 0) are not supported.

To specify a compression format for the group, call the IAMTimelineGroup::SetSmartRecompressFormat method.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetMediaTypeForVB

The SetMediaTypeForVB method specifies the group media type, for Automation clients.

Syntax

HRESULT SetMediaTypeForVB(
    long Val
);

Parameters

Val

[in] Value that specifies the media type. Set the value to 0 for video, or 1 for audio.

Return Value

Returns S_OK.

Remarks

This method is intended for Automation clients. For C++ applications, use the IAMTimelineGroup::SetMediaType method.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetOutputBuffering

The SetOutputBuffering method specifies the number of frames rendered in advance during preview.

Syntax

HRESULT SetOutputBuffering(
    int nBuffer
);

Parameters

nBuffer

[in] Number of frames to buffer during preview. Must be two or greater.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

A larger buffer requires more memory but can result in smoother previewing, especially during effects or transitions that require more time to render. The default buffer is 30 frames.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetOutputFPS

The SetOutputFPS method sets the uncompressed output frame rate for this group.

Syntax

HRESULT SetOutputFPS(
    double FPS
);

Parameters

FPS

Output frame rate for this group, in frames per second. The value cannot equal zero, and cannot have more than seven digits after the decimal place.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

Rendered output from this group runs at the specified frame rate, and all edits on the source material are rounded to the nearest frame boundary, as defined by the frame rate. For best performance, use the same frame rate for all groups, video and audio.

The IAMTimelineGroup::SetSmartRecompressFormat method overwrites the frame rate.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetPreviewMode

The SetPreviewMode method sets the preview mode for the group.

Syntax

HRESULT SetPreviewMode(
    BOOL fPreview
);

Parameters

fPreview

Boolean value that specifies the preview mode. If TRUE, the group is in preview mode. If FALSE, the group is in authoring mode.

Return Value

Returns S_OK.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might be out of sync with the audio.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetRecompFormatFromSource

The SetRecompFormatFromSource method sets the video recompression format using the compression format from a source file.

Syntax

HRESULT SetRecompFormatFromSource(
    IAMTimelineSrc *pSource
);

Parameters

pSource

Pointer to the IAMTimelineSrc interface of the source object.

Return Value

Returns an HRESULT values. Possible values include the following.

Return code | Description
S_OK | Success.
E_NO_TIMELINE | The group is not within a timeline.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type. The group is not a video group, or the source file has no video stream.

Remarks

This method finds the source file associated with pSource, retrieves the media type of the first video stream in the file, and sets the group compression format using that type. For more information about compression formats, see IAMTimelineGroup::SetSmartRecompressFormat.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes


IAMTimelineGroup::SetSmartRecompressFormat

The SetSmartRecompressFormat method specifies a video compression format to use for smart recompression.

Smart recompression is not supported for audio groups.

Syntax

HRESULT SetSmartRecompressFormat(
    long *pFormat
);

Parameters

pFormat

Pointer to a structure describing the compression format. Currently, only the SCompFmt0 structure is valid. You must cast this parameter to a pointer of type long.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.

Remarks

Before calling this method, call the IAMTimelineGroup::SetMediaType method on the same group, to specify an uncompressed format.

If the SetSmartRecompressFormat method succeeds, you can use the Smart Render Engine to output a compressed video stream. The compressed video will have the width, height, and frame rate that was specified in the pFormat parameter. These values will override those given for the uncompressed format in the SetMediaType method. However, to get the benefits of smart recompression, the two formats should match. In other words, the compressed and uncompressed formats should have the same height, width, and frame rate.

If the Smart Render Engine is unable to produce the compressed format, it will produce an uncompressed video stream instead. If that occurs, the Smart Render Engine reports a DEX_IDS_CANT_FIND_COMPRESSOR rendering error during the IRenderEngine::ConnectFrontEnd method. The application can catch this error through the IAMErrorLog::LogError method. (For more information, see Logging Errors and Rendering Errors.)

The smart recompression format is not persistent. If an application uses smart recompression, it must set the recompression format whenever it loads a project file.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineGroup Interface
  • Error and Success Codes
  • Smart Render Engine
  • Writing a Project to a File


IAMTimelineGroup::SetTimeline

Not supported. Call the IAMTimeline::AddGroup method instead.

Syntax

HRESULT SetTimeline(
    IAMTimeline *pTimeline
);

See Also

  • IAMTimelineGroup Interface


IAMTimelineObj Interface

The IAMTimelineObj interface provides methods for manipulating timeline objects in DirectShow Editing Services (DES). All timeline objects implement this method, including source, effect, transition, track, group, and composition objects. Create a timeline object by calling the IAMTimeline::CreateEmptyNode method.

In addition to the methods inherited from IUnknown, the IAMTimelineObj interface exposes the following methods.

Method | Description
ClearDirty | Not supported.
FixTimes | Rounds the specified start and stop times to the nearest frame boundaries.
FixTimes2 | Rounds the specified start and stop times, specified as REFTIME values, to the nearest frame boundaries.
GetDirtyRange | Not supported.
GetDirtyRange2 | Not supported.
GetEmbedDepth | Not supported.
GetGenID | Retrieves the object's generated identifier.
GetGroupIBelongTo | Not supported.
GetLocked | Retrieves the object's editing state (locked or unlocked).
GetMuted | Retrieves the object's muted state.
GetPropertySetter | Retrieves the object's property setter.
GetStartStop | Retrieves the object's start and stop times, relative to the object's parent.
GetStartStop2 | Retrieves the object's start and stop times, as REFTIME values.
GetSubObject | Retrieves the subobject associated with this object.
GetSubObjectGUID | Retrieves the GUID of the subobject associated with this timeline object.
GetSubObjectGUIDB | Retrieves the GUID of the subobject as a BSTR value.
GetSubObjectLoaded | Determines whether the object's subobject pointer has been set.
GetTimelineNoRef | Not supported.
GetTimelineType | Retrieves the object's type.
GetUserData | Retrieves the application-defined persistent data.
GetUserID | Retrieves the object's application-defined identifier.
GetUserName | Retrieves the object's application-defined name.
Remove | Removes this object from the timeline, for reinsertion elsewhere.
RemoveAll | Permanently removes this object from the timeline, including subobjects and children.
SetDirtyRange | Not implemented.
SetDirtyRange2 | Not implemented.
SetLocked | Sets the object's editing state to locked or unlocked.
SetMuted | Sets the object's muted state.
SetPropertySetter | Sets the object's property setter.
SetStartStop | Sets the object's start and stop times, relative to the timeline.
SetStartStop2 | Sets the object's start and stop times, as REFTIME values.
SetSubObject | Not supported.
SetSubObjectGUID | Specifies the globally unique identifier (GUID) of the subobject associated with this object.
SetSubObjectGUIDB | Specifies the GUID of the subobject as a BSTR value.
SetTimelineType | Not supported.
SetUserData | Sets application-defined persistent data.
SetUserID | Sets an application-defined identifier for the object.
SetUserName | Sets an application-defined name for the object.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineObj::ClearDirty

Not supported.

Syntax

HRESULT ClearDirty( void );

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::FixTimes

The FixTimes method rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.

Syntax

HRESULT FixTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart

Pointer to a variable that contains the start time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

pStop

Pointer to a variable that contains the stop time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_NOTINTREE if the object is not part of a group.

Remarks

During rendering, DES rounds the object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Time in DirectShow Editing Services.

Use this method to determine accurate start and stop times in the rendered project. For example, you should seek to the rounded times, rather than the object's original start and stop times. Call IAMTimelineObj::GetStartStop to obtain the original times, and pass those values to FixTimes.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::FixTimes2

The FixTimes2 method rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting. This method is equivalent to IAMTimelineObj::FixTimes, but takes REFTIME values.

Syntax

HRESULT FixTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart

Pointer to a variable that contains the start time, in seconds. If the call succeeds, this variable is set to the rounded time.

pStop

Pointer to a variable that contains the stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_NOTINTREE if the object is not part of a group.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetDirtyRange

Not supported.

Syntax

HRESULT GetDirtyRange(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::GetDirtyRange2

Not supported.

Syntax

HRESULT GetDirtyRange2(
    REFTIME *pStart,
    REFTIME *pStop
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::GetEmbedDepth

Not supported.

Syntax

HRESULT GetEmbedDepth(
    long *pVal
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::GetGenID

The GetGenID method retrieves the object's generated identifier. The identifier is a reserved number; applications should not use it.

Syntax

HRESULT GetGenID(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the generated identifier.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetGroupIBelongTo

Not supported.

Syntax

HRESULT GetGroupIBelongTo(
    IAMTimelineGroup **ppGroup
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::GetLocked

The GetLocked method retrieves the object's editing state (locked or unlocked). A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

GetLocked(
    BOOL *pVal
);

Parameters

pVal

Pointer to a Boolean variable that receives the object's editing state. If the value is TRUE, the object is locked and should not be edited. If FALSE, the object is unlocked and can be edited.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetMuted

The GetMuted method retrieves the object's muted state.

Syntax

HRESULT GetMuted(
    BOOL *pVal
);

Parameters

pVal

Pointer to a Boolean variable that receives a value indicating the muted state. If the value is TRUE, the object and its children are muted.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If an object's parent is muted, the object is muted regardless of its muted state. When the parent is no longer muted, the object's previous muted state is restored.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetPropertySetter

The GetPropertySetter method retrieves the object's property setter. When the object is rendered, the property information contained in the property setter is applied to the object.

Syntax

HRESULT GetPropertySetter(
    IPropertySetter **pVal
);

Parameters

pVal

[out, retval] Address of a pointer that receives the property setter's IPropertySetter interface. If the object does not have a property setter, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in pVal is not NULL, the IPropertySetter interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetStartStop

The GetStartStop method retrieves the object's start and stop times, relative to the object's parent.

Syntax

HRESULT GetStartStop(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart

Pointer to a variable that receives the start time, in 100-nanosecond units.

pStop

Pointer to a variable that receives the stop time, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Compositions, groups, and tracks always have a start time of 0.

During rendering, DES rounds an object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, Time in DirectShow Editing Services.

To determine the start and stop times in the rendered project, pass the values returned by GetStartStop to the IAMTimelineObj::FixTimes method.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetStartStop2

The GetStartStop2 method retrieves the object's start and stop times, relative to the object's parent. This method is equivalent to IAMTimelineObj::GetStartStop, but takes REFTIME values.

Syntax

HRESULT GetStartStop2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart

Pointer to a variable that receives the start time, in seconds.

pStop

Pointer to a variable that receives the stop time, in seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetSubObject

The GetSubObject method retrieves the subobject associated with this object.

Syntax

HRESULT GetSubObject(
    IUnknown **pVal
);

Parameters

pVal

[out, retval] Address of a pointer that receives the subobject's IUnknown interface. If the object does not have a subobject, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Every timeline object can hold a pointer to an associated subobject.

If the value returned in pVal is not NULL, the IUnknown interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetSubObjectGUID

The GetSubObjectGUID method retrieves the GUID of the subobject associated with this timeline object.

Syntax

HRESULT GetSubObjectGUID(
    GUID *pVal
);

Parameters

pVal

Pointer to a variable that receives the GUID of the subobject, or GUID_NULL if the object does not have a subobject.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetSubObjectGUIDB

The GetSubObjectGUIDB method retrieves the GUID of the subobject associated with this timeline object. This method is equivalent to IAMTimelineObj::GetSubObjectGUID, but receives a BSTR value.

Syntax

HRESULT GetSubObjectGUIDB(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a BSTR that receives a string representing the subobject GUID.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetSubObjectLoaded

The GetSubObjectLoaded method determines whether the subobject pointer has been set.

Syntax

HRESULT GetSubObjectLoaded(
    BOOL *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value. If the value is TRUE, the subobject pointer has been set. If FALSE, the pointer has not been set.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetTimelineNoRef

Not supported.

Syntax

HRESULT GetTimelineNoRef(
    IAMTimeline **ppResult
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::GetTimelineType

The GetTimelineType method retrieves the object's type.

Syntax

HRESULT GetTimelineType(
    TIMELINE_MAJOR_TYPE *pVal
);

Parameters

pVal

Pointer to a variable that receives a member of the TIMELINE_MAJOR_TYPE enumerated type, indicating the type of object.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetUserData

The GetUserData method retrieves the application-defined persistent data.

Syntax

HRESULT GetUserData(
    BYTE *pData,
    long *pSize
);

Parameters

pData

Pointer to a buffer that receives the data. To determine the size of buffer to allocate, set this parameter to NULL. The required size is returned in pSize.

pSize

Pointer to a variable that receives the size of the data, in bytes.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetUserID

The GetUserID method retrieves the object's application-defined identifier.

Syntax

HRESULT GetUserID(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the application-defined identifier.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::GetUserName

The GetUserName method retrieves the object's application-defined name.

Syntax

HRESULT GetUserName(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a BSTR that receives the name of the object.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::Remove

The Remove method removes this object from the timeline (including subobjects but not children), for reinsertion elsewhere.

Syntax

HRESULT Remove( void );

Return Value

Returns S_OK.

Remarks

Call this method only if the application will immediately insert the object back into the timeline. It is an invalid operation to call this method without then reinserting the object. To remove an object permanently, call IAMTimelineObj::RemoveAll.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::RemoveAll

The RemoveAll method permanently removes this object from the timeline, including subobjects and children.

Syntax

HRESULT RemoveAll( void );

Return Value

Returns S_OK.

Remarks

To remove an object for the purpose of reinserting it elsewhere in the timeline, call IAMTimelineObj::Remove.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetDirtyRange

Not implemented.

Syntax

HRESULT SetDirtyRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::SetDirtyRange2

Not implemented.

Syntax

HRESULT SetDirtyRange2(
    REFTIME Start,
    REFTIME Stop
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::SetLocked

The SetLocked method sets the object's editing state to locked or unlocked.

A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

HRESULT SetLocked(
    BOOL newVal
);

Parameters

newVal

Boolean value that specifies the object's editing state. If TRUE, the object is locked and should not be edited. If FALSE, the object is unlocked and can be edited.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetMuted

The SetMuted method sets the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

HRESULT SetMuted(
    BOOL newVal
);

Parameters

newVal

Flag that specifies the muted state. If TRUE, the object and all of its children are muted.

Return Value

Returns S_OK.

Remarks

Muting an object also mutes any children contained in the object. For example, if you mute a track, the transitions, sources, and effects in that track are also muted. Once the object is no longer muted, its children revert to their previous state, which might be muted or unmuted.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetPropertySetter

The SetPropertySetter method sets the object's property setter. When the object is rendered, the property information contained in the property setter is applied to the object. Call this method on transition and effect objects.

Syntax

HRESULT SetPropertySetter(
    IPropertySetter *newVal
);

Parameters

newVal

Pointer to the property setter's IPropertySetter interface.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetStartStop

The SetStartStop method sets the object's start and stop times, relative to the object's parent.

Syntax

HRESULT SetStartStop(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start

New start time, in 100-nanosecond units, or –1 to keep the existing start time.

Stop

New stop time, in 100-nanosecond units, or –1 to keep the existing stop time.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

Tracks, compositions, and groups do not implement this method. For these objects, the start time is always zero, and the stop time is the maximum stop time of the objects they contain.

Do not set overlapping times on source objects within the same track. Doing so can cause undefined behaviors.

For source objects, the start and stop times are independent of the media start and media stop times. Changing one pair of values does not change the other. To set the media start and stop times, call the IAMTimelineSrc::SetMediaTimes method. For more information, see Time in DirectShow Editing Services.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetStartStop2

The SetStartStop2 method sets the object's start and stop times, relative to the object's parent. This method is equivalent to IAMTimelineObj::SetStartStop, but takes REFTIME values.

Syntax

HRESULT SetStartStop2(
    REFTIME Start,
    REFTIME Stop
);

Parameters

Start

New start time, in seconds, or –1 to keep the existing start time.

Stop

New stop time, in seconds, or –1 to keep the existing stop time.

Return Value

Returns one of the following HRESULT values:

Return code | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetSubObject

Not supported.

Syntax

HRESULT SetSubObject(
    IUnknown *newVal
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::SetSubObjectGUID

The SetSubObjectGUID method specifies the GUID of the subobject associated with this object.

Syntax

HRESULT SetSubObjectGUID(
    GUID newVal
);

Parameters

newVal

GUID of the subobject.

Return Value

Returns S_OK.

Remarks

The render engine creates an instance of the subobject as needed.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetSubObjectGUIDB

The SetSubObjectGUIDB method specifies the GUID of the subobject associated with this object. This method is equivalent to IAMTimelineObj::SetSubObjectGUID but takes a BSTR value.

Syntax

HRESULT SetSubObjectGUIDB(
    BSTR newVal
);

Parameters

newVal

BSTR representing the GUID of the subobject.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetTimelineType

Not supported. Call the IAMTimeline::CreateEmptyNode method to create a new timeline object. Once an object is created, you cannot change its type.

Syntax

HRESULT SetTimelineType(
    TIMELINE_MAJOR_TYPE newVal
);

See Also

  • IAMTimelineObj Interface


IAMTimelineObj::SetUserData

The SetUserData method sets application-defined persistent data.

Syntax

HRESULT SetUserData(
    BYTE *pData,
    long Size
)

Parameters

pData

Pointer to a buffer containing the data.

Size

Size of the data, in bytes.

Return Value

Returns S_OK if successful, or E_OUTOFMEMORY if there is insufficient memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetUserID

The SetUserID method sets an application-defined identifier for the object.

Syntax

HRESULT SetUserID(
    long newVal
);

Parameters

newVal

Value that specifies the identifier. This identifier is used only by the application and can be any value.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineObj::SetUserName

The SetUserName method sets an application-defined name for the object.

Syntax

HRESULT SetUserName(
    BSTR newVal
);

Parameters

newVal

Wide-character string that contains the name. Strings longer than 256 characters might be truncated.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineObj Interface
  • Error and Success Codes


IAMTimelineSplittable Interface

The IAMTimelineSplittable interface splits a timeline object in DirectShow Editing Services (DES). Sources, effects, transitions, and tracks implement this interface.

In addition to the methods inherited from IUnknown, the IAMTimelineSplittable interface exposes the following methods.

Method | Description
SplitAt | Splits the object at the specified time.
SplitAt2 | Splits the object at the specified time, specified as a REFTIME value.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineSplittable::SplitAt

The SplitAt method splits the object at the specified time.

Syntax

HRESULT SplitAt(
    REFERENCE_TIME Time
);

Parameters

Time

Time at which to split the object, relative to the start of the timeline, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | Nothing to split.
S_OK | Success.
E_INVALIDARG | The object does not exist at this time.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you split a source, effect, or transition, this method creates a second object of the same type. The original object is truncated at the specified split time, and the new object replaces the truncated portion. The new object inherits all of the same properties. In a source object, the method also splits any effects that fall on the split time.

Calling this method on a track splits all the sources, effects, and transitions that are contained in the track at the specified split time. It does not create a second track. (A track begins at time zero and extends to infinity.)

For a track, if the split time is later than everything in the track, the method returns S_FALSE. For any other object, if the split time does not fall anywhere within the object, the method returns E_INVALIDARG.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSplittable Interface
  • Error and Success Codes


IAMTimelineSplittable::SplitAt2

The SplitAt2 method splits the object at the specified time. This method is equivalent to IAMTimelineSplittable::SplitAt, but takes a REFTIME value.

Syntax

HRESULT SplitAt2(
    REFTIME Time
);

Parameters

Time

Time at which to split the object, relative to the start of the timeline, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | Nothing to split.
S_OK | Success.
E_INVALIDARG | The object does not exist at this time.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSplittable Interface
  • Error and Success Codes


IAMTimelineSrc Interface

The IAMTimelineSrc interface provides methods for manipulating and setting properties on source objects in DirectShow Editing Services (DES). A source object represents one stream from a media source.

You can use a portion of the data within a source file by setting the media start and media stop times. These values specify the beginning and end of the source object, relative to the original media source. The media times can differ from the object's start and stop times on the timeline, allowing for fast- or slow-motion playback. (With audio sources, pitch shifting occurs.)

To create a source object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_SOURCE. You can query the returned IAMTimelineObj pointer for the IAMTimelineSrc interface. For more information, see Constructing a Timeline and Working with Sources.

In addition to the methods inherited from IUnknown, the IAMTimelineSrc interface exposes the following methods.

Method | Description
GetDefaultFPS | Retrieves the source object's default frame rate.
GetMediaName | Retrieves the name of the source file represented by this source object.
GetMediaTimes | Retrieves the media start and stop times.
GetMediaTimes2 | Retrieves the media start and stop times, as REFTIME values.
GetMediaLength | Retrieves the media length of this source object.
GetMediaLength2 | Retrieves the media length of this source object, as a REFTIME value.
GetStreamNumber | Retrieves the current stream number for the source object.
GetStretchMode | Retrieves the stretch mode of a video source.
FixMediaTimes | Rounds the specified time values to the nearest frame boundary.
FixMediaTimes2 | Rounds the specified time values, given as REFTIME values, to the nearest frame boundary.
IsNormalRate | Indicates whether the clip will play at the normal playback rate.
ModifyStopTime | Sets the stop time, relative to the timeline.
ModifyStopTime2 | Sets the stop time, as a REFTIME value.
SetDefaultFPS | Sets the source object's default frame rate.
SetMediaLength | Specifies the duration of the source file.
SetMediaLength2 | Specifies the duration of the source file, as a REFTIME value.
SetMediaName | Specifies the name of the source file represented by this source object.
SetMediaTimes | Sets the media stop and start times.
SetMediaTimes2 | Sets the media stop and start times, as REFTIME values.
SetStreamNumber | Specifies which stream to read from the source file associated with this source object.
SetStretchMode | Sets the stretch mode of a video source.
SpliceWithNext | Joins this source object to another source object.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineSrc::FixMediaTimes

The FixMediaTimes method rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. In general, applications do not need to call this method.

Syntax

HRESULT FixMediaTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart

Pointer to a variable that contains the start time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

pStop

Pointer to a variable that contains the stop time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

This method is similar to the IAMTimelineObj::FixTimes method, but it preserves the original ratio of media times and timeline times. Just rounding the times to the nearest frame boundary could distort this ratio.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::FixMediaTimes2

The FixMediaTimes2 method rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. This method is equivalent to IAMTimelineSrc::FixMediaTimes, but takes REFTIME values.

Syntax

HRESULT FixMediaTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart

Pointer to a variable that contains the start time, in seconds. If the call succeeds, this variable is set to the rounded time.

pStop

Pointer to a variable that contains the stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetDefaultFPS

The GetDefaultFPS method retrieves the source object's default frame rate. The render engine uses this value if it cannot determine the frame rate from the original source.

Syntax

HRESULT GetDefaultFPS(
    double *pFPS
);

Parameters

pFPS

Pointer to a variable that receives the default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

The default frame rate is not required if the file format specifies the frame rate. This is the case for audio and video formats.

If the source is a bitmap or JPEG image, the render engine uses it as the first image in a device-independent bitmap (DIB) sequence, with a frame rate equal to the default frame rate. To render a static image, rather than a DIB sequence, set the default frame rate to 0.

If the source is a GIF, do not set the frame rate. For animated GIFs, the GIF file specifies the delay between each image.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetMediaLength

The GetMediaLength method retrieves the media length of this source object.

Syntax

HRESULT GetMediaLength(
    REFERENCE_TIME *pLength
);

Parameters

pLength

Pointer to a variable that receives the media length in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_NOTDETERMINED | Media times are not set on this object.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • IAMTimelineSrc::SetMediaLength
  • Error and Success Codes


IAMTimelineSrc::GetMediaLength2

The GetMediaLength2 method retrieves the media length of this source object. This method is equivalent to IAMTimelineSrc::GetMediaLength, but takes REFTIME values.

Syntax

HRESULT GetMediaLength2(
    REFTIME *pLength
);

Parameters

pLength

Pointer to a variable that receives the media length in seconds.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_NOTDETERMINED | Media times are not set on this object.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetMediaName

The GetMediaName method retrieves the name of the source file represented by this source object.

Syntax

HRESULT GetMediaName(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a string that receives the name of the file.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetMediaTimes

The GetMediaTimes method retrieves the media start and stop times.

Syntax

HRESULT GetMediaTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart

Pointer to a variable that receives the media start time, in 100-nanosecond units.

pStop

Pointer to a variable that receives the media stop time, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

The media times are relative to the original media file. For more information, see Time in DirectShow Editing Services.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetMediaTimes2

The GetMediaTimes2 method retrieves the media start and stop times. This method is equivalent to IAMTimelineSrc::GetMediaTimes, but takes REFTIME values.

Syntax

HRESULT GetMediaTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart

Pointer to a variable that receives the media start time, in seconds.

pStop

Pointer to a variable that receives the media stop time, in seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetStreamNumber

The GetStreamNumber method retrieves the current stream number for the source object.

Syntax

HRESULT GetStreamNumber(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the stream number.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::GetStretchMode

The GetStretchMode method retrieves the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

HRESULT GetStretchMode(
    int *pnStretchMode
);

Parameters

pnStretchMode

Pointer to a variable that receives a flag indicating the current stretch mode. For a list of possible values, see Resize Flags.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::IsNormalRate

The IsNormalRate method indicates whether the clip will play at the normal playback rate; that is, the playback rate of the original file.

Syntax

HRESULT IsNormalRate(
    BOOL *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value indicating how the clip will render. If the value is TRUE, the clip will play at the normal rate. Otherwise, it will play faster or slower than normal.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

A clip's playback rate is determined by its media start and stop times, relative to its timeline times:

Playback rate = (Media Stop — Media Start) / (Timeline Stop — Timeline Start)

If this ratio is equal to 1, the clip plays at the authored speed. Otherwise, it plays faster or slower. For more information, see Time in DirectShow Editing Services.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::ModifyStopTime

The ModifyStopTime method sets the stop time, relative to the timeline.

Syntax

HRESULT ModifyStopTime(
    REFERENCE_TIME Stop
);

Parameters

Stop

New stop time, in 100-nanosecond units.

Return Value

Returns S_OK, or E_INVALIDARG if the specified time is not valid.

Remarks

This method is equivalent to calling IAMTimelineObj::SetStartStop with the original start time and a new stop time.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::ModifyStopTime2

The ModifyStopTime2 method sets the stop time. This method is equivalent to IAMTimelineSrc::ModifyStopTime, but takes a REFTIME value.

Syntax

HRESULT ModifyStopTime2(
    REFTIME Stop
);

Parameters

Stop

New stop time, in seconds.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the specified time is not valid.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetDefaultFPS

The SetDefaultFPS method sets the source object's default frame rate.

Syntax

HRESULT SetDefaultFPS(
    double FPS
);

Parameters

FPS

Default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the specified frame rate is less than zero.

Remarks

The render engine uses this value if it cannot determine the frame rate from the original source file.

Call this method only for source files without a predefined frame rate. For bitmap and JPEG files, the default frame rate is zero, which causes the source to be rendered as a still image. To use the image as the first frame in a DIB sequence set the frame rate to a value greater than zero. For more information, see Working with Sources.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetMediaLength

The SetMediaLength method specifies the duration of the source file.

Syntax

HRESULT SetMediaLength(
    REFERENCE_TIME Length
);

Parameters

Length

Media length, in 100-nanosecond units.

Return Value

Returns S_OK.

Remarks

You can avoid potential rendering errors by setting the media length before you set the media stop time. When you set the media stop time, DES checks it against the media length.

This method does not validate the Length parameter, but the value must equal the actual duration of the source file. Obtain the source file duration by calling IMediaDet::get_StreamLength.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetMediaLength2

The SetMediaLength2 method specifies the duration of the source file. This method is equivalent to IAMTimelineSrc::SetMediaLength, but takes a REFTIME value.

Syntax

HRESULT SetMediaLength2(
    REFTIME Length
);

Parameters

Length

Media length, in seconds.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetMediaName

The SetMediaName method specifies the name of the source file represented by this source object.

Syntax

HRESULT SetMediaName(
    BSTR newVal
);

Parameters

newVal

String that specifies the name of the media file.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetMediaTimes

The SetMediaTimes method sets the media stop and start times.

Syntax

HRESULT SetMediaTimes(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start

Media start time, in 100-nanosecond units.

Stop

Media stop time, in 100-nanosecond units.

Return Value

Returns S_OK.

Remarks

The media times are the stop and start times relative to the original media file. Always set the media times when you add a video or audio source to the timeline. Otherwise, rendering problems might occur. The stop time must be greater than the start time.

To use a still frame from a video source, set the stop time to a fractional amount more than the start time, such as 100 nanoseconds. Setting them to the same value causes a rendering error.

If the timeline duration does not match the media duration, the source stretches or shrinks accordingly. This causes the clip to play slower or faster than the authored rate. (Pitch shifting will occur in an audio source.) For more information, see Time in DirectShow Editing Services.

You can specify the duration of the source file by calling the SetMediaLength method. If you set a media stop time that exceeds the duration, DES truncates the stop time.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetMediaTimes2

The SetMediaTimes2 method sets the media stop and start times. This method is equivalent to IAMTimelineSrc::SetMediaTimes, but takes REFTIME values.

Syntax

HRESULT SetMediaTimes2(
    REFTIME Start,
    REFTIME Stop
);

Parameters

Start

Media start time, in seconds.

Stop

Media stop time, in seconds.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetStreamNumber

The SetStreamNumber method specifies which stream to read from the source file associated with this source object.

Syntax

HRESULT SetStreamNumber(
    long Val
);

Parameters

Val

The stream number, from the set of streams matching the media type of the parent group.

Return Value

Returns S_OK if successful, or E_INVALIDARG if Val is less than zero.

Remarks

The Val parameter specifies a stream number from the set of streams that matches the parent group's media type, not from the entire set of streams in the source file. For example, For example, suppose that a file contains two video streams and two audio streams. If the source object is inside a video group, setting Val to 0 selects the first video stream. The caller is responsible for specifying a valid stream number.

The stream number defaults to zero.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SetStretchMode

The SetStretchMode method sets the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

HRESULT SetStretchMode(
    int nStretchMode
);

Parameters

nStretchMode

Flag indicating the current stretch mode. For a list of possible values, see Resize Flags.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineSrc::SpliceWithNext

The SpliceWithNext method joins the source object to another source object.

Syntax

HRESULT SpliceWithNext(
    IAMTimelineObj *pNext
);

Parameters

pNext

Pointer to the IAMTimelineObj interface of the source object to join to the current source.

Return Value

Returns an HRESULT value. Possible return values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pNext parameter is not a source object.
E_POINTER | NULL pointer argument.

Remarks

As currently implemented, this method discards any effects on pNext.

For this method to succeed, pNext must be a match frame of the current source object, defined as follows:

  • It must share the same source file.
  • The media start time must equal the media stop time of the current source.
  • The playback rate must be the same. Playback rate is media duration divided by timeline duration.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineSrc Interface
  • Error and Success Codes


IAMTimelineTrack Interface

The IAMTimelineTrack interface provides methods for manipulating track objects in DirectShow Editing Services (DES).

A track contains a list of sources that are rendered in the final output. Sources within the same track may not overlap. Video tracks can have both effects and transitions. The render engine applies effects before it applies transitions. Audio tracks can have effects, but not transitions. For more information, see The Timeline Model.

To create a track object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_TRACK. You can query the returned IAMTimelineObj pointer for the IAMTimelineTrack interface.

In addition to the methods inherited from IUnknown, the IAMTimelineTrack interface exposes the following methods.

Method | Description
AreYouBlank | Determines whether the track is blank (contains no source objects).
GetNextSrc | Searches the track for the next source that appears at the specified time or later.
GetNextSrc2 | Searches the track for the next source that appears at the specified time or later, with the given as a REFTIME value.
GetNextSrcEx | Retrieves the next source after the specified source.
GetSourcesCount | Retrieves the number of sources in the track.
GetSrcAtTime | Retrieves the source object nearest to the specified time, according to the specified boundary conditions.
GetSrcAtTime2 | Retrieves the source object nearest to the specified time, given as a REFTIME value.
InsertSpace | Splits any objects that exist at the specified time and inserts space between them.
InsertSpace2 | Splits any objects that exist at the specified time and inserts space between them, using REFTIME values.
MoveEverythingBy | Not supported.
MoveEverythingBy2 | Not supported.
SrcAdd | Adds a source to the track.
ZeroBetween | Removes everything from the track between the specified times.
ZeroBetween2 | Removes everything from the track between the specified times, given as REFTIME values.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineTrack::AreYouBlank

The AreYouBlank method determines whether the track is blank (contains no source objects).

Syntax

HRESULT AreYouBlank(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value specifying whether the track is blank. If the value is TRUE, the track is blank and contains no source objects. If FALSE, the track is not blank.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetNextSrc

The GetNextSrc method searches the track for the next source that appears at the specified time or later.

Syntax

HRESULT GetNextSrc(
    IAMTimelineObj **ppSrc,
    REFERENCE_TIME *pInOut
);

Parameters

ppSrc

[out] Address of a pointer that receives the source object's IAMTimelineObj interface.

pInOut

Pointer to a variable that contains the start time for the search, in 100-nanosecond units. If the method retrieves a source, it sets the value to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

Remarks

If the time specified by pInOut falls between the start and stop times of a source, the method retrieves that source.

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetNextSrc2

The GetNextSrc2 method searches the track for the next source that appears at the specified time or later. This method is equivalent to IAMTimelineTrack::GetNextSrc, but takes a REFTIME value.

Syntax

HRESULT GetNextSrc2(
    IAMTimelineObj **ppSrc,
    REFTIME *pInOut
);

Parameters

ppSrc

[out] Address of a pointer that receives the source object's IAMTimelineObj interface.

pInOut

Pointer to a variable that contains the start time for the search, in seconds. If the method retrieves a source, it sets the value to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetNextSrcEx

The GetNextSrcEx method retrieves the next source after the specified source.

Syntax

HRESULT GetNextSrcEx(
    IAMTimelineObj *pLast,
    IAMTimelineObj **ppNext
);

Parameters

pLast

Pointer to the previous source object, or NULL to retrieve the first source in the track.

ppNext

[out] Address of a pointer that receives the next source object's IAMTimelineObj interface.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetSourcesCount

The GetSourcesCount method retrieves the number of sources in the track.

Syntax

HRESULT GetSourcesCount(
    long *pVal
);

Parameters

pVal

Pointer to a variable that receives the number of sources in the track.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetSrcAtTime

The GetSrcAtTime method retrieves the source object nearest to the specified time, according to the specified boundary conditions.

Syntax

HRESULT GetSrcAtTime(
    IAMTimelineObj **ppSrc,
    REFERENCE_TIME Time,
    long SearchDirection
);

Parameters

ppSrc

[out] Address of a pointer that receives the IAMTimelineObj interface of the source object.

Time

Start time for the search, in 100-nanosecond units.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | Did not locate a source object.
S_OK | Located a source object.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::GetSrcAtTime2

The GetSrcAtTime2 method retrieves the source object nearest to the specified time, according to the specified boundary conditions. This method is equivalent to IAMTimelineTrack::GetSrcAtTime, but takes a REFTIME value.

Syntax

HRESULT GetSrcAtTime2(
    IAMTimelineObj **ppSrc,
    REFTIME Time,
    long SearchDirection
);

Parameters

ppSrc

[out] Address of a pointer that receives the IAMTimelineObj interface of the source object.

Time

Start time for the search, in seconds.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | Did not locate a source object.
S_OK | Located a source object.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::InsertSpace

The InsertSpace method splits any objects that exist at the specified time and inserts space between them.

Syntax

HRESULT InsertSpace(
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtEnd
);

Parameters

rtStart

Time at which to create the split, and the starting point of the inserted space, in 100-nanosecond units.

rtEnd

End point of the inserted space, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible return values include the following:

Value | Description
S_FALSE | There are no objects at the specified time.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::InsertSpace2

The InsertSpace2 method splits any objects that exist at the specified time and inserts space between them. This method is equivalent to IAMTimelineTrack::InsertSpace, but takes REFTIME values.

Syntax

HRESULT InsertSpace2(
    REFTIME rtStart,
    REFTIME rtEnd
);

Parameters

rtStart

Time at which to create the split, and the starting point of the inserted space, in seconds.

rtEnd

End point of the inserted space, in seconds.

Return Value

Returns an HRESULT value. Possible return values include the following:

Value | Description
S_FALSE | There are no objects at the specified time.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::MoveEverythingBy

This method is not supported.

Syntax

HRESULT MoveEverythingBy(
    REFERENCE_TIME Start,
    REFERENCE_TIME MoveBy
);

See Also

  • IAMTimelineTrack Interface


IAMTimelineTrack::MoveEverythingBy2

This method is not supported.

Syntax

HRESULT MoveEverythingBy2(
    REFTIME Start,
    REFTIME MoveBy
);

See Also

  • IAMTimelineTrack Interface


IAMTimelineTrack::SrcAdd

The SrcAdd method adds a source to the track.

Syntax

HRESULT SrcAdd(
    IAMTimelineObj *pSrc
);

Parameters

pSrc

Pointer to the source object's IAMTimelineObj interface.

Return Value

Returns S_OK if successful. Returns E_NOINTERFACE if the object is not a source object. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

Set the source's start and stop times before calling this method. (Call IAMTimelineObj::SetStartStop.)

Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see IRenderEngine::SetDynamicReconnectLevel.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::ZeroBetween

The ZeroBetween method removes everything from the track between the specified times. This method splits any objects that span the specified time range and removes the pieces that fall within the range.

Syntax

HRESULT ZeroBetween(
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtEnd
);

Parameters

rtStart

Beginning of the range to clear, in 100-nanosecond units.

rtEnd

End of the range to clear, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The time range falls beyond everything in the track.
S_OK | Success.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrack::ZeroBetween2

The ZeroBetween2 method removes everything from the track between the specified times. This method is equivalent to IAMTimelineTrack::ZeroBetween, but takes REFTIME values.

Syntax

HRESULT ZeroBetween2(
    REFTIME rtStart,
    REFTIME rtEnd
);

Parameters

rtStart

Beginning of the range to clear, in seconds.

rtEnd

End of the range to clear, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The time range falls beyond everything in the track.
S_OK | Success.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrack Interface
  • Error and Success Codes


IAMTimelineTrans Interface

The IAMTimelineTrans interface provides methods for manipulating transitions in DirectShow Editing Services (DES). A transition is a progression between one video layer and the rendered composite of all video layers with a lower priority. A transition can be added to any timeline object that exposes the IAMTimelineTransable interface. To set properties on a transition, use the IPropertySetter interface.

The DES transition object is actually a wrapper for a DirectX Transform object. Any 2-input DirectX Transform object can be used to implement the visual effect for the transition. Microsoft no longer supports the development of third-party DirectX Transform objects. To specify the DirectX Transform object for a transition, call the IAMTimelineObj::SetSubObjectGUID method.

To create a transition object, call IAMTimeline::CreateEmptyNode with the value TIMELINE_MAJOR_TYPE_TRANSITION. You can query the returned IAMTimelineObj pointer for the IAMTimelineTrans interface.

In addition to the methods inherited from IUnknown, the IAMTimelineTrans interface exposes the following methods.

Method | Description
GetCutPoint | Retrieves the cut point.
GetCutPoint2 | Retrieves the cut point, as a REFTIME value.
GetCutsOnly | Determines whether the transition is rendered as a cut.
GetSwapInputs | Retrieves a value that indicates whether the transition inputs are swapped.
SetCutPoint | Sets the cut point.
SetCutPoint2 | Sets the cut point, as a REFTIME value.
SetSwapInputs | Specifies whether the transition inputs are swapped.
SetCutsOnly | Specifies whether the transition is rendered as a cut.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Working with Effects and Transitions


IAMTimelineTrans::GetCutPoint

The GetCutPoint method retrieves the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, this value is the middle of the transition. For example, in a transition that spans one second, the default cut point is 0.5 seconds into the transition.

Syntax

HRESULT GetCutPoint(
    REFERENCE_TIME *pTLTime
);

Parameters

pTLTime

Pointer to a variable that receives the cut point, relative to the start time of the transition, in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | The cut point was not set. The value returned is the default value.
S_OK | The cut point was set to a value other than the default.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • IAMTimelineTrans::SetCutPoint
  • IAMTimelineTrans::GetCutsOnly
  • IAMTimeline::TransitionsEnabled
  • Error and Success Codes


IAMTimelineTrans::GetCutPoint2

The GetCutPoint2 method retrieves the cut point. This method is equivalent to IAMTimelineTrans::GetCutPoint, but takes a REFTIME value.

Syntax

HRESULT GetCutPoint2(
    REFTIME *pTLTime
);

Parameters

pTLTime

Pointer to a variable that receives the cut point, relative to the start time of the transition, in seconds.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | The cut point was not set. The value returned is the default value.
S_OK | The cut point was set to a value other than the default.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTrans::GetCutsOnly

The GetCutsOnly method determines whether the transition is rendered as a cut. If so, the transition occurs instantaneously at the cut point.

Syntax

HRESULT GetCutsOnly(
    BOOL *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value specifying whether the transition is rendered as a cut. If TRUE, the transition is an instantaneous cut. If FALSE, the transition occurs over its normal duration.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • IAMTimelineTrans::SetCutsOnly
  • IAMTimelineTrans::GetCutPoint
  • IAMTimeline::TransitionsEnabled
  • Error and Success Codes


IAMTimelineTrans::GetSwapInputs

The GetSwapInputs method retrieves a value that indicates whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

HRESULT GetSwapInputs(
    BOOL *pVal
);

Parameters

pVal

Pointer to a variable that receives a Boolean value. If the value is FALSE, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is TRUE, the transition goes in the opposite direction. The default value is FALSE.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTrans::SetCutPoint

The SetCutPoint method sets the time at which the transition cuts from one source to the next, if the transition is rendered as a cut.

Syntax

HRESULT SetCutPoint(
    REFERENCE_TIME TLTime
);

Parameters

TLTime

Cut point relative to the start of the transition, in 100-nanosecond units. If the value falls outside the bounds of the transition, it is truncated to the nearest valid time.

Return Value

Returns S_OK.

Remarks

By default, the cut-point is the middle of the transition. For example, in a transition that spans one second, the default cut point is 0.5 seconds into the transition.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTrans::SetCutPoint2

The SetCutPoint2 method sets the time at which the transition cuts from one source to the next, if the transition is rendered as a cut. This method is equivalent to IAMTimelineTrans::SetCutPoint, but takes a REFTIME value.

Syntax

HRESULT SetCutPoint2(
    REFTIME TLTime
);

Parameters

TLTime

Cut point relative to the start of the transition, in seconds.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTrans::SetCutsOnly

The SetCutsOnly method specifies whether the transition is rendered as a cut. If so, the transition occurs instantly at the cut point. If a transition takes a long time to render, you might want to preview it as a cut to speed preview.

Syntax

HRESULT SetCutsOnly(
    BOOL Val
);

Parameters

Val

Boolean value that specifies whether to render the transition as a cut. If TRUE, the transition is rendered as an instantaneous cut. If FALSE, the transition renders over its normal duration.

Return Value

Returns S_OK.

Remarks

Rendering a transition as a cut is not compatible with swapping the inputs. (See IAMTimelineTrans::SetSwapInputs.) If you call SetCutsOnly with a value of TRUE, it temporarily overrides the SetSwapInputs setting. The cuts-only setting is intended for preview, however, so this limitation does not affect file output—just remember to call SetCutsOnly with the value FALSE before writing the file.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTrans::SetSwapInputs

The SetSwapInputs method specifies whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers. For more information, see Transition Direction.

Syntax

HRESULT SetSwapInputs(
    BOOL Val
);

Parameters

Val

Boolean value that specifies whether the inputs are swapped. If the value is FALSE, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is TRUE, the transition goes in the opposite direction.

Return Value

Returns S_OK.

Remarks

This method does not change the direction of the visual effect. For example, a left-to-right wipe will still go from left to right. To change the direction, set the Progress property using the IPropertySetter interface.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTrans Interface
  • Error and Success Codes


IAMTimelineTransable Interface

The IAMTimelineTransable interface adds transitions to an object in DirectShow Editing Services (DES). This interface is exposed by any object that can have transitions applied to it, including tracks, compositions, and groups. An object that implements this interface can have any number of transitions, but the transitions must not overlap in time.

Note Audio does not support transitions. Objects within audio groups can expose the IAMTimelineTransable interface, but the application should not add transitions to them.

In addition to the methods inherited from IUnknown, the IAMTimelineTransable interface exposes the following methods.

Method | Description
GetNextTrans | Retrieves the first transition that appears at the specified time or later.
GetNextTrans2 | Retrieves the first transition that appears at the specified time or later, with the time given as a REFTIME value.
GetTransAtTime | Retrieves the transition nearest to the specified time.
GetTransAtTime2 | Retrieves the transition nearest to the specified time, given as a REFTIME value.
TransAdd | Adds a transition to the object.
TransGetCount | Retrieves the number of transitions on this object.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineTransable::GetNextTrans

The GetNextTrans method retrieves the first transition that appears at the specified time or later.

Syntax

HRESULT GetNextTrans(
    IAMTimelineObj **ppTrans,
    REFERENCE_TIME *pInOut
);

Parameters

ppTrans

[out] Address of a pointer to receive the transition object's IAMTimelineObj interface.

pInOut

Pointer to a variable that specifies the time in 100-nanosecond units. On input, this value specifies the time from which to find the transition. On output, if a transition is retrieved, this value is set to the stop time of the transition.

Return Value

Returns S_OK if the method retrieves a transition, or S_FALSE if it does not find a transition. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

The start time of the transition might be less than the time that you specify in pInOut, if the transition spans the specified time.

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineTransable::GetNextTrans2

The GetNextTrans2 method retrieves the first transition that appears at the specified time or later. This method is equivalent to IAMTimelineTransable::GetNextTrans, but takes a REFTIME value.

Syntax

HRESULT GetNextTrans2(
    IAMTimelineObj **ppTrans,
    REFTIME *pInOut
);

Parameters

ppTrans

[out] Address of a pointer to receive the transition object's IAMTimelineObj interface.

pInOut

Pointer to a variable that specifies the time in seconds. On input, this value specifies the time from which to find the transition. On output, if a transition is retrieved, this value is set to the stop time of the transition.

Return Value

Returns S_OK if the method retrieves a transition, or S_FALSE if it does not find a transition. Otherwise, returns an HRESULT value indicating the cause of the failure.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineTransable::GetTransAtTime

The GetTransAtTime method retrieves the transition nearest to the specified time, according to the specified boundary conditions.

Syntax

HRESULT GetTransAtTime(
    IAMTimelineObj **ppObj,
    REFERENCE_TIME Time,
    long SearchDirection
);

Parameters

ppObj

[out] Address of a pointer to receive the transition's IAMTimelineObj interface.

Time

Time from which to begin the search, in 100-nanosecond units.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | No transition was found.
S_OK | Transition was found.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineTransable::GetTransAtTime2

The GetTransAtTime2 method retrieves the transition nearest to the specified time, according to the specified boundary conditions. This method is equivalent to IAMTimelineTransable::GetTransAtTime, but takes a REFTIME parameter.

Syntax

HRESULT GetTransAtTime2(
    IAMTimelineObj **ppObj,
    REFTIME Time,
    long SearchDirection
);

Parameters

ppObj

[out] Address of a pointer to receive the transition's IAMTimelineObj interface.

Time

Time from which to begin the search, in seconds.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_FALSE | No transition was found.
S_OK | Transition was found.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineTransable::TransAdd

The TransAdd method adds a transition to the object. An object can have multiple transitions, but they must not overlap in time. Transitions must fall within the time boundaries of the object.

Syntax

HRESULT TransAdd(
    IAMTimelineObj *pTrans
);

Parameters

pTrans

Address of the IAMTimelineObj interface of the transition to add.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_INVALIDARG | Cannot insert the transition.
E_NOINTERFACE | pTrans is not a pointer to a transition.

Remarks

If the transition overlaps an existing transition, the method returns E_INVALIDARG.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineTransable::TransGetCount

The TransGetCount method retrieves the number of transitions on this object.

Syntax

HRESULT TransGetCount(
    long *pCount
);

Parameters

pCount

Pointer to a variable that receives the number of transitions.

Return Value

Returns S_OK if successful or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineTransable Interface
  • Error and Success Codes


IAMTimelineVirtualTrack Interface

The IAMTimelineVirtualTrack interface provides methods for working with virtual tracks in DirectShow Editing Services (DES). Compositions and tracks support this interface.

In addition to the methods inherited from IUnknown, the IAMTimelineVirtualTrack interface exposes the following methods.

Method | Description
SetTrackDirty | Not supported.
TrackGetPriority | Retrieves the object's priority level.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IAMTimelineVirtualTrack::SetTrackDirty

Not supported.

Syntax

HRESULT SetTrackDirty( void );

See Also

  • IAMTimelineVirtualTrack Interface


IAMTimelineVirtualTrack::TrackGetPriority

The TrackGetPriority method retrieves the object's priority level.

Syntax

HRESULT TrackGetPriority(
    long *pPriority
);

Parameters

pPriority

Pointer to a variable that receives the priority level. If the object is not part of a timeline, the value is set to –1.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IAMTimelineVirtualTrack Interface
  • Error and Success Codes


IDxtAlphaSetter Interface

The IDxtAlphaSetter interface sets properties on the Alpha Setter effect.

This interface is used internally by DirectShow Editing Services (DES) when it renders the Alpha Setter effect. DES applications do not have to use this interface. To set the properties on a transition in DES, use the IPropertySetter interface.

In addition to the methods inherited from IDXEffect, the IDxtAlphaSetter interface exposes the following methods.

Method | Description
get_Alpha | Retrieves the alpha value for the entire image.
get_AlphaRamp | Retrieves the alpha ramp property.
put_Alpha | Specifies the alpha value for the entire image.
put_AlphaRamp | Specifies the alpha ramp property.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IDxtAlphaSetter::get_Alpha

The get_Alpha method retrieves the alpha value for the entire image.

Syntax

HRESULT get_Alpha(
    long *pAlpha
);

Parameters

pAlpha

[out, retval] Pointer to a variable that receives the alpha value. This alpha value will be applied to the entire target image. A negative value indicates that no alpha value is set.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtAlphaSetter Interface


IDxtAlphaSetter::get_AlphaRamp

The get_AlphaRamp method retrieves the alpha ramp property. The alpha ramp is the percentage by which the alpha values in the original image are adjusted. For example, if the alpha ramp is 0.5, the alpha values in the image are reduced 50%.

Syntax

HRESULT get_AlphaRamp(
    double *pAlpha
);

Parameters

pAlpha

[out, retval] Pointer to a variable that receives the alpha ramp. A negative value indicates that no alpha ramp is set.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtAlphaSetter Interface


IDxtAlphaSetter::put_Alpha

The put_Alpha method specifies the alpha value for the entire image.

Syntax

HRESULT put_Alpha(
    long Alpha
);

Parameters

Alpha

[in] Specifies the alpha value. This value will be applied to the entire target image. To disable this property, set a negative value.

Return Values

Returns S_OK or an error code.

Remarks

If you set this property to a non-negative value, you must also disable the alpha ramp property, by calling put_AlphaRamp with a negative value. Otherwise the effect will not render correctly.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtAlphaSetter Interface
  • IDxtAlphaSetter::put_AlphaRamp


IDxtAlphaSetter::put_AlphaRamp

The put_AlphaRamp method specifies the alpha ramp property. The alpha ramp is the percentage by which the alpha values in the original image are adjusted. For example, if the alpha ramp is 0.5, the alpha values in the image are reduced 50%.

Syntax

HRESULT put_AlphaRamp(
    double Alpha
);

Parameters

Alpha

[in] Specifies the alpha ramp as a percentage. For example, 1.0 is 100%. To disable this property, set a negative value.

Return Values

Returns an HRESULT value.

Remarks

If you set this property to a non-negative value, you must also disable the alpha property, by calling put_Alpha with a negative value. Otherwise the effect will not render correctly.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtAlphaSetter Interface
  • IDxtAlphaSetter::put_Alpha


IDxtCompositor Interface

The IDxtCompositor interface sets properties on the Compositor transition.

This interface is used internally by DirectShow Editing Services (DES) when it renders the Compositor transition. DES applications do not have to use this interface. To set the properties on a transition in DES, use the IPropertySetter interface.

The Compositor transition composites a foreground image onto a background image. The source rectangle defines the section of the foreground image that is composited. The destination rectangle defines the section of the background image that receives the foreground image. The following diagram illustrates these rectangles.

Compositor Transition Properties

In addition to the methods inherited from IDXEffect, the IDxtCompositor interface exposes the following methods.

Method | Description
get_Height | Retrieves the height of the target rectangle.
get_OffsetX | Retrieves the horizontal offset of the target rectangle.
get_OffsetY | Retrieves the vertical offset of the target rectangle.
get_SrcHeight | Retrieves the height of the source rectangle.
get_SrcWidth | Retrieves the width of the source rectangle.
get_SrcOffsetX | Retrieves the horizontal offset of the source rectangle.
get_SrcOffsetY | Retrieves the vertical offset of the source rectangle.
get_Width | Retrieves the width of the target rectangle.
put_Height | Specifies the height of the target rectangle.
put_OffsetX | Specifies the horizontal offset of the target rectangle.
put_OffsetY | Specifies the vertical offset of the target rectangle.
put_SrcHeight | Specifies the height of the source rectangle.
put_SrcWidth | Specifies the width of the source rectangle.
put_SrcOffsetX | Specifies the horizontal offset of the source rectangle.
put_SrcOffsetY | Specifies the vertical offset of the source rectangle.
put_Width | Specifies the width of the target rectangle.


IDxtCompositor::get_Height

The get_Height method retrieves the height of the target rectangle.

Syntax

HRESULT get_Height(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the height of the target rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_OffsetX

The get_OffsetX method retrieves the horizontal offset of the target rectangle.

Syntax

HRESULT get_OffsetX(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the horizontal offset of the target rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_OffsetY

The get_OffsetY method retrieves the vertical offset of the target rectangle.

Syntax

HRESULT get_OffsetY(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the vertical offset of the target rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_SrcHeight

The get_SrcHeight method retrieves the height of the source rectangle.

Syntax

HRESULT get_SrcHeight(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the height of the source rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_SrcWidth

The get_SrcWidth method retrieves the width of the source rectangle.

Syntax

HRESULT get_SrcWidth(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the width of the source rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_SrcOffsetX

The get_SrcOffsetX method retrieves the horizontal offset of the source rectangle.

Syntax

HRESULT get_SrcOffsetX(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the horizontal offset of the source rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_SrcOffsetY

The get_SrcOffsetY method retrieves the vertical offset of the source rectangle.

Syntax

HRESULT get_SrcOffsetY(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the vertical offset of the source rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::get_Width

The get_Width method retrieves the width of the target rectangle.

Syntax

HRESULT get_Width(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the width of the target rectangle, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_Height

The put_Height method specifies the height of the target rectangle.

Syntax

HRESULT put_Height(
    long newVal
);

Parameters

newVal

[in] The height of the target rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_OffsetX

The put_OffsetX method specifies the horizontal offset of the target rectangle.

Syntax

HRESULT (
    long newVal
);

Parameters

newVal

[in] The horizontal offset of the target rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_OffsetY

The put_OffsetY method specifies the vertical offset of the target rectangle.

Syntax

HRESULT put_OffsetY(
    long newVal
);

Parameters

newVal

[in] The vertical offset of the target rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_SrcHeight

The put_SrcHeight method specifies the height of the source rectangle.

Syntax

HRESULT put_SrcHeight(
    long newVal
);

Parameters

newVal

[in] The height of the source rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_SrcWidth

The put_SrcWidth method specifies the width of the source rectangle.

Syntax

HRESULT put_SrcWidth(
    long newVal
);

Parameters

newVal

[in] The width of the source rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_SrcOffsetX

The put_SrcOffsetX method specifies the horizontal offset of the source rectangle.

Syntax

HRESULT put_SrcOffsetX(
    long newVal
);

Parameters

newVal

[in] The horizontal offset of the source rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_SrcOffsetY

The put_SrcOffsetY method specifies the vertical offset of the source rectangle.

Syntax

HRESULT put_SrcOffsetY(
    long newVal
);

Parameters

newVal

[in] The vertical offset of the source rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtCompositor::put_Width

The put_Width method specifies the width of the target rectangle.

Syntax

HRESULT put_Width(
    long newVal
);

Parameters

newVal

[in]The width of the target rectangle, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtCompositor Interface


IDxtJpeg Interface

The IDxtJpeg interface sets properties on the SMPTE Wipe transition.

This interface is used internally by DirectShow Editing Sevices (DES) when it renders the SMPTE Wipe transition. DES applications do not need to use this interface. To set the properties on a transition in DES, use the IPropertySetter interface.

In addition to the methods inherited from IDXEffect, the IDxtJpeg interface exposes the following methods.

Method | Description
ApplyChanges | Applies any properties that have changed.
get_BorderColor | Retrieves the color of the border around the edges of the wipe pattern.
get_BorderSoftness | Retrieves the width of the blurry region around the edges of the wipe pattern.
get_BorderWidth | Retrieves the width of the solid border along the edges of the wipe pattern.
get_MaskName | Retrieves the name of a JPEG file to be used as the wipe mask.
get_MaskNum | Retrieves the SMPTE wipe code of the wipe.
get_OffsetX | Retrieves the horizontal offset of the wipe origin.
get_OffsetY | Retrieves the vertical offset of the wipe origin.
get_ReplicateX | Retrieves the number of times the wipe pattern is replicated horizontally.
get_ReplicateY | Retrieves the number of times the wipe pattern is replicated vertically.
get_ScaleX | Retrieves the amount by which the wipe is stretched horizontally.
get_ScaleY | Retrieves the amount by which the wipe is stretched vertically.
LoadDefSettings | Restores the default settings of the Wipe transition.
put_BorderColor | Specifies the color of the border around the edges of the wipe pattern.
put_BorderSoftness | Specifies the width of the blurry region around the edges of the wipe pattern.
put_BorderWidth | Specifies the width of the solid border along the edges of the wipe pattern.
put_MaskName | Specifies the name of a JPEG file to use as the wipe mask.
put_MaskNum | Specifies the SMPTE wipe code of the wipe.
put_OffsetX | Specifies the horizontal offset of the wipe origin.
put_OffsetY | Specifies the vertical offset of the wipe origin.
put_ReplicateX | Specifies the number of times the wipe pattern is replicated horizontally.
put_ReplicateY | Specifies the number of times the wipe pattern is replicated vertically.
put_ScaleX | Specifies the amount by which the wipe is stretched horizontally.
put_ScaleY | Specifies the amount by which the wipe is stretched vertically.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IDxtJpeg::ApplyChanges

The ApplyChanges method applies any properties that have changed.

Syntax

HRESULT ApplyChanges();

Parameters

This method takes no parameters.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_BorderColor

The get_BorderColor method retrieves the color of the border around the edges of the wipe pattern.

Syntax

HRESULT get_BorderColor(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the color. The returned value is a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_BorderSoftness

The get_BorderSoftness method retrieves the width of the blurry region around the edges of the wipe pattern.

Syntax

HRESULT get_BorderSoftness(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the width of the blurry region, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_BorderWidth

The get_BorderWidth method retrieves the width of the solid border along the edges of the wipe pattern.

Syntax

HRESULT get_BorderWidth(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the width of the border, in pixels.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_MaskName

The get_MaskName method retrieves the name of a JPEG file to be used as the wipe mask.

Syntax

HRESULT get_MaskName(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a BSTR variable that receives the file name.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

If the wipe transition is using one of the built-in SMPTE wipes that it supports, the value of this property is an empty string.

The caller must release the returned string, using the SysFreeString function.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface
  • IDxtJpeg::get_MaskNum


IDxtJpeg::get_MaskNum

The get_MaskNum method retrieves the SMPTE wipe code of the wipe.

Syntax

HRESULT get_MaskNum(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the SMPTE wipe code. For a list of supported SMPTE wipes, see SMPTE Wipe Transition.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_OffsetX

The get_OffsetX method retrieves the horizontal offset of the wipe origin.

Syntax

HRESULT get_OffsetX(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the horizontal offset of the wipe origin, in pixels. The center of the wipe is offset by this amount.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_OffsetY

The get_OffsetY method retrieves the vertical offset of the wipe origin.

Syntax

HRESULT get_OffsetY(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the vertical offset of the wipe origin, in pixels. The center of the wipe is offset by this amount.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_ReplicateX

The get_ReplicateX method retrieves the number of times the wipe pattern is replicated horizontally.

Syntax

HRESULT get_ReplicateX(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the number of times the wipe pattern is replicated horizontally.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_ReplicateY

The get_ReplicateY method retrieves the number of times the wipe pattern is replicated vertically.

Syntax

HRESULT get_ReplicateY(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the number of times the wipe pattern is replicated vertically.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_ScaleX

The get_ScaleX method retrieves the amount by which the wipe is stretched horizontally.

Syntax

HRESULT get_ScaleX(
    double *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the amount by which the wipe is stretched horizontally, as a percentage of the original wipe definition. For example, the value 1.0 means no stretching, and 2.0 means 200% stretching.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::get_ScaleY

The get_ScaleY method retrieves the amount by which the wipe is stretched vertically.

Syntax

HRESULT (
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the amount by which the wipe is stretched vertically, as a percentage of the original wipe definition. For example, the value 1.0 means no stretching, and 2.0 means 200% stretching.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::LoadDefSettings

The LoadDefSettings method restores the default settings of the Wipe transition.

Syntax

HRESULT LoadDefSettings();

Parameters

This method takes no parameters.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_BorderColor

The put_BorderColor method specifies the color of the border around the edges of the wipe pattern.

Syntax

HRESULT put_BorderColor(
    long newVal
);

Parameters

newVal

[in] Specifies the color as a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_BorderSoftness

The put_BorderSoftness method specifies the width of the blurry region around the edges of the wipe pattern.

Syntax

HRESULT put_BorderSoftness(
    long newVal
);

Parameters

newVal

[in] The width of the blurry region, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_BorderWidth

The put_BorderWidth method specifies the width of the solid border along the edges of the wipe pattern.

Syntax

HRESULT put_BorderWidth(
    long newVal
);

Parameters

newVal

[in] The width of the border, in pixels.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_MaskName

The put_MaskName method specifies the name of a JPEG file to use as the wipe mask. This mask will be used instead of one of the built-in wipe masks. The file must contain a monochrome, 8-bits-per-pixel gradient. The gradient is used as a mask to define the wipe's progression.

Syntax

HRESULT put_MaskName(
    BSTR newVal
);

Parameters

newVal

[in] Specifies the name of the file.

Return Values

Returns S_OK or an error code.

Remarks

To revert to a built-in mask, set the MaskNum property.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface
  • IDxtJpeg::put_MaskNum


IDxtJpeg::put_MaskNum

The put_MaskNum method specifies the SMPTE wipe code of the wipe.

Syntax

HRESULT put_MaskNum(
    long newVal
);

Parameters

newVal

[in] Specifies the SMPTE wipe code. For a list of supported SMPTE wipes, see SMPTE Wipe Transition.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_OffsetX

The put_OffsetX method specifies the horizontal offset of the wipe origin.

Syntax

HRESULT put_OffsetX(
    long newVal
);

Parameters

newVal

[in] The horizontal offset of the wipe origin, in pixels. The center of the wipe is offset by this amount.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_OffsetY

The put_OffsetY method specifies the vertical offset of the wipe origin.

Syntax

HRESULT put_OffsetY(
    long newVal
);

Parameters

newVal

[in] The vertical offset of the wipe origin, in pixels. The center of the wipe is offset by this amount.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_ReplicateX

The put_ReplicateX method specifies the number of times the wipe pattern is replicated horizontally.

Syntax

HRESULT put_ReplicateX(
    long newVal
);

Parameters

newVal

[in] The number of times the wipe pattern is replicated horizontally.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_ReplicateY

The put_ReplicateY method specifies the number of times the wipe pattern is replicated vertically.

Syntax

HRESULT put_ReplicateY(
    long newVal
);

Parameters

newVal

[in] The number of times the wipe pattern is replicated vertically.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_ScaleX

The put_ScaleX method specifies the amount by which the wipe is stretched horizontally.

Syntax

HRESULT put_ScaleX(
    double newVal
);

Parameters

newVal

[in] The amount by which the wipe is stretched horizontally, as a percentage of the original wipe definition. For example, the value 1.0 means no stretching, and 2.0 means 200% stretching.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtJpeg::put_ScaleY

The put_ScaleY method specifies the amount by which the wipe is stretched vertically.

Syntax

HRESULT put_ScaleY(
    double newVal
);

Parameters

newVal

[in] The amount by which the wipe is stretched vertically, as a percentage of the original wipe definition. For example, the value 1.0 means no stretching, and 2.0 means 200% stretching.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtJpeg Interface


IDxtKey Interface

The IDxtKey interface sets properties on the Key transition.

This interface is used internally by DirectShow Editing Services (DES) when it renders the Key transition. DES applications do not need to use this interface. To set the properties on a transition in DES, use the IPropertySetter interface.

In addition to the methods inherited from IDXEffect, the IDxtKey interface exposes the following methods.

Method | Description
get_Hue | Retrieves the hue value on which to key.
get_Invert | Retrieves a Boolean value indicating whether the key operation is inverted.
get_KeyType | Retrieves the type of key.
get_Luminance | Retrieves the luminance value on which to key.
get_RGB | Retrieves the RGB color on which to key.
get_Similarity | Retrieves the range of color data that becomes transparent.
put_Hue | Specifies the hue value on which to key.
put_Invert | Specifies whether the key operation is inverted.
put_KeyType | Specifies the type of key.
put_Luminance | Specifies the luminance value on which to key.
put_RGB | Specifies the RGB color on which to key.
put_Similarity | Specifies the range of color data that becomes transparent.


IDxtKey::get_Hue

The get_Hue method retrieves the hue value on which to key. This property applies only when the key type is DXTKEY_HUE.

Syntax

HRESULT get_Hue(
    int *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the hue value on which to key.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::get_KeyType


IDxtKey::get_Invert

The get_Invert method retrieves a Boolean value indicating whether the key operation is inverted. This property applies to all key types except DXTKEY_ALPHA.

Syntax

HRESULT get_Invert(
    BOOL *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives one of the following values.

Value | Description
TRUE | Pixels in the overlying image are inverted with respect to the default operation.
FALSE | Pixels in the overlying image are made transparent in the default manner.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::get_KeyType


IDxtKey::get_KeyType

The get_KeyType method retrieves the type of key.

Syntax

HRESULT get_KeyType(
    int *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives one of the following enumeration values.

Value | Description
DXTKEY_RGB | Chroma key. (Key on RGB value.)
DXTKEY_NONRED | Nonred key. (Makes blue and green areas transparent.)
DXTKEY_LUMINANCE | Luminance key.
DXTKEY_ALPHA | Key by alpha value.
DXTKEY_HUE | Key by hue.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface


IDxtKey::get_Luminance

The get_Luminance method retrieves the luminance value on which to key. This property applies only when the key type is DXTKEY_LUMINANCE.

Syntax

HRESULT get_(
    int *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the luminance value on which to key.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::get_KeyType


IDxtKey::get_RGB

The get_RGB method retrieves the RGB color on which to key. This property applies only when the key type is DXTKEY_RGB.

Syntax

HRESULT get_RGB(
    DWORD *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the color. The returned value is a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::get_KeyType


IDxtKey::get_Similarity

The get_Similarity method retrieves the range of color data that becomes transparent. At higher values, a wider range of similar colors is transparent. This property applies only when the key type is DXTKEY_RGB or DXTKEY_NONRED.

Syntax

HRESULT get_Similarity(
    int *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the similarity value.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::get_KeyType


IDxtKey::put_Hue

The put_Hue method specifies the hue value on which to key. This property applies only when the key type is DXTKEY_HUE.

Syntax

HRESULT put_Hue(
    int newVal
);

Parameters

newVal

[in] Specifies the hue value on which to key. The valid range is from 0 to 360.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::put_KeyType


IDxtKey::put_Invert

The put_Invert method specifies whether the key operation is inverted. This property applies to all key types except DXTKEY_ALPHA.

Syntax

HRESULT put_Invert(
    BOOL newVal
);

Parameters

newVal

[in] Specifies a Boolean value. If TRUE, pixels in the overlying image are inverted with respect to the default operation. If FALSE, pixels in the overlying image are made transparent in the default manner.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::put_KeyType


IDxtKey::put_KeyType

The put_KeyType method specifies the type of key.

Syntax

HRESULT put_KeyType(
    int newVal
);

Parameters

newVal

[in] Specifies the key type. This parameter must be one of the following enumeration values.

Value | Description
DXTKEY_RGB | Chroma key. (Key on RGB value.)
DXTKEY_NONRED | Nonred key. (Makes blue and green areas transparent.)
DXTKEY_LUMINANCE | Luminance key.
DXTKEY_ALPHA | Key by alpha value.
DXTKEY_HUE | Key by hue.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface


IDxtKey::put_Luminance

The put_Luminance method specifies the luminance value on which to key. This property applies only when the key type is DXTKEY_LUMINANCE.

Syntax

HRESULT put_Luminance(
    int newVal
);

Parameters

newVal

[in] The luminance value on which to key. The valid range is from 0 to 100.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::put_KeyType


IDxtKey::put_RGB

The put_RGB method specifies the RGB color on which to key. This property applies only when the key type is DXTKEY_RGB.

Syntax

HRESULT put_RGB(
    DWORD newVal
);

Parameters

newVal

[in] Specifies the color as a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::put_KeyType


IDxtKey::put_Similarity

The put_Similarity method specifies the range of color data that becomes transparent. At higher values, a wider range of similar colors is transparent. This property applies only when the key type is DXTKEY_RGB or DXTKEY_NONRED.

Syntax

HRESULT put_Similarity(
    int newVal
);

Parameters

newVal

[in] Specifies the similarity value. The valid range is from 0 to 100.

Return Values

Returns S_OK or an error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IDxtKey Interface
  • IDxtKey::put_KeyType


IFindCompressorCB Interface

The IFindCompressorCB interface is not supported.


IGrfCache Interface

The IGrfCache interface is not supported.


IMediaDet Interface

The IMediaDet interface retrieves information about a media file, such as the number of streams, and the media type, duration, and frame rate of each stream. It also contains methods for retrieving individual frames from a video stream. The Media Detector (MediaDet) object exposes this interface.

To obtain information about a file using this interface, perform the following steps:

  1. Create an instance of the MediaDet object by calling CoCreateInstance. The class ID is CLSID_MediaDet.
  2. Call IMediaDet::put_Filename to specify the name of the source file.
  3. Call IMediaDet::get_OutputStreams to obtain the number of output streams in the source.
  4. Call IMediaDet::put_CurrentStream to specify a particular stream.
  5. Call any of the following methods:
    • IMediaDet::get_FrameRate
    • IMediaDet::get_StreamLength
    • IMediaDet::get_StreamMediaType
    • IMediaDet::get_StreamType

To retrieve a video frame, call IMediaDet::GetBitmapBits or IMediaDet::WriteBitmapBits. The returned frame is always in 24-bit RGB format.

Note Do not use the same MediaDet object with multiple files. To get information or video frames from more than one file, use separate MediaDet instances.

The IMediaDet interface does not support VIDEOINFOHEADER2 formats, so you cannot use this interface to get interlaced fields or information about interlacing. Also, if the upstream decoder supports only VIDEOINFOHEADER2, you cannot use IMediaDet. This might be the case with an MPEG-2 decoder, for example. Also, the IMediaDet interface ignores any streams in the file that are not video or audio. For example, if the file contains an audio stream, a data stream, and a video stream, the get_OutputStreams method will report only two streams (the audio and video).

In addition to the methods inherited from IUnknown, the IMediaDet interface exposes the following methods.

Method | Description
EnterBitmapGrabMode | Switches the media detector to bitmap grab mode and seeks the filter graph to a specified time.
get_CurrentStream | Retrieves the stream number currently used by the media detector.
get_Filename | Retrieves the name of the source file currently used by the media detector.
get_Filter | Retrieves a pointer to the source filter currently used by the media detector.
get_FrameRate | Retrieves the frame rate of the current stream.
get_OutputStreams | Retrieves the number of audio and video streams contained in the media source.
get_StreamLength | Retrieves the duration of the current stream.
get_StreamMediaType | Retrieves the media type of the current stream.
get_StreamType | Retrieves the globally unique identifier (GUID) for the media type of the current stream.
get_StreamTypeB | Retrieves a string representing the GUID of the media type for the current stream.
GetBitmapBits | Retrieves a video frame at the specified media time.
GetSampleGrabber | Retrieves a pointer to the ISampleGrabber interface.
put_CurrentStream | Specifies the stream number for the media detector to use.
put_Filename | Specifies the name of the source file for the media detector to use.
put_Filter | Specifies a source filter for the media detector to use.
WriteBitmapBits | Retrieves a video frame at the specified media time and writes it to a file.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IMediaDet::EnterBitmapGrabMode

The EnterBitmapGrabMode method switches the media detector to bitmap grab mode and seeks the filter graph to a specified time.

Syntax

HRESULT EnterBitmapGrabMode(
    double StreamTime
);

Parameters

StreamTime

Time, in seconds, to which the graph seeks.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_INVALIDMEDIATYPE | The source file does not have a video stream.
VFW_E_TIME_EXPIRED | Could not seek the graph.

Remarks

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

This method inserts the Sample Grabber filter into the filter graph. You can then call IMediaDet::GetSampleGrabber to obtain a pointer to the ISampleGrabber interface. Once the media detector enters bitmap grab mode, the various informational methods in IMediaDet do not work.

The IMediaDet::GetBitmapBits or IMediaDet::WriteBitmapBits methods also put the media detector into bitmap grab mode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::GetBitmapBits

The GetBitmapBits method retrieves a video frame at the specified media time. The returned frame is always in 24-bit RGB format.

Syntax

HRESULT GetBitmapBits(
    double StreamTime,
    long *pBufferSize,
    char *pBuffer,
    long Width,
    long Height
);

Parameters

StreamTime

Time at which to retrieve the video frame, in seconds.

pBufferSize

Pointer to a variable that receives the required buffer size. If pBuffer is NULL, the variable receives the size of the buffer needed to retrieve the frame. If pBuffer is not NULL, this parameter is ignored.

pBuffer

Pointer to a buffer that receives a BITMAPINFOHEADER structure followed by the DIB bits.

Width

Width of the video image, in pixels.

Height

Height of the video image, in pixels.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer error.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

To determine the size of the buffer that is required, call this method with pBuffer equal to NULL. The size is returned in the variable pointed to by pBufferSize. Then create the buffer and call the method again, with pBuffer equal to the address of the buffer. When the method returns, the buffer contains a BITMAPINFOHEADER structure followed by the bitmap. The bitmap is scaled to the dimensions specified in the Width and Height parameters.

This method puts the media detector into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the media detector.

Example Code

The following code uses the GetBitmapBits method to create a device-independent bitmap.

long size;
hr = pDet->GetBitmapBits(0, &size, 0, width, height);
if (SUCCEEDED(hr))
{
    char *pBuffer = new char[size];
    if (!pBuffer)
        return E_OUTOFMEMORY;
    try {
        hr = pDet->GetBitmapBits(0, 0, pBuffer, width, height);
    }
    catch (...) {
        delete [] pBuffer;
        throw;
    }
    if (SUCCEEDED(hr))
    {
        BITMAPINFOHEADER *bmih = (BITMAPINFOHEADER*)pBuffer;
        HDC hdcDest = GetDC(0);

        // Find the address of the start of the image data.
        void *pData = pBuffer + sizeof(BITMAPINFOHEADER);

        // Note: In general a BITMAPINFOHEADER can include extra color
        // information at the end, so calculating the offset to the image
        // data is not generally correct. However, the IMediaDet interface
        // always returns an RGB-24 image with no extra color information.

        BITMAPINFO bmi;
        ZeroMemory(&bmi, sizeof(BITMAPINFO));
        CopyMemory(&(bmi.bmiHeader), bmih, sizeof(BITMAPINFOHEADER));
        HBITMAP hBitmap = CreateDIBitmap(hdcDest, bmih, CBM_INIT,
            pData, &bmi, DIB_RGB_COLORS);
    }
    delete[] pBuffer;
}

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_CurrentStream

The get_CurrentStream method retrieves the stream number currently used by the media detector.

Syntax

HRESULT get_CurrentStream(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the current stream number.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_Filename

The get_Filename method retrieves the name of the source file currently used by the media detector.

Syntax

HRESULT get_Filename(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the file name.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_Filter

The get_Filter method retrieves a pointer to the source filter currently used by the media detector.

Syntax

HRESULT get_Filter(
    IUnknown **ppVal
);

Parameters

ppVal

[out, retval] Address of a pointer to receive the filter's IUnknown interface. If no source filter is in use, the value is set to NULL.

Return Value

Returns an HRESULT value.

Remarks

When the method returns, if *ppVal is not NULL, the IUnknown interface has an outstanding reference count. Release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_FrameRate

The get_FrameRate method retrieves the frame rate of the current stream. The stream must be a video stream.

Syntax

HRESULT get_FrameRate(
    double *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the frame rate, in frames per second.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | Video format header does not specify a frame rate.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method cannot retrieve the frame rate from an ASF file.

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_OutputStreams

The get_OutputStreams method retrieves the number of audio and video streams contained in the media source. Any other stream types, such as data streams, are ignored.

Syntax

HRESULT get_OutputStreams(
    long *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the number of output streams.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, call IMediaDet::put_Filename to set the file name. If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::GetSampleGrabber

The GetSampleGrabber method retrieves a pointer to the ISampleGrabber interface, which enables an application to retrieve individual samples from a media stream.

Syntax

HRESULT GetSampleGrabber(
    ISampleGrabber **ppVal
);

Parameters

ppVal

[out] Address of a pointer to receive the ISampleGrabber interface.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_NOINTERFACE | Cannot retrieve the interface because the media detector is not in bitmap grab mode.
E_POINTER | NULL pointer argument.

Remarks

Call IMediaDet::EnterBitmapGrabMode before calling this method. The ISampleGrabber interface enables you to retrieve individual media samples from the stream. If you just need a bitmap from a video frame, call the IMediaDet::GetBitmapBits method instead. The ISampleGrabber interface is more flexible, but requires more work by the application.

If this method succeeds, the ISampleGrabber interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_StreamLength

The get_StreamLength method retrieves the duration of the current stream.

Syntax

HRESULT get_StreamLength(
    double *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the duration of the stream, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_StreamMediaType

The get_StreamMediaType method retrieves the media type of the current stream. All video streams are converted to VIDEOINFOHEADER types, and all audio streams are converted to WAVEFORMATEX types.

Syntax

HRESULT get_StreamMediaType(
    AM_MEDIA_TYPE *pVal
);

Parameters

pVal

[out, retval] Pointer to an AM_MEDIA_TYPE structure that is filled with the media type.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_StreamType

The get_StreamType method retrieves the globally unique identifier (GUID) for the media type of the current stream.

Syntax

HRESULT get_StreamType(
    GUID *pVal
);

Parameters

pVal

[out, retval] Pointer to a variable that receives the major type GUID for the media type.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the majortype member of the AM_MEDIA_TYPE structure. The AM_MEDIA_TYPE structure describes the format of the stream, and the majortype member is a GUID that indicates the general category, such as audio or video. For a video stream, the GUID is MEDIATYPE_Video. For audio, it is MEDIATYPE_Audio. To retrieve the entire AM_MEDIA_TYPE structure, call the IMediaDet::get_StreamMediaType method.

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::get_StreamTypeB

The get_StreamTypeB method retrieves a string representing the GUID of the media type for the current stream.

Syntax

HRESULT get_StreamTypeB(
    BSTR *pVal
);

Parameters

pVal

[out, retval] Pointer to a BSTR that receives a string representation of the media type GUID.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

The returned BSTR is formatted like the following: {73647561-0000-0010-8000-00AA00389B71}

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::put_CurrentStream

The put_CurrentStream method specifies the stream number for the media detector to use.

Syntax

HRESULT put_CurrentStream(
    long newVal
);

Parameters

newVal

[in] Stream number.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

Before calling this method, call IMediaDet::put_Filename to set the file name. Call IMediaDet::get_OutputStreams to determine the number of streams contained in the source file.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see IMediaDet::EnterBitmapGrabMode.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::put_Filename

The put_Filename method specifies the name of the source file for the media detector to use.

Do not call this method twice on the same MediaDet object. To use this interface with more than one source file, create separate instances of the MediaDet object.

Syntax

HRESULT put_Filename(
    BSTR newVal
);

Parameters

newVal

[in] File name of the source.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::put_Filter

The put_Filter method specifies a source filter for the media detector to use.

Important Do not add the source filter to your own filter graph, or use a filter that is already in a filter graph. The media detector object automatically builds an internal filter graph, and putting the filter in another graph can cause unexpected results.

Syntax

HRESULT put_Filter(
    IUnknown *newVal
);

Parameters

newVal

[in] Pointer to the source filter's IUnknown interface.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_NOINTERFACE | newVal does not point to a filter.
E_POINTER | NULL pointer argument.

Remarks

For most applications, it is simpler to call the IMediaDet::put_Filename method with the name of a source file.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaDet::WriteBitmapBits

The WriteBitmapBits method retrieves a video frame at the specified media time and writes it to a file. The video frame is always in 24-bit RGB format.

Syntax

HRESULT WriteBitmapBits(
    double StreamTime,
    long Width,
    long Height,
    BSTR Filename
);

Parameters

StreamTime

Time at which to retrieve the video frame.

Width

Width of the image, in pixels.

Height

Height of the image, in pixels.

Filename

Path of the file in which to save the bitmap. If the file already exists, this method overwrites it.

Return Value

Returns S_OK it successful. Otherwise, returns an HRESULT value that indicates the cause of the error. Possible error codes include the following:

Value | Description
E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | Unexpected error.
STG_E_ACCESSDENIED | Cannot overwrite file.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the file name and stream by calling IMediaDet::put_Filename and IMediaDet::put_CurrentStream.

This method puts the media detector into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the media detector.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaDet Interface
  • Error and Success Codes


IMediaLocator Interface

The IMediaLocator interface provides methods for validating file names in DirectShow Editing Services (DES). Use this interface to ensure that a given file name and path correspond to an existing file. This interface also provides a way to search for the file at other locations, and to display an Open dialog box so that the user can locate the file.

The media locator implements this interface. The timeline and the render engine also support file name validation through the following methods:

  • IAMTimeline::ValidateSourceNames: Validates and updates file names in the timeline.
  • IRenderEngine::SetSourceNameValidation: Specifies how the render engine validates file names at rendering time.

Typically, a DES application will call these methods rather than directly create an instance of the media locator. For more information, see Using the Media Locator.

In addition to the methods inherited from IUnknown, the IMediaLocator interface exposes the following methods.

Method | Description
AddFoundLocation | Adds a directory to the directory cache.
FindMediaFile | Searches for a file and, if successful, retrieves the path to the file.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IMediaLocator::AddFoundLocation

The AddFoundLocation method adds a directory to the directory cache.

Syntax

HRESULT AddFoundLocation(
    BSTR DirectoryName
);

Parameters

DirectoryName

Directory path to add to the cache.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The media locator keeps a cache of directory paths where it has successfully found files in past searches. When it successfully locates a file, it adds the directory to the cache.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaLocator Interface
  • Error and Success Codes


IMediaLocator::FindMediaFile

The FindMediaFile method searches for a file and, if successful, retrieves the path to the file.

Syntax

HRESULT FindMediaFile(
    BSTR Input,
    BSTR FilterString,
    BSTR *pOutput,
    long Flags
);

Parameters

Input

File name, including path, where the file was last known to reside. For source objects in the timeline, use the current media name.

FilterString

BSTR containing pairs of filter strings, formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box. The value can be NULL if the Flags parameter does not include the SFN_VALIDATEF_POPUP flag.

pOutput

Pointer to a variable that receives the actual path to the file, if it differs from the value contained in Input and if the method successfully locates the file.

Flags

Bitwise combination of zero or more flags. For a list of possible flags, see File Name Validation Flags.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | File was found in another location.
S_OK | File was found in the specified location.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_POINTER | NULL pointer argument.

Remarks

The filter string for the Open dialog, which is specified by the FilterString parameter, contains internal Null characters. For example, Video\0*.avi\0\0 is a valid filter string. You cannot use the SysAllocStr function to allocate the BSTR, because that function expects a Null-terminated string and will truncate the string at the first Null character. Therefore, use a function such as SysAllocStringLen, which includes an explicit parameter for the length:

BSTR filter = SysAllocStringLen(L"Video\0*.avi\0", 12);
// Note: SysAllocStringLen appends an additional '\0' to the string.

If the user cancels the Open dialog, the method returns E_FAIL.

The method allocates memory for the BSTR in pOutput. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IMediaLocator Interface
  • Error and Success Codes


IPropertySetter Interface

The IPropertySetter interface sets properties on an effect or transition in DirectShow Editing Services (DES).

To use this interface, create an instance of a property setter object (CLSID_PropertySetter), and associate it with an effect or transition by calling the IAMTimelineObj::SetPropertySetter method. For more information, see Working with Effects and Transitions.

Usually an application needs to call only the IPropertySetter::ClearProps method to clear existing properties, and the IPropertySetter::AddProp method to add new properties. The other methods on this interface are called by other DES components.

In addition to the methods inherited from IUnknown, the IPropertySetter interface exposes the following methods.

Method | Description
AddProp | Adds a property to the property setter, with an array of time-value pairs defining the value of the property over a range of time.
ClearProps | Clears all property data from the property setter.
CloneProps | Clones a set of properties from this property setter and adds them to a new property setter.
FreeProps | Frees resources allocated by the IPropertySetter::GetProps method.
GetProps | Retrieves the properties set on this object, with their corresponding values.
LoadFromBlob | Loads property data from a persistence format.
LoadXML | Loads property data expressed in Extensible Markup Language (XML).
PrintXML | Converts property data into an XML string.
SaveToBlob | Saves the property data to a persistence format.
SetProps | Sets the properties of the target object to the appropriate state for the specified time.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IPropertySetter::AddProp

The AddProp method adds a property to the property setter, with an array of time-value pairs defining the value of the property over a range of time.

Syntax

HRESULT AddProp(
    DEXTER_PARAM Param,
    DEXTER_VALUE *paValue
);

Parameters

Param

[in] DEXTER_PARAM structure that specifies the property. The nValues member of the structure must equal the size of the array given in the paValue parameter.

paValue

[in] Pointer to an array of DEXTER_VALUE structures that contain time-value pairs. The array must be in ascending time order. The times are relative to the starting time of the effect or transition.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The first DEXTER_VALUE structure must specify a reference time of zero and an interpolation flag (dwInterp) of DEXTERF_JUMP, or the method returns an error.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::ClearProps

The ClearProps method clears all property data from the property setter. The application can set new property data after calling this function.

Clearing the property data does not restore the object's properties to their original values. It simply prevents DirectShow from applying any further changes. Property values are applied at run time when the project renders.

Syntax

HRESULT ClearProps(void);

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::CloneProps

The CloneProps method clones a set of properties from this property setter and adds them to a new property setter.

Syntax

HRESULT CloneProps(
    IPropertySetter **ppSetter,
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtStop
);

Parameters

ppSetter

[out] Address of a pointer to receive the IPropertySetter interface of the new property setter.

rtStart

[in] Start time of the range of values to clone, in 100-nanosecond units.

rtStop

[in] Reserved.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error. Possible error codes include the following:

Value | Description
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Only values that fall after the specified start time are cloned. The times on the cloned values are then adjusted relative to the start time. For example, if rtStart is 20000000 (2 seconds), then a value at time 30000000 (3 seconds) is cloned with time 10000000 (1 second). Finally, each cloned property is given an initial value equal to the value of the original property at the start time (correctly interpolated if necessary). In effect, the property data is split at the specified start time.

If the method succeeds, the IPropertySetter interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::FreeProps

The FreeProps method frees resources allocated by the IPropertySetter::GetProps method. Call this method after calling GetProps, passing it the structures returned by GetProps.

Syntax

HRESULT FreeProps(
    LONG cParams,
    DEXTER_PARAM *paParam,
    DEXTER_VALUE *paValue
);

Parameters

cParams

[in] Value that specifies the size of the array given in the paParam parameter.

paParam

[in] Pointer to an array of DEXTER_PARAM structures.

paValue

[in] Pointer to an array of DEXTER_VALUE structures.

Return Value

Returns S_OK.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::GetProps

The GetProps method retrieves the properties set on this object, with their corresponding values.

Syntax

HRESULT GetProps(
    LONG *pcParams,
    DEXTER_PARAM **paParam,
    DEXTER_VALUE **paValue
);

Parameters

pcParams

[out] Pointer to a variable that receives the number of structures returned in paParam.

paParam

[out] Address of a pointer to an array of DEXTER_PARAM structures.

paValue

[out] Address of a pointer to an array of DEXTER_VALUE structures.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

For each property returned in paParam, the nValues member indicates the number of DEXTER_VALUE structures associated with the property. The pairs are returned in ascending time order for each property.

When you are finished using the returned structures, call IPropertySetter::FreeProps to free the resources allocated by this method.

Code Example

The following code example shows how to iterate through all the values on an instance of the property setter:

IPropertySetter *pSetter = NULL;
// Get a valid IPropertySetter pointer (not shown).

DEXTER_PARAM *pParam;
DEXTER_VALUE *pValue;
LONG count;

hr = pSetter->GetProps(&count, &pParam, &pValue);

LONG num = 0;
for (LONG i = 0; i < count; i++)
{
    for (LONG j = 0; j < pParam[i].nValues; j++)
    {
        // pValue[num] is the next value in the sequence for pParam[i]
    }
    num += pParam[i].nValues;
}

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::LoadFromBlob

The LoadFromBlob method loads property data from a persistence format.

Syntax

HRESULT LoadFromBlob(
    LONG cSize,
    BYTE *pb
);

Parameters

cSize

[in] Size of the data, in bytes.

pb

[in] Pointer to an array of bytes that contains the data.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another error code.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::LoadXML

The LoadXML method loads property data expressed in Extensible Markup Language (XML).

Syntax

HRESULT LoadXML(
    IUnknown *pxml
);

Parameters

pxml

[in] Pointer to the IUnknown interface of an XML element created by the Microsoft XML parser.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | No property data.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_INVALID_FILE_FORMAT | Invalid format.

Remarks

Typically, applications will not need to use this method. DES uses it internally to load properties from XTL files.

To use this method, create an IXMLDocument object and use it to parse an XML file. Then use the IXMLDocument object to retrieve IXMLElement objects. If the object has properties, you can pass the IXMLElement pointer to the LoadXML method. The method loads the properties into the property setter.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::PrintXML

The PrintXML method converts property data into an Extensible Markup Language (XML) string.

Syntax

HRESULT PrintXML(
    char *pszXML,
    int cbXML,
    int *pcbPrinted,
    int indent
);

Parameters

pszXML

[out] Pointer to a buffer that receives the XML string.

cbXML

[in] Size of the buffer pointed to by pszXML, in bytes.

pcbPrinted

[out] Pointer to a variable that receives the length of the XML string. Can be NULL.

indent

[in] Number of indent levels for the outermost tag.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error. If the XML string is longer than the buffer, the method returns E_OUTOFMEMORY.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::SaveToBlob

The SaveToBlob method saves the property data to a persistence format.

Syntax

HRESULT SaveToBlob(
    LONG *pcSize,
    BYTE **ppb
);

Parameters

pcSize

[out] Pointer to a variable that receives the size of the data, in bytes.

ppb

[out] Address of a pointer to an array of bytes that receives the data.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The method allocates memory for the byte array. The caller must free it, using the CoTaskMemFree function.

All property names and values are truncated to 40 characters in length. For this reason, XML is the preferred persistence format. See IXml2Dex Interface.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IPropertySetter::SetProps

The SetProps method sets the properties of the target object to the appropriate state for the specified time.

Syntax

HRESULT SetProps(
    IUnknown *pTarget,
    REFERENCE_TIME rtNow
);

Parameters

pTarget

[in] Pointer to the target object for which to set the properties.

rtNow

[in] Time at which to set the properties, in 100-nanosecond units, or –1 to set static properties (those that do not vary over time).

Return Value

Returns an HRESULT value.

Remarks

This method is called by DES to set the properties on a transition or effect. An application will not normally call this method.

The object specified by pTarget must implement the IDispatch interface.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IPropertySetter Interface
  • Error and Success Codes


IRenderEngine Interface

The IRenderEngine interface renders a DirectShow Editing Services (DES) project by constructing a filter graph from a timeline.

DES provides two components that implement this interface:

  • The basic render engine creates uncompressed output. You can use the output for preview, or route it through compression filters and write it to a file.
  • The smart render engine creates compressed output, using smart recompression. With smart recompression, a source file is recompressed only if its format differs from the output format. A source with a matching format is written directly to the output file. Depending on the scenario, smart recompression can greatly improve rendering time.

The smart render engine also supports the ISmartRenderEngine interface.

Although an application can create a filter graph and pass it to a render engine, the typical scenario is for the render engine to create the filter graph. Building the graph is a two-stage process. First, build the front end by calling the IRenderEngine::ConnectFrontEnd method. Then connect the output pins on the front end to the desired rendering filters:

  • Video and audio renderers for preview, or
  • Compressors, multiplexers, and file writers to generate the final output.

In addition to the methods inherited from IUnknown, the IRenderEngine interface exposes the following methods.

Method | Description
Commit | Not implemented.
ConnectFrontEnd | Builds the front end of the filter graph from the current timeline.
Decommit | Not implemented.
DoSmartRecompression | Not supported.
GetCaps | Not implemented.
GetFilterGraph | Retrieves the filter graph that the render engine has constructed, if any.
GetGroupOutputPin | Retrieves the output pin for the specified group.
GetTimelineObject | Retrieves the timeline that the render engine is currently using.
GetVendorString | Retrieves the vendor string.
RenderOutputPins | Creates the previewing portion of the filter graph.
ScrapIt | Discards the render engine's filter graph and all associated objects.
SetDynamicReconnectLevel | Sets the level of dynamic reconnection during rendering.
SetFilterGraph | Specifies a filter graph for the render engine to use.
SetInterestRange | Not supported.
SetInterestRange2 | Not supported.
SetRenderRange | Sets the range of time to be rendered.
SetRenderRange2 | Sets the range of time to be rendered, as a double.
SetSourceConnectCallback | Not supported.
SetSourceNameValidation | Specifies how the render engine validates file names.
SetTimelineObject | Sets the timeline for the render engine to use.
UseInSmartRecompressionGraph | Not supported.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Rendering a Project


IRenderEngine::Commit

Not implemented.

Syntax

HRESULT Commit( void );

See Also

  • IRenderEngine Interface


IRenderEngine::ConnectFrontEnd

The ConnectFrontEnd method builds the front end of the filter graph from the current timeline.

Syntax

HRESULT ConnectFrontEnd( void );

Return Value

Returns an HRESULT value. Possible return values include the following:

Value | Description
S_OK | Success.
S_WARN_OUTPUTRESET | Rendering portion of the graph was deleted.
E_INVALIDARG | No timeline set for this render engine.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because the project was not rendered successfully.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method does not build the rendering portion of the filter graph. The application must connect the output pins on the front end to the desired rendering filters:

  • To preview, call the IRenderEngine::RenderOutputPins method.
  • To output a file, call IRenderEngine::GetGroupOutputPin to retrieve the output pin for each group, then connect the pins to a multiplexer filter.

If you are using the basic render engine, the output pins on the front end produce uncompressed data. If you are using the smart render engine, the output pins produce compressed data.

If you change the timeline after you build the filter graph, you must call ConnectFrontEnd again to rebuild the front end. The method preserves the rendering portion of the graph whenever possible. However, if you add or delete a group, or change the order of the groups, ConnectFrontEnd deletes the rendering portion and your application must rebuild it. If the method deletes the rendering portion, it returns S_WARN_OUTPUTRESET.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::Decommit

Not implemented.

Syntax

HRESULT Decommit( void );

See Also

  • IRenderEngine Interface


IRenderEngine::DoSmartRecompression

Not supported.

Syntax

HRESULT DoSmartRecompression( void );

See Also

  • IRenderEngine Interface


IRenderEngine::GetCaps

Not implemented.

Syntax

HRESULT GetCaps(
    long Index,
    long *pReturn
);

See Also

  • IRenderEngine Interface


IRenderEngine::GetFilterGraph

The GetFilterGraph method retrieves the filter graph that the render engine has constructed, if any.

Syntax

HRESULT GetFilterGraph(
    IGraphBuilder **ppFG
);

Parameters

ppFG

[out] Address of a pointer to receive the filter graph's IGraphBuilder interface. It receives the value NULL if there is no filter graph.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_POINTER | Invalid pointer.

Remarks

Use the IRenderEngine::ConnectFrontEnd method to build the front end of the filter graph. For preview, use the IRenderEngine::RenderOutputPins to complete the graph. For file output, connect the front end to a mux/file writer combination. For more information, see Rendering a Project.

The resulting graph can be run, paused, stopped, and seeked; the playback rate cannot be changed, however.

On return, if the value of *ppFG is non-NULL, the IGraphBuilder interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::GetGroupOutputPin

The GetGroupOutputPin method retrieves the output pin for the specified group.

Syntax

HRESULT GetGroupOutputPin(
    long Group,
    IPin **ppRenderPin
);

Parameters

Group

Zero-based index that specifies the group.

ppRenderPin

[out] Address of a pointer to receive the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
S_FALSE | Group does not have an output pin.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_POINTER | Invalid pointer.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call IRenderEngine::ConnectFrontEnd to build the front end of the graph. Each group represents a single media stream, and the front end has a corresponding output pin.

You can use this method to create the rendering portion of a file-writing graph. Connect the output pins to multiplexer filters and file writer filters. For more information, see Rendering a Project.

For preview, you don't need to call this method. Just call ConnectFrontEnd followed by IRenderEngine::RenderOutputPins.

If the method returns S_OK, the IPin interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::GetTimelineObject

The GetTimelineObject method retrieves the timeline that the render engine is currently using.

Syntax

HRESULT GetTimelineObject(
    IAMTimeline **ppTimeline
);

Parameters

ppTimeline

[out] Address of a pointer to receive the timeline's IAMTimeline interface. It receives the value NULL if there is no timeline.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_POINTER | Invalid pointer.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

On return, if the value of *ppTimeline is non-NULL, the IAMTimeline interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::GetVendorString

The GetVendorString method retrieves the name of the vendor. For the render engine objects that are provided by DirectShow, the vendor string is "Microsoft Corporation".

Syntax

HRESULT GetVendorString(
    BSTR *pVendorID
);

Parameters

pVendorID

[out, retval] Pointer to a variable that receives a BSTR containing the vendor string.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
E_NOTIMPL | Not implemented
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::RenderOutputPins

The RenderOutputPins method creates the previewing portion of the filter graph.

Syntax

HRESULT RenderOutputPins( void );

Return Value

Returns an HRESULT values. The following are possible values:

Value | Description
S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream.
E_INVALIDARG | Invalid argument.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call IRenderEngine::ConnectFrontEnd to build the front end of the graph. To perform an operation other than preview, do not call this method. Instead, call IRenderEngine::GetGroupOutputPin to obtain pointers to the output pins.

If there is no sound card on the user's computer, this method returns VFW_S_AUDIO_NOT_RENDERED. There will not be audio preview in this case, but video preview is unaffected.

If the pin is from a video group, this method creates a video window. The calling thread must dispatch messages—for example, to move the window, or respond to mouse clicks in the window's client area.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::ScrapIt

The ScrapIt method discards the render engine's filter graph and all associated objects.

Syntax

HRESULT ScrapIt( void );

Return Value

Returns one of the following HRESULT values:

Value | Description
Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetDynamicReconnectLevel

The SetDynamicReconnectLevel method sets the level of dynamic reconnection during rendering.

Syntax

HRESULT SetDynamicReconnectLevel(
    DWORD Level
);

Parameters

Level

Combination of Dynamic Reconnection Flags, specifying the level of dynamic reconnection.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

By default, the basic render engine loads every source before rendering a project. This can result in a long start-up time. With dynamic reconnection, sources are loaded only when needed. This can shorten the start-up time, but possibly interfere with smooth playback. Generally, the more source clips that a project uses, the more you might benefit from dynamic reconnection.

The smart render engine does not implement this method.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetFilterGraph

The SetFilterGraph method specifies a filter graph for the render engine to use.

Syntax

HRESULT SetFilterGraph(
    IGraphBuilder *pFG
);

Parameters

pFG

Pointer to the IGraphBuilder interface of the filter graph.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Most applications do not need to call this method. It is more typical to let the render engine build the graph for you, by calling the IRenderEngine::ConnectFrontEnd method.

This method fails if the render engine already has a filter graph.

Never retrieve a pointer to a filter graph created by one render engine and then use it as the parameter to this method on another render engine. Doing so will cause unpredictable results.

The ConnectFrontEnd method tears down any existing filter graph, but keeps the same Filter Graph Manager instance.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetInterestRange

Not supported.

Syntax

HRESULT SetInterestRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

See Also

  • IRenderEngine Interface


IRenderEngine::SetInterestRange2

Not supported.

Syntax

HRESULT SetInterestRange2(
    double Start,
    double Stop
);

See Also

  • IRenderEngine Interface


IRenderEngine::SetRenderRange

The SetRenderRange method sets the range of time on the timeline to be rendered. Objects that lie outside the specified range are not rendered, and resources are not allocated for them.

Syntax

HRESULT SetRenderRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start

Start time, in 100-nanosecond units.

Stop

Stop time, in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetRenderRange2

The SetRenderRange2 method sets the range of time on the timeline to be rendered. This method is equivalent to IRenderEngine::SetRenderRange, but takes values of type double.

Syntax

HRESULT SetRenderRange2(
    double Start,
    double Stop
);

Parameters

Start

Start time, in seconds.

Stop

Stop time, in seconds.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetSourceConnectCallback

Not supported.

Syntax

HRESULT SetSourceConnectCallback(
    IGrfCache *pCallback
);

See Also

  • IRenderEngine Interface


IRenderEngine::SetSourceNameValidation

The SetSourceNameValidation method specifies how the render engine validates file names.

Syntax

HRESULT SetSourceNameValidation(
    BSTR FilterString,
    IMediaLocator *pOverride,
    LONG Flags
);

Parameters

FilterString

BSTR value containing pairs of filter strings, formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it presents an Open File dialog box to the end user.

pOverride

Optional pointer to the IMediaLocator interface of a media locator to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.

Flags

Bitwise combination of File Name Validation Flags specifying the behavior of the media locator. The SFN_VALIDATEF_CHECK flag must be present. The SFN_VALIDATEF_IGNOREMUTED flag has no effect with this method.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the IMediaLocator interface. For example, the default media locator does not notify an application about the files that it finds (or cannot find). To get around this limitation, you could implement a custom media locator, making it a wrapper for the default version. Then pass IMediaLocator::FindMediaFile calls directly to the default version and examine the return value.

Currently, this method does not validate dynamically loaded sources. See IRenderEngine::SetDynamicReconnectLevel.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::SetTimelineObject

The SetTimelineObject method sets the timeline for the render engine to use.

Syntax

HRESULT SetTimelineObject(
    IAMTimeline *pTimeline
);

Parameters

pTimeline

Pointer to the timeline object's IAMTimeline interface.

Return Value

Returns one of the following HRESULT values:

Value | Description
S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Invalid pointer.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IRenderEngine Interface
  • Error and Success Codes


IRenderEngine::UseInSmartRecompressionGraph

Not supported.

Syntax

HRESULT UseInSmartRecompressionGraph( void ) ;

See Also

  • IRenderEngine Interface


IRenderEngine2 Interface

The IRenderEngine2 interface enables the application to replace the default video resizing filter used by DirectShow Editing Services (DES). The Basic Render Engine and the Smart Render Engine both support this interface.

In addition to the methods inherited from IUnknown, the IRenderEngine2 interface exposes the following method.

Method | Description
SetResizerGUID | Specifies the CLSID of a custom resizing filter provided by the application.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Providing a Custom Video Resizer


IRenderEngine2::SetResizerGUID

The SetResizerGUID method specifies the CLSID of a custom video resizing filter. Call this method to replace the default resizing filter used by DirectShow Editing Services. Your filter must be registered as a COM object on the user's system, and it must support the IResize interface.

Call this method before calling IRenderEngine::ConnectFrontEnd.

Syntax

HRESULT SetResizerGUID(
    GUID ResizerGuid
);

Parameters

ResizerGuid

[in] Specifies the CLSID of the filter.

Return Value

Returns an HRESULT value.

Remarks

To revert to the default DES resizer, use the following CLSID:

// {F97B8A60-31AD-11CF-B2DE-00DD01101B85}
DEFINE_GUID(CLSID_Resize,
0xF97B8A60, 0x31AD, 0x11CF, 0xB2, 0xDE, 0x00, 0xDD, 0x01, 0x10, 0x1B, 0x85);

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IRenderEngine2 Interface


IResize Interface

The IResize interface must be supported by any custom video resizer filter for DirectShow Editing Services (DES). To set a custom resizer filter, call the IRenderEngine2::SetResizerGUID method on the render engine.

In addition to the methods inherited from IUnknown, the IResize interface exposes the following methods.

Method | Description
get_InputSize | Returns the resizer filter's current input size.
get_MediaType | Returns the resizer filter's output media type.
get_Size | Returns the current output size and stretch mode.
put_MediaType | Sets the output media type.
put_Size | Sets the output size and stretch mode.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Providing a Custom Video Resizer


IResize::get_InputSize

The get_InputSize method returns the resizer filter's current input size.

Syntax

HRESULT get_InputSize(
    int *piHeight,
    int *piWidth
);

Parameters

piHeight

[out] Pointer to a variable that receives the video height, in pixels.

piWidth

[out] Pointer to a variable that receives the video width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

If the filter's input pin is not connected, return an error code. Otherwise, return the width and height of the video, as specified by the input pin's media type.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IResize Interface


IResize::get_MediaType

The get_MediaType method returns the resizer filter's current output media type.

Syntax

HRESULT get_MediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[out] Pointer to an AM_MEDIA_TYPE structure allocated by the caller. The method fills this structure with the media type. The caller must release the format block, if any.

Return Value

Returns an HRESULT value.

Remarks

If the output media type has not been set, return a default media type. The filter must update its output media type when the put_MediaType or put_Size methods are called; the media type returned by get_MediaType must reflect these changes.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IResize Interface


IResize::get_Size

The get_Size method returns the current output size and stretch mode.

Syntax

HRESULT get_Size(
    int *piHeight,
    int *piWidth
    long *pFlag
);

Parameters

piHeight

[out] Pointer to a variable that receives the video height, in pixels.

piWidth

[out] Pointer to a variable that receives the video width, in pixels.

pFlag

[out] Pointer to a variable that receives a flag specifying the stretch mode. See Resize Flags for possible values.

Return Value

Returns an HRESULT value.

Remarks

If the output type has not been set, the filter should return default values. These values can be arbitrarily chosen at design time.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IResize Interface


IResize::put_MediaType

The put_MediaType method sets the output media type on the resizer filter.

Syntax

HRESULT put_MediaType(
    const AM_MEDIA_TYPE *pmt
);

Parameters

pmt

[in] Pointer to an AM_MEDIA_TYPE structure that contains the media type.

Return Value

Returns an HRESULT value.

Remarks

DES calls this method before it connects the filter's output pin. Use the media type as the output pin's media type. Return this media type in the CTransformFilter::GetMediaType method, and check agsint this type in the CTransformFilter::CheckTransform method. DES never calls this method after the output pin is connected.

Currently, DES always sets the output media type to an uncompressed RGB format with a VIDEOINFOHEADER format block (format type equals FORMAT_VideoInfo). The subtype might be MEDIASUBTYPE_ARGB32, which indicates 32-bit RGB with an alpha channel.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IResize Interface


IResize::put_Size

The put_Size method sets the output size and stretch mode.

Syntax

HRESULT put_Size(
    int Height,
    int Width
    int Flags

Parameters

Height

[in] Specifies the video height, in pixels.

Width

[in] Specifies the video width, in pixels.

Flags

[in] Specifies the stretch mode. See Resize Flags for possible values.

Return Value

Returns an HRESULT value.

Remarks

DES may call this method before or after calling put_MediaType. If DES calls this method before calling put_MediaType, the filter should select a default value for the bit depth and use the size values to construct an output media type. If DES calls this method after calling put_MediaType, the filter should modify its current output type with the new sizes.

DES may also call this method after the output pin is connected. In that case, modify the output type and reconnect the output pin with the new type. See Reconnecting Pins for more information.

The Flags parameter specifies how the filter should perform the resizing operation.

Requirements

Requires DirectX 9.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Error and Success Codes
  • IResize Interface


ISmartRenderEngine Interface

The ISmartRenderEngine interface provides methods that support smart recompression in DirectShow Editing Services (DES). The smart render engine exposes this interface.

In addition to the methods inherited from IUnknown, the ISmartRenderEngine interface exposes the following methods.

Method | Description
GetGroupCompressor | Retrieves the compression filter for the specified group.
SetFindCompressorCB | Not implemented.
SetGroupCompressor | Specifies a compression filter to use when rendering the specified group.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • Rendering a Project


ISmartRenderEngine::GetGroupCompressor

The GetGroupCompressor method retrieves the compression filter for the specified group.

Syntax

HRESULT GetGroupCompressor(
    long Group,
    IBaseFilter **pCompressor
);

Parameters

Group

Zero-based index of the group.

pCompressor

Address of a pointer to receive the IBaseFilter interface of the compression filter. It receives the value NULL if there is no compression filter.

Return Value

Returns one of the following values.

Value | Description
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer error.
S_OK | Success.

Remarks

Use this method to set properties on the compression filter, such as the key-frame rate. Call this method after calling IRenderEngine::ConnectFrontEnd, but before rendering the project. Then query the compression filter's output pin for the IAMVideoCompression interface, which contains methods for setting compression parameters. Release the interface when you are done. If you make any subsequent changes to the timeline, call ConnectFrontEnd, and then call GetGroupCompressor again to reset the compression parameters.

On return, if the value of *pCompressor is non-NULL, the IBaseFilter interface has an outstanding reference count. Be sure to release the interface when you are done using it.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • ISmartRenderEngine Interface
  • Error and Success Codes


ISmartRenderEngine::SetFindCompressorCB

Not implemented.

Syntax

HRESULT SetFindCompressorCB(
    IFindCompressorCB *pCallback
);

See Also

  • ISmartRenderEngine Interface


ISmartRenderEngine::SetGroupCompressor

Specifies a compression filter to use when rendering the specified group.

Syntax

HRESULT SetGroupCompressor(
    long Group,
    IBaseFilter *pCompressor
);

Parameters

Group

Zero-based index of the group.

pCompressor

Pointer to the IBaseFilter interface of the compression filter.

Return Value

Returns S_OK if successful. Otherwise, returns E_INVALIDARG.

Requirements

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • ISmartRenderEngine Interface
  • Error and Success Codes


IXml2Dex Interface

The IXml2Dex interface saves and loads DirectShow Editing Services (DES) project files in Extensible Markup Language (XML). This interface also provides methods for reading and writing DirectShow graph (.grf) files.

In addition to the methods inherited from IUnknown, the IXml2Dex interface exposes the following methods.

Method | Description
CopyXML | Not implemented.
CreateGraphFromFile | Not implemented.
Delete | Not implemented.
PasteXML | Not implemented.
ReadXML | Not implemented.
PasteXMLFile | Not implemented.
ReadXMLFile | Loads an XML project file.
Reset | Not implemented.
WriteGrfFile | Writes a filter graph to a file in .grf format.
WriteXML | Translates a timeline to an XML string.
WriteXMLFile | Translates a timeline to XML and writes the XML data to a file.
WriteXMLPart | Not implemented.

Requirements

Requires Internet Explorer 4.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.


IXml2Dex::CopyXML

Not implemented.

Syntax

HRESULT CopyXML(
    IUnknown *pTimeline,
    double dStart,
    double dEnd
);

See Also

  • IXml2Dex Interface


IXml2Dex::CreateGraphFromFile

Not implemented.

Syntax

HRESULT CreateGraphFromFile(
    IUnknown **ppGraph,
    IUnknown *pTimeline,
    BSTR FileName
);

See Also

  • IXml2Dex Interface


IXml2Dex::Delete

Not implemented.

Syntax

HRESULT Delete(
    IUnknown *pTimeline,
    double dStart,
    double dEnd
);

See Also

  • IXml2Dex Interface


IXml2Dex::PasteXML

Not implemented.

Syntax

HRESULT PasteXML(
    IUnknown *pTimeline,
    double dStart
);

See Also

  • IXml2Dex Interface


IXml2Dex::PasteXMLFile

Not implemented.

Syntax

HRESULT PasteXMLFile(
    IUnknown *pTimeline,
    double dStart,
    BSTR FileName
);

See Also

  • IXml2Dex Interface


IXml2Dex::ReadXML

Not implemented.

Syntax

HRESULT ReadXML(
    IUnknown *pTimeline,
    IUnknown *pXML
);

See Also

  • IXml2Dex Interface


IXml2Dex::ReadXMLFile

The ReadXMLFile method loads an XML project file. This method creates instances of all the objects expressed in the XML file and inserts them into the timeline, as well as applying any attributes given for the timeline, such as frame rate or default effect.

Syntax

HRESULT ReadXMLFile(
    IUnknown *pTimeline,
    BSTR XMLName
);

Parameters

pTimeline

Pointer to a timeline object's IUnknown interface.

XMLName

String that specifies the name of the file to load.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success
VFW_E_INVALID_FILE_FORMAT | Invalid file format

Remarks

This method does not clear existing objects from the timeline before it inserts the new objects defined in the XML file. If you need to refresh an existing timeline, call IAMTimeline::ClearAllGroups first.

Requirements

Requires Internet Explorer 4.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IXml2Dex Interface
  • Error and Success Codes


IXml2Dex::Reset

Not implemented.

Syntax

HRESULT Reset(void);

See Also

  • IXml2Dex Interface


IXml2Dex::WriteGrfFile

The WriteGrfFile method writes a filter graph to a file in .grf format.

Syntax

HRESULT WriteGrfFile(
    IUnknown *pGraph,
    BSTR FileName
);

Parameters

pGraph

Pointer to the filter graph's IUnknown interface.

FileName

String that specifies the name of the file to write.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
S_OK | Success.

This method can also return error codes generated by internal calls to the IStorage::CreateStream and IPersist::Save methods. For more information, see the Platform SDK.

Requirements

Requires Internet Explorer 4.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IXml2Dex Interface
  • Error and Success Codes


IXml2Dex::WriteXML

The WriteXML method translates a timeline to an XML string.

Syntax

HRESULT WriteXML(
    IUnknown *pTimeline,
    BSTR *pbstrXML
);

Parameters

pTimeline

Pointer to the timeline object's IUnknown interface.

pbstrXML

Pointer to a variable of type BSTR that receives the XML string describing the timeline.

Return Value

Returns S_OK if successful. If there is insufficient memory for the conversion, returns E_OUTOFMEMORY. Otherwise, returns another error code.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Requirements

Requires Internet Explorer 4.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IXml2Dex Interface
  • Error and Success Codes


IXml2Dex::WriteXMLFile

The WriteXMLFile method translates a timeline to XML and writes the XML data to a file.

Syntax

HRESULT WriteXMLFile(
    IUnknown *pTimeline,
    BSTR FileName
);

Parameters

pTimeline

Pointer to the timeline object's IUnknown interface.

FileName

String that specifies the name of the file to write.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

Value | Description
E_INVALIDARG | Argument is invalid.
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

This method generates an XML file that represents all the components in the timeline.

Requirements

Requires Internet Explorer 4.0 or later.

Header: Include Qedit.h. This header file is not compatible with Microsoft® Direct3D® headers later than version 7.

Library: Use strmiids.lib.

See Also

  • IXml2Dex Interface
  • Error and Success Codes


IXml2Dex::WriteXMLPart

Not implemented.

Syntax

HRESULT WriteXMLPart(
    IUnknown *pTimeline,
    double dStart,
    double dEnd,
    BSTR FileName
);

See Also

  • IXml2Dex Interface


Structures

Microsoft® DirectShow® Editing Services defines the following structures.

Structure | Description
DEXTER_PARAM | Specifies a property on a transition or effect.
DEXTER_VALUE | Specifies the value of a property.
SCompFmt0 | Contains format information for smart recompression.


DEXTER_PARAM Structure

Specifies the value that a property assumes at a given time.

Syntax

typedef struct {
    BSTR      Name;
    DISPID    dispID;
    LONG      nValues;
} DEXTER_PARAM;

Members

Name

Name of the property.

dispID

Reserved. Set to zero.

nValues

Number of values that the property assumes.

Remarks

The object must support the IDispatch interface.

See Also

  • IPropertySetter
  • DEXTER_VALUE


DEXTER_VALUE Structure

Identifies a property that is to be set on a transition or effect, along with the number of distinct values that the property assumes over the duration of the transition or effect.

Syntax

typedef struct {
    VARIANT           v;
    REFERENCE_TIME    rt;
    DWORD             dwInterp;
} DEXTER_VALUE;

Members

v

Value of the property.

rt

Time at which the property assumes the value, relative to the start of the transition or effect.

dwInterp

Flag indicating how the property progresses from the previous value to this value. Must be one of the following:

Value | Description
DEXTERF_JUMP | The property jumps instantly to the new value at the specified time.
DEXTERF_INTERPOLATE | The property is interpolated linearly over time from the previous value.

See Also

  • IPropertySetter
  • DEXTER_PARAM


SCompFmt0 Structure

Contains format information for smart recompression.

Syntax

typedef struct _SCompFmt0
{
    long nFormatId;
    AM_MEDIA_TYPE MediaType;
} SCompFmt0;

Members

nFormatId

Reserved; must be zero.

MediaType

AM_MEDIA_TYPE structure that describes the compression format.

See Also

  • IAMTimelineGroup::GetSmartRecompressFormat
  • IAMTimelineGroup::SetSmartRecompressFormat


Enumerated Types

Microsoft® DirectShow® Editing Services defines the following enumerated types.

DEXTERF_TRACK_SEARCH_FLAGS | Specifies the boundary conditions on a search for an object in the timeline.
TIMELINE_MAJOR_TYPE | Specifies the major type of a timeline object.


DEXTERF_TRACK_SEARCH_FLAGS Enumeration

The DEXTERF_TRACK_SEARCH_FLAGS enumeration specifies the boundary conditions on a search for an object in the timeline.

Syntax

typedef enum {
    DEXTERF_BOUNDING = -1,
    DEXTERF_EXACTLY_AT = 0,
    DEXTERF_FORWARDS = 1
} DEXTERF_TRACK_SEARCH_FLAGS;

Elements

DEXTERF_BOUNDING

Search for an object that spans the specified time.

DEXTERF_EXACTLY_AT

Search for an object that starts exactly at the specified time.

DEXTERF_FORWARDS

Search for an object that starts at the specified time or later.

Remarks

These boundary conditions are summarized in the following table.

Enumeration value | Boundary condition
DEXTERF_BOUNDING | Start <= Time Stop > Time
DEXTERF_EXACTLY_AT | Start == Time
DEXTERF_FORWARDS | Start >= Time

  • Start: start time of the retrieved object.
  • Stop: stop time of the retrieved object.
  • Time: specified search time.

See Also

  • IAMTimelineTrack::GetSrcAtTime


TIMELINE_MAJOR_TYPE Enumeration

The TIMELINE_MAJOR_TYPE enumeration specifies the major type of an object.

Syntax

typedef enum {
    TIMELINE_MAJOR_TYPE_COMPOSITE = 1,
    TIMELINE_MAJOR_TYPE_TRACK = 2,
    TIMELINE_MAJOR_TYPE_SOURCE = 4,
    TIMELINE_MAJOR_TYPE_TRANSITION = 8,
    TIMELINE_MAJOR_TYPE_EFFECT = 16,
    TIMELINE_MAJOR_TYPE_GROUP = 128
} TIMELINE_MAJOR_TYPE;

Elements

TIMELINE_MAJOR_TYPE_COMPOSITE

Composite object. Holds one or more tracks.

TIMELINE_MAJOR_TYPE_TRACK

Track object. Holds one or more sources.

TIMELINE_MAJOR_TYPE_SOURCE

Source object. Contains a reference to a media source.

TIMELINE_MAJOR_TYPE_TRANSITION

Transition object. Defines a transition between composites, tracks, or sources.

TIMELINE_MAJOR_TYPE_EFFECT

Effect object. Defines a single-input effect to be applied to a composite, track, or source object.

TIMELINE_MAJOR_TYPE_GROUP

Group object. Contains one or more tracks of a given type.

See Also

  • IAMTimeline
  • IAMTimelineComp::GetCountOfType
  • IAMTimelineObj::GetTimelineType


Constants

Microsoft® DirectShow® Editing Services defines the following constants.

  • Dynamic Reconnection Flags
  • File Name Validation Flags
  • Resize Flags


Dynamic Reconnection Flags

The following flags specify the level of dynamic reconnection to use during rendering.

Constant | Value | Description
CONNECTF_DYNAMIC_NONE | 0x00 | No dynamic reconnection. Load everything before rendering the project.
CONNECTF_DYNAMIC_SOURCES | 0x01 | Load sources only as needed.
CONNECTF_DYNAMIC_EFFECTS | 0x02 | Reserved. Do not use.

See Also

  • IRenderEngine::SetDynamicReconnectLevel


File Name Validation Flags

These flags specify the behavior of the media locator.

Constant | Value | Description
SFN_VALIDATEF_CHECK | 0x01 | Check the validity of file names. You must set this flag to validate file names. If not, the other flags have no effect.
SFN_VALIDATEF_POPUP | 0x02 | If a file is not located, display an Open File dialog box for the end user.
SFN_VALIDATEF_TELLME | 0x04 | If a missing file is located, briefly display a message box with the name and location of the file. This flag is mostly useful for testing purposes; the message box is probably not suitable for a retail product.
SFN_VALIDATEF_REPLACE | 0x08 | If a missing file is located, update the name of the source object. (Only valid in the IAMTimeline::ValidateSourceNames method.)
SFN_VALIDATEF_USELOCAL | 0x10 | Always use a local file, even if a version of the file exists on the network.
SFN_VALIDATEF_NOFIND | 0x20 | Do not search for missing files. File names are still validated if you set the SFN_VALIDATEF_CHECK flag.
SFN_VALIDATEF_IGNOREMUTED | 0x40 | Ignore muted source objects. (Only valid in the IAMTimeline::ValidateSourceNames method.)

See Also

  • IMediaLocator::FindMediaFile
  • IRenderEngine::SetSourceNameValidation


Resize Flags

These flags specify how a video source is rendered if its size does not match the output dimensions.

Constant | Value | Description
RESIZEF_STRETCH | 0 | The image is stretched to fit the target frame size in both dimensions, without preserving the aspect ratio.
RESIZEF_CROP | 1 | The image is not resized. If the image is smaller than the target frame, the surrounding area is black. If the image is larger than the target frame, the image is cropped.
RESIZEF_PRESERVEASPECTRATIO | 2 | The image is resized to fit the target frame along one dimension, while preserving the aspect ratio. If the ratio of width to height in the image does not match the ratio in the target frame, it creates a letterbox.
RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX | 3 | The image is resized to fill the entire target frame while preserving the aspect ratio. Rather than create a letterbox, this mode crops the image, either along the sides or across the top and bottom.

The following images show the effects of these flags.

See Also

  • IAMTimelineSrc::GetStretchMode
  • IAMTimelineSrc::SetStretchMode


Transitions and Effects

This section describes the effects and transitions provided with Microsoft® DirectShow® Editing Services.

Transition | Description
Compositor | Stretches the foreground into a designated rectangle, without altering the background.
Key | Performs keying based on chroma, alpha, hue, or luminance.
SMPTE Wipe | Performs the standard SMPTE wipes.

Effect | Description
Alpha Setter | Sets the alpha bits on a video image.
Volume Envelope | Sets the volume on an audio stream.

Source Object | Description
Video Color Source | Creates a continuous video image of a solid color.


Alpha Setter Effect

The Alpha Setter effect sets the alpha bits on a video image.

Class ID (CLSID): {506D89AE-909A-44f7-9444-ABD575896E35}

CLSID Variable Name: CLSID_DxtAlphaSetter

Friendly Name: "DxtAlphaSetter"

Properties

Property | Type | Default | Description
Alpha | BYTE | -1 | Sets the alpha for the entire image.
AlphaRamp | double | -1.0 | Sets the alpha as a percentage of the original alpha value.

Remarks

A property with a negative value is ignored. Only one property can have a non-negative value. The Alpha property specifies a constant alpha value for every pixel in the image. This property overwrites the alpha values from the original image. The AlphaRamp property specifies each pixel's alpha value as a percentage of the pixel's original value, from 0.0 to 1.0.

See Also

  • Alpha Blending


Compositor Transition

The Compositor transition composites a subrectangle from the foreground into a designated rectangle on the background, without altering the rest of the background. Use this transition to create split-screen or picture-in-picture effects.

The following image shows the compositor transition:

Class ID (CLSID): {BB44391D-6ABD-422f-9E2E-385C9DFF51FC}

CLSID Variable Name: CLSID_DxtCompositor

Friendly Name: "DxtCompositor"

Properties

Property | Type | Default | Description
Height | long | 0 | Height of the target rectangle, in pixels.
OffsetX | long | 0 | Horizontal offset of the target rectangle, in pixels.
OffsetY | long | 0 | Vertical offset of the target rectangle, in pixels.
SrcHeight | long | 0 | The height of the subrectangle on the source, in pixels.
SrcOffsetX | long | 0 | The x-coordinate of the subrectangle on the source, in pixels.
SrcOffsetY | long | 0 | The y-coordinate of the subrectangle on the source, in pixels.
SrcWidth | long | 0 | The width of the subrectangle on the source, in pixels.
Width | long | 0 | Width of the target rectangle, in pixels.

The following diagram illustrates these properties:


Key Transition

The Key transition performs keying based on RGB value, alpha value, hue or luminance.

The following image shows the key transition:

Class ID (CLSID): {C5B19592-145E-11D3-9F04-006008039E37}

CLSID Variable Name: CLSID_DxtKey

Friendly Name: "DxtKey"

Properties

Property | Type | Valid range | Description | Applies To
Hue | int | 0–360 | The hue value on which to key. | Hue
Invert | BOOL | FALSE or TRUE | Boolean value indicating whether to invert the default operation of the key. If FALSE, pixels in the overlying image are made transparent in the default manner. If TRUE, the operation inverts. | Chroma, Hue, Luminance, Nonred
KeyType | int | See Remarks | Specifies the type of key. For more information, see Remarks. | All
Luminance | int | 0–100 | The luminance value on which to key. | Luminance
RGB | DWORD | 0x0 – 0xFFFFFF | The color on which to key. The value is a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value. (Pure red, green, and blue are 0xFF0000, 0x00FF00, and 0x0000FF, respectively.) | Chroma
Similarity | int | 0–100 | The range of color data that becomes transparent. At higher values, a wider range of similar colors is transparent. | Chroma, Nonred

Remarks

The type of key that is performed depends on the value of the KeyType property, which must be one of the following:

Value | Enumeration | Description
0 | DXTKEY_RGB | Chroma key (key by RGB value).
1 | DXTKEY_NONRED | Nonred key. (Makes blue and green areas transparent.)
2 | DXTKEY_LUMINANCE | Luminance key.
3 | DXTKEY_ALPHA | Key by alpha value.
4 | DXTKEY_HUE | Key by hue.

The key type defaults to DXTKEY_ALPHA.


SMPTE Wipe Transition

The SMPTE Wipe transition produces any of the standard wipes defined by the Society of Motion Picture and Television Engineers (SMPTE) in SMPTE document 258M-1993, with the exception of the quad split.

Wipe transition in progress

Class ID (CLSID): {DE75D012-7A65-11D2-8CEA-00A0C9441E20}

CLSID Variable Name: CLSID_DxtJpeg

Friendly Name: "DxtJpeg"

Properties

Property | Type | Default | Description
BorderColor | long | 0x000000 | Color of the border around the edges of the wipe pattern. The value of this attribute is a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value. (Thus, pure red, green, and blue are 0xFF000, 0x00FF00, and 0x0000FF, respectively.)
BorderSoftness | long | 0 | Width of the blurry region around the edges of the wipe pattern. Specify zero for no blurry region.
BorderWidth | long | 0 | Width of the solid border along the edges of the wipe pattern. Specify zero for no border.
MaskName | BSTR | NULL | If not NULL, specifies the name of a JPEG file to use as the wipe mask instead of a standard, built-in wipe. The file must contain a monochrome, 8-bits-per-pixel gradient. The gradient is used as a mask to define the wipe's progression.
MaskNum | long | 1 | Standard SMPTE wipe code specifying the style of wipe to use. For a list of wipe codes and their associated schematics, see SMPTE document 258M-1993.
OffsetX | long | 0 | Horizontal offset of the wipe origin from the center of the image. Valid only for values of MaskNum from 101 to 131.
OffsetY | long | 0 | Verical offset of the wipe origin from the center of the image. Valid only for values of MaskNum from 101 to 131.
ReplicateX | long | 0 | Number of times to replicate the wipe pattern horizontally. Valid only for values of MaskNum from 101 to 131.
ReplicateY | long | 0 | Number of times to replicate the wipe pattern vertically. Valid only for values of MaskNum from 101 to 131.
ScaleX | double | 1.0 | Amount by which to stretch the wipe horizontally, as a percentage of the original wipe definition. Valid only for values of MaskNum from 101 to 131.
ScaleY | double | 1.0 | Amount by which to stretch the wipe vertically, as a percentage of the original wipe definition. Valid only for values of MaskNum from 101 to 131.

Remarks

This transition supports the following standard SMPTE wipes:

Number | Description | Number | Description
1 | Horizontal | 211 | Radial, left-right, top
2 | Vertical | 212 | Radial, up-down, right
3 | Upper left | 213 | Radial, left-right, top-bottom
4 | Upper right | 214 | Radial, up-down, left-right
5 | Lower right | 221 | Radial, top
6 | Lower left | 222 | Radial, right
7 | Four corners | 223 | Radial, bottom
8 | Four squares | 224 | Radial, left
21 | Barn doors, vertical | 225 | Radial, top clockwise, bottom clockwise
22 | Barn doors, horizontal | 226 | Radial, left clockwise, right clockwise
23 | Top center | 227 | Radial, top clockwise, bottom anticlockwise
24 | Right center | 228 | Radial, left clockwise, right anticlockwise
25 | Bottom center | 231 | Radial, top split
26 | Left center | 232 | Radial, right split
41 | Diagonal, NW to SE | 233 | Radial, bottom split
42 | Diagonal, NE to SW | 234 | Radial, left split
43 | Triangles, top/bottom | 235 | Radial, top-bottom split
44 | Triangles, left/right | 236 | Radial, left-right split
45 | Diagonal stripe, SW to NE | 241 | Radial, top-left corner
46 | Diagonal stripe, NW to SE | 242 | Radial, bottom-left corner
47 | Cross | 243 | Radial, bottom-right corner
48 | Diamond Box | 244 | Radial, top-right corner
61 | Wedge, top | 245 | Radial, top-left, bottom-right
62 | Wedge, right | 246 | Radial, bottom-left, top-right
63 | Wedge, bottom | 251 | Center radial, top
64 | Wedge, left | 252 | Center radial, left
65 | V | 253 | Center radial, bottom
66 | V, right | 254 | Center radial, right
67 | V, inverted | 261 | Box radial, right
68 | V, left | 262 | Box radial, top
71 | Sawtooth, left | 263 | Center radial, top, bottom
72 | Sawtooth, top | 264 | Center radial, left, right
73 | Sawtooth, vertical | 301 | Matrix, horizontal
74 | Sawtooth, horizontal | 302 | Matrix, vertical
101 | Box | 303 | Matrix, diagonal, top-left
102 | Diamond | 304 | Matrix, diagonal, top-right
103 | Triangle, up | 305 | Matrix, diagonal, bottom-right
104 | Triangle, right | 306 | Matrix, diagonal, bottom-left
105 | Triangle, bottom | 310 | Matrix, clockwise top-left
106 | Triangle, left | 311 | Matrix, clockwise top-right
107 | Arrow head, up | 312 | Matrix, clockwise bottom-right
108 | Arrow head, right | 313 | Matrix, clockwise bottom-left
109 | Arrow head, down | 314 | Matrix, anticlockwise top-left
110 | Arrow head, left | 315 | Matrix, anticlockwise top-right
111 | Pentagon, up | 316 | Matrix, anticlockwise bottom-right
112 | Pentagon, down | 317 | Matrix, anticlockwise bottom-left
113 | Hexagon | 320 | Matrix, vertical top-left, top-right
114 | Hexagon, rotated | 321 | Matrix, vertical bottom-left, bottom-right
119 | Circle | 322 | Matrix, vertical top-left, bottom-right
120 | Oval, horizontal | 323 | Matrix, vertical bottom-left, top-right
121 | Oval, vertical | 324 | Matrix, horizontal top-left, bottom-left
122 | Eye, horizontal | 325 | Matrix, horizontal top-right, bottom-right
123 | Eye, vertical | 326 | Matrix, horizontal top-left, bottom-right
124 | Rounded rectangle, horizontal | 327 | Matrix, horizontal top-right, bottom-left
125 | Rounded rectangle, vertical | 328 | Matrix, diagonal bottom-left, top-right
127 | 4-point star | 329 | Matrix, diagonal top-left, bottom-right
128 | 4-point star | 340 | Matrix, top double spiral
129 | 6-point star | 341 | Matrix, bottom double spiral
130 | Heart | 342 | Matrix, left double spiral
131 | Keyhole | 343 | Matrix, right double spiral
201 | Radial, 12 o'clock | 344 | Matrix, quad spiral, top-bottom
202 | Radial, 3 o'clock | 345 | Matrix, quad spiral, left-right
203 | Radial, 6 o'clock | 350 | Waterfall, left
204 | Radial, 9 o'clock | 351 | Waterfall, right
205 | Radial, 12 + 6 o'clock | 352 | Waterfall, horizontal, left
206 | Radial, 3 + 9 o'clock | 353 | Waterfall, horizontal, right
207 | Radial, 4-way | 409 | Random mask


Volume Envelope Effect

The Volume Envelope effect sets the volume on an audio stream.

Class ID (CLSID): {036A9790-C153-11D2-9EF7-006008039E37}

CLSID Variable Name: CLSID_AudMixer

Properties

Property | Type | Default | Description
Vol | double | 1.0 | Volume, as a percentage of the authored volume. You can produce audio fades by varying this property value over time.

Remarks

Each object in a timeline can have at most one volume envelope effect. In a composition or a group, the volume envelope is applied first, before any other audio effects, regardless of its priority. In a source or a track, the volume effect is applied according to its priority.


Video Color Source

The Video Color Source creates a continuous video image of a solid color.

Class ID (CLSID): {0CFDD070-581A-11D2-9EE6-006008039E37}

CLSID Variable Name: CLSID_ColorSource

Properties

Property | Type | Default | Description
Color | DWORD | 0 | Specifies the color to generate. See Remarks.

Remarks

The Video Color Source is used with source objects. First, create a new source object. Then set the source object's subobject GUID to CLSID_ColorSource, by calling the IAMTimelineObj::SetSubObjectGUID method.

To set the color, create a Property Setter object and apply the Color property at time zero. The value of this property is a hexadecimal number with the format 0xAARRGGBB, where AA is the alpha value, RR is the red value, GG is the green value, and BB is the blue value. Alpha values range from 0x00 (transparent) to 0xFF (opaque). The property is static and must be applied at time zero.

If you do not specify the alpha value, it defaults to zero (transparent). In a 32-bit-color video project, this will cause transitions or effects that use alpha to render the Video Color Source as completely transparent. To be safe, always specify the alpha. For example, opaque black is 0xFF000000.

The following code example shows how to use this object. For more information about using IPropertySetter, see Setting Properties on Effects and Transitions:

DWORD           dwYellow = 0xFFFF00;
IAMTimelineObj  *pSource = NULL;
IPropertySetter *pProp = NULL;

// Error handling is omitted for simplicity.

hr = pTimeline->CreateEmptyNode(&pSourceObj, TIMELINE_MAJOR_TYPE_SOURCE);
pSource->SetStartStop(0, 50000000);
pSource->SetSubObjectGUID(CLSID_ColorSource);

// Create a property setter.
CoCreateInstance(CLSID_PropertySetter, NULL, CLSCTX_INPROC_SERVER,
    IID_IPropertySetter, (void**) &pProp);

// Set the color.
DEXTER_PARAM param;
DEXTER_VALUE val;

param.Name = SysAllocString(OLESTR("Color"));
param.dispID = 0;
param.nValues = 1;

val.v.vt = VT_I4;
val.v.lVal = dwYellow;
val.rt = 0;  // Time must be zero.
val.dwInterp = DEXTERF_JUMP;

pProp->AddProp(param, &val);
pSource->SetPropertySetter(pProp);

// Clean up.
SysFreeString(param.Name);
VariantClear(&val.v);
pProp->Release();

The following example shows the XML representation of the object created in the previous example. In this case the param element does not support at or linear elements, because the object does not support dynamic properties:

<clip start="0" stop="5" clsid="{0CFDD070-581A-11D2-9EE6-006008039E37}">
    <param name="Color" value="16776960"/>
</clip>


DirectShow Editing Services Objects

Microsoft® DirectShow® Editing Services (DES) includes the following COM components.

Timeline Objects

  • Composition
  • Effect
  • Group
  • Source
  • Timeline
  • Track
  • Transition

Helper Objects

  • Media Detector (MediaDet)
  • Media Locator
  • Property Setter
  • Basic Render Engine
  • Smart Render Engine
  • XML Parser

See Also

  • Transitions and Effects


Composition

The composition object is a container for tracks. It can also hold other compositions (for nesting of tracks), effects, and transitions. To create this object, call the IAMTimeline::CreateEmptyNode method.

The composition object exposes the following interfaces:

  • IAMTimelineComp
  • IAMTimelineEffectable
  • IAMTimelineObj
  • IAMTimelineObj
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack

See Also

  • The Timeline Model
  • Constructing a Timeline


Effect

The effect object produces a video or audio effect. To create this object, call the IAMTimeline::CreateEmptyNode method.

The effect object exposes the following interfaces:

  • IAMTimelineEffect
  • IAMTimelineObj
  • IAMTimelineSplittable
  • IPropertyPage

See Also

  • The Timeline Model
  • Working with Effects and Transitions


Group

The group object represents a top-level composition. Each group defines one video or audio stream in the final project. To create this object, call the IAMTimeline::CreateEmptyNode method.

The group object exposes the following interfaces:

  • IAMTimelineComp
  • IAMTimelineGroup
  • IAMTimelineObj

See Also

  • The Timeline Model
  • Constructing a Timeline


Media Detector (MediaDet)

The Media Detector (MediaDet) object retrieves format information and still frames from file sources. The Media Detector does not require the Filter Graph Manager to function. To create this object, call CoCreateInstance. The class identifier is CLSID_MediaDet.

To read Windows Media™ files, the application must provide a software certificate, also called a key. Register the application as a key provider through the Media Detector's IObjectWithSite interface. For more information, see Unlocking the Windows Media Format SDK.

The MediaDet object exposes the following interfaces:

  • IMediaDet
  • IObjectWithSite

See Also

  • Working with Sources


Media Locator

The Media Locator object locates the files associated with source objects. Use this object to validate sources in the timeline. To create this object, call CoCreateInstance. The class identifier is CLSID_MediaLocator.

The Media Locator object exposes the following interface:

  • IMediaLocator

See Also

  • Working with Sources


Property Setter

The Property Setter object sets IDispatch properties on a timeline object. To create this object, call CoCreateInstance. The class identifier is CLSID_PropertySetter.

The Property Setter object exposes the following interfaces:

  • IAMSetErrorLog
  • IPropertySetter

See Also

  • The Timeline Model
  • Working with Effects and Transitions


Basic Render Engine

The Basic Render Engine object renders uncompressed output from a timeline. To create this object, call CoCreateInstance. For compressed output, use the Smart Render Engine. The class identifier is CLSID_RenderEngine.

The Basic Render Engine exposes the following interfaces:

  • IAMSetErrorLog
  • IObjectWithSite
  • IRenderEngine
  • IRenderEngine2

See Also

  • Rendering a Project
  • Smart Render Engine


Smart Render Engine

The Smart Render Engine object renders compressed output from a timeline. To create this object, call CoCreateInstance. For uncompressed output, use the Basic Render Engine. The class identifier is CLSID_SmartRenderEngine.

The Smart Render Engine exposes the following interfaces:

  • IAMSetErrorLog
  • IObjectWithSite
  • IRenderEngine
  • IRenderEngine2
  • ISmartRenderEngine

See Also

  • Rendering a Project
  • Basic Render Engine


Source

The source object represents a source clip in timeline. To create this object, call the IAMTimeline::CreateEmptyNode method.

The source object exposes the following interfaces:

  • IAMTimelineEffectable
  • IAMTimelineObj
  • IAMTimelineSrc
  • IAMTimelineSplittable

See Also

  • The Timeline Model
  • Working with Sources


Timeline

The timeline object manages all of the objects in a video editing project. To create this object, call CoCreateInstance. The class identifier is CLSID_AMTimeline.

To read Windows Media™ files, the application must provide a software certificate, also called a key. Register the application as a key provider through the timeline's IObjectWithSite interface. For more information, see Unlocking the Windows Media Format SDK.

The timeline object exposes the following interfaces:

  • IAMSetErrorLog
  • IAMTimeline
  • IObjectWithSite
  • IPersistStream

See Also

  • The Timeline Model
  • Constructing a Timeline


Track

The track object contains source objects. To create this object, call the IAMTimeline::CreateEmptyNode method.

The track object exposes the following interfaces:

  • IAMTimelineEffectable
  • IAMTimelineObj
  • IAMTimelineSplittable
  • IAMTimelineTrack
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack

See Also

  • The Timeline Model
  • Constructing a Timeline


Transition

The transition object creates a video transition between tracks or compositions. To create this object, call the IAMTimeline::CreateEmptyNode method.

The transition object exposes the following interfaces:

  • IAMTimelineObj
  • IAMTimelineSplittable
  • IAMTimelineTrans

See Also

  • The Timeline Model
  • Working with Effects and Transitions


XML Parser

The XML Parser object converts between XML project files and timelines. To create this object, call CoCreateInstance.

The XML Parser object exposes the following interface:

  • 6IXml2Dex

Class Identifier: CLSID_Xml2Dex

See Also

  • Loading and Previewing a Project


XTL Reference

Microsoft® DirectShow® Editing Services supports an Extensible Markup Language (XML) persistence format, called XTL. This section documents the XTL elements and attributes.

  • XTL Elements
  • XTL Attributes


XTL Elements

The XTL format defines the following elements.

Element | Description
at | Specifies a time-based setting for a param element.
clip | Specifies a source file.
composite | Defines a composition.
effect | Defines an effect.
group | Defines a group (audio or video).
linear | Specifies a time-based setting for a param element.
param | Specifies the value of a property on a transition, effect, or other subobject.
timeline | Defines the timeline.
track | Defines a track.
transition | Defines a transition.


at Element

The at element defines the value of a param element at a particular time, relative to the start of the transition or effect that contains the parameter. The at element causes the parameter to jump abruptly to the new value at the given time. For a smooth progression to a new value, use the linear element.

Example

<at time="1" value="0.5" />

Attributes

time, value

Parent/Child Information

Parent | param
Children | None

See Also

  • XTL Elements


clip Element

The clip epecifies a media source.

Example

<clip src="sample.avi" start="1:05" stop="1:42.5" mstart="30" />

Attributes

clsid, framerate, lock, mlength, mstart, mstop, mute, src, start, stop, stream, stretchmode, userdata, userid, username

Parent/Child Information

Parent | track
Children | effect

Remarks

The clsid attribute specifies the CLSID of a source filter to use as the source. Do not specify the src and clsid attributes within the same clip element.

Specify at least one start-time attribute (start or mstart) and one stop-time attribute (stop or mstop). If one of the start-time attributes is unspecified, it defaults to 0 (the beginning of the timeline for start, or the beginning of the clip for mstart). If one of the stop-time attributes is unspecified, DES assumes a normal playback rate and calculates the unspecified stop time accordingly. If both stop times are specified, playback is faster or slower than normal, if necessary.

In the following example, the timeline duration is seven seconds (stop minus start). Normal playback rate is assumed, so the media stop time defaults to 10 seconds (the duration plus mstart).

<clip start="2" stop="9" mstart="3" />

In the next example, the media start time defaults to 0, forcing the media duration to be 10 seconds. The timeline duration is five seconds, so the clip plays back at twice the normal rate.

<clip start="5" stop="10" mstop="10" />

If the src attribute specifies a still image, DES attempts to load a series of still images to create an animation. For example, if the src attribute is IMAGE001.BMP, DES looks for IMAGE002.BMP, IMAGE003.BMP, IMAGE004.BMP, and so on. Assuming they exist, they are displayed in sequential numerical order, at the rate specified by the framerate attribute.

See Also

  • XTL Elements


composite Element

The composite element defines a composition, a container object for tracks and other nested compositions.

Example

<composite> </composite>

Attributes

lock, mute, userdata, userid, username

Parent/Child Information

Parent | composite, group
Children | composite, effect, track, transition

Remarks

Within a composite element, the priority of nested layers is determined implicitly by the order in which they appear within the element. The first layer has priority 0, and subsequent layers have increasing priority values.

See Also

  • XTL Elements


effect Element

The effect element defines an audio or video effect object. An effect is applied to a single stream (such as a composition, track, or source).

Example

<effect clsid="{b05a941c-3ce1-11d2-952a-00c04fa34f05}" start="0" stop="32.0" />

Attributes

clsid, lock, mute, start, stop, userdata, userid, username

Parent/Child Information

Parent | composite, group, clip, track
Children | param

Remarks

The clsid attribute specifies the subobject that creates the effect.

See Also

  • XTL Elements


group Element

The group element defines a group, the top-level object in a timeline.

Example

<group type="video" width="640" height="480" framerate="30"> </group>

Attributes

bitdepth, buffering, framerate, height, lock, mute, name, previewmode, samplingrate, type, userdata, userid, username, width

Parent/Child Information

Parent | timeline
Children | composite, effect, track

Remarks

Within a group element, the priority of nested layers is determined implicitly by the order they appear within the element. The first layer has priority 0, and subsequent layers have increasing priority values.

See Also

  • XTL Elements


linear Element

The linear element defines the value of a param element at a particular time, relative to the start of the transition or effect that contains the param element. The linear element causes the parameter to make a smooth transition from its previous value to the new value. For an instantaneous jump to a new value, use the at element.

Example

<linear time="6" value="0.0" />

Attributes

time, value

Parent/Child Information

Parent | param
Children | None

See Also

  • XTL Elements


param Element

The param element specifies the value of a property on a transition, effect, or other subobject.

Example

<param name="progress" value="1.0" />

Attributes

name, value

Parent/Child Information

Parent | clip, effect, transition
Children | at, linear

Remarks

The value attribute specifies the value of the property at the start of the transition or effect. Use the at or linear element to specify changing values. If the param element contains no at or linear elements, the value remains constant over the duration of the effect or transition.

Note A param element inside a clip element cannot contain at or linear elements.

Many transitions support a standard Progress property that ranges from 0 to 1.0, indicating what percentage of the transition is reflected in the output. At Progress = 0.0, the transition is at the beginning of its sequence (entirely the first video image). At Progress = 0.5, the transition is half complete. (For example, in a wipe, at Progress = 0.5 the transition boundary is in the center of the image) At Progress = 1.0, the transition is complete (entirely the second image). By default, transitions go from Progress = 0.0 at the start of the transition to Progress = 1.0 at the end.

Other properties are usually specific to one particular transition or effect. For example, the wipe transition supports a GradientSize property that controls the width of the transition area.

To run a transition backward, set the Progress property to 1.0 at the start of the transition, and use the linear element to change the value to 0.0, as shown in the following example:

<transition clsid="{af279b30-86eb-11d1-81bf-0000f87557db}" start="0" stop="6">
    <param name="progress" value="1.0">
        <linear time="6" value="0.0" />
    </param>
</transition>

See Also

  • XTL Elements


timeline Element

The timeline element defines the timeline. This element is the root node in the XML file.

Example

<timeline> </timeline>

Attributes

defaultfx, defaulttrans, enablefx, enabletrans, framerate

Parent/Child Information

Parent | None. This element must be the root node in the file.
Children | group

See Also

  • XTL Elements


track Element

The track element defines a track object.

Example

<track> </track>

Attributes

lock, mute, userdata, userid, username

Parent/Child Information

Parent | composite, group
Children | clip, effect, transition

See Also

  • XTL Elements


transition Element

The transition element defines a transition object. A transition is a two-input transform that results in a transition from one stream (such as a composite or track) to another.

Example

<transition
    clsid="{2a54c913-07aa-11d2-8d6d-00c04f8ef8e0}"
    start="7"
    stop="10"
/>

Attributes

clsid, cutpoint, cutsonly, lock, mute, start, stop, swapinputs, userdata, userid, username

Parent/Child Information

Parent | composite, track
Children | param

Remarks

The clsid attribute specifies the subobject that creates the transition.

See Also

  • XTL Elements


XTL Attributes

The XTL format defines the following attributes.

  • bitdepth
  • buffering
  • clsid
  • cutpoint
  • cutsonly
  • defaultfx
  • defaulttrans
  • enablefx
  • enabletrans
  • framerate
  • height
  • lock
  • mlength
  • mstart
  • mstop
  • mute
  • name
  • previewmode
  • samplingrate
  • src
  • start
  • stop
  • stream
  • stretchmode
  • swapinputs
  • time
  • type
  • userdata
  • userid
  • username
  • value
  • width


bitdepth Attribute

The bitdepth attribute specifies the bit depth of the output video, in bits per pixel.

Possible Values

Must be 16, 24, or 32. The default value is 16.

Applies To

group

Remarks

Set this attribute only if the type attribute is video.

See Also

  • XTL Attributes


buffering Attribute

The buffering attribute specifies the number of frames to render in advance during preview.

Possible Values

The value must be a number greater than 1. The default value is 30.

Applies To

group

See Also

  • XTL Attributes
  • IAMTimelineGroup::SetOutputBuffering


clsid Attribute

The clsid attribute specifies a class identifier (CLSID) for an object.

Possible Values

Must be a string with the format {00000000-0000-0000-0000-000000000000}

Applies To

at, effect, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetSubObjectGUID


cutpoint Attribute

The cutpoint attribute specifies when a transition cuts from one source to the next, if the transition is rendered as a cut. The value is relative to the start of the transition.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

transition

See Also

  • XTL Attributes
  • IAMTimelineTrans::SetCutPoint


cutsonly Attribute

The cutsonly attribute specifies whether a transition is rendered as a cut. If the value is TRUE, the transition is an instantaneous cut. Otherwise, the transition is rendered normally. The default value is FALSE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

transition

See Also

  • XTL Attributes
  • IAMTimelineTrans::SetCutPoint


defaultfx Attribute

The defaultfx attribute specifies the class identifier (CLSID) of a default effect for the timeline.

Possible Values

Must be a string with the format {00000000-0000-0000-0000-000000000000}

Applies To

timeline

See Also

  • XTL Attributes
  • IAMTimeline::SetDefaultEffect


defaulttrans Attribute

The defaulttrans attribute specifies the class identifier (CLSID) of a default transition for the timeline.

Possible Values

Must be a string with the format {00000000-0000-0000-0000-000000000000}

Applies To

timeline

See Also

  • XTL Attributes
  • IAMTimeline::SetDefaultTransition


enablefx Attribute

The enablefx attribute specifies whether effects are enabled. If the value is TRUE, the rendering engine renders effects. Otherwise, it does not. The default value is TRUE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

timeline

See Also

  • XTL Attributes
  • IAMTimeline::EnableEffects


enabletrans Attribute

The enabletrans attribute specifies whether transitions are enabled. If the value is TRUE, the rendering engine fully renders transitions. Otherwise, it renders them as cuts. The default value is TRUE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

timeline

See Also

  • XTL Attributes
  • IAMTimeline::EnableTransitions


framerate Attribute

The framerate attribute specifies a framerate, in frames per second.

Possible Values

Floating-point value. The value must include the leading zero before the decimal place. For example, 0.3, not .3. Do not use more than seven decimal digits.

Applies To

clip, group, timeline

Remarks

For the clip element, this attribute specifies the default frame rate of the source. Specify the attribute for still images and DIB sequences. For a still image, set the value to zero. For a DIB sequence, use a nonzero value. The default value is zero.

For the group element, this attribute specifies the output frame rate for the group.

For the timeline element, this attribute specifies the default frame rate for all groups.

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetDefaultFPS
  • IAMTimelineGroup::SetOutputFPS
  • IAMTimeline::SetDefaultFPS


height Attribute

The height attribute specifies the height of the output video, in pixels.

Possible Values

Floating-point value. The value must include the leading zero before the decimal place. For example, 0.3, not .3. Do not use more than seven decimal digits.

Applies To

group

Remarks

Set this attribute only if the type attribute is video.

See Also

  • XTL Attributes


lock Attribute

The lock attribute specifies whether an object should be edited. If the value is TRUE, the application should treat the object as locked, and disallow changes to that object or its children. The default value is FALSE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

clip, composite, effect, group, timeline, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetLocked


mlength Attribute

The mlength attribute specifies the duration of a source file. This value must be the actual duration, or rendering errors may occur.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetMediaLength


mstart Attribute

The mstart attribute specifies the start time of a clip, relative to the original media file.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetMediaTimes


mstop Attribute

The mstop attribute specifies the stop time of a clip, relative to the original media file.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetMediaTimes


mute Attribute

The mute attribute specifies the object's mute state. If the value is TRUE, neither the object nor its children are rendered. If the value is FALSE, the object is rendered, and its children are rendered according to their own mute state. The default value is FALSE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

clip, composite, effect, group, timeline, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetMuted


name Attribute

The name attribute specifies the name of an object.

Possible Values

Can be any value.

Applies To

group, param

Remarks

For the group element, this attribute specifies an application-defined name for the group.

For the param element, this attribute specifies the name of the property.

See Also

  • XTL Attributes
  • IAMTimelineGroup::SetGroupName


previewmode Attribute

The previewmode attribute specifies the preview mode for the group. If the value is TRUE, frames might be dropped during preview. Otherwise, no frames are dropped during preview. The default value is TRUE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

group

Remarks

Under the default setting, frames are dropped while previewing slow effects or transitions, to keep the video synchronized with the audio. The video might look choppy as a result. Setting this attribute to FALSE forces every frame to render during preview, possibly resulting in the video becoming out of sync with the audio. Frames are never dropped when writing to a file.

See Also

  • XTL Attributes
  • IAMTimelineGroup::SetPreviewMode


samplingrate Attribute

The samplingrate attribute specifies the sampling rate of the output audio, in Hz.

Possible Values

The value must be 8000, 11025, 22050, 32000, 44100, or 48000. The default value is 44100.

Applies To

group

Remarks

Set this attribute only if the type attribute is audio.

See Also

  • XTL Attributes


src Attribute

The src attribute specifies the path name of a media file. The file can be any type supported by DirectShow, or a still image. The supported formats for still images are bitmap, device-independent bitmap, GIF, and JPEG.

Possible Values

Must be a string that specifies a path name.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetMediaName


start Attribute

The start attribute specifies the start time of an object, relative to the parent object.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

clip, effect, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetStartStop


stop Attribute

The stop attribute specifies the stop time of an object, relative to the parent object.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

clip, effect, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetStartStop


stream Attribute

The stream attribute specifies which stream to use in a multi-stream source file.

Possible Values

Must be an integer value.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetStreamNumber


stretchmode Attribute

The stretchmode attribute specifies how to stretch an image that does not match the output dimensions.

Possible Values

Must have one of the following values.

  • stretch: The image is stretched to fit the output frame size without preserving aspect ratio. (Default)
  • crop: The image is cropped to fit the output frame size.
  • preserveaspectratio: The original aspect ratio is preserved, with a black letterbox along the shorter dimension.
  • preserveaspectrationoletterbox: The image is resized to fill the entire target frame while preserving the aspect ratio.

Applies To

clip

See Also

  • XTL Attributes
  • IAMTimelineSrc::SetStretchMode


swapinputs Attribute

The swapinputs attribute specifies whether to swap transition inputs. If the value is TRUE, the inputs are swapped. The default value is FALSE.

Possible Values

The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

Applies To

transition

Remarks

By default, a transition proceeds from the composite of all lower-priority layers to the layer on which the transition resides. If the swapinputs attribute is 1, this direction is reversed. For more information about the layering model used by DES, see The Timeline Model.

See Also

  • XTL Attributes
  • IAMTimelineTrans::SetSwapInputs


time Attribute

The time attribute specifies the time at which a parameter assumes a new value, relative to the start of the transition or effect.

Possible Values

Must be a string with the format hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.

Applies To

at, linear

See Also

  • XTL Attributes


type Attribute

The type attribute specifies the media type of a group.

Possible Values

The value must be audio or video.

Applies To

group

See Also

  • XTL Attributes
  • IAMTimelineGroup::SetMediaType


userdata Attribute

The userdata attribute specifies application-defined persistent data for an object.

Possible Values

The value must be a hexedecimal number with an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC.

Applies To

clip, composite, effect, group, timeline, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetUserData


userid Attribute

The userid attribute specifies an application-defined identifier for an object..

Possible Values

The value must be an integer.

Applies To

clip, composite, effect, group, timeline, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetUserID


username Attribute

The userid attribute specifies an application-defined name for an object..

Possible Values

Can be any value.

Applies To

clip, composite, effect, group, timeline, transition

See Also

  • XTL Attributes
  • IAMTimelineObj::SetUserName


value Attribute

The value attribute specifies the value of a parameter.

Possible Values

The possible values depend on the parameter.

Applies To

at, linear, param

See Also

  • XTL Attributes


width Attribute

The width attribute specifies the width of the output video, in pixels.

Possible Values

Floating-point value. The value must include the leading zero before the decimal place. For example, 0.3, not .3. Do not use more than seven decimal digits.

Applies To

group

Remarks

Set this attribute only if the type attribute is video.

See Also

  • XTL Attributes


Rendering Errors

Microsoft® DirectShow® Editing Services (DES) defines various error codes used to log rendering errors. If a project does not render correctly, the render engine calls the IAMErrorLog::LogError method. The following table summarizes the parameters given to LogError:

  • The error code is contained in the ErrorCode parameter
  • The description is contained in the ErrorString parameter.
  • The extra information, if any, is contained in the VARIANT pointed to by pExtraInfo.
  • If there is extra information, the VARIANT type is contained in the vt member of the VARIANT pointed to by pExtraInfo.

Note The error codes described here are not HRESULT values. For a list of HRESULT return values specific to DES, see Error and Success Codes.

Error code | Description | Extra information | Variant type
DEX_IDS_BAD_SOURCE_NAME | File name doesn't exist, or DirectShow doesn't recognize the file extension. | File name | BSTR
DEX_IDS_BAD_SOURCE_NAME2 | File type does not match the file extension or the file is corrupt. | File name | BSTR
DEX_IDS_MISSING_SOURCE_NAME | File name was required, but wasn't given. | None | Not applicable
DEX_IDS_UNKNOWN_SOURCE | Cannot parse data source provided by this source. | None | Not applicable
DEX_IDS_INSTALL_PROBLEM | Unexpected error. Some DirectShow component is not installed properly. | None | Not applicable
DEX_IDS_NO_SOURCE_NAMES | Source filter does not accept file names. | None | Not applicable
DEX_IDS_BAD_MEDIATYPE | Group's media type is not supported. | Group number | int
DEX_IDS_STREAM_NUMBER | Invalid stream number for this source. | Stream number | int
DEX_IDS_OUTOFMEMORY | Out of memory. | None | Not applicable
DEX_IDS_DIBSEQ_NOTALLSAME | One bitmap in the sequence was not the same type as the others. | Bitmap name | BSTR
DEX_IDS_CLIPTOOSHORT | Clip's media times are invalid, or the device-independent bitmap (DIB) sequence is too short. Note If other rendering errors occur, this error might occur even though the media times are valid. | None | Not applicable
DEX_IDS_INVALID_DXT | Class identifier (CLSID) of the effect or transition is not valid. | CLSID | BSTR
DEX_IDS_INVALID_DEFAULT_DXT | The CLSID of the default effect or transition is not valid. | CLSID | BSTR
DEX_IDS_NO_3D | Your version of DirectX does not support three-dimensional transitions. | CLSID | BSTR
DEX_IDS_BROKEN_DXT | This effect is not the right kind, or is broken. | CLSID | BSTR
DEX_IDS_NO_SUCH_PROPERTY | No such property exists on the object. | Property name | BSTR
DEX_IDS_ILLEGAL_PROPERTY_VAL | Illegal value for this property. | Value specified | VARIANT
DEX_IDS_INVALID_XML | Syntax rrr in XML file. | Line number | VT_I4 (4-byte integer)
DEX_IDS_CANT_FIND_FILTER | Cannot find filter specified in XML by category and instance. | Friendly name (instance) | BSTR
DEX_IDS_DISK_WRITE_ERROR | Error writing XML file to disk. | None | Not applicable
DEX_IDS_INVALID_AUDIO_FX | CLSID not a valid DirectShow audio effect filter. | CLSID | BSTR
DEX_IDS_CANT_FIND_COMPRESSOR | Cannot find a compressor to produce the specified compression format. | None | Not applicable

The following errors should never occur. If you encounter one of these errors, please send a bug report to Microsoft.

Error code | Description
DEX_IDS_TIMELINE_PARSE | Unexpected error parsing the timeline.
DEX_IDS_GRAPH_ERROR | Unexpected error building the filter graph.
DEX_IDS_GRID_ERROR | Unexpected error with the internal grid.
DEX_IDS_INTERFACE_ERROR | Unexpected error getting an interface.


DirectShow Editing Services Visual Basic Reference

This section contains reference material for using DirectShow Editing Services in Visual Basic.

  • Objects

See Also

  • DirectShow Editing Services
  • Transitions and Effects
  • XTL Reference
  • Rendering Errors


Objects

DirectShow Editing Services (DES) supports the following objects for video editing:

  • AMTimeline
  • AMTimelineComp
  • AMTimelineEffect
  • AMTimelineGroup
  • AMTimelineObj
  • AMTimelineSrc
  • AMTimelineTrack
  • AMTimelineTrans
  • IAMTimelineEffectable
  • IAMTimelineSplittable
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack
  • MediaDet
  • MediaLocator
  • RenderEngine
  • Xml2Dex


AMTimeline Object

The AMTimeline object provides methods for manipulating the timeline, the central object in DirectShow Editing Services (DES). A timeline is a collection of time-ordered elements, such as video clips, audio clips, effects, and transitions between clips. The render engine uses the timeline to create a filter graph, from which the application can generate the rendered output.

The AMTimeline object performs three basic services:

  • Creates the objects in the timeline.
  • Acts as a container for those objects.
  • Sets and retrieves general parameters of the timeline.

This object has the following methods.

Method | Description
AddGroup | Adds a group to the timeline.
ClearAllGroups | Removes all groups from the timeline, along with all objects contained in those groups.
CreateEmptyNode | Creates a new timeline object.
EffectsEnabled | Determines whether effects are enabled.
EnableEffects | Enables or disables all effects in the timeline.
EnableTransitions | Enables or disables all transitions in the timeline.
GetCountOfType | Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.
GetDefaultEffect | Not supported for Visual Basic.
GetDefaultEffectB | Retrieves the default effect.
GetDefaultFPS | Retrieves the default output frame rate, in frames per second.
GetDefaultTransition | Not supported for Visual Basic.
GetDefaultTransitionB | Retrieves the default transition.
GetDirtyRange | Not supported for Visual Basic.
GetDuration | Not supported for Visual Basic.
GetDuration2 | Retrieves the duration of the timeline.
GetGroup | Retrieves a specified group.
GetGroupCount | Retrieves the number of groups that are contained in the timeline.
GetInsertMode | Not supported for Visual Basic.
IsDirty | Not supported for Visual Basic.
RemGroupFromList | Not supported for Visual Basic.
SetDefaultEffect | Not supported for Visual Basic.
SetDefaultEffectB | Sets the default effect.
SetDefaultFPS | Sets the default output frame rate, in frames per second.
SetDefaultTransition | Not supported for Visual Basic.
SetDefaultTransitionB | Sets the default transition.
SetInsertMode | Not supported for Visual Basic.
SetInterestRange | Not supported for Visual Basic.
TransitionsEnabled | Determines whether transitions are enabled.
ValidateSourceNames | Validates source names in the timeline.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimeline.AddGroup Method

The AddGroup method adds a group to the timeline.

Syntax

object.AddGroup(
    pGroup As AMTimelineObj
)

Parameters

pGroup

AMTimelineObj object that specifies the group.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Maximum number of groups exceeded.
E_NOINTERFACE | The object is not a group.

Remarks

Currently, timelines support a maximum of 32 groups.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.ClearAllGroups Method

The ClearAllGroups method removes all groups from the timeline, along with all objects contained in those groups.

Syntax

object.ClearAllGroups()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.CreateEmptyNode Method

The CreateEmptyNode method creates a new timeline object.

Use this method to create timeline objects, rather than the New keyword, because this method performs important initialization routines.

Syntax

object.CreateEmptyNode(
    ppObj As AMTimelineObj,
    Type As TIMELINE_MAJOR_TYPE
)

Parameters

ppObj

AMTimelineObj object that receives the new object.

Type

Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies the type of object to create.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Object type is not valid.
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.EffectsEnabled Method

The EffectsEnabled method determines whether effects are enabled. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

object.EffectsEnabled(
    pfEnabled As Long
)

Parameters

pfEnabled

Variable that receives a value indicating whether effects are enabled. If the value is zero, effects are disabled. If the value is non-zero, effects are enabled.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.EnableEffects Method

The EnableEffects method enables or disables all effects in the timeline. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

object.EnableEffects(
    fEnabled As Long
)

Parameters

fEnabled

Value that specifies whether to enable or disable effects. If zero, effects are disabled. If non-zero, effects are enabled.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.EnableTransitions Method

The EnableTransitions method enables or disables all transitions in the timeline. If transitions are disabled, the render engine treats them as cuts; that is, the rendered output jumps instantly from one track to the next. The default cut point is halfway through the duration of the transition. You can change the cut point by calling the AMTimelineTrans.SetCutPoint method on the transition. Disabled transitions remain in the timeline.

Syntax

object.EnableTransitions(
    fEnabled As Long
)

Parameters

fEnabled

Value that specifies whether to enable or disable transitions. If zero, transitions are disabled. If non-zero, transitions are enabled.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetCountOfType Method

The GetCountOfType method retrieves the number of objects of the specified type that are contained in a specified group and all of its children.

Syntax

object.GetCountOfType(
    Group As Long,
    pVal As Long,
    pValWithComps As Long,
    MajorType As TIMELINE_MAJOR_TYPE
)

Parameters

Group

Index number of the group for which to retrieve the count.

pVal

Variable that receives the number of objects of the specified type contained in the group and all of its virtual tracks, recursively.

pValWithComps

Variable that receives the count returned in pVal plus the number of compositions searched, including this one.

MajorType

Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | Invalid group number.

Remarks

Calling this method is equivalent to calling AMTimelineComp.GetCountOfType on the specified group. See the Remarks section of that method for more information.

Typically, an application will not call this method. It is called internally by the render engine.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetDefaultEffect Method

The GetDefaultEffect method is not supported for Visual Basic.

Syntax

object.GetDefaultEffect(
    pGuid As GUID
)

See Also

  • AMTimeline Object


AMTimeline.GetDefaultEffectB Method

The GetDefaultEffectB method retrieves the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

object.GetDefaultEffectB() As String

Parameters

This method takes no parameters.

Return Value

Returns a string that contains the GUID of the default effect.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetDefaultFPS Method

The AMTimeline.GetDefaultFPS method retrieves the default output frame rate, in frames per second (FPS). Groups use this value as their default frame rate. To set a group's frame rate, call the AMTimelineGroup.SetOutputFPS method on the group.

Syntax

object.GetDefaultFPS(
    pFPS As Double
)

Parameters

pFPS

Variable that receives the default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetDefaultTransition Method

The GetDefaultTransition method is not supported for Visual Basic.

Syntax

object.GetDefaultTransition(
    pGuid As GUID
)

See Also

  • AMTimeline Object


AMTimeline.GetDefaultTransitionB Method

The GetDefaultTransitionB method retrieves the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

object.GetDefaultTransitionB() As String

Parameters

This method takes no parameters.

Return Value

Returns a string that contains the GUID of the default transition.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetDirtyRange Method

The AMTimeline.GetDirtyRange method not supported for Visual Basic.

Syntax

object.GetDirtyRange(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimeline Object


AMTimeline.GetDuration Method

The GetDuration method not supported for Visual Basic.

Syntax

object.GetDuration(
    pDuration As <Unsupported variant type>
)

See Also

  • AMTimeline Object


AMTimeline.GetDuration2 Method

The GetDuration2 method retrieves the duration of the timeline.

Syntax

object.GetDuration2(
    pDuration As Double
)

Parameters

pDuration

Variable that receives the duration of the timeline, in seconds.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetGroup Method

The GetGroup method retrieves a specified group.

Syntax

object.GetGroup(
    ppGroup As AMTimelineObj,
    WhichGroup As Long
)

Parameters

ppGroup

AMTimelineObj object that receives the specified group.

WhichGroup

Index of the group to retrieve, based on the order in which the groups were added to the timeline. The first group added to the timeline has an index of 0.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetGroupCount Method

The GetGroupCount method retrieves the number of groups that are contained in the timeline.

Syntax

object.GetGroupCount(
    pCount As Long
)

Parameters

pCount

Variable that receives the number of groups in the timeline.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.GetInsertMode Method

The GetInsertMode method not supported for Visual Basic.

Syntax

object.GetInsertMode(
    pMode As Long
)

See Also

  • AMTimeline Object


AMTimeline.IsDirty Method

The IsDirty method is not supported for Visual Basic.

Syntax

object.IsDirty(
    pDirty As Long
);

See Also

  • AMTimeline Object


AMTimeline.RemGroupFromList Method

The RemGroupFromList method is not supported for Visual Basic.

Syntax

object.RemGroupFromList(
    pGroup As AMTimelineObj
);

See Also

  • AMTimeline Object


AMTimeline.SetDefaultEffect Method

The SetDefaultEffect method is not supported for Visual Basic.

Syntax

object.SetDefaultEffect(
    pGuid As GUID
)

See Also

  • AMTimeline Object


AMTimeline.SetDefaultEffectB Method

The SetDefaultEffectB method sets the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

object.SetDefaultEffectB(
    pGuid As String
)

Parameters

pGuid

String that contains the GUID of the default effect.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you do not set a default effect, or if the effect that you specify as a default causes an error, DES uses its own default effect.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.SetDefaultFPS Method

The SetDefaultFPS method sets the default output frame rate, in frames per second. Groups use this value as their default frame rate. To set a group's frame rate, call the AMTimelineGroup.SetOutputFPS method on the group.

Syntax

object.SetDefaultFPS(
    FPS As Double
)

Parameters

FPS

Default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.SetDefaultTransition Method

The AMTimeline.SetDefaultTransition method not supported for Visual Basic.

Syntax

object.SetDefaultTransition(
    pGuid As GUID
)

See Also

  • AMTimeline Object


AMTimeline.SetDefaultTransitionB Method

The SetDefaultTransitionB method sets the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

object.SetDefaultTransitionB(
    pGuid As String
)

Parameters

pGuid

String that contains the GUID of the default transition.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you do not set a default transition, or if the transition that you specify as a default causes an error, DES uses its own default transition.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimeline.SetInsertMode Method

The SetInsertMode method not supported for Visual Basic.

Syntax

object.SetInsertMode(
    Mode As Long
)

See Also

  • AMTimeline Object


AMTimeline.SetInterestRange Method

The AMTimeline.SetInterestRange method is not supported for Visual Basic.

Syntax

object.SetInterestRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • AMTimeline Object


AMTimeline.TransitionsEnabled Method

The TransitionsEnabled method ascertains whether transitions are enabled.

Syntax

object.TransitionsEnabled(
    pfEnabled As Long
)

Parameters

pfEnabled

Value that specifies whether transitions are enabled. If zero, transitions are disabled. If non-zero, transitions are enabled.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimeline Object
  • AMTimeline.EnableTransitions
  • Error and Success Codes


AMTimeline.ValidateSourceNames Method

The ValidateSourceNames method validates source names in the timeline, using the media locator. Optionally, this method also updates any source object for which it locates a file.

Syntax

object.ValidateSourceNames(
    ValidateFlags As Long,
    pOverride As MediaLocator,
    NotifyEventHandle As LONG_PTR
)

Parameters

ValidateFlags

Bitwise combination of flags specifying the behavior of the media locator. See File Name Validation Flags for possible values. The SFN_VALIDATEF_REPLACE and SFN_VALIDATEF_CHECK flags must be present, or the method returns E_INVALIDARG.

pOverride

Optional MediaLocator object to use in place of the default. To use the default media locator, set the value of this parameter to Nothing.

NotifyEventHandle

Variable of type LONG_PTR. This parameter is ignored and can be zero.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • AMTimeline Object
  • Error and Success Codes


AMTimelineComp Object

Inserts or retrieves virtual tracks on a composition in DirectShow Editing Services (DES).

A composition is a collection of layers that acts as a composited track. For example, a composition that contains two tracks with a transition between them acts as a single track with the transition precomposited. A composition should contain media of only one type (such as audio or video), but this limitation is not enforced. A virtual track is any object that can reside in a composition, including tracks and other compositions.

The topmost nodes in the timeline are groups. Groups support both AMTimelineComp and AMTimelineGroup.

For more information, see The Timeline Model.

This object has the following methods.

Method | Description
GetCountOfType | Retrieves the number of objects of a given type contained in this composition and all of its virtual tracks, recursively.
GetNextVTrack | Retrieves the next virtual track after a specified virtual track.
GetRecursiveLayerOfType | Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.
GetRecursiveLayerOfTypeI | Not supported for Visual Basic.
GetVTrack | Retrieves the virtual track at the specified priority.
VTrackGetCount | Retrieves the number of virtual tracks contained in the composition.
VTrackInsBefore | Inserts a virtual track into the composition at the specified priority.
VTrackSwapPriorities | Switches the priority levels of two tracks.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineComp.GetCountOfType Method

The GetCountOfType method retrieves the number of objects of a given type contained in this composition and all its virtual tracks, recursively.

Syntax

object.GetCountOfType(
    pVal As Long,
    pValWithComps As Long,
    MajorType As TIMELINE_MAJOR_TYPE
)

Parameters

pVal

Variable that receives the number of objects of the specified type contained in this composition and all its virtual tracks, recursively.

pValWithComps

Variable that receives the count returned in pVal plus the number of compositions searched, including this one.

MajorType

Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Error Codes

If the method fails, an error is raised.

Remarks

Typically, an application will not call this method. It is called by the render engine.

If you count compositions, the value returned in pVal is zero and the value returned in pValWithComps is the number of compositions. The value of pValWithComps includes the composition on which you call the method. For example, if you call this method on an empty composition, pValWithComps equals 1.

Groups cannot reside inside compositions, so you cannot use this method to count groups (the returned count will always be zero). To count groups, call the AMTimeline.GetGroupCount method.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.GetNextVTrack Method

The GetNextVTrack method retrieves the next virtual track after a specified virtual track.

Syntax

object.GetNextVTrack(
    pVirtualTrack As AMTimelineObj,
    ppNextVirtualTrack As AMTimelineObj
)

Parameters

pVirtualTrack

AMTimelineObj object that specifies the previous virtual track, or Nothing to retrieve the first virtual track in the composition.

ppNextVirtualTrack

AMTimelineObj object that receives the next virtual track, in order of priority.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.GetRecursiveLayerOfType Method

The GetRecursiveLayerOfType method performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.

Syntax

object.GetRecursiveLayerOfType(
    ppVirtualTrack As AMTimelineObj,
    WhichLayer As Long,
    Type As TIMELINE_MAJOR_TYPE
)

Parameters

ppVirtualTrack

AMTimelineObj object that receives the virtual track.

WhichLayer

Value that specifies which virtual track to retrieve, indexed from zero.

Type

Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies whether to include tracks in the search.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | No object of the specified type.

Remarks

Typically, an application will not need to call this method.

If the Type parameter is TIMELINE_MAJOR_TYPE_TRACK, the depth-first ordering includes tracks. If not, it includes only compositions and groups. The object itself is included in the ordering.

For example, in the following arrangement, starting from Composition A, the ordering would be B, C, F, D, E, A.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.GetRecursiveLayerOfTypeI Method

The GetRecursiveLayerOfTypeI method is not supported for Visual Basic. Use the GetRecursiveLayerOfType method instead.

Syntax

object.GetRecursiveLayerOfTypeI(
    ppVirtualTrack As AMTimelineObj,
    pWhichLayer As Long,
    Type As TIMELINE_MAJOR_TYPE
)

See Also

  • AMTimelineComp Object


AMTimelineComp.GetVTrack Method

The GetVTrack method retrieves the virtual track at the specified priority.

Syntax

object.GetVTrack(
    ppVirtualTrack As AMTimelineObj,
    Which As Long
)

Parameters

ppVirtualTrack

AMTimelineObj object that receives the virtual track.

Which

Priority of the virtual track to retrieve.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | No virtual track with the specified priority.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.VTrackGetCount Method

The VTrackGetCount method retrieves the number of virtual tracks contained in the composition.

Syntax

object.VTrackGetCount(
    pVal As Long
)

Parameters

pVal

Variable that receives the number of virtual tracks.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.VTrackInsBefore Method

The VTrackInsBefore method inserts a virtual track into the composition at the specified priority.

Syntax

object.VTrackInsBefore(
    pVirtualTrack As AMTimelineObj,
    Priority As Long
)

Parameters

pVirtualTrack

AMTimelineObj object that specifies the virtual track.

Priority

Priority at which to insert the virtual track, or –1 to insert the virtual track at the end of the priority list.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pVirtualTrack is not a virtual track.

Remarks

Priority levels start at zero. If the timeline already contains a virtual track at the specified priority level, everything from that point on moves down the priority list to make room for the inserted track. This method fails if the specified priority is greater than the current number of tracks.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineComp.VTrackSwapPriorities Method

The VTrackSwapPriorities method switches the priority levels of two tracks.

Given two priority levels, this method switches the virtual tracks at those priorities. When the method returns, the track that was at the first priority level is now at the second priority level, and vice versa.

Syntax

object.VTrackSwapPriorities(
    VirtualTrackA As Long,
    VirtualTrackB As Long
)

Parameters

VirtualTrackA

First priority level at which to swap virtual tracks.

VirtualTrackB

Second priority level at which to swap virtual tracks.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • AMTimelineComp Object
  • Error and Success Codes


AMTimelineEffect Object

Provides methods for manipulating effects in DirectShow Editing Services (DES).

The AMTimelineEffect object is a wrapper object for any type of one-input effect that DES supports. To specify which effect to use, call the AMTimelineObj.SetSubObjectGUID method on the effect.

The object has the following method.

Method | Description
EffectGetPriority | Retrieves the effect's priority level.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineEffect.EffectGetPriority Method

The EffectGetPriority method retrieves the effect's priority level. For each timeline object with effects, the render engine applies that object's effects in the order of their priority, starting with priority level zero.

Syntax

object.EffectGetPriority(
    pVal As Long
)

Parameters

pVal

Variable that receives the priority level.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineEffect Object
  • Error and Success Codes


IAMTimelineEffectable Object

Provides methods for adding effects to a timeline object in DirectShow Editing Services (DES), and for manipulating the effects on an object. Applies to timeline objects that can have effects applied to them, such as sources, tracks, and compositions.

The object has the following methods.

Method | Description
EffectGetCount | Retrieves the number of effects applied to this object.
EffectInsBefore | Inserts an effect into the object at the specified priority level.
EffectSwapPriorities | Switches the priority levels of two effects.
GetEffect | Retrieves the effect at the specified priority level.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


IAMTimelineEffectable.EffectGetCount Method

The EffectGetCount method retrieves the number of effects applied to this object.

Syntax

object.EffectGetCount(
    pCount As Long
)

Parameters

pCount

Variable that receives the number of effects.

Error Codes

If the method fails, an error is raised.

See Also

  • IAMTimelineEffectable Object
  • Error and Success Codes


IAMTimelineEffectable.EffectInsBefore Method

The EffectInsBefore method inserts an effect into the object at the specified priority level.

Syntax

object.EffectInsBefore(
    pFX As AMTimelineObj,
    Priority As Long
)

Parameters

pFX

The AMTimelineObj object that specifies the effect.

Priority

Priority level at which to insert the effect. Use the value –1 to insert the effect at the end of the priority list.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_NOTIMPL | The object specified by pFX is not an effect.

Remarks

The start and stop times of the effect are clipped within the bounds of the object's time range, if necessary.

If there is already an effect at the specified priority level, all the effects from that point on move down the priority list to make room for the new effect.

See Also

  • IAMTimelineEffectable Object
  • Error and Success Codes


IAMTimelineEffectable.EffectSwapPriorities Method

The EffectSwapPriorities method switches the priority levels of two effects.

Given two priority values, this method swaps the effects at those priorities. When the method returns, the effect that was at the first priority level is at the second priority level, and vice versa.

Syntax

object.EffectSwapPriorities(
    PriorityA As Long,
    PriorityB As Long
)

Parameters

PriorityA

First priority level at which to swap effects.

PriorityB

Second priority level at which to swap effects.

Error Codes

If the method fails, an error is raised, and Err.Number can be set the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • IAMTimelineEffectable Object
  • Error and Success Codes


IAMTimelineEffectable.GetEffect Method

The GetEffect method retrieves the effect at the specified priority level.

Syntax

object.GetEffect(
    ppFx As AMTimelineObj,
    Which As Long
)

Parameters

ppFX

The AMTimelineObj object that receives the effect.

Which

Priority level of the effect to retrieve.

Error Codes

If the method fails, an error is raised.

See Also

  • IAMTimelineEffectable Object
  • Error and Success Codes


AMTimelineGroup Object

Sets and retrieves properties on groups in DirectShow Editing Services (DES).

A group contains one or more tracks, and possibly one or more compositions, which in turn contain source clips of a uniform type, such as video or audio. Groups are the topmost compositions in a timeline, and also support the AMTimelineComp object. A timeline can contain multiple groups.

Each group has the following attributes:

  • An associated media type.
  • The frame rate at which the group renders, in frames per second (FPS). All edits occur at a time rounded to the nearest frame boundary, as defined by the group's FPS setting.
  • A priority level, for writing files with multiple streams of the same media type (for example, a two-video-stream AVI file).

This object has the following methods.

Method | Description
ClearRecompressFormatDirty | Not supported for Visual Basic.
GetGroupName | Retrieves the application-defined name of the group.
GetMediaType | Not supported for Visual Basic.
GetOutputBuffering | Retrieves the number of frames rendered in advance during preview.
GetOutputFPS | Retrieves the output frame rate of this group.
GetPreviewMode | Retrieves the preview mode for the group.
GetPriority | Retrieves the group's priority.
GetSmartRecompressFormat | Not supported for Visual Basic.
GetTimeline | Retrieves the timeline to which this group belongs.
IsRecompressFormatDirty | Not supported for Visual Basic.
IsSmartRecompressFormatSet | Not supported for Visual Basic.
SetGroupName | Sets the application-defined name of the group.
SetMediaType | Not supported for Visual Basic.
SetMediaTypeForVB | Specifies the media type for the group.
SetOutputBuffering | Specifies the number of frames rendered in advance during preview.
SetOutputFPS | Sets the uncompressed output frame rate for this group.
SetPreviewMode | Sets the preview mode for the group.
SetRecompFormatFromSource | Sets the video recompression format using the compression format from a source file.
SetSmartRecompressFormat | Not supported for Visual Basic.
SetTimeline | Not supported for Visual Basic.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineGroup.ClearRecompressFormatDirty Method

The ClearRecompressFormatDirty method is not supported for Visual Basic.

Syntax

object.ClearRecompressFormatDirty()

See Also

  • AMTimelineGroup Object


AMTimelineGroup.GetGroupName Method

The GetGroupName method retrieves the application-defined name of the group.

Syntax

object.GetGroupName() As String

Parameters

This method takes no parameters.

Return Value

Returns the application-defined name of the group.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.GetMediaType Method

The AMTimelineGroup.GetMediaType method not supported for Visual Basic.

Syntax

object.GetMediaType(
    pmt As _AMMediaType
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.GetOutputBuffering Method

The GetOutputBuffering method retrieves the number of frames rendered in advance during preview.

Syntax

object.GetOutputBuffering(
    pnBuffer As Long
)

Parameters

pnBuffer

Variable that receives the number of buffered frames.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.GetOutputFPS Method

The GetOutputFPS method retrieves the output frame rate of this group.

Syntax

object.GetOutputFPS(
    pFPS As Double
)

Parameters

pFPS

Variable that receives the output frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.GetPreviewMode Method

The GetPreviewMode method retrieves the preview mode for the group.

Syntax

object.GetPreviewMode(
    pfPreview As Long
)

Parameters

pfPreview

Variable that receives a value indicating the preview mode. If zero, the group is in authoring mode. If non-zero, the group is in preview mode.

Error Codes

If the method fails, an error is raised.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might become out of sync with the audio.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.GetPriority Method

The GetPriority method retrieves the group's priority.

Syntax

object.GetPriority(
    pPriority As Long
)

Parameters

pPriority

Variable that receives the group's priority.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.GetSmartRecompressFormat Method

The GetSmartRecompressFormat method is not supported for Visual Basic.

Syntax

object.GetSmartRecompressFormat(
   ppFormat As Long
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.GetTimeline Method

The AMTimelineGroup.GetTimeline method retrieves the timeline to which this group belongs.

Syntax

object.GetTimeline(
    ppTimeline As AMTimeline
)

Parameters

ppTimeline

AMTimeline object that receives the timeline. If the group is not part of a timeline, the object is set to Nothing.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.IsRecompressFormatDirty Method

The IsRecompressFormatDirty method is not supported for Visual Basic.

Syntax

object.IsRecompressFormatDirty(
    pVal As Long
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.IsSmartRecompressFormatSet Method

The IsSmartRecompressFormatSet method is not supported for Visual Basic.

Syntax

object.IsSmartRecompressFormatSet(
    pVal As Long
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.SetGroupName Method

The SetGroupName method sets the application-defined name of the group.

Syntax

object.SetGroupName(
    pGroupName As String
)

Parameters

pGroupName

Name of the group.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetMediaType Method

The SetMediaType method is not supported for Visual Basic. Use the SetMediaTypeForVB method instead.

Syntax

object.SetMediaType(
    pmt As _AMMediaType
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.SetMediaTypeForVB Method

The SetMediaTypeForVB method specifies the media type for the group.

Syntax

object.SetMediaTypeForVB(
    Val As Long
)

Parameters

Val

Value that specifies the media type:

Value | Description
Zero | Video
Non-zero | Audio

Error Codes

If the method fails, an error is raised.

Remarks

This method supports the following formats.

  • Video: 320 x 240 16-bit RGB, 555 format (MEDIASUBTYPE_RGB555).
  • Audio: 44.1-kHz stereo PCM, 16 bits per sample (MEDIASUBTYPE_PCM).

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetOutputBuffering Method

The SetOutputBuffering method specifies the number of frames rendered in advance during preview.

Syntax

object.SetOutputBuffering(
    nBuffer As Long
)

Parameters

nBuffer

Number of frames to buffer during preview. Must be two or greater.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.

Remarks

A larger buffer requires more memory but can result in smoother previewing, especially during effects or transitions that require more time to render. The default buffer is 30 frames.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetOutputFPS Method

The SetOutputFPS method sets the uncompressed output frame rate for this group.

Syntax

object.SetOutputFPS(
    FPS As Double
)

Parameters

FPS

Output frame rate for this group, in frames per second. The value cannot equal zero, and cannot have more than seven digits after the decimal place.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.

Remarks

Rendered output from this group runs at the specified frame rate, and all edits on the source material are rounded to the nearest frame boundary, as defined by the frame rate. For best performance, use the same frame rate for all groups, video and audio.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetPreviewMode Method

The SetPreviewMode method sets the preview mode for the group.

Syntax

object.SetPreviewMode(
    fPreview As Long
)

Parameters

fPreview

Value that specifies the preview mode. If zero, the group is in authoring mode. If non-zero, the group is in preview mode.

Error Codes

If the method fails, an error is raised.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might be out of sync with the audio.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetRecompFormatFromSource Method

The SetRecompFormatFromSource method sets the video recompression format using the compression format from a source file.

Syntax

object.SetRecompFormatFromSource(
    pSource As AMTimelineSrc
)

Parameters

pSource

AMTimelineSrc object.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_NO_TIMELINE | The group is not within a timeline.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_INVALIDMEDIATYPE | Source file has no video stream.

Remarks

This method finds the source file associated with pSource, retrieves the media type of the first video stream in the file, and sets the group compression format using that type.

See Also

  • AMTimelineGroup Object
  • Error and Success Codes


AMTimelineGroup.SetSmartRecompressFormat Method

The SetSmartRecompressFormat method is not supported for Visual Basic. Use the AMTimelineGroup.SetRecompFormatFromSource method instead.

Syntax

object.SetSmartRecompressFormat(
    pFormat As Long
)

See Also

  • AMTimelineGroup Object


AMTimelineGroup.SetTimeline Method

The SetTimeline method is not supported for Visual Basic.

Syntax

object.SetTimeline(
    pTimeline As AMTimeline
)

See Also

  • AMTimelineGroup Object


AMTimelineObj Object

Provides methods for manipulating timeline objects in DirectShow Editing Services (DES). All timeline objects support AMTimelienObj, including source, effect, transition, track, group, and composition objects. Create a timeline object by calling the AMTimeline.CreateEmptyNode method.

This object has the following methods.

Method | Description
ClearDirty | Not supported for Visual Basic.
FixTimes | Not supported for Visual Basic.
FixTimes2 | Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.
GetDirtyRange | Not supported for Visual Basic.
GetDirtyRange2 | Not supported for Visual Basic.
GetEmbedDepth | Not supported for Visual Basic.
GetGenID | Retrieves the object's generated identifier.
GetGroupIBelongTo | Not supported for Visual Basic.
GetLocked | Retrieves the object's editing state (locked or unlocked).
GetMuted | Retrieves the object's muted state.
GetPropertySetter | Not supported for Visual Basic.
GetStartStop | Not supported for Visual Basic.
GetStartStop2 | Retrieves the object's start and stop times, relative to the object's parent.
GetSubObject | Not supported for Visual Basic.
GetSubObjectGUID | Not supported for Visual Basic.
GetSubObjectGUIDB | Retrieves the GUID of the subobject associated with this object.
GetSubObjectLoaded | Determines whether a subobject has been created for the object.
GetTimelineNoRef | Not supported for Visual Basic.
GetTimelineType | Retrieves the object's type.
GetUserData | Retrieves application-defined persistent data.
GetUserID | Retrieves the object's application-defined identifier.
GetUserName | Retrieves the object's application-defined name.
Remove | Removes this object from the timeline, for reinsertion elsewhere.
RemoveAll | Permanently removes this object from the timeline, including subobjects and children.
SetDirtyRange | Not supported for Visual Basic.
SetDirtyRange2 | Not supported for Visual Basic.
SetLocked | Sets the object's editing state to locked or unlocked.
SetMuted | Sets the object's muted state.
SetPropertySetter | Not supported for Visual Basic.
SetStartStop | Not supported for Visual Basic.
SetStartStop2 | Sets the object's start and stop times, relative to the object's parent.
SetSubObject | Not supported for Visual Basic.
SetSubObjectGUID | Not supported for Visual Basic.
SetSubObjectGUIDB | Specifies the GUID of the subobject associated with this object.
SetTimelineType | Not supported for Visual Basic.
SetUserData | Sets application-defined persistent data.
SetUserID | Sets an application-defined identifier for the object.
SetUserName | Sets an application-defined name for the object.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineObj.ClearDirty Method

The ClearDirty method is not supported for Visual Basic.

Syntax

object.ClearDirty()

See Also

  • AMTimelineObj Object


AMTimelineObj.FixTimes Method

The FixTimes method is not supported for Visual Basic.

Syntax

object.FixTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimelineObj Object


AMTimelineObj.FixTimes2 Method

The FixTimes2 method rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.

Syntax

object.FixTimes2(
    pStart As Double,
    REFTIME As Double*pStop
)

Parameters

pStart

Variable that contains the start time, in seconds. If the call succeeds, the value is set to the rounded time.

pStop

Variable that contains the stop time, in seconds. If the call succeeds, the value is set to the rounded time.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_NOTINTREE | The object is not in the timeline.

Remarks

During rendering, DES rounds the object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Time in DirectShow Editing Services.

Use this method to determine accurate start and stop times in the rendered project. For example, if you seek within the project, seek to the rounded times and not the original times. Call GetStartStop2 to obtain the original times, and pass those values to FixTimes2.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetDirtyRange Method

The GetDirtyRange method is not supported for Visual Basic.

Syntax

object.GetDirtyRange(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetDirtyRange2 Method

The GetDirtyRange2 method is not supported for Visual Basic.

Syntax

object.GetDirtyRange2(
    pStart As Double,
    pStop As Double
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetEmbedDepth Method

The GetEmbedDepth method is not supported for Visual Basic.

Syntax

object.GetEmbedDepth(
    pVal As Long
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetGenID Method

The GetGenID method retrieves the object's generated identifier. The identifier is a reserved number. Applications should not use it.

Syntax

object.GetGenID(
    pVal As Long
)

Parameters

pVal

Variable that receives the generated identifier.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetGroupIBelongTo Method

The GetGroupIBelongTo method is not supported for Visual Basic.

Syntax

object.GetGroupIBelongTo(
    ppGroup As AMTimelineGroup
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetLocked Method

The GetLocked method retrieves the object's editing state (locked or unlocked). A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

GetLocked(
    pVal As Long
)

Parameters

pVal

Variable that receives the object's editing state. If the value is zero, the object is unlocked and can be edited. If the value is non-zero, the object is locked and should not be edited.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetMuted Method

The GetMuted method retrieves the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

object.GetMuted(
    pVal As Long
)

Parameters

pVal

Variable that receives a value indicating the muted state. If the value is zero, the object is not muted. If the value is non-zero, the object and its children are muted.

Error Codes

If the method fails, an error is raised.

Remarks

If an object's parent is muted, the object is muted regardless of its muted state. When the parent is no longer muted, the object's previous muted state is restored.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetPropertySetter Method

The GetPropertySetter method is not supported for Visual Basic..

Syntax

object.GetPropertySetter() As PropertySetter

See Also

  • AMTimelineObj Object


AMTimelineObj.GetStartStop Method

The GetStartStop method is not supported for Visual Basic.

Syntax

object.GetStartStop(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetStartStop2 Method

The GetStartStop2 method retrieves the object's start and stop times, relative to the object's parent.

Syntax

object.GetStartStop2(
    pStart As Double,
    pStop As Double
)

Parameters

pStart

Variable that receives the start time, in seconds.

pStop

Variable that receives the stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

Compositions, groups, and tracks always have a start time of 0.

During rendering, DES rounds an object's start and stop times to the nearest frame boundary. However, it does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Time in DirectShow Editing Services. To determine the start and stop times in the rendered project, pass the values returned by GetStartStop2 to the FixTimes2 method.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetSubObject Method

The GetSubObject method is not supported for Visual Basic.

Syntax

object.GetSubObject(
    pVal As Unknown
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetSubObjectGUID Method

The GetSubObjectGUID method is not supported for Visual Basic.

Syntax

object.GetSubObjectGUID(
    pVal As GUID
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetSubObjectGUIDB Method

The GetSubObjectGUIDB method retrieves the GUID of the subobject associated with this timeline object.

Syntax

object.GetSubObjectGUIDB() As String

Parameters

This method takes no parameters.

Return Value

Returns a string that contains the GUID of the subobject. If the object has no subobject, the return value is {00000000-0000-0000-0000-000000000000}.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetSubObjectLoaded Method

The GetSubObjectLoaded method ascertains whether a subobject has been created for the object.

Syntax

object.GetSubObjectLoaded(
    pVal As Long
)

Parameters

pVal

Variable that receives a value indicating whether a subobject has been created. If zero, a subobject has been not created. If non-zero, a subobject has been created.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetTimelineNoRef Method

The GetTimelineNoRef method is not supported for Visual Basic.

Syntax

object.GetTimelineNoRef(
    ppResult As AMTimeline
)

See Also

  • AMTimelineObj Object


AMTimelineObj.GetTimelineType Method

The GetTimelineType method retrieves the object's type.

Syntax

object.GetTimelineType(
    pVal As TIMELINE_MAJOR_TYPE
)

Parameters

pVal

Variable that receives a member of the TIMELINE_MAJOR_TYPE enumerated type, indicating the type of object.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetUserData Method

The GetUserData method retrieves application-defined persistent data.

Syntax

object.GetUserData(
    pData As Byte,
    pSize As Long
)

Parameters

pData

Reference to an array of bytes that contains the data.

pSize

Size of the array, in bytes. When the method returns, the value is set to the required size. See Remarks.

Error Codes

If the method fails, an error is raised.

Remarks

This method sets the value of pSize equal to the array size needed for the user data. Use the ReDim statement to resize the array and call the method again. Pass the pData parameter by reference, using the first element of the array as the parameter value.

Code Example

Dim UserData(0) As Byte
Dim Size As Long

' Find the required size.
ReDim UserData(1)
objTimelineObject.GetUserData UserData(0), Size

' Resize the array and get all the data.
If Size <> 0 Then
    ReDim UserData(Size)
    objTimelineObject.GetUserData UserData(0), Size
End If

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetUserID Method

The GetUserID method retrieves the object's application-defined identifier.

Syntax

object.GetUserID(
    pVal As Long
)

Parameters

pVal

Variable that receives the application-defined identifier.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.GetUserName Method

The GetUserName method retrieves the object's application-defined name.

Syntax

object.GetUserName() As String

Parameters

This method takes no parameters.

Return Value

Returns a string that contains the application-defined name.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.Remove Method

The Remove method removes this object from the timeline (including subobjects but not children), for reinsertion elsewhere.

Syntax

object.Remove()

Error Codes

If the method fails, an error is raised.

Remarks

Call this method only if the application will immediately insert the object back into the timeline. It is an invalid operation to call this method without then reinserting the object. To remove an object permanently, call RemoveAll.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.RemoveAll Method

The RemoveAll method permanently removes this object from the timeline, including subobjects and children.

Syntax

object.RemoveAll()

Error Codes

If the method fails, an error is raised.

Remarks

To remove an object for the purpose of reinserting it elsewhere in the timeline, call Remove.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetDirtyRange Method

The SetDirtyRange method is not supported for Visual Basic.

Syntax

object.SetDirtyRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetDirtyRange2 Method

The SetDirtyRange2 method is not supported for Visual Basic.

Syntax

object.SetDirtyRange2(
    Start As Double,
    Stop As Double
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetLocked Method

The SetLocked method sets the object's editing state to locked or unlocked. A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

object.SetLocked(
    newVal As Long
)

Parameters

newVal

Value that specifies the object's editing state. If zero, the object is unlocked and can be edited. If non-zero, the object is locked and should not be edited.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetMuted Method

The SetMuted method sets the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

object.SetMuted(
    newVal As Long
)

Parameters

newVal

Value that specifies the muted state. If zero, the object is non muted. If non-zero, the object and all its children are muted.

Error Codes

If the method fails, an error is raised.

Remarks

Muting an object also mutes any children contained in the object. For example, if you mute a track, the transitions, sources, and effects in that track are also muted. Once the object is no longer muted, its children revert to their previous state, which might be muted or unmuted.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetPropertySetter Method

The SetPropertySetter method is not supported for Visual Basic.

Syntax

object.SetPropertySetter(
    newVal As PropertySetter
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetStartStop Method

The SetStartStop method is not supported for Visual Basic.

Syntax

object.SetStartStop(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetStartStop2 Method

The SetStartStop2 method sets the object's start and stop times, relative to the object's parent.

Syntax

object.SetStartStop2(
    Start As Double,
    Stop As Double
)

Parameters

Start

New start time, in seconds, or –1 to keep the existing start time.

Stop

New stop time, in seconds, or –1 to keep the existing stop time.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

Tracks, compositions, and groups do not implement this method. For these objects, the start time is always zero, and the stop time is the maximum stop time of the objects they contain.

Do not set overlapping times on source objects within the same track. Doing so can cause undefined behaviors.

For source objects, the start and stop times are independent of the media start and media stop times. Changing one pair of values does not change the other. To set the media start and stop times, call the AMTimelineSrc.SetMediaTimes2 method. For more information, see Time in DirectShow Editing Services.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetSubObject Method

The SetSubObject method is not supported for Visual Basic.

Syntax

object.SetSubObject(
    newVal As Unknown
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetSubObjectGUID Method

The SetSubObjectGUID method is not supported for Visual Basic.

Syntax

object.SetSubObjectGUID(
    newVal As GUID
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetSubObjectGUIDB Method

The SetSubObjectGUIDB method specifies the GUID of the subobject associated with this object.

Syntax

object.SetSubObjectGUIDB(
    newVal As String
)

Parameters

newVal

String that contains the GUID of the subobject.

Error Codes

If the method fails, an error is raised.

Remarks

The render engine creates an instance of the subobject as needed.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetTimelineType Method

The SetTimelineType method is not supported for Visual Basic. To create a new timeline object, call the AMTimeline.CreateEmptyNode method. Once an object is created, you cannot change its type.

Syntax

object.SetTimelineType(
    newVal As TIMELINE_MAJOR_TYPE
)

See Also

  • AMTimelineObj Object


AMTimelineObj.SetUserData Method

The SetUserData method sets application-defined persistent data.

Syntax

object.SetUserData(
    pData As Byte,
    Size As Long
)

Parameters

pData

Reference to an array of bytes that contains the data.

Size

Size of the array, in bytes.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

Remarks

Pass the pData parameter by reference, using the first element of the array as the parameter value:

Dim UserData(100) As Byte
' Initialize the array (not shown).
objTimelineObject.SetUserData UserData(0), 100

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetUserID Method

The SetUserID method sets an application-defined identifier for the object.

Syntax

object.SetUserID(
    newVal As Long
)

Parameters

newVal

Value that specifies the identifier. This identifier is used only by the application and can be any value.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineObj.SetUserName Method

The SetUserName method sets an application-defined name for the object.

Syntax

object.SetUserName(
    newVal As String
)

Parameters

newVal

String that contains the name. Strings longer than 256 characters might be truncated.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineObj Object
  • Error and Success Codes


AMTimelineSrc Object

Provides methods for manipulating and setting properties on sources in DirectShow Editing Services (DES). An AMTimelineSrc object represents a clip taken from one stream in a media source.

You can use a portion of the data within a source file by setting the media start and media stop times. These values specify the beginning and end of the AMTimelineSrc object, relative to the original media source. The media times can differ from the object's start and stop times on the timeline, allowing for fast- or slow-motion playback (with audio sources, the pitch shifts).

This object has the following methods.

Method | Description
FixMediaTimes | Not supported for Visual Basic.
FixMediaTimes2 | Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate.
GetDefaultFPS | Retrieves the source object's default frame rate.
GetMediaLength | Not supported for Visual Basic.
GetMediaLength2 | Retrieves the media length of this object.
GetMediaName | Retrieves the name of the source file represented by this object.
GetMediaTimes | Not supported for Visual Basic.
GetMediaTimes2 | Retrieves the media start and stop times.
GetStreamNumber | Retrieves the current stream number for the source object.
GetStretchMode | Retrieves the stretch mode.
IsNormalRate | Indicates whether the clip will play at the authored playback rate.
ModifyStopTime | Not supported for Visual Basic.
ModifyStopTime2 | Sets the stop time.
SetDefaultFPS | Sets the source object's default frame rate.
SetMediaLength | Not supported for Visual Basic.
SetMediaLength2 | Specifies the duration of the source file.
SetMediaName | Specifies the name of the source file.
SetMediaTimes | Not supported for Visual Basic.
SetMediaTimes2 | Sets the media stop and start times.
SetStretchMode | Sets the stretch mode.
SetStreamNumber | Specifies which stream to read from the source file.
SpliceWithNext | Joins the AMTimelineSrc object to another AMTimelineSrc object.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineSrc.FixMediaTimes Method

The FixMediaTimes method is not supported for Visual Basic.

Syntax

object.FixMediaTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.FixMediaTimes2 Method

The FixMediaTimes2 method rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. In general, applications do not need to call this method.

Syntax

object.FixMediaTimes2(
    pStart As Double,
    pStop As Double
)

Parameters

pStart

Start time, in seconds. If the call succeeds, this variable is set to the rounded time.

pStop

Stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Error Codes

If the method fails, an error is raised.

Remarks

This method is similar to the AMTimelineObj.FixTimes2 method, but it preserves the original ratio of media times and timeline times. Just rounding the times to the nearest frame boundary could distort this ratio.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.GetDefaultFPS Method

The GetDefaultFPS method retrieves the source object's default frame rate. The render engine uses this value if it cannot determine the frame rate from the original source.

Syntax

object.GetDefaultFPS(
    pFPS As Double
)

Parameters

pFPS

Variable that receives the default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

Remarks

The default frame rate is not required if the file format specifies the frame rate. This is the case for audio and video formats.

If the source is a bitmap or JPEG image, the render engine uses it as the first image in a device-independent bitmap (DIB) sequence, with a frame rate equal to the default frame rate. To render a static image, rather than a DIB sequence, set the default frame rate to 0.

If the source is a GIF, do not set the frame rate. For animated GIFs, the GIF file specifies the delay between each image.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.GetMediaLength Method

The GetMediaLength method is not supported for Visual Basic.

Syntax

object.GetMediaLength(
    pLength As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.GetMediaLength2 Method

The GetMediaLength2 method retrieves the media length of this object.

Syntax

object.GetMediaLength2(
    pLength As Double
)

Parameters

pLength

Variable that receives the media length in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_NOTDETERMINED | Media times are not set on this object.

See Also

  • AMTimelineSrc Object
  • AMTimelineSrc.SetMediaLength2
  • Error and Success Codes


AMTimelineSrc.GetMediaName Method

The GetMediaName method retrieves the name of the source file represented by this object.

Syntax

object.GetMediaName() As String

Parameters

This method takes no parameters.

Return Value

Returns the name of the source file.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.GetMediaTimes Method

The GetMediaTimes method is not supported for Visual Basic.

Syntax

object.GetMediaTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.GetMediaTimes2 Method

The GetMediaTimes2 method retrieves the media start and stop times.

Syntax

object.GetMediaTimes2(
    pStart As Double,
    pStop As Double
)

Parameters

pStart

Variable that receives the media start time, in seconds.

pStop

Variable that receives the media stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

The media times are relative to the original media file. For more information, see Time in DirectShow Editing Services.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.GetStreamNumber Method

The GetStreamNumber method retrieves the current stream number for the source object.

Syntax

object.GetStreamNumber(
    pVal As Long
)

Parameters

pVal

Variable that receives the stream number.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.GetStretchMode Method

The GetStretchMode method retrieves the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

object.GetStretchMode(
    pnStretchMode As Long
)

Parameters

pnStretchMode

Variable that receives one of the following values:

  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

For more information, see Resize Flags.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.IsNormalRate Method

The IsNormalRate method indicates whether the clip will play at the authored playback rate.

Syntax

object.IsNormalRate(
    pVal As Long
)

Parameters

pVal

Variable that receives a value indicating how the clip will render. If non-zero, the clip will play at the normal rate. If zero, it will play faster or slower than normal.

Error Codes

If the method fails, an error is raised.

Remarks

A clip's playback rate is determined by its media start and stop times, relative to its timeline times:

Playback rate = (Media Stop — Media Start) / (Timeline Stop — Timeline Start)

If this ratio is equal to 1, the clip plays at the authored speed. Otherwise, it plays faster or slower. For more information, see Time in DirectShow Editing Services.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.ModifyStopTime Method

The ModifyStopTime method is not supported for Visual Basic.

Syntax

object.ModifyStopTime(
    Stop As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.ModifyStopTime2 Method

The ModifyStopTime2 method sets the stop time.

Syntax

object.ModifyStopTime2(
    Stop As Double
)

Parameters

Stop

New stop time, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | The specified time is invalid.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetDefaultFPS Method

The SetDefaultFPS method sets the source object's default frame rate.

Syntax

object.SetDefaultFPS(
    FPS As Double
)

Parameters

FPS

Default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | The specified frame rate is less than zero.

Remarks

The render engine uses this value if it cannot determine the frame rate from the original source file.

Call this method only for source files without a predefined frame rate. For bitmap and JPEG files, the default frame rate is zero, which causes the source to be rendered as a still image. To use the image as the first frame in a DIB sequence, set the frame rate to a value greater than zero.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetMediaLength Method

The SetMediaLength method is not supported for Visual Basic.

Syntax

object.SetMediaLength(
    Length As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.SetMediaLength2 Method

The SetMediaLength2 method specifies the duration of the source file.

Syntax

object.SetMediaLength2(
    Length As Double
)

Parameters

Length

Media length, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

You can avoid potential rendering errors by setting the media length before you set the media stop time. When you set the media stop time, DES checks it against the media length.

This method does not validate the Length parameter, but the value must equal the actual duration of the source file. Obtain the source file duration by retrieving the MediaDet.StreamLength property.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetMediaName Method

The SetMediaName method specifies the name of the source file.

Syntax

object.SetMediaName(
    newVal As String
)

Parameters

newVal

String that specifies the name of the media file.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetMediaTimes Method

The SetMediaTimes method is not supported for Visual Basic.

Syntax

object.SetMediaTimes(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • AMTimelineSrc Object


AMTimelineSrc.SetMediaTimes2 Method

The SetMediaTimes2 method sets the media stop and start times.

Syntax

object.SetMediaTimes2(
    Start As Double,
    Stop As Double
)

Parameters

Start

Media start time, in seconds.

Stop

Media stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

The media times are the stop and start times relative to the original media file. Always set the media times when you add a video or audio source to the timeline. Otherwise, rendering problems might occur. The stop time must be greater than the start time.

To use a still frame from a video source, set the stop time to a fractional amount more than the start time, such as 100 nanoseconds. Setting them to the same value causes a rendering error.

If the timeline duration does not match the media duration, the source stretches or shrinks accordingly. This causes the clip to play slower or faster than the authored rate (pitch shifting will occur in an audio source). For more information, see Time in DirectShow Editing Services.

You can specify the duration of the source file by calling the SetMediaLength method. If you set a media stop time that exceeds the duration, DES truncates the stop time.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetStreamNumber Method

The SetStreamNumber method specifies which stream to read from the source file.

Syntax

object.SetStreamNumber(
    Val As Long
)

Parameters

Val

The stream number, from the set of streams matching the media type of the parent group.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | The Val parameter is less than zero.

Remarks

The Val parameter specifies a stream number from the set of streams that matches the parent group's media type, not from the entire set of streams in the source file. For example, suppose that a file contains two video streams and two audio streams. If the AMTimelineSrc object is inside a video group, setting Val to 0 selects the first video stream. The caller is responsible for specifying a valid stream number.

The stream number defaults to zero.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SetStretchMode Method

The SetStretchMode method sets the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

object.SetStretchMode(
    nStretchMode As Long
)

Parameters

nStretchMode

Flag indicating the current stretch mode. Must be one of the following values:

  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

For more information, see Resize Flags.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineSrc.SpliceWithNext Method

The SpliceWithNext method joins this AMTimelineSrc object to another AMTimelineSrc object.

Syntax

object.SpliceWithNext(
    pNext As AMTimelineObj
)

Parameters

pNext

AMTimelineObj object to join to the current source.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pNext parameter is not a source object.

Remarks

As currently implemented, this method discards any effects on pNext.

For this method to succeed, pNext must be a match frame of the current source object:

  • It must share the same source file.
  • The media start time must equal the media stop time of the current source.
  • The playback rate must be the same. Playback rate is media duration divided by timeline duration.

See Also

  • AMTimelineSrc Object
  • Error and Success Codes


AMTimelineTrack Object

Provides methods for manipulating tracks in DirectShow Editing Services (DES).

A track contains a list of sources that are rendered in the final output. Sources within the same track may not overlap. Video tracks can have both effects and transitions. The render engine applies effects before it applies transitions. Audio tracks can have effects, but not transitions.

For more information, see The Timeline Model.

This object has the following methods.

Method | Description
AreYouBlank | Determines whether the track is blank (contains no source objects).
GetNextSrc | Not supported for Visual Basic.
GetNextSrc2 | Searches the track for the next source that appears at the specified time or later.
GetNextSrcEx | Retrieves the next source after the specified source.
GetSourcesCount | Retrieves the number of sources in the track.
GetSrcAtTime | Not supported for Visual Basic.
GetSrcAtTime2 | Retrieves the source object nearest to the specified time, according to specified boundary conditions.
InsertSpace | Not supported in Visual Basic.
InsertSpace2 | Splits any objects that exist at the specified time and inserts space between them.
MoveEverythingBy | Not supported for Visual Basic.
MoveEverythingBy2 | Not supported for Visual Basic.
SrcAdd | Adds a source to the track.
ZeroBetween | Not supported for Visual Basic.
ZeroBetween2 | Removes everything from the track between the specified times.


AMTimelineTrack.AreYouBlank Method

The AreYouBlank method ascertains whether the track is blank (contains no source objects).

Syntax

object.AreYouBlank(
    pVal As Long
)

Parameters

pVal

Variable that receives a value specifying whether the track is blank. If non-zero, the track is blank and contains no source objects. If zero, the track is not blank.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.GetNextSrc Method

The GetNextSrc method is not supported for Visual Basic.

Syntax

object.GetNextSrc(
    ppSrc AMTimelineObj,
    pInOut As <Unsupported variant type>
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.GetNextSrc2 Method

The GetNextSrc2 method searches the track for the next source that appears at the specified time or later.

Syntax

object.GetNextSrc2(
    ppSrc As AMTimelineObj,
    pInOut As Double
)

Parameters

ppSrc

The AMTimelineObj object that receives the source object.

pInOut

Start time for the search, in seconds. If the method retrieves a source, it sets this variable to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Error Codes

If the method fails, an error is raised.

Remarks

If the time specified by pInOut falls between the start and stop times of a source, the method retrieves that source.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.GetNextSrcEx Method

The GetNextSrcEx method retrieves the next source after the specified source.

Syntax

object.GetNextSrcEx(
    pLast As AMTimelineObj,
    ppNext As AMTimelineObj
)

Parameters

pLast

The previous AMTimelineObj object, or Nothing to retrieve the first source in the track.

ppNext

The AMTimelineObj object that receives the next source.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.GetSourcesCount Method

The GetSourcesCount method retrieves the number of sources in the track.

Syntax

object.GetSourcesCount(
    pVal As Long
)

Parameters

pVal

Variable that receives the number of sources in the track.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.GetSrcAtTime Method

The GetSrcAtTime method is not supported for Visual Basic.

Syntax

object.GetSrcAtTime(
    ppSrc As AMTimelineObj,
    Time As <Unsupported variant type>,
    SearchDirection As Long
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.GetSrcAtTime2 Method

The GetSrcAtTime2 method retrieves the source object nearest to the specified time, according to the specified boundary conditions.

Syntax

object.GetSrcAtTime2(
    ppSrc As AMTimelineObj,
    Time As Double,
    SearchDirection As Long
)

Parameters

ppSrc

The AMTimelineObj object that receives the source.

Time

Start time for the search, in seconds.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.InsertSpace Method

The InsertSpace method not supported in Visual Basic.

Syntax

object.InsertSpace(
    rtStart As <Unsupported variant type>,
    rtEnd As <Unsupported variant type>
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.InsertSpace2 Method

The InsertSpace2 method splits any objects that exist at the specified time and inserts space between them.

Syntax

object.InsertSpace2(
    rtStart As Double,
    rtEnd As Double
)

Parameters

rtStart

Time at which to create the split, and the starting point of the inserted space, in seconds.

rtEnd

End point of the inserted space, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.MoveEverythingBy Method

The MoveEverythingBy method is not supported for Visual Basic.

Syntax

object.MoveEverythingBy(
    Start As <Unsupported variant type>,
    MoveBy As <Unsupported variant type>
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.MoveEverythingBy2 Method

The MoveEverythingBy2 method is not supported for Visual Basic.

Syntax

object.MoveEverythingBy2(
    Start As Double,
    MoveBy As Double
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.SrcAdd Method

The SrcAdd method adds a source to the track.

Syntax

object.SrcAdd(
    pSrc As AMTimelineObj
)

Parameters

pSrc

The AMTimelineObj object to add.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_NOINTERFACE | The object specified by pSrc is not a source object.

Remarks

Set the source's start and stop times before calling this method. (Call the AMTimelineObj.SetStartStop method.)

Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see RenderEngine.SetDynamicReconnectLevel.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrack.ZeroBetween Method

The ZeroBetween method is not supported for Visual Basic.

Syntax

object.ZeroBetween(
    rtStart As <Unsupported variant type>,
    rtEnd As <Unsupported variant type>
)

See Also

  • AMTimelineTrack Object


AMTimelineTrack.ZeroBetween2 Method

The ZeroBetween2 method removes everything from the track between the specified times. This method splits any objects that span the specified time range and removes the pieces that fall within the range.

Syntax

object.ZeroBetween2(
    rtStart As Double,
    rtEnd As Double
)

Parameters

rtStart

Beginning of the range to clear, in seconds.

rtEnd

End of the range to clear, in seconds.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrack Object
  • Error and Success Codes


AMTimelineTrans Object

Provides methods for manipulating transitions in DirectShow Editing Services (DES).

A transition is a progression between one layer and the rendered composite of all the layers with a lower priority. The AMTimelineTrans object is a wrapper for any two-input Microsoft® DirectX® Transform object. To specify the DirectX Transform object, call the AMTimelineObj.SetSubObjectGUID method.

Timeline objects that can have transitions support the IAMTimelineTransable object.

This object has the following methods.

Method | Description
GetCutPoint | Not supported for Visual Basic.
GetCutPoint2 | Retrieves the cut point.
GetCutsOnly | Determines whether the transition is rendered as a cut.
GetSwapInputs | Determines whether the transition inputs are swapped.
SetCutPoint | Not supported for Visual Basic.
SetCutPoint2 | Sets the cut point.
SetCutsOnly | Specifies whether the transition is rendered as a cut.
SetSwapInputs | Specifies whether the transition inputs are swapped.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


AMTimelineTrans.GetCutPoint Method

The GetCutPoint method is not supported for Visual Basic.

Syntax

object.GetCutPoint(
    pTLTime As <Unsupported variant type>
)

See Also

  • AMTimelineTrans Object


AMTimelineTrans.GetCutPoint2 Method

The GetCutPoint2 method retrieves the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, this value is the middle of the transition. For example, in a transition that spans two seconds, the default cut point is one second into the transition.

Syntax

object.GetCutPoint2(
    pTLTime As Double
)

Parameters

pTLTime

Variable that receives the cut point, relative to the start time of the transition, in seconds.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrans Object
  • AMTimelineTrans.SetCutPoint2
  • AMTimelineTrans.GetCutsOnly
  • AMTimeline.TransitionsEnabled
  • Error and Success Codes


AMTimelineTrans.GetCutsOnly Method

The GetCutsOnly method determines whether the transition is rendered as a cut. If so, the transition occurs instantaneously at the cut point.

Syntax

object.GetCutsOnly(
    pVal As Long
)

Parameters

pVal

Variable that receives a value indicating whether the transition is rendered as a cut. If non-zero, the transition is an instantaneous cut. If zero, the transition occurs over its normal duration.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrans Object
  • AMTimelineTrans.SetCutsOnly
  • AMTimelineTrans.GetCutPoint
  • AMTimeline.TransitionsEnabled
  • Error and Success Codes


AMTimelineTrans.GetSwapInputs Method

The GetSwapInputs method determines whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

object.GetSwapInputs(
    pVal As Long
)

Parameters

pVal

Variable that receives a value indicating whether inputs are swapped. If the value is zero, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is non-zero, the transition goes in the opposite direction. The default value is zero.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrans Object
  • Error and Success Codes


AMTimelineTrans.SetCutPoint Method

The SetCutPoint method is not supported for Visual Basic.

Syntax

object.SetCutPoint(
    TLTime As <Unsupported variant type>
)

See Also

  • AMTimelineTrans Object


AMTimelineTrans.SetCutPoint2 Method

The SetCutPoint2 method sets the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, the cut point is the middle of the transition. For example, in a transition that spans two seconds, the default cut point is one second into the transition.

Syntax

object.SetCutPoint2(
    TLTime As Double
)

Parameters

TLTime

Cut point relative to the start of the transition, in seconds.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrans Object
  • Error and Success Codes


AMTimelineTrans.SetCutsOnly Method

The SetCutsOnly method specifies whether the transition is rendered as a cut. If so, the transition occurs instantly at the cut point. If a transition takes a long time to render, you might want to preview it as a cut to speed preview.

Syntax

object.SetCutsOnly(
    Val As Long
)

Parameters

Val

Value that specifies whether to render the transition as a cut. If zero, the transition is rendered as an instantaneous cut. If non-zero, the transition renders over its normal duration.

Error Codes

If the method fails, an error is raised.

See Also

  • AMTimelineTrans Object
  • Error and Success Codes


AMTimelineTrans.SetSwapInputs Method

The SetSwapInputs method specifies whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

object.SetSwapInputs(
    Val As Long
)

Parameters

Val

Value that specifies whether the inputs are swapped. If zero, the transition goes from the composite of all lower-priority layers to the transition layer. If non-zero, the transition goes in the opposite direction.

Error Codes

If the method fails, an error is raised.

Remarks

This method does not change the direction of the visual effect. For example, a left-to-right wipe will still go from left to right.

See Also

  • AMTimelineTrans Object
  • Error and Success Codes


IAMTimelineSplittable Object

Splits a timeline object in DirectShow Editing Services (DES). Sources, effects, transitions, and tracks support this object.

This object has the following methods.

Method | Description
SplitAt | Not supported for Visual Basic.
SplitAt2 | Splits the object at the specified time.


IAMTimelineSplittable.SplitAt Method

The SplitAt method is not supported for Visual Basic.

Syntax

object.SplitAt(
    Time As <Unsupported variant type>
)

See Also

  • IAMTimelineSplittable Object


IAMTimelineSplittable.SplitAt2 Method

The SplitAt2 method splits the object at the specified time.

Syntax

object.SplitAt2(
    Time As Double
)

Parameters

Time

Time at which to split the object, relative to the timeline, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | The object does not exist at this time.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you split a source, effect, or transition, this method creates a second object of the same type. The original object is truncated at the specified split time, and the new object replaces the truncated portion. The new object inherits all of the same properties. In a source object, the method also splits any effects that fall on the split time.

Calling this method on a track splits all the sources, effects, and transitions that are contained in the track at the specified split time. It does not create a second track (a track begins at time zero and extends to infinity).

See Also

  • IAMTimelineSplittable Object
  • Error and Success Codes


IAMTimelineTransable Object

Adds transitions to an object in DirectShow Editing Services (DES). Applies to objects that can have transitions applied to them, such as tracks, compositions, and groups. An object that supports transitions can have any number of transitions, but the transitions must not overlap in time.

Note Audio does not support transitions.

This object has the following methods.

Method | Description
GetNextTrans | Not supported for Visual Basic.
GetNextTrans2 | Retrieves the first transition that appears at the specified time or later.
GetTransAtTime | Not supported for Visual Basic.
GetTransAtTime2 | Retrieves the transition nearest to the specified time, according to specified boundary conditions.
TransAdd | Adds a transition to the object.
TransGetCount | Retrieves the number of transitions on this object.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


IAMTimelineTransable.GetNextTrans Method

The GetNextTrans method is not supported for Visual Basic.

Syntax

object.GetNextTrans(
    ppTrans As AMTimelineObj,
    pInOut As <Unsupported variant type>
)

See Also

  • IAMTimelineTransable Object


IAMTimelineTransable.GetNextTrans2 Method

The GetNextTrans2 method retrieves the first transition that appears at the specified time or later.

Syntax

object.GetNextTrans2(
    ppTrans As AMTimelineObj,
    pInOut As Double
)

Parameters

ppTrans

The AMTimelineObj object that receives the transition.

pInOut

On input, this parameter specifies the time from which to find the transition. On output, if a transition is retrieved, this parameter is set to the stop time of the transition.

Error Codes

If the method fails, an error is raised.

Remarks

The start time of the transition might be less than the time that you specify in pInOut, if the transition spans the specified time.

See Also

  • IAMTimelineTransable Object
  • Error and Success Codes


IAMTimelineTransable.GetTransAtTime Method

The GetTransAtTime method is not supported for Visual Basic.

Syntax

object.GetTransAtTime(
    ppObj As AMTimelineObj,
    Time As <Unsupported variant type>,
    SearchDirection As Long
)

See Also

  • IAMTimelineTransable Object


IAMTimelineTransable.GetTransAtTime2 Method

The GetTransAtTime2 method retrieves the transition nearest to the specified time, according to specified boundary conditions.

Syntax

object.GetTransAtTime2(
    ppObj As AMTimelineObj,
    Time As Double,
    SearchDirection As Long
)

Parameters

ppObj

The AMTimelineObj object that receives the transition.

Time

Time from which to begin the search, in seconds.

SearchDirection

Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Error Codes

If the method fails, an error is raised, and Err.Number is set to the following value:

Value | Description
E_INVALIDARG | Invalid argument.

See Also

  • IAMTimelineTransable Object
  • Error and Success Codes


IAMTimelineTransable.TransAdd Method

The TransAdd method adds a transition to the object. An object can have multiple transitions, but they must not overlap in time. Transitions must fall within the time boundaries of the object.

Syntax

object.TransAdd(
    pTrans As AMTimelineObj
)

Parameters

pTrans

The AMTimelineObj object that specifies the transition to add.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Cannot insert the transition.
E_NOINTERFACE | pTrans is not a transition.

Remarks

If the transition overlaps an existing transition, the method raises an E_INVALIDARG error.

See Also

  • IAMTimelineTransable Object
  • Error and Success Codes


IAMTimelineTransable.TransGetCount Method

The TransGetCount method retrieves the number of transitions on this object.

Syntax

object.TransGetCount(
    pCount As Long
)

Parameters

pCount

Variable that receives the number of transitions.

Error Codes

If the method fails, an error is raised.

See Also

  • IAMTimelineTransable Object
  • Error and Success Codes


IAMTimelineVirtualTrack Object

Provides methods for working with virtual tracks in DirectShow Editing Services (DES). Compositions and tracks support this object.

Methods

SetTrackDirty | Not supported for Visual Basic.
TrackGetPriority | Retrieves the object's priority level.


IAMTimelineVirtualTrack.SetTrackDirty Method

The SetTrackDirty method is not supported for Visual Basic.

Syntax

object.SetTrackDirty()

See Also

  • IAMTimelineVirtualTrack Object


IAMTimelineVirtualTrack.TrackGetPriority Method

The TrackGetPriority method retrieves the object's priority level.

Syntax

object.TrackGetPriority(
    pPriority As Long
)

Parameters

pPriority

Pointer to a variable that receives the priority level. If the object is not part of a timeline, the value is set to –1.

Error Codes

If the method fails, an error is raised.

See Also

  • IAMTimelineVirtualTrack Object
  • Error and Success Codes


MediaDet Object

Retrieves information about a media file, such as the number of streams and the type, duration, and frame rate of each stream. This object also contains methods for retrieving poster frames from a video stream.

To obtain information about a file, perform the following steps:

  1. Create a new instance of the MediaDet object.
  2. Set the Filename property to specify the name of the source file.
  3. Retrieve the OutputStreams property to obtain the number of output streams in the source.
  4. Set the CurrentStream property to specify a particular stream.
  5. Retrieve any of the following properties: StreamType, StreamMediaType, StreamLength, or FrameRate.

To retrieve poster frames, call WriteBitmapBits. This method puts the MediaDet object into a new mode, called bitmap grab mode. The informational methods described previously do not work in this mode. Therefore, get any information you need before retrieving poster frames, or else create new instances of the MediaDet object for each stream.

The MediaDet object ignores any streams in the file that are not video or audio. For example, if the file contains an audio stream, a data stream, and a video stream, the OutputStreams property will report only two streams (the audio and video).

Code Example

Dim Det As New MediaDet
Const VideoGUID As String = "{73646976-0000-0010-8000-00AA00389B71}"
bFoundVidStream = False

Det.FileName = "C:\Media\Example.avi"

' Look for a video stream.
For i = 0 To Det.OutputStreams - 1
    Det.CurrentStream = i
    StreamType = Det.StreamTypeB
    If StrComp(StreamType, VideoGUID, vbTextCompare) = 0 Then
        bFoundVidStream = True
        Exit For
    End If
Next

If bFoundVidStream Then
    ' Update the label with the duration.
    VideoInfo.Caption = Det.FileName + ": " + Str(Det.StreamLength) + " seconds"

    ' Load a poster frame.
    TempFile = "C:\Temp.bmp"
    Preview.ScaleMode = vbPixels  ' Scale twips to pixels.
    Det.WriteBitmapBits 0, Preview.ScaleWidth, Preview.ScaleHeight, TempFile
    Preview.Picture = LoadPicture(TempFile)
End If

This object has the following properties and methods.

Property | Description
CurrentStream | Stream number currently used by the MediaDet object.
Filename | Name of the source file currently used by the MediaDet object.
Filter | Not supported for Visual Basic.
OutputStreams | Number of audio and video streams contained in the media source.
FrameRate | Frame rate of the current stream, in frames per second.
StreamLength | Duration of the current stream, in seconds.
StreamMediaType | Not supported for Visual Basic.
StreamType | Not supported for Visual Basic.
StreamTypeB | String representing the GUID of the media type for the current stream.

Method | Description
EnterBitmapGrabMode | Switches the MediaDet object to bitmap grab mode and seeks the filter graph to a specified time.
GetBitmapBits | Not supported for Visual Basic.
GetSampleGrabber | Not supported for Visual Basic.
WriteBitmapBits | Retrieves a poster frame at the specified media time and writes it to a file.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


MediaDet.CurrentStream Property

The CurrentStream property sets or retrieves the stream number currently used by the MediaDet object.

Syntax

object.CurrentStream As Long

Parameters

This property takes no parameters.

Remarks

This property is read/write.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.Filename Property

The Filename property sets or retrieves the name of the source file currently used by the MediaDet object.

Syntax

object.Filename As String

Parameters

This property takes no parameters.

Remarks

This property is read/write.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.Filter Property

The Filter property is not supported for Visual Basic.

Syntax

object.Filter As Unknown

See Also

  • MediaDet Object


MediaDet.FrameRate Property

The FrameRate property returns the frame rate of the current stream, in frames per second.

Syntax

object.FrameRate As Double

Parameters

This property takes no parameters.

Remarks

The stream must be a video stream. This property is not valid for ASF files. The property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

Before retrieving this property, set the Filename and CurrentStream properties.

This property is read-only.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.OutputStreams Property

The OutputStreams property returns the number of audio and video streams contained in the media source. Any other stream types, such as data streams, are ignored.

Syntax

object.OutputStreams As Long

Parameters

This property takes no parameters.

Remarks

Before retrieving this property, set the Filename property. This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

This property is read-only.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.StreamLength Property

The StreamLength property returns the duration of the current stream, in seconds.

Syntax

object.StreamLength As Double

Parameters

This property takes no parameters.

Remarks

Before retrieving this property, set the Filename and CurrentStream properties. This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

This property is read-only.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.StreamMediaType Property

The StreamMediaType property is not supported for Visual Basic.

Syntax

object.get_StreamMediaType As _AMMediaType

See Also

  • MediaDet Object


MediaDet.StreamType Property

The StreamType property is not supported for Visual Basic.

Syntax

object.StreamType As GUID

See Also

  • MediaDet Object


MediaDet.StreamTypeB Property

The StreamTypeB property returns a string representing the GUID of the media type for the current stream.

Syntax

object.StreamTypeB As String

Parameters

This property takes no parameters.

Remarks

The string formatted like the following: {73647561-0000-0010-8000-00AA00389B71}

Before retrieving this property, set the Filename and CurrentStream properties. This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

This property is read-only.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.EnterBitmapGrabMode Method

The EnterBitmapGrabMode method switches the MediaDet object to bitmap grab mode and seeks the filter graph to a specified time.

Syntax

object.EnterBitmapGrabMode(
    SeekTime As Double
)

Parameters

SeekTime

Time, in seconds, to which the graph seeks.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
VFW_E_INVALIDMEDIATYPE | File does not have a video stream.
VFW_E_TIME_EXPIRED | Could not seek.

Remarks

Before calling this method, set the Filename and CurrentStream properties.

This method inserts the Sample Grabber filter into the filter graph. Once the MediaDet object enters bitmap grab mode, the various informational methods in MediaDet do not work.

The GetBitmapBits or WriteBitmapBits methods also put the object into bitmap grab mode.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaDet.GetBitmapBits Method

The GetBitmapBits method is not supported for Visual Basic.

Syntax

object.GetBitmapBits(
    StreamTime As Double,
    pBufferSize As Long,
    pBuffer As Byte,
    Width As Long,
    Height As Long
)

See Also

  • MediaDet Object


MediaDet.GetSampleGrabber Method

The GetSampleGrabber method is not supported for Visual Basic.

Syntax

object.GetSampleGrabber(
    ppVal As SampleGrabber
)

See Also

  • MediaDet Object


MediaDet.WriteBitmapBits Method

The WriteBitmapBits method retrieves a poster frame at the specified media time and writes it to a file.

Syntax

object.WriteBitmapBits(
    StreamTime As Double,
    Width As Long,
    Height As Long,
    Filename As String
)

Parameters

StreamTime

Time at which to retrieve the poster frame, in seconds.

Width

Width of the poster frame image, in pixels.

Height

Height of the poster frame image, in pixels.

Filename

Path of the file in which to save the poster frame. If the file already exists, this method overwrites it.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | Unexpected error.
STG_E_ACCESSDENIED | Cannot overwrite file.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the Filename and CurrentStream properties.

This method puts the MediaDet object into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the object.

See Also

  • MediaDet Object
  • Error and Success Codes


MediaLocator Object

Provides methods for validating file names in DirectShow Editing Services (DES). You can use the MediaLocator object to ensure that a given file name and path correspond to an existing file. This object also provides a way to search for the file at other locations, and to display an Open dialog box so that the user can locate the file.

The timeline and the render engine also support file name validation through the following methods:

  • AMTimeline.ValidateSourceNames: Validates and updates file names in the timeline.
  • RenderEngine.SetSourceNameValidation: Specifies how the render engine validates file names at rendering time.

Typically, a DES application will call these methods rather than directly create an instance of the MediaLocator object.

This object has the following methods.

Method | Description
AddFoundLocation | Adds a directory to the directory cache.
FindMediaFile | Searches for a file and, if successful, retrieves the path to the file.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


MediaLocator.AddFoundLocation Method

The AddFoundLocation method adds a directory to the directory cache.

Syntax

object.AddFoundLocation(
    DirectoryName As String
)

Parameters

DirectoryName

Directory path to add to the cache.

Error Codes

If the method fails, an error is raised.

Remarks

The MediaLocator object keeps a cache of directory paths where it has successfully found files in past searches. When it successfully locates a file, it adds the directory to the cache.

See Also

  • MediaLocator Object
  • Error and Success Codes


MediaLocator.FindMediaFile Method

The FindMediaFile method searches for a file and, if successful, retrieves the path to the file.

Syntax

object.FindMediaFile(
    Input As String,
    FilterString As String,
    pOutput As String,
    Flags As Long
)

Parameters

Input

File name, including path, where the file was last known to reside. For source objects in the timeline, use the current media name.

FilterString

String containing pairs of filter strings formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box.

pOutput

Variable that receives the actual path to the file, if it differs from the value contained in Input and if the method successfully locates the file.

Flags

Bitwise combination of zero or more of the following flags, from the File Name Validation Flags:

  • SFN_VALIDATEF_NOFIND
  • SFN_VALIDATEF_POPUP
  • SFN_VALIDATEF_TELLME
  • SFN_VALIDATEF_USELOCAL

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_POINTER | NULL pointer argument.

Remarks

If the SFN_VALIDATEF_POPUP flag is specified and the media locator cannot locate the file, this method displays an Open dialog box for the user to locate the file. If the user cancels the dialog box, the method raises an E_FAIL error. Your application should catch this error using an On Error statement:

If Err.Number = &H80004005 Then
    ' Did not locate the file.
End If

If the SFN_VALIDATEF_POPUP flag is not specified, and the media locator cannot locate the file, the method raises an E_FAIL error without displaying the dialog box.

The filter string for the Open dialog box, which is specified by the FilterString parameter, contains internal Null characters. For example, Video\0*.avi\0\0. You can use Chr(0) to specify the Null characters:

sNullStr = Chr(0)
sFilterStr = "Video" + sNullStr + "*.avi" + sNullStr + sNullStr

See Also

  • MediaLocator Object
  • Error and Success Codes


RenderEngine Object

Renders a DirectShow Editing Services (DES) project by constructing a filter graph from a timeline.

DES provides two objects that rendering timelines:

  • The RenderEngine object creates uncompressed output. You can use the output for preview, or route it through compression filters and write it to a file.
  • The SmartRenderEngine object creates compressed output, using smart recompression. With smart recompression, a source file is recompressed only if its format differs from the output format. A source with a matching format is written directly to the output file. Depending on the scenario, smart recompression can greatly improve rendering time.

Although an application can create a filter graph and pass it to a render engine, the typical scenario is for the render engine to create the filter graph. Building the graph is a two-stage process. First, build the front end by calling the ConnectFrontEnd method. Then connect the output pins on the front end to the desired rendering filters:

  • Video and audio renderers for preview, or
  • Compressors, multiplexers, and file writers to generate the final output.

This object has the following methods.

Method | Description
Commit | Not supported for Visual Basic.
ConnectFrontEnd | Builds the front end of the filter graph from the current timeline.
Decommit | Not supported for Visual Basic.
DoSmartRecompression | Not supported for Visual Basic.
GetCaps | Not supported for Visual Basic.
GetFilterGraph | Retrieves the filter graph that the render engine has constructed, if any.
GetGroupOutputPin | Retrieves the output pin for the specified group.
GetTimelineObject | Retrieves the timeline that the render engine is currently using.
GetVendorString | Retrieves the vendor string.
RenderOutputPins | Creates the previewing portion of the filter graph.
SetDynamicReconnectLevel | Sets the level of dynamic reconnection during rendering.
SetFilterGraph | Specifies a filter graph for the render engine to use.
SetInterestRange | Not supported for Visual Basic.
SetInterestRange2 | Not supported for Visual Basic.
SetRenderRange | Not supported for Visual Basic.
SetRenderRange2 | Sets the range of time on the timeline to be rendered.
SetSourceConnectCallback | Not supported for Visual Basic.
SetSourceNameValidation | Specifies how the render engine validates file names.
SetTimelineObject | Sets the timeline for the render engine to use.
ScrapIt | Discards the render engine's filter graph and all associated objects.
UseInSmartRecompressionGraph | Not supported for Visual Basic.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).


RenderEngine.Commit Method

The Commit method is not supported for Visual Basic.

Syntax

object.Commit()

See Also

  • RenderEngine Object


RenderEngine.ConnectFrontEnd Method

The ConnectFrontEnd method builds the front end of the filter graph from the current timeline.

Syntax

object.ConnectFrontEnd()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | No timeline set for this render engine.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because the project was not rendered successfully.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method does not build the rendering portion of the filter graph. The application must connect the output pins on the front end to the desired rendering filters:

  • To preview, call the RenderOutputPins method.
  • To output a file, call GetGroupOutputPin to retrieve the output pin for each group, then connect the pins to a multiplexer filter.

If you are using the RenderEngine object, the output pins on the front end produce uncompressed data. If you are using the SmartRenderEngine object, the output pins produce compressed data.

If you change the timeline after you build the filter graph, you must call ConnectFrontEnd again to rebuild the front end. The method preserves the rendering portion of the graph whenever possible. However, if you add or delete a group, or change the order of the groups, ConnectFrontEnd deletes the rendering portion and your application must rebuild it.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.Decommit Method

The Decommit method is not supported for Visual Basic.

Syntax

object.Decommit()

See Also

  • RenderEngine Object


RenderEngine.DoSmartRecompression Method

The DoSmartRecompression method is not supported for Visual Basic.

Syntax

object.DoSmartRecompression()

See Also

  • RenderEngine Object


RenderEngine.GetCaps Method

The GetCaps method is not supported for Visual Basic.

Syntax

object.GetCaps(
    Index As Long,
    pReturn As Long
)

See Also

  • RenderEngine Object


RenderEngine.GetFilterGraph Method

The GetFilterGraph method retrieves the filter graph that the render engine has constructed, if any.

Syntax

object.GetFilterGraph(
    ppFG As IGraphBuilder
)

Parameters

ppFG

The FilgraphManager object that receives the filter graph.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.GetGroupOutputPin Method

The GetGroupOutputPin method retrieves the output pin for the specified group.

Syntax

object.GetGroupOutputPin(
    Group As Long,
    ppRenderPin As IPin
)

Parameters

Group

Zero-based index that specifies the group.

ppRenderPin

The IPin object that receives the output pin.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. Each group represents a single media stream, and the front end has a corresponding output pin.

You can use this method to create the rendering portion of a file-writing graph. Connect the output pins to multiplexer filters and file writer filters. For more information, see Rendering a Project.

For preview, you don't need to call this method. Just call ConnectFrontEnd followed by RenderOutputPins.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.GetTimelineObject Method

The GetTimelineObject method retrieves the timeline that the render engine is currently using.

Syntax

object.GetTimelineObject(
    ppTimeline As AMTimeline
)

Parameters

ppTimeline

The AMTimeline object that receives the timeline.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.GetVendorString Method

The GetVendorString method retrieves the vendor string.

Syntax

object.GetVendorString() As String

Parameters

This method takes no parameters.

Return Value

Returns a string containing the vendor name.

Error Codes

If the method fails, an error is raised.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.RenderOutputPins Method

The RenderOutputPins method creates the previewing portion of the filter graph.

Syntax

object.RenderOutputPins()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. To perform an operation other than preview, do not call this method. Instead, call GetGroupOutputPin to obtain pointers to the output pins.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.ScrapIt Method

The ScrapIt method discards the render engine's filter graph and all associated objects.

Syntax

object.ScrapIt()

Parameters

This method takes no parameters.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.SetDynamicReconnectLevel Method

The SetDynamicReconnectLevel method sets the level of dynamic reconnection during rendering.

Syntax

object.SetDynamicReconnectLevel(
    Level As Long
)

Parameters

Level

Bitwise combination of zero or more Dynamic Reconnection Flags, specifying the level of dynamic reconnection.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_NOTIMPL | Not implemented.

Remarks

By default, the RenderEngine object loads every source before rendering a project. This can result in a long start-up time. With dynamic reconnection, sources are loaded only when needed. This can shorten the start-up time, but possibly interfere with smooth playback. Generally, the more source clips that a project uses, the more you might benefit from dynamic reconnection.

The SmartRenderEngine object does not implement this method.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.SetFilterGraph Method

The SetFilterGraph method specifies a filter graph for the render engine to use.

Syntax

object.SetFilterGraph(
    pFG As IGraphBuilder
)

Parameters

pFG

The FilgraphManager object that specifies the filter graph.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Most applications do not need to call this method. It is more typical to let the render engine build the graph for you, by calling the ConnectFrontEnd method.

This method fails if the render engine already has a filter graph.

Never retrieve a filter graph created by one render engine and then use it as the parameter to this method on another render engine. Doing so will cause unpredictable results.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.SetInterestRange Method

The SetInterestRange method is not supported for Visual Basic.

Syntax

object.SetInterestRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • RenderEngine Object


RenderEngine.SetInterestRange2 Method

The SetInterestRange2 method is not supported for Visual Basic.

Syntax

object.SetInterestRange2(
    double Start As Double,
    double Stop As Double
)

See Also

  • RenderEngine Object


RenderEngine.SetRenderRange Method

The SetRenderRange method is not supported for Visual Basic.

Syntax

object.SetRenderRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

See Also

  • RenderEngine Object


RenderEngine.SetRenderRange2 Method

The SetRenderRange2 method sets the range of time on the timeline to be rendered. Objects that lie outside the specified range are not rendered, and resources are not allocated for them.

Syntax

object.SetRenderRange2(
    Start As Double,
    Stop As Double
)

Parameters

Start

Start time, in seconds.

Stop

Stop time, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.SetSourceConnectCallback Method

The SetSourceConnectCallback method is not supported for Visual Basic.

Syntax

object.SetSourceConnectCallback(
    pCallback As IGrfCache
)

See Also

  • RenderEngine Object


RenderEngine.SetSourceNameValidation Method

The SetSourceNameValidation method specifies how the render engine validates file names.

Syntax

object.SetSourceNameValidation(
    FilterString As String,
    pOverride As MediaLocator,
    Flags As Long
)

Parameters

FilterString

String containing pairs of filter strings formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box.

pOverride

Optional MediaLocator object to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.

Flags

Bitwise combination of flags taken from the File Name Validation Flags, specifying the behavior of the MediaLocator object. The SFN_VALIDATEF_CHECK flag must be present. The SFN_VALIDATEF_IGNOREMUTED flag has no effect with this method.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the MediaLocator object.

Currently, this method does not validate dynamically loaded sources. See SetDynamicReconnectLevel.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.SetTimelineObject Method

The SetTimelineObject method sets the timeline for the render engine to use.

Syntax

object.SetTimelineObject(
    pTimeline As AMTimeline
)

Parameters

pTimeline

An AMTimeline object that specifies the timeline.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_OUTOFMEMORY | Insufficient memory.

See Also

  • RenderEngine Object
  • Error and Success Codes


RenderEngine.UseInSmartRecompressionGraph Method

The UseInSmartRecompressionGraph method is not supported for Visual Basic.

Syntax

object.UseInSmartRecompressionGraph()

See Also

  • RenderEngine Object


Xml2Dex Object

Saves and loads DirectShow Editing Services (DES) project files in Extensible Markup Language (XML).

This object has the following methods.

Method | Description
CopyXML | Not supported for Visual Basic.
CreateGraphFromFile | Not supported for Visual Basic.
Delete | Not supported for Visual Basic.
PasteXML | Not supported for Visual Basic.
PasteXMLFile | Not supported for Visual Basic.
ReadXML | Not supported for Visual Basic.
ReadXMLFile | Loads an XML project file.
Reset | Not supported for Visual Basic.
WriteGrfFile | Writes a filter graph to a file in .grf format.
WriteXML | Translates a timeline to an XML string.
WriteXMLFile | Translates a timeline to XML and writes the XML data to a file.
WriteXMLPart | Not supported for Visual Basic.

Requirements

Include a reference in your project to "Dexter 1.0 Type Library" (Qedit.dll).

Requires Internet Explorer 4.0 or later.

See Also

  • XTL Reference


Xml2Dex.CopyXML Method

The CopyXML method is not supported for Visual Basic.

Syntax

object.CopyXML(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double
)

See Also

  • Xml2Dex Object


Xml2Dex.CreateGraphFromFile Method

The CreateGraphFromFile method is not supported for Visual Basic.

Syntax

object.CreateGraphFromFile(
    ppGraph As Unknown,
    pTimeline As Unknown,
    FileName As String
)

See Also

  • Xml2Dex Object


Xml2Dex.Delete Method

The Delete method is not supported for Visual Basic.

Syntax

object.Delete(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double
)

See Also

  • Xml2Dex Object


Xml2Dex.PasteXML Method

The PasteXML method is not supported for Visual Basic.

Syntax

object.PasteXML(
    pTimeline As Unknown,
    dStart As Double
)

See Also

  • Xml2Dex Object


Xml2Dex.PasteXMLFile Method

The PasteXMLFile method is not supported for Visual Basic.

Syntax

object.PasteXMLFile(
    pTimeline As Unknown,
    dStart As Double,
    FileName As String
)

See Also

  • Xml2Dex Object


Xml2Dex.ReadXML Method

The ReadXML method is not supported for Visual Basic.

Syntax

object.ReadXML(
    pXML As Unknown
)

See Also

  • Xml2Dex Object


Xml2Dex.ReadXMLFile Method

The ReadXMLFile method loads an XML project file. This method creates instances of all the objects expressed in the XML file and inserts them into the timeline. The method also applies any attributes given for the timeline, such as frame rate or default effect.

Syntax

object.ReadXMLFile(
    pTimeline As Unknown,
    XMLName As String
)

Parameters

pTimeline

The AMTimeline object that receives the timeline.

XMLName

String that specifies the name of the file to load.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
VFW_E_INVALID_FILE_FORMAT | Invalid file format.

Remarks

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object. The following code example shows how to call this method:

Dim objTimeline as New AMTimeline
Dim objXmlParse as New Xml2Dex
objXmlParse.ReadXMLFile objTimeline, "C:\XTL\Example.xtl"

This method does not clear existing objects from the timeline before it inserts the new objects defined in the XML file. If you need to refresh an existing timeline, call AMTimeline.ClearAllGroups first.

See Also

  • Xml2Dex Object
  • Error and Success Codes


Xml2Dex.Reset Method

The Reset method is not supported for Visual Basic.

Syntax

object.Reset()

See Also

  • Xml2Dex Object


Xml2Dex.WriteGrfFile Method

The WriteGrfFile method writes a filter graph to a file in .grf format.

Syntax

object.WriteGrfFile(
    pGraph As Unknown,
    FileName As String
)

Parameters

pGraph

The FilgraphManager object that specifies the filter graph.

FileName

String that specifies the name of the file to write.

Error Codes

If the method fails, an error is raised.

Remarks

The pGraph parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents a FilgraphManager object. GraphEdit files are intended for debugging use only. For more information, see Simulating Graph Building with GraphEdit.

See Also

  • Xml2Dex Object
  • Error and Success Codes


Xml2Dex.WriteXML Method

The WriteXML method translates a timeline to an XML string.

Syntax

object.WriteXML(
    pTimeline As Unknown,
    pbstrXML As String
)

Parameters

pTimeline

AMTimeline object that specifies the timeline.

pbstrXML

Variable that receives the translated XML string.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

Value | Description
E_OUTOFMEMORY | Insufficient memory.

Remarks

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object.

Code Example

Dim objTimeline As New AMTimeline
' Create timeline (not shown).

Dim objXmlParser As New Xml2Dex
Dim sXml As String
objXmlParser.WriteXml objTimeline, sXml

See Also

  • Xml2Dex Object
  • Error and Success Codes


Xml2Dex.WriteXMLFile Method

The WriteXMLFile method translates a timeline to XML and writes the XML data to a file.

Syntax

object.WriteXMLFile(
    pTimeline As Unknown,
    FileName As String
)

Parameters

pTimeline

The AMTimeline object that specifies the timeline.

FileName

String that specifies the name of the file to write.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

Value | Description
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Remarks

This method generates an XML file that represents all the components in the timeline.

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object.

Code Example

Dim objTimeline As New AMTimeline
' Create timeline (not shown).

Dim objXmlParser As New Xml2Dex
objXmlParser.WriteXmlFile objTimeline, "C:\XTL\Example.xtl"

See Also

  • Xml2Dex Object
  • Error and Success Codes


Xml2Dex.WriteXMLPart Method

The WriteXMLPart method is not supported for Visual Basic.

Syntax

object.WriteXMLPart(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double,
    FileName As String
)

See Also

  • Xml2Dex Object


Stream Buffer Engine Reference

This topic applies to Windows XP Service Pack 1 only.

This section contains the following subsections:

  • Stream Buffer Engine Objects
  • Stream Buffer Engine Filters
  • Stream Buffer Engine Interfaces
  • Stream Buffer Engine Structures
  • Stream Buffer Engine Enumeration Types
  • Stream Buffer Engine Event Codes

See Also

  • Using the Stream Buffer Engine


Stream Buffer Engine Objects

This topic applies to Windows XP Service Pack 1 only.

The stream buffer engine consists of the following objects.

Object | Description
RecComp | Creates new recordings by concatenating existing recordings.
Recording | Creates permanent recordings.
StreamBufferConfig | Configures the Stream Buffer Engine, by setting the location, number, and size of the temporary backing files.

See Also

  • Stream Buffer Engine Reference


RecComp Object

This topic applies to Windows XP Service Pack 1 only.

The RecComp object creates new content recordings by concatenating existing recordings.

CLSID | CLSID_StreamBufferComposeRecording
Interface | IStreamBufferRecComp

See Also

  • Creating Stream Buffer Recordings
  • Stream Buffer Engine Objects


Recording Object

This topic applies to Windows XP Service Pack 1 only.

The Recording object creates permanent recordings from streams that the Stream Buffer Sink filter captures.

CLSID | Not applicable; see Remarks.
Interfaces | IStreamBufferRecordControl, IStreamBufferRecordingAttribute

Remarks

To create this object, call the IStreamBufferSink::CreateRecorder method on the Stream Buffer Sink filter.

After making a recording, stop the Recording object and release it before releasing the Stream Buffer Sink filter.

See Also

  • Creating Stream Buffer Recordings
  • Stream Buffer Engine Objects


StreamBufferConfig Object

This topic applies to Windows XP Service Pack 1 only.

The StreamBufferConfig object configures the Stream Buffer Engine. It enables an application to set the location, number, and size of the temporary backing files.

CLSID | CLSID_StreamBufferConfig
Interfaces | IStreamBufferConfigure, IStreamBufferInitialize

See Also

  • Stream Buffer Engine Objects


Stream Buffer Engine Filters

This topic applies to Windows XP Service Pack 1 only.

The stream buffer engine uses the following DirectShow filters.

Filter | Description
MPEG-2 Video Analyzer | Enables playback at > 4x speed, and enables reverse playback for MPEG-2 sources.
Stream Buffer Sink | Stores streamed content for the Stream Buffer Source filter to read.
Stream Buffer Source | Reads content that the Stream Buffer Sink filter has stored.


MPEG-2 Video Analyzer Filter

This topic applies to Windows XP Service Pack 1 only.

The MPEG-2 Video Analyzer filter enables playback rates faster than 4x and reverse playback when the Stream Buffer Engine is streaming an MPEG-2 source. Insert this filter directly between the MPEG-2 Demultiplexer and the Stream Buffer Sink filter.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_MPEG2_VIDEO
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Must match input type.
Output Pin Interfaces | IQualityControl, IPin
Filter CLSID | CLSID_Mpeg2VideoStreamAnalyzer
Property Page CLSID | Not applicable
Executable | Sbe.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory

See Also

  • Creating Stream Buffer Graphs
  • Stream Buffer Engine Filters


Stream Buffer Sink Filter

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Sink filter is the sink filter for the Stream Buffer Engine. It stores streamed content for the Stream Buffer Source filter to read.

Filter Interfaces | IBaseFilter, ISpecifyPropertyPages, IStreamBufferInitialize, IStreamBufferSink
Input Pin Media Types Video:
  • MEDIATYPE_Video
  • MEDIASUBTYPE_MPEG2_VIDEO
  • MEDIASUBTYPE_dvsd

Audio and Data: All types accepted.
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | CLSID_StreamBufferSink
Property Page CLSID | Not applicable
Executable | Sbeio.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory

Remarks

Note If Stream Buffer Sink is stopped and restarted, the render graph will lose context and be unable to access the capture graph. However, the tuner can change channels while the graph is running without problems.

See Also

  • Stream Buffer Engine Filters
  • Using the Stream Buffer Engine


Stream Buffer Source Filter

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Source filter is the source filter for the Stream Buffer Engine. It reads content that the Stream Buffer Sink filter has stored.

Filter Interfaces | IAMFilterMiscFlags, IBaseFilter, IFileSourceFilter, ISpecifyPropertyPages, IStreamBufferMediaSeeking, IStreamBufferInitialize, IStreamBufferSource.
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types Video:
  • MEDIATYPE_Video
  • MEDIASUBTYPE_MPEG2_VIDEO
  • MEDIASUBTYPE_dvsd

Audio and Data: All types accepted.
Output Pin Interfaces | IMediaSeeking (see Remarks), IQualityControl, IPin
Filter CLSID | CLSID_StreamBufferSource
Property Page CLSID | Not applicable.
Executable | Sbe.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory

Remarks

The Stream Buffer Source filter supports the IMediaSeeking interface for completed recordings only. For live content, use the IStreamBufferMediaSeeking interface, which has the same methods but defines slightly different semantics. This reflects the fact that live content continuously grows on one end, as the show is being recorded, and shrinks on the other end, as backing files are deleted.

You can use the IStreamBufferMediaSeeking interface with completed recordings, but do not mix IStreamBufferMediaSeeking calls and IMediaSeeking calls. After the first call to an IStreamBufferMediaSeeking method, the filter will fail any subsequent calls to IMediaSeeking methods and will also fail any subsequent QueryInterface calls for the IMediaSeeking interface.

To use the IStreamBufferMediaSeeking methods, an application should query the filter directly. To use the IMediaSeeking methods, the application should query the Filter Graph Manager. The Filter Graph Manager routes the seek commands to the filter, as described in Seeking.

See Also

  • Stream Buffer Engine Filters
  • Using the Stream Buffer Engine


Stream Buffer Engine Interfaces

This topic applies to Windows XP Service Pack 1 only.

Applications use the following interfaces for building stream buffer engine graphs in addition to the base filter interfaces.

Interface | Description
IEnumStreamBufferRecordingAttrib | Enumerates a collection of attributes on a stream buffer file.
IStreamBufferConfigure | Configures the location, number, and size of the backing files used by the various stream buffer objects.
IStreamBufferInitialize | Configures the stream buffer filters.
IStreamBufferMediaSeeking | Controls seeking in a stream buffer source graph.
IStreamBufferRecComp | Creates new content recordings by concatenating existing recordings.
IStreamBufferRecordControl | Controls Recording objects
IStreamBufferRecordingAttribute | Sets and retrieves attributes on a stream buffer recording.
IStreamBufferSink | Controls the Stream Buffer Sink filter.
IStreamBufferSource | Controls the Stream Buffer Source filter.


IEnumStreamBufferRecordingAttrib Interface

This topic applies to Windows XP Service Pack 1 only.

The IEnumStreamBufferRecordingAttrib interface enumerates a collection of attributes on a stream buffer file. Attributes are metadata that describe the physical file (such as the bit rate and the duration) or the content of the file (such as the author or title). To obtain this interface, call the IStreamBufferRecordingAttribute::EnumAttributes method.

This interface implements a standard Component Object Model (COM) collection object. For more information on COM collections, see the IEnumXXXX topic in the Microsoft Platform SDK. The collection object represents a snapshot of the attributes when the collection is created; the collection is not updated automatically.

In addition to the methods inherited from IUnknown, the IEnumStreamBufferRecordingAttrib interface exposes the following methods.

Method | Description
Clone | Makes a copy of the enumerator object.
Next | Retrieves a specified number of attributes in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of attributes.

Requirements

Include Sbe.h.


IEnumStreamBufferRecordingAttrib::Clone

This topic applies to Windows XP Service Pack 1 only.

The Clone method makes a copy of the enumerator object. The returned object starts with the same enumeration state as the original.

Syntax

HRESULT Clone(
    IEnumStreamBufferRecordingAttrib **ppIEnumStreamBufferAttrib
);

Parameters

ppIEnumStreamBufferAttrib

[out] Address of a variable that receives a pointer to the IEnumStreamBufferRecordingAttrib interface of the new enumerator.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Requirements

Include Sbe.h.

See Also

  • IEnumStreamBufferRecordingAttrib Interface


IEnumStreamBufferRecordingAttrib::Next

This topic applies to Windows XP Service Pack 1 only.

The Next method returns a specified number of attributes in the enumeration sequence.

Syntax

HRESULT Next(
    ULONG cRequest,
    STREAMBUFFER_ATTRIBUTE *pStreamBufferAttribute,
    ULONG *pcReceived
);

Parameters

cRequest

[in] The number of attributes to retrieve.

pStreamBufferAttribute

[in, out, size_is(cRequest)] Pointer to an array of size cRequest. The array is filled with STREAMBUFFER_ATTRIBUTE structures.

pcReceived

[out] Pointer to a variable that receives the number of attributes that are returned in the pStreamBufferAttribute array. This parameter can be NULL if cRequest is 1.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
S_FALSE | Did not retrieve as many attributes as requested (reached the end of the enumeration).
S_OK | Success.

Remarks

The caller allocates the array of STREAMBUFFER_ATTRIBUTE structures, but the method allocates buffers for the attributes and the attribute names, which are contained in the pszName and pbAttribute members of each structure. The caller must release those buffers, by calling CoTaskMemFree.

Requirements

Include Sbe.h.

See Also

  • IEnumStreamBufferRecordingAttrib Interface


IEnumStreamBufferRecordingAttrib::Reset

This topic applies to Windows XP Service Pack 1 only.

The Reset method resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value.

Requirements

Include Sbe.h.

See Also

  • IEnumStreamBufferRecordingAttrib Interface


IEnumStreamBufferRecordingAttrib::Skip

This topic applies to Windows XP Service Pack 1 only.

The Skip method skips over a specified number of attributes.

Syntax

HRESULT Skip(
    ULONG cRecords
);

Parameters

cRecords

[in] The number of attributes to skip.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Skipped past the end of the sequence.
S_OK | Success.

Requirements

Include Sbe.h.

See Also

  • IEnumStreamBufferRecordingAttrib Interface


IStreamBufferConfigure Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferConfigure interface configures the location, number, and size of the backing files used by the various stream buffer objects.

The StreamBufferConfig object exposes this interface.

Before calling any of the Set methods on this interface, you must specify a registry key to hold the new settings. For more information, see IStreamBufferInitialize::SetHKEY.

In addition to the methods inherited from IUnknown, the IStreamBufferConfigure interface exposes the following methods.

Method | Description
GetBackingFileCount | Retrieves the maximum and minimum number of backing files.
GetBackingFileDuration | Retrieves the backing file size, in seconds.
GetDirectory | Retrieves the directory where backing files are saved.
SetBackingFileCount | Sets the maximum and minimum number of backing files.
SetBackingFileDuration | Sets the backing file size, in seconds.
SetDirectory | Sets the directory where backing files are saved.

Requirements

Include Sbe.h.


IStreamBufferConfigure::GetBackingFileCount

This topic applies to Windows XP Service Pack 1 only.

The GetBackingFileCount method retrieves the maximum and minimum number of backing files.

Syntax

HRESULT GetBackingFileCount(
  DWORD*  pdwMin,
  DWORD*  pdwMax
);

Parameters

pdwMin

[out] Pointer to a variable that receives the backing file minimum.

pdwMax

[out] Pointer to a variable that receives the backing file maximum.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

If the reader lags behind the writer by more than pdwMin files, the writer starts to send STREAMBUFFER_EC_CONTENT_BECOMING_STALE events. If the reader lags behind the writer by more than pdwMax files, the writer begins to overwrite files and sends an STREAMBUFFER_EC_STALE_FILE_DELETED event.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferConfigure::GetBackingFileDuration

This topic applies to Windows XP Service Pack 1 only.

The GetBackingFileDuration method retrieves the duration of each backing file.

Syntax

HRESULT GetBackingFileDuration(
  DWORD*  pdwSeconds
);

Parameters

pdwSeconds

[out] Pointer to a variable that receives the file duration, in seconds.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferConfigure::GetDirectory

This topic applies to Windows XP Service Pack 1 only.

The GetDirectory method retrieves the directory where backing files are saved.

Syntax

HRESULT GetDirectory(
  LPWSTR*  ppszDirectoryName
);

Parameters

ppszDirectoryName

[out] Pointer to a variable that receives the fully qualified directory name.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The caller must free the returned string by calling CoTaskMemFree.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferConfigure::SetBackingFileCount

This topic applies to Windows XP Service Pack 1 only.

The SetBackingFileCount method sets the maximum and minimum number of backing files.

Syntax

HRESULT SetBackingFileCount(
  DWORD  dwMin,
  DWORD  dwMax
);

Parameters

dwMin

[in] Specifies the backing file minimum. The valid range is from 4 to 100.

dwMax

[in] Specifies the backing file maximum. The valid range is from 6 to 102, and the value must be at least 2 greater than dwMin.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
E_UNEXPECTED | The StreamBufferConfig object was not initialized.
S_OK | The method succeeded.

Remarks

If the reader lags behind the writer by more than dwMin files, the writer starts to send STREAMBUFFER_EC_CONTENT_BECOMING_STALE events. If the reader lags behind the writer by more than dwMax files, the writer begins to overwrite files and sends an STREAMBUFFER_EC_STALE_FILE_DELETED event.

Before calling this method, call IStreamBufferInitialize::SetHKEY to specify a registry key where the information will be stored.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferConfigure::SetBackingFileDuration

This topic applies to Windows XP Service Pack 1 only.

The SetBackingFileDuration method sets the duration of all backing files.

Syntax

HRESULT SetBackingFileDuration(
  DWORD  dwSeconds
);

Parameters

dwSeconds

[in] Specifies the file duration, in seconds. The minimum value is 15.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
E_UNEXPECTED | The StreamBufferConfig object was not initialized.
S_OK | The method succeeded.

Remarks

Before calling this method, call IStreamBufferInitialize::SetHKEY to specify a registry key where the information will be stored.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferConfigure::SetDirectory

This topic applies to Windows XP Service Pack 1 only.

The SetDirectory method sets the directory where backing files are saved.

Syntax

HRESULT SetDirectory(
  LPCWSTR  pszDirectoryName
);

Parameters

pszDirectoryName

[in] Pointer to a null-terminated string containing the fully qualified directory name. If the specified directory does not exist, it will be created.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
E_UNEXPECTED | The StreamBufferConfig object was not initialized.
S_OK | The method succeeded.

Remarks

Before calling this method, call IStreamBufferInitialize::SetHKEY to specify a registry key where the information will be stored.

The specified directory is used to store backing files. If no directory is specified, the files are saved in a hidden system directory inside the Temp directory. This directory is not used to store files created by Recording objects; those files are stored in a directory specified by the IStreamBufferSink::CreateRecorder method.

Backing files are created as hidden sytem files.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferConfigure Interface


IStreamBufferInitialize Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferInitialize interface is used to configure the stream buffer filters. The Stream Buffer Source filter, Stream Buffer Sink filter, and StreamBufferConfig object all expose this interface.

In addition to the methods inherited from IUnknown, the IStreamBufferInitialize interface exposes the following methods.

Method | Description
SetHKEY | Sets the registry key where the object stores configuration information.
SetSIDs | Sets the security identifiers (SIDs) that are used to protect access to the backing files.

Requirements

Include Sbe.h.


IStreamBufferInitialize::SetHKEY

This topic applies to Windows XP Service Pack 1 only.

The SetHKEY method sets the registry key where the stream buffer object stores its configuration information.

Syntax

HRESULT SetHKEY(
  HKEY  hkeyRoot
);

Parameters

hkeyRoot

[in] Handle to the registry key.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.
E_UNEXPECTED | SetHKEY was called on a filter after it initialized internally.

Remarks

This method enables an application to specify a registry key where the stream buffer objects will save configuration information, including the location of the backing files, the number of backing files, and their size.

You must call this method before the object is initialized, either explicitly or implicitly. For the Stream Buffer Sink filter, call the method before the profile is locked. For the Stream Buffer Source filter, call the method before setting the source file name.

To use this method, do the following:

  1. Create a new registry key or open an existing key.
  2. Create an instance of the StreamBufferConfig object.
  3. Query the StreamBufferConfig object for the IStreamBufferInitialize interface.
  4. Call SetHKey on the StreamBufferConfig object, with a handle to the registry key.
  5. Optionally, call IStreamBufferConfigure methods to modify the configuration information that will be stored in the registry key.
  6. Call SetHKey on the Stream Buffer Source filter and the Stream Buffer Sink filter, using the same registry key.

The application is responsible for ensuring that the user has read/write permissions for the registry key.

The caller may release the registry key handle after calling this method.

Example Code

The following code shows how to configure the backing file directory. Error checking is omitted for brevity.

// Create the StreamBufferConfig object.
CComPtr<IStreamBufferConfigure> pConfig;
hr = pConfig.CoCreateInstance(CLSID_StreamBufferConfig);

// Create a new registry key to hold our settings.
HKEY hkey = 0;
long lRes = RegCreateKey(HKEY_LOCAL_MACHINE,
    TEXT("SOFTWARE\\MyStreamBufferKey"), &hkey);

// Set the registry key.
CComPtr<IStreamBufferInitialize> pInit;
hr = pConfig.QueryInterface(&pInit);
hr = pInit->SetHKEY(hkey);
pInit.Release();

// Set the backing file directory.
hr = pConfig->SetDirectory(L"C:\\MyDirectory");

// Create the Stream Buffer Sink filter and set the registry key.
CComPtr<IStreamBufferSink> pSink;
hr = pSink.CoCreateInstance(CLSID_StreamBufferSink);
hr = pSink.QueryInterface(&pInit);
hr = pInit->SetHKEY(hkey);
pInit.Release();

// Create the Stream Buffer Source filter and set the registry key.
CComPtr<IStreamBufferSource> pSource;
hr = pSource.CoCreateInstance(CLSID_StreamBufferSource);
hr = pSource.QueryInterface(&pInit);
hr = pInit->SetHKEY(hkey);

Requirements

Include Sbe.h.

See Also

  • IStreamBufferInitialize Interface


IStreamBufferInitialize::SetSIDs

This topic applies to Windows XP Service Pack 1 only.

The SetSIDs method sets the security identifiers (SIDs) that are used to protect access to the backing files.

Syntax

HRESULT SetSIDs(
  DWORD  cSIDs,
  PSID  *ppSID
);

Parameters

cSIDs

[in] Specifies the size of the array given in the ppSID parameter.

ppSID

[in] Pointer to an array of SID structures, of size cSIDs.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
S_OK | The method succeeded.

Remarks

At run time, the Stream Buffer Source and Sink filters create various Win32 objects, such as mutexes, so that access to the backing files is synchronized across threads. Each of the filters maintains a list of SIDs that are used to protect these objects. By default, the filters inherit their SIDs from the hosting process. An application can use the SetSIDs method to override the default SIDs.

If you call this method, do so before locking the sink filter or loading a file in the source filter. It is recommended that all of the filters be given the same SIDs.

Important Setting less-privileged SIDs can create a security vulnerability.

Note that this method does not apply to content recording files, which are protected by the discretionary access-control lists (DACLs) of the directory structure.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferInitialize Interface


IStreamBufferRecComp Interface

The IStreamBufferRecComp interface is used to create new content recordings by concatenating existing recordings. The new recording can be created from a mix of reference and content recordings.

The Stream Buffer RecComp object exposes this interface.

In addition to the methods inherited from IUnknown, the IStreamBufferRecComp interface exposes the following methods.

Method | Description
Append | Appends an entire recording to the target file.
AppendEx | Appends part of a recording to the target file.
Cancel | Cancels an append operation, if one is in progress.
Close | Closes the target file.
GetCurrentLength | Retrieves the length of the target file.
Initialize | Sets the file name and the profile for the new recording.

Requirements

Include Sbe.h.


IStreamBufferRecComp::Append

The Append method appends an entire recording to the target file.

Syntax

HRESULT Append(
    LPCWSTR pszSBRecording,

);

Parameters

pszSBRecording

[in] Null-terminated, wide character string that contains the name of the file to append.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Remarks

The file specified in pszSBRecording must be completed. If the file is live, the method fails. Also, the file's profile must match the one that was configured in the Initialize method.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecComp::AppendEx

The AppendEx method appends part of a recording to the target file.

Syntax

HRESULT AppendEx(
    LPCWSTR pszSBRecording,
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtStop
);

Parameters

pszSBRecording

[in] Null-terminated, wide character string that contains the name of the file to append.

rtStart

[in] Specifies the start time of the segment to append, in 100-nanosecond units.

rtStop

[in] Specifies the stop time of the segment to append, in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Remarks

The file specified in pszSBRecording must be completed. If the file is live, the method fails. Also, the file's profile must match the one that was configured in the Initialize method.

The value of rtStop must be at least 2 seconds (20000000) greater than rtStart.

The caller must validate rtStart and rtStop before calling this method. The method will not automatically correct the times if they fall past the end of the file.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecComp::Cancel

The Cancel method cancels an append operation, if one is in progress. Otherwise, it has no effect.

Syntax

HRESULT Cancel(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecComp::Close

The Close method closes the target file.

Syntax

HRESULT Close(void);

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Remarks

This method is called automatically when the RecComp object is released.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecComp::GetCurrentLength

The GetCurrentLength method retrieves the length of the target file.

Syntax

HRESULT GetCurrentLength(
    DWORD *pcSeconds
);

Parameters

pcSeconds

[out] Pointer to a variable that receives the current length, in seconds.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Remarks

To get accurate updates, you can call this method continually from one thread while another thread performs append operations.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecComp::Initialize

The Initialize method sets the file name and the profile for the new recording. Call this method once, after creating the RecComp object.

Syntax

HRESULT Initialize(
    LPCWSTR pszTargetFilename,
    LPCWSTR pszSBRecProfileRef
);

Parameters

pszTargetFilename

[in] Null-terminated, wide character string that specifies the file name of the new recording.

pszSBRecProfileRef

[in] Null-terminated, wide character string that specifies an existing file. This file must be a complete recording, already created by the Stream Buffer Engine.

Return Values

Returns an HRESULT value. Possible values include those in the following table.

Value | Description
S_OK | Success

Remarks

The profile of the file specified by pszSBRecProfileRef will be used for the target file. All files that are appended to the target file must have the same profile. For more information about profiles, see IStreamBufferSink::LockProfile.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecComp Interface


IStreamBufferRecordControl Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferRecordControl interface is used to control stream buffer Recording objects.

Use the IStreamBufferSink::CreateRecorder method on the Stream Buffer Sink filter to create new Recording objects. After making a recording, stop the Recording object and release it before releasing the Stream Buffer Sink filter.

In addition to the methods inherited from IUnknown, the IStreamBufferRecordControl interface exposes the following methods.

Method | Description
GetRecordingStatus | Retrieves the status of the Recording object.
Start | Starts a recording at a specified time.
Stop | Ends a recording at a specified time.

Requirements

Include Sbe.h.

See Also

  • Creating Stream Buffer Recordings


IStreamBufferRecordControl::GetRecordingStatus

This topic applies to Windows XP Service Pack 1 only.

The GetRecordingStatus method retrieves the status of the recording.

Syntax

HRESULT GetRecordingStatus(
  HRESULT*  phLastResult,
  BOOL*  pbStarted,
  BOOL*  pbStopped
);

Parameters

phLastResult

[out] Pointer to a variable that receives an HRESULT value. The HRESULT value indicates the current status of writing or closing the file. This parameter can be NULL.

pbStarted

[out] Pointer to a variable that receives a Boolean value, indicating whether the recording has started,

Value | Description
TRUE | The recording has started.
FALSE | The recording has not started.

This parameter can be NULL.

pbStopped

[out] Pointer to a variable that receives a Boolean value, indicating whether recording has been stopped.

Value | Description
TRUE | The recording has stopped.
FALSE | The recording has not stopped, or has not started yet.

This parameter can be NULL.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

This method reports the status of the Start and Stop methods, which themselves are asynchronous.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordControl Interface


IStreamBufferRecordControl::Start

This topic applies to Windows XP Service Pack 1 only.

The Start method starts the recording.

Syntax

HRESULT Start(
  REFERENCE_TIME  *prtStart
);

Parameters

prtStart

[in, out] Pointer to a variable that contains the start time. The time is relative to the current stream time, in 100-nanosecond units. The value zero represents now; negative values are in the past; and positive values are in the future.

  • For content recordings, the time must be a value between 0 and 5 seconds (50000000), inclusive. Negative times are not valid.
  • For reference recordings, negative times are valid if they fall within existing content. If the time given in prtStart is earlier than the earliest valid content, the actual start time of the content is used instead. This value is returned in prtStart when the method returns.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
E_INVALIDARG | Invalid time.
E_POINTER | NULL pointer argument.
S_OK | The method succeeded.

Remarks

The start time must be less than or equal to the stop time.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordControl Interface
  • IStreamBufferRecordControl::Stop


IStreamBufferRecordControl::Stop

This topic applies to Windows XP Service Pack 1 only.

The Stop method stops the recording and closes the file.

Syntax

HRESULT Stop(
  REFERENCE_TIME  rtStop
);

Parameters

rtStop

[in] Specifies when the recording stops. The time is relative to the current stream time, in 100-nanosecond units. The value zero represents now; negative values are in the past; and positive values are in the future.

  • For content recordings, the valid range is from 0 to 5 seconds (50000000), inclusive. Negative times are not valid.
  • For reference recordings, a negative time is valid if it falls within valid recorded content.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The stop time must be greater than or equal to the start time.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordControl Interface
  • IStreamBufferRecordControl::Start


IStreamBufferRecordingAttribute Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferRecordingAttribute interface sets and retrieves attributes on a stream buffer recording. Attributes are metadata that describe the physical file (such as the bitrate and the duration) or the content of the file (such as the author or title).

The stream buffer Recording object exposes this interface.

In addition to the methods inherited from IUnknown, the IStreamBufferRecordingAttribute interface exposes the following methods.

Method | Description
EnumAttributes | Enumerates the existing attributes of the stream buffer file.
GetAttributeByIndex | Retrieves an attribute, specified by index number.
GetAttributeByName | Retrieves an attribute, specified by name.
GetAttributeCount | Returns the number of attributes that are currently defined for this stream buffer file.
SetAttribute | Sets an attribute on the stream buffer file.

Requirements

Include Sbe.h.


IStreamBufferRecordingAttribute::EnumAttributes

This topic applies to Windows XP Service Pack 1 only.

The EnumAttributes method enumerates the existing attributes of the stream buffer file. This method returns an enumerator object, which the caller can then use to enumerate the attributes.

Syntax

HRESULT EnumAttributes(
    IEnumStreamBufferRecordingAttrib **ppIEnumStreamBufferAttrib
);

Parameters

ppIEnumStreamBufferAttrib

[out] Address of a variable that receives an IEnumStreamBufferRecordingAttrib interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The caller must release the returned IEnumStreamBufferRecordingAttrib interface.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface


IStreamBufferRecordingAttribute::GetAttributeByIndex

This topic applies to Windows XP Service Pack 1 only.

The GetAttributeByIndex method retrieves an attribute, specified by index number.

Syntax

HRESULT GetAttributeByIndex(
    WORD wIndex,
    ULONG *pulReserved,
    WCHAR *pszAttributeName,
    WORD *pcchNameLength,
    STREAMBUFFER_ATTR_DATATYPE *pStreamBufferAttributeType,
    BYTE *pbAttribute,
    WORD *pcbLength
);

Parameters

wIndex

[in] Zero-based index of the attribute to retrieve.

pulReserved

[in] Reserved. Set this parameter to zero.

pszAttributeName

[out] Pointer to a buffer that receives the name of the attribute, as a null-terminated wide-character string. Specify the size of the buffer in the pcchNameLength parameter. To find out the required size for the array, set pszAttributeName to NULL and check the value that is returned in pcchNameLength.

pcchNameLength

[in,out] On input, specifies the size of the buffer given in pszAttributeName, in wide characters. On output, contains the number of characters that were copied to the buffer, including the null terminator. Remember that wide characters are two bytes each.

pStreamBufferAttributeType

[out] Pointer to a variable that receives a member of the STREAMBUFFER_ATTR_DATATYPE enumeration. This value indicates the data type that you should use to interpret the attribute, which is returned in the pbAttribute parameter.

pbAttribute

[out] Pointer to a buffer that receives the attribute, as an array of bytes. Specify the size of the buffer in the pcbLength parameter. To find out the required size for the array, set pbAttribute to NULL and check the value that is returned in pcbLength.

pcbLength

[in,out] On input, specifies the size of the buffer given in pbAttribute, in bytes. On output, contains the number of bytes that were copied to the buffer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_E_BUFFER_OVERFLOW | One or both of the buffers is too small.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface


IStreamBufferRecordingAttribute::GetAttributeByName

This topic applies to Windows XP Service Pack 1 only.

The GetAttributeByName method retrieves an attribute, specified by name.

Syntax

HRESULT GetAttributeByName(
    LPCWSTR pszAttributeName,
    ULONG *pulReserved,
    STREAMBUFFER_ATTR_DATATYPE *pStreamBufferAttributeType,
    BYTE *pbAttribute,
    WORD *pcbLength
);

Parameters

pszAttributeName

[in] Wide-character string that contains the name of the attribute.

pulReserved

[in] Reserved. Set this parameter to zero.

pStreamBufferAttributeType

[out] Pointer to a variable that receives a member of the STREAMBUFFER_ATTR_DATATYPE enumeration. This value indicates the data type that you should use to interpret the attribute, which is returned in the pbAttribute parameter.

pbAttribute

[out] Pointer to a buffer that receives the attribute, as an array of bytes. Specify the size of the buffer in the pcbLength parameter. To find out the required size for the array, set pbAttribute to NULL and check the value that is returned in pcbLength.

pcbLength

[in,out] On input, specifies the size of the buffer given in pbAttribute, in bytes. On output, contains the number of bytes that were copied to the buffer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_OK | Success.
VFW_E_BUFFER_OVERFLOW | The buffer given in pbAttribute is too small.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface


IStreamBufferRecordingAttribute::GetAttributeCount

This topic applies to Windows XP Service Pack 1 only.

The GetAttributeCount method returns the number of attributes that are currently defined for this stream buffer file.

Syntax

HRESULT GetAttributeCount(
    ULONG ulReserved,
    WORD *pcAttributes
);

Parameters

ulReserved

[in] Reserved. Set this parameter to zero.

pcAttributes

[out] Pointer to a variable that receives the number of attributes.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument
S_OK | Success

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface


IStreamBufferRecordingAttribute::SetAttribute

This topic applies to Windows XP Service Pack 1 only.

The SetAttribute method sets an attribute on the stream buffer file.

Syntax

HRESULT SetAttribute(
    ULONG ulReserved,
    LPCWSTR pszAttributeName,
    STREAMBUFFER_ATTR_DATATYPE StreamBufferAttributeType,
    BYTE *pbAttribute,
    WORD cbAttributeLength
);

Parameters

ulReserved

[in] Reserved. Set this parameter to zero.

pszAttributeName

[in] Wide-character string that contains the name of the attribute.

StreamBufferAttributeType

[in] Member of the STREAMBUFFER_ATTR_DATATYPE enumeration that defines the data type of the attribute data.

pbAttribute

[in] Pointer to a buffer that contains the attribute data.

cbAttributeLength

[in] The size of the buffer specified in pbAttribute.

Return Values

Returns an HRESULT value.

Remarks

If an attribute with that name already exists, the method overwrites it with the new value.

The method fails if the recorder object is already recording.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface
  • IStreamBufferRecordControl::Start


IStreamBufferSink Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferSink interface is exposed by the Stream Buffer Sink filter. Use this interface to lock the filter before capture and to create new recordings.

In addition to the methods inherited from IUnknown, the IStreamBufferSink interface exposes the following methods.

Method | Description
CreateRecorder | Creates a Recording object for permanent file storage.
IsProfileLocked | Indicates whether the profile has been locked.
LockProfile | Locks a graph profile, preventing input streams from changing, and optionally specifies the buffer file's name and location.

Requirements

Include Sbe.h.

See Also

  • Using the Stream Buffer Engine


IStreamBufferSink::CreateRecorder

This topic applies to Windows XP Service Pack 1 only.

The CreateRecorder method creates a new Recording object. Recording objects are used to create permanent files from the stream buffer.

Syntax

HRESULT CreateRecorder(
  LPCWSTR  pszFilename,
  DWORD  dwType,
  IUnknown**  pRecordingIUnknown
);

Parameters

pszFilename

[in] Pointer to a null-terminated wide-character string that contains the file name for the recording.

dwType

[in] Indicates the type of recording to create, either a reference recording or a content recording. Specify one of the following values.

Value | Description
RECORDING_TYPE_REFERENCE | Reference recording. A reference recording is created from temporary backing files that have already been recorded. It uses a stub file to reference the existing files. Because a reference recording refers to existing content, the start time can be in the past.
RECORDING_TYPE_CONTENT | Content recording. A content recording saves content into a new file. Because the content must be new, the start time cannot be in the past.

pRecordingIUnknown

[out] Address of a variable that receives a pointer to the Recording object's IUnknown interface.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The Stream Buffer Sink filter's profile must be locked, either explicitly or implicitly, before you call this method. For more information, see IStreamBufferSink::LockProfile.

The returned IUnknown interface has an outstanding reference count. The caller must release the interface.

Requirements

Include Sbe.h.

See Also

  • Creating Stream Buffer Recordings
  • IStreamBufferSink Interface


IStreamBufferSink::IsProfileLocked

This topic applies to Windows XP Service Pack 1 only.

The IsProfileLocked method queries whether the Stream Buffer Sink filter's profile is locked.

Syntax

HRESULT IsProfileLocked();

Parameters

This method takes no parameters.

Return Values

Returns an HRESULT. Possible values include those in the following table.

Value | Description
S_OK | The profile is locked.
S_FALSE | The profile is not locked.
E_FAIL | The method failed.

Remarks

When the filter's profile is locked, the number of streams and their media types are fixed. For more information, see IStreamBufferSink::LockProfile.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferSink Interface


IStreamBufferSink::LockProfile

This topic applies to Windows XP Service Pack 1 only.

The LockProfile method locks the Stream Buffer Sink filter's profile, thereby fixing the number of streams and their media types. This method can also specify the name and location of the stub file that points to the backing files.

Syntax

HRESULT LockProfile(
  LPCWSTR  pszFilename
);

Parameters

pszFileName

[in] Pointer to a null-terminated wide-character string that specifies the full path name of the stub file. If the specified file already exists, the method fails. If pszFilename is NULL, the stub file is created in the current directory with a default file name.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_UNEXPECTED | The call failed, possibly because it was called with a non-null file name more than once.
VFW_E_UNSUPPORTED_STREAM | The call failed because there are no streams in the profile.

Remarks

The profile describes the number of input streams, their media types, and the location of the stub file that points to the temporary backing files. The profile must be locked before the Stream Buffer Source filter can read data from the backing files. Applications can lock the profile explicitly by calling the LockProfile method, or implicitly by running the filter graph that contains the Stream Buffer Sink filter.

After the profile is locked, the Stream Buffer Sink filter does not accept any new pin connections. Pins already connected can be reconnected, but only with the same media type. The profile is unlocked when the graph stops.

The stub file is automatically deleted when the last process closes the file handle. This occurs when the capture graph stops and no render graphs are reading the file.

The LockProfile method can be called multiple times with the value NULL, but only once with a non-NULL file name. After the filter graph runs, calling the method with NULL succeeds but has no effect, and calling the method with a file name fails.

The name of the stub file can be given to the Stream Buffer Source filter through that filter's IFileSourceFilter::Load method.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferSink Interface


IStreamBufferSource Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferSource interface is exposed by the Stream Buffer Source filter. Use this interface to play live content from the Stream Buffer Sink filter.

In addition to the methods inherited from IUnknown, the IStreamBufferSource interface exposes the following methods.

Method | Description
SetStreamSink | Sets a pointer to the Stream Buffer Sink filter, so that the source filter can stream data from the sink filter.

Requirements

Include Sbe.h.

See Also

  • Using the Stream Buffer Engine


IStreamBufferSource::SetStreamSink

This topic applies to Windows XP Service Pack 1 only.

The SetStreamSink method sets a pointer to the Stream Buffer Sink filter, so that the Stream Buffer Source filter can stream data from the sink filter.

Syntax

HRESULT SetStreamSink(
  IStreamBufferSink*  pIStreamBufferSink
);

Parameters

pIStreamBufferSink

[in] Pointer to the Stream Buffer Sink filter's IStreamBufferSink Interface interface.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Remarks

The source filter and the sink filter must be within the same process, but can reside in different filter graphs. If they are in different processes, call IFileSourceFilter::Load with the same file name used in the IStreamBufferSink::LockProfile method.

Several Stream Buffer Source filters can stream from the same sink filter.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferSource Interface


IStreamBufferMediaSeeking Interface

This topic applies to Windows XP Service Pack 1 only.

The IStreamBufferMediaSeeking interface controls seeking in a stream buffer source graph. The Stream Buffer Source filter exposes this interface.

The methods in this interface have exactly the same names and parameters as those in the IMediaSeeking interface. To seek within a stream buffer file, use this interface directly on the source filter instead of calling IMediaSeeking methods on the filter graph.

Remarks

When the Stream Buffer Source plays a recording created by the Recording object or the RecComp object, it can seek anywhere within the file. When it plays a live stream from the Stream Buffer Sink, it can seek anywhere within the sink filter's buffer. This might include recorded content or temporary backing files. Transitions across files are seamless.

Live content from the Stream Buffer Sink grows on one end, as new content is recorded, and shrinks on the other end, as stale backing files are deleted. Therefore, the positioning information for this interface differs somewhat from the regular IMediaSeeking interface. The following definitions are used.

Value | Description
Content start | The time of the earliest available content. For live content, the value starts at zero and increases whenever the Stream Buffer Engine deletes an old file. For example, if there are six backing files, each 15 minutes long, then after 60 minutes the content start jumps to 15 minutes, as the first file is deleted.
Content stop | The time of the latest available content. For live content, this value starts at zero and increases continuously.
Segment stop | The time when the Stream Buffer Source filter will stop playback. This value starts at positive infinity, but it can be set to arbitrary times by the application. The segment stop time can be later than the content stop time, so it may not be possible to seek to this position. If playback reaches the end of the content before reaching the segment stop time, the graph sends an end-of-stream (EOS) event.
Stream position | The current playback position, relative to the content start. For example, if the source graph runs for 15 seconds and pauses for 10 seconds, the stream position remains at 15 seconds until the source graph runs again.

Given these definition, the following IStreamBufferMediaSeeking methods have special behaviors:

  • GetAvailable: Returns content start and content stop.
  • GetCurrentPosition: Returns stream position.
  • GetDuration: Returns (content start – content stop).
  • GetPositions: Returns stream position and segment stop.
  • GetStopPosition: Returns segment stop.
  • SetPosition: Sets stream position and segment stop.

The only time format supported by this interface is reference time (TIME_FORMAT_MEDIA_TIME).

Rate Changes

For rate changes, the playback speed must be greater than 0.1 or less than -0.1. Negative rates indicate reverse playback. If the capture source is an MPEG-2 source, the MPEG-2 Video Analyzer filter is required to support playback faster than 4x or reverse playback. For more information, see Creating Stream Buffer Graphs.

The IStreamBufferMediaSeeking::SetRate method may return VFW_E_DVD_WRONG_SPEED if the requested rate is too high for very short content. This error is caused when the Stream Buffer Engine cannot get I frames for the available content at the requested rate.

The SetRate method may also return E_NOTIMPL. This error code can happen if several decoders are registered on the user's system. If so, use the standard IMediaSeeking::SetRate method on the source graph to set the playback rate. The IMediaSeeking version of SetRate may return VFW_E_UNSUPPORTED_AUDIO, which indicates that the audio decoder does not support trick mode. It is safe to ignore this error code.

The IStreamBufferMediaSeeking version of SetRate may also fail if the decoder does not support rates other than 1x speed.

Requirements

Include Sbe.h.

See Also

  • Buffering in the Stream Buffer Engine
  • MPEG-2 Video Analyzer Filter
  • Stream Buffer Engine Interfaces


Stream Buffer Engine Structures

This topic applies to Windows XP Service Pack 1 only.

This section contains reference information for the structures used by the stream buffer engine.

Structure | Description
STREAMBUFFER_ATTRIBUTE | Describes an attribute on a stream buffer file.

See Also

  • Stream Buffer Engine Reference


STREAMBUFFER_ATTRIBUTE Structure

This topic applies to Windows XP Service Pack 1 only.

The STREAMBUFFER_ATTRIBUTE structure describes an attribute on a stream buffer file.

Syntax

typedef struct {
    LPWSTR                     pszName;
    STREAMBUFFER_ATTR_DATATYPE StreamBufferAttributeType;
    BYTE                       *pbAttribute;
    WORD                       cbLength;
} STREAMBUFFER_ATTRIBUTE ;

Members

pszName

Pointer to a null-terminated wide-character string that contains the name of the attribute.

StreamBufferAttributeType

Member of the STREAMBUFFER_ATTR_DATATYPE enumeration. The value indicates the data type that you should use to interpret the attribute data, which is contained in the pbAttribute member.

pbAttribute

Pointer to a buffer that contains the attribute data.

cbLength

The size of the buffer given in pbAttribute, in bytes.

Requirements

Include Sbe.h.

See Also

  • IEnumStreamBufferRecordingAttrib::Next
  • Stream Buffer Engine Structures


Stream Buffer Engine Enumeration Types

This topic applies to Windows XP Service Pack 1 only.

This section contains reference information for the enumeration type used by the stream buffer engine.

Structure | Description
STREAMBUFFER_ATTR_DATATYPE | Defines the data type for an attribute.

See Also

  • Stream Buffer Engine Reference


STREAMBUFFER_ATTR_DATATYPE Enumeration

This topic applies to Windows XP Service Pack 1 only.

The STREAMBUFFER_ATTR_DATATYPE enumeration defines the data type for an attribute.

Syntax

typedef enum {
    STREAMBUFFER_TYPE_DWORD  = 0,
    STREAMBUFFER_TYPE_STRING = 1,
    STREAMBUFFER_TYPE_BINARY = 2,
    STREAMBUFFER_TYPE_BOOL   = 3,
    STREAMBUFFER_TYPE_QWORD  = 4,
    STREAMBUFFER_TYPE_WORD   = 5,
    STREAMBUFFER_TYPE_GUID   = 6,
} STREAMBUFFER_ATTR_DATATYPE ;

Members

STREAMBUFFER_TYPE_DWORD

The attribute is a 32-bit DWORD value.

STREAMBUFFER_TYPE_STRING

The attribute is a null-terminated wide-character string.

STREAMBUFFER_TYPE_BINARY

The attribute is an array of bytes.

STREAMBUFFER_TYPE_BOOL

The attribute is a 32-bit Boolean value.

STREAMBUFFER_TYPE_QWORD

The attribute is a 64-bit QWORD value.

STREAMBUFFER_TYPE_WORD

The attribute is a 16-bit WORD value.

STREAMBUFFER_TYPE_GUID

The attribute is a 128-bit GUID value.

Requirements

Include Sbe.h.

See Also

  • IStreamBufferRecordingAttribute Interface
  • Stream Buffer Engine Enumeration Types
  • STREAMBUFFER_ATTRIBUTE Structure


Stream Buffer Engine Event Codes

This topic applies to Windows XP Service Pack 1 only.

The Stream Buffer Engine posts the following events to the Filter Graph Manager.

Event notification code | Description
STREAMBUFFER_EC_TIMEHOLE | The Stream Buffer Source filter has reached a gap in the content. param1 = Time of the start of the gap, in milliseconds, relative to the content start. param2 = Duration of the gap, in milliseconds.
STREAMBUFFER_EC_STALE_DATA_READ | The Stream Buffer Source is reading a backing file that has been marked for deletion.
STREAMBUFFER_EC_STALE_FILE_DELETED | A backing file has been deleted.
STREAMBUFFER_EC_CONTENT_BECOMING_STALE | The Stream Buffer Source has lagged behind the Stream Buffer Sink by more than a pre-set number of backing files. For more information, see IStreamBufferConfigure::GetBackingFileCount.
STREAMBUFFER_EC_READ_FAILURE | A read failure has occurred. param1 = HRESULT code of the failure param2 = not used
STREAMBUFFER_EC_WRITE_FAILURE | A write failure has occurred.
STREAMBUFFER_EC_RATE_CHANGED | The playback rate has changed. param1 = old playback rate x 1000 param2 = new playback rate x 1000 For example, 2x speed is represented as 2000.

See Also

  • Buffering in the Stream Buffer Engine
  • Event Notification in DirectShow
  • Stream Buffer Engine Reference


Appendixes

  • Working with DIBs
  • Working with Codecs
  • Multimedia Streaming
  • Using DirectShow with Visual Basic
  • International Analog TV Tuning
  • GraphEdit File Format
  • Previous DirectShow What's New Sections
  • Controlling Filter Graphs Using C
  • Deprecated Interfaces
  • AVI File Format
  • DVD Region Change Support in Windows
  • DVD Drive Spin Down Timeout


Working with DIBs

Uncompressed video is a sequence of bitmaps played in rapid succession, typically at a rate of about 30 frames per second. Because most video enters a DirectShow filter graph in a compressed format, the video stream generally goes through a decoder for decompression. Many decoders output data in a YUY format and leave the final conversion to RGB for the video hardware just prior to rendering. If a decoder uses DirectX Video Acceleration, the video hardware performs additional work to decode the image. Thus, final decompression of the bitmaps may not be performed until the data reaches the video hardware.

But to perform many types of video analysis, processing or editing, it is often necessary to work on uncompressed bitmaps in some type of RGB or YUV format before they are rendered or written to file. This work is typically done within a transform filter based on the CTransformFilter base class, specifically in the Transform method. This method receives a pointer to an IMediaSample object that encapsulates the video data. The IMediaSample::GetPointer method returns a pointer to the first byte of the raw data. For uncompressed frames, this data consists of pixels that can be accessed or modified directly by the filter. The following sections provide background information that will help you work effectively with DIB data in this manner.

Note You can also modify the bits by using GDI, GDI+, DirectDraw or Direct3D functions, but these techniques are beyond the scope of this article.

This section contains the following topics:

  • Top-Down vs. Bottom-Up DIBs
  • Image Stride
  • GetVideoInfoParameters Helper Function
  • Working with 16-bit RGB


Top-Down vs. Bottom-Up DIBs

If you are new to graphics programming, you might expect that a bitmap would be arranged in memory so that the top row of the image appeared at the start of the buffer, followed by the next row, and so forth. However, this is not necessarily the case. In Windows, device-independent bitmaps (DIBs) can be placed in memory in two different orientations, bottom-up and top-down.

In a bottom-up DIB, the image buffer starts with the bottom row of pixels, followed by the next row up, and so forth. The top row of the image is the last row in the buffer. Therefore, the first byte in memory is the bottom-left pixel of the image. In GDI, all DIBs are bottom-up. The following diagram shows the physical layout of a bottom-up DIB.

In a top-down DIB, the order of the rows is reversed. The top row of the image is the first row in memory, followed by the next row down. The bottom row of the image is the last row in the buffer. With a top-down DIB, the first byte in memory is the top-left pixel of the image. DirectDraw uses top-down DIBs. The following diagram shows the physical layout of a top-down DIB:

For RGB DIBs, the image orientation is indicated by the biHeight member of the BITMAPINFOHEADER structure. If biHeight is positive, the image is bottom-up. If biHeight is negative, the image is top-down.

DIBs in YUV formats are always top-down, and the sign of the biHeight member is ignored. Decoders should offer YUV formats with positive biHeight, but they should also accept YUV formats with negative biHeight and ignore the sign.

Also, any DIB type that uses a FOURCC in the biCompression member, should express its biHeight as a positive number no matter what its orientation is, since the FOURCC itself identifies a compression scheme whose image orientation should be understood by any compatible filter.


Image Stride

When graphics hardware or GDI allocates a memory buffer for bitmaps, it often pads the rows with extra bytes in order to align them on some boundary. The width of the image, in bytes, plus the width of the extra padding, is called the stride. Another way to think of it is that stride gives the number of bytes it takes to advance from the beginning of one row in an image to the beginning of the next row.

For RGB DIBs, the stride is always aligned at least to a DWORD boundary. The same is true for YUV formats where the bitdepth is an even power of 2. Decoders and video sources should propose a format where the biWidth member of the BITMAPINFOHEADER is the width of the image. The video renderer may modify the format so that biWidth equals the stride of the surface, and the rcTarget member of the VIDEOINFOHEADER or VIDEOINFOHEADER2 structure specifies the image width. The video renderer proposes the modified format by calling IPin::QueryAccept on the output pin, and then attaching the new format to the next media sample. For details, see Dynamic Format Changes. If the video renderer does not change the format to specify the stride, then you should round the biWidth value up to the nearest DWORD boundary (except for non-power-of-2 YUV formats).

Never assume that stride is equal to the image width, even with 32-bit pixel formats, because many graphics cards require an alignment that is 64 bits or greater.


GetVideoInfoParameters Helper Function

If you are decoding a video image, or modifying a video image that is already decoded, you must take into account both the stride and the orientation of the image. This section presents a helper function that makes it easier to loop over the pixels in a bitmap in a consistent way.

The function is declared as follows:

void GetVideoInfoParameters(
    const VIDEOINFOHEADER *pvih, // Pointer to the VIDEOINFOHEADER
    BYTE * const pbData,         // Pointer to the start of the buffer.
    bool bYuv,                   // true if YUV format
    DWORD *pdwWidth,             // Receives the image width, in pixels
    DWORD *pdwHeight,            // Receives the image height, in pixels
    LONG *plStrideInBytes,       // Receives the stride, in bytes
    BYTE **ppbTop                // Receives a pointer to the first image row.
);

On input, this function takes three pieces of information: A pointer to a VIDEOINFOHEADER structure that describes the bitmap (pvih), the address of the buffer that holds the bitmap data (pbData), and a Boolean flag that indicates whether the bitmap is a YUV or an RGB format (bYuv).

On output, the function returns the following information:

  • The width and height of the image, in pixels (pdwWidth and pdwHeight).
  • The stride in bytes (plStrideInBytes).
  • A pointer to the first byte in the top row of pixels (ppbTop).

The value returned in ppbTop is always the upper-left corner of the image as it will be displayed on the screen. In a top-down DIB, this is the first byte in memory, but in a bottom-up DIB, the top row appears last in memory.

The value returned in plStrideinBytes is the byte offset from the start of one row to the start of the next row down. Thus, the address of the second row from the top is pbTop + lStrideInBytes.

The following code shows how to use this function on a 32-bit RGB DIB:

HRESULT WriteToBuffer_RGB32(BYTE *pData, VIDEOINFOHEADER *pVih)
{
    DWORD dwWidth, dwHeight;
    long lStride;
    BYTE *pbTop;
    GetVideoInfoParameters(pVih, pData, &dwWidth,
        &dwHeight, &lStride, &pbTop, false);

    // Loop from the top row of pixels to the bottom row.
    for (DWORD y = 0; y < dwHeight; y++)
    {
        // Loop across each pixel in the row, from left to right.
        RGBQUAD *pPixel = (RGBQUAD*)pbRow;
        for (DWORD x = 0; x < dwWidth; x++)
        {
            // pPixel[x] is the x'th pixel in the row.
            pPixel[x].rgbBlue = blue value;
            pPixel[x].rgbGreen = green value;
            pPixel[x].rgbRed = red value;
            pPixel[x].rgbReserved = 0;
        }
        // Advance pbTop by the stride.
        pbTop += lStride;
    }
}

The outer loop moves from the top row to the bottom row. The inner loop moves across each row from left to right. For a 32-bit RGB bitmap, each pixel should be addressed as an RGBQUAD value. (Other formats use other byte layouts.)

The following code shows the complete GetVideoInfoParameters function:

void GetVideoInfoParameters(
    const VIDEOINFOHEADER *pvih, // Pointer to the format header.
    BYTE  * const pbData,   // Pointer to the first address in the buffer.
    bool bYuv      // Is this a YUV format? (true = YUV, false = RGB)
    DWORD *pdwWidth,        // Returns the width in pixels.
    DWORD *pdwHeight,       // Returns the height in pixels.
    LONG  *plStrideInBytes, // Add this to a row to get the new row down.
    BYTE **ppbTop,          // Returns a pointer to the first byte in the
                            // top row of pixels.
    )
{
    LONG lStride;

    //  For 'normal' formats, biWidth is in pixels.
    //  Expand to bytes and round up to a multiple of 4.
    if ((pvih->bmiHeader.biBitCount != 0) &&
        (0 == (7 & pvih->bmiHeader.biBitCount)))
    {
        lStride = (pvih->bmiHeader.biWidth * (pvih->bmiHeader.biBitCount / 8) + 3) & ~3;
    }
    else   // Otherwise, biWidth is in bytes.
    {
        lStride = pvih->bmiHeader.biWidth;
    }

    //  If rcTarget is empty, use the whole image.
    if (IsRectEmpty(&pvih->rcTarget))
    {
        *pdwWidth = (DWORD)pvih->bmiHeader.biWidth;
        *pdwHeight = (DWORD)(abs(pvih->bmiHeader.biHeight));

        if (pvih->bmiHeader.biHeight < 0 || bYuv)   // Top-down bitmap.
        {
            *plStrideInBytes = lStride; // Stride goes "down".
            *ppbTop           = pbData; // Top row is first.
        }
        else        // Bottom-up bitmap.
        {
            *plStrideInBytes = -lStride;    // Stride goes "up".
            // Bottom row is first.
            *ppbTop = pbData + lStride * (*pdwHeight - 1);
        }
    }
    else   // rcTarget is NOT empty. Use a sub-rectangle in the image.
    {
        *pdwWidth = (DWORD)(pvih->rcTarget.right - pvih->rcTarget.left);
        *pdwHeight = (DWORD)(pvih->rcTarget.bottom - pvih->rcTarget.top);

        if (pvih->bmiHeader.biHeight < 0 || bYuv)   // Top-down bitmap.
        {
            // Same stride as above, but first pixel is modified down
            // and over by the target rectangle.
            *plStrideInBytes = lStride;
            *ppbTop = pbData +
                     lStride * pvih->rcTarget.top +
                     (pvih->bmiHeader.biBitCount * pvih->rcTarget.left) / 8;
        }
        else  // Bottom-up bitmap.
        {
            *plStrideInBytes = -lStride;
            *ppbTop = pbData +
                     lStride * (pvih->bmiHeader.biHeight - pvih->rcTarget.top - 1) +
                     (pvih->bmiHeader.biBitCount * pvih->rcTarget.left) / 8;
        }
    }
}

See Also

  • BITMAPINFOHEADER
  • Source and Target Rectangles in Video Renderers
  • Video Subtypes


Working with 16-bit RGB

Two formats are defined for 16-bit uncompressed RGB:

  • MEDIASUBTYPE_555 uses five bits each for the red, green, and blue components in a pixel. The most significant bit in the WORD is ignored.
  • MEDIASUBTYPE_565 uses five bits for the red and blue components, and six bits for the green component. This format reflects the fact that human vision is most sensitive to the green portions of the visible spectrum.

RGB 565

To extract the color components from an RGB 565 image, treat each pixel as a WORD type and use the following bit masks:

WORD red_mask = 0xF800;
WORD green_mask = 0x7E0;
WORD blue_mask = 0x1F;

Get the color components from a pixel as follows:

BYTE red_value = (pixel & red_mask) >> 11;
BYTE green_value = (pixel & green_mask) >> 5;
BYTE blue_value = (pixel & blue_mask);

Reverse this process to create an RGB 565 pixel.

WORD pixel565 = (red << 11) | (green << 5) | blue;

This code assumes the color values have already been truncated to the correct number of bits. The red, green, and blue values are packed into a single WORD value.

RGB 555

Working with RGB 555 is essentially the same as RGB 565, except the bit masks and bit shift operations are different. To get the color components from an RGB 555 pixel, do the following:

WORD red_mask = 0x7C00;
WORD green_mask = 0x3E0;
WORD blue_mask = 0x1F;

BYTE red_value = (pixel & red_mask) >> 10;
BYTE green_value = (pixel & green_mask) >> 5;
BYTE blue_value = (pixel & blue_mask);

To pack the red, green, and blue color values into an RGB 555 pixel, do the following:

WORD pixel565 = (red << 10) | (green << 5) | blue;

See Also

  • Uncompressed RGB Video Subtypes


Working with Codecs

Microsoft Windows provides several codecs as operating system components. The available codecs always include those that ship with whichever version of the DirectX and Windows Media Player was included in the Windows release. Additional codecs may be installed when newer versions of DirectX or Windows Media Player or the Windows Media SDK runtimes are installed. Third parties may install additional codecs on a host system; these codecs may be designed to work only with a particular application, or they may support general use by any DirectShow application.

Codecs may be implemented in one of three different ways:

  • As a Video for Windows-type audio or video installable codec that is loaded by the Video Compression Manager (VCM) or Audio Compression Manager (ACM). In general, this technology is considered deprecated and its use is not recommended. Installable codecs participate in DirectShow filter graphs through the AVI Decompressor wrapper filter.
  • As a DirectShow filter. Many third party codecs are implemented as native DirectShow filters. One such filter is the Frauenhofer MP3 decompressor filter. In general, these filters may be added to the filter graph in the usual ways. One exception to this rule is that some Windows Media™ Audio or Windows Media Video codecs, and the Microsoft MPEG-4 codec, cannot be added to a filter graph manually. These filters can only be added by the ASF Reader and ASF Writer filters.
  • As DirectX Media Objects (DMOs). DMOs are the recommended way to implement codecs because they can be used either within a DirectShow filter graph using the DMO Wrapper filter, or else independently in any other non-DirectShow-based streaming application. Some Windows Media Audio and Windows Media Video codecs are implemented as DMOs. As with the Windows Media filters, these DMOs cannot be used outside the context of the Windows Media SDK. That means that in DirectShow, they can only be added to a graph through the ASF Reader or ASF Writer filters.

In GraphEdit, all these different types of codecs appear together under the following categories:

  • Audio compressor
  • Video compressor
  • DirectShow filter

Many of these codecs, however, are installed by third parties, or by other Microsoft applications or operating system components, and are not meant for use by other DirectShow applications. The list of codecs visible in GraphEdit also depends on which version of Windows is running on the host system, and which version of the DirectShow SDK is installed.


FOURCC Codes

Many digital media formats have FOURCC codes assigned to them. A FOURCC code is a 32-bit unsigned integer that is created by concatenating four ASCII characters. For example, the FOURCC code for YUY2 video is 'YUY2'. For compressed video formats and non-RGB video formats (such as YUV), the biCompression member of the BITMAPINFOHEADER structure should be set to the FOURCC code.

There are various C/C++ macros that make it easier to declare FOURCC values in source code. For example, the MAKEFOURCC macro is declared in Mmsystem.h, and the FCC macro is declared in Aviriff.h. Use them as follows:

DWORD fccYUY2 = MAKEFOURCC('Y','U','Y','2');
DWORD fccYUY2 = FCC('YUY2');

You can also declare a FOURCC code directly as a string literal simply by reversing the order of the characters. For example:

DWORD fccYUY2 = '2YUY';  // Declares the FOURCC 'YUY2'.

Reversing the order is necessary because the Microsoft Windows operating system uses a little-endian architecture. 'Y' = 0x59, 'U' = 0x55, and '2' = 0x32, so '2YUY' is 0x32595559.

Converting FOURCC Codes to Subtype GUIDs

A range of 2*32 GUIDs is reserved for representing FOURCCs. These GUIDs are all of the form XXXXXXXX-0000-0010-8000-00AA00389B71 where XXXXXXXX is the FOURCC code. Thus, the subtype GUID for YUY2 is 32595559-0000-0010-8000-00AA00389B71.

Many of these GUIDs are defined already in the header file Uuids.h. For example, the YUY2 subtype is defined as MEDIASUBTYPE_YUY2. The DirectShow base class library also provides a helper class, FOURCCMap, which can be used to convert FOURCC codes into GUID values. The FOURCCMap constructor takes a FOURCC code as an input parameter. You can then cast the FOURCCMap object to the corresponding GUID:

FOURCCMap fccMap(FCC('YUY2'));
GUID g1 = (GUID)fccMap;

// Equivalent:
GUID g2 = (GUID)FOURCCMap(FCC('YUY2'));

How to Register a New FOURCC

To register a new FOURCC code, send email to mmreg@Microsoft.com providing the FOURCC and a description of the format. Please also include a company ID, an e-mail address, and the name of a contact person. A list of currently registered FOURCC's may be found on the Microsoft Corporation hwdev Web site.

See Also

  • Audio Subtypes
  • Video Subtypes


Multimedia Streaming

Multimedia Streaming is a set of APIs that enable an application to get audio and video data from a DirectShow filter graph without writing a custom DirectShow filter.

This section contains the following topics.

  • About the Multimedia Streaming Architecture
  • Multimedia Streaming Interfaces
  • Multimedia Streaming Enumeration Types
  • Multimedia Streaming Data Types
  • Multimedia Streaming Structures
  • Multimedia Streaming Error and Success Codes
  • Multimedia Streaming Objects
  • Multimedia Streaming Sample Code


About the Multimedia Streaming Architecture

This article describes the architecture of Multimedia Streaming. It contains the following sections.

  • Advantages of Multimedia Streaming
  • Multimedia Streaming Object and Interface Hierarchy
  • Creating Multimedia Stream Objects and Stream Samples
  • Using Multimedia Streams in Applications
  • Sharing Data Between Streams


Advantages of Multimedia Streaming

When developers use multimedia streaming in their applications, it greatly reduces the amount of format-specific programming needed. Typically, an application that must obtain media data from a file or hardware source must know everything about the data format and the hardware device. The application must handle the connection, transfer of data, any necessary data conversion, and the actual data rendering or file storage. Because each format and device is slightly different, this process is often complex and cumbersome. Multimedia streaming, on the other hand, automatically negotiates the transfer and conversion of data from the source to the application. The streaming interfaces provide a uniform and predictable method of data access and control, which makes it easy for an application to play back the data, regardless of its original source or format.

The following steps show how to implement streaming, from hardware device to rendered playback.

  1. A source of video data, such as Microsoft® DirectShow®, exposes the streaming interfaces.
  2. The application developer uses the multimedia streaming interfaces to handle data format conversion.
  3. The application developer uses the Microsoft DirectDraw® interfaces to render the resulting data.

The specification for multimedia streams comprises several interfaces; each interface includes methods that control a certain aspect of the streaming process or handle a certain type of data. See List of Multimedia Streaming Interfaces for additional information.


Multimedia Streaming Object and Interface Hierarchy

The following diagram shows the object hierarchy used in multimedia streaming.

MultimediaStreaming Object Hierarchy

The multimedia streaming architecture defines three general type of object:

  • The AMMultimediaStream object exposes the IAMMultiMediaStream interface. Internally, this object wraps the DirectShow filter graph.
  • Media stream objects expose the IMediaStream interface and are data specific. The AMMultimediaStream object contains one or more media streams.
  • Stream sample objects contain the data for a particular stream.

The following media stream objects are supported:

  • Audio stream. Exposes the IAudioMediaStream interface.
  • DirectDraw stream. Represents a video stream that is rendered to a DirectDraw surface. Exposes the IDirectDrawMediaStream interface.
  • Media type stream. Represents arbitrary data. Exposes the IAMMediaTypeStream interface.

Each media stream object creates its own kind of stream sample object:

  • Audio streams create audio samples, which expose the IAudioStreamSample interface.
  • DirectDraw streams create DirectDraw samples, which expose the IDirectDrawStreamSample interface.
  • Media type streams create media type samples, which expose the IAMMediaTypeSample interface.

The following diagram shows the interface hierarchy for the interfaces listed previously:

MultimediaStreaming Interface Hierarchy


Creating Multimedia Stream Objects and Stream Samples

Objects that support the IMultiMediaStream interface are the basic containers for multimedia data streams. The IMultiMediaStream interface includes methods that enumerate the object's data streams; these streams are typically video and audio data, but can include data of any format, such as closed-captioning, plain text, or SMPTE timecode. The IMultiMediaStream interface is a generic container, however; developers can create other versions of the interface that support specific data formats. Objects that implement the IAMMultiMediaStream interface, for example, can enumerate and control streams of any DirectShow data format. Because individual data streams are format specific, they support at least two different interfaces: one generic and one data-specific. Every stream supports the IMediaStream interface, which provides methods to retrieve its format and a pointer to the stream itself. The IDirectDrawMediaStream interface, on the other hand, has methods that deal specifically with rendering video data. Any interface derived from IMultiMediaStream also supports the creation of stream samples, the basic units of streaming data.

A multimedia sample is a reference to an object containing the media data. For a video image, this is a DirectDraw surface. The sample's exact content varies, depending on the type of media (sound, text, and so on). Because a sample is only a reference to the data object, any number of stream samples can refer to the same object. The IStreamSample interface provides methods that get and set a sample's characteristics, such as its start and stop time, status, and stream association. The IStreamSample::Update method refreshes the sample's data in the case of readable streams. For writable streams, it will write the sample's data to the stream. Typically, you use the Update method in a loop that renders, transfers, or stores streaming data.


Using Multimedia Streams in Applications

The multimedia streaming interfaces greatly simplify the process of manipulating multimedia data by removing the dependency on specific characteristics of the hardware or software source and providing support for all Microsoft DirectX® media formats. Streams abstract the data to a very high level; applications can even move data from one stream to another without knowing anything about the data's format.

Perform the following steps to create a multimedia stream.

  1. Create the multimedia stream. The method of creation and initialization of the stream is architecture specific. DirectShow supports the IAMMultiMediaStream interface, which is used to initialize the stream. Other in-process server implementations of IMultiMediaStream will be created and initialized using different mechanisms.
  2. After the multimedia stream object is initialized, the application will use QueryInterface to retrieve the IMultiMediaStream interface for the object. Use this interface to determine the stream's properties and enumerate the streams themselves. You can retrieve a specific stream by calling the IMultiMediaStream::GetMediaStream method with a specific purpose ID. MSPID_PrimaryVideo and MSPID_PrimaryAudio, which represent the primary video and audio streams, are the most commonly used purpose IDs.
  3. Call IUnknown::QueryInterface for an interface specific to the stream's media type. If you want to render a video stream, for example, retrieve its IDirectDrawMediaStream interface. Media-specific interfaces define additional methods necessary for taking full advantage of a format's capabilities.
  4. Create one or more samples from the stream data. Every media stream supports the IMediaStream::CreateSharedSample method for sample creation. The resulting sample supports the IStreamSample interface, which provides control over the sample and its characteristics. Typically, the media stream supports a format-specific method of sample creation that is more powerful than the aforementioned IStreamSample methods. IDirectDrawMediaStream, for example, can create samples attached to a desired DirectDraw surface and clipping rectangle. In some situations, however, you must handle data without knowing about its data format. If you want to stream data independent of its format, use the IMediaStream::CreateSharedSample method to create the data samples.
  5. After creating all desired stream samples, start the stream by calling the IMultiMediaStream::SetState method and pass in the STREAMSTATE_RUN flag as its parameter.
  6. Call IStreamSample::Update to update the stream sample. When the IStreamSample::Update method exits, you can access the sample's data. If you want a trigger a specific event or function call when the update returns, pass the appropriate pointers to the IStreamSample::Update method.

For more information on the multimedia streaming interfaces, see Multimedia Streaming.


Sharing Data Between Streams

Processing multimedia data typically requires a great deal of system resources; therefore, you should avoid copying data whenever possible. The streaming architecture supports shared stream samples, a mechanism that moves data from one stream to another without copying it. This buffer enables the efficient transportation of data between two streams even if the destination stream doesn't specifically support the underlying data format.

For example, assume that you have a multimedia stream with three data streams: video and audio, and URL data time-stamped to match the video content. You want to write an application that adds a copyright notice on every video frame and writes the data to another stream for storage, but your application doesn't understand any data formats except the video stream. For the video stream, you create a sample attached to the desired DirectDraw surface. You can then create an output stream by calling either the IDirectDrawMediaStream::CreateSample method with that pointer to the same surface, or IMediaStream::CreateSharedSample. In both cases, the input and output streams share the DirectDraw surface. Because you understand the video format, you can access this surface as needed.

To retrieve the other source stream pointers (audio and URL), enumerate the source container stream and grab pointers to the nonvideo streams. Each of these source streams has an associated output stream in the output stream container. Retrieve these output pointers by calling the IMultiMediaStream::GetMediaStream method on the output container with each of the source stream pointers. The following steps describe this process.

  1. Call IMultiMediaStream::EnumMediaStreams to retrieve a pointer to a source stream. Make sure that it's not the video stream, because your application already understands its format.
  2. Call IMultiMediaStream::GetMediaStream on the output container stream with the pointer from step 1. This returns a pointer to the desired output stream.
  3. Call AllocateSample on the source stream.
  4. Call CreateSharedSample on the output stream.
  5. Call Update on the source stream to read the data.
  6. Call Update on the output stream to write the data.

Repeat these steps for each stream whose format you don't support. When both samples finish updating, the output stream has all data from the source stream and you are done.


List of Multimedia Streaming Interfaces

Multimedia streaming comprises a number of interfaces; this article provides a brief description of each interface. For additional information about multimedia streaming, see About the Multimedia Streaming Architecture.

This article contains the following sections.

  • Base Multimedia Streaming Interfaces
  • DirectDraw Streaming Interfaces
  • Audio Streaming Interfaces


Base Multimedia Streaming Interfaces

The base multimedia streaming interfaces provide a programmatic way to access multimedia streams. However, using a base interface to access a specific type of data can limit the amount of control you have over the data, so media developers should create derived versions of these interfaces that provide more powerful control over the unique capabilities of their media type.

IMultiMediaStream

Defines how to access the highest-level multimedia stream object; this object contains and provides access to other stream objects. IMultiMediaStream has methods that enumerate or retrieve specific streams, as well as checking the stream's total time duration and seeking within the stream.

IMediaStream

Defines a generic stream object. Use its methods to retrieve a pointer to the stream, get information about the stream, and create samples from the stream data. You can also create shared stream samples, which multiple streams can access without duplicating the sample's data.

IStreamSample

Controls the behavior of a specific stream sample. You can retrieve the stream that created the sample, check the sample's start and end times and completion status, and perform a user-defined function on the sample itself (through the Update method). Typically, the Update method processes the sample data in an appropriate manner, such as rendering video data or playing back audio data.


DirectDraw Streaming Interfaces

If you use Microsoft® DirectDraw®-supported video formats in your streams, the following interfaces give you more powerful control over the data than the more generic base interfaces.

IDirectDrawMediaStream

Sets and retrieves the stream format and the DirectDraw object associated with the media stream; this interface derives from IMediaStream. You can also use this interface to create video samples.

IDirectDrawStreamSample

Enables you to attach video samples to DirectDraw surfaces; this interface derives from the IStreamSample interface. Each attached surface includes a clipping rectangle to make rendering easier.


Audio Streaming Interfaces

IAudioMediaStream

Controls audio media streams. This interface inherits from the IMediaStream interface and is used to create one or more IAudioStreamSample objects. It is also used to set and retrieve the current format of the stream data.

IAudioStreamSample

Retrieves information from the underlying IAudioData data objects.

IMemoryData

Contains methods that set and retrieve memory data on audio data objects. Audio data objects provide the underlying data that stream samples access. This interface provides a way to initialize memory buffers and to set actual amounts of audio data in the objects. Additionally, the IMemoryData::GetInfo method can be used to retrieve audio memory data.

IAudioData

Provides methods that enable applications to set and get the underlying audio data that audio streams will reference. The audio data format is set in the WAVEFORMATEX structure.


Multimedia Streaming Interfaces

This section contains reference entries for all the multimedia streaming interfaces and their methods, including those that Microsoft DirectShow supports. For convenience, this section also includes documentation on the IDirectDraw and IDirectDrawSurface interfaces that are exposed through other multimedia streaming interfaces.

Interface | Description
IAMMediaStream | Handles the internal connections between DirectShow filters and filter graphs in applications that use multimedia streaming.
IAMMediaTypeSample | Contains methods for manipulating stream samples with arbitrary media types.
IAMMediaTypeStream | Contains methods for creating multimedia streams with arbitrary media types.
IAMMultiMediaStream | Exposes DirectShow functionality to multimedia stream developers.
IAudioData | Provides methods that enable applications to set and get the underlying audio data that audio streams will reference.
IAudioMediaStream | Controls audio media streams by providing methods that set and get the stream's format.
IAudioStreamSample | Retrieves information from the underlying IAudioData data objects.
IDirectDraw | Controls DirectDraw objects.
IDirectDrawClipper | Provides methods to control a DirectDrawClipper object.
IDirectDrawMediaStream | Controls media streams that appear on Microsoft® DirectDraw® surfaces.
IDirectDrawPalette | Provides methods to control a DirectDrawPalette object.
IDirectDrawStreamSample | Provides methods that set and retrieve pointers to the DirectDraw surface associated with the current stream sample.
IDirectDrawSurface | Controls DirectDrawSurface objects.
IMediaStream | Provides access to the characteristics of a media stream, such as the stream's media type and purpose ID. It also has methods that create data samples.
IMediaStreamFilter | Supported by the Media Stream filter, which is used internally by the multimedia stream object. .
IMemoryData | Contains methods that set and retrieve memory data on audio data objects.
IMultiMediaStream | Provides methods that control a multimedia stream and provide access to its underlying media streams.
IStreamSample | Provides control over the behavior of stream samples.


IAMMediaStream Interface

The IAMMediaStream interface handles the internal connections between Microsoft DirectShow filters and filter graphs in applications that use multimedia streaming. This enables applications to automatically negotiate the transfer and conversion of data from the source to the application without having to write code to handle the connection, transfer of data, data conversion, and actual data rendering or file storage. This provides a uniform and predictable method of data access and control.

This interface isn't intended for implementation or use by application developers.

In addition to the methods inherited from IMediaStream, the IAMMediaStreaminterface exposes the following methods.

Method | Description
Initialize | Creates and initializes a new media stream with the specified stream type and purpose ID.
JoinAMMultiMediaStream | The IAMMultiMediaStream::AddMediaStream method calls this method, which adds the specified media stream to the current multimedia stream.
JoinFilter | Connects a media stream to a media stream filter in the underlying filter graph.
JoinFilterGraph | Connects a media stream filter to a filter graph.
SetState | Sets the filter state.


IAMMediaStream::Initialize

The Initialize method creates and initializes a new media stream with the specified stream type and purpose ID.

Syntax

HRESULT Initialize(
  IUnknown *pSourceObject,
  DWORD dwFlags,
  REFMSPID PurposeID,
  const STREAM_TYPE StreamType
);

Parameters

pSourceObject

[in] Pointer to an IUnknown source object.

dwFlags

[in] Value that modifies the media stream's behavior; it is a combination of one or more of the following values.

Value | Description
AMMSF_ADDDEFAULTRENDERER | Add a default renderer.
AMMSF_CREATEPEER | Create a peer stream based on the same object as a pStreamObject.
AMMSF_NOSTALL | Run the stream even if Update is not called.
AMMSF_STOPIFNOSAMPLES | Terminates the stream if no samples were created or if the last sample is deleted.

PurposeID

[in] Purpose ID for the new media stream.

StreamType

[in] STREAM_TYPE enumeration value that specifies the new media stream's media type.

Return Values

Returns S_OK if successful or E_POINTER if one or more of the required parameters are invalid.

Remarks

If dwFlags specifies AMMSF_ADDDEFAULTRENDERER, then the default renderer for the given purpose ID is created, if possible. Currently, the only default renderer supported is for audio using Microsoft® DirectSound®. In this case, the pStreamObject parameter must be NULL and any calls to the IMultiMediaStream::GetMediaStream or IMultiMediaStream::EnumMediaStreams method will not recognize the stream.

If dwFlags specifies AMMSF_CREATEPEER, then a media stream is created using pStreamObject and added to the current multimedia stream. The pStreamObject parameter varies depending on the stream type. In general, pStreamObject can point to an IMediaStream object, in which case a stream with the sample purpose ID and format is created. For IDirectDraw streams, it can also be a pointer to an IDirectDraw interface.

If dwFlags specifies AMMSF_STOPIFNOSAMPLES, then the stream is terminated.

If no flags are set, then pStreamObject can be one of the following.

Value | Description
An IAMMediaStream object | This stream is then added to the streams in the multimedia stream.
NULL | In this case a default IMediaStream object is added to the stream with a default underlying object, if required.
A pointer to an underlying object | This is used to construct default streams. For video streams, this can be an IDirectDraw pointer.

See Also

  • IAMMediaStream Interface


IAMMediaStream::JoinAMMultiMediaStream

The IAMMultiMediaStream::AddMediaStream method calls this method, which adds the specified media stream to the current multimedia stream.

Syntax

HRESULT JoinAMMultiMediaStream(
  IAMMultiMediaStream *pAMMultiMediaStream
);

Parameters

pAMMultiMediaStream

[in] Pointer to the IAMMultiMediaStream object to add the current media stream to.

Return Values

Returns S_OK if successful or MS_E_SAMPLEALLOC if the media stream already has allocated stream samples.

Remarks

Don't increment the reference count of the supplied multimedia stream because it is already accounted for when created.

Applications should not call this method.

See Also

  • IAMMediaStream Interface


IAMMediaStream::JoinFilter

The JoinFilter method connects a media stream to the Media Stream filter, which is used internally by the multimedia stream object. Applications should not call this method.

Syntax

HRESULT JoinFilter(
    IMediaStreamFilter *pMediaStreamFilter
);

Parameters

pMediaStreamFilter

[in] Pointer to the filter's IMediaStreamFilter interface.

Return Values

Returns S_OK if successful.

See Also

  • IAMMediaStream Interface


IAMMediaStream::JoinFilterGraph

The JoinFilterGraph method connects a media stream filter to a filter graph.

Syntax

HRESULT JoinFilterGraph(
    IFilterGraph *pGraph
);

Parameters

pGraph

[in] Pointer to the current media stream filter to add to the specified filter graph.

Return Values

Returns S_OK if successful or E_POINTER if pGraph is NULL.

Remarks

Don't increment the reference count of the specified filter graph.

Applications should not call this method.

See Also

  • IAMMediaStream Interface


IAMMediaStream::SetState

The SetState method sets the filter state.

Syntax

HRESULT SetState(
    FILTER_STATE State
);

Parameters

State

[in] Sets the filter's state, as specified by the FILTER_STATE enumerated type.

Return Values

Returns S_OK if successful or E_INVALIDARG if the State parameter is invalid.

Remarks

Applications should not call this method.

See Also

  • IAMMediaStream Interface


IAMMediaTypeSample Interface

This interface contains methods for manipulating stream samples with arbitrary media types. Call the IAMMediaTypeStream::CreateSample method to create a sample that exposes this interface.

This interface inherits from the IStreamSample interface.

The methods in this interface parallel those of the IMediaSample interface, although IAMMediaTypeSample contains a SetPointer method in addition to the GetPointer method.

In addition to the methods inherited from IStreamSample, the IAMMediaTypeSample interface exposes the following methods.

Method | Description
GetActualDataLength | Retrieves the data length of the sample, in bytes.
GetMediaTime | Retrieves the media time stamps for this sample.
GetMediaType | Retrieves the media type of the sample.
GetPointer | Retrieves a read/write pointer to the buffer's memory.
GetSize | Retrieves the size of the buffer data area, in bytes.
GetTime | Retrieves the stream times at which this sample should start and stop.
IsDiscontinuity | Determines if this sample represents a discontinuity in the data stream.
IsPreroll | Determines if this sample is part of the preroll.
IsSyncPoint | Determines if the beginning of a sample is a synchronization point.
SetActualDataLength | Sets the sample's data length.
SetDiscontinuity | Sets the discontinuity property.
SetMediaTime | Sets the media time stamps for this sample.
SetMediaType | Sets the media type for the sample.
SetPointer | Sets the pointer to the media sample's memory buffer.
SetPreroll | Specifies whether this is a preroll sample.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
SetTime | Sets the stream times at which this sample should start and stop.


IAMMediaTypeSample::GetActualDataLength

The GetActualDataLength method retrieves the data length of the sample, in bytes.

Syntax

long GetActualDataLength(void);

Return Values

Returns the data length of the sample, in bytes.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::GetMediaTime

The GetMediaTime method retrieves the media time stamps for the sample.

Syntax

HRESULT GetMediaTime(
  LONGLONG *pTimeStart,
  LONGLONG *pTimeEnd
);

Parameters

pTimeStart

[out] Pointer to a variable that receives the media start time.

pTimeEnd

[out] Pointer to a variable that receives the media stop time.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | No media time stamp was set for this sample.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::GetMediaType

The GetMediaType method retrieves the media type of the sample. If the format has not changed from the previous sample, the sample might not carry a media type.

Syntax

HRESULT GetMediaType(
  AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType

Address of a pointer that receives an AM_MEDIA_TYPE structure.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | Insufficient memory.
S_FALSE | The format has not changed from the previous sample.
S_OK | Success.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::GetPointer

The GetPointer method retrieves a read/write pointer to the buffer's memory.

Syntax

HRESULT GetPointer(
  BYTE **ppBuffer
);

Parameters

ppBuffer

[out] Address of a pointer to the buffer.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::GetSize

The GetSize method retrieves the size of the buffer data area, in bytes.

Syntax

long GetSize(void);

Return Values

Returns the size of the buffer data area, in bytes.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::GetTime

The GetTime method retrieves the stream times at which the sample should start and stop.

Syntax

HRESULT GetTime(
  REFERENCE_TIME *pTimeStart,
  REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

[out] Pointer to a variable that receives the start time.

pTimeEnd

[out] Pointer to a variable that receives the stop time. If the sample has no stop time, the value is set to the start time plus one.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_SAMPLE_TIME_NOT_SET | The sample does not have any time stamps.
VFW_S_NO_STOP_TIME | The sample has a valid start time but no stop time.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::IsDiscontinuity

The IsDiscontinuity method determines if this sample represents a discontinuity in the data stream.

Syntax

HRESULT IsDiscontinuity(void);

Return Values

Returns S_OK if this sample is a discontinuity, or S_FALSE otherwise.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::IsPreroll

The IsPreroll method determines if this sample is part of the preroll. A preroll sample should not be displayed.

Syntax

HRESULT IsPreroll(void);

Return Values

Returns S_OK if the sample is a preroll sample, or S_FALSE otherwise.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::IsSyncPoint

The IsSyncPoint method determines if the beginning of a sample is a synchronization point.

Syntax

HRESULT IsSyncPoint(void);

Return Values

Returns S_OK if the beginning of the sample is a synchronization point, or S_FALSE otherwise.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetActualDataLength

The SetActualDataLength method sets the sample's data length.

Syntax

HRESULT SetActualDataLength(
  long lActual
);

Parameters

lActual

Length of the data in the media sample, in bytes.

Return Values

Returns one of the following values.

Return code | Description
S_OK | Success.
VFW_E_BUFFER_OVERFLOW | The buffer is not big enough.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetDiscontinuity

The SetDiscontinuity method sets the discontinuity property.

Syntax

HRESULT SetDiscontinuity(
  BOOL bDiscontinuity
);

Parameters

bDiscontinuity

Value that specifies whether this sample is a discontinuity. If the sample is discontinuous with the previous sample, set the value to TRUE. Otherwise, set the value to FALSE.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetMediaTime

The SetMediaTime method sets the media time stamps for this sample.

Syntax

HRESULT SetMediaTime(
  LONGLONG *pTimeStart,
  LONGLONG *pTimeEnd
);

Parameters

pTimeStart

[in] Pointer to a variable that contains the media start time.

pTimeEnd

[in] Pointer to a variable that contains the media stop time.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetMediaType

The SetMediaType method sets the media type for the sample.

Syntax

HRESULT SetMediaType(
  AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType

Pointer to an AM_MEDIA_TYPE structure that describes the media type.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetPointer

The SetPointer method sets the pointer to the media sample's memory buffer.

Syntax

HRESULT SetPointer(
  BYTE *pBuffer,
  long lSize
);

Parameters

pBuffer

[in] Pointer to a memory buffer allocated by the caller, or NULL.

lSize

[in] Size of the buffer, in bytes.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

If the value of the pBuffer parameter is NULL, the method allocates a memory block, with a size in bytes equal to the value of the lSize parameter. There is no guarantee that the memory has been initialized.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetPreroll

The SetPreroll method specifies whether this is a preroll sample. A preroll sample should not be displayed.

Syntax

HRESULT SetPreroll(
  BOOL bIsPreroll
);

Parameters

bIsPreroll

Boolean value that specifies whether the sample is a preroll sample. If TRUE, it is for preroll and should not be displayed.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetSyncPoint

The SetSyncPoint method specifies whether the beginning of this sample is a synchronization point.

Syntax

HRESULT SetSyncPoint(
  BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint

Boolean value that specifies whether the beginning of this sample is a synchronization point. If TRUE, the beginning of the sample is a synchronization point.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeSample::SetTime

The SetTime method sets the stream times at which the sample should start and stop.

Syntax

HRESULT SetTime(
  REFERENCE_TIME *pTimeStart,
  REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart

[in] Pointer to a variable that contains the start time.

pTimeEnd

[in] Pointer to a variable that contains the stop time.

Return Values

Returns S_OK.

See Also

  • IAMMediaTypeSample Interface


IAMMediaTypeStream Interface

This interface contains methods for creating multimedia streams with arbitrary media types. Use this interface if you need to create a multimedia stream with a format that is not supported by the other Microsoft DirectShow multimedia streaming interfaces.

This interface inherits from the IMediaStream interface.

Note For video streams, use the IDirectDrawMediaStream interface instead of this interface. For audio streams, use the IAudioMediaStream interface.

In addition to the methods inherited from IMediaStream, the IAMMediaTypeStream interface exposes the following methods.

Method | Description
CreateSample | Creates a stream sample and optionally specifies the sample buffer.
GetFormat | Retrieves the format of the stream.
GetStreamAllocatorRequirements | Retrieves the allocator requirements for the stream. This method is not currently implemented.
SetFormat | Sets the format of the stream.
SetStreamAllocatorRequirements | Sets the allocator requirements for the stream. This method is not currently implemented.


IAMMediaTypeStream::CreateSample

The CreateSample method creates a stream sample and optionally specifies the sample buffer.

Syntax

HRESULT CreateSample(
  long lSampleSize,
  BYTE *pbBuffer,
  DWORD dwFlags,
  IUnknown *pUnkOuter,
  IAMMediaTypeSample **ppAMMediaTypeSample
);

Parameters

lSampleSize

[in] Size of the sample.

pbBuffer

[in] [optional] Pointer to an array of bytes that contains the sample data, or NULL.

dwFlags

[in] Reserved.

pUnkOuter

[in] [optional] Pointer to the interface of an object that aggregates the stream sample.

ppAMMediaTypeSample

[in] Address of an IAMMediaTypeSample interface pointer that receives a pointer to the created sample.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

If pUnkOuter is non-NULL, the new stream sample is aggregated into the specified object. Filters that receive the sample can then query it for interfaces supported by the aggregating object.

See Also

  • IAMMediaTypeStream Interface


IAMMediaTypeStream::GetFormat

The GetFormat method retrieves the format of the stream.

Syntax

HRESULT GetFormat(
  AM_MEDIA_TYPE *pMediaType,
  DWORD dwFlags
);

Parameters

pMediaType

[out] Pointer to an AM_MEDIA_TYPE structure that receives the stream format.

dwFlags

[in] Reserved.

Return Values

Returns one of the following values.

Return code | Description
MS_E_NOSTREAM | No stream is associated with this object.
S_OK | Success.

See Also

  • IAMMediaTypeStream Interface


IAMMediaTypeStream::GetStreamAllocatorRequirements

The GetStreamAllocatorRequirements retrieves the allocator requirements for the stream. This method is not currently implemented.

Syntax

HRESULT GetStreamAllocatorRequirements(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

[out] Pointer to an ALLOCATOR_PROPERTIES structure that receives the stream allocator requirements.

Return Values

Returns E_FAIL.

See Also

  • IAMMediaTypeStream Interface


IAMMediaTypeStream::SetFormat

The SetFormat method sets the format of the stream.

Syntax

HRESULT SetFormat(
  AM_MEDIA_TYPE *pMediaType,
  DWORD dwFlags
);

Parameters

pMediaType

[in] Pointer to an AM_MEDIA_TYPE structure that contains the stream format.

dwFlags

[in] Reserved.

Return Values

Returns one of the following values.

Return code | Description
MS_E_SAMPLEALLOC | The stream has already allocated a sample with another media type.
S_OK | Success.

See Also

  • IAMMediaTypeStream Interface


IAMMediaTypeStream::SetStreamAllocatorRequirements

The SetStreamAllocatorRequirements sets the allocator requirements for the stream. This method is not currently implemented.

Syntax

HRESULT SetStreamAllocatorRequirements(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps

[in] Pointer to an ALLOCATOR_PROPERTIES structure that contains the stream allocator requirements.

Return Values

Returns E_FAIL.

See Also

  • IAMMediaTypeStream Interface


IAMMultiMediaStream Interface

The IAMMultiMediaStream interface is supported by the multimedia stream object. It contains methods for creating the underlying filter graph that the object manages.

In addition to the methods inherited from IMultiMediaStream, the IAMMultiMediaStream interface exposes the following methods.

Method | Description
AddMediaStream | Adds the specified media stream to the current filter graph.
GetFilter | Retrieves the specified filter from the current filter graph.
GetFilterGraph | Retrieves the associated filter graph's IGraphBuilder interface.
Initialize | Sets the stream type. If the pFilterGraph parameter is non-NULL the filter graph passed in is used for the stream.
OpenFile | Opens and automatically creates a filter graph for the specified media file. If DirectShow doesn't support the file format, this method does nothing.
OpenMoniker | Opens a file or device moniker; you can read media data from this moniker if DirectShow supports the media type.
Render | Renders the current filter graph.


IAMMultiMediaStream::AddMediaStream

The AddMediaStream method adds a new media stream to the filter graph.

Syntax

HRESULT AddMediaStream(
  IUnknown *pStreamObject,
  const MSPID *pPurposeID,
  DWORD dwFlags,
  IMediaStream **ppNewStream
);

Parameters

pStreamObject

[in] Pointer to the IUnknown interface of an object that is used to create the new media stream. This parameter can be NULL. See Remarks for more information.

pPurposeID

[in] Pointer an MSPID the specifies the type of media stream to create. This parameter can be NULL.

dwFlags

[in] Bitwise combination of zero or more of the following flags.

Value | Description
AMMSF_ADDDEFAULTRENDERER | Add a default renderer (audio streams only).
AMMSF_CREATEPEER | Create a new stream based on the object specified in pStreamObject.
AMMSF_NOSTALL | Create a stream that does not block waiting for Update calls.
AMMSF_STOPIFNOSAMPLES | Create a stream that stops if there are not samples.

ppNewStream

[out] Address of a variable that receives an IMediaStream interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
MS_E_PURPOSEID | Invalid purpose ID.
S_OK | Success.

Remarks

If pPurposeID is NULL, pMediaStream must specify an IMediaStream object. The object's GetInformation method is used to determine the purpose ID, which is then used to create the new media stream.

If the purpose ID is MSPID_PrimaryAudio and dwFlags includes the AMMSF_ADDDEFAULTRENDERER flag, the method adds the DirectSound Renderer to the filter graph.

If dwFlags includes the AMMSF_CREATEPEER flag, the method uses the object specified by pStreamObject to create a new media stream. In that case, pStreamObject can specify any of the following:

  • An IAMMediaStream pointer.
  • An IMediaStream pointer.
  • An IDirectDraw pointer.

If neither flag is set, pStreamObject can be any of the following:

  • An IAMMediaStream pointer. The object is added to the multimedia stream.
  • An IDirectDraw pointer. The DirectDraw object is used to create a default video stream.
  • NULL. A defaul media stream object is created.

If the method succeeds, the caller must release the returned IMediaStream interface.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::GetFilter

The GetFilter method retrieves the Media Stream filter, which is used internally by the multimedia stream object.

Syntax

HRESULT GetFilter(
  IMediaStreamFilter **ppFilter
);

Parameters

ppFilter

[out] Address of a variable that receives an IMediaStreamFilter interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Applications should not call this method. The IMediaStreamFilter interface is not intended for applications to use.

If the method succeeds, the caller must release the IMediaStreamFilter interface.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::GetFilterGraph

The GetFilterGraph method retrieves the Filter Graph Manager that is managed by the multimedia stream object.

Syntax

HRESULT GetFilterGraph(
  IGraphBuilder **ppGraphBuilder
);

Parameters

ppGraphBuilder

[out] Address of a variable that receives an IGraphBuilder interface pointer. If there is no filter graph associated with the multimedia stream object, the returned pointer is NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

If the method succeeds and *ppGraphBuilder is non-NULL, the caller must release the IGraphBuilder pointer.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::Initialize

The Initialize method initializes the multimedia stream object.

Syntax

HRESULT Initialize(
  STREAM_TYPE StreamType,
  DWORD dwFlags,
  IGraphBuilder *pFilterGraph
);

Parameters

StreamType

[in] Member of the STREAM_TYPE enumeration, specifying whether the streams are read-only, write-only, or read/write.

dwFlags

[in] Must be one of the following values:

Value | Description
Zero | Create a filter graph that runs on a separate thread.
AMMSF_NOGRAPHTHREAD | Create a filter graph that runs on the calling thread.

pFilterGraph

[in] [optional] Pointer to the IGraphBuilder interface, or NULL. If this parameter is non-NULL, it specifies a filter graph that the multimedia stream object will use. Otherwise, the multimedia stream object creates a new filter graph.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

If you specify AMMSF_NOGRAPHTHREAD in the dwFlags parameter, the calling thread must process window messages, and it must release all multimedia streaming objects before the thread exits. Otherwise, the application might deadlock.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::OpenFile

The OpenFile method opens and automatically creates a filter graph for the specified media file. If DirectShow doesn't support the file format, this method does nothing.

Syntax

HRESULT OpenFile(
  LPCWSTR pszFileName,
  DWORD dwFlags
);

Parameters

pszFileName

[in] Pointer to the name of the file you want to open.

dwFlags

[in] Value that modifies how the filter graph will render the specified file. This value is a combination of one or more of the following flags.

Value | Description
AMMSF_NOCLOCK | Run the stream with no clock.
AMMSF_NORENDER | Open the file, but do not render any streams. This flag should always be accompanied with the AMMSF_RUN flag.
AMMSF_RENDERALLSTREAMS | Render all streams, including those that do not have an existing media stream.
AMMSF_RENDERTOEXISTING | Only render to existing streams.
AMMSF_RUN | Set the stream into the run state.

Return Values

Returns one of the following values.

Return code | Description
E_INVALIDARG | The dwFlags parameter is invalid.
E_POINTER | This method tried to access an invalid pointer.
S_OK | Success.

Remarks

The AMMSF_RENDERALLSTREAMS flag will create default rendering filters for video and audio if they do not exist. However, these default filters cannot be accessed by the IStreamSample::GetMediaStream method.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::OpenMoniker

The OpenMoniker method opens a file or device moniker; you can read media data from this moniker if DirectShow supports the moniker.

Syntax

HRESULT OpenMoniker(
  IBindCtx *pCtx,
  IMoniker *pMoniker,
  DWORD dwFlags
);

Parameters

pCtx

[in] Pointer to the bind context associated with the moniker.

pMoniker

[in] Pointer to an IMoniker interface that specifies the moniker you want to open.

dwFlags

[in] Value that modifies how the filter graph will render the specified file. This value is a combination of one or more of the following flags.

Value | Description
AMMSF_NOCLOCK | Run the stream with no clock.
AMMSF_NORENDER | Open the file, but do not render any streams. This flag should always be accompanied with the AMMSF_RUN flag.
AMMSF_RENDERALLSTREAMS | Render all streams, including those that do not have an existing media stream.
AMMSF_RENDERTOEXISTING | Only render to existing streams.
AMMSF_RUN | Set the stream into the run state.

Return Values

Returns S_OK if successful or E_INVALIDARG if the dwFlags parameter is invalid.

See Also

  • IAMMultiMediaStream Interface


IAMMultiMediaStream::Render

The Render method renders the current filter graph.

Syntax

HRESULT Render(
  DWORD dwFlags
);

Parameters

dwFlags

[in] Value that specifies how the filter graph renders the current multimedia stream. This value currently must be AMMSF_NOCLOCK.

Return Values

Returns S_OK if successful or E_INVALIDARG if the dwFlags parameter is invalid.

Remarks

This method renders each of the source streams for a stream of type STREAMTYPE_WRITE. This can be called several times, for instance, each time a source stream is added, the stream is not set into running mode. Use the IMultiMediaStream::SetState method to set the stream into running mode after calling this method.

The AMMSF_RENDERALLSTREAMS flag will create default rendering streams for video and audio if they do not exist.

See Also

  • IAMMultiMediaStream Interface


IAudioData Interface

The IAudioData interface provides methods that enable applications to set and get the underlying audio data that audio streams will reference. The audio data format is set in the WAVEFORMATEX structure.

Implement this interface on underlying audio data objects that audio stream sample objects will access.

Applications use this interface to set and retrieve information on underlying data objects that an audio stream will reference.

In addition to the methods inherited from IMemoryData, the IAudioData interface exposes the following methods.

Method | Description
GetFormat | Retrieves the current data format.
SetFormat | Sets the current data format.


IAudioData::GetFormat

The GetFormat method retrieves the current data format.

Syntax

HRESULT GetFormat(
  WAVEFORMATEX *pWaveFormatCurrent
);

Parameters

pWaveFormatCurrent

[out] Pointer to a WAVEFORMATEX structure that contains the current data format.

Return Values

Returns S_OK if successful or E_POINTER if pointer is invalid.

Remarks

Currently, Microsoft DirectShow supports only PCM wave data.

See Also

  • IAudioData Interface
  • IAudioData::SetFormat


IAudioData::SetFormat

The SetFormat method sets the current data format.

Syntax

HRESULT SetFormat(
  const WAVEFORMATEX *lpWaveFormat
);

Parameters

lpWaveFormat

[in] Pointer to a WAVEFORMATEX structure that will contain the current data format.

Return Values

Returns an HRESULT value, which can include the following values.

Return code | Description
E_POINTER | Invalid pointer argument.
E_INVALIDARG | Invalid format.
S_OK | Success.

See Also

  • IAudioData Interface
  • 9IAudioData::GetFormat


IAudioMediaStream Interface

The IAudioMediaStream interface controls audio media streams by providing methods that set and get the stream's format. This interface inherits from the IMediaStream interface and is used to create one or more IAudioStreamSample objects. You can also use it to set and retrieve the stream data's current format.

This interface is currently defined only for PCM format audio data.

For sample code that implements the audio streaming interfaces, see Multimedia Streaming Sample Code.

Like video, audio is contained in a self-describing container object. Implement this interface when an object needs to control streaming audio.

Use this interface when you want to generate audio in your application.

In addition to the methods inherited from IMediaStream, the IAudioMediaStream interface exposes the following methods.

Method | Description
CreateSample | Creates an audio stream sample for use with this stream.
GetFormat | Retrieves the stream data's current format.
SetFormat | Sets the format for the stream.


IAudioMediaStream::CreateSample

Creates an audio stream sample for use with the specified stream.

Syntax

HRESULT CreateSample(
  IAudioData *pAudioData,
  DWORD dwFlags,
  IAudioStreamSample **ppSample
);

Parameters

pAudioData

[in] Pointer to an IAudioData container. IAudioData objects can be referenced by samples in more than one stream.

dwFlags

[in] Reserved for flag data. Must be zero.

ppSample

[out] Address of a pointer to the new IAudioStreamSample interface.

Return Values

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

Remarks

The pAudioData object defines the data's format.

See Also

  • IAudioMediaStream Interface


IAudioMediaStream::GetFormat

Retrieves the stream data's current format.

Syntax

HRESULT GetFormat(
  WAVEFORMATEX *pWaveFormatCurrent
);

Parameters

pWaveFormatCurrent

[out] Pointer to a WAVEFORMATEX structure that contains the stream data's current format.

Return Values

Returns S_OK if successful or E_POINTER if the required parameter is NULL.

Remarks

Currently, Microsoft DirectShow supports only PCM wave data.

See Also

  • IAudioMediaStream Interface


IAudioMediaStream::SetFormat

Sets the format for the stream.

Syntax

HRESULT SetFormat(
  const WAVEFORMATEX *lpWaveFormat
);

Parameters

lpWaveFormat

[in] Pointer to a WAVEFORMATEX structure that contains stream format information.

Return Values

Returns an HRESULT value, which can include the following values or others not listed.

Return code | Description
MS_E_INCOMPATIBLE | Format of the IAudioData object is not compatible with stream.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
S_OK | Success.

See Also

  • IAudioMediaStream Interface


IAudioStreamSample Interface

The IAudioStreamSample interface retrieves information from the underlying IAudioData data objects.

For sample code that implements the audio streaming interfaces, see Multimedia Streaming Sample Code.

Implement this interface on audio stream sample objects when they need access to an IAudioData object's data.

Use this interface when your application needs to access an IAudioData object's data for its audio stream.

In addition to the methods inherited from IStreamSample, the IAudioStreamSample interface exposes the following method.

Method | Description
GetAudioData | Retrieves the address of a pointer to the IAudioData object associated with the sample.


IAudioStreamSample::GetAudioData

Retrieves the address of a pointer to the IAudioData object associated with the sample.

Syntax

HRESULT GetAudioData(
  IAudioData **ppAudio
  );

Parameters

ppAudio

[out] Address of a pointer to the IAudioData object.

Return Values

Returns S_OK if successful or E_POINTER if the parameter is NULL.

See Also

  • IAudioStreamSample Interface


IDirectDraw Interface

The IDirectDraw interface is exposed on DirectDraw objects used in the DirectShow multimedia streaming APIs and is included in the DirectShow documentation for convenience.

The DirectDraw object represents the display hardware. The object is hardware-accelerated if the display device for which it was instantiated has hardware acceleration. The three objects which can be created by a DirectDraw object are the DirectDrawSurface, DirectDrawPalette, and DirectDrawClipper objects.

The DirectDraw object manages all of the objects it creates. It controls the default palette if the primary surface is in 8-bpp mode, the default color key values, and the hardware's display mode. It knows what resources have been allocated and what resources remain to be allocated.

Changing the display mode is an important piece of the functionality of DirectDraw. The display mode resolution can be changed at any time unless another application has obtained exclusive access to DirectDraw. The pixel depth of the display mode can only be changed if the application requesting the change has obtained exclusive access to the DirectDraw object. All DirectDrawSurface objects lose their surface memory and become inoperative when the mode is changed. These surfaces' memory must be reallocated using the Restore method

In addition to the methods inherited from IUnknown, the IDirectDraw interface includes the following methods.

Method | Description
Compact | Not yet implemented.
CreateClipper | Creates a DirectDrawClipper object.
CreatePalette | Creates a DirectDrawPalette object for this DirectDraw object.
CreateSurface | Creates a DirectDrawSurface object for this DirectDraw object.
DuplicateSurface | Duplicates a DirectDrawSurface object.
EnumDisplayModes | Enumerates all of the display modes the hardware exposes through the DirectDraw object that are compatible with a provided surface description.
EnumSurfaces | Enumerates all of the existing or possible surfaces that meet the search criterion specified.
FlipToGDISurface | Makes the surface that GDI writes to the primary surface.
GetCaps | Fills in the raw (not remaining) capabilities of the device driver (the hardware) and/or the Hardware Emulation Layer (HEL).
GetDisplayMode | Returns the current display mode.
GetFourCCCodes | Gets the FourCCCodes supported by the DirectDraw object.
GetGDISurface | Returns the DirectDrawSurface object that currently represents the surface memory that GDI treats as the primary surface.
GetMonitorFrequency | Returns the frequency of the monitor being driven by the DirectDraw object.
GetScanLine | Returns the scan line that the monitor is currently updating to the display.
GetVerticalBlankStatus | Returns the status of the vertical blank.
Initialize | Initializes the DirectDraw object.
RestoreDisplayMode | Resets the mode of the display device hardware for the primary surface to what it was before the SetDisplayMode method was called to change it.
SetCooperativeLevel | Determines the top-level behavior of the application.
SetDisplayMode | Sets the mode of the display device hardware. SetCooperativeLevel must be used to set exclusive level access before the mode can be changed.
WaitForVerticalBlank | Used to help the caller synchronize itself with the vertical blank interval.


IDirectDraw::Compact

Not yet implemented.

The Compact method moves all of the pieces of surface memory on the video card to a contiguous block to make the largest chunk of free memory available. This call will fail if any operations are in progress. The application calling this method must have set its cooperative level to exclusive.

Syntax

HRESULT Compact();

Parameters

This method takes no parameters.

Return Values

Possible return values include the following.

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | The object is invalid.
DDERR_INVALIDPARAMS | One or more input parameters are invalid.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.

See Also

  • IDirectDraw Interface


IDirectDraw::CreateClipper

The CreateClipper method creates a DirectDrawClipper object. The DirectDrawClipper object can be attached to a DirectDrawSurface if desired, and used during Blt, BltBatch, and UpdateOverlay operations.

Syntax

HRESULT CreateClipper(
  DWORD dwFlags,
  LPDIRECTDRAWCLIPPER FAR *lplpDDClipper,
  IUnknown FAR *pUnkOuter
  );

Parameters

dwFlags

Not currently used. Zero is the only valid value.

lplpDDClipper

Points to a pointer which will be filled in with the address of the new DirectDrawClipper object if the CreateClipper method is successful.

pUnkOuter

This parameter is provided for future compability with COM aggregation features. Presently, however, CreateClipper returns an error if it is anything but NULL.

Return Values

Value | Description
DDERR_INVALIDOBJECT | The object is invalid.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_NOCOOPERATIVELEVELSET | Create function called without SetCooperativeLevel being called.

See Also

  • IDirectDraw Interface


IDirectDraw::CreatePalette

The CreatePalette method creates a DirectDrawPalette object for this DirectDraw object.

Syntax

HRESULT CreatePalette(
  DWORD dwFlags,
  LPPALETTEENTRY lpColorTable,
  LPDIRECTDRAWPALETTE FAR* lplpDDPalette,
  IUnknown FAR *pUnkOuter
  );

Parameters

dwFlags

May be one of the following values.

Value | Description
DDPCAPS_4BIT | Index is 4 bits. There are sixteen color entries in the palette table.
DDPCAPS_8BITENTRIES | Index is onto an 8-bit color index. This member is only valid with the DDPCAPS_4BITINDEX capability and the target surface is in 8bpp. Each color entry is one byte long and is an index into the destination surface's 8bpp palette.
DDPCAPS_8BIT | Index is 8 bits. There are 256 color entries in the palette table.
DDPCAPS_ALLOW256 | This palette can have all 256 entries defined.
DDPCAPS_INITIALIZE | Indicates that this DirectDrawPalette object should use the palette color array passed into the lpDDColorArray parameter to initialize the DirectDrawPalette object.

lpColorTable

Points to an array of 16 or 256 PALETTEENTRY structures that should be used to initialize this DirectDrawPalette object.

lplpDDPalette

Points to a pointer which will be filled in with the address of the new DirectDrawPalette object if the CreatePalette method is successful.

pUnkOuter

This parameter is provided for future compability with COM aggregation features. Presently, however, CreatePalette will return an error if it is anything but NULL.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | The object is invalid.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOCOOPERATIVELEVELSET | Create function called without SetCooperativeLevel being called.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.
DDERR_UNSUPPORTED | Action not supported.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_OUTOFCAPS | The hardware needed for the requested operation has already been allocated.

See Also

  • IDirectDraw Interface


IDirectDraw::CreateSurface

The CreateSurface method creates a DirectDrawSurface object for this DirectDraw object.

Syntax

HRESULT CreateSurface(
  LPDDSURFACEDESC lpDDSurfaceDesc,
  LPDIRECTDRAWSURFACE FAR *lplpDDSurface,
  IUnknown FAR *pUnkOuter
  );

Parameters

lpDDSurfaceDesc

Points to the DDSURFACEDESC structure describing the requested surface.

lplpDDSurface

Points to a pointer to be initialized with a valid IDirectDrawSurface interface pointer if the call succeeds.

pUnkOuter

Provided for future compability with COM aggregation features. Presently, however, CreateSurface returns an error if it is anything but NULL.

Return Values

Value | Description
DD_OK | The method succeeded.
DERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_OUTOFVIDEOMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_NODIRECTDRAWHW | A hardware-only DirectDraw object creation was attempted but the driver did not support any hardware.
DDERR_NOCOOPERATIVELEVELSET | Create function called without SetCooperativeLevel being called.
DDERR_INVALIDCAPS | One or more of the caps bits passed to the callback are incorrect.
DDERR_INVALIDPIXELFORMAT | The pixel format was invalid as specified.
DDERR_NOALPHAHW | Operation could not be carried out because there is no alpha accleration hardware present or available.
DDERR_NOFLIPHW | Flipping visible surfaces is not supported.
DDERR_NOZBUFFERHW | Operation could not be carried out because there is no hardware support for zbuffer blitting.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_PRIMARYSURFACEALREADYEXISTS | This process already has created a primary surface.
DDERR_NOEMULATION | Software emulation not available.
DDERR_INCOMPATIBLEPRIMARY | Unable to match primary surface creation request with existing primary surface.

Remarks

The DirectDrawSurface object represents a surface (pixel memory), which usually resides in video card memory but may exist in system memory if video memory is exhausted or if explicitly requested. The method will fail if the hardware cannot provide support for the capabilities requested or has previously allocated those resources to another DirectDrawSurface object.

CreateSurface usually creates one DirectDrawSurface object. However, if the DDSCAPS_FLIP flag is set in the dwCaps member of the DDCAPS structure included in the DDSURFACEDESC structure, CreateSurface will create several DirectDrawSurface objects which are referred to collectively as a complex structure. The additional surfaces created are also referred to as implicit surfaces.

Note DirectDraw does not permit the creation of surfaces that are wider than the primary surface.

See Also

  • IDirectDraw Interface


IDirectDraw::DuplicateSurface

The DuplicateSurface method creates a new DirectDrawSurface object which points to the same surface memory as an existing DirectDrawSurface object. This duplicate can be used just like the original. The surface memory will be released when the last object referencing it is released. The primary surface, 3-D surfaces, or implicitly created surfaces cannot be duplicated.

Syntax

HRESULT DuplicateSurface(
  LPDIRECTDRAWSURFACE lpDDSurface,
  LPLPDIRECTDRAWSURFACE lplpDupDDSurface
  );

Parameters

lpDDSurface

Points to the IDirectDrawSurface interface on the surface to be duplicated.

lplpDupDDSurface

Address of a variable to receive the IDirectDrawSurface interface of the new surface.

Return Values

Value | Description
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_CANTDUPLICATE | Can't duplicate primary and 3-D surfaces, or surfaces that are implicitly created.
DD_OK | The method succeeded.

See Also

  • IDirectDraw Interface


IDirectDraw::EnumDisplayModes

The EnumDisplayModes method enumerates all of the display modes the hardware exposes through the DirectDraw object that are compatible with a provided surface description. If NULL is passed for the surface description, all exposed modes will be enumerated.

Syntax

HRESULT EnumDisplayModes(
  DWORD dwFlags,
  LPDDSURFACEDESC lpDDSurfaceDesc,
  LPVOID lpContext,
  LPDDENUMMODESCALLBACK lpEnumCallback
  );

Parameters

dwFlags

Reserved. Must be zero.

lpDDSurfaceDesc

Points to a DDSURFACEDESC structure to be checked against available modes. If NULL, all modes will be enumerated.

lpContext

A user-defined pointer that will be passed to the callback function each time a mode is enumerated.

lpEnumCallback

Points to the user-defined function the enumeration procedure will call for each mode enumerated. See Remarks.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer to an invalid object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

Remarks

The callback function passed as lpEnumCallback must have the following syntax:

HRESULT EnumCallback(PDDMODDESC lpDDModeDesc, LPVOID lpContext);

The lpDDModeDesc parameter points to a DDMODEDESC structure describing a mode that provides the necessary functionality. This data is read-only.

The lpContext parameter contains the value that was passed in the lpContext parameter of EnumDisplayModes.

The callback function should return one of the following values:

Value | Description
DDENUMRET_OK | Continue the enumeration.
DDENUMRET_CANCEL | Stop the enumeration.

See Also

  • IDirectDraw Interface


IDirectDraw::EnumSurfaces

The EnumSurfaces method enumerates all of the existing or possible surfaces that meet the search criterion specified. If the DDENUMSURFACES_CANBECREATED flag is set, then this method will attempt to temporarily create a surface that meets the criteria. Note that as a surface is enumerated, its reference count is increased. If you are not going to use the surface, release the surface after each enumeration.

Syntax

HRESULT EnumSurfaces(
  DWORD dwFlags,
  LPDDSURFACEDESC lpDDSD,
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK lpEnumCallback
  );

Parameters

dwFlags

May be one of the following values.

Value | Description
DDENUMSURFACES_ALL | Enumerates all of the surfaces that meet the search criterion.
DDENUMSURFACES_MATCH | A search hit is a surface that matches the surface description.
DDENUMSURFACES_NOMATCH | A search hit is a surface that does not match the surface description.
DDENUMSURFACES_CANBECREATED | Enumerates the first surface that can be created which meets the search criterion.
DDENUMSURFACES_DOESEXIST | Enumerates the surfaces that already exist that meet the search criterion.

lpDDSD

A pointer to a DDSURFACEDESC structure defining the surface of interest.

lpContext

A user-defined pointer that will be passed to the callback function each time a surface is enumerated.

lpEnumCallback

Points to the user-defined function the enumeration procedure will call for each mode enumerated. See Remarks.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

Remarks

The callback function passed as lpEnumCallback must have the following syntax:

HRESULT EnumCallback(LPDIRECTDRAWSURFACE lpDDSurface, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext)

If existing surfaces are being enumerated (DDENUMSURFACES_DOESEXIST), The lpDDSurface parameter points to the DirectDrawSurface currently being enumerated. If a potential surface is being enumerated (DDENUMSURFACES_CANBECREATED), then the value is NULL.

The lpDDSurfaceDesc parameter points to the DDSURFACEDESC structure for the existing or potential surface that most closely matches the requested surface.

The lpContext parameter contains the value that was passed in the lpContext parameter of EnumDisplayModes.

The callback function should return one of the following values:

Value | Description
DDENUMRET_OK | Continue the enumeration.
DDENUMRET_CANCEL | Stop the enumeration.

See Also

  • IDirectDraw Interface


IDirectDraw::FlipToGDISurface

The FliptoGDISurface method makes the surface that GDI writes to the primary surface. This call is used at the end of a page-flipping application to ensure that the video memory that GDI is writing to is visible to the user.

Syntax

HRESULT FlipToGDISurface();

Parameters

This method takes no parameters.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_NOTFOUND | Requested item was not found.

See Also

  • IDirectDraw Interface


IDirectDraw::GetCaps

The GetCaps method fills in the raw (not remaining) capabilities of the device driver (the hardware) and/or the Hardware Emulation Layer (HEL).

Syntax

HRESULT GetCaps(
  LPDDCAPS lpDDDriverCaps,
  LPDDCAPS lpDDHELCaps
  );

Parameters

lpDDDriverCaps

Points to a DDCAPS structure that will be filled in with the capabilities of the hardware (as reported by the device driver).

lpDDHELCaps

Points to a DDCAPS structure that will be filled in with the capabilities of the Hardware Emulation Layer (HEL).

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDraw Interface


IDirectDraw::GetDisplayMode

The GetDisplayMode method returns the current display mode. An application should not save this mode in order to restore the display mode on clean up. The mode restoration on clean up should be done with RestoreDisplayMode to avoid mode setting conflicts that can arise in a multi-process environment.

Syntax

HRESULT GetDisplayMode(
  LPDDSURFACEDESC lpDDSurfaceDesc
  );

Parameters

lpDDSurfaceDesc

Points to a DDSURFACEDESC structure that will be filled in with a description of the surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDraw Interface


IDirectDraw::GetFourCCCodes

The GetFourCCCodes method gets the FourCC codes (four-character codes) supported by the DirectDraw object. GetFourCCCodes can also be used to return the number of codes supported.

Syntax

HRESULT GetFourCCCodes(
  DWORD FAR *lpNumCodes,
  DWORD FAR *lpCodes
  );

Parameters

lpNumCodes

Points to a DWORD that contains the number of entries the lpCodes array can hold. If this number is too small to accommodate all the codes, it will be set to the required number and the lpCodes array will be filled with all that will fit.

lpCodes

Points to an array of DWORD's that will be filled in with the FourCC codes supported by this DirectDraw object. If NULL is passed, then lpNumCodes will be set to the number of supported FourCC codes and the method will return.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDraw Interface


IDirectDraw::GetGDISurface

The GetGDISurface method returns the DirectDrawSurface object that currently represents the surface memory that GDI treats as the primary surface.

Syntax

HRESULT GetGDISurface(
  LPDIRECTDRAWSURFACE FAR *lplpGDIDDSSurface
  );

Parameters

lplpGDIDDSSurface

Points to a DirectDrawSurface pointer that will be made to point at the DirectDrawSurface object which is currently controlling GDI's primary surface memory.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOTFOUND | Requested item was not found.

See Also

  • IDirectDraw Interface


IDirectDraw::GetMonitorFrequency

The GetMonitorFrequency method returns the frequency of the monitor being driven by the DirectDraw object.

Syntax

HRESULT GetMonitorFrequency(
  LPDWORD lpdwFrequency
  );

Parameters

lpdwFrequency

Points to the DWORD that will be filled in with the monitor frequency, in 100-Hz units. (For example, 60 Hz is returned as 6000.)

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDraw Interface


IDirectDraw::GetScanLine

The GetScanLine method returns the scan line that the monitor is currently updating to the display.

Syntax

HRESULT GetScanLine(
  LPDWORD lpdwScanLine
  );

Parameters

lpdwScanLine

Points to the DWORD that will contain the scan line the display is currently on.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_UNSUPPORTED | Action not supported.
DDERR_VERTICALBLANKINPROGRESS | Vertical blank is in progress.

See Also

  • IDirectDraw Interface


IDirectDraw::GetVerticalBlankStatus

The GetVerticalBlankStatus method returns the status of the vertical blank. It will set the passed BOOL to TRUE if it is in the vertical blank and FALSE otherwise. To synchronize with the vertical blank, consider using WaitForVerticalBlank.

Syntax

HRESULT GetVerticalBlankStatus(
  LPBOOL lpbIsInVB
  );

Parameters

lpbIsInVB

Points to the BOOL that will be filled in with the status of the vertical blank.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDraw Interface


IDirectDraw::Initialize

The Initialize method initializes the DirectDraw object. This method is provided for compliance with the Common Object Model (COM) protocol. Since the DirectDraw object is initialized when it is created, calling this method will always result in the ALREADYINITIALIZED return value.

Syntax

HRESULT Initialize(
  GUID FAR *lpGUID
  );

Parameters

lpGUID

Points to the GUID used as the interface identifier.

Return Values

Value | Description
DDERR_ALREADYINITIALIZED | This object is already initialized.

See Also

  • IDirectDraw Interface


IDirectDraw::RestoreDisplayMode

The RestoreDisplayMode method resets the mode of the display device hardware for the primary surface to what it was before the SetDisplayMode method was called to change it. Exclusive level access is required to use this method.

Syntax

HRESULT RestoreDisplayMode();

Parameters

This method takes no parameters.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_LOCKEDSURFACES | Operation could not be carried out because one or more surfaces are locked.
DDERR_GENERIC | Generic failure.
DDERR_EXCLUSIVEMODENOTOWNED | The application does not have exclusive mode.

See Also

  • IDirectDraw Interface


IDirectDraw::SetCooperativeLevel

The SetCooperativeLevel method determines the top-level behavior of the application. DDSCL_EXCLUSIVE level is needed to call functions that can have drastic performance consequences for other applications. In order to call Compact, change the display mode, or modify the behavior (for example flipping) of the primary surface, an application must have obtained exclusive level. If an application calls SetCooperativeLevel with DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN, DirectDraw will attempt to resize its window to full screen. An application must either set the DDSCL_EXCLUSIVE or DDSCL_NORMAL flags, and DDSCL_EXCLUSIVE requires DDSCL_FULLSCREEN.

ModeX modes are only available if an application sets DDSCL_ALLOWMODEX | DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE. DDSCL_ALLOWMODEX cannot be used with DDSCL_NORMAL. If DDSCL_ALLOWMODEX is not specifed, EnumDisplayModes will not enumerate the ModeX modes, and SetDisplayMode will fail when a ModeX mode is requested. The set of supported display modes may change after using SetCooperativeLevel.

Because the ModeX modes are not supported by Windows, when in a ModeX mode you cannot lock the primary surface, blit to the primary surface, use GetDC on the primary surface, or use GDI with a screen DC. ModeX modes are indicated by the DDCAPS_MODEX flag in the ddscaps member of the DDSURFACEDESC structure returned by IDirectDrawSurface::GetCaps and EnumDisplayModes.

Syntax

HRESULT  SetCooperativeLevel(
  HWND hWnd,
DWORD dwFlags
);

Parameters

hWnd

Window handle used for the application.

dwFlags

May be one of the following values.

Value | Description
DDSCL_ALLOWMODEX | Allow use of ModeX display modes.
DDSCL_ALLOWREBOOT | Allow CTRL_ALT_DEL to function while in full screen exclusive mode.
DDSCL_EXCLUSIVE | Application requests exclusive level.
DDSCL_FULLSCREEN | Exclusive mode owner will be responsible for the entire primary surface. GDI can be ignored.
DDSCL_NORMAL | Application will function as a regular Windows application.
DDSCL_NOWINDOWCHANGES | Do not allow DirectDraw to minimize or restore the application window on activation.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_EXCLUSIVEMODEALREADYSET | An attempt was made to set the cooperative level when it was already set to exclusive.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_HWNDALREADYSET | The cooperative level has already been set. It can not be reset while the process has surfaces or palettes created.
DDERR_HWNDSUBCLASSED | The window used by DirectDraw has been subclassed; this prevents DirectDraw from restoring the state.

See Also

  • IDirectDraw Interface


IDirectDraw::SetDisplayMode

The SetDisplayMode method sets the mode of the display device hardware. SetCooperativeLevel must be used to set exclusive level access before the mode can be changed. If other applications have created a DirectDrawSurface object on the Primary Surface and the mode is changed, those applications' Primary Surface objects will return DDERR_SURFACELOST until they are restored.

Syntax

HRESULT SetDisplayMode(
  DWORD dwWidth,
  DWORD dwHeight,
  DWORD dwBpp
  );

Parameters

dwWidth

Width of the new mode.

dwHeight

Height of the new mode.

dwBpp

Bits per pixel of the new mode.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_GENERIC | Generic failure.
DDERR_UNSUPPORTED | Action not supported.
DDERR_INVALIDMODE | The display mode is not valid.
DDERR_LOCKEDSURFACES | Operation could not be carried out because one or more surfaces are locked.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.

See Also

  • IDirectDraw Interface


IDirectDraw::WaitForVerticalBlank

The WaitForVerticalBlank method is used to help the caller synchronize itself with the vertical blank interval. Depending on the option set with dwFlags, WaitForVerticalBlank will 1) block until blank begins, 2) block until blank ends, or 3) trigger an event when the blank interval begins.

Syntax

HRESULT WaitForVerticalBlank(
  DWORD dwFlags,
  HANDLE hEvent
  );

Parameters

dwFlags

Determines how to wait for the vertical blank. May be one of the following values.

Value | Description
DDWAITVB_BLOCKBEGIN | Return when the vertical blank interval begins.
DDWAITVB_BLOCKBEGINEVENT | Set up an event to trigger when the vertical blank begins. Not currently supported.
DDWAITVB_BLOCKEND | Return when the vertical blank interval ends and display begins.

hEvent

Handle for the event that should be triggered when the vertical blank begins.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDraw Interface


IDirectDrawClipper Interface

Clip lists are managed by DirectDraw using the DirectDrawClipper object. A clipper can be attached to any surface. A window handle can also be attached to a clipper, in which case DirectDraw will update the clipper's clip list with the clip list for the window as it changes.

In addition to the methods inherited from IUnknown, the IDirectDrawClipper interface contains the following methods.

Method | Description
GetClipList | Returns a copy of the clip list associated with a clipper.
GetHWnd | Returns the hWnd previously associated with this clipper using the SetHWnd method.
Initialize | Initializes a clipper.
IsClipListChanged | If a window handle is associated with a clipper, this method can be used to monitor the status of the clip list.
SetClipList | Sets or deletes the clip list.
SetHWnd | Sets the HWnd that will be used to obtain clipping information.


IDirectDrawClipper::GetClipList

The GetClipList method returns a copy of the clip list associated with a DirectDrawClipper object. A subset of the clip list can be selected by passing a rectangle which will be used to clip the clip list.

Syntax

HRESULT GetClipList(
  LPRECT lpRect,
  LPRGNDATA lpClipList,
  LPDWORD lpdwSize
  );

Parameters

lpRect

Points to a rectangle that will be used to clip the clip list.

lpClipList

Points to a RGNDATA structure which will contain the resulting copy of the clip list.

lpdwSize

Set by GetClipList to indicate the size of the resulting clip list.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.
DDERR_INVALIDCLIPLIST | DirectDraw does not support the provided clip list.
DDERR_NOCLIPLIST | No clip list available.
DDERR_REGIONTOOSMALL | Region passed to GetClipList is too small.
DDERR_GENERIC | Generic failure.

See Also

  • IDirectDrawClipper Interface


IDirectDrawClipper::GetHWnd

The GetHWnd method returns the window handle previously associated with this DirectDrawClipper object by using the SetHWnd method.

Syntax

HRESULT GetHWnd(
  HWND FAR *lphWnd
);

Parameters

lphWnd

Points to the window handle previously associated with this clipper using the SetHWnd method.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.

See Also

  • IDirectDrawClipper Interface


IDirectDrawClipper::Initialize

The Initialize method initializes a DirectDrawClipper object. This method is provided for compliance with COM. Since the DirectDrawClipper object is initialized when it is created, this method always returns DDERR_ALREADYINITIALIZED.

Syntax

HRESULT Initialize(
  LPDIRECTDRAW lpDD,
  DWORD dwFlags
);

Parameters

lpDD

Points to the IDirectDraw interface of the DirectDraw object.

dwFlags

Not currently used.

Return Values

Value | Description
DDERR_ALREADYINITIALIZED | This object is already initialized.

See Also

  • IDirectDrawClipper Interface


IDirectDrawClipper::IsClipListChanged

The IsClipListChanged method is used to monitor the status of the clip list.

Syntax

HRESULT IsClipListChanged(
  BOOL FAR *lpbChanged
);

Parameters

lpbChanged

A pointer to a Boolean value set to TRUE if the clip list has changed.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.

See Also

  • IDirectDrawClipper Interface


IDirectDrawClipper::SetClipList

The SetClipList method sets or deletes the clip list used by the Blt, BltBatch, and UpdateOverlay methods of surfaces to which the parent DirectDrawClipper is attached. The clip list is a series of rectangles that describe the areas of the surface that are visible. The clip list cannot be set if there is already a window handle associated with the DirectDrawClipper object. Note that the BltFast method cannot clip.

Syntax

HRESULT SetClipList(
  LPRGNDATA lpClipList,
  DWORD dwFlags
);

Parameters

lpClipList

This is either a pointer to a valid RGNDATA or NULL. If it is NULL, and there is an existing clip list associated with the DirectDrawClipper, it will be deleted.

dwFlags

Not used at this time.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.
DDERR_INVALIDCLIPLIST | DirectDraw does not support the provided clip list.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_CLIPPERISUSINGHWND | An attempt was made to set a clip list for a clipper object that is already monitoring an hwnd.

See Also

  • IDirectDrawClipper Interface


IDirectDrawClipper::SetHWnd

The SetHWnd method sets the window handle that will be used to obtain clipping information.

Syntax

HRESULT SetHWnd(
  DWORD dwFlags,
  HWND hWnd
);

Parameters

dwFlags

Not in use.

hWnd

The window handle associated with the clipping information.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.

See Also

  • IDirectDrawClipper Interface


IDirectDrawMediaStream Interface

The IDirectDrawMediaStream interface controls media streams that appear on Microsoft DirectDraw surfaces. To stream to a DirectDraw surface, DirectDraw must support the video stream format.

For sample code that implements the multimedia streaming interfaces, see Multimedia Streaming Sample Code.

This interface isn't intended for implementation by application developers. It is exposed on DirectDraw media streams that can be added to a DirectShow multimedia stream.

Use this interface when you want to send a video stream to a DirectDraw surface.

In addition to the methods inherited from IMediaStream, the IDirectDrawMediaStream interface exposes the following methods.

Method | Description
CreateSample | Creates a stream sample using the specified DirectDraw surface object.
GetDirectDraw | Retrieves a pointer to the DirectDraw object used by the current media stream.
GetFormat | Retrieves the current media stream's format and, optionally, its desired format.
GetTimePerFrame | Retrieves the average frames per second from a video stream.
SetDirectDraw | Sets the current media stream's DirectDraw object.
SetFormat | Sets the current media stream's format. If the stream already has allocated samples and the sample format doesn't match the specified format, this method fails.


IDirectDrawMediaStream::CreateSample

Creates a stream sample using the specified DirectDraw surface object.

Syntax

HRESULT CreateSample(
  IDirectDrawSurface *pSurface,
  const RECT *pRect,
  DWORD dwFlags,
  IDirectDrawStreamSample **ppSample
);

Parameters

pSurface

[in] Pointer to an existing DirectDraw surface. Use QueryInterface to obtain the IDirectDrawSurface interface from an IDirectDrawSurface7 interface.

pRect

[in] Pointer to the clipping rectangle you want to use with the specified surface. Set this parameter to NULL if you want to use the entire surface.

dwFlags

[in] Specifies miscellaneous flags. The following flag is defined:

Value | Description
DDSFF_PROGRESSIVERENDER | If this flag is set, sample updates are performed directly on the surface. When this flag is absent, if the decoder uses delta frames, an extra copy is performed internally. Setting this flag can improve performance but can also introduce tearing.

ppSample

[out] Address of a pointer to an IDirectDrawStreamSample interface that will point to the newly created sample.

Return Values

Returns one of the following values.

Return code | Description
DDERR_INVALIDPIXELFORMAT | The specified pixel format is incompatible with the stream format.
DDERR_INVALIDRECT | The specified clipping rectangle is invalid.
DDERR_INVALIDSURFACETYPE | The specified surface is incompatible with the stream format.
E_POINTER | One or more of the required parameters is invalid.
MS_E_SAMPLEALLOC | The stream already has allocated samples and the surface doesn't match the sample format.
S_OK | Success.

Remarks

This method creates a sample from the current stream and attaches the sample to this surface.

If the stream doesn't have an allocated surface and the specified surface doesn't match the stream's format, this method calls the IDirectDrawMediaStream::SetFormat method on the stream so the two will match.

To perform a progressive render, create a single sample and repeatedly use that sample for successive frames of video. Video decompressors use this technique to do partial updates to the previous frame.

The pRect parameter should match the format of the stream (see IDirectDrawMediaStream::GetFormat). If the wrong clip rectangle is set or no clip rectangle is set, and the surface size does not match the movie size, the movie might not play. If a primary surface is used, it is advisable to use a clipping rectangle because the primary surface size can change if the user changes display settings.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawMediaStream::GetDirectDraw

Retrieves a pointer to the DirectDraw object used by the current media stream.

Syntax

HRESULT GetDirectDraw(
  IDirectDraw **ppDirectDraw
  );

Parameters

ppDirectDraw

[out] Address of a pointer to an IDirectDraw interface that will contain the current media stream's associated DirectDraw object.

Return Values

Returns S_OK if successful or E_POINTER if the parameter is invalid.

Remarks

If you haven't initialized the stream yet, the retrieved pointer will be NULL and the method will return S_OK. If you have initialized the stream, this method increments the retrieved pointer's reference count.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawMediaStream::GetFormat

Retrieves the current media stream's format and, optionally, its desired format.

Syntax

HRESULT GetFormat(
  DDSURFACEDESC *pDDSDCurrent,
  IDirectDrawPalette **ppDirectDrawPalette,
  DDSURFACEDESC *pDDSDDesired,
  DWORD *pdwFlags
  );

Parameters

pDDSDCurrent

[out] Pointer to a DirectDraw surface description that will contain the current media stream's format.

ppDirectDrawPalette

[out] Address of a pointer to an IDirectDrawPalette interface if one exists.

pDDSDDesired

[out] Pointer to a DirectDraw surface description that will contain the current media stream's desired format.

pdwFlags

[out] Pointer to the flags set in a DDSURFACEDESC structure. Flags of interest include:

Flag | Description
DDSD_CAPS | Indicates that the surface capability member of the structure is valid.
DDSD_HEIGHT | Indicates that the height member of the structure is valid.
DDSD_PIXELFORMAT | Indicates that the pixel format member of the structure is valid.
DDSD_WIDTH | Indicates that the width member of the structure is valid.

Return Values

Returns one of the following values.

Return code | Description
DDERR_INVALIDPARAMS | One of the DirectDraw surface parameters is invalid.
E_POINTER | One or more of the required parameters is invalid.
S_OK | Success.

Remarks

After you call this method, you can either conform to the current format or attempt to change the format by calling the IDirectDrawMediaStream::SetFormat method.

All of this method's parameters are optional; set any of them to NULL to indicate that you don't want to retrieve that information.

To perform a progressive render, create a single sample and repeatedly use that sample for successive frames of video. Video decompressors use this technique to do partial updates to the previous frame.

You must initialize the dwSize member of the DDSURFACEDESC structure before calling this method.

The DDSD_CAPS flag will return one of the values listed in the DDSCAPS structure or DDSCAPS_DATAEXCHANGE, which is defined as DDSCAPS_SYSTEMMEMORY|DDSCAPS_VIDEOMEMORY in Ddrawex.h.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawMediaStream::GetTimePerFrame

Retrieves the average frames per second from a video stream.

Syntax

HRESULT GetTimePerFrame(
  STREAM_TIME *pFrameTime
  );

Parameters

pFrameTime

[out] Pointer to a STREAM_TIME value that indicates the average time per frame in 100-nanosecond units. (See Multimedia Streaming Data Types.)

Return Values

Returns S_OK if successful or E_POINTER if the pointer is invalid.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawMediaStream::SetDirectDraw

Sets the current media stream's DirectDraw object.

Syntax

HRESULT SetDirectDraw(
  IDirectDraw *pDirectDraw
  );

Parameters

pDirectDraw

[in] Pointer to an IDirectDraw interface that contains the media stream's new DirectDraw object.

Return Values

Returns S_OK if successful or E_POINTER if the pointer is invalid.

Remarks

This method fails if the current stream already has allocated samples and its DirectDraw object differs from the specified one. It will always succeed if the specified DirectDraw object matches the stream's current object.

If this stream has no allocated samples, you can set pDirectDraw to NULL. This forces the stream to release its reference to the current DirectDraw object.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawMediaStream::SetFormat

Sets the format of the current media stream.

Syntax

HRESULT SetFormat(
  const DDSURFACEDESC *pDDSurfaceDesc,
  IDirectDrawPalette *pDirectDrawPalette
  );

Parameters

pDDSurfaceDesc

[in] Pointer to a DirectDraw surface description that contains the new format.

pDirectDrawPalette

[in] Optional parameter that is a pointer to an IDirectDrawPalette interface.

Return Values

Returns one of the following values.

Return code | Description
DDERR_INVALIDSURFACETYPE | The specified format is incompatible with the current stream.
MS_E_SAMPLEALLOC | Can't change the format because one or more stream samples are already allocated for this stream.
S_OK | Success.

Remarks

If the stream already has allocated samples and the sample format doesn't match the specified format, this method fails. This method always succeeds if the specified format matches the current format.

See Also

  • IDirectDrawMediaStream Interface


IDirectDrawPalette Interface

The DirectDrawPalette object enables direct manipulation of 16- and 256-color palettes. It reserves entries 0 and 255 for 256-color palettes. It reserves no entries for 16-color palettes. It allows direct manipulation of the palette table as a table. This table can have 16- or 24-bit RGB entries representing the colors associated with each of the indexes or, for 16-color palettes, it can also contain indexes to another 256-color palette.

Entries in these tables can be retrieved with the GetEntries method and changed with the SetEntries method. The SetEntries method has a dwFlags parameter that specifies when the changes to the palette should take effect.

DirectDrawPalette objects are usually attached to DirectDrawSurface objects.

Palette animation is straightforward using DirectDrawPalette objects. There are two approaches. The first involves simply changing the palette entries that correspond to the colors which need to be animated. This can be done with a single call to the SetEntries method. The second one requires two DirectDrawPalette objects. The animation is performed by attaching first one object and then the other to the DirectDrawSurface. This can be done using the SetPalette method of the DirectDrawSurface objects.

In addition to the methods inherited from IUnknown, the IDirectDrawPalette interface contains the following methods.

Method | Description
GetCaps | Return the capabilities of this palette object.
GetEntries | Query palette values from a DirectDrawPalette.
Initialize | This method is provided for compliance with the Common Object Model (COM) protocol.
SetEntries | Change entries in a DirectDrawPalette.


IDirectDrawPalette::GetCaps

The GetCaps method returns the capabilities of this palette object.

Syntax

HRESULT GetCaps(
  LPDWORD lpdwCaps
);

Parameters

lpdwCaps

Flags for dwPalCaps.

Flag | Description
DDPCAPS_4BIT | Four-bit palette.
DDPCAPS_8BITENTRIES | Eight-bit palette entries.
DDPCAPS_8BIT | Eight-bit palette.
DDPCAPS_ALLOW256 | This palette can have all 256 entries defined.
DDPCAPS_PRIMARYSURFACE | Allow vertical sync.
DDPCAPS_PRIMARYSURFACELEFT | This palette is the one attached to the primary surface left. Changing this table has an immediate effect on the display for the left eye unless DDPSETPAL_VSYNC is specified and supported.
DDPCAPS_VSYNC | This palette can have modifications to it synced with the monitor's refresh rate.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.

See Also

  • IDirectDrawPalette Interface


IDirectDrawPalette::GetEntries

The GetEntries method queries palette values from a DirectDrawPalette.

Syntax

HRESULT GetEntries(
  DWORD dwFlags,
  DWORD dwBase,
  DWORD dwNumEntries,
  LPPALETTEENTRY lpEntries
  );

Parameters

dwFlags

Not used at this time. Must be zero.

dwBase

This is the start of the entries that should be retrieved sequentially.

dwNumEntries

Number of palette entries in the buffer pointed to by lpEntries.

lpEntries

A pointer to the palette entries. The palette entries are one byte each if the DDPCAPS_8BITENTRIES flag is set in DDCAPS.dwPalCaps, and four bytes otherwise. Each field is a color description.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.
DDERR_NOTPALETTIZED | The surface being used is not a palette-based surface.

See Also

  • IDirectDrawPalette Interface


IDirectDrawPalette::Initialize

The Initialize method is provided for compliance with COM. Because the DirectDrawPalette object is initialized when it is created, this method always returns DDERR_ALREADYINITIALIZED.

Syntax

HRESULT Initialize(
  LPDIRECTDRAW lpDD
  DWORD dwFlags,
  LPPALETTEENTRY lpDDColorTable
  );

Parameters

lpDD

Points to the IDirectDraw interface of the DirectDraw object.

dwFlags

Not used.

lpDDColorTable

Not used.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_ALREADYINITIALIZED | This object is already initialized.

See Also

  • IDirectDrawPalette Interface


IDirectDrawPalette::SetEntries

The SetEntries method changes entries in a palette. The changes are made immediately. The palette must be attached to a surface using the SetPalette method before SetEntries can be used.

Syntax

HRESULT SetEntries(
  DWORD dwFlags,
  DWORD dwStartingEntry,
  DWORD dwCount,
  LPPALETTEENTRY lpEntries
  );

Parameters

dwFlags

Reserved. Must be zero.

dwStartingEntry

The first entry to be set.

dwCount

The number of palette entries to be changed.

lpEntries

The palette entries are one byte each if the DDPCAPS_8BITENTRIES flag is set in DDCAPS.dwPalCaps and four bytes otherwise. Each field is a color description.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_UNSUPPORTED | Action not supported.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the function are incorrect.
DDERR_NOTPALETTIZED | The surface being used is not a palette-based surface.
DDERR_NOPALETTEATTACHED | No palette object attached to this surface.

See Also

  • IDirectDrawPalette Interface


IDirectDrawStreamSample Interface

The IDirectDrawStreamSample interface provides methods that set and retrieve pointers to the Microsoft DirectDraw surface associated with the current stream sample.

This interface isn't intended for implementation by application developers. It is exposed by sample objects created by the DirectDraw stream.

Use this interface when applications need to set clipping rectangles and retrieve the rendering surface for DirectDraw stream samples.

In addition to the methods inherited from IStreamSample, the IDirectDrawStreamSample interface exposes the following methods.

Method | Description
GetSurface | Retrieves pointers to the current sample's DirectDraw surface and associated clipping rectangle.
SetRect | Changes the clipping rectangle for a sample.


IDirectDrawStreamSample::GetSurface

Retrieves pointers to the current sample's DirectDraw surface and associated clipping rectangle.

Syntax

HRESULT GetSurface(
  IDirectDrawSurface **ppDirectDrawSurface,
  RECT *pRect
  );

Parameters

ppDirectDrawSurface

[out] Address of a pointer to an IDirectDrawSurface interface that specifies the sample's new surface. Set this parameter to NULL if you don't want to specify a new surface.

pRect

[out] Pointer to a RECT structure that will contain the current sample's clipping rectangle. Set this parameter to NULL if you don't want to retrieve the clipping rectangle.

Return Values

Returns an HRESULT value.

Remarks

Both parameters are optional. All implementations of this interface must support null values as valid parameters. If you retrieve a surface pointer, this method increments its reference count, so you must release the reference.

See Also

  • IDirectDrawStreamSample Interface


IDirectDrawStreamSample::SetRect

Changes the clipping rectangle for a sample.

Syntax

HRESULT SetRect (
  const RECT *pRect
  );

Parameters

pRect

[in] Pointer to a RECT structure that specifies the stream's new clipping rectangle.

Return Values

Returns one of the following values.

Return code | Description
DDERR_INVALIDPIXELFORMAT | The stream isn't compatible with the pixel format.
DDERR_INVALIDRECT | The specified rectangle is invalid.
DDERR_INVALIDSURFACETYPE | The stream isn't compatible with the surface.
E_POINTER | One of the pointers is invalid.
MS_E_SAMPLEALLOC | The stream format doesn't match the surface and samples are currently allocated to the stream.
S_OK | Success.

Remarks

Both parameters are optional; set either to NULL to avoid changing that value. If the surface format doesn't match the stream format, this method fails.

If the new rectangle's size isn't the same as the current rectangle, a call to this method will fail.

See Also

  • IDirectDrawStreamSample Interface


IDirectDrawSurface Interface

The IDirectDrawSurface interface is exposed on DirectDrawSurface objects that are used in the DirectShow multimedia streaming APIs.

In addition to the methods inherited from IUnknown, the IDirectDrawSurface interface contains the following methods.

Method | Description
AddAttachedSurface | Attaches a Surface to another Surface.
AddOverlayDirtyRect | Used to build up the list of the rectangles that need to be updated the next time the UpdateOverlayDisplay method is called.
Blt | Performs a bit block transfer.
BltBatch | Performs a sequence of Blt operations from several sources to a single destination.
BltFast | Performs a source copy blit or transparent blit using a source or destination color key.
DeleteAttachedSurfaces | Detaches two attached surfaces.
EnumAttachedSurfaces | Enumerates all the surfaces attached to a given surface.
EnumOverlayZOrders | Enumerates the overlays on the specified destination.
Flip | Makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the FRONTBUFFER surface.
GetAttachedSurface | Finds the attached surface that has the specified capabilities.
GetBltStatus | Returns the blitter status.
GetCaps | Returns the capabilities of the surface.
GetClipper | Returns the DirectDrawClipper associated with this surface.
GetColorKey | Returns the color key value for the DirectDrawSurface object.
GetDC | Creates a GDI device context for the surface.
GetFlipStatus | Returns OK if the surface that it is called on has finished its flipping process, otherwise it returns WASSTILLDRAWING.
GetOverlayPosition | Returns the display coordinates of the surface, given a visible, active overlay surface (DDSCAPS_OVERLAY set).
GetPalette | Returns the IDirectDrawPalette interface associated with this surface.
GetPixelFormat | Returns the color and pixel format of the surface.
GetSurfaceDesc | Returns a DDSURFACEDESC structure describing the surface in its current condition.
Initialize | Initializes a DirectDrawSurface.
IsLost | Determines if the surface memory associated with a DirectDrawSurface has been freed.
Lock | Obtains a valid pointer to the surface memory.
ReleaseDC | Releases the device context previously obtained with GetDC.
Restore | Restores a surface that has been "lost" (the surface memory associated with the DirectDrawSurface object has been freed).
SetClipper | Attaches a DirectDrawClipper to a DirectDrawSurface.
SetColorKey | Sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per surface basis.
SetOverlayPosition | Changes the display coordinates of an overlay surface.
SetPalette | Attachs the specified palette to the surface.
Unlock | Notifies DirectDraw that the surface manipulations are complete.
UpdateOverlay | Repositions and modifies the visual attributes of an overlay surface.
UpdateOverlayDisplay | Repaints the rectangles in the dirty rectangle lists of all active overlays.
UpdateOverlayZOrder | Sets the z order of an overlay.


IDirectDrawSurface::AddAttachedSurface

The AddAttachedSurface method attaches a surface to another surface.

Examples of possible attachments include z-buffers, alpha channels, and back buffers. Some attachments automatically break other attachments. For example, the 3DZBUFFER can only be attached to one back buffer at a time. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated (system memory) surfaces cannot be attached to nonemulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size. A flippable surface cannot be attached to another flippable surface of the same type, however it is allowable to attach two surfaces of different types; for example, a flippable Zbuffer can be attached to a regular flippable surface. If a non-flippable surface is attached to another non-flippable surface of the same type, the two surfaces will become a flippable chain. If a non-flippable surface is attached to a flippable surface, it becomes part of the existing flippable chain. Additional surfaces can be added to this chain, and each call of the Flip method will cycle one step through the surfaces.

Syntax

HRESULT AddAttachedSurface(
  LPDIRECTDRAWSURFACE lpDDSAttachedSurface
  );

Parameters

lpDDSAttachedSurface

Points to the DIRECTDRAWSURFACE that is to be attached.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_GENERIC | Generic failure.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACEALREADYATTACHED | This surface is already attached to the surface it is being attached to.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_CANNOTATTACHSURFACE | This surface can not be attached to the requested surface.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::AddOverlayDirtyRect

The AddOverlayDirtyRect method is used to build up the list of the rectangles that need to be updated the next time the UpdateOverlayDisplay method is called. This method is used for the software implementation. It is not needed if the overlay support is provided in hardware.

Syntax

HRESULT AddOverlayDirtyRect(
  LPRECT lpRect
  );

Parameters

lpRect

Points to the RECT structure that needs to be updated.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Blt

The Blt method performs a bit block transfer. This method is capable of synchronous or asynchronous blits, either video memory to video memory, video memory to system memory, system memory to video memory, or system memory to system memory. The blits can be performed using z information, alpha information, source color keys and destination color keys. Arbitrary stretching/shrinking will be performed if the source and destination rectangles are not the same size.

Normally, Blt will return immediately with an error if the blitter is busy and the blit could not be set up. The DDBLT_WAIT flag can be used to alter this behavior such that Blt will wait until the blit can be set up, or another error occurs, before returning.

Syntax

HRESULT Blt(
  LPRECT lpDestRect,
  LPDIRECTDRAWSURFACE lpDDSrcSurface,
  LPRECT lpSrcRect,
  DWORD dwFlags,
  LPDDBLTFX lpDDBltFX
  );

Parameters

lpDestRect

Points to a RECT structure that defines the upper left and lower right points of the rectangle on the destination surface which is to be blted to.

lpDDSrcSurface

Points to the IDirectDrawSurface interface of the DirectDrawSurface object. This is the source for the blit operation.

lpSrcRect

Points to a RECT structure that defines the upper left and lower right points of the rectangle on the source surface which is to be blted from.

dwFlags

Zero or more of the following values.

Value | Description
DDBLT_ALPHADEST | Use the alpha information in the pixel format or the alpha channel surface attached to the destination surface as the alpha channel for this blit.
DDBLT_ALPHADESTCONSTOVERRIDE | Use the dwConstAlphaDest member in the DDBLTFX structure as the alpha channel for the destination surface for this blit.
DDBLT_ALPHADESTNEG | The NEG suffix indicates that the destination surface becomes more transparent as the alpha value increases. (0 is opaque)
DDBLT_ALPHADESTSURFACEOVERRIDE | Use the lpDDSAlphaDest member in the DDBLTFX structure as the alpha channel for the destination for this blit.
DDBLT_ALPHAEDGEBLEND | Use the dwAlphaEdgeBlend member in the DDBLTFX structure as the alpha channel for the edges of the image that border the color key colors.
DDBLT_ALPHASRC | Use the alpha information in the pixel format or the alpha channel surface attached to the source surface as the alpha channel for this blit.
DDBLT_ALPHASRCCONSTOVERRIDE | Use the dwConstAlphaSrc member in the DDBLTFX structure as the alpha channel for the source for this blit.
DDBLT_ALPHASRCNEG | The NEG suffix indicates that the source surface becomes more transparent as the alpha value increases. (0 is opaque)
DDBLT_ALPHASRCSURFACEOVERRIDE | Use the lpDDSAlphaSrc member in the DDBLTFX structure as the alpha channel for the source for this blit.
DDBLT_ASYNC | Do this blit asynchronously through the FIFO in the order received. If there is no room in the hardware FIFO fail the call.
DDBLT_COLORFILL | Uses the dwFillColor member in the DDBLTFX structure as the RGB color to fill the destination rectangle on the destination surface.
DDBLT_DDFX | Uses the dwDDFX member in the DDBLTFX structure to specify the effects to use for the blit.
DDBLT_DDROPS | Uses the dwDDROPS member in the DDBLTFX structure to specify the ROPS that are not part of the Win32 API.
DDBLT_KEYDEST | Use the color key associated with the destination surface.
DDBLT_KEYDESTOVERRIDE | Use the dckDestColorkey member in the DDBLTFX structure as the color key for the destination surface.
DDBLT_KEYSRC | Use the color key associated with the source surface.
DDBLT_KEYSRCOVERRIDE | Use the dckSrcColorkey member in the DDBLTFX structure as the color key for the source surface.
DDBLT_ROP | Use the dwROP member in the DDBLTFX structure for the raster operation for this blit. These ROPs are the same as the ones defined in the Win32 API.
DDBLT_ROTATIONANGLE | Use the dwRotationAngle member in the DDBLTFX structure as the angle (specified in 1/100th of a degree) to rotate the surface.
DDBLT_WAIT | Do not return immediately with the DDERR_WASSTILLDRAWING message if the bltter is busy -- wait until the blit can be set up or another error occurs.
DDBLT_ZBUFFER | Z-buffered blit using the z-buffers attached to the source and destination surfaces and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer opcode.
DDBLT_ZBUFFERDESTCONSTOVERRIDE | Z-buffered blit using the dwConstDest member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the destination.
DDBLT_ZBUFFERDESTOVERRIDE | Z-buffered blit using the lpDDSDestZBuffer member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the destination.
DDBLT_ZBUFFERSRCCONSTOVERRIDE | Z-buffered blit using the dwConstSrcZ member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the source.
DDBLT_ZBUFFERSRCOVERRIDE | Z-buffered blit using the lpDDSSrcZBuffer member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the source.

lpDDBltFx

Pointer to a DDBLTFX structure

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_GENERIC | Generic failure.
DDERR_INVALIDCLIPLIST | DirectDraw does not support the provided clip list.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDRECT | Rectangle provided was invalid.
DDERR_NOALPHAHW | Operation could not be carried out because there is no alpha accleration hardware present or available.
DDERR_NOBLTHW | No blitter hardware present.
DDERR_NOCLIPLIST | No clip list available.
DDERR_NODDROPSHW | No DirectDraw ROP hardware.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_UNSUPPORTED | Action not supported.
DDERR_NOMIRRORHW | Operation could not be carried out because there is no hardware present or available.
DDERR_NORASTEROPHW | Operation could not be carried out because there is no appropriate raster op hardware present or available.
DDERR_NOROTATIONHW | Operation could not be carried out because there is no rotation hardware present or available.
DDERR_NOSTRETCHHW | Operation could not be carried out because there is no hardware support for stretching.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_NOZBUFFERHW | Operation could not be carried out because there is no hardware support for z-buffer blitting.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::BltBatch

The BltBatch method performs a sequence of blit operations from several sources to a single destination.

Syntax

HRESULT BltBatch(
  LPDDBLTBATCH lpDDBltBatch,
  DWORD dwCount,
  DWORD dwFlags
  );

Parameters

lpDDBltBatch

Points to the first DDBLTBATCH structure defining the parameters for the blit operations.

dwCount

The number of blit operations to be performed.

dwFlags

Not currently used.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_GENERIC | Generic failure.
DDERR_INVALIDCLIPLIST | DirectDraw does not support the provided cliplist.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDRECT | Rectangle provided was invalid.
DDERR_NOALPHAHW | Operation could not be carried out because there is no alpha accleration hardware present or available.
DDERR_NOBLTHW | No blitter hardware present.
DDERR_NOCLIPLIST | No cliplist available.
DDERR_UNSUPPORTED | Action not supported.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_NODDROPSHW | No DirectDraw ROP hardware.
DDERR_NOMIRRORHW | Operation could not be carried out because there is no hardware present or available.
DDERR_NORASTEROPHW | Operation could not be carried out because there is no appropriate raster op hardware present or available.
DDERR_NOROTATIONHW | Operation could not be carried out because there is no rotation hardware present or available.
DDERR_NOSTRETCHHW | Operation could not be carried out because there is no hardware support for stretching.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_NOZBUFFERHW | Operation could not be carried out because there is no hardware support for z-buffer blitting.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::BltFast

The BltFast method performs a source copy blit or transparent blit using a source or destination color key. BltFast always attempts to perform an asynchronous blit if the hardware supports this. It only works on video memory surfaces and cannot clip. The software implementation of BltFast is 10% faster than Blt. There is no speed difference if the video hardware is being used.

Normally, BltFast will return immediately with an error if the blitter is busy and the blit could not be set up. The DDBLTFAST_WAIT flag can be used to alter this behavior such that BltFast will wait until the blit can be set up, or another error occurs, before returning.

Syntax

HRESULT BltFast(
  DWORD dwX,
  DWORD dwY,
  LPDIRECTDRAWSURFACE lpDDSrcSurface,
  LPRECT lpSrcRect,
  DWORD dwTrans
  );

Parameters

dwX

X coordinate on destination surface to blit to.

dwY

Y coordinate on destination surface to blit to.

lpDDSrcSurface

Points to the IDirectDrawSurface interface of the source for the blit operation.

lpSrcRect

Points to a RECT structure that defines the upper left and lower right points of the rectangle on the source surface which is to be blted from.

dwTrans

Specify the type of transfer.

Value | Description
DDBLTFAST_DESTCOLORKEY | Transparent blit using the destination's color key.
DDBLTFAST_NOCOLORKEY | Normal copy blit -- no transparency.
DDBLTFAST_SRCCOLORKEY | Transparent blit using the source's color key.
DDBLTFAST_WAIT | Do not return immediately with the DDERR_WASSTILLDRAWING message if the bltter is busy -- wait until the Blt can be set up or another error occurs.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDRECT | Rectangle provided was invalid.
DDERR_EXCEPTION | An exception was encountered while performing the requested operation.
DDERR_UNSUPPORTED | Action not supported.
DDERR_GENERIC | Generic failure.
DDERR_NOBLTHW | No blitter hardware present.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::DeleteAttachedSurfaces

The DeleteAttachedSurfaces method detaches two attached surfaces. The detached surface is not released.

If NULL is passed as the surface to be detached, all attached surfaces will be detached. Implicit attachments (those formed by DirectDraw, rather than AddAttachedSurface) cannot be detached. Detaching surfaces from a flippable chain can change other surfaces in the chain. If a front buffer is detached from a flippable chain, the next surface in the chain becomes the front buffer and the surface following it becomes the back buffer. If a back buffer is detached from a chain, the following surface becomes a back buffer. If a plain surface is detached from a chain, the chain simply becomes shorter. If a flippable chain only has two surfaces and they are detached, the flippable chain is destroyed and both surfaces return to their previous designations.

Syntax

HRESULT DeleteAttachedSurfaces(
  DWORD dwFlags,
  LPDIRECTDRAWSURFACE lpDDSAttachedSurface
  );

Parameters

dwFlags

Reserved. Must be zero.

lpDDSAttachedSurface

Points to the IDirectDrawSurface interface of the surface to be detached. If NULL is passed, all attached surfaces will be detached.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_SURFACENOTATTACHED | The surface is not attached to a DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_CANNOTDETACHSURFACE | This surface can not be detached from the requested surface.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::EnumAttachedSurfaces

The EnumAttachedSurfaces method enumerates all the surfaces attached to a given surface.

Syntax

HRESULT EnumAttachedSurfaces(
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback
  );

Parameters

lpContext

Application-defined value that is passed to the enumeration method every time it is called.

lpEnumSurfacesCallback

Points to the callback function that will be called for each surface that is attached to this surface. See Remarks.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.

Remarks

The callback function passed as lpEnumCallback must have the following syntax:

lpEnumSurfacesCallback(LPDIRECTDRAWSURFACE lpDDSurface,
   LPDDSURFACEDESC pDDSurfaceDesc, LPVOID lpContext);

The lpDDSurface parameter points to the surface that is attached to this surface.

The lpDDSurfaceDesc parameter points to a DDSURFACEDESC structure that describes the attached surface.

The lpContext parameter contains the value that was passed in the lpContext parameter of EnumAttachedSurfaces.

The callback function should return one of the following values:

Value | Description
DDENUMRET_OK | Continue the enumeration.
DDENUMRET_CANCEL | Stop the enumeration.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::EnumOverlayZOrders

The EnumOverlayZOrders method enumerates the overlays on the specified destination. The overlays can be enumerated in front-to-back or back-to-front order.

Syntax

HRESULT EnumOverlayZOrders(
  DWORD dwFlags,
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK lpfnCallback
  );

Parameters

dwFlags

One of the following flags.

Value | Description
DDENUMOVERLAYZ_BACKTOFRONT | Enumerates overlays back-to-front.
DDENUMOVERLAYZ_FRONTTOBACK | Enumerates overlays front-to-back.

lpContext

Points to the user-defined context that will be passed to the callback for each overlay surface.

lpfnCallback

Points to the callback function that will be called for each overlay that is being overlayed on this surface. See Remarks.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

Remarks

The callback function passed as lpEnumCallback must have the following syntax:

lpEnumSurfacesCallback(LPDIRECTDRAWSURFACE lpDDSurface,
   LPDDSURFACEDESC pDDSurfaceDesc, LPVOID lpContext);

The lpDDSurface parameter points to the surface that is overlayed on this surface.

The lpDDSurfaceDesc parameter points to a DDSURFACEDESC structure that describes the overlayed surface.

The lpContext parameter contains the value that was passed in the lpContext parameter of EnumOverlayZOrders.

The callback function should return one of the following values:

Value | Description
DDENUMRET_OK | Continue the enumeration.
DDENUMRET_CANCEL | Stop the enumeration.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Flip

The Flip method makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the FRONTBUFFER surface. This method can only be called by a surface that has the DDSCAPS_FLIP and DDSCAPS_FRONTBUFFER bits set. The video memory previously associated with the front buffer is associated with the back buffer. If there is more than one back buffer, then a ring is formed and the surface memory buffers cycle one step through it every time Flip is invoked.

The TargetOverride parameter is used in rare cases where the BACKBUFFER is not the buffer that should become the FRONTBUFFER. Normally it is NULL.

Flip will always be synchronized with the vertical blank.

Syntax

HRESULT Flip(
  LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride,
  DWORD dwFlags
  );

Parameters

lpDDSurfaceTargetOverride

Points to the IDirectDrawSurface interface of the surface that is to be flipped to. The default for this parameter is NULL, in which case Flip cycles through the buffers in the order they are attached to each other. This parameter is only used as an override.

dwFlags

Can be 0 or the following value.

Value | Description
DDFLIP_WAIT | Normally, if the Flip method cannot be set up because the state of the video hardware is not appropriate, the error DDERR_WASSTILLDRAWING will be returned immediately and no flip will occur. Setting this flag will cause Flip to continue trying if it receives the DDERR_WASSTILLDRAWING error from the HAL. Flip will not return until the flipping operation has been successfully set up or another error, such as SURFACEBUSY, has occurred.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_GENERIC | Generic failure.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_UNSUPPORTED | Action not supported.
DDERR_NOTFLIPPABLE | An attempt has been made to flip a surface that is not flippable.
DDERR_NOFLIPHW | Flipping visible surfaces is not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetAttachedSurface

The GetAttachedSurface method finds the attached surface that has the specified capabilities. Attachments are used to connect multiple DirectDrawSurface objects into complex structures like the ones needed to support 3-D page flipping with Z buffers. GetAttachedSurface will fail if there is more than one surface attached which matches the capabilities requested. In this case the application must use EnumAttachedSurfaces to obtain the non-unique attached surfaces.

Syntax

HRESULT GetAttachedSurface(
  LPDDSCAPS lpDDSCaps,
  LPLPDIRECTDRAWSURFACE FAR *lplpDDAttachedSurface
  );

Parameters

lpDDSCaps

Points to a DDCAPS structure that contains the hardware capabilities of the surface.

lplpDDAttachedSurface

Points to a pointer that will be filled with the address of the DIRECTDRAWSURFACE that is attached to the requesting surface and has the appropriate capabilities.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOTFOUND | Requested item was not found.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetBltStatus

The GetBltStatus method returns the blitter status.

Syntax

HRESULT GetBltStatus(
  DWORD dwFlags
  );

Parameters

dwFlags

One of the following values.

Value | Description
DDGBS_CANBLT | Query whether a blit involving this surface can occur now. The method returns DD_OK if the blit can be completed.
DDGBS_ISBLTDONE | Query whether the blit is done. The method returns DD_OK if the last blit on this surface has completed.

Return Values

Value | Description
DD_OK | The method succeeded and a blitter is present
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_UNSUPPORTED | Action not supported.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_NOBLTHW | No blitter hardware present.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetCaps

The GetCaps method returns the capabilities of the surface. These are not necessarily related to the capabilities of the display device.

Syntax

HRESULT GetCaps(
  LPDDSCAPS lpDDSCaps
  );

Parameters

lpDDCaps

Points to a DDCAPS structure that will be filled in with the hardware capabilities of the surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetClipper

The GetClipper method returns the DirectDrawClipper associated with this surface. It returns an error if there is no DirectDrawClipper associated.

Syntax

HRESULT GetClipper(
  LPDIRECTDRAWCLIPPER FAR * lplpDDClippe
  );

Parameters

lplpDDClipper

Points to a pointer to the IDirectDrawClipper interface with the surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOCLIPPERATTACHED | No clipper object attached to surface object.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetColorKey

The GetColorKey method returns the color key value for the DirectDrawSurface object.

Syntax

HRESULT GetColorKey(
  DWORD dwFlags,
  LPDDCOLORKEY lpDDColorKey
  );

Parameters

dwFlags

Determines which color key is being requested.

Value | Description
DDCKEY_COLORSPACE | Set if the structure contains a colorspace. Not set if the structure contains a single color key.
DDCKEY_DESTBLT | Set if the structure specifies a color key or color space which is to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY | Set if the structure specifies a color key or color space which is to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT | Set if the structure specifies a color key or color space which is to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY | Set if the structure specifies a color key or color space which is to be used as a source color key for overlay operations.

lpDDColorKey

Points to the DDCOLORKEY structure that will be filled in with the current values for the specified color key for the DirectDrawSurface object.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_UNSUPPORTED | Action not supported.
DDERR_NOCOLORKEYHW | Operation could not be carried out because there is no hardware support of the destination color key.
DDERR_NOCOLORKEY | Surface doesn't currently have a color key.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetDC

The GetDC method creates a GDI-compatible device context for the surface. It uses an internal version of the Lock method to lock the surface, and the surface will remain locked until ReleaseDC is called. See the description of the Lock method for more information on this behavior.

Syntax

HRESULT GetDC(
  HDCFAR *lphDC
  );

Parameters

lphDC

Points to the device context returned.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_GENERIC | Generic failure.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetFlipStatus

The GetFlipStatus method returns OK if the surface that it is called on has finished its flipping process, otherwise it returns WASSTILLDRAWING.

Syntax

HRESULT GetFlipStatus(
  DWORD dwFlags
  );

Parameters

dwFlags

One of the following flags.

Value | Description
DDGFS_CANFLIP | Queries whether the surface can flip now. The method returns DD_OK if the flip can be completed.
DDGFS_ISFLIPDONE | Queries whether the flip is done. The method returns DD_OK if the last flip on this surface has completed.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_UNSUPPORTED | Action not supported.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetOverlayPosition

The GetOverlayPosition method returns the display coordinates of the surface, given a visible, active overlay surface (DDSCAPS_OVERLAY set).

Syntax

HRESULT GetOverlayPosition(
  LPLONG lplX,
  LPLONG lplY
  );

Parameters

lplX

Points to the X display coordinate.

lplY

Points to the Y display coordinate.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_GENERIC | Generic failure.
DDERR_NOTAOVERLAYSURFACE | Returned when an overlay method is called for a non-overlay surface.
DDERR_NOOVERLAYDEST | Returned when GetOverlayPosition is called on an overlay that UpdateOverlay has never been called on to establish a destination.
DDERR_OVERLAYNOTVISIBLE | Returned when GetOverlayPosition is called on a hidden overlay.
DDERR_INVALIDPOSITION | Returned when the position of the overlay on the destination is no longer legal for that destination.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetPalette

The GetPalette method returns the IDirectDrawPalette interface associated with this surface. If no palette has been explicitly associated with this surface then it returns NULL for the associated palette, unless this is the primary surface or a back buffer to the primary surface, in which case it returns a pointer to the system palette if the primary surface is in 8bpp mode.

Syntax

HRESULT GetPalette(
  LPLPDIRECTDRAWPALETTE lplpDDPalette
  );

Parameters

lplpDDPalette

Points to a pointer to an IDirectDrawPalette interface. This will be set to NULL if there is no palette associated with this surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_UNSUPPORTED | Action not supported.
DDERR_GENERIC | Generic failure.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.
DDERR_NOPALETTEATTACHED | No palette object attached to this surface.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetPixelFormat

The GetPixelFormat method returns the color and pixel format of the surface.

Syntax

HRESULT GetPixelFormat(
  LPDDPIXELFORMAT lpDDPixelFormat
  );

Parameters

lpDDPixelFormat

Points to the DDPIXELFORMAT structure which will be filled in with a detailed description of the current pixel and color space format of the surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::GetSurfaceDesc

The GetSurfaceDesc method returns a DDSURFACEDESC structure describing the surface in its current condition.

Syntax

HRESULT GetSurfaceDesc(
  LPDDSURFACEDESC lpDDSurfaceDesc
  );

Parameters

lpDDSurfaceDesc

Points to a DDSURFACEDESC structure to be filled in with the current description of this surface.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Initialize

The Initialize method initializes a DirectDrawSurface. This method is provided for compliance with COM. Because the DirectDrawSurface object is initialized when it is created, this method always returns DDERR_ALREADYINITIALIZED.

Syntax

HRESULT Initialize(
  LPDIRECTDRAW lpDD,
  LPDDSURFACEDESC lpDDSurfaceDesc
  );

Parameters

lpDD

Points to the IDirectDraw interface of the DirectDraw object.

lpDDSurfaceDesc

Points to a DDSURFACEDESC structure to be filled in with the relevant details about the surface.

Return Values

Value | Description
DDERR_ALREADYINITIALIZED | This object is already initialized.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::IsLost

The IsLost method determines if the surface memory associated with a DirectDrawSurface has been freed. If the memory has not been freed, this method will return DD_OK. The Restore method can be used to reallocate surface memory. When a DirectDrawSurface object loses its surface memory, most methods will return DDERR_SURFACELOST and perform no other function.

Surfaces can lose their memory when the mode of the display card is changed, or because an application received exclusive access to the display card and freed all of the surface memory currently allocated on the video card.

Syntax

HRESULT IsLost();

Parameters

This method takes no parameters.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Lock

The Lock method obtains a valid pointer to the surface memory. DirectDraw relies on the application calling Unlock. It is illegal behavior to Blt from a region of a surface that is locked.

An application should call the Lock method with a RECT structure specifying the rectangle on the surface that the application wants access to. If the application calls Lock with a NULL RECT then the application is assumed to be requesting exclusive access to the entire piece of surface memory.

The Lock method fills in a DDSURFACEDESC structure with the information needed by the application to access the surface memory. This information includes the stride (or pitch) and the pixel format of the surface if it is different from the pixel format of the primary surface. The DDSURFACEDESC structure also contains a pointer to the surface memory. Since it is possible to call Lock multiple times for the same Surface with different destination rectangles, this pointer is used to tie the Lock and Unlock calls together.

Normally, Lock will return immediately with an error when a lock cannot be obtained because a blit is in progress. The DDLOCK_WAIT flag can be used to alter this behavior.

In order to prevent VRAM from being lost during access to a surface, DirectDraw holds the Win16 lock between Lock and Unlock operations. The Win16 lock is the critical section used to serialize access to GDI and USER. Although this technique allows direct access to video memory and prevents other applications from changing the mode during this access, it will stop Windows from running, so Lock/Unlock and GetDC/ReleaseDC periods should be kept short. Unfortunately, because Windows is stopped, GUI debuggers cannot be used in between Lock/Unlock and GetDC/ReleaseDC operations.

Syntax

HRESULT Lock(
  LPRECT lpDestRect,
  LPDDSURFACEDESC lpDDSurfaceDesc,
  DWORD dwFlags,
  HANDLE hEvent
  );

Parameters

lpDestRect

Points to a RECT structure identifying the region of surface that is being locked.

lpDDSurfaceDesc

Points to a DDSURFACEDESC structure to be filled in with the relevant details about the surface.

dwFlags

One or more of the following flags.

Value | Description
DDLOCK_SURFACEMEMORYPTR | The default. Set to indicate that Lock should return a valid memory pointer to the top of the specified rectangle. If no rectangle is specified then a pointer to the top of the surface is returned.
DDLOCK_EVENT | Set if an event handle is being passed to Lock. Lock will trigger the event when it can return the surface memory pointer requested. If multiple locks of this type are placed on a surface, events will be triggered in FIFO order.
DDLOCK_WAIT | Normally, if a lock cannot be obtained because a Blt is in progress, a DDERR_WASSTILLDRAWING error will be returned immediately. If this flag is set, however, Lock will retry until a lock is obtained or another error, such as DDERR_SURFACEBUSY, occurs.

hEvent

Handle to a system event that should be triggered when the surface is ready to be locked.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACEBUSY | Access to this surface is being refused because the surface is already locked by another thread.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::ReleaseDC

The ReleaseDC method releases the hDC previously obtained with GetDC. It also Unlocks the surface previously locked when GetDC was called.

Syntax

HRESULT ReleaseDC(
  HDC hDC
  );

Parameters

hDC

Handle to a device context previously obtained by calling GetDC.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_GENERIC | Generic failure.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Restore

The Restore method restores a surface that has been lost—that is, the surface memory associated with the DirectDrawSurface object has been freed. Surfaces can be lost because the mode of the display card was changed or because an application received exclusive access to the display card and freed all of the surface memory currently allocated on the video card. When a DirectDrawSurface object loses its surface memory, many methods will return DDERR_SURFACELOST and perform no other function. Restore will reallocate surface memory and reattach it to the DirectDrawSurface object.

A single call to Restore will restore a DirectDrawSurface's associated implicit surfaces. An attempt to restore an implicitly created surface will result in an error. Restore will not work across explicit attachments created using the AddAttachedSurface method; each of these surfaces must be restored individually.

Syntax

HRESULT Restore();

Parameters

This method takes no parameters.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_IMPLICITLYCREATED | This surface can not be restored because it is an implicitly created surface.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_WRONGMODE | This surface can not be restored because it was created in a different mode.
DDERR_OUTOFMEMORY | DirectDraw does not have enough memory to perform the operation.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.
DDERR_GENERIC | Generic failure.
DDERR_INCOMPATIBLEPRIMARY | Unable to match primary surface creation request with existing primary surface.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::SetClipper

The SetClipper method attaches a DirectDrawClipper to a DirectDrawSurface. This function is primarily used by surfaces that are being overlayed on or blitted to the primary surface, but it can be used on any surface. Once a DirectDrawClipper has been attached, and a clip list associated with it, it will be used for Blt, BltBatch, and UpdateOverlay operations involving the parent DirectDrawSurface. This method can also be used to detach a DirectDrawSurface's current Clipper.

Syntax

HRESULT SetClipper(
  LPDIRECTDRAWCLIPPER lpDDClipper
  );

Parameters

lpDirectDrawClipper

Either NULL, or points to the IDirectDrawClipper interface representing the DirectDrawClipper that will be attached to the DirectDrawSurface. If NULL, the current clipper will be detached.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_NOCLIPPERATTACHED | No clipper object attached to surface object.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::SetColorKey

The SetColorKey method sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per surface basis.

Syntax

HRESULT SetColorKey(
  DWORD dwFlags,
  LPDDCOLORKEY lpDDColorKey
);

Parameters

dwFlags

Determines which color key is being requested.

Value | Description
DDCKEY_COLORSPACE | Set if the structure contains a colorspace. Not set if the structure contains a single color key.
DDCKEY_DESTBLT | Set if the structure specifies a color key or color space which is to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY | Set if the structure specifies a color key or color space which is to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT | Set if the structure specifies a color key or color space which is to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY | Set if the structure specifies a color key or color space which is to be used as a source color key for overlay operations.

lpDDColorKey

Points to the DDCOLORKEY structure which has the new color key values for the DirectDrawSurface object.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_NOOVERLAYHW | Operation could not be carried out because there is no overlay hardware present or available.
DDERR_COLORKEYDRIVERWIDE | The driver has no color key capabilities of any type.
DDERR_NODESTCLRKEYHW | The driver has no destination color key capabilities.
DDERR_NOSRCCLRKEYHW | The driver has no source color key capabilities.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_UNSUPPORTED | Action not supported.
DDERR_WASSTILLDRAWING | Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.
DDERR_GENERIC | Generic failure.
DDERR_NOTAOVERLAYSURFACE | Returned when an overlay method is called for a non-overlay surface.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::SetOverlayPosition

The SetOverlayPosition method changes the display coordinates of an overlay surface.

Syntax

HRESULT SetOverlayPosition(
  LONG lX,
  LONG lY
  );

Parameters

lX

New X display coordinate.

lY

New Y display coordinate.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_GENERIC | Generic failure.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::SetPalette

The SetPalette method attaches the DIRECTDRAWPALETTE specified to a surface. The Surface will use this Palette for all subsequent operations. The palette change takes place immediately, without regard to refresh timing.

Syntax

HRESULT SetPalette(
  LPDIRECTDRAWPALETTE lpDDPalette
  );

Parameters

lpDDPalette

Pointer to the IDirectDrawPalette interface of the palette to use for future operations.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_NOEXCLUSIVEMODE | Operation requires the application to have exclusive mode but the application does not have exclusive mode.
DDERR_NOT8BITCOLOR | DirectDrawSurface is not in 8-bit color mode and the requested operation requires 8-bit color.
DDERR_UNSUPPORTED | Action not supported.
DDERR_GENERIC | Generic failure.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOPALETTEATTACHED | No palette object attached to this surface.
DDERR_NOPALETTEHW | No hardware support for 16- or 256-color palettes.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::Unlock

The Unlock method notifies DirectDraw that the surface manipulations are complete.

Syntax

HRESULT Unlock(
  LPVOID lpSurfaceData
  );

Parameters

lpSurfaceData

This is the pointer returned by Lock. Since it is possible to call Lock multiple times for the same Surface with different destination rectangles, this pointer is used to tie the Lock and Unlock calls together.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
DDERR_NOTLOCKED | Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.
DDERR_GENERIC | Generic failure.
DDERR_INVALIDRECT | Rectangle provided was invalid.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::UpdateOverlay

The UpdateOverlay method repositions and/or modifies the visual attributes of an overlay surface. These surfaces must have the DDSCAPS_OVERLAY bit set.

Syntax

HRESULT UpdateOverlay(
  LPRECT lpSrcRect,
  LPDIRECTDRAWSURFACE lpDDDestSurface,
  LPRECT lpDestRect,
  DWORD dwFlags,
  LPDDOVERLAYFX lpDDOverlayFx
  );

Parameters

dwSrcRect

Points to a RECT structure that defines the X, Y, width, and height of the region on the source surface which is being used as the overlay.

lpDDDestSurface

Points to the IDirectDrawSurface interface of the surface that is being overlayed.

lpDestRect

Points to a RECT structure that defines the X, Y, width, and height of the region on the destination surface which the overlay should be moved to.

dwFlags

Zero or more of the following flags.

Value | Description
DDOVER_ALPHADEST | Use the alpha information in the pixel format or the alpha channel surface attached to the destination surface as the alpha channel for the destination overlay.
DDOVER_ALPHADESTCONSTOVERRIDE | Use the dwConstAlphaDest member in the DDOVERLAYFX structure as the destination alpha channel for this overlay.
DDOVER_ALPHADESTNEG | The NEG suffix indicates that the destination surface becomes more transparent as the alpha value increases.
DDOVER_ALPHADESTSURFACEOVERRIDE | Use the lpDDSAlphaDest member in the DDOVERLAYFX structure as the alpha channel destination for this overlay.
DDOVER_ALPHAEDGEBLEND | Use the dwAlphaEdgeBlend member in the DDOVERLAYFX structure as the alpha channel for the edges of the image that border the color key colors.
DDOVER_ALPHASRC | Use the alpha information in the pixel format or the alpha channel surface attached to the source surface as the source alpha channel for this overlay.
DDOVER_ALPHASRCCONSTOVERRIDE | Use the dwConstAlphaSrc member in the DDOVERLAYFX structure as the source alpha channel for this overlay.
DDOVER_ALPHASRCNEG | The NEG suffix indicates that the source surface becomes more transparent as the alpha value increases.
DDOVER_ALPHASRCSURFACEOVERRIDE | Use the lpDDSAlphaSrc member in the DDOVERLAYFX structure as the alpha channel source for this overlay.
DDOVER_HIDE | Turn this overlay off.
DDOVER_KEYDEST | Use the color key associated with the destination surface.
DDOVER_KEYDESTOVERRIDE | Use the dckDestColorkey member in the DDOVERLAYFX structure as the color key for the destination surface.
DDOVER_KEYSRC | Use the color key associated with the source surface.
DDOVER_KEYSRCOVERRIDE | Use the dckSrcColorkey member in the DDOVERLAYFX structure as the color key for the source surface.
DDOVER_SHOW | Turn this overlay on.
DDOVER_ZORDER | Use the dwZOrderFlags member in the DDOVERLAYFX structure as the z order for the display of this overlay. The lpDDSRelative member will be used if the dwZOrderFlags member is set to either DDOVERZ_INSERTINBACKOF or DDOVERZ_INSERTINFRONTOF.

lpDDOverlayFx

Pointer to a DDOVERLAYFX structure.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_SURFACELOST | Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.
Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it. | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDRECT | Rectangle provided was invalid.
DDERR_HEIGHTALIGN | Height of rectangle provided is not a multiple of alignment.
DDERR_XALIGN | Rectangle provided was not horizontally aligned on required boundary.
DDERR_UNSUPPORTED | Action not supported.
DDERR_NOSTRETCHHW | Operation could not be carried out because there is no hardware support for stretching.
DDERR_GENERIC | Generic failure.
DDERR_NOTAOVERLAYSURFACE | Returned when an overlay method is called for a non-overlay surface.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::UpdateOverlayDisplay

The UpdateOverlayDisplay method repaints the rectangles in the dirty rectangle lists of all active overlays. The dirty rectangle list is cleared. This function is for software emulation only; it does nothing if the hardware supports overlays.

Syntax

HRESULT UpdateOverlayDisplay(
  DWORD dwFlags
  );

Parameters

dwFlags

Specify type of update to perform.

Value | Description
DDOVER_REFRESHDIRTYRECTS | Update the overlay display using the list of dirty rectangles previously constructed for this destination. The dirty rectangle list is cleared after this.
DDOVER_REFRESHALL | Ignore the dirty rectangle list and update the overlay display completely. The dirty rectangle list is cleared after this.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_UNSUPPORTED | Action not supported.

See Also

  • IDirectDrawSurface Interface


IDirectDrawSurface::UpdateOverlayZOrder

The UpdateOverlayZOrder method sets the z order of an overlay. The z order is used to determine which overlay should be occluded when multiple overlays are being displayed simultaneously. Overlay positions are all relative to other overlays -- there is no true z value for them.

Syntax

HRESULT UpdateOverlayZOrder(
  DWORD dwFlags,
  LPDIRECTDRAWSURFACE lpDDSReference
  );

Parameters

dwFlags

Zero or more of the following flags.

Value | Description
DDOVERZ_INSERTINBACKOF | Insert this overlay in the overlay chain in back of the overlay specified as the reference overlay.
DDOVERZ_INSERTINFRONTOF | Insert this overlay in the overlay chain in front of the overlay specified as the reference overlay.
DDOVERZ_MOVEBACKWARD | Move this overlay one overlay position backward.
DDOVERZ_MOVEFORWARD | Move this overlay one overlay position forward.
DDOVERZ_SENDTOBACK | Move this overlay to the back of the overlay chain.
DDOVERZ_SENDTOFRONT | Move this overlay to the front of the overlay chain.

lpDDSReference

Points to the IDirectDrawSurface interface of the surface that should be used as a relative position in the overlay chain. This parameter is needed only for DDOVERZ_INSERTINBACKOF and DDOVERZ_INSERTINFRONTOF.

Return Values

Value | Description
DD_OK | The method succeeded.
DDERR_INVALIDOBJECT | DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the input parameters is invalid.
DDERR_NOTAOVERLAYSURFACE | Returned when an overlay method is called for a non-overlay surface.

See Also

  • IDirectDrawSurface Interface


IMediaStream Interface

The IMediaStream interface provides access to the characteristics of a media stream, such as the stream's media type and purpose ID. It also has methods that create data samples.

For sample code that implements the multimedia streaming interfaces, see Multimedia Streaming Sample Code.

Implement this interface when you want to add media type-specific functionality to your media stream. This interface is implemented on multimedia stream objects. IMediaStream provides generic sample-creation methods, but you usually want to write a more powerful version of these methods that will take advantage of your media type's specific characteristics.

Use this interface when your application needs to access a stream's media type information and create data samples.

In addition to the methods inherited from IUnknown, the IMediaStream interface exposes the following methods.

Method | Description
AllocateSample | Allocates a new stream sample object for the current media stream.
CreateSharedSample | Creates a new stream sample that shares the same backing object as the existing sample.
GetInformation | Retrieves the stream's purpose ID and media type.
GetMultiMediaStream | Retrieves a pointer to the multimedia stream that contains the specified media stream.
SendEndOfStream | Forces the current stream to end. If the current stream isn't writable, this method does nothing.
SetSameFormat | Sets the media stream to the same format as a previous stream.


IMediaStream::AllocateSample

Allocates a new stream sample object for the current media stream.

Syntax

HRESULT AllocateSample(
    DWORD dwFlags,
    IStreamSample **ppSample
  );

Parameters

dwFlags

[in] Flags. Must be zero.

ppSample

[out] Address of a pointer to the newly created stream sample's IStreamSample interface.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | There isn't enough memory available to create a stream sample.
E_POINTER | A parameter is invalid.
S_OK | Success.

Remarks

This method allocates the sample and its associated backing object or buffer. The backing object is either the DirectDraw surface for video or the IAudioData object for audio.

See Also

  • IMediaStream Interface


IMediaStream::CreateSharedSample

Creates a new stream sample that shares the same backing object as the existing sample.

Syntax

HRESULT CreateSharedSample(
  IStreamSample *pExistingSample,
  DWORD dwFlags ,
  IStreamSample **ppNewSample
  );

Parameters

pExistingSample

[in] Pointer to the existing sample.

dwFlags

[in] Reserved for flag data. Must be zero.

ppNewSample

[out] Address of a pointer to an IStreamSample interface that will point to the newly created shared sample.

Return Values

Returns one of the following values.

Return code | Description
E_OUTOFMEMORY | There isn't enough memory available to create the sample.
E_POINTER | One of the parameters is invalid.
MS_E_INCOMPATIBLE | The existing sample isn't compatible with the specified media stream.
S_OK | Success; ppNewSample points to the newly created sample.

Remarks

This method calls IUnknown::QueryInterface on the existing sample to retrieve the media type-specific information, which it uses to create the shared sample.

See Also

  • IMediaStream Interface


IMediaStream::GetInformation

Retrieves the stream's purpose ID and media type.

Syntax

HRESULT GetInformation(
  MSPID *pPurposeId,
  STREAM_TYPE *pType
  );

Parameters

pPurposeId

[out] Pointer to an MSPID value that will contain the stream's purpose ID (see Multimedia Streaming Data Types). If this parameter is NULL on entry, the method won't retrieve the purpose ID.

pType

[out] Pointer to a STREAM_TYPE enumerated data type value that will contain the stream's media type. If this parameter is NULL on entry, the method won't retrieve the media type.

Return Values

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.

Remarks

The value retrieved in the pPurposeId parameter will usually be either MSPID_PrimaryVideo, which identifies the primary video stream, or MSPID_PrimaryAudio, which identifies the primary audio stream; however, you can define other values if necessary.

See Also

  • IMediaStream Interface


IMediaStream::GetMultiMediaStream

Retrieves a pointer to the multimedia stream that contains the specified media stream.

Syntax

HRESULT GetMultiMediaStream(
  IMultiMediaStream **ppMultiMediaStream
  );

Parameters

ppMultiMediaStream

[out] Address of a pointer to an IMultiMediaStream interface object that will point to the multimedia stream from which the current media stream was created.

Return Values

Returns S_OK if successful or E_POINTER if ppMultiMediaStream is invalid.

Remarks

This method increments the reference count of the retrieved object pointer.

See Also

  • IMediaStream Interface


IMediaStream::SendEndOfStream

Forces the current stream to end. If the current stream isn't writable, this method does nothing.

Syntax

HRESULT SendEndOfStream(
  DWORD dwFlags
  );

Parameters

dwFlags

[in] Reserved for flag data. Must be zero.

Return Values

Returns S_OK if successful or MS_E_INCOMPATIBLE if the existing sample isn't compatible with the current media stream.

Remarks

Applications do not call this internal method.

See Also

  • IMediaStream Interface


IMediaStream::SetSameFormat

Sets the media stream to the same format as a previous stream.

Syntax

HRESULT SetSameFormat(
 IMediaStream *pStreamThatHasDesiredFormat,
  DWORD dwFlags
  );

Parameters

pStreamThatHasDesiredFormat

[in] Pointer to a media stream object that has the same format.

dwFlags

[in] Reserved for flag data. Must be zero.

Return Values

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.

See Also

  • IMediaStream Interface


IMediaStreamFilter Interface

The IMediaStreamFilter interface is supported by the Media Stream filter, which is used internally by the multimedia stream object. Applications should not use this interface.

In addition to the methods inherited from IBaseFilter, the IMediaStreamFilter interface exposes the following methods.

Method | Description
AddMediaStream | Connects a media stream object to the underlying filter graph.
EndOfStream | Signals the end of a stream.
EnumMediaStreams | Retrieves a media stream, specified by index.
Flush | Notifies the filter that one of its pins has flushed data.
GetCurrentStreamTime | Retrieves the current stream time.
GetMediaStream | Retrieves a media stream, specified by purpose ID.
ReferenceTimeToStreamTime | Converts a reference time to stream time.
SupportSeeking | Initializes the filter to support seeking.
WaitUntil | Causes the filter to block until a specified stream time.


IMediaStreamFilter::AddMediaStream

The AddMediaStream method connects a media stream object to the underlying filter graph.

Syntax

HRESULT AddMediaStream(
    IAMMediaStream *pAMMediaStream
);

Parameters

pAMMediaStream

[in] Pointer to the media stream object's IAMMediaStream interface.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_OUTOFMEMORY | Insufficient memory
MS_E_PURPOSEID | Duplicate purpose ID
S_OK | Success

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::EndOfStream

The EndOfStream method signals the end of a stream. The Media Stream filter's input pins call this method on the filter.

Syntax

HRESULT EndOfStream(void);

Parameters

This method takes no parameters.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::EnumMediaStreams

The EnumMediaStreams method retrieves a media stream, specified by index.

Syntax

HRESULT EnumMediaStreams(
    long Index,
    IMediaStream **ppMediaStream
);

Parameters

Index

[in] Index of the media stream to retrieve.

ppMediaStream

[out] Address of a variable that receives an IMediaStream interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | Index out of range.
S_OK | Success.

Remarks

If the method succeeds, the caller must release the IMediaStream interface.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::Flush

The Flush method notifies the filter that one of its pins has flushed data. The filter's input pins call this method.

Syntax

HRESULT Flush(
    BOOL bCancelEOS
);

Parameters

bCancelEOS

[in] Boolean value that indicates whether to cancel the pin's previous end-of-stream notification. If TRUE, the filter decrements the internal end-of-stream count.

Return Values

Returns S_OK if successful, or an error code otherwise.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::GetCurrentStreamTime

The GetCurrentStreamTime method retrieves the current stream time.

Syntax

HRESULT GetCurrentStreamTime(
    REFERENCE_TIME *pCurrentStreamTime
);

Parameters

pCurrentStreamTime

[out] Pointer to a variable that receives the stream time, in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_FALSE | The graph is not running, or there is no reference clock.
S_OK | Success.

Remarks

Stream time is defined only when the graph is running and has a reference clock. Otherwise, *pCurrentStreamTime is set to zero and the method returns S_FALSE.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::GetMediaStream

The GetMediaStream method retrieves a media stream, specified by purpose ID.

Syntax

HRESULT GetCurrentStreamTime(
    REFMSPID idPurpose
    IMediaStream **ppMediaStream
);

Parameters

idPurpose

[in] Reference to an MSPID value that specifies which stream to retrieve.

ppMediaStream

[out] Address of a variable that receives an IMediaStream interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
MS_E_NOSTREAM | No matching stream was found.
S_OK | Success.

Remarks

If the method succeeds, the caller must release the IMediaStream interface.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::ReferenceTimeToStreamTime

The ReferenceTimeToStreamTime method converts a reference time to stream time.

Syntax

HRESULT ReferenceTimeToStreamTime(
    REFERENCE_TIME *pTime
);

Parameters

pTime

[in, out] On input, specifies the reference time to convert. On output, contains the equivalent stream time.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
S_FALSE | The graph does not have a reference clock.
S_OK | Success.

Remarks

Stream time equals the current reference time minus the reference time when the graph last started running.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::SupportSeeking

The SupportSeeking method initializes the filter to support seeking. The multimedia stream object calls this method.

Syntax

HRESULT SupportSeeking(
    BOOL bRenderer
);

Parameters

bRenderer

[in] Boolean value that specifies whether the streams are being rendered. Use the value TRUE if the stream type is STREAMTYPE_READ, or FALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_NOINTERFACE | The graph does not contain any seekable streams.
S_OK | Success.

See Also

  • IMediaStreamFilter Interface


IMediaStreamFilter::WaitUntil

The WaitUntil method causes the filter to block until a specified stream time. The filter's pins call this method. They can interrupt the wait by flushing the filter.

Syntax

HRESULT WaitUntil(
    REFERENCE_TIME WaitStreamTime
);

Parameters

WaitStreamTime

[in] Specifies the stream time, in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
S_FALSE | The wait was interrupted.
S_OK | Success.

Remarks

If the graph does not have a reference clock, the method returns E_FAIL.

See Also

  • IMediaStreamFilter Interface


IMemoryData Interface

The IMemoryData interface contains methods that set and retrieve memory data on audio data objects. Audio data objects provide the underlying data which stream samples access. This interface provides a way to initialize memory buffers and to set actual amounts of audio data in the objects. Additionally, the GetInfo method can be used to retrieve audio memory data.

Implement this interface on underlying audio data objects that audio stream sample objects will access.

Typically these methods are called by the IAudioMediaStream or IAudioStreamSample object, rather than by the application.

In addition to the methods inherited from IUnknown, the IMemoryData interface exposes the following methods.

Method | Description
GetInfo | Retrieves information describing an audio data object.
SetActual | Sets the amount of audio data currently in the object, in bytes.
SetBuffer | Initializes a memory buffer with a pointer to memory and length.


IMemoryData::GetInfo

Retrieves information describing an audio data object.

Syntax

HRESULT GetInfo(
  DWORD *pdwLength,
  BYTE **ppbData,
  DWORD *pcbActualData );

Parameters

pdwLength

[out] Length of memory in bytes, if non-NULL.

ppbData

[out] Pointer to the memory, if non-NULL.

pcbActualData

[out] Length of data in bytes, if non-NULL.

Return Values

Returns an HRESULT value.

Remarks

This method determines how much data the object currently contains as last set by SetActual.

See Also

  • IMemoryData Interface


IMemoryData::SetActual

Sets the amount of audio data currently in the object.

Syntax

HRESULT SetActual(
  DWORD cbDataValid
  );

Parameters

cbDataValid

[in] Amount of data, in bytes.

Return Values

Returns S_OK if successful or E_POINTER if the required parameter is NULL.

Remarks

This method is usually called by the IAudioMediaStream or IAudioStreamSample object, rather than by the application.

See Also

  • IMemoryData Interface


IMemoryData::SetBuffer

Initializes a memory buffer with a pointer to memory and length.

Syntax

HRESULT SetBuffer(
  DWORD cbSize,
  BYTE *pbData,
  DWORD dwFlags
  );

Parameters

cbSize

[in] Size of memory pointed to by pbData, in bytes.

pbData

[in] Pointer to memory that this object will use.

dwFlags

[in] Reserved for flag data. Must be zero.

Return Values

Returns S_OK if successful or E_INVALIDARG if cbSize is zero or pbData is NULL.

Remarks

This method can be called as often as needed. When using IStreamSample::Update to update samples asynchronously, make sure that SetBuffer is never called before an update is completed.

See Also

  • IMemoryData Interface


IMultiMediaStream Interface

The IMultiMediaStream interface is exposed by the AMMultimediaStream object. It contains methods for enumerating the media streams, retrieving information about them, and running and stopping them.

In addition to the methods inherited from IUnknown, the IMultiMediaStream interface exposes the following methods.

Method | Description
EnumMediaStreams | Retrieves a media stream, specified by index.
GetDuration | Retrieves the duration of the multimedia stream.
GetEndOfStreamEventHandle | Retrieves an event that is signaled when the multimedia stream completes playback.
GetInformation | Retrieves the capabilities of the multimedia stream object.
GetMediaStream | Retrieves a media stream, specified by purpose ID.
GetState | Retrieves the current state of the multimedia stream object.
GetTime | Retrieves the current stream time.
Seek | Seeks all of the media streams to a new position.
SetState | Runs or stops the multimedia stream object.

See Also

  • IAMMultiMediaStream Interface


IMultiMediaStream::EnumMediaStreams

The EnumMediaStreams method retrieves a media stream object, specified by index.

Syntax

HRESULT EnumMediaStreams(
  long Index,
  IMediaStream **ppMediaStream
);

Parameters

Index

[in] Zero-based index of the media stream to retrieve.

ppMediaStream

[out] Address of a variable that receives an IMediaStream interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_POINTER | NULL pointer argument.
S_FALSE | Index is out of range.
S_OK | Success.

Remarks

If the return value is S_OK, the caller must release the IMediaStream interface.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetDuration

The GetDuration method retrieves the duration of the multimedia stream.

Syntax

HRESULT GetDuration(
  STREAM_TIME *pDuration
);

Parameters

pDuration

[out] Pointer to a variable that receives of the multimedia stream, in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_NOINTERFACE | This multimedia stream does not support seeking.
E_POINTER | NULL pointer value.
MS_E_INVALIDSTREAMTYPE | This multimedia stream is not read-only.
S_FALSE | Could not determine the duration.
S_OK | Success.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetEndOfStreamEventHandle

The GetEndOfStreamEventHandle method retrieves an event that is signaled when the multimedia stream completes playback.

Syntax

HRESULT GetEndOfStreamEventHandle(
  HANDLE *phEOS
);

Parameters

phEOS

[out] Pointer to a variable that receives a handle to the event. The event is signaled when all of the streams in the multimedia stream object complete playback.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
MS_E_BUSY | The multimedia stream is not stopped.
S_OK | Success.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetInformation

The GetInformation method retrieves the capabilities of the multimedia stream object.

Syntax

HRESULT GetInformation(
  DWORD *pdwFlags,
  STREAM_TYPE *pStreamType
);

Parameters

pdwFlags

[out] Pointer to a variable that receives a bitwise combination of the following flags.

Value | Description
MMSSF_ASYNCHRONOUS | The object supports asynchronous sample updates. This flag is always returned.
MMSSF_HASCLOCK | The object has a clock.
MMSSF_SUPPORTSEEK | The object supports seeking.

This parameter can be NULL.

pStreamType

[out] Pointer to a variable that receives a member of the STREAM_TYPE enumeration. This value indicates whether the multimedia stream is read-only, write-only, or read/write. This parameter can be NULL.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_UNEXPECTED | Unexpected error.
S_OK | Success.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetMediaStream

The GetMediaStream method retrieves a media stream, specified by purpose ID.

Syntax

HRESULT GetMediaStream(
  REFMSPID idPurpose,
  IMediaStream **ppMediaStream
);

Parameters

idPurpose

Reference to an MSPID that identifies the media stream to retrieve.

ppMediaStream

Address of variable that receives an IMediaStream interface pointer.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_POINTER | NULL pointer valid.
MS_E_NOSTREAM | No matching stream.
S_OK | Success.

Remarks

If the method succeeds, the caller must release the IMediaStream interface.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetState

The GetState method retrieves the current state of the multimedia stream object.

Syntax

HRESULT GetState(
  STREAM_STATE *pCurrentState
);

Parameters

pCurrentState

[out] Pointer to a variable that receives a member of the STREAM_STATE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::GetTime

The GetTime method retrieves the current stream time.

Syntax

HRESULT GetTime(
  STREAM_TIME *pCurrentTime
  );

Parameters

pCurrentTime

[out] Pointer to a variable that receives the stream time, in 100-nanosecond units.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_POINTER | NULL pointer argument.
S_FALSE | Could not get the stream time, or there is no clock.
S_OK | Success.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::Seek

The Seek method seeks all of the media streams to a new position.

Syntax

HRESULT Seek(
  STREAM_TIME SeekTime
);

Parameters

SeekTime

[in] STREAM_TIME value that specifies the new position.

Return Values

Returns an HRESULT value. Possible values include the following.

Return code | Description
E_NOINTERFACE | The media streams do not support seeking.
S_OK | Success.

Remarks

To determine whether the media streams support seeking, call the IMultiMediaStream::GetInformation method.

See Also

  • IMultiMediaStream Interface


IMultiMediaStream::SetState

The SetState method runs or stops the multimedia stream object.

Syntax

HRESULT SetState(
  STREAM_STATE NewState
);

Parameters

NewState

[in] A member of the STREAM_STATE enumeration, specifying the new state (running or stopped).

Return Values

Returns an HRESULT value. Possible values include the following.

Value | Description
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

Stopping the multimedia stream object deletes any data that is pending.

See Also

  • IMultiMediaStream Interface


IStreamSample Interface

The IStreamSample interface provides control over the behavior of stream samples. You can retrieve the media stream that created the sample, set or retrieve sample start and stop times, check the sample's completion status, and perform a developer-specified function on the sample itself.

Implement this interface when you implement a media stream for a new media type. The interface is exposed on sample objects created by media streams.

Use this interface when you want to control data samples created by IMediaStream or its derived interfaces.

In addition to the methods inherited from IUnknown, the IStreamSample interface exposes the following methods.

Method | Description
CompletionStatus | Retrieves the status of the current sample's latest asynchronous update. If the update isn't complete, you can force it to complete.
GetMediaStream | Retrieves a pointer to the media stream object that created the current sample.
GetSampleTimes | Retrieves the current sample's start and end times.
SetSampleTimes | Sets the current sample's start and end times.
Update | Performs a synchronous or an asynchronous update on the current sample.


IStreamSample::CompletionStatus

Retrieves the status of the current sample's latest asynchronous update. If the update isn't complete, you can force it to complete.

Syntax

HRESULT CompletionStatus(
  DWORD dwFlags,
  DWORD dwMilliseconds
  );

Parameters

dwFlags

[in] Value that specifies whether to forcibly complete the update. This value is a combination of one or more of the following flags.

Value | Description
COMPSTAT_NOUPDATEOK (0x01) | Force the update to complete as soon as possible, even if the sample update isn't yet complete. If the sample is updating and you didn't set the COMPSTAT_WAIT flag, the method returns MS_S_PENDING. If the sample is waiting to be updated, this method removes it from the queue and returns MS_S_NOTUPDATED.
COMPSTAT_WAIT (0x02) | Wait until the sample finishes updating before returning from this method.
COMPSTAT_ABORT (0x04) | Forces the update to complete, even if it's currently updating. This leaves the sample data in an undefined state. Combine this value with the COMPSTAT_WAITFORCOMPLETION flag to ensure that the update canceled.

dwMilliseconds

[in] If the dwFlags parameter is COMPSTAT_WAIT, this value is the number of milliseconds to wait for the update to complete. Specify INFINITE to indicate that you want to wait until the sample updates before this call returns.

Return Values

Returns one of the following values.

Return code | Description
E_ABORT | The update aborted.
MS_S_ENDOFSTREAM | The sample wasn't updated because it reached the end of the stream.
MS_S_NOUPDATE | The update was forcibly completed; the sample was not updated by the stream.
MS_S_PENDING | An asynchronous update is pending.
S_OK | Success.

See Also

  • IStreamSample Interface


IStreamSample::GetMediaStream

Retrieves a pointer to the media stream object that created the current sample.

Syntax

HRESULT GetMediaStream(
  IMediaStream **ppMediaStream
  );

Parameters

ppMediaStream

[in] Address of a pointer to an IMediaStream interface that will point to the media stream that created the current sample.

Return Values

Returns S_OK if successful or E_POINTER if ppMediaStream is invalid.

Remarks

If successful, this method increments the reference count of the media stream specified by ppMediaStream.

See Also

  • IStreamSample Interface


IStreamSample::GetSampleTimes

Retrieves the current sample's start and end times. If the sample is updating, this method returns the times after the update completes.

Syntax

HRESULT GetSampleTimes(
  STREAM_TIME *pStartTime,
  STREAM_TIME *pEndTime,
  STREAM_TIME *pCurrentTime
  );

Parameters

pStartTime

[out] Pointer to a STREAM_TIME value that will contain the sample's start time.

pEndTime

[out] Pointer to a STREAM_TIME value that will contain the sample's end time.

pCurrentTime

[out] Pointer to a STREAM_TIMEvalue that will contain the media stream's current media time.

Return Values

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.

Remarks

For streams that have a clock, the start and end times will be relative to the stream's current time. If the stream doesn't have a clock, the times are media-relative and the current time will be zero.

The pCurrentTime parameter enables you to conveniently track the media stream's current time, so you don't have to call IMultiMediaStream::GetTime. Unlike GetTime, however, this method returns S_OK if the stream doesn't have a clock; GetTime returns S_FALSE. The value assigned to pCurrentTime is the same as the value produced by the following code fragment.

IMediaStream *pMediaStream = 0;
hr = pSample->GetMediaStream(&pMediaStream);
if (SUCCEEDED(hr))
{
  IMultiMediaStream *pMultiMediaStream = 0;
  hr = pMediaStream->GetMultiMediaStream(&pMultiMediaStream);
  pMediaStream->Release();
  if (SUCCEEDED(hr))
  {
    STREAM_TIME CurrentTime = 0;
    hr = pMultiMediaStream->GetTime(&CurrentTime);
    pMultiMediaStream->Release();
  }
}

See Also

  • IStreamSample Interface
  • Multimedia Streaming Data Types


IStreamSample::SetSampleTimes

Sets the current sample's start and end times. You can call this method prior to updating the sample.

Syntax

HRESULT SetSampleTimes(
  const STREAM_TIME *pStartTime,
  const STREAM_TIME *pEndTime
  );

Parameters

pStartTime

[in] Pointer to a STREAM_TIME value that contains the sample's new start time.

pEndTime

[in] Pointer to a STREAM_TIME value that contains the sample's new end time.

Return Values

Returns S_OK if successful or E_POINTER if one of the parameters is NULL.

Remarks

For streams that have a clock, the times must be relative to the stream's current time. If the stream doesn't have a clock, the times should be relative to the media.

This method applies only to writable streams.

See Also

  • IStreamSample Interface
  • Multimedia Streaming Data Types


IStreamSample::Update

Performs a synchronous or an asynchronous update on the current sample.

Syntax

HRESULT Update(
  DWORD dwFlags,
  HANDLE hEvent,
  PAPCFUNC pfnAPC,
  DWORD_PTR dwAPCData
  );

Parameters

dwFlags

[in] Flag that specifies whether the update is synchronous or asynchronous. The SSUPDATE_ASYNC flag specifies an asynchronous update, which you can set if both hEvent and pfnAPC are NULL. Use SSUPDATE_CONTINUOUS to continuously update the sample until you call the IStreamSample::CompletionStatus method.

hEvent

[in] Handle to an event that this method will trigger when the update is complete.

pfnAPC

[in] Pointer to a Win32 asynchronous procedure call (APC) function that this method will call after it completes the sample update.

dwAPCData

[in] Value that this method passes to the function specified by the pfnAPC parameter.

Return Values

Returns one of the following values.

Return code | Description
E_ABORT | The update aborted.
E_INVALIDARG | One of the parameters is invalid.
E_POINTER | One of the parameters is invalid.
MS_E_BUSY | This sample already has a pending update.
MS_S_ENDOFSTREAM | Reached the end of the stream; the sample wasn't updated.
MS_S_PENDING | The asynchronous update is pending.
S_OK | Success.
VFW_E_NOT_COMMITTED | Cannot allocate a sample because the allocator is not committed.

Remarks

This method can be used to perform a synchronous or asynchronous update of a sample. If both hEvent and pfnAPC are NULL then the update will be synchronous unless either of the SSUPDATE_ASYNC or SSUPDATE_CONTINUOUS flags is specified. When a synchronous update returns, the result of the function contains the I/O completion status.

You can't specify values for both hEvent and pfnAPC; the method will fail.

Asynchronous updates might complete before the update returns; in that case, the return value is S_OK. If you specify an event and the update returns S_OK, this method sets the event on return. If you specify an APC function and the update returns S_OK, the APC will not be queued and the function will not be called.

Asynchronous updates that don't complete prior to returning will return a value of MS_S_PENDING.

If an application creates multiple streams, it must perform an asynchronous update on each stream. Call WaitForMultipleObjects to wait for each stream update to complete, before making the next update. Otherwise, the application might block.

See Also

  • IStreamSample Interface


Multimedia Streaming Enumeration Types

This section lists the enumeration types defined for Microsoft DirectShow multimedia.

Enumeration Type | Description
STREAM_STATE | Describes the state of a stream.
STREAM_TYPE | Defines the direction of data flow for a stream.


STREAM_STATE

Describes the state of the stream.

Syntax

typedef enum {
  STREAMSTATE_STOP        = 0,
  STREAMSTATE_RUN         = 1
} STREAM_STATE;

Elements

STREAMSTATE_STOP

Stop state.

STREAMSTATE_RUN

Run state.

Remarks

Change the state by calling the IMultiMediaStream::SetState method.

See Also

  • Multimedia Streaming Enumeration Types


STREAM_TYPE

Defines the direction of data flow for the stream.

Syntax

typedef enum {
  STREAMTYPE_READ         = 0,
  STREAMTYPE_WRITE        = 1,
  STREAMTYPE_TRANSFORM    = 2
} STREAM_TYPE;

Elements

STREAMTYPE_READ

Application can read the stream.

STREAMTYPE_WRITE

Application can write to the stream.

STREAMTYPE_TRANSFORM

Application reads and writes to the stream.

Remarks

Transform streams are read/write where the sample is updated in place.

See Also

  • Multimedia Streaming Enumeration Types


Multimedia Streaming Data Types

The Microsoft DirectShow multimedia streaming interfaces use the following data types.

Data type | Description
MSPID | Identifies the purpose of a media stream.
STREAM_TIME | Defines the data type used to express reference times.


MSPID

The MSPID data type identifies the purpose of a media steam.

Syntax

typedef GUID MSPID;
typedef REFGUID REFMSPID;

Remarks

MSPID is simply a typedef for GUID. The following MSPIDs are defined.

Value | Description
MSPID_PrimaryVideo | Primary video stream.
MSPID_PrimaryAudio | Primary audio stream.

The REFMSPID type defines a reference to an MSPID.

See Also

  • Multimedia Streaming Data Types


STREAM_TIME

The STREAM_TIME data type is used to express reference times in Microsoft DirectShow multimedia streaming. Units are 100 nanoseconds.

Syntax

typedef LONGLONG STREAM_TIME;

Remarks

This data type is equivalent to the DirectShow REFERENCE_TIME data type.

See Also

  • Multimedia Streaming Data Types


Multimedia Streaming Structures

The Microsoft DirectDraw interfaces that are exposed through the multimedia streaming APIs use the following structures.

Structure | Description
DDBLTBATCH | This structure is used to pass blit operations to the BltBatch method.
DDBLTFX | This structure is used to pass raster ops, effects, and override information to the Blt method. It is also part of the DDBLTBATCH structure used with the BltBatch method.
DDCAPS | This structure represents the capabilities of the hardware exposed through the DirectDraw object. It contains a DDSCAPS structure which is used in this context to describe what kinds of DirectDrawSurfaces can be created. It may not be possible to simultaneously create all of the surfaces described by these capabilities.
DDCOLORKEY | This structure is used to describe a source or destination color key or color space. A color key is specified if the low and high range values are the same.
DDMODEDESC | This structure is returned to the EnumModes method to describe the mode that can be created including the monitor frequency and monitor configuration flags.
DDOVERLAYFX | This structure is used to pass override information to UpdateOverlay.
DDPIXELFORMAT | This structure describes the pixel format of a DirectDrawSurface object.
DDSCAPS | This structure defines the capabilities of DirectDrawSurfaces. It is part of the DDCAPS structure which is used to describe the capabilities of the DirectDraw object.
DDSURFACEDESC | The structure is passed to CreateSurface to describe the surface that should be created. The relevant members differ for each type of surface being created.

See Also

  • Multimedia Streaming Interfaces


DDBLTBATCH Structure

This structure is used to pass blit operations to the BltBatch method.

typedef struct _DDBLTBATCH{
LPRECT            lprDest;
LPDIRECTDRAWSURFACE    lpDDSSrc;
LPRECT            lprSrc;
DWORD            dwFlags;
LPDDBLTFX        lpDDBltFx;

} DDBLTBATCH,FAR *LPDDBLTBATCH;

Members

lprDest

Pointer to a RECT structure that defines the destination for the blit.

lpDDSSrc

Pointer to a DirectDrawSurface that will be the source of the blit.

lprSrc

Pointer to a RECT structure that defines the source rectangle of the blit.

dwFlags

Flag | Description
DDBLT_ALPHADEST | Use the alpha information in the pixel format or the alpha channel surface attached to the destination surface as the alpha channel for this blit.
DDBLT_ALPHADESTCONSTOVERRIDE | Use the dwConstAlphaDest member in the DDBLTFX structure as the alpha channel for the destination surface for this blit.
DDBLT_ALPHADESTNEG | The NEG suffix indicates that the destination surface becomes more transparent as the alpha value increases. (0 is opaque)
DDBLT_ALPHADESTSURFACEOVERRIDE | Use the lpDDSAlphaDest member in the DDBLTFX structure as the alpha channel for the destination for this blit.
DDBLT_ALPHAEDGEBLEND | Use the dwAlphaEdgeBlend member in the DDBLTFX structure as the alpha channel for the edges of the image that border the color key colors.
DDBLT_ALPHASRC | Use the alpha information in the pixel format or the alpha channel surface attached to the source surface as the alpha channel for this blit.
DDBLT_ALPHASRCCONSTOVERRIDE | Use the dwConstAlphaSrc member in the DDBLTFX structure as the alpha channel for the source for this blit.
DDBLT_ALPHASRCNEG | The NEG suffix indicates that the source surface becomes more transparent as the alpha value increases. (0 is opaque)
DDBLT_ALPHASRCSURFACEOVERRIDE | Use the lpDDSAlphaSrc member in the DDBLTFX structure as the alpha channel for the source for this blit.
DDBLT_ASYNC | Do this blit asynchronously through the FIFO in the order received. If there is no room in the hardware FIFO fail the call.
DDBLT_COLORFILL | Uses the dwFillColor member in the DDBLTFX structure as the RGB color to fill the destination rectangle on the destination surface with.
DDBLT_DDFX | Uses the dwDDFX member in the DDBLTFX structure to specify the effects to use for the blit.
DDBLT_DDROPS | Uses the dwDDROPS member in the DDBLTFX structure to specify the ROPS that are not part of the Win32 API.
DDBLT_KEYDEST | Use the color key associated with the destination surface.
DDBLT_KEYDESTOVERRIDE | Use the dckDestColorkey member in the DDBLTFX structure as the color key for the destination surface.
DDBLT_KEYSRC | Use the color key associated with the source surface.
DDBLT_KEYSRCOVERRIDE | Use the dckSrcColorkey member in the DDBLTFX structure as the color key for the source surface.
DDBLT_ROP | Use the dwROP member in the DDBLTFX structure for the raster operation for this blit. These ROPs are the same as the ones defined in the Win32 API.
DDBLT_ROTATIONANGLE | Use the dwRotationAngle member in the DDBLTFX structure as the angle (specified in 1/100th of a degree) to rotate the surface.
DDBLT_ZBUFFER | Z-buffered blit using the z-buffers attached to the source and destination surfaces and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer opcode.
DDBLT_ZBUFFERDESTCONSTOVERRIDE | Z-buffered blit using the dwConstDest member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the destination.
DDBLT_ZBUFFERDESTOVERRIDE | Z-buffered blit using the lpDDSDestZBuffer member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the destination.
DDBLT_ZBUFFERSRCCONSTOVERRIDE | Z-buffered blit using the dwConstSrcZ member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the source.
DDBLT_ZBUFFERSRCOVERRIDE | Z-buffered blit using the lpDDSSrcZBuffer member and the dwZBufferOpCode member in the DDBLTFX structure as the z-buffer and z-buffer opcode respectively for the source.

lpDDBltFx

Pointer to a DDBLTFX structure specifying additional blit effects.

See Also

  • Multimedia Streaming Structures


DDBLTFX Structure

This structure is used to pass raster ops, effects, and override information to the Blt method. It is also part of the DDBLTBATCH structure used with the BltBatch method.

typedef struct _DDBLTFX{
  DWORD    dwSize;
  DWORD    dwDDFX;
  DWORD    dwROP;
  DWORD    dwDDROP;
  DWORD    dwRotationAngle;
  DWORD    dwZBufferOpCode;
  DWORD    dwZBufferLow;
  DWORD    dwZBufferHigh;
  DWORD    dwZBufferBaseDest;
  DWORD    dwZDestConstBitDepth;
  union
  {
    DWORD  dwZDestConst;
    LPDIRECTDRAWSURFACE  lpDDSZBufferDest;
  };
  DWORD    dwZSrcConstBitDepth;
  union
  {
    DWORD        dwZSrcConst;
    LPDIRECTDRAWSURFACE lpDDSZBufferSrc;
  };
  DWORD    dwAlphaEdgeBlendBitDepth;
  DWORD    dwAlphaEdgeBlend;
  DWORD    dwReserved;

  DWORD    dwAlphaDestConstBitDepth;
  union
  {
    DWORD  wAlphaDestConst;
    LPDIRECTDRAWSURFACE  lpDDSAlphaDest;
  };
  DWORD    dwAlphaSrcConstBitDepth;
  union
  {
    DWORD dwAlphaSrcConst;
    LPDIRECTDRAWSURFACE     lpDDSAlphaSrc;
  };
  union
  {
    WORD  dwFillColor;
    LPDIRECTDRAWSURFACE  lpDDSPattern;
  };
  DDCOLORKEY    dckDestColorkey;
  DDCOLORKEY    dckSrcColorkey;
} DDBLTFX,FAR* LPDDBLTFX;

Members

dwSize

Size of the structure. Must be initialized before the structure is used.

dwDDFX

FX operations.

Flag | Description
DDBLTFX_ARITHSTRETCHY | If stretching, use arithmetic stretching along the y-axis for this blit.
DDBLTFX_MIRRORLEFTRIGHT | Do this blit mirroring the surface left to right. Spin the surface around its y-axis.
DDBLTFX_MIRRORUPDOWN | Do this blit mirroring the surface up and down. Spin the surface around its x-axis.
DDBLTFX_NOTEARING | Schedule this blit to avoid tearing.
DDBLTFX_ROTATE180 | Do this blit rotating the surface 180 degrees clockwise.
DDBLTFX_ROTATE270 | Do this blit rotating the surface 270 degrees clockwise.
DDBLTFX_ROTATE90 | Do this blit rotating the surface 90 degrees clockwise.
DDBLTFX_ZBUFFERRANGE | Do this z blit using dwZBufferLow and dwZBufferHigh as range values specified to limit the bits copied from the source surface.
DDBLTFX_ZBUFFERBASEDEST | Do this z blit adding the value of dwZBufferBaseDest to each of the sources' z values before comparing it with the destination z values.

dwROP

Win32 raster operations.

dwDDROP

DirectDraw raster operations.

dwRotationAngle

Rotation angle for the blit.

dwZBufferOpCode

Z buffer compares.

dwZBufferLow

Low limit of Z buffer.

dwZBufferHigh

High limit of Z buffer.

dwZBufferBaseDest

Destination base value.

dwZDestConstBitDepth

Bit depth used to specify Z constant for destination.

dwZDestConst

Constant to use as Z buffer for destination.

lpDDSZBufferDest

Surface to use as Z buffer for destination.

dwZSrcConstBitDepth

Bit depth used to specify Z constant for source.

dwZSrcConst

Constant to use as Z buffer for source.

lpDDSZBufferSrc

Surface to use as Z buffer for source.

dwAlphaEdgeBlendBitDepth

Bit depth used to specify constant for alpha edge blend.

dwAlphaEdgeBlend

Alpha for edge blending.

dwReserved

Reserved for future use.

dwAlphaDestConstBitDepth

Bit depth used to specify alpha constant for destination.

dwAlphaDestConst

Constant to use as Alpha Channel.

lpDDSAlphaDest

Surface to use as Alpha Channel.

dwAlphaSrcConstBitDepth

Bit depth used to specify alpha constant for source

dwAlphaSrcConst

Constant to use as Alpha Channel.

pDDSAlphaSrc

Surface to use as Alpha Channel.

dwFillColor

Fill color in RGB or Palettized.

lpDDSPattern

Surface to use as pattern.

dckDestColorkey

DestColorkey override.

dckSrcColorkey

SrcColorkey override.

See Also

  • Multimedia Streaming Structures


DDCAPS Structure

This structure represents the capabilities of the hardware exposed through the DirectDraw object. It contains a DDSCAPS structure which is used in this context to describe what kinds of DirectDrawSurfaces can be created. It may not be possible to simultaneously create all of the surfaces described by these capabilities.

typedef struct _DDCAPS{
  WORD    dwSize;
  DWORD    dwCaps;
  DWORD    dwCaps2;
  DWORD    dwCKeyCaps;
  DWORD    dwFXCaps;
  DWORD    dwFXAlphaCaps;
  DWORD    dwPalCaps;
  DWORD    dwSVCaps;
  DWORD    dwAlphaBltConstBitDepths;
  DWORD    dwAlphaBltPixelBitDepths;
  DWORD    dwAlphaBltSurfaceBitDepths;
  DWORD    dwAlphaOverlayConstBitDepths;
  DWORD    dwAlphaOverlayPixelBitDepths;
  DWORD    dwAlphaOverlaySurfaceBitDepths;
  DWORD    dwZBufferBitDepths;
  DWORD    dwVidMemTotal;
  DWORD    dwVidMemFree;
  DWORD    dwMaxVisibleOverlays;
  DWORD    dwCurrVisibleOverlays;
  DWORD    dwNumFourCCCodes;
  DWORD    dwAlignBoundarySrc;
  DWORD    dwAlignSizeSrc;
  DWORD    dwAlignBoundaryDest;
  DWORD    dwAlignSizeDest;
  DWORD    dwAlignStrideAlign;
  DWORD    dwRops[DD_ROP_SPACE];
  DDSCAPS    ddsCaps;
  DWORD    dwMinOverlayStretch;
  DWORD    dwMaxOverlayStretch;
  DWORD    dwMinLiveVideoStretch;
  DWORD    dwMaxLiveVideoStretch;
  DWORD    dwMinHwCodecStretch;
  DWORD    dwMaxHwCodecStretch;
  DWORD    dwReserved1;
  DWORD    dwReserved2;
  DWORD    dwReserved3;
} DDCAPS,FAR* LPDDCAPS;

Members

dwSize

Size of structure. Must be initialized before use.

dwCaps

Driver-specific capabilities.

Flag | Description
DDCAPS_3D | Display hardware has 3D acceleration.
DDCAPS_ALIGNBOUNDARYDEST | Indicates that DirectDraw will support only source rectangles whose x-axis is aligned on DIRECTDRAWCAPS.dwAlignBoundaryDest boundaries of the surface, respectively.
DDCAPS_ALIGNSIZEDEST | Indicates that DirectDraw will support only source rectangles whose x-axis size in BYTEs are DIRECTDRAWCAPS.dwAlignSizeDest multiples, respectively.
DDCAPS_ALIGNBOUNDARYSRC | Indicates that DirectDraw will support only source rectangles whose x-axis is aligned on DIRECTDRAWCAPS.dwAlignBoundarySrc boundaries of the surface, respectively.
DDCAPS_ALIGNSIZESRC | Indicates that DirectDraw will support only source rectangles whose x-axis size in BYTEs are DIRECTDRAWCAPS.dwAlignSizeSrc multiples, respectively.
DDCAPS_ALIGNSTRIDE | Indicates that DirectDraw will create video memory surfaces that have a stride alignment equal to DIRECTDRAWCAPS.dwAlignStrideAlign.
DDCAPS_BANKSWITCHED | Display hardware is bank switched, and potentially very slow at random access to VRAM.
DDCAPS_BLT | Display hardware is capable of blit operations.
DDCAPS_BLTCOLORFILL | Display hardware is capable of color fill with bltter.
DDCAPS_BLTQUEUE | Display hardware is capable of asynchronous blit operations.
DDCAPS_BLTFOURCC | Display hardware is capable of color space conversions during the blit operations.
DDCAPS_BLTSTRETCH | Display hardware is capable of stretching during blit operations.
DDCAPS_GDI | Display hardware is shared with GDI.
DDCAPS_OVERLAY | Display hardware can overlay.
DDCAPS_OVERLAYCANTCLIP | Hardware can overlay but can't clip.
DDCAPS_OVERLAYFOURCC | Indicates that overlay hardware is capable of color space conversions during the overlay operation.
DDCAPS_OVERLAYSTRETCH | Stretching can be done by the overlay hardware.
DDCAPS_PALETTE | Indicates that DirectDraw is capable of creating and supporting DirectDrawPalette objects for more than the primary surface.
DDCAPS_PALETTECANVSYNC | Indicates that DirectDraw is capable of updating the palette in sync with the vertical refresh.
DDCAPS_READSCANLINE | Display hardware can return the current scan line.
DDCAPS_STEREOVIEW | Display hardware has stereo vision capabilities. DDSCAPS_PRIMARYSURFACELEFT can be created.
DDCAPS_VBI | Display hardware is capable of generating a vertical blank interrupt.
DDCAPS_ZBLTS | Supports the use of Z buffers with blit operations.
DDCAPS_ZOVERLAYS | Supports the use of OverlayZOrder as a z value for overlays to control their layering.
DDCAPS_COLORKEY | Obsolete flag that represents color key capabilities in either overlay hardware or blit hardware. Will be replaced with DDCAPS_OVERLAYCOLORKEY and DDCAPS_BLTCOLORKEY.
DDCAPS_ALPHA | Display hardware supports alpha channel during blit operations.
DDCAPS_COLORKEY_HWASSIST | Color key is hardware assisted.
DDCAPS_NOHARDWARE | No hardware support at all.

D

dwCaps2

More driver-specific capabilities.

Flag | Description
DDCAPS2_CERTIFIED | Display hardware is certified.

dwCKeyCaps

Color key capabilities.

Flag | Description
DDCKEYCAPS_DESTBLT | Supports transparent blitting using a color key to identify the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACE | Supports transparent blitting using a color space to identify the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACEYUV | Supports transparent blitting using a color space to identify the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTBLTYUV | Supports transparent blitting using a color key to identify the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTOVERLAY | Supports overlaying using color keying of the replaceable bits of the surface being overlayed for RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACE | Supports a color space as the color key for the destination for RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV | Supports a color space as the color key for the destination for YUV colors.
DDCKEYCAPS_DESTOVERLAYONEACTIVE | Supports only one active destination color key value for visible overlay surfaces.
DDCKEYCAPS_DESTOVERLAYYUV | Supports overlaying using color keying of the replaceable bits of the surface being overlayed for YUV colors.
DDCKEYCAPS_SRCBLT | Supports transparent blitting using the color key for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACE | Supports transparent blitting using a color space for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACEYUV | Supports transparent blitting using a color space for the source with this surface for YUV colors.
DDCKEYCAPS_SRCBLTYUV | Supports transparent blitting using the color key for the source with this surface for YUV colors.
DDCKEYCAPS_SRCOVERLAY | Supports overlays using the color key for the source with this overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACE | Supports overlays using a color space as the source color key for the overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV | Supports overlays using a color space as the source color key for the overlay surface for YUV colors.
DDCKEYCAPS_SRCOVERLAYONEACTIVE | Supports only one active source color key value for visible overlay surfaces.
DDCKEYCAPS_SRCOVERLAYYUV | Supports overlays using the color key for the source with this overlay surface for YUV colors.

dwFXCaps

Driver-specific stretching and effects capabilities.

Flag | Description
DDFXCAPS_BLTARITHSTRETCHY | Uses arithmetic operations to stretch and shrink surfaces during blit rather than pixel-doubling techniques. Along the y axis.
DDFXCAPS_BLTARITHSTRETCHYN | Uses arithmetic operations to stretch and shrink surfaces during blit rather than pixel-doubling techniques. Along the y axis. Only works for x1, x2, and so on.
DDFXCAPS_BLTMIRRORLEFTRIGHT | Supports mirroring left to right in blit.
DDFXCAPS_BLTMIRRORUPDOWN | Supports mirroring top to bottom in blit.
DDFXCAPS_BLTROTATION | Supports arbitrary rotation.
DDFXCAPS_BLTROTATION90 | Supports 90 degree rotations.
DDFXCAPS_BLTSHRINKX | Supports arbitrary shrinking of a surface along the x-axis (horizontal direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSHRINKXN | Supports integer shrinking (1x,2x,) of a surface along the x-axis (horizontal direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSHRINKY | Supports arbitrary shrinking of a surface along the y axis (vertical direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSHRINKYN | Supports integer shrinking (1x,2x,) of a surface along the y axis (vertical direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSTRETCHX | Supports arbitrary stretching of a surface along the x-axis (horizontal direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSTRETCHXN | Supports integer stretching (1x,2x,) of a surface along the x-axis (horizontal direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSTRETCHY | Supports arbitrary stretching of a surface along the y axis (vertical direction). This flag is only valid for blit operations.
DDFXCAPS_BLTSTRETCHYN | Supports integer stretching (1x,2x,) of a surface along the y axis (vertical direction). This flag is only valid for blit operations.
DDFXCAPS_OVERLAYARITHSTRETCHY | Uses arithmetic operations to stretch and shrink surfaces during overlay rather than pixel-doubling techniques. Along the y axis.
DDFXCAPS_OVERLAYARITHSTRETCHYN | Uses arithmetic operations to stretch and shrink surfaces during overlay rather than pixel-doubling techniques. Along the y axis. Only works for x1, x2, and so on.
DDFXCAPS_OVERLAYSHRINKX | Supports arbitrary shrinking of a surface along the x-axis (horizontal direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKXN | Supports integer shrinking (1x,2x,) of a surface along the x-axis (horizontal direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKY | Supports arbitrary shrinking of a surface along the y axis (vertical direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKYN | Supports integer shrinking (1x,2x,) of a surface along the y axis (vertical direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSTRETCHX | Supports arbitrary stretching of a surface along the x-axis (horizontal direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHXN | Supports integer stretching (1x,2x,) of a surface along the x-axis (horizontal direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHY | Supports arbitrary stretching of a surface along the y axis (vertical direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHYN | Supports integer stretching (1x,2x,) of a surface along the y axis (vertical direction). This flag is only valid for DDSCAPS_OVERLAY surfaces. This flag only indicates the capabilities of a surface. It does not indicate that stretching is available.
DDFXCAPS_OVERLAYMIRRORLEFTRIGHT | Supports mirroring of overlays across the vertical axis.
DDFXCAPS_OVERLAYMIRRORUPDOWN | Supports mirroring of overlays across the horizontal axis.
DDFXCAPS_BLTARITHSTRETCHY | Uses arithmetic operations to stretch and shrink surfaces during blit rather than pixel-doubling techniques. Along the y axis.

dwFXAlphaCaps

Driver specific alpha capabilities.

Flag | Description
DDFXALPHACAPS_BLTALPHAEDGEBLEND | Supports alpha blending around the edge of a source color-keyed surface. For Blt.
DDFXALPHACAPS_BLTALPHAPIXELS | Supports alpha information in the pixel format. The bit depth of alpha information in the pixel format can be 1,2,4, or 8. The alpha value becomes more opaque as the alpha value increases. (0 is transparent.) For Blt.
DDFXALPHACAPS_BLTALPHAPIXELSNEG | Supports alpha information in the pixel format. The bit depth of alpha information in the pixel format can be 1,2,4, or 8. The alpha value becomes more transparent as the alpha value increases. (0 is opaque.) This flag can only be set if DDCAPS_ALPHA is set. For Blt.
DDFXALPHACAPS_BLTALPHASURFACES | Supports alpha only surfaces. The bit depth of an alpha only surface can be 1,2,4, or 8. The alpha value becomes more opaque as the alpha value increases. (0 is transparent.) For Blt.
DDFXALPHACAPS_BLTALPHASURFACESNEG | The depth of the alpha channel data can range can be 1,2,4, or 8. The NEG suffix indicates that this alpha channel becomes more transparent as the alpha value increases. (0 is opaque.) This flag can only be set if DDFXCAPS_ALPHASURFACES is set. For Blt.
DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND | Supports alpha blending around the edge of a source color keyed surface. For Overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELS | Supports alpha information in the pixel format. The bit depth of alpha information in the pixel format can be 1,2,4, or 8. The alpha value becomes more opaque as the alpha value increases. (0 is transparent.) For Overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG | Supports alpha information in the pixel format. The bit depth of alpha information in the pixel format can be 1,2,4, or 8. The alpha value becomes more transparent as the alpha value increases. (0 is opaque.) This flag can only be set if DDFXCAPS_ALPHAPIXELS is set. For Overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACES | Supports alpha-only surfaces. The bit depth of an alpha-only surface can be 1,2,4, or 8. The alpha value becomes more opaque as the alpha value increases. (0 is transparent.) For Overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACESNEG | The depth of the alpha channel data can range can be 1,2,4, or 8. The NEG suffix indicates that this alpha channel becomes more transparent as the alpha value increases. (0 is opaque.) This flag can only be set if DDFXCAPS_ALPHASURFACES is set. For Overlays.

dwPalCaps

Palette capabilities.

Flag | Description
DDPCAPS_4BIT | Index is 4 bits. There are sixteen color entries in the palette table.
DDPCAPS_8BITENTRIES | Index is onto an 8-bit color index. This member is only valid with the DDPCAPS_4BIT capability and the target surface is in 8bpp. Each color entry is one byte long and is an index into destination surface's 8bpp palette.
DDPCAPS_8BIT | Index is 8 bits. There are 256 color entries in the palette table.
DDPCAPS_ALLOW256 | This palette can have all 256 entries defined.
DDPCAPS_INITIALIZE | Indicates that this DirectDrawPalette should use the palette color array passed into the lpDDColorArray parameter to initialize the DirectDrawPalette object.
DDPCAPS_PRIMARYSURFACE | This palette is the one attached to the primary surface.
DDPCAPS_PRIMARYSURFACELEFT | This palette is the one attached to the primary surface left. Changing this table has immediate effect on the display unless DDPAL_VSYNC is specified and supported.
DDPCAPS_VSYNC | This palette can have modifications to it synced with the monitor's refresh rate.

dwSVCaps

Stereo vision capabilities.

Flag | Description
DDSVCAPS_ENIGMA | The stereo view is accomplished via Enigma encoding.
DDSVCAPS_FLICKER | The stereo view is accomplished via high frequency flickering.
DDSVCAPS_REDBLUE | The stereo view is accomplished via red and blue filters applied to the left and right eyes. All images must adapt their color spaces for this process.
DDSVCAPS_SPLIT | The stereo view is accomplished with split screen technology.

dwAlphaBltConstBitDepths

DDBD_2,4,8

dwAlphaBltPixelBitDepths

DDBD_1,2,4,8

dwAlphaBltSurfaceBitDepths

DDBD_1,2,4,8

dwAlphaOverlayConstBitDepths

DDBD_2,4,8

dwAlphaOverlayPixelBitDepths

DDBD_1,2,4,8

dwAlphaOverlaySurfaceBitDepths

DDBD_1,2,4,8

dwZBufferBitDepths

DDBD_8,16,24,32

dwVidMemTotal

Total amount of video memory.

dwVidMemFree

Amount of free video memory.

dwMaxVisibleOverlays

Maximum number of visible overlays.

dwCurrVisibleOverlays

Current number of visible overlays.

dwNumFourCCCodes

Number of FOURCC codes.

dwAlignBoundarySrc

Source rectangle alignment.

dwAlignSizeSrc

Source rectangle byte size.

dwAlignBoundaryDest

Destination rectangle alignment.

dwAlignSizeDest

Destination rectangle byte size.

dwAlignStrideAlign

Stride alignment.

dwRops[DD_ROP_SPACE]

ROPS supported.

ddsCaps

DDSCAPS structure with general capabilities.

dwMinOverlayStretch

Minimum overlay stretch factor multiplied by 1000.

dwMaxOverlayStretch

Maximum overlay stretch factor multiplied by 1000.

dwMinLiveVideoStretch

Minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3.

dwMaxLiveVideoStretch

Maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3.

dwMinHwCodecStretch

Minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 = 1.3.

dwMaxHwCodecStretch;

Maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 = 1.3.

dwReserved1,dwReserved2,dwReserved3

Reserved.

dw...BitDepths

  • DDBD_1 1 bit per pixel.
  • DBD_2 2 bits per pixel.
  • DDBD_4 4 bits per pixel.
  • DDBD_8 8 bits per pixel.
  • DDBD_16 16 bits per pixel.
  • DDBD_24 24 bits per pixel.
  • DDBD_32 32 bits per pixel.

See Also

  • Multimedia Streaming Structures


DDCOLORKEY Structure

This structure is used to describe a source or destination color key or color space. A color key is specified if the low and high range values are the same.

typedef struct _DDCOLORKEY{
DWORD    dwColorSpaceLowValue;
DWORD    dwColorSpaceHighValue;

} DDCOLORKEY,FAR* LPDDCOLORKEY;

Members

dwColorSpaceLowValue

The low value of the color range that is to be used as the color key, inclusive.

dwColorSpaceHighValue

The high value of the color range that is to be used as the color key, inclusive.

See Also

  • Multimedia Streaming Structures


DDMODEDESC Structure

This structure is returned to the EnumModes enumeration method to describe the mode that can be created including the monitor frequency and monitor configuration flags.

typedef struct {
DWORD        dwSize;
DWORD        dwFlags;
DWORD        dwMonitorFrequency;
DDSURFACEDESC    dsdSurfaceDesc;

} DDMODEDESC, FAR* LPDDMODEDESC;

Members

dwSize

Size of the structure. Must be initialized before use.

dwFlags

Enumeration flags.

dwMonitorFrequency

Frequency of the monitor in this mode.

dsdSurfaceDesc

Surface description.

See Also

  • Multimedia Streaming Structures


DDOVERLAYFX Structure

This structure is used to pass override information to the UpdateOverlay method.

typedef struct _DDOVERLAYFX{
  DWORD    dwSize;
  DWORD    dwAlphaEdgeBlendBitDepth;
  DWORD    dwAlphaEdgeBlend;
  DWORD    dwReserved;
  DWORD    dwAlphaDestConstBitDepth;
  union
  {
    DWORD  dwAlphaDestConst;
    LPDIRECTDRAWSURFACE  lpDDSAlphaDest;
  };
  DWORD    dwAlphaSrcConstBitDepth;
  union
  {
    DWORD  dwAlphaSrcConst;
    LPDIRECTDRAWSURFACE     lpDDSAlphaSrc;
  };
  DDCOLORKEY    dckDestColorkey;
  DDCOLORKEY    dckSrcColorkey;
  DWORD    dwDDFX;
  DWORD    dwFlags;
} DDOVERLAYFX,FAR *LPDDOVERLAYFX;

Members

dwSize

Size of structure. Must be initialized before use.

dwAlphaEdgeBlendBitDepth

Bit depth used to specify constant for alpha edge blend.

dwAlphaEdgeBlend

Constant to use as alpha for edge blend.

dwReserved

Reserved.

dwAlphaDestConstBitDepth

Bit depth used to specify alpha constant for destination.

dwAlphaDestConst

Constant to use as alpha channel for destination.

lpDDSAlphaDest

Pointer to a surface to use as alpha channel for destination.

dwAlphaSrcConstBitDepth

Bit depth used to specify alpha constant for source.

dwAlphaSrcConst

Constant to use as alpha channel for source.

lpDDSAlphaSrc

Pointer to a surface to use as alpha channel for source.

dckDestColorkey

DestColorkey override.

dckSrcColorkey

DestColorkey override.

dwDDFX

Overlay FX flags.

Flag | Description
DDOVERFX_ARITHSTRETCHY | If stretching, use arithmetic stretching along the y-axis for this overlay.
DDOVERFX_MIRRORLEFTRIGHT | Mirror the overlay across the vertical axis.
DDOVERFX_MIRRORUPDOWN | Mirror the overlay across the horizontal axis.

dwFlags

Flags.

See Also

  • Multimedia Streaming Structures


DDPIXELFORMAT Structure

This structure describes the pixel format of a DirectDrawSurface object.

typedef struct _DDPIXELFORMAT{
  DWORD    dwSize;
  DWORD    dwFlags;
  DWORD    dwFourCC;
  union
  {
    DWORD    dwRGBBitCount;
    DWORD    dwYUVBitCount;
    DWORD    dwZBufferBitDepth;
    DWORD    dwAlphaBitDepth;
  };
  union
  {
    DWORD    dwRBitMask;
    DWORD    dwYBitMask;
  };
  union
  {
    DWORD    dwGBitMask;
    DWORD    dwUBitMask;
  };
  union{
    DWORD    dwBBitMask;
    DWORD    dwVBitMask;
  };
  union
  {
    DWORD    dwRGBAlphaBitMask;
    DWORD    dwYUVAlphaBitMask;
  };
} DDPIXELFORMAT, FAR* LPDDPIXELFORMAT;

Members

dwSize

Size of the structure. Must be initialized prior to use.

dwFlags

Flag | Description
DDPF_ALPHAPIXELS | The surface has alpha channel information in the pixel format.
DDPF_ALPHA | The pixel format describes an alpha-only surface.
DDPF_FOURCC | The FourCC code is valid.
DDPF_PALETTEINDEXED4 | The surface is 4-bit color indexed.
DDPF_PALETTEINDEXED4TO8 | The surface is 4-bit color indexed to an 8-bit palette.
DDPF_PALETTEINDEXED8 | The surface is 8-bit color indexed.
DDPF_RGB | The RGB data in the pixel format structure is valid.
DDPF_COMPRESSED | The surface will accept pixel data in the specified format and compress it during the write.
DDPF_RGBTOYUV | The surface will accept RGB data and translate it during the write to YUV data. The format of the data to be written will be contained in the pixel format structure. The DDPF_RGB flag will be set.
DDPF_YUV | The YUV data in the pixel format structure is valid.
DDPF_ZBUFFER | The pixel format describes a z buffer only surface.

dwFourCC

FOURCC code.

dwRGBBitCount

RGB bits per pixel. (DDBD_4,8,16,24,32)

dwYUVBitCount

YUV bits per pixel. (DDBD_4,8,16,24,32)

dwZBufferBitDepth

Z buffer bit depth. (DDBD_8,16,24,32)

dwAlphaBitDepth

Alpha channel bit depth. (DDBD_1,2,4,8)

dwRBitMask

Mask for red bits.

dwYBitMask

Mask for Y bits.

dwGBitMask

Mask for green bits.

dwUBitMask

Mask for U bits.

dwBBitMask

Mask for blue bits.

dwVBitMask

Mask for V bits.

dwRGBAlphaBitMask

Mask for alpha channel.

dwYUVAlphaBitMask

Mask for alpha channel.

See Also

  • Multimedia Streaming Structures


DDSCAPS Structure

This structure defines the capabilities of DirectDrawSurfaces. It is part of the DDCAPS structure which is used to describe the capabilities of the DirectDraw object.

typedef struct _DDSCAPS{
  WORD  dwCaps;
} DDSCAPS,  FAR* LPDDSCAPS;

Members

dwCaps

Flag | Description
DDSCAPS_3D | Indicates that this surface is a front buffer, back buffer, or texture map that is being used in conjunction with a 3DDDI or Direct3D HAL.
DDSCAPS_ALPHA | Indicates that this surface contains alpha information. The pixel format must be interrogated to determine whether this surface contains only alpha information or alpha information interlaced with pixel color data (such as RGBA or YUVA).
DDSCAPS_BACKBUFFER | Indicates that this surface is a backbuffer. It is generally set by CreateSurface when the DDSCAPS_FLIP capability bit is set. It indicates that this surface is THE back buffer of a surface-flipping structure. DirectDraw supports N surfaces in a surface-flipping structure. Only the surface that immediately precedes the DDSCAPS_FRONTBUFFER has this capability bit set. The other surfaces are identified as back buffers by the presence of the DDSCAPS_FLIP capability, their attachment order, and the absence of the DDSCAPS_FRONTBUFFER and DDSCAPS_BACKBUFFER capabilities. The bit is sent to CreateSurface when a standalone back buffer is being created. This surface could be attached to a front buffer and/or back buffers to form a flipping surface structure after the CreateSurface call. See AddAttachedSurface for a detailed description of the behaviors in this case.
DDSCAPS_COMPLEX | Indicates a complex surface structure is being described. A complex surface structure results in the creation of more than one surface. The additional surfaces are attached to the root surface. The complex structure can only be destroyed by destroying the root.
DDSCAPS_FLIP | Indicates that this surface is a part of a surface flipping structure. When it is passed to CreateSurface the DDSCAPS_FRONTBUFFER and DDSCAP_BACKBUFFER bits are not set.
DDSCAPS_FRONTBUFFER | Indicates that this surface is THE front buffer of a surface flipping structure. It is generally set by CreateSurface when the DDSCAPS_FLIP capability bit is set. If this capability is sent to CreateSurface then a standalone front buffer is created. This surface will not have the DDSCAPS_FLIP capability. It can be attached to other back buffers to form a flipping structure. See AddAttachedSurface for a detailed description of the behaviors in this case.
DDSCAPS_HWCODEC | Indicates surface should be able to have a stream decompressed to it by the hardware.
DDSCAPS_LIVEVIDEO | Indicates surface should be able to receive live video.
DDSCAPS_MODEX | Surface is a 320x200 or 320x240 ModeX surface.
DDSCAPS_OFFSCREENPLAIN | Indicates that this surface is any offscreen surface that is not an overlay, texture, zbuffer, front buffer, back buffer, or alpha surface. It is used to identify plain vanilla surfaces.
DDSCAPS_OWNDC | Indicates surface will have a DC associated long term.
DDSCAPS_OVERLAY | Indicates that this surface is an overlay. It may or may not be directly visible depending on whether or not it is currently being overlayed onto the primary surface. DDSCAPS_VISIBLE can be used to determine whether or not it is being overlayed at the moment.
DDSCAPS_PALETTE | Indicates that unique DirectDrawPalette objects can be created and attached to this surface.
DDSCAPS_PRIMARYSURFACE | Indicates that this surface is the primary surface. The primary surface represents what the user is seeing at the moment.
DDSCAPS_PRIMARYSURFACELEFT | Indicates that this surface is the primary surface for the left eye. The primary surface for the left eye represents what the user is seeing at the moment with the user's left eye. When this surface is created the DDSCAPS_PRIMARYSURFACE represents what the user is seeing with the user's right eye.
DDSCAPS_SYSTEMMEMORY | Indicates that this surface memory was allocated in system memory.
DDSCAPS_TEXTUREMAP | Indicates that this surface can be used as a 3D texture. It does not indicate whether or not the surface is being used for that purpose.
DDSCAPS_VIDEOMEMORY | Indicates that this surface exists in video memory.
DDSCAPS_VISIBLE | Indicates that changes made to this surface are immediately visible. It is always set for the primary surface and is set for overlays while they are being overlayed and texture maps while they are being textured.
DDSCAPS_WRITEONLY | READ ONLY.
DDSCAPS_ZBUFFER | Indicates that this surface is the z buffer. The z buffer does not contain displayable information. Instead, it contains bit depth information that is used to determine which pixels are visible and which are obscured.

See Also

  • Multimedia Streaming Structures


DDSURFACEDESC Structure

The structure is passed to CreateSurface to describe the surface that should be created. The relevant members differ for each type of surface being created.

typedef struct _DDSURFACEDESC{
  DWORD   dwSize;
  DWORD   dwFlags;
  DWORD   dwHeight;
  DWORD   dwWidth;
  LONG    lPitch;
  DWORD   dwBackBufferCount;
  DWORD   dwZBufferBitDepth;
  DWORD   dwAlphaBitDepth;
  LPVOID  lpSurface;
  DDCOLORKEY  ddckCKDestOverlay;
  DDCOLORKEY  ddckCKDestBlt;
  DDCOLORKEY  ddckCKSrcOverlay;
  DDCOLORKEY  ddckCKSrcBlt;
  DDPIXELFORMAT  ddpfPixelFormat;
  DDSCAPS  ddsCaps;
} DDSURFACEDESC,  FAR* LPDDSURFACEDESC;

Members

dwSize

Size of the structure. Must be initialized prior to use.

dwFlags

Flag | Description
DDSD_DDSCAPS | ddsCaps is valid.
DDSD_HEIGHT | dwHeight is valid.
DDSD_WIDTH | dwWidth is valid.
DDSD_PITCH | lPitch is valid.
DDSD_BACKBUFFERCOUNT | dwBackBufferCount is valid.
DDSD_ZBUFFERBITDEPTH | dwZBufferBitDepth is valid.
DDSD_ALPHABITDEPTH | dwAlphaBitDepth is valid.
DDSD_LPSURFACE | lpSurface is valid.
DDSD_PIXELFORMAT | ddpfPixelFormat is valid.
DDSD_CKDESTOVERLAY | ddckCKDestOverlay is valid.
DDSD_CKDESTBLT | ddckCKDestBlt is valid.
DDSD_CKSRCOVERLAY | ddckCKSrcOverlay is valid.
DDSD_CKSRCBLT | ddckCKSrcBlt is valid.
DDSD_ALL | All members are valid.

dwHeight

Height of surface.

dwWidth;

Width of input surface.

lPitch

Distance to start of next line (return value only).

dwBackBufferCount

Number of back buffers.

dwZBufferBitDepth

Depth of Z buffer.

dwAlphaBitDepth

Depth of alpha buffer.

lpSurface

Pointer to the associated surface memory.

ddckCKDestOverlay

Color key for destination overlay use.

ddckCKDestBlt

Color key for destination blit use.

ddckCKSrcOverlay

Color key for source overlay use.

ddckCKSrcBlt

Color key for source blit use.

ddpfPixelFormat

Pixel format description of the surface.

ddsCaps

DirectDraw surface capabilities.

See Also

  • Multimedia Streaming Structures


Multimedia Streaming Error and Success Codes

The following list contains error messages and success notifications for applications that use the multimedia streaming interfaces. This list does not contain all possible errors; the errors shown apply specifically to the Microsoft® DirectShow® implementation of the multimedia streaming interfaces.

Value |  | Hexadecimal code | Description
MS_S_PENDING |  | 0x00040001 | Sample update is not yet complete.
MS_S_NOUPDATE |  | 0x00040002 | Sample was not updated after forced completion.
MS_S_ENDOFSTREAM |  | 0x00040003 | End of stream. Sample not updated.
MS_E_SAMPLEALLOC |  | 0x80040401 | An IMediaStream object could not be removed from an IMultiMediaStream object because it still contains at least one allocated sample.
MS_E_PURPOSEID |  | 0x80040402 | The specified purpose ID can't be used for the call.
MS_E_NOSTREAM |  | 0x80040403 | No stream can be found with the specified attributes.
MS_E_NOSEEKING |  | 0x80040404 | Seeking not supported for this IMultiMediaStream object.
MS_E_INCOMPATIBLE |  | 0x80040405 | The stream formats are not compatible.
MS_E_BUSY |  | 0x80040406 | The sample is busy.
MS_E_NOTINIT |  | 0x80040407 | The object can't accept the call because its initialize function or equivalent has not been called.
MS_E_SOURCEALREADYDEFINED |  | 0x80040408 | Source already defined.
MS_E_INVALIDSTREAMTYPE | 0x80040409 |  | The stream type is not valid for this operation.
MS_E_NOTRUNNING | 0x8004040A |  | The IMultiMediaStream object is not in running state.


Multimedia Streaming Objects

The following table describes the multimedia streaming objects.

Class GUID | Description | Interfaces supported
CLSID_AMMediaTypeStream | Can create media samples for any DirectShow-supported data type | IAMMediaStream IMediaStream IPin IMemInputPin
CLSID_AMAudioData | Implementation of IAudioData audio container object | IAudioData
CLSID_AMDirectDrawStream | DirectDraw media stream that can be added to a DirectShow multimedia stream. | IAMMediaStream IMediaStream IDirectDrawMediaStream IPin IMemInputPin
CLSID_AMMultiMediaStream | DirectShow implementation of multimedia stream. | IAMMultiMediaStream IMultiMediaStream
CLSID_MediaStreamFilter | Provides multimedia streaming functionality for the CLSID_AMMultiMediaStream object through the IAMMultiMediaStream interface. | IBaseFilter
Samples created by the CLSID_AMMediaTypeStream object |  | IStreamSample IMediaSample IMediaSample2
Samples created by the DirectDraw stream. |  | IStreamSample IDirectDrawStreamSample IMediaSample


Multimedia Streaming Sample Code

This article provides sample code that implements the multimedia streaming interfaces. The video streaming sample code demonstrates how to read a file and render it to a primary Microsoft® DirectDraw® surface. For brevity, this code contains no error checking.

The second code sample demonstrates how to use the audio streaming interfaces to stream audio data.

This article contains the following sections.

  • Video Streaming Sample Code
  • Audio Streaming Sample Code


Video Streaming Sample Code

This sample code reads a file and renders it to a primary DirectDraw surface. For brevity, this example performs minimal error checking.

#include <stdio.h>
#include "ddraw.h"       // DirectDraw interfaces
#include "mmstream.h"    // multimedia stream interfaces
#include "amstream.h"    // DirectShow multimedia stream interfaces
#include "ddstream.h"    // DirectDraw multimedia stream interfaces

HRESULT RenderStreamToSurface(IDirectDrawSurface *pSurface,
    IMultiMediaStream *pMMStream)
{
    IMediaStream *pPrimaryVidStream;
    IDirectDrawMediaStream *pDDStream;
    IDirectDrawStreamSample *pSample;
    RECT rect;
    DDSURFACEDESC ddsd;

    HRESULT hr;
    hr = pMMStream->GetMediaStream(MSPID_PrimaryVideo, &pPrimaryVidStream);
    if (FAILED(hr))
    {
        return hr;
    }
    pPrimaryVidStream->QueryInterface(IID_IDirectDrawMediaStream, (void **)&pDDStream);

    ddsd.dwSize = sizeof(ddsd);
    hr = pDDStream->GetFormat(&ddsd, NULL, NULL, NULL);
    if (SUCCEEDED(hr))
    {
        rect.top = rect.left = 0;
        rect.bottom = ddsd.dwHeight;
        rect.right = ddsd.dwWidth;
        hr = pDDStream->CreateSample(pSurface, &rect, 0, &pSample);
        if (SUCCEEDED(hr))
        {
            pMMStream->SetState(STREAMSTATE_RUN);
            while (pSample->Update(0, NULL, NULL, NULL) == S_OK)
            {
                // Empty loop.
            }
            pMMStream->SetState(STREAMSTATE_STOP);
            pSample->Release();
        }
    }
    pDDStream->Release();
    pPrimaryVidStream->Release();
    return hr;
}

HRESULT RenderFileToMMStream(
    const char * szFileName,
    IMultiMediaStream **ppMMStream,
    IDirectDraw *pDD)
{
    if (strlen(szFileName) > MAX_PATH)
    {
        return E_INVALIDARG;
    }

    IAMMultiMediaStream *pAMStream;
    HRESULT hr = CoCreateInstance(CLSID_AMMultiMediaStream, NULL,
        CLSCTX_INPROC_SERVER, IID_IAMMultiMediaStream,
        (void **)&pAMStream);
    if (FAILED(hr)
    {
        return hr;
    }

    WCHAR wPath[MAX_PATH + 1];
    MultiByteToWideChar(CP_ACP, 0, szFileName, -1, wPath, MAX_PATH + 1);

    pAMStream->Initialize(STREAMTYPE_READ, AMMSF_NOGRAPHTHREAD, NULL);
    pAMStream->AddMediaStream(pDD, &MSPID_PrimaryVideo, 0, NULL);
    pAMStream->AddMediaStream(NULL, &MSPID_PrimaryAudio, AMMSF_ADDDEFAULTRENDERER, NULL);
    hr = pAMStream->OpenFile(wPath, 0);
    if (SUCCEEDED(hr))
    {
        hr = pAMStream->QueryInterface(IID_IMultiMediaStream,
            (void**)ppMMStream);
    }
    pAMStream->Release();
    return hr;
}

int __cdecl main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage : showstrm movie.ext\n");
        exit(0);
    }

    DDSURFACEDESC ddsd;
    IDirectDraw *pDD;
    IDirectDrawSurface *pPrimarySurface;
    IMultiMediaStream *pMMStream;

    CoInitialize(NULL);

    DirectDrawCreate(NULL, &pDD, NULL);
    pDD->SetCooperativeLevel(GetDesktopWindow(), DDSCL_NORMAL);

    ddsd.dwSize = sizeof(ddsd);
    ddsd.dwFlags = DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
    pDD->CreateSurface(&ddsd, &pPrimarySurface, NULL);

    HRESULT hr = RenderFileToMMStream(argv[1], &pMMStream, pDD);
    if (SUCCEEDED(hr))
    {
        RenderStreamToSurface(pPrimarySurface, pMMStream);
        pMMStream->Release();
    }
    pPrimarySurface->Release();
    pDD->Release();

    CoUninitialize();
    return 0;
}


Audio Streaming Sample Code

The following code sample demonstrates how to stream audio data using the IAudioMediaStream, IAudioStreamSample, IMemoryData, and IAudioData interfaces. For brevity, this example performs minimal error checking.

#include <windows.h>
#include <stdio.h>
#include <mmsystem.h>
#include <amstream.h>

class CWaveBuffer {
    public:
        ~CWaveBuffer();
        BOOL Init(HWAVEOUT hWave, int Size);
        BOOL Write(PBYTE pData, int nBytes, int& BytesWritten);
        void Flush();
    private:
        WAVEHDR      m_Hdr;
        HWAVEOUT     m_hWave;
        int          m_nBytes;
};

class CWaveOut {
    public:
        CWaveOut(LPCWAVEFORMATEX Format, int nBuffers, int BufferSize);
        ~CWaveOut();
        void Write(PBYTE Data, int nBytes);
        void Flush();
        void Wait();
        void Reset();
    private:
        const HANDLE   m_hSem;
        const int      m_nBuffers;
        int            m_CurrentBuffer;
        BOOL           m_NoBuffer;
        CWaveBuffer   *m_Hdrs;
        HWAVEOUT       m_hWave;
};

BOOL CWaveBuffer::Init(HWAVEOUT hWave, int Size)
{
    m_hWave  = hWave;
    m_nBytes = 0;

    /*  Allocate a buffer and initialize the header. */
    m_Hdr.lpData = (LPSTR)LocalAlloc(LMEM_FIXED, Size);
    if (m_Hdr.lpData == NULL)
    {
        return FALSE;
    }
    m_Hdr.dwBufferLength  = Size;
    m_Hdr.dwBytesRecorded = 0;
    m_Hdr.dwUser = 0;
    m_Hdr.dwFlags = 0;
    m_Hdr.dwLoops = 0;
    m_Hdr.lpNext = 0;
    m_Hdr.reserved = 0;

    /*  Prepare it. */
    waveOutPrepareHeader(hWave, &m_Hdr, sizeof(WAVEHDR));
    return TRUE;
}

CWaveBuffer::~CWaveBuffer()
{
    if (m_Hdr.lpData)
    {
        waveOutUnprepareHeader(m_hWave, &m_Hdr, sizeof(WAVEHDR));
        LocalFree(m_Hdr.lpData);
    }
}

void CWaveBuffer::Flush()
{
    // ASSERT(m_nBytes != 0);
    m_nBytes = 0;
    waveOutWrite(m_hWave, &m_Hdr, sizeof(WAVEHDR));
}

BOOL CWaveBuffer::Write(PBYTE pData, int nBytes, int& BytesWritten)
{
    // ASSERT((DWORD)m_nBytes != m_Hdr.dwBufferLength);
    BytesWritten = min((int)m_Hdr.dwBufferLength - m_nBytes, nBytes);
    CopyMemory((PVOID)(m_Hdr.lpData + m_nBytes), (PVOID)pData, BytesWritten);
    m_nBytes += BytesWritten;
    if (m_nBytes == (int)m_Hdr.dwBufferLength)
    {
        /*  Write it! */
        m_nBytes = 0;
        waveOutWrite(m_hWave, &m_Hdr, sizeof(WAVEHDR));
        return TRUE;
    }
    return FALSE;
}

void CALLBACK WaveCallback(HWAVEOUT hWave, UINT uMsg, DWORD dwUser,
                           DWORD dw1, DWORD dw2)
{
    if (uMsg == WOM_DONE)
    {
        ReleaseSemaphore((HANDLE)dwUser, 1, NULL);
    }
}

CWaveOut::CWaveOut(LPCWAVEFORMATEX Format, int nBuffers, int BufferSize) :
    m_nBuffers(nBuffers),
    m_CurrentBuffer(0),
    m_NoBuffer(TRUE),
    m_hSem(CreateSemaphore(NULL, nBuffers, nBuffers, NULL)),
    m_Hdrs(new CWaveBuffer[nBuffers]),
    m_hWave(NULL)
{
    /*  Create wave device. */
    waveOutOpen(&m_hWave,
                WAVE_MAPPER,
                Format,
                (DWORD)WaveCallback,
                (DWORD)m_hSem,
                CALLBACK_FUNCTION);

    /*  Initialize the wave buffers. */
    for (int i = 0; i < nBuffers; i++)
    {
        m_Hdrs[i].Init(m_hWave, BufferSize);
    }
}

CWaveOut::~CWaveOut()
{
    /*  First, get the buffers back. */
    waveOutReset(m_hWave);
    /*  Free the buffers. */
    delete [] m_Hdrs;
    /*  Close the wave device. */
    waveOutClose(m_hWave);
    /*  Free the semaphore. */
    CloseHandle(m_hSem);
}

void CWaveOut::Flush()
{
    if (!m_NoBuffer)
    {
        m_Hdrs[m_CurrentBuffer].Flush();
        m_NoBuffer = TRUE;
        m_CurrentBuffer = (m_CurrentBuffer + 1) % m_nBuffers;
    }
}

void CWaveOut::Reset()
{
    waveOutReset(m_hWave);
}

void CWaveOut::Write(PBYTE pData, int nBytes)
{
    while (nBytes != 0)
    {
        /*  Get a buffer if necessary. */
        if (m_NoBuffer)
        {
            WaitForSingleObject(m_hSem, INFINITE);
            m_NoBuffer = FALSE;
        }

        /*  Write into a buffer. */
        int nWritten;
        if (m_Hdrs[m_CurrentBuffer].Write(pData, nBytes, nWritten))
        {
            m_NoBuffer = TRUE;
            m_CurrentBuffer = (m_CurrentBuffer + 1) % m_nBuffers;
            nBytes -= nWritten;
            pData += nWritten;
        }
        else
        {
            // ASSERT(nWritten == nBytes);
            break;
        }
    }
}

void CWaveOut::Wait()
{
    /*  Send any remaining buffers. */
    Flush();
    /*  Wait for the buffers back. */
    for (int i = 0; i < m_nBuffers; i++)
    {
        WaitForSingleObject(m_hSem, INFINITE);
    }
    LONG lPrevCount;
    ReleaseSemaphore(m_hSem, m_nBuffers, &lPrevCount);
}

HRESULT RenderStreamToDevice(IMultiMediaStream *pMMStream)
{
    WAVEFORMATEX wfx;
    #define DATA_SIZE 5000

    IMediaStream        *pStream = NULL;
    IAudioStreamSample  *pSample = NULL;
    IAudioMediaStream   *pAudioStream = NULL;
    IAudioData          *pAudioData = NULL;

    HRESULT hr = pMMStream->GetMediaStream(MSPID_PrimaryAudio, &pStream);
    if (FAILED(hr))
    {
        return hr;
    }

    pStream->QueryInterface(IID_IAudioMediaStream, (void **)&pAudioStream);
    pStream->Release();

    hr = CoCreateInstance(CLSID_AMAudioData, NULL,
        CLSCTX_INPROC_SERVER, IID_IAudioData, (void **)&pAudioData);
    if (FAILED(hr))
    {
        pAudioStream->Release();
        return hr;
    }

    PBYTE pBuffer = (PBYTE)LocalAlloc(LMEM_FIXED, DATA_SIZE);
    if (pBuffer == NULL)
    {
        pAudioStream->Release();
        pAudioData->Release();
        return E_OUTOFMEMORY;
    }

    pAudioStream->GetFormat(&wfx);
    pAudioData->SetBuffer(DATA_SIZE, pBuffer, 0);
    pAudioData->SetFormat(&wfx);
    hr = pAudioStream->CreateSample(pAudioData, 0, &pSample);
    pAudioStream->Release();
    if (FAILED(hr))
    {
        LocalFree((HLOCAL)pBuffer);
        pAudioData->Release();
        pSample->Release();
        return hr;
    }

    CWaveOut WaveOut(&wfx, 4, 2048);
    HANDLE hEvent = CreateEvent(FALSE, NULL, NULL, FALSE);
    if (hEvent != 0)
    {
        int iTimes;
        for (iTimes = 0; iTimes < 3; iTimes++)
        {
            DWORD dwStart = timeGetTime();
            for (; ; )
            {
                hr = pSample->Update(0, hEvent, NULL, 0);
                if (FAILED(hr) || hr == MS_S_ENDOFSTREAM)
                {
                    break;
                }
                WaitForSingleObject(hEvent, INFINITE);
                DWORD dwTimeDiff = timeGetTime() - dwStart;
                // Limit to 10 seconds
                if (dwTimeDiff > 10000) {
                    break;
                }
                DWORD dwLength;
                pAudioData->GetInfo(NULL, NULL, &dwLength);
                WaveOut.Write(pBuffer, dwLength);
            }
            pMMStream->Seek(0);
        }
    }

    pAudioData->Release();
    pSample->Release();
    LocalFree((HLOCAL)pBuffer);
    return S_OK;
}

HRESULT RenderFileToMMStream(
    const char * szFileName,
    IMultiMediaStream **ppMMStream)
{
    if (strlen(szFileName) > MAX_PATH)
    {
        return E_INVALIDARG;
    }

    IAMMultiMediaStream *pAMStream;
    HRESULT hr = CoCreateInstance(CLSID_AMMultiMediaStream, NULL,
        CLSCTX_INPROC_SERVER, IID_IAMMultiMediaStream,
        (void **)&pAMStream);
    if (FAILED(hr))
    {
        return hr;
    }

    WCHAR wszName[MAX_PATH + 1];
    MultiByteToWideChar(CP_ACP, 0, szFileName, -1, wszName,
        MAX_PATH + 1);

    pAMStream->Initialize(STREAMTYPE_READ, AMMSF_NOGRAPHTHREAD, NULL);
    pAMStream->AddMediaStream(NULL, &MSPID_PrimaryAudio, 0, NULL);
    hr = pAMStream->OpenFile(wszName, AMMSF_RUN);
    {
        if (SUCCEEDED(hr))
        {
            hr = pAMStream->QueryInterface(IID_IMultiMediaStream,
                (void**)ppMMStream);
        }
    }
    pAMStream->Release();
    return hr;
}

int __cdecl main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Specify a file name.\n");
        exit(0);
    }

    IMultiMediaStream *pMMStream;
    CoInitialize(NULL);
    HRESULT hr = RenderFileToMMStream(argv[1], &pMMStream);
    if (SUCCEEDED(hr))
    {
        RenderStreamToDevice(pMMStream);
        pMMStream->Release();
    }

    CoUninitialize();
    return 0;
}


Using DirectShow with Visual Basic

This section describes how to write Microsoft® DirectShow® applications using Microsoft® Visual Basic®. It contains the following articles.

  • Constructing Filter Graphs Using Visual Basic
  • Controlling Filter Graphs Using Visual Basic
  • Visual Basic Objects


Constructing Filter Graphs Using Visual Basic

This article describes how to use Microsoft® Visual Basic® to manage the components of a filter graph.

This article is written for the Visual Basic developer who is already familiar with application programming in Microsoft® Windows®, Windows-based multimedia programming, and Automation features of the Visual Basic programming system.

Note: In DirectX 9, the DirectShow Visual Basic sample applications are located in [sdk root]\Extras\DirectShow\VB Samples. In DirectX 8.1, the samples are located in [sdk root]\Samples\Multimedia\VBSamples\DirectShow.

This article contains the following sections.

  • About the DirectShow Quartz.dll Objects
  • Creating a Filter Graph
  • Generating the Complete Filter Graph
  • Creating a New Filter Graph and Adding Filters
  • Connecting Filter Pins
  • Viewing Pin Connection Information
  • Summary


About the DirectShow Quartz.dll Objects

Quartz.dll provides objects that you can use in your Visual Basic-based applications to manage filters and pins. There is an implicit hierarchy among these objects; that is, you must often access the properties of one object to obtain another object. In the following example, an object that appears indented below another indicates that you obtain that lower-level object from a property or method of the higher-level object.

Filter graph object (FilgraphManager)
  Filter collection (RegFilterCollection, FilterCollection properties)
    Filter Info object (IFilterInfo or IRegFilterInfo in filter collection)
      Pin collection (Pins property)
        Pin Info object (IPinInfo item in pins collection)

The top-level object in the hierarchy is the filter graph object, or the FilgraphManager object, which represents the entire filter graph. You can access two properties of the FilGraphObject object to obtain collections of filter objects. The FilgraphManager.RegFilterCollection property represents the filters registered with the system. The FilgraphManager.FilterCollection property represents the filters that are part of the filter graph.

As with other collections accessible to Visual Basic, you can access individual items in the collections by using the Visual Basic for each...next statement. The number of items in the collection is indicated by the Count property of the collection.

The filter collection contains IFilterInfo objects. Each IFilterInfo object has a Pins property that represents a collection of pins defined for that filter.

The pins collection contains IPinInfo objects. Each IPinInfo object includes detailed information about that pin, including its media type and its connection to another pin.

To examine a specific pin on a filter in the filter graph, use the following procedure.

  1. Obtain the filter graph object.
  2. Use the FilgraphManager.FilterCollection property of the filter graph object to obtain the collection of filters present in the filter graph.
  3. Search through the filter collection for the specific filter.
  4. Use the IFilterInfo.Pins of the filter object to obtain the collection of pins defined for the filter.
  5. Search through the pins collection for the specific pin.
  6. Examine the properties of the pin object to find connection information and other information for the pin.


Creating a Filter Graph

There are three distinct ways to use Quartz.dll to create a filter graph; each way offers a different amount of control over the filter graph. These range from automatically generating the entire filter graph to specifying every filter and pin connection. The three approaches are as follows:

  • Automatic: Generate the complete filter graph from either a multimedia source or a stored filter graph file.
  • Semi-automatic: Create a new (empty) filter graph, add one or more filters, then automatically generate all filters and connections needed to render a specific pin.
  • Manual: Create a new (empty) filter graph, add individual filters to the graph, and explicitly add connections between pins.


Generating the Complete Filter Graph

The following code fragment demonstrates how to generate the complete filter graph based on the multimedia source or stored filter graph. After creating an FilgraphManager object that is initially "empty," the application calls the FilgraphManager.RenderFile method to build up the complete graph.

' Start by creating a new, empty filter graph.
Dim g_objMC as IMediaControl  ' from the General Declarations section ...
Set g_objMC = New FilgraphManager  ' create the new filter graph
' Use the common File Open dialog to let the user select the input file.
CommonDialog1.ShowOpen  ' user selects a source or filter graph
' call IMediaControl.RenderFile to add all filters and connect all pins.
g_objMC.RenderFile CommonDialog1.filename  ' Generates the complete graph.


Creating a New Filter Graph and Adding Filters

The following code fragment demonstrates how to create the new (empty) filter graph object.

    Dim g_objMC as FilgraphManager
    Set g_objMC = New FilgraphManager  ' create the new filter graph

When you choose to create an empty filter graph and add individual filters, you must know the filter type. In general, there are three categories of filters: source filters, transform filters, and renderer filters. The procedure for adding source filters uses a different method than the procedure for adding transform and renderer filters.

Add source filters to the filter graph by calling the FilgraphManager.AddSourceFilter method and supplying the name of a file of the specified source type or stored filter graph.

Dim objFilter As Object  ' temporary object for valid syntax; not used

    CommonDialog1.ShowOpen  ' get the name of the source or filter graph file
    g_objMC.AddSourceFilter CommonDialog1.filename, objFilter

Add transform and renderer filters to the filter graph by calling the IRegFilterInfo.Filter method. The IRegFilterInfo object can be obtained from the FilgraphManager.RegFilterCollection property, which represents the collection of filter objects registered with the system and available for use.

After creating the filter graph and obtaining the FilgraphManager object, use the following procedure to add filters.

  1. Obtain the list of registered filters by getting the FilgraphManager.RegFilterCollection property.
  2. Search through the collection for the desired filter. Each element in the collection is an IRegFilterInfo object.
  3. Add the filter to the filter graph by calling the IRegFilterInfo.Filter method.

The following code illustrates steps 1 and 2:

 ' code fragment that populates the registered filter list box
' global variable g_objRegFilters is set to FilgraphManager.RegFilterCollection
' Set g_objRegFilters = g_objMC.RegFilterCollection
Dim filter As IRegFilterInfo
    listRegFilters.Clear
    If Not g_objRegFilters Is Nothing Then
        For Each filter In g_objRegFilters  ' for each filter in collection
            listRegFilters.AddItem filter.Name ' add name to the list box
        Next filter
    End If

The following code illustrates step 3:

Dim filter As IRegFilterInfo
' find the selected filter and add it to the graph
' g_objRegFilters is the FilgraphManager object's RegFilterCollection property
For Each filter In g_objRegFilters
    If filter.Name = listRegFilters.Text Then  ' the selected filter?
        Dim f As IFilterInfo  ' yes
        filter.filter f  ' add to the filter graph, return IFilterInfo f
        If f.IsFileSource Then
            CommonDialog1.ShowOpen
            f.filename = CommonDialog1.filename
        End If
        Exit For
    End If
Next filter


Connecting Filter Pins

After adding individual filters to the filter graph, you can establish connections between the filters by explicitly connecting each pin, or by automatically generating all connections that are needed downstream from a specific pin.

In both cases, you must traverse the hierarchy of Microsoft® DirectShow® objects to obtain the IPinInfo object that represents a pin of the filter object. This involves finding the desired filter in the filter collection of the filter graph object, then finding the desired pin in the pin collection of the filter object.

This section contains the following topics.

  • Listing Filters in the Filter Graph
  • Listing Pins Defined for a Filter
  • Explicitly Connecting Two Pins
  • Automatically Connecting Pins

Listing Filters in the Filter Graph

All filters in the filter graph are available in a collection that you can access using the FilgraphManager.FilterCollection property.

' refresh a list box that contains the current filters in the graph
    listFilters.Clear
    For Each objFI In g_objMC.FilterCollection
        listFilters.AddItem objFI.Name ' add to list box
    Next objFI

Listing Pins Defined for a Filter

You can access the pins defined for a filter object through the IFilterInfo.Pins property. The Pins property is a collection of individual IPinInfo objects.

After you obtain an individual IPinInfo object from the collection, you can access its properties and call its methods, as shown in the following code fragment.

For Each objPin In g_objSelFilter.Pins
    If objPin.Name = listPins.Text Then  ' selected pin?
        Set g_objSelPin = objPin ' yes, update information
        ' ... perform operations using that pin
    End If
Next objPin

After you have obtained the pin object, you can explicitly connect to one other pin or automatically generate all subsequent pin connections needed to render the pin.

Explicitly Connecting Two Pins

The IPinInfo object provides three methods to connect pins: Connect, ConnectDirect, and ConnectWithType. Connect adds other transform filters as needed, ConnectDirect does not add transform filters, and ConnectWithType performs the connection only if the specified pin matches the specified media type.

    frmSelectPin.OtherDir = g_objSelPin.Direction
    Set frmSelectPin.Graph = g_objMC  ' give that form a copy of the graph
    Set frmSelectPin.SelFilter = g_objSelFilter  ' and the current filter
    frmSelectPin.RefreshFilters  ' display available filters to connect
    frmSelectPin.Show 1  ' display the form
    If frmSelectPin.bOK Then ' user has selected one--used OK button
        Dim objPI As IPinInfo
        Set objPI = frmSelectPin.SelPin ' get the new pin from the form
        g_objSelPin.Connect objPI  ' connect the two pins
        RefreshFilters  ' display the latest pin information
    End If

Automatically Connecting Pins

Call the IPinInfo.Render method to automatically generate all portions of the filter graph that are needed downstream from that pin.

The term downstream refers to all connections needed to construct a complete path from that pin to a renderer filter. For example, consider the representation of the filter graph by the GraphEdit utility, which shows connections as moving from the source filter at the left to the renderer filter at the right. The Render method adds all required filters and connections to the right of the specified pin.

' call IPinInfo.Render
' complete the graph downstream from this pin
' g_objSelPin refers to the pin selected in the list box labeled 'Pins'
    g_objSelPin.Render


Viewing Pin Connection Information

When you have obtained a pin object from the collection available from the IFilterInfo.Pins property of the filter object, you can list its connection and other information.

  Dim strTemp As String
  On Error Resume Next
  Dim objPin As IPinInfo
  For Each objPin In g_objSelFilter.Pins
    If objPin.Name = listPins.Text Then ' selected in list box?
      Set g_objSelPin = objPin  'yes, get all information
      strTemp = ""  ' clear existing displayed pin information
      Dim objPinOther As IPinInfo
      Set objPinOther = objPin.ConnectedTo
      If Err.Number = 0 Then  ' yes, there is a connection
        strTemp = "Connected to pin: " + objPinOther.Name + " "
        Dim objPeer As IFilterInfo
        Set objPeer = objPinOther.FilterInfo
        strTemp = strTemp + " on filter: " + objPeer.Name + " "
        Dim objMTI As IMediaTypeInfo
        Set objMTI = objPin.ConnectionMediaType
        strTemp = strTemp + vbCrLf + "Media Type: " + objMTI.Type
      End If
      If objPin.Direction = 0 Then
        strTemp = strTemp + " " + vbCrLf + "Direction: Input"
      Else
        strTemp = strTemp + " " + vbCrLf + "Direction: Output"
      End If
    txtPinInfo.Text = strTemp
    End If
  Next objPin


Summary

In summary, this article discussed the use of the following DirectShow objects, properties, and methods.

Task | DirectShow Properties or Methods
Create a new, empty filter graph. | Set objMediaControl = New FilgraphManager.
Generate the complete filter graph for a specific file. | Call the FilgraphManager.RenderFile method.
Add a source filter. | Call the FilgraphManager.AddSourceFilter method.
Add a renderer or transform filter. | Get the IRegFilterInfo objects using the FilgraphManager.RegFilterCollection property; call the IRegFilterInfo.Filter method.
List the pins of a filter object. | Get the IPinInfo objects using the IFilterInfo.Pins property.
Explicitly connect two pins. | Call the IPinInfo.Connect method.
Create all connections from the pin to the renderer filter. | Call the IPinInfo.Render method.


Controlling Filter Graphs Using Visual Basic

This article describes how to use the methods, events, and properties exposed by the Microsoft® DirectShow® dynamic-link library, Quartz.dll, to render a stream of time-stamped video data in applications based in Microsoft® Visual Basic®. This article is written for the Visual Basic developer who is already familiar with Microsoft® Windows®-based application programming, Windows-based multimedia programming, and Automation features of the Visual Basic programming system version 6.x.

This article contains the following sections.

  • DirectShow Filters and Filter Graphs
  • How to Register Quartz.dll to Access DirectShow Interfaces
  • Controlling the Filter Graph in Visual Basic


DirectShow Filters and Filter Graphs

When multimedia is displayed in an application by using Quartz.dll, the application is using a collection of objects called filters; this collection is sometimes called a filter graph. The following diagram depicts a filter graph that can render an Audio-Video Interleaved (AVI) file.

In this diagram, the AVI source filter reads the file from disk. The AVI decompressor filter (codec) decompresses the video data as it is passed from the source filter. The codec filter then passes this data to the video renderer. The video renderer, in turn, passes the data to the device in a format that the device understands. The AVI source filter passes the audio data directly to the audio renderer, which, in turn, passes the data to the audio device.

In addition to filters, DirectShow supports an Automation object called the filter graph manager. This object knows about the available filters and understands which filter types are required to render which file formats. The filter graph manager exposes the methods, events, and properties supported by the filters in a given graph. The filter graph manager also exposes its own set of methods, events, and properties. These are exposed by using interfaces, which are simply collections of related methods, events, and properties.

The following table identifies the DirectShow interfaces available in Quartz.dll for use with Visual Basic-based applications, and describes the purpose of each interface.

Interface | Description
IAMCollection | Accesses pin and filter collections.
IBasicAudio | Controls and retrieves current volume setting.
IBasicVideo2 | Controls a generic video renderer.
IFilterInfo | Retrieves information about a filter and about pin objects in the filter.
FilgraphManager | Instantiates the filter graph and controls media flow (running, paused, stopped).
IMediaEvent | Allows customized event handling for events such as repainting, user termination, completion, and so on.
IMediaPosition | Controls and retrieves start time, stop time, rate, and current position.
IMediaTypeInfo | Retrieves the media type and subtype.
IPinInfo | Accesses pin information, such as pin direction and media type, and controls pin connection, disconnection, and rendering.
IRegFilterInfo | Contains information about registered (transform and render) filters.
IVideoWindow | Controls window aspects of a video renderer.


How to Register Quartz.dll to Access DirectShow Interfaces

To use the DirectShow interfaces in your Microsoft Visual Basic-based application, you must register the Microsoft® ActiveMovie® control type library in your Visual Basic project. You can do this by choosing References from the Project menu, and then selecting the check box next to ActiveMovie control type library.

When you register the ActiveMovie control type library by using the Visual Basic References dialog box, you are identifying the type library that contains the Automation information that Visual Basic requires. The following illustration shows the References dialog box.

Visual Basic references dialog box

After the type library is registered, you can use the Object Browser dialog box to view the list of methods, events, and properties associated with a given interface. Choose Object Browser from the View menu, and then choose QuartzTypeLib from the drop-down list of libraries at the top left of the Object Browser dialog box.

Note The type information in the QuartzTypeLib is organized by interface, rather than object.


Controlling the Filter Graph in Visual Basic

This section contains the following topics.

  • Installing the Files
  • Registering Quartz.dll with Visual Basic
  • Preparing to Use the DirectShow Objects
  • Instantiating the Filter Graph
  • Rendering Video
  • Controlling Audio
  • Scaling and Translating the Video Output
  • Tracking Status
  • Getting and Setting the Start Position
  • Getting and Setting the Rate
  • Cleaning Up

Installing the Files

Before using the DirectShow objects in your Visual Basic-based application, you must install Quartz.dll in the Windows\System directory and ensure that the appropriate entries are made in your system's registry database. Currently, the Microsoft® DirectX® Software Development Kit (SDK) Setup program automates this process. To install, start Setup.exe and choose the Runtime option. The dynamic-link library (DLL) will be copied to the correct location, and the registry will be automatically updated.

Registering Quartz.dll with Visual Basic

To verify that the files were installed successfully, open the Visual Basic application and choose the References command from the View menu. (At startup, Visual Basic examines the registry database for registered automation controls and adds their names to the list that appears in this dialog box.) To use the filter graph manager, select the ActiveMovie control type library box.

After Visual Basic registers the type information, you can use the filter graph manager and its associated interfaces in your application.

Preparing to Use the DirectShow Objects

Visual Basic initializes all objects using the FilgraphManager object, which implements the following interfaces.

  • IBasicAudio
  • IBasicVideo2
  • FilgraphManager
  • IMediaEvent
  • IMediaPosition
  • IVideoWindow

Each of the interfaces is accessed by a Visual Basic programmable object defined to be of that interface type. You can define the objects as global variables in the general declarations section, as shown in the following example.

Dim g_objVideoWindow As IVideoWindow
Dim g_objMediaControl As FilgraphManager
Dim g_objMediaPosition As IMediaPosition
Dim g_objBasicAudio  As IBasicAudio
Dim g_objBasicVideo As IBasicVideo2

Initialize all the programmable objects using FilgraphManager, as shown in the following example.

    Set g_objMediaControl = New FilgraphManager
    g_objMediaControl.RenderFile (g_strFileName)    ' name of input file
    ...
    Set g_objBasicAudio = g_objMediaControl
    Set g_objVideoWindow = g_objMediaControl
    Set g_objMediaEvent = g_objMediaControl
    Set g_objMediaPosition = g_objMediaControl

Obtain the other interfaces by calling methods that explicitly return the desired interface. The following table summarizes how to obtain these interfaces.

Interface | Methods that return the interface pointer
IAMCollection | IPinInfo.MediaTypes, IFilterInfo.Pins, FilgraphManager.FilterCollection, FilgraphManager.RegFilterCollection
IFilterInfo | First FilgraphManager.FilterCollection, then IAMCollection.Item or IPinInfo.FilterInfo
IMediaTypeInfo | IPinInfo.ConnectionMediaType
IPinInfo | IFilterInfo.FindPin, IAMCollection.Item
IRegFilterInfo | First FilgraphManager.RegFilterCollection, then IAMCollection.Item

For a sample that shows how to manipulate these filter and pin interfaces, see Constructing Filter Graphs Using Visual Basic.

Instantiating the Filter Graph

You can use the filter graph manager to render existing files of the following types.

  • .avi (Audio-Video Interleaved)
  • .mov (Apple® QuickTime®)
  • .mpg (Motion Picture Experts Group)

In addition, you can use the filter graph manager to render an existing filter graph by specifying the file that contains that graph as a parameter to the FilgraphManager.RenderFile method.

Because the filters in a filter graph are dependent on the type of file being rendered, do not instantiate a filter graph until the user selects a file. The filter graph manager is instantiated when the Visual Basic keyword New is used to create the AUTOMATION object. The filter graph object is created when the RenderFile method is called, as shown in the following example.

'Instantiate a filter graph for the requested
'file format.

Set g_objMediaControl = New FileGraphManager
g_objMediaControl.RenderFile (g_strFileName)

Rendering Video

The FilgraphManager object supports three methods that an application can call to control the video stream: Run, Pause, and Stop. After the filter graph object is instantiated, your application can call these methods.

The following code example calls these methods in response to the user clicking a button.

Private Sub Toolbar1_ButtonClick(ByVal Button As Button)
' handle buttons on the toolbar

    ' if the objects aren't defined, avoid errors
    If g_objMediaControl Is Nothing Then
        Exit Sub
    End If

    If Button.Index = 1 Then 'PLAY
        'Invoke the MediaControl Run() method
        'and play the video through the predefined
        'filter graph.

        g_objMediaControl.Run
        g_fVideoRun = True

    ElseIf Button.Index = 2 Then  'PAUSE
        'Invoke the MediaControl Pause() method
        'and pause the video that is being
        'displayed through the predefined
        'filter graph.

        g_objMediaControl.Pause
        g_fVideoRun = False

    ElseIf Button.Index = 3 Then  'STOP

        'Invoke the MediaControl Stop() method
        'and stop the video that is being
        'displayed through the predefined
        'filter graph.

        g_objMediaControl.Stop
        g_fVideoRun = False
        ' reset to the beginning of the video
        g_objMediaPosition.CurrentPosition = 0
        txtElapsed.Text = "0.0"

Controlling Audio

The IBasicAudio interface supports two properties: the Volume property and the Balance property. The Volume property retrieves or sets the volume. In the sample application, this property is bound to the slider control slVolume. The Balance property retrieves or sets the stereo balance. In the sample application, this property is bound to the slider control slBalance.

Note The volume is a linear volume scale, so only the far right side of the slider is useful.

The following example adjusts the volume by setting the Volume property.

Private Sub slVolume_Change()

    'Set the volume on the slider

    If Not g_objMediaControl Is Nothing Then
    'if g_objMediaControl has been assigned

       g_objBasicAudio.Volume = slVolume.Value

    End If

End Sub

Scaling and Translating the Video Output

The IVideoWindow interface supports the methods and properties you can use to alter the size, state, owner, palette, visibility, and so on, for the destination window. If you are not concerned with the location or appearance of the destination window, you can render output in the default window (which appears in the upper-left corner of the desktop) without calling any of these methods or properties.

You can also change the window style by removing the caption, border, and dialog box frame. To do this, set the IVideoWindow.WindowStyle property to 0x06000000. This corresponds to the logical OR operation of the values WS_DLGFRAME (0x04000000) and WS_VSCROLL (0x02000000). For a complete list of window styles and corresponding values, see the Winuser.h file in the Microsoft® Platform SDK.

To move the destination window onto the form, specify a new position by setting the IVideoWindow.Top and IVideoWindow.Left properties of g_objVideoWindow. The Top and Left properties are set to correspond to the upper-left corner of a blank control with a rectangular shape, a placeholder of sorts, that appears on the form. The ScaleMode property for the form was set to 3, which specifies units of pixels. This allows the form properties and DirectShow object properties to be used without conversion. The DirectShow object properties are also expressed in pixels. The default units for a Visual Basic form are twips.

Determine the required size of the rectangle by retrieving the source video width and height. These values correspond to the IBasicVideo2.VideoWidth and IBasicVideo2.VideoHeight properties.

In addition to setting the Top and Left properties, it is necessary to identify the form of the application as the new parent window by passing the window handle of the form, hWnd, to the object's IVideoWindow.Owner property. If the handle is not passed, the destination window will appear relative to the desktop and not the form.

The following example shows these tasks.

    Set g_objVideoWindow = g_objMediaControl
    g_objVideoWindow.WindowStyle = CLng(&H6000000)   ' WS_DLGFRAME | WS_VSCROLL
    g_objVideoWindow.Left = CLng(Shape1.Left)   ' shape is a placeholder on the form
    g_objVideoWindow.Top = CLng(Shape1.Top)
    Shape1.Width = g_objVideoWindow.Width    ' resize the shape given the input video
    Shape1.Height = g_objVideoWindow.Height
    g_objVideoWindow.Owner = frmMain.hWnd    ' set the form as the parent

The following example shows how to initialize the ScaleMode property.

' ...
    frmMain.ScaleMode = 3    ' pixels
' ...

Avoid attempting to scale the destination window by setting the IVideoWindow.Width and IVideoWindow.Height properties for the IVideoWindow object, because performance suffers considerably.

Tracking Status

The IMediaPosition object exposes a number of properties that you can use to retrieve or set the current position, stop point, duration, and rate. The following code examples shows how to do this.

Set g_objMediaPosition = g_objMediaControl
g_dblRunLength = g_objMediaPosition.Duration
txtDuration.Text = CStr(g_dblRunLength)   ' display the duration
g_dblStartPosition = 0.0
txtStart.Text = CDbl(g_dblStartPosition)   ' display the start time
g_dblRate = g_objMediaPosition.Rate
txtRate.Text = CStr(g_dblRate)

Getting and Setting the Start Position

Use the IMediaPosition.CurrentPosition property to let the user adjust the point at which the video begins rendering. The following code example changes the current position in response to the user pressing a key.

 Private Sub txtStart_KeyDown(KeyCode As Integer, Shift As Integer)
' handle user input to change the start position
If KeyCode = vbKeyReturn Then
    If g_objMediaPosition Is Nothing Then
        Exit Sub
    ElseIf CDbl(txtStart.Text) > g_dblRunLength Then
        MsgBox "Specified position invalid: re-enter new position."
    ElseIf CDbl(txtStart.Text) < 0 Then
        MsgBox "Specified position invalid: re-enter new position."
    ElseIf CDbl(txtStart.Text) <> "" Then
        g_dblStartPosition = CDbl(txtStart.Text)
        g_objMediaPosition.CurrentPosition = g_dblStartPosition
    End If
End If
End Sub

Getting and Setting the Rate

Use the IMediaPosition.Rate property to let the user adjust the rate at which the video is rendered. This rate is a ratio with respect to typical playback speed. For example, a rate of 0.5 causes the video to be rendered at one-half its typical speed, and a rate of 2.0 causes the video to be rendered at twice its typical speed.

Unlike the CurrentPosition property, which can be set while the video is being rendered, the Rate property must be set prior to rendering.

Note The sound track can be disabled for some videos when the rate is less than 1.0.

The following code example changes the rate in response to the user pressing a key.

Private Sub txtRate_KeyDown(KeyCode As Integer, Shift As Integer)
' DirectShow VB sample
' handle user updates to the Rate value
If KeyCode = vbKeyReturn Then
    If g_objMediaPosition Is Nothing Then
        Exit Sub
    ElseIf CDbl(txtRate.Text) < 0# Then
        MsgBox "Negative values invalid: re-enter value between 0 and 2.0"
    ElseIf CStr(txtRate.Text) <> "" Then
        g_dblRate = CDbl(txtRate.Text)
        g_objMediaPosition.Rate = g_dblRate
    End If
End If
End Sub

Cleaning Up

Each time your application uses the Visual Basic Set statement to create an instance of a new DirectShow object, it must include a corresponding Set statement to remove that object (and its corresponding resources) from memory prior to shutdown, as shown in the following code.

Set g_objBasicAudio = Nothing


Visual Basic Objects

Microsoft® DirectShow® exposes a subset of its functionality to Microsoft® Visual Basic® applications.

Use the following objects to build and control filter graphs.

Object | Description
FilgraphManager | Builds and controls the filter graph.
IAMCollection | Represents a collection of pins, filters, or media types.
IBasicAudio | Supports the audio component of the filter graph.
IBasicVideo2 | Supports the video component of the filter graph.
IFilterInfo | Manages information about a filter.
IMediaEvent | Contains methods for retrieving event notifications.
IMediaPosition | Contains methods for seeking the filter graph and setting the playback rate.
IMediaTypeInfo | Manages information about a media type.
IPinInfo | Manages information about a pin on a filter.
IRegFilterInfo | Represents filter information from the registry.
IVideoWindow | Manages the window of a video renderer.


FilgraphManager Object

The FilgraphManager object (Filter Graph Manager) builds and controls the filter graph. Applications can use it to build file-playback graphs; run, pause, or stop the graph; or find filters in the registry.

To create this object, use the New keyword:

Dim mGraph As New FilgraphManager

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The FilgraphManager object exposes the following properties and methods.

Property | Description
FilterCollection | Retrieves a collection of the filters in the filter graph.
RegFilterCollection | Retrieves a collection of all the filters listed in the registry.

Method | Description
AddSourceFilter | Adds a source filter to the filter graph, for a specified file.
GetState | Retrieves the current state of the filter graph.
Pause | Pauses all the filters in the filter graph.
RenderFile | Builds a filter graph that renders the specified file.
Run | Runs all the filters in the filter graph.
Stop | Stops all the filters in the filter graph.
StopWhenReady | Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.


FilgraphManager.AddSourceFilter

The AddSourceFilter method adds a source filter to the filter graph, for a specified file.

Syntax

objGraph.AddSourceFilter(
    strFileName As String,
    ByRef objFilterInfo As IFilterInfo)

Parameters

strFileName

Specifies the name of the file to load.

objFilterInfo

Variable that receives an IFilterInfo object representing the source filter.

Return Values

This method does not return a value.

Example Code

Dim objFilter As IFilterInfo
mGraph.AddSourceFilter "C:\MyVideo.avi", objFilter

See Also

  • FilgraphManager Object


FilgraphManager.FilterCollection

The FilterCollection property retrieves a collection of the filters in the filter graph.

Syntax

objGraph.FilterCollection As IAMCollection

Parameters

The property takes no parameters.

Return Values

Returns an IAMCollection object that contains zero or more IFilterInfo objects. Each IFilterInfo object represents one filter in the graph.

Remarks

This property is read-only.

Example Code

The following example displays the names of the filters in the filter graph:

Dim objFilter As Object
For i = 1 To mGraph.FilterCollection.Count - 1
    ' Returns the i'th item, and puts it in objFilter
    mGraph.FilterCollection.Item i, objFilter
    List1.AddItem objFilter.Name
Next

You can also use a For ... Each loop to enumerate each filter, as follows:

For Each objFilter In mGraph.FilterCollection
    List1.AddItem objFilter.Name
Next

See Also

  • FilgraphManager Object


FilgraphManager.GetState

The GetState method retrieves the current state of the filter graph.

Syntax

objGraph.GetState(
    msTimeout As Long,
    ByRef State As Long)

Parameters

msTimeout

Specifies the duration to wait for the graph to complete a state transition, in milliseconds.

State

Variable that receives the current state. When the method returns, this variable will have one of the following values.

Value | Description
0 | Stopped
1 | Paused
2 | Running

Return Values

This method does not return a value.

Remarks

If the filter graph is transitioning to a new state, the method waits for the transition to complete, up to the duration specified by the msTimeout method. If this duration expires before the transition is complete, the method returns the new state and sets Err.Number to 567 (VFW_S_STATE_INTERMEDIATE).

Example Code

The following example checks whether the filter graph is stopped:

Dim state As Long
mGraph.GetState 100, state
If state = 0 Then
    ' Filter graph is stopped.
End If

See Also

  • FilgraphManager Object


FilgraphManager.Pause

The Pause method pauses all the filters in the filter graph.

Syntax

objGraph.Pause()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

Pausing the filter graph cues the graph for immediate rendering when the graph is next run. While the graph is paused, filters process data but do not render it. Data is pushed through the graph and processed by transform filters as far as buffering permits, but renderer filters do not render the data. However, video renderers display a static poster frame of the first sample.

See Also

  • FilgraphManager Object


FilgraphManager.RegFilterCollection

The RegFilterCollection property retrieves a collection of all the filters listed in the registry.

Syntax

objGraph.RegFilterCollection

Parameters

This property takes no parameters.

Return Values

Returns an IAMCollection object that contains IRegFilterInfo objects.

Remarks

Retrieving this property is equivalent to calling the C++ IFilterMapper2::EnumMatchingFilters method with the value zero for every parameter.

This property is read-only.

Example Code

Dim objRegFilter As IRegFilterInfo
Dim objFilter As IFilterInfo
For Each objRegFilter In mGraph.RegFilterCollection
    If objRegFilter.Name = "My Filter" Then
        ' Create the filter.
        objRegFilter.Filter objFilter
        Exit For
    End If
Next

See Also

  • FilgraphManager Object


FilgraphManager.RenderFile

The RenderFile method builds a filter graph that renders the specified file.

Syntax

objGraph.RenderFile(
    strFileName As String)

Parameters

strFileName

Name of the file to render.

Return Values

This method does not return a value.

Remarks

The Filter Graph Manager builds a filter graph for default playback, based on the file type.

See Also

  • FilgraphManager Object


FilgraphManager.Run

The Run method runs all the filters in the filter graph.

Syntax

objGrah.Run()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

If the filter graph is stopped, this method pauses the graph before running. If the graph is already running, the method has no effect.

The graph runs until the application calls the FilgraphManager.Pause, FilgraphManager.Stop, or FilgraphManager.StopWhenReady method. When playback reaches the end of the stream, the graph continues to run, although the filters do not stream any more data. At that point, the application can pause or stop the graph.

This method does not seek to the beginning of the stream. Therefore, if you run the graph, pause it, and then run it again, playback resumes from the paused position. If you run the graph after it has reached the end of the stream, nothing is rendered. To seek the graph, use the IMediaPosition object.

See Also

  • FilgraphManager Object


FilgraphManager.Stop

The Stop method stops all the filters in the filter graph.

Syntax

objGraph.Stop()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

If the graph is running, this method pauses the graph before stopping it. While paused, video renderers can copy the current frame to display as a poster frame.

This method does not seek to the beginning of the stream. Therefore, if you call this method and then call the FilgraphManager.Run method, playback resumes from the stopped position. To seek, use the IMediaPosition object.

See Also

  • FilgraphManager Object


FilgraphManager.StopWhenReady

The StopWhenReady method pauses the filter graph, allowing filters to queue data, and then stops the filter graph.

Syntax

objGraph.StopWhenReady()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

This method is useful if you want to seek the filter graph while the graph is stopped. As long as the filter graph is stopped, changes in the current position do not repaint the video window with a new frame. Therefore, seeking the graph does not update the video window. To update the window after the seek operation, call StopWhenReady. This method transitions the graph to a paused state, waits for the pause operation to complete, and then transitions the graph back to stopped. The pause operation queues data in the graph, so that the video renderer receives and displays the new frame.

See Also

  • FilgraphManager Object


IAMCollection Object

The IAMCollection object represents a collection of pins, filters, or media types.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IAMCollection object exposes the following properties and methods.

Property | Description
Count | Retrieves the number of items in the collection.

Method | Description
Item | Retrieves an item from the collection.

Remarks

This object is not thread safe, because it is intended only for use from within Microsoft® Visual Basic®. Clients should not call methods on this object from more than one thread.


IAMCollection.Count

The Count property returns the number of items in the collection.

Syntax

objCollection.Count As Long

Parameters

This property takes no parameters.

Return Values

Returns the number of objects in the collection, as a Long value.

Remarks

This property is read-only.

See Also

  • IAMCollection Object


IAMCollection.Item

The Item method retrieves an item from the collection.

Syntax

objCollection.Item(
    index As Long,
    ByRef objItem As Object)

Parameters

index

Index of the item to retrieve. The value can range from 0 to IAMCollection.Count – 1.

objItem

Variable that receives the item from the collection.

Return Values

This method does not return a value.

Remarks

The item is returned in the objItem parameter; it is an object of type IFilterInfo, IPinInfo, or IMediaTypeInfo, depending on the collection.

See Also

  • FilgraphManager.FilterCollection
  • FilgraphManager.RegFilterCollection
  • IAMCollection Object
  • IFilterInfo.Pins
  • IPinInfo.MediaTypes


IBasicAudio Object

The IBasicAudio object supports the audio component of the filter graph. It allows access to volume and balance functionality. To use this object, declare a variable of type IBasicAudio and set it equal to the FilgraphManager object:

Dim mGraph As New FilgraphManager
Dim iAudio As IBasicAudio
Set iAudio = mGraph

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IBasicAudio object exposes the following properties.

Property | Description
Balance | Sets or retrieves the audio balance.
Volume | Sets or retrieves the audio volume.


IBasicAudio.Balance

The Balance property sets or retrieves the audio balance.

Syntax

objAudio.Balance As Long

Parameters

This property takes no parameters.

Return Values

Returns a value from –10,000 to 10,000. Intermediate values are also valid.

Value | Description
–10,000 | Only the left speaker is receiving an audio signal.
0 | Both speakers are receiving equivalent audio signals.
10,000 | Only the right speaker is receiving an audio signal.

Remarks

This property is read/write.

If you set this property to values outside the specified range, the IBasicAudio object raises run-time error 5. If the filter graph does not contain an audio stream, the object raises run-time error 445.

See Also

  • IBasicAudio Object


IBasicAudio.Volume

The Volume property sets or retrieves the audio volume.

Syntax

objAudio.Volume As Long

Parameters

This property takes no parameters.

Return Values

Returns a value from –10,000 (silence) to 0 (full volume). Each unit corresponds to .01 decibels. Not all devices support 10,000 distinct volume levels.

Remarks

This property is read/write.

If you set this property to values outside the specified range, the object raises run-time error 5.

See Also

  • IBasicAudio Object


IBasicVideo2 Object

The IBasicVideo2 object supports the video component of the filter graph. To use this object, declare a variable of type IBasicVideo2 and set it equal to the FilgraphManager object:

Dim mGraph As New FilgraphManager
Dim iVideo As IBasicVideo2
Set iVideo = mGraph

If the graph does not have a connected video renderer, all IBasicVideo2 properties and methods return run-time error 521. Properties set on a video renderer generally persist between successive connections and disconnections.

The IBasicVideo2 object manipulates the following rectangles associated with the video image:

  • The source rectangle is the portion of the original image that gets displayed.
  • The destination rectangle is the portion of the video window the receives the source rectangle.
  • The video rectangle is the original video image.

In other words, the video renderer crops the image to the source rectangle, and then stretches or shrinks the cropped image to the destination rectangle.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IBasicVideo object exposes the following properties and methods.

Property | Description
AvgTimePerFrame | Retrieves the average time between successive frames.
BitErrorRate | Retrieves the approximate bit error rate of the video stream.
BitRate | Retrieves the approximate bit rate of the video stream.
DestinationHeight | Sets or retrieves the height of the destination rectangle.
DestinationLeft | Sets or retrieves the x-coordinate of the destination rectangle.
DestinationTop | Sets or retrieves the y-coordinate of the destination rectangle.
DestinationWidth | Sets or retrieves the width of the destination rectangle.
SourceHeight | Sets or retrieves the height of the source rectangle.
SourceLeft | Sets or retrieves the x-coordinate of the source rectangle.
SourceTop | Sets or retrieves the y-coordinate of the source rectangle.
SourceWidth | Sets or retrieves the width of the source rectangle.
VideoHeight | Retrieves the video height.
VideoWidth | Retrieves the video width.

Method | Description
GetCurrentImage | Not supported.
GetDestinationPosition | Retrieves the destination rectangle.
GetPreferredAspectRatio | Retrieves the preferred aspect ratio.
GetSourcePosition | Retrieves the source rectangle.
GetVideoPaletteEntries | Retrieves the color palette entries required by the video.
GetVideoSize | Retrieves the native video dimensions.
IsUsingDefaultDestination | Not supported.
IsUsingDefaultSource | Not supported.
SetDefaultDestinationPosition | Reverts to the default destination rectangle.
SetDefaultSourcePosition | Reverts to the default source rectangle.
SetDestinationPosition | Sets the destination rectangle.
SetSourcePosition | Sets the source rectangle.


IBasicVideo2.AvgTimePerFrame

The AvgTimePerFrame property retrieves the average time between successive frames.

Syntax

objVideo.AvgTimePerFrame As Double

Parameters

This property takes no parameters.

Return Values

Returns the time between frames, in seconds.

Remarks

This property is read-only.

See Also

  • IBasicVideo2 Object


IBasicVideo2.BitErrorRate

The BitErrorRate property retrieves the approximate bit error rate of the video stream.

Syntax

objVideo.BitErrorRate As Long

Parameters

This property takes no parameters.

Return Values

Returns the approximate number of bits per error.

Remarks

This property is read-only.

See Also

  • IBasicVideo2 Object


IBasicVideo2.BitRate

The BitRate property retrieves the approximate bit rate of the video stream.

Syntax

objVideo.BitRate As Long

Parameters

This property takes no parameters.

Return Values

Returns the bit rate, in bits per second.

Remarks

This property is read-only.

See Also

  • IBasicVideo2 Object


IBasicVideo2.DestinationHeight

The DestinationHeight property sets or retrieves the height of the destination rectangle.

Syntax

objVideo.DestinationHeight As Long

Parameters

This property takes no parameters.

Return Values

Returns the height, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetDestinationPosition
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.DestinationLeft

The DestinationLeft property sets or retrieves the x-coordinate of the destination rectangle.

Syntax

objVideo.DestinationLeft As Long

Parameters

This property takes no parameters.

Return Values

Returns the x-coordinate, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetDestinationPosition
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.DestinationTop

The DestinationTop property sets or retrieves the y-coordinate of the destination rectangle.

Syntax

objVideo.DestinationTop As Long

Parameters

This property takes no parameters.

Return Values

Returns the y-coordinate, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetDestinationPosition
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.DestinationWidth

The DestinationWidth property sets or retrieves the width of the destination rectangle.

Syntax

objVideo.DestinationWidth As Long

Parameters

This property takes no parameters.

Return Values

Returns the width, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetDestinationPosition
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.GetCurrentImage

Not supported.

Syntax

objVideo.GetCurrentImage(
    BufferSize As Long,
    DIBImage As Long)

See Also

  • IBasicVideo2 Object


IBasicVideo2.GetDestinationPosition

The GetDestinationPosition method retrieves the destination rectangle.

Syntax

objVideo.GetDestinationPosition(
    ByRef Left As Long,
    ByRef Top As Long,
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Left

Variable that receives the destination rectangle's x-coordinate, in pixels.

Top

Variable that receives the destination rectangle's y-coordinate, in pixels.

Width

Variable that receives the width of the destination rectangle, in pixels.

Height

Variable that receives the height of the destination rectangle, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as individually retrieving the IBasicVideo2.DestinationLeft, IBasicVideo2.DestinationTop, IBasicVideo2.DestinationWidth, and IBasicVideo2.DestinationHeight properties.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.GetPreferredAspectRatio

The GetPreferredAspectRatio method retrieves the preferred aspect ratio of the video source, if any.

Syntax

objVideo.GetSourcePosition(
    ByRef AspectX As Long,
    ByRef AspectY As Long)

Parameters

AspectX

Variable that receives the X component of the aspect ratio.

AspectY

Variable that receives the Y component of the aspect ratio.

Return Values

This method does not return a value.

Remarks

This method retrieves a pair of dimensionless numbers whose ratio is equal to the aspect ratio. Depending on the video source, however, the method might return zero for both values.

See Also

  • IBasicVideo2 Object


IBasicVideo2.GetSourcePosition

The GetSourcePosition method retrieves the source rectangle.

Syntax

objVideo.GetSourcePosition(
    ByRef Left As Long,
    ByRef Top As Long,
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Left

Variable that receives the source rectangle's x-coordinate, in pixels.

Top

Variable that receives the source rectangle's y-coordinate, in pixels.

Width

Variable that receives the width of the source rectangle, in pixels.

Height

Variable that receives the height of the source rectangle, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as retrieving the values of the IBasicVideo2.SourceLeft, IBasicVideo2.SourceTop, IBasicVideo2.SourceWidth, and IBasicVideo2.SourceHeight properties.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.GetVideoPaletteEntries

The GetVideoPaletteEntries method retrieves the palette colors for the video.

Syntax

objVideo.GetVideoPaletteEntries(
    StartIndex As Long,
    Entries As Long,
    ByRef Retrieved As Long,
    ByRef Palette As Long)

Parameters

StartIndex

Start index for the palette.

Entries

Number of palette entries to retrieve.

Retrieved

Variable that receives the number of entries returned in Palette.

Palette

Variable that receives the palette entries. Set this parameter equal to the first element in an array of type Long. Treat the returned values as PALETTEENTRY structures.

Return Values

This method does not return a value.

Remarks

The method fails if no palette is available. This can occur if the bit depth of the display is too high.

Example Code

Dim Retrieved As Long, Palette(16) As Long
Dim blue As Byte, red As Byte, green As Byte
iVideo.GetVideoPaletteEntries 0, 16, Retrieved, Palette(0)
For i = 0 To Retrieved - 1
    red = Palette(i) And &HFF
    green = (Palette(i) And &HFF00&) / 256
    blue = (Palette(i) And &HFF0000) / 65536
Next

See Also

  • IBasicVideo2 Object


IBasicVideo2.GetVideoSize

The GetVideoSize method retrieves the native video dimensions.

Syntax

objVideo.GetVideoSize
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Width

Variable that receives the width of the video image, in pixels.

Height

Variable that receives the height of the video image, in pixels.

Return Values

This method does not return a value.

See Also

  • IBasicVideo2 Object


IBasicVideo2.IsUsingDefaultDestination

Not supported.

Syntax

objVideo.IsUsingDefaultDestination()

See Also

  • IBasicVideo2 Object


IBasicVideo2.IsUsingDefaultSource

Not supported.

Syntax

objVideo.IsUsingDefaultSource()

See Also

  • IBasicVideo2 Object


IBasicVideo2.SetDefaultDestinationPosition

The SetDefaultDestinationPosition method reverts to the default destination rectangle. After this method is called, the video renderer uses the entire window for playback.

Syntax

objVideo.SetDefaultDestinationPosition()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.SetDestinationPosition


IBasicVideo2.SetDefaultSourcePosition

The SetDefaultSourcePosition method reverts to the default source rectangle. After this method is called, the video renderer uses the entire video image, without cropping.

Syntax

objVideo.SetDefaultSourcePosition()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.SetDestinationPosition

The SetDestinationPosition method sets the destination rectangle, relative to the video window.

Syntax

objVideo.SetDestinationPosition(
    Left As Long,
    Top As Long,
    Width As Long,
    Height As Long)

Parameters

Left

Specifies the x-coordinate of the destination rectangle, in pixels.

Top

Specifies the y-coordinate of the destination rectangle, in pixels.

Width

Specifies the width of the destination rectangle, in pixels.

Height

Specifies the height of the destination rectangle, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as setting the IBasicVideo2.DestinationLeft, IBasicVideo2.DestinationTop, IBasicVideo2.DestinationWidth, and IBasicVideo2.DestinationHeight properties.

See Also

  • IBasicVideo2 Object


IBasicVideo2.SetSourcePosition

The SetSourcePosition method sets the source rectangle. The video renderer crops to this rectangle.

Syntax

objVideo.SetSourcePosition(
    Left As Long,
    Top As Long,
    Width As Long,
    Height As Long)

Parameters

Left

Specifies the x-coordinate of the source rectangle, in pixels.

Top

Specifies the y-coordinate of the source rectangle, in pixels.

Width

Specifies the width of the source rectangle, in pixels.

Height

Specifies the height of the source rectangle, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as setting the IBasicVideo2.SourceLeft, IBasicVideo2.SourceTop, IBasicVideo2.SourceWidth, and IBasicVideo2.SourceHeight properties.

See Also

  • IBasicVideo2 Object


IBasicVideo2.SourceHeight

The SourceHeight property sets or retrieves the height of the source rectangle.

Syntax

objVideo.SourceHeight As Long

Parameters

This property takes no parameters.

Return Values

Returns the height, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetSourcePosition
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.SourceLeft

The SourceLeft property sets or retrieves the x-coordinate of the source rectangle.

Syntax

objVideo.SourceLeft As Long

Parameters

This property takes no parameters.

Return Values

Returns the x-coordinate, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetSourcePosition
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.SourceTop

The SourceTop property sets or retrieves the y-coordinate of the source rectangle.

Syntax

objVideo.SourceTop As Long

Parameters

This property takes no parameters.

Return Values

Returns the y-coordinate, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetSourcePosition
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.SourceWidth

The SourceWidth property sets or retrieves the width of the source rectangle.

Syntax

objVideo.SourceWidth As Long

Parameters

This property takes no parameters.

Return Values

Returns the width, in pixels.

Remarks

This property is read/write.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetSourcePosition
  • IBasicVideo2.SetSourcePosition


IBasicVideo2.VideoHeight

The VideoHeight property retrieves the native height of the video.

Syntax

objVideo.VideoHeight As Long

Parameters

This property takes no parameters.

Return Values

Returns the height, in pixels.

Remarks

This property is read-only.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetVideoSize


IBasicVideo2.VideoWidth

The VideoWidth property retrieves the native width of the video.

Syntax

objVideo.VideoWidth As Long

Parameters

This property takes no parameters.

Return Values

Returns the width, in pixels.

Remarks

This property is read-only.

See Also

  • IBasicVideo2 Object
  • IBasicVideo2.GetVideoSize


IFilterInfo Object

The IFilterInfo object manages information about a filter. This object is a wrapper for a DirectShow filter object, because DirectShow filters are not Automation-compatible.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IFilterInfo object exposes the following properties and methods.

Property | Description
Filename | Sets or retrieves the name of the file loaded by this filter. (File-source filters only.)
Filter | Retrieves the filter associated with this object.
IsFileSource | Indicates whether the filter is a file-source filter.
Name | Retrieves the name of the filter.
Pins | Retrieves a collection of all the pins on this filter.
VendorInfo | Retrieves a string containing optional information supplied by a vendor about the specified filter.

Method | Description
FindPin | Retrieves a pin with the specified identifier.


IFilterInfo.Filename

The Filename property sets or retrieves the name of the file loaded by this filter.

Syntax

objFilterInfo.Filename As String

Parameters

This property takes no parameters.

Return Values

Returns the name of the file.

Remarks

Only file-source filters support this property. Accessing this property on other filters will cause a run-time error. To determine whether a filter is a file-source filter, check the IFilterInfo.IsFileSource property.

This property is read/write. Setting this property causes the filter to load the specified file. If the filter has already loaded a file, setting this property causes a run-time error.

Example Code

The following example searches for source files in the filter graph and displays the file name for each one:

For Each objFilter In mGraph.FilterCollection
    If objFilter.IsFileSource = True Then
        MsgBox objFilter.FileName
    End If
Next

The next example adds the Async File Source filter to the filter graph, loads a file, and builds the rest of the graph. (Although you could do this in one step with the FilgraphManager.RenderFile method, you can use the Filename property with custom file-source filters.)

Dim objRegFilter As IRegFilterInfo
For Each objRegFilter In mGraph.RegFilterCollection
    If objRegFilter.Name = "File Source (Async.)" Then
        objRegFilter.Filter SrcFilter
        Exit For
    End If
Next
If Not SrcFilter Is Nothing Then
    SrcFilter.FileName = "C:\MyVideo.avi"
    For Each objPin In SrcFilter.Pins
        objPin.Render
    Next
End If

See Also

  • IFilterInfo Object


IFilterInfo.Filter

The Filter property retrieves the filter associated with this object.

Syntax

objFilterInfo.Filter As Unknown

Parameters

This property takes no parameters.

Return Values

Returns the filter.

Remarks

The IFilterInfo object is a wrapper for a DirectShow filter, because DirectShow filters expose the IBaseFilter interface, which is not Automation-compatible. This property returns the underlying filter as an IUnknown pointer. There are no methods in the Quartz.dll type library that can take this object as a parameter. It is provided for use with DLLs that take an IBaseFilter parameter. Also, it might be useful if you write your own Automation-compliant COM wrapper object for DirectShow.

This property is read-only.

See Also

  • IFilterInfo Object


IFilterInfo.FindPin

The FindPin method retrieves a pin with the specified identifier.

Syntax

objFilterInfo.FindPin(
    strPinId As String,
    ByRef objPinInfo As IPinInfo)

Parameters

strPinId

String that contains the pin identifier.

objPinInfo

Variable that receives a IPinInfo object.

Return Values

This method does not return a value.

Remarks

Pin identifiers are used for graph persistence. For more information, see IBaseFilter::FindPin.

See Also

  • IFilterInfo Object


IFilterInfo.IsFileSource

The IsFileSource property indicates whether the filter is a file-source filter.

Syntax

objFilterInfo.IsFileSource As Long

Parameters

This property takes no parameters.

Return Values

Returns True if the filter is a file-source filter, or False otherwise.

Remarks

This property is read-only. Internally, this method queries the filter for the IFileSourceFilter interface.

See Also

  • IFilterInfo Object
  • IFilterInfo.Filename


IFilterInfo.Name

The Name property retrieves the name of the filter.

Syntax

objFilterInfo.Name As String

Parameters

This property takes no parameters.

Return Values

Returns the name of the filter.

Remarks

This property is read-only.

See Also

  • IFilterInfo Object


IFilterInfo.Pins

The Pins property retrieves a collection of all the pins on this filter.

Syntax

objFilterInfo.Pins As IAMCollection

Parameters

This property takes no parameters.

Return Values

Returns an IAMCollection object that contains zero or more IPinInfo objects. Each IPinInfo object represents one pin on the filter.

Remarks

This property is read-only.

See Also

  • IFilterInfo Object


IFilterInfo.VendorInfo

The VendorInfo property retrieves a string containing vendor information.

Syntax

objFilterInfo.VendorInfo As String

Parameters

This property takes no parameters.

Return Values

Returns a string containing the vendor information, or a generic string if none was supplied.

Remarks

This property contains any information that the distributor of the filter chooses to supply. However, most filters do not provide any vendor string.

This property is read-only.

See Also

  • IFilterInfo Object


IMediaEvent Object

The IMediaEvent object contains methods for retrieving event notifications and for overriding the Filter Graph Manager's default handling of events. Applications can use this object to respond to events that occur in the filter graph, such as the end of a stream or a rendering error.

To use this object, declare a variable of type IMediaEvent and set it equal to the FilgraphManager object:

Dim mGraph As New FilgraphManager
Dim iEvent As IMediaEvent
Set iEvent = mGraph

For more information about event notification, see Event Notification in DirectShow. For a list of system-defined event notifications, see Event Notification Codes.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IMediaEvent object exposes the following methods.

Method | Description
CancelDefaultHandling | Cancels the Filter Graph Manager's default handling for a specified event.
FreeEventParams | Frees resources associated with the parameters of an event.
GetEvent | Retrieves the next event notification from the event queue.
GetEventHandle | Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.
RestoreDefaultHandling | Restores the Filter Graph Manager's default handling for a specified event.
WaitForCompletion | Waits for the filter graph to render all available data.


IMediaEvent.CancelDefaultHandling

The CancelDefaultHandling method cancels the Filter Graph Manager's default handling for a specified event. The event notification is passed to the application.

Syntax

objMediaEvent.CancelDefaultHandling(
    lEvCode As Long)

Parameters

lEvCode

Specifies the event code for which to cancel default handling.

Return Values

This method does not return a value.

See Also

  • IMediaEvent Object
  • IMediaEvent.RestoreDefaultHandling


IMediaEvent.FreeEventParams

The FreeEventParams method frees resources associated with the parameters of an event.

Syntax

objMediaEvent.FreeEventParams(
    EvCode As Long,
    Param1 As Long,
    Param2 As Long)

Parameters

EvCode

Specifies the event code.

Param1

Specifies the first event parameter.

Param2

Specifies the second event parameter.

Return Values

This method does not return a value.

Remarks

After you call the IMediaEvent.GetEvent method to retrieve an event notification, you must call FreeEventParams. This method frees any resources that were allocated for the event parameters. Pass in the same variables used for the GetEvent call.

See Also

  • IMediaEvent Object


IMediaEvent.GetEvent

The GetEvent method retrieves the next event notification from the event queue.

Syntax

objMediaEvent.GetEvent(
    ByRef lEventCode As Long,
    ByRef lParam1 As Long,
    ByRef lParam2 As Long,
    msTimeout As Long)

Parameters

lEventCode

Variable that receives the event code.

lParam1

Variable that receives the first event parameter.

lParam2

Variable that receives the first event parameter.

msTimeout

Time-out interval, in milliseconds. Use -1 to block until there is an event.

Return Values

This method does not return a value.

Remarks

If no event is on the queue, this method waits up to msTimeout milliseconds for one to arrive. If the time-out expires, the method raises run-time error 287.

After calling this method, call the IMediaEvent.FreeEventParams method, to release any resources allocated for the event parameters.

Example Code

Dim EvCode As Long, Param1 As Long, Param2 As Long
On Error Resume Next
Do
    mEvent.GetEvent EvCode, Param1, Param2, 100
    If Err.Number = 0 Then
        mEvent.FreeEventParams EvCode, Param1, Param2
        ' Handle the event. (Not shown.)
    End If
Loop While Err.Number = 0

See Also

  • IMediaEvent Object


IMediaEvent.GetEventHandle

The GetEventHandle method retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.

Syntax

objMediaEvent.GetEventHandle(
    ByRef hEvent As Long)

Parameters

hEvent

Variable that receives the event handle.

Return Values

This method does not return a value.

Remarks

The Filter Graph Manager keeps a manual-reset event that reflects the state of the event queue. If the queue contains event notifications, the manual-reset event is signaled. If the queue is empty, the IMediaEvent.GetEvent method resets the event. An application can use this event to determine the state of the queue.

To use this event in Visual Basic, your application must call into a Microsoft® Windows® function such as WaitForSingleObject or WaitForMultipleObjects. You must declare the function in a module, as shown in the example code. However, it might be easier in Visual Basic simply to create a timer and periodically call GetEvent.

Example Code

First declare the WaitForSingleObject and GetEvent methods in a module, as follows:

Public Const WAIT_ABANDONED& = &H80&
Public Const WAIT_OBJECT_0& = 0
Public Const WAIT_OBJECT_1& = 1
Public Const WAIT_TIMEOUT& = &H102&
Public Const INFINITE = &HFFFF
Public Declare Function WaitForSingleObject Lib "kernel32"  _
         (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Declare Function CreateEvent _
          Lib "kernel32" _
          Alias "CreateEventA" _
          (lpEventAttributes As Long, _
          ByVal bManualReset As Long, _
          ByVal bInitialState As Long, _
          ByVal lpName As String) As Long

Then call GetEventHandle to retrieve the event handle, and use the WaitForSingleObject method to wait for the event to be signaled:

Dim hEvent As Long, wait_result As Long
Dim EvCode As Long, Param1 As Long, Param2 As Long

mEvent.GetEventHandle hEvent

wait_result = WaitForSingleObject(hEvent, 1000)
If wait_result = WAIT_OBJECT_0 Then
    On Error Resume Next
    Do
        mEvent.GetEvent EvCode, Param1, Param2, 0
        If Err.Number = 0 Then
            ' Handle event. (Not shown.)
            mEvent.FreeEventParams EvCode, Param1, Param2
    Loop While Err.Number = 0
End If
Err.Clear

See Also

  • IMediaEvent Object


IMediaEvent.RestoreDefaultHandling

The RestoreDefaultHandling method restores the Filter Graph Manager's default handling for a specified event.

Syntax

objMediaEvent.RestoreDefaultHandling(
    lEvCode As Long)

Parameters

lEvCode

Specifies the event code for which to restore default handling.

Return Values

This method does not return a value.

Remarks

If you call the IMediaEvent.CancelDefaultHandling method to override the default handling for an event, you can restore the default behavior by calling RestoreDefaultHandling with the same event code.

See Also

  • IMediaEvent Object


IMediaEvent.WaitForCompletion

The WaitForCompletion method waits for the filter graph to render all available data.

Syntax

objMediaEvent.WaitForCompletion(
    msTimeout As Long,
    ByRef EvCode As Long)

Parameters

msTimeout

Time-out interval, in milliseconds, or -1 to block indefinitely.

EvCode

Variable that receives an event code, or zero if the time-out expires.

Return Values

This method does not return a value.

Remarks

This method blocks until the time-out expires, or one of the following events occurs:

  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_USERABORT

During the wait, the method discards all other event notifications.

The filter graph must be running or the method fails. If the time-out expires, the method raises run-time error 287, and sets EvCode to zero.

Example Code

The following example uses a time-out of zero:

On Error Resume Next
Dim EvCode As Long
iEvent.WaitForCompletion 0, EvCode  'Return immediately
If EventCode <> 0 Then
    ' Playback has stopped.
End If

See Also

  • IMediaEvent Object


IMediaPosition Object

The IMediaPosition object contains methods for seeking the filter graph and setting the playback rate.

To use this object, declare a variable of type IMediaPosition and set it equal to the FilgraphManager object:

Dim mGraph As New FilgraphManager
Dim iPosition As ImediaEvent
Set iPosition = mGraph

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IMediaPosition object exposes the following properties and methods.

Property | Description
CurrentPosition | Sets or retrieves the playback position.
Duration | Retrieves the duration of the stream.
PrerollTime | Sets or retrieves the amount of data that will be queued before the start position.
Rate | Sets or retrieves the playback rate.
StopTime | Sets or retrieves the stop time.

Method | Description
CanSeekBackward | Queries whether the stream can be seeked backward.
CanSeekForward | Queries whether the stream can be seeked forward.


IMediaPosition.CanSeekBackward

The CanSeekBackward method queries whether the stream can be seeked backward.

Syntax

objMediaPosition.CanSeekBackward() As Long

Parameters

This method takes no parameters.

Return Values

Returns True if the stream can be seeked backward, or False otherwise.

Example Code

If iPosition.CanSeekBackward Then
    ' Seek back to the beginning.
    IPosition.CurrentPosition = 0
End If

See Also

  • IMediaPosition Object


IMediaPosition.CanSeekForward

The CanSeekForward method queries whether the stream can be seeked forward.

Syntax

objMediaPosition.CanSeekForward() As Long

Parameters

This method takes no parameters.

Return Values

Returns True if the stream can be seeked forward, or False otherwise.

Example Code

If iPosition.CanSeekBackward Then
    ' Seek forward 5 seconds.
    IPosition.CurrentPosition = iPosition.CurrentPosition + 5.0
End If

See Also

  • IMediaPosition Object


IMediaPosition.CurrentPosition

The CurrentPosition property sets or retrieves the playback position.

Syntax

objMediaPosition.CurrentPosition As Double

Parameters

This property takes no parameters.

Return Values

Returns the current position, in seconds, relative to the start of the original source.

Remarks

If the graph is running, this property is equal to the current position of the stream, relative to the start of the source. If the graph is paused or stopped, this property is equal to the last position that was reached.

This property is read/write. If the stream is seekable, setting this property seeks the stream.

The position is calculated before the rate, so the position is relative to normal playback speed. For example, if you set the rate to twice normal speed and run the graph for 2 seconds, the CurrentPosition property is 4.0.

See Also

  • IMediaPosition Object


IMediaPosition.Duration

The Duration property retrieves the duration of the stream.

Syntax

objMediaPosition.Duration As Double

Parameters

This property takes no parameters.

Return Values

Returns the duration, in seconds.

Remarks

The duration is relative to the normal playback rate. Therefore, setting the IMediaPosition.Rate property does not affect the value of the Duration property.

This property is read-only.

See Also

  • IMediaPosition Object


IMediaPosition.PrerollTime

The PrerollTime property retrieves the amount of data that will be queued before the start position.

Syntax

objMediaPosition.PrerollTime As Double

Parameters

This property takes no parameters.

Return Values

Returns the preroll time, in seconds.

Remarks

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

See Also

  • IMediaPosition Object


IMediaPosition.Rate

The Rate property sets or retrieves the playback rate, relative to normal playback speed.

Syntax

objMediaPosition.Rate As Double

Parameters

This property takes no parameters.

Return Values

Returns the playback rate, as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed. Negative rates indicate reverse playback; however, most sources do not support reverse playback.

Remarks

This property is read/write.

See Also

  • IMediaPosition Object


IMediaPosition.StopTime

The StopTime property sets or retrieves the stop time.

Syntax

objMediaPosition.StopTime As Double

Parameters

This property takes no parameters.

Return Values

Returns the stop time, in seconds, relative to the start of the original source.

Remarks

This property is read/write.

The stop time is calculated before the rate, so the position is relative to normal playback speed.

See Also

  • IMediaPosition Object


IMediaTypeInfo Object

The IMediaTypeInfo object manages information about a media type. This object is a wrapper for the AM_MEDIA_TYPE structure, which is not Automation-compatible. However, only the major type and subtype are accessible through this object, and they cannot be modified.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IMediaTypeInfo object exposes the following properties.

Property | Description
Subtype | Retrieves the subtype GUID as a string.
Type | Retrieves the major type GUID as a string.


IMediaTypeInfo.Subtype

The Subtype property retrieves the subtype GUID as a string.

Syntax

objMediaTypeInfo.Subtype As String

Parameters

This property takes no parameters.

Return Values

Returns a string with the form {00000000-0000-0000-0000-000000000000}.

Remarks

This property retrieves the subtype member of the AM_MEDIA_TYPE structure, converted to a string.

This property is read-only.

See Also

  • IMediaTypeInfo Object


IMediaTypeInfo.Type

The Type property retrieves the major type GUID as a string.

Syntax

objMediaTypeInfo.Type As String

Parameters

This property takes no parameters.

Return Values

Returns a string with the form {00000000-0000-0000-0000-000000000000}.

Remarks

This property retrieves the majortype member of the AM_MEDIA_TYPE structure, converted to a string.

This property is read-only.

See Also

  • IMediaTypeInfo Object


IPinInfo Object

The IPinInfo object manages information about a pin on a filter. This object is a wrapper for a DirectShow pin object, because DirectShow pins are not Automation-compatible.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IPinInfo object exposes the following properties and methods.

Property | Description
ConnectedTo | Retrieves the pin to which this pin is connected, if any.
ConnectionMediaType | Retrieves the media type for the current pin connection, if any.
Direction | Retrieves the direction of the pin.
FilterInfo | Retrieves the filter that owns this pin.
MediaTypes | Retrieves a collection of the pin's preferred media types.
Name | Retrieves the name of the pin.
Pin | Retrieves the pin associated with this object.
PinID | Retrieves an identifier for the pin.

Method | Description
Connect | Connects this pin to another pin, using intermediate filters if needed.
ConnectDirect | Connects this pin directly to another pin, without using intermediate filters.
ConnectWithType | Connects this pin directly to another pin, using a specified media type.
Disconnect | Disconnects this pin, if it is connected.
Render | Builds a section of the filter graph to render data from this pin.


IPinInfo.Connect

The Connect method connects this pin to another pin, using intermediate filters if needed.

Syntax

objPinInfo.Connect(
    objPin As IPinInfo)

Parameters

objPin

IPinInfo object that specifies the other pin in the connection.

Return Values

This method does not return a value.

Remarks

The objPin parameter can also specify a DirectShow pin. For more information, see IPinInfo.Pin.

See Also

  • IPinInfo Object


IPinInfo.ConnectDirect

The ConnectDirect method connects this pin directly to another pin, without using intermediate filters.

Syntax

objPinInfo.ConnectDirect(
    objPin As IPinInfo)

Parameters

objPin

IPinInfo object that specifies the other pin in the connection.

Return Values

This method does not return a value.

Remarks

The objPin parameter can also specify a DirectShow pin. For more information, see IPinInfo.Pin.

See Also

  • IPinInfo Object


IPinInfo.ConnectedTo

The ConnectedTo property retrieves the pin to which this pin is connected, if any.

Syntax

objPinInfo.ConnectedTo As IPinInfo

Parameters

This property takes no parameters.

Return Values

Returns an IPinInfo object.

Remarks

This property is read-only. If the pin is not connected, retrieving this property causes a run-time error.

See Also

  • IPinInfo Object


IPinInfo.ConnectionMediaType

The ConnectionMediaType property retrieves the media type for the current pin connection, if any.

Syntax

objPinInfo.ConnectionMediaType As IMediaTypeInfo

Parameters

This property takes no parameters.

Return Values

Returns an IMediaTypeInfo object.

Remarks

This property is read-only. If the pin is not connected, retrieving this property causes a run-time error.

See Also

  • IPinInfo Object


IPinInfo.ConnectWithType

The ConnectWithType method connects this pin directly to another pin, using a specified media type.

Syntax

objPinInfo.ConnectWithType(
    objPin As IPinInfo,
    objMediaType As IMediaTypeInfo)

Parameters

objPin

IPinInfo object that specifies the other pin in the connection.

objMediaType

IMediaTypeInfo object that specifies the media type.

Return Values

This method does not return a value.

Remarks

The objPin parameter can also specify a DirectShow pin. For more information, see IPinInfo.Pin.

See Also

  • IPinInfo Object


IPinInfo.Direction

The Direction property retrieves the direction of the pin.

Syntax

objPinInfo.Direction As Long

Parameters

This property takes no parameters.

Return Values

Returns 0 if the pin is an input pin, or 1 if the pin is an output pin.

Remarks

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.Disconnect

The Disconnect method disconnects this pin, if it is connected.

Syntax

objPinInfo.Disconnect()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

If the pin is not connected, this method causes a run-time error.

See Also

  • IPinInfo Object


IPinInfo.FilterInfo

The FilterInfo property retrieves the filter that owns this pin.

Syntax

objPinInfo.FilterInfo As FilterInfo

Parameters

This property takes no parameters.

Return Values

Returns an IFilterInfo object.

Remarks

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.MediaTypes

The MediaTypes property retrieves a collection of the pin's preferred media types.

Syntax

objPinInfo.MediaTypes As IAMCollection

Parameters

This property takes no parameters.

Return Values

Returns an IAMCollection object that contains zero or more IMediaTypeInfo objects.

Remarks

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.Name

The Name property retrieves the name of the pin.

Syntax

objPinInfo.Name As String

Parameters

This property takes no parameters.

Return Values

Returns a string containing the pin name.

Remarks

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.Pin

The Pin property retrieves the pin associated with this object.

Syntax

objPinInfo.Pin As Unknown

Parameters

This property takes no parameters.

Return Values

Returns the pin.

Remarks

The IPinInfo object is a wrapper for a DirectShow pin, because DirectShow pins expose the IPin interface, which is not Automation-compatible. This property returns the underlying pin as an IUnknown pointer. This property is provided for use with DLLs that take an IPin parameter.

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.PinID

The PinID property retrieves an identifier for the pin.

Syntax

objPinInfo.PinID As String

Parameters

This property takes no parameters.

Return Values

Returns a string containing the pin identifier.

Remarks

The PinID property is used for graph persistence. You can pass this string as the strPinId parameter in the IFilterInfo.FindPin method.

This property is read-only.

See Also

  • IPinInfo Object


IPinInfo.Render

The Render method builds a section of the filter graph to render data from this pin.

Syntax

objPinInfo.Render()

Parameters

This method takes no parameters.

Return Values

This method does not return a value.

Remarks

This method connects an output pin directly or indirectly to a filter that will render it, adding new filters to the graph as necessary. The method works only on output pins.

See Also

  • IPinInfo Object


IRegFilterInfo Object

The IRegFilterInfo object represents filter information from the registry. Applications can use it to add filters to the filter graph. For more information on using this object, see FilgraphManager.RegFilterCollection.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IRegFilterInfo object exposes the following property and method.

Property | Description
Name | Retrieves the name of the filter.

Method | Description
Filter | Creates an instance of the filter and adds it to the filter graph.


IRegFilterInfo.Filter

The Filter method creates an instance of the filter and adds it to the filter graph.

Syntax

objRegFilterInfo.Filter(
    ByRef objFilterInfo As IFilterInfo)

Parameters

objFilterInfo

Variable that receives an IFilterInfo object, representing the new filter.

Return Values

This method does not return a value.

See Also

  • IRegFilterInfo Object


IRegFilterInfo.Name

The Name property retrieves the name of the filter.

Syntax

objRegFilterInfo.Name As String

Parameters

This property takes no parameters.

Return Values

Returns a string containing the name.

Remarks

This property is read-only.

See Also

  • IRegFilterInfo Object


IVideoWindow Object

The IVideoWindow object manages the window of a video renderer. To use this object, declare a variable of type IVideoWindow and set it equal to the FilgraphManager object:

Dim mGraph As New FilgraphManager
Dim iVidWin As IVideoWindow
Set iVidWin = mGraph

The methods and properties of this object fail if the graph does not have a connected video renderer.

Requirements

Include a reference in your project to "ActiveMovie control type library" (Quartz.dll).

The IVideoWindow object exposes the following properties and methods.

Property | Description
AutoShow | Specifies whether the video renderer automatically shows the video window when it receives video data.
BackgroundPalette | Specifies whether the video window realizes its palette in the background.
BorderColor | Sets or retrieves the color that appears around the edges of the destination rectangle.
Caption | Sets or retrieves the window caption.
FullScreenMode | Enables or disables full-screen mode.
Height | Sets or retrieves the height of the video window.
Left | Sets or retrieves the x-coordinate of the video window.
MessageDrain | Sets or retrieves a window that receives mouse and keyboard messages from the video window.
Owner | Sets or retrieves the parent window for the video window.
Top | Sets or retrieves the y-coordinate of the video window.
Visible | Shows or hides the video window.
Width | Sets or retrieves the width of the video window.
WindowState | Shows, hides, minimizes, or maximizes the video window.
WindowStyle | Sets or retrieves the window style on the video window.
WindowStyleEx | Sets or retrieves the extended window style on the video window.

Method | Description
GetMaxIdealImageSize | Retrieves the maximum ideal size for the video image.
GetMinIdealImageSize | Retrieves the minimum ideal size for the video image.
GetRestorePosition | Retrieves the restored window position.
GetWindowPosition | Retrieves the position of the video window.
HideCursor | Hides or shows the cursor.
IsCursorHidden | Queries whether the cursor is hidden.
NotifyOwnerMessage | Forwards a message to the video window.
SetWindowForeground | Places the video window at the top of the Z order.
SetWindowPosition | Sets the position of the video window.


IVideoWindow.AutoShow

The AutoShow property specifies whether the video renderer automatically shows the video window when it receives video data.

Syntax

objVideoWindow.AutoShow As Long

Parameters

This property takes no parameters.

Return Values

Returns True or False. If the value is True, the video renderer automatically shows the video window when the renderer pauses or runs. If the value is False, the video renderer does not automatically show the window. The default value is True.

Remarks

By default, when the filter graph changes state to paused or running, the video renderer shows the video window and moves it to the foreground. If the user closes the window, it will not automatically reappear.

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.BackgroundPalette

The BackgroundPalette property specifies whether the video window realizes its palette in the background.

Syntax

objVideoWindow.BackgroundPalette As Long

Parameters

This property takes no parameters.

Return Values

Returns True if the video renderer realizes the palette in the background, or False otherwise. The default value is False.

Remarks

If this property is True and the video image requires a palette, the video renderer will realize that palette in the background. Any colors that the palette uses will change to their closest match in the display palette prior to drawing. This ensures that an application will not have its palette disturbed. However, it imposes severe performance penalties on the video.

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.BorderColor

The BorderColor property sets or retrieves the color that appears around the edges of the destination rectangle.

Syntax

objVideoWindow.BorderColor As Long

Parameters

This property takes no parameters.

Return Values

Returns the color as a Long value. Treat the returned value as a COLORREF value.

Remarks

If the destination rectangle is smaller than the client area of the video window, a border is exposed around the edges of the video. The default color is black. Use this method to override the default color. If a palette is in use, a nonsystem color is converted to its closest match.

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.Caption

The Caption property sets or retrieves the window caption.

Syntax

objVideoWindow.Caption As String

Parameters

This property takes no parameters.

Return Values

Returns a string containing the caption.

Remarks

This property is read/write. If the video window is made the child of another window, the caption is not visible.

See Also

  • IVideoWindow Object


IVideoWindow.FullScreenMode

The FullScreenMode property enables or disables full-screen mode.

Syntax

objVideoWindow.FullScreenMode As Long

Parameters

This property takes no parameters.

Return Values

Returns True if the video renderer is in full-screen mode, or False otherwise.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.GetMaxIdealImageSize

The GetMaxIdealImageSize method retrieves the maximum ideal size for the video image.

Syntax

objVideoWindow.GetMaxIdealImageSize(
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Width

Variable that receives the maximum ideal width, in pixels.

Height

Variable that receives the maximum ideal height, in pixels.

Return Values

This method does not return a value.

Remarks

The maximum ideal size may differ from the native video size, because the video hardware might have specific stretching requirements.

See Also

  • IVideoWindow Object


IVideoWindow.GetMinIdealImageSize

The GetMinIdealImageSize method retrieves the minimum ideal size for the video image.

Syntax

objVideoWindow.GetMinIdealImageSize(
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Width

Variable that receives the minimum ideal width, in pixels.

Height

Variable that receives the minimum ideal height, in pixels.

Return Values

This method does not return a value.

Remarks

The minimum ideal size may differ from the native video size, because the video hardware might have specific stretching requirements.

See Also

  • IVideoWindow Object


IVideoWindow.GetRestorePosition

The GetRestorePosition method retrieves the restored window position.

Syntax

objVideoWindow.GetRestorePosition(
    ByRef Left As Long,
    ByRef Top As Long,
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Left

Variable that receives the x-coordinate, in pixels.

Top

Variable that receives the y-coordinate, in pixels.

Width

Variable that receives the width of the window, in pixels.

Height

Variable that receives the height of the window, in pixels.

Return Values

This method does not return a value.

Remarks

If the video window is minimized or maximized, you can use this method to get the window's restored position.

See Also

  • IVideoWindow Object


IVideoWindow.GetWindowPosition

The GetWindowPosition method retrieves the position of the video window.

Syntax

objVideoWindow.GetWindowPosition(
    ByRef Left As Long,
    ByRef Top As Long,
    ByRef Width As Long,
    ByRef Height As Long)

Parameters

Left

Variable that receives the x-coordinate, in pixels.

Top

Variable that receives the y-coordinate, in pixels.

Width

Variable that receives the width of the window, in pixels.

Height

Variable that receives the height of the window, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as setting the IVideoWindow.Left, IVideoWindow.Top, IVideoWindow.Width, and IVideoWindow.Height properties.

See Also

  • IVideoWindow Object


IVideoWindow.Height

The Height property sets or retrieves the height of the video window.

Syntax

objVideoWindow.Height As Long

Parameters

This property takes no parameters.

Return Values

Returns the height in pixels.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.HideCursor

The HideCursor method hides or shows the cursor.

Syntax

objVideoWindow.HideCursor(
    bValue As Long)

Parameters

bValue

Boolean value that specifies whether to hide or show the cursor. If True, the cursor is hidden; if False, the cursor is visible.

Return Values

This method does not return a value.

See Also

  • IVideoWindow Object


IVideoWindow.IsCursorHidden

The IsCursorHidden method queries whether the cursor is hidden.

Syntax

objVideoWindow.IsCursorHidden(
    ByRef bValue As Long)

Parameters

bValue

Variable that receives the value True if the cursor is hidden, or False if the cursor is visible.

Return Values

This method does not return a value.

See Also

  • IVideoWindow Object


IVideoWindow.Left

The Left property sets or retrieves the x-coordinate of the video window.

Syntax

objVideoWindow.Left As Long

Parameters

This property takes no parameters.

Return Values

Returns the x-coordinate in pixels.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.MessageDrain

The MessageDrain property sets or retrieves a window that receives mouse and keyboard messages from the video window.

Syntax

objVideoWindow.MessageDrain As LONG_PTR

Parameters

This property takes no parameters.

Return Values

Returns a handle to the window that receives the messages.

Remarks

An application can set this property in order to receive mouse and keyboard events generated within the video window. The message drain window does not need to be a parent of the video window, so full-screen applications can use this property.

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.NotifyOwnerMessage

The NotifyOwnerMessage method forwards a message to the video window.

Syntax

objVideoWindow.NotifyOwnerMessage(
    hwnd As LONG_PTR,
    uMsg As Long,
    wParam As LONG_PTR,
    lParam As LONG_PTR)

Parameters

hwnd

Handle to the window.

uMsg

Specifies the message.

wParam

Message parameter.

lParam

Message parameter.

Return Values

This method does not return a value.

Remarks

The Filter Graph Manager calls this method to pass various messages to the renderer.

See Also

  • IVideoWindow Object


IVideoWindow.Owner

The Owner property sets or retrieves the parent window for the video window.

Syntax

objVideoWindow.Owner As LONG_PTR

Parameters

This property takes no parameters.

Return Values

Returns a handle to the owner window.

Remarks

This property offers a way for applications to display video in a compound document.

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.SetWindowForeground

The SetWindowForeground method places the video window at the top of the Z order.

Syntax

objVideoWindow.SetWindowForeground(
    Focus As Long)

Parameters

Focus

Boolean value that specifies whether to give the window focus. If True, the window will get the focus.

Return Values

This method does not return a value.

See Also

  • IVideoWindow Object


IVideoWindow.SetWindowPosition

The SetWindowPosition method sets the position of the video window.

Syntax

objVideoWindow.SetWindowPosition(
    Left As Long,
    Top As Long,
    Width As Long,
    Height As Long)

Parameters

Left

Specifies the x-coordinate, in pixels.

Top

Specifies the y-coordinate, in pixels.

Width

Specifies the width, in pixels.

Height

Specifies the height, in pixels.

Return Values

This method does not return a value.

Remarks

This method has the same effect as setting the IVideoWindow.Left, IVideoWindow.Top, IVideoWindow.Width, and IVideoWindow.Height properties.

See Also

  • IVideoWindow Object


IVideoWindow.Top

The Top property sets or retrieves the y-coordinate of the video window.

Syntax

objVideoWindow.Top As Long

Parameters

This property takes no parameters.

Return Values

Returns the y-coordinate in pixels.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.Visible

The Visible property specifies whether the window is visible or hidden.

Syntax

objVideoWindow.Visible As Long

Parameters

This property takes no parameters.

Return Values

Returns True if the window is visible, or False if the window is hidden.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.Width

The Width property sets or retrieves the width of the video window.

Syntax

objVideoWindow.Width As Long

Parameters

This property takes no parameters.

Return Values

Returns the width in pixels.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.WindowState

The WindowState property shows, hides, minimizes, or maximizes the video window, or retrieves the window's current state.

Syntax

objVideoWindow.WindowState As Long

Parameters

This property takes no parameters.

Return Values

Returns one of the following flags:

  • SW_HIDE
  • SW_MAXIMIZE
  • SW_MINIMIZE
  • SW_SHOW

The meanings of these flags are defined by the Windows ShowWindow function.

Remarks

This property is read/write.

See Also

  • IVideoWindow Object


IVideoWindow.WindowStyle

The WindowStyle property sets or retrieves the window styles on the video window.

Syntax

objVideoWindow.WindowStyle As Long

Parameters

This property takes no parameters.

Return Values

Returns one or more flags from the GWL_STYLE value of the Windows SetWindowLong function.

Remarks

This property is a thin wrapper over the SetWindowLong function and must be treated with care. In particular, if you change this property, you should retrieve the current styles and then add or remove flags. With some exceptions, flags allowed by the Windows CreateWindow function are acceptable. However, do not use this method to change the window size, and do not use the following flags:

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

This property is read/write.

See Also

  • IVideoWindow Object
  • IVideoWindow.WindowStyleEx


IVideoWindow.WindowStyleEx

The WindowStyleEx property sets or retrieves the extended window styles on the video window.

Syntax

objVideoWindow.WindowStyleEx As Long

Parameters

This property takes no parameters.

Return Values

Returns one or more flags from the GWL_EXSTYLE value of the Windows SetWindowLong function.

Remarks

This property is a thin wrapper over the SetWindowLong function and must be treated with care. In particular, if you change this property, you should retrieve the current styles and then add or remove flags. With some exceptions, flags allowed by the Windows CreateWindow function are acceptable. However, do not use this method to change the window size.

This property is read/write.

See Also

  • IVideoWindow Object
  • IVideoWindow.WindowStyle


International Analog TV Tuning

This section describes the support for international analog tuning provided by the DirectShow TV Tuner filter. It contains the following topics:

  • Frequency Tables
  • Frequency Overrides
  • Collecting Fine-Tuning Information
  • Tables and Assignments
    • Australia
    • China
    • Czech Republic
    • Eastern Europe
    • France
    • French Overseas Territories
    • Ireland
    • Italy
    • Japan
    • New Zealand
    • NTSC (United States)
    • United Kingdom
    • Western Europe
    • Unicable Frequency Table
    • Country/Region Assignments

See Also

  • Analog Television Tuning


Frequency Tables

The TV Tuner filter (kstvtune.ax) has an internal list of frequency tables. Each frequency table contains a list of frequencies, and corresponds to the broadcast or cable frequencies for a given country/region. An application tunes to a particular frequency by calling the IAMTuner::put_Channel method with the index of the desired frequency.

For some countries/regions, the index numbers of the frequency tables map directly to channel numbers. Fixed channel numbers are not appropriate for all markets, however. For instance, the European channel numbers are not actually used by consumers. Instead, consumers expect to choose and assign their own channel numbers for the frequencies used by the broadcast or cable operators in their area. For these countries/regions, applications should not expose the index numbers directly to the user. Instread, the application should keep an internal mapping between channel numbers (presented to the user) and frequency indexes (for tuning).

Most non-US cable operators are free to broadcast on frequencies of their choosing, often mixing frequencies from different standards into the same channel lineup. Therefore, a "Unicable" frequency table is used for any country/region that lacks a standard cable channel standards authority. Also, a mechanism is provided to override individual frequencies in the frequency tables. This mechanism is described in the section Frequency Overrides.


Frequency Overrides

A significant amount of effort was spent to ensure that the broadcast frequencies and color standard assignments are correct for each country/region. Even so, there will be situations when the frequency tables are not sufficient, have errors, or have become obsolete. To address this problem, the frequencies listed in the TV Tuner filter's frequency tables may be selectively overridden via the registry.

Frequency overrides are grouped into application-defined "tuning spaces," which are identified by number. The following example shows an example override:

HKEY_LOCAL_MACHINE\Software\Microsoft\TV System Services\TVAutoTune\TS0-1
"12"=dword:04022750

In this case, TS0-1 indicates Tuning Space 0 for cable frequencies. The first number identifies the tuning space. The second number is either 0 for broadcast frequencies or 1 for cable frequencies.

The subkey named 12 overrides the frequency value for the frequency at index 12 in the current frequency table. The value of the subkey is a DWORD that specifies the frequency in Hz. In this example, the frequency is set to 67.25MHz. Overrides can be defined for any channel numbers in the range 1 to 999, inclusive. If the tuning hardware does not support a given frequency, the tune request will fail.

This mechanism can also be used to create new channel numbers outside the existing range in the frequency table. The IAMTuner::ChannelMinMax method will return the extended channel range. For example, if the original channel range was 1 to 158, and a channel override of "200" is added to the registry, the ChannelMinMax method will return 200 as the maximum channel. In this case, channel numbers in the range 159 to 199 will have no frequencies assigned to them, so any tune requests in that range will automatically fail.

The IAMTuner::put_TuningSpace method allows the application to choose which set of overrides and fine-tuning information to use. Tuning space numbers are arbitary. It is the application's responsibility to maintain the relationship between the Tuning Space and the frequency table. The most straigtforward approach is to use the country/region code as the tuning space number. Then, every time the application switches to a new country/region code, it would also switch to the same tuning space (in that order).


Collecting Fine-Tuning Information

Although cable frequencies are generally expected to be exact, broadcast frequencies may be adjusted up or down several kHz by the broadcast station to reduce potential interference with neighboring channels.

When the TV Tuner filter tunes to a channel, it scans for the most precise signal. To save this information in the registry for subsequent tune operations, do the following:

  1. Call IAMTuner::ChannelMinMax to determine the range of frequency entries in the current frequency table.
  2. Call the IAMTuner::put_Channel method once for each frequency index in the range.
  3. Call IAMTVTuner::StoreAutoTune to save the fine-tuning information in the registry. The information is stored under the registry key for the current tuning space.

The following code shows these steps:

long lMin = 0, lMax = 0;
hr = pTuner->ChannelMinMax(&lMin, &lMax);
if (SUCCEEDED(hr))
{
    for (long i = lMin; i <= lMax; i++)
    {
        pTuner->put_Channel(i, AMTUNER_SUBCHAN_DEFAULT,
            AMTUNER_SUBCHAN_DEFAULT)
    }
    pTuner->StoreAutoTune();
}

With earlier versions of the TV Tuner filter, the IAMTVTuner::AutoTune method was recommended for fine-tuning. However, this method ignores any frequency overrides, so its use is no longer recommended. The following code is equivalent to the AutoTune method, but works correctly with frequency overrides:

HRESULT MyAutoTune(IAMTVTuner *pTuner, long lIndex, long *plFoundSignal)
{
    long SignalStrength = AMTUNER_NOSIGNAL;
    HRESULT hr;
    hr = pTuner->put_Channel(lIndex, AMTUNER_SUBCHAN_DEFAULT, AMTUNER_SUBCHAN_DEFAULT);
    if (NOERROR == hr)
        pTuner->SignalPresent(&SignalStrength);
    *plFoundSignal = (SignalStrength != AMTUNER_NOSIGNAL);
    // Assume AMTUNER_HASNOSIGNALSTRENGTH means tuned
    return hr;
}

With broadcast reception, it is not always possible to get a horizontal lock, although the picture is viewable. In these cases, the tuner hardware will have a frequency lock, but the decoder won't have horizontal lock. This condition can be detected when using put_Channel or AutoTune by examining the return code.

Value | Description
S_OK | The tune operation succeeded and the tuner got a frequency lock.
S_FALSE | There were no errors in during the tune operation, but the tuner was not able to get a frequency lock. It is highly unlikely that there is a viewable channel resulting from this operation.

Any other return code indicates some error occurred.

A return value of S_OK does not guarantee that the decoder has a horizontal lock. The AutoTune method updates the FoundSignal parameter to indicate whether or not horizontal lock was achieved. The IAMTuner::SignalPresent method returns the same information.

When the return value is S_OK, however, the application has the option of ignoring the FoundSignal parameter, because the tuner is reporting a frequency lock. There is the possibility of a frequency lock on noise, but this possibility should be weighed against the possibility of skipping viewable channels.

Registry Conversion

In order to support frequency overrides, the internal format of the registry key that holds fine-tuning information has changed. The original format is still supported for backward compatibility, but it does not support frequency overrides.

The old registry format is converted to the new format whenever the IAMTVTuner::StoreAutoTune method is called. If your application adds frequency overrides, it should call the StoreAutoTune method in order to convert to the new registry format. It is not necessary to collect any fine-tuning information before calling StoreAutoTune.


Tables and Assignments

This section contains the following frequency tables for international analog TV tuning:

  • Australia
  • China
  • Czech Republic
  • Eastern Europe
  • France
  • French Overseas Territories
  • Ireland
  • Italy
  • Japan
  • New Zealand
  • NTSC (United States)
  • United Kingdom
  • Western Europe
  • Unicable Frequency Table
  • Country/Region Assignments

Frequency Tables

Worldwide, there is a finite, known set of broadcast frequency standards. These standards have been identified by their country/region of origin, but in many cases, multiple countries/regions share the same standard. The TV Tuner filter defines a table for each standard.

Unfortunately, the same cannot be said for cable frequency standards. The cable providers in some countries/regions are free to broadcast programming on frequencies of their choosing. Frequencies from multiple standards are often mixed. In most cases, this practice correlates directly with the country/region of origin for each of the frequency standards. The TV Tuner filter defines tables for the few cable standards (and countries/regions) that have dependable cable frequency allocations. For all others, it uses the Unicable Frequency Table.

The frequency tables in the following sections are extracted verbatim from the resource file definitions used to build the tables in the TV Tuner filter. Each table starts with its resource ID. You can use these resource IDs to cross-reference from the Country/Region Assignments table, to determine which tables are in use for each country/region or locale.

The frequency tables include the theoretical upper and lower channel numbers (or frequency indexes) for each country/region code. This range can be extended via the registry; for more information, see Frequency Overrides.


Australia

The frequency indexes in the Australia table are not suitable for use as channel numbers. Also note that channels 3, 4, 5, and 5A are being phased out for other uses.

Australia Broadcast Assignments

F_OZ__BROAD RCDATA
BEGIN
         1L,            // Lowest index
        53L,            // Highest index
        46250000L,      // 0    (1) VHF Band 1
        57250000L,      // 1    (2)
        64250000L,      // 2    (3) VHF Band 2
        86250000L,      // 3    (4)
        95250000L,      // 4    (5)
       102250000L,      // 5    (6)
       138250000L,      // 5a   (7) VHF Band 3
       175250000L,      // 6    (8)
       182250000L,      // 7    (9)
       189250000L,      // 8    (10)
       196250000L,      // 9    (11)
       209250000L,      // 10   (12)
       216250000L,      // 11   (13)
       223250000L,      // 12   (14)
       527250000L,      // 28   (15) UHF Band 4
       534250000L,      // 29   (16)
       541250000L,      // 30   (17)
       548250000L,      // 31   (18)
       555250000L,      // 32   (19)
       562250000L,      // 33   (20)
       569250000L,      // 34   (21)
       576250000L,      // 35   (22)
       604250000L,      // 39   (23) UHF Band 5
       611250000L,      // 40   (24)
       618250000L,      // 41   (25)
       625250000L,      // 42   (26)
       632250000L,      // 43   (27)
       639250000L,      // 44   (28)
       646250000L,      // 45   (29)
       653250000L,      // 46   (30)
       660250000L,      // 47   (31)
       667250000L,      // 48   (32)
       674250000L,      // 49   (33)
       681250000L,      // 50   (34)
       688250000L,      // 51   (35)
       695250000L,      // 52   (36)
       702250000L,      // 53   (37)
       709250000L,      // 54   (38)
       716250000L,      // 55   (39)
       723250000L,      // 56   (40)
       730250000L,      // 57   (41)
       737250000L,      // 58   (42)
       744250000L,      // 59   (43)
       751250000L,      // 60   (44)
       758250000L,      // 61   (45)
       765250000L,      // 62   (46)
       772250000L,      // 63   (47)
       779250000L,      // 64   (48)
       786250000L,      // 65   (49)
       793250000L,      // 66   (50)
       800250000L,      // 67   (51)
       807250000L,      // 68   (52)
       814250000L,      // 69   (53)
END

Australia Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


China

The frequency indexes in the China table are suitable for use as channel numbers.

China Broadcast Assignments

F_CHN_BROAD RCDATA
BEGIN
        1L,             // Lowest channel
        36L,            // Highest channel
        49750000L,      // 1
        57750000L,      // 2
        65750000L,      // 3
        77250000L,      // 4
        85250000L,      // 5
       168250000L,      // 6
       176250000L,      // 7
       184250000L,      // 8
       192250000L,      // 9
       200250000L,      // 10
       208250000L,      // 11
       216250000L,      // 12
       471250000L,      // 13
       479250000L,      // 14
       487250000L,      // 15
       495250000L,      // 16
       503250000L,      // 17
       511250000L,      // 18
       519250000L,      // 19
       527250000L,      // 20
       535250000L,      // 21
       543250000L,      // 22
       551250000L,      // 23
       559250000L,      // 24
       605250000L,      // 25
       613250000L,      // 26
       621250000L,      // 27
       629250000L,      // 28
       637250000L,      // 29
       645250000L,      // 30
       653250000L,      // 31
       661250000L,      // 32
       669250000L,      // 33
       677250000L,      // 34
       685250000L,      // 35
       693250000L,      // 36
END

China Cable Assignments

F_CHN_CABLE RCDATA
BEGIN
        1L,             // Lowest channel
        52L,            // Highest channel
        49750000L,      // 1
        57750000L,      // 2
        65750000L,      // 3
        77250000L,      // 4
        85250000L,      // 5
       112250000L,      // 6
       120250000L,      // 7
       128250000L,      // 8
       136250000L,      // 9
       144250000L,      // 10
       152250000L,      // 11
       160250000L,      // 12
       168250000L,      // 13
       176250000L,      // 14
       184250000L,      // 15
       192250000L,      // 16
       200250000L,      // 17
       208250000L,      // 18
       216250000L,      // 19
       224250000L,      // 20
       232250000L,      // 21
       240250000L,      // 22
       248250000L,      // 23
       256250000L,      // 24
       264250000L,      // 25
       272250000L,      // 26
       280250000L,      // 27
       288250000L,      // 28
       471250000L,      // 29
       479250000L,      // 30
       487250000L,      // 31
       495250000L,      // 32
       503250000L,      // 33
       511250000L,      // 34
       519250000L,      // 35
       527250000L,      // 36
       535250000L,      // 37
       543250000L,      // 38
       551250000L,      // 39
       559250000L,      // 40
       567250000L,      // 41
       575250000L,      // 42
       583250000L,      // 43
       591250000L,      // 44
       599250000L,      // 45
       607250000L,      // 46
       615250000L,      // 47
       623250000L,      // 48
       631250000L,      // 49
       639250000L,      // 50
       647250000L,      // 51
       655250000L,      // 52
END


Czech Republic

The frequency indexes in the Czech Republic tables are not suitable for use as channel numbers.

Czech Republic Broadcast Assignments

F_CZE_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index
        49750000L,      // 1
        57750000L,      // 2
        59250000L,      // 3
        65750000L,      // 4
        77250000L,      // 5
        85250000L,      // 6
        93250000L,      // 7
       175250000L,      // 8
       183250000L,      // 9
       191250000L,      // 10
       199250000L,      // 11
       207250000L,      // 12
       215250000L,      // 13
       223250000L,      // 14
               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used
       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69
END

Czech Republic Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


Eastern Europe

The frequency indexes in the Eastern Europe tables are not suitable for use as channel numbers.

Eastern Europe Broadcast Assignments

F_EEU_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index
        49750000L,      // 1
        59250000L,      // 2
        77250000L,      // 3
        85250000L,      // 4
        93250000L,      // 5
       175250000L,      // 6
       183250000L,      // 7
       191250000L,      // 8
       199250000L,      // 9
       207250000L,      // 10
       215250000L,      // 11
       223250000L,      // 12
               0L,      // 13 Not used
               0L,      // 14 Not used
               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used
       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69
END

Eastern Europe Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


France

The frequency indexes in the France tables are not suitable for use as channel numbers.

France Broadcast Assignments

F_FRA_BROAD RCDATA
BEGIN
        2L,             // Lowest index
        69L,            // Highest index
        55750000L,      // 2
        60500000L,      // 3
        63750000L,      // 4
       176000000L,      // 5
       184000000L,      // 6
       192000000L,      // 7
       200000000L,      // 8
       208000000L,      // 9
       216000000L,      // 10
               0L,      // 11  Not used
               0L,      // 12  Not used
               0L,      // 13  Not used
               0L,      // 14  Not used
               0L,      // 15  Not used
               0L,      // 16  Not used
               0L,      // 17  Not used
               0L,      // 18  Not used
               0L,      // 19  Not used
               0L,      // 20  Not used
       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69
END

France Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


French Overseas Territories

The frequency indexes in the French Overseas Territories broadcast table are suitable for use as channel numbers; the cable frequency indexes are not suitable for use as channel numbers.

French Overseas Territories Broadcast Assignments

F_FOT_BROAD RCDATA
BEGIN
         4L,            // Lowest channel
         9L,            // Highest channel

       175250000L,      // 4
       183250000L,      // 5
       191250000L,      // 6
       199250000L,      // 7
       207250000L,      // 8
       215250000L,      // 9
END

French Overseas Territories Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


Ireland

The frequency indexes in the Ireland tables are not suitable for use as channel numbers.

Ireland Broadcast Assignments

F_IRE_BROAD RCDATA
BEGIN
         1L,            // Lowest index
        10L,            // Highest index
        45750000L,      // A
        53750000L,      // B
        61750000L,      // C
       175250000L,      // D
       183750000L,      // E
       191250000L,      // F
       199250000L,      // G
       207250000L,      // H
       215250000L,      // I
       223250000L,      // J
END

Ireland Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


Italy

The frequency indexes in the Italy tables are not suitable for use as channel numbers.

Italy Broadcast Assignments

F_ITA_BROAD RCDATA
BEGIN
         1L,            // Lowest index
        10L,            // Highest index
        53750000L,      // 1    A
        59750000L,      // 2    B
        82750000L,      // 3    C
       175250000L,      // 4    D
       183750000L,      // 5    E
       192250000L,      // 6    F
       201250000L,      // 7    G
       210250000L,      // 8    H
       217250000L,      // 9    H1
       224250000L,      // 10   H2
END

Italy Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


Japan

The frequency indexes in the Japan tables are suitable for use as channel numbers.

Japan Broadcast Assignments

F_JAP_BROAD RCDATA
BEGIN
        1L,             // Lowest channel
        62L,            // Highest channel

        91250000L,      // 1
        97250000L,      // 2
       103250000L,      // 3
       171250000L,      // 4
       177250000L,      // 5
       183250000L,      // 6
       189250000L,      // 7
       193250000L,      // 8
       199250000L,      // 9
       205250000L,      // 10
       211250000L,      // 11
       217250000L,      // 12
       471250000L,      // 13
       477250000L,      // 14
       483250000L,      // 15
       489250000L,      // 16
       495250000L,      // 17
       501250000L,      // 18
       507250000L,      // 19
       513250000L,      // 20
       519250000L,      // 21
       525250000L,      // 22
       531250000L,      // 23
       537250000L,      // 24
       543250000L,      // 25
       549250000L,      // 26
       555250000L,      // 27
       561250000L,      // 28
       567250000L,      // 29
       573250000L,      // 30
       579250000L,      // 31
       585250000L,      // 32
       591250000L,      // 33
       597250000L,      // 34
       603250000L,      // 35
       609250000L,      // 36
       615250000L,      // 37
       621250000L,      // 38
       627250000L,      // 39
       633250000L,      // 40
       639250000L,      // 41
       645250000L,      // 42
       651250000L,      // 43
       657250000L,      // 44
       663250000L,      // 45
       669250000L,      // 46
       675250000L,      // 47
       681250000L,      // 48
       687250000L,      // 49
       693250000L,      // 50
       699250000L,      // 51
       705250000L,      // 52
       711250000L,      // 53
       717250000L,      // 54
       723250000L,      // 55
       729250000L,      // 56
       735250000L,      // 57
       741250000L,      // 58
       747250000L,      // 59
       753250000L,      // 60
       759250000L,      // 61
       765250000L,      // 62
END

Japan Cable Assignments

F_JAP_CABLE RCDATA
BEGIN
         1L,            // Lowest channel
       113L,            // Highest channel
        91250000L,      //  1
        97250000L,      //  2
       103250000L,      //  3
       109250000L,      //  4
       115250000L,      //  5
       121250000L,      //  6
       127250000L,      //  7
       133250000L,      //  8
       139250000L,      //  9
       145250000L,      // 10
       151250000L,      // 11
       157250000L,      // 12
       165250000L,      // 13
       171250000L,      // 14
       177250000L,      // 15
       183250000L,      // 16
       189250000L,      // 17
       193250000L,      // 18
       199250000L,      // 19
       205250000L,      // 20
       211250000L,      // 21
       217250000L,      // 22
       223250000L,      // 23
       231250000L,      // 24
       237250000L,      // 25
       243250000L,      // 26
       249250000L,      // 27
       253250000L,      // 28
       259250000L,      // 29
       265250000L,      // 30
       271250000L,      // 31
       277250000L,      // 32
       283250000L,      // 33
       289250000L,      // 34
       295250000L,      // 35
       301250000L,      // 36
       307250000L,      // 37
       313250000L,      // 38
       319250000L,      // 39
       325250000L,      // 40
       331250000L,      // 41
       337250000L,      // 42
       343250000L,      // 43
       349250000L,      // 44
       355250000L,      // 45
       361250000L,      // 46
       367250000L,      // 47
       373250000L,      // 48
       379250000L,      // 49
       385250000L,      // 50
       391250000L,      // 51
       397250000L,      // 52
       403250000L,      // 53
       409250000L,      // 54
       415250000L,      // 55
       421250000L,      // 56
       427250000L,      // 57
       433250000L,      // 58
       439250000L,      // 59
       445250000L,      // 60
       451250000L,      // 61
       457250000L,      // 62
       463250000L,      // 63
       471250000L,      // Test
       477250000L,      // Test
       483250000L,      // Test
       489250000L,      // Test
       495250000L,      // Test
       501250000L,      // Test
       507250000L,      // Test
       513250000L,      // Test
       519250000L,      // Test
       525250000L,      // Test
       531250000L,      // Test
       537250000L,      // Test
       543250000L,      // Test
       549250000L,      // Test
       555250000L,      // Test
       561250000L,      // Test
       567250000L,      // Test
       573250000L,      // Test
       579250000L,      // Test
       585250000L,      // Test
       591250000L,      // Test
       597250000L,      // Test
       603250000L,      // Test
       609250000L,      // Test
       615250000L,      // Test
       621250000L,      // Test
       627250000L,      // Test
       633250000L,      // Test
       639250000L,      // Test
       645250000L,      // Test
       651250000L,      // Test
       657250000L,      // Test
       663250000L,      // Test
       669250000L,      // Test
       675250000L,      // Test
       681250000L,      // Test
       687250000L,      // Test
       693250000L,      // Test
       699250000L,      // Test
       705250000L,      // Test
       711250000L,      // Test
       717250000L,      // Test
       723250000L,      // Test
       729250000L,      // Test
       735250000L,      // Test
       741250000L,      // Test
       747250000L,      // Test
       753250000L,      // Test
       759250000L,      // Test
       765250000L,      // Test
END


New Zealand

The frequency indexes in the New Zealand broadcast table are suitable for use as channel numbers; the cable frequency indexes are not suitable for use as channel numbers.

New Zealand Broadcast Assignments

F_NZ__BROAD RCDATA
BEGIN
         1L,            // Lowest channel
         11L,           // Highest channel

        45250000L,      // 1
        55250000L,      // 2
        62250000L,      // 3
       175250000L,      // 4
       182250000L,      // 5
       189250000L,      // 6
       196250000L,      // 7
       203250000L,      // 8
       210250000L,      // 9
       217250000L,      // 10
       224250000L,      // 11
END

New Zealand Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable Frequency Table is used.


Western Europe

The frequency indexes in the Western Europe tables are not suitable for use as channel numbers.

Western Europe Broadcast Assignments

F_WEU_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index

        48250000L,      // 2
        49750000L,      // 2A
        55250000L,      // 3
        62250000L,      // 4
       175250000L,      // 5
       182250000L,      // 6
       189250000L,      // 7
       196250000L,      // 8
       203250000L,      // 9
       210250000L,      // 10
       217250000L,      // 11
       224250000L,      // 12
               0L,      // 13 Not used
               0L,      // 14 Not used
               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used
       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69
END

Western Europe Cable Assignments

There was data supporting a standardized cable lineup for some countries/regions. However, for those countries/regions not reporting channel lineup data, the Unicable Frequency Table is used.

F_WEU_CABLE RCDATA
BEGIN
         1L,            // Lowest index
       107L,            // Highest index
        48250000L,      // 1    E2
        49750000L,      // 2    E2A
        55250000L,      // 3    E3
        62250000L,      // 4    E4
        69250000L,      // 5    S01
        76250000L,      // 6    S02
        83250000L,      // 7    S03
        90250000L,      // 8    S04
        97250000L,      // 9    S05
       105250000L,      // 10   S1
       112250000L,      // 11   S2
       119250000L,      // 12   S3
       126250000L,      // 13   S4
       133250000L,      // 14   S5
       140250000L,      // 15   S6
       147250000L,      // 16   S7
       154250000L,      // 17   S8
       161250000L,      // 18   S9
       168250000L,      // 19   S10
       175250000L,      // 20   E5
       182250000L,      // 21   E6
       189250000L,      // 22   E7
       196250000L,      // 23   E8
       203250000L,      // 24   E9
       210250000L,      // 25   E10
       217250000L,      // 26   E11
       224250000L,      // 27   E12
       231250000L,      // 28   S11
       238250000L,      // 29   S12
       245250000L,      // 30   S13
       252250000L,      // 31   S14
       259250000L,      // 32   S15
       266250000L,      // 33   S16
       273250000L,      // 34   S17
       280250000L,      // 35   S18
       287250000L,      // 36   S19
       294250000L,      // 37   S20
       303250000L,      // 38   S21
       311250000L,      // 39   S22
       319250000L,      // 40   S23
       327250000L,      // 41   S24
       335250000L,      // 42   S25
       343250000L,      // 43   S26
       351250000L,      // 44   S27
       359250000L,      // 45   S28
       367250000L,      // 46   S29
       375250000L,      // 47   S30
       383250000L,      // 48   S31
       391250000L,      // 49   S32
       399250000L,      // 50   S33
       407250000L,      // 51   S34
       415250000L,      // 52   S35
       423250000L,      // 53   S36
       431250000L,      // 54   S37
       439250000L,      // 55   S38
       447250000L,      // 56   S39
       455250000L,      // 57   S40
       463250000L,      // 58   S41
       471250000L,      // 59
       479250000L,      // 60
       487250000L,      // 61
       495250000L,      // 62
       503250000L,      // 63
       511250000L,      // 64
       519250000L,      // 65
       527250000L,      // 66
       535250000L,      // 67
       543250000L,      // 68
       551250000L,      // 69
       559250000L,      // 70
       567250000L,      // 71
       575250000L,      // 72
       583250000L,      // 73
       591250000L,      // 74
       599250000L,      // 75
       607250000L,      // 76
       615250000L,      // 77
       623250000L,      // 78
       631250000L,      // 79
       639250000L,      // 80
       647250000L,      // 81
       655250000L,      // 82
       663250000L,      // 83
       671250000L,      // 84
       679250000L,      // 85
       687250000L,      // 86
       695250000L,      // 87
       703250000L,      // 88
       711250000L,      // 89
       719250000L,      // 90
       727250000L,      // 91
       735250000L,      // 92
       743250000L,      // 93
       751250000L,      // 94
       759250000L,      // 95
       767250000L,      // 96
       775250000L,      // 97
       783250000L,      // 98
       791250000L,      // 99
       799250000L,      // 100
       807250000L,      // 101
       815250000L,      // 102
       823250000L,      // 103
       831250000L,      // 104
       839250000L,      // 105
       847250000L,      // 106
       855250000L,      // 107
END


Unicable Frequency Table

Due to its length, the Unicable table is not included here. The goal behind the Unicable table is to include a comprehensive set of frequencies (basically all other tables combined, plus some real-world observations) in one table to facilitate an automated channel scan without resorting to a linear search of the entire frequency spectrum. For those frequencies not covered by this table, the consumer will be required to enter a frequency through a custom user interface, resulting in a frequency override entry in the registry.


Country/Region Assignments

The number in the first column is the country/region code, as provided by international telephone dialing standards. This country/region code number can be passed to the IAMTuner::put_CountryCode method to select the television standard and default frequency mappings.

RCDATA_COUNTRYLIST RCDATA
BEGIN
// Each entry consists of:
//   Country/region code
//   Cable frequency table ID
//   Broadcast frequency table ID
//   Analog video standard
1,   F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // USA
                                                     // Anguilla
                                                     // Antigua
                                                     // Bahamas
                                                     // Barbados
                                                     // Bermuda
                                                     // British Virgin Islands
                                                     // Canada
                                                     // Cayman Islands
                                                     // Dominica
                                                     // Dominican Republic
                                                     // Grenada
                                                     // Jamaica
                                                     // Montserrat
                                                     // Nevis
                                                     // St. Kitts
                                                     // St. Vincent and the Grenadines
                                                     // Trinidad and Tobago
                                                     // Turks and Caicos Islands
                                                     // Barbuda
                                                     // Puerto Rico
                                                     // Saint Lucia
                                                     // United States Virgin Islands
2,   F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Canada
20,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Egypt
212, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,  // Morocco
213, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Algeria
216, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Tunisia
218, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Libya
220, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Gambia
221, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Senegal Republic
222, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,  // Mauritania
223, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Mali
224, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Guinea
225, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_K,  // Cote D'Ivoire
226, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Burkina Faso
227, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Niger
228, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Togo
229, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Benin
230, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Mauritius
231, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Liberia
232, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Sierra Leone
233, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Ghana
234, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Nigeria
235, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Chad
236, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Central African Republic
237, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Cameroon
238, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_NTSC_M,   // Cape Verde Islands
239, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Sao Tome and Principe
240, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,  // Equatorial Guinea
241, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Gabon
242, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_D,  // Congo
243, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Congo(DRC)
244, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_PAL_I,    // Angola
245, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_NTSC_M,   // Guinea-Bissau
246, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Diego Garcia
247, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Ascension Island
248, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Seychelle Islands
249, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Sudan
250, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,,   // Rwanda
251, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Ethiopia
252, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Somalia
253, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Djibouti
254, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Kenya
255, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Tanzania
256, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Uganda
257, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_K,  // Burundi
258, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_PAL_B,    // Mozambique
260, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Zambia
261, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Madagascar
262, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Reunion Island
263, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Zimbabwe
264, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_I,    // Namibia
265, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Malawi
266, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_I,    // Lesotho
267, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Botswana
268, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Swaziland
269, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Mayotte Island
269, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Comoros
27,  F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,    // South Africa
290, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // St. Helena
291, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Eritrea
297, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Aruba
298, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Faroe Islands
299, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Greenland
30,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Greece
31,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Netherlands
32,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Belgium
33,  F_UNI_CABLE, F_FRA_BROAD, AnalogVideo_SECAM_L,  // France
34,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Spain
350, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Gibraltar
351, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Portugal
352, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Luxembourg
353, F_UNI_CABLE, F_IRE_BROAD, AnalogVideo_PAL_I,    // Ireland
354, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Iceland
355, F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,    // Albania
356, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Malta
357, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Cyprus
358, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Finland
359, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Bulgaria
36,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Hungary
370, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Lithuania
371, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_D,  // Latvia
372, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Estonia
373, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Moldova
374, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Armenia
375, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Belarus
376, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Andorra
377, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_G,  // Monaco
378, F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,    // San Marino
380, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Ukraine
381, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Serbia and Montenegro
385, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Croatia
386, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Slovenia
387, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Bosnia and Herzegovina
389, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // F.Y.R.O.M. (Former Yugoslav Republic of Macedonia)
39,  F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,    // Italy
39,  F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,    // Vatican City
40,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_PAL_D,    // Romania
41,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Switzerland
41,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Liechtenstein
420, F_UNI_CABLE, F_CZE_BROAD, AnalogVideo_PAL_D,    // Czech Republic
421, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Slovak Republic
43,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Austria
44,  F_UK__CABLE, F_UK__BROAD, AnalogVideo_PAL_I,    // United Kingdom
45,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Denmark
46,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Sweden
47,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Norway
48,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_PAL_B,    // Poland
49,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Germany
500, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,    // Falkland Islands (Islas Malvinas)
501, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Belize
502, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Guatemala
503, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // El Salvador
504, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Honduras
505, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Nicaragua
506, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Costa Rica
507, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Panama
508, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // St. Pierre and Miquelon
509, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Haiti
51,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Peru
52,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Mexico
53,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Cuba
53,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Guantanamo Bay
54,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,    // Argentina
55,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_M,    // Brazil
56,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Chile
57,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Colombia
58,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Bolivarian Republic of Venezuela
590, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Guadeloupe
590, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // French Antilles
591, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,    // Bolivia
592, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Guyana
593, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Ecuador
594, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // French Guiana
595, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,    // Paraguay
596, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // Martinique
597, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Suriname
598, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,    // Uruguay
599, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Netherlands Antilles
60,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Malaysia
61,  F_UNI_CABLE, F_OZ__BROAD, AnalogVideo_PAL_B,    // Australia
61,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Cocos-Keeling Islands
62,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Indonesia
63,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Philippines
64,  F_UNI_CABLE, F_NZ__BROAD, AnalogVideo_PAL_B,    // New Zealand
65,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Singapore
66,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Thailand
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Saipan Island
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Rota Island
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Tinian Island
671, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Guam
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Christmas Island
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Australian Antarctic Territory
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Norfolk Island
673, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Brunei
674, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Nauru
675, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Papua New Guinea
676, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Tonga
677, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Solomon Islands
678, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Vanuatu
679, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Fiji Islands
680, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Palau
681, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,  // Wallis and Futuna Islands
682, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Cook Islands
683, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Niue
684, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Territory of American Samoa
685, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Samoa
686, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Kiribati Republic
687, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // New Caledonia
688, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Tuvalu
689, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,  // French Polynesia
690, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Tokelau
691, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Micronesia
692, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Marshall Islands
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Russia
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Kazakhstan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Kyrgyzstan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Tajikistan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Turkmenistan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Uzbekistan
81,  F_JAP_CABLE, F_JAP_BROAD, AnalogVideo_NTSC_M_J, // Japan
82,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Korea (South)
84,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Vietnam
850, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Korea (North)
852, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,    // Hong Kong SAR
853, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,    // Macao SAR
855, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Cambodia
856, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Laos
86,  F_CHN_CABLE, F_CHN_BROAD, AnalogVideo_PAL_D,    // China
871, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // INMARSAT (Atlantic-East)
872, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // INMARSAT (Pacific)
873, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // INMARSAT (Indian)
874, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // INMARSAT (Atlantic-West)
880, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Bangladesh
886, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Taiwan
90,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Turkey
91,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // India
92,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Pakistan
93,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Afghanistan
94,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Sri Lanka
95,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Myanmar
960, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Maldives
961, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Lebanon
962, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Jordan
963, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Syria
964, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Iraq
965, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Kuwait
966, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Saudi Arabia
967, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Yemen
968, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Oman
971, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // United Arab Emirates
972, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Israel
973, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Bahrain
974, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,    // Qatar
975, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,   // Bhutan
976, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Mongolia
977, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,    // Nepal
98,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,  // Iran
994, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Azerbaijan
995, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,  // Georgia
0,   0,           0,           0                     // End of the list

END


GraphEdit File Format

When the GraphEdit utility saves a DirectShow filter graph, it creates a storage files with a .grf extension. The storage file contains a single stream called ActiveMovieGraph. This stream contains information about all of the filters, filter names, file names, connections, and so forth.

The following grammar describes the syntax of the graph within the stream, using a modified BNF (Backus-Naur Form) syntax:

<graph> ::= 0003\r\n<filters><connections><clock>END | 0002\r\n<filters><connections>END
<filters> ::= FILTERS<b> [<filter list><b>]
<filter list> ::= <filter><b> [<filter list>]
<filter> ::= <filter id><b><name><b><class id><b>[<file>]<length><b1><filter data>
<class id> ::= <guid>
<file> ::= SOURCE <name><b> | SINK <name><b>
<connections> ::= CONNECTIONS<b> {<connection><b>}
<connection> ::= <filter id><b><pin id><b><filter id><b><pin id><b><media type>
<filter id> ::= <id>
<pin id> ::= <name>
<media type> ::= <sample size><major type><b><subtype><b><flags><format>
<major type> ::= <guid>
<subtype> ::= <guid>
<flags> ::= <fixed sample size><b><temporal compression><b>
<fixed sample size> ::= 1 | 0
<temporal compression> ::= 1 | 0
<format> ::= <length><b1><format type><b><length><b1><format data>
<format type> ::= <guid>
<format data> ::= { binary_data }
<clock> ::= CLOCK <b><required><b><clockid>\r\n
<required> ::= 1 | 0
<clockid> ::= <filter id> | <class id>
<name> ::= quote_symbol { any_non_quote_character } quote_symbol
<length> ::= unsigned decimal number (as a string), indicating the number
             of bytes of data in the following token.
<guid> ::= GUID in string format. for example: {CF49D4E0-1115-11CE-B03A-0020AF0BA770}
<b> ::= { space_character } { \t } { \r } { \n } { <b> }
<b1> ::= space_character
<id> ::= integer (as a string), such as 0001

On output there will be a new line ("\r\n") per filter, one per connection, and one for each of the keywords FILTERS and CONNECTIONS. Each other case of <b> will be a single space. The keywords FILTERS, CONNECTIONS, and END are not localizable. Note also that the filter data and the format data are binary, so they might contain incorrect line breaks, null values, and so on. The stream uses wide characters.

The following shows a typical graph. (The connection lines have been broken for clarity, and the binary data omitted.)

003
FILTERS
0001 "C:\SomeFile.avi" {E436EBB5-524F-11CE-9F53-0020AF0BA770} SOURCE "C:\SomeFile.avi" 0000000000
0002 "AVI Splitter" {1B544C20-FD0B-11CE-8C63-00AA0044B51E} 0000000000
0003 "AVI Decompressor" {CF49D4E0-1115-11CE-B03A-0020AF0BA770} 0000000000
0004 "Video Renderer" {70E102B0-5556-11CE-97C0-00AA0055595A} 0000000000
CONNECTIONS
0001 "Output" 0002 "input pin" 0000000288
   {E436EB83-524F-11CE-9F53-0020AF0BA770}
   {E436EB88-524F-11CE-9F53-0020AF0BA770} 1 0 0000000001
   {00000000-0000-0000-0000-000000000000} 0000000000
0002 "Stream 00" 0003 "In" 0000000376
   {73646976-0000-0010-8000-00AA00389B71}
   {64697663-0000-0010-8000-00AA00389B71} 0 0 0000000001
   {05589F80-C356-11CE-BF01-00AA0055595A} 0000000088 <binary data>
0003 "Out" 0004 "In" 0000000376
    {73646976-0000-0010-8000-00AA00389B71}
    {E436EB7D-524F-11CE-9F53-0020AF0BA770} 1 0 0000129600
    {05589F80-C356-11CE-BF01-00AA0055595A} 0000000088 <binary data>
CLOCK 1 0000
END

See Also

  • Simulating Graph Building with GraphEdit


Previous DirectShow What's New Sections

This section contains the What's New in DirectShow topics for previous releases.

  • What's New in DirectShow 8.0?
  • What's New in DirectShow 8.1?
  • What's New for Windows XP?


What's New in DirectShow 8.0?

Windows Media Format Support

Two new filters enable DirectShow applications to read and write files in Microsoft® Windows Media™ Format. The ASF Reader filter reads and parses Windows Media Format files. The ASF Writer filter writes Windows Media Format files; it also does the necessary multiplexing and compressing. DirectShow and the Windows Media Software Development Kit offer complementary solutions for writing applications that create and playback Windows Media Format stream.

DirectShow Editing Services

DirectShow Editing Services is an API that supports video editing and sequenced video playback. You can use DES to create a wide range of applications. For example, with just a few method calls, you can sequence together audio and video clips, add an effect, and play back the result. Or, you can create a entire video editing system. DES is built on top of the core DirectShow architecture. It provides a set of interfaces designed specifically for nonlinear video editing.

DES replaces cutlists, which are no longer supported.

New DVD Support

Two new interfaces, IDVDControl2 and IDVDInfo2, greatly expand the functionality of the DVD Navigator. The new MSWebDVD ActiveX® control makes this functionality available to script-based applications. New DVD features include the following, among others:

  • Karaoke multichannel audio support.
  • AC-3 support for S/PDIF out.
  • Audio volume control through the IBasicAudio interface.
  • Support for frame stepping and frame-accurate seeking.
  • Simplified access to DVD text information strings.
  • Improved support for parental management controls.

New MPEG-2 Transport and Program Stream Support

A new filter, the MPEG-2 Demultiplexer, provides support for MPEG-2 transport streams and program streams in push-mode (for receiving data from live sources).

Microsoft® TV Technologies (Broadcast Driver Architecture)

Microsoft® TV Technologies includes support for the new Broadcast Driver Architecture (BDA) and the Microsoft Tuning Model. The Broadcast Driver Architecture defines a framework that supports various component topologies for receiving digital and analog television. It includes software components for network configuration and control, demultiplexing, table parsing and IP Data delivery for the main digital TV standards including DVB and ATSC. The Tuning Model is a set of objects that enables applications to easily tune across various network types in a simple and uniform manner.

DirectX Video Acceleration

For decoder developers: DirectX Video Acceleration is an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for hardware acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. It provides an interface definition focused on support of MPEG-2 "main profile" video (formally ITU-T H.262 | ISO/IEC 13818-2), but is also intended to support other key video codecs (for example ITU-T Recommendations H.263 and H.261, and MPEG-1 and MPEG-4).

New Filters

DirectShow includes several new filters:

  • ASF Writer: Writes Windows Media Format files.
  • ASF Reader: Reads and parses Windows Media Format files.
  • MJPEG Decompressor: Decodes a video stream from motion JPEG to uncompressed video
  • MJPEG Compressor: Compresses an uncompressed video stream using motion JPEG compression.
  • MPEG-2 Demultiplexer: Demultiplexes MPEG-2 transport and program streams from live sources.
  • Null Renderer: Discards samples without displaying or rendering the sample data. Applications can use this filter to discard data from a stream.
  • Sample Grabber: Retrieves media samples as they move through the filter graph. Applications can use this filter to obtain poster frames or other media data.

New Filter Graph Features

The filter graph manager supports several new features:

  • Dynamic Graph Building. You can now make changes to the filter graph while the graph is running. Previously, to add or remove filters, an application had to stop the graph, which interrupts the flow of data. For more information, see Dynamic Graph Building.
  • Live Source Synchronization. DirectShow now supports synchronization of live sources. For example, a live audio stream can be synchronized with a live video stream. For more information, see Time and Clocks in DirectShow.
  • Frame Stepping. The filter graph manager exposes the new IVideoFrameStep interface, which enables an application to step through a video file one frame at a time.

Changes to the Build Environment

A new header file, DShow.h, replaces the previous header file, Streams.h

The filter base classes now appear in the \Samples\BaseClasses directory under the SDK root directory. To use them, you must build the base-class library and link to it in your project.

New GraphEdit Features

GraphEdit includes some new features that enhance its use as a testing and debugging tool.

  • "Graph Spy": Now GraphEdit can load a filter graph created by an external process. With this feature, you can see exactly what filter graph your application builds, with only a minimal amount of additional code in your application. For more information about this feature, see Loading a Graph From an External Process.
  • Filter Information: When you choose Insert Filters from the Graph menu, the list of filters now includes each filter's registration information, including merit, number of pins, and the media types registered for each pin. To see this information, click the plus (+) symbol next to each filter in the tree view.

DirectX Media Objects

DirectX Media Objects (DMOs) are a new way to write data-streaming components. Like DirectShow filters, DMOs take input data and use it to produce output data. However, the application programming interfaces (APIs) for DMOs are much simpler than the corresponding APIs for DirectShow. As a result, DMOs are easier to create, test, and use than DirectShow filters.

DMOs are fully compatible with DirectShow. You can use a DMO like a filter when you need the services that DirectShow provides, such as graph synchronization, intelligent connection, automatic handling of data flow, and thread management. However, DMOs do not require a filter graph, so applications can use DMOs without using DirectShow.

Media Parameters

Media parameters are a new set of APIs that support run-time changes to an object's properties. They offer precise control over properties that change rapidly and require both high performance and repeatability. They enable a property to follow an exact curve, such as a sine wave or inverse-square curve, in real time.

Using media parameters, data transform objects can support a standard interface for controlling run-time behavior. They are particularly useful for audio effect DMOs and filters. For example, in an echo effect, the ratio of wet (processed) signal to dry (unprocessed) signal can follow a smooth curve. This type of behavior is critical in audio engineering, to avoid introducing artifacts into the recording.


What's New in DirectShow 8.1?

New and Improved Samples

In DirectX 8.1, DirectShow adds some great new samples and also incorporates many enhancements and refinements to the existing DirectX 8.0 samples. Improvements to existing samples include:

  • New features and functionality
  • Numerous bug fixes, including Windows XP support issues
  • UNICODE and IA64 support
  • Clean compilation with Warning Level 4
  • Improved video window repainting for Jukebox-style applications
  • Updated resource files and version information blocks
  • Digital Video sample (Capture\DVApp) was rewritten to take advantage of the ICaptureGraphBuilder2 interface to build its graphs.

New samples for DirectX 8.1 include:

  • Audio Capture (Capture\AudioCap)
  • DMO-enabled Player (Players\PlayDMO)
  • DMO Enumerator (Misc\DMOEnum)
  • Filter Mapper (Misc\Mapper)
  • Sample Grabber Filter (Filters\Grabber) (modified from DX8 version)
  • PlayCap with Moniker (Capture\PlayCapMoniker) (Note: RenderFile moniker support is removed in DirectX 9.0.)
  • Still Image Viewer (Players\StillView)
  • Utility source code and routines in the DirectShow\Common directory

Updated Documentation

The DirectShow documentation has been significantly enhanced for DirectX 8.1. It adds information for the new features available in Windows XP, and expands on previously presented material for the Microsoft TV Technologies. For Microsoft® Windows® XP Service Pack 1, miscellaneous improvements have been made to video capture and filter development documentation.

Modified SampleGrabber Filter Source Code

There have been several requests for Microsoft to publish the source code for the popular SampleGrabber filter. To that end, we now provide a modified (simpler) version of the sample grabber filter, which uses a new GUID and new CLSID to prevent collisions with the original DirectX 8.0 filter. You can review and modify the source code for this filter and use it in your own applications. See the Filters\Grabber directory for more information.

Run-Time Improvements

The DirectX 8.1 binaries and redist files have received various bug fixes since the DirectX 8.0 release, including a large subset of the modifications that were made for Windows XP.

Revised GraphEdit Application

The GraphEdit utility benefits from several improvements, particularly with respect to its user interface, menus, and toolbar. These improvements include:

  • Graph resizing code (View->xxx %) handles all sizes correctly, and you can resize your graphs using the menu, keyboard +/- keys, and Ctrl+MouseWheel.
  • The option to disable the seek bar (and its timed updates), which has been known to cause difficulty when debugging filters with GraphEdit.
  • Better file source filter sizing. To preserve screen real estate, source and file writer filters displayed in GraphEdit will now only display their corresponding filenames as the filter name, instead of displaying the fully qualified path name. For example, a file source for the file C:\DXSDK\samples\Multimedia\Media\lake.mpg" would display "lake.mpg".


What's New for Windows XP?

Microsoft TV Technologies (Broadcast Driver Architecture)

Windows XP and DirectX 8.1 Microsoft TV Technologies includes support for the new Broadcast Driver Architecture (BDA) and the Microsoft Unified Tuning Model. The Broadcast Driver Architecture defines a framework that supports various component topologies for receiving digital and analog television. It includes software components for network configuration and control, demultiplexing, table parsing and IP Data delivery for the main digital TV standards including DVB and ATSC. The Microsoft Unified Tuning Model is a set of objects that enables applications to easily tune across various network types in a simple and uniform manner.

Windows XP only: The new Video Control greatly simplifies TV application development and provides Automation support for both digital and analog TV tuners. It supports the new timeshifting feature available only on Service Pack 1 for Windows XP. (Note that the Guide Store and Conditional Access components, which were present in the original release of Windows XP, have been removed from Service Pack 1.)

  • For more information, see the following topics:
  • Microsoft TV Technologies
  • Microsoft TV Technologies C++ Reference
  • Microsoft TV Technologies Visual Basic and Script Reference

Video Mixing Renderer

Windows XP only: The new Video Mixing Renderer Filter 7 (VMR-7) greatly improves video playback performance and provides enhanced video features to application developers of television and DVD applications. It also enables new presentation capabilities by enabling video applications to utilize the 3D capabilities in graphics hardware.

Other New Filters for Windows XP

Because the Video Mixing Renderer provides different interfaces from the old Video Renderer, some filters that connect upstream of the VMR have been reimplemented in new versions to take advantage of the new interfaces. The following new filters are used only in graphs where the VMR is present: Video Port Manager and Line 21 Decoder 2 (see Line 21 Decoder Filter).

Windows XP provide a new WDM driver for D-VHS and MPEG camcorder devices, MSTape. DirectShow applications can access these devices through software interfaces, which communicate to the driver.

New MPEG-2 Transport and Program Stream Support

The MPEG-2 Demultiplexer now provides support for MPEG-2 transport streams and program streams in both push and pull mode. The MPEG-2 Splitter filter, which previously handled MPEG-2 program streams in pull mode, is deprecated in Microsoft Windows XP. For more information, see MPEG-2 Demultiplexer.

Windows XP Support in Header Files

DirectX 8.1 and later provides support for the following Windows platforms:

  • Windows 98, Windows 98 Second Edition, and Windows Millennium Edition
  • Windows 2000
  • Windows XP

Because Windows XP adds new functionality which is not present on downlevel systems, many of the headers in the \DXSDK\include directory have been revised to allow developers to use this functionality when desired, with full downlevel compatibility. This is achieved by adding the following conditionally compiled sections to the relevant header files:

#if (WINVER >= 0x501)
    // Windows XP content.
#else
    // Downlevel content.
#endif

To enable Windows XP features and to utilize the new portions of the affected headers, set the Windows version to 0x501 (the Windows XP version) in your Visual C++ project files. If the Windows version is less than 0x501, the original DirectX 8.0 content will be used to allow full backward compatibility with the DirectX 8.0 SDK. Similar improvements were also made to the Interface Definition Files (IDLs) in the \DXSDK\include\DShowIDL directory.

See the Samples\DirectShow and Samples\DirectShow_WinXP directories for more information.

New Samples for Windows XP-Based Applications

Windows XP provide new functionality that is not present in downlevel operating systems (Windows 9x, Windows 2000). The DirectShow_WinXP directory provides samples to demonstrate using the new Video Mixing Renderer and the new Microsoft Video Control (for use with the Windows Driver Model and Broadcast Driver Architecture). The new samples include:

  • - Video Control - C++, Visual Basic, and HTML samples showing how to render ATSC, DVB, and analog television in a Windows application. The new Video Control encapsulates much of the new functionality and aids developers in creating television-enabled applications. It also supports file playback and DVD navigation.
  • - Video Mixing Renderer (VMR)
    • Cube
    • Renderless
    • Text Player
    • VMR Mix
    • VMR Player
    • VMR Exclusive Mode (VMRXcl)

See the DirectShow_WinXP directory for more detailed information about these new samples.


Controlling Filter Graphs Using C

If you are writing your Microsoft® DirectShow® application in C (rather than C++), you must use a vtable pointer to call methods. The following example illustrates how to call the IUnknown::QueryInterface method from an application written in C:

pGraph->lpVtbl->QueryInterface(pGraph, &IID_IMediaEvent, (void **)&pEvent);

The following shows the equivalent call in C++:

pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

In C, interfaces are defined as structures. The lpVtbl member is a pointer to a table of interface methods (the vtable). All methods take an additional parameter, which is a pointer to the interface.


Deprecated Interfaces

The following interfaces have been deprecated. They will continue to be supported for backward compatibility with existing applications, but new applications should not use them.

  • IAMAnalogVideoEncoder
  • IAMDevMemoryAllocator
  • IAMDevMemoryControl
  • IAMFilterData
  • IAMovieSetup
  • IAMPhysicalPinInfo
  • IAMTunerNotification
  • IAMTVAudioNotification
  • ICaptureGraphBuilder
  • IDirectDraw3
  • IDirectDrawFactory
  • IDrawVideoImage
  • IDvdControl
  • IDvdInfo
  • IEnumRegFilters
  • IFilterMapper
  • IFullScreenVideo — See IFullScreenVideoEx


IAMAnalogVideoEncoder Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications and filters should not use it.

The IAMAnalogVideoEncoder interface might be implemented by a hardware video encoder in video capture operations when an application is streaming data to disk and sending it back out to videotape. It provides methods for setting the video standard and enabling or disabling closed captioning and copy protection.

In addition to the methods inherited from IUnknown, the IAMAnalogVideoEncoder interface exposes the following methods.

Method | Description
get_AvailableTVFormats | Retrieves the analog video standards (NTSC/M, PAL/B, SECAM/K1, and so on) supported by the encoder.
get_CCEnable | Determines whether closed captioning is currently enabled.
get_CopyProtection | Determines whether copy protection is currently enabled.
get_TVFormat | Retrieves the analog video standard that the encoder is currently set to.
put_CCEnable | Enables or disables closed captioning.
put_CopyProtection | Sets the level of copy protection for the encoder.
put_TVFormat | Sets the encoder to a particular analog video standard.


IAMAnalogVideoEncoder::get_AvailableTVFormats

Note The IAMAnalogVideoEncoder interface is deprecated.

The get_AvailableTVFormats method retrieves the analog video standards (NTSC/M, PAL/B, SECAM/K1, and so on) supported by the encoder.

Syntax

HRESULT get_AvailableTVFormats(
  long *lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard

[out] Specifies a pointer to a long integer to receive the available TV formats. The formats are defined in the AnalogVideoStandard enumeration and the available formats have been combined in this integer with a bitwise OR.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMAnalogVideoEncoder::get_CCEnable

Note The IAMAnalogVideoEncoder interface is deprecated.

The get_CCEnable determines whether closed captioning on the encoder is currently enabled.

Syntax

HRESULT get_CCEnable(
  long *lCCEnable
);

Parameters

lCCEnable

[out] Specifies a pointer to a long integer to receive the current status of closed captioning on the encoder.

Value | Description
1 | Closed captioning enabled.
0 | Closed captioning disabled.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMAnalogVideoEncoder::get_CopyProtection

Note The IAMAnalogVideoEncoder interface is deprecated.

The get_CopyProtection method determines whether copy protection is currently enabled on the encoder.

Syntax

HRESULT get_CopyProtection(
  long *lVideoCopyProtection
);

Parameters

lVideoCopyProtection

[out] Specifies a pointer to a long integer to receive the current copy protection level, as defined in the AM_COPY_MACROVISION_LEVEL enumeration.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMAnalogVideoEncoder::get_TVFormat

Note The IAMAnalogVideoEncoder interface is deprecated.

The get_TVFormat method retrieves the analog video standard that the encoder is currently set to (NTSC/M, PAL/B, SECAM/K1, and so on).

Syntax

HRESULT get_TVFormat(
  long *plAnalogVideoStandard
);

Parameters

plAnalogVideoStandard

[out] Specifies a pointer to a long integer to receive the encoder's current video standard.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

Remarks

Possible values and their meaning are defined in the AnalogVideoStandard enumeration.

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMAnalogVideoEncoder::put_CCEnable

Note The IAMAnalogVideoEncoder interface is deprecated.

The put_CCEnable method enables or disables closed captioning.

Syntax

HRESULT put_CCEnable(
  long lCCEnable
);

Parameters

lCCEnable

[in] Specifies whether closed captioning is on or off as a long integer.

Value | Description
1 | Closed captioning is on.
0 | Closed captioning is off.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • IAMAnalogVideoEncoder Interface
  • Error and Success Codes


IAMAnalogVideoEncoder::put_CopyProtection

Note The IAMAnalogVideoEncoder interface is deprecated.

The put_CopyProtection method sets the level of copy protection for the encoder.

Syntax

HRESULT put_CopyProtection(
  long lVideoCopyProtection
);

Parameters

lVideoCopyProtection

[in] Specifies the level of copy protection as a long integer with a value as defined in the AM_COPY_MACROVISION_LEVEL enumeration.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMAnalogVideoEncoder::put_TVFormat

Note The IAMAnalogVideoEncoder interface is deprecated.

The put_TVFormat method sets the encoder to a particular analog video standard (NTSC/M, PAL/B, SECAM/K1, and so on).

Syntax

HRESULT put_TVFormat(
  long lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard

[in] Specifies the video standard to set in the encoder as a long integer containing a value as defined in the AnalogVideoStandard enumeration.

Return Values

When this method succeeds, it returns S_OK. Otherwise it returns an HRESULT error code.

See Also

  • Error and Success Codes
  • IAMAnalogVideoEncoder Interface


IAMDevMemoryAllocator Interface

Note This interface has been deprecated. It was defined to support older hardware decoders that required AVI files to be read into directly hardware memory. The interface enables the AVI parser to allocate memory from the downstream filter but still provide its own allocator. There should be no need for any newer devices to support this interface.

Implement this interface when your pin must support the creation of on-board memory allocators. Source filters that are aware of on-board memory and need to create their own allocators should query for this interface, request an amount of memory and then create an allocator (aggregating the device memory control object). Source filters that don't need to create their own allocator could just use the allocator of the downstream pin (which also aggregates the device memory control object). The hardware-based filter can confirm the usage of its on-board memory by calling methods on the aggregated allocator.

Use this interface when applications need to control the memory of codecs with on-board memory.

In addition to the methods inherited from IUnknown, the IAMDevMemoryAllocator interface exposes the following methods.

Method | Description
Alloc | Allocates a memory buffer.
CheckMemory | Tests whether the particular device of the allocator allocated a memory pointer.
Free | Frees the previously allocated memory.
GetDevMemoryObject | Retrieves an IUnknown interface pointer to a device memory control object that can be aggregated with a custom allocator.
GetInfo | Retrieves information about the memory capabilities.


IAMDevMemoryAllocator::Alloc

Note The IAMDevMemoryAllocator interface is deprecated.

Allocates a memory buffer.

Syntax

HRESULT Alloc(
    BYTE **ppBuffer,
    DWORD *pdwcbBuffer
);

Parameters

ppBuffer

[out] Pointer that will receive the address of the allocated memory buffer.

pdwcbBuffer

[in, out] Pointer to a DWORD whose input value is the number of bytes to allocate and whose output value is the actual number of bytes allocated.

Return Value

Returns S_OK if the desired quantity of memory was allocated, S_FALSE if memory was unavailable.

Remarks

Call this method to allocate a block of memory from the available pool.

See Also

  • Error and Success Codes
  • IAMDevMemoryAllocator Interface
  • IAMDevMemoryAllocator::Free


IAMDevMemoryAllocator::CheckMemory

Note The IAMDevMemoryAllocator interface is deprecated.

Tests whether the specific instance (device) of the allocator allocated a memory pointer.

Syntax

HRESULT CheckMemory(
    const BYTE *pBuffer
);

Parameters

pBuffer

[in] Pointer to the allocated memory buffer's address.

Return Value

Returns S_OK if the on-board allocator allocated the memory, or S_FALSE if not. Memory that is on the particular device but not allocated will also return S_FALSE.

Remarks

The hardware filter typically uses this method to test whether the pointer actually points to on-board memory.

See Also

  • Error and Success Codes
  • IAMDevMemoryAllocator Interface


IAMDevMemoryAllocator::Free

Note The IAMDevMemoryAllocator interface is deprecated.

Frees the previously allocated memory.

Syntax

HRESULT Free(
    BYTE *pBuffer
);

Parameters

pBuffer

[in] Pointer to the allocated memory.

Return Value

Returns E_INVALIDARG if the specified allocator didn't allocate the memory (that is, CheckMemory fails).

Remarks

This method frees a block of memory from the pool.

See Also

  • Error and Success Codes
  • IAMDevMemoryAllocator Interface


IAMDevMemoryAllocator::GetDevMemoryObject

Note The IAMDevMemoryAllocator interface is deprecated.

Retrieves an IUnknown interface pointer to a device memory control object that can be aggregated with a custom allocator.

Syntax

HRESULT GetDevMemoryObject(
    IUnknown **ppUnkInner,
    IUnknown *pUnkOuter
);

Parameters

ppUnkInner

[out] Address of a pointer to the newly created control object's own IUnknown. This inner IUnknown interface should be released when the outer object is destroyed. The custom allocator should call the QueryInterface method on this pointer to obtain the IAMDevMemoryControl interface.

pUnkOuter

[in] Pointer to the custom allocator's own IUnknown interface. This interface aggregates the device memory control object inside the custom allocator.

Return Value

Returns an HRESULT value.

Remarks

The device memory control object is necessary to aggregate with the custom allocator, because renderers that require the use of on-board memory will query for IAMDevMemoryControl when they receive a new allocator, to verify that the memory is from the same device. This occurs because the hardware filter will receive an IMemAllocator object, which might or might not use the on-board memory. To decide if it is a compatible allocator, the object would query for the IAMDevMemoryControl interface to access specific methods. The IAMDevMemoryControl creates an aggregated object that implements the methods of IAMDevMemoryControl (these are often hardware-specific).

See COM documentation for rules on how the outer object implements aggregation.

See Also

  • Error and Success Codes
  • IAMDevMemoryAllocator Interface


IAMDevMemoryAllocator::GetInfo

Note The IAMDevMemoryAllocator interface is deprecated.

Retrieves information about the memory capabilities.

Syntax

HRESULT GetInfo(
    DWORD *pdwcbTotalFree,
    DWORD *pdwcbLargestFree,
    DWORD *pdwcbTotalMemory,
    DWORD *pdwcbMinimumChunk
);

Parameters

pdwcbTotalFree

[out] Pointer to the total free memory size.

pdwcbLargestFree

[out] Pointer to the returned largest free memory size.

pdwcbTotalMemory

[out] Pointer to the returned total memory size.

pdwcbMinimumChunk

[out] Pointer to the returned minimum chunk size, giving granularity and alignment rules.

Return Value

Returns an HRESULT value.

Remarks

Use this method to find out the total amount of memory available. This method returns values for the entire on-board memory that is available on that device. If multiple filters (devices) share the memory, it will return the amount available to that specific device, which might be a portion of the total amount of on-board memory. This amount will be implementation-specific. For example, the on-board memory manager on the codec might be able to access all 32 megabytes (MB) of memory on the card. However, individual pin implementations of IAMDevMemoryAllocator only report a portion of this memory.

See Also

  • Error and Success Codes
  • IAMDevMemoryAllocator Interface


IAMDevMemoryControl Interface

Note This interface has been deprecated. It was defined to support certain older hardware decoders that required AVI files to be read directly into hardware memory. The interface enables the AVI parser to allocate memory from the downstream filter but still provide its own allocator. There should be no need for any newer devices to support this interface.

A device memory control object supports IAMDevMemoryControl. This object is aggregated with an IMemAllocator object that is used in the connection. Typically, filters will call the IAMDevMemoryAllocator::GetDevMemoryObject method to obtain a pointer to this interface.

Implement this interface with the IAMDevMemoryAllocator interface when pins need to have greater control of memory allocation.

Use this interface to synchronize the completion of writing data to a memory allocator, and to get the device ID of the on-board memory allocator.

In addition to the methods inherited from IUnknown, the IAMDevMemoryControlinterface exposes the following methods.

Method | Description
GetDevId | Retrieves the device ID of the on-board memory allocator.
QueryWriteSync | Checks if the memory supported by the allocator requires the use of the WriteSync method.
WriteSync | Used to synchronize with the completed write operation by returning when any data being written to the specified allocator region is fully written into the memory.


IAMDevMemoryControl::GetDevId

Note The IAMDevMemoryControl interface is deprecated.

Retrieves the device ID of the on-board memory allocator.

Syntax

HRESULT GetDevId(
  DWORD *pdwDevId
);

Parameters

pdwDevId

[out] Pointer to the device ID.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method retrieves a unique ID that the hardware filter can use to verify that the specified allocator passed uses its on-board memory (because there can be more than one). The ID will be the same one as used to create the allocator object (using CoCreateInstance). For another filter to be able to use the on-board memory, it must have the same device ID as the on-board memory allocator.

See Also

  • Error and Success Codes
  • IAMDevMemoryControl Interface


IAMDevMemoryControl::QueryWriteSync

Note The IAMDevMemoryControl interface is deprecated.

Checks if the memory supported by the allocator requires the use of the IAMDevMemoryControl::WriteSync method.

Syntax

HRESULT QueryWriteSync(void);

Return Value

Returns S_OK if the method is required, or S_FALSE otherwise.

Remarks

Not all on-board memory needs to have WriteSync called to synchronize with the completed write. This method is used to check if the call is necessary.

See Also

  • Error and Success Codes
  • IAMDevMemoryControl Interface


IAMDevMemoryControl::WriteSync

Note The IAMDevMemoryControl interface is deprecated.

Used to synchronize with the completed write. This method returns when any data being written to the particular allocator region is fully written into the memory.

Syntax

HRESULT WriteSync(void);

Return Value

Returns an HRESULT value. Possible values include the following:

Value | Description
E_FAIL | A time-out has occurred without this method confirming that data was written.
S_OK | The data was successfully written into memory.
VFW_E_NOT_COMMITTED | The allocator hasn't called the IMemAllocator::Commit method.

Remarks

This method guarantees that all prior write operations to allocated memory have succeeded. Subsequent memory write operations require another call to WriteSync.

This method is implementation dependent, and is used (when necessary) to synchronize memory write operations to the memory. The driver of the on-board memory provides the implementation.

The IAMDevMemoryControl interface is typically found on memory that is accessed through a Peripheral Component Interconnect (PCI) bridge. (A PCI is a local bus for personal computers that provides a high-speed data path between the processor and peripheral devices.) Memory behind a PCI bridge must be synchronized after a memory write operation completes, if another device will access that memory from behind the PCI bridge. This is because the host access to the memory is buffered through the PCI bridge FIFO (first in first out), and the host will assume the write is completed before the bridge actually writes the data. A subsequent action by a device behind the bridge, such as a SCSI controller, might read the memory before the write is completed, if the IAMDevMemoryControl::WriteSync method is not called.

See Also

  • Error and Success Codes
  • IAMDevMemoryControl Interface


IAMFilterData Interface

Note This interface has been deprecated. New applications should use the IFilterMapper2 interface instead.

The IAMFilterData interface converts filter information to packed binary data, which can be stored in the registry. The Filter Mapper object exposes this interface.

In addition to the methods inherited from IUnknown, the IAMFilterData interface exposes the following methods.

Method | Description
CreateFilterData | Creates binary registry data for a filter.
ParseFilterData | Unpacks the binary registry data for a filter.

Requirements

Include fil_data.h, which is located in the Mapper Sample directory.


IAMFilterData::CreateFilterData

Note This interface has been deprecated. New applications should not use it.

The CreateFilterData method creates binary registry data for a filter. This data can be written to the registry as a REG_BINARY subkey named FilterData, under the filter's CLSID key.

There is typically no reason for an application to call this method. The IFilterMapper2::RegisterFilter method automatically creates the binary data and adds it to the correct location in the registry. For more information, see How to Register DirectShow Filters.

Syntax

HRESULT CreateFilterData(
    REGFILTER2 *prf2,
    BYTE **prgbFilterData,
    ULONG *pcb
);

Parameters

prf2

[in] Pointer to a REGFILTER2 structure that contains the filter information.

prgbFilterData

[out] Address of a variable that receives a pointer to the binary data. The method allocates the memory for the data. The caller must release the memory by calling the CoTaskMemFree method.

pcb

[out] Pointer to a variable that receives the size of the binary data, in bytes.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Requirements

Include fil_data.h, which is located in the Mapper Sample directory.

See Also

  • IAMFilterData Interface


IAMFilterData::ParseFilterData

Note This interface has been deprecated. New applications should not use it.

The ParseFilterData method unpacks the binary registry data for a filter.

There is typically no reason for an application to call this method. The IFilterMapper2::EnumMatchingFilters method provides a more convenient way to access the filter registry data.

Syntax

HRESULT ParseFilterData(
    BYTE *rgbFilterData,
    ULONG cb,
    BYTE **prgbRegFilter2
);

Parameters

rgbFilterData

[in] Pointer to the binary registry data.

cb

[in] Specifies the size of the binary data, in bytes.

prgbRegFilter2

[out] Address of a variable that receives a pointer to the unpacked data. When the method returns, cast this pointer to a REGFILTER2 type to access the filter data. The caller must release the memory by calling the CoTaskMemFree method.

Return Values

If the method succeeds, it returns S_OK. If it fails, it returns an error code.

Requirements

Include fil_data.h, which is located in the Mapper Sample directory.

See Also

  • IAMFilterData Interface


IAMovieSetup Interface

Note This interface has been deprecated. It is used by two obsolete functions, AMovieDllRegisterServer and AMovieDllUnregisterServer. These functions are now replaced by AMovieDllRegisterServer2, which does not require IAMovieSetup. However, IAMovieSetup will continue to be supported for backward compatibility with existing applications.

In Microsoft® ActiveMovie® 1.0, filters implemented self-registration as follows:

  • Inside the DllRegisterServer function, the filter's DLL called the AMovieDllRegisterServer function. This function queries each filter for its IAMovie interface and calls the IAMovieSetup::Register method.
  • Inside the DllUnregisterServer function, the filter's DLL called the AMovieDllUnregisterServer function. This function also queries each filter for its IAMovie interface, but calls the IAMovieSetup::Unregister method.

As noted, you should now use the AMovieDllRegisterServer2 function. Filters registered with this function do not need to implement IAMovieSetup. For more information, see How to Register DirectShow Filters.

In addition to the methods inherited from IUnknown, the IAMovieSetup interface exposes the following methods.

Method | Description
Register | Adds the filter to the registry.
Unregister | Removes the filter from the registry.


IAMovieSetup::Register

Note The IAMovieSetup interface is deprecated. Use the AMovieDllRegisterServer2 function instead.

Adds the filter to the registry.

Syntax

HRESULT Register(void);

Return Value

Returns an HRESULT value.

Remarks

This method registers the filter, its pins, and the media type associated with the pins. It should be implemented to use IFilterMapper methods to accomplish this. See the CBaseFilter::Register member function for a description of its implementation.

See Also

  • Error and Success Codes
  • IAMovieSetup Interface


IAMovieSetup::Unregister

Note The IAMovieSetup interface is deprecated. Use the AMovieDllRegisterServer2 function instead.

Removes the filter from the registry.

Syntax

HRESULT Unregister(void);

Return Value

Returns an HRESULT value.

Remarks

This method should be implemented to use the IFilterMapper::UnregisterFilter method to remove the filter from the registry. This effectively removes the pins and media types as well.

See Also

  • Error and Success Codes
  • IAMovieSetup Interface


IAMPhysicalPinInfo Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications and filters should not use it.

This interface enables an application or filter to retrieve information about a pin that represents a physical hardware connections.

In addition to the methods inherited from IUnknown, the IAMPhysicalPinInfo interface exposes the following method.

Method | Description
GetPhysicalType | Retrieves the type and name of the physical pin.


IAMPhysicalPinInfo::GetPhysicalType

Note The IAMPhysicalPinInfo interface is deprecated.

Retrieves the type and name of the physical pin.

Syntax

HRESULT GetPhysicalType(
  long *pType,
  LPOLESTR *ppszType
);

Parameters

pType

[out] Pointer to a variable that receives a value indicating the pin's type. The PhysicalConnectorType enumeration defines the pin type values.

ppszType

[out] Address of a pointer to a buffer that receives a human-readable string identifying the pin type.

Return Value

Returns S_OK if a valid physical pin value is found. Otherwise, returns VFW_E_NO_ACCEPTABLE_TYPES.

See Also

  • Error and Success Codes
  • IAMPhysicalPinInfo Interface


IAMTunerNotification Interface

Note This callback interface has been deprecated, because the TV Tuner filter does not implement the callback mechanism.

In addition to the methods inherited from IUnknown, the IAMTunerNotification interface exposes the following methods.

Method | Description
OnEvent | Handles events from the TV tuner card.


IAMTunerNotification::OnEvent

Note The IAMTunerNotification interface is deprecated.

The OnEvent method handles events from the TV tuner card.

Syntax

HRESULT OnEvent(
  AMTunerEventType Event
);

Parameters

Event

[in] Flag identifying the type of event. Currently, the only value defined is AMTUNER_EVENT_CHANGED.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTunerNotification Interface


IAMTVAudioNotification Interface

Note This callback interface has been deprecated, because the TV Audio filter does not implement the callback mechanism.

In addition to the methods inherited from IUnknown, the IAMTVAudioNotification interface exposes the following method.

Method | Description
OnEvent | Handles events from a TV tuner card controlled by the IAMTVAudio interface.


IAMTVAudioNotification::OnEvent

Note The IAMTVAudioNotification interface is deprecated.

The OnEvent method handles events from a TV tuner card controlled by the IAMTVAudio interface.

Syntax

HRESULT OnEvent(
  AMTVAudioEventType Event
);

Parameters

Event

[in] Flag identifying the type of event. The only value currently defined is AMTVAUDIO_EVENT_CHANGED.

Return Values

Returns an HRESULT value that depends on the implementation of the interface.

See Also

  • Error and Success Codes
  • IAMTVAudioNotification Interface


ICaptureGraphBuilder Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use the ICaptureGraphBuilder2 interface.

The ICaptureGraphBuilder interface enables you to build capture graphs, preview graphs, file recompression graphs, or other custom graphs.

In addition to the methods inherited from IUnknown, the ICaptureGraphBuilder interface exposes the following methods.

Method | Description
AllocCapFile | Preallocates a capture file to a specified size.
ControlStream | Sends stream control messages to the pin of the specified category on one or more capture filters in a graph.
CopyCaptureFile | Copies the valid media data from the preallocated capture file.
FindInterface | Looks for the specified interface on the filter, upstream and downstream from the filter, and, optionally, only on the output pin of the given category.
GetFiltergraph | Retrieves the filter graph that the builder is using.
RenderStream | Connects a source filter's pin, of an optionally specified category, to the rendering filter, and optionally through another filter.
SetFiltergraph | Tells the graph builder object which filter graph to use.
SetOutputFileName | Creates the rendering section of the filter graph, which will save bits to disk with the specified file name.


ICaptureGraphBuilder::AllocCapFile

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Preallocates a capture file to a specified size.

Syntax

HRESULT AllocCapFile(
    LPCOLESTR lpwstr,
    DWORDLONG dwlSize
);

Parameters

lpwstr

[in] Pointer to a wide-character string containing the name of the file to create or resize.

dwSize

[in] Size, in bytes, of the file to be allocated.

Return Value

Returns an HRESULT value.

Remarks

The call will fail if the file is read-only. For best capture results, always capture to a defragmented, preallocated capture file that is larger than the size of the capture data.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::ControlStream

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Sends stream control messages to the pin of the specified category on one or more capture filters in a graph.

Syntax

HRESULT ControlStream(
    const GUID *pCategory,
    IBaseFilter *pFilter,
    REFERENCE_TIME *pstart,
    REFERENCE_TIME *pstop,
    WORD wStartCookie,
    WORD wStopCookie
);

Parameters

pCategory

[in] Pointer to a GUID specifying the output pin category. See Pin Property Set for a list of all pin categories. This value cannot be NULL.

pFilter

[in] Pointer to an IBaseFilter interface on the filter to control. Specifying NULL controls all capture filters in the graph. You will get one notification for each capture filter.

pstart

[in] Pointer to the start time for capture. NULL means start now. MAX_TIME means cancel previous request, or take no action if there is no previous request.

pstop

[in] Pointer to the stop time for capture. NULL means stop now. MAX_TIME means cancel previous request, or take no action if there is no previous request.

wStartCookie

[in] Specifies a particular value to be sent when the start occurs.

wStopCookie

[in] Specifies a particular value to be sent when the stop occurs.

Return Value

Returns S_FALSE if the stop notification is sent before the last sample sent by the capture filter is rendered, otherwise returns S_OK.

If this method returns S_FALSE, the application might want to wait before stopping the filter graph to allow all samples to pass through the graph and be rendered. Otherwise, samples might be lost.

If there are no pins matching the description you provide, or if stream control cannot be supported on all of the indicated pins, this function will return a failure code.

Remarks

Use this method for frame-accurate capture, or for individual control of capture and preview. For example, you could turn off writing of the captured image to disk if you only want to preview the captured image.

This method uses the IAMStreamControl interface on the pins.

This method sends one notification for each filter found with a pin of the specified category.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::CopyCaptureFile

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Copies the valid media data from the preallocated capture file.

Syntax

HRESULT CopyCaptureFile(
    LPOLESTR lpwstrOld,
    LPOLESTR lpwstrNew,
    int fAllowEscAbort,
    IAMCopyCaptureFileProgress *pCallback
);

Parameters

lpwstrOld

[in] Pointer to a Unicode™ string containing the source file name.

lpwstrNew

[in] Pointer to a Unicode string containing the destination file name. Valid data is copied to this file.

fAllowEscAbort

[in] Value indicating whether pressing the ESC key will cancel the copy operation. TRUE indicates that it will; FALSE indicates that this method will ignore that keystroke.

pCallback

[in] Optional pointer to an IAMCopyCaptureFileProgress show the progress (percentage complete) of the copy operation.

Return Value

Returns an HRESULT value.

Remarks

The new file will contain only valid data and therefore can be much shorter than the source file. Typically, you will always capture to the same huge preallocated file and use this method to copy the data you want to save from each capture to a new file.

If you specify pCallback, the Progress method on the IAMCopyCaptureFileProgress interface will be called periodically with an integer between 0 and 100 representing the percentage complete.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::FindInterface

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Looks for the specified interface on the filter, upstream and downstream from the filter, and, optionally, only on the output pin of the given category.

Syntax

HRESULT FindInterface(
    const GUID *pCategory,
    IBaseFilter *pf,
    REFIID riid,
    void **ppint
);

Parameters

pCategory

[in] Pointer to a GUID specifying the output pin category. See Pin Property Set for a list of all pin categories. NULL indicates search all the output pins regardless of category.

pf

[in] Pointer to the IBaseFilter interface of the filter.

riid

[in] Reference ID of the desired interface.

ppint

[out] Address of a void pointer. If the interface was found, this method initializes ppint so that it contains the address of a pointer to the found interface. Call the Release method to decrement the reference count when you're done with the interface.

Return Value

Returns an HRESULT value.

Remarks

This method looks for the interface on the filter, and upstream and downstream of the filter, unless a category is given. If a category is given, it only looks downstream of the output pin of that category. It can be used to find interfaces on renderers, multiplexers, TV tuners, crossbars, and so forth.

If pCategory equals &LOOK_UPSTREAM_ONLY, then the graph builder will look upstream of the filter given in parameter pf, but not on the filter itself, nor downstream of the filter.

If pCategory equals &LOOK_DOWNSTREAM_ONLY, then the graph builder will look downstream of the filter given in parameter pf, but not on the filter itself, nor upstream of the filter.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::GetFiltergraph

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Retrieves the filter graph that the builder is using.

Syntax

HRESULT GetFiltergraph(
    IGraphBuilder **ppfg
);

Parameters

ppfg

[out] Address of a pointer to an IGraphBuilder interface.

Return Value

Returns an HRESULT value.

Remarks

This method increments the reference count on the IGraphBuilder interface; be sure to decrement the reference count on IGraphBuilder by calling the Release method.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::RenderStream

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Connects a source filter's pin, of an optionally specified category, to the rendering filter, and optionally through another filter.

Syntax

HRESULT RenderStream(
    const GUID *pCategory,
    IUnknown *pSource,
    IBaseFilter *pfCompressor,
    IBaseFilter *pfRenderer
);

Parameters

pCategory

[in] Pointer to a GUID specifying which output pin of the source filter to connect. See Pin Property Set for a list of all pin categories. NULL indicates render the only output pin, regardless of category.

pSource

[in] Pointer to an IBaseFilter or an IPin interface representing either the source filter or an output pin. Source filters are typically a file source filter, such as an AVI file source filter or a capture filter.

pfCompressor

[in] Pointer to an IBaseFilter interface representing the optional compression filter.

pfRenderer

[in] Pointer to an IBaseFilter interface representing the renderer. You can use the ppf (multiplexer) parameter from ICaptureGraphBuilder::SetOutputFileName to supply this value.

Return Value

Returns VFW_S_NOPREVIEWPIN if the capture filter has a capture pin but no preview pin, and you call RenderStream with the &PIN_CATEGORY_PREVIEW category on the capture pin. In this case, RenderStream will render the preview pin of the Smart Tee filter. For more information, see Remarks.

Remarks

If you specify a non-NULL Pin Property Set GUID for pCategory and a capture filter for pSource, this method instantiates and connects additional required upstream filters, such as TV tuners and crossbars. It then renders the capture pin of pSource.

If pSource is a pin, then specify NULL for pCategory and this method renders the stream from that pin.

If the source filter has only one output pin, specify NULL for pCategory.

pSource, pfCompressor, and pfRenderer filters given as parameters must be present in the graph before this method is called.

If you are building a capture graph that is using WDM capture filters, this method will build all necessary upstream filters as well as the downstream filters.

Some capture filters that work with new WDM VPE (Video Port Extension) video capture hardware have video port pins instead of preview pins meant for previewing. Video port pins do not connect directly to a video renderer, but instead to a special filter called the Overlay Mixer. Your application does not need to worry about this. All you have to do is call RenderStream with PIN_CATEGORY_PREVIEW and the capture graph builder will correctly render the VIDEO PORT pin through an overlay mixer if that is what is necessary.

When you render a capture or preview pin of a video capture filter (using RenderStream with the PIN_CATEGORY_CAPTURE or PIN_CATEGORY_PREVIEW category) and the capture filter has a capture pin but no preview pin, the Smart Tee filter will be used automatically to allow simultaneous capture and preview. For example, calling RenderStream with the PIN_CATEGORY_CAPTURE category will actually connect a Smart Tee filter to the capture pin of the filter, and then render the capture pin of the Smart Tee. If you then call RenderStream with the PIN_CATEGORY_PREVIEW category on the capture pin, it will actually render the preview pin of the Smart Tee. If calling RenderStream with PIN_CATEGORY_PREVIEW results in using the capture pin and a Smart Tee filter, RenderStream will return VFW_S_NOPREVIEWPIN to indicate this. Thus, if FindInterface fails to find a preview interface, you may need to call FindInterface with the PIN_CATEGORY_PREVIEW category and with the PIN_CATEGORY_CAPTURE category, because the preview interface can be found by looking downstream of the capture pin of the capture filter.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::SetFiltergraph

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Tells the graph builder object which filter graph to use.

Syntax

HRESULT SetFiltergraph(
    IGraphBuilder *pfg
);

Parameters

pfg

[in] Pointer to an IGraphBuilder interface that specifies the filter graph to use for subsequent calls to the IFilterGraph::AddFilter method.

Return Value

Returns an HRESULT value.

Remarks

The graph builder will automatically create a filter graph if you don't call this method. If you call this method after the graph builder has created its own filter graph, the call will fail.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


ICaptureGraphBuilder::SetOutputFileName

Note The ICaptureGraphBuilder interface is deprecated. Use ICaptureGraphBuilder2 instead.

Creates the rendering section of the filter graph, which will save bits to disk with the specified file name.

Syntax

HRESULT SetOutputFileName(
    const GUID *pType,
    LPCOLESTR lpwstrFile,
    IBaseFilter **ppf,
    IFileSinkFilter **pSink
);

Parameters

pType

[in] Pointer to a GUID representing the media subtype. Must be &MEDIASUBTYPE_Avi.

lpwstrFile

[in] Pointer to a wide-character string containing the output file name.

ppf

[out] Address of a pointer to an IBaseFilter interface representing the multiplexer filter. This method increments the reference count on the IBaseFilter interface so you must decrement the reference count by using the Release method on this parameter when done using the filter.

pSink

[out] Address of a pointer to an IFileSinkFilter interface representing the file writer. This method increments the reference count on the IFileSinkFilter interface so you must decrement the reference count using Release when done using the filter.

Return Value

Returns an HRESULT value. Possible values include the following.

Value | Description
E_FAIL | Failure.
E_INVALIDARG | Invalid argument. Audio-Video Interleaved (AVI) is the only supported output format.
E_OUTOFMEMORY | Out of memory.
E_POINTER | Null pointer argument.
E_UNEXPECTED | Unexpected error occurred.
NOERROR | Success.
S_OK | Instance of the AVI multiplexer filter was successfully created.

Remarks

This method inserts the multiplexer and the file writer into the filter graph and calls IFileSinkFilter::SetFileName to set the output file name.

You can use the ppf parameter returned by this method as the pfRenderer parameter in calls to RenderStream.

You can use the pSink parameter from this method in a call to SetFileName to change the file name set by ICaptureGraphBuilder::SetOutputFileName.

See Also

  • Error and Success Codes
  • ICaptureGraphBuilder Interface


IDirectDraw3 Interface

Note This interface has been deprecated. New applications should not use it.

The IDirectDraw3 interface is available to applications that have created a DirectDraw object through the IDirectDrawFactory::CreateDirectDraw method. This method retrieves the address of a pointer to an IDirectDraw interface, which your application can use to query for the IDirectDraw3 interface.

In addition to the methods inherited from IUnknown, the IDirectDraw3 interface exposes the following methods.

Method | Description
CreateSurface | Creates a DirectDrawSurface object from a DirectDraw object.
GetSurfaceFromDC | Retrieves a pointer to an IDirectDrawSurface interface from a handle to a device context.


IDirectDraw3::CreateSurface

Note The IDirectDraw3 interface is deprecated.

Creates a DirectDrawSurface object from a DirectDraw object.

Syntax

STDMETHOD CreateSurface(
    LPDDSURFACEDESC lpDDSurfaceDesc,
    LPDIRECTDRAWSURFACE FAR *lplpDDSurface,
    IUnknown FAR *pUnkOuter
);

Parameters

lpDDSurfaceDesc

[in] Pointer to the DDSURFACEDESC structure that describes the requested surface. You should set any unused members of DDSURFACEDESC to zero before calling this method. A DDSCAPS structure is a member of DDSURFACEDESC.

lplpDDSurface

[out] Address of a pointer to be initialized with a valid DirectDrawSurface pointer if the call succeeds.

pUnkOuter

[in] Pointer to an IUnknown interface on an outer object that will be aggregated with an inner object's IUnknown interface.

Return Value

Returns DD_OK if successful, or one of the following error values otherwise.

Value | Description
DDERR_INCOMPATIBLEPRIMARY | The primary surface creation request does not match the existing primary surface.
DDERR_INVALIDCAPS | One or more of the capability bits passed to the callback function are incorrect.
DDERR_INVALIDOBJECT | DirectDraw received a pointer to an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the method are incorrect.
DDERR_INVALIDPIXELFORMAT | The pixel format was invalid as specified.
DDERR_NOALPHAHW | No alpha acceleration hardware is present or available, which caused the requested operation to fail.
DDERR_NOCOOPERATIVELEVELSET | The IDirectDraw2::SetCooperativeLevel method was not called before the surface was created.
DDERR_NODIRECTDRAWHW | Hardware-only DirectDraw object creation isn't possible; the driver doesn't support any hardware.
DDERR_NOEMULATION | Software emulation isn't available.
DDERR_NOEXCLUSIVEMODE | The operation requires the application to have exclusive mode, but the application doesn't have exclusive mode.
DDERR_NOFLIPHW | Flipping visible surfaces isn't supported.
DDERR_NOMIPMAPHW | The operation can't be carried out because no mipmap texture mapping hardware is present or available.
DDERR_NOOVERLAYHW | The operation can't be carried out because no overlay hardware is present or available.
DDERR_NOZBUFFERHW | The operation to create a z-buffer in display memory or to perform a blit using a z-buffer can't be carried out because there is no hardware support for z-buffers.
DDERR_OUTOFMEMORY | DirectDraw doesn't have enough available memory to perform the operation.
DDERR_OUTOFVIDEOMEMORY | DirectDraw doesn't have enough display memory to perform the operation.
DDERR_PRIMARYSURFACEALREADYEXISTS | The application has already created a primary surface.
DDERR_UNSUPPORTEDMODE | The display is currently in an unsupported mode.
DDERR_UNSUPPORTED | The operation isn't supported.

Remarks

Passing in NULL for the pUnkOuter parameter will return the address of a DirectDraw surface in the lplpDDSurface parameter. However, if you pass in a pointer to an outer interface you want to aggregate with an inner interface, you will get back an IUnknown pointer for the lplpDDSurface parameter.

DirectDrawEx now also provides the DDSCAPS_DATAEXCHANGE flag for the dwcaps member of the DDSCAPS structure, which is defined as a combination of DDSCAPS_SYSTEMMEMORY and DDSCAPS_VIDEOMEMORY in Ddrawex.h. When a surface is created using the DDSCAPS_DATAEXCHANGE flag, the surface will be automatically moved into video memory if there is enough video memory available; otherwise, a system memory surface will be created. Also, setting this flag in conjunction with the DDSCAPS_OWNDC flag enables applications to call the IDirectDrawSurface::GetDC method to lock the device context for as long they require, without holding a lock on the surface.

This method calls the IDirectDraw::CreateSurface and IDirectDraw2::CreateSurface methods.

See Also

  • Error and Success Codes
  • IDirectDraw3 Interface


IDirectDraw3::GetSurfaceFromDC

Note The IDirectDraw3 interface is deprecated.

Retrieves a pointer to an IDirectDrawSurface interface from a handle to a device context.

Syntax

STDMETHOD GetSurfaceFromDC(
  HDC hdc,
  IDirectDrawSurface **ppSurface
);

Parameters

hdc

[in] Handle of the device context (DC).

ppSurface

[out] Address of a pointer to an IDirectDrawSurface interface.

Return Value

Returns S_OK if successful, or one of the following values otherwise.

Value | Description
DDERR_NOTFOUND | The requested item wasn't found.
E_POINTER | Invalid pointer to IDirectDrawSurface.

See Also

  • Error and Success Codes
  • IDirectDraw3 Interface


IDirectDrawFactory Interface

Note This interface has been deprecated. New applications should not use it.

The IDirectDrawFactory interface is used to create and enumerate DirectDraw objects that support extended features.

In addition to the methods inherited from IUnknown, the IDirectDrawFactory interface exposes the following methods.

Method | Description
CreateDirectDraw | Creates a DirectDraw object and retrieves pointers to the IUnknown and the IDirectDraw interfaces.
DirectDrawEnumerate | Enumerates the DirectDraw surfaces installed on the system.


IDirectDrawFactory::CreateDirectDraw

Note The IDirectDrawFactory interface is deprecated.

Creates a DirectDraw object and retrieves a pointer to its IDirectDraw interface.

Syntax

STDMETHOD CreateDirectDraw(
    GUID *pGUID,
    HWND hWnd,
    DWORD dwCoopLevelFlags,
    DWORD dwReserved,
    IUnknown *pUnkOuter,
    IDirectDraw **ppDirectDraw
);

Parameters

pGUID

[out] Pointer to the globally unique identifier (GUID) that represents the driver to be created. Set this to NULL to indicate the active display driver, or you can pass one of the following flags to restrict the active display driver's behavior for debugging purposes.

Value | Description
DDCREATE_EMULATIONONLY | The DirectDraw object will use emulation for all features; it will not take advantage of any hardware-supported features.
DDCREATE_HARDWAREONLY | The DirectDraw object will never emulate features not supported by the hardware. Attempts to call methods that require unsupported features will fail, returning DDERR_UNSUPPORTED (operation not supported).

hWnd

[in] Window handle to the application.

dwCoopLevelFlags

[in] Application's top-level behavior. Specify one or more of the following flags.

Value | Description
DDSCL_ALLOWMODEX | Enables the use of Mode X display modes. You must use this flag with the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags.
DDSCL_ALLOWREBOOT | Enables the user to reboot by pressing CTRL+ALT+DEL while the application is in full-screen exclusive mode.
DDSCL_EXCLUSIVE | Requests the exclusive level. You must use this flag with the DDSCL_FULLSCREEN flag. At the full screen and exclusive cooperative level, you can use the hardware to its fullest. In this mode, you can set custom and dynamic palettes, change display resolutions, compact memory, and implement page flipping. The exclusive (full-screen) mode does not prevent other applications from allocating surfaces, nor does it exclude them from using DirectDraw or GDI. However, it does prevent applications other than the one currently with exclusive access from changing the display mode or palette.
DDSCL_FULLSCREEN | Indicates that the exclusive-mode owner will be in control of the entire primary surface. You must use this flag with the DDSCL_EXCLUSIVE flag.
DDSCL_NORMAL | Indicates that the application will function as a regular Microsoft® Windows® application. You can't use this flag with the DDSCL_ALLOWMODEX, DDSCL_EXCLUSIVE, or DDSCL_FULLSCREEN flags.
DDSCL_NOWINDOWCHANGES | Indicates that DirectDraw can't minimize or restore the application window when the application is activated.

dwReserved

[in] Reserved. Must be NULL.

pUnkOuter

[in] Reserved. Must be NULL.

ppDirectDraw

[out] Address of a pointer to an IDirectDraw interface.

Return Value

Returns DD_OK if successful, or one of the following error values otherwise.

Return code | Description
DDERR_DIRECTDRAWALREADYCREATED | A DirectDrawEx object representing this driver has already been created for this process.
DDERR_GENERIC | There is an undefined error condition.
DDERR_INVALIDDIRECTDRAWGUID | The GUID passed to this method is not a valid DirectDrawEx driver identifier.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the method are incorrect.
DDERR_NODIRECTDRAWHW | Hardware-only DirectDrawEx object creation isn't possible; the driver doesn't support any hardware.
DDERR_UNSUPPORTED | DirectDraw doesn't support the operation.
E_OUTOFMEMORY | There isn't enough memory available to create a DirectDraw object.

Remarks

This method creates DirectDraw objects in the same way that the DirectDraw DirectDrawCreate function is used to create DirectDraw objects, and sets cooperative levels the same way the IDirectDraw2::SetCooperativeLevel method sets cooperative levels. However, in addition to creating a DirectDraw object, successful calls to the IDirectDrawFactory::CreateDirectDraw method will obtain a pointer to the IUnknown and IDirectDraw interfaces, which are exposed on the DirectDraw object. Applications can now query the DirectDraw object to obtain the address of a pointer to an IDirectDraw3 interface.

See Also

  • Error and Success Codes
  • IDirectDrawFactory Interface


IDirectDrawFactory::DirectDrawEnumerate

Note The IDirectDrawFactory interface is deprecated.

Enumerates the available DirectDraw compatible devices in the system.

Syntax

STDMETHOD DirectDrawEnumerate(
    LPDDENUMCALLBACK lpCallback,
    LPVOID lpContext
);

Parameters

lpCallback

[in] Pointer to a DDEnumCallback function that will be called with a description of each DirectDrawEx-enabled hardware abstraction layer (HAL) installed in the system.

lpContext

[in] Address of an application-defined structure that the system will pass to the callback function each time the function is called.

Return Value

Returns DD_OK if successful, or DDERR_INVALIDPARAMS otherwise.

Remarks

This method functions in a similar manner to the DirectDraw function DirectDrawEnumerate, defined in the DirectX SDK.

See Also

  • Error and Success Codes
  • IDirectDrawFactory Interface


IDrawVideoImage Interface

The IDrawVideoImage interface enables an application to draw the same video image in multiple places simultaneously on the screen. The Video Renderer filter exposes this interface. The Video Mixing Renderer (VMR) filter provides a better way to accomplish the same effect, through the use of multiple input streams.

To use this interface, call DrawVideoImageBegin to put the Video Renderer into GDI mode. Then the application can call the DrawVideoImageDraw method as often as necessary. The renderer simply takes the current video frame and draws it to the specified rectangle. This process is asychronous to the delivery of frames to the renderer on the filter graph thread. The application is responsible for the frame rate at which it renders images; this rate will never be the same as the rate of the frames being delivered to the filter. In other words, calling this method is like taking a periodic shapshot of the video and putting it into a device context of your choosing at a rate of your choosing.

In addition to the methods inherited from IUnknown, the IDrawVideoImage interface exposes the following methods.

Methods | Description
DrawVideoImageBegin | Turns off DirectDraw in preparation for a call to DrawVideoImageDraw.
DrawVideoImageDraw | Draws the specified source rectangle to the specified destination rectangle in the specified GDI device context.
DrawVideoImageEnd | Turns DirectDraw back on after drawing has been performed.


IDrawVideoImage::DrawVideoImageBegin

The DrawVideoImageBegin method turns off DirectDraw in preparation for a call to the DrawVideoImageDraw method.

Syntax

HRESULT DrawVideoImageBegin();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Values | Description
S_OK | The method succeeded.

See Also

  • IDrawVideoImage Interface
  • IDrawVideoImage::DrawVideoImageDraw


IDrawVideoImage::DrawVideoImageDraw

The DrawVideoImageDraw method draws the specified source rectangle to the specified destination rectangle in the specified GDI device context.

Syntax

HRESULT DrawVideoImageDraw(
  HDC  hdc,
  LPRECT  lprcSrc,
  LPRECT  lprcDst
);

Parameters

hdc

[in] Specifies the device context.

lprcSrc

[in] Pointer to a RECT structure that specifies the source rectangle, as a subrectangle of the current video frame.

lprcDst

[in] Pointer to a RECT structure that specifies the destination rectangle in the device context.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Values | Description
S_OK | The method succeeded.

See Also

  • IDrawVideoImage Interface


IDrawVideoImage::DrawVideoImageEnd

The DrawVideoImageEnd method turns DirectDraw back on after drawing has been performed.

Syntax

HRESULT DrawVideoImageEnd();

Parameters

This method takes no parameters.

Return Values

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Values | Description
S_OK | The method succeeded.

See Also

  • IDrawVideoImage Interface


IDvdControl Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use IDvdControl2.

The IDvdControl interface controls the playback and search mechanisms of a DVD title that contains one or more video movies. Use this interface to control playback (set root drive, play, stop, and so forth) or use DVD-specific functionality such as menus and buttons when playing DVD-Video files.

In addition to the methods inherited from IUnknown, the IDvdControl interface exposes the following methods.

Method | Description
AngleChange | Sets the new display angle.
AudioStreamChange | Sets the current audio stream.
BackwardScan | Searches backward through the current disc at the specified speed.
ButtonActivate | Activates the selected button.
ButtonSelectAndActivate | Selects and activates the specified button.
ChapterPlay | Plays the media file with the specified title index and chapter value.
ChapterPlayAutoStop | Start playing at the specified chapter within the specified title and play the number of chapters specified.
ChapterSearch | Halts playback of the current chapter and starts playback from the specified chapter value in the same media file.
ForwardScan | Searches forward through the current disc at the specified speed.
GoUp | Halts playback of the current media file and starts playback of the designated previous program chain (PGC).
KaraokeAudioPresentationModeChange | Sets the audio playback mode to karaoke.
LeftButtonSelect | Selects the left directional button from the displayed menu.
LowerButtonSelect | Selects the lower directional button from the displayed menu.
MenuCall | Displays the specified menu on the screen.
MenuLanguageSelect | Sets the displayed language for navigation menus.
MouseActivate | Selects and activates a DVD button in response to a mouse click.
MouseSelect | Selects a DVD button in response to mouse movement.
NextPGSearch | Halts playback of the current program and starts playback from the next program within the program chain (PGC).
ParentalCountrySelect | Sets the current country/region for controlling parental access levels.
ParentalLevelSelect | Sets the parental access level for the current media file.
PauseOff | Unpauses the current media file playback.
PauseOn | Pauses the current media file playback.
PrevPGSearch | Halts playback of the current program and starts playback from the previous program within the program chain (PGC).
Resume | Returns to playing back a title from a menu.
RightButtonSelect | Selects the right directional button from the displayed menu.
SetRoot | Sets the root directory containing the DVD-Video volume.
StillOff | Resumes playback, canceling still mode.
StopForResume | Transitions playback to the DVD_DOMAIN_Stop state after saving resume information.
SubpictureStreamChange | Selects the new subpicture stream and enables or disables it for display.
TimePlay | Plays the media file with the specified title index, starting at the specified time.
TimeSearch | Halts playback of the current chapter and starts playback from the specified time in the same media file.
TitlePlay | Finds the media file with the specified title index and plays it back.
TopPGSearch | Halts playback of the current program and restarts playback of the current program within the program chain (PGC).
UpperButtonSelect | Selects the upper directional button from the displayed menu.
VideoModePreferrence | Sets the video display mode the user prefers.


IDvdControl::AngleChange

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the new display angle.

Syntax

HRESULT AngleChange(
    ULONG ulAngle
);

Parameters

ulAngle

[in] Value of the new angle, which must be from 1 through 9.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::AudioStreamChange

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the current audio stream.

Syntax

HRESULT AudioStreamChange(
    ULONG nAudio
);

Parameters

nAudio

[in] Value that specifies the audio track to use, which must be from 0 through 7.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

AudioStreamChange affects the audio of the current Video Title Set (VTS). When called from within a menu, this method sets the audio stream of the title from which the menu was called.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::BackwardScan

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Searches backward through the current disc at the specified speed.

Syntax

HRESULT BackwardScan(
    double dwSpeed
);

Parameters

dwSpeed

[in] Value that specifies how quickly DirectShow will search through the media file. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 will search backward at two and one-half times the authored speed, while a value of 0.5 will search backward at half the authored speed. The actual speed of playback depends on the capabilities of the video decoder, and might differ from the specified rate.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ButtonActivate

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Activates the selected button.

Syntax

HRESULT ButtonActivate(void);

Return Value

Returns an HRESULT value.

Remarks

Selecting a DVD button simply highlights the button but does not activate the button. Selecting is the Microsoft® Windows® equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface
  • IDvdControl::ButtonSelectAndActivate


IDvdControl::ButtonSelectAndActivate

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects and activates the specified button.

Syntax

HRESULT ButtonSelectAndActivate(
    ULONG uiButton
);

Parameters

uiButton

[in] Value that specifies the button that will be selected and activated, which must be from 1 through 36.

Return Value

Returns an HRESULT value.

Remarks

Electronic remote control devices typically have a number of buttons that activate various functions of a DVD playback unit. Typically, you call this method when a user clicks a button on the control device; DirectShow then indicates that the button was selected (by playing a sound or changing a graphic, for example) and calls methods appropriate to which button was selected, such as ButtonActivate.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ChapterPlay

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Plays the media file with the specified title index and chapter value.

Syntax

HRESULT ChapterPlay(
    ULONG uiTitle,
    ULONG uiChapter
);

Parameters

uiTitle

[in] Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.

uiChapter

[in] Value that specifies the chapter within the specified title where DirectShow will start playback; this value must be from 1 through 999.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ChapterPlayAutoStop

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Instructs the DVD player to start playing at the specified chapter within the specified title and play the number of chapters specified.

Syntax

HRESULT ChapterPlayAutoStop(
    ULONG ulTitle,
    ULONG ulChapter,
    ULONG ulChaptersToPlay
);

Parameters

ulTitle

[in] Title number for playback.

ulChapter

[in] Chapter number to start playback.

ulChaptersToPlay

[in] Number of chapters to play from the start chapter.

Return Value

Returns an HRESULT value.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

Chapters range from 1 through 999. See EC_DVD_CHAPTER_AUTOSTOP in DVD Event Notification Codes for more information.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ChapterSearch

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current chapter and starts playback from the specified chapter within the same title.

Syntax

HRESULT ChapterSearch(
    ULONG Chapter
);

Parameters

Chapter

Chapter value that specifies the point where playback will begin.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ForwardScan

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Searches forward through the current disc at the specified speed.

Syntax

HRESULT ForwardScan(
    double dwSpeed
);

Parameters

dwSpeed

[in] Value that specifies how quickly DirectShow will search through the media file. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 will search forward at two and one-half times the authored speed, while a value of 0.5 will search forward at half the authored speed. Note that the actual speed of playback depends on the capabilities of the video decoder, and might differ from the specified rate.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::GoUp

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current media file and starts playback of the designated previous program chain (PGC).

Syntax

HRESULT GoUp(void);

Return Value

Returns an HRESULT value.

Remarks

Each PGC is associated with a previous PGC at authoring time, which this method sets as the new playback file.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::KaraokeAudioPresentationModeChange

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the audio playback mode to karaoke.

Syntax

HRESULT KaraokeAudioPresentationModeChange(
    ULONG ulMode
);

Parameters

ulMode

[in] Requested audio playback mode.

Return Value

Returns an HRESULT value.

Remarks

Karaoke support is currently not implemented.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::LeftButtonSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects the left directional button from the displayed menu.

Syntax

HRESULT LeftButtonSelect(void);

Return Value

Returns an HRESULT value.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the left directional button.

Selecting a DVD button simply highlights the button but does not activate the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::LowerButtonSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects the lower directional button from the displayed menu.

Syntax

HRESULT LowerButtonSelect(void);

Return Value

Returns an HRESULT value.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the lower directional button.

Selecting a DVD button simply highlights the button but does not activate the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::MenuCall

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Displays the specified menu on the screen.

Syntax

HRESULT MenuCall(
    DVD_MENU_ID MenuID
);

Parameters

MenuID

[in] Value that specifies the menu to display. Member of the DVD_MENU_ID enumerated data type.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::MenuLanguageSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the displayed language for navigation menus.

Syntax

HRESULT MenuLanguageSelect(
    LCID LanguageCode
);

Parameters

LanguageCode

Value that specifies the new language.

Return Value

Returns an HRESULT value.

Remarks

This method selects the default language for menus.

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

Applications specify languages with standard Windows LCIDs.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::MouseActivate

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects and activates a DVD button in response to a mouse click.

Syntax

HRESULT MouseActivate(
    POINT point
);

Parameters

point

[in] Specified point within the display window.

Return Value

Returns an HRESULT value .

Remarks

This method checks the specified point within the display window to see if it is within a current DVD button's highlight rectangle. If it is, this method selects and then activates the button.

DVD buttons do not all necessarily have highlight rectangles. Button rectangles can overlap, and the rectangles do not always correspond to the visual representation of DVD buttons.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::MouseSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects a DVD button in response to mouse movement.

Syntax

HRESULT MouseSelect(
    POINT point
);

Parameters

point

[in] Specified point within the display window.

Return Value

Returns an HRESULT value.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

This method checks the specified point within the display window to see if it is within a current DVD button's highlight rectangle. If it is, this method selects the button.

DVD buttons do not all necessarily have highlight rectangles. Button rectangles can overlap, and the rectangles do not always correspond to the visual representation of DVD buttons.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::NextPGSearch

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current program and starts playback from the next program within the program chain (PGC).

Syntax

HRESULT NextPGSearch(void);

Return Value

Returns an HRESULT value.

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::ParentalCountrySelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the current country/region for controlling parental access levels.

Syntax

HRESULT ParentalCountrySelect(
    WORD wCountry
);

Parameters

wCountry

[in] Value that specifies the current country/region according to the Alpha-2 Code defined in ISO3166. See Remarks.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

The ISO3166 2-letter country/region codes in the wCountry parameter must be supplied to this method as a WORD. The conversion is demonstrated for the United States (US) in the following line of code.

WORD wCountry  =  ( WORD( 'U' ) << 8 ) | 'S';

See Also

  • Error and Success Codes
  • IDvdControl Interface
  • IDvdControl::ParentalLevelSelect


IDvdControl::ParentalLevelSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the parental access level for the current media file.

Syntax

HRESULT ParentalLevelSelect(
    ULONG ulParentalLevel
);

Parameters

ulParentalLevel

Value that specifies the current media file parental access level. Should be a value from 1 to 8, inclusive. Predefined parental levels are as follows:

Value | Description
1 | The rating is G, General.
3 | The rating is PG, Parental Guidance Suggested.
4 | The rating is PG-13, Parental Guidance Suggested, not recommended for those under 13.
6 | The rating is R, Restricted.
7 | The rating is NC-17.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

This method sets the current user's access level; this access level determines what media files the user can play back. Higher levels can play lower-level content; lower levels can't play higher-level content. For example, adults can watch child-safe content, but children can't watch adult content.

The DVD Navigator filter provides no restriction on setting the parental level. DVD player applications can enforce restrictions on the parental level setting, such as providing password protection for raising the current parental level. Parental management in the DVD Navigator is disabled by default.

To disable parental management, pass 0xffffffff for ulParentalLevel. If parental management is disabled, then the player will play the first program chain (PGC) in a parental block regardless of parental IDs.

See Also

  • Error and Success Codes
  • IDvdControl Interface
  • IDvdControl::ParentalCountrySelect


IDvdControl::PauseOff

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Resumes playback of the current media file after a pause.

Syntax

HRESULT PauseOff(void);

Return Value

Returns an HRESULT value.

Remarks

If the media file was not paused in playback, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface
  • IDvdControl::PauseOn


IDvdControl::PauseOn

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Pauses the current media file playback.

Syntax

HRESULT PauseOn(void);

Return Value

Returns an HRESULT value.

Remarks

This method freezes playback and any internal timers, similar to IMediaControl::Pause. If the media file was not running, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface
  • IDvdControl::PauseOff


IDvdControl::PrevPGSearch

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current program and starts playback from the previous program within the program chain (PGC).

Syntax

HRESULT PrevPGSearch(void);

Return Value

Returns an HRESULT value.

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::Resume

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Returns to playing back a title from a menu.

Syntax

HRESULT Resume(void);

Return Value

Returns an HRESULT value.

Remarks

If the file is stopped or already running, this method does nothing.

This method returns to title playback in DVD_DOMAIN_Title. Applications typically call this method after MenuCall which puts the DVD Navigator in DVD_DOMAIN_VideoTitleSetMenu or DVD_DOMAIN_VideoManagerMenu.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu or DVD_DOMAIN_VideoTitleSetMenu. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::RightButtonSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects the right directional button from the displayed menu.

Syntax

HRESULT RightButtonSelect(void);

Return Value

Returns an HRESULT value.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the right directional button.

Selecting a DVD button simply highlights the button but does not activate the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::SetRoot

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the root directory containing the DVD-Video volume.

Syntax

HRESULT SetRoot(
    LPCWSTR pszPath
);

Parameters

pszPath

[in] Pointer to the directory name to set as the root directory.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

If you haven't set the root directory before calling IDvdControl::TitlePlay, the first drive starting from C: that contains a VIDEO_TS directory in the top level directory will be used as the root.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::StillOff

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Resumes playback, canceling still mode.

Syntax

HRESULT StillOff(void);

Return Value

Returns an HRESULT value .

Remarks

If the display image was not in still-store mode, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::StopForResume

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Transitions playback to the DVD_DOMAIN_Stop state after saving resume information.

Syntax

HRESULT StopForResume(void);

Return Value

Returns an HRESULTvalue.

Remarks

If no file is playing or paused, this method does nothing.

The DVD Navigator filter transfers to the stopped state, but the filter graph remains in the DirectShow run state.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::SubpictureStreamChange

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects the new subpicture stream and enables or disables it for display.

Syntax

HRESULT SubpictureStreamChange(
    ULONG nSubPicture,
    BOOL bDisplay
);

Parameters

nSubPicture

Value that specifies the source of the subpicture, which must be from 0 through 32, or 63.

Value | Description
0-31 | Indicates that the stream is valid.
32 | Enables you to toggle the display without changing the current stream (that is, change bDisplay without altering the current stream).
63 | Indicates that the stream is the dummy stream.

bDisplay

Value that specifies whether the subpicture is enabled; TRUE makes the subpicture visible and FALSE hides it.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::TimePlay

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Plays the media file with the specified title index, starting at the specified time.

Syntax

HRESULT TimePlay(
    ULONG uiTitle,
    ULONG bcdTime
);

Parameters

uiTitle

Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.

bcdTime

Pointer to the DVD_TIMECODE structure where DirectShow will start playback.

Return Value

Returns an HRESULT value .

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::TimeSearch

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current chapter and starts playback from the specified time in the same media file.

Syntax

HRESULT TimeSearch(
    ULONG bcdTime
);

Parameters

bcdTime

Pointer to the DVD_TIMECODE structure where DirectShow will start playback.

Return Value

Returns an HRESULT value.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::TitlePlay

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Finds the media file with the specified title index and plays it back.

Syntax

HRESULT TitlePlay(
    ULONG uiTitle
);

Parameters

uiTitle

Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.

Return Value

Returns an HRESULT value .

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::TopPGSearch

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Halts playback of the current program and restarts playback of the current program within the program chain (PGC).

Syntax

HRESULT TopPGSearch(void);

Return Value

Returns an HRESULT value .

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::UpperButtonSelect

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Selects the upper directional button from the displayed menu.

Syntax

HRESULT UpperButtonSelect(void);

Return Value

Returns an HRESULT value .

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the upper directional button.

Selecting a DVD button simply highlights the button but does not activate the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdControl::VideoModePreferrence

Note The IDvdControl interface is deprecated. Use IDvdControl2 instread.

Sets the video display mode the user prefers.

Syntax

HRESULT VideoModePreferrence(
    ULONG ulPreferredDisplayMode
);

Parameters

ulPreferredDisplayMode

[in] Value that specifies the new display mode for DVD content. Member of the DVD_PREFERRED_DISPLAY_MODE enumerated data type.

Return Value

Returns an HRESULT value .

Remarks

This method changes the default video window's aspect ratio, and can also specify a default aspect ratio conversion mechanism.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdControl Interface


IDvdInfo Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use IDvdInfo2.

The IDvdInfo interface enables an application to query for attributes of available DVD titles and the DVD player status. It also allows for control of a DVD player beyond Annex J in the DVD specification. Use this interface to retrieve details about a DVD-Video or about the current state of the DVD player filter graph.

In addition to the methods inherited from IUnknown, the IDvdInfo interface exposes the following methods.

Method | Description
GetAllGPRMs | Retrieves the current contents of all general parameter registers (GPRMs).
GetAllSPRMs | Retrieves the current contents of all system parameter registers (SPRMs).
GetAudioLanguage | Retrieves the language of the specified audio stream within the current title.
GetCurrentAngle | Retrieves the number of available angles and the currently selected angle number.
GetCurrentAudio | Retrieves the number of available audio streams and the number of the currently selected audio stream.
GetCurrentAudioAttributes | Retrieves the attributes for the current audio stream in the current title or menu.
GetCurrentButton | Retrieves the number of available buttons and the currently selected button number.
GetCurrentDomain | Retrieves the current DVD domain of the DVD player.
GetCurrentLocation | Retrieves the current playback location.
GetCurrentSubpicture | Retrieves the number of available subpicture streams, the currently selected subpicture stream number, and whether the subpicture display is disabled.
GetCurrentSubpictureAttributes | Retrieves the attributes for the current subpicture stream in the current title or menu.
GetCurrentUOPS | Retrieves which IDvdControl methods are valid.
GetCurrentVideoAttributes | Retrieves the current video attributes for the current title or menu.
GetCurrentVolumeInfo | Retrieves the current DVD volume information.
GetDVDTextInfo | Retrieves the TXTDT_MG structure, which can contain text descriptions for title name, volume name, producer name, vocalist name, and so on, in various languages.
GetNumberOfChapters | Retrieves the number of chapters that are defined for a given title.
GetPlayerParentalLevel | Retrieves the current parental level and country/region code settings for the DVD player.
GetRoot | Retrieves the root directory that is set in the player.
GetSubpictureLanguage | Retrieves the language of the specified subpicture stream within the current title.
GetTitleAttributes | Retrieves attributes of all video, audio, and subpicture streams for the specified title, including menus.
GetTitleParentalLevels | Retrieves the parental levels that are defined for a particular title.
GetTotalTitleTime | Retrieves the total playback time for the current title.
GetVMGAttributes | Retrieves attributes of all video, audio, and subpicture streams for video manager (VMG) menus.


IDvdInfo::GetAllGPRMs

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current contents of all general parameter registers (GPRMs).

Syntax

HRESULT GetAllGPRMs(
    GPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray

[out] Pointer to the retrieved array of general parameter registers.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

Use of GPRMs is title specific. GPRMs are general parameter registers. For an explanation of GPRMs, see the DVD specifications.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetAllSPRMs

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current contents of all system parameter registers (SPRMs).

Syntax

HRESULT GetAllSPRMs(
    SPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray

[out] Pointer to the retrieved array of system parameter registers.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

For use of individual registers, see the DVD-Video specification.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetAudioLanguage

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the language of the specified audio stream within the current title.

Syntax

HRESULT GetAudioLanguage(
    ULONG nStream,
    LCID *pLanguage
);

Parameters

nStream

[in] Stream number.

pLanguage

[out] Pointer to the retrieved language.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

This method does not return languages for menus. This method sets the value pointed to by pLanguage to zero if the stream does not include language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentAngle

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the number of available angles and the currently selected angle number.

Syntax

HRESULT GetCurrentAngle(
    ULONG *pnAnglesAvailable,
    ULONG *pnCurrentAngle
);

Parameters

pnAnglesAvailable

[out] Pointer to the retrieved number of available angles. If the value pointed to equals 1, then the current video does not contain multiple angles.

pnCurrentAngle

[out] Pointer to the retrieved current angle number.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

Angles are interleaved video streams that presumably contain the same scene shot from different camera angles.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentAudio

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the number of available audio streams and the number of the currently selected audio stream.

Syntax

HRESULT GetCurrentAudio(
    ULONG *pnStreamsAvailable,
    ULONG *pnCurrentStream
);

Parameters

pnStreamsAvailable

[out] Pointer to the retrieved number of available audio streams

pnCurrentStream

[out] Pointer to the current stream number.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentAudioAttributes

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the attributes for the current audio stream in the current title or menu.

Syntax

HRESULT GetCurrentAudioAttributes(
    DVD_AudioATR *pATR
);

Parameters

pATR

[out] Pointer to the retrieved audio attributes.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about the DVD_AudioATR data type, consult the DVD-Video specification.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentButton

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the number of available buttons and the currently selected button number.

Syntax

HRESULT GetCurrentButton(
    ULONG *pnButtonsAvailable,
    ULONG *pnCurrentButton
);

Parameters

pnButtonsAvailable

[out] Pointer to the number of buttons available.

pnCurrentButton

[out] Pointer to the number of the current button.

Return Value

Returns an HRESULT value .

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

If buttons are not present this method returns zero for both pnButtonsAvailable and pnCurrentButton.

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentDomain

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current DVD domain of the DVD player.

Syntax

HRESULT GetCurrentDomain(
    DVD_DOMAIN *pDomain
);

Parameters

pDomain

[out] Pointer to the current domain that is a member of the DVD_DOMAIN enumerated type.

Return Value

Returns an HRESULT value .

Return code | Description
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentLocation

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current playback location.

Syntax

HRESULT GetCurrentLocation(
    DVD_PLAYBACK_LOCATION *pLocation
);

Parameters

pLocation

[out] Pointer to the retrieved playback location information in a DVD_PLAYBACK_LOCATION structure.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method retrieves information sufficient to restart playback of a video from the current playback location in titles that don't explicitly disable seeking to the current location.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentSubpicture

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the number of available subpicture streams, the currently selected subpicture stream number, and whether the subpicture display is disabled.

Syntax

HRESULT GetCurrentSubpicture(
    ULONG *pnStreamsAvailable,
    ULONG *pnCurrentStream,
    BOOL *pIsDisabled
);

Parameters

pnStreamsAvailable

[out] Pointer to the retrieved number of available subpicture streams.

pnCurrentStream

[out] Pointer to the retrieved number of the currently selected subpicture stream.

pIsDisabled

[out] Pointer to a value indicating whether the subpicture display is disabled.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

Subpicture streams authored as forcedly activated streams will be displayed even if the application has disabled subpicture display with the IDvdControl::SubpictureStreamChange method.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentSubpictureAttributes

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the attributes for the current subpicture stream in the current title or menu.

Syntax

HRESULT GetCurrentSubpictureAttributes(
    DVD_SubpictureATR *pATR
);

Parameters

pATR

[out] Pointer to the retrieved subpicture attributes.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about DVD_SubpictureATR, see the DVD-Video specification.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentUOPS

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves which IDvdControl methods are currently valid.

Syntax

HRESULT GetCurrentUOPS(
    VALID_UOP_SOMTHING_OR_OTHER *pUOP
);

Parameters

pUOP

[out] Pointer to a DWORD value containing bits for all user operations (UOP). Each bit in the DWORD represents the state (valid or not valid) of a user operation. If the bit corresponding to a user operation is set, then that user operation is prohibited. For more information, see Remarks.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

The value of pUOP is a bit field defined as follows.

Bit | Flag | User function
0 | UOP_FLAG_Title_Or_Time_Play | TitlePlay, TimePlay
1 | UOP_FLAG_Chapter_Search_Or_Play | ChapterSearch, ChapterPlay
2 | UOP_FLAG_Title_Play | TitlePlay
3 | UOP_FLAG_Stop | StopForResume
4 | UOP_FLAG_GoUp | GoUp
5 | UOP_FLAG_Time_Or_Chapter_Search | TimeSearch, ChapterSearch
6 | UOP_FLAG_Prev_Or_Top_PG_Search | PrevPGSearch, TopPGSearch
7 | UOP_FLAG_Next_PG_Search | NextPGSearch
8 | UOP_FLAG_Forward_Scan | ForwardScan
9 | UOP_FLAG_Backward_Scan | BackwardScan
10 | UOP_FLAG_Title_Menu_Call | MenuCall with a parameter value of 2 (DVD_MENU_Title)
11 | UOP_FLAG_Root_Menu_Call | MenuCall with a parameter value of 3 (DVD_MENU_Root)
12 | UOP_FLAG_SubPic_Menu_Call | MenuCall with a parameter value of 4 (DVD_MENU_Subpicture)
13 | UOP_FLAG_Audio_Menu_Call | MenuCall with a parameter value of 5 (DVD_MENU_Audio)
14 | UOP_FLAG_Angle_Menu_Call | MenuCall with a parameter value of 6 (DVD_MENU_Angle)
15 | UOP_FLAG_Chapter_Menu_Call | MenuCall with a parameter value of 7 (DVD_MENU_Chapter)
16 | UOP_FLAG_Resume | Resume
17 | UOP_FLAG_Button_Select_Or_Activate | UpperButtonSelect, LowerButtonSelect, LeftButtonSelect, RightButtonSelect, ButtonActivate, ButtonSelectAndActivate
18 | UOP_FLAG_Still_Off | StillOff
19 | UOP_FLAG_Pause_On | PauseOn, MenuLanguageSelect
20 | UOP_FLAG_Audio_Stream_Change | AudioStreamChange
21 | UOP_FLAG_SubPic_Stream_Change | SubpictureStreamChange
22 | UOP_FLAG_Angle_Change | AngleChange, ParentalLevelSelect
23 | UOP_FLAG_Karaoke_Audio_Pres_Mode_Change | KaraokeAudioPresentationModeChange
24 | UOP_FLAG_Video_Pres_Mode_Change | VideoModePreferrence

This method is useful because DVD titles can enable or disable individual user operations at almost any point during playback.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentVideoAttributes

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current video attributes for the current title or menu.

Syntax

HRESULT GetCurrentVideoAttributes(
    DVD_VideoATR *pATR
);

Parameters

pATR

[out] Pointer to the retrieved video attributes.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about DVD_VideoATR, see the DVD-Video specification.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetCurrentVolumeInfo

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current DVD volume information.

Syntax

HRESULT GetCurrentVolumeInfo(
    ULONG *pNumOfVol,
    ULONG *pThisVolNum,
    DVD_DISC_SIDE *pSide,
    ULONG *pNumOfTitles
);

Parameters

pNumOfVol

[out] Pointer to the retrieved number of volumes in the volume set.

pThisVolNum

[out] Pointer to the retrieved volume number for this root directory.

pSide

[out] Pointer to the retrieved current disc side (DVD_DISC_SIDE).

pNumOfTitles

[out] Pointer to the retrieved number of titles available in this volume.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetDVDTextInfo

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the TXTDT_MG structure, which can contain text descriptions for title name, volume name, producer name, vocalist name, and so on, in various languages.

Syntax

HRESULT GetDVDTextInfo(
    BYTE *pTextManager,
    ULONG cbBufSize,
    ULONG *pcbActualSize
);

Parameters

pTextManager

[out, size_is(cbBufSize)] Pointer to the retrieved text manager.

cbBufSize

[in] Size of the buffer for pTextManager, in bytes.

pcbActualSize

[out] Pointer to a value containing the number of bytes of data returned.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

If the supplied buffer size in cbBufSize is too small for the data, (for example if cbBufSize equals zero), then this method returns E_OUTOFMEMORY and sets the value pointed to by pcbActualSize to the required size.

For more information, refer to Section 4.1.6 and Annex A of the DVD-Video specification.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetNumberOfChapters

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the number of chapters that are defined for a given title.

Syntax

HRESULT GetNumberOfChapters(
    ULONG ulTitle,
    ULONG *pNumberOfChapters
);

Parameters

ulTitle

[in] Title for which to retrieve the number of chapters.

pNumberOfChapters

[out] Pointer to the retrieved number of chapters for the specified title.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetPlayerParentalLevel

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the current parental level and country/region code settings for the DVD player.

Syntax

HRESULT GetPlayerParentalLevel(
    ULONG *pParentalLevel,
    ULONG *pCountryCode
);

Parameters

pParentalLevel

[out] Pointer to a value indicating the current parental level.

pCountryCode

[out] Pointer to a value indicating the current country/region code.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

For the defined parental levels, see Table 3.3.4-1 of the DVD-Video specification.

Valid parental levels are 1 through 8 if parental management is enabled, 0xffffffff if parental management is disabled.

For the country/region codes, see ISO3166 : Alpha-2 Code.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetRoot

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the root directory that is set in the player.

Syntax

HRESULT GetRoot(
    LPSTR pRoot,
    ULONG cbBufSize,
    ULONG *pcbActualSize
);

Parameters

pRoot

[out, size_is(cbBufSize)] Pointer to the buffer to receive the root string. Note that the root string uses ANSI characters.

cbBufSize

[in] Size of buffer passed in, in bytes.

pcbActualSize

[out] Pointer to a value containing the size of the actual data returned.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

If a valid root was found, this method returns the root string. Otherwise, it returns zero for pcbActualSize, indicating that a valid root directory has not been found or initialized.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetSubpictureLanguage

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the language of the specified subpicture stream within the current title.

Syntax

HRESULT GetSubpictureLanguage(
    ULONG nStream,
    LCID *pLanguage
);

Parameters

nStream

[in] Stream number.

pLanguage

[out] Pointer to the retrieved language.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

This method does not return languages for menus. This method sets the value pointed to by pLanguage to zero if the stream does not include language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetTitleAttributes

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves attributes of all video, audio, and subpicture streams for the specified title, including menus.

Syntax

HRESULT GetTitleAttributes(
    ULONG nTitle,
    DVD_ATR *pATR
);

Parameters

nTitle

[in] Requested title number. Specify 0xFFFFFFFF for the current title.

pATR

[out] Pointer to the retrieved attributes structure.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetTitleParentalLevels

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the parental levels that are defined for a particular title.

Syntax

HRESULT GetTitleParentalLevels(
    ULONG ulTitle,
    ULONG *pParentalLevels
);

Parameters

ulTitle

[in] Title for which parental levels are requested.

pParentalLevels

[out] Pointer to a logical OR combination of the parental levels defined for the title. A higher setting will block out more content than a lower setting. Valid parental levels are the following:

  • DVD_PARENTAL_LEVEL_1
  • DVD_PARENTAL_LEVEL_2
  • DVD_PARENTAL_LEVEL_3
  • DVD_PARENTAL_LEVEL_4
  • DVD_PARENTAL_LEVEL_5
  • DVD_PARENTAL_LEVEL_6
  • DVD_PARENTAL_LEVEL_7
  • DVD_PARENTAL_LEVEL_8

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetTotalTitleTime

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves the total playback time for the current title.

Syntax

HRESULT GetTotalTitleTime(
    ULONG *pTotalTime
);

Parameters

pTotalTime

[out] Pointer to the total time in DVD_TIMECODE format, which includes hours, minutes, seconds, and frames.

Return Value

Returns an HRESULT value.

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

The method is restricted to simple linear movies by design.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IDvdInfo::GetVMGAttributes

Note The IDvdInfo interface is deprecated. Use IDvdInfo2 instead.

Retrieves attributes of all video, audio, and subpicture streams for video manager (VMG) menus.

Syntax

HRESULT GetVMGAttributes(
    DVD_ATR *pATR
);

Parameters

pATR

[out] Pointer to the retrieved attributes structure.

Return Value

Returns an HRESULT value .

Return code | Description
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

The video manager contains a separate group of streams, such as the DVD_MENU_Title menus (see DVD_MENU_ID), and the streams are not associated with any particular title number.

See Also

  • Error and Success Codes
  • IDvdInfo Interface


IEnumRegFilters Interface

Note This interface has been deprecated. New applications should call IFilterMapper2::EnumMatchingFilters, which enumerates monikers and returns a pointer to the IEnumMoniker interface.

This interface provides methods for enumerating registered filters. The IFilterMapper::EnumMatchingFilters method returns a pointer to this interface. However, IFilterMapper has been deprecated in favor of IFilterMapper2.

In addition to the methods inherited from IUnknown, the IEnumRegFilters interface exposes the following methods.

Method | Description
Clone | Not currently implemented.
Next | Fills an array with the next filters that meet the requirements.
Reset | Makes the Next method start again, beginning at the first filter.
Skip | Not currently implemented.


IEnumRegFilters::Clone

Note The IEnumRegFilters interface is deprecated.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Clone(
    IEnumRegFilters **ppEnum
);

Parameters

ppEnum

[out] Address of a pointer to the duplicate enumerator interface.

Return Value

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IEnumRegFilters Interface


IEnumRegFilters::Next

Note The IEnumRegFilters interface is deprecated.

Fills the array with descriptions of the next set of filters (specified by the cFilters parameter) that meet the requirements specified upon creation of the enumerator.

Syntax

HRESULT Next(
    ULONG cFilters,
    REGFILTER **apRegFilter,
    ULONG *pcFetched
);

Parameters

cFilters

[in] Number of filters.

apRegFilter

[out] Address of a pointer to an array of REGFILTER pointers.

pcFetched

[out] Pointer to the actual number of filters passed.

Return Value

Returns one of the following HRESULT values.

Return code | Description
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.
E_UNEXPECTED | Unexpected error.
S_FALSE | Fewer filters were retrieved than requested.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The enumerator has become invalid. For more information, see Remarks.

Remarks

The calling application must use the Microsoft Win32 CoTaskMemFree function to free each REGFILTER pointer returned in the array. Do not free the Name member of the REGFILTER structure separately, because IEnumRegFilters::Next allocates memory for this string as part of the REGFILTER structure.

If the number of registered filters changes, the state of the enumerator will no longer be consistent with the state of the registry. As a result, this method will return VFW_E_ENUM_OUT_OF_SYNC. You should discard any data obtained from previous calls to the enumerator, because it might be invalid, and update the enumerator by calling the Reset method. You can then call the Next method safely.

See Also

  • Error and Success Codes
  • IEnumRegFilters Interface


IEnumRegFilters::Reset

Note The IEnumRegFilters interface is deprecated.

Resets the enumerator so that the next call to the IEnumRegFilters::Next method begins again at the first filter, if any.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

See Also

  • Error and Success Codes
  • IEnumRegFilters Interface


IEnumRegFilters::Skip

Note The IEnumRegFilters interface is deprecated.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Skip(
  ULONG celt
);

Parameters

celt

[in] Number of items to skip.

Return Value

Returns E_NOTIMPL.

See Also

  • Error and Success Codes
  • IEnumRegFilters Interface


IFilterMapper Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use the IFilterMapper2 interface.

This interface provides methods for registering and unregistering filters, and for looking up filters based on their characteristics.

In addition to the methods inherited from IUnknown, the IFilterMapper interface exposes the following methods.

Method | Description
EnumMatchingFilters | Finds all filters matching specific requirements.
RegisterFilter | Records the details of a filter in the registry.
RegisterFilterInstance | Registers an identifiable instance of a filter.
RegisterPin | Records the details of a pin in the registry.
RegisterPinType | Adds a type for the pin to the registry.
UnregisterFilter | Deletes a filter from the registry.
UnregisterFilterInstance | Deletes an identifiable instance of a filter.
UnregisterPin | Deletes a pin from the registry.


IFilterMapper::EnumMatchingFilters

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Provides an enumerator that enumerates registered filters that meet specified requirements.

Syntax

HRESULT EnumMatchingFilters(
    IEnumRegFilters **ppEnum,
    DWORD dwMerit,
    BOOL bInputNeeded,
    CLSID clsInMaj,
    CLSID clsInSub,
    BOOL bRender,
    BOOL bOutputNeeded,
    CLSID clsOutMaj,
    CLSID clsOutSub
);

Parameters

ppEnum

[out] Address of a pointer to the enumerator returned.

dwMerit

[in] Minimum merit value of filters to enumerate.

bInputNeeded

Value indicating whether there must be at least one input pin; TRUE indicates at least one input pin is required.

clsInMaj

[in] Input major type required. Set to GUID_NULL if you do not care.

clsInSub

[in] Input subtype required. Set to GUID_NULL if you do not care.

bRender

[in] Flag that specifies whether the filter must render the input; TRUE means that it must.

bOutputNeeded

[in] Value indicating whether there must be at least one output pin; TRUE indicates at least one output pin is required.

clsOutMaj

[in] Output major type required. Set to GUID_NULL if you do not care.

clsOutSub

[in] Output subtype required. Set to GUID_NULL if you do not care.

Return Value

Returns an HRESULT value.

Remarks

Set the ppEnum parameter to be an enumerator for filters matching the requirements. For a description of merit values for the dwMerit parameter, see the IFilterMapper::RegisterFilter method.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::RegisterFilter

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Adds a filter to the registry; the filter can then be enumerated.

Syntax

HRESULT RegisterFilter(
    CLSID clsid,
    LPCWSTR Name,
    DWORD dwMerit
);

Parameters

clsid

[in] Globally unique identifier (GUID) of the filter.

Name

[in] Descriptive name for the filter.

dwMerit

[in] Position in the order of enumeration. Filters with higher merit are enumerated first.

Return Value

Returns an HRESULT value.

Remarks

The merit (as defined by the dwMerit parameter) controls the order in which the filter graph manager tries filters when performing an operation as a result of a call to IGraphBuilder::Connect, IGraphBuilder::Render, or IGraphBuilder::RenderFile. The filter graph manager finds all filters registered with the correct media type and then tries the one with the highest merit, using other criteria in the registration to choose between filters with equal merit.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::RegisterFilterInstance

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Registers an identifiable instance of a filter.

Syntax

HRESULT RegisterFilterInstance(
    CLSID clsid,
    LPCWSTR Name,
    CLSID *MRId
);

Parameters

clsid

[in] GUID of the filter.

Name

[in] Descriptive name of the instance.

MRId

[out] Pointer to the returned media resource ID. This parameter is a locally unique identifier for this instance of this filter.

Return Value

Returns an HRESULT value.

Remarks

This method handles cases such as when two similar sound cards that are driven by the same driver are available, and it is necessary to choose which card will emit the sound. This is not needed if there is only one instance of the filter (such as when there is only one sound card in the computer), or if all instances of the filter are equivalent.

The filter itself must have already been registered.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::RegisterPin

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Records the details of the pin in the registry.

Syntax

HRESULT RegisterPin(
    CLSID Filter,
    LPCWSTR Name,
    BOOL bRendered,
    BOOL bOutput,
    BOOL bZero,
    BOOL bMany,
    CLSID ConnectsToFilter,
    LPCWSTR ConnectsToPin
);

Parameters

Filter

[in] GUID of the filter.

Name

[in] Name of the pin. This should be unique within the filter. It has no significance other than to indicate type information. You should not use pin names longer than 99 characters, because this causes filter enumeration problems.

bRendered

[in] Value specifying whether the filter renders this input. Set to TRUE if it does; otherwise, set to FALSE.

bOutput

[in] Value specifying whether this is an output pin. Set to TRUE if it is; otherwise, set to FALSE.

bZero

[in] Value specifying whether the filter can have zero instances of this pin. If it can, set to TRUE; otherwise, set to FALSE. For example, a decompression filter doesn't need to create a sound output pin for a movie without a sound track.

bMany

[in] Value specifying whether the filter can have many instances of this pin. If it can, set to TRUE; otherwise, set to FALSE. For example, a mixer might have multiple instances of its input pin.

ConnectsToFilter

[in] Reserved. Must be NULL. (This is intended for filters such as system-wide mixers that have connections outside the filter graph. It is not yet implemented.)

ConnectsToPin

[in] Reserved. Must be NULL.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::RegisterPinType

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Registers this pin type.

Syntax

HRESULT RegisterPinType(
    CLSID clsFilter,
    LPCWSTR strName,
    CLSID clsMajorType,
    CLSID clsSubType
);

Parameters

clsFilter

Class identifier (CLSID) of the filter to which the pin belongs.

strName

Name by which it is known.

clsMajorType

Major type of the media sample supported by this pin class.

clsSubType

Subtype of the media sample supported by this pin class.

Return Value

Returns an HRESULT value.

Remarks

The clsMajorType and clsSubType parameters specify the media type of the pin and correspond to the AM_MEDIA_TYPE structure's majortype and subtype members, respectively.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::UnregisterFilter

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Removes the registration of this filter from the registry.

Syntax

HRESULT UnregisterFilter(
    CLSID Filter
);

Parameters

Filter

[in] GUID of the filter.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::UnregisterFilterInstance

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Removes the registration of this filter instance from the registry.

Syntax

HRESULT UnregisterFilterInstance(
    CLSID MRId
);

Parameters

MRId

[in] Media resource identifier of this instance.

Return Value

Returns an HRESULT value.

See Also

  • Error and Success Codes
  • IFilterMapper Interface


IFilterMapper::UnregisterPin

Note The IFilterMapper interface is deprecated. Use IFilterMapper2 instead.

Removes the registration of this pin from the registry.

Syntax

HRESULT UnregisterPin(
    CLSID Filter,
    LPCWSTR Name
);

Parameters

Filter

[in] GUID of the filter that this pin is part of.

Name

[in] Name of the pin.

Return Value

Returns an HRESULT value.


AVI File Format

This section describes the AVI file format.

  • AVI RIFF File Reference
  • DV Data in the AVI File Format


AVI RIFF File Reference

The Microsoft AVI file format is a RIFF file specification used with applications that capture, edit, and play back audio-video sequences. In general, AVI files contain multiple streams of different types of data. Most AVI sequences use both audio and video streams. A simple variation for an AVI sequence uses video data and does not require an audio stream.

This section does not describe the OpenDML AVI file format extensions. For further information on these extensions, see OpenDML AVI File Format Extensions, published by the OpenDML AVI M-JPEG File Format Subcommittee.

FOURCCs

A FOURCC (four-character code) is a 32-bit unsigned integer created by concatenating four ASCII characters. For example, the FOURCC 'abcd' is represented on a Little-Endian system as 0x64636261. FOURCCs can contain space characters, so ' abc' is a valid FOURCC. The AVI file format uses FOURCC codes to identify stream types, data chunks, index entries, and other information.

RIFF File Format

The AVI file format is based on the RIFF (resource interchange file format) document format. A RIFF file consists of a RIFF header followed by zero or more lists and chunks.

  • The RIFF header has the following form:

    'RIFF' fileSize fileType (data)

    where 'RIFF' is the literal FOURCC code 'RIFF', fileSize is a 4-byte value giving the size of the data in the file, and fileType is a FOURCC that identifies the specific file type. The value of fileSize includes the size of the fileType FOURCC plus the size of the data that follows, but does not include the size of the 'RIFF' FOURCC or the size of fileSize. The file data consists of chunks and lists, in any order.

  • A chunk has the following form:

    ckID ckSize ckData

    where ckID is a FOURCC that identifies the data contained in the chunk, ckData is a 4-byte value giving the size of the data in ckData, and ckData is zero or more bytes of data. The data is always padded to nearest WORD boundary. ckSize gives the size of the valid data in the chunk; it does not include the padding, the size of ckID, or the size of ckSize.

  • A list has the following form:

    'LIST' listSize listType listData

    where 'LIST' is the literal FOURCC code 'LIST', listSize is a 4-byte value giving the size of the list, listType is a FOURCC code, and listData consists of chunks or lists, in any order. The value of listSize includes the size of listType plus the size of listData; it does not include the 'LIST' FOURCC or the size of listSize.

The remainder of this section uses the following notation to describe RIFF chunks:

ckID ( ckData )

where the chunk size is implicit. Using this notation, a list can be represented as:

'LIST' ( listType ( listData ) )

Optional elements are placed in brackets: [ optional element ]

AVI RIFF Form

AVI files are identified by the FOURCC 'AVI ' in the RIFF header. All AVI files include two mandatory LIST chunks, which define the format of the streams and the stream data, respectively. An AVI file might also include an index chunk, which gives the location of the data chunks within the file. An AVI file with these components has the following form:

RIFF ('AVI '
      LIST ('hdrl' ... )
      LIST ('movi' ... )
      ['idx1' (<AVI Index>) ]
     )

The 'hdrl' list defines the format of the data and is the first required LIST chunk. The 'movi' list contains the data for the AVI sequence and is the second required LIST chunk. The 'idx1' list contains the index. AVI files must keep these three components in the proper sequence.

Note The OpenDML extensions define another type of index, identified by the FOURCC 'indx'.

The 'hdrl' and 'movi' lists use subchunks for their data. The following example shows the AVI RIFF form expanded with the chunks needed to complete these lists:

RIFF ('AVI '
      LIST ('hdrl'
            'avih'(<Main AVI Header>)
            LIST ('strl'
                  'strh'(<Stream header>)
                  'strf'(<Stream format>)
                  [ 'strd'(<Additional header data>) ]
                  [ 'strn'(<Stream name>) ]
                  ...
                 )
             ...
           )
      LIST ('movi'
            {SubChunk | LIST ('rec '
                              SubChunk1
                              SubChunk2
                              ...
                             )
               ...
            }
            ...
           )
      ['idx1' (<AVI Index>) ]
     )

AVI Main Header

The 'hdrl' list begins with the main AVI header, which is contained in an 'avih' chunk. The main header contains global information for the entire AVI file, such as the number of streams within the file and the width and height of the AVI sequence. The main header chunk consists of an AVIMAINHEADER structure.

AVI Stream Headers

One or more 'strl' lists follow the main header. A 'strl' list is required for each data stream. Each 'strl' list contains information about one stream in the file, and must contain a stream header chunk ('strh') and a stream format chunk ('strf'). In addition, a 'strl' list might contain a stream-header data chunk ('strd') and a stream name chunk ('strn').

The stream header chunk ('strh') consists of an AVISTREAMHEADER structure.

A stream format chunk ('strf') must follow the stream header chunk. The stream format chunk describes the format of the data in the stream. The data contained in this chunk depends on the stream type. For video streams, the information is a BITMAPINFO structure, including palette information if appropriate. For audio streams, the information is a WAVEFORMATEX structure.

If the stream-header data ('strd') chunk is present, it follows the stream format chunk. The format and content of this chunk are defined by the codec driver. Typically, drivers use this information for configuration. Applications that read and write AVI files do not need to interpret this information; they simple transfer it to and from the driver as a memory block.

The optional 'strn' chunk contains a null-terminated text string describing the stream.

The stream headers in the 'hdrl' list are associated with the stream data in the 'movi' list according to the order of the 'strl' chunks. The first 'strl' chunk applies to stream 0, the second applies to stream 1, and so forth.

Stream Data ('movi' List)

Following the header information is a 'movi' list that contains the actual data in the streams — that is, the video frames and audio samples. The data chunks can reside directly in the 'movi' list, or they might be grouped within 'rec ' lists. The 'rec ' grouping implies that the grouped chunks should be read from disk all at once, and is intended for files that are interleaved to play from CD-ROM.

The FOURCC that identifies each data chunk consists of a two-digit stream number followed by a two-character code that defines the type of information in the chunk.

Two-character code | Description
db | Uncompressed video frame
dc | Compressed video frame
pc | Palette change
wb | Audio data

For example, if stream 0 contains audio, the data chunks for that stream would have the FOURCC '00wb'. If stream 1 contains vidoe, the data chunks for that stream would have the FOURCC '01db' or '01dc'. Video data chunks can also define new palette entries to update the palette during an AVI sequence. Each palette-change chunk ('xxpc') contains an AVIPALCHANGE structure. If a stream contains palette changes, set the AVISF_VIDEO_PALCHANGES flag in the dwFlags member of the AVISTREAMHEADER structure for that stream.

Text streams can use arbitrary two-character codes.

AVI Index Entries

An optional index ('idx1') chunk can follow the 'movi' list. The index contains a list of the data chunks and their location in the file. It consists of an AVIOLDINDEX structure with entries for each data chunk, including 'rec ' chunks. If the file contains an index, set the AVIF_HASINDEX flag in the dwFlags member of the AVIMAINHEADER structure.

Other Data Chunks

Data can be aligned in an AVI file by inserting 'JUNK' chunks as needed. Applications should ignore the contents of a 'JUNK' chunk.

See Also

  • AVI File Format


DV Data in the AVI File Format

Microsoft has specified the format for storage of digital video (DV) data in AVI files. Conforming to this specification will ensure that the AVI files authored in this format will be compatible with future versions of the Microsoft® DirectShow® digital video architecture for the Microsoft® Windows® platform.

This article describes the format of AVI files containing DV data. Specific FOURCCs (four-character codes) for interleaved DV data streams and DV compressor/decompressor stream handlers are defined. The stream format structure for DV data is defined. Specifications for two methods of storing DV data in the AVI file format are specified.

It is assumed that the reader is familiar with the DV data format. (This format is defined in the Specification of Consumer-use Digital VCRs, also called the Blue Book).

There are two types of DV AVI files: AVI files that contain one DV data stream, called type-1 files; and AVI files that contain DV video as a 'vids' stream and DV audio as 'auds' streams, called type-2 files.

AVI Files Containing One DV Data Stream (Type-1)

Interleaved DV data can be stored in its native format as a single stream within an AVI RIFF file. This has the advantage of using the minimum amount of data storage for DV. The primary disadvantage is that this file format is not backward-compatible with Video for Windows, because it doesn't contain either a video 'vids' or an audio 'auds' stream. Support is provided for the interleaved DV stream through the DV Muxer and DV Splitter filters provided with DirectShow.

DV data can be stored in a single stream within an AVI RIFF file by specifying the 'iavs' (interleaved audio and video stream) FOURCC (four-character code) in the fccType member and either of the 'dvsd', 'dvhd', or 'dvsl' FOURCCs in the fccHandler member of the 'strh' stream header chunk. The frames per second of the video stream must be specified in the dwRate and dwScale members and the total number of video blocks in the 'movi' chunk in the dwLength member.

The 'dvsd' stream handler FOURCC specifies that the DV data is as defined in Part 2 of the Specification of Consumer-use Digital VCRs. Video is in the format of 525 lines at 29.97 Hz (525-60) or 625 lines at 25.00 Hz (625-50).

The 'dvhd' stream handler FOURCC specifies that the DV data is as defined in Part 3 of the Specification of Consumer-use Digital VCRs. Video is in the format of 1125 lines at 30.00 Hz (1125-60) or 1250 lines at 25.00 Hz (1250-50).

The 'dvsl' stream handler FOURCC specifies that the DV data is as defined in Part 6 of Specification of Consumer-use Digital VCRs. Video is in the format of high-compression SD (SDL).

Note The remainder of this article provides definitions for 'dvsd' streams.

The stream header chunk must be followed by a DVINFO stream format chunk.

The actual DV data is stored as '##dc' chunks in the 'movi' chunk (the ## in the format represents the stream identifier). Each chunk contains one frame of data, either 10 or 12 DV DIF sequences for 525-60 or 625-50 systems, respectively. The DV SD ('dvsd') DIF sequence format is defined in Part 2 of the Specification of Consumer-use Digital VCRs.

The following example shows the AIFF RIFF form for an AVI file with one DV data stream, expanded with completed header chunks.

00000000 RIFF (0FAE35D4) 'AVI '
0000000C     LIST (00000106) 'hdrl'
00000018         avih (00000038)
                     dwMicroSecPerFrame    : 33367
                     dwMaxBytesPerSec      : 3728000
                     dwPaddingGranularity  : 0
                     dwFlags               : 0x810 HASINDEX | TRUSTCKTYPE
                     dwTotalFrames         : 2192
                     dwInitialFrames       : 0
                     dwStreams             : 1
                     dwSuggestedBufferSize : 120000
                     dwWidth               : 720
                     dwHeight              : 480
                     dwReserved            : 0x0
00000058         LIST (0000006C) 'strl'
00000064             strh (00000038)
                         fccType               : 'iavs'
                         fccHandler            : 'dvsd'
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 100 (29.970 Frames/Sec)
                         dwRate                : 2997
                         dwStart               : 0
                         dwLength              : 2192
                         dwSuggestedBufferSize : 120000
                         dwQuality             : 0
                         dwSampleSize          : 0
                         rcFrame               : 0,0,720,480
000000A4             strf (00000020)
                         dwDVAAuxSrc     : 0x........
                         dwDVAAuxCtl     : 0x........
                         dwDVAAuxSrc1    : 0x........
                         dwDVAAuxCtl1    : 0x........
                         dwDVVAuxSrc     : 0x........
                         dwDVVAuxCtl     : 0x........
                         dwDVReserved[2] : 0,0
000000CC     LIST (0FADAC00) 'movi'
0FADACD4     idx1 (00008900)

AVI Files Containing DV Video and DV Audio Streams (Type-2)

Interleaved DV data can be split into a video stream and one to four audio streams within an AVI RIFF file. This has the advantage of being backward-compatible with Video for Windows, because it contains a standard video 'vids' stream and at least one standard audio 'auds' stream The primary disadvantage is that this file format requires the audio data to be redundantly stored as audio streams. The "video" stream is actually the native interleaved DV data stream. However, as a standard 'vids' stream with a handler type of 'dvsd', the DV Video Decoder is used. This format also requires using the DV Splitter filter to split "captured" files before writing them as AVI files.

DV data can be stored as a video stream with a separate number of audio streams in an AVI RIFF file. The video stream is specified with a standard video stream header (the fccType member value is 'vids'). The fccHandler member is specified as 'dvsd', 'dvhd', or 'dvsl'. The frames per second of the video stream must be specified in the dwRate and dwScale members and the total number of video blocks in the 'movi' chunk in the dwLength member.

In this AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams form of DV, the video stream format chunk is a standard BITMAPINFOHEADER structure. The stream format chunk can be optionally extended to include the DVINFO chunk, by increasing the stream format chunk size from 40 bytes (size of the BITMAPINFOHEADER structure) to 72 bytes (size of BITMAPINFOHEADER plus DVINFO structures) and immediately following the BITMAPINFOHEADER data structure with a DVINFO data structure.

The audio stream(s) is specified with a standard audio stream header (the fccType member value is 'auds'). The fccHandler member is not used for audio streams.

The DV video data is stored as '##dc' chunks, as defined in the preceding description of an AVI file with one DV data, and the audio data is stored as '##wb' chunks in the 'movi' chunk.

The following example shows the AIFF RIFF form for an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams expanded with completed header chunks (including optional DVINFO data following the BITMAPINFO in the 'strf' sub-chunk for the 'vids' stream).

00000000 RIFF (103E2920) 'AVI '
0000000C     LIST (00000146) 'hdrl'
00000018         avih (00000038)
                     dwMicroSecPerFrame    : 33367
                     dwMaxBytesPerSec      : 3728000
                     dwPaddingGranularity  : 0
                     dwFlags               : 0x810 HASINDEX | TRUSTCKTYPE
                     dwTotalFrames         : 2192
                     dwInitialFrames       : 0
                     dwStreams             : 2
                     dwSuggestedBufferSize : 120000
                     dwWidth               : 720
                     dwHeight              : 480
                     dwReserved            : 0x0
00000058         LIST (00000094) 'strl'
00000064             strh (00000038)
                         fccType               : 'vids'
                         fccHandler            : 'dvsd'
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 100 (29.970 Frames/Sec)
                         dwRate                : 2997
                         dwStart               : 0
                         dwLength              : 2192
                         dwSuggestedBufferSize : 120000
                         dwQuality             : 0
                         dwSampleSize          : 0
                         rcFrame               : 0,0,720,480
000000A4             strf (00000048)
                         biSize          : 40
                         biWidth         : 720
                         biHeight        : 480
                         biPlanes        : 1
                         biBitCount      : 24
                         biCompression   : 0x64737664 'dvsd'
                         biSizeImage     : 120000
                         biXPelsPerMeter : 0
                         biYPelsPerMeter : 0
                         biClrUsed       : 0
                         biClrImportant  : 0
                         dwDVAAuxSrc     : 0x........
                         dwDVAAuxCtl     : 0x........
                         dwDVAAuxSrc1    : 0x........
                         dwDVAAuxCtl1    : 0x........
                         dwDVVAuxSrc     : 0x........
                         dwDVVAuxCtl     : 0x........
                         dwDVReserved[2] : 0,0
000000F4         LIST (0000005E) 'strl'
00000100             strh (00000038)
                         fccType               : 'auds'
                         fccHandler            : '    '
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 1 (32000.000 Samples/Sec)
                         dwRate                : 32000
                         dwStart               : 0
                         dwLength              : 2340474
                         dwSuggestedBufferSize : 4272
                         dwQuality             : 0
                         dwSampleSize          : 4
                         rcFrame               : 0,0,0,0
00000140             strf (00000012)
                         wFormatTag      : 1 PCM
                         nChannels       : 2
                         nSamplesPerSec  : 32000
                         nAvgBytesPerSec : 128000
                         nBlockAlign     : 4
                         wBitsPerSample  : 16
                         cbSize          : 0
00000814     LIST (103D0EF4) 'movi'
103D1710     idx1 (00011210)

See Also

  • AVI File Format


DVD Region Change Support in Windows

This section explains how the DVD region selection process works under Microsoft® Windows® 9x and Windows 2000. The first section describes the three sources of DVD Region Information. The second section describes how PC system manufacturers can set a system's initial DVD region. The third section explains how the DVD Navigator determines region match between the drive, decoder and disc. The last section shows how application and decoder developers can implement correct DVD region selection support in their code.

  • Sources of DVD Region Information
  • Setting the Initial DVD Region in Windows 98 and Windows 2000
  • How Microsoft DVD Navigator Selects the DVD Region
  • Subsequent DVD Region Change
  • Installing the Windows Region Change Support Components
  • Adding Region-Change Support to an Application


Sources of DVD Region Information

There are three sources of DVD region information that work together to determine the region for DVD playback on a Windows PC.

  • DVD Title

    Most DVD titles are marked for a specific region. Some titles can be played in only one region, some can be played in multiple regions, and others can be played all regions.

  • DVD-ROM Drive

    There are two types of DVD-ROM drives: RPC Phase 1 and RPC Phase 2 (hereafter referred to as RPC1 and RPC2) drives. RPC1 drives do not have built-in hardware support for region management. For these drives, Windows maintains the region change count information and the region can be changed only once. RPC2 drives maintain the region change count information in hardware and in general the region of such drives can be changed up to 5 times.

  • DVD Decoder

    Some DVD decoders, hardware or software, are set for a specific region. In general, the user cannot change the decoder's region.


Setting the Initial DVD Region in Windows 98 and Windows 2000

It is the responsibility of the system manufacturer to select an initial DVD region for the DVD drive in their PCs.

Important Only encrypted discs can be used to set the region.

  • Windows 98

    The system manufacturer can set a Registry key (HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\DefaultDVDRegion (binary)) to set the default DVD region for the drive. The value of this key should be set to the region number for which it should be set on first playback. System manufacturers using OPK builds can add this value to the registry during an "audit mode boot," so the end user never sets the initial region. If this key is set before any DVD title is played on a DVD-enabled Windows system, then the Windows components will select that region for the drive on the first attempt to play back a DVD title.

    If the system manufacturer sets the default region in the Registry and then plays a multi-region disc that includes the default region, the region is set to the default and the disc just plays. If the disc's region does not match the default region, the user will be prompted to change to the required region. (This will be the only region change allowed for an RPC-1 drive.) If no such default region is specified by the system manufacturer, Windows picks a region based on the Operating System locale, time zone, and other factors. If the first disc played is a multi-region disc, then Windows picks the region based on the locale, time zone, and other factors and looks for a match with the lowest region number. If no region on the multi-region disc matches the region picked by Windows, then the region with the lowest number on disc is selected.

If the manufacturer does not set a region, on first boot the Windows 98 Operating System base components will pick a region based on the Operating System language and the time zone and set the drive to that region. The system manufacturer is free to set the region on the drive and if that is not done during the manufacturing process, it is up to Windows to select the drive's region based on the best guess it can make.

  • Windows 2000

    In Windows 2000, the default DVD region is selected based upon the locale that the machine is set up for. Windows 2000 will always set the initial region for a DVD drive using this default region as well as the disc's region, if there is a disc is in the drive. The system manufacturer does not have to do anything to set the initial region for Windows 2000 DVD drives.

    For RPC1 drives, if there is no disc in the drive during boot up then the default region is set based only on the locale of the machine. If there is a DVD disc in the drive during boot up, the default region is selected to be the drive's region, provided it matches a region of the disc; otherwise the lowest region on the disc is picked as the initial region of the drive. The user (or system manufacturer) has one remaining change allowed, in case the default was not correct.

For RPC2 drives, if during the setup process Windows 2000 finds that the drive does not have any region set (for example fresh drive), it will try to pick a region as above, but only if there is a disc in the drive. (RPC1 drives will choose the region without any disc in drive). Once a region is set for RPC2 drives, it is not auto-changed by either a re-installation or a clean installation of the Operating System.

The registry key on Windows 2000 systems is HKLM\System\CurrentControlSet\Control\Class\<CDROM GUID>\ <instance number>\DefaultDVDRegion(binary) .


How Microsoft DVD Navigator Selects the DVD Region

The Microsoft DVD Navigator uses the following method to determine region match while playing DVD discs on a PC:

The DVD Navigator gets the disc's region, drive's region and decoder's region. If the disc region is "all regions" then the DVD Navigator plays the disc. If the disc is not marked for all regions, the DVD Navigator checks whether the decoder has a preset region. If the decoder has a preset region and it does not match the disc's region, the DVD Navigator will return an error indicating that it cannot play the disc on the current DVD configuration. If the decoder's region is the same as the disc's region, the DVD Navigator will then check whether the drive's region is the same as the disc's region. If they are the same, the DVD Navigator will play the title. If they are not the same, then the DVD Navigator invokes the code to change the drive's region. If the allowed number of region changes has been exhausted, then the region change attempt fails and the title can't be played on that system.


Subsequent DVD Region Change

On Windows 9x, when the DVD Navigator detects that a region change on the DVD drive is necessary, it uses DVDRgn.exe to request a region change on the drive. This application is regionalized along with other components of the operating system. This application is not installed by default under Windows 98. A method of installing it on the target system is demonstrated below.

In Windows 2000, the DVD Navigator invokes a property page on the DVD-ROM drive device in the Device Manager. This property page is also brought up by the DVDPlay.exe application when a region needs to be changed. The UI of this property page is very similar to that of DVDRgn.exe and it is regionalized in the operating system.

For RPC1 drives, the Windows Operating System components manage region changes. RPC2 drives maintain the region setting in their own hardware. When the number of allowed changes are exhausted on a RPC2 drive, the drive will fail the call to change the region and the region-change component in the operating system will indicate that to the user.


Installing the Windows Region Change Support Components

Application developers can utilize the DVD region change support built into Windows to change region inside the DVD playback applications. There are two different ways of doing this for the Windows 9x and Windows 2000 platforms.

  • Under Windows 9x

    Under Windows 9x platforms, the region-change application, DVDRgn.exe, is installed only when a hardware decoder with a WDM stream class minidriver is installed using the standard INF file. For other software decoders and the upgrade market, insert the following lines into an INF file used by an installation program to add DVDRgn.exe to the target system.

    [Version]
Signature=$CHICAGO$
LayoutFile=layout.inf

[DestinationDirs]
DvdRgnCopy=25       ; Windows
DefaultDestDir=25   ; Windows

[DefaultInstall]
CopyFiles=DvdRgnCopy

[DvdRgnCopy]
dvdrgn.exe

  • Under Windows 2000
    On Windows 2000 systems the component that provides the DVD region change support is in the DLL storprop.dll (available in %windir%\system32). This DLL is installed by default and no extra steps are required to ensure that this DLL is available.


Adding Region-Change Support to an Application

The following functions are provided for developers who wish to integrate region-change support into their decoders or DVD applications.

// Forward declares, constants, typedefs.
const short MAX_DRIVE_NAME = 4;
struct DriveName
{
    TCHAR name[MAX_DRIVE_NAME];
};
BOOL DoesFileExist(LPTSTR pszFile);
BOOL GetDriveLetter(IDvdInfo2 *pDvd, DriveName& szDrive);

/////////////////////////////////////////////////////////////////////
// ChangeDVDRegion :  Function to change the DVD drive region.
// Parameters:
//     hWnd - Handle to the application window.
// Returns TRUE if the change is successful, or FALSE otherwise.
// (Failure usually means there was no drive with a valid DVD-V disc.)
/////////////////////////////////////////////////////////////////////
BOOL ChangeDVDRegion(HWND hWnd, IDvdInfo2 *pDvd)
{
    typedef BOOL (APIENTRY *DVDPPLAUNCHER) (HWND hWnd, CHAR DriveLetter);

    // First find out which drive is a DVD drive with a valid DVD-V disc.
    DriveName  szDVDDrive;

    if (! GetDriveLetter(pDvd, szDVDDrive) )
    {
        MessageBox(hWnd, TEXT("No DVD drive was found with DVD-V disc."),
            TEXT("Error"), MB_OK | MB_ICONERROR) ;
        return FALSE;
    }

    // Detect which OS we are running on.

    OSVERSIONINFO   ver;
    ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&ver);

    if (VER_PLATFORM_WIN32_NT  == ver.dwPlatformId)
    {
        // For Windows NT, use the storprop.dll,

        HINSTANCE      hInstDLL;
        DVDPPLAUNCHER  dvdPPLauncher;
        CHAR           szDVDDriveA[MAX_DRIVE_NAME];

        const TCHAR szDllName[] =  TEXT("\\storprop.dll");

        // Allocate a large enough string to hold the path + the name.
        TCHAR szCmdLine[MAX_PATH + (sizeof(szDllName)/sizeof(TCHAR)) + 1];

#ifdef UNICODE
        WideCharToMultiByte(CP_ACP, 0, szDVDDrive.name, -1,
            szDVDDriveA, sizeof(szDVDDriveA), NULL, NULL );
#else
        strncpy(szDVDDriveA, szDVDDrive.name, MAX_DRIVE_NAME);
#endif

        UINT cb = GetSystemDirectory(szCmdLine, MAX_PATH + 1);
        if (cb == 0 || cb > MAX_PATH + 1)
        {
            return FALSE;
        }

        lstrcat(szCmdLine, szDllName);

        hInstDLL = LoadLibrary (szCmdLine);
        if (hInstDLL)
        {
            BOOL bResult = FALSE;

            dvdPPLauncher = (DVDPPLAUNCHER) GetProcAddress(hInstDLL,
                "DvdLauncher");
            if (dvdPPLauncher)
            {
                 bResult = dvdPPLauncher(hWnd, szDVDDriveA[0]);
            }
            FreeLibrary(hInstDLL);
            return bResult;
        }
    }
    else
    {
        // For Windows 9x use the DVDRgn.exe application.

        const TCHAR szUtilName[] = TEXT("\\DVDRgn.exe ");

        // Allocate a large enough string, including a one-character command-line argument.
        TCHAR szCmdLine[MAX_PATH + (sizeof(szUtilName)/sizeof(TCHAR)) + 2];

        // Get path of \windows\dvdrgn.exe for command line string
        UINT cb = GetWindowsDirectory(szCmdLine, MAX_PATH + 1);
        if (cb == 0 || cb > MAX_PATH + 1)
        {
            return FALSE;
        }

        lstrcat(szCmdLine, szUtilName);

        // Add only the drive letter as command line parameter
        _tcsnccat(szCmdLine, szDVDDrive.name, 1);

        // Prepare to execute DVDRgn.exe
        STARTUPINFO               StartupInfo;
        PROCESS_INFORMATION       ProcessInfo;
        StartupInfo.cb            = sizeof(StartupInfo);
        StartupInfo.dwFlags       = STARTF_USESHOWWINDOW;
        StartupInfo.wShowWindow   = SW_SHOWNORMAL;
        StartupInfo.lpReserved    = NULL;
        StartupInfo.lpDesktop     = NULL;
        StartupInfo.lpTitle       = NULL;
        StartupInfo.cbReserved2   = 0;
        StartupInfo.lpReserved2   = NULL;
        if (CreateProcess(0, szCmdLine,
            NULL, NULL, TRUE,
            NORMAL_PRIORITY_CLASS,
            NULL, NULL, &StartupInfo, &ProcessInfo) )
        {
            // Wait until DVDRgn.exe finishes
            WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
            DWORD dwRet = 1;
            BOOL bRet = GetExitCodeProcess(ProcessInfo.hProcess,
                &dwRet);
            // If the user changed the drive region
            // successfully, the exit code of DVDRgn.exe is 0.
            if (bRet && 0 == dwRet)
            {
                return TRUE;
            }
        }
    }

    return FALSE;
}

/////////////////////////////////////////////////////////////////////
// GetDriveLetter: Returns the drive letter of the active DVD drive.
// Parameters:
//     pDvdC - IDvdControl2 interface of the DVD Navigator filter.
//     pszDrive - Receives the first DVD drive with a valid DVD-V disc.
// Returns TRUE if there is a DVD drive with a valid disc.
/////////////////////////////////////////////////////////////////////
BOOL GetDriveLetter(IDvdInfo2 *pDvd, DriveName& pszDrive)
{
    WCHAR  szPathW[MAX_PATH];
    TCHAR  szPath[MAX_PATH];
    ULONG  ulActualSize = 0;

    pszDrive.name[0] = pszDrive.name[MAX_DRIVE_NAME - 1] = 0;

    // Get the current root directory
    HRESULT hr = pDvd->GetDVDDirectory(szPathW, MAX_PATH, &ulActualSize);

    if (SUCCEEDED(hr))
    {

#ifdef UNICODE
        lstrcpyn(pszDrive.name, szPathW, MAX_DRIVE_NAME);
#else
        WideCharToMultiByte(CP_ACP, 0, szPathW, ulActualSize, szPath, MAX_PATH, 0, 0);
        lstrcpyn(pszDrive.name, szPath, MAX_DRIVE_NAME);
#endif

        if (DRIVE_CDROM == GetDriveType(pszDrive.name)) // could be a DVD drive
            return TRUE;
    }

  // Now loop through all the valid drives to detect which one
  // is a DVD drive with a valid DVD-V disc in it.

  // Get all valid drives
  DWORD dwLen = GetLogicalDriveStrings(MAX_PATH, szPath);

  if (dwLen > MAX_PATH)
  {
      // The function returns a larger value if the buffer is too small.
      return FALSE;
  }

  // Try all drives one by one
  for (DWORD dw = 0; dw < dwLen; )
  {

      TCHAR *szTmp = szPath + dw;

      // Look only for CD-ROM drives that has a disc with required (.ifo) files
      if (DRIVE_CDROM  == GetDriveType(szTmp))
      {
          TCHAR   szDVDPath1[MAX_PATH + 1];
          TCHAR   szDVDPath2[MAX_PATH + 1];

          lstrcpyn(szDVDPath1, szTmp, MAX_DRIVE_NAME);
          lstrcpyn(szDVDPath2, szTmp, MAX_DRIVE_NAME);
          lstrcat(szDVDPath1, TEXT("Video_ts\\Video_ts.ifo"));
          lstrcat(szDVDPath2, TEXT("Video_ts\\Vts_01_0.ifo"));

          // If the .ifo files exist on this drive then it has a valid DVD-V disc
          if (DoesFileExist(szDVDPath1) && DoesFileExist(szDVDPath2))
          {
              lstrcpyn(pszDrive.name, szTmp, MAX_DRIVE_NAME);
              return TRUE;   // return the first drive that has a valid DVD-V disc
          }
      }
      dw += lstrlen(szTmp) + 1;
  }

  return FALSE ;   // didn't find any DVD drive with DVD-V content
}

/////////////////////////////////////////////////////////////////////
// DoesFileExist : Determines whether a specified file exists
// Parameters:
//     pszFile - File name to check.
// Returns TRUE if the specified file is found, or FALSE otherwise.
/////////////////////////////////////////////////////////////////////
BOOL DoesFileExist(LPTSTR pszFile)
{
    if (pszFile == NULL)
    {
        return FALSE;
    }

    if (lstrlen(pszFile) > MAX_PATH)
    {
        return FALSE;
    }

    // We don't want any error message box to pop up when we try to test
    // if the required file is available to open for read.

    UINT uErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);

    HANDLE hFile = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ, NULL,
        OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);

    SetErrorMode(uErrorMode);  // restore error mode

    if (INVALID_HANDLE_VALUE  == hFile)
    {
        return FALSE;
    }

    CloseHandle(hFile);
    return TRUE;
}


DVD Drive Spin Down Timeout

On laptop computers, to conserve battery life it may be desirable to reduce the length of time that a DVD drive will continue to spin after the user has paused playback. By default, the DVD Navigator keeps the disc spinning for two minutes. This value can be modified in the Windows Registry under this key:

DWORD HKLM\SOFTWARE\Microsoft\DVDNavigator\DriveSpindown [Sec]

where Sec is the spin down time in seconds.


DirectX Media Objects

Microsoft® DirectX® Media Objects (DMOs) are COM-based data-streaming components. In some respects, DMOs are similar to Microsoft DirectShow® filters. Like DirectShow filters, DMOs take input data and use it to produce output data. However, the application programming interfaces (APIs) for DMOs are much simpler than the corresponding APIs for DirectShow. As a result, DMOs are easier to create, test, and use. DMOs can be used in many scenarios:

  • Applications based on DirectShow can use DMOs through a DirectShow filter called the DMO Wrapper filter. The distinction between filters and DMOs is transparent to the application. The application does not directly call the DMO APIs.
  • Applications based on Microsoft DirectSound® can use audio effect DMOs. Again, the application is shielded from the low-level DMO APIs by the higher-level DirectSound APIs.
  • Applications can use DMOs directly.

Thus, by writing a DMO, you create a component that can be used in a wide range of applications. This documentation contains the following sections:

  • About DMOs
  • Using DMOs
  • Writing a DMO
  • Media Parameters
  • DMO Reference


About DMOs

This section contains the following topics:

  • Benefits of DMOs
  • DMO Architecture


Benefits of DMOs

DMOs offer the following advantages:

  • They are generally smaller and simpler than DirectShow filters, because they support less functionality.
  • They are more flexible than DirectShow filters because they do not require a filter graph. You can use them with DirectShow when you need the services that DirectShow provides, such as synchronization, intelligent connection, automatic handling of data flow, and thread management. Clients that do not need these services can access DMOs directly.
  • DMOs always perform synchronous data processing, which eliminates many of the threading issues that you must consider if you write a filter.
  • Unlike traditional ACM and VCM codecs, DMOs are based on the Component Object Model (COM), so they can be extended through QueryInterface.
  • DMOs support a more generalized streaming model than ACM or VCM codecs. Like DirectShow filters, DMOs can support multiple inputs and multiple outputs.

For these reasons, DMOs are now recommended as the solution for writing encoders, decoders, and audio effects. Many other scenarios are possible as well, depending on the needs of the application.

How DMOs Differ from DirectShow Filters

DirectShow filters cannot function outside of a DirectShow filter graph. In DirectShow, the Filter Graph Manager mediates between the application and the filters. DirectShow filters do most of the work required to stream data, including:

  • Allocating buffers.
  • Negotiating media types and connections to other filters.
  • Pushing data through the filter graph.
  • Sending events to the Filter Graph Manager.
  • Synchronizing multiple threads.

In contrast, a DMO does none of these things. Instead, these kinds of tasks are the responsibility of the client using the DMO. The client allocates buffers, fills them with data, and delivers them to the DMO. The DMO processes the data, and the client retrieves the resulting output buffers.


DMO Architecture

This section describes the overall architecture of a DMO.

Streams

A DMO is an object that takes m inputs and produces n outputs. The inputs and outputs are called streams. Every DMO has at least one stream. Streams are not objects; they are simply referenced on the DMO by index number. The number of streams is fixed at design time.

Media Types

All data is typed using a media type, which defines how to interpret the contents of the data. For example, 320 x 240 24-bit RGB video is one type; 44.1-kilohertz (kHz) 16-bit stereo PCM audio is another type. Media types are described using the DMO_MEDIA_TYPE structure. Before the client can process any data, it must set the media type for each stream on the DMO.

Typically, a stream can accept a range of media types. Some DMOs support a wider range of types than others. The DMO interfaces define methods for the client to discover the supported types. For example, one DMO might support RGB video at any bit depth, while another might support only 24-bit RGB. Also, a DMO might be limited to certain combinations of inputs and outputs. For example, if the input type is 16-bit video, the output stream might require the same bit depth. The client can enumerate each stream's preferred types and then test specific combinations.

Buffers

In the default DMO model, the client allocates separate input buffers and output buffers. It fills the input buffers with data and delivers them to the DMO, and the DMO writes new data into the output buffers.

Optionally, a DMO can support "in-place" processing. With in-place processing, the DMO writes the output directly into the input buffer, over the original data. In-place processing eliminates the need for separate buffers. On the other hand, it alters the original data, which may not be acceptable for some applications.

The default (non-in-place) buffering model is supported through the IMediaObject interface. All DMOs must implement this interface. If a DMO supports in-place processing, it also exposes the IMediaObjectInPlace interface. The client is responsible for allocating all buffers, both input and output.


Using DMOs

This section describes how to use DMOs. It contains the following topics.

  • Directly Hosting a DMO
  • Using DMOs in DirectShow


Directly Hosting a DMO

This section describes how an application can act as the direct client of a DMO. The application delivers input to the DMO, the DMO creates output, and the application uses the output for rendering, further processing, or anything else. The application is responsible for issues such as memory allocation, timing and synchronization, and threading. These requirements will depend on the nature of the application.

The information in this section also applies if you are writing a component that acts as a layer between an application and a DMO (for example, an ActiveX Control that hosts a DMO). In addition, you should read this section if you are writing a DMO, because it describes the functionality that your DMO must implement.

This section contains the following topics:

  • Setting Media Types on a DMO
  • Processing Data in a DMO
  • In-Place Processing
  • Optional Streams
  • Implementing IMediaBuffer


Setting Media Types on a DMO

Before a DMO can process any data, the client must set the media type for each stream. (There is one minor exception to this rule; see Optional Streams.) To find the number of streams, call the IMediaObject::GetStreamCount method:

DWORD cInput = 0, cOutput = 0;
pDMO->GetStreamCount(&cInput, &cOutput);

This method returns two values, the number of inputs and the number of outputs. These values are fixed for the lifetime of the DMO.

Preferred Types

For every stream, the DMO assigns a list of possible media types, in order of preference. For example, the preferred types might be 32-RGB, 24-bit RGB, and 16-bit RGB, in that order. When the client sets the media types, it can use these lists as a hint. To retrieve a preferred type for a stream, call the IMediaObject::GetInputType method or IMediaObject::GetOutputType method. Specify the stream number and an index value for the type (starting from zero). For example, the following code retrieves the first preferred type from the first input stream:

DMO_MEDIA_TYPE mt
hr = pDMO->GetInputType(0, 0, &mt)
if (SUCCEEDED(hr))
{
    // Examine this media type (not shown).
    /* ... */

    // Free the format block.
    MoFreeMediaType(&mt);
}

To enumerate all of the preferred media types on a given stream, use a loop that increments the type index until the method returns DMO_E_NO_MORE_ITEMS, as shown in the following example:

DMO_MEDIA_TYPE mt;
DWORD iType = 0;
while (hr = pDMO->GetInputType(0, iType, &mt), SUCCEEDED(hr))
{
    // Examine this media type (not shown).
    /* ... */

    // Free the format block.
    MoFreeMediaType(&mt);
    ++dwType;
}

You should note the following points about preferred types:

  • The DMO might return a type that has no format block. For example, a DMO could specify a video type, such as 24-bit RGB, without providing the width and height of the image. When you set the type, however, you must provide a complete format block. (Some media types, such as MIDI, never require a format block, in which case this remark does not apply.)
  • The DMO is not required to support every combination of preferred types that it returns. For example, if a DMO has two streams, and each stream has four preferred types, there are 16 possible combinations, but not all of them are guaranteed to be valid.
  • When the client sets the media type for one stream, the DMO might update the preferred types for other streams to reflect the new state. It is not required to do so, however.
  • For some streams, the DMO might not offer any preferred types. Typically, a DMO should offer at least some preferred types on some streams.
  • The DMO is not required to offer a complete list of the media types it can accept. There might be "unadvertised" types that the DMO supports but does not offer as preferred types.

In short, the client should treat the preferred types as guidelines only. The only way to know for certain which types are supported is to test them, as described in the next section.

Setting the Media Type on a Stream

Use the IMediaObject::SetInputType and IMediaObject::SetOutputType methods to set the type for each stream. You must provide a DMO_MEDIA_TYPE structure that contains a complete description of the media type. The following example sets the media type on input stream 0, using 44.1-kHz 16-bit stereo PCM audio:

DMO_MEDIA_TYPE mt;
ZeroMemory(&mt, sizeof(DMO_MEDIA_TYPE));
// Allocate memory for the format block.
HRESULT hr = MoInitMediaType(&mt, sizeof(WAVEFORMATEX));
if (SUCCEEDED(hr))
{
    // Set the type GUIDs.
    mt.majortype  = MEDIATYPE_Audio;
    mt.subtype    = MEDIASUBTYPE_PCM;
    mt.formattype = FORMAT_WaveFormatEx;

    // Initialize the format block.
    WAVEFORMATEX *pWave = reinterpret_cast<WAVEFORMATEX*>(mt.pbFormat);
    pWave->wFormatTag = WAVE_FORMAT_PCM;
    pWave->nChannels = 2;
    pWave->nSamplesPerSec = 44100;
    pWave->wBitsPerSample = 16;
    pWave->nBlockAlign = (pWave->nChannels * pWave->wBitsPerSample) / 8;
    pWave->nAvgBytesPerSec = pWave->nSamplesPerSec * pWave->nBlockAlign;
    pWave->cbSize = 0;

    // Set the media type.
    hr = pDMO->SetInputType(0, &mt, 0);

    // Release the format block.
    MoFreeMediaType(&mt);
}

To test a media type without setting it, call SetInputType or SetOutputType with the DMO_SET_TYPEF_TEST_ONLY flag. The method returns S_OK if the type is acceptable, or S_FALSE otherwise:

if (S_OK == pDMO->SetInputType(DMO_SET_TYPEF_TEST_ONLY, &mt, 0)
{
    // Media type is OK.
}

Because the settings on one stream can affect another stream, you might need to clear a stream's media type. To do this, call SetInputType or SetOutputType with the DMO_SET_TYPEF_CLEAR flag.

For a decoder DMO, the client would typically set the input type first, and then choose an output type. For an encoder DMO, the client would set the output type first, and then the input type.


Processing Data in a DMO

This section explains how to process a stream of data using a DMO. The steps listed in this section are the default behavior; all DMOs must support the methods described here. These methods use separate buffers for input and output. Some DMOs also support in-place processing, using a single buffer. For more information about in-place processing, see In-Place Processing.

Allocating Buffers

The client is responsible for all buffer allocation. After you set the media types on the DMO, query the DMO for each stream's buffer requirements. These can change depending on the media type. For each stream, call the IMediaObject::GetInputSizeInfo or IMediaObject::GetOutputSizeInfo method. These methods return the following information:

  • Minimum buffer size, in bytes.
  • Alignment requirements, if any. A buffer is aligned if the start address is a multiple of some specified integer.
  • The maximum amount of data the DMO will hold for lookahead. This number applies only to input streams. For some kinds of data (for example, MPEG encoding), a DMO might need to look forward in the stream. The lookahead value indicates how much input data the DMO will require before it can produce output.

The client must allocate buffers that match these requirements. In addition, the DMO might have requirements about how the client packages the input data. For example, the DMO might require each buffer to contain exactly one sample (or video frame). To determine these requirements, call the IMediaObject::GetInputStreamInfo method. The IMediaObject::GetOutputStreamInfo method returns similar information about an output stream.

In the default streaming model, the client does not pass raw buffer pointers to the DMO. Instead, it uses a lightweight COM object that exposes the IMediaBuffer interface. The IMediaBuffer interface acts as a COM wrapper for a block of memory. Because it is a COM object, it supports reference counting, which helps to ensure that buffers are not released while still in use.

Note The IMediaBuffer interface serves a function similar to the IMediaSample interface in DirectShow.

The client must implement the IMediaBuffer object. For more information, see Implementing IMediaBuffer.

Processing the Data

To process data, do the following:

  1. For each input stream, fill a buffer with input data.
  2. Call IMediaObject::ProcessInput to deliver each buffer.
  3. Call IMediaObject::ProcessOutput to process the data. This method takes an array of buffers, one for each output stream.
  4. Repeat until there is no more input data.

The ProcessInput method accepts input for one stream at a time. Typically the method returns immediately, and the DMO holds a reference count on the IMediaBuffer object. It releases the object after it processes all of the data in the buffer, or when the application flushes the DMO. Do not re-use a buffer until the DMO has released it. To determine whether an input stream can accept more data, call the IMediaObject::GetInputStatus method. This method returns the DMO_INPUT_STATUSF_ACCEPT_DATA flag if the stream can accept more input.

The ProcessOutput method generates output for all of the output streams at once. The application passes in an array of DMO_OUTPUT_DATA_BUFFER structures, one for each output stream. Each structure in the array has a pointer to an IMediaBuffer object. The DMO writes as much output data as it can into the buffers. It also sets various flags to report the status of the operation. The DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag indicates the DMO can produce more output from the existing input. In that case, the client can call ProcessOutput again. Otherwise, it should call ProcessInput with more input data. The DMO never modifies the data in the input buffers; it writes only to the output buffers.

After you have delivered all of the data to an input stream, call the IMediaObject::Discontinuity method. The DMO does not accept further input to that stream until you process the remaining output (or flush the DMO).

At any point after streaming begins, the DMO is able to receive input or produce output, or both. Therefore, either GetInputStatus returns DMO_INPUT_STATUSF_ACCEPT_DATA, or ProcessOutput returns DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE. The application keeps data flowing by testing for these flags and calling ProcessInput or ProcessOutput accordingly. To interrupt the data flow, call the IMediaObject::Flush method. This method causes the DMO to discard any buffers it is holding internally.

See Also

  • In-Place Processing


In-Place Processing

Certain data transformations can be accomplished by directly modifying the data. This is called in-place processing. Many audio and video effects can be done in this manner. If a DMO supports in-place processing, it exposes the IMediaObjectInPlace interface. In-place processing is generally more efficient than using separate buffers for the output. (One major exception is when the buffer resides in video memory. In that situation, read operations are much slower than write operations, so in-place processing is not recommended.)

To process data in place, the client makes a single call to the IMediaObjectInPlace::Process method, rather than separate calls to ProcessInput and ProcessOutput. The Process method is synchronous; all processing occurs inside the call. Also, in-place processing does not use IMediaBuffer objects. The Process method takes a pointer directly to the memory buffer.

A DMO that supports in-place processing still must implement the IMediaObject interface, including the ProcessInput and ProcessOutput methods. The client can choose whether to use in-place processing or use separate buffers. However, do not mix the two types of processing. If you call Process, do not call ProcessInput or ProcessOutput, and vice-versa.

Effect Tails

An in-place DMO might create some additional output after the input stops. This is called an effect tail. For example, a reverb effect continues after the input reaches silence. If there is an effect tail, the Process method returns S_FALSE. Once the application has processed all of its data, it can generate the effect tail by sending empty buffers to the Process method.


Optional Streams

A DMO can designate some of its output streams as optional. An optional stream produces data that the application can discard, either completely or on occasional samples. For example, an optional stream might contain additional information about a primary stream.

To query whether a stream is optional, call the IMediaObject::GetOutputStreamInfo method and check the pdwFlags parameter. Optional streams return either the DMO_OUTPUT_STREAMF_DISCARDABLE flag or the DMO_OUTPUT_STREAMF_OPTIONAL flag. These flags mean almost the same thing; one minor difference between them will be explained shortly.

If a stream is optional, the client can instruct the DMO to discard data from that stream when it processes the output. To do so, call the IMediaObject::ProcessOutput method and set the output buffer to NULL for each stream that you wish to discard. (The output buffer is specified in the pBuffer member of the DMO_OUTPUT_DATA_BUFFER.) Also set the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag in the dwFlags parameter.

For each stream where the pBuffer pointer is NULL, the DMO will attempt to discard the data. If the stream is optional, the DMO is guaranteed to discard the data. If the stream is not optional, the DMO discards the data when possible, but is not guaranteed to do so. If it cannot discard the data, it sets the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag. If you set a pBuffer pointer to NULL but do not set the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag, the DMO does not discard the data. In that case, the DMO either buffers the output internally, or simply fails the ProcessOutput call.

The only functional difference between the DMO_OUTPUT_STREAMF_OPTIONAL flag and the DMO_OUTPUT_STREAMF_DISCARDABLE flag is the following:

  • The DMO_OUTPUT_STREAMF_OPTIONAL flag indicates that the client does not have to set a media type on that stream. However, if the client begins processing data without setting the media type for that stream, then it must discard the data from that stream for the entire duration of streaming. If you want to discard samples selectively, then you must set the media type.
  • The DMO_OUTPUT_STREAMF_DISCARDABLE flag indicates that, although the stream is optional, it always requires a media type.


Implementing IMediaBuffer

In the default DMO streaming model, buffers are managed through the IMediaBuffer interface. The client of the DMO is responsible for implementing an object that exposes this interface. The IMediaBuffer interface has three methods:

  • GetBufferAndLength returns the address of the buffer (that is, the actual block of memory that holds the data) and the size of any valid data in the buffer.
  • GetMaxLength returns the size of the buffer.
  • SetLength specifies the length of the valid data in the buffer.

In-place processing does not require the IMediaBuffer interface. The following code shows a minimal implementation of IMediaBuffer:

//  CMediaBuffer class.
#include <new>
#include <dmo.h>
class CMediaBuffer : public IMediaBuffer
{
private:
    DWORD        m_cbLength;
    const DWORD  m_cbMaxLength;
    LONG         m_cRef;
    BYTE         *m_pbData;

public:
    CMediaBuffer(DWORD cbMaxLength) :
        m_cRef(0),
        m_cbMaxLength(cbMaxLength),
        m_cbLength(0),
        m_pbData(NULL)
    {
        m_pbData = new BYTE[cbMaxLength];
        if (!m_pbData) throw std::bad_alloc();
    }

    ~CMediaBuffer()
    {
        if (m_pbData) {
            delete [] m_pbData;
        }
    }

    // Function to create a new IMediaBuffer object and return
    // an AddRef'd interface pointer.
    static HRESULT CreateBuffer(long cbMaxLen, REFIID iid, void **ppUnk)
    {
        try {
            CMediaBuffer *pBuffer = new CMediaBuffer(cbMaxLen);
            return pBuffer->QueryInterface(iid, ppUnk);
        }
        catch (std::bad_alloc)
        {
            return E_OUTOFMEMORY;
        }
    }

    // IUnknown methods.
    STDMETHODIMP QueryInterface(REFIID riid, void **ppv)
    {
        if (ppv == NULL) {
            return E_POINTER;
        }
        if (riid == IID_IMediaBuffer || riid == IID_IUnknown) {
            *ppv = static_cast<IMediaBuffer *>(this);
            AddRef();
            return S_OK;
        }
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    STDMETHODIMP_(ULONG) AddRef()
    {
        return InterlockedIncrement(&m_cRef);
    }

    STDMETHODIMP_(ULONG) Release()
    {
        LONG lRef = InterlockedDecrement(&m_cRef);
        if (lRef == 0) {
            delete this;
            // m_cRef is no longer valid! Return lRef.
        }
        return lRef;
    }

    // IMediaBuffer methods.
    STDMETHODIMP SetLength(DWORD cbLength)
    {
        if (cbLength > m_cbMaxLength) {
            return E_INVALIDARG;
        } else {
            m_cbLength = cbLength;
            return S_OK;
        }
    }

    STDMETHODIMP GetMaxLength(DWORD *pcbMaxLength)
    {
        if (pcbMaxLength == NULL) {
            return E_POINTER;
        }
        *pcbMaxLength = m_cbMaxLength;
        return S_OK;
    }

    STDMETHODIMP GetBufferAndLength(BYTE **ppbBuffer, DWORD *pcbLength)
    {
        if (ppbBuffer == NULL || pcbLength == NULL) {
            return E_POINTER;
        }
        *ppbBuffer = m_pbData;
        *pcbLength = m_cbLength;
        return S_OK;
    }
};


Using DMOs in DirectShow

Applications based on DirectShow can use DMOs in a filter graph, through the DMO Wrapper filter. This filter aggregates a DMO and handles all the details of using the DMO, such as passing data to and from the DMO, allocating IMediaBuffer objects, and so forth.

Because the DMO is aggregated by the filter, the application can query the filter for any COM interfaces that the DMO exposes. However, the application should let the filter handle all streaming operations on the DMO. For example, do not set media types, process any buffers, flush the DMO, lock the DMO, enable or disable quality control, or set video optimizations.

If you know the class identifier (CLSID) of a specific DMO that you want to use, you can initialize the DMO Wrapper filter with that DMO, as follows:

  1. Call CoCreateInstance to create the DMO Wrapper filter.
  2. Query the DMO Wrapper filter for the IDMOWrapperFilter interface.
  3. Call the IDMOWrapperFilter::Init method. Specify the CLSID of the DMO and the GUID of the DMO's category. For a list of DMO categories, see DMO GUIDs.

The following code shows these steps:

// Create the DMO Wrapper filter.
IBaseFilter *pFilter;
HRESULT hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL,
    CLSCTX_INPROC_SERVER, IID_IBaseFilter,
    reinterpret_cast<void**>(&pFilter));

if (SUCCEEDED(hr))
{
    // Query for IDMOWrapperFilter.
    IDMOWrapperFilter *pDmoWrapper;
    hr = pFilter->QueryInterface(IID_IDMOWrapperFilter,
        reinterpret_cast<void**>(&pDmoWrapper));

    if (SUCCEEDED(hr))
    {
        // Initialize the filter.
        hr = pDmoWrapper->Init(CLSID_MyDMO, DMOCATEGORY_VIDEO_EFFECT);
        pDmoWrapper->Release();

        if (SUCCEEDED(hr))
        {
            // Add the filter to the graph.
            hr = pGraph->AddFilter(pFilter, L"My DMO");
        }
    }
    pFilter->Release();
}

The DMOEnum function enumerates DMOs in the registry. This function uses a different set of category GUIDs from the ones used for DirectShow filters.

Using the System Device Enumerator with DMOs

Instead of creating a DMO directly, you can use the System Device Enumerator, which can enumerate any DMO category that is supported by the DMOEnum method. The System Device Enumerator also includes DMOs when it enumerates certain DirectShow filter categories. The following table shows the mapping between DMO categories and DirectShow categories.

DMO Category | DirectShow Equivalent
DMOCATEGORY_AUDIO_ENCODER | CLSID_AudioCompressorCategory
DMOCATEGORY_AUDIO_DECODER | CLSID_LegacyAmFilterCategory
DMOCATEGORY_VIDEO_ENCODER | CLSID_VideoCompressorCategory
DMOCATEGORY_VIDEO_DECODER | CLSID_LegacyAmFilterCategory

The System Device Enumerator returns a list of moniker objects. If the moniker represents a DMO, the IMoniker::BindToObject method automatically creates the DMO Wrapper filter and initializes it with that DMO. Thus, the fact that a DMO is involved is transparent to the application. For more information on using the System Device Enumerator, see the topic "Using the System Device Enumerator" in the DirectShow documentation.

Limitations

There are some limitations when using DMOs in DirectShow:

  • The DMO Wrapper filter does not support DMOs with zero inputs, multiple inputs, or zero outputs.
  • All pin connections on the DMO Wrapper Filter use the IMemInputPin interface.
  • The current version of DirectShow Editing Services does not support DMO-based effects or transitions.


Writing a DMO

This section describes how to write a DMO. Before reading this section, you should read the section "Using DMOs", so that you understand how a DMO functions from the client's perspective.

This section contains the following topics:

  • DMO Minimum Requirements
  • DMO Media Types
  • Registering a DMO
  • Using the DMO Class Template
  • Using the DMOTest Application


DMO Minimum Requirements

Every DMO should meet the following minimum requirements:

  • It must support aggregation.
  • It must expose the IMediaObject interface.
  • The threading model must be 'both'. DMOs must function correctly in a free-threaded environment.

Audio effect DMOs should support the IMediaObjectInPlace interface, for use in DirectMusic and DirectSound.

The following interfaces are documented elsewhere, but are useful for many DMOs. They are not required, however.

  • ISpecifyPropertyPages, IPropertyPage: These interfaces enable a DMO to provide a property page, for the user to set properties.
  • IPersistStream: This interface enables the DMO to save its state to persistent storage.
  • IAMStreamConfig, IAMVideoCompression: These interfaces enable a client to configure an encoder's output format and compression settings. (These two interfaces are part of the DirectShow API, but are also recommended for DMOs.)

See Also

  • DMO Interfaces


DMO Media Types

A media type describes the format associated with a stream of media data. This article describes how DMOs handle media types. It is primarily intended for developers who are writing their own custom DMOs.

Media types are defined using the DMO_MEDIA_TYPE structure. This structure includes the following information:

  • The major type is a globally unique identifier (GUID) that defines a broad category, such as audio or video.
  • The subtype is a GUID that defines more specific aspects of the type. For example, within video, the subtypes include 16-bit RGB, 24-bit RGB, UYVY, DV-encoded video, and so forth.
  • The format block is a secondary structure that fully specifies the format. The layout of the format block depends on the type of data. For example, PCM audio uses the WAVEFORMATEX structure. Video uses various other structures, including VIDEOINFOHEADER and VIDEOINFOHEADER2. The layout of the format block is identified by a format type GUID. For example, FORMAT_WaveFormatEx specifies a WAVEFORMATEX structure.

When a DMO is first created, the streams do not have a media type. Before the DMO can process any data, the client must set a media type for each stream. This process is described from the client's perspective in Setting Media Types on a DMO.

Media Types in the Registry

A DMO can add a list of media types that it supports to the registry, by calling the DMORegister function. An application can use this information to search for DMOs that match a particular format. The information in the registry is not meant to be comprehensive. Typically, you would include only the main types that the DMO supports. The registry entry has separate keys for input and output types, but does not distinguish among individual streams.

The DMORegister function uses the DMO_PARTIAL_MEDIATYPE structure to describe media types. This structure contains a subset of the information found in the DMO_MEDIA_TYPE structure—namely the major type and the subtype. It does not include a format block, because the format block typically contains information that is too granular to include in the registry, such as the height and width of a video image.

Preferred Media Types

After the application has created a DMO, it can query the DMO for the media types it supports. For each stream, the DMO creates a list of media types (possibly empty), ranked in order of preference. The IMediaObject::GetInputType and IMediaObject::GetOutputType methods enumerate the preferred types. A stream's preferred types can change dynamically when the application sets media types on other streams. For example, the list of preferred output types might change after the input type is set, or vice versa. However, the DMO is not required to update its preferred types dynamically. The application cannot assume that every type it receives is valid. For this reason, the IMediaObject::SetInputType and IMediaObject::SetOutputType methods support a flag for testing a specific type.

The GetInputType and GetOutputType methods both return a DMO_MEDIA_TYPE structure. The DMO can leave some of the information in this structure blank, to indicate a range of types. The major type or subtype can be GUID_NULL, and the format block can be empty (zero bytes). If the format block is empty, the format type must be GUID_NULL.

After the application sets all of a DMO's input types, the DMO should generally return at least one complete type for each output stream. A complete output type facilitates testing, and applications can use it as a reasonable default. The DMO test application relies on this behavior. (See Using the DMOTest Application.)

Setting the Media Types

Applications use the SetInputType and SetOutputType methods to test, set, or clear types on a specified stream. The application must fully specify the type. The DMO verifies whether it can accept the proposed type. The answer may depend on which types have been set on other streams. The DMO_SET_TYPEF_CLEAR flag clears a stream's type, so the application can "back out" and try another combination.

Example Scenarios

The following examples describe some typical scenarios, to illustrate the points made in the previous sections.

  • Video Decoders. In a typical video decoder, the input type partly determines the output type. For example, usually both streams must have the same frame rate and image dimensions. One option is not to define any preferred output types until the input type is set. Another option is to enumerate a set of incomplete types, omitting the format block. Use the subtype to indicate the supported uncompressed types, such as 16-bit RGB, 24-bit RGB, and so forth. Also, video decoders generally do not support setting the output type before the input type. The usual scenario is to decode from a known input format, so this limitation is reasonable.
  • Audio Decoders. An audio decoder might support a limited, fixed set of output formats. In that case, it may be able to create a list of preferred output formats before the input format is known.
  • Compressors. In most cases, a video compressor cannot fully specify its preferred output formats until the application sets the input format, and vice versa. Instead, the DMO should return an incomplete type with no format block. For both audio and video compression, the application usually needs to set various output parameters, such as the bit rate. However, after the input type is set, the compressor should return at least one complete output type, for the reasons mentioned previously.


Registering a DMO

In order for clients to use your DMO, the CLSID must be registered on the user's system. This is done through the DLL's DllRegisterServer function. If you are using the Active Template Library (ATL), the ATL wizard automatically generates this function.

You can also register your DMO under one or more standard DMO categories. This enables clients to discover your DMO using the DMOEnum function. The categories are defined by GUID, and are listed in the section DMO GUIDs.

Registering a DMO under a category is optional. To do so, call the DMORegister function and specify the friendly name of the DMO, the CLSID, and the category. Optionally, you can also register a set of media types that your DMOs supports. For more information, see DMO Media Types.

The following example shows how to register an audio effect DMO that supports PCM audio input and output. In this case the input types and output types are the same.

STDAPI DllRegisterServer(void)
{
    // Register the DMO as a PCM audio effect DMO
    DMO_PARTIAL_MEDIATYPE mt;
    mt.type    = MEDIATYPE_Audio;
    mt.subtype = MEDIASUBTYPE_PCM;
    HRESULT hr = DMORegister(
        L"MyDMO",                  // Friendly name
        CLSID_MyDMO,               // CLSID
        DMOCATEGORY_AUDIO_EFFECT,  // Category
        0,                         // Flags
        1,                         // Number of input types
        &mt,                       // Array of input types
        1,                         // Number of output types
        &mt);                      // Array of output types

    if (FAILED(hr)) return hr;

    // Registers the object, with no typelib.
    return _Module.RegisterServer(FALSE);
}

This example assumes that ATL was used to create the project; the last line of the function calls the standard ATL method to register the COM server. If you are not using ATL, your function will look different.

Unregistering a DMO

Your DllUnregisterServer function must remove any registry entries that the DllRegisterServer function creates. If you call DMORegister when you register the DMO, you must DMOUnregister with the same category when you unregister the DMO.

The following example removes the registry entries created in the previous example:

STDAPI DllUnregisterServer(void)
{
    DMOUnregister(CLSID_MyDMO, DMOCATEGORY_AUDIO_EFFECT);
    return _Module.UnregisterServer(TRUE);
}

DirectShow Merit Values

For purposes of building filter graphs, DirectShow assigns a default merit value to DMOs. You can override this value by adding a registry entry to the DMO's registry key in HKEY_CLASSES_ROOT\CLSID. Include a DWORD value named Merit whose value specifies the merit.


Using the DMO Class Template

The DirectX SDK includes a class template, IMediaObjectImpl, for implementing DMOs. The template handles many of the "bookkeeping" tasks, such as validating input parameters. By using the template, you can focus on the functionality that is specific to your DMO. In addition, the template helps to ensure that you create a robust implementation. The template is defined in the header file Dmoimpl.h, located in the Include directory of the SDK.

The IMediaObjectImpl template inherits the IMediaObject interface. To create a DMO using the template, define a new class that derives from IMediaObjectImpl. The template implements all of the IMediaObject methods. In most cases, the template calls a corresponding private method on the derived class. The template provides the following features:

  • Basic parameter checking. The template methods verify that required parameters are not NULL, that stream indexes are within range, and that flags are valid.
  • Locking. The template methods call two internal methods, Lock and Unlock, to serialize operations on the DMO. This feature ensures that the DMO is thread-safe.
  • Media types. The template stores the media types set by the client, and provides accessor methods for the media types.
  • Streaming. The template prevents streaming until the client has set media types for all non-optional streams. It also ensures that the IMediaObject::AllocateStreamingResources method is called before streaming begins, which guarantees that resources are allocated.

The derived class must implement the IUnknown interface; the template does not provide this interface. You can use the Active Template Library (ATL) to implement IUnknown, or you can provide some other implementation. The template also does not implement the locking mechanism. The derived class must implement the Lock and Unlock methods. If you create your class using ATL, you can use the default ATL implementations.

Declaring the Derived Class

The IMediaObjectImpl class template is declared as follows:

template <class _DERIVED_, int NUMBEROFINPUTS, int NUMBEROFOUTPUTS>
class IMediaObjectImpl : public ImediaObject

The three template parameters are _DERIVED_, NUMBEROFINPUTS, and NUMBEROFOUTPUTS. Set _DERIVED_ equal to the name of your class. The other two parameters define the number of input streams and output streams on the DMO. For example, to create a DMO class named CMyDmo that supports one input stream and two output streams, use the following declaration:

class CMyDmo : public IMediaObjectImpl<CMyDmo, 1, 2>

The remainder of this section describes how the template implements the various methods in IMediaObject.

Methods for Setting Media Types

The following methods set or retrieve media types on the DMO:

  • GetInputType, GetOutputType. These methods return preferred media types, by stream number and type index. The template calls InternalGetInputType or InternalGetOutputType on the derived class.
  • SetInputType, SetOutputType. These methods set the media type on a stream, test a media type, or clear a media type. To validate the media type, the template calls InternalCheckInputType or InternalCheckOutputType on the derived class. The derived class returns S_OK to accept the type or DMO_E_INVALIDTYPE to reject the type. The template handles setting or clearing the media type.
  • GetInputCurrentType, GetOutputCurrentType. These methods return the current media type for a stream, or DMO_E_TYPE_NOT_SET if no type is set. The template completely implements these methods.

Informational Methods

The following methods provide information about the DMO.

  • GetInputMaxLatency, SetInputMaxLatency. These methods retrieve or set the maximum latency. The template calls InternalGetInputMaxLatency or InternalSetInputMaxLatency on the derived class.
  • GetInputSizeInfo, GetOutputSizeInfo. These methods return the DMO's buffer requirements for a specified stream. If no media type has been set on that stream, the template returns DMO_E_TYPE_NOT_SET. Otherwise, it calls InternalGetInputSizeInfo or InternalGetOutputSizeInfo on the derived class.
  • GetInputStreamInfo, GetOutputStreamInfo. These methods return various flags that indicate how the client should format the data. The template calls InternalGetInputStreamInfo or InternalGetOutputStreamInfo on the derived class.
  • GetStreamCount. This method returns the number of input and output streams. The template implements this method, using the template parameters.

Methods for Resource Allocation

  • The AllocateStreamingResources method allocates any resources the DMO needs before streaming begins. The FreeStreamingResources method releases the same resources. The template calls InternalAllocateStreamingResources and InternalFreeStreamingResources, respectively.

The client of the DMO is not required to call these methods, but the template automatically calls AllocateStreamingResources before streaming starts. Therefore, the DMO can assume that resources are have been allocated correctly by the time ProcessInput is called. The DMO should call FreeStreamingResources in its destructor.

Also, when the template calls InternalAllocateStreamingResources, it sets an internal flag, so that it does not call that method again until calling InternalFreeStreamingResources. This ensures that resources are not re-allocated accidentally, which could cause memory leaks.

Methods for Streaming

The following methods are used to stream data:

  • GetInputStatus. This method indicates whether the DMO can accept input at this time. The template calls InternalAcceptingInput on the derived class. If the DMO can accept input, the derived class returns S_OK and the template sets the DMO_INPUT_STATUSF_ACCEPT_DATA bit in the dwFlags parameter. Otherwise, the derived class returns S_FALSE and the template sets dwFlags to zero.
  • ProcessInput. This method processes an input buffer. The template calls AllocateStreamingResources, described previously. Then it calls InternalAcceptingInput on the derived class. If the DMO can accept new input, the template calls InternalProcessInput.
  • ProcessOutput. This method processes a set of output buffers, one buffer for each output stream. The template calls AllocateStreamingResources and then InternalProcessOutput.
  • Discontinuity. This method signals a discontinuity in an input stream. The template calls InternalAcceptingInput on the derived class. If that method returns S_OK, the template calls InternalDiscontinuity on the derived class.
  • Flush. This method flushes the DMO. The template calls InternalFlush on the derived class. The DMO should discard any input buffers that it still holds to be processed.

The template does not provide any direct support for the IMediaObjectInPlace interface.

Methods for Locking

Locking is used to protect the DMO's state in a multithreaded environment. In an ATL project, the IMediaObject::Lock method causes a name conflict with the ATL Lock method. To resolve the conflict, the template renames the IMediaObject method to DMOLock. When you compile the derived class, define FIX_LOCK_NAME before including the header file Dmo.h:

#define FIX_LOCK_NAME
#include <dmo.h>

This directive causes the preprocessor to substitute DMOLock for Lock in the declaration of the IMediaObject interface. Applications can still invoke the method using the name Lock, because the vtable order does not change. The DMOLock method calls Lock or Unlock on the derived class. If you are using ATL to implement the derived class, these methods are already defined by ATL, so no additional code is necessary. If you are not using ATL, you must provide Lock and Unlock methods in your derived class.

The template automatically locks the DMO in each of the IMediaObject methods. The derived class might need to lock the DMO inside other public methods that it implements (for example, if it supports IMediaObjectInPlace). The class template also provides an internal helper class, IMediaObjectImpl::LockIt, which is useful for locking and unlocking the DMO.

Summary

For the following IMediaObject methods, the template calls a corresponding method with the same signature on the derived class. The derived class must implement each of the methods shown in the second column.

IMediaObject Method | Derived Class Method
AllocateStreamingResources | InternalAllocateStreamingResources
Discontinuity | InternalDiscontinuity
Flush | InternalFlush
FreeStreamingResources | InternalFreeStreamingResources
GetInputMaxLatency | InternalGetInputMaxLatency
GetInputSizeInfo | InternalGetInputSizeInfo
GetInputStreamInfo | InternalGetInputStreamInfo
GetInputType | InternalGetInputType
GetOutputSizeInfo | InternalGetOutputSizeInfo
GetOutputStreamInfo | InternalGetOutputStreamInfo
GetOutputType | InternalGetOutputType
ProcessInput | InternalProcessInput
ProcessOutput | InternalProcessOutput
SetInputMaxLatency | InternalSetInputMaxLatency

For the remaining IMediaObject methods, there is not a one-to-one correspondence between template methods and derived-class methods. The following table summarizes which methods are fully implemented by the template, and which methods call other methods on the derived class.

IMediaObject Method | Derived Class Method
GetInputCurrentType | Fully implemented
GetOutputCurrentType | Fully implemented
GetStreamCount | Fully implemented
GetInputStatus | InternalAcceptingInput
Lock (implemented as DMOLock) | Lock, Unlock
SetInputType | InternalCheckInputType
SetOutputType | InternalCheckOutputType

See Also

  • IMediaObjectImpl Class Template


Using the DMOTest Application

The DirectX SDK includes a DMO test application named DMOTest. This application can help verify that a DMO meets the DMO specifications. If you develop a DMO, you should include the DMO test application as part of your testing.

DMOTest is installed in the Bin\DXUtils directory, under the SDK root directory. To use DMOTest, you must first generate some test data for the DMO. The SDK includes a DirectShow filter for this purpose. Details about the filter and the DMOTest application can be found in the DMOTest application Help. In the application, choose Contents from the Help menu. The Help includes step-by-step instructions for generating test data and running tests.


Media Parameters

Media parameters enable an application to configure an object's properties so that they change over time in a mathematically deterministic way.

For example, suppose that a sound engineer is mixing a digital master tape and wants to apply a slight delay to a vocal section, to fill out the sound. The effect will be jarring if the delay cuts in abruptly. Instead, the effect should begin 100% dry (no delay), and the wet/dry mix should increase gradually until it reaches the desired level. Moreover, this transition should follow a smooth curve or linear progression. To support this scenario, a DMO can expose the following interfaces:

  • IMediaParamInfo contains methods for discovering information about the supported properties. Typically, the client will call these methods before it begins to stream data.
  • IMediaParams contain methods for setting the curves that a parameter will follow during streaming.

These interfaces are designed primarily for DMOs, but any object can support them. Within this section, the term parameter refers to any property that supports these two interfaces.

This section contains the following topics:

  • Parameter Curves
  • Parameter Information
  • Envelope Segments
  • Calculating Parameter Values


Parameter Curves

Media parameters are able to follow a curve over time. Each curve is described by a mathematical formula and two end-points. Each end-point is defined by a reference time and the value of the curve at that time. The formula is used to calculate intermediate values between the points, and determines the shape of the curve. The possible curves are:

  • Jump
  • Linear
  • Square
  • Inverse square
  • Sine

"Jump" means jump directly to the end value. The other curves are shown in the following diagram.

Mathematically, the curves work as follows. Suppose that a curve begins at time t0 with a value of v0, and ends at time t1 with a value of v1. The two points that define the curve are (t0,v0) and (t1,v1).

  • Let Δt be the total duration of the curve, t1 – t0.
  • Let Δv be the interval between the starting and ending values, v1 – v0.
  • At any time t such that t0 <= t <= t1, let Δt' = t – t0.

The value of the parameter at time t is:

v = f( Δt' / Δt ) * Δv + v0

where f(x) is a function determined by the curve type:

  • Linear: y = x
  • Square: y = x2
  • Inverse square: y = sqrt(x)
  • Sine: y = [ sin(πx – π/2) + 1 ] / 2

Observe that Δt' < Δt, so the term Δt'/Δt ranges from 0 to 1. Therefore, f(x) also ranges from 0 to 1, and v always falls between v0 and v1. This is true whether v0 < v1 or vice versa. In other words, the curve is bounded by the rectangle (t0,v0,t1,v1).

For the sine curve, the value of (πx – π/2) ranges from –π/2 to π/2, which means that sin(πx – π/2) ranges from –1 to 1. The result is then normalized so that f(x) falls into the range (0–1).


Parameter Information

The IMediaParamInfo::GetParamInfo method returns an MP_PARAMINFO structure that describes a parameter. This structure contains the following information:

  • The mpType member indicates the data type of the parameter value. For efficiency, all parameters are implemented as 32-bit floating-point values. The MP_TYPE enumeration defines whether to interpret the value as an integer, floating-point value, Boolean, or enumeration (integer series).
  • The mopCaps member indicates which curves this parameter supports. If the data type is Boolean or enumeration, the only curve that the parameter can support is "Jump."
  • The mpdMinValue and mpdMaxValue members define the minimum and maximum values for this parameter. Any curves for this parameter must fall within this range.
  • The mpdNeutralValue member is the default value of the parameter.
  • The szLabel member is the name of the parameter, and the szUnitText member is the name for the unit of measure for the parameter. Examples might include "Volume" and "Decibels," or "Frequency" and "kHz." Both strings are English and are never localized. The DMO can provide localized versions through the IMediaParamInfo::GetParamText method.

The information for each parameter remains fixed throughout the lifetime of the DMO. Therefore, the client can query for this information once and then cache it.

Time Formats

The client must time stamp the input data, so that the DMO can calculate the corresponding parameter values. By default, time stamps represent units of 100 nanoseconds, also called reference time. This time unit is not convenient for every application, however, so a DMO has an option to support other time formats. Time formats are identified by GUID.

GUID | Description
GUID_TIME_REFERENCE | Reference time
GUID_TIME_MUSIC | Parts per quarter note (PPQN)
GUID_TIME_SAMPLES | Samples per second

Third parties are encouraged to define their own time formats as needed. However, all DMOs must support reference time. This provides a standard baseline that everyone can use. To determine how many time formats a DMO supports, call the IMediaParamInfo::GetNumTimeFormats method. To enumerate the supported formats, call the IMediaParamInfo::GetSupportedTimeFormat method.

To set the time format, call IMediaParams::SetTimeFormat. This method specifies the time format GUID and the time data, which is the number of units per clock tick. For example, if the time format is samples per second, and the time data is 32, then a time stamp value of 10 corresponds to 320 samples.


Envelope Segments

A parameter curve consists of one or more envelope segments, defined using the MP_ENVELOPE_SEGMENT structure. This structure contains the following information:

  • The start and end times.
  • The starting and ending values.
  • The curve type (linear, square, and so forth).
  • Optional flags, described shortly.

The client adds envelope segments to a parameter by calling the IMediaParams::AddEnvelope method and passing in an array of MP_ENVELOPE_SEGMENT structures. The client should sort the segments into ascending time order before calling the method. As the DMO processes data, you can imagine the parameter traveling over each envelope segment, like a car driving over a series of hills. The IMediaParams::GetParam method returns the most recent value.

Two adjacent segments can have a gap between them. During gaps, the parameter retains its previous value, as follows:

  • Before the first segment, the value is the neutral value.
  • Between segments, the value is the ending value of the previous segment.
  • After the last segment, the value remains at the ending value of that segment.
  • If the client flushes the DMO, the value reverts to the neutral value.

You can alter a segment by setting either of the following flags:

  • MPF_ENVLP_BEGIN_CURRENTVAL. The DMO uses the most recent value of the parameter as the starting value for the segment. This might be the neutral value, or the ending value from the previous segment. The DMO ignores the valStart member of the MP_ENVELOPE_SEGMENT structure.
  • MPF_ENVLP_BEGIN_NEUTRALVAL. The DMO uses the neutral value of the parameter as the starting value for the segment. It ignores valStart.

You can think of these flags as grabbing the starting point of the segment and moving it up or down, while the ending value remains fixed. The segment will "stretch" accordingly.


Calculating Parameter Values

Potentially, an input buffer could be very large. Ideally, when the DMO processes the buffer, the parameters will exactly follow their curves throughout the entire batch of data. However, a DMO has some leeway in how it calculates those values.

  • The most accurate approach is to calculate the exact value for every atomic unit of data; for example, each audio sample. This approach is the most computationally expensive.
  • Another approach is to slice the data into smaller units of some fixed size, such as 100 samples. This approach creates a "stair-stepping" effect. For some parameters, that might be acceptable. In audio effects, it might create audible artifacts.
  • A compromise is to use the previous technique, but within each batch, perform a linear interpolation of the parameter value for each sample.

These issues are especially important for audio processing. One second of audio might contain 48,000 audio samples per channel, which is a lot of calculations to perform, yet the ear is sensitive to artifacts such as aliasing.


DMO Reference

This section contains reference information for DirectX Media Objects (DMOs).

  • DMO Interfaces
  • DMO Structures
  • DMO Enumerated Types
  • DMO Functions
  • DMO Constants
  • IMediaObjectImpl Class Template


DMO Interfaces

This section contains reference entries for all the Microsoft DirectX Media Object (DMO) COM interfaces and their methods.

Interface | Description
IDMOQualityControl | Supports quality control on a DMO.
IDMOVideoOutputOptimizations | Supports video optimizations on a DMO.
IEnumDMO | Provides methods for enumerating DMOs.
IMediaBuffer | Provides methods for manipulating a data buffer.
IMediaObject | Provides methods for manipulating a DMO.
IMediaObjectInPlace | Provides methods for processing data in place.
IMediaParamInfo | Retrieves information about the media parameters that an object supports
IMediaParams | Sets and retrieves media parameters on an object.


IDMOQualityControl Interface

The IDMOQualityControl interface supports quality control on a Microsoft DirectX Media Object (DMO).

A DMO exposes this interface if it can respond to late samples. When quality control is enabled, the DMO attempts to process samples on time, discarding late samples if necessary. When quality control is disabled, the DMO processes every sample. By default, quality control is disabled.

Applications use this interface to enable or disable quality control. Using quality control is appropriate when you are viewing media data in real time. If you are capturing data to a file, do not enable quality control, because the DMO might discard samples. It does not matter in file capture whether samples arrive late, and you do not want to lose the data.

To use quality control, perform the following steps:

  1. Call the IDMOQualityControl::SetNow method with the reference time of the earliest sample to be processed.
  2. Call the IDMOQualityControl::SetStatus method with the DMO_QUALITY_STATUS_ENABLED flag.

To disable quality control, call SetStatus with no flag.

In addition to the methods inherited from IUnknown, the IDMOQualityControl interface exposes the following methods.

Method | Description
GetStatus | Determines whether quality control is active.
SetNow | Specifies the earliest time stamp for which the DMO should deliver data.
SetStatus | Enables or disables quality control.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IDMOQualityControl::GetStatus

The GetStatus method determines whether quality control is active.

Syntax

HRESULT GetStatus(
    DWORD *pdwFlags
);

Parameters

pdwFlags

[out] Pointer to a variable that receives the quality control status. If quality control is disabled, the value is zero. If quality control is enabled, the value is DMO_QUALITY_STATUS_ENABLED.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_POINTER | NULL pointer value
S_OK | Success

See Also

  • IDMOQualityControl Interface


IDMOQualityControl::SetNow

The SetNow method specifies the earliest time stamp that the DMO will deliver.

Syntax

HRESULT SetNow(
    REFERENCE_TIME rtNow
);

Parameters

rtNow

[in] Reference time specifying the earliest time stamp to deliver.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_FAIL | Failure
S_OK | Success

Remarks

If quality control is enabled, the DMO discards any samples whose time stamp is less than rtNow. Samples whose time stamp is rtNow or later are processed as efficiently as possible. Depending on the implementation, the DMO might drop some samples to keep pace.

If quality control is disabled, this method has no immediate effect. However, the DMO stores the specified reference time. It uses this value if quality control is enabled at a later time. To enable quality control, call the IDMOQualityControl::SetNow method.

If incoming samples are not time-stamped, the DMO never performs quality control. The application sets the time stamp in the IMediaObject::ProcessInput method.

See Also

  • IDMOQualityControl Interface


IDMOQualityControl::SetStatus

The SetStatus method enables or disables quality control.

Syntax

HRESULT SetStatus(
    DWORD dwFlags
);

Parameters

dwFlags

[in] Value that specifies whether to enable or disable quality control. Use DMO_QUALITY_STATUS_ENABLED to enable quality control, or zero to disable quality control.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

With quality control enabled, the DMO attempts to deliver samples on time. It can skip late samples if necessary. With quality control disabled, the DMO delivers every sample. If you enable quality control, call the IDMOQualityControl::SetNow method to specify the earliest time stamp that the DMO should process. Otherwise, the call to SetStatus succeeds but the DMO does not perform quality control.

By default, quality control is disabled.

See Also

  • IDMOQualityControl Interface


IDMOVideoOutputOptimizations Interface

The IDMOVideoOutputOptimizations interface supports video optimizations on a Microsoft DirectX Media Object (DMO).

This interface enables an application to negotiate with a DMO about video output optimizations. A DMO exposes this interface when it can perform optimizations that require support from the application. The application can query the DMO for its preferred features, and then agree (or not agree) to provide them. The DMO must process output even if the application rejects the optimizations.

For example, a video decoder might generate an output frame by applying deltas to the previous output frame. When queried, it requests that the application supply the previous frame in the output buffer. The application can agree to this request or not.

Video optimizations are negotiated separately for each output stream.

The following pseudo-code shows how an application might negotiate with the DMO:

IDMOVideoOutputOptimizations *pVidOpt;
// Query the DMO for IDMOVideoOutputOptimizations (not shown).

BOOL  bWantsPreviousBuffer = FALSE;
DWORD wFlags;
pVidOpt->QueryOperationModePreferences(0,&dwFlags);

if (dwFlags & DMO_VOSF_NEEDS_PREVIOUS_SAMPLE)
{
    // Agree to the request.
    pVidOpt->SetOperationMode(0, DMO_VOSF_NEEDS_PREVIOUS_SAMPLE);
    bWantsPreviousBuffer = TRUE;
}

// Processing loop
while (there is input).
{
    ProcessInput(0, ...);
    if (bWantsPreviousBuffer)
        pDMO->ProcessOutput(0, ...) // Use the same buffer as last time.
    else
        pDMO->ProcessOutput(0, ...) // OK to use a new buffer.
}

In addition to the methods inherited from IUnknown, the IDMOVideoOutputOptimizations interface exposes the following methods.

Method | Description
GetCurrentOperationMode | Retrieves the optimization features in effect.
GetCurrentSampleRequirements | Retrieves the optimization features required to process the next sample, given the features already agreed to by the application.
QueryOperationModePreferences | Retrieves the DMO's preferred optimization features.
SetOperationMode | Notifies the DMO of the optimization features in effect.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IDMOVideoOutputOptimizations::GetCurrentOperationMode

The GetCurrentOperationMode method retrieves the optimization features in effect.

Syntax

HRESULT GetCurrentOperationMode(
    ULONG ulOutputStreamIndex,
    DWORD *pdwEnabledFeatures
);

Parameters

ulOutputStreamIndex

Zero-based index of an output stream on the DMO.

pdwEnabledFeatures

Pointer to a variable that receives the current features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IDMOVideoOutputOptimizations Interface


IDMOVideoOutputOptimizations::GetCurrentSampleRequirements

The GetCurrentSampleRequirements method retrieves the optimization features required to process the next sample, given the features already agreed to by the application.

Syntax

HRESULT GetCurrentSampleRequirements(
    ULONG ulOutputStreamIndex,
    DWORD* pdwRequestedFeatures
);

Parameters

ulOutputStreamIndex

Zero-based index of an output stream on the DMO.

pdwRequestedFeatures

Pointer to a variable that receives the required features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

After an application calls the IDMOVideoOutputOptimizations::SetOperationMode method, it must provide all the features it has agreed to. However, the DMO might not require every feature on every sample. This method enables the DMO to waive an agreed-upon feature for one sample.

Before processing a sample, the application can call this method. If the DMO does not require a given feature in order to process the next sample, it omits the corresponding flag from the pdwRequestedFeatures parameter. For the next sample only, the application can ignore the feature. The results of this method are valid only for the next call to the IMediaObject::ProcessOutput method.

The DMO will return only the flags that were agreed to in the SetOperationMode method. In other words, you cannot dynamically enable new features with this method.

See Also

  • IDMOVideoOutputOptimizations Interface


IDMOVideoOutputOptimizations::QueryOperationModePreferences

The QueryOperationModePreferences method retrieves the DMO's preferred optimization features.

Syntax

HRESULT QueryOperationModePreferences(
    ULONG ulOutputStreamIndex,
    DWORD* pdwRequestedCapabilities
);

Parameters

ulOutputStreamIndex

Zero-based index of an output stream on the DMO.

pdwRequestedCapabilities

Pointer to a variable that receives the DMO's requested features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IDMOVideoOutputOptimizations Interface


IDMOVideoOutputOptimizations::SetOperationMode

The SetOperationMode method notifies the DMO of the optimization features that are in effect.

Syntax

HRESULT SetOperationMode(
    ULONG ulOutputStreamIndex,
    DWORD dwEnabledFeatures
);

Parameters

ulOutputStreamIndex

Zero-based index of an output stream on the DMO.

dwEnabledFeatures

Bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

Before calling this method, call the IDMOVideoOutputOptimizations::QueryOperationModePreferences method to determine which features the DMO requests. Then call this method to inform the DMO which of those features you are providing. If you are not providing any of them, it is not necessary to call this method. The DMO does not assume that any of them will be provided.

The application must provide all the features it has agreed to. For some features, however, the DMO might not require the feature on every sample. To determine if the DMO can dispense with any features on the next sample, call the IDMOVideoOutputOptimizations::GetCurrentSampleRequirements method. In effect, this enables the DMO to waive an agreed-upon feature for one sample.

Before streaming begins, subsequent calls to this method override earlier calls. To set multiple features, you must do so in a single method call. Once streaming begins, this method returns an error. Streaming begins when the applications calls IMediaObject::ProcessInput on at least one input stream.

When streaming ends, the application can renegotiate the features. Streaming ends if the application calls the IMediaObject::Flush method, or if the application calls IMediaObject::Discontinuity on all the input streams and then processes all of the remaining output.

See Also

  • IDMOVideoOutputOptimizations Interface


IEnumDMO Interface

The IEnumDMO interface provides methods for enumerating Microsoft DirectX Media Objects (DMOs). It is based on the OLE enumeration interfaces. For more information, see the IEnumXXXX topic in the Platform SDK.

To enumerate registered DMOs, call the DMOEnum function.

In addition to the methods inherited from IUnknown, the IEnumDMO interface exposes the following methods.

Method | Description
Clone | Not implemented.
Next | Retrieves a specified number of items in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of items in the enumeration sequence.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IEnumDMO::Clone

This method is not implemented.

Syntax

HRESULT Clone(
    IEnumDMO **ppEnum
);

Return Value

Returns E_NOTIMPL.

See Also

  • IEnumDMO Interface


IEnumDMO::Next

The Next method retrieves a specified number of items in the enumeration sequence.

Syntax

HRESULT Next(
    DWORD cItemsToFetch,
    CLSID *pCLSID,
    WCHAR **Names,
    DWORD *pcItemsFetched
);

Parameters

cItemsToFetch

Number of items to retrieve.

pCLSID

[out] Array of size cItemsToFetch that is filled with the CLSIDs of the enumerated DMOs.

Names

[out] Array of size cItemsToFetch that is filled with the friendly names of the enumerated DMOs.

pcItemsFetched

[out] Pointer to a variable that receives the actual number of items retrieved. Can be NULL if cItemsToFetch equals 1.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_FALSE | Retrieved fewer items than requested.
S_OK | Retrieved the requested number of items.

Remarks

If the method succeeds, the arrays given by the pCLSID and Names parameters are filled with CLSIDs and wide-character strings. The value of *pcItemsFetched specifies the number of items returned in these arrays.

The method returns S_OK if it retrieves the requested number of items (in other words, if *pcItemsFetched equals cItemsToFetch). Otherwise, it returns S_FALSE or an error code.

The caller must free the memory allocated for each string returned in the Names parameter, using the CoTaskMemFree function.

See Also

  • IEnumDMO Interface


IEnumDMO::Reset

The Reset method resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

See Also

  • IEnumDMO Interface


IEnumDMO::Skip

The Skip method skips over a specified number of items in the enumeration sequence.

Syntax

HRESULT Skip(
    DWORD cItemsToSkip
);

Parameters

cItemsToSkip

Number of items to skip.

Return Value

Returns S_OK if the number items skipped equals cItemsToSkip. Otherwise, returns S_FALSE.

See Also

  • IEnumDMO Interface


IMediaBuffer Interface

The IMediaBuffer interface provides methods for manipulating a data buffer. Buffers passed to the IMediaObject::ProcessInput and ProcessOutput methods must implement this interface.

In addition to the methods inherited from IUnknown, the IMediaBuffer interface exposes the following methods.

Method | Description
GetBufferAndLength | Retrieves the buffer and the size of the valid data in the buffer.
GetMaxLength | Retrieves the maximum number of bytes this buffer can hold.
SetLength | Specifies the length of the data currently in the buffer.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IMediaBuffer::GetBufferAndLength

The GetBufferAndLength method retrieves the buffer and the size of the valid data in the buffer.

Syntax

HRESULT GetBufferAndLength(
    BYTE** ppBuffer,
    DWORD* pcbLength
);

Parameters

ppBuffer

[out] Address of a pointer that receives the buffer array. Can be NULL if pcbLength is not NULL.

pcbLength

[out] Pointer to a variable that receives the size of the valid data, in bytes. Can be NULL if ppBuffer is not NULL.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

Either parameter can be NULL, in which case it does not receive a value. At least one parameter must be non-NULL. If both parameters are NULL, the method returns E_POINTER.

The value returned in the pcbLength parameter is the size of the valid data in the buffer, not the buffer's allocated size. To obtain the buffer's allocated size, call the IMediaBuffer::GetMaxLength method.

See Also

  • IMediaBuffer Interface


IMediaBuffer::GetMaxLength

The GetMaxLength method retrieves the maximum number of bytes this buffer can hold.

Syntax

HRESULT GetMaxLength(
    DWORD* pcbMaxLength
);

Parameters

pcbMaxLength

[out] Pointer to a variable that receives the buffer's maximum size, in bytes.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

See Also

  • IMediaBuffer Interface


IMediaBuffer::SetLength

The SetLength method specifies the length of the data currently in the buffer.

Syntax

HRESULT SetLength(
   DWORD cbLength
);

Parameters

cbLength

Size of the data, in bytes. The value must not exceed the buffer's maximum size. Call the IMediaBuffer::GetMaxLength method to obtain the maximum size.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method sets the size of the valid data currently in the buffer, not the buffer's allocated size.

See Also

  • IMediaBuffer Interface


IMediaObject Interface

The IMediaObject interface provides methods for manipulating a Microsoft DirectX Media Object (DMO).

In addition to the methods inherited from IUnknown, the IMediaObject interface exposes the following methods.

Method | Description
AllocateStreamingResources | Allocates any resources needed by the DMO.
Discontinuity | Signals a discontinuity on the specified input stream.
Flush | Flushes all internally buffered data.
FreeStreamingResources | Frees resources allocated by the DMO.
GetInputCurrentType | Retrieves the media type that was previously set for an input stream, if any.
GetInputMaxLatency | Retrieves the maximum latency on a specified input stream.
GetInputSizeInfo | Retrieves the buffer requirements for a specified input stream.
GetInputStatus | Queries whether a specified input stream can accept more input data.
GetInputStreamInfo | Retrieves information about a specified input stream.
GetInputType | Retrieves a preferred media type for a specified input stream.
GetOutputCurrentType | Retrieves the media type that was previously set for an output stream, if any.
GetOutputSizeInfo | Retrieves the buffer requirements for a specified output stream.
GetOutputStreamInfo | Retrieves information about a specified output stream.
GetOutputType | Retrieves a preferred media type for a specified output stream.
GetStreamCount | Retrieves the number of input and output streams.
Lock | Acquires or releases a lock on the DMO.
ProcessInput | Delivers a buffer to the specified input stream.
ProcessOutput | Generates output from the current input data.
SetInputMaxLatency | Sets the maximum latency on a specified input stream.
SetInputType | Sets the media type on an input stream, or tests whether a particular media type is acceptable.
SetOutputType | Sets the media type on an output stream, or tests whether a particular media type is acceptable.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IMediaObject::AllocateStreamingResources

The AllocateStreamingResources method allocates any resources needed by the DMO. Calling this method is always optional.

Syntax

HRESULT AllocateStreamingResources(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

An application can call this method as a streaming optimization. It gives the DMO an opportunity to perform any time-consuming initializations before streaming begins. If you call this method, do so after you set the media types on the DMO, but before you make the first calls to ProcessInput or ProcessOutput.

This method is optional in the following sense:

  • If the DMO does not support this method, the method returns S_OK.
  • If the application never calls this method, the DMO allocates resources within a call to IMediaObject::ProcessInput or IMediaObject::ProcessOutput.

If the DMO supports this method, it should also support the IMediaObject::FreeStreamingResources method.

See Also

  • IMediaObject Interface


IMediaObject::Discontinuity

The Discontinuity method signals a discontinuity on the specified input stream.

Syntax

HRESULT Discontinuity(
    DWORD dwInputStreamIndex
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
DMO_E_NOTACCEPTING | The DMO is not accepting input.
DMO_E_TYPE_NOT_SET | The input and output types have not been set.
S_OK | Success

Remarks

A discontinuity represents a break in the input. A discontinuity might occur because no more data is expected, the format is changing, or there is a gap in the data. After a discontinuity, the DMO does not accept further input on that stream until all pending data has been processed. The application should call the IMediaObject::ProcessOutput method until none of the streams returns the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag.

This method might fail if it is called before the client sets the input and output types on the DMO.

See Also

  • IMediaObject Interface


IMediaObject::Flush

The Flush method flushes all internally buffered data.

Syntax

HRESULT Flush(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The DMO performs the following actions when this method is called:

  • Releases any IMediaBuffer references it holds.
  • Discards any values that specify the time stamp or sample length for a media buffer.
  • Reinitializes any internal states that depend on the contents of a media sample.

Media types, maximum latency, and locked state do not change.

When the method returns, every input stream accepts data. Output streams cannot produce any data until the application calls the IMediaObject::ProcessInput method on at least one input stream.

See Also

  • IMediaObject Interface


IMediaObject::FreeStreamingResources

The FreeStreamingResources method frees resources allocated by the DMO. Calling this method is always optional.

Syntax

HRESULT FreeStreamingResources(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method releases any resources that the IMediaObject::AllocateStreamingResources method initializes.

If the DMO does not support this method, the method returns S_OK. If you call this method during streaming, the method fails and the DMO does not release any resources.

Regardless of whether the method fails or succeeds, the application can continue to call other methods on the DMO. The DMO might need to re-initialize resources that were previously freed.

See Also

  • IMediaObject Interface


IMediaObject::GetInputCurrentType

The GetInputCurrentType method retrieves the media type that was set for an input stream, if any.

Syntax

HRESULT GetInputCurrentType(
    DWORD dwInputStreamIndex,
    DMO_MEDIA_TYPE* pmt
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

pmt

[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

The caller must set the media type for the stream before calling this method. To set the media type, call the IMediaObject::SetInputType method.

If the method succeeds, call MoFreeMediaType to free the format block.

See Also

  • IMediaObject Interface


IMediaObject::GetInputMaxLatency

The GetInputMaxLatency method retrieves the maximum latency on a specified input stream.

Syntax

HRESULT GetInputMaxLatency(
    DWORD dwInputStreamIndex,
    REFERENCE_TIME* prtMaxLatency
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

prtMaxLatency

[out] Pointer to a variable that receives the maximum latency.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
E_FAIL | Failure.
E_NOTIMPL | Not implemented. Assume zero latency.
S_OK | Success.

The latency is the difference between a time stamp on the input stream and the corresponding time stamp on the output stream. The maximum latency is the largest possible difference in the time stamps. For a DMO, determine the maximum latency as follows:

  • Process input buffers until the DMO can produce output.
  • Process as many output buffers as possible.
  • The maximum latency is the largest delta between input time stamps and output time stamps (taken as an absolute value).

Under this definition, latency does not include the time that it takes to process samples. Nor does it include any latency introduced by the size of the input buffer.

For the special case where a DMO processes exactly one sample at a time, the maximum latency is simply the difference in time stamps.

Latency is defined only when samples have time stamps, and the time stamps increase or decrease monotonically. Maximum latency might depend on the media types for the input and output streams.

See Also

  • IMediaObject Interface


IMediaObject::GetInputSizeInfo

The GetInputSizeInfo method retrieves the buffer requirements for a specified input stream.

Syntax

HRESULT GetInputSizeInfo(
    DWORD dwInputStreamIndex,
    DWORD* pcbSize,
    DWORD* pcbMaxLookahead,
    DWORD* pcbAlignment
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

pcbSize

[out] Pointer to a variable that receives the minimum size of an input buffer for this stream, in bytes.

pcbMaxLookahead

[out] Pointer to a variable that receives the maximum amount of data that the DMO will hold for lookahead, in bytes. If the DMO does not perform lookahead on the stream, the value is zero.

pcbAlignment

[out] Pointer to a variable that receives the required buffer alignment, in bytes. If the input stream has no alignment requirement, the value is 1.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
S_OK | Success.

Remarks

The buffer requirements may depend on the media types of the various streams. Before calling this method, set the media type of each stream by calling the IMediaObject::SetInputType and IMediaObject::SetOutputType methods. If the media types have not been set, this method might return an error.

If the DMO performs lookahead on the input stream, it returns the DMO_INPUT_STREAMF_HOLDS_BUFFERS flag in the IMediaObject::GetInputStreamInfo method. During processing, the DMO holds up to the number of bytes indicated by the pcbMaxLookahead parameter. The application must allocate enough buffers for the DMO to hold this much data.

A buffer is aligned if the buffer's start address is a multiple of *pcbAlignment. The alignment must be a power of two. Depending on the microprocessor, reads and writes to an aligned buffer might be faster than to an unaligned buffer. Also, some microprocessors do not support unaligned reads and writes.

See Also

  • IMediaObject Interface


IMediaObject::GetInputStatus

The GetInputStatus method queries whether an input stream can accept more input data.

Syntax

HRESULT GetInputStatus(
    DWORD dwInputStreamIndex,
    DWORD* dwFlags
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

dwFlags

[out] Pointer to a variable that receives either zero or DMO_INPUT_STATUSF_ACCEPT_DATA.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
S_OK | Success

Remarks

If the input stream will accept more data, the method returns the DMO_INPUT_STATUSF_ACCEPT_DATA flag in the dwFlags parameter. Otherwise, it sets this parameter to zero. If the stream will accept more data, the application can call the IMediaObject::ProcessInput method.

The status of an input stream can change only as the result of one of the following method calls.

Method | Description
IMediaObject::Discontinuity | Signals a discontinuity on the specified input stream.
IMediaObject::Flush | Flushes all internally buffered data.
IMediaObject::ProcessInput | Delivers a buffer to the specified input stream.
IMediaObject::ProcessOutput | Generates output from the current input data.

See Also

  • IMediaObject Interface


IMediaObject::GetInputStreamInfo

The GetInputStreamInfo method retrieves information about an input stream, such as any restrictions on the number of samples per buffer, and whether the stream performs lookahead on the input data. This information never changes.

Syntax

HRESULT GetInputStreamInfo(
    DWORD dwInputStreamIndex,
    DWORD* pdwFlags
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

pdwFlags

[out] Pointer to a variable that receives a bitwise combination of zero or more DMO_INPUT_STREAM_INFO_FLAGS flags.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The DMO_INPUT_STREAMF_HOLDS_BUFFERS flag indicates that the DMO performs lookahead on the incoming data.

The application must be sure to allocate sufficient buffers for the DMO to process the input. Call the IMediaObject::GetInputSizeInfo method to determine the buffer requirements.

See Also

  • IMediaObject Interface


IMediaObject::GetInputType

The GetInputType method retrieves a preferred media type for a specified input stream.

Syntax

HRESULT GetInputType(
    DWORD dwInputStreamIndex,
    DWORD dwTypeIndex,
    DMO_MEDIA_TYPE* pmt
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

dwTypeIndex

Zero-based index on the set of acceptable media types.

pmt

[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller, or NULL. If this parameter is non-NULL, the method fills the structure with the media type. You can use the value NULL to test whether the type index is in range, by checking the return code.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NO_MORE_ITEMS | Type index is out of range.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Call this method to enumerate an input stream's preferred media types. The DMO assigns each media type an index value in order of preference. The most preferred type has an index of zero. To enumerate all the types, make successive calls while incrementing the type index until the method returns DMO_E_NO_MORE_ITEMS. The DMO is not guaranteed to enumerate every media type that it supports.

The format block in the returned type might be NULL. If so, the format type is GUID_NULL. Check the format type before dereferencing the format block.

If the method succeeds, call MoFreeMediaType to free the format block. (This method is also safe to call when the format block is NULL.)

To set the media type, call the IMediaObject::SetInputType method. Setting the media type on one stream can change another stream's preferred types. In fact, a stream might not have a preferred type until the type is set on another stream. For example, a decoder might not have a preferred output type until the input type is set. However, the DMO is not required to update its preferred types dynamically in this fashion. Thus, the types returned by this method are not guaranteed to be valid; they might fail when used in the SetInputType method.

To test whether a particular media type is acceptable, call SetInputType with the DMO_SET_TYPEF_TEST_ONLY flag.

To test whether the dwTypeIndex parameter is in range, set pmt to NULL. The method returns S_OK if the index is in range, or DMO_E_NO_MORE_ITEMS if the index is out of range.

See Also

  • IMediaObject Interface


IMediaObject::GetOutputCurrentType

The GetOutputCurrentType method retrieves the media type that was set for an output stream, if any.

Syntax

HRESULT GetOutputCurrentType(
    DWORD dwOutputStreamIndex,
    DMO_MEDIA_TYPE *pmt
);

Parameters

dwOutputStreamIndex

Zero-based index of an output stream on the DMO.

pmt

[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

The caller must set the media type for the stream before calling this method. To set the media type, call the IMediaObject::SetOutputType method.

If the method succeeds, call MoFreeMediaType to free the format block.


IMediaObject::GetOutputSizeInfo

The GetOutputSizeInfo method retrieves the buffer requirements for a specified output stream.

Syntax

HRESULT GetOutputSizeInfo(
    DWORD dwOutputStreamIndex,
    DWORD *pcbSize,
    DWORD *pcbAlignment
);

Parameters

dwOutputStreamIndex

Zero-based index of an output stream on the DMO.

pcbSize

[out] Pointer to a variable that receives the minimum size of an output buffer for this stream, in bytes.

pcbAlignment

[out] Pointer to a variable that receives the required buffer alignment, in bytes. If the output stream has no alignment requirement, the value is 1.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
S_OK | Success.

Remarks

The buffer requirements may depend on the media types set for each of the streams.

Before calling this method, set the media type of each stream by calling the IMediaObject::SetInputType and IMediaObject::SetOutputType methods. If the media types have not been set, this method might return an error. However, if a stream is optional, and the application will not use the stream, you do not have to set the media type for the stream.

A buffer is aligned if the buffer's start address is a multiple of *pcbAlignment. Depending on the architecture of the microprocessor, it is faster to read and write to an aligned buffer than to an unaligned buffer. On some microprocessors, reading and writing to an unaligned buffer is not supported and can cause the program to crash. Zero is not a valid alignment.

See Also

  • IMediaObject Interface


IMediaObject::GetOutputStreamInfo

The GetOutputStreamInfo method retrieves information about an output stream; for example, whether the stream is discardable, and whether it uses a fixed sample size. This information never changes.

Syntax

HRESULT GetOutputStreamInfo(
    DWORD dwOutputStreamIndex,
    DWORD* pdwFlags
);

Parameters

dwOutputStreamIndex

Zero-based index of an output stream on the DMO.

pdwFlags

[out] Pointer to a variable that receives a bitwise combination of zero or more DMO_OUTPUT_STREAM_INFO_FLAGS flags.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument
S_OK | Success

See Also

  • IMediaObject Interface


IMediaObject::GetOutputType

The GetOutputType method retrieves a preferred media type for a specified output stream.

Syntax

HRESULT GetOutputType(
    DWORD dwOutputStreamIndex,
    DWORD dwTypeIndex,
    DMO_MEDIA_TYPE* pmt
);

Parameters

dwOutputStreamIndex

Zero-based index of an output stream on the DMO.

dwTypeIndex

Zero-based index on the set of acceptable media types.

pmt

[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller, or NULL. If this parameter is non-NULL, the method fills the structure with the media type. You can use the value NULL to test whether the type index is in range, by checking the return code.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NO_MORE_ITEMS | Type index is out of range.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Call this method to enumerate an output stream's preferred media types. The DMO assigns each media type an index value, in order of preference. The most preferred type has an index of zero. To enumerate all the types, make successive calls while incrementing the type index, until the method returns DMO_E_NO_MORE_ITEMS. The DMO is not guaranteed to enumerate every media type that it supports.

The format block in the returned type might be NULL. If so, the format type is GUID_NULL. You should check the format type before dereferencing the format block.

If the method succeeds, call MoFreeMediaType to free the format block. (This method is also safe to call when the format block is NULL.)

To set the media type, call the IMediaObject::SetOutputType method. Setting the media type on one stream can change another stream's preferred types. In fact, a stream might not have a preferred type until the type is set on another stream. For example, a decoder might not have a preferred output type until the input type is set. However, the DMO is not required to update its preferred types dynamically in this fashion. Thus, the types returned by this method are not guaranteed to be valid; they might fail when used in the SetOutputType method.

To test whether a particular media type is acceptable, call SetOutputType with the DMO_SET_TYPEF_TEST_ONLY flag.

To test whether the dwTypeIndex parameter is in range, set pmt to NULL. The method returns S_OK if the index is in range, or DMO_E_NO_MORE_ITEMS if the index is out of range.

See Also

  • IMediaObject Interface


IMediaObject::GetStreamCount

The GetStreamCount method retrieves the number of input and output streams.

Syntax

HRESULT GetStreamCount(
    DWORD* pcInputStreams,
    DWORD* pcOutputStreams
);

Parameters

pcInputStreams

[out] Pointer to a variable that receives the number of input streams. Cannot be NULL.

pcOutputStreams

[out] Pointer to a variable that receives the number of output streams. Cannot be NULL.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

The DMO might have zero input streams or zero output streams. The number of streams does not change; a DMO cannot dynamically add or remove streams.

See Also

  • IMediaObject Interface


IMediaObject::Lock

The Lock method acquires or releases a lock on the DMO. Call this method to keep the DMO serialized when performing multiple operations.

Syntax

HRESULT Lock(
    LONG bLock
);

Parameters

bLock

Value that specifies whether to acquire or release the lock. If the value is non-zero, a lock is acquired. If the value is zero, the lock is released.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_FAIL | Failure
S_OK | Success

Remarks

This method prevents other threads from calling methods on the DMO. If another thread calls a method on the DMO, the thread blocks until the lock is released.

Implementation Note: If you are using the Active Template Library (ATL) to implement a DMO, the name of the Lock method conflicts with the CComObjectRootEx::Lock method. To work around this problem, define the preprocessor symbol FIX_LOCK_NAME before including the header file Dmo.h:

#define FIX_LOCK_NAME
#include <dmo.h>

This directive causes the preprocessor to rename the IMediaObject method to DMOLock. In your DMO, implement the method as DMOLock. In your implementation, call the ATL Lock or Unlock method, depending on the value of bLock. Applications can still invoke the method using the name Lock, because the vtable order does not change.

See also

  • IMediaObject Interface
  • Using the DMO Class Template


IMediaObject::ProcessInput

The ProcessInput method delivers a buffer to the specified input stream.

Syntax

HRESULT ProcessInput(
    DWORD dwInputStreamIndex,
    IMediaBuffer* pBuffer,
    DWORD dwFlags,
    REFERENCE_TIME rtTimestamp,
    REFERENCE_TIME rtTimelength
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

pBuffer

Pointer to the buffer's IMediaBuffer interface.

dwFlags

Bitwise combination of zero or more flags from the DMO_INPUT_DATA_BUFFER_FLAGS enumeration.

rtTimestamp

Time stamp that specifies the start time of the data in the buffer. If the buffer has a valid time stamp, set the DMO_INPUT_DATA_BUFFERF_TIME flag in the dwFlags parameter. Otherwise, the DMO ignores this value.

rtTimelength

Reference time specifying the duration of the data in the buffer. If this value is valid, set the DMO_INPUT_DATA_BUFFERF_TIMELENGTH flag in the dwFlags parameter. Otherwise, the DMO ignores this value.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NOTACCEPTING | Data cannot be accepted.
S_FALSE | No output to process.
S_OK | Success.

Remarks

The input buffer specified in the pBuffer parameter is read-only. The DMO will not modify the data in this buffer. All write operations occur on the output buffers, which are given in a separate call to the IMediaObject::ProcessOutput method.

If the DMO does not process all the data in the buffer, it keeps a reference count on the buffer. It releases the buffer once it has generated all the output, unless it needs to perform lookahead on the data. (To determine whether a DMO performs lookahead, call the IMediaObject::GetInputStreamInfo method.)

If this method returns DMO_E_NOTACCEPTING, call ProcessOutput until the input stream can accept more data. To determine whether the stream can accept more data, call the IMediaObject::GetInputStatus method.

If the method returns S_FALSE, no output was generated from this input and the application does not need to call ProcessOutput. However, a DMO is not required to return S_FALSE in this situation; it might return S_OK.

See Also

  • IMediaObject Interface


IMediaObject::ProcessOutput

The ProcessOutput method generates output from the current input data.

Syntax

HRESULT ProcessOutput(
    DWORD dwFlags,
    DWORD cOutputBufferCount,
    DMO_OUTPUT_DATA_BUFFER* pOutputBuffers,
    DWORD* pdwStatus
);

Parameters

dwFlags

Bitwise combination of zero or more flags from the DMO_PROCESS_OUTPUT_FLAGS enumeration.

cOutputBufferCount

Number of output buffers.

pOutputBuffers

[in, out] Pointer to an array of DMO_OUTPUT_DATA_BUFFER structures containing the output buffers. Specify the size of the array in the cOutputBufferCount parameter.

pdwStatus

[out] Pointer to a variable that receives a reserved value (zero). The application should ignore this value.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_FAIL | Failure
E_INVALIDARG | Invalid argument
E_POINTER | NULL pointer argument
S_FALSE | No output was generated
S_OK | Success

Remarks

The pOutputBuffers parameter points to an array of DMO_OUTPUT_DATA_BUFFER structures. The application must allocate one structure for each output stream. To determine the number of output streams, call the IMediaObject::GetStreamCount method. Set the cOutputBufferCount parameter to this number.

Each DMO_OUTPUT_DATA_BUFFER structure contains a pointer to a buffer's IMediaBuffer interface. The application allocates these buffers. The other members of the structure are status fields. The DMO sets these fields if the method succeeds. If the method fails, their values are undefined.

When the application calls ProcessOutput, the DMO processes as much input data as possible. It writes the output data to the output buffers, starting from the end of the data in each buffer. (To find the end of the data, call the IMediaBuffer::GetBufferAndLength method.) The DMO never holds a reference count on an output buffer.

If the DMO fills an entire output buffer and still has input data to process, the DMO returns the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag in the DMO_OUTPUT_DATA_BUFFER structure. The application should check for this flag by testing the dwStatus member of each structure.

If the method returns S_FALSE, no output was generated. However, a DMO is not required to return S_FALSE in this situation; it might return S_OK.

Discarding data:

You can discard data from a stream by setting the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag in the dwFlags parameter. For each stream that you want to discard, set the pBuffer member of the DMO_OUTPUT_DATA_BUFFER structure to NULL.

For each stream in which pBuffer is NULL:

  • If the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag is set, and the stream is discardable or optional, the DMO discards the data.
  • If the flag is set but the stream is neither discardable nor optional, the DMO discards the data if possible. It is not guaranteed to discard the data.
  • If the flag is not set, the DMO does not produce output data for that stream, but does not discard the data.

To check whether a stream is discardable or optional, call the IMediaObject::GetOutputStreamInfo method.

See Also

  • IMediaObject Interface


IMediaObject::SetInputMaxLatency

The SetInputMaxLatency method sets the maximum latency on a specified input stream. For the definition of maximum latency, see IMediaObject::GetInputMaxLatency.

Syntax

HRESULT SetInputMaxLatency(
    DWORD dwInputStreamIndex,
    REFERENCE_TIME rtMaxLatency
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

rtMaxLatency

Maximum latency.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_FAIL | Failure
E_NOTIMPL | Not implemented
S_OK | Success

See Also

  • IMediaObject Interface
  • IMediaObject::GetInputMaxLatency


IMediaObject::SetInputType

The SetInputType method sets the media type on an input stream, or tests whether a media type is acceptable.

Syntax

HRESULT SetInputType(
    DWORD dwInputStreamIndex,
    const DMO_MEDIA_TYPE *pmt,
    DWORD dwFlags
);

Parameters

dwInputStreamIndex

Zero-based index of an input stream on the DMO.

pmt

[in] Pointer to a DMO_MEDIA_TYPE structure that specifies the media type.

dwFlags

Bitwise combination of zero or more flags from the DMO_SET_TYPE_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted
S_FALSE | Media type is not acceptable
S_OK | Media type was set successfully, or is acceptable

Remarks

Call this method to test, set, or clear the media type on an input stream:

  • To test the media type without setting it, use the DMO_SET_TYPEF_TEST_ONLY flag. If the media type is not acceptable, the method returns S_FALSE.
  • To set the media type, set dwFlags to zero. If the media type is not acceptable, the method returns DMO_E_TYPE_NOT_ACCEPTED.
  • To clear the current media type (if any), use the DMO_SET_TYPEF_CLEAR flag and set pmt to NULL. When the method returns, the stream no longer has a media type. The DMO cannot process samples until the application sets a new media type.

The media types that are currently set on other streams can affect whether the media type is acceptable.

See Also

  • IMediaObject Interface


IMediaObject::SetOutputType

The SetOutputType method sets the media type on an output stream, or tests whether a media type is acceptable.

Syntax

HRESULT SetOutputType(
    DWORD dwOutputStreamIndex,
    const DMO_MEDIA_TYPE* pmt,
    DWORD dwFlags
);

Parameters

dwOutputStreamIndex

Zero-based index of an output stream on the DMO.

pmt

[in] Pointer to a DMO_MEDIA_TYPE structure that specifies the media type.

dwFlags

Bitwise combination of zero or more flags from the DMO_SET_TYPE_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted
S_FALSE | Media type is not acceptable
S_OK | Media type was set successfully, or is acceptable

Remarks

Call this method to test, set, or clear the media type on an output stream:

  • To test the media type without setting it, use the DMO_SET_TYPEF_TEST_ONLY flag. If the media type is not acceptable, the method returns S_FALSE.
  • To set the media type, set dwFlags to zero. If the media type is not acceptable, the method returns DMO_E_TYPE_NOT_ACCEPTED.
  • To clear the current media type (if any), use the DMO_SET_TYPEF_CLEAR flag and set pmt to NULL. When the method returns, the stream no longer has a media type. The DMO cannot process samples until the application sets a new media type, unless the stream is optional.

The media types that are currently set on other streams can affect whether the media type is acceptable.

See Also

  • IMediaObject Interface


IMediaObjectInPlace Interface

The IMediaObjectInPlace interface provides methods for processing data in place. A Microsoft DirectX Media Object (DMO) can expose this interface if it meets the following conditions:

  • It has one input stream and one output stream.
  • Both streams use the same media type.
  • The output is produced in place on the buffer; that is, without copying data.

This interface provides an optimized way to process data. The application calls a single IMediaObjectInPlace::Process method instead of the IMediaObject::ProcessInput and IMediaObject::ProcessOutput methods. However, any DMO that implements this interface must also implement the IMediaObject interface. Therefore, an application is never obligated to use this interface, and a DMO is never guaranteed to implement it.

In addition to the methods inherited from IUnknown, the IMediaObjectInPlace interface exposes the following methods.

Method | Description
Clone | Creates a copy of the DMO in its current state.
GetLatency | Retrieves the latency introduced by this DMO.
Process | Processes a block of data.

Requirements

Declared in Mediaobj.h; include Dmo.h.

Link to Dmoguids.lib.


IMediaObjectInPlace::Clone

The Clone method creates a copy of the DMO in its current state.

Syntax

HRESULT Clone(
    IMediaObjectInPlace** ppMediaObject
);

Parameters

ppMediaObject

[out] Address of a pointer to receive the new DMO's IMediaObjectInPlace interface.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

If the method succeeds, the IMediaObjectInPlace interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

See Also

  • IMediaObjectInPlace Interface


IMediaObjectInPlace::GetLatency

The GetLatency method retrieves the latency introduced by this DMO.

Syntax

HRESULT GetLatency(
    REFERENCE_TIME *pLatencyTime
);

Parameters

pLatencyTime

[out] Pointer to a variable that receives the latency, in 100-nanosecond units.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method returns the average time required to process each buffer. This value usually depends on factors in the run-time environment, such as the processor speed and the CPU load. One possible way to implement this method is for the DMO to keep a running average based on historical data.

See Also

  • IMediaObjectInPlace Interface


IMediaObjectInPlace::Process

The Process method processes a block of data. The application supplies a pointer to a block of input data. The DMO processes the data in place.

Syntax

HRESULT Process(
    ULONG ulSize,
    BYTE *pData
    REFERENCE_TIME refTimeStart,
    DWORD dwFlags
);

Parameters

ulSize

[in] Size of the data, in bytes.

pData

[in, out] Pointer to a buffer of size ulSize. On input, the buffer holds the input data. If the method returns successfully, the buffer contains the output data.

refTimeStart

[in] Start time of the data.

dwFlags

[in] Either DMO_INPLACE_NORMAL or DMO_INPLACE_ZERO. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

Return Code | Description
E_FAIL | Failure
S_FALSE | Success. There is still data to process.
S_OK | Success. There is no remaining data to process.

Remarks

If the method fails, the buffer might contain garbage. The application should not use the contents of the buffer.

The DMO might produce output data beyond the length of the input data. This is called an effect tail. For example, a reverb effect continues after the input reaches silence. If the DMO has an effect tail, this method returns S_FALSE.

While the application has input data for processing, call the Process method with the dwFlags parameter set to DMO_INPLACE_NORMAL. If the last such call returns S_FALSE, call Process again, this time with a zeroed input buffer and the DMO_INPLACE_ZERO flag. The DMO will now fill the zeroed buffer with the effect tail. Continue calling Process in this way until the return value is S_OK, indicating that the DMO has finished processing the effect tail.

If the DMO has no effect tail, this method returns S_TRUE or an error code.

See Also

  • IMediaObjectInPlace Interface


IMediaParamInfo Interface

The IMediaParamInfo interface retrieves information about the parameters that an object supports. The set of parameters that an object supports will not change over the lifetime of an application. To set parameter values, use the IMediaParams interface.

In addition to the methods inherited by IUnknown, the IMediaParamInfo interface exposes the following methods.

Method | Description
GetCurrentTimeFormat | Retrieves the current time format.
GetNumTimeFormats | Retrieves the number of time formats that the object supports.
GetParamCount | Retrieves the number of parameters that the object supports.
GetParamInfo | Retrieves information about a specified parameter.
GetParamText | Retrieves an array of text strings that describe the parameter.
GetSupportedTimeFormat | Retrieves a supported time format.

Requirements

Include Medparam.h.

Link to Dmoguids.lib.


IMediaParamInfo::GetCurrentTimeFormat

The GetCurrentTimeFormat method retrieves the current time format.

Syntax

HRESULT GetCurrentTimeFormat(
    GUID *pguidTimeFormat,
    MP_TIMEDATA *pTimeData
);

Parameters

pguidTimeFormat

[out] Pointer to a variable that receives a time format GUID.

pTimeData

[out] Pointer to a variable that receives an MP_TIMEDATA value specifying the unit of measure for the new format.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

The meaning of the value returned in the pTimeData parameter depends on the time format GUID. For more information, see IMediaParams::SetTimeFormat.

See Also

  • IMediaParamInfo Interface


IMediaParamInfo::GetNumTimeFormats

The GetNumTimeFormats method retrieves the number of time formats that the object supports.

Syntax

HRESULT GetNumTimeFormats(
    DWORD *pdwNumTimeFormats
);

Parameters

pdwNumTimeFormats

[out] Pointer to a variable that receives the number of supported time formats.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • IMediaParamInfo Interface


IMediaParamInfo::GetParamCount

The GetParamCount method retrieves the number of parameters that the object supports.

Syntax

HRESULT GetParamCount(
    DWORD *pdwParams
);

Parameters

pdwParams

[out] Pointer to a variable that receives the number of parameters.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_POINTER | NULL pointer argument.
S_OK | Success.

See Also

  • IMediaParamInfo Interface


IMediaParamInfo::GetParamInfo

The GetParamInfo method retrieves information about a specified parameter.

Syntax

HRESULT GetParamInfo(
    DWORD dwParamIndex,
    MP_PARAMINFO *pInfo
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter.

pInfo

[out] Pointer to an MP_PARAMINFO structure that is filled with the parameter information.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Call the GetParamCount method to retrieve the number of parameters that the object supports.

See Also

  • IMediaParamInfo Interface


IMediaParamInfo::GetParamText

The GetParamText method retrieves a series of text strings that describe the parameter.

Syntax

HRESULT GetParamText(
    DWORD dwParamIndex,
    WCHAR **ppwchText
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter.

ppwchText

[out] Address of a variable that receives a pointer to a series of Unicode™ strings.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

If the method succeeds, *ppwchText points to a string with the following format:

Name\0Unit\0Enum1\0Enum2\0...EnumN\0\0

where

  • Name is the name of the parameter.
  • Unit is the name of the units; for example, milliseconds.
  • Enum1 through EnumN are descriptive names for the parameter's enumerated values. (Applies only to parameters of type MPT_ENUM.)

The application can display these values within its user interface. They are not guaranteed to follow a consistent naming scheme. If the user's computer is using an international code page, the method might return a localized string corresponding to that code page.

The object uses the CoTaskMemAlloc function to allocate memory for the string. After you call this method, call CoTaskMemFree to free the buffer.

See Also

  • IMediaParamInfo Interface


IMediaParamInfo::GetSupportedTimeFormat

The GetSupportedTimeFormat method retrieves a supported time format.

Syntax

HRESULT GetSupportedTimeFormat(
    DWORD dwFormatIndex,
    GUID *pguidTimeFormat
);

Parameters

dwFormatIndex

[in] Index of the time format to retrieve.

pguidTimeFormat

[out] Pointer to a variable that receives a time format GUID.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

Call the GetNumTimeFormats method to retrieve the number of time formats that the object supports.

See Also

  • IMediaParamInfo Interface
  • Time Format GUIDs


IMediaParams Interface

The IMediaParams interface sets and retrieves envelope-following parameters on an object.

To reduce overhead, parameters are referenced by index value, and all parameter values are 32 bits, defined as type MP_DATA. Use the IMediaParamInfo interface to determine whether a given parameter is an integer, floating-point value, Boolean value, or member of an enumerated type.

In addition to the methods inherited by IUnknown, the IMediaParams interface exposes the following methods.

Method | Description
AddEnvelope | Adds an envelope to a parameter.
FlushEnvelope | Flushes envelope data for a specified parameter over the specified time range.
GetParam | Retrieves the most recent value of the specified parameter.
SetParam | Sets the value of a parameter.
SetTimeFormat | Specifies the time format for the object.

Requirements

Include Medparam.h.

Link to Dmoguids.lib.


IMediaParams::AddEnvelope

The AddEnvelope method adds an envelope to a parameter.

Syntax

HRESULT AddEnvelope(
    DWORD dwParamIndex,
    DWORD cPoints,
    MP_ENVELOPE_SEGMENT *pEnvelope,
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to add the envelope to every parameter.

cPoints

[in] Number of segments in the envelope.

pEnvelope

[in] Pointer to an array of MP_ENVELOPE_SEGMENT structures that define the envelope segments. The size of the array is given in the cPoints parameter.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
E_OUTOFMEMEORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

The caller should add envelopes in time-ascending order. Otherwise, the results on playback are indeterminate. If one envelope overlaps another, the later envelope takes precedence.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

Example Code

The following code sets two envelope segments, both using a linear function.

#define MSEC 10000  // One millisecond

// Define an array with two segments. Note the segments appear in
// time-ascending order.
MP_ENVELOPE_SEGMENT Segments[] =
{
    {
        0,                  // rtStart
        3 * MSEC,           // rtStop
        0,                  // valStart
        12,                 // valStop
        MP_CURVE_LINEAR,    // iCurve
        MPF_ENVLP_STANDARD  // flags
    },
    {
        6 * MSEC,
        9 * MSEC,
        12,
        0,
        MP_CURVE_LINEAR,
        MPF_ENVLP_STANDARD
    }
};
// Define the number of segments in the array.
DWORD cSegments = sizeof(Segments) / sizeof(Segments[0]);
DWORD dwParam = 0;  // Which parameter to set.

hr = pMediaParams->AddEnvelope(dwParam, cSegments, Segments);

This example assumes that the caller has previous used the IMediaParamInfo interface to query whether the DMO supports the MP_CURVE_LINEAR curve for that parameter.

See Also

  • IMediaParams Interface


IMediaParams::FlushEnvelope

The FlushEnvelope method flushes envelope data for a specified parameter over the specified time range.

Syntax

HRESULT FlushEnvelope(
    DWORD dwParamIndex,
    REFERENCE_TIME refTimeStart,
    REFERENCE_TIME refTimeEnd
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to flush envelope data from every parameter.

refTimeStart

[in] Start time of the envelope data to flush.

refTimeEnd

[in] Stop time of the envelope data to flush.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
S_OK | Success.

Remarks

If the time span specified by refTimeStart and refTimeEnd overlaps an envelope segment, the entire segment is flushed. On the other hand, if it falls on the boundary of an envelope segment, the entire segment is retained. Thus:

  • If the start time falls inside an envelope segment, the segment is flushed.
  • If the end time falls inside an envelope segment, the segment is flushed.
  • If the start time equals the end time of an envelope segment, the segment is retained.
  • If the end time equals the start time of an envelope segment, the segment is retained.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

See Also

  • IMediaParams Interface


IMediaParams::GetParam

The GetParam method retrieves the current value of the specified parameter. If the parameter is currently within an envelope segment, the returned value is the value on the most recently processed sample.

Syntax

HRESULT GetParam(
    DWORD dwParamIndex,
    MP_DATA *pValue
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter.

pValue

[out] Pointer to a variable of type MP_DATA that receives the parameter value.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

See Also

  • IMediaParams Interface


IMediaParams::SetParam

The SetParam method sets the value of a parameter.

Syntax

HRESULT SetParam(
    DWORD dwParamIndex,
    MP_DATA value
);

Parameters

dwParamIndex

[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to apply the value to every parameter.

value

[in] New value of the parameter.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_INVALIDARG | Index out of range, or illegal parameter value.
S_OK | Success.

Remarks

If the parameter is currently within an envelope segment, the envelope segment will overwrite the new value. To remove an envelope segment, call the FlushEnvelope method.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

See Also

  • IMediaParams Interface


IMediaParams::SetTimeFormat

The SetTimeFormat method specifies the time format for the object.

Syntax

HRESULT SetTimeFormat(
    GUID guidTimeFormat,
    MP_TIMEDATA mpTimeData
);

Parameters

guidTimeFormat

[in] Time format GUID that specifies the time format.

mpTimeData

[in] Value of type MP_TIMEDATA that specifies the unit of measure for the new format.

Return Values

Returns an HRESULT value. Possible values include the following.

Return Code | Description
E_DMOTIMESTAMPFORMAT | Object does not support this time format.
S_OK | Success.

Remarks

Objects can support more than one time format. Every object must support reference time, in which each unit of time is 100 nanoseconds (ns). Other formats are optional. The application must ensure that time stamps on the input buffers match whatever time format was set using this method.

The meaning of the mpTimeData parameter depends on the value of the guidTimeFormat parameter.

Time Format | Meaning of Time Data
GUID_TIME_MUSIC | Parts per quarter note.
GUID_TIME_REFERENCE | Ignored.
GUID_TIME_SAMPLES | Samples per second.

When you call this method, also call the FlushEnvelope method, to flush any envelopes that were set using the previous time format.

To determine what time formats an object supports, call the IMediaParamInfo::GetSupportedTimeFormat method. To retrieve the current format, call the IMediaParamInfo::GetCurrentTimeFormat method.

See Also

  • IMediaParams Interface
  • Time Format GUIDs


DMO Structures

This section describes the DirectX Media Object (DMO) structures.

Structure | Description
DMO_MEDIA_TYPE | Describes the format of the data used by a stream in a DMO.
DMO_OUTPUT_DATA_BUFFER | Describes an output buffer used by a DMO.
DMO_PARTIAL_MEDIATYPE | Partially describes a media type used by a DMO.
MP_ENVELOPE_SEGMENT | Defines an envelope segment used by a media parameter.
MP_PARAMINFO | Contains information about a media parameter.


DMO_MEDIA_TYPE Structure

The DMO_MEDIA_TYPE structure describes the format of the data used by a stream in a Microsoft DirectX Media Object (DMO).

Syntax

typedef struct _DMOMediaType {
    GUID     majortype;
    GUID     subtype;
    BOOL     bFixedSizeSamples;
    BOOL     bTemporalCompression;
    ULONG    lSampleSize;
    GUID     formattype;
    IUnknown *pUnk;
    ULONG    cbFormat;
    [size_is(cbFormat)] BYTE * pbFormat;
} DMO_MEDIA_TYPE;

Members

majortype

Major type GUID of the stream.

subtype

Subtype GUID of the stream.

bFixedSizeSamples

If TRUE, samples are of a fixed size. This field is informational only. For audio, it is generally set to TRUE. For video, it is usually TRUE for uncompressed video and FALSE for compressed video.

bTemporalCompression

If TRUE, samples are compressed using temporal (interframe) compression. (A value of TRUE indicates that not all frames are key frames.) This field is informational only.

lSampleSize

Size of the sample in bytes. For compressed data, the value can be zero.

formattype

GUID specifying the format type. The pbFormat member points to the corresponding format structure. Format types include the following.

Format Type | Format structure
FORMAT_DVInfo | DVINFO
FORMAT_MPEG2Video | MPEG2VIDEOINFO
FORMAT_MPEGVideo | MPEG1VIDEOINFO
FORMAT_None | NULL
FORMAT_VideoInfo | VIDEOINFOHEADER
FORMAT_VideoInfo2 | VIDEOINFOHEADER2
FORMAT_WaveFormatEx | WAVEFORMATEX

pUnk

Not used.

cbFormat

Size of the format block of the media type.

pbFormat

Pointer to the format structure. The structure type is specified by the formattype member. The format structure must be present, unless formattype is GUID_NULL or FORMAT_None.

Remarks

This structure is identical to the DirectShow AM_MEDIA_TYPE structure. The bFixedSizeSamples, bTemporalCompression, and lSampleSize members are for compatibility with DirectShow. Other DMO clients are not required to use them.

See Also

  • DMO Structures


DMO_OUTPUT_DATA_BUFFER Structure

The DMO_OUTPUT_DATA_BUFFER structure describes an output buffer used by a Microsoft DirectX Media Object (DMO).

Syntax

typedef struct _DMO_OUTPUT_DATA_BUFFER {
    IMediaBuffer *pBuffer;
    DWORD dwStatus;
    REFERENCE_TIME rtTimestamp;
    REFERENCE_TIME rtTimelength;
} DMO_OUTPUT_DATA_BUFFER, *PDMO_OUTPUT_DATA_BUFFER;

Members

pBuffer

[in] Pointer to the IMediaBuffer interface of a buffer allocated by the application.

dwStatus

[out] Status flags. After processing output, the DMO sets this member to a bitwise combination of zero or more DMO_OUTPUT_DATA_BUFFER_FLAGS flags.

rtTimestamp

[out] Time stamp that specifies the start time of the data in the buffer. If the buffer has a valid time stamp, the DMO sets this member and also sets the DMO_OUTPUT_DATA_BUFFERF_TIME flag in the dwStatus member. Otherwise, ignore this member.

rtTimelength

[out] Reference time specifying the length of the data in the buffer. If the DMO sets this member to a valid value, it also sets the DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH flag in the dwStatus member. Otherwise, ignore this member.

See Also

  • IMediaObject::ProcessOutput
  • DMO Structures


DMO_PARTIAL_MEDIATYPE Structure

The DMO_PARTIAL_MEDIATYPE structure partially describes a media type used by a Microsoft DirectX Media Object (DMO). The DMO registration functions use this structure to specify supported media types.

Syntax

typedef struct _DMO_PARTIAL_MEDIATYPE {
    GUID type;
    GUID subtype;
} DMO_PARTIAL_MEDIATYPE, *PDMO_PARTIAL_MEDIATYPE;

Members

type

Major type GUID. Use GUID_NULL to match any major type.

subtype

Subtype GUID. Use GUID_NULL to match any subtype.

See Also

  • DMO Structures


MP_ENVELOPE_SEGMENT Structure

The MP_ENVELOPE_SEGMENT structure defines an envelope segment used by an envelope-following parameter.

Syntax

typedef struct _MP_ENVELOPE_SEGMENT {
    REFERENCE_TIME   rtStart;
    REFERENCE_TIME   rtEnd;
    MP_DATA          valStart;
    MP_DATA          valEnd;
    MP_CURVE_TYPE    iCurve;
    MP_FLAGS         flags;
} MP_ENVELOPE_SEGMENT;

Members

rtStart

Start time of the segment, relative to the time stamp on the first buffer, in 100-nanosecond units.

rtEnd

Stop time of the segment, relative to the time stamp on the first buffer, in 100-nanosecond units.

valStart

Initial value of the parameter, at the start of the segment.

valEnd

Final value of the parameter, at the end of the segment.

iCurve

Member of the MP_CURVE_TYPE enumerated type that specifies the curve followed by the parameter.

flags

Specifies one of the following flags.

Constant | Value | Description
MP_FLAGS MPF_ENVLP_STANDARD | 0x0000 | Use all the information provided with the envelope segment.
MP_FLAGS MPF_ENVLP_BEGIN_CURRENTVAL | 0x0001 | Ignore the specified start value. Start from the current value.
MP_FLAGS MPF_ENVLP_BEGIN_NEUTRALVAL | 0x0002 | Ignore the specified start value. Start from the neutral value. (See MP_PARAMINFO.)

See Also

  • DMO Structures


MP_PARAMINFO Structure

The MP_PARAMINFO structure contains information about a parameter.

Syntax

typedef struct _MP_PARAMINFO {
    MP_TYPE    mpType;
    MP_CAPS    mopCaps;
    MP_DATA    mpdMinValue;
    MP_DATA    mpdMaxValue;
    MP_DATA    mpdNeutralValue;
    WCHAR      szUnitText[32];
    WCHAR      szLabel[32];
} MP_PARAMINFO;

Members

mpType

Member of the MP_TYPE enumeration that specifies the valid data type for this parameter.

mopCaps

Bitwise combination of one or more Parameter Capabilities Flags that specify which envelope curves are supported. For Boolean and enumeration parameters, only MP_CAPS_CURVE_JUMP is valid.

mpdMinValue

Minimum value of the parameter. Used only for parameters with numeric values.

mpdMaxValue

Maximum value of the parameter. Used only for parameters with numeric values.

mpdNeutralValue

Default or "neutral" value of the parameter.

szUnitText

NULL-terminated wide-character string that contains the name of the units for the parameter.

szLabel

NULL-terminated wide-character string that contains the name of the parameter.

Remarks

The szUnitText and szLabel members always contain English-language strings. For international support, use the IMediaParamInfo::GetParamText method.

See Also

  • DMO Structures


DMO Enumerated Types

This section describes the Microsoft DirectX Media Object (DMO) enumerated types.

Enumerated type | Description
DMO_ENUM_FLAGS | Defines flags that specify search criteria when enumerating DMOs.
DMO_INPUT_DATA_BUFFER_FLAGS | Defines flags that describe an input buffer.
DMO_INPUT_STREAM_INFO_FLAGS | Defines flags that describe an input stream.
DMO_OUTPUT_DATA_BUFFER_FLAGS | Defines flags that describe an output buffer.
DMO_OUTPUT_STREAM_INFO_FLAGS | Defines flags that describe an output stream.
DMO_PROCESS_OUTPUT_FLAGS | Defines flags that specify output processing requests.
DMO_REGISTER_FLAGS | Defines flags that specify registry information for a DMO.
DMO_SET_TYPE_FLAGS | Defines flags for setting the media type on a stream.
DMO_VIDEO_OUTPUT_STREAM_FLAGS | Defines flags that describe requested features for video optimizations.
MP_CURVE_TYPE | Defines the curve that a media parameter follows within an envelope segment.
MP_TYPE | Specifies the data type for a parameter.


DMO_ENUM_FLAGS Enumeration

The DMO_ENUM_FLAGS enumeration defines flags that specify search criteria when enumerating Microsoft DirectX Media Objects (DMOs).

Syntax

enum DMO_ENUM_FLAGS {
    DMO_ENUMF_INCLUDE_KEYED = 0x00000001
};

Elements

DMO_ENUMF_INCLUDE_KEYED

The enumeration should include DMOs whose use is restricted by a software key. If this flag is absent, keyed DMOs are omitted from the enumeration.

Remarks

A software key enables the developer of a DMO to control who uses the DMO. If a DMO has a software key, applications must unlock the DMO to use it. The method for unlocking the DMO depends on the implementation. Consult the documentation for the particular DMO.

See Also

  • DMO Enumerated Types
  • DMOEnum


DMO_INPUT_DATA_BUFFER_FLAGS Enumeration

The DMO_INPUT_DATA_BUFFER_FLAGS enumeration defines flags that describe an input buffer.

Syntax

enum _DMO_INPUT_DATA_BUFFER_FLAGS {
    DMO_INPUT_DATA_BUFFERF_SYNCPOINT       = 0x00000001,
    DMO_INPUT_DATA_BUFFERF_TIME            = 0x00000002,
    DMO_INPUT_DATA_BUFFERF_TIMELENGTH      = 0x00000004
};

Elements

DMO_INPUT_DATA_BUFFERF_SYNCPOINT

The beginning of the data is a synchronization point.

DMO_INPUT_DATA_BUFFERF_TIME

The buffer's time stamp is valid.

DMO_INPUT_DATA_BUFFERF_TIMELENGTH

The buffer's indicated time length is valid.

See Also

  • DMO Enumerated Types
  • IMediaObject::ProcessInput


DMO_INPUT_STREAM_INFO_FLAGS Enumeration

The DMO_INPUT_STREAM_INFO_FLAGS enumeration defines flags that describe an input stream.

Syntax

enum _DMO_INPUT_STREAM_INFO_FLAGS {
    DMO_INPUT_STREAMF_WHOLE_SAMPLES            = 0x00000001,
    DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 0x00000002,
    DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE        = 0x00000004,
    DMO_INPUT_STREAMF_HOLDS_BUFFERS            = 0x00000008
};

Elements

DMO_INPUT_STREAMF_WHOLE_SAMPLES

The stream requires whole samples. Samples must not span multiple buffers, and buffers must not contain partial samples.

DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER

Each buffer must contain exactly one sample.

DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE

All the samples in this stream must be the same size.

DMO_INPUT_STREAMF_HOLDS_BUFFERS

The DMO performs lookahead on the incoming data, and may hold multiple input buffers for this stream.

See Also

  • DMO Enumerated Types
  • IMediaObject::GetInputStreamInfo


DMO_OUTPUT_DATA_BUFFER_FLAGS Enumeration

The DMO_OUTPUT_DATA_BUFFER_FLAGS enumeration defines flags that describe an output buffer.

Syntax

enum _DMO_OUTPUT_DATA_BUFFER_FLAGS {
    DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT       = 0x00000001,
    DMO_OUTPUT_DATA_BUFFERF_TIME            = 0x00000002,
    DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH      = 0x00000004,
    DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE      = 0x01000000
};

Elements

DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT

The beginning of the data is a synchronization point.

DMO_OUTPUT_DATA_BUFFERF_TIME

The buffer's time stamp is valid.

DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH

The buffer's indicated time length is valid.

DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE

There is still input data available for processing, but the output buffer is full.

See Also

  • DMO Enumerated Types
  • IMediaObject::ProcessOutput


DMO_OUTPUT_STREAM_INFO_FLAGS Enumeration

The DMO_OUTPUT_STREAM_INFO_FLAGS enumeration defines flags that describe an output stream.

Syntax

enum _DMO_OUTPUT_STREAM_INFO_FLAGS {
    DMO_OUTPUT_STREAMF_WHOLE_SAMPLES            = 0x00000001,
    DMO_OUTPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 0x00000002,
    DMO_OUTPUT_STREAMF_FIXED_SAMPLE_SIZE        = 0x00000004,
    DMO_OUTPUT_STREAMF_DISCARDABLE              = 0x00000008,
    DMO_OUTPUT_STREAMF_OPTIONAL                 = 0x00000010
};

Elements

DMO_OUTPUT_STREAMF_WHOLE_SAMPLES

The stream contains whole samples. Samples do not span multiple buffers, and buffers do not contain partial samples.

DMO_OUTPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER

Each buffer contains exactly one sample.

DMO_OUTPUT_STREAMF_FIXED_SAMPLE_SIZE

All the samples in this stream are the same size.

DMO_OUTPUT_STREAMF_DISCARDABLE

The stream is discardable. Within calls to IMediaObject::ProcessOutput, the DMO can discard data for this stream without copying it to an output buffer.

DMO_OUTPUT_STREAMF_OPTIONAL

The stream is optional. An optional stream is discardable. Also, the application can ignore this stream entirely; it does not have to set the media type for the stream. Optional streams generally contain additional information, or data not needed by all applications.

Remarks

The DMO_OUTPUT_STREAMF_DISCARDABLE and DMO_OUTPUT_STREAMF_OPTIONAL flags are mutually exclusive. The DMO can set one of these flags (or neither), but not both.

See Also

  • DMO Enumerated Types
  • IMediaObject::GetOutputStreamInfo


DMO_PROCESS_OUTPUT_FLAGS Enumeration

The DMO_PROCESS_OUTPUT_FLAGS enumeration defines flags that specify output processing requests.

Syntax

enum _DMO_PROCESS_OUTPUT_FLAGS {
    DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = 0x00000001
};

Elements

DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER

Discard the output when the pointer to the output buffer is NULL.

See Also

  • DMO Enumerated Types
  • IMediaObject::ProcessOutput


DMO_REGISTER_FLAGS Enumeration

The DMO_REGISTER_FLAGS enumeration defines flags that specify registry information for a Microsoft DirectX Media Object (DMO).

Syntax

enum DMO_REGISTER_FLAGS {
    DMO_REGISTERF_IS_KEYED = 0x00000001
};

Elements

DMO_REGISTERF_IS_KEYED

Use of the DMO is restricted by a software key.

Remarks

A software key enables the developer of a DMO to control who uses the DMO. If a DMO has a software key, applications must unlock the DMO to use it. The method for unlocking the DMO depends on the implementation. Consult the documentation for the particular DMO.

See Also

  • DMO Enumerated Types
  • DMORegister


DMO_SET_TYPE_FLAGS Enumeration

The DMO_SET_TYPE_FLAGS enumeration defines flags for setting the media type on a stream.

Syntax

enum _DMO_SET_TYPE_FLAGS {
    DMO_SET_TYPEF_TEST_ONLY = 0x00000001,
    DMO_SET_TYPEF_CLEAR     = 0x00000002
};

Elements

DMO_SET_TYPEF_TEST_ONLY

Test the media type but do not set it.

DMO_SET_TYPEF_CLEAR

Clear the media type that was set for the stream.

Remarks

The DMO_SET_TYPEF_TEST_ONLY and DMO_SET_TYPEF_CLEAR flags are mutually exclusive. Do not set both flags.

See Also

  • DMO Enumerated Types
  • IMediaObject::SetInputType
  • IMediaObject::SetOutputType


DMO_VIDEO_OUTPUT_STREAM_FLAGS Enumeration

The DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration defines flags that describe requested features, for video optimizations.

Syntax

enum _DMO_VIDEO_OUTPUT_STREAM_FLAGS {
    DMO_VOSF_NEEDS_PREVIOUS_SAMPLE = 0x00000001
};

Elements

DMO_VOSF_NEEDS_PREVIOUS_SAMPLE

Requests that every output buffer passed to the DMO contain the previous data that was generated.

See Also

  • DMO Enumerated Types
  • IDMOVideoOutputOptimizations


MP_CURVE_TYPE Enumeration

The MP_CURVE_TYPE enumeration defines the curve that a media parameter follows within an envelope segment.

Syntax

typedef enum _MP_CURVE_TYPE {
    MP_CURVE_JUMP       = 0x0001,
    MP_CURVE_LINEAR     = 0x0002,
    MP_CURVE_SQUARE     = 0x0004,
    MP_CURVE_INVSQUARE  = 0x0008,
    MP_CURVE_SINE       = 0x0010,
} MP_CURVE_TYPE;

Elements

MP_CURVE_JUMP

No interpolation. Jump to the next point.

MP_CURVE_LINEAR

Linear interpolation.

MP_CURVE_SQUARE

Parabolic curve.

MP_CURVE_INVSQUARE

Inverse square curve.

MP_CURVE_SINE

Sine curve.

Remarks

The following table lists the defined curves and their mathematical equivalents.

Value | Curve to Fit | Range
MP_CURVE_LINEAR | y = x | 0.0 – 1.0
MP_CURVE_SQUARE | y = x2 | 0.0 – 1.0
MP_CURVE_INVSQUARE | y = 1 – x2 | 0.0 – 1.0
MP_CURVE_SINE | y = sin(x) | –π/2 – π/2

For Boolean and enumeration parameters, only MP_CURVE_JUMP is valid.

See Also

  • DMO Enumerated Types
  • MP_ENVELOPE_SEGMENT


MP_TYPE Enumeration

The MP_TYPE enumeration specifies the data type for a parameter.

Syntax

typedef enum _MP_Type {
    MPT_INT,
    MPT_FLOAT,
    MPT_BOOL,
    MPT_ENUM,
    MPT_MAX,
} MP_TYPE;

Elements

MPT_INT

Value is a signed 32-bit integer.

MPT_FLOAT

Value is a 32-bit IEEE floating-point value.

MPT_BOOL

Value is Boolean. Use the following constants for Boolean parameters:

Constant | Description
MP_DATA MPBOOL_FALSE | FALSE
MP_DATA MPBOOL_TRUE | TRUE

MPT_ENUM

Value is taken from a set of consecutive integers.

MPT_MAX

Reserved.

Remarks

To reduce type conversions at run time, all parameters have 32-bit float values, defined as type MP_DATA. The members of this enumeration specify how a given parameter should be interpreted.

See Also

  • MP_PARAMINFO
  • DMO Enumerated Types


DMO Functions

This section describes the Microsoft DirectX Media Object (DMO) functions.

Function | Description
DMOEnum | Enumerates DMOs listed in the registry.
DMOGetName | Retrieves the name of a DMO from the registry.
DMOGetTypes | Retrieves the media types registered for a DMO.
DMORegister | Registers a DMO.
DMOUnregister | Unregisters a DMO.
MoCopyMediaType | Copies one media type structure to another.
MoCreateMediaType | Allocates a new media type structure.
MoDeleteMediaType | Deletes a media type structure that was previously allocated.
MoDuplicateMediaType | Duplicates a media type structure.
MoFreeMediaType | Frees the allocated members of a media type structure.
MoInitMediaType | Initializes a media type structure.


DMOEnum

The DMOEnum function enumerates DMOs listed in the registry. The caller can search by category, media type, or both.

Syntax

HRESULT DMOEnum(
    REFGUID guidCategory,
    DWORD dwFlags,
    DWORD cInTypes,
    const DMO_PARTIAL_MEDIATYPE *pInTypes,
    DWORD cOutTypes,
    const DMO_PARTIAL_MEDIATYPE *pOutTypes,
    IEnumDMO **ppEnum
);

Parameters

guidCategory

GUID that specifies which category of DMO to search. Use GUID_NULL to search every category. See DMO GUIDs for a list of category GUIDs.

dwFlags

Bitwise combination of zero or more flags from the DMO_ENUM_FLAGS enumeration.

cInTypes

Number of input media types to use in the search criteria. Use zero to match any input type.

pInTypes

Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that contain the input media types. Specify the size of the array in the cInTypes parameter.

cOutTypes

Number of output media types to use in the search criteria. Use zero to match any output type.

pOutTypes

Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that contain the output media types. Specify the size of the array in the cOutTypes parameter.

ppEnum

Address of a variable to receive the IEnumDMO interface of the enumerator.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

Remarks

This method returns a pointer to an enumerator object that supports the IEnumDMO interface. The application uses the IEnumDMO interface to enumerate over the set of DMOs that match the search criteria.

Requirements

Declared in Dmoreg.h; include Dmo.h.

Link to Msdmo.lib.

Example Code

The following example enumerates all audio effect DMOs on the user's system, including keyed DMOs.

IEnumDMO* pEnum = NULL;
HRESULT hr = DMOEnum(
    DMOCATEGORY_AUDIO_EFFECT, // Category
    DMO_ENUMF_INCLUDE_KEYED,  // Included keyed DMOs
    0, NULL,                  // Input types (don't care)
    0, NULL,                  // Output types (don't care)
    &pEnum);

if (SUCCEEDED(hr))
{
    CLSID clsidDMO;
    WCHAR* wszName;
    do
    {
        hr = pEnum->Next(1, &clsidDMO, &wszName, NULL);
        if (hr == S_OK)
        {
            // Now wszName holds the friendly name of the DMO,
            // and clsidDMO holds the CLSID.

            // Remember to release wszName!
            CoTaskMemFree(wszName);
        }
    } while (hr == S_OK);
    pEnum->Release();
}

See Also

  • DMO Functions


DMOGetName

The DMOGetName function retrieves the name of a DMO from the registry.

Syntax

HRESULT DMOGetName(
   REFCLSID clsidDMO,
   WCHAR szName[]
);

Parameters

clsidDMO

Class identifier (CLSID) of the DMO.

szName

Array of 80 Unicode characters that receives the name of the DMO. The caller must allocate the array. The name is a NULL-terminated string.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_FAIL | Failure.
S_FALSE | No name was registered for this DMO, or the name has zero length.
S_OK | Success.

Remarks

If the method returns S_FALSE, szName is set to '\0'.

Requirements

Declared in Dmoreg.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


DMOGetTypes

The DMOGetTypes function retrieves the media types registered for a DMO.

Syntax

HRESULT DMOGetTypes(
    REFCLSID clsidDMO,
    unsigned long ulInputTypesRequested,
    unsigned long *pulInputTypesSupplied,
    DMO_PARTIAL_MEDIATYPE *pInputTypes,
    unsigned long ulOutputTypesRequested,
    unsigned long *pulOutputTypesSupplied,
    DMO_PARTIAL_MEDIATYPE *pOutputTypes
);

Parameters

clsidDMO

Class identifier (CLSID) of the DMO.

ulInputTypesRequested

Size of the array passed in the pInputTypes parameter.

pulInputTypesSupplied

Pointer to a variable that receives the number of DMO_PARTIAL_MEDIATYPE structures in pInputTypes that the function fills in.

pInputTypes

Pointer to a caller-allocated array of DMO_PARTIAL_MEDIATYPE structures. The size of the array is given in the ulInputTypesRequested parameter. The function fills the array with the input types registered for the DMO.

ulOutputTypesRequested

Size of the array passed in the pOutputTypes parameter.

pulOutputTypesSupplied

Pointer to a variable that receives the number of DMO_PARTIAL_MEDIATYPE structures in pOutputTypes that the function fills in.

pOutputTypes

Pointer to a caller-allocated array of DMO_PARTIAL_MEDIATYPE structures. The size of the array is given in the ulOutputTypesRequested parameter. The function fills the array with the DMO output types registered for the DMO.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_FAIL | Failure
S_FALSE | Array too small
S_OK | Success

Remarks

If one of the arrays is too small to hold all of the registered types, the function fills the array but returns S_FALSE.

If the DMO did not register any media types, the function returns S_OK and sets *pulInputTypesSupplied and *pulOutputTypesSupplied to zero.

Requirements

Declared in Dmoreg.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


DMORegister

The DMORegister function registers a DMO.

Syntax

HRESULT DMORegister(
   LPCWSTR szName,
   REFCLSID clsidDMO,
   REFGUID guidCategory,
   DWORD dwFlags,
   DWORD cInTypes,
   const DMO_PARTIAL_MEDIATYPE *pInTypes,
   DWORD cOutTypes,
   const DMO_PARTIAL_MEDIATYPE *pOutTypes
);

Parameters

szName

NULL-terminated string that contains a descriptive name for the DMO. Names longer than 79 characters might be truncated.

clsidDMO

Class identifier (CLSID) of the DMO.

guidCategory

GUID that specifies the category of the DMO. See DMO GUIDs for a list of category GUIDs.

dwFlags

Bitwise combination of zero or more flags from the DMO_REGISTER_FLAGS enumeration.

cInTypes

Number of input media types to register. Can be zero.

pInTypes

Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that specify the input media types. The size of the array is specified in the cInTypes parameter.

cOutTypes

Number of output media types to register.

pOutTypes

Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that specify the output media types. The size of the array is specified in the cOutTypes parameter. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_FAIL | Failure
E_INVALIDARG | Invalid argument
S_OK | Success

Remarks

This function adds information about a DMO to the registry. Applications or software components can use this information to locate the DMOs they need to use, by calling the DMOEnum function. For example, to encode a video stream, you would search in the DMOCATEGORY_VIDEO_ENCODER category for a DMO whose media types matched your requirements.

The media types registered by this function are only for the purpose of finding the DMO. They do not necessarily match the types returned by the IMediaObject::GetInputType and IMediaObject::GetOutputType methods. For example, a decoder might register just its main input types. After the DMO is created and its input type has been set, its GetOutputType method will return all of the decompressed types it can generate.

Requirements

Declared in Dmoreg.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


DMOUnregister

The DMOUnregister function unregisters a DMO.

Syntax

HRESULT DMOUnregister(
   REFCLSID clsidDMO,
   REFGUID guidCategory
);

Parameters

clsidDMO

Class identifier (CLSID) of the DMO.

guidCategory

GUID that specifies the category from which to remove the DMO. Use GUID_NULL to unregister the DMO from every category. See DMO GUIDs for a list of category GUIDs.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_INVALIDARG | Invalid argument.
S_FALSE | This CLSID was not registered in the specified category.
S_OK | Success.

Requirements

Declared in Dmoreg.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoCopyMediaType

The MoCopyMediaType function copies the members of one media type structure into another media type structure.

Syntax

HRESULT MoCopyMediaType(
    DMO_MEDIA_TYPE *pmtDest,
    const DMO_MEDIA_TYPE *pmtSrc
);

Parameters

pmtDest

Pointer to the target DMO_MEDIA_TYPE structure. The caller must allocate, but not initialize, this structure.

pmtSrc

Pointer to the source DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This function copies all the members of pmtSrc to pmtDest and copies the format block. The caller must free the target media type by calling the MoFreeMediaType function.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoCreateMediaType

The MoCreateMediaType function allocates a new media type structure.

Syntax

HRESULT MoCreateMediaType(
    DMO_MEDIA_TYPE **ppmt,
    DWORD cbFormat
);

Parameters

ppmt

Address of a pointer to a DMO_MEDIA_TYPE structure that receives the allocated structure.

cbFormat

Number of bytes to allocate for the format block. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This function allocates a new DMO_MEDIA_TYPE structure and then initializes it by calling the MoInitMediaType function. The caller must delete the media type structure by calling the MoDeleteMediaType function.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoDeleteMediaType

The MoDeleteMediaType function deletes a media type structure that was previously allocated.

Syntax

HRESULT MoDeleteMediaType(
    DMO_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to an initialized DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This function frees the allocated members of the media type structure by calling MoFreeMediaType. Then it frees the media type structure itself.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoDuplicateMediaType

The MoDuplicateMediaType function duplicates a media type structure.

Syntax

HRESULT MoDuplicateMediaType(
    DMO_MEDIA_TYPE **ppmtDest,
    const DMO_MEDIA_TYPE *pmtSrc
);

Parameters

ppmtDest

Address of a pointer to a DMO_MEDIA_TYPE structure that receives the duplicated structure.

pmtSrc

Pointer to the media type structure to duplicate.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This method is equivalent to calling MoCreateMediaType and MoCopyMediaType. The caller must delete the returned media type structure by calling the MoDeleteMediaType function.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoFreeMediaType

The MoFreeMediaType function frees the allocated members of a media type structure.

Syntax

HRESULT MoFreeMediaType(
    DMO_MEDIA_TYPE *pmt
);

Parameters

pmt

Pointer to an initialized DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This function frees the format block pointed to by the pbFormat member of the DMO_MEDIA_TYPE structure.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


MoInitMediaType

The MoInitMediaType function initializes a media type structure.

Syntax

HRESULT MoInitMediaType(
    DMO_MEDIA_TYPE *pmt,
    DWORD cbFormat
);

Parameters

pmt

Pointer to an uninitialized DMO_MEDIA_TYPE structure allocated by the caller.

cbFormat

Number of bytes to allocate for the format block. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following.

Result Code | Description
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument
S_OK | Success

Remarks

This function allocates the format block and sets the cbFormat and pbFormat members of the DMO_MEDIA_TYPE structure.

The caller must free the media type by calling the MoFreeMediaType function.

Requirements

Declared in Dmort.h; include Dmo.h.

Link to Msdmo.lib.

See Also

  • DMO Functions


DMO Constants

  • DMO Error Codes
  • DMO GUIDs
  • Parameter Capabilities Flags
  • Time Format GUIDs


DMO Error Codes

The following table contains error codes that are specific to Microsoft DirectX Media Objects (DMOs). These error codes are defined in the header file Mediaerr.h.

Return code | Description | Hexadecimal value
DMO_E_INVALIDSTREAMINDEX | Invalid stream index. | 0x80040201
DMO_E_INVALIDTYPE | Invalid media type. | 0x80040202
DMO_E_TYPE_NOT_SET | Media type was not set. One or more streams require a media type before this operation can be performed. | 0x80040203
DMO_E_NOTACCEPTING | Data cannot be accepted on this stream. You might need to process more output data; see IMediaObject::ProcessInput. | 0x80040204
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted. | 0x80040205
DMO_E_NO_MORE_ITEMS | Media-type index is out of range. | 0x80040206

See Also

  • DMO Constants


DMO GUIDs

The following table lists the globally unique identifiers (GUIDs) defined for Microsoft DirectX Media Object (DMO) categories. These GUIDs are defined in the header file Dmoreg.h and exported by the Dmoguids.lib library.

To enumerate the DMOs registered in a category, pass the corresponding GUID to the DMOEnum function.

GUID | Description
DMOCATEGORY_AUDIO_DECODER | Audio decoder
DMOCATEGORY_AUDIO_EFFECT | Audio effect
DMOCATEGORY_AUDIO_ENCODER | Audio encoder
DMOCATEGORY_VIDEO_DECODER | Video decoder
DMOCATEGORY_VIDEO_EFFECT | Video effect
DMOCATEGORY_VIDEO_ENCODER | Video encoder
DMOCATEGORY_AUDIO_CAPTURE_EFFECT | Audio capture effect

See Also

  • DMO Constants


Parameter Capabilities Flags

These flags specify which envelope curves are supported by a media parameter.

Constant | Description
MP_CAPS_CURVE_INVSQUARE | Inverse square curve.
MP_CAPS_CURVE_JUMP | Jump to the next point without interpolation.
MP_CAPS_CURVE_LINEAR | Linear interpolation.
MP_CAPS_CURVE_SINE | Sine curve.
MP_CAPS_CURVE_SQUARE | Parabolic curve.

See Also

  • DMO Constants


Time Format GUIDs

The following table lists the globally unique identifiers (GUIDs) defined for media parameter time formats.

GUID | Description
GUID_TIME_MUSIC | Music time, in parts per quarter note.
GUID_TIME_REFERENCE | Reference time, in 100-nanosecond units.
GUID_TIME_SAMPLES | Samples per second.

See Also

  • DMO Constants


IMediaObjectImpl Class Template

The IMediaObjectImpl class template provides a base implementation for the IMediaObject interface. For more information on using this template, see Using the DMO Class Template.

This IMediaObjectImpl template exposes the following members.

Nested Class | Description
LockIt | Helper class that locks and unlocks the DMO.

Method | Description
CheckTypesSet | Determines whether all of the non-optional streams have media types.
InputType | Retrieves the current media type for a specified input stream.
InputTypeSet | Queries whether the media type was set on an input stream.
InternalAcceptingInput | Queries whether an input stream can accept more input.
InternalCheckInputType | Queries whether an input stream can accept a given media type.
InternalCheckOutputType | Queries whether an output stream can accept a given media type.
Lock | Locks the DMO
OutputType | Retrieves the current media type for a specified output stream.
OutputTypeSet | Queries whether the media type was set on an output stream.
Unlock | Unlocks the DMO

Requirements

Include Dmoimpl.h

See Also

  • Using the DMO Class Template


IMediaObjectImpl::LockIt Class

The LockIt class is an internal class that locks and unlocks the DMO.

Syntax

LockIt(
    _DERIVED_ *p
);

Parameters

p

Pointer to the derived object.

Remarks

The LockIt constructor locks the DMO, and the destructor unlocks the DMO. To lock the object from inside your derived class, declare a local variable of type LockIt. The DMO is locked while the LockIt object remains in scope:

void SomeMethod()
{
    // The DMO is not locked.
    {
        LockIt dmoLock(this); // Locks the DMO.
        /* ... */
    }
    // dmoLock goes out of scope, DMO is unlocked.
}

The methods in IMediaObjectImpl automatically lock the DMO.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::CheckTypesSet

The CheckTypesSet determines whether the media type has been set on all of the streams.

Syntax

bool CheckTypesSet(void);

Return Value

Returns TRUE if the media type has been set on all of the non-optional streams. Otherwise, returns FALSE.

Remarks

Call this method after any operation that changes the media type on a stream. This method sets a private flag within the class. Some IMediaObjectImpl methods test this flag to determine whether certain operations are permitted. These methods generally return DMO_E_TYPE_NOT_SET if the flag is FALSE.

The only two methods in IMediaObject that change the media type on a stream are SetInputType and SetOutputType. The class template implements both of these methods.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::InputType

The InputType method retrieves the current media type for a specified input stream.

Syntax

const DMO_MEDIA_TYPE *InputType(
    DWORD ulInputStreamIndex
);

Parameters

ulInputStreamIndex

Index of an input stream.

Return Value

Returns a pointer to a DMO_MEDIA_TYPE structure, or NULL if the media type is not set for this stream.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::InputTypeSet

The InputTypeSet method queries whether the media type was set on an input stream.

Syntax

bool InputTypeSet(
    DWORD ulInputStreamIndex
);

Parameters

ulInputStreamIndex

Index of an input stream.

Return Value

Returns TRUE if the media type was set on this stream, or FALSE otherwise.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::InternalAcceptingInput

The InternalAcceptingInput method queries whether an input stream can accept more input. The derived class must declare and implement this method.

Syntax

HRESULT InternalAcceptingInput(
    DWORD dwInputStreamIndex
);

Parameters

dwInputStreamIndex

Index of an input stream.

Return Value

Returns S_OK if the input stream can accept input, or S_FALSE otherwise.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::InternalCheckInputType

The InternalCheckInputType method queries whether an input stream can accept a given media type. The derived class must declare and implement this method.

Syntax

HRESULT InternalCheckInputType(
    DWORD dwInputStreamIndex,
    const DMO_MEDIA_TYPE *pmt
);

Parameters

dwInputStreamIndex

Index of an input stream.

pmt

Pointer to a DMO_MEDIA_TYPE structure that describes the media type.

Return Value

Returns S_OK if the media type is valid, or DMO_E_INVALIDTYPE otherwise.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::InternalCheckOutputType

The InternalCheckOutputType method queries whether an output stream can accept a given media type. The derived class must declare and implement this method.

Syntax

HRESULT InternalCheckOutputType(
    DWORD dwOutputStreamIndex,
    const DMO_MEDIA_TYPE *pmt
);

Parameters

dwOutputStreamIndex

Index of an output stream.

pmt

Pointer to a DMO_MEDIA_TYPE structure that describes the media type.

Return Value

Returns S_OK if the media type is valid, or DMO_E_INVALIDTYPE otherwise.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::Lock

The Lock method locks the DMO, using a critical section. The derived class must declare and implement this method.

Syntax

void Lock(void);

Remarks

If you implement the derived class using the Active Template Library (ATL), you can use ATL's default implementation of this method.


IMediaObjectImpl::OutputType

The OutputType method retrieves the current media type for a specified output stream.

Syntax

const DMO_MEDIA_TYPE *OutputType(
    DWORD ulOutputStreamIndex
);

Parameters

ulOutputStreamIndex

Index of an output stream.

Return Value

Returns a pointer to a DMO_MEDIA_TYPE structure, or NULL if the type is not set for this stream.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::OutputTypeSet

The OutputType method queries whether the media type was set on an output stream.

Syntax

bool OutputTypeSet(
    DWORD ulOutputStreamIndex
);

Parameters

ulOutputStreamIndex

Index of an output stream.

Return Value

Returns TRUE if the media type was set on this stream, or FALSE otherwise.

See Also

  • IMediaObjectImpl Class Template


IMediaObjectImpl::Unlock

The Unlock method unlocks the DMO. The derived class must declare and implement this method.

Syntax

void Unlock(void);

Remarks

If you implement your derived class using the Active Template Library (ATL), you can use ATL's default implementation of this method.

See Also

  • IMediaObjectImpl Class Template


DirectX Glossary

A | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
alpha | In computer graphics, the measure of a pixel's opacity. A pixel with the maximum alpha value is opaque, one with a value of zero is transparent, and one with an intermediate value is translucent.
alpha blend | Method for combining two images that uses both pixel colors and alpha values to determine the color of the resulting pixel. This allows an image to be rendered on top of another image, with a blend of both images showing. When blending two pixels, the color components of both pixels are first scaled by their alpha values. Then, the bottom pixel is scaled by the inverse of the top pixel alpha value and added to the top pixel to form the final blended color.
alpha channel | Opacity of an image defined by an alpha value per pixel, interleaved with the color components (for example, ARGB), an alpha value per pixel stored in a separate alpha surface, or a constant alpha value for the entire surface.
alpha color component | Portion of a 32-bit color that determines its opacity. In this case, the alpha value per pixel is interleaved with the color components (for example, ARGB). Less commonly, this term refers to an image with an alpha value per pixel stored in a separate alpha surface.
alpha constant | Level of opacity (alpha value) applied to an entire surface.
alpha edge blend | Particular use of alpha blending (and alpha channel information) to reduce aliasing by blending edges, based on pixel coverage information.
ambient | Description of a light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because it illuminates a scene with equal strength everywhere, the position and orientation of the frame that an ambient light source is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
anisotropic filtering | Mipmap filtering mode that compensates for anisotropic distortion.
anisotropy | Distortion visible in the image of a 3-D object whose surface is oriented at an angle with respect to the viewing plane. The anisotropy is measured as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.
ARGB | Alpha (opacity), red, green, and blue components of a pixel. Each color is represented in memory by data in BGRA order.
array object | Group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The Component Object Model (COM) interfaces that enable you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.
articulation | A series of adjustments applied by a synthesizer to the pitch, volume, and other parameters of an instrument sound to make it more realistic.
ASP.NET HTML controls | HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render.
attach | To connect multiple DirectDrawSurface objects into complex structures, such as those needed to support 3-D page flipping with z-buffers. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to non-emulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size.
attached | Physically connected to the system. A device may be installed but not currently attached.
attack | Period at the beginning of a force-feedback effect when the magnitude is reaching its basic or sustain level.
B | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
back buffer | Nonvisible surface to which bitmaps and other images can be drawn while the front buffer displays the currently visible image.
back clipping plane | Far boundary of a viewing frustum beyond which objects are not rendered. See also "front clipping plane."
bank select | A MIDI controller that enables instruments to be chosen from different groups or banks, each identified by a 2-byte code.
billboard | Primitive inserted into a 3-D scene that is oriented so that one face is toward the viewer. A texture, usually an animated sprite, is applied to the billboard to give the appearance of a 3-D object in the scene.
billboarding | 2-D technique of simulating the appearance of a 3-D object in a scene. An application inserts a primitive, typically rectangular, into the scene, orients it so that one face is toward the viewer, and applies a texture or a set of textures. The texture or set of textures gives the appearance of an animated 3-D object.
bit block transfer (bitblt or blit) | A graphics function that moves blocks of bits from one bitmap to another in the most efficient manner supported by the hardware.
bitblt | Bit block transfer (bitblt). A graphics function that moves blocks of bits from one bitmap to another in the most efficient manner supported by the hardware.
blend factor | Description of how each color component is blended in texture blending.
blend mode | Algorithm used to determine how a texture is blended with the colors of the surface to which the texture is applied.
blending stage | One step in a texture cascade. A blending stage includes one texture and a set of texture-blending operations that are used when blending multiple textures.
blit | Bit block transfer. Sometimes called bitblt.
bob | A technique for displaying interlaced video. In bob mode, each field is displayed individually. The gaps between scan lines are filled using interpolation.
bounds checking | Process of checking that an on-screen image is displayed within the bounds of the screen.
bump mapping | Technique for simulating the appearance of rough surfaces in 3-D scenes. Variations in depth are stored in a texture and applied to a primitive, using standard texture-blending techniques.
C | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
camera | Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction in the direction of the positive y-axis.
camera space | Frame of reference in which the viewer is at the origin, looking in the direction of the positive z-axis. Objects are transformed from world space to camera space by using the view transformation.
chordmap | A scheme of chord progressions, arranged in a flowchart along a time line.
client/server session | Microsoft® DirectPlay® session in which only the server stores the session's complete state, and each client has only a subset of the session's state. Each client receives only the information that is relevant to that computer from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change. See also "peer-to-peer session."
clip list | Series of rectangles that describes the visible areas of the surface. The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object.
clipper | DirectDrawClipper object.
codec | An abbreviation for compressor/decompressor. Software or hardware used to compress and decompress digital media.
collision detection | Process for determining if any pixels for two images share the same location on the screen. See also "hit detection."
color key | A color value used for pixel selection that enables transparent or translucent effects. When using a hardware blitter in graphics, for example, all the pixels of a rectangular area are blitted, except the value that was set as the color key. This creates nonrectangular sprites on a surface. In Microsoft DirectShow®, an overlay surface is displayed in the region of the primary surface that contains the color key. In video production, color keys are used to combine two video signals. Also called a chroma key.
color space | Model for representing color as three or more coordinates. Color-space models map color components onto a Cartesian coordinate system in three or more dimensions. A color space may use any of several types of color encoding and visualizing. The two most common types of color space models are RGB and YUV.
color table | Array of n color values (normally RGB triples).
color-space conversion | Technique for converting a color in one color space to another color space. Typically, this conversion is from YUV colors from a video source to RGB for display.
complex surface | Collective term for several DirectDrawSurface objects, all of which are attached to a root surface. The complex-surface structure can be destroyed only by destroying the root.
composition | A collection of tracks and (optionally) other compositions. At rendering time, the sources in a composition are composited into a single image.
control segment | Musical segment that controls certain aspects of playback. Normally it is the primary segment, but a secondary segment can be designated as the control segment.
culling | Removing a face from the list of faces to render. Faces can be culled using a number of techniques including: back face, view frustum, and occlusion culling.
curve | In Microsoft DirectMusic®, a continuous series of events with a start and end value, such as volume fade.
D | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
dark light | Light source that removes illumination from a scene Dark light is created by specifying negative values for the colors of the light.
DCI | Display Control Interface. Defined by the Intel and Microsoft corporations, DCI is an interface that offers improved graphics performance as a result of direct video memory access.
dead zone | Area within the physical range of an axis where the axis is considered to be at the center.
deadband | Zone around the offset of a force-feedback axis at which a condition is not active.
decal | Texture that is rendered directly, as a visual. Decals are rendered into a viewport-aligned rectangle.
deinterlace | To combine the interlaced fields in a video frame so that, during playback, the lines of the video frame are painted sequentially.
delta frame | A video frame that contains only the changes from the previous frame. In contrast, a key frame contains all the data necessary to construct that frame.
destination color key | Color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface.
device window | Visible application window that Microsoft DirectDraw® uses for display. Applications can have a device window for each display device attached to a given computer. See also "focus window."
DIB sequence | In DirectShow Editing Services, a series of device-independent bitmap (DIB) files rendered in a sequence as video frames.
directional | Description of a light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.
DirectPlay address | Data format that DirectPlay uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. A DirectPlay address is a sequence of variable-length data chunks tagged with a globally unique identifier (GUID) that supplies all the address information needed by DirectPlay. Examples of address information are: the network address of a server, the network address of a player, the e-mail name of a player, and the network address of a session.
DirectX Media Object (DMO) | A COM object that processes multimedia data streams from buffers allocated by the client.
dither | Method to display a range of colors with a limited palette. Each pixel on the source image is represented by multiple pixels (usually a 2x2 square) on the destination image. From a distance, the eye blends the multiple pixels into one color that has more shades than the original palette. The technique results in a better visual appearance than the removal of low precision bits. See a standard graphics reference for details. Dithering is a supported option by DXSurface and Microsoft DirectX® Transform objects.
DLS | Downloadable sounds. A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
DMO | DirectX Media Object. A COM object that processes multimedia data streams from buffers allocated by the client.
downloadable sounds (DLS) | A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
downsample | To reduce the sampling rate of a signal.
downstream | In a filter graph, the direction in which digital media samples travel.
E | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
emissive property | Material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also "specular property."
emissive setting | See "emissive property."
enable frame | Frame to which a light applies.
envelope | In force feedback, a set of values that defines the shape of an effect by modifying the magnitude at the beginning (attack) and end (fade). In audio, a set of values that defines the shape of the amplitude or pitch of a sound. Downloadable sounds (DLS) level 1 defines a four-segment envelope: attack, decay, sustain, and release (ADSR). DLS level 2 defines six segments: delay, attack, hold, decay, sustain, and release (DAHDSR).
even field | Second field, comprising a video frame in an odd/even field set. Also known as field 2.
execute buffer | Fully self-contained, independent packet of information that describes a 3-D scene. An execute buffer contains a vertex list followed by an instruction stream. The instruction stream consists of operation codes, and the data that is operated on by those codes.
F | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
face | Single polygon in a mesh.
fade | Period between the central, or sustain, portion of a force-feedback effect and its end.
falloff | Light attenuation between a spotlight's inner and outer cones.
field | A portion of an interlaced video frame. With interlaced video, the scan lines of even-numbered fields fall spatially halfway between the scan lines of odd-numbered fields.
field polarity | Quality determining whether a field is an even field or an odd field. In odd fields, the trailing edge of the vertical refresh (VREF) does not occur during a scan line. In even fields, the trailing edge of the VREF occurs during a scan line.
flimmering | Shimmering appearance on 3-D primitives that results from a poor separation of z-values when doing decaling. Some pixels from the back texture are rendered onto the front texture and vice versa.
flip | Process of swapping the addresses associated with the back and front buffer. This effectively swaps the image in the back buffer to the front buffer, thus displaying the image.
flipping chain | Series of surfaces attached to each other that can be flipped. See also "flip."
flipping surface | Any piece of memory that can be flipped. See also "flip."
focus window | Application window, visible or not visible, that DirectDraw uses to hook window messages. The focus window's message handler receives input messages forwarded by DirectDraw. Applications can have only one focus window. See also "device window."
frame | Invisible box that provides a frame of reference for objects in a scene. Objects can be placed in a scene by specifying their spatial relationship to a relevant reference frame. Visual objects take their positions and orientations from frames. In a movie or animation, a single image.
front buffer | Rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
front clipping plane | Near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also "clipping plane."
G | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
gamma | The curve in the function that maps changes in voltage to changes in brightness on a phosphor screen. The change in voltage needed to produce a specified change in brightness is not constant across voltage levels.
genlocking | Process of synchronizing one video signal with another. Because they are synchronized, the genlocked signal can be mixed with the original signal, enabling dissolves, wipes, and other transition effects.
grid | Subdivision of a beat. The number of grids per beat is part of the DirectMusic time signature.
groove level | A value given to music during style playback. The groove level determines which patterns can be selected at any given time. The author assigns a range of groove levels to each pattern.
group | In DirectPlay, a logical collection of players. DirectPlay supports groups within a session. By creating a group of players, an application can send a single message to the group, and all players in the group receive the message. A group is the means by which a network's multicast capabilities are exposed to the application. Groups can be used to organize players in a session. A player can belong to more than one group. DirectPlay provides methods for administering groups and their membership. In DirectShow, a top-level collection of compositions and tracks, all representing the same multimedia type. Each group produces a separate stream in the rendered project.
H | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
HAL | The hardware abstraction layer (HAL) consists of hardware and device driver mechanisms that insulate applications from device-specific implementation details. If a capability requested by an application is not implemented by the current hardware, the capability is emulated by the software.
hardware blitter | Hardware component, built into the display adapter, that performs efficient blit operations.
HEL | Hardware emulation layer. The HEL provides software-based emulation of features that are not present in hardware.
HID | Human Interface Device. A universal serial bus (USB) class representing devices that enable a human to control a computer.
hit detection | See "collision detection."
host | In DirectPlay, a virtual player whose identifier (ID) is DPID_SYSMSG. The host manages system messages and messages sent to all players in a session.
host byte order | On an Intel x86 computer, the byte order for the system, or host, is little endian. Network byte order is always big endian.
HREF | In a video stream, the horizontal refresh (HREF) is active to signal that the display is to begin a new scan line. See also "VREF."
HRTF | Head-related transfer function. A mathematical representation of the effect of the listener's physiology on the pitch and timing of sounds arriving from different directions.
I | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
index palette | DirectDrawPalette object whose entries are indexes into another palette object.
intelligent connect | An algorithm used by the filter graph manager to build graphs and connect filters. If an output pin is specified, the filter graph manager renders the data from that pin by using default renderers. If two filters are specified, the filter graph manager attempts to connect them. It will insert intermediate filters if necessary.
interlace | To display a video frame in two fields. One field contains the even lines of the frame, the other field contains the odd lines. During playback, the lines in one field are displayed first, then the lines in the second field are displayed.
interleaving | The arrangement of video frames and audio samples in a file, such that video data alternates with audio data at regular intervals.
IPX service provider | Service provider that uses Windows Sockets to communicate over a local area network (LAN) using the Internetwork Packet Exchange (IPX) protocol. The service provider supports only non-guaranteed messaging. A single computer can host only one DirectPlay session using IPX.
IRE scale | International Radio Engineers scale. A scale of values ranging from 0 to 100 that defines the brightness level of a broadcast video signal. The spectrum of low-to-high IRE values describes increasing brightness levels of a video signal. At 7.5 IRE brightness, the black cut-off threshold for a National Television System Committee (NTSC) signal, the electron guns of an NTSC display device are cut off and do not display images.
K | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
kernel mode | The operational state of a processor that enables full, unprotected access to a system. A driver or thread running in kernel mode has access to system memory and hardware.
key frame | A video frame containing all the data needed to construct an image without reference to previous frames.
L | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
latency | A delay in response. For example, in Microsoft DirectSound®, it is the interval between the time at which a sound buffer plays and the time that the speakers actually reproduce the sound. In DirectPlay, it is the time that it takes for a packet to reach a specified destination. In DirectShow, it is the amount of time it takes a filter to process a sample.
LED | Light-emitting diode.
letterbox | A video display format in which black bars appear above and below the video image while it is played. The letterbox format maintains the original aspect ratio of an image when it is displayed in a window with a different aspect ratio.
light map | Texture or group of textures that contain lighting information for a 3-D scene.
lobby client | Lobby management routines associated with the user's computer, including launching applications, updating the user interface, and communicating with the lobby server.
lobby provider | Client component (dynamic-link library) supplied by the developer of a lobby server. It implements communication functions with the lobby server, as requested by DirectPlay.
lobby server | Lobby management routines associated with a remote server. The lobby server coordinates all the information about the users who are connected to a specific application.
lobby session | Connection to a lobby server on which clients and the server have not been specifically written to interoperate.
lobby-aware application | Application that, at a minimum, supports being launched from a lobby.
locked audio | A video format in which the number of audio samples in a specified number of frames is fixed. In unlocked audio, the number of samples in a set of frames may vary, although the average equals the stated sample rate.
lookahead | To use data from later in the stream to process the current data. For example, the next key frame is used to calculate a delta frame.
M | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Mach bands | Bands of color that are not smoothly blended across a 3-D primitive.
material | Property that determines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting.
medium | Structure that identifies a hardware data path between two devices on the host system. They can be devices on the same card, such as a crossbar and a tuner on a TV card; devices on separate cards; or external devices. Kernel-mode filters based on the Windows Driver Model can use mediums instead of media types to determine pin connections.
mesh | Set of faces, each of which is described by a simple polygon.
mipmap | Also known as MIP map (Latin: multum in parvo, translated as "much in little"). A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer. As the object moves farther away (and gets smaller), lower-resolution images are used.
mix-in buffer | In DirectSound, a buffer that receives data from other DirectSound buffers rather than directly from the synthesizer.
mixing | In DirectSound, the process of combining sound buffers that are playing, and writing the result to the primary sound buffer, which supplies audio data to the sound hardware. There is no limit to the number of buffers that can be mixed, except the available processing time.
Mode X | Hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 KB of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.
model coordinates | Coordinates that are relative to a local origin. See also "model space" and "world coordinates."
model space | Frame of reference (used by model coordinates) that uses vertices relative to a single 3-D model's local origin.
motif | In DirectMusic, a type of pattern played explicitly by an application to mark an event.
multipass texture blending | Repeated rendering of a 3-D primitive while blending on a texture with each pass. This technique is widely used to achieve a variety of special effects.
multiplexer (MUX) | A filter that combines multiple input streams into one output stream.
music value | In DirectMusic, a note in a pattern within a style whose pitch is defined only when it is transposed to the current chord according to the current play mode and subchord level.
MUX | Multiplexer.
N | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
nagling | Algorithm that causes the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider to buffer small data packets into larger ones before sending. Nagling prevents a TCP/IP protocol server from transmitting many very small packets by requiring the server to wait either until it has accumulated enough small data packets to combine them into a single large packet or until it has received an acknowledgment of the prior packet. Nagling can reduce message overhead (and decrease required bandwidth), but also causes a delay before small data packets are sent (increasing latency).
National Television Standards Committee (NTSC) | The dominant television standard in the United States and Japan. NTSC delivers 30 interlaced frames per second at 525 lines of resolution.
nonregistered parameter number (NRPN) | An identifier for a device-specific parameter that can be accessed through a MIDI controller. Nonregistered parameters can be used for different functions by different manufacturers.
normal vector | Imaginary ray extending perpendicularly from a surface that defines the face's orientation.
NRPN | Nonregistered parameter number.
NTSC | National Television Standards Committee.
O | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
odd field | First field comprising a video frame in an odd/even field set.
off-screen surface | Conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to a back buffer before being displayed. Commonly used to store sprites.
opcode | Operation code that defines how to interpret the vertices in an execute buffer or how to change the state of the system.
overdraw | Average number of times that a screen pixel is written to.
overlay surface | Conceptually rectangular area in memory whose stored image information covers the image information of the primary surface to which it is applied. Overlays are assumed to be on top of all other screen components.
overlay z-order | Determines the order in which overlays clip each other, enabling a hardware sprite system to be implemented under DirectDraw.
P | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
page flipping | See "flip."
PAL | Phase Alternate Line.
palette | Set of colors used by an object or application. In DirectX, a DirectDrawPalette object.
palette index | Integer index into the palette table array that is used to select a particular color.
palettized surface | Collection of numbers where each number represents a pixel. Also called a color-indexed surface. Also, a DirectDrawSurface object that uses an attached palette to contain color information.
pan scan | A digital video disc (DVD) display format in which a 16x9 video is cropped for display in a 4x3 window, by using parameters defined by the video author.
pan value | Relative volume, measured in hundredths of decibels, between the left and right audio channels.
parallel point | Description of a light source that illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source.
pattern | In DirectMusic, a musical figure, one or more measures long, consisting of a basic sequence of music values for each instrument part.
PChannel | Performance channel.
PCM | Pulse code modulation.
peer-to-peer session | DirectPlay session in which the session's complete state is replicated on all the computers in the session. The session description data (the list of players and groups and the names and remote data associated with each session) are duplicated on every computer. When one computer changes something, it is immediately propagated to all the other computers. This is the default mode of communication for DirectPlay. See also "client/server session."
performance | In DirectMusic, an object that manages the flow of data from the source to the synthesizer, and controls global values, such as timing, tempo, and master volume.
performance channel (PChannel) | A MIDI channel in a particular channel group on a particular port. In DirectMusic, a set of parameters used to play one or more parts in a segment. Each performance channel has its own instrument, pan, volume, and transposition settings, and belongs to a single audiopath.
perspective correction | Technique of applying a texture map to a polygon that is angled away from the camera, interpolating so that the texture is stretched onto the polygon appropriately for the apparent depth of the polygon. Microsoft Direct3D® supplies perspective correction automatically.
phase alternate line (PAL) | The dominant television standard in Europe and China. PAL delivers 25 interlaced frames per second at 625 lines of resolution.
pick | To search for visuals in a scene, given a 2-D coordinate in a viewport.
PID | Physical interface device. A universal serial bus (USB) class that enables humans to feel force feedback from a computer.
pitch | Distance, in bytes, between an address that represents the beginning of a bitmap line and the beginning of the next line. Do not confuse memory pitch and memory width because not all display memory is laid out as one linear block. For example, with rectangular memory, the pitch of the display memory could include the width of the bitmap plus part of a cache. See also "width" and "stride."
player | Single participant in a DirectPlay session. Each player is associated with a player ID that enables messages to be exchanged among players.
player ID | Unique number that is assigned to each participant in a DirectPlay session when the participant is created. The application can exchange messages among players by using player IDs. The host is always assigned the DPID_SYSMSG player ID.
PNG | Portable Network Graphics. A nonproprietary bitmap format using lossless compression.
point light | Light source that radiates equally in all directions from its origin.
point list | Simplest 3-D primitive. A collection of unconnected points in 3-D space.
power | In the specular property of a material, value that determines the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.
preroll | To capture or play a number of video frames or a portion of audio data before encoding or rendering begins, in order to allow the source device to stabilize. Also used as a noun to describe the portion of the data to be prerolled.
primary buffer | A sound buffer in which all data is mixed for the final time and then passed to the rendering device.
primary surface | Memory containing the image being displayed on the screen.
projection space | Frame of reference containing vertices after they are modified from their world space locations by the projection transformation. Projection space is a homogeneous cuboid space in which all vertices in a scene have x-coordinates and y-coordinates that range from -1.0 to 1.0, and a z-coordinate that ranges from 0.0 to 1.0. Projection space is sometimes referred to as post-perspective homogeneous space.
projection transformation | Application of a matrix to vertices to change them from camera space to projection space.
pulse code modulation (PCM) | A technique for digitizing audio into an uncompressed format by assigning a value to the amplitude of the signal at fixed intervals.
Q | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
quality control | Mechanism for adjusting the rate of data flow in response to run-time conditions.
quaternion | Fourth element added to the [x, y, z] values that define a vector. Quaternions define a 3-D axis and a rotation around that axis.
R | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
reference clock | A clock that provides a common reference time with which filters can be synchronized.
reference count | Control for a COM object. When an object is created, its reference count is set to 1. Every time an interface is bound to the object, its reference count is incremented; when the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All interfaces to that object are then invalid.
reference time | An absolute time established by a reference clock in the filter graph.
region | In downloadable sounds (DLS), range of notes for which a particular digital sample is used in synthesizing an instrument's timbre.
registered parameter number (RPN) | An identification number for a registered parameter that has been assigned a function by the MIDI Manufacturers Association and can be accessed through controllers.
RGBA | Red, green, blue, and alpha (opacity) components of a pixel. Each color is represented in memory by data in ABGR order.
RHW | Transformed vertices in homogeneous space. The (x,y,z) data has already been divided by w (multiplied by the reciprocal of w).
rolloff | The attenuation of sound over distance.
root frame | Frame in Direct3D that has no parent frame; it is at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene. See also "scene."
RPN | Registered parameter number.
S | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
saturation | In input and force feedback, adjustment to an axis range so that minimum or maximum values are retrieved or set before the physical extremities are reached. If the maximum value in a range is 1,000 and the maximum saturation point is set to 900, the maximum value is reached after 90 percent of the travel in that direction.
scene | Entire set of objects that make up a virtual environment, including visible objects, sounds, lights, and frames. In Direct3D, the entire set of objects is contained in a root frame.
screen space | Frame of reference that relates 2-D coordinates to locations in the frame buffer. Screen space coordinates typically display on a monitor. The origin, or (0,0) is defined at the upper left corner. Y increases in the downward direction; X increases to the right. You use a viewport transformation matrix to convert points from projection space to screen space.
script | In DirectMusic, a file containing variables and routines that can be accessed from within an application.
secondary sound buffer | Object that manages a single sound or audio stream and plays it to the primary sound buffer.
segment state | An object created each time a segment is played. It is used to get information about the state of playback and the audiopath for that instance of the segment being played.
send | A sound effect for a buffer that is applied by sending the sound data to a second buffer.
service provider | Dynamic-link library used by DirectPlay to communicate over a network. The service provider contains all the network-specific code required to send and receive messages. Online services and network operators can supply service providers to use specialized hardware, protocols, communications media, and network resources.
session | In DirectPlay, instance of several applications on remote computers communicating with each other. Before an application can start communicating with other computers, it must be part of a session. An application can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.
sink | An object that manages the distribution of data from the synthesizer through buses to DirectSound buffers.
sink-in buffer | A DirectSound buffer that receives data directly from the synthesizer rather than from other DirectSound buffers.
smart recompression | In DirectShow Editing Services, the decompression and recompression of source data only when the data must be altered in some way before being written to the destination file.
sound buffer | Object that manages DirectSound audio data.
source color key | Color that (in the case of blitting) is not copied to or (in the case of overlays) not visible on the destination.
specular property | Material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also "emissive property."
spotlight | Light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section that acts as a point source, and a surrounding dimly lit section that merges with the surrounding deep shadow.
sRGB | Color space defined by Microsoft.
static buffer | A secondary sound buffer that contains an entire sound. Typically it is filled with data only once. See also "streaming buffer."
sticky focus | In DirectSound, ability to play sound buffers when the owning application does not have the input focus. For example, a DirectSound application could continue to play a sound buffer while the user is working in another application.
stream time | The current time minus the previous start time. Stream time is defined only in a running filter graph.
streaming buffer | A secondary sound buffer that contains only part of a sound. Its data must be refreshed as it is playing. See also "static buffer."
stretching | Blitting an image into a destination with different dimensions. This operation is supported directly by some hardware.
stride | Synonymous with pitch. See also "width."
style | In DirectMusic, a collection of musical patterns and other data that can be used to create a dynamic score. A style defines a basic melody and rhythm with variations, motifs, and embellishments, contains a time signature and a tempo, and can contain one or more bands.
subtype | A GUID value that describes the specific format of data digital media stream.
surface | Memory that represents visual images. This is often display memory but it can also be system memory. See also "complex surface," "off-screen surface," "overlay surface," and "primary surface."
sustain | Period during which the basic magnitude of a force-feedback effect is attained, after the attack and before the fade.
swap chain | A collection of one or more back buffers that can be serially presented to the front buffer.
synchronization point | A media sample that can be decoded without requiring the decompressor to examine any other samples. One example is a key frame.
system message | In DirectPlay, message from the player ID DPID_SYSMSG. All system messages begin with a DWORD value.
T | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
TCP/IP | Transmission Control Protocol/Internet Protocol. A protocol developed by the Department of Defense for communications between computers. It is built into the UNIX system and has become the standard for data transmission over networks, including the Internet.
TCP/IP service provider | Service provider that uses Microsoft Windows® Sockets to communicate over the Internet or LAN, using the TCP/IP protocol. The User Datagram Protocol (UDP) TCP/IP service provider uses DirectPlay packets for nonguaranteed and guaranteed messaging. Using TCP/IP protocol, a single computer can host multiple DirectPlay sessions.
tearing | A visual artifact that occurs when one displayed video frame contains parts of two different source video frames. It is usually caused by improper synchronization between video rendering and the graphics display.
template | In DirectMusic, a segment that can be used in combination with a chordmap to compose a new segment at run time.
tessellating | Breaking an image into small square regions for processing or output.
texel | Single element in a texture. When a texture has been applied to an object, the texels rarely correspond to pixels on the screen. Applications can use texture filtering to control how the system interpolates between texels to create pixels in a scene.
texture | Rectangular array of pixels that is applied to a visual object in Direct3D.
texture blending | Technique of combining the colors of a texture with the colors of the surface to which the texture is applied.
texture coordinates | Coordinates that determine which texel in each texture is assigned to each vertex in an object.
texture filtering | Process of mapping texel colors from one or more textures onto the pixels that comprise the image of a 3-D primitive.
texture mapping | Application of a texture to an object. Because a texture is a flat image and the object is often not, the texture must be mapped to the surface of the object, using texture coordinates and wrapping flags. See also "texture coordinates" and "wrap."
texture stage | Contains a texture and operations that can be performed on the texture. As used in DirectX, a texture stage takes two arguments and performs a blending operation on them.
thrashing | Removing textures used in the current frame to reclaim texture memory for subsequent frames.
throttling | Restricting the number of messages to avoid sending them faster than the underlying transport can deliver them.
time code | A digital signal applied to a stream. The signal assigns a number to every frame of video, representing hours, minutes, seconds, and frames.
time stamp | The time on a media sample indicating when it was recorded or when it should be scheduled for playback.
timeline | In a DirectShow Editing Services video-editing project, the root node that contains all the other objects.
track | In DirectShow, a collection of nonoverlapping sources with a common media type (audio or video).
transform filter | A filter that receives data from an upstream filter, processes it, and then delivers it to the next filter in the graph.
trans-in-place filter | A filter that can modify data without copying it to a new buffer.
transport | A mechanism for moving data from one point to another. In a filter, the transport moves media samples across pins. In an external device such as a digital video (DV) camcorder, the transport channels data from the device to a computer, or from the computer to the device.
U | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
unit vector | Vector with a magnitude (length) of 1.0.
Universal Serial Bus (USB) | A serial bus with a bandwidth of 1.5 megabits per second (Mbps) for connecting peripherals to a PC.
upsample | To increase the number of audio samples or pixels, through a process such as interpolation.
USB | Universal Serial Bus.
V | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
VBI | Vertical blanking interval.
velocity | In music, the speed at which a MIDI key is pressed. This is roughly equivalent to the dynamic level at which the note is played in some instrumental timbres. In 3-D sound, for purposes of calculating Doppler shift, velocity is the speed at which a sound source or listener is considered to be moving.
vertex | Point in 3-D space.
vertical blanking interval (VBI) | In broadcast video, small period of time that elapses between video frames during which a display device refreshes its display for the next frame.
vertical refresh (VREF) | In a video stream, the VREF is active to signal that the display is to begin a new screen. See also "HREF."
video frame | Single image in a video stream, comprised of one odd field and one even field. See also "field."
view space | See "camera space."
view state | Accumulation of all a control's property values.
view transformation | Application of a matrix to a model's vertices to change its orientation from world space to view space.
viewing frustum | 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cubic.
viewport | Rectangle that defines how a 3-D scene is rendered into a 2-D window. A viewport also defines an area on a device into which objects are rendered.
virtual device driver (VxD) | Software that manages a hardware or software system resource. These drivers are described using three letters, beginning with V and ending with D. The middle letter indicates the type of device, such as D for display, P for printer, T for timer, or x when the type of device is not under discussion.
virtual track | In DirectShow Editing Services, any object that can be contained in a composition.
VREF | Vertical refresh.
VxD | Virtual device driver.
W | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
WAV | A file format in which Windows stores sounds as waveforms. Such files have the extension .wav.
weave | A method to display interlaced video. In weave mode, alternating fields are combined into a single image.
width | Distance between two addresses in memory that represent the beginning of a line and the end of the line of a stored bitmap. This distance represents only the width of the bitmap in memory. It does not include any extra memory required to reach the beginning of the next line of the bitmap, such as a cache in rectangular memory.
world coordinates | Coordinates that are relative to the origin of a scene. See also "model coordinates" and "world space."
world space | Frame of reference used by world coordinates that declares vertices relative to a single origin within a 3-D scene.
world transformation | Application of a matrix to a model's vertices to change its orientation from model space to world space.
wrap | Procedure used to calculate texture coordinates for a face or mesh. The basic wrapping types are flat, cylindrical, spherical, and chrome.
Z | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
z-buffer | Buffer that stores a depth value for each pixel in a scene. Pixels with a small z-value overwrite pixels with a large z-value.
z-fighting | See "flimmering."

© 2002 Microsoft Corporation. All rights reserved.


dcl_usage (Pixel Shader)

Declare the association between a vertex shader outputs and pixel shader inputs.

Syntax

dcl_semantics [_centroid] dest[.write_mask]

Where:

  • _semantics: The same set of semantics as for the input declaration can be used. Semantic names come from the enum D3DDECLUSAGE (and are paired with an index, that is, position3). There always has to be one o register with _positiont0 declaration when not used for process vertices. The positiont0 semantic and the pointsize0 semantic are the only ones that have meaning to Microsoft® Direct3D®, beyond simply allowing linkage from vertex to pixel shaders. For shaders with flow control, it is assumed that the worst-case output is dcl'd. There are no defaults if a shader does not actually output what it declares it should (due to flow control).
  • [_centroid] is an optional instruction modifier. It is is supported on dcl_usage instructions that declare the input registers and on texture lookup instructions. The centroid is appended with no space. See Centroid.
  • dest: destination register. See Registers - ps_3_0.
  • write_mask: The same "out" register may be dcl'd multiple times (so different semantics can be applied to individual components), each time with a unique write mask. However, the same semantic cannot be used multiple times in a declaration. This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual "out" registers). When the _pointsize semantic is used, it should have a full write mask because it is considered a scalar. When the _position semantic is used, it should have full write mask because all four components have to be written.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage |  |  |  |  |  |  |  | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

ps_3_0

; declaring inputs
dcl_normal      v0.xyz
dcl_blendweight v0.w ; Must be same reg# as normal, matching vshader packing.
dcl_texcoord1   v1.y ; Mask can be any subset of mask from vshader semantic.
dcl_texcoord0   v1.zw; Has to be same reg# as texcoord1, to match vshader.

; declaring samplers
dcl_2d s0
dcl_2d s1

def c0, 0, 0, 0, 0

mov r0.x, v1.y ; texcoord1
mov r0.y, c0
texld r0, r0, s0

texld r1, v1.zw, s1
...
(output regs in ps_3_0 are same as ps_2_0: oC0-oC3, oDepth)
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


defb (Pixel Shader)

Defines a boolean constant value, which should be loaded any time a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a single boolean value, either true or false.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  |  |  |  |  | x | x | x | x

The defb instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetPixelShaderConstantB.

There are two ways to set a booleanconstant in a shader.

  1. Use defb to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.

Instruction Information

Minimum operating system Windows 98

Related Topics

  • def
  • defi

© 2002 Microsoft Corporation. All rights reserved.


defi (Pixel Shader)

Defines an integer constant value, which should be loaded any time a shader is set to a device.

Syntax

defi dst, integerValue
  • dst is the destination register.
  • integerValue is a constant integer value.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  |  |  |  |  |  |  | x | x

The defi instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetPixelShaderConstantB.

There are two ways to set a constant in a shader.

  1. Use defi to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantF to set a floating-point constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantI to set an integer constant.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


endloop (Pixel Shader)

End of a loop...endloop block.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  |  |  |  |  |  |  | x | x

This instruction works as shown here.

LoopCounter += LoopStep;
LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset

The endloop instruction offset must be greater than the loop instruction offset.

The code block defined between the loop and endloop instructions does not consume additional instruction slots beyond those required to define it.

© 2002 Microsoft Corporation. All rights reserved.


Exercise 2

Vertex Shader Diffuse Lighting. Light the model, taking both diffuse material and a diffuse light source into consideration.
//
// Effect File Workshop Solution for Exercise 2
// Copyright (c) 2001-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;	// Light direction from app
vector matD; 	// Object diffuse material color

matrix mWld;	// World
matrix mTot;	// Total

// Load model
string XFile = "f40.x";

// Background color
DWORD  BCLR = 0xff000000;

// No pixel shader
pixelshader pNIL;

// Technique names for display in viewer window
string tec0 = "Solution 2: Vertex Shader Diffuse Lighting";

/////////////////////////////////////////////////////////////////////////////
///////        Exercise 2: Vertex Shader Diffuse Lighting          //////////
///////     Light the model taking both diffuse material and       //////////
///////     diffuse light source into consideration.               //////////
/////////////////////////////////////////////////////////////////////////////
technique tec0
{
    pass p0
    {
        //Load matrices
        VertexShaderConstant[0] = ;                 // World Matrix
        VertexShaderConstant[4] = ;                 // World*View*Proj Matrix

        //Material properties of object
        VertexShaderConstant[9]  = ;    // Diffuse from object material diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);
                                                // Specular from constant color
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);
                                                // Ambient from constant color

        // Light Properties. lhtR is input from the shader app
        VertexShaderConstant[13] = (1.0f,0.9f,0.9f,1.0f);   // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);   // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f);   // Ambient
        VertexShaderConstant[16] = ;	                    // Light direction

        // Assign diffuse color to be used
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        // Only one color being used
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        // Definition of the vertex shader, declarations then assembly
        VertexShader =
        decl
        {
            stream 0;
            float v0[3];        // Position
            float v3[3];        // Normal
            float v7[3];        // Texture Coord1
            float v8[3];        // Texture coord2
        }
        asm
        {
            vs_1_1              // Version number

            m4x4 oPos, v0, c4   // Transform point to projection space

            dp3  r0,v3,-c16     // Dot product against untransformed light

            mul  r0,r0,c13      // Modulate against diffuse light color
            mul  r0,r0,c9       // Modulate against diffuse material

            mov oD0,r0          // Put into diffuse color output
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 3

Transforms. Transform the vertex normal into world space to take light source movement into consideration.
//
// Effect File Workshop Solution for Exercise 3
// Copyright (c) 2001-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;	// Light direction from app
vector matD; 	// Object diffuse material color

matrix mWld;	// World
matrix mTot;	// Total

// Load model
string XFile = "f40.x";

// Background Color
DWORD  BCLR = 0xff000000;

// No pixel shader
pixelshader pNIL;

// Technique names for display in viewer window
string tec0 = "Solution 3: Transforms";

/////////////////////////////////////////////////////////////////////////////
///////        Exercise 3: Transforms                              //////////
///////     Transform the vertex normal into world space to take   //////////
///////     light source movement into consideration.              //////////
/////////////////////////////////////////////////////////////////////////////
technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;                   // World Matrix
        VertexShaderConstant[4] = ;                   // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;    // Diffuse from object material diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);
                                               // Specular from constant color
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);
                                               // Ambient from constant color

        // Light Properties. lhtR is input from the shader app
        VertexShaderConstant[13] = (1.0f,0.9f,0.9f,1.0f);   // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);   // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f);   // Ambient
        VertexShaderConstant[16] = ;	                    // Light direction

        // Assign diffuse color to be used
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        // Only one color being used
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        // Definition of the vertex shader, declarations then assembly
        VertexShader =
        decl
        {
            stream 0;
            float v0[3];        // Position
            float v3[3];        // Normal
            float v7[3];        // Texture coord1
            float v8[3];        // Texture coord2
        }
        asm
        {
            vs_1_1              // Version number

            m4x4 oPos, v0, c4   // Transform point to projection space.

            mov  r0,v3          // Copy untransformed normal into r0.
            m3x3 r0,v3,c0       // Transform normal to world space, put result
                                //   into r0 so preceding mov not necessary.

            dp3  r0,r0,-c16     // Dot product against light, r0 now has
                                //   lighting constant in x,y and z
                                //   components (r,g,b).

            mul  r0,r0,c13      // Modulate against diffuse light color.
            mul  r0,r0,c9       // Modulate against diffuse material.

            mov oD0,r0          // Put into diffuse color output.
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 4

Texturing. Set up texture to pass onto FF PS Modulate between the texture and diffuse color arguments.
//
// Effect File Workshop Solution for Exercise 4
// Copyright (c) 2001-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction from app
vector matD;    // Object diffuse material color

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object

// Load model
string XFile = "bust.x";

// Background color
DWORD  BCLR = 0xff000000;

// No pixel shader
pixelshader pNIL;

// Technique names for display in viewer window
string tec0 = "Exercise 4: Texturing";

/////////////////////////////////////////////////////////////////////////////
///////        Exercise 4: Texturing                               //////////
///////     Set up texture to pass onto FF PS                      //////////
///////     Modulate between the texture and diffuse color args.   //////////
/////////////////////////////////////////////////////////////////////////////
technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;                   // World Matrix
        VertexShaderConstant[4] = ;                   // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;    // Diffuse from object material diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);
                                                // Specular from constant color
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);
                                                // Ambient from constant color

        // Light Properties. lhtR is input from the shader app
        VertexShaderConstant[13] = (0.8f,0.8f,0.8f,0.8f);   // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);   // Specular
        VertexShaderConstant[15] = (0.3f,0.3f,0.3f,1.0f);   // Ambient
        VertexShaderConstant[16] = ;	                // Light Direction

        // Useful constant(s)
        VertexShaderConstant[20] = (-1.0f, -1.0f, 0.5f, 1.0f);

        // Assign diffuse texture
        Texture[0]   = ;

        // Set up texture wrapping mode
        wrap0        = U | V;
        AddressU[0]  = Wrap;
        AddressV[0]  = Wrap;

        // Assign texture color to be used
        ColorArg1[0] = Texture;
        ColorOp[0]   = Modulate;      // Modulate between args
        ColorArg2[0] = Diffuse;       // Add diffuse component as arg

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        // Ensure remaining stages are disabled
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        // Definition of the vertex shader, declarations then assembly
        VertexShader =
        decl
        {
            stream 0;
            float v0[3];        // Position
            float v3[3];        // Normal
            float v7[3];        // Texture Coord1
            float v8[3];        // Texture coord2
        }
        asm
        {
            vs_1_1              // Version number

            m4x4 oPos, v0, c4   // Transform point to projection space
            m3x3 r0,v3,c0       // Transform normal to world space,
                                //   put result into r0.
            dp3  r0,r0,-c16     // Dot product against light, r0 now has lighting
                                //   constant in x,y and z components (r,g,b).

            mul  r0,r0,c13      // Modulate against diffuse light color
            mul  r0,r0,c9       // Modulate against diffuse material

            mov oD0,r0          // Output diffuse color

            //mov oT0,v7        // output texture coordinates
                                // - or -
            mov oT0.xy,v7.xy    // output only x and y channels for efficiency
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 5

Vertex Shader Specular Lighting.
//
// Effect File Workshop Exercise 5
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction

matrix mWld;    // World
matrix mTot;    // Total

vector matD;    // Material diffuse
vector matS;    // Material specular

vector vCPS;    // Camera position

// Background color
DWORD  BCLR = 0xFF000000;

pixelshader pNIL;

string XFile = "f40.x";

// Technique names for display in viewer window
string tec0 = "Exercise 5: Vertex Shader Specular Lighting";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;                 // World Matrix
        VertexShaderConstant[4] = ;                 // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = ;                      // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      // Light direction

        // Blending Constants
        VertexShaderConstant[20] = (0.7f,0.7f,0.7f,0.7f);
        VertexShaderConstant[21] = (0.3f,0.3f,0.3f,0.3f);

        // Camera Information.
        VertexShaderConstant[24] = ;

        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to world space

            add r0,-r0,c24     // Get a vector toward the camera position
                               // This is the negative of the camera direction

            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = -(camera vector)

            add r2.xyz,r0.xyz,-c16    // Get half angle

            // Normalize
            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r2 = HalfAngle

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            // r2 = half angle, r1 = normal, r3 (output) = intensity
            dp3  r3.xyzw,r1,r2

            // Now raise it several times
            mul r3,r3,r3    //  2nd
            mul r3,r3,r3    //  4th
            mul r3,r3,r3    //  8th
            mul r3,r3,r3    // 16th

            // Compute diffuse term
            dp3 r4,r1,-c16

            // Blend it in
            mul r3,c20,r3   // Kd
            mul r4,r4,c21   // Ks

            mul r4,r4,c10   // Specular
            mad r4,r3,c9,r4 // Diffuse

            mov oD0,r4      // Put into Diffuse Color
       };
    }
}

Exercise 5B

//
// Effect File Workshop Exercise 5B
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;	// Light Direction

matrix mWld;	// World
matrix mTot;	// Total

vector vCPS;    // Camera position

texture tEnv;   // Environment texture
texture tDif;

vector matD;    // Object Diffuse Material Color
vector matS;    // Object Specular Material Color

// Background color
DWORD  BCLR = 0xFF000000;

pixelshader pNIL;

//string XFile = "f40.x";
string XFile = "viper.x";

string BIMG  = "lobbyzneg.bmp";

// Technique names for display in viewer window
string tec0 = "Exercise 5b: Vertex Shader Specular Envmap";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ; 	// World matrix
        VertexShaderConstant[4] = ;	// World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;	                  // Light direction

        // Blending constants
        VertexShaderConstant[20] = (-2.0f,-2.0f,-2.0f,-2.0f);
        VertexShaderConstant[21] = ( 0.25f, 0.25f, 0.25f, 0.05f );
        VertexShaderConstant[22] = ( 0.75f, 0.75f, 0.75f, 0.95f );
        VertexShaderConstant[23] = ( 1.00f, 1.00f, 1.00f, 1.00f );

        // Camera information
        VertexShaderConstant[24] = ;

        ColorOp[0]   = Modulate;
        ColorArg2[0] = Diffuse;
        ColorArg1[0] = Texture;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        Texture[0]   = ;
        PixelShader  = ;

        AlphaBlendEnable = True;
        SrcBlend  = One;
        DestBlend = InvSrcAlpha;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to world space

            add r0,r0,-c24     // Get a vector toward the camera position
                               // This is the camera direction

            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = (camera vector)

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            dp3 r3,r0,r1              // Dot product Cam*Normal
            mul r2,c20,r3
            mad oT0.xyz,r2,r1,r0      // Compute reflection vector

            // (1-cos)^4 = approx fresnel
            add r0,c23,r3             // Complement color
            mul r1,r0,r0              // Square
            mul r0,r1,r1              // 4th
            mul r0,r0,c22
//          mov r1,c9
//          mul r1,r1,c21             // Blend in scaled diffuse material color
            add oD0,r0,r1             // Put into Diffuse Color
        };
    }
}

technique tec1
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;     // World Matrix
        VertexShaderConstant[4] = ;	    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;	                  // Light direction

        // Blending Constants
        VertexShaderConstant[20] = (-2.0f,-2.0f,-2.0f,-2.0f);
        VertexShaderConstant[21] = ( 0.25f, 0.25f, 0.25f, 0.05f );
        VertexShaderConstant[22] = ( 0.75f, 0.75f, 0.75f, 0.95f );
        VertexShaderConstant[23] = ( 1.00f, 1.00f, 1.00f, 1.00f );
        VertexShaderConstant[24] = ( 1.0f, 1.0f, 1.0f, 1.0f );

        // Camera Information
        VertexShaderConstant[25] = ;

        ColorOp[0]   = Modulate;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        ColorOp[1]   = Add;
        ColorArg1[1] = Current;
        ColorArg2[1] = Specular;

        ColorOp[2]   = Disable;
        AlphaOp[2]   = Disable;

        Texture[0]   = ;
        PixelShader  = ;

//      AlphaBlendEnable = True;
//      SrcBlend  = One; // SrcAlpha;
//      DestBlend = InvSrcAlpha;

//      CullMode = None;

        SpecularEnable = True;
        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to World space

            add r0,r0,-c25     // Get a vector toward the camera position.
                               //   This is the camera direction

            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = (camera vector)

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            dp3 r3,r0,r1              // Dot product Cam*Normal
            mul r2,c20,r3
            mad oT0.xyz,r2,r1,r0      // Compute reflection vector

            // (1-cos)^4 = approx fresnel
            add r0,c23,r3             // Complement color
            mul r1,r0,r0              // Square

            add oD0,r1,c21
            mov r1,c9
            mul oD1,r1,c21            // Blend in scaled diffuse material color
        };
    }
}

technique tec2
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;	    // World Matrix
        VertexShaderConstant[4] = ;	    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = ;                      // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      // Light direction

        // Blending constants
        VertexShaderConstant[20] = (-2.0f,-2.0f,-2.0f,-2.0f);
        VertexShaderConstant[21] = ( 0.25f, 0.25f, 0.25f, 0.05f );
        VertexShaderConstant[22] = ( 0.75f, 0.75f, 0.75f, 0.95f );
        VertexShaderConstant[23] = ( 1.00f, 1.00f, 1.00f, 1.00f );
        VertexShaderConstant[24] = ( 1.0f, 1.0f, 1.0f, 1.0f );

        // Camera information
        VertexShaderConstant[25] = ;

        ColorOp[0]   = Modulate;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        ColorOp[1]   = Add;
        ColorArg1[1] = Current;
        ColorArg2[1] = Specular;

        ColorOp[2]   = Disable;
        AlphaOp[2]   = Disable;

        Texture[0]   = ;
        PixelShader  = ;

//      FillMode = Wireframe;

        SpecularEnable = True;
        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to world Space

            add r0,r0,-c25     // Get a vector toward the camera position,
                               //   this is the camera direction

            //Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = (camera vector)

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            dp3 r3,r0,r1              // Dot product Cam*Normal
            mul r2,c20,r3
            mad oT0.xyz,r2,r1,r0      // Compute reflection vector

            //(1-cos)^4 = approx fresnel
            add r0,c23,r3             // Complement color
            mul r1,r0,r0              // Square

//          add r1, r1, c21
//          mul oD0, r1, c10

            mad oD0, r1, c10, c10

            mov r1,c9
            mul oD1,r1,c21            // Blend in scaled diffuse mat color
        };
    }
}

technique tec4
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;	    // World Matrix
        VertexShaderConstant[4] = ;	    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = ;                      // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      // Light direction

        // Blending Constants
        VertexShaderConstant[20] = (-2.0f,-2.0f,-2.0f,-2.0f);

        VertexShaderConstant[21] = ( 1.0f, 1.0f, 1.0f, 1.0f );
        VertexShaderConstant[22] = ( 0.75f, 0.75f, 0.75f, 0.95f );
        VertexShaderConstant[23] = ( 1.00f, 1.00f, 1.00f, 1.00f );

        // Camera Information
        VertexShaderConstant[24] = ;

//      FillMode = Wireframe;

        ColorOp[0]   = Modulate;
        ColorArg2[0] = Diffuse;
        ColorArg1[0] = Texture;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        Texture[0]   = ;
        PixelShader  = ;

        AlphaBlendEnable = True;
        SrcBlend  = One;
        DestBlend = InvSrcAlpha;

//      CullMode = None;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to World Space

            add r0,r0,-c24     // Get a vector toward the camera position,
                               //   this is the camera direction

            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = (camera vector)

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            dp3 r3,r0,r1              // Dot product Cam*Normal
            mul r2,c20,r3
            mad oT0.xyz,r2,r1,r0      // Compute reflection vector

            // (1-cos)^4 = approx fresnel
            add r0,c23,r3				// Complement color
            mul r1,r0,r0				// Square
            mul r0,r1,r1				// 4th

            mul r0,r0,c22
            mov r1,c9
//          add r0, r0, c10             // Add in specular
            add oD0,r0,r1               // Put into Diffuse Color
        };
    }
}

Exercise 5C

//
// Effect File Workshop Exercise 5C
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;	// Light direction

matrix mWld;	// World
matrix mTot;	// Total

vector vCPS;	// Camera position

texture tEnv;   // Environment texture
texture tDif;

vector matD; 	// Object diffuse material color

// Background color
DWORD  BCLR = 0xFF000000;

pixelshader pNIL;

// string XFile = "sphere.x";
// string XFile = "f40.x";
string XFile = "viper.x";

string BIMG  = "lobbyzneg.bmp";

// Technique names for display in viewer window
string tec0 = "Exercise 5b: Vertex Shader Specular Envmap";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;	    // World Matrix
        VertexShaderConstant[4] = ;	    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                      // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      // Light direction

        // Blending Constants
        VertexShaderConstant[20] = (-2.0f,-2.0f,-2.0f,-2.0f);

        VertexShaderConstant[25] = ( 1.0f, 1.0f, 1.0f, 1.0f );
        VertexShaderConstant[21] = ( 0.25f, 0.25f, 0.25f, 0.05f );
        VertexShaderConstant[22] = ( 0.75f, 0.75f, 0.75f, 0.95f );
        VertexShaderConstant[23] = ( 1.00f, 1.00f, 1.00f, 1.00f );

        // Camera information
        VertexShaderConstant[24] = ;

        ColorOp[0]   = Modulate;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        ColorOp[1]   = Add;
        ColorArg1[1] = Current;
        ColorArg2[1] = Specular;

        AlphaOp[1]   = Disable;

        Texture[0]   = ;
        PixelShader  = ;

//      AlphaBlendEnable = True;
//      SrcBlend  = One; // SrcAlpha;
//      DestBlend = InvSrcAlpha;

//      CullMode = None;

        SpecularEnable = True;
        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture coord1
            float v8[3]; // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to World Space

            add r0,r0,-c24     // Get a vector toward the camera position,
                               //   this is the camera direction

            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = (camera vector)

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            dp3 r3,r0,r1              // Dot product Cam*Normal
            mul r2,c20,r3
            mad oT0.xyz,r2,r1,r0      // Compute reflection vector

            // (1-cos)^4 = approx fresnel
            add r0,c23,r3             // Complement color
            mul r1,r0,r0              // Square
//          mul r0,r1,r1              // 4th
//          mul r0,r1,r1
            add oD0,r1,c21
            mul r0,r0,c22
            mov r1,c9
            mul oD1,r1,c25            // Blend in scaled diffuse mat color

//          add oD0,r0,r1             // Put into Diffuse Color
//          add oD0,r0,r1             // Put into Diffuse Color
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 6

Standard Texture Effect.
//
// Standard Texture Effect
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector matD;    // Material diffuse
vector matS;    // Material specular
vector matA;    // Material ambient

DWORD  lhtT;    // Light type
vector lhtD;    // Light diffuse
vector lhtS;    // Light specular
vector lhtA;    // Light ambient
vector lhtR;    // Light direction
vector lhtP;    // Light position

vector vOff;    // Emboss offset
vector vVwD;    // View direction
vector vCPS;    // Camera position

matrix mEnv;    // Environment map transform
matrix mWld;    // World
matrix mTot;    // Total

matrix mWl0;    // Blending matrices
matrix mWl1;
matrix mWl2;
matrix mWl3;
matrix mWl4;
matrix mWl5;
matrix mWl6;
matrix mWl7;

matrix mIdt =
[
    1.0,0.0,0.0,0.0,
    0.0,1.0,0.0,0.0,
    0.0,0.0,1.0,0.0,
    0.0,0.0,0.0,1.0
];

DWORD  BCLR = 0x0000000;

texture tDif;   // Diffuse texture
texture tEnv;   // Environment texture
texture tEvC;   // Circulary integratex cube texture
texture tEvL;

texture tDf2;   // Second texture
texture tDf3;
texture tDf4;

texture tSt1;   // Procedural satin texture
texture tSt2;   // Procedural stain texture2
texture tMt1;   // Brushed metal texture
texture tFrn;   // Fresnel Shader
texture tGlw;   // Glow Shader
texture tL10;   // Light lookup texture for spec
texture tL80;
texture tL64;
texture tL32;
texture tL16;

texture tfg1;
texture tfg2;
texture tNSE;
texture tNSN;

pixelshader pNIL;

string XFile = "tiny.x";
string Skinned = "true";

// Skinned version, lots of transforms have to happen here
vertexshader sDif =
decl
{
    stream 0;
    float v0[3];    // Blend weights
    float v1[3];    // Indices
    ubyte v2[4];
// OR
//  d3dcolor v2[1]; // if hardware doesn't support ubyte, use d3dcolor instead
    float v3[3];
    float v7[3];
    float v8[3];
}
asm
{
    vs_1_1

    // The indices are put into an color
    // If ubyte is supported, this the right way to do it
    mul r1,v2.xyzw,c41.zzzz
    // OR
    // If ubyte is not supported, decode from a 32 bit d3dcolor value
    //mul r1,v2.zyxw,c41.wwww

    // First compute the last blending weight
    mov r0.xyz,v1.xyz;
    dp3 r0.w,v1.xyz,c40.xxx;

    add r0.w,-r0.w,c40.x

    // Now do a bunch of matrix multiples,
    //    r5 = Position
    //    r6 = Normal

    mov a0.x,r1.x
    mov r5,v0
    m4x3 r5,v0,c[a0.x]; //World matrices start at 0
    m3x3 r6,v3,c[a0.x];

    // Blend them
    mul r5,r5,r0.xxxx
    mul r6,r6,r0.xxxx

    // Set 2
    mov a0.x,r1.y
    m4x3 r2,v0,c[a0.x];
    m3x3 r3,v3,c[a0.x];

    // Add them in
    mad r5,r2,r0.yyyy,r5;
    mad r6,r3,r0.yyyy,r6;

    // Set 3
    mov a0.x,r1.z
    m4x3 r2,v0,c[a0.x];
    m3x3 r3,v3,c[a0.x];

    // Add them in
    mad r5,r2,r0.zzzz,r5;
    mad r6,r3,r0.zzzz,r6;

    // Set 4
    mov a0.x,r1.w
    m4x3 r2,v0,c[a0.x];
    m3x3 r3,v3,c[a0.x];

    // Add them in
    mad r5,r2,r0.wwww,r5;
    mad r6,r3,r0.wwww,r6;

    // Compute position
    mov r5.w,c40.x
    m4x4 oPos,r5,c50;

    dp3 r11.x,r6.xyz,r6.xyz   // Load the square into r1
    rsq r11.xyz,r11.x         // Get the inverse of the square
    mul r6.xyz,r6.xyz,r11.xyz // Multiply

    dp3 r4.xyz,r6,-c48

    mov oD0.xyz,r4.xyz
    mov oT0.xy,v7.xy
};

//Skinned Diffuse 1

string tec0 = "Exercise 6: Skinned Diffuse";
technique tec0
{
    pass P0
    {
        ColorOp[0]   = Modulate;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Current;

        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Linear;

        VertexShaderConstant[0]  = ;
        VertexShaderConstant[4]  = ;
        VertexShaderConstant[8]  = ;
        VertexShaderConstant[12] = ;
        VertexShaderConstant[16] = ;
        VertexShaderConstant[20] = ;
        VertexShaderConstant[24] = ;
        VertexShaderConstant[28] = ;
        VertexShaderConstant[32] = ;

        VertexShaderConstant[50] = ;           // mTot is just view*proj
        VertexShaderConstant[48] = ;
        VertexShaderConstant[40] = (1.0f,-1.0f,0.0f,.0f);
        VertexShaderConstant[41] = (0.00390625f, 256.0f, 4.0f,1020.01f);
        VertexShaderConstant[43] = (0.0,0.0,1.0,0.0f);
        VertexShaderConstant[44] = (0.0,0.0,0.0,0.0);
        VertexShaderConstant[60] = (0.5,0.5,0.5,0.5);

        VertexShaderConstant[60] = (1.0f,1.0f,1.0f,1.0f);
        VertexShaderConstant[61] = (.50f,0.43f,0.38f,1.0f);   // Sky color
        VertexShaderConstant[62] = (0.18f,.10f,0.15f,1.0f);   // Ground color
        VertexShaderConstant[63] = ;                    // Object color
        VerteXShaderConstant[64] = (0.0f,1.0f,0.0f,1.0f);     // Sky direction

        Texture[0]   = ;
        vertexshader = ;

        wrap0        = U | V;
        wrap1        = U | V;

        AddressU[0]  = Wrap;
        AddressV[0]  = Wrap;

        AlphaBlendEnable = False;
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 7

Multi-Texturing with Shaders.
//
// Effect File Workshop Exercise 7
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object
texture tNSE;   // Noise texture

// Background color
DWORD  BCLR = 0xFF0000FF;

pixelshader pNIL;

string XFile = "sphere.x";

// Technique names for display in viewer window
string tec0 = "Exercise 7: Multi-Texturing with shaders";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;     // World Matrix
        VertexShaderConstant[4] = ;    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,0.0f,0.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                // Light direction

        // Useful constant(s)
        VertexShaderConstant[20] = (-1.0f,-1.0f,-1.0f,-1.0f);

        Texture[0]   = ;
        Texture[1]   = ;
        wrap0        = U | V;
        wrap1        = U | V;

        AddressU[0] = wrap;
        AddressV[0] = wrap;
        AddressU[1] = wrap;
        AddressV[1] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3];       // Position
            float v3[3];       // Normal
            float v7[3];       // Texture coord1
            float v8[3];       // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m3x3 r0,v3,c0      // Transform normal to world space, put
                               //   result into r0

            dp3  r0,r0,-c16    // Dot product against light, r0
                               // now has lighting constant in x,y and z
                               // components (r,g,b)

            mov r0.xy,v7.xy    // Copy texture coordinates to r0
            //mul r0.y,r0.y,c20  // Invert texture coordinates

            mov oT0.xy,r0.xy   // Copy texture coordinates to oT0
            mov oT1.xy,r0.xy   // Copy texture coordinates to oT1
            mov oD0,r0         // Copy diffuse to output
        };

        PixelShader =
        asm
        {
           ps_1_1
           tex t0              // Get texture sample from stage 0
           tex t1              // Get texture sample from stage 1
           mul_x2 r0,t1,t0;    // Blend them together in an interesting way
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 8

Texturing with Lights.
//
// Effect File Workshop Exercise 8
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object
texture tNSE;   // Noise Texture

vector vCPS;    // Camera position

// Background color
DWORD  BCLR = 0xFF0000FF;

pixelshader pNIL;

string XFile = "sphere.x";

// Technique names for display in viewer window
string tec0 = "Exercise 8: Texturing with lights";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;                 // World Matrix
        VertexShaderConstant[4] = ;                 // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                //Light Direction

        // Useful constants
        VertexShaderConstant[20] = (1.0f,1.0f,1.0f,1.0f);
        VertexShaderConstant[21] = (1.0f,1.0f,1.0f,0.0f);

        // Camera Information
        VertexShaderConstant[24] = ;

        Texture[0]   = ;
        Texture[1]   = ;
        wrap0        = U | V;
        wrap1        = U | V;

        AddressU[0] = wrap;
        AddressV[0] = wrap;
        AddressU[1] = wrap;
        AddressV[1] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3];       // Position
            float v3[3];       // Normal
            float v7[3];       // Texture coord1
            float v8[3];       // Texture coord2
        }
        asm
        {
            vs_1_1             // Version number
            m4x4 oPos, v0, c4  // Transform point to projection space
            m4x4 r0,v0,c0      // Transform point to world space

            add r0,-r0,c24     // Get a vector toward the camera position.
                               // This is the negative of the camera direction.
            // Normalize
            dp3 r11.x,r0.xyz,r0.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r0.xyz,r0.xyz,r11.xyz // Multiply, r0 = -(camera vector)

            add r2.xyz,r0.xyz,-c16    // Get half angle

            // Normalize
            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r2 = HalfAngle

            m3x3 r1,v3,c0             // Transform normal to world space,
                                      //   put in r1

            // r2 = half angle, r1 = normal, r3 (output) = intensity
            dp3  r3.xyzw,r2,r1

            // Now raise it several times
            mul r3,r3,r3              // 2nd
            mul r3,r3,r3              // 4th
            mul r3,r3,r3              // 8th
            mul r3,r3,r3              // 16th

            mul r3,r3,c20

            // Compute diffuse term
            dp3 r4,r1,-c16
            mul r4,r4,c21

            mov oD0,r4
            mov oD1,r3

            mov oT0.xy,v7.xy          // Copy texture coordinates to oT0
            mov oT1.xy,v7.xy          // Copy texture coordinates to oT1
        };

        PixelShader =
        asm
        {
           ps_1_1
           tex t0                     // Sample texture 0
           tex t1                     // Sample texture 1

           mul_x2 r1,t1,t0;           // Blend them together
           mov    r0,r1

           mul    r0,r1,v0;           // Modulate diffuse
           mul    r1,r1,v1;           // Modulate specular
           add    r0,r0,v1;           // Blend them together
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 9

Dot 3 Bump Mapping, Dot 3 Specular Bump Mapping, and Table Lookup Specular Bump Mapping.
//
// Effect File Workshop Exercise 9
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object
texture tDf3;   // Normal map for earth

texture tL10;   // Light lookup texture for spec
texture tL80;
texture tL64;
texture tL32;
texture tL16;

vector vCPS;    // Camera Position

// Background color
DWORD  BCLR = 0xFF0000FF;

pixelshader pNIL;

string XFile = "sphere.x";

// Technique names for display in viewer window
string tec0 = "Exercise 9a: Dot 3 Bump Mapping";
string tec1 = "Exercise 9b: Dot 3 Specular Bump Mapping";
string tec2 = "Exercise 9c: Table Lookup Specular Bump Mapping";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ; 	// World Matrix
        VertexShaderConstant[4] = ;	// World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = (0.8f,0.8f,0.8f,0.8f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (0.7f,0.7f,0.7f,0.7f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;	//Light Direction

        vertexShaderConstant[20] = (.5f,.5f,.5f,.5f);

        // Camera information
        VertexShaderConstant[24] = ;

        Texture[0]   = ;
        Texture[1]   = ;
        wrap0        = U | V;
        wrap1        = U | V;

        AddressU[0] = wrap;
        AddressV[0] = wrap;
        AddressU[1] = wrap;
        AddressV[1] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture Coord1
            float v8[3]; // Tangent
        }
        asm
        {
            vs_1_1
            // Transform position
            m4x4 oPos,v0,c4

            // Transform normal and tangent
            m3x3 r7,v8,c0
            m3x3 r8,v3,c0

            // Cross product
            mul r0,-r7.zxyw,r8.yzxw;
            mad r5,-r7.yzxw,r8.zxyw,-r0;

            // Transform the light vector
            dp3 r6.x,r7,-c16
            dp3 r6.y,r5,-c16
            dp3 r6.z,r8,-c16

            // Multiply by a half to bias, then add half
            mad r6.xyz,r6.xyz,c20,c20

            mov oT0.xy,v7.xy
            mov oT1.xy,v7.xy
            mov oD0.xyz,r6.xyz
        };

        PixelShader =
        asm
        {
            ps_1_1
            tex t0	 // Sample texture
            tex t1	 // Sample normal
            mov r0,t1
            dp3	r0,t1_bx2,v0_bx2; // Dot(light,normal)
            mul r0,t0,r0          // Modulate against base color
        };
    }
}

technique tec1
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ; 	// World matrix
        VertexShaderConstant[4] = ;	// World*View*Proj matrix

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                // Light direction

        VertexShaderConstant[20] = (.5f,.5f,.5f,.5f);

        // Camera information
        VertexShaderConstant[24] = ;

        Texture[0]   = ;
        Texture[1]   = ;
        wrap0        = U | V;
        wrap1        = U | V;

        AddressU[0] = wrap;
        AddressV[0] = wrap;
        AddressU[1] = wrap;
        AddressV[1] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture Coord1
            float v8[3]; // Tangent
        }
        asm
        {
            vs_1_1
            // Transform position
            m4x4 oPos,v0,c4

            // Transform normal and tangent
            m3x3 r7,v8,c0
            m3x3 r8,v3,c0

            // Cross product
            mul r0,-r7.zxyw,r8.yzxw;
            mad r5,-r7.yzxw,r8.zxyw,-r0;

            // Transform position
            m4x4 r2,v0,c0

            // Get a vector toward the camera
            add r2,-r2,c24

            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r11
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r0 = -(camera vector)

            add r2.xyz,r2.xyz,-c16    // Get half angle

            // Normalize
            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r2 = HalfAngle

            // Transform the half angle vector
            dp3 r6.x,r7,r2
            dp3 r6.y,r5,r2
            dp3 r6.z,r8,r2

            // Multiply by a half to bias, then add half
            mad r6.xyz,r6.xyz,c20,c20

            mov oT0.xy,v7.xy
            mov oT1.xy,v7.xy
            mov oD0.xyz,r6.xyz
        };

        PixelShader =
        asm
        {
            ps_1_1
            tex t0                // Sample base map
            tex t1                // Sample normal
            dp3	r0,t1_bx2,v0_bx2; // Dot(normal,half)

            mul r1,r0,r0;         // Raise it to 32nd power
            mul r0,r1,r1;
            mul r1,r0,r0;
            mul r0,r1,r1;
            mul r0,t0,r0
        };
    }
}

technique tec2
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ; 	// World Matrix
        VertexShaderConstant[4] = ;	    // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      //Light Direction

        vertexShaderConstant[20] = (.5f,.5f,.5f,.5f);

        // Camera Information
        VertexShaderConstant[24] = ;

        Texture[0]   = ;
        Texture[2]   = ;
        Texture[3]   = ;
        wrap0        = U | V;
        wrap1        = 0;
        wrap2        = 0;
        wrap3        = U | V;

        AddressU[0] = wrap;
        AddressV[0] = wrap;
        AddressU[1] = clamp;
        AddressV[1] = clamp;
        AddressU[2] = clamp;
        AddressV[2] = clamp;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3]; // Position
            float v3[3]; // Normal
            float v7[3]; // Texture Coord1
            float v8[3]; // Tangent
        }
        asm
        {
            vs_1_1
            // Transform position
            m4x4 oPos,v0,c4

            // Transform normal and tangent
            m3x3 r7,v8,c0
            m3x3 r8,v3,c0

            // Cross product
            mul r0,-r7.zxyw,r8.yzxw;
            mad r5,-r7.yzxw,r8.zxyw,-r0;

            // Transform position
            m4x4 r2,v0,c0

            // Get a vector toward the camera
            add r2,-r2,c24

            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r11
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r0 = -(camera vector)

            add r2.xyz,r2.xyz,-c16    // Get half angle

            // Normalize
            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r1
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r2 = HalfAngle

            // Transform the half angle vector
            dp3 r6.x,r7,r2
            dp3 r6.y,r5,r2
            dp3 r6.z,r8,r2

            mov oT0.xy,v7.xy         // Coordinate to samp normal from
            mov oT1.xyz,r6           // Not a tex coordinate, but half
            mov oT2.xyz,r6           // Angle
            mov oT3.xy,v7.xy
        };

        PixelShader =
        asm
        {
            ps_1_1
            tex t0	                // Sample normal
            texm3x2pad t1, t0_bx2   // Look it up in a table
            texm3x2tex t2, t0_bx2
            tex t3                  // Sample base color

            mov r0,t2
            mul r0,r0,t3            // Blend terms
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 10

Anisotropic Bump Mapping.
//
// Effect File Workshop Exercise 10
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light direction

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object
texture tDf4;   // Normal map for earth
texture tSt2;   // Anisotropic lighting table
vector vCPS;    // Camera position

// Background color
DWORD  BCLR = 0xFF0000FF;

pixelshader pNIL;

string XFile = "bust.x";

// Technique names for display in viewer window
string tec0 = "Exercise 10: Anisotropic Bump Mapping";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;             // World Matrix
        VertexShaderConstant[4] = ;             // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f); // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f); // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f); // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f); // Ambient
        VertexShaderConstant[16] = ;                      // Light direction

        vertexShaderConstant[20] = (.5f,.5f,.5f,.5f);
        vertexShaderConstant[40] = (1.0f,1.0f,1.0f,1.0f);

        // Camera information
        VertexShaderConstant[24] = ;
        PixelShaderConstant[0]   = (0.5f, 0.2f, 0.2f, 0.2f);

        Texture[0]  = ;
        Texture[3]  = ;

        wrap0        = U | V;
        wrap1        = 0;
        wrap2        = 0;
        wrap3        = 0;

        AddressU[0]  = wrap;
        AddressV[0]  = wrap;
        AddressU[1]  = wrap;
        AddressV[1]  = wrap;
        AddressU[3]  = wrap;
        AddressV[3]  = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3];              // Position
            float v3[3];              // Normal
            float v7[3];              // Texture Coord1
            float v8[3];              // Tangent
        }
        asm
        {
            vs_1_1

            // Transform position
            m4x4 oPos,v0,c4

            // Transform normal and tangent
            m3x3 r7,v8,c0
            m3x3 r8,v3,c0

            // Cross product
            mul r0,-r7.zxyw,r8.yzxw;
            mad r5,-r7.yzxw,r8.zxyw,-r0;

            // Transform position
            m4x4 r2,v0,c0

            // Get a vector toward the camera
            add r2,-r2,c24

            dp3 r11.x,r2.xyz,r2.xyz   // Load the square into r11
            rsq r11.xyz,r11.x         // Get the inverse of the square
            mul r2.xyz,r2.xyz,r11.xyz // Multiply, r0 = -(camera vector)

             // Transform the view angle vector
            dp3 r6.x,r7,r2
            dp3 r6.y,r5,r2
            dp3 r6.z,r8,r2

            // Transform the light vector
            dp3 r2.x,r7,-c16
            dp3 r2.y,r5,-c16
            dp3 r2.z,r8,-c16

            mov oT0.xy,v7.xy          // Coordinates to samp normal from
            mov oT1.xyz,r2            // Light
            mov oT2.xyz,r6            // View angle
            mov oT3.xyz,c40           // Garbage in this register
        };

        PixelShader =
        asm
        {
           ps_1_1
           tex t0
           texm3x3pad t1, t0_bx2      // 3x3 transform
           texm3x3pad t2, t0_bx2      // These generate a texcoord which is
           texm3x3tex t3, t0_bx2      // u = dot(light,normal)
                                      // v = dot(view, normal)
                                      // w = some positive number

           mov r0,t3;
           mad r0,c0,t3.a,r0;         // Alpha has the diffuse, so add it
                                      // to specular for final result
           };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Exercise 11

Area Lighting, Area, and Diffuse Lighting.
//
// Effect File Workshop Exercise 11
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//

vector lhtR;    // Light Direction
vector matD;    // Material Diffuse

matrix mWld;    // World
matrix mTot;    // Total

texture tDif;   // Diffuse texture of object

// Background color
DWORD  BCLR = 0xFF000000;

pixelshader pNIL;

string XFile = "skullhiv.x";

// Technique names for display in viewer window
string tec0 = "Exercise 11a: Area Lighting";
string tec1 = "Exercise 11b: Area and Diffuse Lighting";

technique tec0
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;             // World Matrix
        VertexShaderConstant[4] = ;             // World*View*Proj Matrix

        // Material properties of object
        VertexShaderConstant[9]  = ;                  // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);   // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);   // Ambient

        // Properties of light
        VertexShaderConstant[13] = (1.0f,1.0f,1.0f,1.0f);   // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);   // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f);   // Ambient
        VertexShaderConstant[16] = ;                  // Light direction

        VertexShaderConstant[20] = (.5f,.5f,.5f,.5f);
        VertexShaderConstant[40] = (1.0f,1.0f,1.0f,1.0f);
        VertexShaderConstant[41] = (1.00f,0.86f,0.75f,1.0f); // sky color
        VertexShaderConstant[42] = (0.25f,.25f,0.15f,1.0f);  // ground color
        VertexShaderConstant[43] = ;                   // object color
        VerteXShaderConstant[44] = (0.0f,-1.0f,0.0f,1.0f);   // sky direction

        Texture[0]   = ;

        wrap0        = U | V;
        wrap1        = 0;
        wrap2        = 0;

        AddressU[0] = wrap;
        AddressV[0] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        ColorOp[0]   = Modulate;
        ColorArg1[0] = Diffuse;
        ColorArg2[0] = Texture;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3];         // Position
            float v3[3];         // Normal
            float v7[3];         // Texture Coord1
            float v8[3];         // Tangent
        }
        asm
        {
            vs_1_1
            m4x4 oPos,v0,c4      // Transform position
            m3x3   r0,v3,c0      // Transform normal to world space

            dp3 r0,r0,-c44       // Dot product against sky vector

            // The dot product was between -1 to 1.
            //   Re-range this to 0 to 1.
            mad r0,r0,c20,c20

            // Now lerp between the two sky colors.
            mov r1,c42
            sub r1,c41,r1        // To save a clock, this delta should be
                                 //   saved in a register.
            mad r0,r1,r0,c42     // Now lerp

            sub r1,c40,v7.zzz    // This modulates against a darkening term
                                 //   or occlusion term, embedded in the z-tex
                                 //   coordinate, you want 1-z though.
            mul r0,r0,r1         // Darken sky term
            mul oD0,r0,c9        // Now modulate against object's color

            mov oT0.xy,v7.xy
        };
    }
}

technique tec1
{
    pass p0
    {
        // Load matrices
        VertexShaderConstant[0] = ;             // World Matrix
        VertexShaderConstant[4] = ;             // World*View*Proj Matrix

        //Material properties of object
        VertexShaderConstant[9]  = ;                   // Diffuse
        VertexShaderConstant[10] = (0.0f,0.0f,0.0f,0.0f);    // Specular
        VertexShaderConstant[11] = (0.0f,0.0f,0.0f,0.0f);    // Ambient

        //properties of light
        VertexShaderConstant[13] = (.6f,.6f,.6f,1.0f);       // Diffuse
        VertexShaderConstant[14] = (0.0f,0.0f,0.0f,0.0f);    // Specular
        VertexShaderConstant[15] = (0.0f,0.0f,0.0f,0.0f);    // Ambient
        VertexShaderConstant[16] = ;                   // Light direction

        VertexShaderConstant[20] = (.5f,.5f,.5f,.5f);
        VertexShaderConstant[40] = (1.0f,1.0f,1.0f,1.0f);
        VertexShaderConstant[41] = (.80f,0.76f,0.65f,1.0f);  // Sky color
        VertexShaderConstant[42] = (0.25f,.25f,0.15f,1.0f);  // Ground color
        VertexShaderConstant[43] = ;                   // Object color
        VerteXShaderConstant[44] = (0.0f,-1.0f,0.0f,1.0f);   // Sky direction

        FillMode = Wireframe;

        Texture[0]   = ;

        wrap0        = U | V;
        wrap1        = 0;
        wrap2        = 0;

        AddressU[0] = wrap;
        AddressV[0] = wrap;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MinFilter[1] = Linear;
        MagFilter[1] = Linear;

        ColorOp[0]   = Modulate;
        ColorArg1[0] = Diffuse;
        ColorArg2[0] = Texture;
        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Diffuse;

        VertexShader =
        decl
        {
            stream 0;
            float v0[3];        // Position
            float v3[3];        // Normal
            float v7[3];        // Texture Coord1
            float v8[3];        // Tangent
        }
        asm
        {
            vs_1_1
            m4x4 oPos,v0,c4     // Transform position
            m3x3   r9,v3,c0     // Transform normal to world space

            dp3 r0,r9,-c44      // Dot product against sky vector

            // The dot product was between -1 to 1. You want
            //   to re-range this to 0 to 1
            mad r0,r0,c20,c20

            //now lerp between the two sky colors
            mov r1,c42
            sub r1,c41,r1      // To save a clock, this delta should
                                //   be saved in a register
            mad r0,r1,r0,c42    // Now lerp

            sub r1,c40,v7.zzz   // This modulates against a darkening term
                                //   or occlusion term, embedded in the z-tex
                                //   coordinate, you want 1-z though.
            mul r2,r0,r1        // Darken sky term
            dp3 r1,r9,-c16      // Dot against light vector
            max r1, c15, r1

            // Complement, square, complement
            sub r1, c40, r1
            mul r1, r1, r1
            mul r1, r1, r1
            sub r1, c40, r1

            mad r0,r1,c13,r2    // Combine with light diffuse
            mul oD0,r0,c9       // Now modulate against object's color

            mov oT0.xy,v7.xy
        };
    }
}

© 2002 Microsoft Corporation. All rights reserved.


Beginning and Ending a Scene

Applications written in C++ notify Microsoft® Direct3D® that scene rendering is about to begin by calling the IDirect3DDevice9::BeginScene method. IDirect3DDevice9::BeginScene causes the system to check its internal data structures and the availability and validity of rendering surfaces. It also sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail. For more information, see Rendering Primitives.

After you complete the scene, call the IDirect3DDevice9::EndScene method. The IDirect3DDevice9::EndScene method flushes cached data, verifies the integrity of rendering surfaces, and clears an internal flag that signals when a scene is in progress.

All rendering methods must be bracketed by calls to the IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene methods. If surfaces are lost or internal errors occur, the scene methods return error values. If IDirect3DDevice9::BeginScene fails, the scene does not begin, and subsequent calls to IDirect3DDevice9::EndScene will fail.

To summarize these cases:

  • If IDirect3DDevice9::BeginScene returns any error, you must not call IDirect3DDevice9::EndScene because the scene has not successfully begun.
  • If IDirect3DDevice9::BeginScene succeeds, but you get an error while rendering the scene, you must call IDirect3DDevice9::EndScene.
  • If IDirect3DDevice9::EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like the following example.

HRESULT hr;

if(SUCCEEDED(pDevice->BeginScene()))
{
    // Render primitives only if the scene
    // starts successfully.

    // Close the scene.
    hr = pDevice->EndScene();
    if(FAILED(hr))
        return hr;
}

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling IDirect3DDevice9::EndScene when IDirect3DDevice9::BeginScene has not been called returns an error value. Likewise, calling IDirect3DDevice9::BeginScene when a previous scene has not been completed with the IDirect3DDevice9::EndScene method results in an error.

Do not attempt to call Microsoft Windows® Graphics Device Interface (GDI) functions on Direct3D surfaces, such as the render target or textures, while a scene is being rendered—is between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls. Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, be sure that all GDI calls are made outside the scene functions.

© 2002 Microsoft Corporation. All rights reserved.


Clearing Surfaces

Before rendering objects in a scene, clear the viewport on the render-target surface or a subset of the viewport. Clearing the viewport causes the system to set the desired portion of the render-target surface and any attached depth or stencil buffers to a desired state. This resets the areas of the surface that will be rendered again, and it resets the corresponding areas of the depth and stencil buffers, if any are in use. Clearing a render-target surface can set the desired region to a default color or texture. For depth and stencil buffers, this can set a depth or stencil value.

Use the IDirect3DDevice9::Clear method to clear the viewport.

For more information about using this method, see Clearing a Viewport.

Performance Note Applications that render scenes covering the entire area of the render-target surface can improve performance by clearing the attached depth and stencil buffer surfaces, if any, instead of the render target. In this case, clearing the depth buffer causes Microsoft® Direct3D® to rewrite the render target on the next rendered frame, making an explicit clear operation on the render target redundant. However, if your application renders only to a portion of the render-target surface, explicit clear operations are required.

© 2002 Microsoft Corporation. All rights reserved.


Alpha Blending State

The alpha value of a color controls its transparency. Enabling alpha blending allows colors, materials, and textures on a surface to be blended with transparency onto another surface.

For more information, see Alpha Texture Blending and Texture Blending.

Applications written in C++ use the D3DRS_ALPHABLENDABLE render state to enable alpha transparency blending. The Microsoft® Direct3D® application programming interface (API) allows many types of alpha blending. However, it is important to note the user's 3-D hardware might not support all the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code example demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the source blend state.
d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);

// Set the destination blend state.

d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is to control the lighting in a 3-D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

You can achieve color light mapping by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.

© 2002 Microsoft Corporation. All rights reserved.


Alpha Testing State

C++ applications can use alpha testing to control when pixels are written to the render-target surface. By using the D3DRS_ALPHATESTENABLE render state, your application sets the current Microsoft® Direct3D® device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it does not, Direct3D ignores the pixel. Select the alpha test function with the D3DRS_ALPHAFUNC render state. Your application can set a reference alpha value for all pixels to compare against by using the D3DRS_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color at a given pixel (D3DPCMPCAPS_GREATEREQUAL), then the pixel is written. Otherwise, the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following code example checks if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

// This code example assumes that pCaps is a
// D3DCAPS9 structure that was filled with a
// previous call to IDirect3D9::GetDeviceCaps.

if (pCaps.AlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL)
{
    dev->SetRenderState(D3DRS_ALPHAREF, (DWORD)0x00000001);
    dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
    dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
}

// If the comparison is not supported, render anyway.
// The only drawback is no performance gain.

Not all hardware supports all alpha-testing features. You can check the device capabilities by calling the IDirect3D9::GetDeviceCaps method. After retrieving the device capabilities, check the associated D3DCAPS9 structure's AlphaCmpCaps member for the desired comparison function. If the AlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests.

© 2002 Microsoft Corporation. All rights reserved.


Ambient Lighting State

Ambient light is surrounding light that radiates from all directions.

For specific information about how Microsoft® Direct3D® uses ambient light, see Direct Light vs. Ambient Light, and Mathematics of Lighting.

A C++ application sets the color of ambient lighting by invoking the IDirect3DDevice9::SetRenderState method and passing the enumerated value D3DRS_AMBIENT as the first parameter. The second parameter is a color value. The default value is zero.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the ambient light.

d3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00202020);

© 2002 Microsoft Corporation. All rights reserved.


Antialiasing State

Antialiasing is a method of making lines and edges appear smoother on the screen. Microsoft® Direct3D® supports two antialiasing methods: edge antialiasing and full-scene antialiasing.

For details about these techniques, see Antialiasing.

By default, Direct3D does not perform antialiasing. To enable edge-antialiasing, which requires a second rendering pass, set the D3DRS_EDGEANTIALIAS render state to TRUE. To disable it, set D3DRS_EDGEANTIALIAS to FALSE.

To enable full-scene antialiasing, set the D3DRS_MULTISAMPLEANTIALIAS render state to TRUE. To disable it, set D3DRS_MULTISAMPLEANTIALIAS to FALSE.

© 2002 Microsoft Corporation. All rights reserved.


Culling State

As Microsoft® Direct3D® renders primitives, it culls primitives that are facing away from the user.

C++ applications set the culling mode by using the D3DRS_CULLMODE render state, which can be set to a member of the D3DCULL enumerated type. By default, Direct3D culls back faces with counterclockwise vertices.

The following code sample illustrates the process of setting the culling mode to cull back faces with clockwise vertices.

// This code example assumes that d3dDevice is a valid
// pointer to an IDirect3DDevice9 interface.
// Set the culling state.
d3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);

© 2002 Microsoft Corporation. All rights reserved.


Depth Buffering State

Depth buffering is a method of removing hidden lines and surfaces. By default, Microsoft® Direct3D® does not use depth buffering.

For a conceptual overview of depth buffers, see Depth Buffers.

C++ applications update the depth-buffering state with the D3DRS_ZENABLE render state, using a member of the D3DZBUFFERTYPE enumeration to specify the new state value.

If your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRS_ZWRITEENABLE enumerated value, specifying D3DZB_FALSE as the second parameter for the call to IDirect3DDevice9::SetRenderState.

The following code example shows how the depth-buffer state is set to enable z-buffering.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.
// Enable z-buffering.
d3dDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

Your application can also use the D3DRS_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another, even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRS_DEPTHBIAS).

© 2002 Microsoft Corporation. All rights reserved.


Fog State

Fog effects can give a 3-D scene greater realism. You can use fog effects for more than simulating fog. They can also decrease the clarity of a scene with distance. This mirrors what happens in the real world; as objects become more distant from the user, their detail is less distinct.

For more information about using fog in your application, see Fog.

A C++ application controls fog through device rendering states. The D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters of the formula.

You enable fog by setting the D3DRS_FOGENABLE render state to TRUE. The fog color can be set to any color value by using the D3DRS_FOGCOLOR render state; the alpha component of the fog color is ignored.

The D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states control the fog formula applied for fog calculations, and they indirectly control which type of fog is applied. Both render states can be set to a member of the D3DFOGMODE enumerated type. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system applies only pixel fog effects.

The D3DRS_FOGSTART and D3DRS_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRS_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters.

© 2002 Microsoft Corporation. All rights reserved.


Lighting State

Applications that use the Microsoft® Direct3D® geometry pipeline can enable or disable lighting calculations. Only vertices that contain a vertex normal are properly lit; vertices with no normal will use a dot product of zero in all lighting computations. Therefore, a vertex that does not use a normal receives no light.

For more information, see Mathematics of Lighting.

Applications enable Direct3D lighting by setting the D3DRS_LIGHTING render state to TRUE, which is the default setting, and they disable Direct3D lighting by setting the render state to FALSE.

The lighting render state is entirely independent of lighting computations that can be performed on vertices within a vertex buffer. The IDirect3DDevice9::ProcessVertices method accepts its own flags to control lighting calculations during vertex processing.

© 2002 Microsoft Corporation. All rights reserved.


Outline and Fill State

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. You can select the method to fill them by specifying a value defined by the D3DFILLMODE enumerated type for the D3DRS_FILLMODE render state.

To enable dithering, your application must pass the D3DRS_DITHERENABLE enumerated value as the first parameter to IDirect3DDevice9::SetRenderState. It must set the second parameter to TRUE to enable dithering, and FALSE to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. You can control this using the D3DRS_LASTPIXEL enumerated value. However, do not alter this setting without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

Object outlines can be drawn by setting the appropriate line drawing pattern. The default line drawing state is to draw solid lines. For more information, see Direct3D Extentions (D3DX) Line Drawing render state.

© 2002 Microsoft Corporation. All rights reserved.


Per-Vertex Color State

When using flexible vertex format (FVF) codes, vertices can contain both vertex color and vertex normal information. By default, Microsoft® Direct3D® uses this information when it calculates lighting. To disable use of vertex color lighting information, invoke the IDirect3DDevice9::SetRenderState method and pass D3DRS_COLORVERTEX as the first parameter. Set the second parameter to FALSE to disable vertex color lighting, or TRUE to enable it.

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE render states control the ambient, diffuse, emissive, and specular color component sources, respectively. Each state can be set to members of the D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.

© 2002 Microsoft Corporation. All rights reserved.


Primitive Clipping State

Microsoft® Direct3D® can clip primitives that render partially outside the viewport. When using C++, Direct3D clipping is controlled by the D3DRS_CLIPPING render state. Set this render state to TRUE (the default value) to enable primitive clipping. Set it to FALSE to disable Direct3D clipping services.

© 2002 Microsoft Corporation. All rights reserved.


Shading State

Microsoft® Direct3D® supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your C++ application specifies a member of the D3DSHADEMODE enumerated type for the D3DRS_SHADEMODE render state.

The following C++ code example demonstrates the process of setting the shading state to flat shading mode.

// This code example assumes that d3dDevice is a
// valid pointer to a IDirect3DDevice9 interface.
// Set the shading state.
d3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);

© 2002 Microsoft Corporation. All rights reserved.


Stencil Buffer State

Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface.

For details, see Stencil Buffer Techniques.

Applications written in C++ enable or disable stenciling by calling the IDirect3DDevice9::SetRenderState method. Pass D3DRS_STENCILENABLE as the value of the first parameter. Set the value of the second parameter to TRUE or FALSE to enable or disable stenciling, respectively.

Set the comparison function that Microsoft® Direct3D® uses to perform the stencil test by calling IDirect3DDevice9::SetRenderState. Set the value of the first parameter to D3DRS_STENCILFUNC. Pass a member of the D3DCMPFUNC enumerated type as the value of the second parameter.

The stencil reference value is the value in the stencil buffer that the stencil function uses for its test. By default, the stencil reference value is zero. Your application can set the value by calling D3DRENDERSTATETYPE. Pass D3DRS_STENCILREF as the value of the first parameter. Set the value of the second parameter to the new reference value.

Before the Direct3D module performs the stencil test for any pixel, it performs a bitwise AND operation of the stencil reference value and a stencil mask value. The result is compared against the contents of the stencil buffer using the stencil comparison function. Your application can set the stencil mask with D3DRENDERSTATETYPE. Pass D3DRS_STENCILMASK as the value of the first parameter. Set the value of the second parameter to the new stencil mask.

To set the action that Direct3D takes when the stencil test fails, call IDirect3DDevice9::SetRenderState and pass D3DRS_STENCILFAIL as the first parameter. The second parameter is D3DSTENCILCAPS.

Your application can also control how Direct3D responds when the stencil test passes but the z-buffer test fails. Call IDirect3DDevice9::SetRenderState and pass D3DRS_STENCILZFAIL as the first parameter and use D3DSTENCILCAPS for the second parameter.

In addition, your application can control what Direct3D does when both the stencil test and the z-buffer test pass. Call IDirect3DDevice9::SetRenderState and pass D3DRS_STENCILPASS as the first parameter. Again, the second parameter is D3DSTENCILCAPS.

A write mask can be applied to the values written into the stencil buffer. To set a stencil buffer write mask, call IDirect3DDevice9::SetRenderState and pass D3DRS_STENCILWRITEMASK as the first parameter. Pass the value of the write mask as the second parameter.

© 2002 Microsoft Corporation. All rights reserved.


Texture Wrapping State

The D3DRS_WRAP0 thru D3DRS_WRAP7 render states enable and disable u- and v-wrapping for various textures in the device's multitexture cascade. You can set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in first, second, third, and fourth directions of the texture. Use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default.

For a conceptual overview, see Texture Wrapping.

© 2002 Microsoft Corporation. All rights reserved.


Common Framework

This source code is furnished to help you get up and running with Microsoft® DirectX® quickly. It is intended to illustrate how Microsoft Direct3D® works, and reduce the time it takes to build simple applications that allow you to experiment. It is used by the samples in the software development kit (SDK). All of this source code is stored in the Samples\Multimedia\Common\Src directory, which can be installed during the SDK install.

This code is not intended to be incorporated into a production application, using a cut-and-paste operation, because the code is not designed for production. No attempt has been made to optimize it for performance. Very little error checking has been added because it obscures the functionality. Use this code to experiment with Direct3D and to better understand how it works.

Classes | Names
 | CD3DApplication
 | CD3DArcBall
 | CD3DCamera
 | CD3DFrame
 | CD3DFile
 | CD3DFont
 | CD3DMesh
 | CD3DScreenSaver
Functions | Names
 | D3DUtil_CreateTexture
 | D3DUtil_CreateVertexShader
 | D3DUtil_GetCubeMapVertex
 | D3DUtil_GetRotationFromCursor
 | D3DUtil_InitMaterial
 | D3DUtil_InitLight
 | D3DUtil_SetColorKey
 | D3DUtil_SetDeviceCursor
Structures | Names
 | D3DModeInfo
 | D3DWindowedModeInfo
 | D3DDeviceInfo
 | D3DAdapterInfo
 | MonitorInfo
 | RenderUnit
Macros | Names
Error Codes | Names

© 2002 Microsoft Corporation. All rights reserved.


Volume Fog Sample

Description

The Volume Fog sample shows the per-pixel density volumetric rendering technique. The fog volume is modeled as a polygonal mesh, and the density of the fog at every pixel is computed by subtracting the front side of the fog volume from the back side. The fog is mixed with the scene by accumulating an in/out test at every pixel, that is, back-facing fog polygons will add, while front-facing ones will subtract. If the value is nonzero, the scene intersects the fog and the scene's depth value is used. To get better results, this sample uses 12 bits of precision by encoding high and low bits in different color channels.

Path

Source: (SDK root)\Samples\C++\Direct3D\VolumeFog

Executable: (SDK root)\Samples\C++\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
J | Move object backward on the z-axis.
M | Move object forward on the z-axis.
H | Move object forward on the x-axis.
K | Move object backward on the x-axis.
N | Move object forward on the y-axis.
Y | Move object backward on the y-axis.

Camera controls:

Key | Action
LEFT | Slide left
RIGHT | Slide right
DOWN | Slide down
UP | Slide up
W | Move forward
S | Move backward
NUMPAD8 | Pitch down
NUMPAD2 | Pitch up
NUMPAD4 | Turn right
NUMPAD6 | Turn left
NUMPAD9 | Roll clockwise (CW)
NUMPAD7 | Roll counterclockwise (CCW)

The mouse is used in this sample to control the fog volume.

Programming Notes

Introduction

The article "Volumetric Rendering in Real-Time," printed in the 2001 Game Developers Conference Proceedings, covered the basis of volumetric depth rendering, but at the time of the writing, no pixel-shader-compliant hardware was available. This supplement describes a process designed to achieve two goals: to get more precision out of an 8-bit part, and to allow the creation of concave fog volumes.

Handling Concavity

Computing the distance of fog for the convex case was relatively simple. Recall that the front side of the fog volume was subtracted away from the back side (where the depth is measured in number of units from the camera). Unfortunately, this does not work with concave fog volumes because at any given pixel, it may have two back sides and two front sides. The solution is intuitive and has sound mathematical backing: Sum all of the front sides and subtract them from the summed back sides.

Computing concavity is as simple as adding the multiple front sides and subtracting them from the multiple back sides. Eight bits are not enough for this. Every bit added would allow another summation and subtraction, and allow for more complex fog scenes.

There is an important assumption being made about the fog volume. Is must be a continuous, orientable hull. That is, it cannot have any holes in it. Every ray cast through the volume must enter through hull the same number of times it exits.

Getting Higher Precision

Although most 3-D hardware handle 32 bits, it is really four 8-bit channels. The way most hardware works today, there is only one place where the fog depths could be summed up: the alpha blender. The alpha blender is typically used to blend on alpha textures by configuring the source destination to multiply against the source alpha, and the destination to multiply against the inverse alpha. However, they can also be used to add (or subtract) the source and destination color channels. Unfortunately, there is no way to perform a carry operation here: If one channel would exceed 255 for a color value, it simply saturates to 255. To perform higher bit precision additions on the alpha blending unit, the incoming data has to be formatted in a way that is compatible with the way the alpha blender adds. To do this, the color channels can hold different bits of the actual result, and most importantly, be allowed some overlap in their bits.

This sample uses the following scheme: The red channel will contain the upper eight bits and the blue channel will contain the lower four bits, plus three carry spots. The upper bit should not be used for reasons that are discussed later. So the actual value encoded is: Red times 16 plus Blue. Now, the alpha blender will add multiple values in this format correctly up to eight times before there is any possibility of a carry bit not propagating. This limits the fog hulls to ones that do not have concavity, where looking in any direction a ray might pass in and out of the volume more than eight times. Encoding the bits that will be added cannot be done with a pixel shader. There are two primary limitations. First, the color interpolators are 8 bit as well. Since the depth is computed on a per vertex level, this will not let higher bit values into the independent color channels. Even if the color channel had a higher precision, the pixel shader has no instruction to capture the lower bits of a higher bit value.

The alternative is to use a texture to hold the encoded depths. The advantage of this is twofold. First, texture interpolaters have much higher precision than color interpolaters. And second, no pixel shader is needed for the initial step of summing the front and back sides of the fog volume. It should be possible, on parts with at least 12-bit precision in the pixel shader, to embed the precision in a texture register instead. Unfortunately, most hardware limits the dimensions of textures. For example, 4096 is a typical limitation. This amounts to 12 bits of precision to be encoded in the texture. Twelve bits, however, is vastly superior to 8 bits and can make all the difference in making fog volumes practical. More precision could be obtained by making the texture a sliding window and breaking the object into sizable chunks that would index into that depth, but this sample does not go that far.

Setting it all up

Three important details remain: The actual summing of the fog sides, compensating for objects inside the fog, and the final subtraction. The summing is done in three steps.

First, the scene needs to be rendered to set a z-buffer. This will prevent fog pixels from being drawn that are behind some totally occluding objects. In a real application, this z could be shared from the pass that draws the geometry. The z-buffer is then write disabled so that fog writes will not update it.

After this, the summing is exactly as expected. The application simply draws all the forward facing polygons in one buffer, adding up their results, and then draws all the backward facing polygons in another buffer. There is one potential problem, however. In order to sum the depths of the fog volume, the alpha blend constants need to be set to 1 for the destination and 1 for the source, thereby adding the incoming pixel with the 1 already in the buffer.

Unfortunately, this does not take into account objects inside the fog that are acting as a surrogate fog cover. In this case, the scene itself must be added to the scene since the far end of the fog would have been rejected by the z-test.

At first, this looks like an easy solution. In the article, the buffers were set up so that they were initialized to the depth value of the scene. This way, fog depth values would replace any depth value in the scene if they were in front of it (that is, the z-test succeeds). But, if no fog was present, the scene would act as the fog cover.

This cannot be done for general concavity, however. While technically correct in the convex case, in the concave case there may be pixels at which the fog volumes are rendered multiple times on the front side and multiple sides on the back side. For these pixels, if there was part of an object in between fog layers than the front buffer would be the sum of n front sides, and the back side would be sum of n-1 back sides. But because the fog cover was replaced by the fog, there are now more entry points then exit points. The result is painfully obvious: parts of the scene suddenly loose all fog when they should have some.

The solution requires knowing which scenarios where the w-depth off the scene should be added and which scenarios the w-depth should be ignored. Fortunately, this is not difficult to find. The only situation where the w-depth should be added to the total fog depth are those pixels where the object is in between the front side of a fog volume and its corresponding back side.

The above question can be thought of as asking the question: did the ray ever leave the fog volume? Since the fog hulls are required to be continuous, then if the answer is no then part of the scene must have blocked the ray. This test can be performed by a standard inside/outside test.

To perform an inside/outside test each time a fog pixel is rendered, the alpha value is incremented. If the alpha values of the far fog distances is subtracted to the corresponding point on the near fog distance, then values greater then 1 indicate the ray stopped inside the volume. Values of 0 indicate that the ray left the fog volume.

To set up this test, the alpha buffer of the near and far w-depth buffers must be cleared to 0. Each time a fog pixel is rendered, the alpha will be incremented by the hex value 0x10. This value was used because the pixel shader must perform a 1 or 0 logical operation. A small positive value must be mapped to 1.0 in the pixel shader, a step that requires multiple shifts. Due to instruction count restraints, the initial value has to be at least 0x10 for the shifts to saturate a nonzero value to 1. The rest is straightforward: All the front sides and all the back sides are summed up in their independent buffers. The scene is also drawn in its own buffer. Then all three buffers are ran through the final pass where the w-depth of the scene is added on only if the differences of the alpha values is not 0.

This requires a lengthy pixel shader. Take care to avoid potential precision pitfalls. The following pixel shader performs the required math, although it requires every instruction slot of the pixel shader and nearly every register. Unfortunately, with no carry bit, there is no way to achieve a full 8-bit value at the end of the computation, so it must settle for 8.

ps.1.1
def c1, 1.0f,0.0f,0.0f,0.0f
def c4, 0.0f,0.0f,1.0f,0.0f

tex t0		// Near buffer B
tex t1		// Far buffer A
tex t2      // Scene buffer C

// input:
// b    = low bits (a)  (4 bits)
// r   = high bits (b) (8 bits)
// intermediate output:
// r1.b  = (a1 - a2) (can't be greater than 7 bits set)
// r1.r   = (b1 - b2)

sub r1.rgb,t1,t0
+sub_4x r1.a,t0,t1      // If this value is nonzero,
mov_4x r0.a,r1.a        //   there were not as many backs as
mad r1.rgb,r0.a,t2,r1   //   front and must add in the scene
dp3 t0.rgba,r1,c4       // Move red component into alpha

// Need to shift r1.rgb 6 bits.  This could saturate
//   to 255 if any other bits are set, but that is fine
//   because in this case, the end result of the subtract
//   would have to be saturated (you can't
//   subtract more than 127).
mov_x4 r1.rgb,r1
dp3_x4 t1.rgba,r1,c1   // Move into the alpha
add_x2  r0.a,t0.a,t1.a // The subtract was in 0-127
mov_d2   r0.a,r0.a     // Chop off last bit else banding
+mov r0.rgb,c3         // Load the fog color

This pixel shader gives an alpha value that represents the density of fog and loads the fog-color constant into the color channels. The alpha blending stage can now be used to blend on the fog.

Finally, there is one situation that can cause serious problems: clipping. If a part of the fog volume is clipped away by the camera because the camera is partially in the fog, then part of the scene might be in the fog. Previously, it was assumed the camera was either entirely in, or all the way out of the fog. This might not always be the case.

An alternative solution is to not allow polygons to get clipped. The vertex shader can detect vertices that would get clipped away and snap them to the near clip plane. The following vertex shader clips w-depths to the near clip plane, and z-depths to zero.

// Transform position into projection space
m4x4 r0,v0,c8
max r0.z,c40.z,r0.z     // Clamp to 0
max r0.w,c12.x,r0.w     // Clamp to near clip plane
mov oPos,r0

// Subtract the near clipping plane
add r0.w,r0.w,-c12.x

// Scale to give us the far clipping plane
mul r0.w,r0.w,c12.y

// Load depth into texture; don't care about y
mov oT0.xy,r0.w

This sample uses the sample framework code that is shared with other samples in the Microsoft® DirectX® software development kit (SDK). You can find the sample framework headers and source code in (SDK root)\DXSDK\Samples\C++\Common\Include and (SDK root)\DXSDK\Samples\C++\Common\Src.

© 2002 Microsoft Corporation. All rights reserved.


Working with Mouse Cursors

The mouse cursor methods enable the application to specify a color cursor by providing a surface that contains an image. The system will ensure that this cursor will be updated at half the display rate or more if the application's frame rate is slow. However, the cursor will never be updated more frequently than the display refresh rate.

The mouse cursor position is tied to the system cursor, appropriately scaled for the current display mode spatial resolution, but it can be moved explicitly by the application. This is analogous to the behavior of the Microsoft® Win32® application programming interface (API)–supported system mouse cursor. For more information about how to use a mouse cursor in your Microsoft Direct3D® application, see the following reference topics.

  • IDirect3DDevice9::ShowCursor
  • IDirect3DDevice9::SetCursorPosition
  • IDirect3DDevice9::SetCursorProperties

Direct3D ensures that the mouse is supported either by hardware implementations or by the Direct3D run time that performs hardware-accelerated blitting operations when calling IDirect3DDevice9::Present.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DBaseTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DBaseTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DBaseTexture9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DBaseTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DBaseTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DBaseTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DCubeTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time, specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with USAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DCubeTexture9::GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

See Also

IDirect3DBaseTexture9::SetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DCubeTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DCubeTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DCubeTexture9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DCubeTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DCubeTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DCubeTexture9::SetLOD communicates to the Microsoft® Direct3D® texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DCubeTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DCubeTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DCubeTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DIndexBuffer9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DIndexBuffer9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DIndexBuffer9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DIndexBuffer9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DIndexBuffer9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DIndexBuffer9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DResource9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time, specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with USAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DTexture9::GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

See Also

IDirect3DBaseTexture9::SetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DTexture9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DTexture9::SetLOD communicates to the Microsoft® Direct3D® texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DVertexBuffer9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DVertexBuffer9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DVertexBuffer9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DVertexBuffer9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVertexBuffer9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVertexBuffer9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DVolumeTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time, specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with USAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DVolumeTexture9::GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

See Also

IDirect3DBaseTexture9::SetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DVolumeTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DVolumeTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DVolumeTexture9::PreLoad silently does nothing.

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DVolumeTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DVolumeTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DVolumeTexture9::SetLOD communicates to the Microsoft® Direct3D® texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DVolumeTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority

© 2002 Microsoft Corporation. All rights reserved.


IDirect3DVolumeTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVolumeTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData

© 2002 Microsoft Corporation. All rights reserved.


D3DDECL_END Macro

Initialize the last vertex element in a vertex declaration array.

Syntax

#define D3DDECL_END() {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}

Remarks

This is used to initialize the last vertex element in a vertex declaration array.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DGETDATA_FLUSH Macro

This macro creates a value used by IDirect3DQuery9::Issue to flush query data.

Syntax

#define D3DGETDATA_FLUSH (1 << 0)

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DISSUE_BEGIN, D3DISSUE_END, D3DQUERYTYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DISSUE_BEGIN Macro

This macro creates a value used by IDirect3DQuery9::Issue to issue a query begin.

Syntax

#define D3DISSUE_BEGIN (1 << 1)

Remarks

D3DISSUE_BEGIN is valid for the following query type.

  • D3DQUERYTYPE_OCCLUSION

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DISSUE_END, D3DGETDATA_FLUSH, D3DQUERYTYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DISSUE_END Macro

This macro creates a value used by IDirect3DQuery9::Issue to issue a query end.

Syntax

#define D3DISSUE_END (1 << 0)

Remarks

This macro changes the query state to nonsignaled.

D3DISSUE_END is valid for the following query types.

  • D3DQUERYTYPE_VCACHE
  • D3DQUERYTYPE_RESOURCEMANAGER
  • D3DQUERYTYPE_VERTEXSTATS
  • D3DQUERYTYPE_EVENT
  • D3DQUERYTYPE_OCCLUSION

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DISSUE_BEGIN, D3DQUERYTYPE

© 2002 Microsoft Corporation. All rights reserved.


D3DPS_VERSION Macro

Create a pixel shader version token.

Syntax

#define D3DPS_VERSION(_Major,_Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DPS_VERSION(1,1)
1 | 2 | D3DPS_VERSION(1,2)
1 | 3 | D3DPS_VERSION(1,3)
1 | 4 | D3DPS_VERSION(1,4)
2 | 0 | D3DPS_VERSION(2,0)
3 | 0 | D3DPS_VERSION(3,0)

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DVS_VERSION Macro

Create a vertex shader version number token.

Syntax

#define D3DVS_VERSION(Major, Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DVS_VERSION(1,1)
2 | 0 | D3DVS_VERSION(2,0)
3 | 0 | D3DVS_VERSION(3,0)

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


D3DCOLOR

Defines the fundamental Microsoft® Direct3D® color type.

D3DCOLOR is defined as:

typedef DWORD D3DCOLOR

To use this type, include d3d9types.h in your project.

© 2002 Microsoft Corporation. All rights reserved.


D3DXCreateLine Function

Uses a left-handed coordinate system to create a line.

Syntax

HRESULT D3DXCreateLine(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXLINE* ppLine
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
ppLine
[out] Pointer to an ID3DXLine interface.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetLastSRT Method

Returns the previous scale, rotation, and translation values.

Syntax

HRESULT GetLastSRT(

    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotate,
    D3DXVECTOR3 *pTranslate
);

Parameters

pScale
[in] Returns the scale vector.
pRotate
[in] Returns the rotation quaternion.
pTranslate
[in] Returns the translate vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetName Method

Gets the name of the interpolator.

Syntax

LPCSTR GetName(VOID);

Return Value

Returns a pointer to the name that identifies the interpolator.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetPeriod Method

Gets the interpolator period.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

The value of the interpolator period.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXKeyFrameInterpolator::GetSRT Method

Returns the scale, rotation, and translation at a given time.

Syntax

HRESULT GetSRT(

    DOUBLE Time,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotate,
    D3DXVECTOR3 *pTranslate
);

Parameters

Time
[in] Time at which the interpolator should be queried.
pScale
[in] Returns the scale vector.
pRotate
[in] Returns the rotation quaternion.
pTranslate
[in] Returns the translate vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GenerateAdjacency Method

Generates adjacency information based on mesh indices.

Syntax

HRESULT GenerateAdjacency(

    FLOAT fEpsilon,
    DWORD* pAdjacency
);

Parameters

fEpsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft® Direct3D® device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetFVF Method

Get the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::CloneMesh Method

Creates a new patch mesh with the specified vertex declaration.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST D3DVERTEXELEMENT9* pDecl,
    LPD3DXPATCHMESH* ppCloneMesh
);

Parameters

Options
[in] Combination of one or more D3DXMESH flags that specify creation options for the mesh.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements that specify the vertex format for the vertices in the output mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface that represents the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXPatchMesh::CloneMesh converts the vertex buffer to the new vertex declaration. Entries in the vertex declaration that are new to the original mesh are set to 0. If the current mesh has adjacency, the new mesh will also have adjacency.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPatchMesh::GenerateAdjacency Method

Generates adjacency information based on mesh indices.

Syntax

HRESULT GenerateAdjacency(

    FLOAT fTolerance
);

Parameters

fTolerance
[in] Specifies that vertices that differ in position by less than the tolerance should be treated as coincident.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

This method determines which patches are adjacent (within the provided tolerance). This information is used internally to optimize tessellation.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST LPD3DVERTEXELEMENT9 pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GenerateAdjacency Method

Generates adjacency information based on mesh indices.

Syntax

HRESULT GenerateAdjacency(

    FLOAT fEpsilon,
    DWORD* pAdjacency
);

Parameters

fEpsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft® Direct3D® could not allocate sufficient memory to complete the call.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft® Direct3D® device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetFVF Method

Get the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    VOID **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NO_SYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer

© 2002 Microsoft Corporation. All rights reserved.


ID3DXPMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXPMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParent,
    UINT Index
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParent,
    LPCSTR pName
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParent,
    LPCSTR pSemantic
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name or the semantic index cast to an LPCSTR.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParent,
    UINT ElementIndex
);

Parameters

hParent
[in] Handle of the parent array parameter. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParent or ElementIndex are invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::SetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrix Method

Sets a nontransposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    CONST LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::GetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffect::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::SetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParent,
    UINT Index
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParent,
    LPCSTR pName
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParent,
    LPCSTR pSemantic
);

Parameters

hParent
[in] Handle of the parent structure parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name or the semantic index cast to an LPCSTR.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParent,
    UINT ElementIndex
);

Parameters

hParent
[in] Handle of the parent array parameter. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParent or ElementIndex are invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::SetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrix Method

Sets a nontransposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrix

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

See Also

ID3DXBaseEffect::GetMatrixArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTranspose

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    CONST LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know you buffer is large enough to contain the entire parameter, and want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For examples, see Getting and Setting Effect Values.

See Also

ID3DXBaseEffect::GetValue

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVector

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVectorArray

© 2002 Microsoft Corporation. All rights reserved.


ID3DXEffectCompiler::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader

© 2002 Microsoft Corporation. All rights reserved.


Header

Defines the application-specific header.

        template Header \
        { \
            < 3D82AB43-62DA-11cf-AB39-0020AF71E433 > \
            DWORD major; \
            WORD minor; \
            WORD flags; \
        }

© 2002 Microsoft Corporation. All rights reserved.


Counting Flow Control Instructions

Flow control instructions have special restrictions for how they count against instruction limits.

Vertex Shader 2_0

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
call |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Vertex Shader 2_x

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Vertex Shader 2_sw

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Vertex Shader 3_0

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Vertex Shader 3_sw

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Pixel Shader 2_0

No flow control instructions in ps_2_0.

Pixel Shader 2_x

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
rep, endrep |  |  |  |

Pixel Shader 2_sw

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Pixel Shader 3_0

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

Pixel Shader 3_sw

 | static depth | dynamic depth | call depth | loop/rep depth
if |  |  |  |
if_comp |  |  |  |
if pred |  |  |  |
call |  |  |  |
callnz |  |  |  |
callnz pred |  |  |  |
break |  |  |  |
break_comp |  |  |  |
break pred |  |  |  |
loop, endloop |  |  |  |
rep, endrep |  |  |  |

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader ALU

The diagram below shows the parallel pipeline structure of a pixel shader arithmetic logic unit (ALU). The left side is the vector pipeline, which operates on vector data. Vector data is also called color data and contains three channels (RGB) of data. The right side is the scalar pipeline, which operates on a single alpha data value. The pipeline is commonly referred to by the data type operated on, so the vector pipeline is commonly called the color pipe and the scalar pipeline is commonly called the alpha pipe.

Pixel shader arithmetic logic unit diagram

The blocks are identified below.

  • Input Registers - Pixel Shader Registers provide the RGBA input data for a pixel shader.
  • Component Copy - Source Register Selectors copy data from one channel into other channels. This is commonly called swizzling.
    • Modify Data - Source Register Modifiers modify data read from source registers before an instruction is run.
    • Execute Instruction - Pixel Shader 1_X are used to perform arithmetic and texture address operations on the pixel data. The color and alpha pipes do not have to run the same instruction or have the same source registers. For pixel shader version 1_4, destination registers may also be different across the two pipes.
    • Modify Result - Instruction Modifiers modify the result of the instruction before it is written to an output register.
  • Masking - Destination Register Write Masks control which components of the destination register are written by the instruction.
  • Output Register - Output Register - At the end of the shader, pixel shader register r0 contains the output color.

© 2002 Microsoft Corporation. All rights reserved.


Pixel Shader Texture Addressing

Texture addressing is the mechanism by which texture coordinates are either retrieved directly or used to sample data from a texture.

Texture coordinates can be supplied as part of the vertex format or can be read from certain kinds of texture maps. Texture coordinates are sometimes referred to as TCs. A 2-D texture map is addressed, or looked up, using (UV) coordinates. A 3-D texture map (cube map or volume map) is addressed using (UVW) texture coordinates. Alternately, texture coordinates can be used directly, with no lookup.

Sampling occurs when a texture coordinate is used to address the texel data at a particular location. This is also commonly referred to as performing a texture lookup. In order to sample a texture, it must first be associated with a texture stage. The actual data sampled at the texture coordinate address is controlled by four things.

  1. The pixel shader texture addressing instruction.
  2. The texture coordinates.
  3. The texture set at a texture stage.
  4. The texture sampling attributes set in the texture stage states.

The following diagram shows ways that texture coordinates are used for texture addressing.

Pixel shader texture addressing diagram

For pixel shader version 1_1 to 1_3, texture coordinates are used in three ways:

  • Texture coordinates are used as texture coordinate data. No texture lookup is performed. No texture sampling is done. The texture register is simply loaded with the texture coordinate data.
  • The texture sampler samples a texture at the given texture coordinates. The texture is set at a texture stage. The texture is sampled according to the sampling attributes in the texture stage states. A texture coordinate set and the texture stage number to sample from always correspond to the instruction's destination register number in pixel shader version 1_1 to 1_3.
  • Certain texture addressing instructions in pixel shader version 1_1 to 1_3, such as texbem and texm3x3spec, perform various transformations on input texture coordinates to produce new texture coordinates for texture sampling. In two cases (texdp3 and texm3x3 instructions), a transformation is applied, but the result is passed directly to the destination register without doing any texture sampling.

For pixel shader version 1_4, the texture registers (t#) have a different meaning than previous pixel shader versions. They contain texture coordinates so they should be thought of as texture coordinate registers. These texture coordinate registers are read only (used as source parameters for texture addressing instructions) and are not available to arithmetic instructions.

Having texture coordinates in their own register means that the texture coordinate set and the texture stage number can be different in pixel shader version 1_4 texture addressing instructions. The texture stage number from which to sample is determined by the destination register number, but the texture coordinate set is determined by the new source (t#) register specified.

The "Modify TCs" box in the previous diagram does not apply to pixel shader version 1_4 because modification of texture coordinates before texture sampling is accomplished using standard arithmetic instructions, followed by a dependent read. Dependent reads are described in the following diagram and text.

Pixel shader dependent read diagram

Often, it is useful to perform some operation on texture coordinates before using them to sample a texture. This is referred to as a dependent read. The term "dependent" indicates that the texture data that gets sampled depends on some result computed in the pixel shader.

For pixel shader version 1_1 to 1_3, dependent reads are limited to a texture addressing instruction using the result of a previous texture addressing instruction as a source parameter. For pixel shader version 1_4, the dependent reads are much more flexible in that the texture coordinates for a texture sample may be derived from the result of previous texture addressing instructions and/or arbitrary pixel shader arithmetic instructions. Dependent reads in pixel shader version 1_4 always involve an (r#) registers being used as the texture coordinates for a texture address instruction. This means that the dependent read only occurs in phase 2. For more information about ordering arithmetic and texture addressing instructions within a shader, see Instruction Flow.

© 2002 Microsoft Corporation. All rights reserved.


Counting Instructions

Each shader has a maximum number of instructions allowed. Five types of instructions can be used in a shader: version, constant definition, phase, arithmetic, and texture address. Arithmetic and texture addressing instructions count toward the total number of instructions allowed. Phase, def, and version instructions do not count. These are summarized in the following table.

Instruction type | Version
 | 1_1 | 1_2 | 1_3 | 1_4 phase 1 | 1_4 phase 2
Version | * | * | * | * | N/A
Constant definition | * | * | * | * | N/A
Phase | N/A | N/A | N/A | * | *
Arithmetic | 8 | 8 | 8 | 8 | 8
Texture address | 4 | 4 | 4 | 6 | 6
Total | 12 | 12 | 12 | 14 | 14

*Version, constant definition, and phase instructions do not count toward instruction limits.

N/A Not applicable. The phase instruction applies only to pixel shader version 1_4. The version and constant definition instructions can be used only in phase 1.

Instruction count exceptions for pixel shader versions 1_1, 1_2, 1_3

  • texbem counts as one texture address instruction.
  • texbeml counts as one texture address instruction plus one arithmetic instruction.
  • For pixel shader version 1_2 and 1_3, both cmp and dp4 count as two instructions. Unfortunately, this was discovered too late in the development cycle and therefore is not validated properly when calling CreatePixelShader. They are incorrectly being counted as only consuming one instruction. Be sure to manually count each of these instructions as two instructions toward the maximum instruction count. For more information about instruction counts, see Counting Instructions.

Instruction count exceptions for pixel shader version 1_4

  • In version 1_4, only one phase instruction (also commonly called the phase marker) can be used per shader.
  • Version 1_4 allows 14 instructions in both phase 1 and phase 2, for a total of 28 instructions. If no phase marker is specified, the default is phase 2 and the total instruction count is 14.

© 2002 Microsoft Corporation. All rights reserved.


Instruction Pairing

The pixel shader processor has two parallel pipelines: one for vector processing (RGB) and one for scalar processing (alpha). As a result, pixel shaders allow potentially different arithmetic operations to be performed concurrently in the RGB and alpha pipes.

A destination Register Write Masks can affect how the two pipelines are allocated, but there can be ambiguities in the order of operations unless explicit pairing syntax is used. The following table illustrates the destination register write masks and their associated pipe.

Destination register write mask | Pipe
.a | The operation is in the scalar pipe.
.rgb | The operation is in the vector pipe.
.rgba | The operation is in both the scalar and vector pipes. It already counts as a pair.

Pairing, or co-issuing, is indicated by a plus sign (+) preceding the second instruction of the pair.

mul r0.rgb, t0, v0    // Component-wise multiply of the colors.
+ add r1.a, r1, c2    // Add an alpha component at the same time.

The dot product instructions are a special case. They are vector operations and are always run in the vector pipeline. However, you still have the option to specify a different instruction in the scalar pipe and still get pairing.

dp3 r0.rgb, t0, v0
+ mul r0.a, r1, c2

The destination register for co-issued instruction pairs can be different.

© 2002 Microsoft Corporation. All rights reserved.


Instruction Flow

Pixel shader versions 1_1, 1_2, and 1_3 allow four types of Pixel Shader 1_X. The instructions must appear in the order shown below.

Pixel shader instruction flow diagram for versions 1_1 to 1_3

Pixel shader version 1_4 adds a phase instruction that allows double the number of texture addressing and arithmetic instructions. The shader is separated into phase 1 and phase 2 by a phase marker. Each phase begins with up to six texture instructions, followed by up to eight arithmetic instructions. If a shader does not contain a phase marker, the shader behaves as if all the instructions are phase 2 instructions.

Pixel shader instruction flow diagram for version 1_4

The structure of a pixel shader version 1_4 shader is therefore:

  • Version instruction (ps_1_4)
  • Constant instructions
  • Up to six texture addressing instructions
  • Up to eight arithmetic instructions
  • Phase marker
  • Up to six texture addressing instructions
  • Up to eight arithmetic instructions

The unfortunate side-effect of the phase transition is that the alpha component of temporary registers are unset or uninitialized during the transition. For additional information, see the phase instruction.

© 2002 Microsoft Corporation. All rights reserved.


Order of Operations

Pixel shaders instructions can be modified by a combination of source register modifiers, instruction modifiers, and destination register write masks. The result of the instruction is determined by the order in which they are run. The sequence shown below identifies the order in which source register modifiers, instruction modifiers, and destination register write masks are run.

  1. Run Source Register Selectors and source Register Modifiers.
  2. Run instruction.
  3. Run Instruction Modifiers.
  4. Update destination register based on destination Register Write Masks.
Note The saturate instruction modifier can be combined with any one of the other instruction modifiers. The Source Register Selectors and Register Modifiers may be combined.

© 2002 Microsoft Corporation. All rights reserved.


add (Pixel Shader)

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


bem (Pixel Shader)

Apply a fake bump environment-map transform.

Syntax

bem dst.rg, src0, src1

where

  • dst.rg dst is the destination register. The red and green component write mask must be used.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
bem |  |  |  | x |  |  |  |  |

This instruction performs the following calculation.

(Given n == dest register #)
dest.r = src0.r + D3DTSS_BUMPENVMAT00(stage n) * src1.r
                + D3DTSS_BUMPENVMAT10(stage n) * src1.g

dest.g = src0.g + D3DTSS_BUMPENVMAT01(stage n) * src1.r
                + D3DTSS_BUMPENVMAT11(stage n) * src1.g

Rules for using bem:

  1. bem must appear in the first phase of a shader (that is, before a phase marker).
  2. bem consumes two arithmetic instruction slots.
  3. Only one use of this instruction is allowed per shader.
  4. Destination writemask must be .rg /.xy.
  5. This instruction cannot be co-issued.
  6. Aside from the restriction that destination write mask be .rg, modifiers on source src0, src1, and instruction modifiers are unconstrained.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


cmp (Pixel Shader)

Conditionally chooses between src1 and src2, based on the comparison src0 >= 0. The comparison is done per channel.

Syntax

cmp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cmp | x | x | x | x | x | x | x | x | x

There are a few additional limitations for versions 1_2 and 1_3:

  • Each shader can use up to a maximum of three cmp instructions.
  • The destination register cannot be the same as any of the source registers.

This example does a four-channel comparison.

ps_1_4
def c0, -0.6, 0.6, 0, 0.6
def c1  0,0,0,0
def c2  1,1,1,1

mov r1, c1
mov r2, c2

cmp r0, c0, r1, r2   // r0 is assigned 1,0,0,0 based on the following:

// r0.x = c2.x because c0.x <  0
// r0.y = c1.y because c0.y >= 0
// r0.z = c1.z because c0.z >= 0
// r0.w = c1.w because c0.w >= 0

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


cnd (Pixel Shader)

Conditionally chooses between src1 and src2, based on the comparison src0 > 0.5.

Syntax

cnd dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cnd | x | x | x | x |  |  |  |  |

For versions 1_1 to 1_3, src0 must be r0.a.

// Version 1.1 to 1.3
if (r0.a > 0.5)
  dest = src1
else
  dest = src2

Version 1.4 compares each channel separately.

for each component in src0
{
   if (src0.component > 0.5)
     dest.component = src1.component
   else
     dest.component = src2.component
}

These examples show a four-channel comparison done in a version 1_4 shader, as well as a single-channel comparison possible in a version 1_1 shader.

ps_1_4
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1

cnd r1, c0, c1, c2   // r0 contains 1,1,1,0 because
// r1.x = c2.x because c0.x <= 0.5
// r1.y = c2.y because c0.y <= 0.5
// r1.z = c2.z because c0.z <= 0.5
// r1.w = c1.w because c0.w >  0.5

Version 1_1 to 1_3 compares against the replicated alpha channel of r0 only.

ps_1_1
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1
mov r0, c0
cnd r1, r0.a, c1, c2   // r1 gets assigned 0,0,0,0 because
                       //   r0.a > 0.5, therefore r1.xyzw = c1.xyzw

This example compares two values, A and B. The example assumes A is loaded into v0 and B is loaded into v1. Both A and B must be in the range of -1 to +1, and since the color registers (vn) are defined to be between 0 and 1, the restriction happens to be satisfied in this example.

ps_1_1                // version instruction
sub r0, v0, v1_bias   // r0 = A - (B - 0.5)
cnd r0, r0.a, c0, c1  // r0 = ( A > B ? c0 : c1 )

// The result in r0 is c0 if A > B. Otherwise, the result in r0 is c1.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


def (Pixel Shader)

Defines pixel shader floating-point constants.

Syntax

def dest, fVvalue1, fValue2, fValue3, fValue4

Where:

  • dst is the destination register.
  • fValue1 to fValue4 are floating-point values..

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x | x | x | x

There are two ways to set a floating-point constant in a pixel shader.

  1. Use def to define the constant directly inside a shader.
  2. Use the API to set a constant with IDirect3DDevice9::SetPixelShaderConstantF.

The def instruction defines a shader constant whose value is loaded any time a shader is set to a device. These are called "immediate constants." Immediate constants take precedence over constants set by the application programming interface (API) method.

  • Must appear before the first arithmetic or addressing instruction in shader.
  • Can be intermixed with dcl instructions (which are the other type of instruction that resides at the beginning of a shader).
  • dst register must be a constant register (cn).
  • Write mask must be full (default).
  • If a constant register is defined multiple times in a shader, the last one persists.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dp3 (Pixel Shader)

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = unused;

In version 1_X, this instruction cannot be co-issued.

In version 1_X, this instruction does not automatically clamp the output result between zero and one. If clamping is necessary, use the Instruction Modifiers.

This instruction runs in the vector pipeline, always writing out to the color channels. For version 1_4, this instruction still uses the vector pipeline but may write to any channel.

dp3 r0.rgb, t0, v0            // Copy scalar result to RGB components.

An instruction with a destination register RGB write mask may be co-issued with dp3 as shown below.

dp3 r0.rgb, t0, v0            // Copy scalar result to color components.
+mov r2.a, t0                 // Copy alpha component from t0 in parallel.

The dp3 instruction can be modified using the Signed Scaling input argument modifier (_bx2) applied to its input arguments if they are not already expanded to signed dynamic range. For a lighting shader, the saturate instruction modifier (_sat) is often used to clamp the negative values to black, as shown in the following example.

dp3_sat r0, t0_bx2, v0_bx2    // Here t0 is a bump map, v0 contains the light direction.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dp4 (Pixel Shader)

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 | x | x | x | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = unused;

In version 1_X, this instruction cannot be co-issued.

In version 1_X, this instruction does not automatically clamp the output result between zero and one. If clamping is necessary, use the Instruction Modifiers.

In version 1_X, this instruction runs in both the vector and alpha pipeline.

Limitations for versions 1_2 and 1_3:

  • Each shader can use up to a maximum of fourdp instructions.
  • Each dp4 instruction counts as two arithmetic instructions.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


lrp (Pixel Shader)

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp | x | x | x | x | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest = src0 * src1 + (1-src0) * src2
// which is the same as
dest = src2 + src0 * (src1 - src2)

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mad (Pixel Shader)

Multiply and add instruction. Sets the destination register to (src0 * src1) + src2.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mov (Pixel Shader)

Move data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x |  | x | x | x | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mul (Pixel Shader)

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


nop (Pixel Shader)

No operation is performed.

Syntax

nop

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


phase (Pixel Shader)

The phase instruction marks the transition between phase 1 and phase 2. If no phase instruction is present, the entire shader runs as if it is a phase 2 shader.

This instruction applies to version 1_4 only.

Syntax

phase

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
phase |  |  |  | x |  |  |  |  |

Shader instructions that occur before the phase instruction are phase 1 instructions. All other instructions are phase 2 instructions. By having two phases for instructions, the maximum number of instructions per shader is increased.

The unfortunate side-effect of the phase transition is that the alpha component of temporary registers do not persist across the transition. In other words, the alpha component must be reinitialized after the phase instruction.

Example

This example shows how to group instructions as phase 1 or phase 2 instructions within a shader.

The phase instruction is also commonly called the phase marker because it marks the transition between phase 1 and 2 instructions. In a version 1_4 pixel shader, if the phase marker is not present, the shader is run as if it is running in phase 2. This is important because there are differences between phase 1 and 2 instructions and register availability. The differences are noted throughout the reference section.

ps_1_4
  // Add phase 1 instructions here.

phase
  // Add phase 2 instructions here.

© 2002 Microsoft Corporation. All rights reserved.


ps (Pixel Shader)

This instruction specifies the shader version number and works on all shader versions.

Syntax

ps_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1, 2, 3, 4
2 | 0, x (extended), sw (software)
3 | 0, sw (software)

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ps | x | x | x | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a pixel shader.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 pixel shader.

ps_1_1

This partial example declares a version 1_4 pixel shader.

ps_1_4

© 2002 Microsoft Corporation. All rights reserved.


sub (Pixel Shader)

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest = src0 - src1

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


tex (Pixel Shader)

Loads the destination register with color data (RGBA) sampled from a texture.

The texture must be bound to a particular texture stage (n) using IDirect3DDevice9::SetTexture. Texture sampling is controlled by IDirect3DDevice9::SetSamplerState.

Syntax

tex (Pixel Shader) dest

Registers

dest
Destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
tex | x | x | x | x

The destination register number specifies the texture stage number.

Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes.

The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. The default association is a one-to-one mapping between texture stage number and texture coordinate declaration order. This means that the first set of texture coordinates defined in the vertex format are by default associated with texture stage 0.

Texture coordinates may be associated with any stage using two techniques. When using a fixed function vertex shader or the fixed function pipeline, the texture stage state flag TSS_TEXCOORDINDEX can be used in IDirect3DDevice9::SetTextureStageState to associate coordinates to a stage. Otherwise, the texture coordinates are output by the vertex shader oTn registers when using a programmable vertex shader.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texbem (Pixel Shader)

Apply a fake bump environment-map transform. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), and a 2-D bump environment matrix.

Syntax

texbem (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbem | x | x | x

The red and green color data in the src register is interpreted as the perturbation data (du,dv).

This instruction transforms red and green components in the source register using the 2-D bump environment-mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number, and is used to sample the current texture stage.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain signed format data. Mixed format data works only if the first two channels contain signed data. For more information about surface formats, see D3DFORMAT.

This can be used for a variety of techniques based on address perturbation, including fake per-pixel environment mapping and diffuse lighting (bump mapping).

When using this instruction, texture registers must follow the following sequence.

// The texture assigned to stage t(n) contains the (du,dv) data.
// The texture assigned to stage t(m) is sampled.
tex     t(n)
texbem  t(m),  t(n)      where m > n

The calculations done within the instruction are shown below.

// 1. New values for texture addresses (u',v') are calculated.
// 2. Sample the texture using (u',v').

u' = TextureCoordinates(stage m)u +
      D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
      D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m)
// using (u',v') as coordinates.

Register data that has been read by a texbem (Pixel Shader) or texbeml instruction cannot be read later, except by another texbem (Pixel Shader) or texbeml.

// This example demonstrates the validation error caused by t0 being reread:
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; define t0 to get a 2-tuple DuDv
texbem t1, t0       ; compute (u',v')
                    ; sample t1 using (u',v')
mov r0, t1          ; output result

texbem (Pixel Shader) requires the following textures in the following texture stages.

Stage 0 is assigned a bump map with (du, dv) perturbation data.

Stage 1 uses a texture map with color data.

This instruction sets the matrix data on the texture stage that is sampled.

This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texbeml (Pixel Shader)

Apply a fake bump environment-map transform with luminance correction. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), a 2-D bump environment matrix, and luminance.

Syntax

texbeml (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbeml | x | x | x

The red and green color data in the src register is interpreted as the perturbation data (du,dv). The blue color data in the src register is interpreted as the luminance data.

This instruction transforms the red and green components in the source register using the 2-D bump environment mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number. A luminance correction is applied using the luminance value and the bias texture stage values. The result is used to sample the current texture stage.

This can be used for a variety of techniques based on address perturbation such as fake per-pixel environment mapping.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain mixed format data. For more information about surface formats, see D3DFORMAT.

// When using this instruction, texture registers must follow
//   the following sequence.
// The texture assigned to stage tn contains the (du,dv) data.
// The texture assigned to stage t(m) is sampled.
tex     t(n)
texbeml t(m),  t(n)      where m > n

This example shows the calculations done within the instruction.

// 1. New values for texture addresses (u',v') are calculated.
// 2. Sample the texture using (u',v').
// 3. Luminance correction is applied.

u' = TextureCoordinates(stage m)u +
    D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
    D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m) using (u',v') as coordinates.

t(m)RGBA = t(m)RGBA*
    [(t(n)B * D3DTSS_BUMPENVLSCALE(stage m)) +
        D3DTSS_BUMPENVLOFFSET(stage m)]

Register data that has been read by a texbem or texbeml (Pixel Shader) instruction cannot be read later, except by another texbem or texbeml (Pixel Shader).

// This example demonstrates the validation error caused by
//   t0 being reread.
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; define t0 to get a 2-tuple DuDv
texbeml t1, t0      ; compute (u',v')
                    ; apply luminance correction
                    ; sample t1 using (u',v')
mov r0, t1          ; output result

This example requires the following textures in the following texture stages.

Stage 0 is assigned a bump map with (du, dv) perturbation data.

Stage 1 is assigned a texture map with color data.

texbeml (Pixel Shader) sets the matrix data on the texture stage that is sampled.

This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texcoord (Pixel Shader)

Interprets texture coordinate data (UVW1) as color data (RGBA).

Syntax

texcoord (Pixel Shader) dest

Registers

dest
Destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcoord | x | x | x

This instruction interprets the texture coordinate set (UVW1) corresponding to the destination register number as color data (RGBA). If the texture coordinate set contains fewer than three components, the missing components are set to 0. The fourth component is always set to 1. All values are clamped between 0 and 1.

The advantage of texcoord (Pixel Shader) is that it provides a way to pass vertex data interpolated at high precision directly into the pixel shader. However, when the data is written into the destination register, some precision will be lost, depending on the number of bits used by the hardware for registers.

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

Any texture data (such as position, normal, and light source direction) can be mapped by a vertex shader into a texture coordinate. This is done by associating a texture with a texture register using ID3DXBaseEffect::SetTexture and by specifying how the texture sampling is done using IDirect3DDevice9::SetTextureStageState. If the fixed function pipeline is used, be sure to supply the TSS_TEXCOORDINDEX flag.

This instruction is used as follows:

texcoord tn

A texture register (tn) contains four color values (RGBA). The data can also be thought of as vector data (xyzw). texcoord (Pixel Shader) will retrieve three of these values (xyz) from texture coordinate set x, and the fourth component (w) is set to 1. The texture address is copied from the texture coordinate set n. The result is clamped between 0 and 1.

Examples

This example is for illustration only. The C code accompanying the shader has not been optimized for performance. It can use helper functions from the Sample Framework. The sample framework is the foundation on which many of the samples are built.

Here is an example shader using texcoord (Pixel Shader).

ps_1_1        ; version instruction
texcoord t0   ; declare t0 hold texture coordinates,
              ; which represent rgba values in this example
mov r0, t0    ; move the color in t0 to output register r0

The rendered output from the pixel shader is shown below. The (u,v,w,1) coordinate values map to the (rgb) channels. The alpha channel is set to 1. At the corners of the image, coordinate (0,0,0,1) is interpreted as black, (1,0,0,1) is red, (0,1,0,1) is green, and (1,1,0,1) contains green and red, producing yellow.

Image of pixel shader output from texture coordinate data

Additional code is required to use this shader and an example scenario is shown below.

// This code creates the shader from a file. The contents of
//   the shader file can also be supplied as a text string.
TCHAR               strPShaderPath[512];
LPD3DXBUFFER        pCode;
DXUtil_FindMediaFile( strPShaderPath, _T("shaderFile.txt") );

// Assemble the vertex shader from the file.
D3DXAssembleShaderFromFile( strPShaderPath, 0, NULL, &pCode, NULL );
m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),
                   &m_hPixelShader );
pCode->Release();

// This code defines the object vertex data.
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_TEX1|TEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     u1    v1
    { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, },
    { +1.0f, -1.0f, 0.0f, 1.0f, 0.0f, },
    { +1.0f, +1.0f, 0.0f, 1.0f, 1.0f, },
    { -1.0f, +1.0f, 0.0f, 0.0f, 1.0f, },
};

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texcrd (Pixel Shader)

Copies texture coordinate data from the source texture coordinate iterator register as color data in the destination register.

Syntax

texcrd (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcrd | x

This instruction interprets coordinate data as color data (RGBA).

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

When using texcrd (Pixel Shader), keep in mind the following detail about how data is copied from the source register to the destination register. The source texture coordinate register (t#) holds data in the range [-D3DCAPS9.MaxTextureRepeat, D3DCAPS9.MaxTextureRepeat], while the destination register (r#) can hold data only in the (likely smaller) range [-D3DCAPS9.PixelShader1xMaxValue, D3DCAPS9.PixelShader1xMaxValue]. Note that for pixel shader version 1_4, D3DCAPS9.PixelShader1xMaxValue must be a minimum of eight. The texcrd (Pixel Shader) instruction, in the process of clamping source data that is out of range of the destination register, is likely to behave differently on different hardware. The first pixel shader version 1_4 hardware on the market will perform a special clamp for values outside of range. This clamp is designed to produce a number that can fit into the destination register, but also to preserve texture addressing behavior for out-of-range data (see D3DTEXTUREADDRESS) if the data were to be subsequently used for texture sampling. However, new hardware from different manufacturers might not exhibit this behavior and might just chop data to fit the destination register range. Therefore, the safest course of action when using pixel shader version 1_4 texcrd (Pixel Shader) is to supply texture coordinate data only into the pixel shader that is already within the range [-8,8] so that you do not rely on the way hardware clamps.

Unlike texcoord, texcrd (Pixel Shader) does not clamp values between 0 and 1.

Rules for using texcrd (Pixel Shader):

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within a texcrd (Pixel Shader) or texld instruction.
  2. The fourth channel result of texcrd (Pixel Shader) is unset/undefined in all cases.
  3. The third channel is unset/undefined for the xyw_dw case.

Examples

The complete set of allowed syntax for texcrd (Pixel Shader), taking into account all valid source modifier/selector and destination write mask combinations, is shown below. Note that the .rgba and .xyzw notation can be used interchangeably.

Copies first three channels of texture coordinate iterator register, t(n), into r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyz

// Produces the same result as the previous instruction.
texcrd  r(m).rgb, t(n)

Puts first, second, and fourth components of t(n) into first three channels of r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyw

Here is a projective divide example using the _dw modifier.

This example copies x/w and y/w from t(n) into the first two channels of r(m). The third and fourth channels of r(m) are uninitialized. Any data previously written to the third channel of r(m) will be lost. Data in the fourth channel of r(m) is lost due to the phase marker. For version 1_4, the D3DTTFF_PROJECTED flag is ignored.

texcrd  r(m).rg,  t(n)_dw.xyw

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texdepth (Pixel Shader)

Calculate depth values to be used in the depth buffer comparison test for this pixel.

Syntax

texdepth (Pixel Shader) dest

Registers

dest
Destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdepth | x

This instruction uses r5.r / r5.g in the depth buffer comparison test for this pixel. The data in the blue and alpha channels is ignored. If r5.g = 0, the result of r5.r / r5.g = 1.0.

Temporary register r5 is the only register that this instruction can use.

After executing this instruction, temporary register r5 is unavailable for additional use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth or texdepth (Pixel Shader) will be used for each of the subpixel depth comparison tests.

Example

Here is an example using texdepth.

ps_1_4
texld  r0, t0        // Sample texture from texture stage 0 (dest
                     //   register number) into r0.
                     // Use texture coordinate data from t0.
texcrd r1.rgb, t1    // Load a second set of texture coordinate data into r1.
add    r5.rg, r0, r1 // Add the two sets of texture coordinate data.
phase                // Phase marker, required when using texdepth instruction.
texdepth  r5         // Calculate pixel depth as r5.r / r5.g.
                     // Do other color calculations with shader output r0.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texdp3 (Pixel Shader)

Performs a three-component dot product between data in the texture register number and the texture coordinate set corresponding to the destination register number.

Syntax

texdp3 (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3 | x | x

Texture registers must use the following sequence.

tex    t(n)        // Define tn as a standard 3-vector (tn must be
                   //   defined in some way before texdp3 uses it).
texdp3 t(m), t(n)  // where m > n
                   // Perform a three-component dot product between tn and
                   //   the texture coordinate set m. The scalar result is
                   //   replicated to all components of t(m).

Here is more detail about how the dot product is accomplished.

The texdp3 (Pixel Shader) instruction performs a three-component dot product and replicates it to all four color channels.

t(m)RGBA = TextureCoordinates(stage m)UVW • t(n)RGB

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texdp3tex (Pixel Shader)

Performs a three-component dot product and uses the result to do a 1-D texture lookup.

Syntax

texdp3tex (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3tex | x | x

Texture registers must use the following sequence.

tex       t(n)        // Define tn as a standard 3-vector (tn must be
                      // defined in some way before texdp3tex uses it).
texdp3tex t(m), t(n)  // where m > n.
                      // Perform a three-component dot product between t(n) and
                      // the texture coordinate set m. Use the scalar result to
                      // do a 1-D texture lookup at texturestage m and place
                      // the result in t(m).

Here is more detail about how the dot product and texture lookup are done.

The texdp3tex instruction performs a three-component dot product.

u' = TextureCoordinates(stage m)UVW • t(n)RGB

The result is used to sample the texture at texture stage m by performing a 1-D lookup.

t(m)RGBA = TextureSample(stage m)RGBA using (u',0,0) as coordinates.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texkill (Pixel Shader)

Cancels rendering of the current pixel if any of the first three components (UVW) of the texture coordinates is less than zero.

Syntax

texkill (Pixel Shader) src

Registers

src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texkill | x | x | x

texkill (Pixel Shader) does not sample any texture. It operates on the first three components of the texture coordinates given by the source register number. For ps_1_4, texkill (Pixel Shader) operates on the data in the first three components of the source register.

You can use this instruction to implement arbitrary clip planes in the rasterizer.

When using vertex shaders, the application is responsible for applying the perspective transform. This can cause problems for the arbitrary clipping planes because if it contains anisomorphic scale factors, the clip planes need to be transformed as well. Therefore, it is best to provide an unprojected vertex position to use in the arbitrary clipper, which is the texture coordinate set identified by the texkill (Pixel Shader) operator.

This instruction is used as follows:

texkill tn

// The pixel masking is accomplished as follows:
if ( the x,y,z components of TextureCoordinates(stage n)UVWQ < 0 )

  cancel pixel render

For pixel shader 1_1, 1_2, and 1_3, texkill (Pixel Shader) operates on the texture coordinate set given by the source register number. In version 1_4, however, texkill (Pixel Shader) operates on the data contained in the texture coordinate iterator register (tn) or in the temporary register (rn) that has been specified as the source.

When multisampling is enabled, any antialiasing effect achieved on polygon edges due to multisampling will not be achieved along any edge that has been generated by texkill. The pixel shader runs once per pixel.

Examples

This example is for illustration only.

This example masks out pixels that have negative texture coordinates. The pixel colors are interpolated from vertex colors provided in the vertex data.

// The shader is shown below.
ps_1_1       // Version instruction
texkill t0   // Mask out pixel using texture coordinates from stage 0.
mov r0, v0   // Move the diffuse color in v0 to r0.

// The rendered output from the pixel shader is shown below.

The texture coordinates range from -0.5 to 0.5 in u, and 0.0 to 1.0 in v. This instruction causes the negative u values get masked out. The first image shows the vertex color applied to the quad without the texkill (Pixel Shader) instruction applied. The second image shows the result of the texkill instruction. The pixel colors from the texture coordinates below 0 (where x goes from -0.5 to 0.0) are masked out. The background color (white) is used where the pixel color is masked.

Vertex color applied to the quad without the texkill instruction Output with the texkill instruction applied

The texture coordinate data is declared in the vertex data declaration in this example.

struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DTEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z    color         u1,    v1
    { -1.0f, -1.0f, 0.0f, 0xffff0000, -0.5f,  1.0f, },
    {  1.0f, -1.0f, 0.0f, 0xff00ff00,  0.5f,  1.0f, },
    {  1.0f,  1.0f, 0.0f, 0xff0000ff,  0.5f,  0.0f, },
    { -1.0f,  1.0f, 0.0f, 0xffffffff, -0.5f,  0.0f, },

};

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texld (Pixel Shader)

Loads the destination register with color data (RGBA) sampled using the contents of the source register as texture coordinates. The sampled texture is the texture associated with the destination register number.

texld dest, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dest | Destination register |  |  |  | x | 1.4, 2.0
src | Source register |  |  | x |  | 1.4 phase 1
 |  |  |  | x | x | 1.4 phase 2, 2.0

When using r(n) as a source register, the first three components (XYZ) must have been initialized in the previous phase of the shader.

To learn more about registers, see Registers - ps_1_X.

Remarks

This instruction samples the texture in the texture stage associated with the destination register number. The texture is sampled using texture coordinate data from the source register.

The syntax for the texld and texcrd instructions expose support for a projective divide with a Texture Register Modifier. For pixel shader version 1.4, the D3DTTFF_PROJECTED texture transform flags is always ignored.

Rules for using texld:

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within both texcrd or texld instructions. If .xyw is being used on t(n) register read(s), this can be mixed with other read(s) of the same t(n) register using .xyw_dw.
  2. The _dz source modifier is only valid on texld with r(n) source register (thus phase 2 only).
  3. The _dz source modifier may be used no more than two times per shader.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  | x | x | x |  |  |

Examples

The texld instruction offers some control over which components of the source texture coordinate data are used. The complete set of allowed syntax for texld follows, and includes all valid source register modifiers, selectors, and write mask combinations.

texld  r(m), t(n).xyz
// Uses xyz from t(n) to sample 1-D, 2-D, or 3-D texture.

texld  r(m), t(n)
// Same as previous.

texld  r(m), t(n).xyw
// Uses xyw (skipping z) from t(n) to sample 1-D, 2-D or 3-D texture.

texld  r(m), t(n)_dw.xyw
// Samples 1-D or 2-D texture at x/w, y/w from t(n). The result
// is undefined for a cube-map lookup.

texld  r(m), r(n).xyz
// Samples 1-D, 2-D, or 3-D texture at xyz from r(m).
// This is possible in the second phase of the shader.

texld  r(m), r(n)
// Same as previous.

texld  r(m), r(n)_dz.xyz
// Samples 1-D or 2-D texture at x/z, y/z from r(m).
// Possible only in second phase.
// The result is undefined for a cube-map lookup.

texld  r(n), r(n)_dz
// Same as previous.

© 2002 Microsoft Corporation. All rights reserved.


texm3x2depth (Pixel Shader)

Calculate the depth value to be used in depth testing for this pixel.

Syntax

texm3x2depth (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2depth | x

This instruction must be used with the texm3x2pad instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                     // Define tn as a standard 3-vector.(tn must be
                             // defined in some way before it is used.
texm3x2pad   t(m),   t(n)    // Where m > n
                             // Calculate z value.
texm3x2depth t(m+1), t(n)    // Calculate w value; use both z and w to
                             // find depth.

The depth calculation is done after using a dot product operation to find z and w. Here is more detail about how the depth calculation is accomplished.

The texm3x2pad instruction calculates z.

z = TextureCoordinates(stage m)UVW • t(n)RGB

The texm3x2depth instruction calculates w.

w = TextureCoordinates(stage m+1)UVW • t(n)RGB

Calculate depth and store the result in t(m+1).

if (w == 0)
  t(m+1) = 1.0
else
  t(m+1) = z/w

The calculated depth is tagged to be used in the depth test for the pixel, replacing the existing depth test value for the pixel.

Be sure to clamp z/w to be in the range of (0-1). If z/w is outside this range, the result stored in the depth buffer will be undefined.

After running tex3x2depth, register t(m+1) is no longer available for use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth (Pixel Shader) or texdepth will be used for each of the subpixel depth comparison tests.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x2pad (Pixel Shader)

Performs the first row multiplication of a two-row matrix multiply. This instruction must be combined with either texm3x2tex or texm3x2depth. Refer to either of these instructions for details on using texm3x2pad (Pixel Shader).

Syntax

texm3x2pad (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2pad | x | x | x

This instruction cannot be used by itself.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x2tex (Pixel Shader)

Performs the final row of a 3x2 matrix multiply and uses the result to do a texture lookup. texm3x2tex must be used in conjunction with the texm3x2pad instruction.

Syntax

texm3x2tex (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2tex | x | x | x

The instruction is used as one of two instructions representing a 3x2 matrix multiply operation. This instruction must be used with the texm3x2pad instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              // be defined in some way before it is used).
texm3x2pad  t(m),   t(n)      // where m > n
                              // Perform first row of matrix multiply.
texm3x2tex  t(m+1), t(n)      // Perform second row of matrix multiply
                              // to get (u,v) to sample texture
                              // associated with stage m+1.

Here is more detail about how the 3x2 multiply is accomplished.

The texm3x2pad instruction performs the first row of the multiply to find u'.

u' = t(n)RGB * TextureCoordinates(stage m)UVW

The texm3x2tex instruction performs the second row of the multiply to find v'.

v' = t(n)RGB * TextureCoordinates(stage m+1)UVW

The texm3x2tex instruction samples the texture on stage (m+1) with (u',v') and stores the result in t(m+1).

t(m+1)RGB = TextureSample(stage m+1)RGB using (u', v') as coordinates.

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0.
texm3x2pad  t1,  t0   // First row of matrix multiply.
texm3x2tex  t2,  t0   // Second row of matrix multiply to get (u,v)
                      // with which to sample texture in stage 2.
mov r0, t2            // Output result.

This example requires the following textures in the following texture stages.

Stage 0 takes a map with (x,y,z) perturbation data.

Stage 1 holds texture coordinates. No texture is required in the texture stage.

Stage 2 holds both texture coordinates as well as a 2-D texture set at that texture stage.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x3 (Pixel Shader)

Performs a 3x3 matrix multiply when used in conjunction with two texm3x3pad instructions.

Syntax

texm3x3 (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3 | x | x

This instruction is the same as the texm3x3tex instruction, without the texture lookup.

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation. The 3x3 matrix is comprised of the texture coordinates of the third texture stage, and by the two preceding texture stages. Any texture assigned to any of the three texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must follow the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         // be defined in some way before it is used).
texm3x3pad t(m),   t(n)  // where m > n
                         // Perform first row of matrix multiply.
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply.
texm3x3    t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         // 3-vector result.

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3tex instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Place the result of the matrix multiply in the destination register.

t(m+2)RGBA = (u', v', w', 1)

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x3pad (Pixel Shader)

Performs the first or second row multiply of a three-row matrix multiply. This instruction must be used in combination with texm3x3, texm3x3spec, texm3x3vspec, or texm3x3tex.

Syntax

texm3x3pad (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3pad | x | x | x

This instruction cannot be used by itself.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x3spec (Pixel Shader)

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping. texm3x3spec must be used in conjunction with two texm3x3pad instructions.

Syntax

texm3x3spec (Pixel Shader) dest, src0, src1

Registers

dest
Destination register.
src0
Input source register.
src1
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3spec | x | x | x

This instruction performs the final row of a 3x3 matrix multiply, uses the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector to perform a texture lookup. The shader reads the eye-ray vector from a constant register. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post reflection vector (u,v,w) is used to sample the texture on the final texture stage. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              //   be defined in some way before it is used).
texm3x3pad t(m),   t(n)       //   where m > n
                              // Perform first row of matrix multiply.
texm3x3pad  t(m+1), t(n)      // Perform second row of matrix multiply.
texm3x3spec t(m+2), t(n), c0  // Perform third row of matrix multiply.
                              // Then do a texture lookup on the texture
                              //   associated with texture stage m+2.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3spec instruction then does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
//   N = (u', v', w')
//   and the eye-ray vector E is given by the constant register
//   E = c# (Any constant register--c0, c1, c2, etc.--can be used.)

Lastly, the texm3x3spec instruction samples t(m+2) with (u'',v'',w'') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u'', v'', w'') as coordinates.

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                    // Bind texture in stage 0 to register t0 (tn must
                          //   be defined in some way before it is used).
texm3x3pad  t1,  t0       // First row of matrix multiply.
texm3x3pad  t2,  t0       // Second row of matrix multiply.
texm3x3spec t3,  t0,  c#  // Third row of matrix multiply to get a 3-vector.
                          // Reflect 3-vector by the eye-ray vector in c#.
                          // Use reflected vector to lookup texture in
                          //   stage 3.
mov r0, t3                // output result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines where to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is given by a constant register E = c#.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x3tex (Pixel Shader)

Performs a 3x3 matrix multiply and uses the result to do a texture lookup. texm3x3tex (Pixel Shader) must be used with two texm3x3pad instructions.

Syntax

texm3x3tex (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3tex | x | x | x

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation, followed by a texture lookup. The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting three-component vector (u,v,w) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         //   be defined in some way before it is used).
texm3x3pad t(m),   t(n)  //   where m > n
                         // Perform first row of matrix multiply.
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply.
texm3x3tex t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         //   3-vector with which to sample texture
                         //   associated with texture stage m+2.

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Lastly, the texm3x3tex instruction samples t(m+2) with (u',v',w') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u', v', w') as coordinates.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0.
texm3x3pad  t1,  t0   // First row of matrix multiply.
texm3x3pad  t2,  t0   // Second row of matrix multiply.
texm3x3tex  t3,  t0   // Third row of matrix multiply to get a
                      //   3-vector with which to sample texture at
mov r0, t3            //   stage 3 output result.

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinate set 0 defines how to sample this normal map.
  • Texture coordinate set 1 is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage 1 is ignored.
  • Texture coordinate set 2 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage 2 is ignored.
  • Texture coordinate set 3 is assigned to row 3 of the 3x3 matrix. A volume or cube texture should be set to stage 3 for lookup by the transformed 3-D vector.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texm3x3vspec (Pixel Shader)

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping where the eye-ray vector is not constant. texm3x3vspec (Pixel Shader) must be used in conjunction with two texm3x3pad instructions.

If the eye-ray vector is constant, the texm3x3spec instruction will perform the same matrix multiply and texture lookup.

Syntax

texm3x3vspec (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3vspec | x | x | x

This instruction performs the final row of a 3x3 matrix multiply operation, interprets the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector as a texture address for a texture lookup. It works just like texm3x3spec, except that the eye-ray vector is taken from the fourth component of the texture coordinates. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post-reflection vector (UVW) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                    // Define tn as a standard 3-vector (tn must
                            //   be defined in some way before it is used).
texm3x3pad   t(m),   t(n)   // where m > n
                            // Perform first row of matrix multiply.
texm3x3pad   t(m+1), t(n)   // Perform second row of matrix multiply.
texm3x3vspec t(m+2), t(n)   // Perform third row of matrix multiply.
                            // Then do a texture lookup on the texture
                            //   associated with texture stage m+2.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3vspec instruction also does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
// N = (u', v', w')
// and the eye-ray vector E is given by
// E = (TextureCoordinates(stage m)Q,
//      TextureCoordinates(stage m+1)Q,
//      TextureCoordinates(stage m+2)Q)

Lastly, the texm3x3vspec instruction samples t(m+2) with (u'',v'',w'')and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA
  using (u'', v'', w'') as coordinates.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0.
texm3x3pad   t1,  t0  // First row of matrix multiply.
texm3x3pad   t2,  t0  // Second row of matrix multiply.
texm3x3vspec t3,  t0  // Third row of matrix multiply to get a 3-vector.
                      // Reflect 3-vector by the eye-ray vector.
                      // Use reflected vector to do a texture lookup
                      //   at stage 3.
mov r0, t3            // Output result.

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines how to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is passed into the instruction in the fourth component (q) of the texture coordinate data at stages m, m+1, and m+2.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texreg2ar (Pixel Shader)

Interprets the alpha and red color components of the source register as texture address data (u,v) to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2ar (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2ar | x | x | x

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2ar t(m), t(n)     where m > n

// Here is more detail about how the remapping is accomplished.
// The first instruction loads the texture color (RGBA)
// into register tn.
tex tn
// The second instruction remaps the color.
t(m)RGBA = TextureSample(stage m)RGBA using t(n)AR as coordinates.

_bx2 cannot be used on the src register for texreg2ar (Pixel Shader) or texreg2gb instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texreg2gb (Pixel Shader)

Interprets the green and blue color components of the source register as texture address data to sample the texture at the stage corresponding to the destination register number.

Syntax

texreg2gb (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2gb | x | x

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

// Here is an example of the sequence the instruction follows.
tex t(n)
texreg2gb t(m), t(n)     where m > n

// Here is more detail about how the remapping is accomplished.
// The first instruction loads the texture color (RGBA)
// into register tn.
tex tn
// The second instruction remaps the color.
t(m)RGBA = TextureSample(stage m)RGBA using t(n)GB as coordinates.

_bx2 cannot be used on the src register for texreg2ar or texreg2gb (Pixel Shader) instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texreg2rgb (Pixel Shader)

Interprets the red, green, and blue (RGB) color components of the source register as texture address data in order to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2rgb (Pixel Shader) dest, src

Registers

dest
Destination register.
src
Input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2rgb | x | x

This instruction is useful for color-space remapping operations. It supports two-dimensional (2-D) and three-dimensional (3-D) coordinates. It can be used just like the texreg2ar or texreg2gb to remap 2-D data. However, this instruction also supports 3-D data so it can be used with cube maps and 3-D volume textures.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2rgb t(m), t(n)     where m > n

Here is more detail about how the remapping is accomplished.

// The first instruction loads the texture color (RGBA) into register tn.
tex tn

// The second instruction remaps the color.
t(m)RGB = TextureSample(stage m)RGB using t(n)RGB as coordinates.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


abs (Pixel Shader)

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


crs (Pixel Shader)

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

This is a macro instruction.

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dcl (Pixel Shader)

Declare a pixel shader input register.

Syntax

dcl_[pp] dest[.mask]

Where:

  • _[pp] is optional partial precision. See Partial Precision.
  • dest is a destination register. It must be either an Color Register (vn), or an Input Texture Coordinate Register (tn).
  • [.mask] is an optional write mask that controls which components of the destination register that can be written to. See Destination Register Masking.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl |  |  |  |  | x | x | x | x | x

All dcl instructions must appear before the first executable instruction.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dcl_textureType (Pixel Shader)

Declare a pixel shader sampler register.

Syntax

dcl_textureType s#

where:

  • _textureType defines the texture type. This detemines how many coordinates are required by each texture coordinate when sampling. The following texture dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler register. s is an abbreviation for the sampler register and # is the register number. For more information about sampler registers, see Sampler Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_textureType |  |  |  |  | x | x | x | x | x

All dclxxx instructions must appear before the first executable instruction.

Example

dcl_cube t0.rgb;  // Define a 3-D texture map

add r0, r0, t0;   // perturb texture coordinates
texld r0, s0, r0; // load r0 with a color sampled from stage0
                  // at perturbed texture coordinates r0
                  // this is a dependent texture read

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dp2add (Pixel Shader)

Performs a 2-D dot product and a scalar addition.

Syntax

dp2add[_sat] dst[.mask], [-]src0[.swizzle],
                         [-]src1[.swizzle],
                         [-]src2[.replicate_swizzle]

Where:

  • [_sat] - is an optional saturate modifier.
  • dest - is a destination register. The see more about the limitations of pixel shader registers with this instruction, see the remarks below.
  • [_mask] - is an optional mask modifier.
  • [-] - is an optional negate modifier.
  • src0, src1, src2 - three input source registers. Each of these registers allows an optional negate [-] modifier. src0 and src1 allow an optional swizzle mask [.swizzle]. src2 requires replicate swizzle mask. [.replicate_swizzle].
  • [swizzle, replicateSwizzle-] - are optional swizzle modifiers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp2add |  |  |  |  | x | x | x | x | x

The scalar value for add is chosen by the replicate swizzle on src2.

The following code fragment shows the operations performed.

dest = src0.r * src1.r + src0.g * src1.g + src2.selected_component
// The scalar result is replicated to write mask components

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


exp (Pixel Shader)

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp |  |  |  |  | x | x | x | x | x

The following code fragment shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src0.w);

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


frc (Pixel Shader)

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc |  |  |  |  | x | x | x | x | x

The following code fragment shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

Each component of the result is in the range from 0.0 through 1.0.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


log (Pixel Shader)

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log |  |  |  |  | x | x | x | x | x

The following code fragment shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x2 (Pixel Shader)

Computes the product of a 3-component vector and a 2x3 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 |  |  |  |  | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2-D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2-D transforms. This macro instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

This is a macro instruction. Swizzle and negate modifiers are invalid for the src1 register. The dest and src0 register, or any of src1+i registers, cannot be the same.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x3 (Pixel Shader)

Computes the product of a 3-component vector and a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This macro instruction is implemented as a set of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x4 (Pixel Shader)

Computes the product of a 3-component vector and a 3x4 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z);
dest.z = (src0.z * src1.x) + (src0.z * src1.y) + (src0.z * src1.z);
dest.w = (src0.w * src1.x) + (src0.w * src1.y) + (src0.w * src1.z);

The input vector is in register src0. The input 3x4 matrix is in register src1, and the next two higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This macro instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m4x3 (Pixel Shader)

Computes the product of a 4-component vector and a 4x3 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);
dest.y = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);
dest.z = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This macro instruction is implemented as a set of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

This is a macro instruction. Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m4x4 (Pixel Shader)

Computes the product of a 4-component vector and a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

This is a macro instruction, which takes four instruction slots. Swizzle and negate modifiers are invalid for the src0 register. The dest and src0 registers cannot be the same.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z) +
        (src0.x * src1.w);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z) +
        (src0.y * src1.w);
dest.z = (src0.z * src1.x) + (src0.z * src1.y) + (src0.z * src1.z) +
        (src0.z * src1.w);
dest.w = (src0.w * src1.x) + (src0.w * src1.y) + (src0.z * src1.z) +
        (src0.w * src1.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This macro instruction is implemented as a set of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


max (Pixel Shader)

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max |  |  |  |  | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


min (Pixel Shader)

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min |  |  |  |  | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


nrm (Pixel Shader)

Normalize a 3-D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  |  |  |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);

This is a macro instruction. The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


pow (Pixel Shader)

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  |  |  |  | x | x | x | x | x

This instruction works as follows:

dest.x = dest.y = dest.z = dest.w = [abs(src0)]src1;

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The input power (src1) must be a scalar.

The scalar result is replicated to all four output channels.

This is a macro instruction.

This instruction could be expanded as exp(src1 * log(src0)).

The dst register should be a temporary register, and should not be the same register as src1.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rcp (Pixel Shader)

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp |  |  |  |  | x | x | x | x | x

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

The scalar result is replicated to all channels in the destination write mask.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rsq (Pixel Shader)

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq |  |  |  |  | x | x | x | x | x

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


sincos (Pixel Shader)

Computes sine and cosine, in radians. The x-component of result contains cos(x). The y component contains sin(x). The src1 register needs to have a replicate swizzle to indicate which channel is used.

Syntax

sincos dst, src0, src1, src2

where

  • dst is the destination register. Should be a temporary register.
  • src0 is a source register that provides the input angle. The angle must be within [-Pi, +Pi].
  • src1 is a source register. Must be a constant register. For ps_3_0 or above, this parameter is not strictly needed, as the component values are provided.
  • src2 is a source register. Must be a constant register. For ps_3_0 or above, this parameter is not strictly needed, as the component values are provided.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  |  |  |  | x | x | x | x | x

Source register rules:

  • src0.w is an angle measured in radians between -Pi and +Pi.
  • src1 = (-1.0f/(7!*128), -1.0f/(6!*64), 1/(4!*16), 1/(5!*32) ).
  • src2 = (-1.0f/(3!*8), -1.0f/(2!*8), 1, 0.5f).

These values are defined in the following macros: D3DSINCOSCONST1 and D3DSINCOSCONST2.

Destination register rules:

  • dest.x = cos(src1.selected_channel), dest.y = sin(src1.selected_channel), dest.z is undefined after the instruction.
  • dest should not be the same register as src1.
  • Only .x and .y are allowed to be in the destination write mask.

The maximum absolute error is 0.002.

This is a macro instruction, which takes eight instruction slots.

If application wants to compute sincos for an arbitrary angle, then the angle could be mapped to the range -Pi to +Pi by using the following macro (r0.x holds the original angle).

def c0, Pi, 0.5f, 2*Pi, 1/(2*Pi)
mad r0.x, r.x, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x

Instruction Information

Minimum operating system Windows 98

Related Topics

  • D3DSINCOSCONST1
  • D3DSINCOSCONST2

© 2002 Microsoft Corporation. All rights reserved.


texld (Pixel Shader)

Sample a texture at a particular sampler, using provided texture coordinates. This instruction is different from the texld instruction used in pixel shader version 1_4.

Syntax

texld dst[_pp], src0, src1

Where:

  • dst is a destination register. It must be the predicate register.
  • [_pp] optional partial precision. This has been available for pixel shaders since ps_2_0. See Partial Precision.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (ex. D3DSAMP_MINFILTER).

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  |  | x | x | x | x | x

Restrictions:

  • Occupies 1 addressing instruction slot.
  • dst must be r#.
  • dst requires no writemask, texld* instructions always write out 4 components. If the source texture contains less than 4 components, defaults are placed in the missing components. Defaults for missing components are either 0 or 1, and depend on the texture format. The reference rasterizer source lists the defaults.
  • _sat instruction modifier is NOT allowed on dst.
  • src1 must be s#, with no negate or swizzle. The s# must have been declared at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the s# was declared. If it was declared as a cube, a 3 component texture coordinate is required (.rgb). Validation enforces that coordinates provided to texld are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually set a texture (through the API) with dimensions equal to the dimension declared for the sampler. In such a case, the debug runtime will attempt to detect mismatches. Sampling a texture with lower dimensions than are present in the texture coordinate will be allowed, and be assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with higher dimensions than are present in the texture coordinate is illegal.
  • For texldb and texldp, in addition to the components of the texture coordinate required to index the texture dimension, the w-component of the coordinate is required.
  • src0 (texture coordinate) may be t#/r# registers only, with no negate or swizzle.
  • If src0 (texture coordinate) is a t# register, the components required for the lookup (described above) must have been dcl'd.
  • If src0 (texture coordinate) is r#, the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0. If these textures contain vectors, for example, that are stored as biased-signed values, then an explicit ps instruction can be used to expand them.
     def c2, 2, 2, 2, 2
 def c5, 1, 1, 1, 1
 ...
 texld r0, t0, s0
 mad r0, r0, c2, -c5
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • A first order dependent tex-op is a tex[ld*|kill] instruction in which either:
    • an r# reg is input (NOT t# reg)
    • output r# reg was previously written, now being written AGAIN.
    A 2nd order dependent tex-op occurs if: a tex-op reads OR WRITES to an r# reg whose contents, BEFORE executing the tex-op, depend (perhaps indirectly) on the outcome of a 1st order dependent tex-op. An (n)th order dependent tex-op derives from an (n-1)th order tex-op. A given tex-op may be dependent to at most 3rd order.

© 2002 Microsoft Corporation. All rights reserved.


texldb (Pixel Shader)

Projected texture load instruction. This instruction uses the fourth element (.a or .w) to bias the texture-sampling level of detail (LOD) just before sampling.

Syntax

texldb dst[_pp], src0, src1

where

  • [_pp] is optional partial precision. See Partial Precision.
  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

For the restrictions when using texldb, see the texld instruction.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldb |  |  |  |  | x | x | x | x | x

texldb biases the mipmap LOD, computed normally as part of the sample process by the (signed) value in src0.w. Recall that positive bias values will result in smaller mipmaps being selected and vice versa. For ps_2_0 and ps_s_x, bias values can be within the range [-3.0,+3.0]. For ps_3_0, bias values can be within the range [-16.0,+15.0]. Bias values outside this range will produce undefined results. The sampler state D3DSAMP_MIPMAPLODBIAS is still honored, and the texldb bias is added to this, but on a per-pixel basis. After the biased LOD is computed, D3DSAMP_MAXMIPLEVEL is still honored and the texture sample occurs. After texldb, the contents of src0 are unaffected (unless dst is the same register).

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texldp (Pixel Shader)

Projected texture load instruction. This instruction divides the input texture coordinate by the fourth element (.a or .w) just before sampling.

Syntax

texldp dst[_pp], src0, src1

where

  • [_pp] is optional partial precision. See Partial Precision.
  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

For the set of restrictions when using texldp, see the texld instruction.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldp |  |  |  |  | x | x | x | x | x

texldp performs projection on the coordinates read from src0 before performing the sample. Each texture coordinate is divided src0.w, then the texture is sampled. After the texldp, the contents of src0 are unaffected (unless dst is the same register). The D3DTTFF_PROJECTED texture-transform flag was retired in ps_1_4.

An alternative to using texldp is to manually perform projection in the shader, to get post-projection texture coordinate perturbation. For example:

rcp r0, t0.w     // Do projective divide on t0 texcoords.
mul r1, t0, r0.w // Complete it with multiply.
add r1, r1, r2   // Perturb post-projected coordinates by r2.
texld r0, r1, s0 // Sample at those coordinates.

Performing the division in shader code is usually slower than when performed by the texldp instruction, so avoid such additional math when possible.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Constant Float Register

Pixel-shader input register containing a constant. Constant registers hold constant values that are used by the shader. Constant values are set by the application.

Syntax

Constant Float Register

Remarks

Syntax
def c#, float1, float2, float3, float4

where:

  • def is a declarator.
  • c is a constant register and # is the register number.
  • float1, float2, float3, and float4 are floating-point numbers.

Remarks

  • There are 32 pixel-shader vertex constant registers: c0 to c31.
  • For version 2.0, each instruction can read a maximum of one constant register. The only exception is the sincos instruction, which reads two constant registers.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Color Register

Pixel shader input register containing vertex color.

Syntax

Color Register

Remarks

Syntax
dcl v#.components

where:

  • dcl is a register declarator. See dcl.
  • v is a vertex register and # is the register number.
  • components are the [xyzw] or [rgba].

Remarks

  • There are two pixel shader vertex color registers: v0 and v1. They are read-only registers.
  • They contain four-component RGBA values iterated from input vertices.
  • They have lower precision than most registers, guaranteed to have 8 bits of unsigned data in the range 0, +1.
  • There is a maximum of one in a single instruction.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Output Color Register

Pixel shader output registers represent the different elements of a Multielement Texture.

Syntax

Output Color Register

Remarks

Name | Description
oC0 | Color 0 (element 0)
oC1 | Color 1 (element 1)
oC2 | Color 2 (element 2)
oC3 | Color 3 (element 3)
oDepth | New depth value for depth test against depth-stencil buffer.

If an application has a w-buffer set as its depth buffer, the application might also need to send w-range information to the pixel shader to scale the w-values written out to oDepth.

Remarks

Additional output register properties:

  • These must be written to using a mov instruction.
  • There can be only one write to an any oCn register per shader.
  • Write masks cannot be used. All four channels of oCn registers are emitted from the pixel shader. The mov instruction writing to an oCn register must have a source parameter (r#/v#/t#/c#) containing no swizzle or modifier. oDepth register is a scalar output, and the mov instruction that writes to it must use a source parameter (r#/v#/t#/c#) using a REPLICATE swizzle on the source and no modifier. This is the generalization of the texm3x2depth instruction in ps_1_3 and texdepth in ps_1_4.
  • The runtime will fail validation if there are uninitialized registers that get written to.
  • The minimal shader always has to write all four components of oC0. If any of the others are used, all four channels should be written.
  • If oCn is written to using a mov instruction but there is no corresponding element in the multielement texture surface set as a render target, this instruction is ignored.
  • If no depth buffer had been created/attached to the device, mov to the oDepth register is ignored.
  • Each mov into output registers consume one instruction slot and can be present anywhere in the shader, in any order. oCn registers have to be updated in a contiguous way. That is, if you write to oCn, you must also write from oC0 to oCn-1.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Output Depth Register

Depth test register.

Syntax

Output Depth Register

Remarks

Name | Description
oDepth | New depth value for depth test against depth-stencil buffer.

If an application has a w-buffer set as its depth buffer, the application might also need to send w-range information to the pixel shader to scale the w-values written out to oDepth.

Remarks

If no depth buffer had been created/attached to the device, mov to the oDepth register is ignored.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Sampling Stage Register

A pixel shader input sampling stage register identifies a sampling unit that can be used in texture load statements. A sampling unit is initialized with IDirect3DDevice9::SetSamplerState. Prior to Microsoft® DirectX® 9.0, the sampling state was initialized with IDirect3DDevice9::SetTextureStageState.

There are 16 pixel shader sampling stage registers: s0 to s15. Therefore, up to 16 texture surfaces can be read in a single shader pass. The instructions that use a sampler register are texld and texldp.

Syntax

Sampling Stage Register

Remarks

Sampler registers must be declared before use with the dcl_textureType instruction.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler Register | x | x | x | x | x
  • A sampling stage register identifies the sampling unit to be used in texture load statements. A sampling unit corresponds to the texture sampling stage of DirectX 6.0 or DirectX 7.0 multi-texture, encapsulating the sampling-specific state provided in the TextureStageState constant of DirectX 6.0 to DirectX 8.x. This state information can be defined in its declarator statement.
  • Each sampler uniquely identifies a single texture surface that is set to the corresponding sampler using IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.
  • They are read-only registers.
  • Sampling a texture with a higher dimension than is present in the texture coordinates is illegal. Sampling a texture with a lower dimension than is present in the texture coordinates will ignore the extra texture coordinates.

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Temporary Register

Pixel shader input temporary registers are used to hold intermediate results.

Syntax

Temporary Register

Remarks

Syntax
no declaration is required

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x
  • There are 12 pixel-shader temporary registers: r0 to r11.
  • These registers are used for storing intermediate results during computations.
  • If a temporary register uses components that are not defined in previous code, shader validation will fail.
  • These are at least floating-point precision.
  • A maximum of three can be used in a single instruction.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Input Texture Coordinate Register

Pixel shader input register containing texture coordinates.

Syntax

Input Texture Coordinate Register

Remarks

Remarks
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x

A texture coordinate register contains texture coordinate data. Before a texture coordinate register is used, it must be declared by a pixel shader declaration. For details about how to declare a texture register, see dcl.

In addition, here are some other properties of texture coordinate registers.

  • There are eight pixel-shader texture coordinate registers, t0 to t7.
  • These are read-only registers.
  • They contain four-component RGBA values iterated from input vertices.
  • They contain high precision, high dynamic range data values interpolated from the vertex data. Values are generated with perspective-correct interpolation. Data is floating-point precision, and is signed.
  • There is a maximum of one in a single instruction.
  • Multiple reads of a texture coordinate register within a shader must use identical source selectors. See Source Register Selectors.
  • The optional partial precision modifier [_pp] applies to dependent reads. This is because partial precision affects arithmetic operations involving the texture coordinate register. It will not affect the precision of texture address instructions because it does not affect the texture coordinate iterators.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Predicate Register

This pixel shader output register contains a per-channel boolean value.

Syntax

Predicate Register

Remarks

A predicate register is supported by the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp. There are no default values for this register; an application needs to set the register before it is used.

Minimum operating system Windows 98

Instruction Information

Minimum operating systems Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break (Pixel Shader)

Break out of the current loop at the nearest endloop or endrep.

Syntax

break

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  |  |  |  | x | x | x | x

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break_comp (Pixel Shader)

Break out of the current loop at the nearest endloop or endrep, based on a comparison.

Syntax

break_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a single component.
  • src1 is a source register. Replicate swizzle is required to select a single component.

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  |  |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (!(src0 comparison src1))
   jump to the corresponding endloop or endrep instruction;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break pred (Pixel Shader)

Conditionally break out of the current loop at the nearest endloop or endrep. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

break [!]p0.replicateSwizzle

Where:

  • [!] optional boolean NOT.
  • p0 is the predicate register. See Predicate.
  • replicateSwizzle specifies the component that contains the predicate value. Valid components are: x, y, z, w or r, g, b, a. The predicate value can be modified with the negate modifier.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break pred |  |  |  |  |  | x | x | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


call (Pixel Shader)

Performs a function call to the instruction marked with the provided label index.

Syntax

call label

Where:

  • label is a label number.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  |  |  |  |  | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.

Only forward calls are allowed. This means that the location of the label inside the pixel shader should be after the call instruction referencing it.

Nested calls are not allowed for ps_2_x or ps_2_sw.

Nested calls are allowed for ps_3_0 and ps_3_sw.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


callnz (Pixel Shader)

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz label, booleanRegister

where:

  • label is a label. A label is an integer between 0 and 16.
  • booleanRegister identifies a boolean register number. See Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified boolean register is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


callnz pred (Pixel Shader)

Call if not zero, with a predicate. Performs a conditional call to the instruction marked by the label index. Predication uses a boolean value to determine whether of not to perform the instruction.

Syntax

callnz label, [!] p0.replicateSwizzle

where:

  • label specifies a label number.
  • [!] is an optional boolean NOT.
  • p0 is the predicate register. See Predicate.
  • replicateSwizzle specifies the component that contains the predicate value. Valid components are: x, y, z, w or r, g, b, a. The predicate value can be modified with the negate modifier.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz pred |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dsx (Pixel Shader)

Compute the rate of change in the render target's x-direction.

Syntax

dsx dest, src

Where:

  • dest is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsx |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel. This is designed to work even if adjacent pixels follow different paths due to flow control, because the hardware is required to run a group of lock-step pixel shaders, disabling writes as necessary when flow control goes down a path that a particular pixel does not take.

The dsx, dsy instructions can simply compute therir result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies deoebgubg nb hardware but should be consistent with the way the hardware does the same operations as part of the LOD calculation process for texture sampling.

Related Topics

  • dsy
  • texldd

© 2002 Microsoft Corporation. All rights reserved.


dsy (Pixel Shader)

Compute the rate of change in the render target's y-direction.

Syntax

dsy dest, src

Where:

  • dest is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsy |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel. This is designed to work even if adjacent pixels follow different paths due to flow control, because the hardware is required to run a group of lock-step pixel shaders, disabling writes as necessary when flow control goes down a path that a particular pixel does not take.

The dsx, dsy instructions can simply compute therir result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies deoebgubg nb hardware but should be consistent with the way the hardware does the same operations as part of the LOD calculation process for texture sampling.

Related Topics

  • dsx
  • texldd

© 2002 Microsoft Corporation. All rights reserved.


else (Pixel Shader)

Start of an else block.

Syntax

else

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  |  |  |  |  | x | x | x | x

If the condition in the corresponding if statement is true, the code enclosed by the if statement and the matching else is run.

Minimum operating system Windows 98

Related Topics

  • if
  • endif

© 2002 Microsoft Corporation. All rights reserved.


endif (Pixel Shader)

Marks the end of an if...else block.

Syntax

endif

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  |  |  |  |  | x | x | x | x

Minimum operating system Windows 98

Related Topics

  • if
  • else

© 2002 Microsoft Corporation. All rights reserved.


endrep (Pixel Shader)

End of a repeat block.

Syntax

endrep

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  |  |  |  |  | x | x | x | x

  • rep uses integer registers (i#).
  • endrep must follow the last instruction of a repeat block.
  • The endrep offset must be greater than the rep instruction offset.
  • Repeat loops cannot be nested.
  • Repeat loops are allowed to be either completely inside an if block or completely surrounding it, no straddling is allowed.
  • The maximum loop iteration count is 255.

This instruction works as shown here.

LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


if (Pixel Shader)

Start of an if...else...endif block.

Syntax

if boolRegister

Where:

  • boolRegister is a bool register number. See Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if |  |  |  |  |  | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching else is run. Otherwise, the code enclosed by the else...endif statements is run. This instruction consumes one instruction slot.

An if block can be nested.

An if block cannot straddle a loop block.

Example

This instruction provides conditional static flow control.

defb b3, true

if b3
// Instructions to run if b3 is nonzero.
else
// Instructions to run otherwise.
endif

Instruction Information

Minimum operating system Windows 98

Related Topics

  • else
  • endif

© 2002 Microsoft Corporation. All rights reserved.


if_comp (Pixel Shader)

Start an if...else...endif block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if (src0 comparison src1)
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else...endif blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else or endif instruction.
  • if_comp...else...endif blocks cannot straddle a loop block. The if_comp block must be completely inside or outside the loop block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


if pred (Pixel Shader)

Start of an if...else...endif block, with the condition taken from the content of the predicate register.

Syntax

if [!]p.replicateSwizzle

Where:

  • [!] an optional NOT modifier. This modifies the value in the predicate register.
  • p0 is the predicate register. See Predicate.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: x, y, z, w or r, g, b, a.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_pred |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else or endif instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block, it should be either completely inside it or surround it.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


label (Pixel Shader)

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For ps_2_x, the label number must be between between 0 and 15.

For ps_2_sw and ps_3_0, the label number must be between between 0 and 2047.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  |  |  |  |  | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction is allowed to be present directly after a ret instruction (which defines the end of the previous subroutine or main program).

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rep (Pixel Shader)

Start a rep...endrep block.

Syntax

rep integerReg

where integerReg is an integer register that specifies the repeat count in the x component. See Constant Integer Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  |  |  |  |  | x | x | x | x
  • rep uses integer registers (i#).
  • endrep must follow the last instruction of a repeat block.
  • The endrep offset must be greater than the rep instruction offset.
  • Repeat loops cannot be nested for ps_2_sw or ps_2_x.
  • Repeat loops can be nested between 0 and 4 levels for ps_3_0 and ps_3_sw.
  • Repeat loops are allowed to be either completely inside an if block or completely surrounding it; no straddling is allowed.
  • rep consumes one vertex shader instruction slot but must be used with endrep, which consumes another.
  • The maximum loop iteration count is 255.

Here is how the instruction works.

StartLoopOffset = next instruction offset
    LoopIterationCount   = IntegerRegister.x
    if (LoopIterationCount <= 0)
        Continue execution after the next EndRep instruction

© 2002 Microsoft Corporation. All rights reserved.


ret (Pixel Shader)

Takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

Syntax

rep integerReg

where integerReg is an integer register that specifies the instruction count. See Constant Integer Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  |  |  |  |  | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.

© 2002 Microsoft Corporation. All rights reserved.


setp (Pixel Shader)

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp |  |  |  |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dest register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, srcReg, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, srcReg, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

(p0) add r1, r2, r3

to perform a 2 component add.

r1.x = r2.x + r3.x
r1.y = r2.y + r3.y

The x and y components of r1 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases it's instruction slot count by 1.

The predicate register can also be applied to if pred, callnz pred and break pred instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texldd (Pixel Shader)

Samples a texture using the texture coordinates at src0, the sampler specified by src1, and the x-gradient (dsx) and y-gradient (dsy) coming from src2 and src3.

Syntax

texldd, dest, src0, src1, src2, src3

Where:

  • dest is a destination register.
  • src0 is an input source register containing texture coordinates.
  • src1 is an input source register that specifies the sampler register. See Sampler Register. The sampler states supported are D3DSAMP_MAXMIPLEVEL and D3DSAMP_MIPMAPLODBIAS.
  • src2 is an input source register that specifies the x gradient.
  • src3 is an input source register that specifies the y gradient.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldd |  |  |  |  |  | x | x | x | x

This instruction samples a texture using the texture coordinates at SRC0, the sampler specified by SRC1, and the gradients DSX and DSY coming from SRC2 and SRC3.

All sources support arbitrary swizzles.

All write masks are valid on the destination.

© 2002 Microsoft Corporation. All rights reserved.


Constant Boolean Register

This register is a collection of bits used in static flow control instructions (eg. if - else - endif).

There are 16 of them, therefore, a shader can have 16 independent branch conditions.

They can be set using def or IDirect3DDevice9::SetPixelShaderConstantI.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Boolean Register |  |  |  |  |  |  | x | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Constant Integer Register

Constant integer registers are used only by loop and rep.

They can be set using def or IDirect3DDevice9::SetPixelShaderConstantI.

When used as an argument to the loop instruction:

  • .x is the iteration count. (rep uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Integer Register |  |  |  |  |  |  | x | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop...endloop block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Loop Counter Register |  |  |  |  |  |  |  | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


loop (Pixel Shader)

Starts a loop...endloop block.

Syntax

loop aL, integerRegister

Where:

  • aL is the Loop Counter Register, holding the current loop count. The address register can be used to index into the Color Registers, ( v#).
  • integerRegister is an input source register. integerRegister.x specifies the iteration count, integerRegister.y specifies the initial value of the current loop counter register, and integerRegister.z specifies the increment for the current loop counter register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  |  |  |  |  |  |  | x | x

Only integer registers may be used in this instruction The loop instruction is provided for iteration, and supports an auto-incremented loop counter register that can be used to index the constant array. When nested, any time the loop counter register is used, it refers to the current loop.

This instruction works as shown below.

StartLoopOffset = next instruction offset
LoopCounter      = IntegerReg.x
IterationCount   = IntegerReg.y
LoopStep         = InteferReg.z
if (IterationCounter <= 0)
  Continue execution after the next EndLoop instruction
  • The endloop instruction must follow the last instruction of a loop block.
  • The endloop instruction offset must be greater than the corresponding loop instruction offset.
  • Loops cannot be nested for ps_2_x or ps_2_sw.
  • Loops can be nested between 0 and 4 levels in ps_3_0 and ps_3_sw.
  • Loops are allowed to be either completely inside an if block or completely surrounding it; no straddling is allowed.
  • The maximum loop initial value (base offset) is 255.
  • The maximum loop iteration count is 255.
  • The maximum step/stride size is 127 as signed strides, for example, -128 are supported.
  • The loop initial value and loop iteration count cannot be negative.

© 2002 Microsoft Corporation. All rights reserved.


texldl (Pixel Shader)

Sample a texture with a particular sampler. The particular mipmap level (LOD) being sampled has to be specified as the 4th component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (ex. D3DSAMP_MINFILTER).

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  |  |  |  | x | x

texldl (Pixel Shader) looks up the texture set at the sampler stage referenced by src1. The LOD is selected from src0.w. This value can be negative in which case the LOD selected is the zero'th one (biggest map) with the MAGFILTER. Since src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, then 0001 is obtained in the destination register.

The following rough algorithm has been provided for reference, that the reference device follows.

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD);
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be r#
  • dst can accept a writemask.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be s#, with no negate, but can have swizzle. The s# must have been declared (using dcl) at the beginning of the shader. The swizzle specifies how to output each component result of the sample.
  • The number of coordinates required to perform the texture sample depends on how the s# was declared. If it was declared as a cube, a 3 component texture coordinate is required (.rgb). Validation enforces that coordinates provided to texld are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually set a texture (through the API) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with lower dimensions than are present in the texture coordinate will be allowed, and be assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with higher dimensions than are present in the texture coordinate is illegal.
  • If the src0 (texture coordinate) is r#, the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


add (Vertex Shader)

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dcl_usage (Vertex Shader)

Declare the association between a vertex element usage and usage index, to a vertex shader position register.

Syntax

dcl_usage[usage_index] dest[.mask]

Where:

  • _usage identifies how the register data will be used. This is the same value as the members of D3DDECLUSAGE without the "D3DDECLUSAGE" prefix.
  • [usage_index] is an optional integer index between 0 and 15. It modifies the usage data. The index matches the usage index in a vertex declaration. See Decoupling Vertex Shaders and Vertex Declarations. The index is appended to the usage value with no space. If it is not supplied, it is assumed to be 0.
  • dest is a destination register. A position register (v#) is a valid destination register in all vertex shader versions. See Position Registers.

    Version vs_3_0 supports output registers (o#) as valid destination registers. See Output Registers.

    Version vs_3_0 must have at least one o register with _position0 usage when not used for process-vertices. The _position0 and _psize0 usages are the only usages that have a meaning that extends beyond linkage from vertex shader outputs to pixel shader inputs. For shaders with flow control, it is assumed that the worst case output is declared. There are no defaults if a shader does not actually output what it declares it should (due to flow control).

  • [.mask] is an optional write mask that controls which components of the destination register that can be written to. See Destination Register Masking.

    The write mask option is supported in versions 2_x and later.

    For version vs_3_0, the same o register may be declared multiple times (so different usages can be applied to individual components), each time with a unique write mask. However, the same usage may not be used multiple times in a declaration. This means that vectors must be 4 components or less, and cannot go across 4-component register boundaries (individual o registers). When the _psize usage is specified, it must have a full write mask since it is considered a scalar. When the _position usage is specified, it must have a full write mask since all 4 components have to be written.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage | x | x | x | x |  |

All dcl_usage instructions must appear before the first executable instruction.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


def (Vertex Shader)

Defines vertex shader constants.

Syntax

def dst, value

where

  • dst is the destination register.
  • value is either a 4-D floating point number.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x

The def instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by application programming interface (API) methods SetVertexShaderConstantF.

There are two ways to set a constant in a shader.

  1. Use def (Vertex Shader) to define the constant directly inside a shader.

    def (Vertex Shader) can only define floating-point constants.

  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantF to set a floating-point constant.

Instruction Information

Minimum operating system Windows 98

Related Topics

  • defi
  • defb

© 2002 Microsoft Corporation. All rights reserved.


dp3 (Vertex Shader)

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.x = dest.y = dest.z = dest.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dp4 (Vertex Shader)

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = unused;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dst (Vertex Shader)

Calculates a distance vector.

Syntax

dst dest, src0, src1

where

  • dest is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dst | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.x = 1;
dest.y = src0.y * src1.y;
dest.z = src0.z;
dest.w = src1.w;

The first source operand (src0) is assumed to be the vector (ignored, d*d, d*d, ignored) and the second source operand (src1) is assumed to be the vector (ignored, 1/d, ignored, 1/d). The destination (dest) is the result vector (1, d, d*d, 1/d).

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


exp (Vertex Shader)

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp | x | x | x | x | x | x

This instruction provides at least 21 bits of precision.

The following code fragment shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src0.w);

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


expp (Vertex Shader)

Provides partial precision exponential 2x.

Syntax

expp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
expp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float w = src.w;
float v = (float)floor(src.w);
dest.x = (float)pow(2, v);
dest.y = w - v;

// Reduced precision exponent
float tmp = (float)pow(2, w);
DWORD tmpd = *(DWORD*)&tmp & 0xffffff00;
dest.z = *(float*)&tmpd;
dest.w = 1;

This instruction provides exponential base 2 partial precision. It allows for a more accurate determination of dest.x*function(dest.y), where function is a user approximation to 2*dest.y over the limited range where dest.y is between 0.0 and 1.0.

This instruction provides 10-bit precision.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


frc (Vertex Shader)

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc | x | x | x | x | x | x

The following code fragment shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

Each component of the result is in the range from 0.0 through 1.0.

For version 1_1, the allowable write masks are .y and .xy (.x is not allowed).

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


lit (Vertex Shader)

Provides partial support for lighting by calculating lighting coefficients from two dot products and an exponent.

Syntax

lit dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lit | x | x | x | x | x | x

The source vector is assumed to contain the values shown in the following pseudocode.

src.x = N*L        ; The dot product between normal and direction to light
src.y = N*H        ; The dot product between normal and half vector
src.z = ignored    ; This value is ignored
src.w = exponent   ; The value must be between -128.0 and 128.0

The following code fragment shows the operations performed.

dest.x = 1;
dest.y = 0;
dest.z = 0;
dest.w = 1;

float power = src.w;
const float MAXPOWER = 127.9961f;
if (power < -MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format
else if (power > MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format

if (src.x > 0)
{
    dest.y = src.x;
    if (src.y > 0)
    {
        // Allowed approximation is EXP(power * LOG(src.y))
        dest.z = (float)(pow(src.y, power));
    }
}

Reduced precision arithmetic is acceptable in evaluating the destination y component (dest.y). An implementation must support at least eight fraction bits in the power argument. Dot products are calculated with normalized vectors, and clamp limits are -128 to 128.

Error should correspond to a logp and expp combination, or no more than approximately one least significant bit (LSB) for an 8-bit color component.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


log (Vertex Shader)

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log | x | x | x | x | x | x

The following code fragment shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.

This instruction provides 21 bits of precision.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


logp (Vertex Shader)

Partial precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
logp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src);
if (f != 0)
    dest.x = dest.y = dest.z = dest.w = (float)(log(f)/log(2));
else
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;

This instruction provides logarithm base 2 partial precision, up to 10 bits.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x2 (Vertex Shader)

Computes the product of a 3-component vector and a 2x3 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 | x | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2-D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2-D transforms. This macro instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

This is a macro instruction. Swizzle and negate modifiers are invalid for the src1 register. The dest and src0 register, or any of src1+i registers, cannot be the same.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x3 (Vertex Shader)

Computes the product of a 3-component vector and a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This macro instruction is implemented as a pair of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m3x4 (Vertex Shader)

Computes the product of a 3-component vector and a 4x3 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z);
dest.z = (src0.z * src1.x) + (src0.z * src1.y) + (src0.z * src1.z);
dest.w = (src0.w * src1.x) + (src0.w * src1.y) + (src0.w * src1.z);

The input vector is in register src0. The input 3x4 matrix is in register src1, and the next two higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This macro instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m4x3 (Vertex Shader)

Computes the product of a 4-component vector and a 3x4 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);
dest.y = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);
dest.z = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This macro instruction is implemented as a pair of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

This is a macro instruction. Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


m4x4 (Vertex Shader)

Computes the product of a 4-component vector and a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

This is a macro instruction, which takes four instruction slots. Swizzle and negate modifiers are invalid for the src0 register. The dest and src0 registers cannot be the same.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z) +
        (src0.x * src1.w);
dest.y = (src0.y * src1.x) + (src0.y * src1.y) + (src0.y * src1.z) +
        (src0.y * src1.w);
dest.z = (src0.z * src1.x) + (src0.z * src1.y) + (src0.z * src1.z) +
        (src0.z * src1.w);
dest.w = (src0.w * src1.x) + (src0.w * src1.y) + (src0.z * src1.z) +
        (src0.w * src1.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This macro instruction is implemented as a series of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mad (Vertex Shader)

Multiplies and adds sources.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


max (Vertex Shader)

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


min (Vertex Shader)

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mov (Vertex Shader)

Move data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x

Can be used for floating point data and to update address registers. When used to update address registers, the values are converted from floating point using rounding to nearest.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src.w);
    dest = intSrc;
}
else
{
    dest = src;
}

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mul (Vertex Shader)

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


nop (Vertex Shader)

No operation is performed.

Syntax

nop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rcp (Vertex Shader)

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = src0;
if(f == 0.0f)
{
    f = FLT_MAX;
}
else
{
    if(f != 1.0)
    {
        f = 1/f;
    }
}

dest = f;

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.

If the source has no subscripts, the x-component is used.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rsq (Vertex Shader)

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src0);
if (f == 0)
    f = FLT_MAX
else
{
    if (f != 1.0)
        f = 1.0/(float)sqrt(f);
}

dest.z = dest.y = dest.z = dest.w = f;

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

If source has no subscripts, the x-component is used. The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


sge (Vertex Shader)

Computes the sign if the first source is greater than or equal to the second source.

Syntax

sge dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sge | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x >= src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y >= src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z >= src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w >= src1.w) ? 1.0f : 0.0f;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


slt (Vertex Shader)

Computes the sign if the first source is less than the second source.

Syntax

slt dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
slt | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x < src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y < src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z < src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w < src1.w) ? 1.0f : 0.0f;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


sub (Vertex Shader)

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest = src0 - src1

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


vs (Vertex Shader)

This instruction specifies the shader version number. This instruction works on all shader versions.

Syntax

vs_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1
2 | 0, sw (software), x (extended)
3 | 0, sw (software)

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
vs | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a vertex shader.

This instruction is supported in all vertex shader versions.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 vertex shader.

vs_1_1

This partial example declares a version 2 software vertex shader.

vs_2_sw

© 2002 Microsoft Corporation. All rights reserved.


Input Registers

  • Address Register - a0
  • Constant Register - cn
  • Position Registers - vn
  • Temporary Registers - rn

Address Register - a0

The a0 registers are the address registers. A single register is available in version 1_1. The address register, designated as a0.x, can be used as a signed integer offset for relative addressing into the constant register file.

c[a0.x + n]

Reads from out of the legal range will return (0.0, 0.0, 0.0, 0.0). Address registers can be a destination only for the mov instruction. Address registers cannot be read by the vertex shader, just used in relative addressing of the constant register file. Addresses read from outside the range of constant registers supported will return unpredictable results.

Version 1_1 vertex shaders that attempt to use the address register before setting it will also fail.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Address Register | x | x | x | x | x | x

Constant Register - cn

The cn registers are the constant registers. There are at least 96 four-component floating-point vectors comprising the constant register file. The constant registers are designated as either absolute or relative.

c[n]           ; absolute
c[a0.x + n]    ; relative - supported only in version 1_1

The constant register can be read, therefore, by using an absolute address, or addressed relative to an address register. Reads from out-of-range registers return (0.0, 0.0, 0.0, 0.0).

The constant register file is read-only from the perspective of the vertex shader. Any single instruction may access only one constant register. However, each source in that instruction may independently swizzle and negate that vector as it is read.

The MaxVertexShaderConst member of D3DCAPS8 indicates the number of available constant registers. As shown in the table, vertex shaders support at least 96 constant registers.

The constant register file has its data loaded by calling the IDirect3DDevice8::SetVertexShaderConstant. Alternatively, when creating a vertex shader, a user can declare constants in a vertex declaration. These constants are loaded every time IDirect3DDevice8::SetVertexShader is called.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Register | x | x | x | x | x | x

Position Registers - vn

The vn registers are the input vertex registers. Each vertex from one or more input vertex streams is loaded into the vertex input registers before the vertex shader is run. The vertex input registers are a register file consisting of 16 four-component floating-point vectors, designated as v0 through v15. These registers are read-only.

Any single instruction can access only one vertex input register. However, each source in the instruction can independently swizzle and negate that vector as it is read.

A programmable vertex shader can use up to 16 registers for vertex data.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x

Temporary Registers - rn

The rn registers are the temporary registers. The temporary registers are grouped into a file of 12 4-D floating point vectors. Each temporary register has single-write and triple-read access. Therefore, an instruction can have as many as three temporary registers in its set of input source operands.

No values in a temporary register that remain from preceding invocations of the vertex shader can be used. Vertex shaders that read a value from a temporary register before writing to it will fail the Microsoft® Direct3D® application programming interface (API) call to create the vertex shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x | x

© 2002 Microsoft Corporation. All rights reserved.


Output Registers

  • Vertex Color Register - oD0, oD1
  • Fog Register - oFog
  • Position Register - oPos
  • Point Size Register - oPts
  • Texture Coordinate Register - oT0 to oT7

Register names are preceded by a lowercase o (oh), indicating that the output registers are write-only.

Vertex Color Register - oD0, oD1

oD0 is the diffuse color register. oD1 is the specular color register. The oD0 value is interpolated and is written to the input color register 0 (v0) of the pixel shader. The oD1 value is interpolated and written to the input color register 1 (v1) of the pixel shader. For more information about pixel shader color registers, see Registers.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Vertex Color Register | x | x | x | x | x | x

Fog Register - oFog

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used. Values are clamped between zero and one before passing to the rasterizer.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Fog Register | x | x | x | x | x | x

Position Register - oPos

The output position registers. The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x

Point Size Register - oPts

The output point-size registers. Only the scalar x-component of the point size is used.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x | x | x

Texture Coordinate Register - oT0 to oT7

The output texture coordinates registers. Specifically, these are an array of output data registers that are iterated and used as texture coordinates by the texture sampling stages routing data to the pixel shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x | x

When writing to a texture coordinate register, it is recommended to pass only as many floating point values as the dimension of the corresponding texture map. Control the values passed with a modifier. For example, use .xy for a 2-D texture map.

When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register.

Any of the D3DTTFF* texture transform flags should be zero when the programmable pipeline is being used.

Texture Coordinate Range

Object vertex data supplies input texture coordinates. Objects that do not used tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-?,+?] where ? can be a large floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping and scaled by the texture size (also taking into account texture address mode) to produce an integer index. The index is then used to perform a texture lookup. MaxTextureRepeat can be used to determine how many times a texture can be tiled.

If texture coordinates are read directly into a pixel shader (using texcoord or texcrd), the texture coordinate range depends on the instruction and the pixel shader version.

© 2002 Microsoft Corporation. All rights reserved.


abs (Vertex Shader)

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


call (Vertex Shader)

Performs a function call to the instruction marked with the provided label index.

Syntax

call label

where label is a label number.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  | x | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.

In vertex shader 2_0, nesting calls are not allowed.

In vertex shader 2_x, the nesting depth is limited by the StaticFlowControlDepth element of the D3DVSHADERCAPS2_0 structure. For more information, see IDirect3D9::GetDeviceCaps.

In vertex shader 3_0, four levels of call nesting are allowed.

Only forward calls are allowed. This means that the location of the label inside the vertex shader should be after the call instruction referencing it.

If a call instruction is invoked inside loop...endloop block, the value of the Loop Counter Register (aL) is accessible inside the subroutine.

If a subroutine is referencing the Loop Counter Register (aL) located outside of the subroutine, every instance of the call to this subroutine should be surrounded by a loop...endloop block.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


callnz (Vertex Shader)

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz label, booleanRegister

where:

  • label is a label. A label is an integer between 0 and 16. See label.
  • booleanRegister identifies a Boolean register. See Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz |  | x | x | x | x | x

This instruction does the following:

if (specified boolean register is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


crs (Vertex Shader)

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

This is a macro instruction, which takes two instruction slots.

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


defb (Vertex Shader)

Defines a Boolean constant value, which should be loaded anytime a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a boolean value, either True or False.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  | x | x | x | x | x

The defb (Vertex Shader) instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetVertexShaderConstantB.

There are two ways to set a boolean constant in a shader.

  1. Use defb (Vertex Shader) to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantB to set a Boolean constant.

Instruction Information

Minimum operating system Windows 98

Related Topics

  • def
  • defi

© 2002 Microsoft Corporation. All rights reserved.


defi (Vertex Shader)

Defines an integer constant value, which should be loaded anytime a shader is set to a device.

Syntax

defi dst, integerValue0, integerValue1, integerValue2, integerValue3
  • dst is the destination register.
  • integerValue# is a constant integer value.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defi |  | x | x | x | x | x

The defi (Vertex Shader) instruction defines an integer shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetVertexShaderConstantI.

There are two ways to set an integer constant in a shader.

  1. Use defi (Vertex Shader) to define the integer constant vector directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantI to set an integer constant.

Instruction Information

Minimum operating system Windows 98

Related Topics

  • def
  • defb

© 2002 Microsoft Corporation. All rights reserved.


else (Vertex Shader)

Start of an else block.

Syntax

else

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  | x | x | x | x | x

If the condition in the corresponding if statement is true, the code enclosed by the if statement and the matching endif is run. Otherwise, the code enclosed by the else...endif statements is run.

Minimum operating system Windows 98

Related Topics

  • if
  • endif

© 2002 Microsoft Corporation. All rights reserved.


endif (Vertex Shader)

Marks the end of an if...else block.

Syntax

endif

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  | x | x | x | x | x

Minimum operating system Windows 98

Related Topics

  • if
  • else

© 2002 Microsoft Corporation. All rights reserved.


endrep (Vertex Shader)

End of a repeat block.

Syntax

endrep

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  | x | x | x | x | x

  • rep uses integer registers (i#).
  • endrep must follow the last instruction of a repeat block.
  • The endrep offset must be greater than the rep instruction offset.
  • Repeat loops cannot be nested.
  • Repeat loops are allowed to be either completely inside an if block or completely surrounding it, no straddling is allowed.
  • rep consumes one vertex shader instruction slot but must be used with endrep, which consumes another.
  • The maximum loop iteration count is 255.

This instruction works as shown here.

LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


if (Vertex Shader)

Starts an if...else...endif block.

Syntax

if boolRegister

where boolRegister is a bool register number. See Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if |  | x | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching else is run. Otherwise, the code enclosed by the else...endif statements is run. This instruction consumes one instruction slot.

if blocks can be nested.

An if block cannot straddle a loop block.

Example

This instruction provides conditional static flow control.

defb b2, TRUE

if b3
// Instructions to run if b3 is nonzero

else
// Instructions to run otherwise

endif

Instruction Information

Minimum operating system Windows 98

Related Topics

  • else
  • endif

© 2002 Microsoft Corporation. All rights reserved.


label (Vertex Shader)

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For vs_2_0 and vs_2_x, the label number must be between between 0 and 15.

For vs_2_sw and vs_3_0, the label number must be between between 0 and 2047.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  | x | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction is allowed to be present directly after a ret instruction (which defines the end of the previous subroutine or main program).

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


loop (Vertex Shader)

Starts a loop...endloop block.

Syntax

loop aL, integerRegister

Where:

  • aL is the Loop Counter Register, holding the current loop count.
  • integerRegister is an input source register. integerRegister.x specifies the iteration count, integerRegister.y specifies the initial value of the current loop counter register, and integerRegister.z specifies the increment for the current loop counter register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  | x | x | x | x | x

loop starts a loop...endloop block. Only integer registers can be used in this instruction The loop instruction is provided for iteration, and supports an auto-incremented loop counter register that can be used to index the constant array. When nested, any time the loop counter register is used, it refers to the current loop.

This instruction works as shown here.

StartLoopOffset = next instruction offset
LoopCounter      = IntegerReg.x
IterationCount   = IntegerReg.y
LoopStep         = InteferReg.z
if (IterationCounter <= 0)
  Continue execution after the next EndLoop instruction
  • The endloop instruction must follow the last instruction of a loop block.
  • The endloop instruction offset must be greater than the corresponding loop instruction offset.
  • Loops cannot be nested in version vs_2_0. Versions vs_2_x and above support nesting.
  • Loops are allowed to be either completely inside an if block or completely surrounding it; no straddling is allowed.
  • The maximum loop initial value (base offset) is 255.
  • The maximum loop iteration count is 255.
  • The maximum step/stride size is 127 as signed strides, for example, -128 are supported.
  • The loop initial value and loop iteration count cannot be negative.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


lrp (Vertex Shader)

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2, src3

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.
  • src3 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp |  | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest.x = src0.x * (src1.x - src2.x) + src2.x;
dest.y = src0.y * (src1.y - src2.y) + src2.y;
dest.z = src0.z * (src1.z - src2.z) + src2.z;
dest.w = src0.w * (src1.w - src2.w) + src2.w;

Instruction Information

Minimum operating system Windows 98

Related Topics

    © 2002 Microsoft Corporation. All rights reserved.


mov (Vertex Shader)

Move floating-point data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x

Can be used for floating point data. For version vs_1_1, it can also be used to write the address register. When used to update address registers, the values are converted from floating point using rounding to nearest.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src.w);
    dest = intSrc;
}
else
{
    dest = src;
}

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


mova (Vertex Shader)

Move data from a floating point register to the Address Register, a0.

Syntax

mova dst, src

where

  • dst must be the Address Register, a0.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mova |  | x | x | x | x | x

Moves floating point data to an integer register. The values are converted from floating point using rounding to nearest.

The address register is the only destination register allowed.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src);
    dest = intSrc;
}
else
{
    dest = src;
}

For versions 2_x and above, the address register is a component vector. Therefore, any write mask is allowed.

mova a0.xz, r0

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


nrm (Vertex Shader)

Normalize a 3-D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);

This is a macro instruction. The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


pow (Vertex Shader)

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  | x | x | x | x | x

This instruction works as shown here.

dest = pow(abs(src0), src1);

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The scalar result is replicated to all four output channels.

This is a macro instruction.

This instruction could be expanded as exp(src1 * log(src0)).

Precision is not lower than 15 bits.

The dest register should be a temporary register, and should not be the same register as src1.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


rep (Vertex Shader)

Start a rep...endrep block.

Syntax

rep integerReg

where integerReg is an integer register that specifies the repeat count in the x component. See Constant Integer Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  | x | x | x | x | x

  • rep uses Constant Integer Registers (i#).
  • endrep must follow the last instruction of a repeat block.
  • The endrep offset must be greater than the rep instruction offset.
  • Repeat loops cannot be nested.
  • Repeat loops are allowed to be either completely inside an if block or completely surrounding it, no straddling is allowed.
  • rep consumes one vertex shader instruction slot but must be used with endrep, which consumes another.
  • The maximum loop iteration count is 255.

Here is how the instruction works.

StartLoopOffset = next instruction offset
    LoopIterationCount   = IntegerRegister.x
    if (LoopIterationCount <= 0)
        Continue execution after the next EndRep instruction

© 2002 Microsoft Corporation. All rights reserved.


ret (Vertex Shader)

Return from a subroutine or a main function.

Syntax

ret

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  | x | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


sgn (Vertex Shader)

Computes the sign of the input.

Syntax

sgn dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sgn |  | x | x | x | x | x

This instruction works as shown below.

for each component in src0
{
   if (src0.component <  0)
       dest.component = -1;
   else
       if (src0.component == 0)
           dest.component = 0;
       else
           dest.component = 1;
}

This is a macro instruction, which takes three instruction slots.

src1, and src2 should be different temporary registers.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


sincos (Vertex Shader)

Computes sine and cosine, in radians. The x component of result contains cos(x). The y component contains sin(x). The src1 register needs to have a replicate swizzle to indicate which channel is used.

Syntax

sincos dst, src0, src1, src2

where

  • dst is the destination register. Should be a temporary register.
  • src0 is a source register. Replicate swizzle is required for selecting a single component. The means exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is a source register. Must be a constant register.
  • src2 is a source register. Must be a constant register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  | x | x | x | x | x

Source register rules:

  • src0.selectedChannel is an angle measured in radians between -Pi and +Pi.
  • src1 = (-1.0f/(7!*128), -1.0f/(6!*64), 1/(4!*16), 1/(5!*32) ).
  • src2 = (-1.0f/(3!*8), -1.0f/(2!*8), 1, 0.5f).

These values are defined in the following macros: D3DSINCOSCONST1 and D3DSINCOSCONST2 macros.

Destination register rules:

  • dest.x = cos(src1.selected_channel), dest.y = sin(src1.selected_channel), dest.z is undefined after the instruction.
  • dest should not be the same register as src1.
  • Only .x and .y are allowed to be in the destination write mask.

The maximum absolute error is 0.002.

This is a macro instruction, which takes eight instruction slots.

If application wants to compute sincos for an arbitrary angle, then the angle could be mapped to the range -Pi to +Pi by using the following macro (r0.x holds the original angle).

def c0, Pi, 0.5f, 2*Pi, 1/(2*Pi)
mad r0.x, r.x, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Address Register

This is unchanged from vs_1_1 except that components other than .x can be used for relative addressing. The mova instruction is used to move a floating point value to an address register.

Round to nearest happens on the conversion from floating point to integer.

These registers cannot be used in any other instructions.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Constant Boolean Register

This register is a collection of bits used in static flow control instructions (eg. if - else - endif).

There are 16 of them, therefore, a shader can have 16 independent branch conditions.

They can be set using def or IDirect3DDevice9::SetVertexShaderConstantI.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Constant Float Register

Vertex shader input register for a 4-D floating-point constant.

They can be set using def or IDirect3DDevice9::SetVertexShaderConstantF.

Examples

Here is an example declaring two floating-point constants within a shader.

def c40, 0.0f,0.0f,0.0f,0.0f;

These constants are loaded every time IDirect3DDevice9::SetVertexShader is called.

Here is an example using the application programming interface (API).

    // Set up the vertex shader constants.
    {
        D3DXMATRIXA16 mat;
        D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
        D3DXMatrixTranspose( &mat, &mat );

        D3DXVECTOR4 vA( sinf(m_fTime)*15.0f, 0.0f, 0.5f, 1.0f );
        D3DXVECTOR4 vD( D3DX_PI, 1.0f/(2.0f*D3DX_PI), 2.0f*D3DX_PI, 0.05f );

        // Taylor series coefficients for sin and cos.
        D3DXVECTOR4 vSin( 1.0f, -1.0f/6.0f, 1.0f/120.0f, -1.0f/5040.0f );
        D3DXVECTOR4 vCos( 1.0f, -1.0f/2.0f, 1.0f/ 24.0f, -1.0f/ 720.0f );

        m_pd3dDevice->SetVertexShaderConstantF(  0, (float*)&mat,  4 );
        m_pd3dDevice->SetVertexShaderConstantF(  4, (float*)&vA,   1 );
        m_pd3dDevice->SetVertexShaderConstantF(  7, (float*)&vD,   1 );
        m_pd3dDevice->SetVertexShaderConstantF( 10, (float*)&vSin, 1 );
        m_pd3dDevice->SetVertexShaderConstantF( 11, (float*)&vCos, 1 );
    }

If you are setting constant values with the API, there is no shader declaration required. For a more complete code sample, see the VertexShader software development kit (SDK) sample.

© 2002 Microsoft Corporation. All rights reserved.


Constant Integer Register

Constant integer registers are used only by loop and rep.

They can be set using def or IDirect3DDevice9::SetVertexShaderConstantI.

When used as an argument to the loop instruction:

  • .x is the iteration count. (rep uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Fog Register

This vertex shader output register contains a per-vertex fog color.

Syntax

Fog Register

Remarks

A register consists of properties that determine how each register behaves.

Property | Description
Name | oFog
Count | One vector, of which only one component can be used and must be specified by the component mask
I/O permissions | Write-only.

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used. Values are clamped between zero and one before passing to the rasterizer.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Input Register

Vertex shader input register. An input register is bound to the vertex data, so that the vertex data can be input to the shader.

Syntax

Input Register

Remarks

An input register is bound to vertex data through a vertex declaration. There is no way to set an input register inside the shader, or through the application programming interface (API).

A register consists of properties that determine how each register behaves.

Property | Description
Name | v[n] - n is an optional register number. 0 is the default value used, if it is omitted.
Count | A maximum of 16 registers, v0 - v15.
I/O permissions | Read-only. This register cannot be written by the API or within the shader.
Read ports | 1. This is the number of times a register can be read within a single instruction. See below.

Any single instruction can access only one vertex input register. However, each source in the instruction can independently swizzle and negate that vector as it is read.

Example

Here is an example using a vertex declaration to bind 2-D vertex position data to register v0.

Here is the vertex declaration. This belongs in the application.

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
      D3DDECL_END()
};

Here is the vertex shader declaration that binds the position data to register v0.

dcl_position v0

For a more complete code sample, see the VertexShader software development kit (SDK) sample.

Here is the vertex declaration that uses several vertex registers and data types.

dcl_position0 v0
dcl_position1 v1
dcl_position2 v2
dcl_normal0   v3
dcl_normal1   v4
dcl_normal2   v5
dcl_texcoord0 v6

This example is from the dolphin tweening SDK sample.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop...endloop block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Point Size Register

This vertex shader output register contains per-vertex point size data.

Syntax

Point Size Register

Remarks

Remarks
Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPts
Count | 1 vector, of which of only 1 component can be used and must be specified by the component mask.
I/O permissions | Write-only.

Only the scalar x-component of the point size is used.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Position Register

This vertex shader output register contains per-vertex position date.

Syntax

Position Register

Remarks

Remarks
Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPos
Count | 1 vector
I/O permissions | Write-only.

The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Example

dcl_position v0

def c40, 0.0f,0.0f,0.0f,0.0f;
// transform into projection space
m4x4 r0,v0,c8
max r0.z,c40.z,r0.z //clamp to 0
max r0.w,c12.x,r0.w //clamp to near clip plane
mov oPos,r0

For a more complete code sample, see the VertexBlend software development kit (SDK) sample.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Sampler Register

A vertex shader sampling stage register identifies a sampling unit that can be used in texture load statements. A sampler register is an input register for a vertex shader, which is used to identify the sampling stage. There are four vertex shader sampling stage registers: s0 to s3. Four texture surfaces can be read in a single shader pass.

Sampler registers must be declared before use with the dcl_textureType instruction.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler register |  | x | x | x | x | x

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because there are four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler register can only appear as an argument in the texture load instruction: texldl.

Related Topics

  • Vertex Textures

© 2002 Microsoft Corporation. All rights reserved.


Temporary Register

Vertex shader temporary register. A temporary register is used to hold 4-D intermediate results.

Syntax

Temporary Register

Remarks

Remarks
Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | r[n] - n is an optional register number. 0 is the default value used, if it is omitted.
Count | A maximum of 12 registers.
I/O permissions | read/write. This register can be read or written by the application programming interface (API) or by the shader.
Read ports | 3. This is the number of times a register can be read within a single instruction. A temporary register is the only register that can be read and written more than once in a single instruction.

Each temporary register has single-write and triple-read access. Therefore, an instruction can have as many as three temporary registers in its set of input source operands.

No values in a temporary register that remain from preceding invocations of the vertex shader can be used. Vertex shaders that read a value from a temporary register before writing to it will fail the Microsoft® Direct3D® API call to create the vertex shader.

Example

Here is an example using a temporary register r0. Constant registers do not get declared, so jump directly to the shader code that uses them.

// Decompress position
mov r0.x, v0.x
mov r0.y, c4.w       // 1
mov r0.z, v0.y
mov r0.w, c4.w       // 1

// Compute theta from distance and time
mov r4.xz, r0        // xz

In this example, the shader writes vertex data (v0) and constant data (c4) into r0. The data is later read into temporary register r4 to help compute an angle theta. The constant register (c4) must either be initialized in shader code, or set by the API.

For a more complete code sample, see the VertexShader software development kit (SDK) sample.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Texture Coordinates Register

This vertex shader output register contains per-vertex texture coordinates.

Syntax

Texture Coordinates Register

Remarks

A register consists of properties that determine how each register behaves.

Property | Description
Name | oT0 - oT7
Count | Eight vectors
I/O permissions | Write-only

The output texture coordinates registers are an array of output data registers. The register data is iterated and used as texture coordinates by the texture sampling stages to supply data to the pixel shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x

When writing to a texture coordinate register, it is recommended that you pass only as many floating point values as the dimension of the corresponding texture map. Control the values that are passed with a modifier. For example, use .xy for a two-dimensional texture map.

When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register.

Any of the D3DTTFF* D3DTEXTURETRANSFORMFLAGS should be zero when the programmable pipeline is being used.

Texture Coordinate Range

Object vertex data supplies input texture coordinates. Objects that do not used tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-?,+?] where the question mark (?) can be a large floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping, and scaled by the texture size (also taking into account texture addressing modes) to produce an integer index. The index is then used to perform a texture lookup. Use the MaxTextureRepeat value in D3DCAPS9 to determine how many times a texture can be tiled.

If texture coordinates are read directly into a pixel shader (using texcoord or texcrd), the texture coordinate range depends on the instruction and the pixel shader version.

Example

Declare the texture coordinate register.

dcl_texcoord v7

Copy the per-vertex texture coordinates to the output register.

mov oT0,  v7

For a more complete code sample, see the Vertex Blend Sample.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Diffuse/Specular Register

This vertex shader output register contains a per-vertex diffuse or specular color value.

Syntax

Diffuse/Specular Register

Remarks

A register consists of properties that determine how each register behaves.

Property | Description
Name | oD[n] - n is an optional register number. If the register number is omitted, 0 is the default value used.
Count | A maximum of two registers, oD0 and oD1.
I/O permissions | Write-only.

oD0 is the diffuse color register. oD1 is the specular color register. The oD0 value is interpolated and is written to the pixel shader color register 0 (v0). The oD1 value is interpolated and written to the pixel shader color register 1 (v1). For more information about pixel shader color registers, see the pixel shader Color Register page.

Example

min oD0, r0, c1.x

For a more complete code sample, see the Vertex Blend Sample.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break (Vertex Shader)

Break out of the current loop at the nearest endloop or endrep.

Syntax

break

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  | x | x | x | x

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break_comp (Vertex Shader)

Conditionally break out of the current loop at the nearest endloop or endrep.

Syntax

break_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a single component.
  • src1 is a source register. Replicate swizzle is required to select a single component.

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (src0 comparison src1)
   jump to the corresponding endloop or endrep instruction;

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


break pred (Vertex Shader)

Conditionally break out of the current loop at the nearest endloop or endrep. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

break [!]p0.replicateSwizzle

Where:

  • [!] optional negate modifier. This modifies the value in the predicate register. See Negate.
  • p0 is a predicate register. See Predicate.
  • replicateSwizzle specifies the component that contains the predicate value. Valid components are: x, y, z, w or r, g, b, a. The predicate value can be modified with the negate modifier.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break pred |  |  | x | x | x | x

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


callnz pred (Vertex Shader)

Call if not zero, with a predicate. Performs a conditional call to the instruction marked by the label index. Predication uses a boolean value to determine whether of not to perform the instruction.

Syntax

callnz label, [!] p0.replicateSwizzle

where:

  • label specifies a label number.
  • [!] is an optional boolean NOT.
  • p0 is the predicate register. See Predicate.
  • replicateSwizzle specifies the component that contains the predicate value. Valid components are: x, y, z, w or r, g, b, a. The predicate value can be modified with the negate modifier.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


if_comp (Vertex Shader)

Start an if...else...endif block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if (src0 comparison src1)
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else...endif blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else or endif instruction.
  • if_comp...else...endif blocks cannot straddle a loop block. The if_comp block must be completely inside, or outside the loop block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


if pred (Vertex Shader)

Start of an if...else...endif block, with the condition taken from the content of the predicate register.

Syntax

if [!]p0.replicateSwizzle

Where:

  • [!] an optional NOT modifier. This modifies the value in the predicate register.
  • p0 is the predicate register. See Predicate.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: x, y, z, w or r, g, b, a.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if pred |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else or endif instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block, it should be either completely inside it or surround it.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


setp (Vertex Shader)

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dest register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, srcReg, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, srcReg, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

// given r0 = 0,0,1,1
// given r1 = 1,1,0,0
setp_le p0, r0, r1
(p0) add r2, r3, r4

to perform a 2 component add.

r2.x = r3.x + r4.x
r2.y = r3.y + r4.y

The x and y components of r1 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases it's instruction slot count by 1.

The predicate register can also be applied to if pred, callnz pred and break pred instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.

For these instructions, the slot count is what is listed in the slot count table (link?), and there is no increment of 1 as in other cases.
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Predicate Register

This vertex shader output register contains a per-channel Boolean value.

Syntax

Predicate Register

Remarks

A predicate register is supported by the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp. There are no default values for this register, an application needs to set the register before it is used.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dcl_textureType (Vertex Shader)

Declare a vertex shader sampler register.

Syntax

dcl_textureType s#

where:

  • _textureType defines the texture type. This determines how many coordinates are required by each texture coordinate when sampling. The following texture dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler register. s is an abbreviation for the sampler register and # is the register number.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_textureType |  |  |  |  | x | x

All dcl_xxx instructions must appear before the first executable instruction.

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


dcl_usage (Vertex Shader)

The various types of output registers have been collapsed into 12 o (output) registers (2 for color, 8 for texture, 1 for position, and 1 for fog and point size). These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, etc.

Output declarations are introduced, whereby semantics are assigned to each register. Old oPos and oPts are replaced by declaring an o register with a position or pointsize semantic, further described here.

There are 12 "out" registers. Ten have 4-components (xyzw) (any 10, not necessarily o0 to o9), another one must be declared as position (all 4-components), and optionally one more can be a scalar point size.

Syntax

The syntax for declaring outputs (o registers) is similar to the declarations for the inputs:

dcl_semantics o[.write_mask]

Where:

  • _semantics: The same set of semantics as for the input declaration can be used. Semantic names come from the enum D3DDECLUSAGE (and are paired with an index, that is, position3). There always has to be one o register with _positiont0 declaration when not used for process vertices. The positiont0 semantic and the pointsize0 semantic are the only ones that have meaning to Microsoft® Direct3D®, beyond simply allowing linkage from vertex to pixel shaders. For shaders with flow control, it is assumed that the worst case output is dcl'd. There are no defaults if a shader does not actually output what it declares it should (due to flow control).
  • o: output register. See Output Registers.
  • write_mask: The same "out" register can be dcl'd multiple times (so different semantics can be applied to individual components), each time with a unique write mask. However, the same semantic cannot be used multiple times in a declaration -> This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual "out" registers). When the _pointsize semantic is used, it should have full write mask because it is considered a scalar. When the _position semantic is used, it should have a full write mask because all four components have to be written.

Remarks

Vertex shader versions | 3_0 | 3_sw
dcl_usage | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

vs_3_0
dcl_color4     o3.x    // color4 is a semantic name.
dcl_texcoord3  o3.yz   // Different semantics can be packed into one register.
dcl_fog        o3.w
dcl_tangent	   o4.xyz
dcl_positiont  o7.xyzw // positiont must be declared to some unique register
                       //   in a vertex shader, with all 4 components.

dcl_psize	   o6      // Pointsize cannot have a mask
                       //   (that is, mask is full .xyzw) ->
                       // This is an implied scalar register.
                       // No other semantics can be assigned to any components
                       //   of this register.
                       // If pointsize declaration is not used (typical),
                       //   only 11 "out" registers are available, not 12.
                       // Pixel shaders cannot see this value.
Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


texldl (Vertex Shader)

Sample a texture with a particular sampler. The particular mipmap level (LOD) being sampled has to be specified as the fourth component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (for example, D3DSAMP_MINFILTER).

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  | x | x

texldl looks up the texture set at the sampler stage referenced by src1. The level of detail (LOD) is selected from src0.w. This value can be negative, in which case the LOD selected is the "zero'th one" (biggest map) with the MAGFILTER. Because src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, 0001 is obtained in the destination register.

The following rough algorithm has been provided for reference that the reference device follows.

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD);
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be r#.
  • dst can accept a write mask.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be s# with no negate, but can have swizzle. The s# must have been declared (using dcl) at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the s# was declared. If it was declared as a cube, a 3-component texture coordinate is required (.rgb). Validation enforces that coordinates provided to texld are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually set a texture (through the application programming interface (API)) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with lower dimensions than are present in the texture coordinate will be allowed, and will be assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with higher dimensions than are present in the texture coordinate is not allowed.
  • If the src0 (texture coordinate) is r#, the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.

© 2002 Microsoft Corporation. All rights reserved.


Sampler Register

A sampler register is an input register for a vertex shader, which is used to identify the sampling stage. There are four vertex shader sampling stage registers: s0 to s3. Four texture surfaces can be read in a single shader pass.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler register |  |  |  |  | x | x

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because there are four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler register might appear only as an argument in the texture load instruction: texldl.

In vs_3_0, if a sampler is used, it needs to be declared at the beginning of the shader program using the dcl_textureType instruction.

Related Topics

  • Vertex Textures

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileBinary::GetName Method

Retrieves a pointer to a Microsoft® DirectX® file object's name.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileData::GetName Method

Retrieves a pointer to a Microsoft® DirectX® file object's name.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileDataReference::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

© 2002 Microsoft Corporation. All rights reserved.


IDirectXFileDataReference::GetName Method

Retrieves a pointer to a Microsoft® DirectX® file object's name.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

© 2002 Microsoft Corporation. All rights reserved.


endloop (Vertex Shader)

End of a loop...endloop block.

Syntax

endloop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  | x | x | x | x | x

This instruction works as shown here.

LoopCounter += LoopStep;
LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset

The endloop instruction offset must be greater than the loop instruction offset.

The code block defined between the loop and endloop instructions does not consume additional instruction slots beyond those required to define it.

Instruction Information

Minimum operating system Windows 98

© 2002 Microsoft Corporation. All rights reserved.


Basic Networking

This section covers some basic networking technology topics that you need to understand to write Microsoft® DirectPlay® applications. For a general discussion of networking technology, see one of the standard texts on the subject, such as Computer Networks by Andrew Tannenbaum.

  • DirectPlay Addressing
  • DirectPlay Protocol
  • Optimizing Network Usage
  • Network Address Translation, Firewalls, and Proxies
  • Using the DirectX Protocol in an Application

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectPlay Core API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® core application programming interface (API). Some of this material is also relevant to DirectPlay Lobby and DirectPlay Voice.

  • Handling DirectPlay Messaging
  • Using DirectPlay Enumerations
  • Using Player Context Values
  • Using the DirectPlay DPNSVR Application
  • Testing Network Performance
  • Monitoring DirectPlay Network Traffic with Netmon
  • Implementing a Callback Function in DirectPlay and DirectPlay Voice

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectPlay Lobby API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® Lobby application programming interface (API). For general information about using DirectPlay, see Using the DirectPlay Core API.

Overviews

  • Implementing a Lobby Client
  • Implementing a Lobbyable Application

© 2002 Microsoft Corporation. All rights reserved.


Using DirectPlay

This section of the Microsoft® DirectPlay® documentation is designed to show you how to use the DirectPlay application programming interface (API) to implement a number of important aspects of multiplayer applications.

  • Using the DirectPlay Core API
  • Using the DirectPlay Lobby API
  • Using the DirectPlay Voice API
Note Because DirectPlay is based on Component Object Model (COM) objects, you will need to initialize COM. You should do so by calling CoInitializeEx(NULL, COINIT_MULTITHREADED). Initializing COM by calling CoInitialize() might create serious race conditions.

© 2002 Microsoft Corporation. All rights reserved.


Using the DirectPlay Voice API

This documentation provides detailed information about how to use the Microsoft® DirectPlay® Voice application programming interface (API). For general information about using DirectPlay, see Using the DirectPlay Core API.

© 2002 Microsoft Corporation. All rights reserved.